From 2cdc5ce842ae9c4dfe1005e4f7010b26e5e395ac Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:46:16 +0800 Subject: [PATCH 001/171] docs(decisions): record the Swift manifest, component model and executable approval --- Documentation/Decisions/AgentComponents.md | 92 +++++++++++++++++++ Documentation/Decisions/ExecutableApproval.md | 53 +++++++++++ Documentation/Decisions/README.md | 5 + Documentation/Decisions/SwiftManifest.md | 90 ++++++++++++++++++ 4 files changed, 240 insertions(+) create mode 100644 Documentation/Decisions/AgentComponents.md create mode 100644 Documentation/Decisions/ExecutableApproval.md create mode 100644 Documentation/Decisions/SwiftManifest.md diff --git a/Documentation/Decisions/AgentComponents.md b/Documentation/Decisions/AgentComponents.md new file mode 100644 index 0000000..5c317f0 --- /dev/null +++ b/Documentation/Decisions/AgentComponents.md @@ -0,0 +1,92 @@ +# Agent Components and Adapters + +## Status + +Accepted + +## Context + +Core manages skills and instructions, with each agent's locations encoded in +the agent registry. The next stage manages every agent configuration +component: MCP servers, hooks, subagents, commands and prompts, LSP servers, +permissions, ignore rules and plugins. Each supported agent stores these in +its own places and formats, often several components in one settings file. + +Other tools distribute the same components in their own containers: Claude +Code, Codex and Cursor plugins and marketplaces, Gemini CLI extensions, APM +packages, rulesync sources and npx skills locks. Some agents also share +physical locations; Codex, Cursor, Gemini CLI and OpenCode read the same +`.agents/skills` directory. + +## Decision + +- **One component model.** Core models components independently of any agent. + The manifest declares components; adapters deploy them. +- **Capability registry.** Core records, for each agent, component and scope, + whether the agent supports it, its native location and format, and the keys + agents owns in a shared file. CLI validation and GUI controls derive from + the registry. Each supported combination is verified against the agent's + current stable client. +- **Key-level ownership.** In shared configuration files agents changes and + removes only the keys it wrote and preserves every other key. +- **Deployment ledger.** The lock records each physical target with its owner + and content hash, and cleanup removes only what the lock proves agents owns. +- **Agent targeting.** Every component can be limited to agents and platforms. + A producer declares targeting in front matter or a package manifest; a + consumer narrows it in the manifest with `agents` or `.when(...)` and never + widens it. A component reaches the declared agents that the registry says + support it. When a shared location exposes a component to agents beyond its + targeting, agents reports the conflict and the user chooses to share or to + deploy to the agent's own location. +- **Absorb, decompose, recompose.** Input adapters read Claude marketplaces and + plugins, Codex and Cursor plugins, Gemini CLI extensions, APM packages, + rulesync sources, npx skills locks and hand-written native files. They split + each container into components and record its provenance. A marketplace is a + source that can be browsed and searched; installing from it is declared in + the manifest and pinned in the lock. +- **Import.** The same adapters back `agents import`, which previews the + manifest changes and target ownership it would take, and writes only with + `--apply`. Import is one-way and never automatic. Adopting an existing + native file goes through import, as the whole file or as a marked section. +- **Native deployment.** Components deploy to each agent's native locations. + Where an agent accepts a component only through its plugin system, as Claude + Code does for LSP servers, agents generates a native plugin that carries it. + A vendor plugin can also be installed unchanged for its own agent. A + component an agent cannot represent is reported, not dropped or + approximated. +- **Distribution.** A source is a Git repository, local directory or index. + A repository publishes reusable groups by declaring them in its + `Agents.swift`; agents runs no hosted marketplace or registry. + +## Consequences + +- The agent registry grows into the capability registry and gains per-agent + adapters for every component; adding an agent or component means adding + registry entries, adapters and client probes. +- The lock grows from pins and hashes into a deployment ledger, a lock format + change that `agents migrate` covers. +- Input adapters are versioned against the upstream formats they read and need + fixtures from those formats. +- Shared settings files require structured, format-preserving edits for JSON, + TOML and Markdown targets. +- Targeting is deployment intent, not isolation; shared locations remain + visible to every agent that reads them. + +## Alternatives Considered + +- **Per-agent code paths without a registry.** Every new component would add + special cases across CLI and GUI. +- **Copying plugins between agents unchanged.** Plugin formats and runtimes + differ; components move between agents, containers do not. +- **Reading and writing other tools' manifests as agents' own.** Two managers + would own the same outputs. +- **A hosted marketplace.** Git repositories already identify, version and + distribute sources. + +## Related Documentation + +- Accepted by the repository owner (showxu) on 2026-10-28. +- Current agent locations and state: [Package](../Architecture/Package.md), + [State](../Architecture/State.md) +- Manifest that declares components: [Swift Manifest](SwiftManifest.md) +- Approval before executable components deploy: [Executable Component Approval](ExecutableApproval.md) diff --git a/Documentation/Decisions/ExecutableApproval.md b/Documentation/Decisions/ExecutableApproval.md new file mode 100644 index 0000000..6fc9ef9 --- /dev/null +++ b/Documentation/Decisions/ExecutableApproval.md @@ -0,0 +1,53 @@ +# Executable Component Approval + +## Status + +Accepted + +## Context + +Hooks, MCP servers, LSP servers and plugins run commands on the machine where +they are deployed. A project's manifest is committed and changed by every +contributor, and sources change upstream, so a component can appear in a +scope's declaration without the person who runs `agents update` having +written or reviewed it. + +## Decision + +- Approval is per machine and bound to content identity: the component's + declaration, the command it runs and the content it ships. +- A component that runs code is not deployed to a machine until it is approved + there. Adding it through the CLI or GUI on that machine approves it. + Components that arrive through a project manifest, an imported container or + a source are pending until approved. +- A change to an approved component's content identity makes it pending again. +- Approvals are stored in the machine's user state, never in a committed lock. +- Update previews list pending components and what they would run. Applying + deploys approved components and leaves pending ones undeployed and reported. +- Non-interactive runs approve only components named with their content + identity. +- Reading, previewing and inspecting never run manifest code; the manifest is + parsed, not executed. + +## Consequences + +- The deployment ledger distinguishes approved, pending and refused + components. +- CLI and GUI share one approval flow; the GUI can show an on-device + explanation of a pending command before the user decides. +- Teams that want shared trust approve on each machine or name approved + content identities in automation. + +## Alternatives Considered + +- **Trust everything declared in the manifest.** A contributor's change to a + committed manifest would run on everyone's machine without review. +- **Trust per source.** One approval would cover every later change from that + source. +- **No approval.** Comparable tools already gate executable content. + +## Related Documentation + +- Accepted by the repository owner (showxu) on 2026-10-28. +- Components and deployment ledger: [Agent Components and Adapters](AgentComponents.md) +- Parse-only manifest: [Swift Manifest](SwiftManifest.md) diff --git a/Documentation/Decisions/README.md b/Documentation/Decisions/README.md index 7c1a0d8..31615bf 100644 --- a/Documentation/Decisions/README.md +++ b/Documentation/Decisions/README.md @@ -10,6 +10,11 @@ This directory holds durable decision records for `skill-cli`. - `SPMInspiredRegistry.md`: SPM-inspired first-party skill registry schema - `SwiftStyleFlagSurface.md`: Swift-style canonical flag spelling for install/list/remove/update +- `SwiftManifest.md`: `Agents.swift` as a statically evaluated Swift + declaration with lossless edits +- `AgentComponents.md`: component model, capability registry, input adapters + and native deployment +- `ExecutableApproval.md`: per-machine approval of components that run code ## Placement diff --git a/Documentation/Decisions/SwiftManifest.md b/Documentation/Decisions/SwiftManifest.md new file mode 100644 index 0000000..8f09081 --- /dev/null +++ b/Documentation/Decisions/SwiftManifest.md @@ -0,0 +1,90 @@ +# Swift Manifest + +## Status + +Accepted + +## Context + +A scope's declaration is `agents.json`, standard JSON that the state store +rewrites in full on every save. People cannot annotate it, and every write +normalizes it. + +The declaration is about to describe every agent configuration component, not +only skills and instructions, and two front ends will edit it: the `agents` +CLI and a macOS GUI. People still read it in review and edit it by hand, so it +needs comments, and every tool write must keep them. + +Swift has no maintained library that edits YAML without losing comments; a +YAML route needs a custom editor built on libyaml internals, plus rules for +YAML's implicit typing and indentation. A SwiftPM-style manifest that is +compiled and run executes repository code whenever a project is opened or +previewed, needs a toolchain and compile step on every read, and becomes +uneditable for tools once it contains logic. + +## Decision + +- The declaration is a Swift file, `Agents.swift`: `.agent/Agents.swift` for a + project and `~/.agents/Agents.swift` for the user scope. +- Its vocabulary is a types-only module, `AgentsDescription`, modeled on + `PackageDescription`. Sources, skills, instructions, MCP servers, hooks, + subagents, commands and LSP servers are types, as are agents, scopes, + platforms and conditions. A valid manifest type-checks against + `AgentsDescription`. +- Core never compiles or runs a manifest. It parses the file with SwiftSyntax + and evaluates a static subset: literals; initializers, static members and + enum cases of `AgentsDescription` types; arrays and array concatenation; + top-level `let` constants and references to them; `.when(agents:scopes:platforms:)` + conditions; named groups, and references to groups that sources export. + Functions, closures, loops, `var`, `if`, `#if`, `switch`, string + interpolation and other imports are rejected with a line and column, and + nothing is written. +- A leading version comment, in the manner of `swift-tools-version`, declares + the language version. A tool refuses a manifest newer than it understands. +- Every write is a source edit. A write with no semantic change returns the + original bytes; a change replaces only its target ranges, keeps comments by + defined ownership rules, and is parsed and validated again before it is + committed. A valid construct that an edit cannot address exactly, such as a + constant assembled by concatenation, stays readable but is not edited by + tools. +- `agents.resolved` remains the tool-owned JSON lock. Resolved pins live in the + lock, not in the manifest. +- `agents manifest dump --json` prints the evaluated declaration for tools in + other languages. +- `agents migrate` converts `agents.json` to `Agents.swift` once and gives the + same result when repeated. Commands report an unmigrated `agents.json` + instead of converting it implicitly. + +## Consequences + +- Core depends on swift-syntax, which lengthens clean builds. +- The static subset is a versioned contract. `AgentsDescription` and the static + evaluator must not drift; examples are compiled against the types and + compared with the evaluated model in tests. +- The state store gains a document layer that owns the original bytes, syntax + tree, model and source locations, and that CLI and GUI edits share. Writes + join the existing transaction and recovery model. +- Parsing untrusted manifests needs explicit limits on file size, nesting and + evaluation work, and fuzzing before release. +- Editors offer completion only where `AgentsDescription` is available to them. +- Every repository that commits `agents.json`, and every user scope, migrates + once. + +## Alternatives Considered + +- **Keep JSON.** No comments; explanations would need a structured field. +- **YAML.** Readable and familiar, but comment-preserving edits need a custom + editor on non-public libyaml APIs, and implicit typing and indentation + errors reach users. +- **JSONC or TOML.** Not chosen. +- **A compiled manifest, as in SwiftPM.** Full Swift, but opening or + previewing a repository would run its code, every read would compile, and + the GUI could not edit computed values. + +## Related Documentation + +- Accepted by the repository owner (showxu) on 2026-10-28. +- Current declaration, lock and state layout: [State](../Architecture/State.md) +- Component model the manifest describes: [Agent Components and Adapters](AgentComponents.md) +- Approval of executable components: [Executable Component Approval](ExecutableApproval.md) +- Product scope and front ends: [agents-tools/cli decisions](https://github.com/agents-tools/cli/tree/master/Documentation/Decisions) From c00c8e2bc4e3f9cd9d08307202211ec813fdfd76 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:27:17 +0800 Subject: [PATCH 002/171] test: discard the unused add outcome in the shorthand test --- Tests/AgentsInstructionsTests/SourceShorthandTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/AgentsInstructionsTests/SourceShorthandTests.swift b/Tests/AgentsInstructionsTests/SourceShorthandTests.swift index daf7001..38d4532 100644 --- a/Tests/AgentsInstructionsTests/SourceShorthandTests.swift +++ b/Tests/AgentsInstructionsTests/SourceShorthandTests.swift @@ -14,7 +14,7 @@ struct InstructionSourceShorthandTests { InstructionAddOptions( source: fixture.repo.path + "@skill:rules", environment: fixture.environment)) } - try InstructionOperations.add( + _ = try InstructionOperations.add( InstructionAddOptions( source: fixture.repo.path + "@branch:main", names: ["rules"], agents: [.codex], environment: fixture.environment)) From 790a32aa4b98a9145f0cc4cff20d9558f61dcdcf Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 29 Oct 2026 02:52:25 +0800 Subject: [PATCH 003/171] docs: propose the Agents.swift manifest contract --- Documentation/Proposals/AgentsManifest.md | 1615 +++++++++++++++++++++ Documentation/Proposals/README.md | 4 + 2 files changed, 1619 insertions(+) create mode 100644 Documentation/Proposals/AgentsManifest.md diff --git a/Documentation/Proposals/AgentsManifest.md b/Documentation/Proposals/AgentsManifest.md new file mode 100644 index 0000000..45497fe --- /dev/null +++ b/Documentation/Proposals/AgentsManifest.md @@ -0,0 +1,1615 @@ +# Agents Manifest Contract + +## Status + +Proposed — language version 1.0. + +## Authors / Owners + +- Author: showxu. +- Implementation owner: core; CLI, macOS GUI and skill CLI are consumers. +- Accepting authority: repository owner showxu. + +## Summary + +`Agents.swift` is source for a non-executing configuration compiler: bounded +grammar recognition, SwiftSyntax parsing and static type checking produce an +agent-independent intermediate +representation (IR); source linking and capability-driven adapters produce native +configuration files. The **deployment ledger**, `agents.resolved`, records exact +source pins, physical artifacts, owned keys/sections and their hashes. Machine +user state separately owns approvals for executable content. + +The core repository's complete declaration is: + +```swift +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + sources: [ + .git( + name: "agents-tools", + url: "github.com/agents-tools/.github", + branch: "master", + subpath: ".agent" + ), + ], + components: [ + .instructions( + sections: [ + "guide", + .section("shared/swift-package-route", from: "agents-tools"), + .section("shared/swift-package-tests", from: "agents-tools"), + ], + agents: [.claudeCode, .codex] + ), + ] +) +``` + +A **producer** publishes content or a named group; a **consumer** selects it for +installation. A **recipient** is the agent that will read a component's native +configuration. This consumer narrows an exported group's recipients to Codex, +while its own indexing rule inherits Cursor as its default recipient: + +```swift +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + defaultAgents: [.cursor], + sources: [.local(name: "team", directory: "./team")], + components: [ + .ignore( + name: "build-products", patterns: [".build/"], purpose: .indexing, + condition: .when(scopes: [.project]) + ), + ], + uses: [ + .exported(name: "review", from: "team", condition: .when(agents: [.codex])), + ] +) +``` + +CLI, GUI and skill CLI send domain edits to one document layer. It maps edits to +source patches, reparses and validates the entire candidate, and passes it to +core's prepare/apply transaction. The manifest owns intent; the ledger owns +resolved deployment facts. Comments and untouched source bytes remain intact. + +## Motivation + +A typed Swift vocabulary provides reusable composition and editor completion +while static interpretation keeps reads independent of arbitrary code execution. +One component construction shape lets groups combine every family. Explicit +conditions and source provenance make deployment and conflicts explainable. + +The accepted [Swift manifest](../Decisions/SwiftManifest.md), +[component](../Decisions/AgentComponents.md) and +[approval](../Decisions/ExecutableApproval.md) decisions constrain this contract. + +## Proposed Change + +Adopt the vocabulary, static grammar, source editing, migration and JSON contract +below. Add the types-only `AgentsDescription` and document/compiler-front-end +`AgentsManifest` library products, with linking and native adapters in an internal +`Components` target. Keep shared IR, source storage, capabilities and transactions +in `AgentsCore`, and orchestration in `AgentsUpdates`. + +## Detailed Design + +### Construction vocabulary + +`AgentsDescription` is a compilable, types-only Swift module. Every manifest +accepted by the static evaluator must type-check against the matching module +with the real Swift compiler, including contextual factories, dictionaries and +literal conversions. Compiler type-checkability is a language 1.0 requirement; +editor integration, including making the module available to SourceKit-LSP, is +outside this contract. + +The interface below lists the entire public construction surface. Types conform +to `Sendable` and `Equatable`; factory results are immutable data. Opaque structs +have no public memberwise initializer. Literal-protocol initializers are compiler +entry points, invoked through literals in the manifest grammar. The module uses +the standard library and performs no I/O, registration, resolution or evaluation. +Public names are distinct from top-level standard-library, Foundation and SwiftUI +types so front ends can import those modules together. + +Factories and labels follow SwiftPM's authoring shape and the +[Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/). +Each component occupies one construction level. Its family-specific fields end +with the same `agents:`, `condition:`, `native:` tail. Payload storage is private. + +A **watch subscription** observes changes in a named source independently of +installation. **Install mode** chooses a link to verified cached content (`.link`), +a verified installed copy (`.copy`), or a live local skill link (`.edit`). Edit +mode has no immutable pin or content hash and requires a local source without a +requirement. + +#### Root, sources and composition + +```swift +public enum Agent: Sendable, Equatable { + case claudeCode, codex, cursor, geminiCLI, openCode +} +public enum Scope: Sendable, Equatable { case project, user } +public enum Platform: Sendable, Equatable { case macOS, linux } +public enum InstallMode: Sendable, Equatable { case link, copy, edit } + +public struct Condition: Sendable, Equatable { + public static func when( + agents: [Agent]? = nil, scopes: [Scope]? = nil, + platforms: [Platform]? = nil + ) -> Condition +} + +public struct Agents: Sendable, Equatable { + public init( + defaultAgents: [Agent]? = nil, sources: [Source] = [], + components: [Component] = [], groups: [ComponentGroup] = [], + uses: [GroupReference] = [], exports: [String] = [], watch: [String] = [] + ) +} + +public struct Source: Sendable, Equatable { + public static func git(name: String, url: String, subpath: String? = nil) -> Source + public static func git(name: String, url: String, from: String, subpath: String? = nil) -> Source + public static func git(name: String, url: String, exact: String, subpath: String? = nil) -> Source + public static func git(name: String, url: String, branch: String, subpath: String? = nil) -> Source + public static func git(name: String, url: String, revision: String, subpath: String? = nil) -> Source + public static func git( + name: String, url: String, upToNextMinorFrom: String, subpath: String? = nil + ) -> Source + public static func git( + name: String, url: String, from: String, to: String, subpath: String? = nil + ) -> Source + public static func local(name: String, directory: String, subpath: String? = nil) -> Source + public static func local( + name: String, directory: String, from: String, subpath: String? = nil + ) -> Source + public static func local( + name: String, directory: String, exact: String, subpath: String? = nil + ) -> Source + public static func local( + name: String, directory: String, branch: String, subpath: String? = nil + ) -> Source + public static func local( + name: String, directory: String, revision: String, subpath: String? = nil + ) -> Source + public static func local( + name: String, directory: String, upToNextMinorFrom: String, subpath: String? = nil + ) -> Source + public static func local( + name: String, directory: String, from: String, to: String, subpath: String? = nil + ) -> Source + public static func index(name: String, url: String, subpath: String? = nil) -> Source +} + +public struct ComponentGroup: Sendable, Equatable { + public init( + name: String, components: [Component] = [], uses: [GroupReference] = [], + condition: Condition? = nil + ) +} +public struct GroupReference: Sendable, Equatable { + public static func local(name: String, condition: Condition? = nil) -> GroupReference + public static func exported( + name: String, from source: String, condition: Condition? = nil + ) -> GroupReference +} +``` + +There is one `let agents = Agents(...)`, optionally annotated `: Agents`. +Other constants contain reusable values. Source names are lexical aliases, not +output paths. A **discovery root** is the source root with its optional safe +`subpath` applied; component and export discovery start there. Core owns source +identity normalization and requirement resolution. `from:` means up to the next +major version, `upToNextMinorFrom:` up to the next minor, and `from:to:` a +half-open range. `exact:`, `branch:` and `revision:` retain their existing meanings. +Prerelease matching and default latest-tag/default-branch selection remain core's +rules. Only a Git-backed local source accepts a requirement. `.index` represents +the existing well-known index kind and has no Git requirement. + +Source aliases follow the existing nonempty, colon-free string rule, with `.` +reserved for the declaring package. Escapes preserve otherwise valid string +contents. Two aliases for one normalized source identity in a document are errors. +Group and newly introduced named component identifiers are relative slash-separated +names with no empty, `.` or `..` segment, colon, backslash or control character. +Skill and instruction names retain their domain validators. ChatGPT prompt names +retain the existing arbitrary string-key namespace; they are not filesystem paths. +Names must be unique in their respective namespace. + +`exports: ["review"]` exports the group named `review`; export name and group name +are identical. A differently named wrapper group provides a renamed export. +`watch` is a unique array of declared source aliases, with no recipient or condition. Observed +baselines remain in `agents.watch`, not the manifest. Neither exports nor unused +groups cause deployment or subscriptions in a consumer. + +#### Literal values and supporting types + +```swift +public struct SkillSelection: Sendable, Equatable, ExpressibleByArrayLiteral { + public static var all: SkillSelection { get } + public init(arrayLiteral elements: String...) +} +public struct SkillOverride: Sendable, Equatable { + public init(name: String, mode: InstallMode? = nil, agents: [Agent]? = nil) +} +public struct SectionReference: Sendable, Equatable, ExpressibleByStringLiteral { + public init(stringLiteral value: String) + public static func section( + _ name: String, from source: String? = nil, condition: Condition? = nil + ) -> SectionReference +} +public struct ChatGPTPrompt: Sendable, Equatable { + public init( + name: String, sections: [SectionReference], append: String? = nil, + condition: Condition? = nil + ) +} +public struct Resource: Sendable, Equatable { + public init(path: String, from source: String? = nil) +} +public struct PromptContent: Sendable, Equatable, ExpressibleByStringLiteral { + public init(stringLiteral value: String) + public static func file(path: String, from source: String? = nil) -> PromptContent +} +public enum RuntimeValue: Sendable, Equatable, ExpressibleByStringLiteral { + case literal(String) + case environment(String) + case secret(String) + public init(stringLiteral value: String) +} +public struct ExecutableInvocation: Sendable, Equatable { + public static func executable( + _ executable: String, arguments: [String] = [], + environment: [String: RuntimeValue] = [:], workingDirectory: Resource? = nil + ) -> ExecutableInvocation +} +public indirect enum ConfigurationValue: Sendable, Equatable, + ExpressibleByStringLiteral, ExpressibleByIntegerLiteral, + ExpressibleByBooleanLiteral, ExpressibleByNilLiteral, + ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral +{ + case string(String) + case integer(Int) + case decimal(String) + case boolean(Bool) + case null + case array([ConfigurationValue]) + case object([String: ConfigurationValue]) + public init(stringLiteral value: String) + public init(integerLiteral value: Int) + public init(booleanLiteral value: Bool) + public init(nilLiteral: ()) + public init(arrayLiteral elements: ConfigurationValue...) + public init(dictionaryLiteral elements: (String, ConfigurationValue)...) +} +public typealias NativeConfiguration = [String: [String: ConfigurationValue]] + +public struct MCPTransport: Sendable, Equatable { + public static func stdio( + _ executable: String, arguments: [String] = [], + environment: [String: RuntimeValue] = [:], workingDirectory: Resource? = nil + ) -> MCPTransport + public static func streamableHTTP( + url: String, headers: [String: RuntimeValue] = [:] + ) -> MCPTransport + public static func sse(url: String, headers: [String: RuntimeValue] = [:]) -> MCPTransport +} +public enum HookEvent: Sendable, Equatable { + case beforeTool, afterTool, sessionStart, sessionEnd + case native(String) +} +public struct PromptParameter: Sendable, Equatable { + public init(name: String, description: String, defaultValue: String? = nil) +} +public enum PermissionOperation: Sendable, Equatable { + case read, write, execute + case tool(String) +} +public struct PermissionRule: Sendable, Equatable { + public static func allow(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule + public static func ask(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule + public static func deny(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule +} +public enum IgnorePurpose: Sendable, Equatable { case context, indexing } +public enum PluginMode: Sendable, Equatable { case native, components } +public enum ComponentKind: Sendable, Equatable { + case skills, instructions, mcpServer, hook, subagent, command + case lspServer, permissions, ignore, plugin +} +public enum ComponentReference: Sendable, Equatable { + case skill(String) + case instruction(String) + case mcpServer(String) + case hook(String) + case subagent(String) + case command(String) + case lspServer(String) + case permissions(String) + case ignore(String) + case plugin(String) +} +``` + +Literal conversions are closed and contextual. `PromptContent`, +`SectionReference` and `RuntimeValue` accept string literals; `SkillSelection` +accepts string array literals. `ConfigurationValue` accepts strings, signed +64-bit integer literals, booleans, `nil`, arrays and string-keyed dictionaries. +Decimals use `.decimal("1.25")`, with finite JSON-number text; floating-point +literals are outside the grammar. Native configuration is a dictionary keyed +by registry schema ID, with a string-keyed configuration object as each value. +Duplicate decoded keys, compared using Swift String equality including canonical +Unicode equivalence, are domain errors at every dictionary level, even if their +values are equal. There is no user-defined literal conformance or conversion +from an already-typed `String`, `[String]` or dictionary to a wrapper type. + +A bare section string names the declaring project's own instruction section; +`.section("engineering", from: "rules")` names a source section. A root user-scope +declaration uses named instruction sources. Exported own sections belong to the +producer package and may be consumed in either supported scope. Ordered sections, +Markdown rendering and **front matter** (the structured metadata preceding a +content file's body) retain their domain semantics. ChatGPT is a named prompt +rendering destination, not an `Agent`. Prompt `append` paths remain relative to +the project root in project scope and runtime home in user scope; exported +prompt append paths are attached to the producer snapshot. + +Omitted mode inherits the selection mode, then `.link`. Link and copy modes +preserve independent item pins. Omitted skill selection means all discovered +members; `[]` selects none. Exclusions win; overrides do not re-add excluded items. +An override outside an explicit selection is a `manifest.domain` error; +compatibility conversion of inert JSON overrides is defined under migration. +An all-member selection can retain overrides for members not yet discovered. + +`path` locates a resource inside the declaring package or a named source +discovery root; `subpath` narrows the source's own root before discovery. Resource +paths are safe relative paths. Project package roots are project directories; a user package root is its +user-state directory. Exported resources remain pinned to their producer. +Absolute resource paths, traversal and escaping symlinks are errors. Source +locations retain their existing absolute/home-relative path support. +Executables are fixed program names or package-relative executable paths, with +separate argument arrays. Shell interpretation requires an explicitly declared +shell command. Symbolic environment and secret bindings are resolved by core's +machine binding provider at apply, or emitted as native references where supported. +Reading and dumping do not fetch values. Previews redact secrets; locks retain +binding identity, not values. Secret rotation does not change command identity. + +A native schema ID, for example `claude-code/subagent@1`, identifies its agent, +component kind and adapter schema version. Agent identity is not repeated in the +value. Registry validation checks fields, client-version compatibility and the +component's recipients. A schema contributes only to its own agent and cannot +replace portable fields, conditions, resource identities, target paths, owned-key +boundaries or approval metadata. Collisions and unknown schemas/fields/types are +errors for active deployment. A native permission policy can use empty portable +rules when no exact portable translation exists. Native configuration remains +subject to ordinary preview, ownership and approval checks. + +#### Component factories + +```swift +public struct Component: Sendable, Equatable { + public static func skills( + from source: String, select: SkillSelection = .all, exclude: [String] = [], + mode: InstallMode? = nil, overrides: [SkillOverride] = [], + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func instructions( + sections: [SectionReference] = [], chatGPT: [ChatGPTPrompt] = [], + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func mcpServer( + name: String, transport: MCPTransport, + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func hook( + name: String, event: HookEvent, run: ExecutableInvocation, + matcher: String? = nil, timeoutSeconds: Int? = nil, + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func subagent( + name: String, description: String, prompt: PromptContent, + model: String? = nil, tools: [String]? = nil, + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func command( + name: String, description: String, prompt: PromptContent, + parameters: [PromptParameter] = [], + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func lspServer( + name: String, run: ExecutableInvocation, languages: [String: String], + initializationOptions: [String: ConfigurationValue] = [:], + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func permissions( + name: String, rules: [PermissionRule], + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func ignore( + name: String, patterns: [String], purpose: IgnorePurpose = .context, + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func plugin( + name: String, path: String, from source: String, + mode: PluginMode = .components, select: [ComponentKind]? = nil, + exclude: [ComponentReference] = [], + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component +} +``` + +| Family | Payload semantics | +| --- | --- | +| Skills | Selection, exclusions, installation mode and member overrides preserve membership tracking and item pins. Duplicate names and conflicting members are diagnosed. | +| Instructions | Contributions append sections in traversal order. Prompt names are unique; each prompt has its own ordered sections. | +| MCP server | Stdio, Streamable HTTP and SSE are distinct transports. HTTP(S) URLs have no embedded credentials or fragments. Transport conversion must be exact; all registrations require approval. | +| Hook | Portable events mean before/after a tool invocation and session start/end. Adapters preserve event and command-result behavior. `.native("event")` requires exactly one explicit agent recipient and uses that agent's event grammar. Matchers use its verified grammar. Timeouts are positive seconds; omission retains the native default. Hooks preserve declaration order. | +| Subagent | Description and prompt are portable text. Model/tool names are identifiers validated by the recipient adapter. Omitted tools inherit its default; `[]` requires no tools. | +| Command | A named user-invoked prompt. Unique parameter names appear as literal `${input:name}` tokens; `$${input:name}` escapes a token. Missing required inputs and undeclared tokens are errors. Substitution is text, not shell evaluation. | +| LSP server | A stdio executable invocation, an extension-keyed `languages` dictionary and initialization options. Each dot-prefixed extension key maps to one language ID; duplicate keys are domain errors, so one extension has one language by construction. Plugin-only recipients get an adapter-generated native plugin recorded in the ledger. | +| Permissions | `.allow(.read, "pattern")`, `.ask(.write, "pattern")` and `.deny(.execute, "pattern")` put the operation before its pattern. Ordered last-match rules, with no match inheriting native policy. Read/write patterns are scope-relative globs (`*`, `**`, `?`). Execute/tool patterns use the adapter's verified request representation. Translation must preserve the full policy, including unmanaged rules; otherwise deployment fails. | +| Ignore | Ordered gitignore-style patterns with `!` negation, rooted at scope. Context and indexing are separate purposes, neither an access-denial guarantee. | +| Plugin/extension | Components mode decomposes a pinned container and selects all kinds when `select` is omitted; `[]` selects none. Typed references exclude individual children. Native mode keeps the container unchanged, requires one explicit recipient in `agents`, and accepts neither selection nor exclusions. Native configuration may configure only its registration, not rewrite container content. | + +Capability validation checks every active agent/component/scope/feature against +the registry; unsupported requests are reported rather than dropped. Inactive +branches still undergo syntax, type and domain checks. Pending executable +approval is separate: apply deploys approved components and reports pending or +refused components as undeployed. Local additions approve their reviewed content +identity through core's mutation API. Imports and group declarations do not +approve transitive or future content. + +### Targeting + +`defaultAgents` supplies recipients when a component omits `agents`. The language +1.0 fallback is `{claude-code, codex}`. Explicit `agents`, including an empty +array, is the complete recipient set and replaces the default everywhere. +An exported component retains its producer's explicit set; it does not become +an intersection with consumer defaults. When the component omits `agents`, its +declaring document supplies the default, which is captured when exporting it, +including its language-version fallback. A producer omitting `defaultAgents` +publishes to Claude Code and Codex in language 1.0. Consumer defaults never +retarget imported content. + +A skill member's explicit override recipients replace its selection's recipients; +otherwise those selection recipients are its default. This is the same fallback +rule. A component discovered without a declaring manifest gets its default from +the enclosing selection. Producer front matter expresses conditions, never a +consumer-editable default. Imported metadata retains those conditions. + +For each component or selected member: + +```text +requested = explicitAgents ?? defaultAgents +active = requested ∩ agents admitted by every applicable condition +``` + +For candidate agent `a`, operation scope `s` and explicit platform context `p`, +`when(agents:scopes:platforms:)` is: + +```text +(agents == nil OR a belongs to agents) +AND (scopes == nil OR s belongs to scopes) +AND (platforms == nil OR p belongs to platforms) +``` + +Members within a dimension are OR; dimensions and nested conditions are AND. +A specified empty dimension is false; `.when()` is true. Duplicate members are +domain errors. Applicable conditions include front matter, the component, +its section, every enclosing `ComponentGroup` and every `GroupReference` in its +expansion chain. Group references expose only `condition` for narrowing. +Consumers can add conditions but cannot remove producer conditions or replace +published recipients. Scope selects one operation's destination, not a request +to write multiple scopes. Platform is data supplied to resolution, not a Swift +compile-time conditional. + +ChatGPT rendering has no agent recipient. For that destination, project each +condition onto scope/platform dimensions and preserve all those restrictions; +agent dimensions apply to native agent rendering only. Watch has no conditions +and is independent of this algebra. + +Registry checks follow targeting. Every unsupported active request is a +capability error with origin and reason; the tool does not silently filter it. +Physical visibility is checked independently: if a shared destination exposes +content to additional agents, prepare reports the extra readers. An explicit +producer-authorized sharing change or a registry-supported private location is +required. Consumers cannot override published restrictions to resolve such a +conflict. Targeting is deployment intent, not filesystem isolation. + +### Groups and source linking + +A `ComponentGroup` is an inert ordered fragment until selected by a +`GroupReference`. The root emits its components, then `uses` in order. Each group +emits its components, then recursively its `uses`, depth first. This defines +section, hook and policy contribution order. A source's root components, root +subscriptions and unrelated exports are not imported through a group reference. +The producer's defaults are captured as described under targeting. + +`exports: ["review"]` publishes that local group. A consumer writes +`.exported(name: "review", from: "team")`. To publish an existing group under a +new name, declare a wrapper `ComponentGroup(name: "quality", uses: +[.local(name: "review")])` and export `"quality"`. References do not import Swift +symbols. There are no wildcard exports, implicit exports or executable package +initializers. Duplicate group/export names and unknown local group names are +errors, including in unused declarations. + +A source manifest is `/.agent/Agents.swift`; when the discovery +root itself is `.agent`, it is `/Agents.swift`. Exactly one lookup +is performed. Conventional repositories need no manifest to provide skills or +instructions; an export request from such a source reports a missing export. +An index export must identify an immutable package artifact containing a manifest. +An index publishing only individual skills cannot satisfy a group reference. + +Aliases bind in the document that declares them. Within an exported component, +`from: "rules"` refers to the producer's alias; `.` refers to its package. +Relative local sources in a downloaded package must remain within that snapshot; +absolute, home-relative and escaping producer-local sources are invalid for +remote consumption. Root local sources retain core's existing path rules. +Qualified identity includes normalized source identity, snapshot, discovery root, +group name, component kind and component name. Different discovery roots retain +different namespaces even when they share a repository revision. + +Resolve one snapshot per normalized source identity for the export graph, +satisfying all requirements on that source. SemVer constraints intersect; choose +the greatest permitted version. Explicit branch/revision constraints must name +the same commit; mixed version and revision constraints require a matching +permitted tag at that commit. Core owns version ordering and tag tie-breaking. +Resolve dependencies to a complete consistent graph, with deterministic descending +version candidates and normalized-source-ID ordering for equally eligible next +choices; backtrack on incompatible transitive requirements within the link budget. +An unsatisfiable graph reports both dependency paths. Existing direct skill and +section pins remain item-specific and are not upgraded by group resolution. + +The ledger records every reference with source identity, discovery root, effective +requirement, exact revision/artifact digest, manifest digest, group name and full +child closure. Non-Git local export packages receive content-addressed snapshots; +explicit edit-mode skill children remain live. `install` restores the recorded +closure without consulting a mutable index or branch. `update` re-resolves the +affected closure and previews changes. Pins are never copied into the manifest. + +Cycle detection follows the active local/cross-source reference stack before +memoization and reports the cycle with source spans. A diamond is not a cycle. +Repeated references retain occurrence provenance. Conflicting active payloads +for the same named identity and overlapping recipients are errors. Equal named +hooks/policies coalesce at their first position to avoid duplicate execution; +ordered instruction sections retain intentional repetition. Disjoint targeting +may reuse a name. + +Skill selections expand to member identities; instruction contributions form +ordered section streams; adapters may aggregate disjoint structured entries. +These explicit aggregations retain every owner. Other collisions on physical +names, paths or keys fail, even across different aliases. Permission aggregation +must preserve the entire ordered policy including unmanaged rules. There is no +last-writer-wins merge or implicit deployment rename. Resolve conflicts through +producer naming, selection/exclusions or conditions. + +### Examples + +#### showxu/skills + +The skills repository's existing declaration converts to: + +```swift +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + components: [ + .instructions( + sections: ["guide", "code-review-rules"], + agents: [.claudeCode, .codex] + ), + ] +) +``` + +#### Producer + +A package at `team` publishes this `team/.agent/Agents.swift`. Its own instruction +sections live under `team/.agent/instructions/`; skills follow source discovery +conventions. The project condition prevents deployment of this group in user scope. + +```swift +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + groups: [ + ComponentGroup( + name: "review", + components: [ + .instructions(sections: ["review-principles"], agents: [.claudeCode, .codex]), + .skills(from: ".", select: ["review"], mode: .copy, agents: [.claudeCode, .codex]), + ], + condition: .when(scopes: [.project]) + ), + ], + exports: ["review"] +) +``` + +#### Consumer with every component family + +This consumer combines local and exported groups. The exported reference selects +Codex from the producer's two recipients; its local subagent runs only on macOS. +The plugin container activates only in user scope. Files, commands, native schema +IDs and source exports are validated during resolution, not accessed by parsing. + +```swift +// agents-tools-version: 1.0 +import AgentsDescription + +let base: [SectionReference] = ["guide"] +let sections = base + [.section("engineering", from: "rules")] +let reviewer: Component = .subagent( + name: "reviewer", + description: "Review correctness and tests.", + prompt: "Check invariants and explain concrete failures.", + agents: [.claudeCode], + condition: .when(platforms: [.macOS]), + native: ["claude-code/subagent@1": ["memory": "project"]] +) + +let agents = Agents( + sources: [ + .local(name: "team", directory: "./team"), + .local(name: "drafts", directory: "./draft-skills"), + .git(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), + .index(name: "catalog", url: "https://example.org/skills/index.json"), + .git(name: "vendor", url: "https://example.org/vendor/tools.git", exact: "2.1.0"), + ], + components: [ + .skills( + from: "rules", exclude: ["experimental"], mode: .copy, + overrides: [SkillOverride(name: "testing", mode: .link, agents: [.codex])] + ), + .skills( + from: "drafts", select: ["draft"], mode: .edit, + condition: .when(agents: [.claudeCode], scopes: [.project]) + ), + .instructions( + sections: sections, + chatGPT: [ChatGPTPrompt(name: "weekly", sections: base, append: "notes/weekly.md")] + ), + .mcpServer( + name: "workspace", + transport: .stdio( + "workspace-tools", arguments: ["serve"], + environment: ["TOKEN": .secret("workspace-token"), "LOG_LEVEL": "info"] + ), + agents: [.claudeCode] + ), + .mcpServer( + name: "reference", + transport: .streamableHTTP( + url: "https://example.org/mcp", headers: ["Authorization": .environment("MCP_AUTH")] + ), + agents: [.openCode] + ), + .hook( + name: "format", event: .afterTool, + run: .executable("swift", arguments: ["format", "--in-place", "Sources"]), + timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) + ), + .command( + name: "review/change", description: "Review a selected change.", + prompt: "Review ${input:change} and cite evidence.", + parameters: [PromptParameter(name: "change", description: "The change to review.")], + agents: [.claudeCode] + ), + .lspServer( + name: "swift", run: .executable("sourcekit-lsp"), + languages: [".swift": "swift"], + initializationOptions: ["backgroundIndexing": true], + agents: [.claudeCode], condition: .when(platforms: [.macOS]) + ), + .permissions( + name: "private-files", + rules: [.deny(.read, "secrets/**")], + agents: [.claudeCode], condition: .when(scopes: [.project]) + ), + .ignore( + name: "build-products", patterns: [".build/", "DerivedData/"], purpose: .indexing, + agents: [.cursor], condition: .when(scopes: [.project]) + ), + .plugin( + name: "vendor-tools", path: "plugins/tools", from: "vendor", mode: .native, + agents: [.claudeCode], condition: .when(scopes: [.user]) + ), + .plugin( + name: "shared-tools", path: "plugins/shared", from: "vendor", + exclude: [.hook("format")], condition: .when(scopes: [.project]) + ), + ], + groups: [ + ComponentGroup( + name: "review-tools", components: [reviewer], + uses: [.exported(name: "review", from: "team", condition: .when(agents: [.codex]))] + ), + ], + uses: [.local(name: "review-tools")], + watch: ["rules", "catalog"] +) +``` + +### Files, versions and static grammar + +Project source is `.agent/Agents.swift` relative to the explicit project root; +user source is `~/.agents/Agents.swift` relative to core's runtime home. Their +locks remain adjacent `agents.resolved` files. There is no ancestor search or +automatic user/project merge. An absent manifest means an absent declaration. +Existing `agents.json` requires migration; both filenames present is a conflict. + +The first line is exactly `// agents-tools-version: 1.0`, at byte zero after an +optional UTF-8 BOM, terminated by LF, CRLF or EOF. General version syntax is +`// agents-tools-version: MAJOR.MINOR`, with the shown spaces, decimal components +without leading zeroes except `0`, and no patch, suffix or trailing whitespace. +A missing, malformed, duplicate or unsupported directive has its own diagnostic. +Directive recognition is lexical: a directive-shaped line comment outside a +string is a duplicate; text inside a string literal is ordinary content. +A 1.0 reader accepts exactly `1.0`. A future reader explicitly declares its support +set. Newer unsupported versions request an upgrade; older unsupported versions +request a supported converter. Language, package, adapter, lock and dump versions +are independent. Editing preserves BOM/newlines; migration emits UTF-8 without BOM. + +Exactly one unqualified `import AgentsDescription` precedes top-level initialized, +single-binding `let` declarations. Names use the identifier grammar below, are +unique and cannot shadow vocabulary types. Constants bind in textual order; references to later constants +or themselves fail. There are no modifiers, attributes, wrappers or semicolons. +Every declaration, including unused constants and inactive branches, is checked. +Group-name references are resolved separately and may refer forward. + +| Accepted syntax | Rule | +| --- | --- | +| `SourceFileSyntax`, `ImportDeclSyntax`, `VariableDeclSyntax` | The file structure above, with one identifier-pattern binding and initializer per declaration. | +| `StringLiteralExprSyntax` | Single-line and multiline literals from the closed lexical grammar below, with Swift decoding and no interpolation. | +| Integer, Boolean and nil literals | Decimal signed-64 integers with underscore separators, Bool and contextual nil. One unary minus is accepted only immediately adjacent to a decimal integer literal, with no intervening trivia. Other bases, floating literals and other numeric operators fail admission. | +| `ArrayExprSyntax` | Homogeneous arrays or a contextual, whitelisted array-literal conversion. Trailing commas are allowed. Empty literals require contextual type. | +| `DictionaryExprSyntax` | String-literal keys, homogeneous contextual values, or a contextual configuration object. `[:]` is an empty dictionary. Keys are decoded before duplicate detection; key references/interpolation are rejected. | +| `DeclReferenceExprSyntax` | A preceding constant, a vocabulary type as a member/call base, or the permitted operator. | +| Sequence/folded infix expressions | Only left-associative array `+` with exact `[T]` operands, at most 32 terms per additive chain. No concatenation of selections or configuration values, dictionary merging, string concatenation, range expressions or other operators. | +| `TupleExprSyntax` | One unlabeled expression in parentheses, not tuple values. | +| `MemberAccessExprSyntax` | Listed static factories, static `.all`, and enum cases, qualified or contextual. No instance-property access, subscripts or optional chaining. | +| `FunctionCallExprSyntax` | Listed ordinary initializers spelled with the bare type name, factories and associated cases, with exact labels and order. Literal-protocol entry points are reached only through literals. No arbitrary functions or trailing closures. | +| Type annotations | `String`, `Int`, `Bool`, named vocabulary types/aliases, `[T]` and `[String: T]`. No explicit Optional annotations, user aliases, qualified/generic/existential/function/metatype syntax. | + +Grammar admission precedes SwiftParser and the iterative tree check precedes all +recursive SwiftSyntax processing. The normative productions below and the syntax +node table describe the same constructs, subject to the byte, token, chain and +depth limits below. These limits apply even to unused or inactive +expressions. Parser recovery, missing tokens and unexpected syntax are errors. +Tokens inside accepted nodes are admitted only in the roles above. Constructors create data; +they never invoke Swift compiler code while evaluating a manifest. + +#### Type inference and literal conversions + +An annotation or parameter type supplies context inward. Otherwise literals, +qualified calls and references synthesize types outward. Without context, a +string is `String`, an integer is `Int`, and a boolean is `Bool`. Arrays infer +from the first element; dictionaries infer from the first value and require all +other values to agree. Empty collections, nil and a leading shorthand member +cannot infer a type alone. Dictionary keys are always strings. + +Optional parameter types remain part of the construction API: their context +admits `nil` or injection of a value of the wrapped type. Source annotations use +the non-Optional forms in the grammar; `T?` and `Optional` fail grammar admission. +This does not change the module's public Optional signatures or compiler typing. + +In contextual vocabulary types, only the literal conformances declared above +apply. Nested configuration literals propagate `ConfigurationValue` context to +every child. For an Optional parameter with wrapped type `T`, nil means absence; +non-nil values may receive `T` context and Optional injection. For non-Optional `ConfigurationValue`, nil means +configuration null. Signed integer literal conversion follows Swift's literal +semantics and must fit the declared literal type. `.decimal(...)` remains explicit. +No arbitrary user protocol dispatch or conversion of pre-existing typed values +is allowed. In particular, a `String` constant is not implicitly a `PromptContent` +or a `SectionReference`, and a `[String]` constant is not a `SkillSelection`. + +For array `+`, context propagates to both operands when present; otherwise infer +the left array and use its element type for the right array. An expression of +`SkillSelection` or `ConfigurationValue` type is not a Swift array. Constants +must be typed where declared, not inferred backward from later uses. A standalone +component is `let reviewer: Component = .subagent(...)` or a fully qualified +factory call. The evaluator's accepted language is a subset of real Swift typing, +not an alternative type system. + +| Diagnostic | Meaning | +| --- | --- | +| `manifest.version.missing`, `.invalid`, `.duplicate`, `.unsupported` | Version selection failed. | +| `manifest.syntax` | Recognizer: a lexical or production violation, including missing/extra imports, juxtaposed identifiers, unsupported prefixes, raw strings, interpolation and malformed literals. SwiftParser syntax/recovery diagnostics can occur only after recognizer acceptance and the tree guard; such a disagreement is also an implementation regression. | +| `manifest.call`, `manifest.type`, `manifest.operator` | After the tree guard: unlisted call/member, incorrect labels/order/type, missing context, integer overflow or non-array use of the admitted `+` operator. Other operators fail admission. | +| `manifest.reference` | Unknown, forward, self, duplicate or shadowing constant name. | +| `manifest.domain`, `manifest.dictionary.duplicateKey` | Invalid domain value or duplicate decoded dictionary key. | +| `manifest.group.cycle`, `.missing`, `.conflict` | Invalid group/source graph, with the relevant reference chain. | +| `manifest.limit` | Recognizer: byte, token, syntax-storage reservation, comment, delimiter or chain limit. Iterative tree guard: node/depth limit. Later stages: evaluation, expansion, output or other named budget. | + +Diagnostics include stable code, severity, message, primary span, related spans +and optional suggested edit. Spans use half-open UTF-8 byte offsets and 1-based +line/UTF-8-byte-column positions. At most 100 diagnostics plus one truncation +notice are produced. Any structural/type/domain error rejects the candidate; +no partial declaration is published. + +#### Normative admission grammar + +`AgentsManifest` owns a strict lexer and a deterministic recognizer for these +productions. No byte reaches SwiftParser until the complete input snapshot passes +recognition. SwiftParser supplies the lossless tree for editing and diagnostics; +it does not decide which source grammar is admitted. The recognizer does not +resolve constants or evaluate constructors. The subsequent type/domain checks +restrict identifiers and calls to the vocabulary and rules above. + +The grammar uses `?` for optional, `*` for repetition and `|` for alternatives; +quoted punctuation denotes source tokens. Trivia may separate tokens except at +explicitly contiguous spellings. `newline` means at least one LF, CRLF or CR in +the separating trivia. The version directive is checked as specified above using +the same lexer's comment/string boundaries, before syntax is handed to SwiftParser. + +```ebnf +document = "import" "AgentsDescription" newline declaration + (newline declaration)* EOF ; +declaration = "let" bareName (":" type)? "=" expression ; +type = typeName | "[" type "]" | "[" "String" ":" type "]" ; +expression = primary ("+" primary)* ; +primary = string | integer | "-" integer | "true" | "false" | "nil" + | namedValue | array | dictionary | "(" expression ")" ; +namedValue = callee ("(" arguments? ")")? ; +callee = bareName | bareName "." name | "." name ; +arguments = argument ("," argument)* ; +argument = (name ":")? expression ; +array = "[" (expression ("," expression)* ","?)? "]" ; +dictionary = "[" ":" "]" + | "[" string ":" expression + ("," string ":" expression)* ","? "]" ; +``` + +`typeName` is exactly `String`, `Int`, `Bool`, or a public vocabulary type/alias +listed in §2. Type existence is checked during recognition. `callee` is a +syntactic spelling; subsequent vocabulary checking rejects unlisted functions, +instance members, literal-protocol entry points and invalid factory labels. +There is no postfix loop: a callee has at most one member operation and one call, +for a maximum grammatical chain of **2**. The independent postfix-operation +counter has a ceiling of **4** per primary; budget headroom admits no additional +production. No operation attaches to a call result, grouped +expression or subscript. The leading shorthand dot counts as one operation. +These are exactly the construction forms needed by the vocabulary. Parentheses +contain one expression; calls have no trailing comma; collections may have one. +The sole infix production has at most **32 terms**, with later type checking +requiring array operands. No assignment expression or prefix-keyword production +exists. An identifier after a completed expression is a syntax error, not an +implicit prefix, argument or declaration. + +The lexical grammar is closed: + +- An identifier has ASCII head `[A-Za-z_]` and continuation `[A-Za-z_0-9]*`. + Backticks, `$` names and non-ASCII identifiers are excluded; Unicode remains + available in string values, including all domain names and paths. `name` excludes + the reserved spellings listed below. `bareName` additionally excludes `await`, + `copy`, `consume`, `each` and `unsafe`; those contextual spellings may occur as + argument labels or member names, including `.copy`. They cannot introduce a + prefix production or a bare binding/reference/callee in language 1.0. +- `integer` is `[0-9][0-9_]*`. The optional minus is a separate token immediately + adjacent to its digits and only in the shown primary production. Its preceding + source character must be ASCII whitespace (space, tab, CR or LF), `(`, `[`, `,` + or `:`; an adjacent operator or comment terminator cannot precede the sign. + Range checking follows during typing. There are no floating-point, exponent or + radix literals; + decimal configuration values use `.decimal("1.25")`. +- `string` is an ordinary double-quoted single-line literal or a triple-quoted + multiline literal. Both allow exactly `\0`, `\\`, `\t`, `\n`, `\r`, `\"`, `\'` + and `\u{H}` escapes, where `H` is one to eight ASCII hex digits naming a Unicode + scalar (not a surrogate and at most `10FFFF`). Interpolation and escaped newline + continuation are excluded. A single-line literal contains no unescaped CR/LF. + A multiline opener is followed immediately by LF, CRLF or CR; its closing + delimiter is preceded on its line only by spaces. A content line is either + empty (zero characters before its newline) or starts with the closing delimiter's + exact space indentation prefix, which Swift decoding removes. Additional leading + spaces remain content. Whitespace-only lines are nonempty and must carry the + full prefix. A tab anywhere in a content line's leading whitespace or in the + closing delimiter's indentation is a syntax error; tabs after the first + non-whitespace content character remain literal content. These rules apply + identically to LF, CRLF and CR lines. Unescaped single/double quote runs are + multiline content; the first + unescaped triple quote closes it. Unescaped control scalars below U+0020 other + than tab and multiline CR/LF are rejected. Raw strings do not exist: `#` outside + string/comment content always fails recognition. +- Trivia is ASCII space, tab, LF, CRLF or CR, an optional BOM at byte zero, `//` + comments through the next CR/LF or EOF, and `/* ... */` comments with at most + **20** nested levels. The lexer validates UTF-8 throughout the snapshot. Strings + and comments are opaque to expression counters. No other whitespace or comment + form is admitted. +- Source punctuation is `( ) [ ] , : . = +` and the adjacent numeric sign `-`, + only in the roles in the productions. Callee member spellings contain no trivia + around their dot; the call opener immediately follows its callee. Both `=` and + binary `+` require at least one ASCII whitespace character (space, tab, CR or LF) + immediately on each side. Comments do not substitute for whitespace: every + comment in an operator-to-operand gap must itself have whitespace immediately + before and after it. Thus `value /* note */ = -1` is admitted, but `value=0`, + `value= 0`, `value=-1`, `a+b` and `a/* note */ + b` fail recognition. A located + `manifest.syntax` diagnostic names the canonical spelling, such as + `let value = -1` or `left + right`. These adjacency rules make + Swift operator/member tokenization unambiguous. Other operators, generic angle + brackets, braces, attributes, directives, macros and regex literals fail at + recognition. There is no fallback to SwiftParser recovery. + +The exact reserved identifier spellings are: + +```text +_ Any Self as associatedtype break case catch class continue default defer deinit +do else enum extension fallthrough false fileprivate for func guard if import in +init inout internal is let nil open operator precedencegroup private protocol public +repeat rethrows return self static struct subscript super switch throw throws true +try typealias var where while +``` + +The lexer consumes each byte a bounded number of times, without backtracking or +unbounded lookahead. The parser uses at most two tokens of lookahead to distinguish +argument labels and dictionary entries, bounded delimiter frames for nested +productions, and loops for siblings and additive terms. It never speculatively +parses a whole expression and rewinds. Its work, storage, literal validation and +located-diagnostic construction are linear in bounded input size. A failure ends +recognition with a located `manifest.syntax` or `manifest.limit`; SwiftParser is +not called. Accepted grammar structure and spans are retained for differential +validation, independently of the later semantic IR. + +#### Expanded-size accounting and resource limits + +Admission reads at most 2,097,153 bytes, rejecting the extra byte before decoding, +lexing or parsing; it never allocates an unbounded file buffer. The exact admitted +snapshot is subsequently parsed. The recognizer permits at most 100,000 non-trivia +tokens; the minus and integer count separately. It additionally reserves syntax +storage conservatively as **16 + 4 × (tokens + literal breaks + literal escapes)**, +capped at 100,000 nodes before SwiftParser is invoked. A literal break is each +CR or LF byte inside a string (CRLF counts twice); a literal escape is each +backslash byte inside a string, including escaped backslashes. These extra units +cover the parser's segmentation of multiline/escaped literals. The grammar-derived +reservation covers file and wrapper nodes as well as tokens; the independent +post-parse guard verifies actual counts. +A parser dependency change must revalidate the reservation against every grammar +production. The reservation is a language budget even when an individual input's +actual tree would be smaller; migration preflight applies it too. + +Every open `[` or `(` increments a grammar counter before entering the enclosed +production, including type annotations. Square depth above **8** or combined +depth above **20** is `manifest.limit` at the first excess opener. Block-comment +depth above 20, a thirty-third additive term or an excess token/storage reservation +likewise fails before parsing. All other missing, misplaced or unsupported tokens +are `manifest.syntax` at the expected production's location (EOF for missing +input). Unbalanced openers remain counted until rejection; neither trivia nor +parenthesized subexpressions can bypass the counters. No production permits more +than two postfix operations or more than one numeric sign. These grammar bounds +apply equally to unused constants and inactive components. + +Immediately after parsing, an **iterative, non-recursive** walk checks all syntax +nodes, including collections, tokens, missing nodes and unexpected nodes, in the +all-nodes view. The root has depth 1; depth above **128** or more than **100,000** +nodes is `manifest.limit`. Reserve stack/node budget before enqueueing children; +compute failure offsets from cached byte lengths during the walk. Do not call +recursive visitors, `hasError`, diagnostic generation, tree descriptions, source +mapping, equality or evaluation before this guard succeeds. The same rule applies +to transformed/folded trees: build/check them iteratively before recursive use. +The tree ceiling is independent of source delimiter depth and leaves room for +SwiftSyntax's wrapper nodes. Evaluation retains its separate frame/work limits. + +No manifest input within the byte limit may crash or hang the hosting process, +including the GUI. Invalid and over-budget input must end in a bounded diagnostic +without writes or partial IR publication. This is a required implementation and +release invariant, not a conclusion inferred from `maximumNestingLevel` or a +finite set of passing examples. Parser construction, error inspection, tree +lifetime/teardown and every consumer of syntax are included in the invariant. + +The square-bracket ceiling is **8**, independently of the general delimiter +ceiling of **20**. The complete manifest examples in this contract reach depth +3. Fixed family fields, excluding recursive configuration values and arbitrary +nested array constants, reach depth 5: root groups, components, ChatGPT prompts, +sections, then a section condition's recipient array. +Eight leaves three levels of syntax-depth margin over that fixed structure. +`ConfigurationValue` is recursive, so its vocabulary has no intrinsic finite +nesting maximum; its expanded values remain limited to depth 64. Named constants +allow deeper configuration values to be assembled without deep source nesting, +subject to all expansion budgets. This separates authoring depth from value depth +and caps square-bracket ambiguity before parser recovery. The parser's own +nesting option remains defense in depth, not a parse-time bound. + +The evaluator may store immutable values as a DAG, but all limits are measured +as if each reference were expanded by value. Each value carries a checked cost +summary: expanded node count, decoded string/key bytes, canonical encoded byte +count, maximum depth and source-origin count. For a container, costs are its own +cost plus the sum of each child's costs **for every occurrence**. Reusing a +constant twice adds its full cost twice, including all descendants. An alias +inherits the referenced cost; memoization does not discount expansion. + +Compute costs bottom-up with checked, saturating arithmetic capped at the limit +plus one. Before concatenation, reference insertion, group expansion or any output +allocation, combine the summaries and reject an oversized result. No descendant +walk, copying, formatting, map expansion or equality comparison occurs first. +This rejects exponential reuse such as repeated `array([previous, previous])` +while that value is constructed, even when its underlying storage is small. +Every constant must fit individually; totals count every top-level definition +and every root occurrence, including inactive and unused values. + +Encoded-size summaries include repeated dictionary keys, string escaping, +punctuation, indentation and trailing newline. Before writing a dump or generated +source, reserve its complete bounded size from those summaries. When formatting +context changes indentation, use a checked worst-case bound or recompute the +summary over the bounded structure before emitting bytes. Locations and provenance +are separately budgeted and included in the final dump's size reservation. + +| Resource | Language 1.0 bound | +| --- | --- | +| Input | 2,097,152 UTF-8 bytes per manifest, enforced by bounded reading before grammar admission, decoding or parsing; invalid UTF-8 fails. | +| Admission | Linear lexer and grammar recognizer; 100,000 tokens; syntax reservation `16 + 4 × (tokens + literal breaks + literal escapes) ≤ 100,000`; square depth 8; combined square/parenthesis depth 20; comment depth 20; postfix-operation budget 4 (the grammar uses at most 2); one adjacent numeric sign; additive chain 32 terms. Failures reject before SwiftParser. | +| Parser/tree | `maximumNestingLevel: 20` in every build configuration. Iterative guard: depth 128 (root 1), 100,000 syntax nodes including tokens and excluding trivia, before any recursive processing. | +| Evaluator | 64 active expression/reference frames; 100,000 work steps per document. Every visited expression, lookup, produced node and concatenation element costs a step. | +| Expanded values | 100,000 nodes and 16,777,216 decoded string/key bytes across the document's values, charged by occurrence, with 10,000 entries per array/dictionary and maximum expanded value depth 64, including referenced descendants. | +| Linking | 256 distinct source snapshots, 16,777,216 aggregate manifest input bytes, 64 active group references, 10,000 component contributions and 1,000,000 total resolution/evaluation steps, including backtracking. Linked expanded values also obey the node/string limits above. | +| Source maps | 100,000 location records, 1,000,000 total origin spans and 16,777,216 encoded bytes; repeated origins count repeatedly. Reserve before expanding a reference's map. | +| Output | 33,554,432 bytes for the entire dump including locations/diagnostics; generated manifest source still obeys the 2,097,152-byte input limit. | +| Comparison/edit batch | 200,000 expanded node-pair visits per full comparison; 1,000,000 aggregate steps and 100 requests per edit batch. Operand cost summaries are checked before comparison starts. | + +A work budget is charged before executing a step; exhaustion is a diagnostic, +not an invitation to return a truncated model. Comparisons can use identity or +memoization only after verifying expanded operand bounds. Diagnostics and JSON +escaping are bounded operations. Source download/extraction limits remain in +core's loader before the linker receives bytes. Cancellation is separate from +language semantics. Fuzzing and adversarial reuse tests cover every bounded +consumer of values, not just the parser. + +### Document editing + +`AgentsManifest.DeclarationDocument` owns original bytes, syntax, declaration IR, +source maps, diagnostics, editability and the original byte digest. Domain edits +use the same vocabulary names as authored values; lowering converts them to core +IR. Snapshot node handles are separate from persistent component identities. + +```swift +public struct DeclarationDocument: Sendable { + public init(bytes: [UInt8], identity: DocumentIdentity) throws + public var declaration: DeclarationIR { get } + public var diagnostics: [ManifestDiagnostic] { get } + public func editability(of node: NodeID) -> Editability + public func preparing(_ edits: [ManifestEdit]) throws -> DocumentChange +} +public enum ManifestEdit: Sendable { + case setDefaultAgents([Agent]?) + case upsertSource(Source) + case removeSource(alias: String) + case insertComponent(Component, into: ContainerID, at: InsertionPosition) + case replaceComponent(NodeID, with: Component) + case removeComponent(NodeID) + case moveComponent(NodeID, into: ContainerID, at: InsertionPosition) + case setSkillSelection(NodeID, SkillSelection) + case upsertSkillOverride(NodeID, SkillOverride) + case removeSkillOverride(NodeID, name: String) + case insertSection(SectionReference, into: NodeID, at: InsertionPosition) + case removeSection(NodeID) + case moveSection(NodeID, at: InsertionPosition) + case upsertPrompt(NodeID, ChatGPTPrompt) + case removePrompt(NodeID, name: String) + case upsertGroup(ComponentGroup) + case removeGroup(name: String) + case insertGroupReference(GroupReference, into: ContainerID, at: InsertionPosition) + case removeGroupReference(NodeID) + case setExports([String]) + case setWatch([String]) + case setDictionaryEntry(NodeID, key: String, value: StaticValue) + case removeDictionaryEntry(NodeID, key: String) + case replaceConstant(NodeID, with: StaticValue, acceptingUses: [NodeID]) +} +``` + +`NodeID` is an opaque handle bound to the document digest. `ContainerID` addresses +the root or a group. `InsertionPosition` is `.first`, `.last`, `.before(NodeID)` +or `.after(NodeID)`. `StaticValue` is the bounded checked algebra of literals, +collections and vocabulary values, not raw Swift text. Dictionary value edits +must match the target's inferred value type. Whole-component replacement covers +recipients, conditions and all family-specific fields. + +The document applies requests in order to construct the expected complete IR, +checks their complete impact and budgets, and produces disjoint byte patches. +`DocumentChange` contains the original digest, patches, resulting bytes/digest, +expected declaration, impacted references, diagnostics and semantic delta. +Only the document layer constructs it. `AgentsUpdates` incorporates it in prepare; +front ends never save source independently. + +| Construct | Editability | +| --- | --- | +| Direct literal/factory argument | Replace the exact value range; retain outer trivia. | +| Direct array literal | Insert, remove and move identifiable elements, preserving order. | +| Direct dictionary literal | Set/remove a decoded key's value or entry; preserve unrelated entries and their order/comments. | +| Direct root/group/component construction | Insert missing arguments in signature order and remove/replace unambiguous arguments. | +| Constant reference | Readable with all references identified. Only explicit `replaceConstant` changes its definition, accepting the complete impacted reference set. | +| Concatenation/assembled value | Readable; expanded element edits are read-only. An independently addressed literal leaf or explicitly replaced constant can be edited with its full impact accepted. | +| Exported declaration | Read-only in a consumer. Edit its `GroupReference.condition` or the producer's own document, never cached source. | +| Ambiguous trivia or separators | `manifest.edit.readOnly` with a span and reason; no regeneration fallback. | + +Removing referenced sources/groups requires a complete batch that repairs the +references. Stale handles, overlaps, incomplete impact and mismatched results have +separate `manifest.edit.stale`, `.overlap`, `.impact`, `.mismatch` diagnostics. + +Comments follow SwiftSyntax trivia ownership: + +1. Standalone comments immediately above a node with no separating blank line + belong to that node; a dictionary key and value form one entry node. +2. Comments beginning on a node's or its comma's line belong to that preceding + node, including multiline block comments. +3. Comments inside an expression or between it and its comma belong to it. +4. Comments separated from the next node by a blank line belong to the container. + The preamble and version directive belong to the file. +5. Delete/move operations carry owned comments. Value replacement preserves outer + comments; whole-node replacement refuses if internal comments cannot be mapped + to retained fields. Unowned comments remain in place. +6. Empty containers become `[]` or `[:]` only when their interiors are whitespace. + Container comments survive; ambiguous mixed layouts or comment-only insertion + sites are read-only. + +New nodes use the shortest canonical type-correct spelling: strings for prompts +and own sections, array literals for explicit skill selections, dictionaries and +JSON-style configuration literals, direct component factories and labeled source +requirements. Existing unmodified expressions keep their spelling. New text uses +the container's consistent indentation, newline and comma style; absent evidence, +use two spaces, LF and trailing commas in multiline collections. Argument order +follows signatures. Fresh node layout follows the deterministic migration printer; +existing surrounding style takes precedence. Conflicting local style is an +editability diagnostic, not permission to reformat the file. + +The editor and migration printer emit one ASCII space on each side of `=` and +`+`, with adjacent sign/digits for negative integers: `let value = -1`. A value +replacement re-checks both joins with the unchanged source, including neighboring +comments, against the lexical rules before it becomes a patch. For example, +replacing `0` in `[/* note */0]` emits ` -1` inside that value's replacement range, +producing `[/* note */ -1]` while preserving all bytes outside the range. The +editor never joins a sign to `=` or to a comment terminator. A source that already +fails recognition, such as `let value=0`, cannot receive a domain edit. If a safe +boundary cannot be represented in the authorized patch range, preparation fails +with an editability diagnostic. The complete candidate passes recognition again +before SwiftParser is invoked; a failed check publishes no patch or source bytes. + +The invariants are byte-exact no-op return, byte preservation outside disjoint +patch ranges, and full reparse/type-check/evaluation/domain validation before +commit. The resulting complete IR must equal the expected IR, including inactive +groups and exports; only source positions and trivia are excluded. Prepare then +re-links affected sources and revalidates capabilities/targets. All stages use the +expanded-size budgets. BOM, final-newline presence and unrelated bytes survive. + +### Evaluated JSON dump + +`agents manifest dump --json` reads and evaluates only the local declaration. +It does not resolve external groups, fetch sources/secrets, inspect native files +or compile/run the manifest. Conditional branches and group references remain +symbolic. Successful stdout is one UTF-8 JSON object with sorted keys, two-space +indentation and a trailing LF. Invalid input exits 1 with stderr diagnostics and +no partial success object. + +The root has `schemaVersion: 1`, `kind: "manifest"`, `languageVersion: "1.0"`, +`sourceDigest`, `declaration`, `locations` and `diagnostics`. The digest is +`sha256:` plus 64 lowercase hexadecimal digits over the original bytes. +`declaration` has `defaultAgents`, `sources`, `components`, `groups`, `uses`, +`exports` and `watch`. Default arrays are empty, Optional absence is null, and +explicit empty recipients remain distinct from inheritance. + +A component encodes directly as `{ "kind": "mcpServer", "name": "workspace", +"transport": { ... }, "agents": ["claude-code"], "condition": null, +"native": {} }`. There is no payload wrapper. The remaining schema is determined +by the vocabulary as follows: + +- Opaque factory values encode `{kind, ...fields}`. Component/transport kinds are + their factory names. `ExecutableInvocation` is `kind: "executable"` with executable, + arguments, environment and workingDirectory. Group references are `local` or + `exported`, with name, optional source and condition. Conditions encode their + three dimensions without a kind. Permission rules encode + `{kind: "allow" | "ask" | "deny", operation, pattern}`; their two unlabeled + factory arguments use the keys `operation` and `pattern`. LSP `languages` + encodes an object mapping extension keys to language-ID strings. +- A source has `kind: "git" | "local" | "index"`, name, location (`url` or + `directory`), subpath and requirement. Requirement is null or an object with + exactly one of branch/revision/exact/from/upToNextMinorFrom, or from plus to. + Overload spelling does not change the source kind. +- Named structs encode their initializer fields. `from source:` uses JSON key + `source`. Arrays/dictionaries encode as JSON collections, with defaults supplied. + Exports and watch are string arrays. An instruction section is always an object + with name, source and condition, even when authored as a string. +- Skill selection encodes `"all"` or an array of names. Prompt content is + `{kind: "literal", value: }` or `{kind: "file", path, source}`. + Runtime values similarly use literal/environment/secret and value. Literal + spelling and explicit equivalent cases have identical evaluated output. +- Payload-free enum cases are strings, except mixed enums always use tagged + objects. Associated values retain labels; a single unlabeled payload uses + `value`. Typed component references use kind and value. Configuration values + retain kind and value tags, including nested arrays/objects; null has only kind, + and decimal values remain strings to prevent numeric rounding. +- Agent IDs are `claude-code`, `codex`, `cursor`, `gemini-cli`, `opencode`; + platforms are `macos`, `linux`; other enum spellings are unchanged. + +Components, group references, sections, hooks, permission rules, ignore patterns, +arguments and prompt parameters preserve order. Definitions of sources/groups, +exports, watch, named prompts and overrides sort by name; recipients, exclusions +and explicit skill selections sort by canonical identity. Dictionary keys sort +by decoded UTF-8 bytes. Typed plugin exclusions sort by kind then value. +Constants are substituted by value within the checked expansion budget. + +A location has `pointer` (JSON Pointer into the normalized declaration), `span`, +`origins`, `defaulted` and `editability`. Spans have document `"manifest"`, start/end +byte offsets and starting line/column. A use's span identifies the use site; +origins include definitions. Missing fields anchor to their containing construction +with defaulted true. Editability has kind `direct`, `sharedConstant` or `readOnly`, +plus relevant stable reason and impacted-reference spans. Locations sort by +pointer then start offset; runtime node handles are not serialized. + +Diagnostics have code, severity, message, span and related spans, sorted by +position then code. No timestamps, cache paths or resolved secrets are emitted. +Readers ignore unknown object keys but reject unsupported schema versions and +unknown semantic discriminants. Changed meanings or new discriminants require +a new schema version; optional metadata additions do not. Source digest/locations +may change with comments while declaration stays equal. Entire output and map +size are reserved before serialization under the expanded-size budgets. + +## Target Architecture + +```text +UTF-8 -> strict lexer + bounded grammar recognizer -> SwiftParser -> iterative tree guard + -> vocabulary type checking/static evaluation + -> declaration IR + source map -> source/group linking + discovery + -> resolved component IR -> capability validation/native adapter lowering + -> artifact and ledger plan -> state transaction + +CLI/GUI/skill CLI -> domain edits -> source patches -> front end again + -> expected-IR comparison -> prepare -> transaction +``` + +| Target | Ownership and dependencies | +| --- | --- | +| `AgentsDescription` | Public immutable construction vocabulary and literal conformances; standard library only. | +| `AgentsCore` | Agent-independent declaration/resolved IR, source identity, requirements, provenance/span values, capability protocols/descriptors, approval identity, cache, locks and transactions. No syntax or adapter-implementation dependency. | +| `AgentsManifest` | Version selection, strict lexer and grammar recognizer, iterative tree guard, static symbol/type checking and evaluation, diagnostics, source maps, lowering to IR and source editing. Depends on `AgentsDescription`, `AgentsCore`, SwiftSyntax and SwiftParser. No deployment/resolution I/O. | +| `AgentsSkills` | Existing skill discovery, metadata and materialization; depends on `AgentsCore` and Yams. | +| `AgentsInstructions` | Existing instruction discovery, lifecycle and Markdown transformations; depends on `AgentsCore` and swift-markdown. | +| `Components` | Internal group linker, input-container adapters and native output adapters. Depends on `AgentsCore`, `AgentsManifest`, `AgentsSkills`, `AgentsInstructions`. Uses core source-resolution sessions and registers capability implementations during composition. Agent adapters are types/files, not one target per agent. | +| `AgentsUpdates` | Public prepare/apply orchestration across document edits, domains, components, approvals and one state transaction. Depends on the targets above; front ends consume its workflows. | + +Core does not depend on `Components`; descriptions and document editing do not +own a second state store. Public import names retain family identity; the +internal `Components` name reflects its responsibility. + +Declaration IR preserves defaults versus explicit values, ordered sections, +conditions and symbolic groups without choosing a host or reading sources. +Resolved IR carries tagged component payloads, logical identity, effective +recipients, content identity and provenance. Neither contains native output +paths. Backend plans add registered physical targets, owned keys/sections, +observed hashes, replacement bytes and adapter verification versions. + +Every field's source map records use/definition spans and inherited defaults. +Provenance includes normalized source identity, exact revision/artifact digest, +relative path, input format/adapter version, group and reference chain. Cache +paths are not identity. Coalesced artifacts retain all owners and origins. + +Future language versions can add bounded pure functions within the front end's +syntax, typing, evaluation and provenance rules. Their results lower to the same +values and IR. Adapters and the state engine remain independent of expression +syntax; editability remains a document-layer capability. + +## State Transaction and Recovery + +These guarantees extend [State and Source Cache](../Architecture/State.md) when +implemented. The existing journal remains the sole persistence owner. Validated +source bytes replace declaration re-encoding; lock/watch retain their encoders. +One transaction includes source, ledger, affected watch state, native artifacts, +cache retention and pruning. Source-only changes use the same protocol. + +Prepare records presence, physical identity and byte digest for the manifest, +ledger, watch state and relevant targets, plus source snapshot identities. +Under the scope writer lock, recover first, re-read/compare preconditions before +retention and again immediately before publication. A changed comment invalidates +a preview even when semantics are equal. Apply never rebases a stale source patch. +Descriptor-relative operations retain validated ancestors and reject symlinked or +unregistered paths. Staging, backups, journal records and parent directories follow +the existing fsync/metadata rules. + +### Publication and concurrent writers + +The transaction must read the exact preimage of any committed replacement. +Presence checks alone never authorize a blind overwrite. Each journal operation +records its expected presence/identity/hash, transaction-owned staging identity +and intended postimage before publication: + +| Expected destination | Atomic operation and conflict handling | +| --- | --- | +| Absent | Publish with atomic no-replace semantics: Linux `renameat2(RENAME_NOREPLACE)`, macOS `renamex_np(RENAME_EXCL)` or a descriptor-relative/link-based equivalent with the same guarantee. A concurrent creator causes an existence conflict; its bytes and identity remain untouched. Ordinary replacing rename is never a fallback. | +| Existing | Revalidate the read preimage, exchange atomically with staging and retain the displaced object. Read/compare that displaced object before confirming publication. Unexpected bytes are preserved as a conflict preimage; the operation cannot commit as a successful replacement. | +| Deletion | Move the entry into unique journal-owned quarantine without replacing another entry; verify its identity/digest before destructive cleanup. Unexpected content remains recoverable, and restoration uses no-replace semantics if the original name is occupied. | + +For an absent destination, the staged inode identity and content digest are +recorded durably before no-replace publication. After successful publication, +sync the destination's parent before marking the operation applied. Recovery +classifies the destination using that recorded physical identity and digest, +not just its filename or equal content. In a link-based implementation it also +accounts for the retained staging link until cleanup. + +If another file appeared and publication failed, the transaction rolls back its +other verified changes, preserves the concurrent file, and reports a conflict. +During migration, `agents.json` remains available or is restored through the +same protected rollback; the tool does not accept the newly appeared Swift file +as its own migration output. If a crash occurred before recording publication's +result, recovery can recognize its own published inode. Any other inode, even +with equal bytes, is external and must be preserved. Missing/changed evidence +produces an unresolved conflict rather than guessed ownership. + +Recovery verifies exchanged/quarantined preimages even if a crash preceded the +conflict marker. An unexpected preimage is never disposable staging. Restoring a +preimage may replace only the verified transaction-owned postimage; if an external +writer changed that path again, retain both versions and stop for owner resolution. +Creation rollback removes only its verified transaction-owned object; it never +unlinks a concurrent creator's file. Unsupported atomic primitives cause failure +before mutation. These rules also protect creation/replacement of the ledger and +other transaction destinations; there is no unguarded creation path. + +### Recovery outcomes and approvals + +An applying journal restores the previous verified generation; a committed journal +finishes cleanup. Conflicted journals retain all data needed for resolution. +Backup/staging cleanup requires both a durable terminal phase and verified +ownership. Read-only operations report pending recovery and never replay it. +Recovery remains repeatable across interruption and reports +`CoreError.transactionRecovered`; consumers retry preparation. Outcome reporting +distinguishes unchanged, committed and unresolved recovery, including failures +after the commit marker. The scope lock serializes cooperating tools; the +publication rules protect retained data when external editors ignore that lock. + +Approval identity covers declarations, commands and shipped content, excluding +comments and formatting. Approval is machine-local; a copied ledger disposition +is not authorization on another machine. Apply checks the local approval for the +resolved content identity and reports pending/refused components independently +of source validity. + +## Compatibility / Migration Impact + +### Field mapping + +`agents migrate` validates the existing strict JSON declaration and converts its +intent without fetching, re-resolving pins or inferring installed recipients. + +| JSON | Swift construction | +| --- | --- | +| `agents` | `Agents(defaultAgents: [...])`; omitted remains inheritance, explicit empty remains empty. | +| `sources..git` | `.git(name: , url: , ...)`. | +| `sources..local` | `.local(name: , directory: , ...)`. | +| `sources..well-known` | `.index(name: , url: , ...)`. | +| `sources..path` | `subpath:` unchanged. | +| `branch`, `revision`, `exact` | Corresponding source factory label. | +| `from` | `from:`; with `to`, the `from:to:` overload. | +| `upToNextMinor` | `upToNextMinorFrom:`. | +| `skills.` | `.skills(from: , ...)` in components. | +| `select: "all"` | Omit `select`; explicit names become a string array literal, including `[]`. | +| `exclude` | String array, omitted when empty. | +| Skill `agents`, `mode` | Corresponding fields; omission preserves inheritance. | +| `overrides.` | `SkillOverride(name: ..., mode: ..., agents: ...)`, subject to the explicit inert-override rule below. | +| `instructions` | One `.instructions(...)` after skill selections; missing object means no contribution. | +| `instructions.agents` | `agents:` on that component, preserving explicit recipient intent. | +| `instructions.sections[]` | Bare name becomes a string literal; `alias:name` becomes `.section("name", from: "alias")`. Preserve order and repetitions. | +| `instructions.chatgpt.` | `ChatGPTPrompt(name: ..., sections: ..., append: ...)` in `chatGPT`. Names and per-prompt section order remain exact. | +| Prompt `append` | Unchanged string, with existing project-root/user-home interpretation. | +| `watch[]` | Source alias strings in `watch`, with no condition. | +| Missing sources/skills/prompts/watch | Empty collections, with default-valued arguments omitted. | + +Unknown JSON fields, duplicate object keys, invalid UTF-8 and declarations invalid +under the existing validators remain errors. Every currently valid declaration +whose converted manifest fits the language budgets has a deterministic conversion. +Migration preflights all applicable language budgets, including parsing, evaluation, +expansion and output, before starting a state transaction. If any limit is exceeded, it reports `migration.limit` +with the limiting budget and leaves the original declaration, ledger, watch state +and native files untouched. The compatibility transformations below handle valid +JSON that differs from the manifest's domain rules; exceeding a resource budget +never triggers truncation or partial migration. + +### Compatibility transformations + +Two explicit transformations precede printing and are included in the migration +result's ordered diagnostics: + +1. For an explicit skill selection, an override whose name is not in `select` is + provably inert under existing lifecycle behavior. Remove it from the converted + declaration and report `migration.inertOverride` with its original JSON Pointer, + full value and reason. Preserve overrides for selected names, including excluded + selected names, and all overrides of an all-member selection. No override is + removed merely because discovery does not currently find its member. +2. Rename a source alias `.` to the first unused name in `source`, `source-2`, + `source-3`, and so on, considering all original aliases. Report + `migration.sourceAliasRenamed` with old/new aliases. Rewrite its source entry, + skill-selection key, watch references and explicit `.:name` section references + in both native instructions and ChatGPT prompts. Bare section names still mean + own sections and are not rewritten. Normalized source identities and pins do + not change. + +Diagnostics sort by original JSON Pointer and code. They are returned in preview +and apply reports; conversion never silently discards the removed override or +hides a rename. The compatibility projection compares effective selections, +recipients, modes, ordered content, subscriptions and source identities after +applying precisely those reported transformations. Apart from them, explicit +versus inherited intent and every field above are preserved. No groups, native +settings or additional approvals are synthesized. + +### Deterministic source and migration transaction + +The same validated JSON, language version and compatibility transformations +produce identical source bytes and diagnostic records. Emit the version line, +import, one blank line, then `let agents = Agents(...)`; two-space indentation, +LF, no BOM and one final newline. Assignment and array concatenation use one +ASCII space on each side of `=` and `+`; negative literals use an adjacent sign +and digits, as in `let value = -1`. Strings use ordinary quotes; escape quotes, +backslashes, LF, CR and tab, and encode other controls as lowercase Swift +`\u{...}`. Preserve other Unicode scalars without normalization. + +Use literal prompts/sections/selections/dictionaries and direct factories. +Omit default-valued arguments, retaining explicit Optional values that distinguish +inheritance. Signature order determines labels. Sort aliases, selection/override +names, prompt names, watch names and recipient IDs by canonical UTF-8 identity; +keep instruction and per-prompt section order. A collection of scalar literals or +payload-free enum members fits inline when the complete line, including indentation +and comma, is at most 80 UTF-8 bytes; otherwise expand it. Collections containing +factory/initializer calls are multiline. A call with only scalar arguments fits +inline under the same limit; calls with collections/nested calls are multiline. +Multiline collections have trailing commas; call arguments have none after the +last argument. Empty collections are `[]` or `[:]`. No formatting pass touches +an already migrated manifest. + +One transaction creates `Agents.swift`, upgrades an existing ledger as needed and +removes `agents.json`. Creation uses the no-replace protocol above. Existing native +files, cache content and watch-state bytes do not change. A missing ledger stays +missing. Repeating migration after success is unchanged. Both declaration files +present is a conflict; Swift source with a version-1 lock permits a lock-only +migration. Normal commands report required migration rather than converting +implicitly. A failed migration retains a recoverable original declaration and +never treats a concurrent file as generated output. + +### Lock version 2 and ownership conversion + +Version 2 retains exact item-specific source identities, revisions, versions, +artifact coordinates, hashes, section order and installation modes. Content +records refer to unified `deployments` IDs instead of duplicating ownership. +`groupResolutions` records the source/group closure; `components` records resolved +MCP servers, hooks, subagents, commands, LSP servers, permission/ignore policies +and plugins. Empty new collections are present; future unknown versions are refused. + +A deployment records registered-root-relative target, artifact kind, owners, +recipients, owned keys/sections, expected content hash, source pins and adapter +format. Whole-file versus managed-section ownership is explicit. For structured +files, hash the owned values and retain formatting-sensitive patch preconditions; +unmanaged keys are not claimed. Local approval dispositions are observations, +not transferable authorization. + +Migration derives ownership only from existing install/target records. Shared +skill destinations coalesce only when mode, content and ownership agree. +Instruction records preserve these separate removal rules exactly: + +| Existing instruction record | Version-2 ownership and removal | +| --- | --- | +| Generated unit target (`import == nil`) | Whole generated rendering, governed by `blockHash`. When obsolete, delete the file if its current bytes hash to `blockHash`; preserve drifted bytes. Its existing `created: false` does not prevent deletion. | +| Forwarding/import target (`import != nil`) | Managed import block with its marker/hash and the existing `created` flag. Remove the managed block; delete the whole file only when `created` is true and no custom content remains. Otherwise preserve the remaining file. | + +Heading offsets, import markers, block hashes and creation provenance retain their +meanings. Missing targets remain missing; drifted targets retain expected hashes, +not hashes of adopted bytes. Migration does not scan and claim unmanaged native +files. Source-alias renaming changes no normalized ledger identity. No generated +unit is reclassified as a non-deletable custom file, and no forwarding file gains +whole-file ownership from a unit-target rule. + +Lock conversion is deterministic for the same old lock and explicit registered +layout. An already-version-2 ledger remains byte-identical when unchanged. +Restoration must address the same original pins and physical targets after +conversion, and removing the last instruction must produce the same deletion or +preservation result as before conversion. + +## Validation Contract + +Positive fixtures compile against `AgentsDescription` and their compiled values +match static evaluation. Compiler-required literal conformances and evaluator +registrations are checked against the same signature inventory. Negative fixtures +cover unsupported syntax, contextual typing, duplicate dictionary keys, budgets +and spans. No accepted static value may fail real Swift type checking. + +Adversarial tests run every input in a subprocess with a parent watchdog and +assert normal completion without signals, crashes or unbounded memory growth. +Fixed regressions include balanced/unbalanced square nests, mixed square/call +nests, dictionaries, nested shorthand calls and parentheses, brace nests, generic +types `A>`, ambiguous `a Date: Thu, 29 Oct 2026 04:05:33 +0800 Subject: [PATCH 004/171] feat: support Linux Build and test on Linux with glibc alongside macOS: swift-crypto replaces CryptoKit, a small C platform layer covers file locks, directory handles, atomic exchange, metadata and process spawning, and Foundation networking and resource lookup work on both platforms. CI adds a Linux job on the digest-pinned official Swift image. Permission failures on state, cache and target files now report the failing path with an actionable hint instead of a raw Foundation error. --- .github/swift-package.json | 10 +- CHANGELOG.md | 4 + Documentation/Architecture/Package.md | 30 +- Documentation/Architecture/State.md | 8 + Package.resolved | 20 +- Package.swift | 22 +- README.md | 24 +- Sources/AgentsCore/DirectoryHandle.swift | 149 +++++--- Sources/AgentsCore/FileHash.swift | 4 +- Sources/AgentsCore/FileLock.swift | 24 +- Sources/AgentsCore/FileSystem.swift | 87 +++++ Sources/AgentsCore/ProcessRunner.swift | 37 +- Sources/AgentsCore/SourceCache.swift | 15 +- .../AgentsCore/SourceResolutionSession.swift | 6 +- Sources/AgentsCore/StateInspection.swift | 15 +- Sources/AgentsCore/UpdatePreconditions.swift | 7 +- Sources/AgentsCore/WatchOperations.swift | 9 +- .../InstructionDoctor.swift | 36 +- .../InstructionOperations.swift | 2 +- .../InstructionSources.swift | 12 +- .../InstructionTargets.swift | 2 +- Sources/AgentsSkills/Discovery.swift | 20 +- Sources/AgentsSkills/SkillLifecycle.swift | 19 +- Sources/AgentsSkills/SkillOperations.swift | 14 +- Sources/AgentsSkills/WellKnownProvider.swift | 14 +- Sources/AgentsUpdates/PreparedUpdate.swift | 7 +- Sources/CPlatform/CPlatform.c | 251 ++++++++++++++ Sources/CPlatform/include/CPlatform.h | 41 +++ .../CachePublicationTests.swift | 2 +- Tests/AgentsCoreTests/CoreTestSupport.swift | 2 +- .../DirectoryHandleTests.swift | 82 +++++ Tests/AgentsCoreTests/FileHashTests.swift | 9 + .../FileLockProcessTests.swift | 43 ++- .../FileSystemAccessTests.swift | 325 ++++++++++++++++++ .../AgentsCoreTests/MetadataTestSupport.swift | 139 ++++++++ .../AgentsCoreTests/ProcessTestSupport.swift | 10 +- .../StateTransactionTests.swift | 2 +- .../TransactionMetadataTests.swift | 65 +--- .../WatchDurabilityTests.swift | 6 +- Tests/AgentsCoreTests/WatchGitLockTests.swift | 12 +- .../WatchMirrorConcurrencyTests.swift | 2 +- Tests/AgentsCoreTests/WatchStateTests.swift | 2 +- .../FileReadAccessTests.swift | 95 +++++ .../TargetLifecycleTests.swift | 13 + .../ArchiveSafetyTests.swift | 49 +-- .../ArchiveTestSupport.swift | 46 +++ .../AutomaticSelectionTests.swift | 3 +- .../DiscoveryBehaviorTests.swift | 11 + .../FileReadAccessTests.swift | 77 +++++ .../LockedArtifactLifecycleTests.swift | 4 +- Tests/AgentsSkillsTests/NetworkingTests.swift | 47 +++ .../ReadOnlyInspectionTests.swift | 6 +- .../WellKnownArtifactTests.swift | 38 +- .../UpdateTransactionTests.swift | 4 +- Tests/StateTestProcess/main.swift | 2 +- 55 files changed, 1633 insertions(+), 352 deletions(-) create mode 100644 Sources/AgentsCore/FileSystem.swift create mode 100644 Sources/CPlatform/CPlatform.c create mode 100644 Sources/CPlatform/include/CPlatform.h create mode 100644 Tests/AgentsCoreTests/DirectoryHandleTests.swift create mode 100644 Tests/AgentsCoreTests/FileSystemAccessTests.swift create mode 100644 Tests/AgentsCoreTests/MetadataTestSupport.swift create mode 100644 Tests/AgentsInstructionsTests/FileReadAccessTests.swift create mode 100644 Tests/AgentsSkillsTests/ArchiveTestSupport.swift create mode 100644 Tests/AgentsSkillsTests/FileReadAccessTests.swift create mode 100644 Tests/AgentsSkillsTests/NetworkingTests.swift diff --git a/.github/swift-package.json b/.github/swift-package.json index 7f67f67..ff57b9b 100644 --- a/.github/swift-package.json +++ b/.github/swift-package.json @@ -1,5 +1,13 @@ { "compilers": [ {"name": "macos-26-xcode-26.6", "runner": "macos-26", "xcode": "26.6"} - ] + ], + "platforms": { + "linux": [ + { + "name": "linux-swift-6.4.1", + "image": "swift:6.4.1-noble@sha256:6304481cf2717966b7ba175162e397ea2f2cc3161909f2b2a5cf40036079a0f7" + } + ] + } } diff --git a/CHANGELOG.md b/CHANGELOG.md index 977f5cf..0be230c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ## Unreleased +### Added + +- Linux support. + ## 0.2.0 - 2026-10-27 ### Added diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index b05e09f..6c3637d 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -6,12 +6,15 @@ transformations. Both `agents` in `agents-tools/cli` and `skill` in `skill-cli/cli` consume this package. Consumers own command trees, argument parsing, terminal presentation, and executable distribution. The package uses -Swift 6.3, Swift 6 language mode, and a macOS 15 minimum deployment platform. +Swift 6.3 and Swift 6 language mode. It supports macOS 15 or newer and Linux +with glibc 2.34 or newer. ## Products and Dependencies ```text -AgentsUpdates ──> AgentsCore, AgentsSkills, AgentsInstructions +AgentsUpdates ──> AgentsCore, AgentsSkills, AgentsInstructions, CPlatform + +AgentsCore ──> Crypto (swift-crypto), CPlatform AgentsSkills ──> AgentsCore │ @@ -21,11 +24,11 @@ AgentsInstructions ──> AgentsCore │ └───────> Markdown (swift-markdown) ──> cmark-gfm -StateTestProcess ──> AgentsCore, AgentsSkills, AgentsInstructions, AgentsUpdates -AgentsCoreTests ──> AgentsCore, StateTestProcess -AgentsSkillsTests ──> AgentsSkills, AgentsCore, Yams, StateTestProcess +StateTestProcess ──> AgentsCore, AgentsSkills, AgentsInstructions, AgentsUpdates, CPlatform +AgentsCoreTests ──> AgentsCore, StateTestProcess, CPlatform +AgentsSkillsTests ──> AgentsSkills, AgentsCore, AgentsInstructions, Yams, StateTestProcess, CPlatform AgentsInstructionsTests ──> AgentsInstructions -AgentsUpdatesTests ──> AgentsUpdates, StateTestProcess +AgentsUpdatesTests ──> AgentsUpdates, StateTestProcess, CPlatform ``` `AgentsCore`, `AgentsSkills`, `AgentsInstructions` and `AgentsUpdates` are library products with @@ -34,6 +37,21 @@ implementation uses `package` access; consumers receive the workflow APIs and the state and result models they need. `Package.swift` owns this dependency graph. +`CPlatform` is an internal C target for filesystem and process differences. It +wraps file locks, access checks, atomic directory exchange, directory entry names, durable +synchronization, metadata copying and spawn actions. Linux uses +`renameat2(RENAME_EXCHANGE)`, `fsync`, descriptor-based mode/xattr copying +(including POSIX ACLs) and glibc's +`posix_spawn_file_actions_addclosefrom_np`. Symlink metadata uses no-follow calls +through pinned parent paths in `/proc/self/fd`; Linux symlink modes remain 0777. +Darwin keeps `renameatx_np`, `F_FULLFSYNC`, `fcopyfile` and its spawn inheritance +policy. Business workflows share the same Swift implementation. +Foundation re-exports the platform libc used by the Swift code; `CPlatform` +bridges APIs missing from those overlays. + +`AgentsCore` hashes through swift-crypto's `Crypto` product, which delegates to +CryptoKit on Apple platforms and supplies its own implementation on Linux. + ## AgentsCore - `SourceParser` and `ParsedSource` parse local paths, Git URLs and HTTP indexes. diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index 262c834..c8ed937 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -120,6 +120,14 @@ is fsynced before target mutation, including when an interrupted creator left a visible directory entry. Empty managed containers can remain after a failed operation. +Managed directories are created with mode 0700 and files/locks with mode 0600. +Directory permissions, inherited/default ACLs and other filesystem policy must +allow the owner to use newly created entries. Core checks access without changing +that policy. Permission denial stops the operation with the affected path and a +message to check directory permissions and default ACLs; retries remain denied +until the environment is corrected. This is a filesystem requirement, not a +transaction recovery case. Existing user content and metadata are preserved. + 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 diff --git a/Package.resolved b/Package.resolved index e22904f..bacc9b7 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,6 +1,15 @@ { - "originHash" : "ae0e3d7c64e7b90b867d3dcc9ced8ade57036f06db9caea7e98ebe08898ef86a", + "originHash" : "0e9fe4bea4fa453e8427d13cf8ceba58d78c327328841cb8c7c2e4550b3c96ed", "pins" : [ + { + "identity" : "swift-asn1", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-asn1.git", + "state" : { + "revision" : "3b6410f7dee09eb33cdd26260c5fd47fda19b0e2", + "version" : "1.7.3" + } + }, { "identity" : "swift-cmark", "kind" : "remoteSourceControl", @@ -10,6 +19,15 @@ "version" : "0.9.0" } }, + { + "identity" : "swift-crypto", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-crypto.git", + "state" : { + "revision" : "c2cbadd7263439d8015189668f96ff5b5be565ce", + "version" : "5.0.3" + } + }, { "identity" : "swift-markdown", "kind" : "remoteSourceControl", diff --git a/Package.swift b/Package.swift index 7a801f8..286eb81 100644 --- a/Package.swift +++ b/Package.swift @@ -15,29 +15,39 @@ let package = Package( .library(name: "AgentsUpdates", targets: ["AgentsUpdates"]), ], dependencies: [ + .package(url: "https://github.com/apple/swift-crypto.git", from: "5.0.0"), .package(url: "https://github.com/jpsim/Yams", from: "6.0.0"), .package(url: "https://github.com/swiftlang/swift-markdown.git", from: "0.9.0"), ], targets: [ - .target(name: "AgentsCore"), + .target(name: "CPlatform"), + .target( + name: "AgentsCore", + dependencies: ["CPlatform", .product(name: "Crypto", package: "swift-crypto")] + ), .target( name: "AgentsInstructions", dependencies: ["AgentsCore", .product(name: "Markdown", package: "swift-markdown")] ), .target(name: "AgentsSkills", dependencies: ["AgentsCore", "Yams"]), .target( - name: "AgentsUpdates", dependencies: ["AgentsCore", "AgentsSkills", "AgentsInstructions"]), + name: "AgentsUpdates", + dependencies: ["AgentsCore", "AgentsSkills", "AgentsInstructions", "CPlatform"]), .executableTarget( name: "StateTestProcess", - dependencies: ["AgentsCore", "AgentsInstructions", "AgentsSkills", "AgentsUpdates"], + dependencies: [ + "AgentsCore", "AgentsInstructions", "AgentsSkills", "AgentsUpdates", "CPlatform", + ], path: "Tests/StateTestProcess"), - .testTarget(name: "AgentsCoreTests", dependencies: ["AgentsCore", "StateTestProcess"]), + .testTarget( + name: "AgentsCoreTests", dependencies: ["AgentsCore", "StateTestProcess", "CPlatform"]), .testTarget(name: "AgentsInstructionsTests", dependencies: ["AgentsInstructions"]), - .testTarget(name: "AgentsUpdatesTests", dependencies: ["AgentsUpdates", "StateTestProcess"]), + .testTarget( + name: "AgentsUpdatesTests", dependencies: ["AgentsUpdates", "StateTestProcess", "CPlatform"]), .testTarget( name: "AgentsSkillsTests", dependencies: [ - "AgentsSkills", "AgentsCore", "AgentsInstructions", "Yams", "StateTestProcess", + "AgentsSkills", "AgentsCore", "AgentsInstructions", "Yams", "StateTestProcess", "CPlatform", ]), ], swiftLanguageModes: [.v6] diff --git a/README.md b/README.md index d680f05..d5d80bd 100644 --- a/README.md +++ b/README.md @@ -22,8 +22,8 @@ alt="Swift 6.3+"> - Platforms: macOS 15+ + Platforms: macOS 15+ and Linux License: MIT @@ -245,7 +245,15 @@ contracts, target paths, read-only inspection and deletion rules. ## Requirements - Swift 6.3 or newer, using Swift 6 language mode. -- macOS 15 or newer, as declared in [Package.swift](Package.swift). +- macOS 15 or newer, as declared in [Package.swift](Package.swift), or Linux + with glibc 2.34 or newer, `/proc` mounted and a filesystem supporting file + `flock`, atomic directory exchange, POSIX ACLs and extended attributes. +- Git and `tar`; ZIP artifacts also require `unzip` (including `zipinfo`). +- Directory permissions, inherited/default ACLs and other filesystem policy must + allow the owner to read/write created files and read/write/search created + directories. Core does not repair access policy; denied operations stop with + the affected path and a permission diagnostic. Correct the environment before + retrying. ## Documentation @@ -287,10 +295,12 @@ swift format lint --strict --configuration .swift-format \ The required checks are `policy / policy` and `validate / result`, provided by full-SHA-pinned reusable workflows from `agents-tools/github-workflows`. Source policy validates PR titles, new commit messages and added lines. -[Package validation configuration](.github/swift-package.json) selects one -compiler: the latest stable Xcode, 26.6, on `macos-26`. Validation runs tests -and a release build, plus strict formatting with `.swift-format` over -`Package.swift`, `Sources` and `Tests`. +[Package validation configuration](.github/swift-package.json) selects Xcode 26.6 on `macos-26` and a digest-pinned official Swift Linux +container. macOS validation runs tests and a release build, plus strict +formatting with `.swift-format` over `Package.swift`, `Sources` and `Tests`. +Linux runs the full test suite, including the subprocess recovery tests. The +configuration owns the Linux compiler version and image digest. Tests also +require Perl, which is included by the Linux image's Git dependencies. Render and check the committed [social preview](.github/assets/social-preview/social-preview.png) locally with diff --git a/Sources/AgentsCore/DirectoryHandle.swift b/Sources/AgentsCore/DirectoryHandle.swift index 8e7d806..707e528 100644 --- a/Sources/AgentsCore/DirectoryHandle.swift +++ b/Sources/AgentsCore/DirectoryHandle.swift @@ -1,11 +1,6 @@ +import CPlatform import Foundation -#if canImport(Darwin) - import Darwin -#else - import Glibc -#endif - /// Pins directory ancestry. Child operations never traverse symbolic links. final class DirectoryHandle { let descriptor: Int32 @@ -21,13 +16,16 @@ final class DirectoryHandle { for (index, component) in self.url.pathComponents.dropFirst().enumerated() { // macOS exposes these root-owned system directories through immutable aliases. // All task-controlled components, including every cache ancestor, use O_NOFOLLOW. - let systemAlias = index == 0 && ["var", "tmp", "etc"].contains(component) + let systemAlias = index == 0 && platform_system_alias(component) if create { var info = stat() if fstatat(current, component, &info, AT_SYMLINK_NOFOLLOW) != 0 { guard errno == ENOENT, mkdirat(current, component, 0o700) == 0 else { - throw CoreError.unsafePath("cannot create directory: \(url.path)") + throw FileSystem.posixError( + errno, at: self.url, otherwise: .unsafePath("cannot create directory: \(url.path)")) } + try FileSystem.requireAccess( + R_OK | W_OK | X_OK, at: self.url, parent: current, name: component) try checkpoint("directory.created.\(component)") } // An existing entry may have been published by an interrupted creator. @@ -36,10 +34,16 @@ final class DirectoryHandle { } let next = openat( current, component, O_RDONLY | O_DIRECTORY | (systemAlias ? 0 : O_NOFOLLOW) | O_CLOEXEC) - guard next >= 0 else { throw CoreError.unsafePath("unsafe directory: \(url.path)") } + guard next >= 0 else { + throw FileSystem.posixError( + errno, at: self.url, otherwise: .unsafePath("unsafe directory: \(url.path)")) + } close(current) current = next } + if create { + try FileSystem.requireAccess(R_OK | W_OK | X_OK, at: self.url, parent: current, name: ".") + } descriptor = current current = -1 } @@ -47,7 +51,10 @@ final class DirectoryHandle { private init(parent: DirectoryHandle, name: String) throws { url = parent.url.appendingPathComponent(name) descriptor = openat(parent.descriptor, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) - guard descriptor >= 0 else { throw CoreError.unsafePath("unsafe directory: \(url.path)") } + guard descriptor >= 0 else { + throw FileSystem.posixError( + errno, at: url, otherwise: .unsafePath("unsafe directory: \(url.path)")) + } } deinit { close(descriptor) } @@ -60,7 +67,9 @@ final class DirectoryHandle { var value = stat() if fstatat(descriptor, name, &value, AT_SYMLINK_NOFOLLOW) == 0 { return value } if errno == ENOENT { return nil } - throw CoreError.unsafePath("cannot inspect \(url.appendingPathComponent(name).path)") + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), + otherwise: .unsafePath("cannot inspect \(url.appendingPathComponent(name).path)")) } func names() throws -> [String] { @@ -72,11 +81,7 @@ final class DirectoryHandle { var names: [String] = [] errno = 0 while let entry = readdir(stream) { - let name = withUnsafePointer(to: &entry.pointee.d_name) { - $0.withMemoryRebound(to: CChar.self, capacity: Int(entry.pointee.d_namlen) + 1) { - String(cString: $0) - } - } + let name = String(cString: platform_entry_name(entry)) if name != "." && name != ".." { names.append(name) } } guard errno == 0 else { throw CoreError.unsafePath("cannot enumerate \(url.path)") } @@ -111,16 +116,10 @@ final class DirectoryHandle { _ name: String, to destination: String, swap: Bool = false, afterRename: () throws -> Void = {} ) throws { - let result: Int32 - if swap { - #if canImport(Darwin) - result = renameatx_np(descriptor, name, descriptor, destination, UInt32(RENAME_SWAP)) - #else - throw CoreError.unsupported("atomic directory exchange requires renameatx_np") - #endif - } else { - result = renameat(descriptor, name, descriptor, destination) - } + let result = + swap + ? platform_exchange(descriptor, name, destination) + : renameat(descriptor, name, descriptor, destination) guard result == 0 else { throw CoreError.invalidState("cannot replace \(destination): \(errno)") } @@ -129,9 +128,17 @@ final class DirectoryHandle { } func makeDirectory(_ name: String) throws { + if try info(name) != nil { + try FileSystem.requireAccess( + R_OK | W_OK | X_OK, at: url.appendingPathComponent(name), parent: descriptor) + } guard mkdirat(descriptor, name, 0o700) == 0 else { - throw CoreError.invalidState("cannot create directory: \(name)") + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), + otherwise: .invalidState("cannot create directory: \(name)")) } + try FileSystem.requireAccess( + R_OK | W_OK | X_OK, at: url.appendingPathComponent(name), parent: descriptor) try sync() } @@ -141,7 +148,9 @@ final class DirectoryHandle { func link(_ name: String, destination: String) throws { guard symlinkat(destination, descriptor, name) == 0 else { - throw CoreError.invalidState("cannot create link: \(name)") + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), + otherwise: .invalidState("cannot create link: \(name)")) } try sync() } @@ -149,14 +158,25 @@ final class DirectoryHandle { func write( _ name: String, data: Data, mode: mode_t = 0o600, preservingMetadataOf original: String? = nil ) throws { + if try info(name) != nil { + try FileSystem.requireAccess( + R_OK | W_OK, at: url.appendingPathComponent(name), parent: descriptor) + } let file = openat(descriptor, name, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, mode) - guard file >= 0 else { throw CoreError.invalidState("cannot stage \(name)") } + guard file >= 0 else { + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), + otherwise: .invalidState("cannot stage \(name)")) + } defer { close(file) } + try FileSystem.requireAccess( + R_OK | W_OK, at: url.appendingPathComponent(name), parent: descriptor) try data.withUnsafeBytes { bytes in var offset = 0 while offset < bytes.count { - let count = Foundation.write( + let count = CPlatform.write( file, bytes.baseAddress!.advanced(by: offset), bytes.count - offset) + if count < 0 && errno == EINTR { continue } guard count > 0 else { throw CoreError.invalidState("cannot write \(name)") } offset += count } @@ -182,8 +202,13 @@ final class DirectoryHandle { var data = Data() var buffer = [UInt8](repeating: 0, count: 65536) while true { - let count = Darwin.read(file, &buffer, buffer.count) - guard count >= 0 else { throw CoreError.invalidState("cannot read \(name)") } + let count = CPlatform.read(file, &buffer, buffer.count) + if count < 0 && errno == EINTR { continue } + guard count >= 0 else { + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), + otherwise: .invalidState("cannot read \(name)")) + } if count == 0 { return data } data.append(contentsOf: buffer.prefix(count)) } @@ -193,7 +218,9 @@ final class DirectoryHandle { var buffer = [CChar](repeating: 0, count: Int(PATH_MAX) + 1) let count = readlinkat(descriptor, name, &buffer, buffer.count - 1) guard count >= 0, count < buffer.count - 1 else { - throw CoreError.unsafePath("invalid symbolic link") + throw FileSystem.posixError( + count < 0 ? errno : 0, at: url.appendingPathComponent(name), + otherwise: .unsafePath("invalid symbolic link")) } return String(decoding: buffer.prefix(count).map { UInt8(bitPattern: $0) }, as: UTF8.self) } @@ -218,7 +245,11 @@ final class DirectoryHandle { private func regularFile(_ name: String) throws -> Int32 { let file = openat(descriptor, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) var info = stat() - guard file >= 0 else { throw CoreError.unsafePath("cannot open file: \(name)") } + guard file >= 0 else { + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), + otherwise: .unsafePath("cannot open file: \(name)")) + } guard fstat(file, &info) == 0, info.st_mode & S_IFMT == S_IFREG else { close(file) throw CoreError.unsafePath("expected regular file: \(name)") @@ -227,12 +258,9 @@ final class DirectoryHandle { } private static func synchronize(_ file: Int32) throws { - guard fsync(file) == 0 else { throw CoreError.invalidState("cannot sync filesystem entry") } - #if canImport(Darwin) - guard fcntl(file, F_FULLFSYNC) == 0 else { - throw CoreError.invalidState("cannot flush filesystem entry to storage") - } - #endif + guard platform_sync(file) == 0 else { + throw CoreError.invalidState("cannot sync filesystem entry: \(errno)") + } } /// Copies through pinned descriptors, including modes, ACLs and extended attributes. @@ -243,9 +271,17 @@ final class DirectoryHandle { guard let info = try source.info(original) else { throw CoreError.notFound(original) } switch info.st_mode & S_IFMT { case S_IFDIR: + if try self.info(name) != nil { + try FileSystem.requireAccess( + R_OK | W_OK | X_OK, at: url.appendingPathComponent(name), parent: descriptor) + } guard mkdirat(descriptor, name, 0o700) == 0 else { - throw CoreError.invalidState("cannot stage directory") + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), + otherwise: .invalidState("cannot stage directory")) } + try FileSystem.requireAccess( + R_OK | W_OK | X_OK, at: url.appendingPathComponent(name), parent: descriptor) try checkpoint("directory") let destination = try child(name) let origin = try source.child(original) @@ -255,24 +291,26 @@ final class DirectoryHandle { try Self.copyMetadata(from: origin.descriptor, to: destination.descriptor, mode: info.st_mode) case S_IFLNK: try link(name, destination: source.readLink(original)) - let origin = openat(source.descriptor, original, O_RDONLY | O_SYMLINK | O_CLOEXEC) - let destination = openat(descriptor, name, O_RDONLY | O_SYMLINK | O_CLOEXEC) - defer { - close(origin) - close(destination) + guard platform_copy_link_metadata(source.descriptor, original, descriptor, name) == 0 else { + throw CoreError.invalidState("cannot preserve link metadata: \(errno)") } - guard origin >= 0, destination >= 0 else { - throw CoreError.unsafePath("cannot copy link metadata") - } - try Self.copyMetadata(from: origin, to: destination, mode: info.st_mode) case S_IFREG: + if try self.info(name) != nil { + try FileSystem.requireAccess( + R_OK | W_OK, at: url.appendingPathComponent(name), parent: descriptor) + } let origin = try source.regularFile(original) defer { close(origin) } let destination = openat( descriptor, name, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) - guard destination >= 0 else { throw CoreError.unsafePath("cannot copy file") } + guard destination >= 0 else { + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), otherwise: .unsafePath("cannot copy file")) + } defer { close(destination) } - guard fcopyfile(origin, destination, nil, copyfile_flags_t(COPYFILE_DATA)) == 0 else { + try FileSystem.requireAccess( + R_OK | W_OK, at: url.appendingPathComponent(name), parent: descriptor) + guard platform_copy_data(origin, destination) == 0 else { throw CoreError.invalidState("cannot copy file content") } try Self.copyMetadata(from: origin, to: destination, mode: info.st_mode) @@ -283,9 +321,8 @@ final class DirectoryHandle { } private static func copyMetadata(from origin: Int32, to destination: Int32, mode: mode_t) throws { - guard fcopyfile(origin, destination, nil, copyfile_flags_t(COPYFILE_METADATA)) == 0, - fchmod(destination, mode & 0o7777) == 0 - else { throw CoreError.invalidState("cannot preserve filesystem metadata") } - try synchronize(destination) + guard platform_copy_metadata(origin, destination, mode) == 0 else { + throw CoreError.invalidState("cannot preserve filesystem metadata: \(errno)") + } } } diff --git a/Sources/AgentsCore/FileHash.swift b/Sources/AgentsCore/FileHash.swift index 11a4338..2d68cf9 100644 --- a/Sources/AgentsCore/FileHash.swift +++ b/Sources/AgentsCore/FileHash.swift @@ -1,4 +1,4 @@ -import CryptoKit +import Crypto import Foundation package enum FileHash { @@ -7,7 +7,7 @@ package enum FileHash { } package static func sha256Hex(file: URL) throws -> String { - try sha256Hex(data: Data(contentsOf: file)) + try sha256Hex(data: FileSystem.read(at: file)) } /// Hashes every tree entry in path order, including hidden files and symlink destinations. diff --git a/Sources/AgentsCore/FileLock.swift b/Sources/AgentsCore/FileLock.swift index 207d745..45d3db7 100644 --- a/Sources/AgentsCore/FileLock.swift +++ b/Sources/AgentsCore/FileLock.swift @@ -1,11 +1,6 @@ +import CPlatform import Foundation -#if canImport(Darwin) - import Darwin -#else - import Glibc -#endif - package enum FileLock { package static func withLock( at url: URL, checkpoint: (String) throws -> Void = { _ in }, _ body: () throws -> T @@ -24,7 +19,15 @@ package enum FileLock { parent.descriptor, url.lastPathComponent, O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC, S_IRUSR | S_IWUSR) guard descriptor >= 0 else { - throw CoreError.invalidState("cannot open writer lock: \(url.path)") + throw FileSystem.posixError( + errno, at: url, otherwise: .invalidState("cannot open writer lock: \(url.path)")) + } + do { + // O_CREAT can return a writable fd even when the inherited ACL prevents reopening it. + try FileSystem.requireAccess(R_OK | W_OK, at: url, parent: parent.descriptor) + } catch { + close(descriptor) + throw error } return try withDescriptor(descriptor, at: url, checkpoint: checkpoint, body) } @@ -39,7 +42,8 @@ package enum FileLock { parent.descriptor, url.lastPathComponent, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) if descriptor < 0, errno == ENOENT { return nil } guard descriptor >= 0 else { - throw CoreError.invalidState("cannot open existing lock: \(url.path)") + throw FileSystem.posixError( + errno, at: url, otherwise: .invalidState("cannot open existing lock: \(url.path)")) } return try withDescriptor(descriptor, at: url, checkpoint: { _ in }, body) } @@ -53,13 +57,13 @@ package enum FileLock { guard fstat(descriptor, &info) == 0, info.st_mode & 0o170000 == 0o100000 else { throw CoreError.unsafePath("writer lock must be a regular file: \(url.path)") } - while flock(descriptor, LOCK_EX | LOCK_NB) != 0 { + while platform_flock(descriptor, LOCK_EX | LOCK_NB) != 0 { if errno == EINTR { continue } guard errno == EWOULDBLOCK else { throw CoreError.invalidState("cannot acquire writer lock: \(url.path)") } try checkpoint("lock.contended") - while flock(descriptor, LOCK_EX) != 0 { + while platform_flock(descriptor, LOCK_EX) != 0 { if errno != EINTR { throw CoreError.invalidState("cannot acquire writer lock: \(url.path)") } diff --git a/Sources/AgentsCore/FileSystem.swift b/Sources/AgentsCore/FileSystem.swift new file mode 100644 index 0000000..393ee22 --- /dev/null +++ b/Sources/AgentsCore/FileSystem.swift @@ -0,0 +1,87 @@ +import CPlatform +import Foundation + +/// Filesystem access diagnostics shared by descriptor and Foundation operations. +package enum FileSystem { + static func permissionDenied(at url: URL) -> CoreError { + .invalidState( + "permission denied: \(url.path); check the directory's permissions and default ACL") + } + + static func posixError(_ code: Int32, at url: URL, otherwise error: CoreError) -> CoreError { + code == EACCES || code == EPERM ? permissionDenied(at: url) : error + } + + static func requireAccess( + _ mode: Int32, at url: URL, parent: Int32 = AT_FDCWD, name: String? = nil + ) throws { + let path = name ?? (parent == AT_FDCWD ? url.path : url.lastPathComponent) + guard platform_access(parent, path, mode) == 0 else { + throw posixError(errno, at: url, otherwise: .invalidState("cannot access \(url.path)")) + } + } + + package static func withAccessErrors(at url: URL, _ body: () throws -> T) throws -> T { + do { + return try body() + } catch let error as GitError { + throw error + } catch { + throw denial(in: error, at: url) ?? error + } + } + + /// The permission-denied error for `error`, or nil when no cause in its chain is a denial. + private static func denial(in error: Error, at url: URL) -> CoreError? { + var cause: NSError? = error as NSError + var denied = false + var failingURL: URL? + while let current = cause { + // Preserve the innermost supplied path; the operation URL may be a copy destination. + if let path = current.userInfo[NSFilePathErrorKey] as? String, !path.isEmpty { + failingURL = URL(fileURLWithPath: path) + } else if let url = current.userInfo[NSURLErrorKey] as? URL, url.isFileURL { + failingURL = url + } + if (current.domain == NSPOSIXErrorDomain + && [Int(EACCES), Int(EPERM)].contains(current.code)) + || (current.domain == NSCocoaErrorDomain + && [NSFileReadNoPermissionError, NSFileWriteNoPermissionError].contains(current.code)) + { + denied = true + } + cause = current.userInfo[NSUnderlyingErrorKey] as? NSError + } + return denied ? permissionDenied(at: failingURL ?? url) : nil + } + + package static func read(at url: URL) throws -> Data { + try withAccessErrors(at: url) { try Data(contentsOf: url) } + } + + /// Reads optional content whose absence or unreadability the caller tolerates. Only a + /// permission denial throws, so an unusable environment is not mistaken for missing content. + package static func readUnlessDenied(at url: URL) throws -> Data? { + do { + return try Data(contentsOf: url) + } catch { + if let denied = denial(in: error, at: url) { throw denied } + return nil + } + } + + package static func createDirectory(at url: URL) throws { + // Foundation callers permit existing aliases; descriptor operations still + // pin the resolved ancestry and create each missing component with 0700. + _ = try DirectoryHandle(at: url.resolvingSymlinksInPath(), create: true) + } + + package static func requireWritableFile(at url: URL) throws { + try requireAccess(R_OK | W_OK, at: url) + } + + package static func write(_ data: Data, to url: URL) throws { + let parent = try DirectoryHandle(at: url.deletingLastPathComponent().resolvingSymlinksInPath()) + try parent.write(url.lastPathComponent, data: data) + } +} diff --git a/Sources/AgentsCore/ProcessRunner.swift b/Sources/AgentsCore/ProcessRunner.swift index 84a9a6f..49aece5 100644 --- a/Sources/AgentsCore/ProcessRunner.swift +++ b/Sources/AgentsCore/ProcessRunner.swift @@ -1,11 +1,6 @@ +import CPlatform import Foundation -#if canImport(Darwin) - import Darwin -#else - import Glibc -#endif - package struct ProcessOutput: Equatable, Sendable { package var stdout: String package var stderr: String @@ -106,21 +101,6 @@ package enum ProcessRunner { // Capture stdin before pipes can reuse a closed standard descriptor. A lock // occupying stdin is internal state, not input for the child. let inputIsOpen = lock != STDIN_FILENO && fcntl(STDIN_FILENO, F_GETFD) >= 0 - var actions: posix_spawn_file_actions_t? - try check(posix_spawn_file_actions_init(&actions)) - defer { posix_spawn_file_actions_destroy(&actions) } - var attributes: posix_spawnattr_t? - try check(posix_spawnattr_init(&attributes)) - defer { posix_spawnattr_destroy(&attributes) } - try check(posix_spawnattr_setflags(&attributes, Int16(POSIX_SPAWN_CLOEXEC_DEFAULT))) - if inputIsOpen { - try check(posix_spawn_file_actions_addinherit_np(&actions, STDIN_FILENO)) - } else { - try check(posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0)) - } - if let workingDirectory { - try check(posix_spawn_file_actions_addchdir_np(&actions, workingDirectory.path)) - } let stdout = Pipe() let stderr = Pipe() defer { @@ -143,10 +123,17 @@ package enum ProcessRunner { defer { close(output) } let error = try duplicate(stderr.fileHandleForWriting.fileDescriptor) defer { close(error) } - try check(posix_spawn_file_actions_addinherit_np(&actions, inheritedLock)) - try check(posix_spawn_file_actions_adddup2(&actions, output, STDOUT_FILENO)) - try check(posix_spawn_file_actions_adddup2(&actions, error, STDERR_FILENO)) - try check(posix_spawn(&pid, executable, &actions, &attributes, argv, environment)) + func launch(_ directory: UnsafePointer?) throws { + try check( + platform_spawn( + &pid, executable, argv, environment, directory, inheritedLock, inputIsOpen, output, + error)) + } + if let workingDirectory { + try workingDirectory.path.withCString { try launch($0) } + } else { + try launch(nil) + } }() stdout.fileHandleForWriting.closeFile() stderr.fileHandleForWriting.closeFile() diff --git a/Sources/AgentsCore/SourceCache.swift b/Sources/AgentsCore/SourceCache.swift index 2d28e27..da3d126 100644 --- a/Sources/AgentsCore/SourceCache.swift +++ b/Sources/AgentsCore/SourceCache.swift @@ -325,7 +325,7 @@ package struct SourceCache { if !cacheSource { let root = FileManager.default.temporaryDirectory.appendingPathComponent( "agents-discovery-" + UUID().uuidString) - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try FileSystem.createDirectory(at: root) defer { try? FileManager.default.removeItem(at: root) } if case .revision(let object) = source.requirement, Self.isObjectID(object), let cached = try withExistingMirror( @@ -373,7 +373,7 @@ package struct SourceCache { let mirror = try pinnedMirror(sourceID: sourceID, source: source, revision: revision) let root = FileManager.default.temporaryDirectory.appendingPathComponent( "agents-snapshot-" + UUID().uuidString) - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try FileSystem.createDirectory(at: root) defer { try? FileManager.default.removeItem(at: root) } return try body( extract( @@ -411,7 +411,7 @@ package struct SourceCache { ) throws -> URL { let archive = root.appendingPathComponent("tree.tar") let tree = root.appendingPathComponent("tree") - try FileManager.default.createDirectory(at: tree, withIntermediateDirectories: true) + try FileSystem.createDirectory(at: tree) let arguments = [ "--no-optional-locks", "archive", "--format=tar", "--output=" + archive.path, revision, ] @@ -435,7 +435,7 @@ package struct SourceCache { } let url = try artifactURL(digest: digest) if FileManager.default.fileExists(atPath: url.path) { - guard try Data(contentsOf: url) == data else { + guard try FileSystem.read(at: url) == data else { throw CoreError.invalidState("cached artifact digest mismatch") } } else { @@ -587,8 +587,7 @@ package struct SourceCache { let url = source.kind == .local ? source.localURL(environment: store.environment).path : source.gitURL let mirror = mirrorURL(sourceID: id) - try FileManager.default.createDirectory( - at: mirror.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileSystem.createDirectory(at: mirror.deletingLastPathComponent()) if FileManager.default.fileExists(atPath: mirror.path) { _ = try git( mirror, @@ -601,7 +600,9 @@ package struct SourceCache { Self.gitOptions + ["clone", "--mirror", "--no-local", "--", url, staging.path], operation: .clone, source: source.location, replacingPaths: [staging, store.cacheDirectory], inheritingLock: lock) - try FileManager.default.moveItem(at: staging, to: mirror) + try FileSystem.withAccessErrors(at: mirror) { + try FileManager.default.moveItem(at: staging, to: mirror) + } } // A remote can change its default branch after the initial clone. let head = try ProcessRunner.git( diff --git a/Sources/AgentsCore/SourceResolutionSession.swift b/Sources/AgentsCore/SourceResolutionSession.swift index 93a8c5f..a5ee4b1 100644 --- a/Sources/AgentsCore/SourceResolutionSession.swift +++ b/Sources/AgentsCore/SourceResolutionSession.swift @@ -18,7 +18,7 @@ package final class SourceResolutionSession { cache = SourceCache(store: store) workspace = FileManager.default.temporaryDirectory.appendingPathComponent( "agents-resolution-" + UUID().uuidString) - try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + try FileSystem.createDirectory(at: workspace) } deinit { try? FileManager.default.removeItem(at: workspace) } @@ -36,7 +36,9 @@ package final class SourceResolutionSession { } let snapshot = try cache.withResolvedSnapshot(source) { pin, tree in let root = workspace.appendingPathComponent(UUID().uuidString) - try FileManager.default.copyItem(at: tree, to: root) + try FileSystem.withAccessErrors(at: root) { + try FileManager.default.copyItem(at: tree, to: root) + } return Snapshot(identity: identity, source: effective, pin: pin, root: root) } snapshots.append(snapshot) diff --git a/Sources/AgentsCore/StateInspection.swift b/Sources/AgentsCore/StateInspection.swift index 20617c3..2b8eb5e 100644 --- a/Sources/AgentsCore/StateInspection.swift +++ b/Sources/AgentsCore/StateInspection.swift @@ -1,11 +1,6 @@ +import CPlatform import Foundation -#if canImport(Darwin) - import Darwin -#else - import Glibc -#endif - extension StateStore { /// Takes an existing scope lock without creating files or replaying recovery. /// Pending recovery runs the diagnostic callback instead of inspecting inconsistent state. @@ -23,15 +18,17 @@ extension StateStore { openat($0.descriptor, ".agents.lock", O_RDONLY | O_NOFOLLOW | O_CLOEXEC) } ?? -1 if directory != nil, descriptor < 0, errno != ENOENT { - throw CoreError.invalidState("cannot open scope lock for inspection") + throw FileSystem.posixError( + errno, at: self.directory.appendingPathComponent(".agents.lock"), + otherwise: .invalidState("cannot open scope lock for inspection")) } defer { if descriptor >= 0 { close(descriptor) } } if descriptor >= 0 { - while flock(descriptor, LOCK_SH) != 0 { + while platform_flock(descriptor, LOCK_SH) != 0 { if errno != EINTR { throw CoreError.invalidState("cannot acquire scope inspection lock") } } } - defer { if descriptor >= 0 { flock(descriptor, LOCK_UN) } } + defer { if descriptor >= 0 { platform_flock(descriptor, LOCK_UN) } } let pending = try hasPendingRecovery(in: directory) let result = Result { try pending ? onPendingRecovery() : body() } // Writers create the lock before mutation and never remove it. A failed diff --git a/Sources/AgentsCore/UpdatePreconditions.swift b/Sources/AgentsCore/UpdatePreconditions.swift index 355c27e..381dc9b 100644 --- a/Sources/AgentsCore/UpdatePreconditions.swift +++ b/Sources/AgentsCore/UpdatePreconditions.swift @@ -1,11 +1,6 @@ +import CPlatform import Foundation -#if canImport(Darwin) - import Darwin -#else - import Glibc -#endif - /// Captures existing ancestry and the final entry without following that entry's link. /// Missing ancestors may be created, but existing ancestors cannot be exchanged. package struct PathIdentity { diff --git a/Sources/AgentsCore/WatchOperations.swift b/Sources/AgentsCore/WatchOperations.swift index 100651c..00b536c 100644 --- a/Sources/AgentsCore/WatchOperations.swift +++ b/Sources/AgentsCore/WatchOperations.swift @@ -194,16 +194,15 @@ public struct WatchOperations: Sendable { let artifacts = try artifacts(source) let root = FileManager.default.temporaryDirectory.appendingPathComponent( "agents-watch-" + UUID().uuidString) - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try FileSystem.createDirectory(at: root) defer { try? FileManager.default.removeItem(at: root) } for artifact in artifacts { let directory = root.appendingPathComponent(artifact.name) - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try FileSystem.createDirectory(at: directory) for (path, data) in artifact.files { let destination = try PathSafety.resolvedChild(base: directory, subpath: path) - try FileManager.default.createDirectory( - at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) - try data.write(to: destination) + try FileSystem.createDirectory(at: destination.deletingLastPathComponent()) + try FileSystem.write(data, to: destination) } for (digest, data) in artifact.payloads { _ = try cache.storeArtifact(data, digest: digest) } _ = try cache.materializeArtifact( diff --git a/Sources/AgentsInstructions/InstructionDoctor.swift b/Sources/AgentsInstructions/InstructionDoctor.swift index 4f9114a..6853a49 100644 --- a/Sources/AgentsInstructions/InstructionDoctor.swift +++ b/Sources/AgentsInstructions/InstructionDoctor.swift @@ -57,7 +57,7 @@ extension InstructionOperations { 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) + let current = try FileSystem.readUnlessDenied(at: file) if current.map(Instructions.hash) != record.hash { unchanged = false report( @@ -72,10 +72,18 @@ extension InstructionOperations { ? try? sources.restore( lock.instructions.sections, sources: lock.sources, cachedOnly: true ).map(\.section) : nil + // Targets already reported as unreadable; the Codex chain must not report them again. + var unreadableTargets = Set() 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) + let bytes: Data? + do { + bytes = try InstructionTargets.read(file) + } catch { + unreadableTargets.insert(file.resolvingSymlinksInPath().path) + throw error + } if target.import != nil { switch try Instructions.detectDrift( in: bytes ?? Data(), lockedBlockHash: target.blockHash) @@ -171,7 +179,8 @@ extension InstructionOperations { } if agents.contains(.codex), scope == .user || otherSections != nil { diagnostics += InstructionDoctor.codex( - scope: scope, environment: environment, lock: lock, configuration: codexConfiguration) + scope: scope, environment: environment, lock: lock, configuration: codexConfiguration, + reportedUnreadable: unreadableTargets) } diagnostics += InstructionSourceDiagnostics.inspect( store: store, declaration: declaration, lock: lock) @@ -219,9 +228,11 @@ private enum InstructionDoctor { return result } + /// `reportedUnreadable` holds resolved paths the caller already reported as unreadable. static func codex( scope: InstallScope, environment: RuntimeEnvironment, lock: ResolvedState, - configuration supplied: CodexInstructionConfiguration? + configuration supplied: CodexInstructionConfiguration?, + reportedUnreadable: Set = [] ) -> [InstructionDiagnostic] { var result: [InstructionDiagnostic] = [] let user = InstructionLocations.file(for: .codex, scope: .user, environment: environment)! @@ -229,7 +240,7 @@ private enum InstructionDoctor { var configuration = supplied ?? CodexInstructionConfiguration() do { if supplied == nil, FileManager.default.fileExists(atPath: config.path) { - configuration = try CodexInstructionConfiguration(Data(contentsOf: config)) + configuration = try CodexInstructionConfiguration(FileSystem.read(at: config)) } } catch { result.append( @@ -244,14 +255,25 @@ private enum InstructionDoctor { value.agents.contains(.codex) && (try? InstructionLocations.file(for: key, store: store)) == InstructionLocations.physical(file) - } || (try? Data(contentsOf: file)).map(Instructions.isGenerated) == true + } || content(file).map(Instructions.isGenerated) == true } + var unreadable = reportedUnreadable 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() + do { + return try FileSystem.readUnlessDenied(at: file) ?? Data() + } catch { + // The chain visits a file once per leaf and once for ownership; report it once. + if unreadable.insert(file.resolvingSymlinksInPath().path).inserted { + result.append( + InstructionDiagnostic( + kind: .invalidTarget, message: "Cannot read instructions: \(error)", path: file)) + } + return Data() + } } func blank(_ data: Data) -> Bool { String(decoding: data, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty diff --git a/Sources/AgentsInstructions/InstructionOperations.swift b/Sources/AgentsInstructions/InstructionOperations.swift index 55a94dc..7b3f9ad 100644 --- a/Sources/AgentsInstructions/InstructionOperations.swift +++ b/Sources/AgentsInstructions/InstructionOperations.swift @@ -285,7 +285,7 @@ public enum InstructionOperations { let root = scope == .project ? environment.projectDirectory : environment.homeDirectory let file = try PathSafety.resolvedChild(base: root, subpath: append) try InstructionSources.contained(file, in: root) - custom = try Data(contentsOf: file) + custom = try FileSystem.read(at: file) } return try Instructions.renderChatGPT( sections: sections.map(\.section), customContent: custom) diff --git a/Sources/AgentsInstructions/InstructionSources.swift b/Sources/AgentsInstructions/InstructionSources.swift index 66fbcc6..eccffae 100644 --- a/Sources/AgentsInstructions/InstructionSources.swift +++ b/Sources/AgentsInstructions/InstructionSources.swift @@ -49,7 +49,8 @@ final class InstructionSources { for container in Self.containers { let directory = root.appendingPathComponent(container) for (name, file) in try Self.files(in: directory, tree: tree) { - let section = try Instructions.validateSource(Data(contentsOf: file), id: id + ":" + name) + let section = try Instructions.validateSource( + FileSystem.read(at: file), id: id + ":" + name) units.append( InstructionUnit( record: LockedSection( @@ -77,7 +78,7 @@ final class InstructionSources { 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) + let section = try Instructions.validateSource(FileSystem.read(at: file), id: name) return InstructionUnit( record: LockedSection( name: name, source: Self.own, @@ -100,7 +101,7 @@ final class InstructionSources { 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) + let section = try Instructions.validateSource(FileSystem.read(at: file), id: name) return InstructionUnit( record: LockedSection(name: name, source: Self.own, path: path, hash: section.hash), section: section) @@ -149,7 +150,8 @@ final class InstructionSources { func read(_ root: URL) throws -> InstructionSection { let file = try PathSafety.resolvedChild(base: root, subpath: record.path) try Self.contained(file, in: root) - return try Instructions.validateSource(Data(contentsOf: file), id: Self.identity(record)) + return try Instructions.validateSource( + FileSystem.read(at: file), id: Self.identity(record)) } if FileManager.default.fileExists(atPath: materialized.path) { section = try read(materialized) @@ -178,7 +180,7 @@ final class InstructionSources { let root = try cache.materialize(sourceID: record.source, source: source, revision: revision) let file = try PathSafety.resolvedChild(base: root, subpath: record.path) try Self.contained(file, in: root) - guard Instructions.hash(try Data(contentsOf: file)) == record.hash else { + guard Instructions.hash(try FileSystem.read(at: file)) == record.hash else { throw CoreError.invalidState("cached instruction digest mismatch: \(record.name)") } } diff --git a/Sources/AgentsInstructions/InstructionTargets.swift b/Sources/AgentsInstructions/InstructionTargets.swift index 12a5971..57c2aff 100644 --- a/Sources/AgentsInstructions/InstructionTargets.swift +++ b/Sources/AgentsInstructions/InstructionTargets.swift @@ -288,7 +288,7 @@ struct InstructionTargets { guard try file.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw CoreError.unsafePath("instruction target is not a regular file: \(file.path)") } - return try Data(contentsOf: file) + return try FileSystem.read(at: file) } private static func importBlock(in bytes: Data, at path: ClaudeInstructionPath) throws diff --git a/Sources/AgentsSkills/Discovery.swift b/Sources/AgentsSkills/Discovery.swift index 40eb5ea..282827c 100644 --- a/Sources/AgentsSkills/Discovery.swift +++ b/Sources/AgentsSkills/Discovery.swift @@ -36,7 +36,9 @@ enum Discovery { ]) static func parseSkill(at skillFile: URL, includeInternal: Bool = false) throws -> Skill? { - let content = try String(contentsOf: skillFile, encoding: .utf8) + let content = try FileSystem.withAccessErrors(at: skillFile) { + try String(contentsOf: skillFile, encoding: .utf8) + } let data: [String: Any] do { data = try parseFrontmatter(content) @@ -72,7 +74,7 @@ enum Discovery { ) throws -> [Skill] { let searchRoot = try subpath.map { try PathSafety.resolvedChild(base: base, subpath: $0) } ?? base - let pluginGroups = pluginGroupings(base: searchRoot) + let pluginGroups = try pluginGroupings(base: searchRoot) let projectInstalledSkillNames = projectInstalledAgentSkillNames(base: searchRoot) var skills: [Skill] = [] var seen = Set() @@ -112,7 +114,7 @@ enum Discovery { searchRoot.appendingPathComponent(".codex/skills"), searchRoot.appendingPathComponent(".opencode/skills"), ] - priorityDirectories.append(contentsOf: pluginSkillSearchDirectories(base: searchRoot)) + priorityDirectories.append(contentsOf: try pluginSkillSearchDirectories(base: searchRoot)) for directory in priorityDirectories { let candidates = @@ -239,12 +241,12 @@ enum Discovery { (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true } - private static func pluginSkillSearchDirectories(base: URL) -> [URL] { + private static func pluginSkillSearchDirectories(base: URL) throws -> [URL] { var directories: [URL] = [] let decoder = JSONDecoder() let marketplaceURL = base.appendingPathComponent(".claude-plugin/marketplace.json") - if let data = try? Data(contentsOf: marketplaceURL), + if let data = try FileSystem.readUnlessDenied(at: marketplaceURL), let manifest = try? decoder.decode(MarketplaceManifest.self, from: data) { let root = manifest.metadata?.pluginRoot @@ -269,7 +271,7 @@ enum Discovery { } let pluginURL = base.appendingPathComponent(".claude-plugin/plugin.json") - if let data = try? Data(contentsOf: pluginURL), + if let data = try FileSystem.readUnlessDenied(at: pluginURL), let manifest = try? decoder.decode(PluginManifest.self, from: data) { for skill in manifest.skills ?? [] where skill.hasPrefix("./") { @@ -285,12 +287,12 @@ enum Discovery { return directories } - private static func pluginGroupings(base: URL) -> [String: String] { + private static func pluginGroupings(base: URL) throws -> [String: String] { var groups: [String: String] = [:] let decoder = JSONDecoder() let marketplaceURL = base.appendingPathComponent(".claude-plugin/marketplace.json") - if let data = try? Data(contentsOf: marketplaceURL), + if let data = try FileSystem.readUnlessDenied(at: marketplaceURL), let manifest = try? decoder.decode(MarketplaceManifest.self, from: data) { let root = manifest.metadata?.pluginRoot @@ -314,7 +316,7 @@ enum Discovery { } let pluginURL = base.appendingPathComponent(".claude-plugin/plugin.json") - if let data = try? Data(contentsOf: pluginURL), + if let data = try FileSystem.readUnlessDenied(at: pluginURL), let manifest = try? decoder.decode(PluginManifest.self, from: data), let name = manifest.name { diff --git a/Sources/AgentsSkills/SkillLifecycle.swift b/Sources/AgentsSkills/SkillLifecycle.swift index 84efc55..491175c 100644 --- a/Sources/AgentsSkills/SkillLifecycle.swift +++ b/Sources/AgentsSkills/SkillLifecycle.swift @@ -44,7 +44,7 @@ final class SkillLifecycle { self.provider = provider workspace = FileManager.default.temporaryDirectory.appendingPathComponent( "agents-operation-" + UUID().uuidString) - try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + try FileSystem.createDirectory(at: workspace) } deinit { try? FileManager.default.removeItem(at: workspace) } @@ -84,7 +84,9 @@ final class SkillLifecycle { root = workspace.appendingPathComponent(UUID().uuidString) func copy(_ resolved: SourceRevision, _ snapshot: URL) throws { pin = resolved - try FileManager.default.copyItem(at: snapshot, to: root) + try FileSystem.withAccessErrors(at: root) { + try FileManager.default.copyItem(at: snapshot, to: root) + } } if let resolutions { try resolutions.withSnapshot(source, copy) @@ -195,7 +197,9 @@ final class SkillLifecycle { root = workspace.appendingPathComponent(UUID().uuidString) try cache.withSnapshot(sourceID: skill.source, source: source, revision: revision) { snapshot in - try FileManager.default.copyItem(at: snapshot, to: root) + try FileSystem.withAccessErrors(at: root) { + try FileManager.default.copyItem(at: snapshot, to: root) + } } } directory = try PathSafety.resolvedChild(base: root, subpath: path) @@ -414,12 +418,11 @@ final class SkillLifecycle { } private func write(_ files: [String: Data], to directory: URL) throws { - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try FileSystem.createDirectory(at: directory) for (path, data) in files { let url = try PathSafety.resolvedChild(base: directory, subpath: path) - try FileManager.default.createDirectory( - at: url.deletingLastPathComponent(), withIntermediateDirectories: true) - try data.write(to: url) + try FileSystem.createDirectory(at: url.deletingLastPathComponent()) + try FileSystem.write(data, to: url) } } @@ -434,7 +437,7 @@ final class SkillLifecycle { case .typeDirectory: return .directory case .typeRegular: let mode = (attributes[.posixPermissions] as? NSNumber)?.uint16Value ?? 0 - return .file(try Data(contentsOf: url), executable: mode & 0o111 != 0) + return .file(try FileSystem.read(at: url), executable: mode & 0o111 != 0) default: throw CoreError.unsafePath("unsupported installed entry: \(url.path)") } } diff --git a/Sources/AgentsSkills/SkillOperations.swift b/Sources/AgentsSkills/SkillOperations.swift index 8523e51..d436da0 100644 --- a/Sources/AgentsSkills/SkillOperations.swift +++ b/Sources/AgentsSkills/SkillOperations.swift @@ -534,14 +534,18 @@ public enum SkillOperations { let name = name.map(PathSafety.sanitizeName) let root = name.map { directory.appendingPathComponent($0) } ?? directory let file = root.appendingPathComponent("SKILL.md") - guard !FileManager.default.fileExists(atPath: file.path) else { + if FileManager.default.fileExists(atPath: file.path) { + try FileSystem.requireWritableFile(at: file) throw CoreError.invalidSkill("SKILL.md already exists at \(file.path)") } - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try FileSystem.createDirectory(at: root) let title = name ?? PathSafety.sanitizeName(root.lastPathComponent) - try - "---\nname: \(title)\ndescription: Describe when to use this skill\n---\n\n# \(title)\n\nWrite the skill instructions here.\n" - .write(to: file, atomically: true, encoding: .utf8) + try FileSystem.withAccessErrors(at: file) { + try + "---\nname: \(title)\ndescription: Describe when to use this skill\n---\n\n# \(title)\n\nWrite the skill instructions here.\n" + .write(to: file, atomically: true, encoding: .utf8) + } + try FileSystem.requireWritableFile(at: file) return root } } diff --git a/Sources/AgentsSkills/WellKnownProvider.swift b/Sources/AgentsSkills/WellKnownProvider.swift index 7f9fe95..7e969cf 100644 --- a/Sources/AgentsSkills/WellKnownProvider.swift +++ b/Sources/AgentsSkills/WellKnownProvider.swift @@ -2,6 +2,10 @@ import AgentsCore import Foundation import Yams +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + struct WellKnownRemoteSkill: Equatable, Sendable { var installName: String var description: String @@ -194,7 +198,7 @@ struct WellKnownProvider: Sendable { let cached = try cache.artifactURL(digest: digest) let data = FileManager.default.fileExists(atPath: cached.path) - ? try Data(contentsOf: cached) : try fetch(URL(string: url)!) + ? try FileSystem.read(at: cached) : try fetch(URL(string: url)!) try verifyDigest(data: data, expected: digest) payloads[digest] = data return data @@ -259,8 +263,8 @@ struct WellKnownProvider: Sendable { .appendingPathComponent("agents-artifact-" + UUID().uuidString) let archive = tempRoot.appendingPathComponent("artifact.tar.gz") let extract = tempRoot.appendingPathComponent("extract") - try FileManager.default.createDirectory(at: extract, withIntermediateDirectories: true) - try data.write(to: archive) + try FileSystem.createDirectory(at: extract) + try FileSystem.write(data, to: archive) defer { try? FileManager.default.removeItem(at: tempRoot) } @@ -299,8 +303,8 @@ struct WellKnownProvider: Sendable { .appendingPathComponent("agents-artifact-" + UUID().uuidString) let archive = tempRoot.appendingPathComponent("artifact.zip") let extract = tempRoot.appendingPathComponent("extract") - try FileManager.default.createDirectory(at: extract, withIntermediateDirectories: true) - try data.write(to: archive) + try FileSystem.createDirectory(at: extract) + try FileSystem.write(data, to: archive) defer { try? FileManager.default.removeItem(at: tempRoot) } diff --git a/Sources/AgentsUpdates/PreparedUpdate.swift b/Sources/AgentsUpdates/PreparedUpdate.swift index 61d7d7f..9c3d194 100644 --- a/Sources/AgentsUpdates/PreparedUpdate.swift +++ b/Sources/AgentsUpdates/PreparedUpdate.swift @@ -1,12 +1,7 @@ import AgentsCore +import CPlatform import Foundation -#if canImport(Darwin) - import Darwin -#else - import Glibc -#endif - /// Valid only on the preparing thread, inside `withPreparedUpdate`. Any apply attempt consumes it. /// Render `report` directly; re-entering scope operations while this handle is active can deadlock. public final class PreparedUpdate { diff --git a/Sources/CPlatform/CPlatform.c b/Sources/CPlatform/CPlatform.c new file mode 100644 index 0000000..fbde767 --- /dev/null +++ b/Sources/CPlatform/CPlatform.c @@ -0,0 +1,251 @@ +#define _GNU_SOURCE 1 +#include "CPlatform.h" + +#include +#include +#include + +#if defined(__APPLE__) +#include +#else +#include +#endif + +int platform_flock(int descriptor, int operation) { + return flock(descriptor, operation); +} + +int platform_access(int directory, const char *name, int mode) { + return faccessat(directory, name, mode, AT_EACCESS); +} + +const char *platform_entry_name(const struct dirent *entry) { + return entry->d_name; +} + +bool platform_system_alias(const char *name) { +#if defined(__APPLE__) + return strcmp(name, "var") == 0 || strcmp(name, "tmp") == 0 || strcmp(name, "etc") == 0; +#else + (void)name; + return false; +#endif +} + +int platform_exchange(int directory, const char *name, const char *destination) { +#if defined(__APPLE__) + return renameatx_np(directory, name, directory, destination, RENAME_SWAP); +#else + // Call the kernel primitive without relying on the libc Swift overlay. + return (int)syscall(SYS_renameat2, directory, name, directory, destination, 2 /* RENAME_EXCHANGE */); +#endif +} + +int platform_sync(int descriptor) { + int result; + do { result = fsync(descriptor); } while (result < 0 && errno == EINTR); +#if defined(__APPLE__) + if (result == 0) { + do { result = fcntl(descriptor, F_FULLFSYNC); } while (result < 0 && errno == EINTR); + } +#endif + return result; +} + +int platform_copy_data(int source, int destination) { +#if defined(__APPLE__) + return fcopyfile(source, destination, NULL, COPYFILE_DATA); +#else + char buffer[65536]; + for (;;) { + ssize_t count; + do { count = read(source, buffer, sizeof(buffer)); } while (count < 0 && errno == EINTR); + if (count < 0) return -1; + if (count == 0) return 0; + ssize_t offset = 0; + while (offset < count) { + ssize_t written = write(destination, buffer + offset, (size_t)(count - offset)); + if (written < 0 && errno == EINTR) continue; + if (written <= 0) { + if (written == 0) errno = EIO; + return -1; + } + offset += written; + } + } +#endif +} + +#if !defined(__APPLE__) +// POSIX ACLs are Linux system.posix_acl_* xattrs. Copy them along with all other +// attributes, without requiring libacl or an external executable. +static int copy_xattrs(int source, int destination, const char *sourceLink, + const char *destinationLink) { + ssize_t size = sourceLink ? llistxattr(sourceLink, NULL, 0) : flistxattr(source, NULL, 0); + if (size < 0) return errno == ENOTSUP ? 0 : -1; + char *names = malloc(size ? (size_t)size : 1); + if (!names) { errno = ENOMEM; return -1; } + ssize_t count = sourceLink ? llistxattr(sourceLink, names, (size_t)size) + : flistxattr(source, names, (size_t)size); + if (count < 0 || count > size) { + if (count > size) errno = ERANGE; + free(names); + return -1; + } + // A new entry may inherit a default ACL from its parent. Remove destination + // attributes absent from the source before restoring the source's metadata. + ssize_t targetSize = destinationLink ? llistxattr(destinationLink, NULL, 0) + : flistxattr(destination, NULL, 0); + if (targetSize < 0) { free(names); return -1; } + char *targetNames = malloc(targetSize ? (size_t)targetSize : 1); + if (!targetNames) { free(names); errno = ENOMEM; return -1; } + ssize_t targetCount = destinationLink ? llistxattr(destinationLink, targetNames, (size_t)targetSize) + : flistxattr(destination, targetNames, (size_t)targetSize); + if (targetCount < 0 || targetCount > targetSize) { + if (targetCount > targetSize) errno = ERANGE; + free(targetNames); + free(names); + return -1; + } + int result = 0; + for (ssize_t offset = 0; offset < targetCount;) { + const char *name = targetNames + offset; + offset += (ssize_t)strlen(name) + 1; + bool found = false; + for (ssize_t i = 0; i < count; i += (ssize_t)strlen(names + i) + 1) { + if (strcmp(name, names + i) == 0) { found = true; break; } + } + if (!found) { + result = destinationLink ? lremovexattr(destinationLink, name) + : fremovexattr(destination, name); + if (result < 0) break; + } + } + free(targetNames); + if (result < 0) { free(names); return -1; } + // Setting an access ACL may make the destination read-only. Install it only + // after every other xattr, while the staging file still has owner write access. + for (int pass = 0; pass < 2 && result == 0; ++pass) { + for (ssize_t offset = 0; offset < count;) { + const char *name = names + offset; + offset += (ssize_t)strlen(name) + 1; + bool accessACL = strcmp(name, "system.posix_acl_access") == 0; + if (accessACL != (pass == 1)) continue; + ssize_t length = sourceLink ? lgetxattr(sourceLink, name, NULL, 0) + : fgetxattr(source, name, NULL, 0); + if (length < 0) { result = -1; break; } + void *value = malloc(length ? (size_t)length : 1); + if (!value) { errno = ENOMEM; result = -1; break; } + ssize_t readCount = sourceLink ? lgetxattr(sourceLink, name, value, (size_t)length) + : fgetxattr(source, name, value, (size_t)length); + if (readCount < 0 || readCount > length) { + if (readCount > length) errno = ERANGE; + free(value); + result = -1; + break; + } + result = destinationLink ? lsetxattr(destinationLink, name, value, (size_t)readCount, 0) + : fsetxattr(destination, name, value, (size_t)readCount, 0); + free(value); + if (result < 0) break; + } + } + int error = errno; + free(names); + errno = error; + return result; +} +#endif + +int platform_copy_metadata(int source, int destination, mode_t mode) { +#if defined(__APPLE__) + if (fcopyfile(source, destination, NULL, COPYFILE_METADATA) < 0) return -1; +#else + struct stat info; + if (fstat(source, &info) < 0) return -1; + // Inherited default ACLs can restrict even a freshly created staging entry. + if (fchmod(destination, S_ISDIR(mode) ? 0700 : 0600) < 0) return -1; + if (copy_xattrs(source, destination, NULL, NULL) < 0) return -1; + const struct timespec times[2] = {info.st_atim, info.st_mtim}; + if (futimens(destination, times) < 0) return -1; +#endif + if (fchmod(destination, mode & 07777) < 0) return -1; + return platform_sync(destination); +} + +int platform_copy_link_metadata(int sourceDirectory, const char *source, + int destinationDirectory, const char *destination) { +#if defined(__APPLE__) + int origin = openat(sourceDirectory, source, O_RDONLY | O_SYMLINK | O_CLOEXEC); + if (origin < 0) return -1; + int target = openat(destinationDirectory, destination, O_RDONLY | O_SYMLINK | O_CLOEXEC); + int result = -1; + struct stat info; + if (target >= 0 && fstat(origin, &info) == 0) { + result = platform_copy_metadata(origin, target, info.st_mode); + } + int error = errno; + close(origin); + if (target >= 0) close(target); + errno = error; + return result; +#else + // /proc/self/fd keeps both parent paths anchored to the pinned descriptors; + // l*xattr and AT_SYMLINK_NOFOLLOW operate on the links, never their targets. + char origin[64 + NAME_MAX], target[64 + NAME_MAX]; + int n = snprintf(origin, sizeof(origin), "/proc/self/fd/%d/%s", sourceDirectory, source); + int m = snprintf(target, sizeof(target), "/proc/self/fd/%d/%s", destinationDirectory, destination); + if (n < 0 || m < 0 || (size_t)n >= sizeof(origin) || (size_t)m >= sizeof(target)) { + errno = ENAMETOOLONG; + return -1; + } + struct stat info; + if (fstatat(sourceDirectory, source, &info, AT_SYMLINK_NOFOLLOW) < 0) return -1; + if (!S_ISLNK(info.st_mode)) { errno = EINVAL; return -1; } + if (copy_xattrs(-1, -1, origin, target) < 0) return -1; + const struct timespec times[2] = {info.st_atim, info.st_mtim}; + return utimensat(destinationDirectory, destination, times, AT_SYMLINK_NOFOLLOW); +#endif +} + +int platform_spawn(pid_t *pid, const char *executable, char *const argv[], + char *const environment[], const char *directory, int lock, + bool inheritInput, int output, int error) { + posix_spawn_file_actions_t actions; + posix_spawnattr_t attributes; + int result = posix_spawn_file_actions_init(&actions); + if (result != 0) return result; + result = posix_spawnattr_init(&attributes); + if (result != 0) { posix_spawn_file_actions_destroy(&actions); return result; } +#define CHECK(call) do { result = (call); if (result != 0) goto done; } while (0) +#if defined(__APPLE__) + CHECK(posix_spawnattr_setflags(&attributes, POSIX_SPAWN_CLOEXEC_DEFAULT)); + if (inheritInput) CHECK(posix_spawn_file_actions_addinherit_np(&actions, STDIN_FILENO)); +#else + if (inheritInput) CHECK(posix_spawn_file_actions_adddup2(&actions, STDIN_FILENO, STDIN_FILENO)); +#endif + if (!inheritInput) { + CHECK(posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0)); + } + // The _np spelling is required on macOS 15 and glibc 2.34. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + if (directory) CHECK(posix_spawn_file_actions_addchdir_np(&actions, directory)); +#pragma clang diagnostic pop + CHECK(posix_spawn_file_actions_adddup2(&actions, output, STDOUT_FILENO)); + CHECK(posix_spawn_file_actions_adddup2(&actions, error, STDERR_FILENO)); +#if defined(__APPLE__) + CHECK(posix_spawn_file_actions_addinherit_np(&actions, lock)); +#else + // All sources have been duplicated above fd 2 by the caller. Install the lock + // last at fd 3, then close everything higher without enumerating a racy fd list. + CHECK(posix_spawn_file_actions_adddup2(&actions, lock, 3)); + CHECK(posix_spawn_file_actions_addclosefrom_np(&actions, 4)); +#endif + result = posix_spawn(pid, executable, &actions, &attributes, argv, environment); +done: + posix_spawnattr_destroy(&attributes); + posix_spawn_file_actions_destroy(&actions); +#undef CHECK + return result; +} diff --git a/Sources/CPlatform/include/CPlatform.h b/Sources/CPlatform/include/CPlatform.h new file mode 100644 index 0000000..4e6d97e --- /dev/null +++ b/Sources/CPlatform/include/CPlatform.h @@ -0,0 +1,41 @@ +#ifndef CORE_CPLATFORM_H +#define CORE_CPLATFORM_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__APPLE__) +#include +#endif + +int platform_flock(int descriptor, int operation); +int platform_access(int directory, const char *name, int mode); +const char *platform_entry_name(const struct dirent *entry); +bool platform_system_alias(const char *name); +int platform_exchange(int directory, const char *name, const char *destination); +int platform_sync(int descriptor); +int platform_copy_data(int source, int destination); +int platform_copy_metadata(int source, int destination, mode_t mode); +int platform_copy_link_metadata(int sourceDirectory, const char *source, + int destinationDirectory, const char *destination); + +// Returns a POSIX error number, as posix_spawn does. The caller owns all fds. +// In the child only stdin, stdout, stderr and the specified lock survive exec. +int platform_spawn(pid_t *pid, const char *executable, char *const argv[], + char *const environment[], const char *directory, int lock, + bool inheritInput, int output, int error); + +#endif diff --git a/Tests/AgentsCoreTests/CachePublicationTests.swift b/Tests/AgentsCoreTests/CachePublicationTests.swift index fed75c4..7ae0ac1 100644 --- a/Tests/AgentsCoreTests/CachePublicationTests.swift +++ b/Tests/AgentsCoreTests/CachePublicationTests.swift @@ -1,4 +1,4 @@ -import Darwin +import CPlatform import Foundation import Testing diff --git a/Tests/AgentsCoreTests/CoreTestSupport.swift b/Tests/AgentsCoreTests/CoreTestSupport.swift index 7100df7..001d7ad 100644 --- a/Tests/AgentsCoreTests/CoreTestSupport.swift +++ b/Tests/AgentsCoreTests/CoreTestSupport.swift @@ -45,7 +45,7 @@ func gitHead(_ repo: URL) throws -> String { func stateTestProcess( root: URL, arguments: [String], environment: [String: String] = [:] ) throws -> Process { - var directory = Bundle(for: TransactionTestBundle.self).bundleURL.deletingLastPathComponent() + var directory = Bundle(for: TransactionTestBundle.self).bundleURL while !FileManager.default.isExecutableFile( atPath: directory.appendingPathComponent("StateTestProcess").path), directory.path != "/" { diff --git a/Tests/AgentsCoreTests/DirectoryHandleTests.swift b/Tests/AgentsCoreTests/DirectoryHandleTests.swift new file mode 100644 index 0000000..718c54c --- /dev/null +++ b/Tests/AgentsCoreTests/DirectoryHandleTests.swift @@ -0,0 +1,82 @@ +import CPlatform +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Portable filesystem contracts") +struct DirectoryHandleTests { + @Test func enumeratesHiddenUnicodeAndLongNamesAcrossRepeatedReads() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let names = [".hidden", "目录-🌍", String(repeating: "a", count: 255)] + for name in names { try Data(name.utf8).write(to: root.appendingPathComponent(name)) } + let directory = try DirectoryHandle(at: root) + #expect(try directory.names() == names.sorted()) + #expect(try directory.names() == names.sorted()) + #expect( + try FileManager.default.contentsOfDirectory(atPath: root.path).sorted() == names.sorted()) + } + + @Test func copiesModesAndDanglingLinksWithoutFollowingThem() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let source = root.appendingPathComponent("source") + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true) + let content = Data(repeating: 0xa5, count: 200_000) + let file = source.appendingPathComponent("executable") + try content.write(to: file) + try FileManager.default.setAttributes([.posixPermissions: 0o751], ofItemAtPath: file.path) + try FileManager.default.createSymbolicLink( + atPath: source.appendingPathComponent("dangling").path, withDestinationPath: "missing") + try FileManager.default.createSymbolicLink( + atPath: source.appendingPathComponent("reference").path, withDestinationPath: "executable") + let directory = try DirectoryHandle(at: root) + try directory.copy("copy", from: directory, named: "source") + let copy = try directory.child("copy") + #expect(try copy.read("executable") == content) + let executableInfo = try #require(try copy.info("executable")) + #expect(executableInfo.st_mode & 0o7777 == 0o751) + #expect(try copy.readLink("dangling") == "missing") + #expect(try copy.readLink("reference") == "executable") + #expect( + try FileHash.folderHash(root.appendingPathComponent("copy")) == FileHash.folderHash(source)) + let dangling = root.appendingPathComponent("copy/dangling") + #expect(!FileManager.default.fileExists(atPath: dangling.path)) + #expect( + try FileManager.default.attributesOfItem(atPath: dangling.path)[.type] as? FileAttributeType + == .typeSymbolicLink) + #expect( + try FileManager.default.attributesOfItem(atPath: file.path)[.posixPermissions] as? NSNumber + == 0o751) + } + + @Test func atomicallyExchangesNonemptyDirectories() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + for name in ["first", "second"] { + let child = root.appendingPathComponent(name) + try FileManager.default.createDirectory(at: child, withIntermediateDirectories: true) + try Data(name.utf8).write(to: child.appendingPathComponent("content")) + } + let directory = try DirectoryHandle(at: root) + try directory.rename("first", to: "second", swap: true) + #expect(try directory.child("first").read("content") == Data("second".utf8)) + #expect(try directory.child("second").read("content") == Data("first".utf8)) + } + + @Test func directoryAndRegularFileReadsRejectLinks() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let source = root.appendingPathComponent("source") + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true) + try Data("content".utf8).write(to: source.appendingPathComponent("file")) + let link = root.appendingPathComponent("link") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: source) + #expect(throws: CoreError.self) { try DirectoryHandle(at: link) } + let directory = try DirectoryHandle(at: root) + #expect(throws: CoreError.self) { try directory.read("link") } + let linkInfo = try #require(try directory.info("link")) + #expect(linkInfo.st_mode & S_IFMT == S_IFLNK) + } +} diff --git a/Tests/AgentsCoreTests/FileHashTests.swift b/Tests/AgentsCoreTests/FileHashTests.swift index ccc3168..42b33c9 100644 --- a/Tests/AgentsCoreTests/FileHashTests.swift +++ b/Tests/AgentsCoreTests/FileHashTests.swift @@ -5,6 +5,15 @@ import Testing @Suite("File hashes") struct FileHashTests { + @Test func sha256MatchesStandardVectors() { + #expect( + FileHash.sha256Hex(data: Data()) + == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") + #expect( + FileHash.sha256Hex(data: Data("abc".utf8)) + == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad") + } + @Test func arbitraryBytesCannotImpersonateTreeEntries() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } diff --git a/Tests/AgentsCoreTests/FileLockProcessTests.swift b/Tests/AgentsCoreTests/FileLockProcessTests.swift index a223281..c0a615f 100644 --- a/Tests/AgentsCoreTests/FileLockProcessTests.swift +++ b/Tests/AgentsCoreTests/FileLockProcessTests.swift @@ -1,17 +1,48 @@ import AgentsCore -import Darwin +import CPlatform import Foundation import Testing @Suite("Inherited file locks") struct FileLockProcessTests { + @Test func lockedChildClosesUnrelatedDescriptors() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let file = open(root.appendingPathComponent("private").path, O_CREAT | O_RDWR, 0o600) + try #require(file >= 0) + defer { close(file) } + let unrelated = fcntl(file, F_DUPFD, 64) + try #require(unrelated >= 64) + defer { close(unrelated) } + try FileLock.withDescriptor(at: root.appendingPathComponent("writer.lock")) { descriptor in + let output = try ProcessRunner.run( + "/bin/sh", arguments: ["-c", "test ! -e /dev/fd/$1", "sh", String(unrelated)], + inheritingLock: descriptor) + #expect(output.exitCode == 0) + } + } + + @Test func lockedChildPropagatesLaunchErrors() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + try FileLock.withDescriptor(at: root.appendingPathComponent("writer.lock")) { descriptor in + let error = + try #require(throws: (any Error).self) { + try ProcessRunner.run( + root.appendingPathComponent("missing").path, arguments: [], inheritingLock: descriptor) + } as NSError + #expect(error.domain == NSPOSIXErrorDomain) + #expect(error.code == Int(ENOENT)) + } + } + @Test func childKeepsLockAfterParentClosesItsDescriptor() throws { let root = try temporaryDirectory() defer { try? FileManager.default.removeItem(at: root) } let lock = root.appendingPathComponent("writer.lock") let ready = root.appendingPathComponent("child-ready") var child: Int32? - defer { if let child { Darwin.kill(child, SIGKILL) } } + defer { if let child { CPlatform.kill(child, SIGKILL) } } try FileLock.withDescriptor(at: lock) { descriptor in let script = """ defined(my $child = fork) or die $!; @@ -40,14 +71,14 @@ struct FileLockProcessTests { let contender = open(lock.path, O_RDWR | O_CLOEXEC) try #require(contender >= 0) defer { close(contender) } - #expect(flock(contender, LOCK_EX | LOCK_NB) == -1) + #expect(platform_flock(contender, LOCK_EX | LOCK_NB) == -1) #expect(errno == EWOULDBLOCK) - Darwin.kill(try #require(child), SIGCONT) + CPlatform.kill(try #require(child), SIGCONT) let deadline = Date().addingTimeInterval(10) var acquired = false repeat { - if let child { Darwin.kill(child, SIGCONT) } - acquired = flock(contender, LOCK_EX | LOCK_NB) == 0 + if let child { CPlatform.kill(child, SIGCONT) } + acquired = platform_flock(contender, LOCK_EX | LOCK_NB) == 0 if !acquired { Thread.sleep(forTimeInterval: 0.01) } } while !acquired && Date() < deadline #expect(acquired) diff --git a/Tests/AgentsCoreTests/FileSystemAccessTests.swift b/Tests/AgentsCoreTests/FileSystemAccessTests.swift new file mode 100644 index 0000000..a8ec06b --- /dev/null +++ b/Tests/AgentsCoreTests/FileSystemAccessTests.swift @@ -0,0 +1,325 @@ +import CPlatform +import Foundation +import Testing + +@testable import AgentsCore + +@Suite( + "Filesystem access policy", + .enabled(if: geteuid() != 0, "Permission-denial checks require an unprivileged user"), + .timeLimit(.minutes(1))) +struct FileSystemAccessTests { + @Test func firstAndRepeatedLockAcquisitionsReportInheritedDenial() throws { + let fixture = try AccessPolicyFixture(directories: false) + let lock = fixture.directory.appendingPathComponent("writer.lock") + var identity: ino_t? + for _ in 0..<3 { + expectAccessDenied(at: lock) { + try FileLock.withLock(at: lock) { _ = Issue.record("Denied lock must not enter its body") } + } + var info = stat() + try #require(lstat(lock.path, &info) == 0) + if let identity { #expect(info.st_ino == identity) } + identity = info.st_ino + #expect(platform_access(AT_FDCWD, lock.path, R_OK | W_OK) == -1) + try fixture.expectUnchanged() + } + #expect(try fixture.names() == ["user.txt", "writer.lock"]) + } + + @Test(arguments: ["locks", "one/two/locks"]) + func missingLockAncestorsRemainDenied(_ path: String) throws { + let fixture = try AccessPolicyFixture(directories: true) + let directory = fixture.directory.appendingPathComponent(path) + for _ in 0..<3 { + expectAccessDenied(at: directory) { + try FileLock.withLock(at: directory.appendingPathComponent("writer.lock")) { + _ = Issue.record("Denied directory must not reach the operation") + } + } + try fixture.expectUnchanged() + } + #expect(try fixture.names() == [path.components(separatedBy: "/")[0], "user.txt"].sorted()) + } + + @Test func sharedDirectoryCreationReportsFirstAndRepeatedDenial() throws { + let fixture = try AccessPolicyFixture(directories: true) + let target = fixture.directory.appendingPathComponent("workspace") + for _ in 0..<3 { + expectAccessDenied(at: target) { try FileSystem.createDirectory(at: target) } + try fixture.expectUnchanged() + } + #expect(try fixture.names() == ["user.txt", "workspace"]) + } + + @Test func scopeOperationsStopBeforeChangingUserContent() throws { + let fixture = try AccessPolicyFixture(directories: true) + let store = StateStore( + scope: .project, environment: RuntimeEnvironment(projectDirectory: fixture.directory)) + for _ in 0..<3 { + expectAccessDenied(at: store.directory) { + try store.withLock { try Data("changed".utf8).write(to: fixture.userFile) } + } + try fixture.expectUnchanged() + } + } + + @Test(arguments: ["directory", "file", "copied-directory", "copied-file"]) + func entryCreationReportsFirstAndRepeatedDenial(_ kind: String) throws { + let fixture = try AccessPolicyFixture(directories: true) + let source = fixture.root.appendingPathComponent("source") + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: false) + try Data("source".utf8).write(to: source.appendingPathComponent("content")) + let sourceHash = try FileHash.folderHash(source) + let directory = try DirectoryHandle(at: fixture.directory) + let target = fixture.directory.appendingPathComponent("entry") + for _ in 0..<3 { + expectAccessDenied(at: target) { + switch kind { + case "directory": try directory.makeDirectory("entry") + case "file": try directory.write("entry", data: Data("new bytes".utf8)) + case "copied-directory": + try directory.copy("entry", from: DirectoryHandle(at: fixture.root), named: "source") + default: + try directory.copy("entry", from: DirectoryHandle(at: source), named: "content") + } + } + try fixture.expectUnchanged() + #expect(try FileHash.folderHash(source) == sourceHash) + } + #expect(try fixture.names() == ["entry", "user.txt"]) + } + + @Test func deniedParentReportsDirectoryFileAndLinkCreationErrors() throws { + let fixture = try AccessPolicyFixture(directories: false) + let directory = try DirectoryHandle(at: fixture.directory) + try #require(chmod(fixture.directory.path, 0o500) == 0) + for _ in 0..<2 { + expectAccessDenied(at: fixture.directory.appendingPathComponent("child")) { + try directory.makeDirectory("child") + } + expectAccessDenied(at: fixture.directory.appendingPathComponent("file")) { + try directory.write("file", data: Data()) + } + expectAccessDenied(at: fixture.directory.appendingPathComponent("link")) { + try directory.link("link", destination: "user.txt") + } + #expect(try fixture.names() == ["user.txt"]) + #expect(try Data(contentsOf: fixture.userFile) == fixture.bytes) + #expect(try fixtureMetadata(fixture.userFile) == fixture.userMetadata) + } + } + + @Test func foundationPermissionErrorsKeepUserFilesUnchanged() throws { + let fixture = try AccessPolicyFixture(directories: false) + try #require(chmod(fixture.directory.path, 0o500) == 0) + let destination = fixture.directory.appendingPathComponent("copy") + for _ in 0..<2 { + expectAccessDenied(at: destination) { + try FileSystem.withAccessErrors(at: destination) { + try FileSystem.read(at: fixture.userFile).write(to: destination) + } + } + #expect(try Data(contentsOf: fixture.userFile) == fixture.bytes) + #expect(try fixtureMetadata(fixture.userFile) == fixture.userMetadata) + #expect(try fixture.names() == ["user.txt"]) + } + } + + @Test func unreadableCachedArtifactReportsItsPathOnEveryAttempt() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) + let cache = SourceCache(store: store) + let bytes = Data("cached artifact".utf8) + let digest = "sha256:" + FileHash.sha256Hex(data: bytes) + let cached = try store.withLock { try cache.storeArtifact(bytes, digest: digest) } + var original = stat() + try #require(lstat(cached.path, &original) == 0) + try #require(chmod(cached.path, 0) == 0) + defer { chmod(cached.path, original.st_mode & 0o777) } + for _ in 0..<2 { + expectAccessDenied(at: cached) { + _ = try store.withLock { try cache.storeArtifact(bytes, digest: digest) } + } + expectAccessDenied(at: cached) { _ = try FileHash.sha256Hex(file: cached) } + expectAccessDenied(at: cached) { _ = try FileSystem.readUnlessDenied(at: cached) } + var current = stat() + try #require(lstat(cached.path, ¤t) == 0) + #expect(current.st_mode & 0o777 == 0 && current.st_ino == original.st_ino) + } + try #require(chmod(cached.path, original.st_mode & 0o777) == 0) + #expect(try Data(contentsOf: cached) == bytes) + } + + @Test func unreadableCopySourceReportsSourceInsteadOfDestination() throws { + let fixture = try AccessPolicyFixture(directories: false) + let source = fixture.userFile + let destination = fixture.root.appendingPathComponent("copy") + var original = stat() + try #require(lstat(source.path, &original) == 0) + try #require(chmod(source.path, 0) == 0) + defer { chmod(source.path, original.st_mode & 0o777) } + for _ in 0..<2 { + expectAccessDenied(at: source) { + try FileSystem.withAccessErrors(at: destination) { + try FileManager.default.copyItem(at: source, to: destination) + } + } + var current = stat() + try #require(lstat(source.path, ¤t) == 0) + #expect(current.st_mode & 0o777 == 0 && current.st_ino == original.st_ino) + if FileManager.default.fileExists(atPath: destination.path) { + try FileManager.default.removeItem(at: destination) + } + } + try #require(chmod(source.path, original.st_mode & 0o777) == 0) + try fixture.expectUnchanged() + } +} + +@Suite("Filesystem diagnostics") +struct FileSystemErrorTests { + @Test(arguments: [NSFilePathErrorKey, NSURLErrorKey], [false, true]) + func preservesFoundationPaths(_ key: String, nested: Bool) throws { + let operation = URL(fileURLWithPath: "/fixture/destination") + let source = URL(fileURLWithPath: "/fixture/source/file") + let value: Any = key == NSFilePathErrorKey ? source.path : source + let permission = NSError( + domain: NSCocoaErrorDomain, code: NSFileReadNoPermissionError, + userInfo: [ + key: value, + NSUnderlyingErrorKey: NSError(domain: NSPOSIXErrorDomain, code: Int(EACCES)), + ]) + let error = + nested + ? NSError( + domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError, + userInfo: [NSFilePathErrorKey: operation.path, NSUnderlyingErrorKey: permission]) + : permission + expectAccessDenied(at: source) { + try FileSystem.withAccessErrors(at: operation) { throw error } + } + } + + @Test func optionalReadsTolerateEverythingButPermissionDenial() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + #expect(try FileSystem.readUnlessDenied(at: root.appendingPathComponent("missing")) == nil) + #expect(try FileSystem.readUnlessDenied(at: root) == nil) + } + + @Test(arguments: [EACCES, EPERM]) + func mapsPOSIXAndUnderlyingFoundationPermissionErrors(_ code: Int32) throws { + let path = URL(fileURLWithPath: "/fixture/entry") + let original = NSError(domain: NSPOSIXErrorDomain, code: Int(code)) + expectAccessDenied(at: path) { + throw FileSystem.posixError(code, at: path, otherwise: .invalidState("original")) + } + for error in [ + original, + NSError( + domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError, + userInfo: [NSUnderlyingErrorKey: original]), + ] { + expectAccessDenied(at: path) { + try FileSystem.withAccessErrors(at: path) { throw error } + } + } + } + + @Test func preservesGitAndUnrelatedFailures() throws { + let path = URL(fileURLWithPath: "/fixture/entry") + let git = GitError( + operation: .clone, source: "source", stderr: "Permission denied", + command: ["git", "clone"], exitCode: 128) + #expect(throws: git) { try FileSystem.withAccessErrors(at: path) { throw git } } + let other = CoreError.invalidState("unrelated") + #expect(throws: other) { try FileSystem.withAccessErrors(at: path) { throw other } } + #expect(FileSystem.posixError(ENOSPC, at: path, otherwise: other) == other) + } + + @Test func existingLockRetainsContentIdentityAndMetadata() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let lock = root.appendingPathComponent("writer.lock") + let bytes = Data("existing lock".utf8) + try bytes.write(to: lock) + try setFixtureMetadata(lock, mode: 0o640, value: Data("owner metadata".utf8)) + let before = try fixtureMetadata(lock) + var original = stat() + try #require(lstat(lock.path, &original) == 0) + for _ in 0..<2 { + try FileLock.withDescriptor(at: lock) { descriptor in + var current = stat() + try #require(fstat(descriptor, ¤t) == 0) + #expect(current.st_ino == original.st_ino && current.st_dev == original.st_dev) + } + #expect(try Data(contentsOf: lock) == bytes) + #expect(try fixtureMetadata(lock) == before) + } + } +} + +private func expectAccessDenied(at url: URL, _ body: () throws -> Void) { + let expected = CoreError.invalidState( + "permission denied: \(url.path); check the directory's permissions and default ACL") + #expect(throws: expected) { try body() } +} + +private final class AccessPolicyFixture { + let root: URL + let directory: URL + let userFile: URL + let bytes = Data("user-owned content".utf8) + let userMetadata: FixtureMetadata + let directoryMetadata: FixtureMetadata + + init(directories: Bool) throws { + root = try temporaryDirectory() + directory = root.appendingPathComponent("policy") + userFile = directory.appendingPathComponent("user.txt") + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + try bytes.write(to: userFile) + try setFixtureMetadata(userFile, mode: 0o640, value: Data("user metadata".utf8)) + try setFixtureMetadata(directory, mode: 0o700, value: Data("directory metadata".utf8)) + if directories { + try setRestrictiveInheritedDirectoryACL(directory) + } else { + try setRestrictiveInheritedFileACL(directory) + } + userMetadata = try fixtureMetadata(userFile) + directoryMetadata = try fixtureMetadata(directory) + } catch { + removeTemporaryDirectory(root) + throw error + } + } + + deinit { + #if os(macOS) + do { try ProcessRunner.run("/bin/chmod", arguments: ["-RN", root.path]) } catch { + Issue.record(error) + } + #endif + // The test owns these denied entries; only teardown restores access to remove them. + chmod(directory.path, 0o700) + if let entries = FileManager.default.enumerator(atPath: root.path) { + for case let name as String in entries { + chmod(root.appendingPathComponent(name).path, 0o700) + } + } + removeTemporaryDirectory(root) + } + + func names() throws -> [String] { + try FileManager.default.contentsOfDirectory(atPath: directory.path).sorted() + } + + func expectUnchanged() throws { + #expect(try Data(contentsOf: userFile) == bytes) + #expect(try fixtureMetadata(userFile) == userMetadata) + #expect(try fixtureMetadata(directory) == directoryMetadata) + } +} diff --git a/Tests/AgentsCoreTests/MetadataTestSupport.swift b/Tests/AgentsCoreTests/MetadataTestSupport.swift new file mode 100644 index 0000000..a36aaa3 --- /dev/null +++ b/Tests/AgentsCoreTests/MetadataTestSupport.swift @@ -0,0 +1,139 @@ +import AgentsCore +import CPlatform +import Foundation +import Testing + +struct FixtureMetadata: Equatable { + var mode: mode_t + var acl: Data + var attribute: Data + var defaultACL = Data() +} + +func setRestrictiveInheritedFileACL(_ directory: URL) throws { + do { + #if os(macOS) + try ProcessRunner.run( + "/bin/chmod", + arguments: ["+a", "everyone deny read,write,file_inherit,only_inherit", directory.path]) + #else + try setFixtureMetadata( + directory, mode: 0o700, value: Data(), defaultOwnerPermissions: 5) + #endif + } catch { + throw CoreError.invalidState( + "Restrictive inherited ACL fixture unavailable at \(directory.path): \(error)") + } +} + +func setRestrictiveInheritedDirectoryACL(_ directory: URL) throws { + do { + try setFixtureMetadata(directory, mode: 0o700, value: Data(), defaultOwnerPermissions: 5) + #if os(macOS) + try ProcessRunner.run( + "/bin/chmod", + arguments: [ + "+a", "everyone deny write,append,file_inherit,directory_inherit,only_inherit", + directory.path, + ]) + #endif + } catch { + throw CoreError.invalidState( + "Restrictive inherited directory ACL fixture unavailable at \(directory.path): \(error)") + } +} + +func setFixtureMetadata( + _ url: URL, mode: mode_t, value: Data, defaultOwnerPermissions: UInt16 = 6 +) throws { + var info = stat() + try #require(lstat(url.path, &info) == 0) + #if os(macOS) + try #require( + value.withUnsafeBytes { + setxattr(url.path, "org.agents.tests", $0.baseAddress, $0.count, 0, XATTR_NOFOLLOW) + } == 0) + if info.st_mode & S_IFMT != S_IFLNK { + try ProcessRunner.run( + "/bin/chmod", + arguments: ["+a", "everyone allow readattr,readextattr,readsecurity", url.path]) + } + try #require(lchmod(url.path, mode) == 0) + #else + // Linux symlink modes are fixed at 0777 and user xattrs/ACLs cannot be set + // on symlinks. Never chmod or set attributes through their referents. + guard info.st_mode & S_IFMT != S_IFLNK else { return } + try #require( + value.withUnsafeBytes { + lsetxattr(url.path, "user.org.agents.tests", $0.baseAddress, $0.count, 0) + } == 0) + // Linux's little-endian POSIX ACL xattr format: version 2, owner, named + // nobody (uid 65534), owning group, mask and other. No libacl dependency. + var acl = Data([2, 0, 0, 0]) + for (tag, permissions, identifier): (UInt16, UInt16, UInt32) in [ + (1, 6, .max), (2, 4, 65534), (4, 4, .max), (16, 4, .max), (32, 0, .max), + ] { + for field in [UInt32(tag) | (UInt32(permissions) << 16), identifier] { + var bytes = field.littleEndian + withUnsafeBytes(of: &bytes) { acl.append(contentsOf: $0) } + } + } + try #require( + acl.withUnsafeBytes { + lsetxattr(url.path, "system.posix_acl_access", $0.baseAddress, $0.count, 0) + } == 0) + if info.st_mode & S_IFMT == S_IFDIR { + var defaultACL = acl + defaultACL[6] = UInt8(truncatingIfNeeded: defaultOwnerPermissions) + defaultACL[7] = UInt8(truncatingIfNeeded: defaultOwnerPermissions >> 8) + try #require( + defaultACL.withUnsafeBytes { + lsetxattr(url.path, "system.posix_acl_default", $0.baseAddress, $0.count, 0) + } == 0) + } + try #require(chmod(url.path, mode) == 0) + #endif +} + +func fixtureMetadata(_ url: URL) throws -> FixtureMetadata { + var info = stat() + try #require(lstat(url.path, &info) == 0) + #if os(macOS) + let size = getxattr(url.path, "org.agents.tests", nil, 0, 0, XATTR_NOFOLLOW) + try #require(size >= 0) + var attribute = Data(count: size) + try #require( + attribute.withUnsafeMutableBytes { + getxattr(url.path, "org.agents.tests", $0.baseAddress, $0.count, 0, XATTR_NOFOLLOW) + } == size) + var text = "" + if info.st_mode & S_IFMT != S_IFLNK { + let acl = try #require(acl_get_file(url.path, ACL_TYPE_EXTENDED)) + defer { acl_free(UnsafeMutableRawPointer(acl)) } + if let value = acl_to_text(acl, nil) { + text = String(cString: value) + acl_free(value) + } + } + return FixtureMetadata(mode: info.st_mode, acl: Data(text.utf8), attribute: attribute) + #else + if info.st_mode & S_IFMT == S_IFLNK { + return FixtureMetadata(mode: info.st_mode, acl: Data(), attribute: Data()) + } + func read(_ name: String) throws -> Data { + let size = lgetxattr(url.path, name, nil, 0) + if size < 0 && errno == ENODATA { return Data() } + try #require(size >= 0) + var value = Data(count: size) + try #require( + value.withUnsafeMutableBytes { + lgetxattr(url.path, name, $0.baseAddress, $0.count) + } == size) + return value + } + return FixtureMetadata( + mode: info.st_mode, acl: try read("system.posix_acl_access"), + attribute: try read("user.org.agents.tests"), + defaultACL: info.st_mode & S_IFMT == S_IFDIR ? try read("system.posix_acl_default") : Data()) + #endif +} diff --git a/Tests/AgentsCoreTests/ProcessTestSupport.swift b/Tests/AgentsCoreTests/ProcessTestSupport.swift index d62a377..b34fd50 100644 --- a/Tests/AgentsCoreTests/ProcessTestSupport.swift +++ b/Tests/AgentsCoreTests/ProcessTestSupport.swift @@ -1,4 +1,4 @@ -import Darwin +import CPlatform import Foundation import Testing @@ -18,7 +18,7 @@ func finishProcesses(_ processes: [Process], resuming pause: GitTransactionPause func terminateProcess(_ process: Process) { if process.isRunning { - Darwin.kill(process.processIdentifier, SIGKILL) + CPlatform.kill(process.processIdentifier, SIGKILL) process.waitUntilExit() } } @@ -39,7 +39,7 @@ final class ProcessSignal { func send(_ message: String) throws { let data = Data((message + "\n").utf8) - let count = data.withUnsafeBytes { Darwin.write(descriptor, $0.baseAddress, $0.count) } + let count = data.withUnsafeBytes { CPlatform.write(descriptor, $0.baseAddress, $0.count) } try #require(count == data.count) } @@ -53,7 +53,7 @@ final class ProcessSignal { if result < 0 && errno == EINTR { continue } try #require(result > 0, "Timed out waiting for \(url.lastPathComponent)") var byte: UInt8 = 0 - try #require(Darwin.read(descriptor, &byte, 1) == 1) + try #require(CPlatform.read(descriptor, &byte, 1) == 1) if byte == 10 { return String(decoding: bytes, as: UTF8.self) } bytes.append(byte) } @@ -113,6 +113,6 @@ final class GitTransactionPause { let pids = (try? String(contentsOf: marker, encoding: .utf8))? .split(whereSeparator: \.isWhitespace).compactMap { Int32($0) } ?? [] - for pid in pids { Darwin.kill(pid, SIGKILL) } + for pid in pids { CPlatform.kill(pid, SIGKILL) } } } diff --git a/Tests/AgentsCoreTests/StateTransactionTests.swift b/Tests/AgentsCoreTests/StateTransactionTests.swift index bd52944..1df6c5b 100644 --- a/Tests/AgentsCoreTests/StateTransactionTests.swift +++ b/Tests/AgentsCoreTests/StateTransactionTests.swift @@ -1,4 +1,4 @@ -import Darwin +import CPlatform import Foundation import Testing diff --git a/Tests/AgentsCoreTests/TransactionMetadataTests.swift b/Tests/AgentsCoreTests/TransactionMetadataTests.swift index 65bb776..dcc9c93 100644 --- a/Tests/AgentsCoreTests/TransactionMetadataTests.swift +++ b/Tests/AgentsCoreTests/TransactionMetadataTests.swift @@ -1,4 +1,4 @@ -import Darwin +import CPlatform import Foundation import Testing @@ -14,15 +14,7 @@ struct TransactionMetadataTests { try Data("owner content".utf8).write(to: target) let files = [target, fixture.store.declarationURL, fixture.store.resolvedURL] for (file, mode) in zip(files, [0o644, 0o440, 0o600]) { - let value = Data("owner metadata".utf8) - try #require( - value.withUnsafeBytes { - setxattr(file.path, "org.agents.tests", $0.baseAddress, $0.count, 0, XATTR_NOFOLLOW) - } == 0) - try ProcessRunner.run( - "/bin/chmod", - arguments: ["+a", "everyone allow readattr,readextattr,readsecurity", file.path]) - try #require(chmod(file.path, mode_t(mode)) == 0) + try setFixtureMetadata(file, mode: mode_t(mode), value: Data("owner metadata".utf8)) } let before = try files.map(metadata) let original = try files.map { try Data(contentsOf: $0) } @@ -122,17 +114,8 @@ struct TransactionMetadataTests { try FileManager.default.createSymbolicLink(atPath: link.path, withDestinationPath: "SKILL.md") let urls = [target, file, nested, link] for (url, mode) in zip(urls, [0o750, 0o666, 0o775, 0o751]) { - #expect(lchmod(url.path, mode_t(mode)) == 0) - let value = Data("metadata:\(url.lastPathComponent)".utf8) - let result = value.withUnsafeBytes { - setxattr(url.path, "org.agents.tests", $0.baseAddress, $0.count, 0, XATTR_NOFOLLOW) - } - #expect(result == 0) - if url != link { - try ProcessRunner.run( - "/bin/chmod", - arguments: ["+a", "everyone allow readattr,readextattr,readsecurity", url.path]) - } + try setFixtureMetadata( + url, mode: mode_t(mode), value: Data("metadata:\(url.lastPathComponent)".utf8)) } let before = try urls.map(metadata) let bytes = try FileHash.folderHash(target) @@ -146,12 +129,6 @@ struct TransactionMetadataTests { try fixture.check(committed: false) } - private struct Metadata: Equatable { - var mode: mode_t - var acl: String - var attribute: Data - } - private func makeReadOnlyTree(_ root: URL) throws -> [URL] { let nested = root.appendingPathComponent("nested") try FileManager.default.createDirectory(at: nested, withIntermediateDirectories: true) @@ -161,17 +138,7 @@ struct TransactionMetadataTests { try FileManager.default.createSymbolicLink(atPath: link.path, withDestinationPath: "SKILL.md") let urls = [root, root.appendingPathComponent("SKILL.md"), nested, file, link] for (url, mode) in zip(urls, [0o555, 0o444, 0o555, 0o444, 0o751]) { - let value = Data("preserved metadata".utf8) - try #require( - value.withUnsafeBytes { - setxattr(url.path, "org.agents.tests", $0.baseAddress, $0.count, 0, XATTR_NOFOLLOW) - } == 0) - if url != link { - try ProcessRunner.run( - "/bin/chmod", - arguments: ["+a", "everyone allow readattr,readextattr,readsecurity", url.path]) - } - try #require(lchmod(url.path, mode_t(mode)) == 0) + try setFixtureMetadata(url, mode: mode_t(mode), value: Data("preserved metadata".utf8)) } return urls } @@ -221,25 +188,7 @@ struct TransactionMetadataTests { } } - private func metadata(_ url: URL) throws -> Metadata { - var info = stat() - try #require(lstat(url.path, &info) == 0) - let size = getxattr(url.path, "org.agents.tests", nil, 0, 0, XATTR_NOFOLLOW) - try #require(size >= 0) - var data = Data(count: size) - let count = data.withUnsafeMutableBytes { - getxattr(url.path, "org.agents.tests", $0.baseAddress, $0.count, 0, XATTR_NOFOLLOW) - } - try #require(count == size) - var text = "" - if info.st_mode & S_IFMT != S_IFLNK { - let acl = try #require(acl_get_file(url.path, ACL_TYPE_EXTENDED)) - defer { acl_free(UnsafeMutableRawPointer(acl)) } - if let value = acl_to_text(acl, nil) { - text = String(cString: value) - acl_free(value) - } - } - return Metadata(mode: info.st_mode, acl: text, attribute: data) + private func metadata(_ url: URL) throws -> FixtureMetadata { + try fixtureMetadata(url) } } diff --git a/Tests/AgentsCoreTests/WatchDurabilityTests.swift b/Tests/AgentsCoreTests/WatchDurabilityTests.swift index b651a3e..5aaa87a 100644 --- a/Tests/AgentsCoreTests/WatchDurabilityTests.swift +++ b/Tests/AgentsCoreTests/WatchDurabilityTests.swift @@ -1,5 +1,5 @@ import AgentsCore -import Darwin +import CPlatform import Foundation import Testing @@ -231,7 +231,7 @@ final class WatchGitFixture { func kill(_ child: Process, at step: String) throws { defer { if child.isRunning { - Darwin.kill(child.processIdentifier, SIGKILL) + CPlatform.kill(child.processIdentifier, SIGKILL) child.waitUntilExit() } } @@ -242,7 +242,7 @@ final class WatchGitFixture { } try #require(FileManager.default.fileExists(atPath: marker.path), "did not reach \(step)") #expect(try String(contentsOf: marker, encoding: .utf8) == step) - Darwin.kill(child.processIdentifier, SIGKILL) + CPlatform.kill(child.processIdentifier, SIGKILL) child.waitUntilExit() try FileManager.default.removeItem(at: marker) } diff --git a/Tests/AgentsCoreTests/WatchGitLockTests.swift b/Tests/AgentsCoreTests/WatchGitLockTests.swift index 6ec0d28..279cc9b 100644 --- a/Tests/AgentsCoreTests/WatchGitLockTests.swift +++ b/Tests/AgentsCoreTests/WatchGitLockTests.swift @@ -1,5 +1,5 @@ import AgentsCore -import Darwin +import CPlatform import Foundation import Testing @@ -39,10 +39,10 @@ struct WatchGitLockTests { defer { // Freeze the scope owner before killing its Git children, so error handling // cannot race the assertions about abandoned locks. - if writer.isRunning { Darwin.kill(writer.processIdentifier, SIGSTOP) } + if writer.isRunning { CPlatform.kill(writer.processIdentifier, SIGSTOP) } if let text = try? String(contentsOf: ready, encoding: .utf8) { for pid in text.split(whereSeparator: \.isWhitespace).compactMap({ Int32($0) }) { - Darwin.kill(pid, SIGKILL) + CPlatform.kill(pid, SIGKILL) } } terminate(writer) @@ -63,11 +63,11 @@ struct WatchGitLockTests { atPath: fixture.root.appendingPathComponent("reader-finished").path)) for lock in locks { #expect(FileManager.default.fileExists(atPath: lock.path)) } terminate(reader) - Darwin.kill(writer.processIdentifier, SIGSTOP) + CPlatform.kill(writer.processIdentifier, SIGSTOP) let pids = try String(contentsOf: ready, encoding: .utf8) .split(whereSeparator: \.isWhitespace).compactMap { Int32($0) } try #require(pids.count == 2) - for pid in pids { Darwin.kill(pid, SIGKILL) } + for pid in pids { CPlatform.kill(pid, SIGKILL) } terminate(writer) try FileManager.default.removeItem(at: ready) try FileManager.default.removeItem(at: hook) @@ -161,7 +161,7 @@ struct WatchGitLockTests { private func terminate(_ process: Process) { if process.isRunning { - Darwin.kill(process.processIdentifier, SIGKILL) + CPlatform.kill(process.processIdentifier, SIGKILL) process.waitUntilExit() } } diff --git a/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift b/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift index c7713e9..04bd666 100644 --- a/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift +++ b/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift @@ -1,5 +1,5 @@ import AgentsCore -import Darwin +import CPlatform import Foundation import Testing diff --git a/Tests/AgentsCoreTests/WatchStateTests.swift b/Tests/AgentsCoreTests/WatchStateTests.swift index e4c5ea7..ba320c3 100644 --- a/Tests/AgentsCoreTests/WatchStateTests.swift +++ b/Tests/AgentsCoreTests/WatchStateTests.swift @@ -1,5 +1,5 @@ import AgentsCore -import Darwin +import CPlatform import Foundation import Testing diff --git a/Tests/AgentsInstructionsTests/FileReadAccessTests.swift b/Tests/AgentsInstructionsTests/FileReadAccessTests.swift new file mode 100644 index 0000000..5ae3c85 --- /dev/null +++ b/Tests/AgentsInstructionsTests/FileReadAccessTests.swift @@ -0,0 +1,95 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsInstructions + +@Suite( + "Instruction file read access", + .enabled(if: geteuid() != 0, "Permission-denial checks require an unprivileged user"), + .timeLimit(.minutes(1))) +struct InstructionFileReadAccessTests { + @Test func unreadableTargetReportsItsPath() throws { + let fixture = try InstructionFixture() + let file = fixture.project.appendingPathComponent("AGENTS.md") + try fixture.write("User content", to: file) + let before = try fixture.snapshot() + try withUnreadableFile(file) { + #expect(throws: accessError(file)) { try InstructionTargets.read(file) } + } + #expect(try fixture.snapshot() == before) + } + + @Test func unreadableOwnInstructionsReportTheirPath() throws { + let fixture = try InstructionFixture() + try fixture.own("guide") + let file = fixture.project.appendingPathComponent(".agent/instructions/guide.md") + let before = try fixture.snapshot() + try withUnreadableFile(file) { + #expect { + try InstructionOperations.listOwn(environment: fixture.environment) + } throws: { error in + guard case CoreError.invalidState(let message) = error else { return false } + let prefix = "permission denied: " + let suffix = "; check the directory's permissions and default ACL" + guard message.hasPrefix(prefix), message.hasSuffix(suffix) else { return false } + let path = String(message.dropFirst(prefix.count).dropLast(suffix.count)) + return URL(fileURLWithPath: path).resolvingSymlinksInPath() + == file.resolvingSymlinksInPath() + } + } + #expect(try fixture.snapshot() == before) + } + + @Test(arguments: ["config", "target"]) + func doctorReportsUnreadableFiles(_ kind: String) throws { + let fixture = try InstructionFixture() + let file = + kind == "config" + ? fixture.home.appendingPathComponent(".codex/config.toml") + : fixture.project.appendingPathComponent("AGENTS.md") + try fixture.write("", to: file) + let before = try fixture.snapshot() + try withUnreadableFile(file) { + let report = try InstructionOperations.doctor(environment: fixture.environment) + #expect( + report.diagnostics.contains { + $0.path == file && $0.message.contains(accessError(file).description) + }) + } + #expect(try fixture.snapshot() == before) + } + + @Test func doctorReportsAnUnreadableManagedTargetOnce() throws { + let fixture = try InstructionFixture() + try fixture.own("guide") + try fixture.addOwn(names: ["guide"], agents: [.codex]) + let file = fixture.project.appendingPathComponent("AGENTS.md") + try withUnreadableFile(file) { + let report = try InstructionOperations.doctor(environment: fixture.environment) + #expect(report.diagnostics.filter { $0.message.contains("permission denied: ") }.count == 1) + } + } +} + +private func accessError(_ file: URL) -> CoreError { + .invalidState( + "permission denied: \(file.path); check the directory's permissions and default ACL") +} + +private func withUnreadableFile(_ file: URL, _ body: () throws -> Void) throws { + let attributes = try FileManager.default.attributesOfItem(atPath: file.path) + let mode = try #require(attributes[.posixPermissions] as? NSNumber) + try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: file.path) + defer { + do { + try FileManager.default.setAttributes([.posixPermissions: mode], ofItemAtPath: file.path) + } catch { Issue.record(error) } + } + for _ in 0..<2 { + try body() + let current = try FileManager.default.attributesOfItem(atPath: file.path) + #expect((current[.posixPermissions] as? NSNumber)?.intValue == 0) + #expect(current[.systemFileNumber] as? NSNumber == attributes[.systemFileNumber] as? NSNumber) + } +} diff --git a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift index 392fe1c..27d9c52 100644 --- a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift @@ -5,6 +5,19 @@ import Testing @Suite("Own instructions and generated targets") struct TargetLifecycleTests { + @Test func doctorReportsAnOwnFileReplacedByADirectory() throws { + let fixture = try InstructionFixture() + try fixture.own("guide", heading: "# Project Guide") + try fixture.addOwn(names: ["guide"]) + let file = fixture.project.appendingPathComponent(".agent/instructions/guide.md") + try FileManager.default.removeItem(at: file) + try FileManager.default.createDirectory(at: file, withIntermediateDirectories: false) + #expect( + try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { + $0.kind == .ownChanged + }) + } + @Test func ownInstructionsAreReadLiveAndRecordedByHash() throws { let fixture = try InstructionFixture() try fixture.section("shared") diff --git a/Tests/AgentsSkillsTests/ArchiveSafetyTests.swift b/Tests/AgentsSkillsTests/ArchiveSafetyTests.swift index 4094927..1fbae37 100644 --- a/Tests/AgentsSkillsTests/ArchiveSafetyTests.swift +++ b/Tests/AgentsSkillsTests/ArchiveSafetyTests.swift @@ -16,7 +16,7 @@ struct ArchiveSafetyTests { try fixture.commit() _ = try fixture.add(mode: .copy) let before = try fixture.stateAndTargetBytes() - let archive = zip(entries: [ + let archive = zipArchive(entries: [ ("SKILL.md", Data("---\nname: zip-skill\ndescription: Test\n---".utf8), 0o100644), ( path, path.hasSuffix("/") ? Data() : Data("payload".utf8), @@ -64,7 +64,7 @@ struct ArchiveSafetyTests { @Test func generatedZipFixtureIsAValidArchive() throws { let fixture = try SkillFixture() let skill = Data("---\nname: demo\ndescription: Test\n---".utf8) - let data = zip(entries: [("SKILL.md", skill, 0o100644)]) + let data = zipArchive(entries: [("SKILL.md", skill, 0o100644)]) let provider = WellKnownProvider { _ in data } let artifact = LockedArtifact( type: .archive, url: "https://archive.test/skill.zip", @@ -72,49 +72,4 @@ struct ArchiveSafetyTests { let restored = try provider.restore(artifact, cache: SourceCache(store: fixture.store())) #expect(restored.files["SKILL.md"] == skill) } - - private func zip(entries: [(String, Data, UInt32)]) -> Data { - var local = Data() - var central = Data() - func number(_ value: T, to data: inout Data) { - var little = value.littleEndian - withUnsafeBytes(of: &little) { data.append(contentsOf: $0) } - } - for (path, content, mode) in entries { - let name = Data(path.utf8) - let offset = UInt32(local.count) - var crc: UInt32 = 0xffff_ffff - for byte in content { - crc ^= UInt32(byte) - for _ in 0..<8 { crc = (crc >> 1) ^ (crc & 1 == 0 ? 0 : 0xedb8_8320) } - } - crc ^= 0xffff_ffff - number(UInt32(0x0403_4b50), to: &local) - for value: UInt16 in [20, 0, 0, 0, 0] { number(value, to: &local) } - for value in [crc, UInt32(content.count), UInt32(content.count)] { number(value, to: &local) } - number(UInt16(name.count), to: &local) - number(UInt16(0), to: &local) - local.append(name) - local.append(content) - number(UInt32(0x0201_4b50), to: ¢ral) - for value: UInt16 in [0x0314, 20, 0, 0, 0, 0] { number(value, to: ¢ral) } - for value in [crc, UInt32(content.count), UInt32(content.count)] { - number(value, to: ¢ral) - } - for value: UInt16 in [UInt16(name.count), 0, 0, 0, 0] { number(value, to: ¢ral) } - number(mode << 16, to: ¢ral) - number(offset, to: ¢ral) - central.append(name) - } - let offset = UInt32(local.count) - local.append(central) - number(UInt32(0x0605_4b50), to: &local) - for value: UInt16 in [0, 0, UInt16(entries.count), UInt16(entries.count)] { - number(value, to: &local) - } - number(UInt32(central.count), to: &local) - number(offset, to: &local) - number(UInt16(0), to: &local) - return local - } } diff --git a/Tests/AgentsSkillsTests/ArchiveTestSupport.swift b/Tests/AgentsSkillsTests/ArchiveTestSupport.swift new file mode 100644 index 0000000..1ae3d2f --- /dev/null +++ b/Tests/AgentsSkillsTests/ArchiveTestSupport.swift @@ -0,0 +1,46 @@ +import Foundation + +func zipArchive(entries: [(String, Data, UInt32)]) -> Data { + var local = Data() + var central = Data() + func number(_ value: T, to data: inout Data) { + var little = value.littleEndian + withUnsafeBytes(of: &little) { data.append(contentsOf: $0) } + } + for (path, content, mode) in entries { + let name = Data(path.utf8) + let offset = UInt32(local.count) + var crc: UInt32 = 0xffff_ffff + for byte in content { + crc ^= UInt32(byte) + for _ in 0..<8 { crc = (crc >> 1) ^ (crc & 1 == 0 ? 0 : 0xedb8_8320) } + } + crc ^= 0xffff_ffff + number(UInt32(0x0403_4b50), to: &local) + for value: UInt16 in [20, 0, 0, 0, 0] { number(value, to: &local) } + for value in [crc, UInt32(content.count), UInt32(content.count)] { number(value, to: &local) } + number(UInt16(name.count), to: &local) + number(UInt16(0), to: &local) + local.append(name) + local.append(content) + number(UInt32(0x0201_4b50), to: ¢ral) + for value: UInt16 in [0x0314, 20, 0, 0, 0, 0] { number(value, to: ¢ral) } + for value in [crc, UInt32(content.count), UInt32(content.count)] { + number(value, to: ¢ral) + } + for value: UInt16 in [UInt16(name.count), 0, 0, 0, 0] { number(value, to: ¢ral) } + number(mode << 16, to: ¢ral) + number(offset, to: ¢ral) + central.append(name) + } + let offset = UInt32(local.count) + local.append(central) + number(UInt32(0x0605_4b50), to: &local) + for value: UInt16 in [0, 0, UInt16(entries.count), UInt16(entries.count)] { + number(value, to: &local) + } + number(UInt32(central.count), to: &local) + number(offset, to: &local) + number(UInt16(0), to: &local) + return local +} diff --git a/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift b/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift index dc0eab5..7bb3fdf 100644 --- a/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift +++ b/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift @@ -1,5 +1,5 @@ import AgentsCore -import Darwin +import CPlatform import Foundation import Testing @@ -130,7 +130,6 @@ struct AutomaticSelectionTests { ).write(to: git) try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: git.path) var directory = Bundle(for: AutomaticSelectionTestBundle.self).bundleURL - .deletingLastPathComponent() while !FileManager.default.isExecutableFile( atPath: directory.appendingPathComponent("StateTestProcess").path), directory.path != "/" { diff --git a/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift b/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift index 3216cc2..8d1e5a0 100644 --- a/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift +++ b/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift @@ -6,6 +6,17 @@ import Testing @Suite("Skill Discovery") struct SkillDiscoveryTests { + @Test(arguments: ["marketplace.json", "plugin.json"]) + func pluginMetadataThatIsADirectoryDoesNotStopDiscovery(_ name: String) throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + try writeDiscoverySkill(root.appendingPathComponent("skills/source"), name: "source") + try FileManager.default.createDirectory( + at: root.appendingPathComponent(".claude-plugin/" + name), + withIntermediateDirectories: true) + #expect(try Discovery.discover(in: root).map(\.name) == ["source"]) + } + @Test func discoversSkillsWithUndecodableResolvedHint() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } diff --git a/Tests/AgentsSkillsTests/FileReadAccessTests.swift b/Tests/AgentsSkillsTests/FileReadAccessTests.swift new file mode 100644 index 0000000..a6d781b --- /dev/null +++ b/Tests/AgentsSkillsTests/FileReadAccessTests.swift @@ -0,0 +1,77 @@ +import AgentsCore +import CPlatform +import Foundation +import Testing + +@testable import AgentsSkills + +@Suite( + "Skill file read access", + .enabled(if: geteuid() != 0, "Permission-denial checks require an unprivileged user"), + .timeLimit(.minutes(1))) +struct SkillFileReadAccessTests { + @Test func unreadableCachedArtifactStopsRestoreWithoutFetching() throws { + let fixture = try SkillFixture() + let store = fixture.store() + let cache = SourceCache(store: store) + let bytes = Data("---\nname: demo\ndescription: Test skill\n---\n".utf8) + let digest = "sha256:" + FileHash.sha256Hex(data: bytes) + let cached = try store.withLock { try cache.storeArtifact(bytes, digest: digest) } + let artifact = LockedArtifact( + type: .skillMD, url: "https://example.test/SKILL.md", digest: digest) + let provider = WellKnownProvider { _ in + Issue.record("An unreadable cached artifact must not trigger a fetch") + return bytes + } + try withUnreadableFile(cached) { + _ = try provider.restore(artifact, cache: cache) + } + #expect(try Data(contentsOf: cached) == bytes) + } + + @Test func unreadableSkillFileStopsInspectionAndDiscovery() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "Original") + let directory = fixture.repo.appendingPathComponent("skills/demo") + let file = directory.appendingPathComponent("SKILL.md") + let lifecycle = try SkillLifecycle(store: fixture.store(), provider: WellKnownProvider()) + try withUnreadableFile(file) { _ = try lifecycle.entries(directory) } + try withUnreadableFile(file) { _ = try Discovery.parseSkill(at: file) } + } + + @Test(arguments: ["marketplace.json", "plugin.json"]) + func unreadablePluginMetadataStopsDiscovery(_ name: String) throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "Original") + let directory = fixture.repo.appendingPathComponent(".claude-plugin") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + let file = directory.appendingPathComponent(name) + try Data("{}".utf8).write(to: file) + try withUnreadableFile(file) { _ = try Discovery.discover(in: fixture.repo) } + } +} + +private func withUnreadableFile(_ file: URL, _ body: () throws -> Void) throws { + let bytes = try Data(contentsOf: file) + var original = stat() + try #require(lstat(file.path, &original) == 0) + try #require(chmod(file.path, 0) == 0) + defer { chmod(file.path, original.st_mode & 0o777) } + for _ in 0..<2 { + #expect { + try body() + } throws: { error in + guard case CoreError.invalidState(let message) = error else { return false } + let prefix = "permission denied: " + let suffix = "; check the directory's permissions and default ACL" + guard message.hasPrefix(prefix), message.hasSuffix(suffix) else { return false } + let path = String(message.dropFirst(prefix.count).dropLast(suffix.count)) + return URL(fileURLWithPath: path).resolvingSymlinksInPath() == file.resolvingSymlinksInPath() + } + var current = stat() + try #require(lstat(file.path, ¤t) == 0) + #expect(current.st_mode & 0o777 == 0 && current.st_ino == original.st_ino) + } + try #require(chmod(file.path, original.st_mode & 0o777) == 0) + #expect(try Data(contentsOf: file) == bytes) +} diff --git a/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift b/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift index 9790231..7f52db1 100644 --- a/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift @@ -1,5 +1,5 @@ import AgentsCore -import Darwin +import CPlatform import Foundation import Testing @@ -212,7 +212,7 @@ extension LockedArtifactLifecycleTests { } private func artifactTestProcess(root: URL) throws -> Process { - var directory = Bundle(for: ArtifactTestBundle.self).bundleURL.deletingLastPathComponent() + var directory = Bundle(for: ArtifactTestBundle.self).bundleURL while !FileManager.default.isExecutableFile( atPath: directory.appendingPathComponent("StateTestProcess").path), directory.path != "/" { diff --git a/Tests/AgentsSkillsTests/NetworkingTests.swift b/Tests/AgentsSkillsTests/NetworkingTests.swift new file mode 100644 index 0000000..e927274 --- /dev/null +++ b/Tests/AgentsSkillsTests/NetworkingTests.swift @@ -0,0 +1,47 @@ +import Foundation +import Testing + +@testable import AgentsSkills + +@Suite("Artifact networking") +struct NetworkingTests { + @Test func defaultFetcherLoadsHTTPData() throws { + // Exercise the default loader: injected fetch closures cannot detect a + // missing FoundationNetworking linkage on Linux. The child alarm bounds I/O. + let script = """ + use IO::Socket::INET; + alarm 15; + my $server = IO::Socket::INET->new( + LocalAddr => '127.0.0.1', LocalPort => 0, Listen => 1, Proto => 'tcp' + ) or die $!; + $| = 1; + print $server->sockport, "\\n"; + my $client = $server->accept() or die $!; + while (my $line = <$client>) { last if $line eq "\\r\\n"; } + print $client "HTTP/1.1 200 OK\\r\\nContent-Length: 8\\r\\nConnection: close\\r\\n\\r\\nartifact"; + close $client; + """ + let process = Process() + let output = Pipe() + process.executableURL = URL(fileURLWithPath: "/usr/bin/perl") + process.arguments = ["-e", script] + process.standardOutput = output + try process.run() + output.fileHandleForWriting.closeFile() + defer { + if process.isRunning { process.terminate() } + process.waitUntilExit() + try? output.fileHandleForReading.close() + } + var bytes = Data() + while let byte = try output.fileHandleForReading.read(upToCount: 1), !byte.isEmpty { + if byte == Data([10]) { break } + bytes.append(byte) + } + let port = try #require(Int(String(decoding: bytes, as: UTF8.self))) + let url = try #require(URL(string: "http://127.0.0.1:\(port)/artifact")) + #expect(try WellKnownProvider().fetch(url) == Data("artifact".utf8)) + process.waitUntilExit() + #expect(process.terminationStatus == 0) + } +} diff --git a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift index 3f965da..a3419db 100644 --- a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift +++ b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift @@ -1,7 +1,7 @@ import AgentsCore import AgentsInstructions import AgentsSkills -import Darwin +import CPlatform import Foundation import Testing @@ -32,7 +32,7 @@ struct ReadOnlyInspectionTests { let descriptor = open(lock.path, O_RDONLY | O_CLOEXEC) try #require(descriptor >= 0) defer { close(descriptor) } - let acquired = flock(descriptor, LOCK_EX | LOCK_NB) + let acquired = platform_flock(descriptor, LOCK_EX | LOCK_NB) let lockError = errno #expect(acquired == -1) #expect(lockError == EWOULDBLOCK) @@ -416,7 +416,7 @@ struct ReadOnlyInspectionTests { } private func interruptedTransaction(root: URL, scope: InstallScope) throws -> Process { - var directory = Bundle(for: InspectionTestBundle.self).bundleURL.deletingLastPathComponent() + var directory = Bundle(for: InspectionTestBundle.self).bundleURL while !FileManager.default.isExecutableFile( atPath: directory.appendingPathComponent("StateTestProcess").path), directory.path != "/" { diff --git a/Tests/AgentsSkillsTests/WellKnownArtifactTests.swift b/Tests/AgentsSkillsTests/WellKnownArtifactTests.swift index b51a80d..5dd801f 100644 --- a/Tests/AgentsSkillsTests/WellKnownArtifactTests.swift +++ b/Tests/AgentsSkillsTests/WellKnownArtifactTests.swift @@ -131,26 +131,20 @@ extension WellKnownSourceTests { } @Test func fetchesDigestVerifiedZipArchives() throws { - let archiveRoot = try temporaryDirectory() - defer { removeTemporaryDirectory(archiveRoot) } - try """ - --- - name: zip-skill - description: Zip skill. - --- - # Zip - """.write(to: archiveRoot.appendingPathComponent("SKILL.md"), atomically: true, encoding: .utf8) - try FileManager.default.createDirectory( - at: archiveRoot.appendingPathComponent("references"), withIntermediateDirectories: true) - try "Zip Reference".write( - to: archiveRoot.appendingPathComponent("references/README.md"), atomically: true, - encoding: .utf8) - let outputRoot = try temporaryDirectory() - defer { removeTemporaryDirectory(outputRoot) } - let archive = outputRoot.appendingPathComponent("skill.zip") - try ProcessRunner.run( - "/usr/bin/env", arguments: ["zip", "-qr", archive.path, "."], workingDirectory: archiveRoot) - let archiveData = try Data(contentsOf: archive) + let skill = Data( + """ + --- + name: zip-skill + description: Zip skill. + --- + # Zip + """.utf8) + let reference = Data("Zip Reference".utf8) + let archiveData = zipArchive(entries: [ + ("SKILL.md", skill, 0o100644), + ("references/", Data(), 0o040755), + ("references/README.md", reference, 0o100644), + ]) let digest = "sha256:" + FileHash.sha256Hex(data: archiveData) let responses: [String: Data] = [ @@ -180,8 +174,8 @@ extension WellKnownSourceTests { let skills = try provider.fetchAllSkills(from: "https://example.com") #expect(skills.count == 1) - #expect(skills[0].files["SKILL.md"] != nil) - #expect(skills[0].files["references/README.md"] == Data("Zip Reference".utf8)) + #expect(skills[0].files["SKILL.md"] == skill) + #expect(skills[0].files["references/README.md"] == reference) } @Test func rejectsSymlinkEntriesInWellKnownArchives() throws { diff --git a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift index 01dd744..87fbc57 100644 --- a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift +++ b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift @@ -1,6 +1,6 @@ import AgentsCore import AgentsSkills -import Darwin +import CPlatform import Foundation import Testing @@ -193,7 +193,7 @@ private func lastSkillIndex(_ store: StateStore) throws -> Int { private final class UpdateTestBundle: NSObject {} private func launch(_ fixture: UpdateFixture, command: String, argument: String) throws -> Process { - var directory = Bundle(for: UpdateTestBundle.self).bundleURL.deletingLastPathComponent() + var directory = Bundle(for: UpdateTestBundle.self).bundleURL while !FileManager.default.isExecutableFile( atPath: directory.appendingPathComponent("StateTestProcess").path), directory.path != "/" diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 1bedbe9..29e24fb 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -2,7 +2,7 @@ import AgentsCore import AgentsInstructions import AgentsSkills import AgentsUpdates -import Darwin +import CPlatform import Foundation let arguments = CommandLine.arguments From b971727c12a3cab234047d54ae4b6967cfac9014 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 29 Oct 2026 12:05:27 +0800 Subject: [PATCH 005/171] docs: accept the Agents.swift manifest contract --- Documentation/Proposals/AgentsManifest.md | 415 +++++++++++++++------- Documentation/Proposals/README.md | 2 +- 2 files changed, 281 insertions(+), 136 deletions(-) diff --git a/Documentation/Proposals/AgentsManifest.md b/Documentation/Proposals/AgentsManifest.md index 45497fe..f17cc8d 100644 --- a/Documentation/Proposals/AgentsManifest.md +++ b/Documentation/Proposals/AgentsManifest.md @@ -2,7 +2,7 @@ ## Status -Proposed — language version 1.0. +Accepted — language version 1.0. ## Authors / Owners @@ -28,9 +28,9 @@ import AgentsDescription let agents = Agents( sources: [ - .git( + .source( name: "agents-tools", - url: "github.com/agents-tools/.github", + url: "https://github.com/agents-tools/.github", branch: "master", subpath: ".agent" ), @@ -39,8 +39,8 @@ let agents = Agents( .instructions( sections: [ "guide", - .section("shared/swift-package-route", from: "agents-tools"), - .section("shared/swift-package-tests", from: "agents-tools"), + .section(name: "shared/swift-package-route", source: "agents-tools"), + .section(name: "shared/swift-package-tests", source: "agents-tools"), ], agents: [.claudeCode, .codex] ), @@ -59,7 +59,7 @@ import AgentsDescription let agents = Agents( defaultAgents: [.cursor], - sources: [.local(name: "team", directory: "./team")], + sources: [.source(name: "team", path: "./team")], components: [ .ignore( name: "build-products", patterns: [".build/"], purpose: .indexing, @@ -67,7 +67,7 @@ let agents = Agents( ), ], uses: [ - .exported(name: "review", from: "team", condition: .when(agents: [.codex])), + .group(name: "review", source: "team", condition: .when(agents: [.codex])), ] ) ``` @@ -145,56 +145,74 @@ public struct Condition: Sendable, Equatable { public struct Agents: Sendable, Equatable { public init( - defaultAgents: [Agent]? = nil, sources: [Source] = [], + defaultAgents: [Agent]? = nil, exports: [String] = [], sources: [Source] = [], components: [Component] = [], groups: [ComponentGroup] = [], - uses: [GroupReference] = [], exports: [String] = [], watch: [String] = [] + uses: [GroupReference] = [], watch: [String] = [] ) } +public struct Version: Sendable, Comparable, ExpressibleByStringLiteral { + public init(stringLiteral value: String) + public static func == (lhs: Version, rhs: Version) -> Bool + public static func < (lhs: Version, rhs: Version) -> Bool +} + +extension Range where Bound == Version { + public static func upToNextMajor(from version: Version) -> Range + public static func upToNextMinor(from version: Version) -> Range +} + public struct Source: Sendable, Equatable { - public static func git(name: String, url: String, subpath: String? = nil) -> Source - public static func git(name: String, url: String, from: String, subpath: String? = nil) -> Source - public static func git(name: String, url: String, exact: String, subpath: String? = nil) -> Source - public static func git(name: String, url: String, branch: String, subpath: String? = nil) -> Source - public static func git(name: String, url: String, revision: String, subpath: String? = nil) -> Source - public static func git( - name: String, url: String, upToNextMinorFrom: String, subpath: String? = nil + public static func source( + name: String, url: String, subpath: String? = nil + ) -> Source + public static func source( + name: String, url: String, from: Version, subpath: String? = nil ) -> Source - public static func git( - name: String, url: String, from: String, to: String, subpath: String? = nil + public static func source( + name: String, url: String, exact: Version, subpath: String? = nil ) -> Source - public static func local(name: String, directory: String, subpath: String? = nil) -> Source - public static func local( - name: String, directory: String, from: String, subpath: String? = nil + public static func source( + name: String, url: String, branch: String, subpath: String? = nil ) -> Source - public static func local( - name: String, directory: String, exact: String, subpath: String? = nil + public static func source( + name: String, url: String, revision: String, subpath: String? = nil ) -> Source - public static func local( - name: String, directory: String, branch: String, subpath: String? = nil + public static func source( + name: String, url: String, _ range: Range, subpath: String? = nil ) -> Source - public static func local( - name: String, directory: String, revision: String, subpath: String? = nil + public static func source( + name: String, path: String, subpath: String? = nil ) -> Source - public static func local( - name: String, directory: String, upToNextMinorFrom: String, subpath: String? = nil + public static func source( + name: String, path: String, from: Version, subpath: String? = nil ) -> Source - public static func local( - name: String, directory: String, from: String, to: String, subpath: String? = nil + public static func source( + name: String, path: String, exact: Version, subpath: String? = nil ) -> Source - public static func index(name: String, url: String, subpath: String? = nil) -> Source + public static func source( + name: String, path: String, branch: String, subpath: String? = nil + ) -> Source + public static func source( + name: String, path: String, revision: String, subpath: String? = nil + ) -> Source + public static func source( + name: String, path: String, _ range: Range, subpath: String? = nil + ) -> Source + public static func source(name: String, index: String, subpath: String? = nil) -> Source } public struct ComponentGroup: Sendable, Equatable { - public init( + public static func group( name: String, components: [Component] = [], uses: [GroupReference] = [], condition: Condition? = nil - ) + ) -> ComponentGroup } -public struct GroupReference: Sendable, Equatable { - public static func local(name: String, condition: Condition? = nil) -> GroupReference - public static func exported( - name: String, from source: String, condition: Condition? = nil +public struct GroupReference: Sendable, Equatable, ExpressibleByStringLiteral { + public init(stringLiteral value: String) + public static func group(name: String, condition: Condition? = nil) -> GroupReference + public static func group( + name: String, source: String, condition: Condition? = nil ) -> GroupReference } ``` @@ -203,12 +221,37 @@ There is one `let agents = Agents(...)`, optionally annotated `: Agents`. Other constants contain reusable values. Source names are lexical aliases, not output paths. A **discovery root** is the source root with its optional safe `subpath` applied; component and export discovery start there. Core owns source -identity normalization and requirement resolution. `from:` means up to the next -major version, `upToNextMinorFrom:` up to the next minor, and `from:to:` a -half-open range. `exact:`, `branch:` and `revision:` retain their existing meanings. -Prerelease matching and default latest-tag/default-branch selection remain core's -rules. Only a Git-backed local source accepts a requirement. `.index` represents -the existing well-known index kind and has no Git requirement. +identity normalization and requirement resolution. + +`Version` uses core's semantic-version validation and precedence. A requirement +is a value: `from: x` and `.upToNextMajor(from: x)` denote +`x ..< (major + 1).0.0`; `.upToNextMinor(from: x)` denotes +`x ..< major.(minor + 1).0`. The upper bounds have no prerelease or build metadata, +even when the lower bound has either. The lower bound retains its prerelease and +metadata. All range forms use the resolver's `isInRange(from:to:)`: build metadata +does not affect precedence, and a prerelease tag additionally needs a bound with +a prerelease and the same major/minor/patch triple. Exact requirements retain +core's full normalized-version matching, including build metadata. + +Lowering canonicalizes the `Range` value. An upper bound equal by SemVer +precedence to `(major + 1).0.0` becomes `SourceRequirement.upToNextMajor`; one +equal to `major.(minor + 1).0` becomes `upToNextMinor`; any other upper bound +becomes `SourceRequirement.range(from:to:)`. The two canonical upper bounds +never coincide. Version strings use core's +normalized description; range equality compares bounds by SemVer precedence, +while exact-version equality includes metadata. Invalid versions, non-increasing +ranges and successor overflow are located `manifest.domain` errors. Candidate +successor bounds are computed with checked arithmetic; a literal range does not +fail merely because a nonmatching candidate successor would overflow. + +The canonical printer uses `from:` for a major range, +`.upToNextMinor(from:)` for a minor range and adjacent `"lower"..<"upper"` for +other half-open ranges. `exact:`, `branch:` and `revision:` retain their meanings. +Default latest-tag/default-branch selection remains core's rule. Requirements +apply to Git URL sources and Git-backed local paths only. `.source(name:index:)` +represents the existing well-known index kind and has no Git requirement. +`path:` locates a resource inside a named source or supplies a local source +location; `subpath:` narrows the source's own discovery root. Source aliases follow the existing nonempty, colon-free string rule, with `.` reserved for the declaring package. Escapes preserve otherwise valid string @@ -219,6 +262,17 @@ Skill and instruction names retain their domain validators. ChatGPT prompt names retain the existing arbitrary string-key namespace; they are not filesystem paths. Names must be unique in their respective namespace. +Git URLs are complete transport URLs, as in SwiftPM. A hand-written shorthand is +admitted with `SourceDeclaration` normalization and a `manifest.domain` warning +whose fix-it is the complete URL: `intranet/team` means `https://intranet/team`, +preserving the host; it is not the CLI's owner/repository shorthand. The editor +and migration emit complete URLs using `SourceDeclaration.gitURL`: add `https://` +to host/repository shorthand, preserve existing schemes and preserve complete +SCP-style URLs such as `user@host:path`. Preserving SCP transport syntax also +preserves its remote path interpretation. Identity normalization lowercases the +host, retains an explicit port, trims path slashes and removes a terminal `.git`; +printing preserves the repository suffix. + `exports: ["review"]` exports the group named `review`; export name and group name are identical. A differently named wrapper group provides a renamed export. `watch` is a unique array of declared source aliases, with no recipient or condition. Observed @@ -233,26 +287,26 @@ public struct SkillSelection: Sendable, Equatable, ExpressibleByArrayLiteral { public init(arrayLiteral elements: String...) } public struct SkillOverride: Sendable, Equatable { - public init(name: String, mode: InstallMode? = nil, agents: [Agent]? = nil) + public static func skill(name: String, mode: InstallMode? = nil, agents: [Agent]? = nil) -> SkillOverride } public struct SectionReference: Sendable, Equatable, ExpressibleByStringLiteral { public init(stringLiteral value: String) public static func section( - _ name: String, from source: String? = nil, condition: Condition? = nil + name: String, source: String? = nil, condition: Condition? = nil ) -> SectionReference } public struct ChatGPTPrompt: Sendable, Equatable { - public init( + public static func prompt( name: String, sections: [SectionReference], append: String? = nil, condition: Condition? = nil - ) + ) -> ChatGPTPrompt } public struct Resource: Sendable, Equatable { - public init(path: String, from source: String? = nil) + public static func path(_ path: String, source: String? = nil) -> Resource } public struct PromptContent: Sendable, Equatable, ExpressibleByStringLiteral { public init(stringLiteral value: String) - public static func file(path: String, from source: String? = nil) -> PromptContent + public static func file(_ path: String, source: String? = nil) -> PromptContent } public enum RuntimeValue: Sendable, Equatable, ExpressibleByStringLiteral { case literal(String) @@ -302,7 +356,7 @@ public enum HookEvent: Sendable, Equatable { case native(String) } public struct PromptParameter: Sendable, Equatable { - public init(name: String, description: String, defaultValue: String? = nil) + public static func parameter(name: String, description: String, defaultValue: String? = nil) -> PromptParameter } public enum PermissionOperation: Sendable, Equatable { case read, write, execute @@ -320,21 +374,21 @@ public enum ComponentKind: Sendable, Equatable { case lspServer, permissions, ignore, plugin } public enum ComponentReference: Sendable, Equatable { - case skill(String) - case instruction(String) - case mcpServer(String) - case hook(String) - case subagent(String) - case command(String) - case lspServer(String) - case permissions(String) - case ignore(String) - case plugin(String) + case skill(name: String) + case instruction(name: String) + case mcpServer(name: String) + case hook(name: String) + case subagent(name: String) + case command(name: String) + case lspServer(name: String) + case permissions(name: String) + case ignore(name: String) + case plugin(name: String) } ``` Literal conversions are closed and contextual. `PromptContent`, -`SectionReference` and `RuntimeValue` accept string literals; `SkillSelection` +`SectionReference`, `GroupReference`, `Version` and `RuntimeValue` accept string literals; `SkillSelection` accepts string array literals. `ConfigurationValue` accepts strings, signed 64-bit integer literals, booleans, `nil`, arrays and string-keyed dictionaries. Decimals use `.decimal("1.25")`, with finite JSON-number text; floating-point @@ -346,7 +400,7 @@ values are equal. There is no user-defined literal conformance or conversion from an already-typed `String`, `[String]` or dictionary to a wrapper type. A bare section string names the declaring project's own instruction section; -`.section("engineering", from: "rules")` names a source section. A root user-scope +`.section(name: "engineering", source: "rules")` names a source section. A root user-scope declaration uses named instruction sources. Exported own sections belong to the producer package and may be consumed in either supported scope. Ordered sections, Markdown rendering and **front matter** (the structured metadata preceding a @@ -390,7 +444,7 @@ subject to ordinary preview, ownership and approval checks. ```swift public struct Component: Sendable, Equatable { public static func skills( - from source: String, select: SkillSelection = .all, exclude: [String] = [], + source: String, select: SkillSelection = .all, exclude: [String] = [], mode: InstallMode? = nil, overrides: [SkillOverride] = [], agents: [Agent]? = nil, condition: Condition? = nil, native: NativeConfiguration = [:] @@ -440,7 +494,7 @@ public struct Component: Sendable, Equatable { native: NativeConfiguration = [:] ) -> Component public static func plugin( - name: String, path: String, from source: String, + name: String, path: String, source: String, mode: PluginMode = .components, select: [ComponentKind]? = nil, exclude: [ComponentReference] = [], agents: [Agent]? = nil, condition: Condition? = nil, @@ -530,16 +584,18 @@ conflict. Targeting is deployment intent, not filesystem isolation. ### Groups and source linking A `ComponentGroup` is an inert ordered fragment until selected by a -`GroupReference`. The root emits its components, then `uses` in order. Each group +`GroupReference`; a string literal denotes an unconditional local reference, +equivalent to `.group(name: "review")` for `"review"`. A conditional local +reference uses `.group(name:condition:)`. The root emits its components, then `uses` in order. Each group emits its components, then recursively its `uses`, depth first. This defines section, hook and policy contribution order. A source's root components, root subscriptions and unrelated exports are not imported through a group reference. The producer's defaults are captured as described under targeting. `exports: ["review"]` publishes that local group. A consumer writes -`.exported(name: "review", from: "team")`. To publish an existing group under a -new name, declare a wrapper `ComponentGroup(name: "quality", uses: -[.local(name: "review")])` and export `"quality"`. References do not import Swift +`.group(name: "review", source: "team")`. To publish an existing group under a +new name, declare a wrapper `.group(name: "quality", uses: +["review"])` and export `"quality"`. References do not import Swift symbols. There are no wildcard exports, implicit exports or executable package initializers. Duplicate group/export names and unknown local group names are errors, including in unused declarations. @@ -552,7 +608,7 @@ An index export must identify an immutable package artifact containing a manifes An index publishing only individual skills cannot satisfy a group reference. Aliases bind in the document that declares them. Within an exported component, -`from: "rules"` refers to the producer's alias; `.` refers to its package. +`source: "rules"` refers to the producer's alias; `.` refers to its package. Relative local sources in a downloaded package must remain within that snapshot; absolute, home-relative and escaping producer-local sources are invalid for remote consumption. Root local sources retain core's existing path rules. @@ -625,17 +681,17 @@ conventions. The project condition prevents deployment of this group in user sco import AgentsDescription let agents = Agents( + exports: ["review"], groups: [ - ComponentGroup( + .group( name: "review", components: [ .instructions(sections: ["review-principles"], agents: [.claudeCode, .codex]), - .skills(from: ".", select: ["review"], mode: .copy, agents: [.claudeCode, .codex]), + .skills(source: ".", select: ["review"], mode: .copy, agents: [.claudeCode, .codex]), ], condition: .when(scopes: [.project]) ), - ], - exports: ["review"] + ] ) ``` @@ -651,7 +707,7 @@ IDs and source exports are validated during resolution, not accessed by parsing. import AgentsDescription let base: [SectionReference] = ["guide"] -let sections = base + [.section("engineering", from: "rules")] +let sections = base + [.section(name: "engineering", source: "rules")] let reviewer: Component = .subagent( name: "reviewer", description: "Review correctness and tests.", @@ -663,24 +719,24 @@ let reviewer: Component = .subagent( let agents = Agents( sources: [ - .local(name: "team", directory: "./team"), - .local(name: "drafts", directory: "./draft-skills"), - .git(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), - .index(name: "catalog", url: "https://example.org/skills/index.json"), - .git(name: "vendor", url: "https://example.org/vendor/tools.git", exact: "2.1.0"), + .source(name: "team", path: "./team"), + .source(name: "drafts", path: "./draft-skills"), + .source(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), + .source(name: "catalog", index: "https://example.org/skills/index.json"), + .source(name: "vendor", url: "https://example.org/vendor/tools.git", exact: "2.1.0"), ], components: [ .skills( - from: "rules", exclude: ["experimental"], mode: .copy, - overrides: [SkillOverride(name: "testing", mode: .link, agents: [.codex])] + source: "rules", exclude: ["experimental"], mode: .copy, + overrides: [.skill(name: "testing", mode: .link, agents: [.codex])] ), .skills( - from: "drafts", select: ["draft"], mode: .edit, + source: "drafts", select: ["draft"], mode: .edit, condition: .when(agents: [.claudeCode], scopes: [.project]) ), .instructions( sections: sections, - chatGPT: [ChatGPTPrompt(name: "weekly", sections: base, append: "notes/weekly.md")] + chatGPT: [.prompt(name: "weekly", sections: base, append: "notes/weekly.md")] ), .mcpServer( name: "workspace", @@ -699,13 +755,16 @@ let agents = Agents( ), .hook( name: "format", event: .afterTool, - run: .executable("swift", arguments: ["format", "--in-place", "Sources"]), + run: .executable( + "swift", arguments: ["format", "--in-place", "Sources"], + workingDirectory: .path("tools", source: "rules") + ), timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) ), .command( name: "review/change", description: "Review a selected change.", prompt: "Review ${input:change} and cite evidence.", - parameters: [PromptParameter(name: "change", description: "The change to review.")], + parameters: [.parameter(name: "change", description: "The change to review.")], agents: [.claudeCode] ), .lspServer( @@ -724,21 +783,21 @@ let agents = Agents( agents: [.cursor], condition: .when(scopes: [.project]) ), .plugin( - name: "vendor-tools", path: "plugins/tools", from: "vendor", mode: .native, + name: "vendor-tools", path: "plugins/tools", source: "vendor", mode: .native, agents: [.claudeCode], condition: .when(scopes: [.user]) ), .plugin( - name: "shared-tools", path: "plugins/shared", from: "vendor", - exclude: [.hook("format")], condition: .when(scopes: [.project]) + name: "shared-tools", path: "plugins/shared", source: "vendor", + exclude: [.hook(name: "format")], condition: .when(scopes: [.project]) ), ], groups: [ - ComponentGroup( + .group( name: "review-tools", components: [reviewer], - uses: [.exported(name: "review", from: "team", condition: .when(agents: [.codex]))] + uses: [.group(name: "review", source: "team", condition: .when(agents: [.codex]))] ), ], - uses: [.local(name: "review-tools")], + uses: ["review-tools"], watch: ["rules", "catalog"] ) ``` @@ -773,15 +832,15 @@ Group-name references are resolved separately and may refer forward. | Accepted syntax | Rule | | --- | --- | | `SourceFileSyntax`, `ImportDeclSyntax`, `VariableDeclSyntax` | The file structure above, with one identifier-pattern binding and initializer per declaration. | -| `StringLiteralExprSyntax` | Single-line and multiline literals from the closed lexical grammar below, with Swift decoding and no interpolation. | +| `StringLiteralExprSyntax` | Single-line and multiline literals from the closed lexical grammar below, with Swift decoding and no interpolation. Contextual `GroupReference` literals denote local groups; this is a type conversion, not an extra grammar production. | | Integer, Boolean and nil literals | Decimal signed-64 integers with underscore separators, Bool and contextual nil. One unary minus is accepted only immediately adjacent to a decimal integer literal, with no intervening trivia. Other bases, floating literals and other numeric operators fail admission. | | `ArrayExprSyntax` | Homogeneous arrays or a contextual, whitelisted array-literal conversion. Trailing commas are allowed. Empty literals require contextual type. | | `DictionaryExprSyntax` | String-literal keys, homogeneous contextual values, or a contextual configuration object. `[:]` is an empty dictionary. Keys are decoded before duplicate detection; key references/interpolation are rejected. | | `DeclReferenceExprSyntax` | A preceding constant, a vocabulary type as a member/call base, or the permitted operator. | -| Sequence/folded infix expressions | Only left-associative array `+` with exact `[T]` operands, at most 32 terms per additive chain. No concatenation of selections or configuration values, dictionary merging, string concatenation, range expressions or other operators. | +| Sequence/folded infix expressions | Only left-associative array `+` with exact `[T]` operands, at most 32 terms per additive chain. No concatenation of selections or configuration values, dictionary merging or string concatenation. A single half-open version range is admitted only in the source requirement position defined below; other operators are rejected. | | `TupleExprSyntax` | One unlabeled expression in parentheses, not tuple values. | | `MemberAccessExprSyntax` | Listed static factories, static `.all`, and enum cases, qualified or contextual. No instance-property access, subscripts or optional chaining. | -| `FunctionCallExprSyntax` | Listed ordinary initializers spelled with the bare type name, factories and associated cases, with exact labels and order. Literal-protocol entry points are reached only through literals. No arbitrary functions or trailing closures. | +| `FunctionCallExprSyntax` | `Agents(...)`, listed static factories and associated cases, with exact labels and order. Literal-protocol entry points are reached only through literals. No arbitrary functions or trailing closures. | | Type annotations | `String`, `Int`, `Bool`, named vocabulary types/aliases, `[T]` and `[String: T]`. No explicit Optional annotations, user aliases, qualified/generic/existential/function/metatype syntax. | Grammar admission precedes SwiftParser and the iterative tree check precedes all @@ -814,7 +873,7 @@ configuration null. Signed integer literal conversion follows Swift's literal semantics and must fit the declared literal type. `.decimal(...)` remains explicit. No arbitrary user protocol dispatch or conversion of pre-existing typed values is allowed. In particular, a `String` constant is not implicitly a `PromptContent` -or a `SectionReference`, and a `[String]` constant is not a `SkillSelection`. +or a `SectionReference`, `GroupReference` or `Version`, and a `[String]` constant is not a `SkillSelection`. For array `+`, context propagates to both operands when present; otherwise infer the left array and use its element type for the right array. An expression of @@ -828,7 +887,7 @@ not an alternative type system. | --- | --- | | `manifest.version.missing`, `.invalid`, `.duplicate`, `.unsupported` | Version selection failed. | | `manifest.syntax` | Recognizer: a lexical or production violation, including missing/extra imports, juxtaposed identifiers, unsupported prefixes, raw strings, interpolation and malformed literals. SwiftParser syntax/recovery diagnostics can occur only after recognizer acceptance and the tree guard; such a disagreement is also an implementation regression. | -| `manifest.call`, `manifest.type`, `manifest.operator` | After the tree guard: unlisted call/member, incorrect labels/order/type, missing context, integer overflow or non-array use of the admitted `+` operator. Other operators fail admission. | +| `manifest.call`, `manifest.type`, `manifest.operator` | After the tree guard: unlisted call/member, incorrect labels/order/type, missing context, integer overflow or non-array use of the admitted `+` operator. The `..<` operator is typed as `Range` only in its admitted requirement position. Other operators, including closed ranges (`...`), fail admission with a located `manifest.syntax` diagnostic; `ClosedRange` also has no matching compiler overload. | | `manifest.reference` | Unknown, forward, self, duplicate or shadowing constant name. | | `manifest.domain`, `manifest.dictionary.duplicateKey` | Invalid domain value or duplicate decoded dictionary key. | | `manifest.group.cycle`, `.missing`, `.conflict` | Invalid group/source graph, with the relevant reference chain. | @@ -863,10 +922,19 @@ type = typeName | "[" type "]" | "[" "String" ":" type "]" ; expression = primary ("+" primary)* ; primary = string | integer | "-" integer | "true" | "false" | "nil" | namedValue | array | dictionary | "(" expression ")" ; -namedValue = callee ("(" arguments? ")")? ; +namedValue = sourceCall | callee ("(" arguments? ")")? ; callee = bareName | bareName "." name | "." name ; arguments = argument ("," argument)* ; argument = (name ":")? expression ; +sourceCall = (".source" | "Source.source") "(" "name" ":" expression "," + (("url" | "path") ":" expression + ("," requirement)? | "index" ":" expression) + ("," "subpath" ":" expression)? ")" ; +requirement = ("from" | "exact" | "branch" | "revision") ":" expression + | versionRange | rangeFactory ; +versionRange = string "..<" string ; +rangeFactory = (".upToNextMajor" | ".upToNextMinor") + "(" "from" ":" expression ")" ; array = "[" (expression ("," expression)* ","?)? "]" ; dictionary = "[" ":" "]" | "[" string ":" expression @@ -874,7 +942,15 @@ dictionary = "[" ":" "]" ``` `typeName` is exactly `String`, `Int`, `Bool`, or a public vocabulary type/alias -listed in §2. Type existence is checked during recognition. `callee` is a +listed under Construction vocabulary. Type existence is checked during recognition. `sourceCall` takes +precedence over the general call production for `.source` and `Source.source`; those spellings cannot bypass it through `callee`. The +`.upToNextMajor` and `.upToNextMinor` callees are reserved to `rangeFactory`, +including its required argument list; other positions fail recognition. +`versionRange` is not a general expression: no grouping, constants, chaining or +other operands are admitted at its position. A range factory is contextual to +this same unlabeled requirement slot. Its argument receives `Version` context; +`from:` and `exact:` on the source also receive `Version` context. The subsequent +checker enforces version typing and domain validation. `callee` is a syntactic spelling; subsequent vocabulary checking rejects unlisted functions, instance members, literal-protocol entry points and invalid factory labels. There is no postfix loop: a callee has at most one member operation and one call, @@ -884,9 +960,9 @@ production. No operation attaches to a call result, grouped expression or subscript. The leading shorthand dot counts as one operation. These are exactly the construction forms needed by the vocabulary. Parentheses contain one expression; calls have no trailing comma; collections may have one. -The sole infix production has at most **32 terms**, with later type checking -requiring array operands. No assignment expression or prefix-keyword production -exists. An identifier after a completed expression is a syntax error, not an +The additive production has at most **32 terms**, with later type checking +requiring array operands. A version range has exactly two literal operands. +No assignment expression or prefix-keyword production exists. An identifier after a completed expression is a syntax error, not an implicit prefix, argument or declaration. The lexical grammar is closed: @@ -928,7 +1004,7 @@ The lexical grammar is closed: **20** nested levels. The lexer validates UTF-8 throughout the snapshot. Strings and comments are opaque to expression counters. No other whitespace or comment form is admitted. -- Source punctuation is `( ) [ ] , : . = +` and the adjacent numeric sign `-`, +- Source punctuation is `( ) [ ] , : . = + ..<` and the adjacent numeric sign `-`, only in the roles in the productions. Callee member spellings contain no trivia around their dot; the call opener immediately follows its callee. Both `=` and binary `+` require at least one ASCII whitespace character (space, tab, CR or LF) @@ -938,7 +1014,13 @@ The lexical grammar is closed: `value= 0`, `value=-1`, `a+b` and `a/* note */ + b` fail recognition. A located `manifest.syntax` diagnostic names the canonical spelling, such as `let value = -1` or `left + right`. These adjacency rules make - Swift operator/member tokenization unambiguous. Other operators, generic angle + Swift operator/member tokenization unambiguous. The single `..<` token is + admitted only by `versionRange`, with either no whitespace on both sides or + at least one ASCII whitespace character immediately on both sides. Comments + in either operand gap must themselves be surrounded by whitespace, as for `+`. + The canonical operator spelling is `"1.2.0"..<"1.8.0"`; an asymmetric boundary + reports that spelling in a located `manifest.syntax` diagnostic. A lone `<` + or `>` is never admitted. Other operators, generic angle brackets, braces, attributes, directives, macros and regex literals fail at recognition. There is no fallback to SwiftParser recovery. @@ -967,7 +1049,10 @@ validation, independently of the later semantic IR. Admission reads at most 2,097,153 bytes, rejecting the extra byte before decoding, lexing or parsing; it never allocates an unbounded file buffer. The exact admitted snapshot is subsequently parsed. The recognizer permits at most 100,000 non-trivia -tokens; the minus and integer count separately. It additionally reserves syntax +tokens; the minus and integer count separately, and `..<` counts as one token +plus its two string-literal operands. Range factories count as ordinary calls. +Version values charge their decoded bytes and nodes; range costs include both +endpoints before canonical lowering or serialization. It additionally reserves syntax storage conservatively as **16 + 4 × (tokens + literal breaks + literal escapes)**, capped at 100,000 nodes before SwiftParser is invoked. A literal break is each CR or LF byte inside a string (CRLF counts twice); a literal escape is each @@ -1153,13 +1238,19 @@ Comments follow SwiftSyntax trivia ownership: Container comments survive; ambiguous mixed layouts or comment-only insertion sites are read-only. -New nodes use the shortest canonical type-correct spelling: strings for prompts -and own sections, array literals for explicit skill selections, dictionaries and -JSON-style configuration literals, direct component factories and labeled source -requirements. Existing unmodified expressions keep their spelling. New text uses +New nodes use the shortest canonical type-correct spelling. `Agents(...)` is the +only ordinary initializer in manifest expressions; nested values use leading-dot +factories. Sources use `.source(name:url:)`, `.source(name:path:)` or +`.source(name:index:)`, and references use `source:`. +Requirement values use the canonical printer defined under Construction vocabulary. Literal conformances provide strings +for prompts, own sections, local group references and versions, array literals for explicit skill +selections, and JSON-style configuration literals. Dictionary literals and +direct factories construct the remaining values. Existing unmodified expressions keep their spelling. New text uses the container's consistent indentation, newline and comma style; absent evidence, use two spaces, LF and trailing commas in multiline collections. Argument order -follows signatures. Fresh node layout follows the deterministic migration printer; +follows signatures; root insertion order is `defaultAgents`, `exports`, `sources`, +`components`, `groups`, `uses`, `watch`. `upsertSource(Source)` preserves the +complete requirement value. Fresh node layout follows the deterministic migration printer; existing surrounding style takes precedence. Conflicting local style is an editability diagnostic, not permission to reformat the file. @@ -1182,6 +1273,14 @@ groups and exports; only source positions and trivia are excluded. Prepare then re-links affected sources and revalidates capabilities/targets. All stages use the expanded-size budgets. BOM, final-newline presence and unrelated bytes survive. +Range replacement re-checks both operator/operand boundaries and the containing +source requirement slot. A complete replacement uses the canonical requirement +printer, including changing the argument label when its range category changes. A leaf endpoint edit preserves surrounding trivia only if the +result still meets balanced spacing and comment rules; otherwise include the +necessary whitespace in the explicit patch or report `manifest.edit.readOnly` +when comment ownership is ambiguous. Re-run admission, typing and expected-IR +comparison before publishing any edit. + ### Evaluated JSON dump `agents manifest dump --json` reads and evaluates only the local declaration. @@ -1194,8 +1293,8 @@ no partial success object. The root has `schemaVersion: 1`, `kind: "manifest"`, `languageVersion: "1.0"`, `sourceDigest`, `declaration`, `locations` and `diagnostics`. The digest is `sha256:` plus 64 lowercase hexadecimal digits over the original bytes. -`declaration` has `defaultAgents`, `sources`, `components`, `groups`, `uses`, -`exports` and `watch`. Default arrays are empty, Optional absence is null, and +`declaration` has `defaultAgents`, `exports`, `sources`, `components`, `groups`, +`uses` and `watch`. Default arrays are empty, Optional absence is null, and explicit empty recipients remain distinct from inheritance. A component encodes directly as `{ "kind": "mcpServer", "name": "workspace", @@ -1203,20 +1302,28 @@ A component encodes directly as `{ "kind": "mcpServer", "name": "workspace", "native": {} }`. There is no payload wrapper. The remaining schema is determined by the vocabulary as follows: -- Opaque factory values encode `{kind, ...fields}`. Component/transport kinds are +- Tagged families encode `{kind, ...fields}`. Component/transport kinds are their factory names. `ExecutableInvocation` is `kind: "executable"` with executable, - arguments, environment and workingDirectory. Group references are `local` or - `exported`, with name, optional source and condition. Conditions encode their + arguments, environment and workingDirectory. `.group(name:)` references encode + kind `local`; `.group(name:source:)` references encode kind `exported`, with + name and condition. An exported reference always has a non-null source; a local + reference has none (encoded as null). Conditions encode their three dimensions without a kind. Permission rules encode `{kind: "allow" | "ask" | "deny", operation, pattern}`; their two unlabeled factory arguments use the keys `operation` and `pattern`. LSP `languages` encodes an object mapping extension keys to language-ID strings. -- A source has `kind: "git" | "local" | "index"`, name, location (`url` or - `directory`), subpath and requirement. Requirement is null or an object with - exactly one of branch/revision/exact/from/upToNextMinorFrom, or from plus to. - Overload spelling does not change the source kind. -- Named structs encode their initializer fields. `from source:` uses JSON key - `source`. Arrays/dictionaries encode as JSON collections, with defaults supplied. +- A source has `kind: "git" | "local" | "index"`, name, location (`url`, `path` or + `index`, matching its factory field), subpath and requirement. A `path:` source + with a requirement remains kind `local`. Requirement is null or an + object with exactly one of `branch`, `revision`, `exact`, `from`, `upToNextMinor`, + or `from` plus `to`, matching core's `SourceRequirement` encoding. Version values encode + as normalized version strings. Every range value encodes its canonical + requirement kind: `from`, + `upToNextMinor`, or `from`/`to`, regardless of its construction spelling. +- Groups, skill overrides, ChatGPT prompts, prompt parameters and resources encode + their factory fields without a factory-name tag; the resource's unlabeled + subject uses key `path`. Arrays/dictionaries encode as JSON collections, + with defaults supplied. Exports and watch are string arrays. An instruction section is always an object with name, source and condition, even when authored as a string. - Skill selection encodes `"all"` or an array of names. Prompt content is @@ -1225,7 +1332,7 @@ by the vocabulary as follows: spelling and explicit equivalent cases have identical evaluated output. - Payload-free enum cases are strings, except mixed enums always use tagged objects. Associated values retain labels; a single unlabeled payload uses - `value`. Typed component references use kind and value. Configuration values + `value`. Typed component references use kind and name. Configuration values retain kind and value tags, including nested arrays/objects; null has only kind, and decimal values remain strings to prevent numeric rounding. - Agent IDs are `claude-code`, `codex`, `cursor`, `gemini-cli`, `opencode`; @@ -1235,7 +1342,7 @@ Components, group references, sections, hooks, permission rules, ignore patterns arguments and prompt parameters preserve order. Definitions of sources/groups, exports, watch, named prompts and overrides sort by name; recipients, exclusions and explicit skill selections sort by canonical identity. Dictionary keys sort -by decoded UTF-8 bytes. Typed plugin exclusions sort by kind then value. +by decoded UTF-8 bytes. Typed plugin exclusions sort by kind then name. Constants are substituted by value within the checked expansion budget. A location has `pointer` (JSON Pointer into the normalized declaration), `span`, @@ -1381,22 +1488,22 @@ intent without fetching, re-resolving pins or inferring installed recipients. | JSON | Swift construction | | --- | --- | | `agents` | `Agents(defaultAgents: [...])`; omitted remains inheritance, explicit empty remains empty. | -| `sources..git` | `.git(name: , url: , ...)`. | -| `sources..local` | `.local(name: , directory: , ...)`. | -| `sources..well-known` | `.index(name: , url: , ...)`. | +| `sources..git` | `.source(name: , url: , ...)`. | +| `sources..local` | `.source(name: , path: , ...)`. | +| `sources..well-known` | `.source(name: , index: , ...)`. | | `sources..path` | `subpath:` unchanged. | | `branch`, `revision`, `exact` | Corresponding source factory label. | -| `from` | `from:`; with `to`, the `from:to:` overload. | -| `upToNextMinor` | `upToNextMinorFrom:`. | -| `skills.` | `.skills(from: , ...)` in components. | +| `from`, `to` | Decode the lower bound and optional upper bound, canonicalize the range value, then print `from:`, the minor-range factory or the unlabeled literal range as appropriate. | +| `upToNextMinor` | The unlabeled `.upToNextMinor(from: "version")` requirement. | +| `skills.` | `.skills(source: , ...)` in components. | | `select: "all"` | Omit `select`; explicit names become a string array literal, including `[]`. | | `exclude` | String array, omitted when empty. | | Skill `agents`, `mode` | Corresponding fields; omission preserves inheritance. | -| `overrides.` | `SkillOverride(name: ..., mode: ..., agents: ...)`, subject to the explicit inert-override rule below. | +| `overrides.` | `.skill(name: ..., mode: ..., agents: ...)`, subject to the explicit inert-override rule below. | | `instructions` | One `.instructions(...)` after skill selections; missing object means no contribution. | | `instructions.agents` | `agents:` on that component, preserving explicit recipient intent. | -| `instructions.sections[]` | Bare name becomes a string literal; `alias:name` becomes `.section("name", from: "alias")`. Preserve order and repetitions. | -| `instructions.chatgpt.` | `ChatGPTPrompt(name: ..., sections: ..., append: ...)` in `chatGPT`. Names and per-prompt section order remain exact. | +| `instructions.sections[]` | Bare name becomes a string literal; `alias:name` becomes `.section(name: "name", source: "alias")`. Preserve order and repetitions. | +| `instructions.chatgpt.` | `.prompt(name: ..., sections: ..., append: ...)` in `chatGPT`. Names and per-prompt section order remain exact. | | Prompt `append` | Unchanged string, with existing project-root/user-home interpretation. | | `watch[]` | Source alias strings in `watch`, with no condition. | | Missing sources/skills/prompts/watch | Empty collections, with default-valued arguments omitted. | @@ -1440,6 +1547,13 @@ settings or additional approvals are synthesized. ### Deterministic source and migration transaction +Git locations use the legacy `SourceDeclaration` identity normalization described +under Construction vocabulary, including single-label hosts and SCP-style SSH +locations. Local paths remain paths. Migration and the JSON-to-IR compatibility +path canonicalize requirement values identically to Swift lowering. A legacy +`from`/`to` pair may therefore print as `from:` or a minor-range factory. This +preserves the selected tag set and every exact ledger pin. + The same validated JSON, language version and compatibility transformations produce identical source bytes and diagnostic records. Emit the version line, import, one blank line, then `let agents = Agents(...)`; two-space indentation, @@ -1471,6 +1585,29 @@ migration. Normal commands report required migration rather than converting implicitly. A failed migration retains a recoverable original declaration and never treats a concurrent file as generated output. +### Requirement persistence and comparison + +Canonicalization applies to new IR and new serialized requirement fields. +Semantic comparison of existing range requirements expands them to bounds; +raw enum-case equality or raw requirement JSON equality is insufficient. Branch +and revision compare their strings; exact versions compare normalized full +versions; absence retains its distinct latest-tag/default-branch policy. + +| Site | Contract | +| --- | --- | +| Declaration IR, JSON compatibility projection and dump | Canonical requirement kinds and normalized version strings; comparisons use range-value equality. A factory, literal range and legacy JSON denoting equal bounds compare equal. | +| Document edits and `upsertSource` | Compare semantic values; an equal edit returns original source bytes. New or changed nodes print canonically; untouched spelling is retained. | +| `LockedSource.requirement` in the deployment ledger and requirements in `groupResolutions` | Newly written records use canonical requirements. Reading existing records preserves their bytes and builds a semantic comparison view. A requirement-spelling difference alone never changes pins, reports an update or stages a write. | +| Lock version 1 to version 2 conversion | Canonicalize requirements while preserving exact source/item pins and ownership. An existing version-2 ledger is not upgraded merely to canonicalize requirements. | +| Skill/instruction lock producers, combined update-plan conflict and change detection | Compare source identity, discovery root and semantic requirement values; merge equal ranges without a conflict. If the complete resulting ledger is semantically unchanged, keep its original bytes even when another state file changes. A necessary ledger rewrite emits canonical requirements. | +| Resolution-session reuse and cache descriptors | Key requirement comparisons by semantic value, not case spelling. Cache identity/materialization keys continue to use source identity and exact revision/artifact digest; restore uses the stored pins without requirement re-resolution. | +| `agents.watch` | Stores source identities and `seen` revision/artifact digests, no requirement kind. Migration retains its bytes. Re-evaluating an equivalent declaration preserves the subscription and baseline; watch-created lock descriptors follow the ledger rule. | + +These rules extend the existing requirement comparisons in source argument +selection, source resolution sessions and combined update planning. They do not +rewrite historical records on read. State transactions compare semantic state +before choosing any serialization and retain the original ledger bytes on a no-op. + ### Lock version 2 and ownership conversion Version 2 retains exact item-specific source identities, revisions, versions, @@ -1511,8 +1648,12 @@ preservation result as before conversion. ## Validation Contract -Positive fixtures compile against `AgentsDescription` and their compiled values -match static evaluation. Compiler-required literal conformances and evaluator +Every Swift code block, including interface and editor-API blocks, must pass +`swiftc -parse`; signature-only interface blocks use `swiftc -frontend -parse` +with `.swiftinterface` inputs so getter declarations are parsed in interface mode. +Positive fixtures compile against `AgentsDescription` and their +compiled values match static evaluation under plain value equality, including +equal range forms and string-literal group references. Compiler-required literal conformances and evaluator registrations are checked against the same signature inventory. Negative fixtures cover unsupported syntax, contextual typing, duplicate dictionary keys, budgets and spans. No accepted static value may fail real Swift type checking. @@ -1579,7 +1720,11 @@ Tests also cover condition narrowing, default capture on export, namespaces, cycles/diamonds, conflicting requirements, shared-target exposure, byte-preserving edits, comment ownership, deterministic dumps, compatibility transformations and lock restoration/removal equivalence. Resource tests include exponential constant -reuse in unused declarations, dumping, source maps and comparison. Fuzzing runs +reuse in unused declarations, dumping, source maps and comparison. +Range differential cases cover balanced/unbalanced spacing, comment adjacency, +misplacement, chained and closed ranges, nonliteral endpoints and replacement +boundaries; admitted cases must match SwiftParser's structure, and semantically +accepted cases must type-check against the types module. Fuzzing runs with fixed budgets on macOS and Linux. Native capability claims require current client probes. Fault tests interrupt every publication/recovery stage, including concurrent creation of an absent destination and external replacement of both diff --git a/Documentation/Proposals/README.md b/Documentation/Proposals/README.md index d1ab527..d59f26d 100644 --- a/Documentation/Proposals/README.md +++ b/Documentation/Proposals/README.md @@ -5,7 +5,7 @@ This directory holds design-in-progress documents and unresolved alternatives. ## Active Proposals - [Agents Manifest Contract](AgentsManifest.md) — owner: showxu; review status: - Proposed. Static Swift vocabulary, compiler stages, source editing, composition, + Accepted. Static Swift vocabulary, compiler stages, source editing, composition, migration and evaluated JSON contract. - `AgentInstructions.md`: skills and instructions as two kinds of one model, From 080f508978b319952d63144c1db1a930e7102647 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:56:41 +0800 Subject: [PATCH 006/171] docs: gate manifest parse time on the release configuration --- Documentation/Proposals/AgentsManifest.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Documentation/Proposals/AgentsManifest.md b/Documentation/Proposals/AgentsManifest.md index f17cc8d..fc3e3c2 100644 --- a/Documentation/Proposals/AgentsManifest.md +++ b/Documentation/Proposals/AgentsManifest.md @@ -1706,10 +1706,15 @@ tree-budget failure or structural/literal disagreement is a test failure. Retain and minimize counterexamples. Scheduled fuzzing extends the same bounded corpus. Each input must finish admission, parsing, iterative checking, syntax-error -inspection and tree teardown, when reached, within **2 seconds wall-clock** on -each required CI runner, separately from compiler build time. The parent watchdog -covers the entire child lifetime; a timeout or signal fails the test, never counts -as a successful rejection. Record runner/toolchain identity, seeds, stage, token +inspection and tree teardown, when reached, within **2 seconds wall-clock** in +the release test configuration on each required CI runner, separately from +compiler build time. The release configuration is the shipped front end, so it is +the performance gate. CI runs both the debug and release test configurations on +macOS and Linux. The debug configuration runs the same inputs with a 30-second +watchdog that detects hangs; unoptimized dependencies make its timings a hang +check, not the performance gate. The parent watchdog covers the entire child +lifetime; a timeout or signal fails the test, never counts as a successful +rejection. Record runner/toolchain identity, seeds, stage, token and tree counts and timings. These are regression gates, not permission to relax language limits on slower machines. Every SwiftParser dependency or host-toolchain update reruns the fixed and fuzz suites at the candidate version and compares From c48bc40f269df0a93b83460f4d9581f125a27b33 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:56:42 +0800 Subject: [PATCH 007/171] ci: test the debug and release configurations --- .github/swift-package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/swift-package.json b/.github/swift-package.json index ff57b9b..9c4a8bc 100644 --- a/.github/swift-package.json +++ b/.github/swift-package.json @@ -1,4 +1,5 @@ { + "test_configurations": ["debug", "release"], "compilers": [ {"name": "macos-26-xcode-26.6", "runner": "macos-26", "xcode": "26.6"} ], From 911213507524a4580249aca01a1d1deec29ac202 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:56:42 +0800 Subject: [PATCH 008/171] feat: add the Agents.swift manifest front end --- Documentation/Architecture/Package.md | 49 +- Documentation/Architecture/README.md | 4 +- Documentation/Architecture/State.md | 20 + Package.resolved | 11 +- Package.swift | 23 + Scripts/ManifestVocabulary.json | 1684 +++++++++++++++++ Scripts/generate-manifest-fixtures.py | 20 + Scripts/generate-manifest-vocabulary.py | 103 + Sources/AgentsCore/Declaration.swift | 10 + Sources/AgentsCore/DeclarationIR.swift | 78 + Sources/AgentsCore/SourceProvenance.swift | 72 + Sources/AgentsCore/SourceRequirement.swift | 33 + .../AgentsDescription/ConstructionValue.swift | 104 + Sources/AgentsDescription/Version.swift | 103 + Sources/AgentsDescription/Vocabulary.swift | 861 +++++++++ .../VocabularyInventory.swift | 802 ++++++++ Sources/AgentsManifest/Admission.swift | 729 +++++++ Sources/AgentsManifest/CanonicalPrinter.swift | 181 ++ .../AgentsManifest/DeclarationDocument.swift | 383 ++++ Sources/AgentsManifest/DocumentEditor.swift | 1062 +++++++++++ Sources/AgentsManifest/DocumentModels.swift | 206 ++ Sources/AgentsManifest/DomainValidation.swift | 440 +++++ Sources/AgentsManifest/Evaluation.swift | 387 ++++ Sources/AgentsManifest/Lowering.swift | 67 + .../AgentsManifest/ManifestDiagnostic.swift | 109 ++ Sources/AgentsManifest/PieceTable.swift | 78 + Sources/AgentsManifest/SyntaxValidation.swift | 147 ++ Sources/AgentsManifest/ValueBudget.swift | 88 + .../AdversarialTests.swift | 311 +++ .../CompiledFixtures.swift | 819 ++++++++ .../DifferentialFuzzTests.swift | 151 ++ Tests/AgentsManifestTests/EditingTests.swift | 279 +++ .../Fixtures/ConsumerExample.swift.txt | 97 + .../Fixtures/Contract00.swift.txt | 23 + .../Fixtures/Contract01.swift.txt | 16 + .../Fixtures/Contract05.swift.txt | 11 + .../Fixtures/Contract06.swift.txt | 16 + .../Fixtures/Contract07.swift.txt | 97 + .../Fixtures/CoreExample.swift.txt | 23 + .../Fixtures/LiteralCoverage.swift.txt | 43 + .../Fixtures/MigrationEdgeExample.swift.txt | 51 + .../Fixtures/ParserBaseline.json | 102 + .../Fixtures/ProducerExample.swift.txt | 16 + .../Fixtures/RequirementValues.swift.txt | 24 + .../Fixtures/RequirementsExample.swift.txt | 46 + .../Fixtures/SketchExample.swift.txt | 16 + .../Fixtures/SkillsExample.swift.txt | 11 + .../Fixtures/TasteSample.swift.txt | 81 + .../Fixtures/VocabularyDepthExample.swift.txt | 22 + Tests/AgentsManifestTests/FrontEndTests.swift | 153 ++ .../AgentsManifestTests/InventoryTests.swift | 126 ++ .../ResourceAndVersionTests.swift | 160 ++ .../ReviewRegressionTests.swift | 144 ++ .../VersionCompatibilityTests.swift | 46 + Tests/AgentsManifestTests/Watchdog.swift | 154 ++ Tests/ManifestTestProcess/main.swift | 165 ++ 56 files changed, 11052 insertions(+), 5 deletions(-) create mode 100644 Scripts/ManifestVocabulary.json create mode 100644 Scripts/generate-manifest-fixtures.py create mode 100644 Scripts/generate-manifest-vocabulary.py create mode 100644 Sources/AgentsCore/DeclarationIR.swift create mode 100644 Sources/AgentsCore/SourceProvenance.swift create mode 100644 Sources/AgentsDescription/ConstructionValue.swift create mode 100644 Sources/AgentsDescription/Version.swift create mode 100644 Sources/AgentsDescription/Vocabulary.swift create mode 100644 Sources/AgentsDescription/VocabularyInventory.swift create mode 100644 Sources/AgentsManifest/Admission.swift create mode 100644 Sources/AgentsManifest/CanonicalPrinter.swift create mode 100644 Sources/AgentsManifest/DeclarationDocument.swift create mode 100644 Sources/AgentsManifest/DocumentEditor.swift create mode 100644 Sources/AgentsManifest/DocumentModels.swift create mode 100644 Sources/AgentsManifest/DomainValidation.swift create mode 100644 Sources/AgentsManifest/Evaluation.swift create mode 100644 Sources/AgentsManifest/Lowering.swift create mode 100644 Sources/AgentsManifest/ManifestDiagnostic.swift create mode 100644 Sources/AgentsManifest/PieceTable.swift create mode 100644 Sources/AgentsManifest/SyntaxValidation.swift create mode 100644 Sources/AgentsManifest/ValueBudget.swift create mode 100644 Tests/AgentsManifestTests/AdversarialTests.swift create mode 100644 Tests/AgentsManifestTests/CompiledFixtures.swift create mode 100644 Tests/AgentsManifestTests/DifferentialFuzzTests.swift create mode 100644 Tests/AgentsManifestTests/EditingTests.swift create mode 100644 Tests/AgentsManifestTests/Fixtures/ConsumerExample.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/Contract00.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/Contract01.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/Contract05.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/Contract06.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/Contract07.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/CoreExample.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/LiteralCoverage.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationEdgeExample.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/ParserBaseline.json create mode 100644 Tests/AgentsManifestTests/Fixtures/ProducerExample.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/RequirementValues.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/RequirementsExample.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/SketchExample.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/SkillsExample.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/TasteSample.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/VocabularyDepthExample.swift.txt create mode 100644 Tests/AgentsManifestTests/FrontEndTests.swift create mode 100644 Tests/AgentsManifestTests/InventoryTests.swift create mode 100644 Tests/AgentsManifestTests/ResourceAndVersionTests.swift create mode 100644 Tests/AgentsManifestTests/ReviewRegressionTests.swift create mode 100644 Tests/AgentsManifestTests/VersionCompatibilityTests.swift create mode 100644 Tests/AgentsManifestTests/Watchdog.swift create mode 100644 Tests/ManifestTestProcess/main.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 6c3637d..62a1dcb 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -12,6 +12,9 @@ with glibc 2.34 or newer. ## Products and Dependencies ```text +AgentsDescription (standard library only) +AgentsManifest ──> AgentsDescription, AgentsCore, SwiftSyntax, SwiftParser (swift-syntax) + AgentsUpdates ──> AgentsCore, AgentsSkills, AgentsInstructions, CPlatform AgentsCore ──> Crypto (swift-crypto), CPlatform @@ -24,6 +27,9 @@ AgentsInstructions ──> AgentsCore │ └───────> Markdown (swift-markdown) ──> cmark-gfm +ManifestTestProcess ──> AgentsManifest, AgentsCore, AgentsDescription +AgentsManifestTests ──> AgentsManifest, AgentsDescription, AgentsCore, ManifestTestProcess, SwiftParser, SwiftSyntax + StateTestProcess ──> AgentsCore, AgentsSkills, AgentsInstructions, AgentsUpdates, CPlatform AgentsCoreTests ──> AgentsCore, StateTestProcess, CPlatform AgentsSkillsTests ──> AgentsSkills, AgentsCore, AgentsInstructions, Yams, StateTestProcess, CPlatform @@ -31,8 +37,10 @@ AgentsInstructionsTests ──> AgentsInstructions AgentsUpdatesTests ──> AgentsUpdates, StateTestProcess, CPlatform ``` -`AgentsCore`, `AgentsSkills`, `AgentsInstructions` and `AgentsUpdates` are library products with -matching targets under `Sources/` and test targets under `Tests/`. Shared +`AgentsDescription`, `AgentsManifest`, `AgentsCore`, `AgentsSkills`, +`AgentsInstructions` and `AgentsUpdates` are library products with +matching targets under `Sources/`. Tests under `Tests/` include construction +vocabulary and compiler-oracle coverage in `AgentsManifestTests`. Shared implementation uses `package` access; consumers receive the workflow APIs and the state and result models they need. `Package.swift` owns this dependency graph. @@ -52,6 +60,38 @@ bridges APIs missing from those overlays. `AgentsCore` hashes through swift-crypto's `Crypto` product, which delegates to CryptoKit on Apple platforms and supplies its own implementation on Linux. +## AgentsDescription and AgentsManifest + +`AgentsDescription` owns the immutable language 1.0 authoring vocabulary. It uses +only the standard library, with private payload storage and closed literal +conformances. `Scripts/ManifestVocabulary.json` is the construction signature and +literal inventory; `Scripts/generate-manifest-vocabulary.py` generates the public +factories and package-only static registrations together. Contract signature and +compiler-backed fixture tests check that inventory. + +`AgentsManifest.DeclarationDocument` compiles supplied UTF-8 bytes without +executing code or reading sources. Version selection, strict lexing and bounded +grammar recognition complete before SwiftParser sees the exact snapshot. An +iterative all-nodes guard precedes syntax inspection and independent projection +comparison. Static typing, occurrence-based expanded-size accounting and offline +domain validation produce `AgentsCore.DeclarationIR` and `DeclarationSourceMap`. +Constants, inactive values and unused groups receive the same checks. Group +references and conditions remain symbolic. + +The document retains original bytes, a lossless syntax tree, a byte digest and +snapshot-bound `NodeID` handles. `preparing(_:)` accepts `ManifestEdit` batches, +constructs expected intent, produces disjoint byte patches, reruns the complete +front end and compares the resulting declaration. `DocumentChange` carries both +byte digests, resulting bytes, diagnostics, impacted references and semantic delta +for later orchestration. Source edits do not publish files. Shared constants +require explicit impact acceptance; ambiguous comments or separators are refused. + +`ManifestTestProcess` is a test-only executable. Parent watchdogs exercise +admission, parsing, checking and tree teardown, including fixed adversarial forms +and deterministic differential fuzzing. Positive corpus sources are also compiled +as ordinary Swift in the test target and compared using value equality. Parser +baselines and seeds belong to the test corpus, not the runtime language. + ## AgentsCore - `SourceParser` and `ParsedSource` parse local paths, Git URLs and HTTP indexes. @@ -69,7 +109,10 @@ CryptoKit on Apple platforms and supplies its own implementation on Linux. - `SourceRequirement` expresses branch, revision, exact version, next-major, next-minor and half-open version ranges. Semantic-version comparison governs Git tag selection, including prerelease bounds. -- `Declaration` and `ResolvedState` define intent and resolved version 1 state, +- `DeclarationIR`, `DeclarationRecord` and `DeclarationValue` hold syntax-independent + manifest intent; `SourceSpan`, `SourceProvenance` and `DeclarationSourceMap` + carry document coordinates and origins without syntax or source access. +- `Declaration` and `ResolvedState` define the current stored intent and resolved version 1 state, including the complete instruction section, prompt and physical-target models. - `StateStore` owns scope paths, validation, deterministic encoding and state persistence. `FileLock` serializes state access; `FileTransaction` durably diff --git a/Documentation/Architecture/README.md b/Documentation/Architecture/README.md index b953f61..8405abb 100644 --- a/Documentation/Architecture/README.md +++ b/Documentation/Architecture/README.md @@ -1,7 +1,9 @@ # Architecture This directory holds the current truth for `core`, a SwiftPM library package. -`AgentsCore` owns shared sources, declaration and lock storage, cache, watch subscriptions, and agent locations; +`AgentsDescription` supplies the types-only construction vocabulary, and +`AgentsManifest` compiles and edits supplied manifest snapshots without I/O. +`AgentsCore` owns syntax-independent declaration IR, spans, provenance, shared sources, declaration and lock storage, cache, watch subscriptions, and agent locations; `AgentsSkills` owns skill discovery and lifecycle operations and depends on `AgentsCore` and Yams. `AgentsInstructions` owns instruction lifecycle and text transformations. It depends on `AgentsCore` for sources and state, and on diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index c8ed937..bfb76af 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -1,5 +1,25 @@ # State and Source Cache +## Manifest Front End + +`AgentsManifest.DeclarationDocument` accepts a supplied `Agents.swift` snapshot +and produces `AgentsCore.DeclarationIR`, diagnostics and `DeclarationSourceMap`. +The IR distinguishes inherited Optional values from explicit empty recipients, +retains ordered section streams, and keeps conditions and group references +symbolic. Span and provenance values contain stable document/source coordinates; +cache paths and deployment targets are not declaration identity. + +A prepared `DocumentChange` contains its original byte digest, disjoint source +patches, candidate bytes/digest, expected complete declaration, impacted references +and semantic delta. It is an input to state orchestration, not a second state +store or a file-saving API. Parsing and edit preparation perform no deployment, +source discovery, secret lookup or filesystem validation. + +The storage and lifecycle APIs below continue to own `agents.json` and the current +lock format. They do not yet load or publish `DocumentChange`. Manifest selection, +migration detection, transactional source publication and recovery belong to the +state integration; an accepted document alone does not authorize publication. + ## Scope Locations | Scope | Declaration | Lock | Watch state | Cache | diff --git a/Package.resolved b/Package.resolved index bacc9b7..c2cdde8 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "0e9fe4bea4fa453e8427d13cf8ceba58d78c327328841cb8c7c2e4550b3c96ed", + "originHash" : "2c053518874423b9cbd21ad05cd15590e43cf4686b80c1421255af9007ac3963", "pins" : [ { "identity" : "swift-asn1", @@ -37,6 +37,15 @@ "version" : "0.9.0" } }, + { + "identity" : "swift-syntax", + "kind" : "remoteSourceControl", + "location" : "https://github.com/swiftlang/swift-syntax.git", + "state" : { + "revision" : "050f1a346fbbac0ca2cfb15a95274f7bd1cf0ccf", + "version" : "604.0.0" + } + }, { "identity" : "yams", "kind" : "remoteSourceControl", diff --git a/Package.swift b/Package.swift index 286eb81..10a99e3 100644 --- a/Package.swift +++ b/Package.swift @@ -9,6 +9,8 @@ let package = Package( .macOS(.v15) ], products: [ + .library(name: "AgentsDescription", targets: ["AgentsDescription"]), + .library(name: "AgentsManifest", targets: ["AgentsManifest"]), .library(name: "AgentsCore", targets: ["AgentsCore"]), .library(name: "AgentsSkills", targets: ["AgentsSkills"]), .library(name: "AgentsInstructions", targets: ["AgentsInstructions"]), @@ -18,9 +20,18 @@ let package = Package( .package(url: "https://github.com/apple/swift-crypto.git", from: "5.0.0"), .package(url: "https://github.com/jpsim/Yams", from: "6.0.0"), .package(url: "https://github.com/swiftlang/swift-markdown.git", from: "0.9.0"), + .package(url: "https://github.com/swiftlang/swift-syntax.git", exact: "604.0.0"), ], targets: [ .target(name: "CPlatform"), + .target(name: "AgentsDescription"), + .target( + name: "AgentsManifest", + dependencies: [ + "AgentsDescription", "AgentsCore", + .product(name: "SwiftSyntax", package: "swift-syntax"), + .product(name: "SwiftParser", package: "swift-syntax"), + ]), .target( name: "AgentsCore", dependencies: ["CPlatform", .product(name: "Crypto", package: "swift-crypto")] @@ -42,6 +53,18 @@ let package = Package( .testTarget( name: "AgentsCoreTests", dependencies: ["AgentsCore", "StateTestProcess", "CPlatform"]), .testTarget(name: "AgentsInstructionsTests", dependencies: ["AgentsInstructions"]), + .executableTarget( + name: "ManifestTestProcess", + dependencies: ["AgentsManifest", "AgentsCore", "AgentsDescription"], + path: "Tests/ManifestTestProcess"), + .testTarget( + name: "AgentsManifestTests", + dependencies: [ + "AgentsManifest", "AgentsDescription", "AgentsCore", "ManifestTestProcess", + .product(name: "SwiftParser", package: "swift-syntax"), + .product(name: "SwiftSyntax", package: "swift-syntax"), + ], + resources: [.copy("Fixtures")]), .testTarget( name: "AgentsUpdatesTests", dependencies: ["AgentsUpdates", "StateTestProcess", "CPlatform"]), .testTarget( diff --git a/Scripts/ManifestVocabulary.json b/Scripts/ManifestVocabulary.json new file mode 100644 index 0000000..280fd07 --- /dev/null +++ b/Scripts/ManifestVocabulary.json @@ -0,0 +1,1684 @@ +{ + "enums": { + "Agent": [ + { + "name": "claudeCode", + "parameters": [] + }, + { + "name": "codex", + "parameters": [] + }, + { + "name": "cursor", + "parameters": [] + }, + { + "name": "geminiCLI", + "parameters": [] + }, + { + "name": "openCode", + "parameters": [] + } + ], + "Scope": [ + { + "name": "project", + "parameters": [] + }, + { + "name": "user", + "parameters": [] + } + ], + "Platform": [ + { + "name": "macOS", + "parameters": [] + }, + { + "name": "linux", + "parameters": [] + } + ], + "InstallMode": [ + { + "name": "link", + "parameters": [] + }, + { + "name": "copy", + "parameters": [] + }, + { + "name": "edit", + "parameters": [] + } + ], + "RuntimeValue": [ + { + "name": "literal", + "parameters": [ + { + "label": "_", + "name": "value", + "type": "String" + } + ] + }, + { + "name": "environment", + "parameters": [ + { + "label": "_", + "name": "value", + "type": "String" + } + ] + }, + { + "name": "secret", + "parameters": [ + { + "label": "_", + "name": "value", + "type": "String" + } + ] + } + ], + "ConfigurationValue": [ + { + "name": "string", + "parameters": [ + { + "label": "_", + "name": "value", + "type": "String" + } + ] + }, + { + "name": "integer", + "parameters": [ + { + "label": "_", + "name": "value", + "type": "Int" + } + ] + }, + { + "name": "decimal", + "parameters": [ + { + "label": "_", + "name": "value", + "type": "String" + } + ] + }, + { + "name": "boolean", + "parameters": [ + { + "label": "_", + "name": "value", + "type": "Bool" + } + ] + }, + { + "name": "null", + "parameters": [] + }, + { + "name": "array", + "parameters": [ + { + "label": "_", + "name": "value", + "type": "[ConfigurationValue]" + } + ] + }, + { + "name": "object", + "parameters": [ + { + "label": "_", + "name": "value", + "type": "[String: ConfigurationValue]" + } + ] + } + ], + "HookEvent": [ + { + "name": "beforeTool", + "parameters": [] + }, + { + "name": "afterTool", + "parameters": [] + }, + { + "name": "sessionStart", + "parameters": [] + }, + { + "name": "sessionEnd", + "parameters": [] + }, + { + "name": "native", + "parameters": [ + { + "label": "_", + "name": "value", + "type": "String" + } + ] + } + ], + "PermissionOperation": [ + { + "name": "read", + "parameters": [] + }, + { + "name": "write", + "parameters": [] + }, + { + "name": "execute", + "parameters": [] + }, + { + "name": "tool", + "parameters": [ + { + "label": "_", + "name": "value", + "type": "String" + } + ] + } + ], + "IgnorePurpose": [ + { + "name": "context", + "parameters": [] + }, + { + "name": "indexing", + "parameters": [] + } + ], + "PluginMode": [ + { + "name": "native", + "parameters": [] + }, + { + "name": "components", + "parameters": [] + } + ], + "ComponentKind": [ + { + "name": "skills", + "parameters": [] + }, + { + "name": "instructions", + "parameters": [] + }, + { + "name": "mcpServer", + "parameters": [] + }, + { + "name": "hook", + "parameters": [] + }, + { + "name": "subagent", + "parameters": [] + }, + { + "name": "command", + "parameters": [] + }, + { + "name": "lspServer", + "parameters": [] + }, + { + "name": "permissions", + "parameters": [] + }, + { + "name": "ignore", + "parameters": [] + }, + { + "name": "plugin", + "parameters": [] + } + ], + "ComponentReference": [ + { + "name": "skill", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + } + ] + }, + { + "name": "instruction", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + } + ] + }, + { + "name": "mcpServer", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + } + ] + }, + { + "name": "hook", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + } + ] + }, + { + "name": "subagent", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + } + ] + }, + { + "name": "command", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + } + ] + }, + { + "name": "lspServer", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + } + ] + }, + { + "name": "permissions", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + } + ] + }, + { + "name": "ignore", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + } + ] + }, + { + "name": "plugin", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + } + ] + } + ] + }, + "structs": [ + "Condition", + "Agents", + "Source", + "ComponentGroup", + "GroupReference", + "SkillSelection", + "SkillOverride", + "SectionReference", + "ChatGPTPrompt", + "Resource", + "PromptContent", + "ExecutableInvocation", + "MCPTransport", + "PromptParameter", + "PermissionRule", + "Component" + ], + "factories": [ + { + "type": "Condition", + "name": "when", + "parameters": [ + { + "label": "agents", + "name": "agents", + "default": "nil", + "type": "[Agent]?" + }, + { + "label": "scopes", + "name": "scopes", + "default": "nil", + "type": "[Scope]?" + }, + { + "label": "platforms", + "name": "platforms", + "default": "nil", + "type": "[Platform]?" + } + ] + }, + { + "type": "Agents", + "name": "Agents", + "parameters": [ + { + "label": "defaultAgents", + "name": "defaultAgents", + "default": "nil", + "type": "[Agent]?" + }, + { + "label": "exports", + "name": "exports", + "default": "[]", + "type": "[String]" + }, + { + "label": "sources", + "name": "sources", + "default": "[]", + "type": "[Source]" + }, + { + "label": "components", + "name": "components", + "default": "[]", + "type": "[Component]" + }, + { + "label": "groups", + "name": "groups", + "default": "[]", + "type": "[ComponentGroup]" + }, + { + "label": "uses", + "name": "uses", + "default": "[]", + "type": "[GroupReference]" + }, + { + "label": "watch", + "name": "watch", + "default": "[]", + "type": "[String]" + } + ] + }, + { + "type": "Source", + "name": "source", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "url", + "name": "url", + "type": "String" + }, + { + "label": "subpath", + "name": "subpath", + "default": "nil", + "type": "String?" + } + ] + }, + { + "type": "Source", + "name": "source", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "url", + "name": "url", + "type": "String" + }, + { + "label": "from", + "name": "from", + "type": "Version" + }, + { + "label": "subpath", + "name": "subpath", + "default": "nil", + "type": "String?" + } + ] + }, + { + "type": "Source", + "name": "source", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "url", + "name": "url", + "type": "String" + }, + { + "label": "exact", + "name": "exact", + "type": "Version" + }, + { + "label": "subpath", + "name": "subpath", + "default": "nil", + "type": "String?" + } + ] + }, + { + "type": "Source", + "name": "source", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "url", + "name": "url", + "type": "String" + }, + { + "label": "branch", + "name": "branch", + "type": "String" + }, + { + "label": "subpath", + "name": "subpath", + "default": "nil", + "type": "String?" + } + ] + }, + { + "type": "Source", + "name": "source", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "url", + "name": "url", + "type": "String" + }, + { + "label": "revision", + "name": "revision", + "type": "String" + }, + { + "label": "subpath", + "name": "subpath", + "default": "nil", + "type": "String?" + } + ] + }, + { + "type": "Source", + "name": "source", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "url", + "name": "url", + "type": "String" + }, + { + "label": "_", + "name": "range", + "type": "Range" + }, + { + "label": "subpath", + "name": "subpath", + "default": "nil", + "type": "String?" + } + ] + }, + { + "type": "Source", + "name": "source", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "path", + "name": "path", + "type": "String" + }, + { + "label": "subpath", + "name": "subpath", + "default": "nil", + "type": "String?" + } + ] + }, + { + "type": "Source", + "name": "source", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "path", + "name": "path", + "type": "String" + }, + { + "label": "from", + "name": "from", + "type": "Version" + }, + { + "label": "subpath", + "name": "subpath", + "default": "nil", + "type": "String?" + } + ] + }, + { + "type": "Source", + "name": "source", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "path", + "name": "path", + "type": "String" + }, + { + "label": "exact", + "name": "exact", + "type": "Version" + }, + { + "label": "subpath", + "name": "subpath", + "default": "nil", + "type": "String?" + } + ] + }, + { + "type": "Source", + "name": "source", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "path", + "name": "path", + "type": "String" + }, + { + "label": "branch", + "name": "branch", + "type": "String" + }, + { + "label": "subpath", + "name": "subpath", + "default": "nil", + "type": "String?" + } + ] + }, + { + "type": "Source", + "name": "source", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "path", + "name": "path", + "type": "String" + }, + { + "label": "revision", + "name": "revision", + "type": "String" + }, + { + "label": "subpath", + "name": "subpath", + "default": "nil", + "type": "String?" + } + ] + }, + { + "type": "Source", + "name": "source", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "path", + "name": "path", + "type": "String" + }, + { + "label": "_", + "name": "range", + "type": "Range" + }, + { + "label": "subpath", + "name": "subpath", + "default": "nil", + "type": "String?" + } + ] + }, + { + "type": "Source", + "name": "source", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "index", + "name": "index", + "type": "String" + }, + { + "label": "subpath", + "name": "subpath", + "default": "nil", + "type": "String?" + } + ] + }, + { + "type": "ComponentGroup", + "name": "group", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "components", + "name": "components", + "default": "[]", + "type": "[Component]" + }, + { + "label": "uses", + "name": "uses", + "default": "[]", + "type": "[GroupReference]" + }, + { + "label": "condition", + "name": "condition", + "default": "nil", + "type": "Condition?" + } + ] + }, + { + "type": "GroupReference", + "name": "group", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "condition", + "name": "condition", + "default": "nil", + "type": "Condition?" + } + ] + }, + { + "type": "GroupReference", + "name": "group", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "source", + "name": "source", + "type": "String" + }, + { + "label": "condition", + "name": "condition", + "default": "nil", + "type": "Condition?" + } + ] + }, + { + "type": "SkillSelection", + "name": "all", + "property": true, + "parameters": [] + }, + { + "type": "SkillOverride", + "name": "skill", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "mode", + "name": "mode", + "default": "nil", + "type": "InstallMode?" + }, + { + "label": "agents", + "name": "agents", + "default": "nil", + "type": "[Agent]?" + } + ] + }, + { + "type": "SectionReference", + "name": "section", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "source", + "name": "source", + "default": "nil", + "type": "String?" + }, + { + "label": "condition", + "name": "condition", + "default": "nil", + "type": "Condition?" + } + ] + }, + { + "type": "ChatGPTPrompt", + "name": "prompt", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "sections", + "name": "sections", + "type": "[SectionReference]" + }, + { + "label": "append", + "name": "append", + "default": "nil", + "type": "String?" + }, + { + "label": "condition", + "name": "condition", + "default": "nil", + "type": "Condition?" + } + ] + }, + { + "type": "Resource", + "name": "path", + "parameters": [ + { + "label": "_", + "name": "path", + "type": "String" + }, + { + "label": "source", + "name": "source", + "default": "nil", + "type": "String?" + } + ] + }, + { + "type": "PromptContent", + "name": "file", + "parameters": [ + { + "label": "_", + "name": "path", + "type": "String" + }, + { + "label": "source", + "name": "source", + "default": "nil", + "type": "String?" + } + ] + }, + { + "type": "ExecutableInvocation", + "name": "executable", + "parameters": [ + { + "label": "_", + "name": "executable", + "type": "String" + }, + { + "label": "arguments", + "name": "arguments", + "default": "[]", + "type": "[String]" + }, + { + "label": "environment", + "name": "environment", + "default": "[:]", + "type": "[String: RuntimeValue]" + }, + { + "label": "workingDirectory", + "name": "workingDirectory", + "default": "nil", + "type": "Resource?" + } + ] + }, + { + "type": "MCPTransport", + "name": "stdio", + "parameters": [ + { + "label": "_", + "name": "executable", + "type": "String" + }, + { + "label": "arguments", + "name": "arguments", + "default": "[]", + "type": "[String]" + }, + { + "label": "environment", + "name": "environment", + "default": "[:]", + "type": "[String: RuntimeValue]" + }, + { + "label": "workingDirectory", + "name": "workingDirectory", + "default": "nil", + "type": "Resource?" + } + ] + }, + { + "type": "MCPTransport", + "name": "streamableHTTP", + "parameters": [ + { + "label": "url", + "name": "url", + "type": "String" + }, + { + "label": "headers", + "name": "headers", + "default": "[:]", + "type": "[String: RuntimeValue]" + } + ] + }, + { + "type": "MCPTransport", + "name": "sse", + "parameters": [ + { + "label": "url", + "name": "url", + "type": "String" + }, + { + "label": "headers", + "name": "headers", + "default": "[:]", + "type": "[String: RuntimeValue]" + } + ] + }, + { + "type": "PromptParameter", + "name": "parameter", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "description", + "name": "description", + "type": "String" + }, + { + "label": "defaultValue", + "name": "defaultValue", + "default": "nil", + "type": "String?" + } + ] + }, + { + "type": "PermissionRule", + "name": "allow", + "parameters": [ + { + "label": "_", + "name": "operation", + "type": "PermissionOperation" + }, + { + "label": "_", + "name": "pattern", + "type": "String" + } + ] + }, + { + "type": "PermissionRule", + "name": "ask", + "parameters": [ + { + "label": "_", + "name": "operation", + "type": "PermissionOperation" + }, + { + "label": "_", + "name": "pattern", + "type": "String" + } + ] + }, + { + "type": "PermissionRule", + "name": "deny", + "parameters": [ + { + "label": "_", + "name": "operation", + "type": "PermissionOperation" + }, + { + "label": "_", + "name": "pattern", + "type": "String" + } + ] + }, + { + "type": "Component", + "name": "skills", + "parameters": [ + { + "label": "source", + "name": "source", + "type": "String" + }, + { + "label": "select", + "name": "select", + "default": ".all", + "type": "SkillSelection" + }, + { + "label": "exclude", + "name": "exclude", + "default": "[]", + "type": "[String]" + }, + { + "label": "mode", + "name": "mode", + "default": "nil", + "type": "InstallMode?" + }, + { + "label": "overrides", + "name": "overrides", + "default": "[]", + "type": "[SkillOverride]" + }, + { + "label": "agents", + "name": "agents", + "default": "nil", + "type": "[Agent]?" + }, + { + "label": "condition", + "name": "condition", + "default": "nil", + "type": "Condition?" + }, + { + "label": "native", + "name": "native", + "default": "[:]", + "type": "NativeConfiguration" + } + ] + }, + { + "type": "Component", + "name": "instructions", + "parameters": [ + { + "label": "sections", + "name": "sections", + "default": "[]", + "type": "[SectionReference]" + }, + { + "label": "chatGPT", + "name": "chatGPT", + "default": "[]", + "type": "[ChatGPTPrompt]" + }, + { + "label": "agents", + "name": "agents", + "default": "nil", + "type": "[Agent]?" + }, + { + "label": "condition", + "name": "condition", + "default": "nil", + "type": "Condition?" + }, + { + "label": "native", + "name": "native", + "default": "[:]", + "type": "NativeConfiguration" + } + ] + }, + { + "type": "Component", + "name": "mcpServer", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "transport", + "name": "transport", + "type": "MCPTransport" + }, + { + "label": "agents", + "name": "agents", + "default": "nil", + "type": "[Agent]?" + }, + { + "label": "condition", + "name": "condition", + "default": "nil", + "type": "Condition?" + }, + { + "label": "native", + "name": "native", + "default": "[:]", + "type": "NativeConfiguration" + } + ] + }, + { + "type": "Component", + "name": "hook", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "event", + "name": "event", + "type": "HookEvent" + }, + { + "label": "run", + "name": "run", + "type": "ExecutableInvocation" + }, + { + "label": "matcher", + "name": "matcher", + "default": "nil", + "type": "String?" + }, + { + "label": "timeoutSeconds", + "name": "timeoutSeconds", + "default": "nil", + "type": "Int?" + }, + { + "label": "agents", + "name": "agents", + "default": "nil", + "type": "[Agent]?" + }, + { + "label": "condition", + "name": "condition", + "default": "nil", + "type": "Condition?" + }, + { + "label": "native", + "name": "native", + "default": "[:]", + "type": "NativeConfiguration" + } + ] + }, + { + "type": "Component", + "name": "subagent", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "description", + "name": "description", + "type": "String" + }, + { + "label": "prompt", + "name": "prompt", + "type": "PromptContent" + }, + { + "label": "model", + "name": "model", + "default": "nil", + "type": "String?" + }, + { + "label": "tools", + "name": "tools", + "default": "nil", + "type": "[String]?" + }, + { + "label": "agents", + "name": "agents", + "default": "nil", + "type": "[Agent]?" + }, + { + "label": "condition", + "name": "condition", + "default": "nil", + "type": "Condition?" + }, + { + "label": "native", + "name": "native", + "default": "[:]", + "type": "NativeConfiguration" + } + ] + }, + { + "type": "Component", + "name": "command", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "description", + "name": "description", + "type": "String" + }, + { + "label": "prompt", + "name": "prompt", + "type": "PromptContent" + }, + { + "label": "parameters", + "name": "parameters", + "default": "[]", + "type": "[PromptParameter]" + }, + { + "label": "agents", + "name": "agents", + "default": "nil", + "type": "[Agent]?" + }, + { + "label": "condition", + "name": "condition", + "default": "nil", + "type": "Condition?" + }, + { + "label": "native", + "name": "native", + "default": "[:]", + "type": "NativeConfiguration" + } + ] + }, + { + "type": "Component", + "name": "lspServer", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "run", + "name": "run", + "type": "ExecutableInvocation" + }, + { + "label": "languages", + "name": "languages", + "type": "[String: String]" + }, + { + "label": "initializationOptions", + "name": "initializationOptions", + "default": "[:]", + "type": "[String: ConfigurationValue]" + }, + { + "label": "agents", + "name": "agents", + "default": "nil", + "type": "[Agent]?" + }, + { + "label": "condition", + "name": "condition", + "default": "nil", + "type": "Condition?" + }, + { + "label": "native", + "name": "native", + "default": "[:]", + "type": "NativeConfiguration" + } + ] + }, + { + "type": "Component", + "name": "permissions", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "rules", + "name": "rules", + "type": "[PermissionRule]" + }, + { + "label": "agents", + "name": "agents", + "default": "nil", + "type": "[Agent]?" + }, + { + "label": "condition", + "name": "condition", + "default": "nil", + "type": "Condition?" + }, + { + "label": "native", + "name": "native", + "default": "[:]", + "type": "NativeConfiguration" + } + ] + }, + { + "type": "Component", + "name": "ignore", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "patterns", + "name": "patterns", + "type": "[String]" + }, + { + "label": "purpose", + "name": "purpose", + "default": ".context", + "type": "IgnorePurpose" + }, + { + "label": "agents", + "name": "agents", + "default": "nil", + "type": "[Agent]?" + }, + { + "label": "condition", + "name": "condition", + "default": "nil", + "type": "Condition?" + }, + { + "label": "native", + "name": "native", + "default": "[:]", + "type": "NativeConfiguration" + } + ] + }, + { + "type": "Component", + "name": "plugin", + "parameters": [ + { + "label": "name", + "name": "name", + "type": "String" + }, + { + "label": "path", + "name": "path", + "type": "String" + }, + { + "label": "source", + "name": "source", + "type": "String" + }, + { + "label": "mode", + "name": "mode", + "default": ".components", + "type": "PluginMode" + }, + { + "label": "select", + "name": "select", + "default": "nil", + "type": "[ComponentKind]?" + }, + { + "label": "exclude", + "name": "exclude", + "default": "[]", + "type": "[ComponentReference]" + }, + { + "label": "agents", + "name": "agents", + "default": "nil", + "type": "[Agent]?" + }, + { + "label": "condition", + "name": "condition", + "default": "nil", + "type": "Condition?" + }, + { + "label": "native", + "name": "native", + "default": "[:]", + "type": "NativeConfiguration" + } + ] + } + ], + "literals": { + "SectionReference": { + "protocols": [ + "ExpressibleByStringLiteral" + ], + "kinds": [ + "string" + ], + "initializers": [ + "public init(stringLiteral value: String) { self.init(value: .construct(type: \"SectionReference\", member: \"section\", fields: [\"name\": .text(value), \"source\": .none, \"condition\": .none])) }" + ] + }, + "GroupReference": { + "protocols": [ + "ExpressibleByStringLiteral" + ], + "kinds": [ + "string" + ], + "initializers": [ + "public init(stringLiteral value: String) { self.init(value: .construct(type: \"GroupReference\", member: \"group\", fields: [\"name\": .text(value), \"source\": .none, \"condition\": .none])) }" + ] + }, + "PromptContent": { + "protocols": [ + "ExpressibleByStringLiteral" + ], + "kinds": [ + "string" + ], + "initializers": [ + "public init(stringLiteral value: String) { self.init(value: .node(type: \"PromptContent\", member: \"literal\", fields: [\"value\": .text(value)])) }" + ] + }, + "RuntimeValue": { + "protocols": [ + "ExpressibleByStringLiteral" + ], + "kinds": [ + "string" + ], + "initializers": [ + "public init(stringLiteral value: String) { self = .literal(value) }" + ] + }, + "SkillSelection": { + "protocols": [ + "ExpressibleByArrayLiteral" + ], + "kinds": [ + "array" + ], + "initializers": [ + "public init(arrayLiteral elements: String...) { self.init(value: .node(type: \"SkillSelection\", member: \"names\", fields: [\"names\": elements.constructionValue])) }" + ] + }, + "ConfigurationValue": { + "protocols": [ + "ExpressibleByStringLiteral", + "ExpressibleByIntegerLiteral", + "ExpressibleByBooleanLiteral", + "ExpressibleByNilLiteral", + "ExpressibleByArrayLiteral", + "ExpressibleByDictionaryLiteral" + ], + "kinds": [ + "string", + "integer", + "boolean", + "nil", + "array", + "dictionary" + ], + "initializers": [ + "public init(stringLiteral value: String) { self = .string(value) }", + "public init(integerLiteral value: Int) { self = .integer(value) }", + "public init(booleanLiteral value: Bool) { self = .boolean(value) }", + "public init(nilLiteral: ()) { self = .null }", + "public init(arrayLiteral elements: ConfigurationValue...) { self = .array(elements) }", + "public init(dictionaryLiteral elements: (String, ConfigurationValue)...) { self = .object(Dictionary(elements, uniquingKeysWith: { _, last in last })) }" + ] + }, + "Version": { + "protocols": [ + "ExpressibleByStringLiteral" + ], + "kinds": [ + "string" + ], + "initializers": [] + } + } +} diff --git a/Scripts/generate-manifest-fixtures.py b/Scripts/generate-manifest-fixtures.py new file mode 100644 index 0000000..3d3a396 --- /dev/null +++ b/Scripts/generate-manifest-fixtures.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +"""Compile the reviewed positive corpus as ordinary Swift in the test target.""" +from pathlib import Path +import re +ROOT = Path(__file__).resolve().parent.parent +paths = sorted((ROOT / 'Tests/AgentsManifestTests/Fixtures').glob('*.swift.txt')) +lines = ['// Generated from Tests/AgentsManifestTests/Fixtures. Run Scripts/generate-manifest-fixtures.py.', '', 'import AgentsDescription', 'import Foundation', '', '#if canImport(SwiftUI)', ' import SwiftUI', '#endif', '', 'struct CompiledManifestFixture {', ' let name: String', ' let agents: Agents', ' let constants: [String: ConstructionValue]', '}', '', 'func compiledFixtures() -> [CompiledManifestFixture] {', ' ['] +for i,p in enumerate(paths):lines.append(f' fixture{i}(),') +lines+=[' ]','}',''] +for i,p in enumerate(paths): + body='\n'.join(l for l in p.read_text().splitlines() if l!='import AgentsDescription') + names = re.findall(r'^let ([A-Za-z_][A-Za-z_0-9]*)\b', body, re.MULTILINE) + lines += [f'private func fixture{i}() -> CompiledManifestFixture {{']+[' '+l if l else '' for l in body.splitlines()] + lines += [f' return CompiledManifestFixture(name: "{p.name}", agents: agents, constants: ['] + lines += [f' "{name}": {name}.constructionValue,' for name in names] + lines += [' ])','}',''] +(ROOT / 'Tests/AgentsManifestTests/CompiledFixtures.swift').write_text('\n'.join(lines)) + +import subprocess +subprocess.run(["swift", "format", "format", "--in-place", "--configuration", str(ROOT / ".swift-format"), str(ROOT / 'Tests/AgentsManifestTests/CompiledFixtures.swift')], check=True) diff --git a/Scripts/generate-manifest-vocabulary.py b/Scripts/generate-manifest-vocabulary.py new file mode 100644 index 0000000..e1180c8 --- /dev/null +++ b/Scripts/generate-manifest-vocabulary.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""Generate authoring declarations and static registrations from the language inventory.""" +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SPEC = json.loads((ROOT / 'Scripts/ManifestVocabulary.json').read_text()) +DEST = ROOT / 'Sources/AgentsDescription' +HEADER = '// Generated from Scripts/ManifestVocabulary.json. Run Scripts/generate-manifest-vocabulary.py.\n\n' + + +def type_expr(t): + if t == 'NativeConfiguration': + return '.dictionary(.dictionary(.named("ConfigurationValue")))' + if t.endswith('?'): + return '.optional(' + type_expr(t[:-1]) + ')' + if t.startswith('['): + inner = t[1:-1] + if inner.startswith('String: '): + return '.dictionary(' + type_expr(inner[8:]) + ')' + return '.array(' + type_expr(inner) + ')' + if t == 'Range': + return '.named("VersionRange")' + return '.named(' + json.dumps(t) + ')' + + +def signature(p): + ext = p['label'] + name = p['name'] + s = (ext + ' ' if ext != name else '') + name + ': ' + p['type'] + if 'default' in p: + s += ' = ' + p['default'] + return s + + +def default_expr(p): + if 'default' not in p: + return 'nil' + return '(' + p['default'] + ' as ' + p['type'] + ').constructionValue' + + +lines = [HEADER] +for name, cases in SPEC['enums'].items(): + recursive = 'indirect ' if name == 'ConfigurationValue' else '' + protocols = ['Sendable', 'Equatable'] + SPEC['literals'].get(name, {}).get('protocols', []) + lines.append(f'public {recursive}enum {name}: ' + ', '.join(protocols) + ' {') + for c in cases: + ps = c.get('parameters', []) + decl = c['name'] + if ps: + decl += '(' + ', '.join((p['label'] + ': ' if p['label'] != '_' else '') + p['type'] for p in ps) + ')' + lines.append(' case ' + decl) + for init in SPEC['literals'].get(name, {}).get('initializers', []): + lines.append(' ' + init) + lines += ['}', '', f'extension {name}: ConstructionRepresentable {{', ' package var constructionValue: ConstructionValue {', ' switch self {'] + for c in cases: + ps = c.get('parameters', []) + pattern = '.' + c['name'] + if ps: + pattern += '(' + ', '.join('let ' + p['name'] for p in ps) + ')' + fields = ', '.join(json.dumps(p['name']) + ': ' + p['name'] + '.constructionValue' for p in ps) + lines.append(f' case {pattern}: .node(type: "{name}", member: "{c["name"]}", fields: [' + (fields or ':') + '])') + lines += [' }', ' }', '}', ''] + +for name in SPEC['structs']: + protocols = ['Sendable', 'Equatable'] + SPEC['literals'].get(name, {}).get('protocols', []) + lines += [f'public struct {name}: ' + ', '.join(protocols) + ' {', ' private let storage: ConstructionValue', ' package var constructionValue: ConstructionValue { storage }', ' package init(value: ConstructionValue) { storage = value }'] + for init in SPEC['literals'].get(name, {}).get('initializers', []): + lines.append(' ' + init) + for m in SPEC['factories']: + if m['type'] != name: + continue + if m.get('property'): + lines.append(f' public static var {m["name"]}: {name} {{ Self(value: .node(type: "{name}", member: "{m["name"]}", fields: [:])) }}') + continue + ps = m['parameters'] + decl = 'public init' if name == 'Agents' else 'public static func ' + m['name'] + decl += '(' + ', '.join(signature(p) for p in ps) + ')' + if name != 'Agents': + decl += ' -> ' + name + fields = ', '.join(json.dumps(p['name']) + ': ' + p['name'] + '.constructionValue' for p in ps) + construct = f'ConstructionValue.construct(type: "{name}", member: "{m["name"]}", fields: [' + (fields or ':') + '])' + body = 'self.init(value: ' + construct + ')' if name == 'Agents' else 'Self(value: ' + construct + ')' + lines.append(' ' + decl + ' { ' + body + ' }') + lines += ['}', f'extension {name}: ConstructionRepresentable {{}}', ''] +lines += ['public typealias NativeConfiguration = [String: [String: ConfigurationValue]]', ''] +(DEST / 'Vocabulary.swift').write_text('\n'.join(lines)) + +reg = [HEADER, 'package enum Vocabulary {', ' package static let typeNames: Set = [' + ', '.join(json.dumps(n) for n in ['String', 'Int', 'Bool', 'Version', 'NativeConfiguration'] + list(SPEC['enums']) + SPEC['structs']) + ']', ' package static let signatures: [ConstructionSignature] = ['] +for m in SPEC['factories'] + [dict(type=n, name=c['name'], parameters=c.get('parameters', []), enumCase=True) for n, cases in SPEC['enums'].items() for c in cases]: + ps = ', '.join('ConstructionParameter(label: ' + json.dumps(p['label']) + ', name: ' + json.dumps(p['name']) + ', type: ' + type_expr(p['type']) + ', defaultValue: ' + default_expr(p) + ')' for p in m.get('parameters', [])) + reg.append(' ConstructionSignature(type: ' + json.dumps(m['type']) + ', member: ' + json.dumps(m['name']) + ', parameters: [' + ps + '], callable: ' + str(not m.get('property') and (not m.get('enumCase') or bool(m.get('parameters')))).lower() + '),') +# Range factories are only contextual at their grammar slot. +for name in ['upToNextMajor', 'upToNextMinor']: + reg.append(' ConstructionSignature(type: "VersionRange", member: "' + name + '", parameters: [ConstructionParameter(label: "from", name: "from", type: .named("Version"), defaultValue: nil)], callable: true),') +reg += [' ]', ' package static let literalTypes: [String: Set] = ['] +for n, lit in SPEC['literals'].items(): + reg.append(' ' + json.dumps(n) + ': [' + ', '.join(json.dumps(x) for x in lit['kinds']) + '],') +reg += [' ]', '}', ''] +(DEST / 'VocabularyInventory.swift').write_text('\n'.join(reg)) + +import subprocess +subprocess.run(["swift", "format", "format", "--in-place", "--configuration", str(ROOT / ".swift-format"), str(ROOT / 'Sources/AgentsDescription/Vocabulary.swift'), str(ROOT / 'Sources/AgentsDescription/VocabularyInventory.swift')], check=True) diff --git a/Sources/AgentsCore/Declaration.swift b/Sources/AgentsCore/Declaration.swift index ee78408..7c37ee1 100644 --- a/Sources/AgentsCore/Declaration.swift +++ b/Sources/AgentsCore/Declaration.swift @@ -56,6 +56,16 @@ public struct SourceDeclaration: Codable, Equatable, Sendable { switch kind { case .local: return "local:" + localURL(environment: environment).path + case .wellKnown, .git: + return try transportIdentity() + } + } + + /// Normalizes a transport location without a runtime filesystem context. + package func transportIdentity() throws -> String { + guard !location.isEmpty else { throw CoreError.invalidSource("empty source location") } + switch kind { + case .local: throw CoreError.invalidSource("local identity requires a package root") case .wellKnown: guard let components = URLComponents(string: location), ["http", "https"].contains(components.scheme), components.host != nil, diff --git a/Sources/AgentsCore/DeclarationIR.swift b/Sources/AgentsCore/DeclarationIR.swift new file mode 100644 index 0000000..054ccac --- /dev/null +++ b/Sources/AgentsCore/DeclarationIR.swift @@ -0,0 +1,78 @@ +/// Syntax-independent declaration data. Collections retain authored order; recipients are IDs, +/// conditions remain data, and group references are symbolic until linking. +public indirect enum DeclarationValue: Sendable, Equatable { + case string(String) + case integer(Int) + case boolean(Bool) + case null + case array([DeclarationValue]) + case dictionary([String: DeclarationValue]) + case record(DeclarationRecord) + case requirement(SourceRequirement) + + public static func == (lhs: DeclarationValue, rhs: DeclarationValue) -> Bool { + switch (lhs, rhs) { + case (.string(let a), .string(let b)): return a == b + case (.integer(let a), .integer(let b)): return a == b + case (.boolean(let a), .boolean(let b)): return a == b + case (.null, .null): return true + case (.array(let a), .array(let b)): return a == b + case (.dictionary(let a), .dictionary(let b)): return a == b + case (.record(let a), .record(let b)): return a == b + case (.requirement(let a), .requirement(let b)): return a.declarationEquivalent(to: b) + default: return false + } + } + + public var string: String? { + if case .string(let value) = self { return value } + return nil + } + + public var elements: [DeclarationValue]? { + if case .array(let value) = self { return value } + return nil + } + + public var record: DeclarationRecord? { + if case .record(let value) = self { return value } + return nil + } +} + +/// A tagged domain value. No field contains a deployment path or a syntax node. +public struct DeclarationRecord: Sendable, Equatable { + public let kind: String + public let fields: [String: DeclarationValue] + + public init(kind: String, fields: [String: DeclarationValue]) { + self.kind = kind + self.fields = fields + } + + public subscript(_ field: String) -> DeclarationValue? { fields[field] } +} + +public struct DeclarationIR: Sendable, Equatable { + public let defaultAgents: [String]? + public let exports: [String] + public let sources: [DeclarationRecord] + public let components: [DeclarationRecord] + public let groups: [DeclarationRecord] + public let uses: [DeclarationRecord] + public let watch: [String] + + public init( + defaultAgents: [String]? = nil, exports: [String] = [], sources: [DeclarationRecord] = [], + components: [DeclarationRecord] = [], groups: [DeclarationRecord] = [], + uses: [DeclarationRecord] = [], watch: [String] = [] + ) { + self.defaultAgents = defaultAgents + self.exports = exports + self.sources = sources + self.components = components + self.groups = groups + self.uses = uses + self.watch = watch + } +} diff --git a/Sources/AgentsCore/SourceProvenance.swift b/Sources/AgentsCore/SourceProvenance.swift new file mode 100644 index 0000000..a59154d --- /dev/null +++ b/Sources/AgentsCore/SourceProvenance.swift @@ -0,0 +1,72 @@ +public struct DocumentIdentity: Sendable, Hashable { + public let rawValue: String + public init(_ rawValue: String) { self.rawValue = rawValue } +} + +/// Half-open UTF-8 byte offsets and the 1-based line and byte column of the start. +public struct SourceSpan: Sendable, Hashable { + public let document: DocumentIdentity + public let start: Int + public let end: Int + public let line: Int + public let column: Int + + public init(document: DocumentIdentity, start: Int, end: Int, line: Int, column: Int) { + self.document = document + self.start = start + self.end = end + self.line = line + self.column = column + } +} + +/// Stable source coordinates, independent of a checkout or cache location. +public struct SourceProvenance: Sendable, Equatable { + public let sourceIdentity: String + public let revision: String? + public let artifactDigest: String? + public let relativePath: String + public let format: String + public let adapterVersion: String + public let group: String? + public let referenceChain: [SourceSpan] + + public init( + sourceIdentity: String, revision: String? = nil, artifactDigest: String? = nil, + relativePath: String, format: String, adapterVersion: String, group: String? = nil, + referenceChain: [SourceSpan] = [] + ) { + self.sourceIdentity = sourceIdentity + self.revision = revision + self.artifactDigest = artifactDigest + self.relativePath = relativePath + self.format = format + self.adapterVersion = adapterVersion + self.group = group + self.referenceChain = referenceChain + } +} + +public struct SourceMapEntry: Sendable, Equatable { + public let pointer: String + public let span: SourceSpan + public let origins: [SourceSpan] + public let defaulted: Bool + + public init( + pointer: String, span: SourceSpan, origins: [SourceSpan] = [], defaulted: Bool = false + ) { + self.pointer = pointer + self.span = span + self.origins = origins + self.defaulted = defaulted + } +} + +public struct DeclarationSourceMap: Sendable, Equatable { + public let entries: [SourceMapEntry] + public init(entries: [SourceMapEntry]) { self.entries = entries } + public func locations(at pointer: String) -> [SourceMapEntry] { + entries.filter { $0.pointer == pointer } + } +} diff --git a/Sources/AgentsCore/SourceRequirement.swift b/Sources/AgentsCore/SourceRequirement.swift index a6b2f70..8351048 100644 --- a/Sources/AgentsCore/SourceRequirement.swift +++ b/Sources/AgentsCore/SourceRequirement.swift @@ -225,3 +225,36 @@ struct SemanticVersion: Comparable, Equatable, Sendable, CustomStringConvertible } } } + +extension SourceRequirement { + /// Declaration comparison expands range spellings; exact requirements retain metadata. + package func declarationEquivalent(to other: SourceRequirement) -> Bool { + switch (self, other) { + case (.branch(let lhs), .branch(let rhs)), (.revision(let lhs), .revision(let rhs)): + return lhs == rhs + case (.exact(let lhs), .exact(let rhs)): + guard let left = SemanticVersion(lhs), let right = SemanticVersion(rhs) else { return false } + return left.description == right.description + default: + guard let left = declarationBounds, let right = other.declarationBounds else { return false } + return left.0 == right.0 && left.1 == right.1 + } + } + + private var declarationBounds: (SemanticVersion, SemanticVersion)? { + switch self { + case .range(let from, let to): + guard let lower = SemanticVersion(from), let upper = SemanticVersion(to) else { return nil } + return (lower, upper) + case .upToNextMajor(let from), .upToNextMinor(let from): + guard let lower = SemanticVersion(from) else { return nil } + if case .upToNextMajor = self { + let (major, overflow) = lower.major.addingReportingOverflow(1) + return overflow ? nil : (lower, SemanticVersion(major: major, minor: 0, patch: 0)) + } + let (minor, overflow) = lower.minor.addingReportingOverflow(1) + return overflow ? nil : (lower, SemanticVersion(major: lower.major, minor: minor, patch: 0)) + default: return nil + } + } +} diff --git a/Sources/AgentsDescription/ConstructionValue.swift b/Sources/AgentsDescription/ConstructionValue.swift new file mode 100644 index 0000000..ad4fe93 --- /dev/null +++ b/Sources/AgentsDescription/ConstructionValue.swift @@ -0,0 +1,104 @@ +package indirect enum ConstructionType: Sendable, Hashable { + case named(String) + case array(ConstructionType) + case dictionary(ConstructionType) + case optional(ConstructionType) + + package var unwrapped: ConstructionType { + if case .optional(let type) = self { return type } + return self + } +} + +package struct ConstructionParameter: Sendable { + package let label: String + package let name: String + package let type: ConstructionType + package let defaultValue: ConstructionValue? +} + +package struct ConstructionSignature: Sendable { + package let type: String + package let member: String + package let parameters: [ConstructionParameter] + package let callable: Bool +} + +package indirect enum ConstructionValue: Sendable, Equatable { + case text(String) + case integer(Int) + case boolean(Bool) + case none + case array([ConstructionValue]) + case object([String: ConstructionValue]) + case node(type: String, member: String, fields: [String: ConstructionValue]) + case version(Version) + case range(Range) + + package static func construct( + type: String, member: String, fields: [String: ConstructionValue] + ) -> Self { + if type == "GroupReference" { + var result = fields + if result["source"] == nil { result["source"] = ConstructionValue.none } + return .node(type: type, member: member, fields: result) + } + if type == "Source" { + var result = fields + if case .version(let lower) = result.removeValue(forKey: "from") { + result["requirement"] = .range(.upToNextMajor(from: lower)) + } else if let range = result.removeValue(forKey: "range") { + result["requirement"] = range + } else if let exact = result.removeValue(forKey: "exact") { + let value: ConstructionValue + if case .version(let version) = exact { + value = .text(version.normalized) + } else { + value = exact + } + result["requirement"] = .node( + type: "Requirement", member: "exact", fields: ["value": value]) + } else if let branch = result.removeValue(forKey: "branch") { + result["requirement"] = .node( + type: "Requirement", member: "branch", fields: ["value": branch]) + } else if let revision = result.removeValue(forKey: "revision") { + result["requirement"] = .node( + type: "Requirement", member: "revision", fields: ["value": revision]) + } else { + result["requirement"] = ConstructionValue.none + } + return .node(type: type, member: member, fields: result) + } + if type == "VersionRange", case .version(let lower) = fields["from"] { + return .range( + member == "upToNextMajor" ? .upToNextMajor(from: lower) : .upToNextMinor(from: lower)) + } + return .node(type: type, member: member, fields: fields) + } +} + +package protocol ConstructionRepresentable { + var constructionValue: ConstructionValue { get } +} +extension String: ConstructionRepresentable { + package var constructionValue: ConstructionValue { .text(self) } +} +extension Int: ConstructionRepresentable { + package var constructionValue: ConstructionValue { .integer(self) } +} +extension Bool: ConstructionRepresentable { + package var constructionValue: ConstructionValue { .boolean(self) } +} +extension Optional: ConstructionRepresentable where Wrapped: ConstructionRepresentable { + package var constructionValue: ConstructionValue { self?.constructionValue ?? .none } +} +extension Array: ConstructionRepresentable where Element: ConstructionRepresentable { + package var constructionValue: ConstructionValue { .array(map(\.constructionValue)) } +} +extension Dictionary: ConstructionRepresentable +where Key == String, Value: ConstructionRepresentable { + package var constructionValue: ConstructionValue { .object(mapValues(\.constructionValue)) } +} +extension Range: ConstructionRepresentable where Bound == Version { + package var constructionValue: ConstructionValue { .range(self) } +} diff --git a/Sources/AgentsDescription/Version.swift b/Sources/AgentsDescription/Version.swift new file mode 100644 index 0000000..e67b049 --- /dev/null +++ b/Sources/AgentsDescription/Version.swift @@ -0,0 +1,103 @@ +/// A semantic version literal. Manifest domain validation diagnoses invalid spellings. +public struct Version: Sendable, Comparable, ExpressibleByStringLiteral { + package let major: Int + package let minor: Int + package let patch: Int + package let prerelease: [String] + package let metadata: [String] + package let valid: Bool + package let normalized: String + + public init(stringLiteral value: String) { + var body = value.drop(while: \.isWhitespace) + while body.last?.isWhitespace == true { body = body.dropLast() } + if body.first == "v" || body.first == "V" { body = body.dropFirst() } + let builds = body.split(separator: "+", maxSplits: 1, omittingEmptySubsequences: false) + let releases = builds[0].split(separator: "-", maxSplits: 1, omittingEmptySubsequences: false) + let numbers = releases[0].split(separator: ".", omittingEmptySubsequences: false) + let parsed = numbers.map { Int($0) } + let pre = + releases.count == 2 + ? releases[1].split(separator: ".", omittingEmptySubsequences: false).map(String.init) : [] + let meta = + builds.count == 2 + ? builds[1].split(separator: ".", omittingEmptySubsequences: false).map(String.init) : [] + major = parsed.first.flatMap { $0 } ?? 0 + minor = parsed.count > 1 ? parsed[1] ?? 0 : 0 + patch = parsed.count > 2 ? parsed[2] ?? 0 : 0 + prerelease = pre + metadata = meta + valid = + numbers.count == 3 && parsed.allSatisfy { $0 != nil } + && numbers.allSatisfy { Self.numeric(String($0)) && ($0.count == 1 || !$0.hasPrefix("0")) } + && pre.allSatisfy { + Self.identifier($0) && (!Self.numeric($0) || $0.count == 1 || !$0.hasPrefix("0")) + } + && meta.allSatisfy(Self.identifier) + normalized = String(body) + } + + private init(major: Int, minor: Int, patch: Int, valid: Bool = true) { + self.major = major + self.minor = minor + self.patch = patch + prerelease = [] + metadata = [] + self.valid = valid + normalized = "\(major).\(minor).\(patch)" + } + + public static func == (lhs: Version, rhs: Version) -> Bool { + lhs.major == rhs.major && lhs.minor == rhs.minor && lhs.patch == rhs.patch + && lhs.prerelease == rhs.prerelease && lhs.valid == rhs.valid + } + + public static func < (lhs: Version, rhs: Version) -> Bool { + if lhs.major != rhs.major { return lhs.major < rhs.major } + if lhs.minor != rhs.minor { return lhs.minor < rhs.minor } + if lhs.patch != rhs.patch { return lhs.patch < rhs.patch } + if lhs.prerelease.isEmpty || rhs.prerelease.isEmpty { + return !lhs.prerelease.isEmpty && rhs.prerelease.isEmpty + } + for (left, right) in zip(lhs.prerelease, rhs.prerelease) { + if left == right { continue } + let ln = numeric(left) + let rn = numeric(right) + if ln && rn && left.count != right.count { return left.count < right.count } + if ln != rn { return ln } + return left < right + } + return lhs.prerelease.count < rhs.prerelease.count + } + + package func successor(major incrementMajor: Bool) -> Version { + let (next, overflow) = (incrementMajor ? major : minor).addingReportingOverflow(1) + if overflow || !valid { return Version(major: major, minor: minor, patch: patch, valid: false) } + return Version(major: incrementMajor ? next : major, minor: incrementMajor ? 0 : next, patch: 0) + } + + private static func numeric(_ value: String) -> Bool { + !value.isEmpty && value.utf8.allSatisfy { (48...57).contains($0) } + } + + private static func identifier(_ value: String) -> Bool { + !value.isEmpty + && value.utf8.allSatisfy { + $0 == 45 || (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) + } + } +} + +extension Version: ConstructionRepresentable { + package var constructionValue: ConstructionValue { .version(self) } +} + +extension Range where Bound == Version { + public static func upToNextMajor(from version: Version) -> Range { + Range(uncheckedBounds: (version, version.successor(major: true))) + } + + public static func upToNextMinor(from version: Version) -> Range { + Range(uncheckedBounds: (version, version.successor(major: false))) + } +} diff --git a/Sources/AgentsDescription/Vocabulary.swift b/Sources/AgentsDescription/Vocabulary.swift new file mode 100644 index 0000000..ce537fa --- /dev/null +++ b/Sources/AgentsDescription/Vocabulary.swift @@ -0,0 +1,861 @@ +// Generated from Scripts/ManifestVocabulary.json. Run Scripts/generate-manifest-vocabulary.py. + +public enum Agent: Sendable, Equatable { + case claudeCode + case codex + case cursor + case geminiCLI + case openCode +} + +extension Agent: ConstructionRepresentable { + package var constructionValue: ConstructionValue { + switch self { + case .claudeCode: .node(type: "Agent", member: "claudeCode", fields: [:]) + case .codex: .node(type: "Agent", member: "codex", fields: [:]) + case .cursor: .node(type: "Agent", member: "cursor", fields: [:]) + case .geminiCLI: .node(type: "Agent", member: "geminiCLI", fields: [:]) + case .openCode: .node(type: "Agent", member: "openCode", fields: [:]) + } + } +} + +public enum Scope: Sendable, Equatable { + case project + case user +} + +extension Scope: ConstructionRepresentable { + package var constructionValue: ConstructionValue { + switch self { + case .project: .node(type: "Scope", member: "project", fields: [:]) + case .user: .node(type: "Scope", member: "user", fields: [:]) + } + } +} + +public enum Platform: Sendable, Equatable { + case macOS + case linux +} + +extension Platform: ConstructionRepresentable { + package var constructionValue: ConstructionValue { + switch self { + case .macOS: .node(type: "Platform", member: "macOS", fields: [:]) + case .linux: .node(type: "Platform", member: "linux", fields: [:]) + } + } +} + +public enum InstallMode: Sendable, Equatable { + case link + case copy + case edit +} + +extension InstallMode: ConstructionRepresentable { + package var constructionValue: ConstructionValue { + switch self { + case .link: .node(type: "InstallMode", member: "link", fields: [:]) + case .copy: .node(type: "InstallMode", member: "copy", fields: [:]) + case .edit: .node(type: "InstallMode", member: "edit", fields: [:]) + } + } +} + +public enum RuntimeValue: Sendable, Equatable, ExpressibleByStringLiteral { + case literal(String) + case environment(String) + case secret(String) + public init(stringLiteral value: String) { self = .literal(value) } +} + +extension RuntimeValue: ConstructionRepresentable { + package var constructionValue: ConstructionValue { + switch self { + case .literal(let value): + .node(type: "RuntimeValue", member: "literal", fields: ["value": value.constructionValue]) + case .environment(let value): + .node(type: "RuntimeValue", member: "environment", fields: ["value": value.constructionValue]) + case .secret(let value): + .node(type: "RuntimeValue", member: "secret", fields: ["value": value.constructionValue]) + } + } +} + +public indirect enum ConfigurationValue: Sendable, Equatable, ExpressibleByStringLiteral, + ExpressibleByIntegerLiteral, ExpressibleByBooleanLiteral, ExpressibleByNilLiteral, + ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral +{ + case string(String) + case integer(Int) + case decimal(String) + case boolean(Bool) + case null + case array([ConfigurationValue]) + case object([String: ConfigurationValue]) + public init(stringLiteral value: String) { self = .string(value) } + public init(integerLiteral value: Int) { self = .integer(value) } + public init(booleanLiteral value: Bool) { self = .boolean(value) } + public init(nilLiteral: ()) { self = .null } + public init(arrayLiteral elements: ConfigurationValue...) { self = .array(elements) } + public init(dictionaryLiteral elements: (String, ConfigurationValue)...) { + self = .object(Dictionary(elements, uniquingKeysWith: { _, last in last })) + } +} + +extension ConfigurationValue: ConstructionRepresentable { + package var constructionValue: ConstructionValue { + switch self { + case .string(let value): + .node( + type: "ConfigurationValue", member: "string", fields: ["value": value.constructionValue]) + case .integer(let value): + .node( + type: "ConfigurationValue", member: "integer", fields: ["value": value.constructionValue]) + case .decimal(let value): + .node( + type: "ConfigurationValue", member: "decimal", fields: ["value": value.constructionValue]) + case .boolean(let value): + .node( + type: "ConfigurationValue", member: "boolean", fields: ["value": value.constructionValue]) + case .null: .node(type: "ConfigurationValue", member: "null", fields: [:]) + case .array(let value): + .node(type: "ConfigurationValue", member: "array", fields: ["value": value.constructionValue]) + case .object(let value): + .node( + type: "ConfigurationValue", member: "object", fields: ["value": value.constructionValue]) + } + } +} + +public enum HookEvent: Sendable, Equatable { + case beforeTool + case afterTool + case sessionStart + case sessionEnd + case native(String) +} + +extension HookEvent: ConstructionRepresentable { + package var constructionValue: ConstructionValue { + switch self { + case .beforeTool: .node(type: "HookEvent", member: "beforeTool", fields: [:]) + case .afterTool: .node(type: "HookEvent", member: "afterTool", fields: [:]) + case .sessionStart: .node(type: "HookEvent", member: "sessionStart", fields: [:]) + case .sessionEnd: .node(type: "HookEvent", member: "sessionEnd", fields: [:]) + case .native(let value): + .node(type: "HookEvent", member: "native", fields: ["value": value.constructionValue]) + } + } +} + +public enum PermissionOperation: Sendable, Equatable { + case read + case write + case execute + case tool(String) +} + +extension PermissionOperation: ConstructionRepresentable { + package var constructionValue: ConstructionValue { + switch self { + case .read: .node(type: "PermissionOperation", member: "read", fields: [:]) + case .write: .node(type: "PermissionOperation", member: "write", fields: [:]) + case .execute: .node(type: "PermissionOperation", member: "execute", fields: [:]) + case .tool(let value): + .node(type: "PermissionOperation", member: "tool", fields: ["value": value.constructionValue]) + } + } +} + +public enum IgnorePurpose: Sendable, Equatable { + case context + case indexing +} + +extension IgnorePurpose: ConstructionRepresentable { + package var constructionValue: ConstructionValue { + switch self { + case .context: .node(type: "IgnorePurpose", member: "context", fields: [:]) + case .indexing: .node(type: "IgnorePurpose", member: "indexing", fields: [:]) + } + } +} + +public enum PluginMode: Sendable, Equatable { + case native + case components +} + +extension PluginMode: ConstructionRepresentable { + package var constructionValue: ConstructionValue { + switch self { + case .native: .node(type: "PluginMode", member: "native", fields: [:]) + case .components: .node(type: "PluginMode", member: "components", fields: [:]) + } + } +} + +public enum ComponentKind: Sendable, Equatable { + case skills + case instructions + case mcpServer + case hook + case subagent + case command + case lspServer + case permissions + case ignore + case plugin +} + +extension ComponentKind: ConstructionRepresentable { + package var constructionValue: ConstructionValue { + switch self { + case .skills: .node(type: "ComponentKind", member: "skills", fields: [:]) + case .instructions: .node(type: "ComponentKind", member: "instructions", fields: [:]) + case .mcpServer: .node(type: "ComponentKind", member: "mcpServer", fields: [:]) + case .hook: .node(type: "ComponentKind", member: "hook", fields: [:]) + case .subagent: .node(type: "ComponentKind", member: "subagent", fields: [:]) + case .command: .node(type: "ComponentKind", member: "command", fields: [:]) + case .lspServer: .node(type: "ComponentKind", member: "lspServer", fields: [:]) + case .permissions: .node(type: "ComponentKind", member: "permissions", fields: [:]) + case .ignore: .node(type: "ComponentKind", member: "ignore", fields: [:]) + case .plugin: .node(type: "ComponentKind", member: "plugin", fields: [:]) + } + } +} + +public enum ComponentReference: Sendable, Equatable { + case skill(name: String) + case instruction(name: String) + case mcpServer(name: String) + case hook(name: String) + case subagent(name: String) + case command(name: String) + case lspServer(name: String) + case permissions(name: String) + case ignore(name: String) + case plugin(name: String) +} + +extension ComponentReference: ConstructionRepresentable { + package var constructionValue: ConstructionValue { + switch self { + case .skill(let name): + .node(type: "ComponentReference", member: "skill", fields: ["name": name.constructionValue]) + case .instruction(let name): + .node( + type: "ComponentReference", member: "instruction", fields: ["name": name.constructionValue]) + case .mcpServer(let name): + .node( + type: "ComponentReference", member: "mcpServer", fields: ["name": name.constructionValue]) + case .hook(let name): + .node(type: "ComponentReference", member: "hook", fields: ["name": name.constructionValue]) + case .subagent(let name): + .node( + type: "ComponentReference", member: "subagent", fields: ["name": name.constructionValue]) + case .command(let name): + .node(type: "ComponentReference", member: "command", fields: ["name": name.constructionValue]) + case .lspServer(let name): + .node( + type: "ComponentReference", member: "lspServer", fields: ["name": name.constructionValue]) + case .permissions(let name): + .node( + type: "ComponentReference", member: "permissions", fields: ["name": name.constructionValue]) + case .ignore(let name): + .node(type: "ComponentReference", member: "ignore", fields: ["name": name.constructionValue]) + case .plugin(let name): + .node(type: "ComponentReference", member: "plugin", fields: ["name": name.constructionValue]) + } + } +} + +public struct Condition: Sendable, Equatable { + private let storage: ConstructionValue + package var constructionValue: ConstructionValue { storage } + package init(value: ConstructionValue) { storage = value } + public static func when( + agents: [Agent]? = nil, scopes: [Scope]? = nil, platforms: [Platform]? = nil + ) -> Condition { + Self( + value: ConstructionValue.construct( + type: "Condition", member: "when", + fields: [ + "agents": agents.constructionValue, "scopes": scopes.constructionValue, + "platforms": platforms.constructionValue, + ])) + } +} +extension Condition: ConstructionRepresentable {} + +public struct Agents: Sendable, Equatable { + private let storage: ConstructionValue + package var constructionValue: ConstructionValue { storage } + package init(value: ConstructionValue) { storage = value } + public init( + defaultAgents: [Agent]? = nil, exports: [String] = [], sources: [Source] = [], + components: [Component] = [], groups: [ComponentGroup] = [], uses: [GroupReference] = [], + watch: [String] = [] + ) { + self.init( + value: ConstructionValue.construct( + type: "Agents", member: "Agents", + fields: [ + "defaultAgents": defaultAgents.constructionValue, "exports": exports.constructionValue, + "sources": sources.constructionValue, "components": components.constructionValue, + "groups": groups.constructionValue, "uses": uses.constructionValue, + "watch": watch.constructionValue, + ])) + } +} +extension Agents: ConstructionRepresentable {} + +public struct Source: Sendable, Equatable { + private let storage: ConstructionValue + package var constructionValue: ConstructionValue { storage } + package init(value: ConstructionValue) { storage = value } + public static func source(name: String, url: String, subpath: String? = nil) -> Source { + Self( + value: ConstructionValue.construct( + type: "Source", member: "source", + fields: [ + "name": name.constructionValue, "url": url.constructionValue, + "subpath": subpath.constructionValue, + ])) + } + public static func source(name: String, url: String, from: Version, subpath: String? = nil) + -> Source + { + Self( + value: ConstructionValue.construct( + type: "Source", member: "source", + fields: [ + "name": name.constructionValue, "url": url.constructionValue, + "from": from.constructionValue, "subpath": subpath.constructionValue, + ])) + } + public static func source(name: String, url: String, exact: Version, subpath: String? = nil) + -> Source + { + Self( + value: ConstructionValue.construct( + type: "Source", member: "source", + fields: [ + "name": name.constructionValue, "url": url.constructionValue, + "exact": exact.constructionValue, "subpath": subpath.constructionValue, + ])) + } + public static func source(name: String, url: String, branch: String, subpath: String? = nil) + -> Source + { + Self( + value: ConstructionValue.construct( + type: "Source", member: "source", + fields: [ + "name": name.constructionValue, "url": url.constructionValue, + "branch": branch.constructionValue, "subpath": subpath.constructionValue, + ])) + } + public static func source(name: String, url: String, revision: String, subpath: String? = nil) + -> Source + { + Self( + value: ConstructionValue.construct( + type: "Source", member: "source", + fields: [ + "name": name.constructionValue, "url": url.constructionValue, + "revision": revision.constructionValue, "subpath": subpath.constructionValue, + ])) + } + public static func source( + name: String, url: String, _ range: Range, subpath: String? = nil + ) -> Source { + Self( + value: ConstructionValue.construct( + type: "Source", member: "source", + fields: [ + "name": name.constructionValue, "url": url.constructionValue, + "range": range.constructionValue, "subpath": subpath.constructionValue, + ])) + } + public static func source(name: String, path: String, subpath: String? = nil) -> Source { + Self( + value: ConstructionValue.construct( + type: "Source", member: "source", + fields: [ + "name": name.constructionValue, "path": path.constructionValue, + "subpath": subpath.constructionValue, + ])) + } + public static func source(name: String, path: String, from: Version, subpath: String? = nil) + -> Source + { + Self( + value: ConstructionValue.construct( + type: "Source", member: "source", + fields: [ + "name": name.constructionValue, "path": path.constructionValue, + "from": from.constructionValue, "subpath": subpath.constructionValue, + ])) + } + public static func source(name: String, path: String, exact: Version, subpath: String? = nil) + -> Source + { + Self( + value: ConstructionValue.construct( + type: "Source", member: "source", + fields: [ + "name": name.constructionValue, "path": path.constructionValue, + "exact": exact.constructionValue, "subpath": subpath.constructionValue, + ])) + } + public static func source(name: String, path: String, branch: String, subpath: String? = nil) + -> Source + { + Self( + value: ConstructionValue.construct( + type: "Source", member: "source", + fields: [ + "name": name.constructionValue, "path": path.constructionValue, + "branch": branch.constructionValue, "subpath": subpath.constructionValue, + ])) + } + public static func source(name: String, path: String, revision: String, subpath: String? = nil) + -> Source + { + Self( + value: ConstructionValue.construct( + type: "Source", member: "source", + fields: [ + "name": name.constructionValue, "path": path.constructionValue, + "revision": revision.constructionValue, "subpath": subpath.constructionValue, + ])) + } + public static func source( + name: String, path: String, _ range: Range, subpath: String? = nil + ) -> Source { + Self( + value: ConstructionValue.construct( + type: "Source", member: "source", + fields: [ + "name": name.constructionValue, "path": path.constructionValue, + "range": range.constructionValue, "subpath": subpath.constructionValue, + ])) + } + public static func source(name: String, index: String, subpath: String? = nil) -> Source { + Self( + value: ConstructionValue.construct( + type: "Source", member: "source", + fields: [ + "name": name.constructionValue, "index": index.constructionValue, + "subpath": subpath.constructionValue, + ])) + } +} +extension Source: ConstructionRepresentable {} + +public struct ComponentGroup: Sendable, Equatable { + private let storage: ConstructionValue + package var constructionValue: ConstructionValue { storage } + package init(value: ConstructionValue) { storage = value } + public static func group( + name: String, components: [Component] = [], uses: [GroupReference] = [], + condition: Condition? = nil + ) -> ComponentGroup { + Self( + value: ConstructionValue.construct( + type: "ComponentGroup", member: "group", + fields: [ + "name": name.constructionValue, "components": components.constructionValue, + "uses": uses.constructionValue, "condition": condition.constructionValue, + ])) + } +} +extension ComponentGroup: ConstructionRepresentable {} + +public struct GroupReference: Sendable, Equatable, ExpressibleByStringLiteral { + private let storage: ConstructionValue + package var constructionValue: ConstructionValue { storage } + package init(value: ConstructionValue) { storage = value } + public init(stringLiteral value: String) { + self.init( + value: .construct( + type: "GroupReference", member: "group", + fields: ["name": .text(value), "source": .none, "condition": .none])) + } + public static func group(name: String, condition: Condition? = nil) -> GroupReference { + Self( + value: ConstructionValue.construct( + type: "GroupReference", member: "group", + fields: ["name": name.constructionValue, "condition": condition.constructionValue])) + } + public static func group(name: String, source: String, condition: Condition? = nil) + -> GroupReference + { + Self( + value: ConstructionValue.construct( + type: "GroupReference", member: "group", + fields: [ + "name": name.constructionValue, "source": source.constructionValue, + "condition": condition.constructionValue, + ])) + } +} +extension GroupReference: ConstructionRepresentable {} + +public struct SkillSelection: Sendable, Equatable, ExpressibleByArrayLiteral { + private let storage: ConstructionValue + package var constructionValue: ConstructionValue { storage } + package init(value: ConstructionValue) { storage = value } + public init(arrayLiteral elements: String...) { + self.init( + value: .node( + type: "SkillSelection", member: "names", fields: ["names": elements.constructionValue])) + } + public static var all: SkillSelection { + Self(value: .node(type: "SkillSelection", member: "all", fields: [:])) + } +} +extension SkillSelection: ConstructionRepresentable {} + +public struct SkillOverride: Sendable, Equatable { + private let storage: ConstructionValue + package var constructionValue: ConstructionValue { storage } + package init(value: ConstructionValue) { storage = value } + public static func skill(name: String, mode: InstallMode? = nil, agents: [Agent]? = nil) + -> SkillOverride + { + Self( + value: ConstructionValue.construct( + type: "SkillOverride", member: "skill", + fields: [ + "name": name.constructionValue, "mode": mode.constructionValue, + "agents": agents.constructionValue, + ])) + } +} +extension SkillOverride: ConstructionRepresentable {} + +public struct SectionReference: Sendable, Equatable, ExpressibleByStringLiteral { + private let storage: ConstructionValue + package var constructionValue: ConstructionValue { storage } + package init(value: ConstructionValue) { storage = value } + public init(stringLiteral value: String) { + self.init( + value: .construct( + type: "SectionReference", member: "section", + fields: ["name": .text(value), "source": .none, "condition": .none])) + } + public static func section(name: String, source: String? = nil, condition: Condition? = nil) + -> SectionReference + { + Self( + value: ConstructionValue.construct( + type: "SectionReference", member: "section", + fields: [ + "name": name.constructionValue, "source": source.constructionValue, + "condition": condition.constructionValue, + ])) + } +} +extension SectionReference: ConstructionRepresentable {} + +public struct ChatGPTPrompt: Sendable, Equatable { + private let storage: ConstructionValue + package var constructionValue: ConstructionValue { storage } + package init(value: ConstructionValue) { storage = value } + public static func prompt( + name: String, sections: [SectionReference], append: String? = nil, condition: Condition? = nil + ) -> ChatGPTPrompt { + Self( + value: ConstructionValue.construct( + type: "ChatGPTPrompt", member: "prompt", + fields: [ + "name": name.constructionValue, "sections": sections.constructionValue, + "append": append.constructionValue, "condition": condition.constructionValue, + ])) + } +} +extension ChatGPTPrompt: ConstructionRepresentable {} + +public struct Resource: Sendable, Equatable { + private let storage: ConstructionValue + package var constructionValue: ConstructionValue { storage } + package init(value: ConstructionValue) { storage = value } + public static func path(_ path: String, source: String? = nil) -> Resource { + Self( + value: ConstructionValue.construct( + type: "Resource", member: "path", + fields: ["path": path.constructionValue, "source": source.constructionValue])) + } +} +extension Resource: ConstructionRepresentable {} + +public struct PromptContent: Sendable, Equatable, ExpressibleByStringLiteral { + private let storage: ConstructionValue + package var constructionValue: ConstructionValue { storage } + package init(value: ConstructionValue) { storage = value } + public init(stringLiteral value: String) { + self.init( + value: .node(type: "PromptContent", member: "literal", fields: ["value": .text(value)])) + } + public static func file(_ path: String, source: String? = nil) -> PromptContent { + Self( + value: ConstructionValue.construct( + type: "PromptContent", member: "file", + fields: ["path": path.constructionValue, "source": source.constructionValue])) + } +} +extension PromptContent: ConstructionRepresentable {} + +public struct ExecutableInvocation: Sendable, Equatable { + private let storage: ConstructionValue + package var constructionValue: ConstructionValue { storage } + package init(value: ConstructionValue) { storage = value } + public static func executable( + _ executable: String, arguments: [String] = [], environment: [String: RuntimeValue] = [:], + workingDirectory: Resource? = nil + ) -> ExecutableInvocation { + Self( + value: ConstructionValue.construct( + type: "ExecutableInvocation", member: "executable", + fields: [ + "executable": executable.constructionValue, "arguments": arguments.constructionValue, + "environment": environment.constructionValue, + "workingDirectory": workingDirectory.constructionValue, + ])) + } +} +extension ExecutableInvocation: ConstructionRepresentable {} + +public struct MCPTransport: Sendable, Equatable { + private let storage: ConstructionValue + package var constructionValue: ConstructionValue { storage } + package init(value: ConstructionValue) { storage = value } + public static func stdio( + _ executable: String, arguments: [String] = [], environment: [String: RuntimeValue] = [:], + workingDirectory: Resource? = nil + ) -> MCPTransport { + Self( + value: ConstructionValue.construct( + type: "MCPTransport", member: "stdio", + fields: [ + "executable": executable.constructionValue, "arguments": arguments.constructionValue, + "environment": environment.constructionValue, + "workingDirectory": workingDirectory.constructionValue, + ])) + } + public static func streamableHTTP(url: String, headers: [String: RuntimeValue] = [:]) + -> MCPTransport + { + Self( + value: ConstructionValue.construct( + type: "MCPTransport", member: "streamableHTTP", + fields: ["url": url.constructionValue, "headers": headers.constructionValue])) + } + public static func sse(url: String, headers: [String: RuntimeValue] = [:]) -> MCPTransport { + Self( + value: ConstructionValue.construct( + type: "MCPTransport", member: "sse", + fields: ["url": url.constructionValue, "headers": headers.constructionValue])) + } +} +extension MCPTransport: ConstructionRepresentable {} + +public struct PromptParameter: Sendable, Equatable { + private let storage: ConstructionValue + package var constructionValue: ConstructionValue { storage } + package init(value: ConstructionValue) { storage = value } + public static func parameter(name: String, description: String, defaultValue: String? = nil) + -> PromptParameter + { + Self( + value: ConstructionValue.construct( + type: "PromptParameter", member: "parameter", + fields: [ + "name": name.constructionValue, "description": description.constructionValue, + "defaultValue": defaultValue.constructionValue, + ])) + } +} +extension PromptParameter: ConstructionRepresentable {} + +public struct PermissionRule: Sendable, Equatable { + private let storage: ConstructionValue + package var constructionValue: ConstructionValue { storage } + package init(value: ConstructionValue) { storage = value } + public static func allow(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule { + Self( + value: ConstructionValue.construct( + type: "PermissionRule", member: "allow", + fields: ["operation": operation.constructionValue, "pattern": pattern.constructionValue])) + } + public static func ask(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule { + Self( + value: ConstructionValue.construct( + type: "PermissionRule", member: "ask", + fields: ["operation": operation.constructionValue, "pattern": pattern.constructionValue])) + } + public static func deny(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule { + Self( + value: ConstructionValue.construct( + type: "PermissionRule", member: "deny", + fields: ["operation": operation.constructionValue, "pattern": pattern.constructionValue])) + } +} +extension PermissionRule: ConstructionRepresentable {} + +public struct Component: Sendable, Equatable { + private let storage: ConstructionValue + package var constructionValue: ConstructionValue { storage } + package init(value: ConstructionValue) { storage = value } + public static func skills( + source: String, select: SkillSelection = .all, exclude: [String] = [], mode: InstallMode? = nil, + overrides: [SkillOverride] = [], agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component { + Self( + value: ConstructionValue.construct( + type: "Component", member: "skills", + fields: [ + "source": source.constructionValue, "select": select.constructionValue, + "exclude": exclude.constructionValue, "mode": mode.constructionValue, + "overrides": overrides.constructionValue, "agents": agents.constructionValue, + "condition": condition.constructionValue, "native": native.constructionValue, + ])) + } + public static func instructions( + sections: [SectionReference] = [], chatGPT: [ChatGPTPrompt] = [], agents: [Agent]? = nil, + condition: Condition? = nil, native: NativeConfiguration = [:] + ) -> Component { + Self( + value: ConstructionValue.construct( + type: "Component", member: "instructions", + fields: [ + "sections": sections.constructionValue, "chatGPT": chatGPT.constructionValue, + "agents": agents.constructionValue, "condition": condition.constructionValue, + "native": native.constructionValue, + ])) + } + public static func mcpServer( + name: String, transport: MCPTransport, agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component { + Self( + value: ConstructionValue.construct( + type: "Component", member: "mcpServer", + fields: [ + "name": name.constructionValue, "transport": transport.constructionValue, + "agents": agents.constructionValue, "condition": condition.constructionValue, + "native": native.constructionValue, + ])) + } + public static func hook( + name: String, event: HookEvent, run: ExecutableInvocation, matcher: String? = nil, + timeoutSeconds: Int? = nil, agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component { + Self( + value: ConstructionValue.construct( + type: "Component", member: "hook", + fields: [ + "name": name.constructionValue, "event": event.constructionValue, + "run": run.constructionValue, "matcher": matcher.constructionValue, + "timeoutSeconds": timeoutSeconds.constructionValue, "agents": agents.constructionValue, + "condition": condition.constructionValue, "native": native.constructionValue, + ])) + } + public static func subagent( + name: String, description: String, prompt: PromptContent, model: String? = nil, + tools: [String]? = nil, agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component { + Self( + value: ConstructionValue.construct( + type: "Component", member: "subagent", + fields: [ + "name": name.constructionValue, "description": description.constructionValue, + "prompt": prompt.constructionValue, "model": model.constructionValue, + "tools": tools.constructionValue, "agents": agents.constructionValue, + "condition": condition.constructionValue, "native": native.constructionValue, + ])) + } + public static func command( + name: String, description: String, prompt: PromptContent, parameters: [PromptParameter] = [], + agents: [Agent]? = nil, condition: Condition? = nil, native: NativeConfiguration = [:] + ) -> Component { + Self( + value: ConstructionValue.construct( + type: "Component", member: "command", + fields: [ + "name": name.constructionValue, "description": description.constructionValue, + "prompt": prompt.constructionValue, "parameters": parameters.constructionValue, + "agents": agents.constructionValue, "condition": condition.constructionValue, + "native": native.constructionValue, + ])) + } + public static func lspServer( + name: String, run: ExecutableInvocation, languages: [String: String], + initializationOptions: [String: ConfigurationValue] = [:], agents: [Agent]? = nil, + condition: Condition? = nil, native: NativeConfiguration = [:] + ) -> Component { + Self( + value: ConstructionValue.construct( + type: "Component", member: "lspServer", + fields: [ + "name": name.constructionValue, "run": run.constructionValue, + "languages": languages.constructionValue, + "initializationOptions": initializationOptions.constructionValue, + "agents": agents.constructionValue, "condition": condition.constructionValue, + "native": native.constructionValue, + ])) + } + public static func permissions( + name: String, rules: [PermissionRule], agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component { + Self( + value: ConstructionValue.construct( + type: "Component", member: "permissions", + fields: [ + "name": name.constructionValue, "rules": rules.constructionValue, + "agents": agents.constructionValue, "condition": condition.constructionValue, + "native": native.constructionValue, + ])) + } + public static func ignore( + name: String, patterns: [String], purpose: IgnorePurpose = .context, agents: [Agent]? = nil, + condition: Condition? = nil, native: NativeConfiguration = [:] + ) -> Component { + Self( + value: ConstructionValue.construct( + type: "Component", member: "ignore", + fields: [ + "name": name.constructionValue, "patterns": patterns.constructionValue, + "purpose": purpose.constructionValue, "agents": agents.constructionValue, + "condition": condition.constructionValue, "native": native.constructionValue, + ])) + } + public static func plugin( + name: String, path: String, source: String, mode: PluginMode = .components, + select: [ComponentKind]? = nil, exclude: [ComponentReference] = [], agents: [Agent]? = nil, + condition: Condition? = nil, native: NativeConfiguration = [:] + ) -> Component { + Self( + value: ConstructionValue.construct( + type: "Component", member: "plugin", + fields: [ + "name": name.constructionValue, "path": path.constructionValue, + "source": source.constructionValue, "mode": mode.constructionValue, + "select": select.constructionValue, "exclude": exclude.constructionValue, + "agents": agents.constructionValue, "condition": condition.constructionValue, + "native": native.constructionValue, + ])) + } +} +extension Component: ConstructionRepresentable {} + +public typealias NativeConfiguration = [String: [String: ConfigurationValue]] diff --git a/Sources/AgentsDescription/VocabularyInventory.swift b/Sources/AgentsDescription/VocabularyInventory.swift new file mode 100644 index 0000000..dbaa3ce --- /dev/null +++ b/Sources/AgentsDescription/VocabularyInventory.swift @@ -0,0 +1,802 @@ +// Generated from Scripts/ManifestVocabulary.json. Run Scripts/generate-manifest-vocabulary.py. + +package enum Vocabulary { + package static let typeNames: Set = [ + "String", "Int", "Bool", "Version", "NativeConfiguration", "Agent", "Scope", "Platform", + "InstallMode", "RuntimeValue", "ConfigurationValue", "HookEvent", "PermissionOperation", + "IgnorePurpose", "PluginMode", "ComponentKind", "ComponentReference", "Condition", "Agents", + "Source", "ComponentGroup", "GroupReference", "SkillSelection", "SkillOverride", + "SectionReference", "ChatGPTPrompt", "Resource", "PromptContent", "ExecutableInvocation", + "MCPTransport", "PromptParameter", "PermissionRule", "Component", + ] + package static let signatures: [ConstructionSignature] = [ + ConstructionSignature( + type: "Condition", member: "when", + parameters: [ + ConstructionParameter( + label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), + defaultValue: (nil as [Agent]?).constructionValue), + ConstructionParameter( + label: "scopes", name: "scopes", type: .optional(.array(.named("Scope"))), + defaultValue: (nil as [Scope]?).constructionValue), + ConstructionParameter( + label: "platforms", name: "platforms", type: .optional(.array(.named("Platform"))), + defaultValue: (nil as [Platform]?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Agents", member: "Agents", + parameters: [ + ConstructionParameter( + label: "defaultAgents", name: "defaultAgents", type: .optional(.array(.named("Agent"))), + defaultValue: (nil as [Agent]?).constructionValue), + ConstructionParameter( + label: "exports", name: "exports", type: .array(.named("String")), + defaultValue: ([] as [String]).constructionValue), + ConstructionParameter( + label: "sources", name: "sources", type: .array(.named("Source")), + defaultValue: ([] as [Source]).constructionValue), + ConstructionParameter( + label: "components", name: "components", type: .array(.named("Component")), + defaultValue: ([] as [Component]).constructionValue), + ConstructionParameter( + label: "groups", name: "groups", type: .array(.named("ComponentGroup")), + defaultValue: ([] as [ComponentGroup]).constructionValue), + ConstructionParameter( + label: "uses", name: "uses", type: .array(.named("GroupReference")), + defaultValue: ([] as [GroupReference]).constructionValue), + ConstructionParameter( + label: "watch", name: "watch", type: .array(.named("String")), + defaultValue: ([] as [String]).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Source", member: "source", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "subpath", name: "subpath", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Source", member: "source", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "from", name: "from", type: .named("Version"), defaultValue: nil), + ConstructionParameter( + label: "subpath", name: "subpath", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Source", member: "source", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "exact", name: "exact", type: .named("Version"), defaultValue: nil), + ConstructionParameter( + label: "subpath", name: "subpath", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Source", member: "source", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "branch", name: "branch", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "subpath", name: "subpath", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Source", member: "source", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "revision", name: "revision", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "subpath", name: "subpath", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Source", member: "source", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "_", name: "range", type: .named("VersionRange"), defaultValue: nil), + ConstructionParameter( + label: "subpath", name: "subpath", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Source", member: "source", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "path", name: "path", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "subpath", name: "subpath", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Source", member: "source", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "path", name: "path", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "from", name: "from", type: .named("Version"), defaultValue: nil), + ConstructionParameter( + label: "subpath", name: "subpath", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Source", member: "source", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "path", name: "path", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "exact", name: "exact", type: .named("Version"), defaultValue: nil), + ConstructionParameter( + label: "subpath", name: "subpath", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Source", member: "source", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "path", name: "path", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "branch", name: "branch", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "subpath", name: "subpath", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Source", member: "source", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "path", name: "path", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "revision", name: "revision", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "subpath", name: "subpath", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Source", member: "source", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "path", name: "path", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "_", name: "range", type: .named("VersionRange"), defaultValue: nil), + ConstructionParameter( + label: "subpath", name: "subpath", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Source", member: "source", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "index", name: "index", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "subpath", name: "subpath", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "ComponentGroup", member: "group", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "components", name: "components", type: .array(.named("Component")), + defaultValue: ([] as [Component]).constructionValue), + ConstructionParameter( + label: "uses", name: "uses", type: .array(.named("GroupReference")), + defaultValue: ([] as [GroupReference]).constructionValue), + ConstructionParameter( + label: "condition", name: "condition", type: .optional(.named("Condition")), + defaultValue: (nil as Condition?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "GroupReference", member: "group", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "condition", name: "condition", type: .optional(.named("Condition")), + defaultValue: (nil as Condition?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "GroupReference", member: "group", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "source", name: "source", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "condition", name: "condition", type: .optional(.named("Condition")), + defaultValue: (nil as Condition?).constructionValue), + ], callable: true), + ConstructionSignature(type: "SkillSelection", member: "all", parameters: [], callable: false), + ConstructionSignature( + type: "SkillOverride", member: "skill", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "mode", name: "mode", type: .optional(.named("InstallMode")), + defaultValue: (nil as InstallMode?).constructionValue), + ConstructionParameter( + label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), + defaultValue: (nil as [Agent]?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "SectionReference", member: "section", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "source", name: "source", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ConstructionParameter( + label: "condition", name: "condition", type: .optional(.named("Condition")), + defaultValue: (nil as Condition?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "ChatGPTPrompt", member: "prompt", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "sections", name: "sections", type: .array(.named("SectionReference")), + defaultValue: nil), + ConstructionParameter( + label: "append", name: "append", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ConstructionParameter( + label: "condition", name: "condition", type: .optional(.named("Condition")), + defaultValue: (nil as Condition?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Resource", member: "path", + parameters: [ + ConstructionParameter(label: "_", name: "path", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "source", name: "source", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "PromptContent", member: "file", + parameters: [ + ConstructionParameter(label: "_", name: "path", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "source", name: "source", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "ExecutableInvocation", member: "executable", + parameters: [ + ConstructionParameter( + label: "_", name: "executable", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "arguments", name: "arguments", type: .array(.named("String")), + defaultValue: ([] as [String]).constructionValue), + ConstructionParameter( + label: "environment", name: "environment", type: .dictionary(.named("RuntimeValue")), + defaultValue: ([:] as [String: RuntimeValue]).constructionValue), + ConstructionParameter( + label: "workingDirectory", name: "workingDirectory", type: .optional(.named("Resource")), + defaultValue: (nil as Resource?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "MCPTransport", member: "stdio", + parameters: [ + ConstructionParameter( + label: "_", name: "executable", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "arguments", name: "arguments", type: .array(.named("String")), + defaultValue: ([] as [String]).constructionValue), + ConstructionParameter( + label: "environment", name: "environment", type: .dictionary(.named("RuntimeValue")), + defaultValue: ([:] as [String: RuntimeValue]).constructionValue), + ConstructionParameter( + label: "workingDirectory", name: "workingDirectory", type: .optional(.named("Resource")), + defaultValue: (nil as Resource?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "MCPTransport", member: "streamableHTTP", + parameters: [ + ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "headers", name: "headers", type: .dictionary(.named("RuntimeValue")), + defaultValue: ([:] as [String: RuntimeValue]).constructionValue), + ], callable: true), + ConstructionSignature( + type: "MCPTransport", member: "sse", + parameters: [ + ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "headers", name: "headers", type: .dictionary(.named("RuntimeValue")), + defaultValue: ([:] as [String: RuntimeValue]).constructionValue), + ], callable: true), + ConstructionSignature( + type: "PromptParameter", member: "parameter", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "description", name: "description", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "defaultValue", name: "defaultValue", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ], callable: true), + ConstructionSignature( + type: "PermissionRule", member: "allow", + parameters: [ + ConstructionParameter( + label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil), + ConstructionParameter( + label: "_", name: "pattern", type: .named("String"), defaultValue: nil), + ], callable: true), + ConstructionSignature( + type: "PermissionRule", member: "ask", + parameters: [ + ConstructionParameter( + label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil), + ConstructionParameter( + label: "_", name: "pattern", type: .named("String"), defaultValue: nil), + ], callable: true), + ConstructionSignature( + type: "PermissionRule", member: "deny", + parameters: [ + ConstructionParameter( + label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil), + ConstructionParameter( + label: "_", name: "pattern", type: .named("String"), defaultValue: nil), + ], callable: true), + ConstructionSignature( + type: "Component", member: "skills", + parameters: [ + ConstructionParameter( + label: "source", name: "source", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "select", name: "select", type: .named("SkillSelection"), + defaultValue: (.all as SkillSelection).constructionValue), + ConstructionParameter( + label: "exclude", name: "exclude", type: .array(.named("String")), + defaultValue: ([] as [String]).constructionValue), + ConstructionParameter( + label: "mode", name: "mode", type: .optional(.named("InstallMode")), + defaultValue: (nil as InstallMode?).constructionValue), + ConstructionParameter( + label: "overrides", name: "overrides", type: .array(.named("SkillOverride")), + defaultValue: ([] as [SkillOverride]).constructionValue), + ConstructionParameter( + label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), + defaultValue: (nil as [Agent]?).constructionValue), + ConstructionParameter( + label: "condition", name: "condition", type: .optional(.named("Condition")), + defaultValue: (nil as Condition?).constructionValue), + ConstructionParameter( + label: "native", name: "native", + type: .dictionary(.dictionary(.named("ConfigurationValue"))), + defaultValue: ([:] as NativeConfiguration).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Component", member: "instructions", + parameters: [ + ConstructionParameter( + label: "sections", name: "sections", type: .array(.named("SectionReference")), + defaultValue: ([] as [SectionReference]).constructionValue), + ConstructionParameter( + label: "chatGPT", name: "chatGPT", type: .array(.named("ChatGPTPrompt")), + defaultValue: ([] as [ChatGPTPrompt]).constructionValue), + ConstructionParameter( + label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), + defaultValue: (nil as [Agent]?).constructionValue), + ConstructionParameter( + label: "condition", name: "condition", type: .optional(.named("Condition")), + defaultValue: (nil as Condition?).constructionValue), + ConstructionParameter( + label: "native", name: "native", + type: .dictionary(.dictionary(.named("ConfigurationValue"))), + defaultValue: ([:] as NativeConfiguration).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Component", member: "mcpServer", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "transport", name: "transport", type: .named("MCPTransport"), defaultValue: nil), + ConstructionParameter( + label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), + defaultValue: (nil as [Agent]?).constructionValue), + ConstructionParameter( + label: "condition", name: "condition", type: .optional(.named("Condition")), + defaultValue: (nil as Condition?).constructionValue), + ConstructionParameter( + label: "native", name: "native", + type: .dictionary(.dictionary(.named("ConfigurationValue"))), + defaultValue: ([:] as NativeConfiguration).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Component", member: "hook", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "event", name: "event", type: .named("HookEvent"), defaultValue: nil), + ConstructionParameter( + label: "run", name: "run", type: .named("ExecutableInvocation"), defaultValue: nil), + ConstructionParameter( + label: "matcher", name: "matcher", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ConstructionParameter( + label: "timeoutSeconds", name: "timeoutSeconds", type: .optional(.named("Int")), + defaultValue: (nil as Int?).constructionValue), + ConstructionParameter( + label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), + defaultValue: (nil as [Agent]?).constructionValue), + ConstructionParameter( + label: "condition", name: "condition", type: .optional(.named("Condition")), + defaultValue: (nil as Condition?).constructionValue), + ConstructionParameter( + label: "native", name: "native", + type: .dictionary(.dictionary(.named("ConfigurationValue"))), + defaultValue: ([:] as NativeConfiguration).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Component", member: "subagent", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "description", name: "description", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "prompt", name: "prompt", type: .named("PromptContent"), defaultValue: nil), + ConstructionParameter( + label: "model", name: "model", type: .optional(.named("String")), + defaultValue: (nil as String?).constructionValue), + ConstructionParameter( + label: "tools", name: "tools", type: .optional(.array(.named("String"))), + defaultValue: (nil as [String]?).constructionValue), + ConstructionParameter( + label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), + defaultValue: (nil as [Agent]?).constructionValue), + ConstructionParameter( + label: "condition", name: "condition", type: .optional(.named("Condition")), + defaultValue: (nil as Condition?).constructionValue), + ConstructionParameter( + label: "native", name: "native", + type: .dictionary(.dictionary(.named("ConfigurationValue"))), + defaultValue: ([:] as NativeConfiguration).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Component", member: "command", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "description", name: "description", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "prompt", name: "prompt", type: .named("PromptContent"), defaultValue: nil), + ConstructionParameter( + label: "parameters", name: "parameters", type: .array(.named("PromptParameter")), + defaultValue: ([] as [PromptParameter]).constructionValue), + ConstructionParameter( + label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), + defaultValue: (nil as [Agent]?).constructionValue), + ConstructionParameter( + label: "condition", name: "condition", type: .optional(.named("Condition")), + defaultValue: (nil as Condition?).constructionValue), + ConstructionParameter( + label: "native", name: "native", + type: .dictionary(.dictionary(.named("ConfigurationValue"))), + defaultValue: ([:] as NativeConfiguration).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Component", member: "lspServer", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "run", name: "run", type: .named("ExecutableInvocation"), defaultValue: nil), + ConstructionParameter( + label: "languages", name: "languages", type: .dictionary(.named("String")), + defaultValue: nil), + ConstructionParameter( + label: "initializationOptions", name: "initializationOptions", + type: .dictionary(.named("ConfigurationValue")), + defaultValue: ([:] as [String: ConfigurationValue]).constructionValue), + ConstructionParameter( + label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), + defaultValue: (nil as [Agent]?).constructionValue), + ConstructionParameter( + label: "condition", name: "condition", type: .optional(.named("Condition")), + defaultValue: (nil as Condition?).constructionValue), + ConstructionParameter( + label: "native", name: "native", + type: .dictionary(.dictionary(.named("ConfigurationValue"))), + defaultValue: ([:] as NativeConfiguration).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Component", member: "permissions", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "rules", name: "rules", type: .array(.named("PermissionRule")), defaultValue: nil), + ConstructionParameter( + label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), + defaultValue: (nil as [Agent]?).constructionValue), + ConstructionParameter( + label: "condition", name: "condition", type: .optional(.named("Condition")), + defaultValue: (nil as Condition?).constructionValue), + ConstructionParameter( + label: "native", name: "native", + type: .dictionary(.dictionary(.named("ConfigurationValue"))), + defaultValue: ([:] as NativeConfiguration).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Component", member: "ignore", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "patterns", name: "patterns", type: .array(.named("String")), defaultValue: nil), + ConstructionParameter( + label: "purpose", name: "purpose", type: .named("IgnorePurpose"), + defaultValue: (.context as IgnorePurpose).constructionValue), + ConstructionParameter( + label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), + defaultValue: (nil as [Agent]?).constructionValue), + ConstructionParameter( + label: "condition", name: "condition", type: .optional(.named("Condition")), + defaultValue: (nil as Condition?).constructionValue), + ConstructionParameter( + label: "native", name: "native", + type: .dictionary(.dictionary(.named("ConfigurationValue"))), + defaultValue: ([:] as NativeConfiguration).constructionValue), + ], callable: true), + ConstructionSignature( + type: "Component", member: "plugin", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "path", name: "path", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "source", name: "source", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "mode", name: "mode", type: .named("PluginMode"), + defaultValue: (.components as PluginMode).constructionValue), + ConstructionParameter( + label: "select", name: "select", type: .optional(.array(.named("ComponentKind"))), + defaultValue: (nil as [ComponentKind]?).constructionValue), + ConstructionParameter( + label: "exclude", name: "exclude", type: .array(.named("ComponentReference")), + defaultValue: ([] as [ComponentReference]).constructionValue), + ConstructionParameter( + label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), + defaultValue: (nil as [Agent]?).constructionValue), + ConstructionParameter( + label: "condition", name: "condition", type: .optional(.named("Condition")), + defaultValue: (nil as Condition?).constructionValue), + ConstructionParameter( + label: "native", name: "native", + type: .dictionary(.dictionary(.named("ConfigurationValue"))), + defaultValue: ([:] as NativeConfiguration).constructionValue), + ], callable: true), + ConstructionSignature(type: "Agent", member: "claudeCode", parameters: [], callable: false), + ConstructionSignature(type: "Agent", member: "codex", parameters: [], callable: false), + ConstructionSignature(type: "Agent", member: "cursor", parameters: [], callable: false), + ConstructionSignature(type: "Agent", member: "geminiCLI", parameters: [], callable: false), + ConstructionSignature(type: "Agent", member: "openCode", parameters: [], callable: false), + ConstructionSignature(type: "Scope", member: "project", parameters: [], callable: false), + ConstructionSignature(type: "Scope", member: "user", parameters: [], callable: false), + ConstructionSignature(type: "Platform", member: "macOS", parameters: [], callable: false), + ConstructionSignature(type: "Platform", member: "linux", parameters: [], callable: false), + ConstructionSignature(type: "InstallMode", member: "link", parameters: [], callable: false), + ConstructionSignature(type: "InstallMode", member: "copy", parameters: [], callable: false), + ConstructionSignature(type: "InstallMode", member: "edit", parameters: [], callable: false), + ConstructionSignature( + type: "RuntimeValue", member: "literal", + parameters: [ + ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "RuntimeValue", member: "environment", + parameters: [ + ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "RuntimeValue", member: "secret", + parameters: [ + ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "ConfigurationValue", member: "string", + parameters: [ + ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "ConfigurationValue", member: "integer", + parameters: [ + ConstructionParameter(label: "_", name: "value", type: .named("Int"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "ConfigurationValue", member: "decimal", + parameters: [ + ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "ConfigurationValue", member: "boolean", + parameters: [ + ConstructionParameter(label: "_", name: "value", type: .named("Bool"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "ConfigurationValue", member: "null", parameters: [], callable: false), + ConstructionSignature( + type: "ConfigurationValue", member: "array", + parameters: [ + ConstructionParameter( + label: "_", name: "value", type: .array(.named("ConfigurationValue")), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "ConfigurationValue", member: "object", + parameters: [ + ConstructionParameter( + label: "_", name: "value", type: .dictionary(.named("ConfigurationValue")), + defaultValue: nil) + ], callable: true), + ConstructionSignature(type: "HookEvent", member: "beforeTool", parameters: [], callable: false), + ConstructionSignature(type: "HookEvent", member: "afterTool", parameters: [], callable: false), + ConstructionSignature( + type: "HookEvent", member: "sessionStart", parameters: [], callable: false), + ConstructionSignature(type: "HookEvent", member: "sessionEnd", parameters: [], callable: false), + ConstructionSignature( + type: "HookEvent", member: "native", + parameters: [ + ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "PermissionOperation", member: "read", parameters: [], callable: false), + ConstructionSignature( + type: "PermissionOperation", member: "write", parameters: [], callable: false), + ConstructionSignature( + type: "PermissionOperation", member: "execute", parameters: [], callable: false), + ConstructionSignature( + type: "PermissionOperation", member: "tool", + parameters: [ + ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "IgnorePurpose", member: "context", parameters: [], callable: false), + ConstructionSignature( + type: "IgnorePurpose", member: "indexing", parameters: [], callable: false), + ConstructionSignature(type: "PluginMode", member: "native", parameters: [], callable: false), + ConstructionSignature( + type: "PluginMode", member: "components", parameters: [], callable: false), + ConstructionSignature(type: "ComponentKind", member: "skills", parameters: [], callable: false), + ConstructionSignature( + type: "ComponentKind", member: "instructions", parameters: [], callable: false), + ConstructionSignature( + type: "ComponentKind", member: "mcpServer", parameters: [], callable: false), + ConstructionSignature(type: "ComponentKind", member: "hook", parameters: [], callable: false), + ConstructionSignature( + type: "ComponentKind", member: "subagent", parameters: [], callable: false), + ConstructionSignature( + type: "ComponentKind", member: "command", parameters: [], callable: false), + ConstructionSignature( + type: "ComponentKind", member: "lspServer", parameters: [], callable: false), + ConstructionSignature( + type: "ComponentKind", member: "permissions", parameters: [], callable: false), + ConstructionSignature(type: "ComponentKind", member: "ignore", parameters: [], callable: false), + ConstructionSignature(type: "ComponentKind", member: "plugin", parameters: [], callable: false), + ConstructionSignature( + type: "ComponentReference", member: "skill", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "ComponentReference", member: "instruction", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "ComponentReference", member: "mcpServer", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "ComponentReference", member: "hook", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "ComponentReference", member: "subagent", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "ComponentReference", member: "command", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "ComponentReference", member: "lspServer", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "ComponentReference", member: "permissions", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "ComponentReference", member: "ignore", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "ComponentReference", member: "plugin", + parameters: [ + ConstructionParameter( + label: "name", name: "name", type: .named("String"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "VersionRange", member: "upToNextMajor", + parameters: [ + ConstructionParameter( + label: "from", name: "from", type: .named("Version"), defaultValue: nil) + ], callable: true), + ConstructionSignature( + type: "VersionRange", member: "upToNextMinor", + parameters: [ + ConstructionParameter( + label: "from", name: "from", type: .named("Version"), defaultValue: nil) + ], callable: true), + ] + package static let literalTypes: [String: Set] = [ + "SectionReference": ["string"], + "GroupReference": ["string"], + "PromptContent": ["string"], + "RuntimeValue": ["string"], + "SkillSelection": ["array"], + "ConfigurationValue": ["string", "integer", "boolean", "nil", "array", "dictionary"], + "Version": ["string"], + ] +} diff --git a/Sources/AgentsManifest/Admission.swift b/Sources/AgentsManifest/Admission.swift new file mode 100644 index 0000000..89fa81d --- /dev/null +++ b/Sources/AgentsManifest/Admission.swift @@ -0,0 +1,729 @@ +import AgentsDescription +import Foundation + +package struct ProjectionEvent: Sendable, Equatable, Comparable, Codable { + package let start: Int + package let end: Int + package let kind: String + package let detail: String + package static func < (lhs: Self, rhs: Self) -> Bool { + if lhs.start != rhs.start { return lhs.start < rhs.start } + if lhs.end != rhs.end { return lhs.end < rhs.end } + if lhs.kind != rhs.kind { return lhs.kind < rhs.kind } + return lhs.detail < rhs.detail + } +} + +package struct Lexeme: Sendable { + package let text: String + package let range: Range + package let kind: String + package let decoded: String? +} + +package struct GrammarArgument: Sendable { + package let label: String + package let labelRange: Range? + package let value: Int +} + +package struct GrammarNode: Sendable { + package let kind: String + package let range: Range + package var text: String = "" + package var children: [Int] = [] + package var arguments: [GrammarArgument] = [] + package var keys: [Lexeme] = [] +} + +package struct GrammarDeclaration: Sendable { + package let name: String + package let nameRange: Range + package let type: ConstructionType? + package let expression: Int + package let range: Range +} + +package struct Admission: Sendable { + package let nodes: [GrammarNode] + package let declarations: [GrammarDeclaration] + package let tokens: [Lexeme] + package let comments: [Range] + package let projection: [ProjectionEvent] + package let reservation: Int +} + +package final class Recognizer { + private let source: SourceText + private let bytes: [UInt8] + private var tokens: [Lexeme] = [] + private var comments: [Range] = [] + private var index = 0 + private var nodes: [GrammarNode] = [] + private var events: [ProjectionEvent] = [] + private var depth = 0 + private var square = 0 + private var literalUnits = 0 + private let reserved: Set = Set( + "_ Any Self as associatedtype break case catch class continue default defer deinit do else enum extension fallthrough false fileprivate for func guard if import in init inout internal is let nil open operator precedencegroup private protocol public repeat rethrows return self static struct subscript super switch throw throws true try typealias var where while" + .split(separator: " ").map(String.init)) + private let prefixes: Set = ["await", "copy", "consume", "each", "unsafe"] + + package init(source: SourceText) { + self.source = source + bytes = source.bytes + } + + private func fail(_ message: String, at offset: Int, code: String = "manifest.syntax") + -> ManifestFailure + { + var metrics = FrontEndMetrics() + metrics.tokens = tokens.count + metrics.syntaxReservation = 16 + 4 * (tokens.count + literalUnits) + return ManifestFailure( + ManifestDiagnostic(code: code, message: message, span: source.span(offset.. Admission { + if bytes.count > 2_097_152 { + throw fail("input byte limit", at: 2_097_152, code: "manifest.limit") + } + try validateUTF8() + let header = bytes.starts(with: [239, 187, 191]) ? 3 : 0 + try version(at: header) + try lex(from: header) + let start = try take("import").range.lowerBound + let module = try take("AgentsDescription") + emit("import", start.. 1 || parts[0] > "1" || parts[0] == "1" && parts[1] != "0" + throw fail( + newer + ? "unsupported language version; upgrade the reader" + : "unsupported language version; use a supported converter", at: start, + code: "manifest.version.unsupported") + } + } + + private func validateUTF8() throws { + var i = 0 + while i < bytes.count { + let b = bytes[i] + if b < 128 { + i += 1 + continue + } + let length: Int + if b >= 194 && b <= 223 { + length = 2 + } else if b >= 224 && b <= 239 { + length = 3 + } else if b >= 240 && b <= 244 { + length = 4 + } else { + throw fail("invalid UTF-8", at: i) + } + guard i + length <= bytes.count else { throw fail("invalid UTF-8", at: i) } + for j in 1.. 191 { + throw fail("invalid UTF-8", at: i + j) + } + let next = bytes[i + 1] + if b == 224 && next < 160 || b == 237 && next >= 160 || b == 240 && next < 144 + || b == 244 && next >= 144 + { + throw fail("invalid UTF-8 scalar", at: i) + } + i += length + } + } + + private func isSpace(_ byte: UInt8) -> Bool { + byte == 32 || byte == 9 || byte == 10 || byte == 13 + } + private func isHead(_ byte: UInt8) -> Bool { + byte == 95 || (65...90).contains(byte) || (97...122).contains(byte) + } + private func starts(_ spelling: [UInt8], at offset: Int) -> Bool { + offset + spelling.count <= bytes.count + && bytes[offset..<(offset + spelling.count)].elementsEqual(spelling) + } + private func canonical(_ op: String) -> String { + op == "=" ? "let value = -1" : op == "+" ? "left + right" : "\"1.2.0\"..<\"1.8.0\"" + } + + private func lex(from start: Int) throws { + var i = start + while i < bytes.count { + if isSpace(bytes[i]) { + i += 1 + continue + } + if starts([47, 47], at: i) { + let first = i + i += 2 + while i < bytes.count && bytes[i] != 10 && bytes[i] != 13 { i += 1 } + let range = first.. 0 { + if starts([47, 42], at: i) { + level += 1 + if level > 20 { throw fail("block comment depth", at: i, code: "manifest.limit") } + i += 2 + } else if starts([42, 47], at: i) { + level -= 1 + i += 2 + } else { + i += 1 + } + } + if level != 0 { throw fail("unterminated comment", at: first) } + comments.append(first.. 0 && isSpace(bytes[first - 1])) != (i < bytes.count && isSpace(bytes[i])) { + throw fail( + "range requires balanced whitespace; canonical spelling: \(canonical(kind))", at: first) + } + } else if [40, 41, 91, 93, 44, 58, 46, 61, 43, 45].contains(bytes[i]) { + let byte = bytes[i] + i += 1 + kind = String(UnicodeScalar(byte)) + if byte == 61 || byte == 43 { + if first == 0 || i == bytes.count || !isSpace(bytes[first - 1]) || !isSpace(bytes[i]) { + throw fail( + "operator requires whitespace on both sides; canonical spelling: \(canonical(kind))", + at: first) + } + } + if byte == 45 { + if i == bytes.count || !(48...57).contains(bytes[i]) || first == 0 + || !(isSpace(bytes[first - 1]) || [40, 91, 44, 58].contains(bytes[first - 1])) + { + throw fail( + "negative integer requires an adjacent sign and separated boundary; canonical spelling: let value = -1", + at: first) + } + } + } else { + throw fail("token outside the lexical grammar", at: i) + } + if tokens.count == 100_000 { throw fail("token count", at: first, code: "manifest.limit") } + if 16 + 4 * (tokens.count + 1 + literalUnits) > 100_000 { + throw fail("syntax storage reservation", at: first, code: "manifest.limit") + } + tokens.append( + Lexeme(text: source.spelling(first..= left.range.upperBound { + let op = ["=", "+", "..<"].contains(left.text) ? left : right + if ["=", "+", "..<"].contains(op.text) { + if comment.lowerBound == 0 || comment.upperBound == bytes.count + || !isSpace(bytes[comment.lowerBound - 1]) || !isSpace(bytes[comment.upperBound]) + { + throw fail( + "operator-adjacent comments require whitespace; canonical spelling: \(canonical(op.text))", + at: op.range.lowerBound) + } + } + } + ci += 1 + } + } + tokens.append(Lexeme(text: "", range: bytes.count.. (Int, String?) { + let multiline = starts([34, 34, 34], at: start) + let width = multiline ? 3 : 1 + var i = start + width + var body = i + if multiline { + guard i < bytes.count && (bytes[i] == 10 || bytes[i] == 13) else { + throw fail("multiline opener requires a newline", at: i) + } + if starts([13, 10], at: i) { i += 2 } else { i += 1 } + body = i + } + while i < bytes.count { + let byte = bytes[i] + if byte < 32 && byte != 9 && byte != 10 && byte != 13 { + throw fail("control scalar in string", at: i) + } + if !multiline && (byte == 10 || byte == 13) { + throw fail("newline in single-line string", at: i) + } + if byte == 92 { + let escape = i + i += 1 + if i < bytes.count && [48, 92, 116, 110, 114, 34, 39].contains(bytes[i]) { + i += 1 + continue + } + guard starts([117, 123], at: i) else { + throw fail("unsupported escape or interpolation", at: escape) + } + i += 2 + let digits = i + var scalar: UInt32 = 0 + while i < bytes.count, let hex = hex(bytes[i]), i - digits < 9 { + scalar = scalar &* 16 &+ hex + i += 1 + } + guard (1...8).contains(i - digits), i < bytes.count, bytes[i] == 125, + scalar <= 0x10ffff, !(0xd800...0xdfff).contains(scalar) + else { throw fail("invalid Unicode escape", at: escape) } + i += 1 + continue + } + if byte == 34 && (!multiline || starts([34, 34, 34], at: i)) { + let closing = i + let end = i + width + let content: [UInt8] + if multiline { + var lineStart = i + while lineStart > body && bytes[lineStart - 1] != 10 && bytes[lineStart - 1] != 13 { + lineStart -= 1 + } + let indent = i - lineStart + guard bytes[lineStart.. first + && (lineEnd - first < indent + || !bytes[first..<(first + indent)].allSatisfy({ $0 == 32 })) + { + throw fail("nonempty multiline line requires full indentation", at: first) + } + let contentStart = lineEnd == first ? first : first + indent + decodedBody.append(contentsOf: bytes[contentStart.. UInt32? { + if (48...57).contains(b) { return UInt32(b - 48) } + if (65...70).contains(b) { return UInt32(b - 55) } + if (97...102).contains(b) { return UInt32(b - 87) } + return nil + } + + private func decode(_ raw: [UInt8]) -> String { + if !raw.contains(92) { return String(decoding: raw, as: UTF8.self) } + var result: [UInt8] = [] + var i = 0 + while i < raw.count { + if raw[i] != 92 { + result.append(raw[i]) + i += 1 + continue + } + i += 1 + switch raw[i] { + case 48: result.append(0) + case 116: result.append(9) + case 110: result.append(10) + case 114: result.append(13) + case 117: + i += 2 + var scalar: UInt32 = 0 + while raw[i] != 125 { + scalar = scalar * 16 + hex(raw[i])! + i += 1 + } + result.append(contentsOf: String(UnicodeScalar(scalar)!).utf8) + default: result.append(raw[i]) + } + i += 1 + } + return String(decoding: result, as: UTF8.self) + } + + private func peek() -> Lexeme { tokens[index] } + private func peek(_ text: String) -> Bool { peek().text == text } + @discardableResult private func take(_ text: String? = nil) throws -> Lexeme { + let token = peek() + if let text, token.text != text { throw fail("expected \(text)", at: token.range.lowerBound) } + if token.kind != "eof" { index += 1 } + return token + } + private func identifier(bare: Bool = false) throws -> Lexeme { + let token = peek() + guard token.kind == "identifier", !reserved.contains(token.text), + !(bare && prefixes.contains(token.text)) + else { throw fail("expected an identifier", at: token.range.lowerBound) } + return try take() + } + private func open(_ text: String) throws -> Int { + let token = try take(text) + depth += 1 + if text == "[" { square += 1 } + if depth > 20 || square > 8 { + throw fail("grammar delimiter depth", at: token.range.lowerBound, code: "manifest.limit") + } + return token.range.lowerBound + } + private func close(_ text: String) throws -> Int { + let token = try take(text) + depth -= 1 + if text == "]" { square -= 1 } + return token.range.upperBound + } + private func emit(_ kind: String, _ range: Range, _ detail: String = "") { + events.append( + ProjectionEvent(start: range.lowerBound, end: range.upperBound, kind: kind, detail: detail)) + } + private func node(_ value: GrammarNode, projection: Bool = true) -> Int { + let id = nodes.count + nodes.append(value) + if projection { emit(value.kind, value.range, value.text) } + return id + } + + private func type() throws -> ConstructionType { + if peek("[") { + let start = try open("[") + let first = try type() + let result: ConstructionType + let kind: String + if peek(":") { + guard first == .named("String") else { + throw fail("dictionary key type must be String", at: start) + } + _ = try take(":") + result = .dictionary(try type()) + kind = "dictionaryType" + } else { + result = .array(first) + kind = "arrayType" + } + emit(kind, start..<(try close("]"))) + return result + } + let token = try identifier(bare: true) + guard Vocabulary.typeNames.contains(token.text) else { + throw fail("type outside construction vocabulary", at: token.range.lowerBound) + } + emit("type", token.range, token.text) + return token.text == "NativeConfiguration" + ? .dictionary(.dictionary(.named("ConfigurationValue"))) : .named(token.text) + } + + private func expression() throws -> Int { + let first = try primary() + var terms = [first] + while peek("+") { + let op = try take("+") + if terms.count == 32 { + throw fail( + "additive chain exceeds 32 terms", at: op.range.lowerBound, code: "manifest.limit") + } + terms.append(try primary()) + } + if terms.count == 1 { return first } + return node( + GrammarNode( + kind: "sequence", + range: nodes[first].range.lowerBound.. Int { + let token = peek() + let start = token.range.lowerBound + if token.kind == "string" || token.kind == "integer" + || ["true", "false", "nil"].contains(token.text) + { + _ = try take() + let kind = token.kind == "identifier" ? (token.text == "nil" ? "nil" : "boolean") : token.kind + emit(kind, token.range, token.text) + return node( + GrammarNode(kind: kind, range: token.range, text: token.decoded ?? token.text), + projection: false) + } + if peek("-") { + _ = try take("-") + let integer = try take() + guard integer.kind == "integer", integer.range.lowerBound == token.range.upperBound else { + throw fail("minus requires adjacent decimal digits", at: integer.range.lowerBound) + } + emit("integer", integer.range, integer.text) + return node( + GrammarNode(kind: "negative", range: start..? + if peek().kind == "identifier" && tokens[index + 1].text == ":" { + let name = try identifier() + label = name.text + labelRange = name.range + emit("label", name.range, name.text) + _ = try take(":") + } + arguments.append( + GrammarArgument(label: label, labelRange: labelRange, value: try expression())) + if !peek(",") { break } + _ = try take(",") + if peek(")") { throw fail("calls have no trailing comma", at: peek().range.lowerBound) } + } + } + return node( + GrammarNode( + kind: "call", range: start..<(try close(")")), text: callee, arguments: arguments), + projection: falseWithEvent("call", start..) -> Bool { + emit(kind, range) + return false + } + + private func argument(label: String) throws -> GrammarArgument { + let token = try take(label) + emit("label", token.range, token.text) + _ = try take(":") + return GrammarArgument(label: label, labelRange: token.range, value: try expression()) + } + + private func sourceArguments() throws -> [GrammarArgument] { + var args = [try argument(label: "name")] + _ = try take(",") + let location = peek().text + guard ["url", "path", "index"].contains(location) else { + throw fail("source requires url:, path: or index:", at: peek().range.lowerBound) + } + args.append(try argument(label: location)) + if !peek(",") { return args } + _ = try take(",") + if peek("subpath") { + args.append(try argument(label: "subpath")) + return args + } + if location == "index" { + throw fail("index source has no requirement", at: peek().range.lowerBound) + } + if ["from", "exact", "branch", "revision"].contains(peek().text) { + args.append(try argument(label: peek().text)) + } else if peek().kind == "string" { + let first = try primary() + let op = try take("..<") + emit("reference", op.range, "..<") + guard peek().kind == "string" else { + throw fail("range endpoint must be a string literal", at: peek().range.lowerBound) + } + let second = try primary() + let range = nodes[first].range.lowerBound.. String { + var result = "\"" + for scalar in string.unicodeScalars { + switch scalar.value { + case 34: result += "\\\"" + case 92: result += "\\\\" + case 10: result += "\\n" + case 13: result += "\\r" + case 9: result += "\\t" + case 0..<32, 127: result += "\\u{" + String(scalar.value, radix: 16) + "}" + default: result.unicodeScalars.append(scalar) + } + } + return result + "\"" +} + +package struct PrintStyle { + package var indent = " " + package var newline = "\n" + package var trailingComma = true +} + +package struct CanonicalPrinter { + package var style = PrintStyle() + + package func render(_ value: ConstructionValue, indentation: String = "") -> String { + switch value { + case .text(let text): return quoted(text) + case .integer(let value): return String(value) + case .boolean(let value): return value ? "true" : "false" + case .none: return "nil" + case .version(let version): return quoted(version.normalized) + case .range(let range): + let requirement = Lowering.requirement(range) + if case .upToNextMajor(let lower) = requirement { + return ".upToNextMajor(from: \(quoted(lower)))" + } + if case .upToNextMinor(let lower) = requirement { + return ".upToNextMinor(from: \(quoted(lower)))" + } + return quoted(range.lowerBound.normalized) + "..<" + quoted(range.upperBound.normalized) + case .array(let values): + return collection( + values.map { render($0, indentation: indentation + style.indent) }, dictionary: false, + forceMultiline: values.contains(where: nested), indentation: indentation) + case .object(let fields): + let keys = fields.keys.sorted(by: utf8Less) + return collection( + keys.map { + quoted($0) + ": " + render(fields[$0]!, indentation: indentation + style.indent) + }, dictionary: true, forceMultiline: fields.values.contains(where: nested), + indentation: indentation) + case .node(let type, let member, let fields): + if type == "SkillSelection" { + return member == "all" ? ".all" : render(fields["names"]!, indentation: indentation) + } + if type == "VersionRange", let lower = fields["from"] { + return ".\(member)(from: \(render(lower, indentation: indentation)))" + } + if type == "PromptContent" && member == "literal" + || type == "RuntimeValue" && member == "literal" + { + return render(fields["value"]!, indentation: indentation) + } + if ["SectionReference", "GroupReference"].contains(type), + fields["source"] == ConstructionValue.none, fields["condition"] == ConstructionValue.none + { + return render(fields["name"]!, indentation: indentation) + } + if type == "ConfigurationValue" { + if member == "null" { return "nil" } + if member != "decimal" { return render(fields["value"]!, indentation: indentation) } + } + if type == "Source" { return source(fields, indentation: indentation) } + let signature = Vocabulary.signatures.first { signature in + guard signature.type == type, signature.member == member else { return false } + let names = Set(signature.parameters.map(\.name)) + guard fields.allSatisfy({ names.contains($0.key) || $0.value == .none }) else { + return false + } + return signature.parameters.allSatisfy { parameter in + guard let value = fields[parameter.name] else { return parameter.defaultValue != nil } + if value == .none, parameter.defaultValue == nil { + if case .optional = parameter.type { return true } + return false + } + return true + } + } + guard let signature else { return ".\(member)" } + var arguments: [(String, ConstructionValue)] = [] + for parameter in signature.parameters { + guard let value = fields[parameter.name] else { continue } + if let fallback = parameter.defaultValue, fallback == value { continue } + arguments.append((parameter.label, value)) + } + if !signature.callable { return ".\(member)" } + return call( + type == "Agents" ? "Agents" : "." + member, arguments: arguments, indentation: indentation) + } + } + + private func source(_ fields: [String: ConstructionValue], indentation: String) -> String { + var args: [(String, ConstructionValue)] = [("name", fields["name"]!)] + for key in ["url", "path", "index"] { + if let value = fields[key] { + if key == "url", let url = value.text { + args.append((key, .text(SourceDeclaration(kind: .git, location: url).gitURL))) + } else { + args.append((key, value)) + } + } + } + if let requirement = fields["requirement"], requirement != .none { + if case .range(let range) = requirement { + if case .upToNextMajor(let lower) = Lowering.requirement(range) { + args.append(("from", .version(Version(stringLiteral: lower)))) + } else { + args.append(("_", requirement)) + } + } else if case .node(_, let member, let payload) = requirement { + args.append((member, payload["value"]!)) + } + } + if let subpath = fields["subpath"], subpath != .none { args.append(("subpath", subpath)) } + return call(".source", arguments: args, indentation: indentation) + } + + private func call(_ callee: String, arguments: [(String, ConstructionValue)], indentation: String) + -> String + { + let parts = arguments.map { label, value in + (label == "_" ? "" : label + ": ") + render(value, indentation: indentation + style.indent) + } + let inline = callee + "(" + parts.joined(separator: ", ") + ")" + if !arguments.contains(where: { nested($0.1) }) + && indentation.utf8.count + inline.utf8.count + 1 <= 80 + { + return inline + } + if parts.isEmpty { return inline } + return callee + "(" + style.newline + + parts.enumerated().map { index, part in + indentation + style.indent + part + (index == parts.count - 1 ? "" : ",") + }.joined(separator: style.newline) + style.newline + indentation + ")" + } + + private func collection( + _ parts: [String], dictionary: Bool, forceMultiline: Bool, indentation: String + ) -> String { + if parts.isEmpty { return dictionary ? "[:]" : "[]" } + let inline = "[" + parts.joined(separator: ", ") + "]" + if !forceMultiline && indentation.utf8.count + inline.utf8.count + 1 <= 80 { return inline } + return "[" + style.newline + + parts.enumerated().map { index, part in + indentation + style.indent + part + + (style.trailingComma || index < parts.count - 1 ? "," : "") + }.joined(separator: style.newline) + style.newline + indentation + "]" + } + + private func nested(_ value: ConstructionValue) -> Bool { + switch value { + case .array, .object: return true + case .node(let type, let member, _): + return ![ + "Agent", "Scope", "Platform", "InstallMode", "IgnorePurpose", "PluginMode", "ComponentKind", + ].contains(type) + && !(type == "SkillSelection" && member == "all") + case .range: return true + default: return false + } + } +} + +package func utf8Less(_ lhs: String, _ rhs: String) -> Bool { + lhs.utf8.lexicographicallyPrecedes(rhs.utf8) +} diff --git a/Sources/AgentsManifest/DeclarationDocument.swift b/Sources/AgentsManifest/DeclarationDocument.swift new file mode 100644 index 0000000..2621ff8 --- /dev/null +++ b/Sources/AgentsManifest/DeclarationDocument.swift @@ -0,0 +1,383 @@ +import AgentsCore +import AgentsDescription +import Foundation +import SwiftSyntax + +public struct DeclarationDocument: Sendable { + public let declaration: DeclarationIR + public let diagnostics: [ManifestDiagnostic] + public let sourceMap: DeclarationSourceMap + public let digest: String + public let metrics: FrontEndMetrics + public var bytes: [UInt8] { source.bytes } + package let source: SourceText + package let admission: Admission + package let syntax: SourceFileSyntax + package let evaluation: Evaluation + package let locations: [String: NodeID] + package let values: [String: EvaluatedValue] + + public init(bytes: [UInt8], identity: DocumentIdentity) throws { + try self.init(bytes: bytes, identity: identity, validateDomain: true) + } + + package init(bytes: [UInt8], identity: DocumentIdentity, validateDomain: Bool) throws { + // Reject the extra byte before building line tables or decoding the snapshot. + if bytes.count > 2_097_152 { + let bounded = SourceText(Array(bytes.prefix(2_097_153)), identity: identity) + throw bounded.failure("manifest.limit", "input byte limit", 2_097_152) + } + let clock = ContinuousClock() + let start = clock.now + let source = SourceText(bytes, identity: identity) + let admission: Admission + var metrics = FrontEndMetrics() + do { + admission = try Recognizer(source: source).recognize() + } catch let failure as ManifestFailure { + metrics = failure.metrics + metrics.admissionSeconds = seconds(start.duration(to: clock.now)) + throw ManifestFailure(failure.diagnostics[0], metrics: metrics) + } + metrics.admissionSeconds = seconds(start.duration(to: clock.now)) + metrics.tokens = admission.tokens.count + metrics.syntaxReservation = admission.reservation + let checked = try SyntaxValidation.parse(source, admission: admission, metrics: metrics) + metrics = checked.metrics + let evaluation: Evaluation + let diagnostics: [ManifestDiagnostic] + let digest = "sha256:" + FileHash.sha256Hex(data: Data(bytes)) + let mapping: BuiltMap + let declaration: DeclarationIR + var stage = "evaluation" + var stageStart = clock.now + do { + evaluation = try Evaluator(source: source, admission: admission).evaluate() + metrics.evaluationSeconds = seconds(stageStart.duration(to: clock.now)) + stage = "domain" + stageStart = clock.now + diagnostics = + validateDomain + ? try DomainValidator(source: source, admission: admission, evaluation: evaluation) + .validate() : [] + metrics.domainSeconds = seconds(stageStart.duration(to: clock.now)) + stage = "lowering" + stageStart = clock.now + declaration = Lowering.declaration(evaluation.root.value) + metrics.loweringSeconds = seconds(stageStart.duration(to: clock.now)) + stage = "sourceMap" + stageStart = clock.now + mapping = try MapBuilder(source: source, admission: admission, digest: digest).build( + evaluation) + metrics.sourceMapSeconds = seconds(stageStart.duration(to: clock.now)) + } catch let failure as ManifestFailure { + let elapsed = seconds(stageStart.duration(to: clock.now)) + switch stage { + case "evaluation": metrics.evaluationSeconds = elapsed + case "domain": metrics.domainSeconds = elapsed + case "sourceMap": metrics.sourceMapSeconds = elapsed + default: metrics.loweringSeconds = elapsed + } + throw ManifestFailure(failure.diagnostics[0], metrics: metrics) + } + self.source = source + self.admission = admission + syntax = checked.tree + self.evaluation = evaluation + self.declaration = declaration + self.diagnostics = diagnostics + self.digest = digest + sourceMap = DeclarationSourceMap(entries: mapping.entries) + locations = mapping.locations + values = mapping.values + metrics.evaluationSteps = evaluation.steps + metrics.expandedNodes = evaluation.total.nodes + metrics.decodedBytes = evaluation.total.strings + self.metrics = metrics + } + + public func node(at pointer: String) -> NodeID? { locations[pointer] } + public func constant(named name: String) -> NodeID? { + locations["/constants/" + pointerEscape(name)] + } + public func uses(ofConstant name: String) -> [NodeID] { + var pending = [name] + var seen = Set() + var references = Set() + while let name = pending.popLast() { + if !seen.insert(name).inserted { continue } + for id in evaluation.references[name] ?? [] { + references.insert(id) + let offset = admission.nodes[id].range.lowerBound + if let owner = admission.declarations.first(where: { $0.range.contains(offset) }), + owner.name != "agents" + { + pending.append(owner.name) + } + } + } + return references.sorted().map { + NodeID(digest: digest, pointer: "/references/\($0)", syntax: $0) + } + } + + public func editability(of node: NodeID) -> Editability { + guard node.digest == digest, values[node.pointer]?.syntax == node.syntax else { + return .readOnly(reason: "stale snapshot handle") + } + if node.pointer.hasPrefix("/constants/") { + let name = String(node.pointer.dropFirst("/constants/".count)).replacingOccurrences( + of: "~1", with: "/" + ).replacingOccurrences(of: "~0", with: "~") + return .sharedConstant(uses: uses(ofConstant: name)) + } + guard let value = values[node.pointer], !value.defaulted, value.type != .named("") else { + return .readOnly(reason: "default field has no source range") + } + if value.referent != nil || hasAssembledAncestor(node.pointer) { + return .readOnly( + reason: "shared constant or assembled value; replace its definition explicitly") + } + let kind = admission.nodes[node.syntax].kind + if kind == "sequence" || kind == "name" { + return .readOnly(reason: "expanded value has no independent source range") + } + return .direct + } + + package func hasAssembledAncestor(_ pointer: String) -> Bool { + var prefix = pointer + while let slash = prefix.lastIndex(of: "/"), slash != prefix.startIndex { + prefix = String(prefix[.. DocumentChange { + try DocumentEditor(document: self).prepare(edits) + } +} + +package func pointerEscape(_ text: String) -> String { + text.replacingOccurrences(of: "~", with: "~0").replacingOccurrences(of: "/", with: "~1") +} + +package struct BuiltMap { + package var entries: [SourceMapEntry] = [] + package var locations: [String: NodeID] = [:] + package var values: [String: EvaluatedValue] = [:] +} + +package final class MapBuilder { + private let source: SourceText + private let admission: Admission + private let digest: String + private var result = BuiltMap() + private var originCount = 0 + private var encodedBytes = 0 + + package init(source: SourceText, admission: Admission, digest: String) { + self.source = source + self.admission = admission + self.digest = digest + } + + package func build(_ evaluation: Evaluation) throws -> BuiltMap { + try append(evaluation.root, pointer: "", origins: [], use: nil) + // Constants are separately addressable; declaration locations remain language independent. + for (name, value) in evaluation.constants where name != "agents" { + let pointer = "/constants/" + pointerEscape(name) + result.locations[pointer] = NodeID(digest: digest, pointer: pointer, syntax: value.syntax) + result.values[pointer] = value + } + result.entries.sort { ($0.pointer, $0.span.start) < ($1.pointer, $1.span.start) } + return result + } + + private func append( + _ value: EvaluatedValue, pointer: String, origins: [SourceSpan], use: SourceSpan?, + ownOrigins: [SourceSpan] = [] + ) throws { + let range = admission.nodes[value.syntax].range + let span = use ?? source.span(range) + var inherited = origins + let definition = source.span(range) + if use != nil, definition != span, inherited.last != definition { inherited.append(definition) } + var resolved = value + while let next = resolved.referent { + inherited.append(source.span(admission.nodes[next.syntax].range)) + resolved = next + } + if value.referent != nil { + guard resolved.cost.nodes <= 100_000 - result.entries.count, + value.cost.origins <= 1_000_000 - originCount + else { + throw source.failure("manifest.limit", "reference source map expansion", range.lowerBound) + } + } + let recordedOrigins = inherited + ownOrigins + let estimate = + pointer.utf8.count + (source.identity.rawValue.utf8.count + 160) * (recordedOrigins.count + 1) + + 80 + guard result.entries.count < 100_000, recordedOrigins.count <= 1_000_000 - originCount, + estimate <= 16_777_216 - encodedBytes + else { + throw source.failure( + "manifest.limit", "source map locations, origins or encoded bytes", range.lowerBound) + } + originCount += recordedOrigins.count + encodedBytes += estimate + result.entries.append( + SourceMapEntry( + pointer: pointer, span: span, origins: recordedOrigins, defaulted: value.defaulted)) + result.locations[pointer] = NodeID(digest: digest, pointer: pointer, syntax: value.syntax) + result.values[pointer] = value + let useSpan = value.referent != nil || use != nil ? span : nil + if case .node(let type, let member, let fields) = resolved.value { + let tagged: Set = [ + "Source", "Component", "MCPTransport", "ExecutableInvocation", "GroupReference", + "PromptContent", "RuntimeValue", "ConfigurationValue", "HookEvent", "PermissionOperation", + "ComponentReference", "PermissionRule", + ] + if tagged.contains(type), case .record(let record) = Lowering.lower(resolved.value) { + let discriminator = EvaluatedValue( + type: .named(""), value: .text(record.kind), cost: ValueCost.scalar(record.kind), + syntax: resolved.syntax) + try append(discriminator, pointer: pointer + "/kind", origins: inherited, use: useSpan) + } + if type == "SkillSelection" { + for (offset, child) in resolved.elementsForUse.enumerated() { + try append(child, pointer: pointer + "/\(offset)", origins: inherited, use: useSpan) + } + return + } + if type == "ConfigurationValue", resolved.fields["value"] == nil, + let payload = fields["value"] + { + let childType: ConstructionType = + member == "object" + ? .dictionary(.named("ConfigurationValue")) + : member == "array" + ? .array(.named("ConfigurationValue")) + : member == "integer" + ? .named("Int") : member == "boolean" ? .named("Bool") : .named("String") + let child = EvaluatedValue( + type: childType, value: payload, cost: resolved.cost, syntax: resolved.syntax, + fields: resolved.fields, elements: resolved.elements) + try append(child, pointer: pointer + "/value", origins: inherited, use: useSpan) + return + } + for (key, childValue) in fields { + if type == "Source", key == "requirement" { + let trace = ["from", "exact", "branch", "revision", "range"].compactMap { + resolved.fields[$0] + }.first + if let trace, childValue != .none { + let shape = requirementShape(childValue, trace: trace) + var definitions: [SourceSpan] = [] + var referent = trace.referent + while let definition = referent { + definitions.append(source.span(admission.nodes[definition.syntax].range)) + referent = definition.referent + } + try append( + shape, pointer: pointer + "/requirement", origins: inherited, use: useSpan, + ownOrigins: definitions) + } else { + let absent = EvaluatedValue( + type: .named(""), value: .none, cost: ValueCost(), syntax: resolved.syntax, + defaulted: true) + try append(absent, pointer: pointer + "/requirement", origins: inherited, use: useSpan) + } + continue + } + let sourceKey = + type == "Source" && key == "requirement" + ? ["from", "exact", "branch", "revision", "range"].first(where: { + resolved.fields[$0] != nil + }) ?? key : key + let child: EvaluatedValue + if let field = resolved.fields[sourceKey] { + child = field + } else { + child = EvaluatedValue( + type: .named(""), value: childValue, cost: ValueCost(), syntax: resolved.syntax, + defaulted: (key == "source" || key == "condition") && childValue == .none + || resolved.defaulted) + } + try append( + child, pointer: pointer + "/" + pointerEscape(key), origins: inherited, use: useSpan) + } + } else if !resolved.fields.isEmpty { + for (key, child) in resolved.fields { + try append( + child, pointer: pointer + "/" + pointerEscape(key), origins: inherited, use: useSpan) + } + } else if !resolved.elements.isEmpty { + for (offset, child) in resolved.elements.enumerated() { + try append(child, pointer: pointer + "/\(offset)", origins: inherited, use: useSpan) + } + } else { + try synthetic( + resolved.value, syntax: resolved.syntax, pointer: pointer, span: span, origins: inherited, + defaulted: value.defaulted) + } + } + + private func requirementShape(_ value: ConstructionValue, trace: EvaluatedValue) -> EvaluatedValue + { + let requirement = Lowering.lower(value) + var fields: [String: ConstructionValue] = [:] + var traces: [String: EvaluatedValue] = [:] + if case .requirement(let requirement) = requirement { + let lower = trace.field("from") ?? trace.elementsForUse.first ?? trace + switch requirement { + case .branch(let text): + fields["branch"] = .text(text) + traces["branch"] = trace + case .revision(let text): + fields["revision"] = .text(text) + traces["revision"] = trace + case .exact(let text): + fields["exact"] = .text(text) + traces["exact"] = trace + case .upToNextMajor(let text): + fields["from"] = .text(text) + traces["from"] = lower + case .upToNextMinor(let text): + fields["upToNextMinor"] = .text(text) + traces["upToNextMinor"] = lower + case .range(let from, let to): + fields["from"] = .text(from) + fields["to"] = .text(to) + traces["from"] = lower + traces["to"] = trace.elementsForUse.last ?? trace + } + } + return EvaluatedValue( + type: .named("Requirement"), value: .object(fields), cost: trace.cost, syntax: trace.syntax, + fields: traces) + } + + private func synthetic( + _ value: ConstructionValue, syntax: Int, pointer: String, span: SourceSpan, + origins: [SourceSpan], defaulted: Bool + ) throws { + let fields: [(String, ConstructionValue)] + switch value { + case .node(_, _, let values), .object(let values): fields = Array(values) + case .array(let values): fields = values.enumerated().map { (String($0.offset), $0.element) } + default: return + } + for (key, child) in fields { + let v = EvaluatedValue( + type: .named(""), value: child, cost: ValueCost(), syntax: syntax, defaulted: defaulted) + try append(v, pointer: pointer + "/" + pointerEscape(key), origins: origins, use: span) + } + } +} diff --git a/Sources/AgentsManifest/DocumentEditor.swift b/Sources/AgentsManifest/DocumentEditor.swift new file mode 100644 index 0000000..eadc761 --- /dev/null +++ b/Sources/AgentsManifest/DocumentEditor.swift @@ -0,0 +1,1062 @@ +import AgentsCore +import AgentsDescription +import Foundation + +package final class DocumentEditor { + private let original: DeclarationDocument + private var current: DeclarationDocument + private var table: PieceTable + private var history: [SourcePatch] = [] + private var expected: ConstructionValue + private var impacted: [NodeID] = [] + private var steps = 0 + + package init(document: DeclarationDocument) { + original = document + current = document + table = PieceTable(document.bytes) + expected = document.evaluation.root.value + } + + private func fail(_ code: String, _ message: String, range: Range? = nil) -> ManifestFailure + { + current.source.failure( + code, message, (range ?? 0..<0).lowerBound, end: (range ?? 0..<0).upperBound) + } + private func charge(_ count: Int) throws { + if count > 1_000_000 - steps { throw fail("manifest.limit", "edit batch work steps") } + steps += count + } + private func valueCost(_ value: ConstructionValue) throws -> ValueCost { + // Iterative preflight bounds external vocabulary values before recursive consumers. + var pending: [(ConstructionValue, Int)] = [(value, 1)] + var nodes = 0 + var strings = 0 + while let (value, depth) = pending.popLast() { + try charge(1) + nodes += 1 + if nodes > 100_000 || depth > 64 { + throw fail("manifest.limit", "edit value node/depth budget") + } + let children: [ConstructionValue] + switch value { + case .text(let text): + strings = ValueCost.add(strings, text.utf8.count) + children = [] + case .array(let values): + if values.count > 10_000 { throw fail("manifest.limit", "edit collection entries") } + children = values + case .object(let fields), .node(_, _, let fields): + if fields.count > 10_000 { throw fail("manifest.limit", "edit dictionary entries") } + strings = ValueCost.add(strings, fields.keys.reduce(0) { ValueCost.add($0, $1.utf8.count) }) + children = Array(fields.values) + case .version(let version): + strings = ValueCost.add(strings, version.normalized.utf8.count) + children = [] + case .range(let range): children = [.version(range.lowerBound), .version(range.upperBound)] + default: children = [] + } + if strings > 16_777_216 || pending.count + children.count > 100_000 { + throw fail("manifest.limit", "edit expanded value bytes/nodes") + } + for child in children { pending.append((child, depth + 1)) } + } + let cost = constructionCost(value) + if !cost.fits { throw fail("manifest.limit", "edit value/output budget") } + return cost + } + + package func prepare(_ edits: [ManifestEdit]) throws -> DocumentChange { + if edits.count > 100 { throw fail("manifest.limit", "edit batch has more than 100 requests") } + for edit in edits { + let before = history.count + try apply(edit) + if before != history.count { + current = try DeclarationDocument( + bytes: table.bytes, identity: original.source.identity, validateDomain: false) + try charge(current.metrics.evaluationSteps + current.metrics.syntaxNodes) + } + } + let expectedCost = try valueCost(expected) + try charge(expectedCost.nodes) + let bytes = table.bytes + if bytes == original.bytes { + guard Lowering.declaration(expected) == original.declaration else { + throw fail("manifest.edit.mismatch", "no-op bytes disagree with expected declaration") + } + return DocumentChange( + originalDigest: original.digest, patches: [], bytes: bytes, digest: original.digest, + expectedDeclaration: original.declaration, impactedReferences: [], + diagnostics: original.diagnostics, delta: SemanticDelta(changedPointers: [])) + } + let candidate = try DeclarationDocument(bytes: bytes, identity: original.source.identity) + let actualCost = candidate.evaluation.root.cost + if expectedCost.nodes + actualCost.nodes > 200_000 { + throw fail("manifest.limit", "comparison node-pair budget") + } + try charge(expectedCost.nodes + actualCost.nodes) + let expectedIR = Lowering.declaration(expected) + guard candidate.declaration == expectedIR else { + throw fail( + "manifest.edit.mismatch", "complete candidate differs from the expected declaration") + } + return DocumentChange( + originalDigest: original.digest, patches: table.patches(), bytes: bytes, + digest: candidate.digest, expectedDeclaration: expectedIR, + impactedReferences: Array(Set(impacted)).sorted { $0.syntax < $1.syntax }, + diagnostics: candidate.diagnostics, + delta: try semanticDelta()) + } + + private func semanticDelta() throws -> SemanticDelta { + var pending: [(DeclarationValue, DeclarationValue, String)] = [ + (Lowering.lower(original.evaluation.root.value), Lowering.lower(expected), "") + ] + var visited = 0 + var pointers: [String] = [] + while let (left, right, pointer) = pending.popLast() { + try charge(1) + visited += 1 + if visited > 200_000 { throw fail("manifest.limit", "semantic delta comparison node pairs") } + switch (left, right) { + case (.array(let a), .array(let b)) where a.count == b.count: + for index in a.indices { pending.append((a[index], b[index], pointer + "/\(index)")) } + case (.dictionary(let a), .dictionary(let b)) where a.keys == b.keys: + for key in a.keys { pending.append((a[key]!, b[key]!, pointer + "/" + pointerEscape(key))) } + case (.record(let a), .record(let b)) where a.kind == b.kind: + pending.append((.dictionary(a.fields), .dictionary(b.fields), pointer)) + default: + if left != right { pointers.append(pointer) } + } + if pending.count > 200_000 - visited { + throw fail("manifest.limit", "semantic delta scheduled pairs") + } + } + return SemanticDelta(changedPointers: pointers.sorted()) + } + + private func apply(_ edit: ManifestEdit) throws { + switch edit { + case .setDefaultAgents(let agents): try setField("", "defaultAgents", agents.constructionValue) + case .setExports(let exports): try setField("", "exports", exports.constructionValue) + case .setWatch(let watch): try setField("", "watch", watch.constructionValue) + case .upsertSource(let source): + try upsert(source.constructionValue, collection: "/sources", key: "name") + case .removeSource(let alias): try removeNamed(alias, collection: "/sources", key: "name") + case .upsertGroup(let group): + try upsert(group.constructionValue, collection: "/groups", key: "name") + case .removeGroup(let name): try removeNamed(name, collection: "/groups", key: "name") + case .insertComponent(let component, let container, let position): + try insert( + component.constructionValue, into: containerPath(container) + "/components", at: position) + case .replaceComponent(let handle, let component): + let pointer = try resolve(handle) + try requireType(pointer, "Component") + try replace(pointer, with: component.constructionValue) + case .removeComponent(let handle): + let pointer = try resolve(handle) + try requireType(pointer, "Component") + try remove(pointer) + case .moveComponent(let handle, let container, let position): + let pointer = try resolve(handle) + try requireType(pointer, "Component") + try move(pointer, into: containerPath(container) + "/components", at: position) + case .setSkillSelection(let handle, let selection): + let pointer = try resolve(handle) + try requireType(pointer, "Component", member: "skills") + try setField(pointer, "select", selection.constructionValue) + case .upsertSkillOverride(let handle, let override): + let pointer = try resolve(handle) + try requireType(pointer, "Component", member: "skills") + try upsert(override.constructionValue, collection: pointer + "/overrides", key: "name") + case .removeSkillOverride(let handle, let name): + let pointer = try resolve(handle) + try requireType(pointer, "Component", member: "skills") + try removeNamed(name, collection: pointer + "/overrides", key: "name") + case .insertSection(let section, let handle, let position): + let pointer = try resolve(handle) + guard current.values[pointer]?.value.fields["sections"] != nil else { + throw fail("manifest.edit.readOnly", "target has no instruction sections") + } + try insert(section.constructionValue, into: pointer + "/sections", at: position) + case .removeSection(let handle): + let pointer = try resolve(handle) + try requireType(pointer, "SectionReference") + try remove(pointer) + case .moveSection(let handle, let position): + let pointer = try resolve(handle) + try requireType(pointer, "SectionReference") + try move(pointer, into: parent(pointer), at: position) + case .upsertPrompt(let handle, let prompt): + let pointer = try resolve(handle) + try requireType(pointer, "Component", member: "instructions") + try upsert(prompt.constructionValue, collection: pointer + "/chatGPT", key: "name") + case .removePrompt(let handle, let name): + let pointer = try resolve(handle) + try requireType(pointer, "Component", member: "instructions") + try removeNamed(name, collection: pointer + "/chatGPT", key: "name") + case .insertGroupReference(let reference, let container, let position): + try insert( + reference.constructionValue, into: containerPath(container) + "/uses", at: position) + case .removeGroupReference(let handle): + let pointer = try resolve(handle) + try requireType(pointer, "GroupReference") + try remove(pointer) + case .setDictionaryEntry(let handle, let key, let value): + let pointer = try resolve(handle) + try dictionary(pointer, key: key, value: value) + case .removeDictionaryEntry(let handle, let key): + try dictionary(resolve(handle), key: key, value: nil) + case .replaceConstant(let handle, let value, let accepted): + try constant(handle, value: value, accepted: accepted) + } + } + + private func requireType(_ pointer: String, _ type: String, member: String? = nil) throws { + guard current.values[pointer]?.type.unwrapped == .named(type), + member == nil || current.values[pointer]?.value.member == member + else { throw fail("manifest.edit.readOnly", "handle has the wrong domain kind") } + } + private func resolve(_ handle: NodeID) throws -> String { + guard handle.digest == original.digest, let originalValue = original.values[handle.pointer], + originalValue.syntax == handle.syntax + else { throw fail("manifest.edit.stale", "handle belongs to a different snapshot") } + let mapped = try translated(original.admission.nodes[handle.syntax].range) + if handle.pointer.hasPrefix("/constants/"), let value = current.values[handle.pointer], + current.admission.nodes[value.syntax].range == mapped + { + return handle.pointer + } + guard + let pointer = current.values.keys.sorted().first(where: { key in + guard let value = current.values[key], !value.defaulted else { return false } + return value.type == originalValue.type + && current.admission.nodes[value.syntax].range == mapped + }) + else { throw fail("manifest.edit.stale", "the addressed occurrence was removed or replaced") } + return pointer + } + private func translated(_ originalRange: Range) throws -> Range { + var range = originalRange + for patch in history { + let delta = patch.replacement.count - patch.range.count + if patch.range.isEmpty && patch.range.lowerBound == range.lowerBound { + range = (range.lowerBound + delta)..<(range.upperBound + delta) + } else if patch.range.upperBound <= range.lowerBound { + range = (range.lowerBound + delta)..<(range.upperBound + delta) + } else if patch.range.lowerBound >= range.upperBound { + continue + } else if patch.range.lowerBound >= range.lowerBound + && patch.range.upperBound <= range.upperBound + { + if patch.range == range && patch.replacement.isEmpty { + throw fail("manifest.edit.stale", "addressed occurrence was removed") + } + range = range.lowerBound..<(range.upperBound + delta) + } else { + throw fail("manifest.edit.overlap", "edit overlaps a previously changed occurrence") + } + } + return range + } + private func direct(_ pointer: String) throws -> EvaluatedValue { + guard let value = current.values[pointer], !value.defaulted, value.referent == nil, + !current.hasAssembledAncestor(pointer), + current.admission.nodes[value.syntax].kind != "sequence", + current.admission.nodes[value.syntax].kind != "name" + else { + throw fail( + "manifest.edit.readOnly", + "target is a shared constant, assembled value or inherited default") + } + return value + } + private func containerPath(_ container: ContainerID) throws -> String { + switch container { + case .root: return "" + case .group(let handle): + let pointer = try resolve(handle) + try requireType(pointer, "ComponentGroup") + return pointer + } + } + private func parent(_ pointer: String) -> String { + String(pointer[.. String { + String(pointer[pointer.index(after: pointer.lastIndex(of: "/")!)...]).replacingOccurrences( + of: "~1", with: "/" + ).replacingOccurrences(of: "~0", with: "~") + } + + private func patch(_ range: Range, _ text: String) throws { + try patch(range, bytes: Array(text.utf8)) + } + private func patch(_ range: Range, bytes: [UInt8]) throws { + guard range.lowerBound >= 0, range.upperBound <= table.count else { + throw fail("manifest.edit.overlap", "patch is outside the snapshot") + } + if table.count - range.count + bytes.count > 2_097_152 { + throw fail("manifest.limit", "generated manifest input bytes") + } + if current.bytes[range].elementsEqual(bytes) { return } + table.replace(range, with: bytes) + history.append(SourcePatch(range: range, replacement: bytes)) + } + private func mutate(_ pointer: String, _ replacement: ConstructionValue) throws { + _ = try valueCost(replacement) + let parts = pointer.split(separator: "/").map { + String($0).replacingOccurrences(of: "~1", with: "/").replacingOccurrences(of: "~0", with: "~") + } + func update(_ value: ConstructionValue, _ depth: Int) throws -> ConstructionValue { + try charge(1) + if depth == parts.count { return replacement } + let part = parts[depth] + switch value { + case .node(let type, let member, var fields): + guard let child = fields[part] else { + throw fail("manifest.edit.mismatch", "expected field is missing") + } + fields[part] = try update(child, depth + 1) + return .node(type: type, member: member, fields: fields) + case .object(var fields): + guard let child = fields[part] else { + throw fail("manifest.edit.mismatch", "expected dictionary field is missing") + } + fields[part] = try update(child, depth + 1) + return .object(fields) + case .array(var values): + guard let index = Int(part), values.indices.contains(index) else { + throw fail("manifest.edit.mismatch", "expected array occurrence is missing") + } + values[index] = try update(values[index], depth + 1) + return .array(values) + default: throw fail("manifest.edit.readOnly", "value has no editable child") + } + } + expected = try update(expected, 0) + _ = try valueCost(expected) + } + + private func style(at range: Range) throws -> (PrintStyle, String) { + try charge(current.admission.nodes.count) + let bytes = current.bytes + var endings = Set() + var cursor = 0 + while cursor < bytes.count { + if bytes[cursor] == 13 { + if cursor + 1 < bytes.count && bytes[cursor + 1] == 10 { + endings.insert("\r\n") + cursor += 1 + } else { + endings.insert("\r") + } + } else if bytes[cursor] == 10 { + endings.insert("\n") + } + cursor += 1 + } + guard endings.count <= 1 else { + throw fail("manifest.edit.readOnly", "conflicting newline styles", range: range) + } + let indentation = indentation(at: range.lowerBound) + let candidates = current.admission.nodes.filter { node in + ["array", "dictionary", "call"].contains(node.kind) + && node.range.lowerBound <= range.lowerBound && node.range.upperBound >= range.upperBound + } + var unit: String? + var trailingComma = true + for container in candidates.sorted(by: { $0.range.count < $1.range.count }) { + var units = Set() + let base = self.indentation(at: container.range.lowerBound) + let offsets = + container.kind == "dictionary" + ? container.keys.map { $0.range.lowerBound } + : container.kind == "array" + ? container.children.map { current.admission.nodes[$0].range.lowerBound } + : container.arguments.map { + $0.labelRange?.lowerBound ?? current.admission.nodes[$0.value].range.lowerBound + } + for offset in offsets { + let start = lineStart(offset) + let prefix = current.source.spelling(start.. base.count else { + throw fail("manifest.edit.readOnly", "conflicting local indentation", range: range) + } + units.insert(String(prefix.dropFirst(base.count))) + } + guard units.count <= 1 else { + throw fail("manifest.edit.readOnly", "conflicting local indentation", range: range) + } + if let evidence = units.first { + unit = evidence + break + } + } + for container in candidates.sorted(by: { $0.range.count < $1.range.count }) + where container.kind == "array" || container.kind == "dictionary" { + guard let last = container.children.last, + let token = current.admission.tokens.first(where: { + $0.range.lowerBound >= current.admission.nodes[last].range.upperBound + }) + else { continue } + trailingComma = token.text == "," + break + } + return ( + PrintStyle( + indent: unit ?? " ", newline: endings.first ?? "\n", trailingComma: trailingComma), + indentation + ) + } + + private func indentation(at offset: Int) -> String { + String(current.source.spelling(lineStart(offset)..) throws -> String { + _ = try valueCost(value) + let (style, indentation) = try style(at: range) + var text = CanonicalPrinter(style: style).render(value, indentation: indentation) + if text.hasPrefix("-"), range.lowerBound > 0 { + let previous = current.bytes[range.lowerBound - 1] + if ![32, 9, 10, 13, 40, 91, 44, 58].contains(previous) { text = " " + text } + } + return text + } + private func internalComments(_ range: Range) -> Bool { + current.admission.comments.contains { + $0.lowerBound >= range.lowerBound && $0.upperBound <= range.upperBound + } + } + + private func replace(_ pointer: String, with value: ConstructionValue) throws { + let old = try direct(pointer) + _ = try valueCost(value) + if Lowering.lower(old.value) == Lowering.lower(value) { return } + let range = current.admission.nodes[old.syntax].range + if internalComments(range) { + throw fail( + "manifest.edit.readOnly", + "internal comments cannot be mapped through whole-node replacement", range: range) + } + try patch(range, replacementText(value, at: range)) + try mutate(pointer, value) + } + + private func setField( + _ pointer: String, _ field: String, _ value: ConstructionValue, spelling: String? = nil + ) throws { + let owner = try direct(pointer) + let node = current.admission.nodes[owner.syntax] + guard node.kind == "call", let old = owner.value.fields[field] else { + throw fail("manifest.edit.readOnly", "target is not a direct construction") + } + _ = try valueCost(value) + if Lowering.lower(old) == Lowering.lower(value) { return } + if let child = owner.field(field), !child.defaulted { + try replace(pointer + "/" + pointerEscape(field), with: value) + return + } + let signatures = Vocabulary.signatures.filter { + $0.type == owner.type.name && $0.member == owner.value.member + } + guard + let signature = signatures.first(where: { + $0.parameters.contains(where: { $0.name == field }) + }), let position = signature.parameters.firstIndex(where: { $0.name == field }) + else { throw fail("manifest.edit.readOnly", "unknown construction field") } + let next = node.arguments.first { argument in + let index = signature.parameters.firstIndex { $0.label == argument.label } ?? -1 + return index > position + } + let (style, indentation) = try style(at: node.range) + let content = + field + ": " + + (spelling + ?? CanonicalPrinter(style: style).render(value, indentation: indentation + style.indent)) + let multiline = current.bytes[node.range].contains(10) || current.bytes[node.range].contains(13) + if let next { + let start = + next.labelRange?.lowerBound ?? current.admission.nodes[next.value].range.lowerBound + if multiline { + let line = lineStart(start) + if current.bytes[line.. Int + { + switch position { + case .first: return 0 + case .last: return count + case .before(let handle), .after(let handle): + let pointer = try resolve(handle) + guard parent(pointer) == collection, let index = Int(key(pointer)) else { + throw fail("manifest.edit.impact", "insertion anchor belongs to another container") + } + if case .after = position { return index + 1 } + return index + } + } + + private func insert( + _ value: ConstructionValue, into pointer: String, at position: InsertionPosition, + carried: [UInt8]? = nil + ) throws { + guard let collection = current.values[pointer], case .array(let previous) = collection.value + else { throw fail("manifest.edit.readOnly", "target is not an array") } + let incoming = try valueCost(value) + guard previous.count < 10_000 else { throw fail("manifest.limit", "edited array entries") } + let combined = ValueCost.container(collection.elementsForUse.map(\.cost) + [incoming]) + let total = current.evaluation.total + let projected = ValueCost( + nodes: total.nodes - collection.cost.nodes + combined.nodes, + strings: total.strings - collection.cost.strings + combined.strings, + encoded: total.encoded - collection.cost.encoded + combined.encoded, + depth: max(total.depth, incoming.depth + pointer.split(separator: "/").count + 1), + origins: total.origins - collection.cost.origins + combined.origins) + guard combined.fits, projected.fits else { + throw fail("manifest.limit", "edited expanded document budget") + } + let index = try self.position(position, collection: pointer, count: previous.count) + var expectedValues = previous + expectedValues.insert(value, at: index) + if collection.defaulted { + if let carried { + let owner = try direct(parent(pointer)) + let (style, indentation) = try style(at: current.admission.nodes[owner.syntax].range) + let text = + "[" + style.newline + indentation + style.indent + style.indent + + String(decoding: carried, as: UTF8.self) + style.newline + indentation + style.indent + + "]" + try setField(parent(pointer), key(pointer), .array(expectedValues), spelling: text) + } else { + try setField(parent(pointer), key(pointer), .array(expectedValues)) + } + return + } + _ = try direct(pointer) + let node = current.admission.nodes[collection.syntax] + guard node.kind == "array" else { + throw fail("manifest.edit.readOnly", "target is an assembled array") + } + let (style, indentation) = try style(at: node.range) + let multiline = + current.bytes[node.range].contains(10) || current.bytes[node.range].contains(13) + || carried?.contains(10) == true || carried?.contains(13) == true + let rendered = + carried.map { String(decoding: $0, as: UTF8.self) } + ?? CanonicalPrinter(style: style).render( + value, indentation: multiline ? indentation + style.indent : indentation) + if previous.isEmpty { + let interior = (node.range.lowerBound + 1)..<(node.range.upperBound - 1) + if !current.bytes[interior].allSatisfy({ [32, 9, 10, 13].contains($0) }) { + throw fail( + "manifest.edit.readOnly", "comment-only container insertion is ambiguous", range: interior + ) + } + try patch( + interior, + multiline + ? style.newline + indentation + style.indent + rendered + (carried == nil ? "," : "") + + style.newline + indentation : rendered) + } else if index < previous.count { + let child = collection.elementsForUse[index] + let owned = try ownedRange(child, container: node, index: index) + if multiline { + guard owned.lowerBound == lineStart(owned.lowerBound) else { + throw fail("manifest.edit.readOnly", "mixed inline and multiline collection layout") + } + try patch( + owned.lowerBound..= range.upperBound && $0.range.upperBound <= close + } + let gap = range.upperBound.. Int { + var result = offset + while result > 0 && current.bytes[result - 1] != 10 && current.bytes[result - 1] != 13 { + result -= 1 + } + return result + } + private func lineEnd(_ offset: Int) -> Int { + var result = offset + while result < current.bytes.count && current.bytes[result] != 10 && current.bytes[result] != 13 + { result += 1 } + return result + } + private func blankLine(_ range: Range) -> Bool { + let normalized = current.source.spelling(range).replacingOccurrences(of: "\r\n", with: "\n") + .replacingOccurrences(of: "\r", with: "\n") + return normalized.split(separator: "\n", omittingEmptySubsequences: false).dropFirst() + .dropLast().contains { $0.allSatisfy { $0 == " " || $0 == "\t" } } + } + private func ownedRange(_ value: EvaluatedValue, container: GrammarNode, index: Int) throws + -> Range + { + let expressionRange = current.admission.nodes[value.syntax].range + let range = + container.kind == "dictionary" + ? container.keys[index].range.lowerBound..= previous && $0.upperBound <= start + } + for comment in preceding.reversed() { + if blankLine(comment.upperBound..= previous, + current.bytes[line..= previous && current.bytes[line..= end && $0.range.upperBound <= next + } + if let comma { end = comma.range.upperBound } + for comment in current.admission.comments + where comment.lowerBound >= range.upperBound && comment.upperBound <= next { + if comment.lowerBound <= (comma?.range.lowerBound ?? range.upperBound) + || lineStart(comment.lowerBound) == lineStart(end) + { + end = max(end, comment.upperBound) + } + } + let ending = lineEnd(end) + if start == lineStart(start), ending <= next, + current.bytes[end..= current.admission.nodes[value.syntax].range.upperBound + && $0.range.upperBound <= range.upperBound + } + var patches = [SourcePatch(range: range, replacement: [])] + if !hasComma && index > 0 { + let previous = current.admission.nodes[node.children[index - 1]].range.upperBound + if let comma = current.admission.tokens.last(where: { + $0.text == "," && $0.range.lowerBound >= previous && $0.range.upperBound <= range.lowerBound + }) { + patches.append(SourcePatch(range: comma.range, replacement: [])) + } else { + throw fail("manifest.edit.readOnly", "ambiguous separator ownership", range: range) + } + } + values.remove(at: index) + for patch in patches.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { + try self.patch(patch.range, bytes: patch.replacement) + } + try mutate(collectionPointer, .array(values)) + } + + private func move(_ pointer: String, into collection: String, at position: InsertionPosition) + throws + { + let value = try direct(pointer) + let from = parent(pointer) + guard let old = current.values[from], let index = Int(key(pointer)), + let target = current.values[collection], case .array = target.value + else { throw fail("manifest.edit.readOnly", "move requires array containers") } + let destination = try self.position( + position, collection: collection, count: target.elementsForUse.count) + if from == collection && (destination == index || destination == index + 1) { return } + let node = current.admission.nodes[old.syntax] + let owned = try ownedRange(value, container: node, index: index) + let expression = current.admission.nodes[value.syntax].range + let leading = current.source.spelling(owned.lowerBound..= expression.upperBound + && $0.range.upperBound <= owned.upperBound + } + let beforeComma = + comma.map { current.source.spelling(expression.upperBound..<$0.range.lowerBound) } ?? "" + let afterComma = current.source.spelling( + (comma?.range.upperBound ?? expression.upperBound).. index ? destination - 1 : destination + let count = current.values[refreshed]?.elementsForUse.count ?? 0 + let insertion: InsertionPosition + if adjusted == 0 { + insertion = .first + } else if adjusted == count { + insertion = .last + } else { + // Use a current local anchor for the internal move only. + try insertAtIndex(value.value, pointer: refreshed, index: adjusted, carried: carried) + return + } + try insert(value.value, into: refreshed, at: insertion, carried: Array(carried.utf8)) + } + private func insertAtIndex( + _ value: ConstructionValue, pointer: String, index: Int, carried: String + ) throws { + // A direct byte anchor avoids manufacturing a public snapshot handle. + let collection = try direct(pointer) + let node = current.admission.nodes[collection.syntax] + let owned = try ownedRange(collection.elementsForUse[index], container: node, index: index) + let (style, indentation) = try style(at: node.range) + let multiline = current.bytes[node.range].contains(10) + try patch( + owned.lowerBound.. String + { + // Removing a root component cannot move a group definition, and group moves never nest groups. + if let value = current.values[pointer], value.type == previous.type { return pointer } + throw fail("manifest.edit.stale", "destination container changed during move") + } + + private func contextualValue(_ input: StaticValue, as context: ConstructionType) throws + -> ConstructionValue + { + _ = try valueCost(input.value) + if input.type == context || input.type == context.unwrapped { return input.value } + guard input.literal else { + throw fail("manifest.type", "replacement has the wrong contextual type") + } + func convert(_ value: ConstructionValue, _ context: ConstructionType) throws + -> ConstructionValue + { + try charge(1) + if case .optional(let wrapped) = context { + if value == .none { return .none } + return try convert(value, wrapped) + } + switch (value, context) { + case (.text, .named("String")), (.integer, .named("Int")), (.boolean, .named("Bool")): + return value + case (.array(let values), .array(let element)): + return .array(try values.map { try convert($0, element) }) + case (.object(let fields), .dictionary(let element)): + return .object(try fields.mapValues { try convert($0, element) }) + case (.text(let text), .named("Version")): + let version = Version(stringLiteral: text) + guard version.valid else { throw fail("manifest.domain", "invalid version replacement") } + return .version(version) + case (.text, .named("PromptContent")), (.text, .named("RuntimeValue")): + return .node(type: context.name, member: "literal", fields: ["value": value]) + case (.text, .named("SectionReference")), (.text, .named("GroupReference")): + return .node( + type: context.name, member: context.name == "SectionReference" ? "section" : "group", + fields: ["name": value, "source": .none, "condition": .none]) + case (.array(let values), .named("SkillSelection")): + return .node( + type: "SkillSelection", member: "names", + fields: ["names": .array(try values.map { try convert($0, .named("String")) })]) + case (_, .named("ConfigurationValue")): + let kind: String + let payload: ConstructionValue + switch value { + case .text: + kind = "string" + payload = value + case .integer: + kind = "integer" + payload = value + case .boolean: + kind = "boolean" + payload = value + case .none: return .node(type: "ConfigurationValue", member: "null", fields: [:]) + case .array(let values): + kind = "array" + payload = .array(try values.map { try convert($0, context) }) + case .object(let fields): + kind = "object" + payload = .object(try fields.mapValues { try convert($0, context) }) + case .node(let type, _, _) where type == "ConfigurationValue": return value + default: throw fail("manifest.type", "value cannot use configuration literal conversion") + } + return .node(type: "ConfigurationValue", member: kind, fields: ["value": payload]) + default: throw fail("manifest.type", "replacement has the wrong contextual type") + } + } + let result = try convert(input.value, context) + _ = try valueCost(result) + return result + } + + private func dictionary(_ pointer: String, key: String, value replacement: StaticValue?) throws { + let value = try direct(pointer) + if value.type == .named("ConfigurationValue"), value.value.member == "object" { + try dictionary(pointer + "/value", key: key, value: replacement) + return + } + let node = current.admission.nodes[value.syntax] + guard node.kind == "dictionary", case .dictionary(let elementType) = value.type.unwrapped, + case .object(var fields) = value.value + else { throw fail("manifest.edit.readOnly", "target is not a direct dictionary") } + if let replacement { + let replacementValue = try contextualValue(replacement, as: elementType) + if let index = node.keys.firstIndex(where: { $0.decoded == key }) { + let childPointer = pointer + "/" + pointerEscape(key) + try replace(childPointer, with: replacementValue) + _ = index + return + } + let close = node.range.upperBound - 1 + let (style, indentation) = try style(at: node.range) + let text = + quoted(key) + ": " + + CanonicalPrinter(style: style).render( + replacementValue, indentation: indentation + style.indent) + let multiline = current.bytes[node.range].contains(10) + if node.children.isEmpty { + let interior = (node.range.lowerBound + 1)..= end && $0.range.upperBound <= close + } + if multiline { + let at = comma?.range.upperBound ?? end + try patch( + at..= childEnd && $0.range.upperBound <= range.upperBound + } + var patches = [SourcePatch(range: range, replacement: [])] + if !hasComma && index > 0 { + let previous = current.admission.nodes[node.children[index - 1]].range.upperBound + guard + let comma = current.admission.tokens.last(where: { + $0.text == "," && $0.range.lowerBound >= previous + && $0.range.upperBound <= range.lowerBound + }) + else { throw fail("manifest.edit.readOnly", "dictionary separator is ambiguous") } + patches.append(SourcePatch(range: comma.range, replacement: [])) + } + for patch in patches.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { + try self.patch(patch.range, bytes: patch.replacement) + } + fields.removeValue(forKey: key) + if fields.isEmpty { + // The colon is necessary even if retained container whitespace/comments remain. + let opener = node.range.lowerBound + 1 + try patch(opener.. ConstructionValue + { + try charge(1) + if old == new { return expected } + switch (old, new, expected) { + case (.array(let a), .array(let b), .array(let e)) + where a.count == b.count && a.count == e.count: + return .array(try a.indices.map { try merge(a[$0], b[$0], e[$0]) }) + case (.node(let t, let m, let a), .node(let nt, let nm, let b), .node(_, _, let e)) + where t == nt && m == nm && a.keys == b.keys && a.keys == e.keys: + var result = e + for key in a.keys { result[key] = try merge(a[key]!, b[key]!, e[key]!) } + return .node(type: t, member: m, fields: result) + case (.object(let a), .object(let b), .object(let e)) + where a.keys == b.keys && a.keys == e.keys: + var result = e + for key in a.keys { result[key] = try merge(a[key]!, b[key]!, e[key]!) } + return .object(result) + default: return new + } + } + expected = try merge(current.evaluation.root.value, altered.root.value, expected) + impacted += uses + try patch(range, replacementText(replacementValue, at: range)) + if let declaration = current.admission.declarations.first(where: { $0.name == name }), + declaration.type == nil, + needsContext(replacementValue, type: old.type) + { + let offset = declaration.nameRange.upperBound + try patch(offset.. Bool { + switch (value, type) { + case (.text, .named("String")), (.integer, .named("Int")), (.boolean, .named("Bool")): + return false + case (.node(let type, _, _), _) where type == "Agents": return false + case (.array(let values), .array(let element)): + return values.first.map { needsContext($0, type: element) } ?? true + case (.object(let fields), .dictionary(let element)): + return fields.keys.sorted(by: utf8Less).first.map { needsContext(fields[$0]!, type: element) } + ?? true + default: return true + } + } + + private func typeSpelling(_ type: ConstructionType) -> String { + switch type { + case .named(let name): return name + case .array(let element): return "[" + typeSpelling(element) + "]" + case .dictionary(let element): return "[String: " + typeSpelling(element) + "]" + case .optional(let element): return typeSpelling(element) + } + } +} + +extension ConstructionType { + package var name: String { + if case .named(let name) = unwrapped { return name } + return "" + } +} diff --git a/Sources/AgentsManifest/DocumentModels.swift b/Sources/AgentsManifest/DocumentModels.swift new file mode 100644 index 0000000..f7222c9 --- /dev/null +++ b/Sources/AgentsManifest/DocumentModels.swift @@ -0,0 +1,206 @@ +import AgentsCore +import AgentsDescription + +/// An occurrence in one immutable document snapshot, never a persistent component identity. +public struct NodeID: Sendable, Hashable { + package let digest: String + package let pointer: String + package let syntax: Int +} + +public enum ContainerID: Sendable { + case root + case group(NodeID) +} + +public enum InsertionPosition: Sendable { + case first + case last + case before(NodeID) + case after(NodeID) +} + +public enum Editability: Sendable, Equatable { + case direct + case sharedConstant(uses: [NodeID]) + case readOnly(reason: String) +} + +/// Checked values are constructed from the vocabulary or literal algebra, never source text. +public struct StaticValue: Sendable { + package let value: ConstructionValue + package let type: ConstructionType + package let literal: Bool + private init(_ value: ConstructionValue, _ type: ConstructionType, literal: Bool = false) { + self.value = value + self.type = type + self.literal = literal + } + package static func checked(_ value: ConstructionValue, type: ConstructionType) -> Self { + Self(value, type) + } + + public static var null: Self { Self(.none, .named(""), literal: true) } + + public static func string(_ value: String) -> Self { + Self(.text(value), .named("String"), literal: true) + } + public static func integer(_ value: Int) -> Self { + Self(.integer(value), .named("Int"), literal: true) + } + public static func boolean(_ value: Bool) -> Self { + Self(.boolean(value), .named("Bool"), literal: true) + } + public static func configuration(_ value: ConfigurationValue) -> Self { + Self(value.constructionValue, .named("ConfigurationValue")) + } + public static func component(_ value: Component) -> Self { + Self(value.constructionValue, .named("Component")) + } + public static func source(_ value: Source) -> Self { + Self(value.constructionValue, .named("Source")) + } + public static func section(_ value: SectionReference) -> Self { + Self(value.constructionValue, .named("SectionReference")) + } + public static func groupReference(_ value: GroupReference) -> Self { + Self(value.constructionValue, .named("GroupReference")) + } + public static func version(_ value: Version) -> Self { + Self(value.constructionValue, .named("Version")) + } + public static func runtime(_ value: RuntimeValue) -> Self { + Self(value.constructionValue, .named("RuntimeValue")) + } + public static func condition(_ value: Condition) -> Self { + Self(value.constructionValue, .named("Condition")) + } + public static func selection(_ value: AgentsDescription.SkillSelection) -> Self { + Self(value.constructionValue, .named("SkillSelection")) + } + public static func skillOverride(_ value: AgentsDescription.SkillOverride) -> Self { + Self(value.constructionValue, .named("SkillOverride")) + } + public static func prompt(_ value: ChatGPTPrompt) -> Self { + Self(value.constructionValue, .named("ChatGPTPrompt")) + } + public static func resource(_ value: Resource) -> Self { + Self(value.constructionValue, .named("Resource")) + } + public static func promptContent(_ value: PromptContent) -> Self { + Self(value.constructionValue, .named("PromptContent")) + } + public static func executable(_ value: ExecutableInvocation) -> Self { + Self(value.constructionValue, .named("ExecutableInvocation")) + } + public static func transport(_ value: MCPTransport) -> Self { + Self(value.constructionValue, .named("MCPTransport")) + } + public static func parameter(_ value: PromptParameter) -> Self { + Self(value.constructionValue, .named("PromptParameter")) + } + public static func permissionRule(_ value: PermissionRule) -> Self { + Self(value.constructionValue, .named("PermissionRule")) + } + public static func agent(_ value: Agent) -> Self { + Self(value.constructionValue, .named("Agent")) + } + public static func scope(_ value: Scope) -> Self { + Self(value.constructionValue, .named("Scope")) + } + public static func platform(_ value: Platform) -> Self { + Self(value.constructionValue, .named("Platform")) + } + public static func installMode(_ value: AgentsDescription.InstallMode) -> Self { + Self(value.constructionValue, .named("InstallMode")) + } + public static func hookEvent(_ value: HookEvent) -> Self { + Self(value.constructionValue, .named("HookEvent")) + } + public static func permissionOperation(_ value: PermissionOperation) -> Self { + Self(value.constructionValue, .named("PermissionOperation")) + } + public static func ignorePurpose(_ value: IgnorePurpose) -> Self { + Self(value.constructionValue, .named("IgnorePurpose")) + } + public static func pluginMode(_ value: PluginMode) -> Self { + Self(value.constructionValue, .named("PluginMode")) + } + public static func componentKind(_ value: ComponentKind) -> Self { + Self(value.constructionValue, .named("ComponentKind")) + } + public static func componentReference(_ value: ComponentReference) -> Self { + Self(value.constructionValue, .named("ComponentReference")) + } + public static func group(_ value: ComponentGroup) -> Self { + Self(value.constructionValue, .named("ComponentGroup")) + } + public static func agents(_ value: Agents) -> Self { + Self(value.constructionValue, .named("Agents")) + } + public static func array(_ values: [StaticValue]) -> Self { + Self(.array(values.map(\.value)), .array(values.first?.type ?? .named("String")), literal: true) + } + public static func dictionary(_ values: [String: StaticValue]) -> Self { + Self( + .object(values.mapValues(\.value)), + .dictionary(values.values.first?.type ?? .named("String")), literal: true + ) + } +} + +public enum ManifestEdit: Sendable { + case setDefaultAgents([Agent]?) + case upsertSource(Source) + case removeSource(alias: String) + case insertComponent(Component, into: ContainerID, at: InsertionPosition) + case replaceComponent(NodeID, with: Component) + case removeComponent(NodeID) + case moveComponent(NodeID, into: ContainerID, at: InsertionPosition) + case setSkillSelection(NodeID, AgentsDescription.SkillSelection) + case upsertSkillOverride(NodeID, AgentsDescription.SkillOverride) + case removeSkillOverride(NodeID, name: String) + case insertSection(SectionReference, into: NodeID, at: InsertionPosition) + case removeSection(NodeID) + case moveSection(NodeID, at: InsertionPosition) + case upsertPrompt(NodeID, ChatGPTPrompt) + case removePrompt(NodeID, name: String) + case upsertGroup(ComponentGroup) + case removeGroup(name: String) + case insertGroupReference(GroupReference, into: ContainerID, at: InsertionPosition) + case removeGroupReference(NodeID) + case setExports([String]) + case setWatch([String]) + case setDictionaryEntry(NodeID, key: String, value: StaticValue) + case removeDictionaryEntry(NodeID, key: String) + case replaceConstant(NodeID, with: StaticValue, acceptingUses: [NodeID]) +} + +public struct SemanticDelta: Sendable, Equatable { + public let changedPointers: [String] +} + +public struct DocumentChange: Sendable { + public let originalDigest: String + public let patches: [SourcePatch] + public let bytes: [UInt8] + public let digest: String + public let expectedDeclaration: DeclarationIR + public let impactedReferences: [NodeID] + public let diagnostics: [ManifestDiagnostic] + public let delta: SemanticDelta + package init( + originalDigest: String, patches: [SourcePatch], bytes: [UInt8], digest: String, + expectedDeclaration: DeclarationIR, impactedReferences: [NodeID], + diagnostics: [ManifestDiagnostic], delta: SemanticDelta + ) { + self.originalDigest = originalDigest + self.patches = patches + self.bytes = bytes + self.digest = digest + self.expectedDeclaration = expectedDeclaration + self.impactedReferences = impactedReferences + self.diagnostics = diagnostics + self.delta = delta + } +} diff --git a/Sources/AgentsManifest/DomainValidation.swift b/Sources/AgentsManifest/DomainValidation.swift new file mode 100644 index 0000000..de20e42 --- /dev/null +++ b/Sources/AgentsManifest/DomainValidation.swift @@ -0,0 +1,440 @@ +import AgentsCore +import AgentsDescription +import Foundation + +package final class DomainValidator { + private let source: SourceText + private let admission: Admission + private let evaluation: Evaluation + private var diagnostics: [ManifestDiagnostic] = [] + private var aliases: [String: ConstructionValue] = [:] + private var groups: [String: EvaluatedValue] = [:] + private var work = 0 + + package init(source: SourceText, admission: Admission, evaluation: Evaluation) { + self.source = source + self.admission = admission + self.evaluation = evaluation + } + + private func failure( + _ message: String, _ value: EvaluatedValue, code: String = "manifest.domain", + related: [SourceSpan] = [] + ) -> ManifestFailure { + ManifestFailure( + ManifestDiagnostic( + code: code, message: message, span: source.span(admission.nodes[value.syntax].range), + related: related)) + } + + package func validate() throws -> [ManifestDiagnostic] { + let root = evaluation.root + let fields = root.value.fields + var identities: [String: EvaluatedValue] = [:] + let sources = root.field("sources")?.elementsForUse ?? [] + for value in sources { + let f = value.value.fields + let name = f["name"]?.text ?? "" + guard !name.isEmpty, name != ".", !name.contains(":"), aliases[name] == nil else { + throw failure("invalid or duplicate source alias", value) + } + aliases[name] = value.value + let identity: String + if let url = f["url"]?.text { + let declaration = SourceDeclaration(kind: .git, location: url) + do { identity = try declaration.transportIdentity() } catch { + throw failure("invalid Git URL", value.field("url") ?? value) + } + if declaration.gitURL != url { + let target = value.field("url") ?? value + let range = admission.nodes[target.syntax].range + if diagnostics.count < 100 { + diagnostics.append( + ManifestDiagnostic( + code: "manifest.domain", severity: .warning, + message: "use the complete Git transport URL", span: source.span(range), + fixIt: SourcePatch( + range: range, replacement: Array(quoted(declaration.gitURL).utf8)))) + } else if diagnostics.count == 100 { + diagnostics.append( + ManifestDiagnostic( + code: "manifest.diagnostics.truncated", severity: .warning, + message: "further diagnostics omitted", span: source.span(range))) + } + } + } else if let index = f["index"]?.text { + do { + identity = try SourceDeclaration(kind: .wellKnown, location: index).transportIdentity() + } catch { throw failure("invalid index URL", value) } + } else { + let location = f["path"]?.text ?? "" + if location.isEmpty || location.contains("\0") { + throw failure("empty or invalid local source", value) + } + identity = "local:" + lexicalPath(location) + } + if let original = identities[identity] { + throw failure( + "two aliases normalize to the same source identity", value, + related: [source.span(admission.nodes[original.syntax].range)]) + } + identities[identity] = value + } + for value in root.field("groups")?.elementsForUse ?? [] { + let name = value.value.fields["name"]?.text ?? "" + if groups[name] != nil { throw failure("duplicate group name", value) } + groups[name] = value + } + try unique(fields["exports"]?.array ?? [], at: root, message: "duplicate export") + for name in fields["exports"]?.strings ?? [] where groups[name] == nil { + throw failure("unknown exported group: \(name)", root, code: "manifest.group.missing") + } + try unique(fields["watch"]?.array ?? [], at: root, message: "duplicate watch subscription") + for name in fields["watch"]?.strings ?? [] where aliases[name] == nil { + throw failure("unknown watch source: \(name)", root) + } + // All definitions, including unused constants and inactive values, get domain checks. + for value in evaluation.constants.values { try walk(value, anchor: value) } + var completed = Set() + for (name, value) in groups { + try cycle(name, stack: [], spans: [], value: value, completed: &completed) + } + return diagnostics.sorted { ($0.span.start, $0.code) < ($1.span.start, $1.code) } + } + + private func walk(_ value: EvaluatedValue, anchor: EvaluatedValue) throws { + var pending = [(value, anchor)] + while let (value, anchor) = pending.popLast() { + work += 1 + if work > 100_000 { throw failure("domain traversal budget", anchor, code: "manifest.limit") } + if let referent = value.referent { + pending.append((referent, value)) + continue + } + try check(value.value, at: value) + let children = + !value.fields.isEmpty + ? Array(value.fields.values) : value.elements + if children.isEmpty { + try checkChildren(value.value, at: value) + } else { + for child in children { pending.append((child, anchor)) } + } + } + } + + private func checkChildren(_ value: ConstructionValue, at anchor: EvaluatedValue) throws { + let children: [ConstructionValue] + switch value { + case .node(_, _, let fields), .object(let fields): children = Array(fields.values) + case .array(let values): children = values + default: return + } + for child in children { + work += 1 + if work > 100_000 { throw failure("domain traversal budget", anchor, code: "manifest.limit") } + try check(child, at: anchor) + try checkChildren(child, at: anchor) + } + } + + private func check(_ value: ConstructionValue, at anchor: EvaluatedValue) throws { + guard case .node(let type, let member, let f) = value else { return } + if let agents = f["agents"]?.array { + try unique(agents, at: anchor, message: "duplicate recipients") + } + switch type { + case "Agents": + if let defaults = f["defaultAgents"]?.array { + try unique(defaults, at: anchor, message: "duplicate default recipients") + } + case "Condition": + for dimension in ["agents", "scopes", "platforms"] { + if let array = f[dimension]?.array { + try unique(array, at: anchor, message: "duplicate condition member") + } + } + case "Source": + let alias = f["name"]?.text ?? "" + if alias.isEmpty || alias == "." || alias.contains(":") { + throw failure("invalid source alias", anchor) + } + if let url = f["url"]?.text { + do { _ = try SourceDeclaration(kind: .git, location: url).transportIdentity() } catch { + throw failure("invalid Git URL", anchor) + } + } else if let index = f["index"]?.text { + do { + _ = try SourceDeclaration(kind: .wellKnown, location: index).transportIdentity() + } catch { throw failure("invalid index URL", anchor) } + } else if let path = f["path"]?.text, path.isEmpty || path.contains("\0") { + throw failure("invalid local source location", anchor) + } + if let path = f["subpath"]?.text { try resource(path, anchor) } + if let requirement = f["requirement"] { + if case .node(_, let kind, let fields) = requirement, ["branch", "revision"].contains(kind) + { + let text = fields["value"]?.text ?? "" + if text.isEmpty || text.hasPrefix("-") || text.contains("\0") { + throw failure("invalid source requirement", anchor) + } + } + } + case "ComponentGroup": try name(f["name"]?.text ?? "", anchor) + case "GroupReference": + let group = f["name"]?.text ?? "" + try name(group, anchor) + if let alias = f["source"]?.text { + try sourceAlias(alias, anchor) + } else if groups[group] == nil { + throw failure("unknown local group: \(group)", anchor, code: "manifest.group.missing") + } + case "SectionReference": + if !Declaration.isInstructionName(f["name"]?.text ?? "") { + throw failure("invalid instruction section name", anchor) + } + if let alias = f["source"]?.text { try sourceAlias(alias, anchor) } + case "ChatGPTPrompt": + if let append = f["append"]?.text { try resource(append, anchor) } + case "Resource", "PromptContent": + if let path = f["path"]?.text { try resource(path, anchor) } + if let alias = f["source"]?.text { try sourceAlias(alias, anchor) } + case "ExecutableInvocation", "MCPTransport": + if let executable = f["executable"]?.text { + if executable.isEmpty || executable.contains("\0") { + throw failure("invalid executable", anchor) + } + if executable.contains("/") || executable.hasPrefix("~") { + try resource(executable, anchor) + } + } + if type == "MCPTransport" && member != "stdio" { try http(f["url"]?.text ?? "", anchor) } + case "ConfigurationValue": + if member == "decimal" { + let text = f["value"]?.text ?? "" + let valid = + text.range( + of: #"^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?$"#, options: .regularExpression) + != nil + if !valid || Double(text)?.isFinite != true { + throw failure("decimal requires finite JSON-number text", anchor) + } + } + case "PromptParameter": + let n = f["name"]?.text ?? "" + if n.isEmpty || n.contains("}") || n.contains(":") || n.contains("\0") { + throw failure("invalid prompt parameter name", anchor) + } + case "ComponentReference": try name(f["name"]?.text ?? "", anchor) + case "PermissionRule": + if ["read", "write"].contains(f["operation"]?.member ?? "") { + try resource(f["pattern"]?.text ?? "", anchor) + } + case "Component": try component(member, fields: f, anchor: anchor) + default: break + } + } + + private func component( + _ kind: String, fields f: [String: ConstructionValue], anchor: EvaluatedValue + ) throws { + if let n = f["name"]?.text { try name(n, anchor) } + if kind == "skills" { + let alias = f["source"]?.text ?? "" + try sourceAlias(alias, anchor) + let selection = f["select"]! + let names = selection.fields["names"]?.strings + if let names { try skillNames(names, anchor) } + try skillNames(f["exclude"]?.strings ?? [], anchor) + let overrides = f["overrides"]?.array ?? [] + try uniqueNames(overrides, anchor) + for override in overrides { + let n = override.fields["name"]?.text ?? "" + try skillNames([n], anchor) + if let names, !names.contains(n) { + throw failure("override is outside explicit skill selection", anchor) + } + } + let modes = [f["mode"]].compactMap { $0 } + overrides.compactMap { $0.fields["mode"] } + if modes.contains(where: { $0.member == "edit" }) { + if alias != ".", let source = aliases[alias], + source.fields["path"]?.text == nil + || source.fields["requirement"] != ConstructionValue.none + { + throw failure("edit mode needs a local source without a requirement", anchor) + } + } + } + if kind == "instructions" { try uniqueNames(f["chatGPT"]?.array ?? [], anchor) } + if kind == "hook" { + if case .integer(let timeout) = f["timeoutSeconds"], timeout <= 0 { + throw failure("hook timeout must be positive", anchor) + } + if f["event"]?.member == "native", f["agents"]?.array?.count != 1 { + throw failure("native hook event requires exactly one explicit recipient", anchor) + } + } + if kind == "plugin" { + try sourceAlias(f["source"]?.text ?? "", anchor) + try resource(f["path"]?.text ?? "", anchor) + if f["mode"]?.member == "native" { + if f["agents"]?.array?.count != 1 || f["select"] != ConstructionValue.none + || !(f["exclude"]?.array ?? []).isEmpty + { + throw failure( + "native plugin requires one explicit recipient and no selection/exclusions", anchor) + } + } + if let selection = f["select"]?.array { + try unique(selection, at: anchor, message: "duplicate plugin selection") + } + try unique(f["exclude"]?.array ?? [], at: anchor, message: "duplicate plugin exclusion") + } + if kind == "lspServer", case .object(let languages) = f["languages"] { + if languages.keys.contains(where: { + !$0.hasPrefix(".") || $0.count <= 1 || $0.contains("/") || $0.contains("\0") + }) || languages.values.contains(where: { $0.text?.isEmpty != false }) { + throw failure("invalid language extension mapping", anchor) + } + } + if kind == "command" { + let parameters = f["parameters"]?.array ?? [] + try uniqueNames(parameters, anchor) + let declared = Set(parameters.compactMap { $0.fields["name"]?.text }) + if f["prompt"]?.member == "literal", let prompt = f["prompt"]?.fields["value"]?.text { + let bytes = Array(prompt.utf8) + var i = 0 + let escapedInput = Array("$${input:".utf8) + let input = Array("${input:".utf8) + while i < bytes.count { + if bytes[i...].starts(with: escapedInput) { + i += 2 + while i < bytes.count && bytes[i] != 125 { i += 1 } + } else if bytes[i...].starts(with: input) { + let first = i + 8 + i = first + while i < bytes.count && bytes[i] != 125 { i += 1 } + if i == bytes.count + || !declared.contains(String(decoding: bytes[first.. + ) throws { + if stack.contains(name) { + throw failure( + "local group reference cycle: \((stack + [name]).joined(separator: " -> "))", value, + code: "manifest.group.cycle", related: spans) + } + if completed.contains(name) { return } + if stack.count == 64 { + throw failure("local group reference depth", value, code: "manifest.limit") + } + for reference in value.field("uses")?.elementsForUse ?? [] + where reference.value.fields["source"] == ConstructionValue.none { + let next = reference.value.fields["name"]?.text ?? "" + if let child = groups[next] { + try cycle( + next, stack: stack + [name], + spans: spans + [source.span(admission.nodes[reference.syntax].range)], value: child, + completed: &completed) + } + } + completed.insert(name) + } + + private func sourceAlias(_ alias: String, _ anchor: EvaluatedValue) throws { + if alias != "." && aliases[alias] == nil { + throw failure("unknown source alias: \(alias)", anchor) + } + } + private func unique(_ values: [ConstructionValue], at anchor: EvaluatedValue, message: String) + throws + { + var seen = Set() + for value in values { + let key = value.text ?? value.member + ":" + (value.fields["name"]?.text ?? "") + if !seen.insert(key).inserted { throw failure(message, anchor) } + } + } + private func uniqueNames(_ values: [ConstructionValue], _ anchor: EvaluatedValue) throws { + try unique( + values.map { .text($0.fields["name"]?.text ?? "") }, at: anchor, + message: "duplicate named member") + } + private func skillNames(_ names: [String], _ anchor: EvaluatedValue) throws { + do { try Declaration.validateNames(names) } catch { + throw failure("invalid or duplicate skill names", anchor) + } + } + private func name(_ value: String, _ anchor: EvaluatedValue) throws { + let parts = value.split(separator: "/", omittingEmptySubsequences: false) + if parts.isEmpty || parts.contains(where: { $0.isEmpty || $0 == "." || $0 == ".." }) + || value.contains(":") || value.contains("\\") + || value.unicodeScalars.contains(where: { $0.value < 32 || $0.value == 127 }) + { + throw failure("invalid relative name", anchor) + } + } + private func resource(_ path: String, _ anchor: EvaluatedValue) throws { + if path == "~" || path.hasPrefix("~/") { + throw failure("resource needs a safe relative path", anchor) + } + do { _ = try PathSafety.sanitizeSubpath(path) } catch { + throw failure("resource needs a safe relative path", anchor) + } + } + private func http(_ text: String, _ anchor: EvaluatedValue) throws { + guard let url = URLComponents(string: text), + ["http", "https"].contains(url.scheme?.lowercased() ?? ""), + url.host?.isEmpty == false, url.user == nil, url.password == nil, url.fragment == nil + else { throw failure("transport needs an HTTP(S) URL without credentials or fragment", anchor) } + } + private func lexicalPath(_ path: String) -> String { + let prefix = path.hasPrefix("/") ? "/" : path.hasPrefix("~/") ? "~/" : "" + let body = prefix.isEmpty ? path[...] : path.dropFirst(prefix.count) + var parts: [Substring] = [] + for part in body.split(separator: "/") { + if part == "." { continue } + if part == "..", let last = parts.last, last != ".." { + parts.removeLast() + } else { + parts.append(part) + } + } + return prefix + parts.joined(separator: "/") + } +} + +extension ConstructionValue { + package var text: String? { + if case .text(let value) = self { return value } + return nil + } + package var array: [ConstructionValue]? { + if case .array(let value) = self { return value } + return nil + } + package var strings: [String]? { array?.compactMap(\.text) } + package var fields: [String: ConstructionValue] { + if case .node(_, _, let fields) = self { return fields } + return [:] + } + package var member: String { + if case .node(_, let member, _) = self { return member } + return "" + } +} + +extension EvaluatedValue { + package func field(_ name: String) -> EvaluatedValue? { referent?.field(name) ?? fields[name] } +} diff --git a/Sources/AgentsManifest/Evaluation.swift b/Sources/AgentsManifest/Evaluation.swift new file mode 100644 index 0000000..2cc5f0a --- /dev/null +++ b/Sources/AgentsManifest/Evaluation.swift @@ -0,0 +1,387 @@ +import AgentsDescription + +package struct Evaluation: Sendable { + package let root: EvaluatedValue + package let constants: [String: EvaluatedValue] + package let expressions: [Int: EvaluatedValue] + package let references: [String: [Int]] + package let steps: Int + package let total: ValueCost +} + +package final class Evaluator { + private let source: SourceText + private let admission: Admission + private let replacements: [String: StaticValue] + private var constants: [String: EvaluatedValue] = [:] + private var expressions: [Int: EvaluatedValue] = [:] + private var references: [String: [Int]] = [:] + private var steps = 0 + private var frames = 0 + private var total = ValueCost(nodes: 0, strings: 0, encoded: 0, depth: 0, origins: 0) + + package init(source: SourceText, admission: Admission, replacements: [String: StaticValue] = [:]) + { + self.source = source + self.admission = admission + self.replacements = replacements + } + + private func fail(_ code: String, _ message: String, _ id: Int) -> ManifestFailure { + source.failure( + code, message, admission.nodes[id].range.lowerBound, end: admission.nodes[id].range.upperBound + ) + } + private func charge(_ amount: Int = 1, at id: Int) throws { + guard amount <= 100_000 - steps else { + throw fail("manifest.limit", "evaluation work steps", id) + } + steps += amount + } + private func check(_ cost: ValueCost, at id: Int) throws { + guard cost.fits else { + throw fail("manifest.limit", "expanded value budget (nodes, bytes, depth or origins)", id) + } + } + + package func evaluate() throws -> Evaluation { + for declaration in admission.declarations { + if constants[declaration.name] != nil || Vocabulary.typeNames.contains(declaration.name) { + throw source.failure( + "manifest.reference", "duplicate or shadowing constant", declaration.nameRange.lowerBound, + end: declaration.nameRange.upperBound) + } + let value: EvaluatedValue + if let replacement = replacements[declaration.name] { + let cost = constructionCost(replacement.value) + try check(cost, at: declaration.expression) + value = EvaluatedValue( + type: replacement.type, value: replacement.value, cost: cost, + syntax: declaration.expression) + } else { + value = try evaluate(declaration.expression, context: declaration.type) + } + try check(value.cost, at: declaration.expression) + let next = ValueCost( + nodes: ValueCost.add(total.nodes, value.cost.nodes), + strings: ValueCost.add(total.strings, value.cost.strings), + encoded: ValueCost.add(total.encoded, value.cost.encoded), + depth: max(total.depth, value.cost.depth), + origins: ValueCost.add(total.origins, value.cost.origins)) + try check(next, at: declaration.expression) + total = next + constants[declaration.name] = value + } + guard let root = constants["agents"], root.type == .named("Agents"), + let declaration = admission.declarations.first(where: { $0.name == "agents" }), + admission.nodes[declaration.expression].kind == "call", + admission.nodes[declaration.expression].text == "Agents" + else { + throw source.failure( + "manifest.type", "one let agents = Agents(...) is required", source.bytes.count) + } + return Evaluation( + root: root, constants: constants, expressions: expressions, references: references, + steps: steps, total: total) + } + + private func evaluate(_ id: Int, context: ConstructionType?) throws -> EvaluatedValue { + try charge(at: id) + frames += 1 + defer { frames -= 1 } + guard frames <= 64 else { throw fail("manifest.limit", "evaluation frames", id) } + let node = admission.nodes[id] + let expected = context?.unwrapped + let result: EvaluatedValue + if node.kind == "nil", case .optional = context { + result = EvaluatedValue(type: context!, value: .none, cost: ValueCost(), syntax: id) + } else { + switch node.kind { + case "group": + let child = try evaluate(node.children[0], context: context) + result = EvaluatedValue( + type: child.type, value: child.value, cost: child.cost, syntax: id, referent: child) + case "string": + result = try literal( + .text(node.text), kind: "string", inferred: "String", context: expected, id: id) + case "integer", "negative": + let raw = (node.kind == "negative" ? "-" : "") + node.text.filter { $0 != "_" } + guard let integer = Int(raw) else { + throw fail("manifest.type", "integer literal must fit signed 64-bit Int", id) + } + result = try literal( + .integer(integer), kind: "integer", inferred: "Int", context: expected, id: id) + case "boolean": + result = try literal( + .boolean(node.text == "true"), kind: "boolean", inferred: "Bool", context: expected, + id: id) + case "nil": + result = try literal(.none, kind: "nil", inferred: "", context: expected, id: id) + case "array", "dictionary": result = try collection(id, context: expected) + case "sequence": + var arrayType = expected + if let expected, case .array = expected { + } else if expected != nil { + throw fail("manifest.operator", "+ requires exact Swift array operands", id) + } + var operands: [EvaluatedValue] = [] + var count = 0 + var costs: [ValueCost] = [] + for child in node.children { + let value = try evaluate(child, context: arrayType) + guard case .array = value.type, case .array = value.value else { + throw fail("manifest.operator", "+ requires exact Swift arrays", child) + } + arrayType = value.type + count += value.elementsForUse.count + if count > 10_000 { throw fail("manifest.limit", "concatenation entries", id) } + // Cost is combined before copying any concatenated elements. + operands.append(value) + costs.append(contentsOf: value.elementsForUse.map(\.cost)) + } + let cost = ValueCost.container(costs) + try check(cost, at: id) + try charge(count, at: id) + let elements = operands.flatMap(\.elementsForUse) + result = EvaluatedValue( + type: arrayType!, value: .array(elements.map(\.value)), cost: cost, syntax: id, + elements: elements) + case "range": + let lower = try evaluate(node.children[0], context: .named("Version")) + let upper = try evaluate(node.children[1], context: .named("Version")) + guard case .version(let l) = lower.value, case .version(let u) = upper.value, l < u else { + throw fail("manifest.domain", "version range must be increasing", id) + } + let cost = ValueCost.container([lower.cost, upper.cost]) + try check(cost, at: id) + result = EvaluatedValue( + type: .named("VersionRange"), value: .range(l..= 63 { + throw fail("manifest.limit", "active reference frames", id) + } + references[node.text, default: []].append(id) + var cost = bound.cost + cost.origins = ValueCost.add(cost.origins, cost.nodes) + try check(cost, at: id) + result = EvaluatedValue( + type: bound.type, value: bound.value, cost: cost, syntax: id, referent: bound) + } else { + result = try call(id, context: expected) + } + default: throw fail("manifest.syntax", "unhandled admitted production", id) + } + } + try check(result.cost, at: id) + if let context { + if result.type != context && result.type != context.unwrapped { + throw fail("manifest.type", "value does not match contextual type", id) + } + } + try charge(at: id) + expressions[id] = result + return result + } + + private func literal( + _ value: ConstructionValue, kind: String, inferred: String, context: ConstructionType?, id: Int + ) throws -> EvaluatedValue { + let type = context ?? .named(inferred) + let converted: ConstructionValue + if type == .named(inferred), !inferred.isEmpty { + converted = value + } else if case .named(let name) = type, Vocabulary.literalTypes[name]?.contains(kind) == true { + switch name { + case "Version": + guard case .text(let text) = value else { + throw fail("manifest.type", "version requires a string literal", id) + } + let version = Version(stringLiteral: text) + guard version.valid else { throw fail("manifest.domain", "invalid semantic version", id) } + converted = .version(version) + case "SectionReference", "GroupReference": + converted = .node( + type: name, member: name == "SectionReference" ? "section" : "group", + fields: ["name": value, "source": .none, "condition": .none]) + case "PromptContent", "RuntimeValue": + converted = .node(type: name, member: "literal", fields: ["value": value]) + case "ConfigurationValue": + converted = .node( + type: name, member: kind == "nil" ? "null" : kind, + fields: kind == "nil" ? [:] : ["value": value]) + default: throw fail("manifest.type", "unsupported literal conversion", id) + } + } else { + throw fail("manifest.type", "literal needs a compatible context", id) + } + return EvaluatedValue( + type: type, value: converted, cost: constructionCost(converted), syntax: id) + } + + private func collection(_ id: Int, context: ConstructionType?) throws -> EvaluatedValue { + let node = admission.nodes[id] + let dictionary = node.kind == "dictionary" + if node.children.count > 10_000 { throw fail("manifest.limit", "collection entries", id) } + let wrapper: String? + var elementType: ConstructionType? + switch context { + case .array(let type) where !dictionary: + elementType = type + wrapper = nil + case .dictionary(let type) where dictionary: + elementType = type + wrapper = nil + case .named("NativeConfiguration") where dictionary: + elementType = .dictionary(.named("ConfigurationValue")) + wrapper = nil + case .named("ConfigurationValue"): + elementType = .named("ConfigurationValue") + wrapper = "ConfigurationValue" + case .named("SkillSelection") where !dictionary: + elementType = .named("String") + wrapper = "SkillSelection" + case nil: wrapper = nil + default: throw fail("manifest.type", "collection is incompatible with contextual type", id) + } + var values: [EvaluatedValue] = [] + var fields: [String: EvaluatedValue] = [:] + var keySpans: [String: Range] = [:] + for (offset, child) in node.children.enumerated() { + if dictionary { + let key = node.keys[offset].decoded! + if let original = keySpans[key] { + throw ManifestFailure( + ManifestDiagnostic( + code: "manifest.dictionary.duplicateKey", message: "duplicate decoded dictionary key", + span: source.span(node.keys[offset].range), related: [source.span(original)])) + } + keySpans[key] = node.keys[offset].range + } + let value = try evaluate(child, context: elementType) + if elementType == nil { elementType = value.type } + values.append(value) + if dictionary { fields[node.keys[offset].decoded!] = value } + } + guard let elementType else { + throw fail("manifest.type", "empty collection needs a contextual type", id) + } + var cost = ValueCost.container( + values.map(\.cost), keys: dictionary ? node.keys.map { $0.decoded! } : []) + if wrapper != nil { + cost.nodes += 1 + cost.depth += 1 + cost.encoded += 32 + } + try check(cost, at: id) + let payload: ConstructionValue = + dictionary ? .object(fields.mapValues(\.value)) : .array(values.map(\.value)) + let value: ConstructionValue + let type: ConstructionType + if let wrapper { + type = .named(wrapper) + value = .node( + type: wrapper, + member: wrapper == "SkillSelection" ? "names" : (dictionary ? "object" : "array"), + fields: [wrapper == "SkillSelection" ? "names" : "value": payload]) + } else { + type = dictionary ? .dictionary(elementType) : .array(elementType) + value = payload + } + return EvaluatedValue( + type: type, value: value, cost: cost, syntax: id, fields: fields, + elements: dictionary ? [] : values) + } + + private func call(_ id: Int, context: ConstructionType?) throws -> EvaluatedValue { + let node = admission.nodes[id] + let parts = node.text.split(separator: ".", omittingEmptySubsequences: false).map(String.init) + let name: String + let member: String + if node.text == "Agents", node.kind == "call" { + name = "Agents" + member = "Agents" + } else if parts.count == 2, parts[0].isEmpty { + guard case .named(let expected) = context else { + throw fail("manifest.type", "shorthand factory or member needs a named context", id) + } + name = expected + member = parts[1] + } else if parts.count == 2, Vocabulary.typeNames.contains(parts[0]) { + name = parts[0] + member = parts[1] + } else { + throw fail("manifest.call", "unlisted call or member", id) + } + let candidates = Vocabulary.signatures.filter { + $0.type == name && $0.member == member && $0.callable == (node.kind == "call") + } + var match: ConstructionSignature? + for signature in candidates { + var argument = 0 + var valid = true + for parameter in signature.parameters { + if argument < node.arguments.count && node.arguments[argument].label == parameter.label { + argument += 1 + } else if parameter.defaultValue == nil { + valid = false + break + } + } + if valid && argument == node.arguments.count { + match = signature + break + } + } + guard let signature = match else { + throw fail("manifest.call", "unlisted factory/case or incorrect labels/order", id) + } + var fields: [String: EvaluatedValue] = [:] + var argument = 0 + for parameter in signature.parameters { + if argument < node.arguments.count && node.arguments[argument].label == parameter.label { + fields[parameter.name] = try evaluate( + node.arguments[argument].value, context: parameter.type) + argument += 1 + } else { + let value = parameter.defaultValue! + fields[parameter.name] = EvaluatedValue( + type: parameter.type, value: value, cost: constructionCost(value), syntax: id, + defaulted: true) + } + } + var cost = ValueCost.container( + fields.values.map(\.cost), keys: [name, member] + Array(fields.keys)) + if name == "VersionRange" { + guard case .version(let lower) = fields["from"]?.value, + lower.successor(major: member == "upToNextMajor").valid + else { throw fail("manifest.domain", "version successor overflow", id) } + } + if name == "Source", case .version(let lower) = fields["from"]?.value, + !lower.successor(major: true).valid + { + throw fail("manifest.domain", "version successor overflow", id) + } + try check(cost, at: id) + try charge(fields.count + 1, at: id) + let value = ConstructionValue.construct( + type: name, member: member, fields: fields.mapValues(\.value)) + // Canonical source requirements charge both range endpoints before lowering. + if name == "Source" { cost = constructionCost(value) } + try check(cost, at: id) + return EvaluatedValue(type: .named(name), value: value, cost: cost, syntax: id, fields: fields) + } +} + +extension EvaluatedValue { + package var elementsForUse: [EvaluatedValue] { + var value = self + while let next = value.referent { value = next } + return value.elements + } +} diff --git a/Sources/AgentsManifest/Lowering.swift b/Sources/AgentsManifest/Lowering.swift new file mode 100644 index 0000000..d176c05 --- /dev/null +++ b/Sources/AgentsManifest/Lowering.swift @@ -0,0 +1,67 @@ +import AgentsCore +import AgentsDescription + +package enum Lowering { + package static func declaration(_ value: ConstructionValue) -> DeclarationIR { + let fields = value.fields + return DeclarationIR( + defaultAgents: fields["defaultAgents"]?.array?.compactMap { lower($0).string }, + exports: fields["exports"]?.strings ?? [], + sources: (fields["sources"]?.array ?? []).compactMap { lower($0).record }, + components: (fields["components"]?.array ?? []).compactMap { lower($0).record }, + groups: (fields["groups"]?.array ?? []).compactMap { lower($0).record }, + uses: (fields["uses"]?.array ?? []).compactMap { lower($0).record }, + watch: fields["watch"]?.strings ?? []) + } + + package static func requirement(_ range: Range) -> SourceRequirement { + let lower = range.lowerBound + let upper = range.upperBound + let major = lower.successor(major: true) + let minor = lower.successor(major: false) + if major.valid && upper == major { return .upToNextMajor(from: lower.normalized) } + if minor.valid && upper == minor { return .upToNextMinor(from: lower.normalized) } + return .range(from: lower.normalized, to: upper.normalized) + } + + package static func lower(_ value: ConstructionValue) -> DeclarationValue { + switch value { + case .text(let text): return .string(text) + case .integer(let integer): return .integer(integer) + case .boolean(let boolean): return .boolean(boolean) + case .none: return .null + case .version(let version): return .string(version.normalized) + case .range(let range): return .requirement(requirement(range)) + case .array(let values): return .array(values.map(lower)) + case .object(let fields): return .dictionary(fields.mapValues(lower)) + case .node(let type, let member, let fields): + let scalarEnums: Set = [ + "Agent", "Scope", "Platform", "InstallMode", "IgnorePurpose", "PluginMode", "ComponentKind", + ] + if scalarEnums.contains(type) { + let ids = [ + "claudeCode": "claude-code", "geminiCLI": "gemini-cli", "openCode": "opencode", + "macOS": "macos", + ] + return .string(ids[member] ?? member) + } + if type == "SkillSelection" { + return member == "all" ? .string("all") : .array((fields["names"]?.array ?? []).map(lower)) + } + if type == "Requirement", let text = fields["value"]?.text { + return .requirement( + member == "exact" ? .exact(text) : member == "branch" ? .branch(text) : .revision(text)) + } + var lowered = fields.mapValues(lower) + var kind = member + if type == "Source" { + kind = fields["url"] != nil ? "git" : fields["path"] != nil ? "local" : "index" + if let url = fields["url"]?.text { + lowered["url"] = .string(SourceDeclaration(kind: .git, location: url).gitURL) + } + } + if type == "GroupReference" { kind = fields["source"]?.text == nil ? "local" : "exported" } + return .record(DeclarationRecord(kind: kind, fields: lowered)) + } + } +} diff --git a/Sources/AgentsManifest/ManifestDiagnostic.swift b/Sources/AgentsManifest/ManifestDiagnostic.swift new file mode 100644 index 0000000..baa4c57 --- /dev/null +++ b/Sources/AgentsManifest/ManifestDiagnostic.swift @@ -0,0 +1,109 @@ +import AgentsCore + +public struct ManifestDiagnostic: Sendable, Equatable { + public enum Severity: String, Sendable { case warning, error } + public let code: String + public let severity: Severity + public let message: String + public let span: SourceSpan + public let related: [SourceSpan] + public let fixIt: SourcePatch? + + public init( + code: String, severity: Severity = .error, message: String, span: SourceSpan, + related: [SourceSpan] = [], fixIt: SourcePatch? = nil + ) { + self.code = code + self.severity = severity + self.message = message + self.span = span + self.related = related + self.fixIt = fixIt + } +} + +public struct ManifestFailure: Error, Sendable { + public let diagnostics: [ManifestDiagnostic] + public let metrics: FrontEndMetrics + package init(_ diagnostic: ManifestDiagnostic, metrics: FrontEndMetrics = FrontEndMetrics()) { + diagnostics = [diagnostic] + self.metrics = metrics + } +} + +public struct SourcePatch: Sendable, Equatable { + public let range: Range + public let replacement: [UInt8] + package init(range: Range, replacement: [UInt8]) { + self.range = range + self.replacement = replacement + } +} + +public struct FrontEndMetrics: Sendable, Codable { + public package(set) var parserCalls = 0 + public package(set) var tokens = 0 + public package(set) var syntaxReservation = 0 + public package(set) var syntaxNodes = 0 + public package(set) var syntaxDepth = 0 + public package(set) var evaluationSteps = 0 + public package(set) var expandedNodes = 0 + public package(set) var decodedBytes = 0 + public package(set) var admissionSeconds = 0.0 + public package(set) var parsingSeconds = 0.0 + public package(set) var guardSeconds = 0.0 + public package(set) var inspectionSeconds = 0.0 + public package(set) var evaluationSeconds = 0.0 + public package(set) var domainSeconds = 0.0 + public package(set) var loweringSeconds = 0.0 + public package(set) var sourceMapSeconds = 0.0 + public package(set) var teardownSeconds = 0.0 + public init() {} +} + +package struct SourceText: Sendable { + package let bytes: [UInt8] + package let identity: DocumentIdentity + private let lines: [Int] + + package init(_ bytes: [UInt8], identity: DocumentIdentity) { + self.bytes = bytes + self.identity = identity + var starts = [0] + var i = 0 + while i < min(bytes.count, 2_097_153) { + if bytes[i] == 13 { + if i + 1 < bytes.count && bytes[i + 1] == 10 { i += 1 } + starts.append(i + 1) + } else if bytes[i] == 10 { + starts.append(i + 1) + } + i += 1 + } + lines = starts + } + + package func span(_ range: Range) -> SourceSpan { + let start = min(max(0, range.lowerBound), bytes.count) + var lo = 0 + var hi = lines.count + while lo + 1 < hi { + let mid = (lo + hi) / 2 + if lines[mid] <= start { lo = mid } else { hi = mid } + } + return SourceSpan( + document: identity, start: start, end: min(max(start, range.upperBound), bytes.count), + line: lo + 1, column: start - lines[lo] + 1) + } + + package func failure(_ code: String, _ message: String, _ offset: Int, end: Int? = nil) + -> ManifestFailure + { + ManifestFailure( + ManifestDiagnostic(code: code, message: message, span: span(offset..<(end ?? offset)))) + } + + package func spelling(_ range: Range) -> String { + String(decoding: bytes[range], as: UTF8.self) + } +} diff --git a/Sources/AgentsManifest/PieceTable.swift b/Sources/AgentsManifest/PieceTable.swift new file mode 100644 index 0000000..8a0431f --- /dev/null +++ b/Sources/AgentsManifest/PieceTable.swift @@ -0,0 +1,78 @@ +package struct PieceTable { + private enum Piece { + case original(Range) + case inserted([UInt8]) + var count: Int { + switch self { + case .original(let range): range.count + case .inserted(let bytes): bytes.count + } + } + func slice(_ range: Range) -> Piece { + switch self { + case .original(let original): + return .original( + (original.lowerBound + range.lowerBound)..<(original.lowerBound + range.upperBound)) + case .inserted(let bytes): return .inserted(Array(bytes[range])) + } + } + } + private let original: [UInt8] + private var pieces: [Piece] + package init(_ bytes: [UInt8]) { + original = bytes + pieces = [.original(0.., with replacement: [UInt8]) { + var result: [Piece] = [] + var offset = 0 + var inserted = false + for piece in pieces { + let end = offset + piece.count + if offset < range.lowerBound { + let kept = min(end, range.lowerBound) - offset + if kept > 0 { result.append(piece.slice(0..= range.lowerBound { + if !replacement.isEmpty { result.append(.inserted(replacement)) } + inserted = true + } + if end > range.upperBound { + let first = max(offset, range.upperBound) - offset + if first < piece.count { result.append(piece.slice(first.. [SourcePatch] { + var result: [SourcePatch] = [] + var consumed = 0 + var replacement: [UInt8] = [] + for piece in pieces { + switch piece { + case .inserted(let bytes): replacement.append(contentsOf: bytes) + case .original(let range): + if range.lowerBound > consumed || !replacement.isEmpty { + result.append(SourcePatch(range: consumed.. ( + nodes: Int, depth: Int + ) { + var pending: [(Syntax, Int, Int)] = [(root, 1, 0)] + var scheduled = 1 + var count = 0 + var maximum = 0 + while let (node, depth, offset) = pending.popLast() { + if depth > 128 { throw source.failure("manifest.limit", "syntax tree depth", offset) } + count += 1 + maximum = max(maximum, depth) + var childOffset = offset + for child in node.children(viewMode: .all) { + if scheduled == 100_000 { + throw source.failure("manifest.limit", "syntax tree nodes", childOffset) + } + if depth == 128 { throw source.failure("manifest.limit", "syntax tree depth", childOffset) } + scheduled += 1 + pending.append((child, depth + 1, childOffset)) + childOffset += child.totalLength.utf8Length + } + } + return (count, maximum) + } + + package static func parse( + _ source: SourceText, admission: Admission, metrics initial: FrontEndMetrics + ) throws -> CheckedSyntax { + var metrics = initial + let clock = ContinuousClock() + let parseStart = clock.now + let tree = source.bytes.withUnsafeBufferPointer { + Parser.parse(source: $0, maximumNestingLevel: 20) + } + metrics.parserCalls += 1 + metrics.parsingSeconds = seconds(parseStart.duration(to: clock.now)) + let guardStart = clock.now + do { + let bounds = try guardTree(Syntax(tree), source: source) + metrics.syntaxNodes = bounds.nodes + metrics.syntaxDepth = bounds.depth + } catch let failure as ManifestFailure { + throw ManifestFailure(failure.diagnostics[0], metrics: metrics) + } + metrics.guardSeconds = seconds(guardStart.duration(to: clock.now)) + let inspectionStart = clock.now + if tree.hasError { + throw ManifestFailure( + ManifestDiagnostic( + code: "manifest.syntax", message: "SwiftParser disagreed with grammar admission", + span: source.span(0..<0)), metrics: metrics) + } + // This independent projection is also a dependency-upgrade regression gate. + let actual = projection(Syntax(tree), source: source) + guard actual == admission.projection, metrics.syntaxNodes <= admission.reservation else { + let offset = zip(actual, admission.projection).first(where: { $0 != $1 })?.0.start ?? 0 + throw ManifestFailure( + ManifestDiagnostic( + code: "manifest.syntax", + message: "SwiftParser projection or syntax reservation disagreed with admission", + span: source.span(offset.. [ProjectionEvent] { + var pending = [root] + var events: [ProjectionEvent] = [] + func emit(_ node: Syntax, _ kind: String, _ detail: String = "") { + events.append( + ProjectionEvent( + start: node.positionAfterSkippingLeadingTrivia.utf8Offset, + end: node.endPositionBeforeTrailingTrivia.utf8Offset, kind: kind, detail: detail)) + } + func literal(_ node: Syntax, _ kind: String) { + emit( + node, kind, + source.spelling( + node.positionAfterSkippingLeadingTrivia + .utf8Offset.. Double { + Double(duration.components.seconds) + Double(duration.components.attoseconds) / 1e18 +} diff --git a/Sources/AgentsManifest/ValueBudget.swift b/Sources/AgentsManifest/ValueBudget.swift new file mode 100644 index 0000000..101e568 --- /dev/null +++ b/Sources/AgentsManifest/ValueBudget.swift @@ -0,0 +1,88 @@ +import AgentsDescription + +package struct ValueCost: Sendable { + package var nodes = 1 + package var strings = 0 + package var encoded = 16 + package var depth = 1 + package var origins = 1 + + package static func scalar(_ text: String = "") -> Self { + var encoded = 2 + for byte in text.utf8 { + encoded += byte < 32 ? 6 : (byte == 34 || byte == 92 ? 2 : 1) + } + return Self(strings: text.utf8.count, encoded: encoded) + } + + package static func container(_ children: [ValueCost], keys: [String] = []) -> Self { + var result = Self() + for child in children { + result.nodes = add(result.nodes, child.nodes) + result.strings = add(result.strings, child.strings) + result.encoded = add(result.encoded, add(child.encoded, 4 + child.nodes * 2)) + result.origins = add(result.origins, child.origins) + result.depth = max(result.depth, child.depth + 1) + } + for key in keys { + let cost = scalar(key) + result.strings = add(result.strings, cost.strings) + result.encoded = add(result.encoded, cost.encoded + 4) + } + return result + } + + package var fits: Bool { + nodes <= 100_000 && strings <= 16_777_216 && encoded <= 33_554_432 + && depth <= 64 && origins <= 1_000_000 + } + + package static func add(_ lhs: Int, _ rhs: Int) -> Int { + let (result, overflow) = lhs.addingReportingOverflow(rhs) + return overflow ? 33_554_433 : min(result, 33_554_433) + } +} + +package final class EvaluatedValue: Sendable { + package let type: ConstructionType + package let value: ConstructionValue + package let cost: ValueCost + package let syntax: Int + package let fields: [String: EvaluatedValue] + package let elements: [EvaluatedValue] + package let referent: EvaluatedValue? + package let defaulted: Bool + package let referenceDepth: Int + + package init( + type: ConstructionType, value: ConstructionValue, cost: ValueCost, syntax: Int, + fields: [String: EvaluatedValue] = [:], elements: [EvaluatedValue] = [], + referent: EvaluatedValue? = nil, defaulted: Bool = false + ) { + self.type = type + self.value = value + self.cost = cost + self.syntax = syntax + self.fields = fields + self.elements = elements + self.referent = referent + self.defaulted = defaulted + referenceDepth = (referent?.referenceDepth ?? 0) + (referent == nil ? 0 : 1) + } +} + +package func constructionCost(_ value: ConstructionValue) -> ValueCost { + switch value { + case .text(let text): return .scalar(text) + case .version(let version): return .scalar(version.normalized) + case .range(let range): + return .container([.scalar(range.lowerBound.normalized), .scalar(range.upperBound.normalized)]) + case .array(let values): return .container(values.map(constructionCost)) + case .object(let fields): + return .container(fields.values.map(constructionCost), keys: Array(fields.keys)) + case .node(let type, let member, let fields): + return .container( + fields.values.map(constructionCost), keys: [type, member] + Array(fields.keys)) + case .none, .integer, .boolean: return ValueCost() + } +} diff --git a/Tests/AgentsManifestTests/AdversarialTests.swift b/Tests/AgentsManifestTests/AdversarialTests.swift new file mode 100644 index 0000000..f160b4b --- /dev/null +++ b/Tests/AgentsManifestTests/AdversarialTests.swift @@ -0,0 +1,311 @@ +import AgentsCore +import Foundation +import SwiftSyntax +import Testing + +@testable import AgentsManifest + +struct AdmissionCase { + let name: String + let bytes: [UInt8] + let expected: String? + init(_ name: String, _ expression: String, expected: String? = nil, complete: Bool = false) { + self.name = name + bytes = Array((complete ? expression : manifestHeader + "let value = " + expression).utf8) + self.expected = expected + } + init(_ name: String, bytes: [UInt8], expected: String?) { + self.name = name + self.bytes = bytes + self.expected = expected + } +} + +func fixedAdmissionCases() -> [AdmissionCase] { + var cases: [AdmissionCase] = [] + for depth in [7, 8, 9, 20, 200, 20_000] { + for (name, left, right) in [ + ("squares", "[", "]"), ("mixed", "f([", "])"), ("dictionaries", "[\"k\":", "]"), + ("calls", ".f(", ")"), ("parentheses", "(", ")"), + ] { + cases.append( + AdmissionCase( + "\(name)-\(depth)", + String(repeating: left, count: depth) + "0" + String(repeating: right, count: depth), + expected: name == "squares" && depth <= 8 || name == "dictionaries" && depth <= 8 + || name == "mixed" && depth <= 8 + || name == "parentheses" && depth <= 20 || name == "calls" && depth <= 20 + ? "accepted" : nil)) + cases.append( + AdmissionCase( + "\(name)-unbalanced-\(depth)", String(repeating: left, count: depth) + "0", expected: nil) + ) + } + } + for (name, expression) in [ + ( + "brace-nests", + String(repeating: "{", count: 20_000) + "0" + String(repeating: "}", count: 20_000) + ), + ("generic-small", "let value: A = 0"), + ( + "generic-large", + "let value: " + String(repeating: "A<", count: 20_000) + "B" + + String(repeating: ">", count: 20_000) + " = 0" + ), + ("ambiguous-angle", String(repeating: "a<", count: 200_000) + "b"), + ("members", "a" + String(repeating: ".b", count: 200_000)), + ("numeric-prefix", String(repeating: "-", count: 200_000) + "1"), + ("force-unwrap", "a" + String(repeating: "!", count: 200_000)), + ("postfix-calls", "a" + String(repeating: "()", count: 200_000)), + ("subscripts", "a" + String(repeating: "[0]", count: 200_000)), + ("plus-chain", "1" + String(repeating: " + 1", count: 200_000)), + ] { cases.append(AdmissionCase(name, expression, expected: nil)) } + for word in ["copy", "await", "consume", "each", "unsafe"] { + for count in [2, 200_000] { + cases.append( + AdmissionCase( + "prefix-\(word)-\(count)", String(repeating: word + " ", count: count) + "x", + expected: count == 2 ? "manifest.syntax" : nil)) + } + cases.append(AdmissionCase("label-\(word)", "f(\(word): 0)", expected: "accepted")) + cases.append(AdmissionCase("member-\(word)", ".\(word)", expected: "accepted")) + cases.append( + AdmissionCase( + "binding-\(word)", manifestHeader + "let \(word) = 0", expected: "manifest.syntax", + complete: true)) + } + for body in [ + "#\"\"\"#\nlet danger: A> = 0\n// \"\"\"#", "#\"raw\"#", "##\"\"\"\ntext\n\"\"\"##", + ] { cases.append(AdmissionCase("raw-\(cases.count)", body, expected: "manifest.syntax")) } + for bad in [ + "x y", "f(x y)", "`x`", "é", "$x", "1.0", "0x1", "1e2", "- 1", "--1", "+1", "a+b", "a +b", + "a+ b", "f(0,)", "(0,)", "[key: 0]", "a[0]", "(a).b", "a.b.c", "a()()", "a.b().c()", + "a /* x */ .b", "\"\\q\"", "\"\\u{D800}\"", "\"\\u{110000}\"", "\"\\u{}\"", "\"\\(x)\"", + "/*unterminated", "\"unterminated", + ] { cases.append(AdmissionCase("forbidden-\(cases.count)", bad, expected: "manifest.syntax")) } + for value in [ + "\"\\0\\t\\n\\r\\\"\\'\\\\\"", "\"\\u{0}\\u{1F600}\"", "\"é😀\"", "-1_000", "1_", + "\"\\\\(literal)\"", "/* nested /* comment */ */ 0", + String(repeating: "/*", count: 20) + "x" + String(repeating: "*/", count: 20) + " 0", + ] { cases.append(AdmissionCase("literal-\(cases.count)", value, expected: "accepted")) } + cases.append( + AdmissionCase( + "comments-21", + String(repeating: "/*", count: 21) + "x" + String(repeating: "*/", count: 21) + "0", + expected: "manifest.limit")) + for newline in ["\n", "\r\n", "\r"] { + for (content, closing, good) in [ + ("", " ", true), (" ", " ", false), (" ", " ", true), (" ", " ", true), + ("\t", " ", false), (" \ttext", " ", false), (" text\ttail", " ", true), + (" text", " ", true), ("", "\t", false), + ] { + cases.append( + AdmissionCase( + "indent-\(cases.count)", "\"\"\"" + newline + content + newline + closing + "\"\"\"", + expected: good ? "accepted" : "manifest.syntax")) + } + } + let gaps = ["", " ", "\t", "\n", "\r\n"] + for left in gaps { + for right in gaps { + cases.append( + AdmissionCase( + "assignment-\(cases.count)", manifestHeader + "let value" + left + "=" + right + "-1", + expected: !left.isEmpty && !right.isEmpty ? "accepted" : "manifest.syntax", complete: true + )) + cases.append( + AdmissionCase( + "plus-spacing-\(cases.count)", "[]" + left + "+" + right + "[]", + expected: !left.isEmpty && !right.isEmpty ? "accepted" : "manifest.syntax")) + cases.append( + AdmissionCase( + "range-spacing-\(cases.count)", + ".source(name: \"s\", path: \"s\", \"1.2.0\"" + left + "..<" + right + "\"2.0.0\")", + expected: left.isEmpty == right.isEmpty ? "accepted" : "manifest.syntax")) + } + } + for op in ["=", "+", "..<"] { + for (left, right, good) in [ + (" /*a*/ ", " /*b*/ ", true), ("/*a*/ ", " ", false), (" /*a*/", " ", false), + (" ", "/*a*/ ", false), (" /*a*//*b*/ ", " ", false), (" /*a*/ /*b*/ ", " ", true), + (" //a\n", " ", true), + ] { + let expression = + op == "=" + ? manifestHeader + "let value" + left + op + right + "0" + : op == "+" + ? "[]" + left + op + right + "[]" + : ".source(name: \"s\", path: \"s\", \"1.2.0\"" + left + op + right + "\"2.0.0\")" + cases.append( + AdmissionCase( + "operator-comments-\(op)-\(cases.count)", expression, + expected: good ? "accepted" : "manifest.syntax", complete: op == "=")) + } + } + for body in ["-1", "(-1)", "[-1]", "[0,-1]", "[\"k\":-1]", "f(-1)", "f(label:-1)", "/*c*/ -1"] { + cases.append(AdmissionCase("negative-good-\(cases.count)", body, expected: "accepted")) + } + for body in ["a-1", "1-1", ")-1", "]-1", ".-1", "--1", "+-1", "/*c*/-1", "-\n1"] { + cases.append(AdmissionCase("negative-bad-\(cases.count)", body, expected: "manifest.syntax")) + } + for range in [ + "\"1.2.0\"...\"2.0.0\"", "\"1.2.0\"..<\"2.0.0\"..<\"3.0.0\"", "lower..<\"2.0.0\"", + "\"1.2.0\".. [CompiledManifestFixture] { + [ + fixture0(), + fixture1(), + fixture2(), + fixture3(), + fixture4(), + fixture5(), + fixture6(), + fixture7(), + fixture8(), + fixture9(), + fixture10(), + fixture11(), + fixture12(), + fixture13(), + fixture14(), + fixture15(), + ] +} + +private func fixture0() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let base: [SectionReference] = ["guide"] + let sections = base + [.section(name: "engineering", source: "rules")] + let reviewer: Component = .subagent( + name: "reviewer", + description: "Review correctness and tests.", + prompt: "Check invariants and explain concrete failures.", + agents: [.claudeCode], + condition: .when(platforms: [.macOS]), + native: ["claude-code/subagent@1": ["memory": "project"]] + ) + + let agents = Agents( + sources: [ + .source(name: "team", path: "./team"), + .source(name: "drafts", path: "./draft-skills"), + .source(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), + .source(name: "catalog", index: "https://example.org/skills/index.json"), + .source(name: "vendor", url: "https://example.org/vendor/tools.git", exact: "2.1.0"), + ], + components: [ + .skills( + source: "rules", exclude: ["experimental"], mode: .copy, + overrides: [.skill(name: "testing", mode: .link, agents: [.codex])] + ), + .skills( + source: "drafts", select: ["draft"], mode: .edit, + condition: .when(agents: [.claudeCode], scopes: [.project]) + ), + .instructions( + sections: sections, + chatGPT: [.prompt(name: "weekly", sections: base, append: "notes/weekly.md")] + ), + .mcpServer( + name: "workspace", + transport: .stdio( + "workspace-tools", arguments: ["serve"], + environment: ["TOKEN": .secret("workspace-token"), "LOG_LEVEL": "info"] + ), + agents: [.claudeCode] + ), + .mcpServer( + name: "reference", + transport: .streamableHTTP( + url: "https://example.org/mcp", headers: ["Authorization": .environment("MCP_AUTH")] + ), + agents: [.openCode] + ), + .hook( + name: "format", event: .afterTool, + run: .executable( + "swift", arguments: ["format", "--in-place", "Sources"], + workingDirectory: .path("tools", source: "rules") + ), + timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) + ), + .command( + name: "review/change", description: "Review a selected change.", + prompt: "Review ${input:change} and cite evidence.", + parameters: [.parameter(name: "change", description: "The change to review.")], + agents: [.claudeCode] + ), + .lspServer( + name: "swift", run: .executable("sourcekit-lsp"), + languages: [".swift": "swift"], + initializationOptions: ["backgroundIndexing": true], + agents: [.claudeCode], condition: .when(platforms: [.macOS]) + ), + .permissions( + name: "private-files", + rules: [.deny(.read, "secrets/**")], + agents: [.claudeCode], condition: .when(scopes: [.project]) + ), + .ignore( + name: "build-products", patterns: [".build/", "DerivedData/"], purpose: .indexing, + agents: [.cursor], condition: .when(scopes: [.project]) + ), + .plugin( + name: "vendor-tools", path: "plugins/tools", source: "vendor", mode: .native, + agents: [.claudeCode], condition: .when(scopes: [.user]) + ), + .plugin( + name: "shared-tools", path: "plugins/shared", source: "vendor", + exclude: [.hook(name: "format")], condition: .when(scopes: [.project]) + ), + ], + groups: [ + .group( + name: "review-tools", components: [reviewer], + uses: [.group(name: "review", source: "team", condition: .when(agents: [.codex]))] + ) + ], + uses: ["review-tools"], + watch: ["rules", "catalog"] + ) + return CompiledManifestFixture( + name: "ConsumerExample.swift.txt", agents: agents, + constants: [ + "base": base.constructionValue, + "sections": sections.constructionValue, + "reviewer": reviewer.constructionValue, + "agents": agents.constructionValue, + ]) +} + +private func fixture1() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + sources: [ + .source( + name: "agents-tools", + url: "https://github.com/agents-tools/.github", + branch: "master", + subpath: ".agent" + ) + ], + components: [ + .instructions( + sections: [ + "guide", + .section(name: "shared/swift-package-route", source: "agents-tools"), + .section(name: "shared/swift-package-tests", source: "agents-tools"), + ], + agents: [.claudeCode, .codex] + ) + ] + ) + return CompiledManifestFixture( + name: "Contract00.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func fixture2() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + defaultAgents: [.cursor], + sources: [.source(name: "team", path: "./team")], + components: [ + .ignore( + name: "build-products", patterns: [".build/"], purpose: .indexing, + condition: .when(scopes: [.project]) + ) + ], + uses: [ + .group(name: "review", source: "team", condition: .when(agents: [.codex])) + ] + ) + return CompiledManifestFixture( + name: "Contract01.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func fixture3() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + components: [ + .instructions( + sections: ["guide", "code-review-rules"], + agents: [.claudeCode, .codex] + ) + ] + ) + return CompiledManifestFixture( + name: "Contract05.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func fixture4() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + exports: ["review"], + groups: [ + .group( + name: "review", + components: [ + .instructions(sections: ["review-principles"], agents: [.claudeCode, .codex]), + .skills(source: ".", select: ["review"], mode: .copy, agents: [.claudeCode, .codex]), + ], + condition: .when(scopes: [.project]) + ) + ] + ) + return CompiledManifestFixture( + name: "Contract06.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func fixture5() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let base: [SectionReference] = ["guide"] + let sections = base + [.section(name: "engineering", source: "rules")] + let reviewer: Component = .subagent( + name: "reviewer", + description: "Review correctness and tests.", + prompt: "Check invariants and explain concrete failures.", + agents: [.claudeCode], + condition: .when(platforms: [.macOS]), + native: ["claude-code/subagent@1": ["memory": "project"]] + ) + + let agents = Agents( + sources: [ + .source(name: "team", path: "./team"), + .source(name: "drafts", path: "./draft-skills"), + .source(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), + .source(name: "catalog", index: "https://example.org/skills/index.json"), + .source(name: "vendor", url: "https://example.org/vendor/tools.git", exact: "2.1.0"), + ], + components: [ + .skills( + source: "rules", exclude: ["experimental"], mode: .copy, + overrides: [.skill(name: "testing", mode: .link, agents: [.codex])] + ), + .skills( + source: "drafts", select: ["draft"], mode: .edit, + condition: .when(agents: [.claudeCode], scopes: [.project]) + ), + .instructions( + sections: sections, + chatGPT: [.prompt(name: "weekly", sections: base, append: "notes/weekly.md")] + ), + .mcpServer( + name: "workspace", + transport: .stdio( + "workspace-tools", arguments: ["serve"], + environment: ["TOKEN": .secret("workspace-token"), "LOG_LEVEL": "info"] + ), + agents: [.claudeCode] + ), + .mcpServer( + name: "reference", + transport: .streamableHTTP( + url: "https://example.org/mcp", headers: ["Authorization": .environment("MCP_AUTH")] + ), + agents: [.openCode] + ), + .hook( + name: "format", event: .afterTool, + run: .executable( + "swift", arguments: ["format", "--in-place", "Sources"], + workingDirectory: .path("tools", source: "rules") + ), + timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) + ), + .command( + name: "review/change", description: "Review a selected change.", + prompt: "Review ${input:change} and cite evidence.", + parameters: [.parameter(name: "change", description: "The change to review.")], + agents: [.claudeCode] + ), + .lspServer( + name: "swift", run: .executable("sourcekit-lsp"), + languages: [".swift": "swift"], + initializationOptions: ["backgroundIndexing": true], + agents: [.claudeCode], condition: .when(platforms: [.macOS]) + ), + .permissions( + name: "private-files", + rules: [.deny(.read, "secrets/**")], + agents: [.claudeCode], condition: .when(scopes: [.project]) + ), + .ignore( + name: "build-products", patterns: [".build/", "DerivedData/"], purpose: .indexing, + agents: [.cursor], condition: .when(scopes: [.project]) + ), + .plugin( + name: "vendor-tools", path: "plugins/tools", source: "vendor", mode: .native, + agents: [.claudeCode], condition: .when(scopes: [.user]) + ), + .plugin( + name: "shared-tools", path: "plugins/shared", source: "vendor", + exclude: [.hook(name: "format")], condition: .when(scopes: [.project]) + ), + ], + groups: [ + .group( + name: "review-tools", components: [reviewer], + uses: [.group(name: "review", source: "team", condition: .when(agents: [.codex]))] + ) + ], + uses: ["review-tools"], + watch: ["rules", "catalog"] + ) + return CompiledManifestFixture( + name: "Contract07.swift.txt", agents: agents, + constants: [ + "base": base.constructionValue, + "sections": sections.constructionValue, + "reviewer": reviewer.constructionValue, + "agents": agents.constructionValue, + ]) +} + +private func fixture6() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + sources: [ + .source( + name: "agents-tools", + url: "https://github.com/agents-tools/.github", + branch: "master", + subpath: ".agent" + ) + ], + components: [ + .instructions( + sections: [ + "guide", + .section(name: "shared/swift-package-route", source: "agents-tools"), + .section(name: "shared/swift-package-tests", source: "agents-tools"), + ], + agents: [.claudeCode, .codex] + ) + ] + ) + return CompiledManifestFixture( + name: "CoreExample.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func fixture7() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let text: PromptContent = "Review invariants." + let section: SectionReference = "guide" + let local: GroupReference = "review" + let selection: SkillSelection = ["review", "testing"] + let configuration: ConfigurationValue = [ + "string": "value", "integer": -1, "boolean": true, "null": nil, + "array": [1, "two", false, nil], "object": ["enabled": true], "decimal": .decimal("1.25"), + ] + let environment: [String: RuntimeValue] = ["LEVEL": "info", "TOKEN": .secret("token")] + let emptySelection: SkillSelection = [] + let emptyObject: ConfigurationValue = [:] + let emptyArray: ConfigurationValue = [] + let emptyTools: Component = .subagent( + name: "empty-tools", description: "No tools", prompt: "Read", tools: []) + let invocation: ExecutableInvocation = .executable( + "server", environment: environment, workingDirectory: .path("tools", source: "vendor")) + let runtime: RuntimeValue = .literal("literal") + let scalar: ConfigurationValue = .string("x") + let integer: ConfigurationValue = .integer(-9_223_372_036_854_775_808) + let boolean: ConfigurationValue = .boolean(false) + let null: ConfigurationValue = .null + let array: ConfigurationValue = .array([scalar, integer, boolean, null]) + let object: ConfigurationValue = .object(["array": array]) + let agents = Agents( + exports: ["review"], + sources: [.source(name: "team", path: "team"), .source(name: "vendor", path: "vendor")], + components: [ + .mcpServer(name: "tools", transport: .stdio("server", environment: environment)), + .mcpServer(name: "sse", transport: .sse(url: "https://example.org/events")), + .command(name: "review", description: "Review", prompt: text), + .instructions(sections: [section]), + .skills( + source: "team", select: selection, + overrides: [.skill(name: "review", mode: .copy, agents: [.codex])]), + .lspServer( + name: "swift", run: invocation, languages: [".swift": "swift"], + initializationOptions: ["config": configuration]), + .permissions( + name: "policy", + rules: [ + .allow(.read, "Sources/**"), .ask(.write, "**"), .deny(.execute, "rm *"), + .deny(.tool("fetch"), "*"), + ]), + .plugin( + name: "tools", path: "plugins/tools", source: "vendor", + select: [ + .skills, .instructions, .mcpServer, .hook, .subagent, .command, .lspServer, .permissions, + .ignore, .plugin, + ], + exclude: [ + .skill(name: "a"), .instruction(name: "a"), .mcpServer(name: "a"), .hook(name: "a"), + .subagent(name: "a"), .command(name: "a"), .lspServer(name: "a"), .permissions(name: "a"), + .ignore(name: "a"), .plugin(name: "a"), + ]), + .hook(name: "native", event: .native("Event"), run: invocation, agents: [.codex]), + .ignore( + name: "context", patterns: [], purpose: .context, agents: [], + condition: .when(scopes: [.project, .user], platforms: [.macOS, .linux])), + emptyTools, + ], + groups: [.group(name: "review")], + uses: [local, .group(name: "review", condition: .when(agents: [.codex]))] + ) + return CompiledManifestFixture( + name: "LiteralCoverage.swift.txt", agents: agents, + constants: [ + "text": text.constructionValue, + "section": section.constructionValue, + "local": local.constructionValue, + "selection": selection.constructionValue, + "configuration": configuration.constructionValue, + "environment": environment.constructionValue, + "emptySelection": emptySelection.constructionValue, + "emptyObject": emptyObject.constructionValue, + "emptyArray": emptyArray.constructionValue, + "emptyTools": emptyTools.constructionValue, + "invocation": invocation.constructionValue, + "runtime": runtime.constructionValue, + "scalar": scalar.constructionValue, + "integer": integer.constructionValue, + "boolean": boolean.constructionValue, + "null": null.constructionValue, + "array": array.constructionValue, + "object": object.constructionValue, + "agents": agents.constructionValue, + ]) +} + +private func fixture8() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + sources: [ + .source(name: "source", path: "./drafts", from: "1.2.0"), + .source( + name: "source-2", + path: "./more", + .upToNextMinor(from: "1.2.0") + ), + .source(name: "source-3", url: "https://example.org/rules.git"), + ], + components: [ + .skills( + source: "source", + overrides: [ + .skill( + name: "future", + agents: [.openCode] + ) + ] + ), + .skills( + source: "source-3", + select: ["a"], + overrides: [ + .skill( + name: "a", + mode: .copy, + agents: [.codex] + ) + ] + ), + .instructions( + sections: [ + "guide", + .section(name: "rule", source: "source-3"), + ], + chatGPT: [ + .prompt( + name: "", + sections: [ + .section(name: "rule", source: "source-3") + ] + ) + ] + ), + ], + watch: ["source-3"] + ) + return CompiledManifestFixture( + name: "MigrationEdgeExample.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func fixture9() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + exports: ["review"], + groups: [ + .group( + name: "review", + components: [ + .instructions(sections: ["review-principles"], agents: [.claudeCode, .codex]), + .skills(source: ".", select: ["review"], mode: .copy, agents: [.claudeCode, .codex]), + ], + condition: .when(scopes: [.project]) + ) + ] + ) + return CompiledManifestFixture( + name: "ProducerExample.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func fixture10() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let majorFrom: Source = .source( + name: "rules", url: "https://example.org/rules.git", from: "1.2.0") + let majorHelper: Source = .source( + name: "rules", url: "https://example.org/rules.git", .upToNextMajor(from: "1.2.0")) + let majorRange: Source = .source( + name: "rules", url: "https://example.org/rules.git", "1.2.0"..<"2.0.0") + let minorHelper: Source = .source( + name: "rules", url: "https://example.org/rules.git", .upToNextMinor(from: "1.2.0")) + let minorRange: Source = .source( + name: "rules", url: "https://example.org/rules.git", "1.2.0"..<"1.3.0") + let prereleaseFrom: Source = .source( + name: "rules", url: "https://example.org/rules.git", from: "1.2.3-beta.1+build.7") + let prereleaseHelper: Source = .source( + name: "rules", url: "https://example.org/rules.git", + .upToNextMajor(from: "1.2.3-beta.1+build.7")) + let prereleaseRange: Source = .source( + name: "rules", url: "https://example.org/rules.git", "1.2.3-beta.1+build.7"..<"2.0.0") + let prereleaseMinor: Source = .source( + name: "rules", url: "https://example.org/rules.git", + .upToNextMinor(from: "1.2.3-beta.1+build.7")) + let prereleaseMinorRange: Source = .source( + name: "rules", url: "https://example.org/rules.git", "1.2.3-beta.1+build.7"..<"1.3.0") + let localLiteral: GroupReference = "review" + let localFactory: GroupReference = .group(name: "review") + let agents = Agents( + exports: ["review"], + sources: [majorFrom], + components: [ + .plugin(name: "tools", path: "tools", source: "rules", exclude: [.hook(name: "format")]) + ], + groups: [.group(name: "review")], + uses: [localLiteral] + ) + return CompiledManifestFixture( + name: "RequirementValues.swift.txt", agents: agents, + constants: [ + "majorFrom": majorFrom.constructionValue, + "majorHelper": majorHelper.constructionValue, + "majorRange": majorRange.constructionValue, + "minorHelper": minorHelper.constructionValue, + "minorRange": minorRange.constructionValue, + "prereleaseFrom": prereleaseFrom.constructionValue, + "prereleaseHelper": prereleaseHelper.constructionValue, + "prereleaseRange": prereleaseRange.constructionValue, + "prereleaseMinor": prereleaseMinor.constructionValue, + "prereleaseMinorRange": prereleaseMinorRange.constructionValue, + "localLiteral": localLiteral.constructionValue, + "localFactory": localFactory.constructionValue, + "agents": agents.constructionValue, + ]) +} + +private func fixture11() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let minimum: Version = "1.2.0" + let review: ComponentGroup = .group( + name: "review", + components: [ + .skills(source: ".", overrides: [.skill(name: "review", mode: .copy)]), + .instructions( + sections: [.section(name: "guide", source: ".")], + chatGPT: [.prompt(name: "weekly", sections: ["guide"])] + ), + .command( + name: "review", description: "Review a change", prompt: .file("review.md", source: "."), + parameters: [ + .parameter(name: "change", description: "Change identifier", defaultValue: "HEAD") + ] + ), + .hook( + name: "format", event: .afterTool, + run: .executable("swift", workingDirectory: .path("Sources", source: ".")) + ), + ] + ) + let agents = Agents( + exports: ["review"], + sources: [ + .source(name: "major", url: "https://example.org/major.git", from: minimum), + .source(name: "exact", url: "https://example.org/exact.git", exact: "1.2.0"), + .source(name: "branch", url: "https://example.org/branch.git", branch: "main"), + .source(name: "revision", url: "https://example.org/revision.git", revision: "abc123"), + .source(name: "range", url: "https://example.org/range.git", "1.2.0"..<"2.0.0"), + .source(name: "minor", url: "https://example.org/minor.git", .upToNextMinor(from: "1.2.0")), + .source( + name: "explicit-major", url: "https://example.org/explicit.git", + .upToNextMajor(from: minimum)), + .source(name: "local-major", path: "./major", from: "1.2.0"), + .source(name: "local-exact", path: "./exact", exact: "1.2.0"), + .source(name: "local-branch", path: "./branch", branch: "main"), + .source(name: "local-revision", path: "./revision", revision: "abc123"), + .source(name: "local-range", path: "./range", "1.2.0"..<"2.0.0", subpath: "tools"), + .source(name: "local-minor", path: "./minor", .upToNextMinor(from: "1.2.0")), + .source(name: "local-explicit-major", path: "./explicit", .upToNextMajor(from: "1.2.0")), + .source(name: "unversioned", url: "https://example.org/unversioned.git"), + .source(name: "local", path: "./local"), + .source(name: "catalog", index: "https://example.org/index.json", subpath: "tools"), + ], + groups: [review, .group(name: "quality", uses: ["review"])], + uses: ["quality", .group(name: "review", source: "major")] + ) + return CompiledManifestFixture( + name: "RequirementsExample.swift.txt", agents: agents, + constants: [ + "minimum": minimum.constructionValue, + "review": review.constructionValue, + "agents": agents.constructionValue, + ]) +} + +private func fixture12() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + defaultAgents: [.cursor], + sources: [.source(name: "team", path: "./team")], + components: [ + .ignore( + name: "build-products", patterns: [".build/"], purpose: .indexing, + condition: .when(scopes: [.project]) + ) + ], + uses: [ + .group(name: "review", source: "team", condition: .when(agents: [.codex])) + ] + ) + return CompiledManifestFixture( + name: "SketchExample.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func fixture13() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + components: [ + .instructions( + sections: ["guide", "code-review-rules"], + agents: [.claudeCode, .codex] + ) + ] + ) + return CompiledManifestFixture( + name: "SkillsExample.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func fixture14() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + // A team repository's .agent/Agents.swift. + // Everything here is a declaration: agents reads it, never runs it. + + let reviewer: Component = .subagent( + name: "reviewer", + description: "Review correctness and tests.", + prompt: "Check invariants and explain concrete failures.", + agents: [.claudeCode] + ) + + let agents = Agents( + // Components without their own `agents:` go to these. + defaultAgents: [.claudeCode, .codex], + + sources: [ + .source( + name: "org", url: "https://github.com/acme/.github", branch: "main", subpath: ".agent"), + .source(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), + .source(name: "drafts", path: "./draft-skills"), + ], + + components: [ + // AGENTS.md / CLAUDE.md, assembled from sections. + .instructions( + sections: [ + "guide", + .section(name: "shared/swift-package-route", source: "org"), + ] + ), + + // Every skill from `rules` except one; Codex gets `testing` as a link. + .skills( + source: "rules", exclude: ["experimental"], mode: .copy, + overrides: [.skill(name: "testing", mode: .link, agents: [.codex])] + ), + + // Work-in-progress skills, only for Claude Code in this project. + .skills( + source: "drafts", select: ["draft"], mode: .edit, + condition: .when(agents: [.claudeCode], scopes: [.project]) + ), + + .mcpServer( + name: "workspace", + transport: .stdio( + "workspace-tools", arguments: ["serve"], + environment: ["TOKEN": .secret("workspace-token"), "LOG_LEVEL": "info"] + ) + ), + + .hook( + name: "format", event: .afterTool, + run: .executable("swift", arguments: ["format", "--in-place", "Sources"]), + timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) + ), + + .lspServer( + name: "swift", run: .executable("sourcekit-lsp"), + languages: [".swift": "swift"], + agents: [.claudeCode], condition: .when(platforms: [.macOS]) + ), + + .permissions( + name: "private-files", + rules: [.deny(.read, "secrets/**")], + condition: .when(scopes: [.project]) + ), + + .ignore( + name: "build-products", patterns: [".build/", "DerivedData/"], purpose: .indexing, + agents: [.cursor] + ), + + reviewer, + ], + + // Re-check these sources for updates. + watch: ["rules"] + ) + return CompiledManifestFixture( + name: "TasteSample.swift.txt", agents: agents, + constants: [ + "reviewer": reviewer.constructionValue, + "agents": agents.constructionValue, + ]) +} + +private func fixture15() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + groups: [ + .group( + name: "review", + components: [ + .instructions( + chatGPT: [ + .prompt( + name: "review", + sections: [ + .section(name: "guide", condition: .when(agents: [.codex])) + ] + ) + ] + ) + ] + ) + ] + ) + return CompiledManifestFixture( + name: "VocabularyDepthExample.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} diff --git a/Tests/AgentsManifestTests/DifferentialFuzzTests.swift b/Tests/AgentsManifestTests/DifferentialFuzzTests.swift new file mode 100644 index 0000000..8972a33 --- /dev/null +++ b/Tests/AgentsManifestTests/DifferentialFuzzTests.swift @@ -0,0 +1,151 @@ +import Foundation +import Testing + +@testable import AgentsManifest + +struct ManifestRandom { + static let seed: UInt64 = 0xa631_2026_1029 + var state = seed + mutating func next(_ upper: Int) -> Int { + state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407 + return Int((state >> 24) % UInt64(upper)) + } + mutating func choose(_ values: [String]) -> String { values[next(values.count)] } + mutating func expression(depth: Int = 0) -> String { + let leaves = [ + "0", "-1", "1_000", "true", "false", "nil", "value", "\"text\"", "\"é😀\"", "\"\\u{1F600}\"", + "\"\"\"\n line\n \\\"quote\n \"\"\"", ".copy", "Type.member", "[]", "[:]", + ] + if depth == 3 || next(4) == 0 { return choose(leaves) } + switch next(7) { + case 0: + return "[" + (0.. [AdmissionCase] { + var rng = ManifestRandom() + var cases: [AdmissionCase] = [] + var generated: [String] = [] + for index in 0..<256 { + var expression = rng.expression() + if index == 255 { + expression = "[" + Array(repeating: "0", count: 12_450).joined(separator: ",") + "]" + } + generated.append(expression) + let type = rng.choose([ + "", ": String", ": [Int]", ": [String: ConfigurationValue]", ": Component", + ": [[String: [Bool]]]", + ]) + let text = + manifestHeader + "let base: [String] = []\nlet value" + type + " = " + expression + "\n" + cases.append(AdmissionCase("grammar-\(index)", text, expected: "accepted", complete: true)) + } + let tokens = [ + "let", "import", "copy", "await", "consume", "each", "unsafe", "x", "0", "\"s\"", "(", ")", "[", + "]", ",", ":", ".", "=", "+", "-1", + ] + for index in 0..<128 { + let sequence = (0..<(1 + rng.next(48))).map { _ in rng.choose(tokens) }.joined(separator: " ") + cases.append(AdmissionCase("tokens-\(index)", sequence)) + } + for index in 0..<128 { + cases.append( + AdmissionCase( + "injected-\(index)", + rng.expression() + " " + + rng.choose(["<", ">", "{", "}", "#", "?", "!", "&", "*", "/", "`x`", "$x"]), + expected: "manifest.syntax")) + } + for (index, source) in generated.enumerated() { + let bytes = Array(source.utf8) + let point = rng.next(bytes.count + 1) + let skip = min(rng.next(2), bytes.count - point) + let mutation = Array( + rng.choose(["", "copy ", "#\"\"\"#", "/*", "\"", "[", ")", " + ", " "]).utf8) + cases.append( + AdmissionCase( + "mutation-\(index)", + bytes: Array((manifestHeader + "let value = ").utf8) + bytes[.. 0 && attempts < 64 { + var offset = manifestHeader.utf8.count + var found = false + while offset + chunk <= minimized.count && attempts < 64 { + var candidate = minimized + candidate.removeSubrange(offset..<(offset + chunk)) + attempts += 1 + let check = try probe("minimize", candidate, in: directory) + if check.report.stage == "parser" { + minimized = candidate + found = true + break + } + offset += chunk + } + if !found { chunk /= 2 } + } + try Data(minimized).write( + to: retained.appendingPathComponent(fixture.name + ".minimal.swift")) + Issue.record( + "differential counterexample retained: \(fixture.name), seed=\(ManifestRandom.seed)") + } + if let expected = fixture.expected { + #expect(result.report.status == expected, "\(fixture.name): \(result.report.message)") + } + results.append(result) + } + let slowest = results.max { $0.wallSeconds < $1.wallSeconds }! + let accepted = results.filter { $0.report.status == "accepted" }.count + print( + "MANIFEST_FUZZ configuration=\(probeConfiguration) watchdogSeconds=\(probeWatchdogSeconds) seed=\(ManifestRandom.seed) grammar=256 tokens=128 injected=128 mutations=256 ranges=128 cases=\(results.count) accepted=\(accepted) slowest=\(slowest.name) seconds=\(slowest.wallSeconds) peakMemory=\(results.map { $0.report.peakMemoryBytes }.max()!)" + ) + try recordProbeResults(results, name: "differential-run") + } +} diff --git a/Tests/AgentsManifestTests/EditingTests.swift b/Tests/AgentsManifestTests/EditingTests.swift new file mode 100644 index 0000000..cbd54e7 --- /dev/null +++ b/Tests/AgentsManifestTests/EditingTests.swift @@ -0,0 +1,279 @@ +import AgentsCore +import AgentsDescription +import Foundation +import Testing + +@testable import AgentsManifest + +func edited(_ doc: DeclarationDocument, _ edits: [ManifestEdit]) throws -> DeclarationDocument { + let change = try doc.preparing(edits) + #expect(change.originalDigest == doc.digest) + var applied = doc.bytes + for patch in change.patches.reversed() { + applied.replaceSubrange(patch.range, with: patch.replacement) + } + #expect(applied == change.bytes) + for pair in zip(change.patches, change.patches.dropFirst()) { + #expect(pair.0.range.upperBound <= pair.1.range.lowerBound) + } + let result = try DeclarationDocument(bytes: change.bytes, identity: DocumentIdentity("manifest")) + #expect(result.declaration == change.expectedDeclaration) + return result +} + +@Suite("Manifest document editing") +struct EditingTests { + @Test func rootArgumentsUseSignatureOrderAndCanonicalSourceRequirements() throws { + let initial = try document("let agents = Agents()") + let result = try edited( + initial, + [ + .setWatch(["rules"]), .setExports(["review"]), + .upsertGroup(.group(name: "review")), + .upsertSource(.source(name: "rules", url: "intranet/team.git", "1.2.0"..<"1.3.0")), + .setDefaultAgents([.codex]), + ]) + let source = String(decoding: result.bytes, as: UTF8.self) + let order = ["defaultAgents:", "exports:", "sources:", "groups:", "watch:"].map { + source.range(of: $0)!.lowerBound + } + #expect(zip(order, order.dropFirst()).allSatisfy { $0 < $1 }) + #expect(source.contains("https://intranet/team.git")) + #expect(source.contains(".upToNextMinor(from: \"1.2.0\")")) + #expect(result.declaration.defaultAgents == ["codex"]) + let major = try edited( + result, + [.upsertSource(.source(name: "rules", url: "https://intranet/team.git", "1.2.0"..<"2.0.0"))]) + #expect(String(decoding: major.bytes, as: UTF8.self).contains("from: \"1.2.0\"")) + let range = try edited( + major, + [.upsertSource(.source(name: "rules", url: "https://intranet/team.git", "1.2.0"..<"1.8.0"))]) + #expect(String(decoding: range.bytes, as: UTF8.self).contains("\"1.2.0\"..<\"1.8.0\"")) + } + + @Test func everyComponentSectionPromptAndOverrideOperation() throws { + var doc = try document( + "let agents = Agents(sources: [.source(name: \"s\", path: \"s\")], components: [.skills(source: \"s\"), .instructions(sections: [\"guide\", \"second\"])], groups: [.group(name: \"g\")])" + ) + doc = try edited( + doc, [.insertComponent(.ignore(name: "ignore", patterns: []), into: .root, at: .first)]) + doc = try edited( + doc, + [ + .replaceComponent( + doc.node(at: "/components/0")!, with: .ignore(name: "replacement", patterns: [".build/"])) + ]) + doc = try edited(doc, [.setSkillSelection(doc.node(at: "/components/1")!, ["a", "b"])]) + doc = try edited( + doc, [.upsertSkillOverride(doc.node(at: "/components/1")!, .skill(name: "a", mode: .copy))]) + doc = try edited(doc, [.removeSkillOverride(doc.node(at: "/components/1")!, name: "a")]) + doc = try edited( + doc, [.insertSection("third", into: doc.node(at: "/components/2")!, at: .last)]) + doc = try edited(doc, [.moveSection(doc.node(at: "/components/2/sections/2")!, at: .first)]) + #expect( + doc.declaration.components[2]["sections"]?.elements?.first?.record?["name"] + == .string("third")) + doc = try edited(doc, [.removeSection(doc.node(at: "/components/2/sections/1")!)]) + doc = try edited( + doc, + [.upsertPrompt(doc.node(at: "/components/2")!, .prompt(name: "weekly", sections: ["guide"]))]) + doc = try edited(doc, [.removePrompt(doc.node(at: "/components/2")!, name: "weekly")]) + doc = try edited( + doc, + [ + .moveComponent( + doc.node(at: "/components/0")!, into: .group(doc.node(at: "/groups/0")!), at: .last) + ]) + #expect(doc.declaration.components.count == 2) + #expect(doc.declaration.groups[0]["components"]?.elements?.count == 1) + doc = try edited(doc, [.insertGroupReference("g", into: .root, at: .first)]) + doc = try edited(doc, [.removeGroupReference(doc.node(at: "/uses/0")!)]) + doc = try edited(doc, [.removeComponent(doc.node(at: "/groups/0/components/0")!)]) + doc = try edited(doc, [.removeGroup(name: "g")]) + doc = try edited( + doc, [.removeComponent(doc.node(at: "/components/0")!), .removeSource(alias: "s")]) + #expect(doc.declaration.sources.isEmpty) + } + + @Test func dictionaryEntryEditsPreserveUnrelatedBytesAndHandleNegativeBoundaries() throws { + var doc = try document( + "let agents = Agents(components: [.lspServer(name: \"s\", run: .executable(\"tool\"), languages: [\".swift\": \"swift\"], initializationOptions: [\"x\":/* note */0, \"other\": true])])" + ) + let original = String(decoding: doc.bytes, as: UTF8.self) + doc = try edited( + doc, + [ + .setDictionaryEntry( + doc.node(at: "/components/0/initializationOptions")!, key: "x", value: .configuration(-1)) + ]) + let replaced = String(decoding: doc.bytes, as: UTF8.self) + #expect(replaced == original.replacingOccurrences(of: "/* note */0", with: "/* note */ -1")) + doc = try edited( + doc, + [ + .setDictionaryEntry( + doc.node(at: "/components/0/initializationOptions")!, key: "added", + value: .configuration(["nested": nil])) + ]) + doc = try edited( + doc, + [.removeDictionaryEntry(doc.node(at: "/components/0/initializationOptions")!, key: "added")]) + #expect(String(decoding: doc.bytes, as: UTF8.self).contains("\"other\": true")) + #expect(throws: ManifestFailure.self) { + try doc.preparing([ + .setDictionaryEntry( + doc.node(at: "/components/0/languages")!, key: ".js", value: .integer(3)) + ]) + } + } + + @Test func wholeDefinitionReplacementAcceptsAllTransitiveUses() throws { + let doc = try document( + "let base: [String] = [\"one\"]\nlet alias = base\nlet agents = Agents(components: [.ignore(name: \"a\", patterns: base), .ignore(name: \"b\", patterns: alias)])" + ) + let handle = doc.constant(named: "base")! + let uses = doc.uses(ofConstant: "base") + #expect(uses.count == 3) + #expect(throws: ManifestFailure.self) { + try doc.preparing([ + .replaceConstant(handle, with: .array([.string("two")]), acceptingUses: []) + ]) + } + let changed = try doc.preparing([ + .replaceConstant(handle, with: .array([.string("two")]), acceptingUses: uses) + ]) + #expect(changed.impactedReferences.count == 3) + let result = try DeclarationDocument( + bytes: changed.bytes, identity: DocumentIdentity("manifest")) + #expect(result.declaration.components[0]["patterns"] == .array([.string("two")])) + #expect(result.declaration.components[1]["patterns"] == .array([.string("two")])) + } + + @Test func commentsBOMCRLFFinalNewlineAndUnchangedRangesSurvive() throws { + let text = + "\u{feff}" + + (manifestHeader + + "// file\nlet agents = Agents(\n components: [\n // first owner\n .ignore(name: \"first\", patterns: []), // trailing owner\n\n // second owner\n .ignore(name: \"second\", patterns: [])\n ]\n)") + .replacingOccurrences(of: "\n", with: "\r\n") + let doc = try DeclarationDocument( + bytes: Array(text.utf8), identity: DocumentIdentity("manifest")) + let result = try edited(doc, [.removeComponent(doc.node(at: "/components/0")!)]) + let source = String(decoding: result.bytes, as: UTF8.self) + #expect(source.hasPrefix("\u{feff}// agents-tools-version: 1.0\r\n")) + #expect(!source.hasSuffix("\n")) + #expect(!source.contains("first owner")) + #expect(!source.contains("trailing owner")) + #expect(source.contains("// second owner\r\n .ignore(name: \"second\"")) + #expect(source.contains("// file\r\n")) + } + + @Test func noOpsKeepOriginalBytesAndUnsafeEditsPublishNothing() throws { + let doc = try document( + "let agents = Agents(defaultAgents: nil, sources: [.source(name: \"s\", url: \"https://example.org/s.git\", \"1.2.0\" ..< \"2.0.0\")], components: [/*container*/])" + ) + let noOp = try doc.preparing([ + .setDefaultAgents(nil), + .upsertSource(.source(name: "s", url: "https://example.org/s.git", from: "1.2.0")), + ]) + #expect(noOp.bytes == doc.bytes) + #expect(noOp.patches.isEmpty) + #expect(throws: ManifestFailure.self) { + try doc.preparing([.insertComponent(.instructions(), into: .root, at: .first)]) + } + let unrelated = try document("let agents = Agents()") + #expect(throws: ManifestFailure.self) { + try unrelated.preparing([.removeComponent(doc.node(at: "/sources/0")!)]) + } + #expect(doc.bytes == noOp.bytes) + } + + @Test func symbolicReferencesNeedCompleteRepairBatch() throws { + let doc = try document( + "let agents = Agents(exports: [\"g\"], sources: [.source(name: \"s\", path: \"s\")], groups: [.group(name: \"g\", components: [.skills(source: \"s\")])], uses: [\"g\"], watch: [\"s\"])" + ) + #expect(throws: ManifestFailure.self) { try doc.preparing([.removeSource(alias: "s")]) } + #expect(throws: ManifestFailure.self) { try doc.preparing([.removeGroup(name: "g")]) } + let repaired = try edited( + doc, + [ + .removeSource(alias: "s"), .removeGroup(name: "g"), + .removeGroupReference(doc.node(at: "/uses/0")!), .setExports([]), .setWatch([]), + ]) + #expect(repaired.declaration.sources.isEmpty) + #expect(repaired.declaration.groups.isEmpty) + } + + @Test func replacementKeepsVersionSlotAndNegativeConstantBoundariesValid() throws { + let doc = try document( + "let number: [Int] = [/*keep*/0]\nlet minimum: Version = \"1.2.0\"\nlet agents = Agents(sources: [.source(name: \"s\", path: \"s\", from: minimum)])" + ) + let changed = try edited( + doc, + [ + .replaceConstant( + doc.constant(named: "minimum")!, with: .version("1.3.0"), + acceptingUses: doc.uses(ofConstant: "minimum")) + ]) + #expect( + changed.declaration.sources[0]["requirement"] == .requirement(.upToNextMajor(from: "1.3.0"))) + let n = try document("let number: [Int] = [/*keep*/0]\nlet agents = Agents()") + let scalar = try document("let number = 0\nlet agents = Agents()") + let negative = try edited( + scalar, + [.replaceConstant(scalar.constant(named: "number")!, with: .integer(-1), acceptingUses: [])]) + #expect(String(decoding: negative.bytes, as: UTF8.self).contains("let number = -1")) + #expect(throws: ManifestFailure.self) { + try n.preparing([ + .replaceConstant( + n.constant(named: "number")!, with: .array([.integer(-1)]), acceptingUses: []) + ]) + } + } + @Test func movesCarryLeadingAndTrailingCommentsAndDictionaryEntriesOwnTheirTrivia() throws { + let doc = try document( + """ + let agents = Agents( + components: [ + // follows first + .ignore(name: "first", patterns: []), // inline owner + .ignore(name: "second", patterns: []) + ], + groups: [.group(name: "g")] + ) + """) + let moved = try edited( + doc, + [ + .moveComponent( + doc.node(at: "/components/0")!, into: .group(doc.node(at: "/groups/0")!), at: .last) + ]) + let text = String(decoding: moved.bytes, as: UTF8.self) + #expect(text.range(of: "// follows first")!.lowerBound > text.range(of: "groups:")!.lowerBound) + #expect(text.contains("// inline owner")) + let dictionary = try document( + """ + let agents = Agents(components: [.lspServer( + name: "s", run: .executable("tool"), languages: [".swift": "swift"], + initializationOptions: [ + // remove with x + "x": /* inside x */ 1, // after x + + // keep with y + "y": true + ] + )]) + """) + let removed = try edited( + dictionary, + [ + .removeDictionaryEntry( + dictionary.node(at: "/components/0/initializationOptions")!, key: "x") + ]) + let result = String(decoding: removed.bytes, as: UTF8.self) + #expect(!result.contains("remove with x")) + #expect(!result.contains("inside x")) + #expect(!result.contains("after x")) + #expect(result.contains("keep with y")) + } + +} diff --git a/Tests/AgentsManifestTests/Fixtures/ConsumerExample.swift.txt b/Tests/AgentsManifestTests/Fixtures/ConsumerExample.swift.txt new file mode 100644 index 0000000..d31bf3b --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/ConsumerExample.swift.txt @@ -0,0 +1,97 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let base: [SectionReference] = ["guide"] +let sections = base + [.section(name: "engineering", source: "rules")] +let reviewer: Component = .subagent( + name: "reviewer", + description: "Review correctness and tests.", + prompt: "Check invariants and explain concrete failures.", + agents: [.claudeCode], + condition: .when(platforms: [.macOS]), + native: ["claude-code/subagent@1": ["memory": "project"]] +) + +let agents = Agents( + sources: [ + .source(name: "team", path: "./team"), + .source(name: "drafts", path: "./draft-skills"), + .source(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), + .source(name: "catalog", index: "https://example.org/skills/index.json"), + .source(name: "vendor", url: "https://example.org/vendor/tools.git", exact: "2.1.0"), + ], + components: [ + .skills( + source: "rules", exclude: ["experimental"], mode: .copy, + overrides: [.skill(name: "testing", mode: .link, agents: [.codex])] + ), + .skills( + source: "drafts", select: ["draft"], mode: .edit, + condition: .when(agents: [.claudeCode], scopes: [.project]) + ), + .instructions( + sections: sections, + chatGPT: [.prompt(name: "weekly", sections: base, append: "notes/weekly.md")] + ), + .mcpServer( + name: "workspace", + transport: .stdio( + "workspace-tools", arguments: ["serve"], + environment: ["TOKEN": .secret("workspace-token"), "LOG_LEVEL": "info"] + ), + agents: [.claudeCode] + ), + .mcpServer( + name: "reference", + transport: .streamableHTTP( + url: "https://example.org/mcp", headers: ["Authorization": .environment("MCP_AUTH")] + ), + agents: [.openCode] + ), + .hook( + name: "format", event: .afterTool, + run: .executable( + "swift", arguments: ["format", "--in-place", "Sources"], + workingDirectory: .path("tools", source: "rules") + ), + timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) + ), + .command( + name: "review/change", description: "Review a selected change.", + prompt: "Review ${input:change} and cite evidence.", + parameters: [.parameter(name: "change", description: "The change to review.")], + agents: [.claudeCode] + ), + .lspServer( + name: "swift", run: .executable("sourcekit-lsp"), + languages: [".swift": "swift"], + initializationOptions: ["backgroundIndexing": true], + agents: [.claudeCode], condition: .when(platforms: [.macOS]) + ), + .permissions( + name: "private-files", + rules: [.deny(.read, "secrets/**")], + agents: [.claudeCode], condition: .when(scopes: [.project]) + ), + .ignore( + name: "build-products", patterns: [".build/", "DerivedData/"], purpose: .indexing, + agents: [.cursor], condition: .when(scopes: [.project]) + ), + .plugin( + name: "vendor-tools", path: "plugins/tools", source: "vendor", mode: .native, + agents: [.claudeCode], condition: .when(scopes: [.user]) + ), + .plugin( + name: "shared-tools", path: "plugins/shared", source: "vendor", + exclude: [.hook(name: "format")], condition: .when(scopes: [.project]) + ), + ], + groups: [ + .group( + name: "review-tools", components: [reviewer], + uses: [.group(name: "review", source: "team", condition: .when(agents: [.codex]))] + ), + ], + uses: ["review-tools"], + watch: ["rules", "catalog"] +) diff --git a/Tests/AgentsManifestTests/Fixtures/Contract00.swift.txt b/Tests/AgentsManifestTests/Fixtures/Contract00.swift.txt new file mode 100644 index 0000000..44f9882 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/Contract00.swift.txt @@ -0,0 +1,23 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + sources: [ + .source( + name: "agents-tools", + url: "https://github.com/agents-tools/.github", + branch: "master", + subpath: ".agent" + ), + ], + components: [ + .instructions( + sections: [ + "guide", + .section(name: "shared/swift-package-route", source: "agents-tools"), + .section(name: "shared/swift-package-tests", source: "agents-tools"), + ], + agents: [.claudeCode, .codex] + ), + ] +) diff --git a/Tests/AgentsManifestTests/Fixtures/Contract01.swift.txt b/Tests/AgentsManifestTests/Fixtures/Contract01.swift.txt new file mode 100644 index 0000000..dd35e54 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/Contract01.swift.txt @@ -0,0 +1,16 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + defaultAgents: [.cursor], + sources: [.source(name: "team", path: "./team")], + components: [ + .ignore( + name: "build-products", patterns: [".build/"], purpose: .indexing, + condition: .when(scopes: [.project]) + ), + ], + uses: [ + .group(name: "review", source: "team", condition: .when(agents: [.codex])), + ] +) diff --git a/Tests/AgentsManifestTests/Fixtures/Contract05.swift.txt b/Tests/AgentsManifestTests/Fixtures/Contract05.swift.txt new file mode 100644 index 0000000..a8fb88d --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/Contract05.swift.txt @@ -0,0 +1,11 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + components: [ + .instructions( + sections: ["guide", "code-review-rules"], + agents: [.claudeCode, .codex] + ), + ] +) diff --git a/Tests/AgentsManifestTests/Fixtures/Contract06.swift.txt b/Tests/AgentsManifestTests/Fixtures/Contract06.swift.txt new file mode 100644 index 0000000..91bbf6a --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/Contract06.swift.txt @@ -0,0 +1,16 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + exports: ["review"], + groups: [ + .group( + name: "review", + components: [ + .instructions(sections: ["review-principles"], agents: [.claudeCode, .codex]), + .skills(source: ".", select: ["review"], mode: .copy, agents: [.claudeCode, .codex]), + ], + condition: .when(scopes: [.project]) + ), + ] +) diff --git a/Tests/AgentsManifestTests/Fixtures/Contract07.swift.txt b/Tests/AgentsManifestTests/Fixtures/Contract07.swift.txt new file mode 100644 index 0000000..d31bf3b --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/Contract07.swift.txt @@ -0,0 +1,97 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let base: [SectionReference] = ["guide"] +let sections = base + [.section(name: "engineering", source: "rules")] +let reviewer: Component = .subagent( + name: "reviewer", + description: "Review correctness and tests.", + prompt: "Check invariants and explain concrete failures.", + agents: [.claudeCode], + condition: .when(platforms: [.macOS]), + native: ["claude-code/subagent@1": ["memory": "project"]] +) + +let agents = Agents( + sources: [ + .source(name: "team", path: "./team"), + .source(name: "drafts", path: "./draft-skills"), + .source(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), + .source(name: "catalog", index: "https://example.org/skills/index.json"), + .source(name: "vendor", url: "https://example.org/vendor/tools.git", exact: "2.1.0"), + ], + components: [ + .skills( + source: "rules", exclude: ["experimental"], mode: .copy, + overrides: [.skill(name: "testing", mode: .link, agents: [.codex])] + ), + .skills( + source: "drafts", select: ["draft"], mode: .edit, + condition: .when(agents: [.claudeCode], scopes: [.project]) + ), + .instructions( + sections: sections, + chatGPT: [.prompt(name: "weekly", sections: base, append: "notes/weekly.md")] + ), + .mcpServer( + name: "workspace", + transport: .stdio( + "workspace-tools", arguments: ["serve"], + environment: ["TOKEN": .secret("workspace-token"), "LOG_LEVEL": "info"] + ), + agents: [.claudeCode] + ), + .mcpServer( + name: "reference", + transport: .streamableHTTP( + url: "https://example.org/mcp", headers: ["Authorization": .environment("MCP_AUTH")] + ), + agents: [.openCode] + ), + .hook( + name: "format", event: .afterTool, + run: .executable( + "swift", arguments: ["format", "--in-place", "Sources"], + workingDirectory: .path("tools", source: "rules") + ), + timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) + ), + .command( + name: "review/change", description: "Review a selected change.", + prompt: "Review ${input:change} and cite evidence.", + parameters: [.parameter(name: "change", description: "The change to review.")], + agents: [.claudeCode] + ), + .lspServer( + name: "swift", run: .executable("sourcekit-lsp"), + languages: [".swift": "swift"], + initializationOptions: ["backgroundIndexing": true], + agents: [.claudeCode], condition: .when(platforms: [.macOS]) + ), + .permissions( + name: "private-files", + rules: [.deny(.read, "secrets/**")], + agents: [.claudeCode], condition: .when(scopes: [.project]) + ), + .ignore( + name: "build-products", patterns: [".build/", "DerivedData/"], purpose: .indexing, + agents: [.cursor], condition: .when(scopes: [.project]) + ), + .plugin( + name: "vendor-tools", path: "plugins/tools", source: "vendor", mode: .native, + agents: [.claudeCode], condition: .when(scopes: [.user]) + ), + .plugin( + name: "shared-tools", path: "plugins/shared", source: "vendor", + exclude: [.hook(name: "format")], condition: .when(scopes: [.project]) + ), + ], + groups: [ + .group( + name: "review-tools", components: [reviewer], + uses: [.group(name: "review", source: "team", condition: .when(agents: [.codex]))] + ), + ], + uses: ["review-tools"], + watch: ["rules", "catalog"] +) diff --git a/Tests/AgentsManifestTests/Fixtures/CoreExample.swift.txt b/Tests/AgentsManifestTests/Fixtures/CoreExample.swift.txt new file mode 100644 index 0000000..44f9882 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/CoreExample.swift.txt @@ -0,0 +1,23 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + sources: [ + .source( + name: "agents-tools", + url: "https://github.com/agents-tools/.github", + branch: "master", + subpath: ".agent" + ), + ], + components: [ + .instructions( + sections: [ + "guide", + .section(name: "shared/swift-package-route", source: "agents-tools"), + .section(name: "shared/swift-package-tests", source: "agents-tools"), + ], + agents: [.claudeCode, .codex] + ), + ] +) diff --git a/Tests/AgentsManifestTests/Fixtures/LiteralCoverage.swift.txt b/Tests/AgentsManifestTests/Fixtures/LiteralCoverage.swift.txt new file mode 100644 index 0000000..cceecf7 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/LiteralCoverage.swift.txt @@ -0,0 +1,43 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let text: PromptContent = "Review invariants." +let section: SectionReference = "guide" +let local: GroupReference = "review" +let selection: SkillSelection = ["review", "testing"] +let configuration: ConfigurationValue = [ + "string": "value", "integer": -1, "boolean": true, "null": nil, + "array": [1, "two", false, nil], "object": ["enabled": true], "decimal": .decimal("1.25") +] +let environment: [String: RuntimeValue] = ["LEVEL": "info", "TOKEN": .secret("token")] +let emptySelection: SkillSelection = [] +let emptyObject: ConfigurationValue = [:] +let emptyArray: ConfigurationValue = [] +let emptyTools: Component = .subagent(name: "empty-tools", description: "No tools", prompt: "Read", tools: []) +let invocation: ExecutableInvocation = .executable("server", environment: environment, workingDirectory: .path("tools", source: "vendor")) +let runtime: RuntimeValue = .literal("literal") +let scalar: ConfigurationValue = .string("x") +let integer: ConfigurationValue = .integer(-9223372036854775808) +let boolean: ConfigurationValue = .boolean(false) +let null: ConfigurationValue = .null +let array: ConfigurationValue = .array([scalar, integer, boolean, null]) +let object: ConfigurationValue = .object(["array": array]) +let agents = Agents( + exports: ["review"], + sources: [.source(name: "team", path: "team"), .source(name: "vendor", path: "vendor")], + components: [ + .mcpServer(name: "tools", transport: .stdio("server", environment: environment)), + .mcpServer(name: "sse", transport: .sse(url: "https://example.org/events")), + .command(name: "review", description: "Review", prompt: text), + .instructions(sections: [section]), + .skills(source: "team", select: selection, overrides: [.skill(name: "review", mode: .copy, agents: [.codex])]), + .lspServer(name: "swift", run: invocation, languages: [".swift": "swift"], initializationOptions: ["config": configuration]), + .permissions(name: "policy", rules: [.allow(.read, "Sources/**"), .ask(.write, "**"), .deny(.execute, "rm *"), .deny(.tool("fetch"), "*")]), + .plugin(name: "tools", path: "plugins/tools", source: "vendor", select: [.skills, .instructions, .mcpServer, .hook, .subagent, .command, .lspServer, .permissions, .ignore, .plugin], exclude: [.skill(name: "a"), .instruction(name: "a"), .mcpServer(name: "a"), .hook(name: "a"), .subagent(name: "a"), .command(name: "a"), .lspServer(name: "a"), .permissions(name: "a"), .ignore(name: "a"), .plugin(name: "a")]), + .hook(name: "native", event: .native("Event"), run: invocation, agents: [.codex]), + .ignore(name: "context", patterns: [], purpose: .context, agents: [], condition: .when(scopes: [.project, .user], platforms: [.macOS, .linux])), + emptyTools + ], + groups: [.group(name: "review")], + uses: [local, .group(name: "review", condition: .when(agents: [.codex]))] +) diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationEdgeExample.swift.txt b/Tests/AgentsManifestTests/Fixtures/MigrationEdgeExample.swift.txt new file mode 100644 index 0000000..b153fea --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationEdgeExample.swift.txt @@ -0,0 +1,51 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + sources: [ + .source(name: "source", path: "./drafts", from: "1.2.0"), + .source( + name: "source-2", + path: "./more", + .upToNextMinor(from: "1.2.0") + ), + .source(name: "source-3", url: "https://example.org/rules.git"), + ], + components: [ + .skills( + source: "source", + overrides: [ + .skill( + name: "future", + agents: [.openCode] + ), + ] + ), + .skills( + source: "source-3", + select: ["a"], + overrides: [ + .skill( + name: "a", + mode: .copy, + agents: [.codex] + ), + ] + ), + .instructions( + sections: [ + "guide", + .section(name: "rule", source: "source-3"), + ], + chatGPT: [ + .prompt( + name: "", + sections: [ + .section(name: "rule", source: "source-3"), + ] + ), + ] + ), + ], + watch: ["source-3"] +) diff --git a/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json b/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json new file mode 100644 index 0000000..58eeb81 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json @@ -0,0 +1,102 @@ +{ + "swiftSyntax": "604.0.0", + "toolchain": "Apple Swift 6.4 (swiftlang-6.4.0.34.1), arm64 macOS 27", + "fixtures": { + "ConsumerExample.swift.txt": { + "tokens": 741, + "syntaxReservation": 2980, + "syntaxNodes": 1707, + "syntaxDepth": 31 + }, + "Contract00.swift.txt": { + "tokens": 82, + "syntaxReservation": 344, + "syntaxNodes": 199, + "syntaxDepth": 26 + }, + "Contract01.swift.txt": { + "tokens": 97, + "syntaxReservation": 404, + "syntaxNodes": 217, + "syntaxDepth": 25 + }, + "Contract05.swift.txt": { + "tokens": 34, + "syntaxReservation": 152, + "syntaxNodes": 88, + "syntaxDepth": 23 + }, + "Contract06.swift.txt": { + "tokens": 93, + "syntaxReservation": 388, + "syntaxNodes": 210, + "syntaxDepth": 29 + }, + "Contract07.swift.txt": { + "tokens": 741, + "syntaxReservation": 2980, + "syntaxNodes": 1707, + "syntaxDepth": 31 + }, + "CoreExample.swift.txt": { + "tokens": 82, + "syntaxReservation": 344, + "syntaxNodes": 199, + "syntaxDepth": 26 + }, + "MigrationEdgeExample.swift.txt": { + "tokens": 191, + "syntaxReservation": 780, + "syntaxNodes": 446, + "syntaxDepth": 32 + }, + "ProducerExample.swift.txt": { + "tokens": 93, + "syntaxReservation": 388, + "syntaxNodes": 210, + "syntaxDepth": 29 + }, + "RequirementValues.swift.txt": { + "tokens": 304, + "syntaxReservation": 1232, + "syntaxNodes": 823, + "syntaxDepth": 26 + }, + "RequirementsExample.swift.txt": { + "tokens": 503, + "syntaxReservation": 2028, + "syntaxNodes": 1251, + "syntaxDepth": 29 + }, + "SketchExample.swift.txt": { + "tokens": 97, + "syntaxReservation": 404, + "syntaxNodes": 217, + "syntaxDepth": 25 + }, + "SkillsExample.swift.txt": { + "tokens": 34, + "syntaxReservation": 152, + "syntaxNodes": 88, + "syntaxDepth": 23 + }, + "TasteSample.swift.txt": { + "tokens": 414, + "syntaxReservation": 1672, + "syntaxNodes": 961, + "syntaxDepth": 29 + }, + "VocabularyDepthExample.swift.txt": { + "tokens": 68, + "syntaxReservation": 288, + "syntaxNodes": 155, + "syntaxDepth": 43 + }, + "LiteralCoverage.swift.txt": { + "tokens": 729, + "syntaxReservation": 2932, + "syntaxNodes": 1805, + "syntaxDepth": 29 + } + } +} diff --git a/Tests/AgentsManifestTests/Fixtures/ProducerExample.swift.txt b/Tests/AgentsManifestTests/Fixtures/ProducerExample.swift.txt new file mode 100644 index 0000000..91bbf6a --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/ProducerExample.swift.txt @@ -0,0 +1,16 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + exports: ["review"], + groups: [ + .group( + name: "review", + components: [ + .instructions(sections: ["review-principles"], agents: [.claudeCode, .codex]), + .skills(source: ".", select: ["review"], mode: .copy, agents: [.claudeCode, .codex]), + ], + condition: .when(scopes: [.project]) + ), + ] +) diff --git a/Tests/AgentsManifestTests/Fixtures/RequirementValues.swift.txt b/Tests/AgentsManifestTests/Fixtures/RequirementValues.swift.txt new file mode 100644 index 0000000..98a5199 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/RequirementValues.swift.txt @@ -0,0 +1,24 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let majorFrom: Source = .source(name: "rules", url: "https://example.org/rules.git", from: "1.2.0") +let majorHelper: Source = .source(name: "rules", url: "https://example.org/rules.git", .upToNextMajor(from: "1.2.0")) +let majorRange: Source = .source(name: "rules", url: "https://example.org/rules.git", "1.2.0"..<"2.0.0") +let minorHelper: Source = .source(name: "rules", url: "https://example.org/rules.git", .upToNextMinor(from: "1.2.0")) +let minorRange: Source = .source(name: "rules", url: "https://example.org/rules.git", "1.2.0"..<"1.3.0") +let prereleaseFrom: Source = .source(name: "rules", url: "https://example.org/rules.git", from: "1.2.3-beta.1+build.7") +let prereleaseHelper: Source = .source(name: "rules", url: "https://example.org/rules.git", .upToNextMajor(from: "1.2.3-beta.1+build.7")) +let prereleaseRange: Source = .source(name: "rules", url: "https://example.org/rules.git", "1.2.3-beta.1+build.7"..<"2.0.0") +let prereleaseMinor: Source = .source(name: "rules", url: "https://example.org/rules.git", .upToNextMinor(from: "1.2.3-beta.1+build.7")) +let prereleaseMinorRange: Source = .source(name: "rules", url: "https://example.org/rules.git", "1.2.3-beta.1+build.7"..<"1.3.0") +let localLiteral: GroupReference = "review" +let localFactory: GroupReference = .group(name: "review") +let agents = Agents( + exports: ["review"], + sources: [majorFrom], + components: [ + .plugin(name: "tools", path: "tools", source: "rules", exclude: [.hook(name: "format")]), + ], + groups: [.group(name: "review")], + uses: [localLiteral] +) diff --git a/Tests/AgentsManifestTests/Fixtures/RequirementsExample.swift.txt b/Tests/AgentsManifestTests/Fixtures/RequirementsExample.swift.txt new file mode 100644 index 0000000..eee30dd --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/RequirementsExample.swift.txt @@ -0,0 +1,46 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let minimum: Version = "1.2.0" +let review: ComponentGroup = .group( + name: "review", + components: [ + .skills(source: ".", overrides: [.skill(name: "review", mode: .copy)]), + .instructions( + sections: [.section(name: "guide", source: ".")], + chatGPT: [.prompt(name: "weekly", sections: ["guide"])] + ), + .command( + name: "review", description: "Review a change", prompt: .file("review.md", source: "."), + parameters: [.parameter(name: "change", description: "Change identifier", defaultValue: "HEAD")] + ), + .hook( + name: "format", event: .afterTool, + run: .executable("swift", workingDirectory: .path("Sources", source: ".")) + ), + ] +) +let agents = Agents( + exports: ["review"], + sources: [ + .source(name: "major", url: "https://example.org/major.git", from: minimum), + .source(name: "exact", url: "https://example.org/exact.git", exact: "1.2.0"), + .source(name: "branch", url: "https://example.org/branch.git", branch: "main"), + .source(name: "revision", url: "https://example.org/revision.git", revision: "abc123"), + .source(name: "range", url: "https://example.org/range.git", "1.2.0"..<"2.0.0"), + .source(name: "minor", url: "https://example.org/minor.git", .upToNextMinor(from: "1.2.0")), + .source(name: "explicit-major", url: "https://example.org/explicit.git", .upToNextMajor(from: minimum)), + .source(name: "local-major", path: "./major", from: "1.2.0"), + .source(name: "local-exact", path: "./exact", exact: "1.2.0"), + .source(name: "local-branch", path: "./branch", branch: "main"), + .source(name: "local-revision", path: "./revision", revision: "abc123"), + .source(name: "local-range", path: "./range", "1.2.0" ..< "2.0.0", subpath: "tools"), + .source(name: "local-minor", path: "./minor", .upToNextMinor(from: "1.2.0")), + .source(name: "local-explicit-major", path: "./explicit", .upToNextMajor(from: "1.2.0")), + .source(name: "unversioned", url: "https://example.org/unversioned.git"), + .source(name: "local", path: "./local"), + .source(name: "catalog", index: "https://example.org/index.json", subpath: "tools"), + ], + groups: [review, .group(name: "quality", uses: ["review"])], + uses: ["quality", .group(name: "review", source: "major")] +) diff --git a/Tests/AgentsManifestTests/Fixtures/SketchExample.swift.txt b/Tests/AgentsManifestTests/Fixtures/SketchExample.swift.txt new file mode 100644 index 0000000..dd35e54 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/SketchExample.swift.txt @@ -0,0 +1,16 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + defaultAgents: [.cursor], + sources: [.source(name: "team", path: "./team")], + components: [ + .ignore( + name: "build-products", patterns: [".build/"], purpose: .indexing, + condition: .when(scopes: [.project]) + ), + ], + uses: [ + .group(name: "review", source: "team", condition: .when(agents: [.codex])), + ] +) diff --git a/Tests/AgentsManifestTests/Fixtures/SkillsExample.swift.txt b/Tests/AgentsManifestTests/Fixtures/SkillsExample.swift.txt new file mode 100644 index 0000000..a8fb88d --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/SkillsExample.swift.txt @@ -0,0 +1,11 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + components: [ + .instructions( + sections: ["guide", "code-review-rules"], + agents: [.claudeCode, .codex] + ), + ] +) diff --git a/Tests/AgentsManifestTests/Fixtures/TasteSample.swift.txt b/Tests/AgentsManifestTests/Fixtures/TasteSample.swift.txt new file mode 100644 index 0000000..efa409a --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/TasteSample.swift.txt @@ -0,0 +1,81 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +// A team repository's .agent/Agents.swift. +// Everything here is a declaration: agents reads it, never runs it. + +let reviewer: Component = .subagent( + name: "reviewer", + description: "Review correctness and tests.", + prompt: "Check invariants and explain concrete failures.", + agents: [.claudeCode] +) + +let agents = Agents( + // Components without their own `agents:` go to these. + defaultAgents: [.claudeCode, .codex], + + sources: [ + .source(name: "org", url: "https://github.com/acme/.github", branch: "main", subpath: ".agent"), + .source(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), + .source(name: "drafts", path: "./draft-skills"), + ], + + components: [ + // AGENTS.md / CLAUDE.md, assembled from sections. + .instructions( + sections: [ + "guide", + .section(name: "shared/swift-package-route", source: "org"), + ] + ), + + // Every skill from `rules` except one; Codex gets `testing` as a link. + .skills( + source: "rules", exclude: ["experimental"], mode: .copy, + overrides: [.skill(name: "testing", mode: .link, agents: [.codex])] + ), + + // Work-in-progress skills, only for Claude Code in this project. + .skills( + source: "drafts", select: ["draft"], mode: .edit, + condition: .when(agents: [.claudeCode], scopes: [.project]) + ), + + .mcpServer( + name: "workspace", + transport: .stdio( + "workspace-tools", arguments: ["serve"], + environment: ["TOKEN": .secret("workspace-token"), "LOG_LEVEL": "info"] + ) + ), + + .hook( + name: "format", event: .afterTool, + run: .executable("swift", arguments: ["format", "--in-place", "Sources"]), + timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) + ), + + .lspServer( + name: "swift", run: .executable("sourcekit-lsp"), + languages: [".swift": "swift"], + agents: [.claudeCode], condition: .when(platforms: [.macOS]) + ), + + .permissions( + name: "private-files", + rules: [.deny(.read, "secrets/**")], + condition: .when(scopes: [.project]) + ), + + .ignore( + name: "build-products", patterns: [".build/", "DerivedData/"], purpose: .indexing, + agents: [.cursor] + ), + + reviewer, + ], + + // Re-check these sources for updates. + watch: ["rules"] +) diff --git a/Tests/AgentsManifestTests/Fixtures/VocabularyDepthExample.swift.txt b/Tests/AgentsManifestTests/Fixtures/VocabularyDepthExample.swift.txt new file mode 100644 index 0000000..b6b6f35 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/VocabularyDepthExample.swift.txt @@ -0,0 +1,22 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + groups: [ + .group( + name: "review", + components: [ + .instructions( + chatGPT: [ + .prompt( + name: "review", + sections: [ + .section(name: "guide", condition: .when(agents: [.codex])), + ] + ), + ] + ), + ] + ), + ] +) diff --git a/Tests/AgentsManifestTests/FrontEndTests.swift b/Tests/AgentsManifestTests/FrontEndTests.swift new file mode 100644 index 0000000..3e32aec --- /dev/null +++ b/Tests/AgentsManifestTests/FrontEndTests.swift @@ -0,0 +1,153 @@ +import AgentsCore +import AgentsDescription +import Foundation +import Testing + +@testable import AgentsManifest + +let manifestHeader = "// agents-tools-version: 1.0\nimport AgentsDescription\n\n" + +func document(_ body: String) throws -> DeclarationDocument { + try DeclarationDocument( + bytes: Array((manifestHeader + body).utf8), identity: DocumentIdentity("manifest")) +} + +@Suite("Manifest front end") +struct FrontEndTests { + @Test func completeExamplesCompileAndAgreeUnderValueEquality() throws { + let baselineURL = Bundle.module.resourceURL!.appendingPathComponent( + "Fixtures/ParserBaseline.json") + let baseline = + try JSONSerialization.jsonObject(with: Data(contentsOf: baselineURL)) as! [String: Any] + let baselineFixtures = baseline["fixtures"] as! [String: [String: Int]] + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent() + let resolved = + try JSONSerialization.jsonObject( + with: Data(contentsOf: root.appendingPathComponent("Package.resolved"))) as! [String: Any] + let pins = resolved["pins"] as! [[String: Any]] + let syntaxPin = pins.first { $0["identity"] as? String == "swift-syntax" }! + #expect( + (syntaxPin["state"] as! [String: String])["version"] == baseline["swiftSyntax"] as? String) + for fixture in compiledFixtures() { + let name = fixture.name + let url = Bundle.module.resourceURL!.appendingPathComponent("Fixtures/" + name) + let doc = try DeclarationDocument( + bytes: Array(Data(contentsOf: url)), identity: DocumentIdentity("manifest")) + #expect(fixture.agents == Agents(value: doc.evaluation.root.value), "\(name)") + #expect(fixture.constants.keys.sorted() == doc.evaluation.constants.keys.sorted()) + for (constant, compiled) in fixture.constants { + #expect(compiled == doc.evaluation.constants[constant]?.value, "\(name): \(constant)") + } + #expect(doc.metrics.parserCalls == 1) + #expect(doc.metrics.syntaxNodes <= doc.metrics.syntaxReservation) + #expect(doc.metrics.syntaxDepth <= 128) + #expect(!doc.sourceMap.entries.isEmpty) + if let expected = baselineFixtures[name] { + #expect(doc.metrics.tokens == expected["tokens"]) + #expect(doc.metrics.syntaxReservation == expected["syntaxReservation"]) + #expect(doc.metrics.syntaxNodes == expected["syntaxNodes"]) + #expect(doc.metrics.syntaxDepth == expected["syntaxDepth"]) + } else { + Issue.record("fixture is missing from parser baseline: \(name)") + } + } + } + + @Test func closedLiteralTyping() throws { + let bodies = [ + "let text = \"x\"\nlet value: SectionReference = text", + "let text = \"x\"\nlet value: PromptContent = text", + "let text = \"x\"\nlet value: RuntimeValue = text", + "let text = \"1.2.0\"\nlet value: Version = text", + "let text = \"review\"\nlet value: GroupReference = text", + "let names = [\"x\"]\nlet value: SkillSelection = names", + "let text = \"x\"\nlet value: ConfigurationValue = text", + "let value = .copy", "let value = []", "let value = [:]", "let value = nil", + "let value = \"a\" + \"b\"", "let value: SkillSelection = [\"a\"] + [\"b\"]", + "let value: ConfigurationValue = [1] + [2]", "let value = Version(\"1.2.0\")", + "let value = String(stringLiteral: \"x\")", "let value = future\nlet future = 1", + ] + for body in bodies { + #expect(throws: ManifestFailure.self) { try document(body + "\nlet agents = Agents()") } + } + } + + @Test func rangeValuesAndLiteralGroupReferencesAreEqual() throws { + let fixtures = compiledFixtures().first { $0.name == "RequirementValues.swift.txt" }! + let url = Bundle.module.resourceURL!.appendingPathComponent("Fixtures/" + fixtures.name) + let doc = try DeclarationDocument( + bytes: Array(Data(contentsOf: url)), identity: DocumentIdentity("manifest")) + let constants = doc.evaluation.constants + for pair in [ + ("majorFrom", "majorHelper"), ("majorFrom", "majorRange"), ("minorHelper", "minorRange"), + ("prereleaseFrom", "prereleaseHelper"), ("prereleaseFrom", "prereleaseRange"), + ("prereleaseMinor", "prereleaseMinorRange"), ("localLiteral", "localFactory"), + ] { + #expect(constants[pair.0]!.value == constants[pair.1]!.value, "\(pair)") + #expect( + Lowering.lower(constants[pair.0]!.value) == Lowering.lower(constants[pair.1]!.value), + "\(pair)") + } + } + + @Test func domainValidationIsOfflineAndIncludesUnusedValues() throws { + let bad = [ + "let bad: Condition = .when(agents: [.codex, .codex])\nlet agents = Agents()", + "let agents = Agents(sources: [.source(name: \".\", path: \"a\")])", + "let agents = Agents(sources: [.source(name: \"a\", url: \"https://EXAMPLE.org/r.git\"), .source(name: \"b\", url: \"https://example.org/r/\")])", + "let agents = Agents(components: [.hook(name: \"h\", event: .native(\"x\"), run: .executable(\"tool\"))])", + "let agents = Agents(components: [.hook(name: \"h\", event: .beforeTool, run: .executable(\"tool\"), timeoutSeconds: 0)])", + "let agents = Agents(components: [.subagent(name: \"../bad\", description: \"x\", prompt: \"x\")])", + "let agents = Agents(components: [.mcpServer(name: \"x\", transport: .sse(url: \"https://user:pw@example.org/mcp\"))])", + "let agents = Agents(components: [.command(name: \"x\", description: \"x\", prompt: \"${input:missing}\")])", + "let value: ConfigurationValue = .decimal(\"1e99999\")\nlet agents = Agents()", + "let value: Resource = .path(\"../escape\")\nlet agents = Agents()", + "let value: PermissionRule = .allow(.read, \"/private/**\")\nlet agents = Agents()", + "let value: PermissionRule = .deny(.write, \"../**\")\nlet agents = Agents()", + "let agents = Agents(groups: [.group(name: \"a\", uses: [\"b\"]), .group(name: \"b\", uses: [\"a\"])])", + "let agents = Agents(groups: [.group(name: \"unused\", uses: [\"missing\"])])", + ] + for input in bad { #expect(throws: ManifestFailure.self) { try document(input) } } + let doc = try document( + "let agents = Agents(sources: [.source(name: \"r\", url: \"intranet/team\")])") + #expect(doc.diagnostics.first?.code == "manifest.domain") + #expect(doc.diagnostics.first?.severity == .warning) + #expect( + String(decoding: doc.diagnostics.first!.fixIt!.replacement, as: UTF8.self) + == "\"https://intranet/team\"") + _ = try document( + "let root: Resource = .path(\"\")\nlet notes: Resource = .path(\"~notes\")\nlet rule: PermissionRule = .allow(.read, \"src/**\")\nlet agents = Agents(components: [.mcpServer(name: \"s\", transport: .streamableHTTP(url: \"HTTPS://example.org/mcp\"))])" + ) + } + + @Test func duplicateKeysUseDecodedSwiftStringEqualityAndLocatedRelatedSpans() throws { + for key in ["\\u{61}", "a"] { + do { + _ = try document( + "let value: [String: Int] = [\"a\": 1, \"\(key)\": 2]\nlet agents = Agents()") + Issue.record("duplicate accepted") + } catch let error as ManifestFailure { + #expect(error.diagnostics[0].code == "manifest.dictionary.duplicateKey") + #expect(error.diagnostics[0].related.count == 1) + #expect(error.diagnostics[0].span.start > error.diagnostics[0].related[0].start) + } + } + #expect(throws: ManifestFailure.self) { + try document( + "let value: ConfigurationValue = [\"é\": 1, \"e\\u{301}\": 2]\nlet agents = Agents()") + } + } + + @Test func defaultsOrderConditionsAndProvenanceRemainSymbolic() throws { + let doc = try document( + "let sections: [SectionReference] = [\"guide\", \"guide\"]\nlet agents = Agents(defaultAgents: [], components: [.instructions(sections: sections, condition: .when(agents: []))], groups: [.group(name: \"inert\")])" + ) + #expect(doc.declaration.defaultAgents == []) + #expect(doc.declaration.components[0]["agents"] == .null) + #expect(doc.declaration.components[0]["sections"]?.elements?.count == 2) + #expect(doc.declaration.groups.count == 1) + #expect(doc.sourceMap.locations(at: "/components/0/agents").first?.defaulted == true) + #expect(doc.sourceMap.locations(at: "/components/0/sections/0").first?.origins.isEmpty == false) + } +} diff --git a/Tests/AgentsManifestTests/InventoryTests.swift b/Tests/AgentsManifestTests/InventoryTests.swift new file mode 100644 index 0000000..1999770 --- /dev/null +++ b/Tests/AgentsManifestTests/InventoryTests.swift @@ -0,0 +1,126 @@ +import AgentsCore +import AgentsDescription +import Foundation +import SwiftParser +import SwiftSyntax +import Testing + +@testable import AgentsManifest + +@Suite("Manifest construction inventory") +struct InventoryTests { + private var root: URL { + URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent() + } + + @Test func contractSignaturesDefaultsAndLiteralProtocolsMatchRegistration() throws { + let contract = try String( + contentsOf: root.appendingPathComponent("Documentation/Proposals/AgentsManifest.md"), + encoding: .utf8) + let vocabulary = String(contract.prefix(upTo: contract.range(of: "### Targeting")!.lowerBound)) + let blocks = vocabulary.components(separatedBy: "```swift\n").dropFirst().compactMap { + $0.components(separatedBy: "```").first + }.filter { $0.hasPrefix("public ") } + var signatures: [String] = [] + var namedTypes = Set(["String", "Int", "Bool"]) + var literalTypes: [String: Set] = [:] + let protocolKinds = [ + "ExpressibleByStringLiteral": "string", "ExpressibleByIntegerLiteral": "integer", + "ExpressibleByBooleanLiteral": "boolean", "ExpressibleByNilLiteral": "nil", + "ExpressibleByArrayLiteral": "array", "ExpressibleByDictionaryLiteral": "dictionary", + ] + for block in blocks { + let tree = Parser.parse(source: block) + let source = SourceText(Array(block.utf8), identity: DocumentIdentity("interface")) + _ = try SyntaxValidation.guardTree(Syntax(tree), source: source) + var pending: [(Syntax, String)] = [(Syntax(tree), "")] + while let (node, owner) = pending.popLast() { + var name = owner + if let declaration = node.as(StructDeclSyntax.self) { + name = declaration.name.text + namedTypes.insert(name) + for inherited in declaration.inheritanceClause?.inheritedTypes ?? [] { + if let kind = protocolKinds[inherited.type.trimmedDescription] { + literalTypes[name, default: []].insert(kind) + } + } + } else if let declaration = node.as(EnumDeclSyntax.self) { + name = declaration.name.text + namedTypes.insert(name) + for inherited in declaration.inheritanceClause?.inheritedTypes ?? [] { + if let kind = protocolKinds[inherited.type.trimmedDescription] { + literalTypes[name, default: []].insert(kind) + } + } + } else if let declaration = node.as(TypeAliasDeclSyntax.self) { + namedTypes.insert(declaration.name.text) + } else if let method = node.as(FunctionDeclSyntax.self), name != "Version" { + let parameters = method.signature.parameterClause.parameters.map { parameter in + let defaultValue = parameter.defaultValue?.value.trimmedDescription ?? "required" + return parameter.firstName.text + ":" + + parameter.type.trimmedDescription.replacingOccurrences(of: " ", with: "") + "=" + + defaultValue + }.joined(separator: ",") + signatures.append(name + "." + method.name.text + "(" + parameters + ")") + } else if let initializer = node.as(InitializerDeclSyntax.self), name == "Agents" { + let parameters = initializer.signature.parameterClause.parameters.map { parameter in + parameter.firstName.text + ":" + + parameter.type.trimmedDescription.replacingOccurrences(of: " ", with: "") + "=" + + (parameter.defaultValue?.value.trimmedDescription ?? "required") + }.joined(separator: ",") + signatures.append("Agents.Agents(" + parameters + ")") + } + for child in node.children(viewMode: .sourceAccurate) { pending.append((child, name)) } + } + } + #expect(namedTypes == Vocabulary.typeNames) + #expect(literalTypes == Vocabulary.literalTypes) + let inventory = + try JSONSerialization.jsonObject( + with: Data(contentsOf: root.appendingPathComponent("Scripts/ManifestVocabulary.json"))) + as! [String: Any] + let factories = inventory["factories"] as! [[String: Any]] + let registered = factories.filter { $0["property"] == nil }.map { method in + let parameters = (method["parameters"] as! [[String: String]]).map { parameter in + parameter["label"]! + ":" + parameter["type"]!.replacingOccurrences(of: " ", with: "") + "=" + + (parameter["default"] ?? "required") + }.joined(separator: ",") + return (method["type"] as! String) + "." + (method["name"] as! String) + "(" + parameters + + ")" + } + #expect(Set(signatures.filter { !$0.hasPrefix(".upToNext") }) == Set(registered)) + let enumCount = (inventory["enums"] as! [String: [[String: Any]]]).values.reduce(0) { + $0 + $1.count + } + #expect(Vocabulary.signatures.count == factories.count + enumCount + 2) + #expect(Vocabulary.signatures.filter { $0.type == "VersionRange" }.count == 2) + #expect( + Vocabulary.signatures.filter { $0.type == "SkillSelection" && $0.member == "all" }.count == 1) + } + + @Test func allContractSwiftBlocksPassTheRealParser() throws { + let contract = try String( + contentsOf: root.appendingPathComponent("Documentation/Proposals/AgentsManifest.md"), + encoding: .utf8) + let directory = try temporaryManifestDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + for (index, tail) in contract.components(separatedBy: "```swift\n").dropFirst().enumerated() { + let block = tail.components(separatedBy: "```")[0] + let file = directory.appendingPathComponent( + "block\(index)." + (block.hasPrefix("public ") ? "swiftinterface" : "swift")) + try Data(block.utf8).write(to: file) + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/env") + process.arguments = ["swiftc", "-frontend", "-parse", file.path] + let errors = Pipe() + process.standardError = errors + try process.run() + let errorData = errors.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + #expect( + process.terminationReason == .exit && process.terminationStatus == 0, + "block \(index): \(String(decoding: errorData, as: UTF8.self))") + } + } +} diff --git a/Tests/AgentsManifestTests/ResourceAndVersionTests.swift b/Tests/AgentsManifestTests/ResourceAndVersionTests.swift new file mode 100644 index 0000000..34557ae --- /dev/null +++ b/Tests/AgentsManifestTests/ResourceAndVersionTests.swift @@ -0,0 +1,160 @@ +import AgentsCore +import AgentsDescription +import Foundation +import Testing + +@testable import AgentsManifest + +@Suite("Manifest resources and language versions") +struct ResourceAndVersionTests { + @Test func directiveDiagnosticsAreLexicalAndDistinct() throws { + for (text, code) in [ + ("import AgentsDescription\nlet agents = Agents()", "manifest.version.missing"), + ( + "// agents-tools-version: 01.0\nimport AgentsDescription\nlet agents = Agents()", + "manifest.version.invalid" + ), + ( + "// agents-tools-version: 1.0 \nimport AgentsDescription\nlet agents = Agents()", + "manifest.version.invalid" + ), + ( + "// agents-tools-version: 2.0\nimport AgentsDescription\nlet agents = Agents()", + "manifest.version.unsupported" + ), + ( + manifestHeader + "// agents-tools-version: 1.0\nlet agents = Agents()", + "manifest.version.duplicate" + ), + ] { + do { + _ = try DeclarationDocument(bytes: Array(text.utf8), identity: DocumentIdentity("manifest")) + Issue.record("directive accepted") + } catch let failure as ManifestFailure { + #expect(failure.diagnostics[0].code == code) + #expect(failure.metrics.parserCalls == 0) + } + } + _ = try document("let text = \"// agents-tools-version: 1.0\"\nlet agents = Agents()") + } + + @Test func everyConstantChargesItsFullExpandedCostBeforeUseOrMapping() throws { + let directory = try temporaryManifestDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + var body = "let v0: ConfigurationValue = 1\n" + for index in 1...24 { + body += "let v\(index): ConfigurationValue = .array([v\(index - 1), v\(index - 1)])\n" + } + let report = try probe( + "unused-exponential-reuse", Array((manifestHeader + body + "let agents = Agents()").utf8), + semantics: true, in: directory) + #expect(report.report.stage == "evaluation") + #expect(report.report.status == "manifest.limit") + var aliases = "let seed: ConfigurationValue = 0\n" + var tail = "seed" + for level in 0..<50 { + let container = "c\(level)" + aliases += "let \(container): ConfigurationValue = .array([\(tail)])\n" + tail = container + for index in 0..<40 { + let name = "a\(level)_\(index)" + aliases += "let \(name) = \(tail)\n" + tail = name + } + } + let aliasReport = try probe( + "aliases-across-container-depth", + Array((manifestHeader + aliases + "let agents = Agents()").utf8), + semantics: true, in: directory) + #expect(aliasReport.report.status == "manifest.limit") + var flatAliases = "" + for chain in 0..<100 { + var previous = "c\(chain)" + flatAliases += "let \(previous) = 0\n" + for index in 0..<60 { + let name = "a\(chain)_\(index)" + flatAliases += "let \(name) = \(previous)\n" + previous = name + } + } + let domainReport = try probe( + "domain-reference-work", + Array((manifestHeader + flatAliases + "let agents = Agents()").utf8), + semantics: true, in: directory) + #expect(domainReport.report.stage == "domain") + #expect(domainReport.report.status == "manifest.limit") + var deep = "let v0: ConfigurationValue = 0\n" + for index in 1...65 { deep += "let v\(index): ConfigurationValue = .array([v\(index - 1)])\n" } + #expect(throws: ManifestFailure.self) { try document(deep + "let agents = Agents()") } + #expect(throws: ManifestFailure.self) { + try document( + "let values: [Int] = [" + Array(repeating: "0", count: 10_001).joined(separator: ",") + + "]\nlet agents = Agents()") + } + } + + @Test func mapOriginsAndComparisonHaveIndependentBudgets() throws { + let base = + "let sections: [SectionReference] = [" + + Array(repeating: "\"guide\"", count: 100).joined(separator: ",") + "]\n" + let components = Array(repeating: ".instructions(sections: sections)", count: 40).joined( + separator: ",") + let doc = try document(base + "let agents = Agents(components: [" + components + "])") + #expect(doc.sourceMap.entries.count > 10_000) + #expect(doc.sourceMap.entries.count <= 100_000) + #expect(doc.sourceMap.entries.reduce(0) { $0 + $1.origins.count } <= 1_000_000) + let unchanged = try doc.preparing([.setWatch([])]) + #expect(unchanged.patches.isEmpty) + #expect(throws: ManifestFailure.self) { + try doc.preparing(Array(repeating: .setWatch([]), count: 101)) + } + let tiny = try document("let agents = Agents()") + #expect(throws: ManifestFailure.self) { + try tiny.preparing([.setWatch(Array(repeating: "x", count: 10_001))]) + } + } + + @Test func checkedSuccessorsCanonicalizeRangesAndKeepExactMetadata() throws { + let doc = try document( + """ + let agents = Agents(sources: [ + .source(name: "major", path: "major", " v1.2.0+lower "..<"2.0.0+upper"), + .source(name: "minor", path: "minor", "1.2.0"..<"1.3.0+meta"), + .source(name: "exact", path: "exact", exact: "V1.2.0+meta") + ]) + """) + #expect( + doc.declaration.sources[0]["requirement"] == .requirement(.upToNextMajor(from: "1.2.0+lower")) + ) + #expect( + doc.declaration.sources[1]["requirement"] == .requirement(.upToNextMinor(from: "1.2.0"))) + #expect(doc.declaration.sources[2]["requirement"] == .requirement(.exact("1.2.0+meta"))) + _ = try document( + "let agents = Agents(sources: [.source(name: \"s\", path: \"s\", \"\(Int.max).0.0\"..<\"\(Int.max).1.0\")])" + ) + for requirement in [ + "from: \"\(Int.max).0.0\"", ".upToNextMinor(from: \"1.\(Int.max).0\")", + "\"2.0.0\"..<\"1.0.0\"", "exact: \"1.0\"", + ] { + #expect(throws: ManifestFailure.self) { + try document( + "let agents = Agents(sources: [.source(name: \"s\", path: \"s\", \(requirement))])") + } + } + } + + @Test func valueLiteralExamplesMatchTheRealCompiler() throws { + let values: [(String, ConfigurationValue)] = [ + ("nil", nil), ("true", true), ("-9_223_372_036_854_775_808", .integer(Int.min)), + ("[1, true, nil, \"x\"]", [1, true, nil, "x"]), + ("[\"x\": [\"y\": .decimal(\"1.25\")]]", ["x": ["y": .decimal("1.25")]]), + ("\"\\0\\t\\n\\r\\\"\\'\\\\\\u{1F600}\"", "\0\t\n\r\"'\\😀"), + ("\"\"\"\n first\n\n last\n \"\"\"", "first\n\nlast"), + ] + for (expression, compiled) in values { + let doc = try document( + "let value: ConfigurationValue = " + expression + "\nlet agents = Agents()") + #expect(doc.evaluation.constants["value"]!.value == compiled.constructionValue) + } + } +} diff --git a/Tests/AgentsManifestTests/ReviewRegressionTests.swift b/Tests/AgentsManifestTests/ReviewRegressionTests.swift new file mode 100644 index 0000000..00f1940 --- /dev/null +++ b/Tests/AgentsManifestTests/ReviewRegressionTests.swift @@ -0,0 +1,144 @@ +import AgentsCore +import AgentsDescription +import Foundation +import Testing + +@testable import AgentsManifest + +@Suite("Manifest review regressions") +struct ReviewRegressionTests { + @Test func oversizedExplicitInsertionIsRejectedBeforeRendering() throws { + let directory = try temporaryManifestDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let result = try probe( + "oversized-direct-insert", + Array((manifestHeader + "let agents = Agents(components: [])").utf8), + extraArguments: ["--edit-oversized"], in: directory) + #expect(result.report.status == "manifest.limit") + #expect(result.report.stage == "editing") + #expect(result.report.peakMemoryBytes < 67_108_864) + } + + @Test func inferredConstantsRetainContextDuringReplacement() throws { + let doc = try document( + "let recipient = Agent.codex\nlet agents = Agents(defaultAgents: [recipient])") + let change = try edited( + doc, + [ + .replaceConstant( + doc.constant(named: "recipient")!, with: .agent(.cursor), + acceptingUses: doc.uses(ofConstant: "recipient")) + ]) + #expect(change.declaration.defaultAgents == ["cursor"]) + let array = try document( + "let recipients = [Agent.codex]\nlet agents = Agents(defaultAgents: recipients)") + let changed = try edited( + array, + [ + .replaceConstant( + array.constant(named: "recipients")!, with: .array([.agent(.cursor)]), + acceptingUses: array.uses(ofConstant: "recipients")) + ]) + #expect(changed.declaration.defaultAgents == ["cursor"]) + let unused = try document("let recipient = Agent.codex\nlet agents = Agents()") + let unusedChange = try unused.preparing([ + .replaceConstant( + unused.constant(named: "recipient")!, with: .agent(.cursor), acceptingUses: []) + ]) + #expect(unusedChange.delta.changedPointers.isEmpty) + #expect(!unusedChange.patches.isEmpty) + let changedDefault = try doc.preparing([ + .replaceConstant( + doc.constant(named: "recipient")!, with: .agent(.cursor), + acceptingUses: doc.uses(ofConstant: "recipient")) + ]) + #expect(changedDefault.delta.changedPointers == ["/defaultAgents/0"]) + } + + @Test func consistentFourSpaceIndentationIsInheritedAndConflictsAreRejected() throws { + let doc = try document( + """ + let agents = Agents( + components: [ + .ignore(name: "first", patterns: []), + ] + ) + """) + let change = try edited(doc, [.insertComponent(.instructions(), into: .root, at: .last)]) + #expect(String(decoding: change.bytes, as: UTF8.self).contains("\n .instructions(),")) + let replacement = try edited( + doc, + [.replaceComponent(doc.node(at: "/components/0")!, with: .ignore(name: "new", patterns: []))]) + #expect( + String(decoding: replacement.bytes, as: UTF8.self).contains("\n name: \"new\",")) + let withoutComma = try document( + """ + let agents = Agents( + components: [ + .ignore(name: "first", patterns: []) + ] + ) + """) + let longPattern = String(repeating: "x", count: 80) + let replaced = try edited( + withoutComma, + [ + .replaceComponent( + withoutComma.node(at: "/components/0")!, + with: .ignore(name: "new", patterns: [longPattern])) + ]) + #expect(String(decoding: replaced.bytes, as: UTF8.self).contains("\"\(longPattern)\"\n")) + let multiline = try document( + """ + let agents = Agents( + components: [ + .ignore( + name: "first", + patterns: [ + "first", + ] + ), + ] + ) + """) + let withComma = try edited( + multiline, + [ + .replaceComponent( + multiline.node(at: "/components/0")!, + with: .ignore(name: "new", patterns: [longPattern])) + ]) + #expect(String(decoding: withComma.bytes, as: UTF8.self).contains("\"\(longPattern)\",\n")) + let mixed = try document( + """ + let agents = Agents( + components: [ + .ignore(name: "first", patterns: []), + .ignore(name: "second", patterns: []), + ] + ) + """) + #expect(throws: ManifestFailure.self) { + try mixed.preparing([.insertComponent(.instructions(), into: .root, at: .last)]) + } + } + + @Test func normalizedRequirementParentsKeepTheCompleteReferenceOriginChain() throws { + let doc = try document( + """ + let minimum: Version = "1.2.0" + let alias: Version = minimum + let agents = Agents(sources: [.source(name: "s", path: "s", from: alias)]) + """) + for pointer in ["/sources/0/requirement", "/sources/0/requirement/from"] { + let location = try #require(doc.sourceMap.locations(at: pointer).first) + #expect( + String(decoding: doc.bytes[location.span.start.. URL { + var directory = Bundle(for: ManifestTestBundle.self).bundleURL + for _ in 0..<6 { + let candidate = directory.appendingPathComponent("ManifestTestProcess") + if FileManager.default.isExecutableFile(atPath: candidate.path) { return candidate } + directory.deleteLastPathComponent() + } + throw CocoaError(.fileNoSuchFile) +} + +func probe( + _ name: String, _ bytes: [UInt8], semantics: Bool = false, extraArguments: [String] = [], + in directory: URL +) throws + -> ProbeResult +{ + let input = directory.appendingPathComponent("input.swift") + let output = directory.appendingPathComponent("output.json") + let errors = directory.appendingPathComponent("stderr.txt") + try Data(bytes).write(to: input) + FileManager.default.createFile(atPath: output.path, contents: nil) + FileManager.default.createFile(atPath: errors.path, contents: nil) + let stdout = try FileHandle(forWritingTo: output) + let stderr = try FileHandle(forWritingTo: errors) + defer { + try? stdout.close() + try? stderr.close() + } + let process = Process() + process.executableURL = try testProcessURL() + process.arguments = [input.path] + (semantics ? ["--semantics"] : []) + extraArguments + process.standardOutput = stdout + process.standardError = stderr + let clock = ContinuousClock() + let start = clock.now + try process.run() + // The timer starts before launch and remains active through child exit and teardown. + while process.isRunning && start.duration(to: clock.now) < .seconds(probeWatchdogSeconds) { + Thread.sleep(forTimeInterval: 0.002) + } + let timedOut = process.isRunning + if timedOut { + process.interrupt() + process.terminate() + } + if timedOut { + #if canImport(Darwin) + _ = Darwin.kill(process.processIdentifier, SIGKILL) + #else + _ = Glibc.kill(process.processIdentifier, SIGKILL) + #endif + } + process.waitUntilExit() + let elapsed = seconds(start.duration(to: clock.now)) + let errorText = (try? String(contentsOf: errors, encoding: .utf8)) ?? "" + try #require( + !timedOut, + "\(name) [\(probeConfiguration)] exceeded \(probeWatchdogSeconds) seconds: \(elapsed); \(errorText)" + ) + try #require( + process.terminationReason == .exit && process.terminationStatus == 0, + "\(name) crashed or signaled: \(process.terminationStatus); \(errorText)") + #expect(elapsed < probeWatchdogSeconds, "\(name): launch-to-exit deadline") + let report = try JSONDecoder().decode(ProbeReport.self, from: Data(contentsOf: output)) + #expect(report.configuration == probeConfiguration, "\(name): child build configuration") + #expect(report.peakMemoryBytes < 536_870_912, "\(name): peak memory \(report.peakMemoryBytes)") + #expect(report.status != "unexpected", "\(report.message)") + if report.stage == "admission" { #expect(report.metrics.parserCalls == 0) } + if report.status == "accepted" { + #expect(report.stage == "complete") + #expect(report.metrics.parserCalls == 1) + #expect(report.metrics.syntaxNodes <= report.metrics.syntaxReservation) + } + return ProbeResult( + name: name, configuration: probeConfiguration, watchdogSeconds: probeWatchdogSeconds, + wallSeconds: elapsed, report: report) +} + +func temporaryManifestDirectory() throws -> URL { + let url = FileManager.default.temporaryDirectory.appendingPathComponent( + "manifest-tests-" + UUID().uuidString) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return url +} + +func recordProbeResults(_ results: [ProbeResult], name: String) throws { + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent() + let evidenceRoot = + ProcessInfo.processInfo.environment["MANIFEST_TEST_EVIDENCE"].map { + URL(fileURLWithPath: $0) + } ?? root.appendingPathComponent(".build/manifest-test-evidence") + let directory = evidenceRoot.appendingPathComponent(probeConfiguration) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + let path = directory.appendingPathComponent(name + ".json") + try encoder.encode(results).write(to: path) + let compiler = try ProcessRunner.run("/usr/bin/env", arguments: ["swift", "--version"]) + struct Runner: Encodable { + let configuration: String + let watchdogSeconds: Double + let operatingSystem: String + let compiler: String + } + let runner = Runner( + configuration: probeConfiguration, watchdogSeconds: probeWatchdogSeconds, + operatingSystem: ProcessInfo.processInfo.operatingSystemVersionString, compiler: compiler.stdout + ) + try encoder.encode(runner).write( + to: directory.appendingPathComponent(name + "-runner.json")) + print("MANIFEST_EVIDENCE \(path.path)") +} + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif diff --git a/Tests/ManifestTestProcess/main.swift b/Tests/ManifestTestProcess/main.swift new file mode 100644 index 0000000..107d77e --- /dev/null +++ b/Tests/ManifestTestProcess/main.swift @@ -0,0 +1,165 @@ +import AgentsCore +import AgentsDescription +import AgentsManifest +import Foundation + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +#if DEBUG + let manifestTestConfiguration = "debug" +#else + let manifestTestConfiguration = "release" +#endif + +struct Report: Codable { + var configuration = manifestTestConfiguration + var status: String + var stage: String + var offset: Int + var line: Int + var column: Int + var message: String + var metrics: FrontEndMetrics + var peakMemoryBytes: UInt64 +} + +func progress(_ stage: String, _ metrics: FrontEndMetrics) { + struct Progress: Encodable { + let configuration: String + let stage: String + let metrics: FrontEndMetrics + } + if let data = try? JSONEncoder().encode( + Progress(configuration: manifestTestConfiguration, stage: stage, metrics: metrics)) + { + FileHandle.standardError.write(data + Data([10])) + } +} + +func peakMemory() -> UInt64 { + var usage = rusage() + #if canImport(Darwin) + _ = getrusage(RUSAGE_SELF, &usage) + return UInt64(max(0, usage.ru_maxrss)) + #else + _ = getrusage(Int32(RUSAGE_SELF.rawValue), &usage) + return UInt64(max(0, usage.ru_maxrss)) * 1024 + #endif +} + +func run(_ bytes: [UInt8], semantics: Bool) -> Report { + var metrics = FrontEndMetrics() + let clock = ContinuousClock() + let start = clock.now + let source = SourceText(Array(bytes.prefix(2_097_153)), identity: DocumentIdentity("manifest")) + var stage = "admission" + var stageStart = clock.now + progress(stage, metrics) + do { + let admission = try Recognizer(source: source).recognize() + metrics.admissionSeconds = seconds(start.duration(to: clock.now)) + metrics.tokens = admission.tokens.count + metrics.syntaxReservation = admission.reservation + stage = "parser" + var enteringParser = metrics + enteringParser.parserCalls = 1 + progress(stage, enteringParser) + var syntax: CheckedSyntax? = try SyntaxValidation.parse( + source, admission: admission, metrics: metrics) + metrics = syntax!.metrics + if semantics { + stage = "evaluation" + stageStart = clock.now + progress(stage, metrics) + let evaluation = try Evaluator(source: source, admission: admission).evaluate() + metrics.evaluationSeconds = seconds(stageStart.duration(to: clock.now)) + metrics.evaluationSteps = evaluation.steps + metrics.expandedNodes = evaluation.total.nodes + metrics.decodedBytes = evaluation.total.strings + stage = "domain" + stageStart = clock.now + progress(stage, metrics) + _ = try DomainValidator(source: source, admission: admission, evaluation: evaluation) + .validate() + metrics.domainSeconds = seconds(stageStart.duration(to: clock.now)) + stage = "lowering" + stageStart = clock.now + progress(stage, metrics) + _ = Lowering.declaration(evaluation.root.value) + metrics.loweringSeconds = seconds(stageStart.duration(to: clock.now)) + stage = "sourceMap" + stageStart = clock.now + progress(stage, metrics) + _ = try MapBuilder(source: source, admission: admission, digest: "probe").build(evaluation) + metrics.sourceMapSeconds = seconds(stageStart.duration(to: clock.now)) + } + stage = "teardown" + let teardown = clock.now + syntax = nil + metrics.teardownSeconds = seconds(teardown.duration(to: clock.now)) + return Report( + status: "accepted", stage: "complete", offset: 0, line: 1, column: 1, message: "", + metrics: metrics, peakMemoryBytes: peakMemory()) + } catch let error as ManifestFailure { + let diagnostic = error.diagnostics[0] + if stage == "admission" { + metrics = error.metrics + metrics.admissionSeconds = seconds(start.duration(to: clock.now)) + } else if stage == "parser" { + metrics = error.metrics + } else { + let elapsed = seconds(stageStart.duration(to: clock.now)) + switch stage { + case "evaluation": metrics.evaluationSeconds = elapsed + case "domain": metrics.domainSeconds = elapsed + case "sourceMap": metrics.sourceMapSeconds = elapsed + default: break + } + } + return Report( + status: diagnostic.code, stage: stage, offset: diagnostic.span.start, + line: diagnostic.span.line, column: diagnostic.span.column, message: diagnostic.message, + metrics: metrics, peakMemoryBytes: peakMemory()) + } catch { + return Report( + status: "unexpected", stage: stage, offset: 0, line: 0, column: 0, + message: String(describing: error), metrics: metrics, peakMemoryBytes: peakMemory()) + } +} + +let path = CommandLine.arguments[1] +let handle = try FileHandle(forReadingFrom: URL(fileURLWithPath: path)) +var bytes: [UInt8] = [] +while bytes.count < 2_097_153 { + let data = try handle.read(upToCount: 2_097_153 - bytes.count) ?? Data() + if data.isEmpty { break } + bytes.append(contentsOf: data) +} +try handle.close() +let report: Report +if CommandLine.arguments.contains("--edit-oversized") { + do { + let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) + let component = Component.ignore( + name: "large", patterns: [String(repeating: "x", count: 20_000_000)]) + _ = try document.preparing([.insertComponent(component, into: .root, at: .first)]) + report = Report( + status: "accepted", stage: "editing", offset: 0, line: 1, column: 1, message: "", + metrics: document.metrics, peakMemoryBytes: peakMemory()) + } catch let error as ManifestFailure { + let diagnostic = error.diagnostics[0] + report = Report( + status: diagnostic.code, stage: "editing", offset: diagnostic.span.start, + line: diagnostic.span.line, column: diagnostic.span.column, message: diagnostic.message, + metrics: error.metrics, peakMemoryBytes: peakMemory()) + } +} else { + report = run(bytes, semantics: CommandLine.arguments.contains("--semantics")) +} +let encoder = JSONEncoder() +encoder.outputFormatting = [.sortedKeys] +FileHandle.standardOutput.write(try encoder.encode(report)) From c2e81fa80c7cafefc382f15b1385fd4aa82a418f Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:22:26 +0800 Subject: [PATCH 009/171] fix: harden the manifest front end and share one pipeline Validate standalone skill values, reject bare CR in the version directive, keep line endings and indentation when moving annotated elements, and record expression representation instead of inferring it from dictionary keys. The production front end and the test process now share one pipeline with a stage observer. Contract limits live in one named table, literal conversion is shared by the evaluator and the editor, and generated vocabulary, fixtures and signatures are checked for drift. --- Documentation/Architecture/Package.md | 34 +- Documentation/Architecture/README.md | 2 +- Documentation/Architecture/State.md | 20 - Package.swift | 6 +- README.md | 9 + Scripts/ManifestVocabulary.json | 286 +++++- Scripts/generate-manifest-fixtures.py | 69 +- Scripts/generate-manifest-vocabulary.py | 274 ++++-- Sources/AgentsCore/DeclarationIR.swift | 4 +- .../AgentsDescription/ConstructionValue.swift | 15 + Sources/AgentsDescription/Vocabulary.swift | 11 +- .../VocabularyInventory.swift | 592 ++++++++---- Sources/AgentsManifest/Admission.swift | 367 +++++--- Sources/AgentsManifest/CanonicalPrinter.swift | 4 +- .../ConstructionValueAccessors.swift | 21 + .../AgentsManifest/DeclarationDocument.swift | 358 ++----- Sources/AgentsManifest/DocumentEditor.swift | 874 ++---------------- Sources/AgentsManifest/DocumentEdits.swift | 559 +++++++++++ Sources/AgentsManifest/DocumentModels.swift | 89 +- Sources/AgentsManifest/DocumentStyle.swift | 82 ++ Sources/AgentsManifest/DocumentTrivia.swift | 138 +++ Sources/AgentsManifest/DomainValidation.swift | 55 +- Sources/AgentsManifest/EvaluatedValue.swift | 44 + Sources/AgentsManifest/Evaluation.swift | 173 ++-- Sources/AgentsManifest/JSONPointer.swift | 17 + .../AgentsManifest/LiteralConversion.swift | 77 ++ Sources/AgentsManifest/Lowering.swift | 11 +- .../AgentsManifest/ManifestDiagnostic.swift | 94 +- Sources/AgentsManifest/ManifestFrontEnd.swift | 108 +++ Sources/AgentsManifest/ManifestLimits.swift | 54 ++ Sources/AgentsManifest/MapBuilder.swift | 213 +++++ Sources/AgentsManifest/SourceText.swift | 48 + .../StaticValueVocabulary.swift | 93 ++ Sources/AgentsManifest/SyntaxValidation.swift | 31 +- Sources/AgentsManifest/ValueBudget.swift | 63 +- .../AdversarialTests.swift | 12 +- .../CompiledFixtures.swift | 388 ++++---- .../DifferentialFuzzTests.swift | 5 +- Tests/AgentsManifestTests/EditingTests.swift | 271 +++++- ...ct06.swift.txt => ExportedGroup.swift.txt} | 0 ...ft.txt => InstructionRecipients.swift.txt} | 0 .../Fixtures/ParserBaseline.json | 134 +-- ...wift.txt => RecipientConditions.swift.txt} | 0 ...ift.txt => SectionConcatenation.swift.txt} | 0 ...ract00.swift.txt => SharedRules.swift.txt} | 0 ....swift.txt => TeamConfiguration.swift.txt} | 0 Tests/AgentsManifestTests/FrontEndTests.swift | 54 +- .../AgentsManifestTests/InventoryTests.swift | 153 ++- .../ManifestExpectations.swift | 17 + ...VersionTests.swift => ResourceTests.swift} | 102 +- .../ReviewRegressionTests.swift | 144 --- .../SemanticVersionTests.swift | 94 ++ .../AgentsManifestTests/SourceMapTests.swift | 45 + .../VersionCompatibilityTests.swift | 46 - Tests/AgentsManifestTests/Watchdog.swift | 28 +- Tests/ManifestTestProcess/main.swift | 130 +-- Tests/ManifestTestSupport/ProbeReport.swift | 37 + 57 files changed, 3875 insertions(+), 2680 deletions(-) create mode 100644 Sources/AgentsManifest/ConstructionValueAccessors.swift create mode 100644 Sources/AgentsManifest/DocumentEdits.swift create mode 100644 Sources/AgentsManifest/DocumentStyle.swift create mode 100644 Sources/AgentsManifest/DocumentTrivia.swift create mode 100644 Sources/AgentsManifest/EvaluatedValue.swift create mode 100644 Sources/AgentsManifest/JSONPointer.swift create mode 100644 Sources/AgentsManifest/LiteralConversion.swift create mode 100644 Sources/AgentsManifest/ManifestFrontEnd.swift create mode 100644 Sources/AgentsManifest/ManifestLimits.swift create mode 100644 Sources/AgentsManifest/MapBuilder.swift create mode 100644 Sources/AgentsManifest/SourceText.swift create mode 100644 Sources/AgentsManifest/StaticValueVocabulary.swift rename Tests/AgentsManifestTests/Fixtures/{Contract06.swift.txt => ExportedGroup.swift.txt} (100%) rename Tests/AgentsManifestTests/Fixtures/{Contract05.swift.txt => InstructionRecipients.swift.txt} (100%) rename Tests/AgentsManifestTests/Fixtures/{Contract01.swift.txt => RecipientConditions.swift.txt} (100%) rename Tests/AgentsManifestTests/Fixtures/{Contract07.swift.txt => SectionConcatenation.swift.txt} (100%) rename Tests/AgentsManifestTests/Fixtures/{Contract00.swift.txt => SharedRules.swift.txt} (100%) rename Tests/AgentsManifestTests/Fixtures/{TasteSample.swift.txt => TeamConfiguration.swift.txt} (100%) create mode 100644 Tests/AgentsManifestTests/ManifestExpectations.swift rename Tests/AgentsManifestTests/{ResourceAndVersionTests.swift => ResourceTests.swift} (62%) delete mode 100644 Tests/AgentsManifestTests/ReviewRegressionTests.swift create mode 100644 Tests/AgentsManifestTests/SemanticVersionTests.swift create mode 100644 Tests/AgentsManifestTests/SourceMapTests.swift delete mode 100644 Tests/AgentsManifestTests/VersionCompatibilityTests.swift create mode 100644 Tests/ManifestTestSupport/ProbeReport.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 62a1dcb..1c4be86 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -27,8 +27,9 @@ AgentsInstructions ──> AgentsCore │ └───────> Markdown (swift-markdown) ──> cmark-gfm -ManifestTestProcess ──> AgentsManifest, AgentsCore, AgentsDescription -AgentsManifestTests ──> AgentsManifest, AgentsDescription, AgentsCore, ManifestTestProcess, SwiftParser, SwiftSyntax +ManifestTestSupport ──> AgentsManifest +ManifestTestProcess ──> AgentsManifest, AgentsCore, AgentsDescription, ManifestTestSupport +AgentsManifestTests ──> AgentsManifest, AgentsDescription, AgentsCore, ManifestTestProcess, ManifestTestSupport, SwiftParser, SwiftSyntax StateTestProcess ──> AgentsCore, AgentsSkills, AgentsInstructions, AgentsUpdates, CPlatform AgentsCoreTests ──> AgentsCore, StateTestProcess, CPlatform @@ -66,10 +67,11 @@ CryptoKit on Apple platforms and supplies its own implementation on Linux. only the standard library, with private payload storage and closed literal conformances. `Scripts/ManifestVocabulary.json` is the construction signature and literal inventory; `Scripts/generate-manifest-vocabulary.py` generates the public -factories and package-only static registrations together. Contract signature and -compiler-backed fixture tests check that inventory. +factories, literal conversions, package-only registrations and `StaticValue` factories +together. Byte-for-byte generation checks and exact contract signature comparisons +cover factories and enum cases; compiler-backed fixture tests check ordinary values. -`AgentsManifest.DeclarationDocument` compiles supplied UTF-8 bytes without +`AgentsManifest.DeclarationDocument` parses and statically evaluates supplied UTF-8 bytes without executing code or reading sources. Version selection, strict lexing and bounded grammar recognition complete before SwiftParser sees the exact snapshot. An iterative all-nodes guard precedes syntax inspection and independent projection @@ -78,6 +80,24 @@ domain validation produce `AgentsCore.DeclarationIR` and `DeclarationSourceMap`. Constants, inactive values and unused groups receive the same checks. Group references and conditions remain symbolic. +`DeclarationDocument` is the public consumer surface: + +| Operation | Consumer API | +| --- | --- | +| Parse and statically evaluate supplied bytes | `init(bytes:identity:)` | +| Read declaration and provenance | `declaration`, `sourceMap`, `diagnostics` | +| Read the immutable snapshot | `bytes`, `digest` | +| Address an occurrence | `node(at:)`, `constant(named:)`, `uses(ofConstant:)`, `NodeID` | +| Check an editing boundary | `editability(of:)`, `Editability` | +| Prepare checked source changes | `preparing(_:)`, `ManifestEdit`, `StaticValue`, `DocumentChange` | + +`node(at:)` accepts a JSON Pointer into lowered declaration fields. The empty +pointer addresses the root, decimal segments index arrays, and dictionary keys +escape `~` as `~0` and `/` as `~1`. Literal configuration payloads appear under +`value`; source requirements use normalized requirement fields. `constant(named:)` +and `uses(ofConstant:)` accept Swift identifiers directly. Handles belong to one +snapshot digest and cannot be reused after preparing a new document. + The document retains original bytes, a lossless syntax tree, a byte digest and snapshot-bound `NodeID` handles. `preparing(_:)` accepts `ManifestEdit` batches, constructs expected intent, produces disjoint byte patches, reruns the complete @@ -86,7 +106,9 @@ byte digests, resulting bytes, diagnostics, impacted references and semantic del for later orchestration. Source edits do not publish files. Shared constants require explicit impact acceptance; ambiguous comments or separators are refused. -`ManifestTestProcess` is a test-only executable. Parent watchdogs exercise +`ManifestTestProcess` is a test-only executable and calls the same instrumented +front-end pipeline as document construction. `ManifestTestSupport` owns the +shared process report and build-configuration watchdog limits. Parent watchdogs exercise admission, parsing, checking and tree teardown, including fixed adversarial forms and deterministic differential fuzzing. Positive corpus sources are also compiled as ordinary Swift in the test target and compared using value equality. Parser diff --git a/Documentation/Architecture/README.md b/Documentation/Architecture/README.md index 8405abb..90f30ec 100644 --- a/Documentation/Architecture/README.md +++ b/Documentation/Architecture/README.md @@ -2,7 +2,7 @@ This directory holds the current truth for `core`, a SwiftPM library package. `AgentsDescription` supplies the types-only construction vocabulary, and -`AgentsManifest` compiles and edits supplied manifest snapshots without I/O. +`AgentsManifest` statically evaluates and edits supplied manifest snapshots without I/O. `AgentsCore` owns syntax-independent declaration IR, spans, provenance, shared sources, declaration and lock storage, cache, watch subscriptions, and agent locations; `AgentsSkills` owns skill discovery and lifecycle operations and depends on `AgentsCore` and Yams. `AgentsInstructions` owns instruction lifecycle and text diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index bfb76af..c8ed937 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -1,25 +1,5 @@ # State and Source Cache -## Manifest Front End - -`AgentsManifest.DeclarationDocument` accepts a supplied `Agents.swift` snapshot -and produces `AgentsCore.DeclarationIR`, diagnostics and `DeclarationSourceMap`. -The IR distinguishes inherited Optional values from explicit empty recipients, -retains ordered section streams, and keeps conditions and group references -symbolic. Span and provenance values contain stable document/source coordinates; -cache paths and deployment targets are not declaration identity. - -A prepared `DocumentChange` contains its original byte digest, disjoint source -patches, candidate bytes/digest, expected complete declaration, impacted references -and semantic delta. It is an input to state orchestration, not a second state -store or a file-saving API. Parsing and edit preparation perform no deployment, -source discovery, secret lookup or filesystem validation. - -The storage and lifecycle APIs below continue to own `agents.json` and the current -lock format. They do not yet load or publish `DocumentChange`. Manifest selection, -migration detection, transactional source publication and recovery belong to the -state integration; an accepted document alone does not authorize publication. - ## Scope Locations | Scope | Declaration | Lock | Watch state | Cache | diff --git a/Package.swift b/Package.swift index 10a99e3..e515d69 100644 --- a/Package.swift +++ b/Package.swift @@ -53,14 +53,18 @@ let package = Package( .testTarget( name: "AgentsCoreTests", dependencies: ["AgentsCore", "StateTestProcess", "CPlatform"]), .testTarget(name: "AgentsInstructionsTests", dependencies: ["AgentsInstructions"]), + .target( + name: "ManifestTestSupport", dependencies: ["AgentsManifest"], + path: "Tests/ManifestTestSupport"), .executableTarget( name: "ManifestTestProcess", - dependencies: ["AgentsManifest", "AgentsCore", "AgentsDescription"], + dependencies: ["AgentsManifest", "AgentsCore", "AgentsDescription", "ManifestTestSupport"], path: "Tests/ManifestTestProcess"), .testTarget( name: "AgentsManifestTests", dependencies: [ "AgentsManifest", "AgentsDescription", "AgentsCore", "ManifestTestProcess", + "ManifestTestSupport", .product(name: "SwiftParser", package: "swift-syntax"), .product(name: "SwiftSyntax", package: "swift-syntax"), ], diff --git a/README.md b/README.md index d5d80bd..bff4087 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,10 @@ Both [agents](https://github.com/agents-tools/cli) and [skill](https://github.com/skill-cli/cli) consume this package. Consumers own command parsing, terminal output and executable distribution. +- **AgentsDescription**: standard-library-only types for authoring the Swift + manifest construction vocabulary. +- **AgentsManifest**: parses and statically evaluates manifest snapshots into + declaration IR and source maps, and prepares byte-preserving edits. - **AgentsCore**: source parsing and identity, Git requirements, declaration and resolved-state models, atomic state storage, bare mirrors and immutable source materializations, watch subscriptions, hashing, path safety, process execution @@ -97,6 +101,8 @@ targets: [ .executableTarget( name: "YourCLI", dependencies: [ + .product(name: "AgentsDescription", package: "core"), + .product(name: "AgentsManifest", package: "core"), .product(name: "AgentsCore", package: "core"), .product(name: "AgentsSkills", package: "core"), .product(name: "AgentsInstructions", package: "core"), @@ -281,6 +287,9 @@ Read the [organization contributing guide][contributing] and the ### Development +Manifest generation checks require `python3` and `swift format` from the toolchain. +They regenerate into a temporary directory and leave checked-in sources unchanged. + Run the package's build, test, release and formatting checks: ```bash diff --git a/Scripts/ManifestVocabulary.json b/Scripts/ManifestVocabulary.json index 280fd07..441d178 100644 --- a/Scripts/ManifestVocabulary.json +++ b/Scripts/ManifestVocabulary.json @@ -3,7 +3,8 @@ "Agent": [ { "name": "claudeCode", - "parameters": [] + "parameters": [], + "loweredValue": "claude-code" }, { "name": "codex", @@ -15,11 +16,13 @@ }, { "name": "geminiCLI", - "parameters": [] + "parameters": [], + "loweredValue": "gemini-cli" }, { "name": "openCode", - "parameters": [] + "parameters": [], + "loweredValue": "opencode" } ], "Scope": [ @@ -35,7 +38,8 @@ "Platform": [ { "name": "macOS", - "parameters": [] + "parameters": [], + "loweredValue": "macos" }, { "name": "linux", @@ -460,7 +464,8 @@ "default": "[]", "type": "[String]" } - ] + ], + "initializer": true }, { "type": "Source", @@ -1597,9 +1602,17 @@ "kinds": [ "string" ], - "initializers": [ - "public init(stringLiteral value: String) { self.init(value: .construct(type: \"SectionReference\", member: \"section\", fields: [\"name\": .text(value), \"source\": .none, \"condition\": .none])) }" - ] + "conversions": { + "string": { + "member": "section", + "payload": "name", + "payloadType": "String", + "defaults": { + "source": "nil", + "condition": "nil" + } + } + } }, "GroupReference": { "protocols": [ @@ -1608,9 +1621,17 @@ "kinds": [ "string" ], - "initializers": [ - "public init(stringLiteral value: String) { self.init(value: .construct(type: \"GroupReference\", member: \"group\", fields: [\"name\": .text(value), \"source\": .none, \"condition\": .none])) }" - ] + "conversions": { + "string": { + "member": "group", + "payload": "name", + "payloadType": "String", + "defaults": { + "source": "nil", + "condition": "nil" + } + } + } }, "PromptContent": { "protocols": [ @@ -1619,9 +1640,13 @@ "kinds": [ "string" ], - "initializers": [ - "public init(stringLiteral value: String) { self.init(value: .node(type: \"PromptContent\", member: \"literal\", fields: [\"value\": .text(value)])) }" - ] + "conversions": { + "string": { + "member": "literal", + "payload": "value", + "payloadType": "String" + } + } }, "RuntimeValue": { "protocols": [ @@ -1630,9 +1655,13 @@ "kinds": [ "string" ], - "initializers": [ - "public init(stringLiteral value: String) { self = .literal(value) }" - ] + "conversions": { + "string": { + "member": "literal", + "payload": "value", + "payloadType": "String" + } + } }, "SkillSelection": { "protocols": [ @@ -1641,9 +1670,13 @@ "kinds": [ "array" ], - "initializers": [ - "public init(arrayLiteral elements: String...) { self.init(value: .node(type: \"SkillSelection\", member: \"names\", fields: [\"names\": elements.constructionValue])) }" - ] + "conversions": { + "array": { + "member": "names", + "payload": "names", + "payloadType": "[String]" + } + } }, "ConfigurationValue": { "protocols": [ @@ -1662,14 +1695,36 @@ "array", "dictionary" ], - "initializers": [ - "public init(stringLiteral value: String) { self = .string(value) }", - "public init(integerLiteral value: Int) { self = .integer(value) }", - "public init(booleanLiteral value: Bool) { self = .boolean(value) }", - "public init(nilLiteral: ()) { self = .null }", - "public init(arrayLiteral elements: ConfigurationValue...) { self = .array(elements) }", - "public init(dictionaryLiteral elements: (String, ConfigurationValue)...) { self = .object(Dictionary(elements, uniquingKeysWith: { _, last in last })) }" - ] + "conversions": { + "string": { + "member": "string", + "payload": "value", + "payloadType": "String" + }, + "integer": { + "member": "integer", + "payload": "value", + "payloadType": "Int" + }, + "boolean": { + "member": "boolean", + "payload": "value", + "payloadType": "Bool" + }, + "nil": { + "member": "null" + }, + "array": { + "member": "array", + "payload": "value", + "payloadType": "[ConfigurationValue]" + }, + "dictionary": { + "member": "object", + "payload": "value", + "payloadType": "[String: ConfigurationValue]" + } + } }, "Version": { "protocols": [ @@ -1678,7 +1733,180 @@ "kinds": [ "string" ], - "initializers": [] + "conversions": {} + } + }, + "aliases": { + "NativeConfiguration": "[String: [String: ConfigurationValue]]" + }, + "recursiveEnums": [ + "ConfigurationValue" + ], + "taggedRecordTypes": [ + "Source", + "Component", + "MCPTransport", + "ExecutableInvocation", + "GroupReference", + "PromptContent", + "RuntimeValue", + "ConfigurationValue", + "HookEvent", + "PermissionOperation", + "ComponentReference", + "PermissionRule" + ], + "rangeFactories": [ + { + "type": "VersionRange", + "name": "upToNextMajor", + "parameters": [ + { + "label": "from", + "name": "from", + "type": "Version" + } + ] + }, + { + "type": "VersionRange", + "name": "upToNextMinor", + "parameters": [ + { + "label": "from", + "name": "from", + "type": "Version" + } + ] } + ], + "staticValueFactories": [ + { + "type": "ConfigurationValue", + "name": "configuration" + }, + { + "type": "Component", + "name": "component" + }, + { + "type": "Source", + "name": "source" + }, + { + "type": "SectionReference", + "name": "section" + }, + { + "type": "GroupReference", + "name": "groupReference" + }, + { + "type": "Version", + "name": "version" + }, + { + "type": "RuntimeValue", + "name": "runtime" + }, + { + "type": "Condition", + "name": "condition" + }, + { + "type": "SkillSelection", + "name": "selection" + }, + { + "type": "SkillOverride", + "name": "skillOverride" + }, + { + "type": "ChatGPTPrompt", + "name": "prompt" + }, + { + "type": "Resource", + "name": "resource" + }, + { + "type": "PromptContent", + "name": "promptContent" + }, + { + "type": "ExecutableInvocation", + "name": "executable" + }, + { + "type": "MCPTransport", + "name": "transport" + }, + { + "type": "PromptParameter", + "name": "parameter" + }, + { + "type": "PermissionRule", + "name": "permissionRule" + }, + { + "type": "Agent", + "name": "agent" + }, + { + "type": "Scope", + "name": "scope" + }, + { + "type": "Platform", + "name": "platform" + }, + { + "type": "InstallMode", + "name": "installMode" + }, + { + "type": "HookEvent", + "name": "hookEvent" + }, + { + "type": "PermissionOperation", + "name": "permissionOperation" + }, + { + "type": "IgnorePurpose", + "name": "ignorePurpose" + }, + { + "type": "PluginMode", + "name": "pluginMode" + }, + { + "type": "ComponentKind", + "name": "componentKind" + }, + { + "type": "ComponentReference", + "name": "componentReference" + }, + { + "type": "ComponentGroup", + "name": "group" + }, + { + "type": "Agents", + "name": "agents" + } + ], + "primitiveTypes": [ + "String", + "Int", + "Bool" + ], + "customTypes": [ + "Version" + ], + "contextualTypes": { + "Range": "VersionRange" } } diff --git a/Scripts/generate-manifest-fixtures.py b/Scripts/generate-manifest-fixtures.py index 3d3a396..dbe3b3c 100644 --- a/Scripts/generate-manifest-fixtures.py +++ b/Scripts/generate-manifest-fixtures.py @@ -1,20 +1,57 @@ #!/usr/bin/env python3 -"""Compile the reviewed positive corpus as ordinary Swift in the test target.""" -from pathlib import Path +"""Generate compiler-backed values for every complete positive manifest fixture.""" +import argparse +import json import re +import subprocess +from pathlib import Path + ROOT = Path(__file__).resolve().parent.parent -paths = sorted((ROOT / 'Tests/AgentsManifestTests/Fixtures').glob('*.swift.txt')) -lines = ['// Generated from Tests/AgentsManifestTests/Fixtures. Run Scripts/generate-manifest-fixtures.py.', '', 'import AgentsDescription', 'import Foundation', '', '#if canImport(SwiftUI)', ' import SwiftUI', '#endif', '', 'struct CompiledManifestFixture {', ' let name: String', ' let agents: Agents', ' let constants: [String: ConstructionValue]', '}', '', 'func compiledFixtures() -> [CompiledManifestFixture] {', ' ['] -for i,p in enumerate(paths):lines.append(f' fixture{i}(),') -lines+=[' ]','}',''] -for i,p in enumerate(paths): - body='\n'.join(l for l in p.read_text().splitlines() if l!='import AgentsDescription') - names = re.findall(r'^let ([A-Za-z_][A-Za-z_0-9]*)\b', body, re.MULTILINE) - lines += [f'private func fixture{i}() -> CompiledManifestFixture {{']+[' '+l if l else '' for l in body.splitlines()] - lines += [f' return CompiledManifestFixture(name: "{p.name}", agents: agents, constants: ['] - lines += [f' "{name}": {name}.constructionValue,' for name in names] - lines += [' ])','}',''] -(ROOT / 'Tests/AgentsManifestTests/CompiledFixtures.swift').write_text('\n'.join(lines)) +FIXTURES = ROOT / "Tests/AgentsManifestTests/Fixtures" +DESTINATION = Path("Tests/AgentsManifestTests/CompiledFixtures.swift") +HEADER = "// Generated from Tests/AgentsManifestTests/Fixtures. Run Scripts/generate-manifest-fixtures.py." +BINDING = re.compile(r"^let ([A-Za-z_][A-Za-z_0-9]*)\b", re.MULTILINE) -import subprocess -subprocess.run(["swift", "format", "format", "--in-place", "--configuration", str(ROOT / ".swift-format"), str(ROOT / 'Tests/AgentsManifestTests/CompiledFixtures.swift')], check=True) + +def function_name(path): + return "compiled" + path.name.removesuffix(".swift.txt") + + +def fixture_function(path): + # Imports stay at file scope; all bindings remain ordinary Swift inside the function. + lines = [line for line in path.read_text().splitlines() if line != "import AgentsDescription"] + names = BINDING.findall("\n".join(lines)) + result = ["private func " + function_name(path) + "() -> CompiledManifestFixture {"] + result += [" " + line if line else "" for line in lines] + result += [" return CompiledManifestFixture(", " name: " + json.dumps(path.name) + ", agents: agents, constants: ["] + result += [" " + json.dumps(name) + ": " + name + ".constructionValue," for name in names] + return result + [" ])", "}", ""] + + +def generated_source(paths): + lines = [HEADER, "", "import AgentsDescription", "import Foundation", "", + "#if canImport(SwiftUI)", " import SwiftUI", "#endif", "", + "struct CompiledManifestFixture {", " let name: String", " let agents: Agents", + " let constants: [String: ConstructionValue]", "}", "", + "func compiledFixtures() -> [CompiledManifestFixture] {", " ["] + lines += [" " + function_name(path) + "()," for path in paths] + lines += [" ]", "}", ""] + for path in paths: + lines += fixture_function(path) + return "\n".join(lines) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-root", type=Path, default=ROOT) + arguments = parser.parse_args() + paths = sorted(FIXTURES.glob("*.swift.txt")) + destination = arguments.output_root / DESTINATION + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(generated_source(paths)) + subprocess.run(["swift", "format", "format", "--in-place", "--configuration", + str(ROOT / ".swift-format"), str(destination)], check=True) + + +if __name__ == "__main__": + main() diff --git a/Scripts/generate-manifest-vocabulary.py b/Scripts/generate-manifest-vocabulary.py index e1180c8..a479b97 100644 --- a/Scripts/generate-manifest-vocabulary.py +++ b/Scripts/generate-manifest-vocabulary.py @@ -1,103 +1,185 @@ #!/usr/bin/env python3 -"""Generate authoring declarations and static registrations from the language inventory.""" +"""Generate authoring types, evaluation metadata and editor factories from one inventory.""" +import argparse import json +import subprocess from pathlib import Path ROOT = Path(__file__).resolve().parent.parent -SPEC = json.loads((ROOT / 'Scripts/ManifestVocabulary.json').read_text()) -DEST = ROOT / 'Sources/AgentsDescription' -HEADER = '// Generated from Scripts/ManifestVocabulary.json. Run Scripts/generate-manifest-vocabulary.py.\n\n' - - -def type_expr(t): - if t == 'NativeConfiguration': - return '.dictionary(.dictionary(.named("ConfigurationValue")))' - if t.endswith('?'): - return '.optional(' + type_expr(t[:-1]) + ')' - if t.startswith('['): - inner = t[1:-1] - if inner.startswith('String: '): - return '.dictionary(' + type_expr(inner[8:]) + ')' - return '.array(' + type_expr(inner) + ')' - if t == 'Range': - return '.named("VersionRange")' - return '.named(' + json.dumps(t) + ')' - - -def signature(p): - ext = p['label'] - name = p['name'] - s = (ext + ' ' if ext != name else '') + name + ': ' + p['type'] - if 'default' in p: - s += ' = ' + p['default'] - return s - - -def default_expr(p): - if 'default' not in p: - return 'nil' - return '(' + p['default'] + ' as ' + p['type'] + ').constructionValue' - - -lines = [HEADER] -for name, cases in SPEC['enums'].items(): - recursive = 'indirect ' if name == 'ConfigurationValue' else '' - protocols = ['Sendable', 'Equatable'] + SPEC['literals'].get(name, {}).get('protocols', []) - lines.append(f'public {recursive}enum {name}: ' + ', '.join(protocols) + ' {') - for c in cases: - ps = c.get('parameters', []) - decl = c['name'] - if ps: - decl += '(' + ', '.join((p['label'] + ': ' if p['label'] != '_' else '') + p['type'] for p in ps) + ')' - lines.append(' case ' + decl) - for init in SPEC['literals'].get(name, {}).get('initializers', []): - lines.append(' ' + init) - lines += ['}', '', f'extension {name}: ConstructionRepresentable {{', ' package var constructionValue: ConstructionValue {', ' switch self {'] - for c in cases: - ps = c.get('parameters', []) - pattern = '.' + c['name'] - if ps: - pattern += '(' + ', '.join('let ' + p['name'] for p in ps) + ')' - fields = ', '.join(json.dumps(p['name']) + ': ' + p['name'] + '.constructionValue' for p in ps) - lines.append(f' case {pattern}: .node(type: "{name}", member: "{c["name"]}", fields: [' + (fields or ':') + '])') - lines += [' }', ' }', '}', ''] - -for name in SPEC['structs']: - protocols = ['Sendable', 'Equatable'] + SPEC['literals'].get(name, {}).get('protocols', []) - lines += [f'public struct {name}: ' + ', '.join(protocols) + ' {', ' private let storage: ConstructionValue', ' package var constructionValue: ConstructionValue { storage }', ' package init(value: ConstructionValue) { storage = value }'] - for init in SPEC['literals'].get(name, {}).get('initializers', []): - lines.append(' ' + init) - for m in SPEC['factories']: - if m['type'] != name: - continue - if m.get('property'): - lines.append(f' public static var {m["name"]}: {name} {{ Self(value: .node(type: "{name}", member: "{m["name"]}", fields: [:])) }}') +SPEC = json.loads((ROOT / "Scripts/ManifestVocabulary.json").read_text()) +HEADER = "// Generated from Scripts/ManifestVocabulary.json. Run Scripts/generate-manifest-vocabulary.py.\n" + + +def quoted(value): + return json.dumps(value, ensure_ascii=False) + + +def type_expression(spelling): + if spelling in SPEC["aliases"]: + return type_expression(SPEC["aliases"][spelling]) + if spelling.endswith("?"): + return ".optional(" + type_expression(spelling[:-1]) + ")" + if spelling.startswith("["): + inner = spelling[1:-1] + if inner.startswith("String: "): + return ".dictionary(" + type_expression(inner[8:]) + ")" + return ".array(" + type_expression(inner) + ")" + if spelling in SPEC["contextualTypes"]: + return ".named(" + quoted(SPEC["contextualTypes"][spelling]) + ")" + return ".named(" + quoted(spelling) + ")" + + +def parameters_declaration(parameters): + result = [] + for parameter in parameters: + label, name = parameter["label"], parameter["name"] + spelling = (label + " " if label != name else "") + name + ": " + parameter["type"] + if "default" in parameter: + spelling += " = " + parameter["default"] + result.append(spelling) + return ", ".join(result) + + +def fields_expression(parameters): + return dictionary_expression({p["name"]: p["name"] + ".constructionValue" for p in parameters}) + + +def dictionary_expression(fields): + return "[" + (", ".join(quoted(k) + ": " + v for k, v in fields.items()) or ":") + "]" + + +def literal_initializers(name): + result = [] + for kind, conversion in SPEC["literals"].get(name, {}).get("conversions", {}).items(): + payload_type = conversion.get("payloadType") + if kind == "nil": + declaration, payload = "nilLiteral: ()", None + elif kind == "array": + declaration, payload = "arrayLiteral elements: " + payload_type[1:-1] + "...", "elements" + elif kind == "dictionary": + element_type = payload_type[len("[String: "):-1] + declaration = "dictionaryLiteral elements: (String, " + element_type + ")..." + payload = "Dictionary(elements, uniquingKeysWith: { _, last in last })" + else: + declaration, payload = kind + "Literal value: " + payload_type, "value" + member = conversion["member"] + if name in SPEC["enums"]: + body = "self = ." + member + ("(" + payload + ")" if payload else "") + else: + fields = {k: ".none" if v == "nil" else v for k, v in conversion.get("defaults", {}).items()} + if payload: + fields[conversion["payload"]] = payload + ".constructionValue" + body = "self.init(value: .construct(type: " + quoted(name) + ", member: " + quoted(member) + ", fields: " + dictionary_expression(fields) + "))" + result.append(" public init(" + declaration + ") { " + body + " }") + return result + + +def authoring_source(): + lines = [HEADER] + for name, cases in SPEC["enums"].items(): + recursive = "indirect " if name in SPEC["recursiveEnums"] else "" + protocols = ["Sendable", "Equatable"] + SPEC["literals"].get(name, {}).get("protocols", []) + lines.append("public " + recursive + "enum " + name + ": " + ", ".join(protocols) + " {") + for case in cases: + parameters = case.get("parameters", []) + declaration = case["name"] + if parameters: + declaration += "(" + ", ".join((p["label"] + ": " if p["label"] != "_" else "") + p["type"] for p in parameters) + ")" + lines.append(" case " + declaration) + lines += literal_initializers(name) + lines += ["}", "", "extension " + name + ": ConstructionRepresentable {", " package var constructionValue: ConstructionValue {", " switch self {"] + for case in cases: + parameters = case.get("parameters", []) + pattern = "." + case["name"] + if parameters: + pattern += "(" + ", ".join("let " + p["name"] for p in parameters) + ")" + lines.append(" case " + pattern + ": .node(type: " + quoted(name) + ", member: " + quoted(case["name"]) + ", fields: " + fields_expression(parameters) + ")") + lines += [" }", " }", "}", ""] + for name in SPEC["structs"]: + protocols = ["Sendable", "Equatable"] + SPEC["literals"].get(name, {}).get("protocols", []) + lines += ["public struct " + name + ": " + ", ".join(protocols) + " {", " private let storage: ConstructionValue", " package var constructionValue: ConstructionValue { storage }", " package init(value: ConstructionValue) { storage = value }"] + lines += literal_initializers(name) + for factory in SPEC["factories"]: + if factory["type"] != name: + continue + member = factory["name"] + parameters = factory.get("parameters", []) + construct = "ConstructionValue.construct(type: " + quoted(name) + ", member: " + quoted(member) + ", fields: " + fields_expression(parameters) + ")" + if factory.get("property"): + declaration = "public static var " + member + ": " + name + body = "Self(value: " + construct + ")" + elif factory.get("initializer"): + declaration = "public init(" + parameters_declaration(parameters) + ")" + body = "self.init(value: " + construct + ")" + else: + declaration = "public static func " + member + "(" + parameters_declaration(parameters) + ") -> " + name + body = "Self(value: " + construct + ")" + lines.append(" " + declaration + " { " + body + " }") + lines += ["}", "extension " + name + ": ConstructionRepresentable {}", ""] + for name, spelling in SPEC["aliases"].items(): + lines += ["public typealias " + name + " = " + spelling, ""] + return "\n".join(lines) + + +def registration_source(): + type_names = SPEC["primitiveTypes"] + SPEC["customTypes"] + list(SPEC["aliases"]) + list(SPEC["enums"]) + SPEC["structs"] + lines = [HEADER, "package enum Vocabulary {", " package static let typeNames: Set = [" + ", ".join(map(quoted, type_names)) + "]", " package static let signatures: [ConstructionSignature] = ["] + enum_cases = [dict(type=name, name=case["name"], parameters=case.get("parameters", []), enumCase=True) for name, cases in SPEC["enums"].items() for case in cases] + for factory in SPEC["factories"] + enum_cases + SPEC["rangeFactories"]: + parameters = [] + for parameter in factory.get("parameters", []): + default = parameter.get("default") + value = "nil" if default is None else "(" + default + " as " + parameter["type"] + ").constructionValue" + parameters.append("ConstructionParameter(label: " + quoted(parameter["label"]) + ", name: " + quoted(parameter["name"]) + ", type: " + type_expression(parameter["type"]) + ", defaultValue: " + value + ", defaultExpression: " + (quoted(default) if default is not None else "nil") + ")") + callable_member = not factory.get("property") and (not factory.get("enumCase") or bool(factory.get("parameters"))) + lines.append(" ConstructionSignature(type: " + quoted(factory["type"]) + ", member: " + quoted(factory["name"]) + ", parameters: [" + ", ".join(parameters) + "], callable: " + str(callable_member).lower() + "),") + lines += [" ]", " package static let literalTypes: [String: Set] = ["] + literal_case = lambda kind: ".nilLiteral" if kind == "nil" else "." + kind + for name, literal in SPEC["literals"].items(): + lines.append(" " + quoted(name) + ": [" + ", ".join(map(literal_case, literal["kinds"])) + "],") + lines += [" ]", " package static let literalConstructions: [String: [LiteralKind: LiteralConstruction]] = ["] + for name, literal in SPEC["literals"].items(): + if not literal["conversions"]: continue - ps = m['parameters'] - decl = 'public init' if name == 'Agents' else 'public static func ' + m['name'] - decl += '(' + ', '.join(signature(p) for p in ps) + ')' - if name != 'Agents': - decl += ' -> ' + name - fields = ', '.join(json.dumps(p['name']) + ': ' + p['name'] + '.constructionValue' for p in ps) - construct = f'ConstructionValue.construct(type: "{name}", member: "{m["name"]}", fields: [' + (fields or ':') + '])' - body = 'self.init(value: ' + construct + ')' if name == 'Agents' else 'Self(value: ' + construct + ')' - lines.append(' ' + decl + ' { ' + body + ' }') - lines += ['}', f'extension {name}: ConstructionRepresentable {{}}', ''] -lines += ['public typealias NativeConfiguration = [String: [String: ConfigurationValue]]', ''] -(DEST / 'Vocabulary.swift').write_text('\n'.join(lines)) - -reg = [HEADER, 'package enum Vocabulary {', ' package static let typeNames: Set = [' + ', '.join(json.dumps(n) for n in ['String', 'Int', 'Bool', 'Version', 'NativeConfiguration'] + list(SPEC['enums']) + SPEC['structs']) + ']', ' package static let signatures: [ConstructionSignature] = ['] -for m in SPEC['factories'] + [dict(type=n, name=c['name'], parameters=c.get('parameters', []), enumCase=True) for n, cases in SPEC['enums'].items() for c in cases]: - ps = ', '.join('ConstructionParameter(label: ' + json.dumps(p['label']) + ', name: ' + json.dumps(p['name']) + ', type: ' + type_expr(p['type']) + ', defaultValue: ' + default_expr(p) + ')' for p in m.get('parameters', [])) - reg.append(' ConstructionSignature(type: ' + json.dumps(m['type']) + ', member: ' + json.dumps(m['name']) + ', parameters: [' + ps + '], callable: ' + str(not m.get('property') and (not m.get('enumCase') or bool(m.get('parameters')))).lower() + '),') -# Range factories are only contextual at their grammar slot. -for name in ['upToNextMajor', 'upToNextMinor']: - reg.append(' ConstructionSignature(type: "VersionRange", member: "' + name + '", parameters: [ConstructionParameter(label: "from", name: "from", type: .named("Version"), defaultValue: nil)], callable: true),') -reg += [' ]', ' package static let literalTypes: [String: Set] = ['] -for n, lit in SPEC['literals'].items(): - reg.append(' ' + json.dumps(n) + ': [' + ', '.join(json.dumps(x) for x in lit['kinds']) + '],') -reg += [' ]', '}', ''] -(DEST / 'VocabularyInventory.swift').write_text('\n'.join(reg)) + lines.append(" " + quoted(name) + ": [") + for kind, conversion in literal["conversions"].items(): + defaults = {k: ".none" if v == "nil" else v for k, v in conversion.get("defaults", {}).items()} + lines.append(" " + literal_case(kind) + ": LiteralConstruction(member: " + quoted(conversion["member"]) + ", payload: " + (quoted(conversion["payload"]) if "payload" in conversion else "nil") + ", payloadType: " + (type_expression(conversion["payloadType"]) if "payloadType" in conversion else "nil") + ", defaults: " + dictionary_expression(defaults) + "),") + lines.append(" ],") + lines += [" ]", " package static let scalarValues: [String: [String: String]] = ["] + for name, cases in SPEC["enums"].items(): + if all(not case.get("parameters") for case in cases): + fields = {case["name"]: quoted(case.get("loweredValue", case["name"])) for case in cases} + lines.append(" " + quoted(name) + ": " + dictionary_expression(fields) + ",") + lines += [" ]", " package static let taggedRecordTypes: Set = [" + ", ".join(map(quoted, SPEC["taggedRecordTypes"])) + "]", " package static let aliasTypes: [String: ConstructionType] = " + dictionary_expression({k: type_expression(v) for k, v in SPEC["aliases"].items()}), " package static let typeAliases: [String: String] = " + dictionary_expression({k: quoted(v) for k, v in SPEC["aliases"].items()}), "}", ""] + return "\n".join(lines) -import subprocess -subprocess.run(["swift", "format", "format", "--in-place", "--configuration", str(ROOT / ".swift-format"), str(ROOT / 'Sources/AgentsDescription/Vocabulary.swift'), str(ROOT / 'Sources/AgentsDescription/VocabularyInventory.swift')], check=True) + +def editor_factories_source(): + lines = [HEADER, "import AgentsDescription", "", "extension StaticValue {"] + for factory in SPEC["staticValueFactories"]: + name, value_type = factory["name"], factory["type"] + lines += [" public static func " + name + "(_ value: AgentsDescription." + value_type + ") -> Self {", " Self.checked(value.constructionValue, type: .named(" + quoted(value_type) + "))", " }"] + return "\n".join(lines + ["}", ""]) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-root", type=Path, default=ROOT) + arguments = parser.parse_args() + outputs = { + "Sources/AgentsDescription/Vocabulary.swift": authoring_source(), + "Sources/AgentsDescription/VocabularyInventory.swift": registration_source(), + "Sources/AgentsManifest/StaticValueVocabulary.swift": editor_factories_source(), + } + paths = [] + for relative, source in outputs.items(): + path = arguments.output_root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(source) + paths.append(str(path)) + subprocess.run(["swift", "format", "format", "--in-place", "--configuration", str(ROOT / ".swift-format"), *paths], check=True) + + +if __name__ == "__main__": + main() diff --git a/Sources/AgentsCore/DeclarationIR.swift b/Sources/AgentsCore/DeclarationIR.swift index 054ccac..db9e314 100644 --- a/Sources/AgentsCore/DeclarationIR.swift +++ b/Sources/AgentsCore/DeclarationIR.swift @@ -1,5 +1,5 @@ -/// Syntax-independent declaration data. Collections retain authored order; recipients are IDs, -/// conditions remain data, and group references are symbolic until linking. +/// Syntax-independent declaration data. Arrays retain authored order; dictionaries are unordered. +/// Recipients use agent IDs, conditions remain data, and group references stay symbolic until linking. public indirect enum DeclarationValue: Sendable, Equatable { case string(String) case integer(Int) diff --git a/Sources/AgentsDescription/ConstructionValue.swift b/Sources/AgentsDescription/ConstructionValue.swift index ad4fe93..a6659ee 100644 --- a/Sources/AgentsDescription/ConstructionValue.swift +++ b/Sources/AgentsDescription/ConstructionValue.swift @@ -1,4 +1,6 @@ package indirect enum ConstructionType: Sendable, Hashable { + /// No contextual type: nil literals and synthesized provenance fields. + case untyped case named(String) case array(ConstructionType) case dictionary(ConstructionType) @@ -15,6 +17,7 @@ package struct ConstructionParameter: Sendable { package let name: String package let type: ConstructionType package let defaultValue: ConstructionValue? + package let defaultExpression: String? } package struct ConstructionSignature: Sendable { @@ -24,6 +27,18 @@ package struct ConstructionSignature: Sendable { package let callable: Bool } +package enum LiteralKind: String, Sendable, Hashable { + case string, integer, boolean, array, dictionary + case nilLiteral = "nil" +} + +package struct LiteralConstruction: Sendable { + package let member: String + package let payload: String? + package let payloadType: ConstructionType? + package let defaults: [String: ConstructionValue] +} + package indirect enum ConstructionValue: Sendable, Equatable { case text(String) case integer(Int) diff --git a/Sources/AgentsDescription/Vocabulary.swift b/Sources/AgentsDescription/Vocabulary.swift index ce537fa..c0f2c0b 100644 --- a/Sources/AgentsDescription/Vocabulary.swift +++ b/Sources/AgentsDescription/Vocabulary.swift @@ -484,7 +484,7 @@ public struct GroupReference: Sendable, Equatable, ExpressibleByStringLiteral { self.init( value: .construct( type: "GroupReference", member: "group", - fields: ["name": .text(value), "source": .none, "condition": .none])) + fields: ["source": .none, "condition": .none, "name": value.constructionValue])) } public static func group(name: String, condition: Condition? = nil) -> GroupReference { Self( @@ -512,11 +512,11 @@ public struct SkillSelection: Sendable, Equatable, ExpressibleByArrayLiteral { package init(value: ConstructionValue) { storage = value } public init(arrayLiteral elements: String...) { self.init( - value: .node( + value: .construct( type: "SkillSelection", member: "names", fields: ["names": elements.constructionValue])) } public static var all: SkillSelection { - Self(value: .node(type: "SkillSelection", member: "all", fields: [:])) + Self(value: ConstructionValue.construct(type: "SkillSelection", member: "all", fields: [:])) } } extension SkillSelection: ConstructionRepresentable {} @@ -547,7 +547,7 @@ public struct SectionReference: Sendable, Equatable, ExpressibleByStringLiteral self.init( value: .construct( type: "SectionReference", member: "section", - fields: ["name": .text(value), "source": .none, "condition": .none])) + fields: ["source": .none, "condition": .none, "name": value.constructionValue])) } public static func section(name: String, source: String? = nil, condition: Condition? = nil) -> SectionReference @@ -600,7 +600,8 @@ public struct PromptContent: Sendable, Equatable, ExpressibleByStringLiteral { package init(value: ConstructionValue) { storage = value } public init(stringLiteral value: String) { self.init( - value: .node(type: "PromptContent", member: "literal", fields: ["value": .text(value)])) + value: .construct( + type: "PromptContent", member: "literal", fields: ["value": value.constructionValue])) } public static func file(_ path: String, source: String? = nil) -> PromptContent { Self( diff --git a/Sources/AgentsDescription/VocabularyInventory.swift b/Sources/AgentsDescription/VocabularyInventory.swift index dbaa3ce..c40f99a 100644 --- a/Sources/AgentsDescription/VocabularyInventory.swift +++ b/Sources/AgentsDescription/VocabularyInventory.swift @@ -15,601 +15,692 @@ package enum Vocabulary { parameters: [ ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), + defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "scopes", name: "scopes", type: .optional(.array(.named("Scope"))), - defaultValue: (nil as [Scope]?).constructionValue), + defaultValue: (nil as [Scope]?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "platforms", name: "platforms", type: .optional(.array(.named("Platform"))), - defaultValue: (nil as [Platform]?).constructionValue), + defaultValue: (nil as [Platform]?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "Agents", member: "Agents", parameters: [ ConstructionParameter( label: "defaultAgents", name: "defaultAgents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), + defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "exports", name: "exports", type: .array(.named("String")), - defaultValue: ([] as [String]).constructionValue), + defaultValue: ([] as [String]).constructionValue, defaultExpression: "[]"), ConstructionParameter( label: "sources", name: "sources", type: .array(.named("Source")), - defaultValue: ([] as [Source]).constructionValue), + defaultValue: ([] as [Source]).constructionValue, defaultExpression: "[]"), ConstructionParameter( label: "components", name: "components", type: .array(.named("Component")), - defaultValue: ([] as [Component]).constructionValue), + defaultValue: ([] as [Component]).constructionValue, defaultExpression: "[]"), ConstructionParameter( label: "groups", name: "groups", type: .array(.named("ComponentGroup")), - defaultValue: ([] as [ComponentGroup]).constructionValue), + defaultValue: ([] as [ComponentGroup]).constructionValue, defaultExpression: "[]"), ConstructionParameter( label: "uses", name: "uses", type: .array(.named("GroupReference")), - defaultValue: ([] as [GroupReference]).constructionValue), + defaultValue: ([] as [GroupReference]).constructionValue, defaultExpression: "[]"), ConstructionParameter( label: "watch", name: "watch", type: .array(.named("String")), - defaultValue: ([] as [String]).constructionValue), + defaultValue: ([] as [String]).constructionValue, defaultExpression: "[]"), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), + ConstructionParameter( + label: "url", name: "url", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), + ConstructionParameter( + label: "url", name: "url", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "from", name: "from", type: .named("Version"), defaultValue: nil), + label: "from", name: "from", type: .named("Version"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), + ConstructionParameter( + label: "url", name: "url", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "exact", name: "exact", type: .named("Version"), defaultValue: nil), + label: "exact", name: "exact", type: .named("Version"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "branch", name: "branch", type: .named("String"), defaultValue: nil), + label: "url", name: "url", type: .named("String"), defaultValue: nil, + defaultExpression: nil), + ConstructionParameter( + label: "branch", name: "branch", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), + ConstructionParameter( + label: "url", name: "url", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "revision", name: "revision", type: .named("String"), defaultValue: nil), + label: "revision", name: "revision", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), + ConstructionParameter( + label: "url", name: "url", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "_", name: "range", type: .named("VersionRange"), defaultValue: nil), + label: "_", name: "range", type: .named("VersionRange"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil), + label: "path", name: "path", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil), + label: "path", name: "path", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "from", name: "from", type: .named("Version"), defaultValue: nil), + label: "from", name: "from", type: .named("Version"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil), + label: "path", name: "path", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "exact", name: "exact", type: .named("Version"), defaultValue: nil), + label: "exact", name: "exact", type: .named("Version"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil), + label: "path", name: "path", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "branch", name: "branch", type: .named("String"), defaultValue: nil), + label: "branch", name: "branch", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil), + label: "path", name: "path", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "revision", name: "revision", type: .named("String"), defaultValue: nil), + label: "revision", name: "revision", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil), + label: "path", name: "path", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "_", name: "range", type: .named("VersionRange"), defaultValue: nil), + label: "_", name: "range", type: .named("VersionRange"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "index", name: "index", type: .named("String"), defaultValue: nil), + label: "index", name: "index", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "ComponentGroup", member: "group", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "components", name: "components", type: .array(.named("Component")), - defaultValue: ([] as [Component]).constructionValue), + defaultValue: ([] as [Component]).constructionValue, defaultExpression: "[]"), ConstructionParameter( label: "uses", name: "uses", type: .array(.named("GroupReference")), - defaultValue: ([] as [GroupReference]).constructionValue), + defaultValue: ([] as [GroupReference]).constructionValue, defaultExpression: "[]"), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), + defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "GroupReference", member: "group", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), + defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "GroupReference", member: "group", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "source", name: "source", type: .named("String"), defaultValue: nil), + label: "source", name: "source", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), + defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature(type: "SkillSelection", member: "all", parameters: [], callable: false), ConstructionSignature( type: "SkillOverride", member: "skill", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "mode", name: "mode", type: .optional(.named("InstallMode")), - defaultValue: (nil as InstallMode?).constructionValue), + defaultValue: (nil as InstallMode?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), + defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "SectionReference", member: "section", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "source", name: "source", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), + defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "ChatGPTPrompt", member: "prompt", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "sections", name: "sections", type: .array(.named("SectionReference")), - defaultValue: nil), + defaultValue: nil, defaultExpression: nil), ConstructionParameter( label: "append", name: "append", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), + defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "Resource", member: "path", parameters: [ - ConstructionParameter(label: "_", name: "path", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "_", name: "path", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "source", name: "source", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "PromptContent", member: "file", parameters: [ - ConstructionParameter(label: "_", name: "path", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "_", name: "path", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "source", name: "source", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "ExecutableInvocation", member: "executable", parameters: [ ConstructionParameter( - label: "_", name: "executable", type: .named("String"), defaultValue: nil), + label: "_", name: "executable", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "arguments", name: "arguments", type: .array(.named("String")), - defaultValue: ([] as [String]).constructionValue), + defaultValue: ([] as [String]).constructionValue, defaultExpression: "[]"), ConstructionParameter( label: "environment", name: "environment", type: .dictionary(.named("RuntimeValue")), - defaultValue: ([:] as [String: RuntimeValue]).constructionValue), + defaultValue: ([:] as [String: RuntimeValue]).constructionValue, defaultExpression: "[:]"), ConstructionParameter( label: "workingDirectory", name: "workingDirectory", type: .optional(.named("Resource")), - defaultValue: (nil as Resource?).constructionValue), + defaultValue: (nil as Resource?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "MCPTransport", member: "stdio", parameters: [ ConstructionParameter( - label: "_", name: "executable", type: .named("String"), defaultValue: nil), + label: "_", name: "executable", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "arguments", name: "arguments", type: .array(.named("String")), - defaultValue: ([] as [String]).constructionValue), + defaultValue: ([] as [String]).constructionValue, defaultExpression: "[]"), ConstructionParameter( label: "environment", name: "environment", type: .dictionary(.named("RuntimeValue")), - defaultValue: ([:] as [String: RuntimeValue]).constructionValue), + defaultValue: ([:] as [String: RuntimeValue]).constructionValue, defaultExpression: "[:]"), ConstructionParameter( label: "workingDirectory", name: "workingDirectory", type: .optional(.named("Resource")), - defaultValue: (nil as Resource?).constructionValue), + defaultValue: (nil as Resource?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "MCPTransport", member: "streamableHTTP", parameters: [ - ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "url", name: "url", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "headers", name: "headers", type: .dictionary(.named("RuntimeValue")), - defaultValue: ([:] as [String: RuntimeValue]).constructionValue), + defaultValue: ([:] as [String: RuntimeValue]).constructionValue, defaultExpression: "[:]"), ], callable: true), ConstructionSignature( type: "MCPTransport", member: "sse", parameters: [ - ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), + ConstructionParameter( + label: "url", name: "url", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "headers", name: "headers", type: .dictionary(.named("RuntimeValue")), - defaultValue: ([:] as [String: RuntimeValue]).constructionValue), + defaultValue: ([:] as [String: RuntimeValue]).constructionValue, defaultExpression: "[:]"), ], callable: true), ConstructionSignature( type: "PromptParameter", member: "parameter", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "description", name: "description", type: .named("String"), defaultValue: nil), + label: "description", name: "description", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "defaultValue", name: "defaultValue", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ], callable: true), ConstructionSignature( type: "PermissionRule", member: "allow", parameters: [ ConstructionParameter( - label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil), + label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "_", name: "pattern", type: .named("String"), defaultValue: nil), + label: "_", name: "pattern", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ], callable: true), ConstructionSignature( type: "PermissionRule", member: "ask", parameters: [ ConstructionParameter( - label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil), + label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "_", name: "pattern", type: .named("String"), defaultValue: nil), + label: "_", name: "pattern", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ], callable: true), ConstructionSignature( type: "PermissionRule", member: "deny", parameters: [ ConstructionParameter( - label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil), + label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "_", name: "pattern", type: .named("String"), defaultValue: nil), + label: "_", name: "pattern", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ], callable: true), ConstructionSignature( type: "Component", member: "skills", parameters: [ ConstructionParameter( - label: "source", name: "source", type: .named("String"), defaultValue: nil), + label: "source", name: "source", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "select", name: "select", type: .named("SkillSelection"), - defaultValue: (.all as SkillSelection).constructionValue), + defaultValue: (.all as SkillSelection).constructionValue, defaultExpression: ".all"), ConstructionParameter( label: "exclude", name: "exclude", type: .array(.named("String")), - defaultValue: ([] as [String]).constructionValue), + defaultValue: ([] as [String]).constructionValue, defaultExpression: "[]"), ConstructionParameter( label: "mode", name: "mode", type: .optional(.named("InstallMode")), - defaultValue: (nil as InstallMode?).constructionValue), + defaultValue: (nil as InstallMode?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "overrides", name: "overrides", type: .array(.named("SkillOverride")), - defaultValue: ([] as [SkillOverride]).constructionValue), + defaultValue: ([] as [SkillOverride]).constructionValue, defaultExpression: "[]"), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), + defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), + defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), + defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), ], callable: true), ConstructionSignature( type: "Component", member: "instructions", parameters: [ ConstructionParameter( label: "sections", name: "sections", type: .array(.named("SectionReference")), - defaultValue: ([] as [SectionReference]).constructionValue), + defaultValue: ([] as [SectionReference]).constructionValue, defaultExpression: "[]"), ConstructionParameter( label: "chatGPT", name: "chatGPT", type: .array(.named("ChatGPTPrompt")), - defaultValue: ([] as [ChatGPTPrompt]).constructionValue), + defaultValue: ([] as [ChatGPTPrompt]).constructionValue, defaultExpression: "[]"), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), + defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), + defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), + defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), ], callable: true), ConstructionSignature( type: "Component", member: "mcpServer", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "transport", name: "transport", type: .named("MCPTransport"), defaultValue: nil), + label: "transport", name: "transport", type: .named("MCPTransport"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), + defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), + defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), + defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), ], callable: true), ConstructionSignature( type: "Component", member: "hook", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "event", name: "event", type: .named("HookEvent"), defaultValue: nil), + label: "event", name: "event", type: .named("HookEvent"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "run", name: "run", type: .named("ExecutableInvocation"), defaultValue: nil), + label: "run", name: "run", type: .named("ExecutableInvocation"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "matcher", name: "matcher", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "timeoutSeconds", name: "timeoutSeconds", type: .optional(.named("Int")), - defaultValue: (nil as Int?).constructionValue), + defaultValue: (nil as Int?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), + defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), + defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), + defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), ], callable: true), ConstructionSignature( type: "Component", member: "subagent", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "description", name: "description", type: .named("String"), defaultValue: nil), + label: "description", name: "description", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "prompt", name: "prompt", type: .named("PromptContent"), defaultValue: nil), + label: "prompt", name: "prompt", type: .named("PromptContent"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "model", name: "model", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), + defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "tools", name: "tools", type: .optional(.array(.named("String"))), - defaultValue: (nil as [String]?).constructionValue), + defaultValue: (nil as [String]?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), + defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), + defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), + defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), ], callable: true), ConstructionSignature( type: "Component", member: "command", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "description", name: "description", type: .named("String"), defaultValue: nil), + label: "description", name: "description", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "prompt", name: "prompt", type: .named("PromptContent"), defaultValue: nil), + label: "prompt", name: "prompt", type: .named("PromptContent"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "parameters", name: "parameters", type: .array(.named("PromptParameter")), - defaultValue: ([] as [PromptParameter]).constructionValue), + defaultValue: ([] as [PromptParameter]).constructionValue, defaultExpression: "[]"), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), + defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), + defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), + defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), ], callable: true), ConstructionSignature( type: "Component", member: "lspServer", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "run", name: "run", type: .named("ExecutableInvocation"), defaultValue: nil), + label: "run", name: "run", type: .named("ExecutableInvocation"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "languages", name: "languages", type: .dictionary(.named("String")), - defaultValue: nil), + defaultValue: nil, defaultExpression: nil), ConstructionParameter( label: "initializationOptions", name: "initializationOptions", type: .dictionary(.named("ConfigurationValue")), - defaultValue: ([:] as [String: ConfigurationValue]).constructionValue), + defaultValue: ([:] as [String: ConfigurationValue]).constructionValue, + defaultExpression: "[:]"), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), + defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), + defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), + defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), ], callable: true), ConstructionSignature( type: "Component", member: "permissions", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "rules", name: "rules", type: .array(.named("PermissionRule")), defaultValue: nil), + label: "rules", name: "rules", type: .array(.named("PermissionRule")), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), + defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), + defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), + defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), ], callable: true), ConstructionSignature( type: "Component", member: "ignore", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "patterns", name: "patterns", type: .array(.named("String")), defaultValue: nil), + label: "patterns", name: "patterns", type: .array(.named("String")), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "purpose", name: "purpose", type: .named("IgnorePurpose"), - defaultValue: (.context as IgnorePurpose).constructionValue), + defaultValue: (.context as IgnorePurpose).constructionValue, defaultExpression: ".context" + ), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), + defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), + defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), + defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), ], callable: true), ConstructionSignature( type: "Component", member: "plugin", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil), + label: "path", name: "path", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( - label: "source", name: "source", type: .named("String"), defaultValue: nil), + label: "source", name: "source", type: .named("String"), defaultValue: nil, + defaultExpression: nil), ConstructionParameter( label: "mode", name: "mode", type: .named("PluginMode"), - defaultValue: (.components as PluginMode).constructionValue), + defaultValue: (.components as PluginMode).constructionValue, + defaultExpression: ".components"), ConstructionParameter( label: "select", name: "select", type: .optional(.array(.named("ComponentKind"))), - defaultValue: (nil as [ComponentKind]?).constructionValue), + defaultValue: (nil as [ComponentKind]?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "exclude", name: "exclude", type: .array(.named("ComponentReference")), - defaultValue: ([] as [ComponentReference]).constructionValue), + defaultValue: ([] as [ComponentReference]).constructionValue, defaultExpression: "[]"), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), + defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), + defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), + defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), ], callable: true), ConstructionSignature(type: "Agent", member: "claudeCode", parameters: [], callable: false), ConstructionSignature(type: "Agent", member: "codex", parameters: [], callable: false), @@ -626,37 +717,50 @@ package enum Vocabulary { ConstructionSignature( type: "RuntimeValue", member: "literal", parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) + ConstructionParameter( + label: "_", name: "value", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "RuntimeValue", member: "environment", parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) + ConstructionParameter( + label: "_", name: "value", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "RuntimeValue", member: "secret", parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) + ConstructionParameter( + label: "_", name: "value", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "ConfigurationValue", member: "string", parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) + ConstructionParameter( + label: "_", name: "value", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "ConfigurationValue", member: "integer", parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("Int"), defaultValue: nil) + ConstructionParameter( + label: "_", name: "value", type: .named("Int"), defaultValue: nil, defaultExpression: nil) ], callable: true), ConstructionSignature( type: "ConfigurationValue", member: "decimal", parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) + ConstructionParameter( + label: "_", name: "value", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "ConfigurationValue", member: "boolean", parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("Bool"), defaultValue: nil) + ConstructionParameter( + label: "_", name: "value", type: .named("Bool"), defaultValue: nil, defaultExpression: nil + ) ], callable: true), ConstructionSignature( type: "ConfigurationValue", member: "null", parameters: [], callable: false), @@ -664,14 +768,15 @@ package enum Vocabulary { type: "ConfigurationValue", member: "array", parameters: [ ConstructionParameter( - label: "_", name: "value", type: .array(.named("ConfigurationValue")), defaultValue: nil) + label: "_", name: "value", type: .array(.named("ConfigurationValue")), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "ConfigurationValue", member: "object", parameters: [ ConstructionParameter( label: "_", name: "value", type: .dictionary(.named("ConfigurationValue")), - defaultValue: nil) + defaultValue: nil, defaultExpression: nil) ], callable: true), ConstructionSignature(type: "HookEvent", member: "beforeTool", parameters: [], callable: false), ConstructionSignature(type: "HookEvent", member: "afterTool", parameters: [], callable: false), @@ -681,7 +786,9 @@ package enum Vocabulary { ConstructionSignature( type: "HookEvent", member: "native", parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) + ConstructionParameter( + label: "_", name: "value", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "PermissionOperation", member: "read", parameters: [], callable: false), @@ -692,7 +799,9 @@ package enum Vocabulary { ConstructionSignature( type: "PermissionOperation", member: "tool", parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) + ConstructionParameter( + label: "_", name: "value", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "IgnorePurpose", member: "context", parameters: [], callable: false), @@ -721,82 +830,161 @@ package enum Vocabulary { type: "ComponentReference", member: "skill", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "instruction", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "mcpServer", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "hook", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "subagent", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "command", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "lspServer", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "permissions", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "ignore", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "plugin", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "VersionRange", member: "upToNextMajor", parameters: [ ConstructionParameter( - label: "from", name: "from", type: .named("Version"), defaultValue: nil) + label: "from", name: "from", type: .named("Version"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ConstructionSignature( type: "VersionRange", member: "upToNextMinor", parameters: [ ConstructionParameter( - label: "from", name: "from", type: .named("Version"), defaultValue: nil) + label: "from", name: "from", type: .named("Version"), defaultValue: nil, + defaultExpression: nil) ], callable: true), ] - package static let literalTypes: [String: Set] = [ - "SectionReference": ["string"], - "GroupReference": ["string"], - "PromptContent": ["string"], - "RuntimeValue": ["string"], - "SkillSelection": ["array"], - "ConfigurationValue": ["string", "integer", "boolean", "nil", "array", "dictionary"], - "Version": ["string"], + package static let literalTypes: [String: Set] = [ + "SectionReference": [.string], + "GroupReference": [.string], + "PromptContent": [.string], + "RuntimeValue": [.string], + "SkillSelection": [.array], + "ConfigurationValue": [.string, .integer, .boolean, .nilLiteral, .array, .dictionary], + "Version": [.string], + ] + package static let literalConstructions: [String: [LiteralKind: LiteralConstruction]] = [ + "SectionReference": [ + .string: LiteralConstruction( + member: "section", payload: "name", payloadType: .named("String"), + defaults: ["source": .none, "condition": .none]) + ], + "GroupReference": [ + .string: LiteralConstruction( + member: "group", payload: "name", payloadType: .named("String"), + defaults: ["source": .none, "condition": .none]) + ], + "PromptContent": [ + .string: LiteralConstruction( + member: "literal", payload: "value", payloadType: .named("String"), defaults: [:]) + ], + "RuntimeValue": [ + .string: LiteralConstruction( + member: "literal", payload: "value", payloadType: .named("String"), defaults: [:]) + ], + "SkillSelection": [ + .array: LiteralConstruction( + member: "names", payload: "names", payloadType: .array(.named("String")), defaults: [:]) + ], + "ConfigurationValue": [ + .string: LiteralConstruction( + member: "string", payload: "value", payloadType: .named("String"), defaults: [:]), + .integer: LiteralConstruction( + member: "integer", payload: "value", payloadType: .named("Int"), defaults: [:]), + .boolean: LiteralConstruction( + member: "boolean", payload: "value", payloadType: .named("Bool"), defaults: [:]), + .nilLiteral: LiteralConstruction( + member: "null", payload: nil, payloadType: nil, defaults: [:]), + .array: LiteralConstruction( + member: "array", payload: "value", payloadType: .array(.named("ConfigurationValue")), + defaults: [:]), + .dictionary: LiteralConstruction( + member: "object", payload: "value", payloadType: .dictionary(.named("ConfigurationValue")), + defaults: [:]), + ], + ] + package static let scalarValues: [String: [String: String]] = [ + "Agent": [ + "claudeCode": "claude-code", "codex": "codex", "cursor": "cursor", "geminiCLI": "gemini-cli", + "openCode": "opencode", + ], + "Scope": ["project": "project", "user": "user"], + "Platform": ["macOS": "macos", "linux": "linux"], + "InstallMode": ["link": "link", "copy": "copy", "edit": "edit"], + "IgnorePurpose": ["context": "context", "indexing": "indexing"], + "PluginMode": ["native": "native", "components": "components"], + "ComponentKind": [ + "skills": "skills", "instructions": "instructions", "mcpServer": "mcpServer", "hook": "hook", + "subagent": "subagent", "command": "command", "lspServer": "lspServer", + "permissions": "permissions", "ignore": "ignore", "plugin": "plugin", + ], + ] + package static let taggedRecordTypes: Set = [ + "Source", "Component", "MCPTransport", "ExecutableInvocation", "GroupReference", + "PromptContent", "RuntimeValue", "ConfigurationValue", "HookEvent", "PermissionOperation", + "ComponentReference", "PermissionRule", + ] + package static let aliasTypes: [String: ConstructionType] = [ + "NativeConfiguration": .dictionary(.dictionary(.named("ConfigurationValue"))) + ] + package static let typeAliases: [String: String] = [ + "NativeConfiguration": "[String: [String: ConfigurationValue]]" ] } diff --git a/Sources/AgentsManifest/Admission.swift b/Sources/AgentsManifest/Admission.swift index 89fa81d..48822fa 100644 --- a/Sources/AgentsManifest/Admission.swift +++ b/Sources/AgentsManifest/Admission.swift @@ -1,12 +1,12 @@ import AgentsDescription import Foundation -package struct ProjectionEvent: Sendable, Equatable, Comparable, Codable { - package let start: Int - package let end: Int - package let kind: String - package let detail: String - package static func < (lhs: Self, rhs: Self) -> Bool { +struct ProjectionEvent: Sendable, Equatable, Comparable, Codable { + let start: Int + let end: Int + let kind: String + let detail: String + static func < (lhs: Self, rhs: Self) -> Bool { if lhs.start != rhs.start { return lhs.start < rhs.start } if lhs.end != rhs.end { return lhs.end < rhs.end } if lhs.kind != rhs.kind { return lhs.kind < rhs.kind } @@ -14,46 +14,67 @@ package struct ProjectionEvent: Sendable, Equatable, Comparable, Codable { } } -package struct Lexeme: Sendable { - package let text: String - package let range: Range - package let kind: String - package let decoded: String? +enum LexemeKind: String, Sendable { + case identifier, string, integer + case rangeOperator = "..<" + case leftParenthesis = "(" + case rightParenthesis = ")" + case leftSquare = "[" + case rightSquare = "]" + case comma = "," + case colon = ":" + case period = "." + case assignment = "=" + case plus = "+" + case minus = "-" + case endOfFile = "eof" } -package struct GrammarArgument: Sendable { - package let label: String - package let labelRange: Range? - package let value: Int +enum GrammarNodeKind: String, Sendable { + case string, integer, negative, boolean, array, dictionary, sequence, range, name, call, group + case nilLiteral = "nil" } -package struct GrammarNode: Sendable { - package let kind: String - package let range: Range - package var text: String = "" - package var children: [Int] = [] - package var arguments: [GrammarArgument] = [] - package var keys: [Lexeme] = [] +struct Lexeme: Sendable { + let text: String + let range: Range + let kind: LexemeKind + let decoded: String? } -package struct GrammarDeclaration: Sendable { - package let name: String - package let nameRange: Range - package let type: ConstructionType? - package let expression: Int - package let range: Range +struct GrammarArgument: Sendable { + let label: String + let labelRange: Range? + let value: Int } -package struct Admission: Sendable { - package let nodes: [GrammarNode] - package let declarations: [GrammarDeclaration] - package let tokens: [Lexeme] - package let comments: [Range] - package let projection: [ProjectionEvent] - package let reservation: Int +struct GrammarNode: Sendable { + let kind: GrammarNodeKind + let range: Range + var text: String = "" + var children: [Int] = [] + var arguments: [GrammarArgument] = [] + var keys: [Lexeme] = [] } -package final class Recognizer { +struct GrammarDeclaration: Sendable { + let name: String + let nameRange: Range + let type: ConstructionType? + let expression: Int + let range: Range +} + +struct Admission: Sendable { + let nodes: [GrammarNode] + let declarations: [GrammarDeclaration] + let tokens: [Lexeme] + let comments: [Range] + let projection: [ProjectionEvent] + let reservation: Int +} + +final class Recognizer { private let source: SourceText private let bytes: [UInt8] private var tokens: [Lexeme] = [] @@ -69,7 +90,7 @@ package final class Recognizer { .split(separator: " ").map(String.init)) private let prefixes: Set = ["await", "copy", "consume", "each", "unsafe"] - package init(source: SourceText) { + init(source: SourceText) { self.source = source bytes = source.bytes } @@ -79,15 +100,17 @@ package final class Recognizer { { var metrics = FrontEndMetrics() metrics.tokens = tokens.count - metrics.syntaxReservation = 16 + 4 * (tokens.count + literalUnits) + metrics.syntaxReservation = + ManifestLimits.Admission.reservationBase + ManifestLimits.Admission.reservationPerUnit + * (tokens.count + literalUnits) return ManifestFailure( ManifestDiagnostic(code: code, message: message, span: source.span(offset.. Admission { - if bytes.count > 2_097_152 { - throw fail("input byte limit", at: 2_097_152, code: "manifest.limit") + func recognize() throws -> Admission { + if bytes.count > ManifestLimits.Input.bytes { + throw fail("input byte limit", at: ManifestLimits.Input.bytes, code: "manifest.limit") } try validateUTF8() let header = bytes.starts(with: [239, 187, 191]) ? 3 : 0 @@ -98,9 +121,9 @@ package final class Recognizer { emit("import", start.. Bool { - byte == 32 || byte == 9 || byte == 10 || byte == 13 + byte == UInt8(ascii: " ") || byte == UInt8(ascii: "\t") || byte == UInt8(ascii: "\n") + || byte == UInt8(ascii: "\r") } private func isHead(_ byte: UInt8) -> Bool { - byte == 95 || (65...90).contains(byte) || (97...122).contains(byte) + byte == UInt8(ascii: "_") || (UInt8(ascii: "A")...UInt8(ascii: "Z")).contains(byte) + || (UInt8(ascii: "a")...UInt8(ascii: "z")).contains(byte) } private func starts(_ spelling: [UInt8], at offset: Int) -> Bool { offset + spelling.count <= bytes.count @@ -213,10 +248,12 @@ package final class Recognizer { i += 1 continue } - if starts([47, 47], at: i) { + if starts([UInt8(ascii: "/"), UInt8(ascii: "/")], at: i) { let first = i i += 2 - while i < bytes.count && bytes[i] != 10 && bytes[i] != 13 { i += 1 } + while i < bytes.count && bytes[i] != UInt8(ascii: "\n") && bytes[i] != UInt8(ascii: "\r") { + i += 1 + } let range = first.. 0 { - if starts([47, 42], at: i) { + if starts([UInt8(ascii: "/"), UInt8(ascii: "*")], at: i) { level += 1 - if level > 20 { throw fail("block comment depth", at: i, code: "manifest.limit") } + if level > ManifestLimits.Admission.commentDepth { + throw fail("block comment depth", at: i, code: "manifest.limit") + } i += 2 - } else if starts([42, 47], at: i) { + } else if starts([UInt8(ascii: "*"), UInt8(ascii: "/")], at: i) { level -= 1 i += 2 } else { @@ -246,40 +285,53 @@ package final class Recognizer { continue } let first = i - let kind: String + let kind: LexemeKind var decoded: String? - if bytes[i] == 34 { + if bytes[i] == UInt8(ascii: "\"") { (i, decoded) = try string(at: i) - kind = "string" + kind = .string } else if isHead(bytes[i]) { i += 1 - while i < bytes.count && (isHead(bytes[i]) || (48...57).contains(bytes[i])) { i += 1 } - kind = "identifier" - } else if (48...57).contains(bytes[i]) { + while i < bytes.count + && (isHead(bytes[i]) || (UInt8(ascii: "0")...UInt8(ascii: "9")).contains(bytes[i])) + { i += 1 } + kind = .identifier + } else if (UInt8(ascii: "0")...UInt8(ascii: "9")).contains(bytes[i]) { i += 1 - while i < bytes.count && ((48...57).contains(bytes[i]) || bytes[i] == 95) { i += 1 } - kind = "integer" - } else if starts([46, 46, 60], at: i) { + while i < bytes.count + && ((UInt8(ascii: "0")...UInt8(ascii: "9")).contains(bytes[i]) + || bytes[i] == UInt8(ascii: "_")) + { i += 1 } + kind = .integer + } else if starts([UInt8(ascii: "."), UInt8(ascii: "."), UInt8(ascii: "<")], at: i) { i += 3 - kind = "..<" + kind = .rangeOperator if (first > 0 && isSpace(bytes[first - 1])) != (i < bytes.count && isSpace(bytes[i])) { throw fail( - "range requires balanced whitespace; canonical spelling: \(canonical(kind))", at: first) + "range requires balanced whitespace; canonical spelling: \(canonical(kind.rawValue))", + at: first) } - } else if [40, 41, 91, 93, 44, 58, 46, 61, 43, 45].contains(bytes[i]) { + } else if [ + UInt8(ascii: "("), UInt8(ascii: ")"), UInt8(ascii: "["), UInt8(ascii: "]"), + UInt8(ascii: ","), UInt8(ascii: ":"), UInt8(ascii: "."), UInt8(ascii: "="), + UInt8(ascii: "+"), UInt8(ascii: "-"), + ].contains(bytes[i]) { let byte = bytes[i] i += 1 - kind = String(UnicodeScalar(byte)) - if byte == 61 || byte == 43 { + kind = LexemeKind(rawValue: String(UnicodeScalar(byte)))! + if byte == UInt8(ascii: "=") || byte == UInt8(ascii: "+") { if first == 0 || i == bytes.count || !isSpace(bytes[first - 1]) || !isSpace(bytes[i]) { throw fail( - "operator requires whitespace on both sides; canonical spelling: \(canonical(kind))", + "operator requires whitespace on both sides; canonical spelling: \(canonical(kind.rawValue))", at: first) } } - if byte == 45 { - if i == bytes.count || !(48...57).contains(bytes[i]) || first == 0 - || !(isSpace(bytes[first - 1]) || [40, 91, 44, 58].contains(bytes[first - 1])) + if byte == UInt8(ascii: "-") { + if i == bytes.count || !(UInt8(ascii: "0")...UInt8(ascii: "9")).contains(bytes[i]) + || first == 0 + || !(isSpace(bytes[first - 1]) + || [UInt8(ascii: "("), UInt8(ascii: "["), UInt8(ascii: ","), UInt8(ascii: ":")] + .contains(bytes[first - 1])) { throw fail( "negative integer requires an adjacent sign and separated boundary; canonical spelling: let value = -1", @@ -289,8 +341,15 @@ package final class Recognizer { } else { throw fail("token outside the lexical grammar", at: i) } - if tokens.count == 100_000 { throw fail("token count", at: first, code: "manifest.limit") } - if 16 + 4 * (tokens.count + 1 + literalUnits) > 100_000 { + if tokens.count == ManifestLimits.Admission.tokens { + throw fail("token count", at: first, code: "manifest.limit") + } + // Reserve container/wrapper storage before SwiftParser: the fixed base plus + // four nodes for every token, literal escape and physical literal line break. + // The independent all-node guard verifies this conservative reservation. + if ManifestLimits.Admission.reservationBase + ManifestLimits.Admission.reservationPerUnit + * (tokens.count + 1 + literalUnits) > ManifestLimits.Admission.syntaxReservation + { throw fail("syntax storage reservation", at: first, code: "manifest.limit") } tokens.append( @@ -317,37 +376,46 @@ package final class Recognizer { ci += 1 } } - tokens.append(Lexeme(text: "", range: bytes.count.. (Int, String?) { - let multiline = starts([34, 34, 34], at: start) + let multiline = starts([UInt8(ascii: "\""), UInt8(ascii: "\""), UInt8(ascii: "\"")], at: start) let width = multiline ? 3 : 1 var i = start + width var body = i if multiline { - guard i < bytes.count && (bytes[i] == 10 || bytes[i] == 13) else { + guard i < bytes.count && (bytes[i] == UInt8(ascii: "\n") || bytes[i] == UInt8(ascii: "\r")) + else { throw fail("multiline opener requires a newline", at: i) } - if starts([13, 10], at: i) { i += 2 } else { i += 1 } + if starts([UInt8(ascii: "\r"), UInt8(ascii: "\n")], at: i) { i += 2 } else { i += 1 } body = i } while i < bytes.count { let byte = bytes[i] - if byte < 32 && byte != 9 && byte != 10 && byte != 13 { + if byte < UInt8(ascii: " ") && byte != UInt8(ascii: "\t") && byte != UInt8(ascii: "\n") + && byte != UInt8(ascii: "\r") + { throw fail("control scalar in string", at: i) } - if !multiline && (byte == 10 || byte == 13) { + if !multiline && (byte == UInt8(ascii: "\n") || byte == UInt8(ascii: "\r")) { throw fail("newline in single-line string", at: i) } - if byte == 92 { + if byte == UInt8(ascii: "\\") { let escape = i i += 1 - if i < bytes.count && [48, 92, 116, 110, 114, 34, 39].contains(bytes[i]) { + if i < bytes.count + && [ + UInt8(ascii: "0"), UInt8(ascii: "\\"), UInt8(ascii: "t"), UInt8(ascii: "n"), + UInt8(ascii: "r"), UInt8(ascii: "\""), UInt8(ascii: "'"), + ].contains(bytes[i]) + { i += 1 continue } - guard starts([117, 123], at: i) else { + guard starts([UInt8(ascii: "u"), UInt8(ascii: "{")], at: i) else { throw fail("unsupported escape or interpolation", at: escape) } i += 2 @@ -357,54 +425,69 @@ package final class Recognizer { scalar = scalar &* 16 &+ hex i += 1 } - guard (1...8).contains(i - digits), i < bytes.count, bytes[i] == 125, + guard (1...8).contains(i - digits), i < bytes.count, bytes[i] == UInt8(ascii: "}"), scalar <= 0x10ffff, !(0xd800...0xdfff).contains(scalar) else { throw fail("invalid Unicode escape", at: escape) } i += 1 continue } - if byte == 34 && (!multiline || starts([34, 34, 34], at: i)) { + if byte == UInt8(ascii: "\"") + && (!multiline + || starts([UInt8(ascii: "\""), UInt8(ascii: "\""), UInt8(ascii: "\"")], at: i)) + { let closing = i let end = i + width let content: [UInt8] if multiline { var lineStart = i - while lineStart > body && bytes[lineStart - 1] != 10 && bytes[lineStart - 1] != 13 { + while lineStart > body && bytes[lineStart - 1] != UInt8(ascii: "\n") + && bytes[lineStart - 1] != UInt8(ascii: "\r") + { lineStart -= 1 } let indent = i - lineStart - guard bytes[lineStart.. first && (lineEnd - first < indent - || !bytes[first..<(first + indent)].allSatisfy({ $0 == 32 })) + || !bytes[first..<(first + indent)].allSatisfy({ $0 == UInt8(ascii: " ") })) { throw fail("nonempty multiline line requires full indentation", at: first) } let contentStart = lineEnd == first ? first : first + indent decodedBody.append(contentsOf: bytes[contentStart.. UInt32? { - if (48...57).contains(b) { return UInt32(b - 48) } - if (65...70).contains(b) { return UInt32(b - 55) } - if (97...102).contains(b) { return UInt32(b - 87) } + if (UInt8(ascii: "0")...UInt8(ascii: "9")).contains(b) { return UInt32(b - UInt8(ascii: "0")) } + if (UInt8(ascii: "A")...UInt8(ascii: "F")).contains(b) { + return UInt32(b - UInt8(ascii: "A")) + 10 + } + if (UInt8(ascii: "a")...UInt8(ascii: "f")).contains(b) { + return UInt32(b - UInt8(ascii: "a")) + 10 + } return nil } private func decode(_ raw: [UInt8]) -> String { - if !raw.contains(92) { return String(decoding: raw, as: UTF8.self) } + if !raw.contains(UInt8(ascii: "\\")) { return String(decoding: raw, as: UTF8.self) } var result: [UInt8] = [] var i = 0 while i < raw.count { - if raw[i] != 92 { + if raw[i] != UInt8(ascii: "\\") { result.append(raw[i]) i += 1 continue } i += 1 switch raw[i] { - case 48: result.append(0) - case 116: result.append(9) - case 110: result.append(10) - case 114: result.append(13) - case 117: + case UInt8(ascii: "0"): result.append(UInt8(ascii: "\0")) + case UInt8(ascii: "t"): result.append(UInt8(ascii: "\t")) + case UInt8(ascii: "n"): result.append(UInt8(ascii: "\n")) + case UInt8(ascii: "r"): result.append(UInt8(ascii: "\r")) + case UInt8(ascii: "u"): i += 2 var scalar: UInt32 = 0 - while raw[i] != 125 { + while raw[i] != UInt8(ascii: "}") { scalar = scalar * 16 + hex(raw[i])! i += 1 } @@ -457,12 +544,12 @@ package final class Recognizer { @discardableResult private func take(_ text: String? = nil) throws -> Lexeme { let token = peek() if let text, token.text != text { throw fail("expected \(text)", at: token.range.lowerBound) } - if token.kind != "eof" { index += 1 } + if token.kind != .endOfFile { index += 1 } return token } private func identifier(bare: Bool = false) throws -> Lexeme { let token = peek() - guard token.kind == "identifier", !reserved.contains(token.text), + guard token.kind == .identifier, !reserved.contains(token.text), !(bare && prefixes.contains(token.text)) else { throw fail("expected an identifier", at: token.range.lowerBound) } return try take() @@ -471,7 +558,9 @@ package final class Recognizer { let token = try take(text) depth += 1 if text == "[" { square += 1 } - if depth > 20 || square > 8 { + if depth > ManifestLimits.Admission.delimiterDepth + || square > ManifestLimits.Admission.squareDepth + { throw fail("grammar delimiter depth", at: token.range.lowerBound, code: "manifest.limit") } return token.range.lowerBound @@ -489,7 +578,7 @@ package final class Recognizer { private func node(_ value: GrammarNode, projection: Bool = true) -> Int { let id = nodes.count nodes.append(value) - if projection { emit(value.kind, value.range, value.text) } + if projection { emit(value.kind.rawValue, value.range, value.text) } return id } @@ -518,8 +607,7 @@ package final class Recognizer { throw fail("type outside construction vocabulary", at: token.range.lowerBound) } emit("type", token.range, token.text) - return token.text == "NativeConfiguration" - ? .dictionary(.dictionary(.named("ConfigurationValue"))) : .named(token.text) + return Vocabulary.aliasTypes[token.text] ?? .named(token.text) } private func expression() throws -> Int { @@ -527,7 +615,7 @@ package final class Recognizer { var terms = [first] while peek("+") { let op = try take("+") - if terms.count == 32 { + if terms.count == ManifestLimits.Admission.additiveTerms { throw fail( "additive chain exceeds 32 terms", at: op.range.lowerBound, code: "manifest.limit") } @@ -536,7 +624,7 @@ package final class Recognizer { if terms.count == 1 { return first } return node( GrammarNode( - kind: "sequence", + kind: .sequence, range: nodes[first].range.lowerBound.. Int { let token = peek() let start = token.range.lowerBound - if token.kind == "string" || token.kind == "integer" + if token.kind == .string || token.kind == .integer || ["true", "false", "nil"].contains(token.text) { _ = try take() - let kind = token.kind == "identifier" ? (token.text == "nil" ? "nil" : "boolean") : token.kind - emit(kind, token.range, token.text) + let kind: GrammarNodeKind = + token.kind == .identifier + ? (token.text == "nil" ? .nilLiteral : .boolean) + : (token.kind == .string ? .string : .integer) + emit(kind.rawValue, token.range, token.text) return node( GrammarNode(kind: kind, range: token.range, text: token.decoded ?? token.text), projection: false) @@ -557,33 +648,34 @@ package final class Recognizer { if peek("-") { _ = try take("-") let integer = try take() - guard integer.kind == "integer", integer.range.lowerBound == token.range.upperBound else { + guard integer.kind == .integer, integer.range.lowerBound == token.range.upperBound else { throw fail("minus requires adjacent decimal digits", at: integer.range.lowerBound) } emit("integer", integer.range, integer.text) + emit("negative", start..? - if peek().kind == "identifier" && tokens[index + 1].text == ":" { + if peek().kind == .identifier && tokens[index + 1].text == ":" { let name = try identifier() label = name.text labelRange = name.range @@ -664,15 +756,11 @@ package final class Recognizer { if peek(")") { throw fail("calls have no trailing comma", at: peek().range.lowerBound) } } } + let end = try close(")") + emit("call", start..) -> Bool { - emit(kind, range) - return false + GrammarNode(kind: .call, range: start.. GrammarArgument { @@ -701,18 +789,19 @@ package final class Recognizer { } if ["from", "exact", "branch", "revision"].contains(peek().text) { args.append(try argument(label: peek().text)) - } else if peek().kind == "string" { + } else if peek().kind == .string { let first = try primary() let op = try take("..<") emit("reference", op.range, "..<") - guard peek().kind == "string" else { + guard peek().kind == .string else { throw fail("range endpoint must be a string literal", at: peek().range.lowerBound) } let second = try primary() let range = nodes[first].range.lowerBound.. 2_097_152 { - let bounded = SourceText(Array(bytes.prefix(2_097_153)), identity: identity) - throw bounded.failure("manifest.limit", "input byte limit", 2_097_152) - } + init( + bytes: [UInt8], identity: DocumentIdentity, validateDomain: Bool, + observe: ((FrontEndStage, FrontEndMetrics) -> Void)? = nil + ) throws { + let result = try ManifestFrontEnd.run( + bytes: bytes, identity: identity, checking: .declaration, + validateDomain: validateDomain, observe: observe) + source = result.source + admission = result.admission + syntax = result.syntax + let values = result.declaration! + evaluation = values.evaluation + declaration = values.ir + diagnostics = values.diagnostics + digest = values.digest + sourceMap = DeclarationSourceMap(entries: values.map.entries) + locations = values.map.locations + self.values = values.map.values + metrics = result.metrics + } + + /// Exercises the production pipeline through the selected phase and releases its tree. + /// The syntax projection corpus intentionally stops before contextual type checking. + package static func inspect( + bytes: [UInt8], identity: DocumentIdentity, checking: FrontEndCheck, + observe: ((FrontEndStage, FrontEndMetrics) -> Void)? = nil + ) throws -> FrontEndMetrics { + var result: FrontEndResult? = try ManifestFrontEnd.run( + bytes: bytes, identity: identity, checking: checking, observe: observe) + var metrics = result!.metrics + observe?(.teardown, metrics) let clock = ContinuousClock() let start = clock.now - let source = SourceText(bytes, identity: identity) - let admission: Admission - var metrics = FrontEndMetrics() - do { - admission = try Recognizer(source: source).recognize() - } catch let failure as ManifestFailure { - metrics = failure.metrics - metrics.admissionSeconds = seconds(start.duration(to: clock.now)) - throw ManifestFailure(failure.diagnostics[0], metrics: metrics) - } - metrics.admissionSeconds = seconds(start.duration(to: clock.now)) - metrics.tokens = admission.tokens.count - metrics.syntaxReservation = admission.reservation - let checked = try SyntaxValidation.parse(source, admission: admission, metrics: metrics) - metrics = checked.metrics - let evaluation: Evaluation - let diagnostics: [ManifestDiagnostic] - let digest = "sha256:" + FileHash.sha256Hex(data: Data(bytes)) - let mapping: BuiltMap - let declaration: DeclarationIR - var stage = "evaluation" - var stageStart = clock.now - do { - evaluation = try Evaluator(source: source, admission: admission).evaluate() - metrics.evaluationSeconds = seconds(stageStart.duration(to: clock.now)) - stage = "domain" - stageStart = clock.now - diagnostics = - validateDomain - ? try DomainValidator(source: source, admission: admission, evaluation: evaluation) - .validate() : [] - metrics.domainSeconds = seconds(stageStart.duration(to: clock.now)) - stage = "lowering" - stageStart = clock.now - declaration = Lowering.declaration(evaluation.root.value) - metrics.loweringSeconds = seconds(stageStart.duration(to: clock.now)) - stage = "sourceMap" - stageStart = clock.now - mapping = try MapBuilder(source: source, admission: admission, digest: digest).build( - evaluation) - metrics.sourceMapSeconds = seconds(stageStart.duration(to: clock.now)) - } catch let failure as ManifestFailure { - let elapsed = seconds(stageStart.duration(to: clock.now)) - switch stage { - case "evaluation": metrics.evaluationSeconds = elapsed - case "domain": metrics.domainSeconds = elapsed - case "sourceMap": metrics.sourceMapSeconds = elapsed - default: metrics.loweringSeconds = elapsed - } - throw ManifestFailure(failure.diagnostics[0], metrics: metrics) - } - self.source = source - self.admission = admission - syntax = checked.tree - self.evaluation = evaluation - self.declaration = declaration - self.diagnostics = diagnostics - self.digest = digest - sourceMap = DeclarationSourceMap(entries: mapping.entries) - locations = mapping.locations - values = mapping.values - metrics.evaluationSteps = evaluation.steps - metrics.expandedNodes = evaluation.total.nodes - metrics.decodedBytes = evaluation.total.strings - self.metrics = metrics + // Keep ARC from releasing the tree before teardown timing starts. + withExtendedLifetime(result) {} + result = nil + metrics.teardownSeconds = seconds(start.duration(to: clock.now)) + observe?(.complete, metrics) + return metrics } + /// A JSON Pointer into the lowered declaration: empty string denotes the root, + /// arrays use decimal indexes, and object keys escape `~` as `~0` and `/` as `~1`. + /// Source requirements and literal wrappers use their lowered fields (for example `/value`). public func node(at pointer: String) -> NodeID? { locations[pointer] } + /// Addresses a constant definition by its Swift identifier, without pointer escaping. public func constant(named name: String) -> NodeID? { locations["/constants/" + pointerEscape(name)] } + /// Returns snapshot handles for all direct and transitive uses of this Swift identifier. public func uses(ofConstant name: String) -> [NodeID] { var pending = [name] var seen = Set() @@ -126,12 +97,10 @@ public struct DeclarationDocument: Sendable { return .readOnly(reason: "stale snapshot handle") } if node.pointer.hasPrefix("/constants/") { - let name = String(node.pointer.dropFirst("/constants/".count)).replacingOccurrences( - of: "~1", with: "/" - ).replacingOccurrences(of: "~0", with: "~") + let name = pointerUnescape(String(node.pointer.dropFirst("/constants/".count))) return .sharedConstant(uses: uses(ofConstant: name)) } - guard let value = values[node.pointer], !value.defaulted, value.type != .named("") else { + guard let value = values[node.pointer], !value.defaulted, value.type != .untyped else { return .readOnly(reason: "default field has no source range") } if value.referent != nil || hasAssembledAncestor(node.pointer) { @@ -139,18 +108,18 @@ public struct DeclarationDocument: Sendable { reason: "shared constant or assembled value; replace its definition explicitly") } let kind = admission.nodes[node.syntax].kind - if kind == "sequence" || kind == "name" { + if kind == .sequence || kind == .name { return .readOnly(reason: "expanded value has no independent source range") } return .direct } - package func hasAssembledAncestor(_ pointer: String) -> Bool { + func hasAssembledAncestor(_ pointer: String) -> Bool { var prefix = pointer while let slash = prefix.lastIndex(of: "/"), slash != prefix.startIndex { prefix = String(prefix[.. String { - text.replacingOccurrences(of: "~", with: "~0").replacingOccurrences(of: "/", with: "~1") -} - -package struct BuiltMap { - package var entries: [SourceMapEntry] = [] - package var locations: [String: NodeID] = [:] - package var values: [String: EvaluatedValue] = [:] -} - -package final class MapBuilder { - private let source: SourceText - private let admission: Admission - private let digest: String - private var result = BuiltMap() - private var originCount = 0 - private var encodedBytes = 0 - - package init(source: SourceText, admission: Admission, digest: String) { - self.source = source - self.admission = admission - self.digest = digest - } - - package func build(_ evaluation: Evaluation) throws -> BuiltMap { - try append(evaluation.root, pointer: "", origins: [], use: nil) - // Constants are separately addressable; declaration locations remain language independent. - for (name, value) in evaluation.constants where name != "agents" { - let pointer = "/constants/" + pointerEscape(name) - result.locations[pointer] = NodeID(digest: digest, pointer: pointer, syntax: value.syntax) - result.values[pointer] = value - } - result.entries.sort { ($0.pointer, $0.span.start) < ($1.pointer, $1.span.start) } - return result - } - - private func append( - _ value: EvaluatedValue, pointer: String, origins: [SourceSpan], use: SourceSpan?, - ownOrigins: [SourceSpan] = [] - ) throws { - let range = admission.nodes[value.syntax].range - let span = use ?? source.span(range) - var inherited = origins - let definition = source.span(range) - if use != nil, definition != span, inherited.last != definition { inherited.append(definition) } - var resolved = value - while let next = resolved.referent { - inherited.append(source.span(admission.nodes[next.syntax].range)) - resolved = next - } - if value.referent != nil { - guard resolved.cost.nodes <= 100_000 - result.entries.count, - value.cost.origins <= 1_000_000 - originCount - else { - throw source.failure("manifest.limit", "reference source map expansion", range.lowerBound) - } - } - let recordedOrigins = inherited + ownOrigins - let estimate = - pointer.utf8.count + (source.identity.rawValue.utf8.count + 160) * (recordedOrigins.count + 1) - + 80 - guard result.entries.count < 100_000, recordedOrigins.count <= 1_000_000 - originCount, - estimate <= 16_777_216 - encodedBytes - else { - throw source.failure( - "manifest.limit", "source map locations, origins or encoded bytes", range.lowerBound) - } - originCount += recordedOrigins.count - encodedBytes += estimate - result.entries.append( - SourceMapEntry( - pointer: pointer, span: span, origins: recordedOrigins, defaulted: value.defaulted)) - result.locations[pointer] = NodeID(digest: digest, pointer: pointer, syntax: value.syntax) - result.values[pointer] = value - let useSpan = value.referent != nil || use != nil ? span : nil - if case .node(let type, let member, let fields) = resolved.value { - let tagged: Set = [ - "Source", "Component", "MCPTransport", "ExecutableInvocation", "GroupReference", - "PromptContent", "RuntimeValue", "ConfigurationValue", "HookEvent", "PermissionOperation", - "ComponentReference", "PermissionRule", - ] - if tagged.contains(type), case .record(let record) = Lowering.lower(resolved.value) { - let discriminator = EvaluatedValue( - type: .named(""), value: .text(record.kind), cost: ValueCost.scalar(record.kind), - syntax: resolved.syntax) - try append(discriminator, pointer: pointer + "/kind", origins: inherited, use: useSpan) - } - if type == "SkillSelection" { - for (offset, child) in resolved.elementsForUse.enumerated() { - try append(child, pointer: pointer + "/\(offset)", origins: inherited, use: useSpan) - } - return - } - if type == "ConfigurationValue", resolved.fields["value"] == nil, - let payload = fields["value"] - { - let childType: ConstructionType = - member == "object" - ? .dictionary(.named("ConfigurationValue")) - : member == "array" - ? .array(.named("ConfigurationValue")) - : member == "integer" - ? .named("Int") : member == "boolean" ? .named("Bool") : .named("String") - let child = EvaluatedValue( - type: childType, value: payload, cost: resolved.cost, syntax: resolved.syntax, - fields: resolved.fields, elements: resolved.elements) - try append(child, pointer: pointer + "/value", origins: inherited, use: useSpan) - return - } - for (key, childValue) in fields { - if type == "Source", key == "requirement" { - let trace = ["from", "exact", "branch", "revision", "range"].compactMap { - resolved.fields[$0] - }.first - if let trace, childValue != .none { - let shape = requirementShape(childValue, trace: trace) - var definitions: [SourceSpan] = [] - var referent = trace.referent - while let definition = referent { - definitions.append(source.span(admission.nodes[definition.syntax].range)) - referent = definition.referent - } - try append( - shape, pointer: pointer + "/requirement", origins: inherited, use: useSpan, - ownOrigins: definitions) - } else { - let absent = EvaluatedValue( - type: .named(""), value: .none, cost: ValueCost(), syntax: resolved.syntax, - defaulted: true) - try append(absent, pointer: pointer + "/requirement", origins: inherited, use: useSpan) - } - continue - } - let sourceKey = - type == "Source" && key == "requirement" - ? ["from", "exact", "branch", "revision", "range"].first(where: { - resolved.fields[$0] != nil - }) ?? key : key - let child: EvaluatedValue - if let field = resolved.fields[sourceKey] { - child = field - } else { - child = EvaluatedValue( - type: .named(""), value: childValue, cost: ValueCost(), syntax: resolved.syntax, - defaulted: (key == "source" || key == "condition") && childValue == .none - || resolved.defaulted) - } - try append( - child, pointer: pointer + "/" + pointerEscape(key), origins: inherited, use: useSpan) - } - } else if !resolved.fields.isEmpty { - for (key, child) in resolved.fields { - try append( - child, pointer: pointer + "/" + pointerEscape(key), origins: inherited, use: useSpan) - } - } else if !resolved.elements.isEmpty { - for (offset, child) in resolved.elements.enumerated() { - try append(child, pointer: pointer + "/\(offset)", origins: inherited, use: useSpan) - } - } else { - try synthetic( - resolved.value, syntax: resolved.syntax, pointer: pointer, span: span, origins: inherited, - defaulted: value.defaulted) - } - } - - private func requirementShape(_ value: ConstructionValue, trace: EvaluatedValue) -> EvaluatedValue - { - let requirement = Lowering.lower(value) - var fields: [String: ConstructionValue] = [:] - var traces: [String: EvaluatedValue] = [:] - if case .requirement(let requirement) = requirement { - let lower = trace.field("from") ?? trace.elementsForUse.first ?? trace - switch requirement { - case .branch(let text): - fields["branch"] = .text(text) - traces["branch"] = trace - case .revision(let text): - fields["revision"] = .text(text) - traces["revision"] = trace - case .exact(let text): - fields["exact"] = .text(text) - traces["exact"] = trace - case .upToNextMajor(let text): - fields["from"] = .text(text) - traces["from"] = lower - case .upToNextMinor(let text): - fields["upToNextMinor"] = .text(text) - traces["upToNextMinor"] = lower - case .range(let from, let to): - fields["from"] = .text(from) - fields["to"] = .text(to) - traces["from"] = lower - traces["to"] = trace.elementsForUse.last ?? trace - } - } - return EvaluatedValue( - type: .named("Requirement"), value: .object(fields), cost: trace.cost, syntax: trace.syntax, - fields: traces) - } - - private func synthetic( - _ value: ConstructionValue, syntax: Int, pointer: String, span: SourceSpan, - origins: [SourceSpan], defaulted: Bool - ) throws { - let fields: [(String, ConstructionValue)] - switch value { - case .node(_, _, let values), .object(let values): fields = Array(values) - case .array(let values): fields = values.enumerated().map { (String($0.offset), $0.element) } - default: return - } - for (key, child) in fields { - let v = EvaluatedValue( - type: .named(""), value: child, cost: ValueCost(), syntax: syntax, defaulted: defaulted) - try append(v, pointer: pointer + "/" + pointerEscape(key), origins: origins, use: span) - } - } -} diff --git a/Sources/AgentsManifest/DocumentEditor.swift b/Sources/AgentsManifest/DocumentEditor.swift index eadc761..e2f6460 100644 --- a/Sources/AgentsManifest/DocumentEditor.swift +++ b/Sources/AgentsManifest/DocumentEditor.swift @@ -2,32 +2,33 @@ import AgentsCore import AgentsDescription import Foundation -package final class DocumentEditor { - private let original: DeclarationDocument - private var current: DeclarationDocument - private var table: PieceTable - private var history: [SourcePatch] = [] - private var expected: ConstructionValue - private var impacted: [NodeID] = [] - private var steps = 0 +final class DocumentEditor { + let original: DeclarationDocument + var current: DeclarationDocument + var table: PieceTable + var history: [SourcePatch] = [] + var expected: ConstructionValue + var impacted: [NodeID] = [] + var steps = 0 - package init(document: DeclarationDocument) { + init(document: DeclarationDocument) { original = document current = document table = PieceTable(document.bytes) expected = document.evaluation.root.value } - private func fail(_ code: String, _ message: String, range: Range? = nil) -> ManifestFailure - { + func fail(_ code: String, _ message: String, range: Range? = nil) -> ManifestFailure { current.source.failure( code, message, (range ?? 0..<0).lowerBound, end: (range ?? 0..<0).upperBound) } - private func charge(_ count: Int) throws { - if count > 1_000_000 - steps { throw fail("manifest.limit", "edit batch work steps") } + func charge(_ count: Int) throws { + if count > ManifestLimits.Editing.steps - steps { + throw fail("manifest.limit", "edit batch work steps") + } steps += count } - private func valueCost(_ value: ConstructionValue) throws -> ValueCost { + func valueCost(_ value: ConstructionValue) throws -> ValueCost { // Iterative preflight bounds external vocabulary values before recursive consumers. var pending: [(ConstructionValue, Int)] = [(value, 1)] var nodes = 0 @@ -35,7 +36,7 @@ package final class DocumentEditor { while let (value, depth) = pending.popLast() { try charge(1) nodes += 1 - if nodes > 100_000 || depth > 64 { + if nodes > ManifestLimits.Values.nodes || depth > ManifestLimits.Values.depth { throw fail("manifest.limit", "edit value node/depth budget") } let children: [ConstructionValue] @@ -44,10 +45,14 @@ package final class DocumentEditor { strings = ValueCost.add(strings, text.utf8.count) children = [] case .array(let values): - if values.count > 10_000 { throw fail("manifest.limit", "edit collection entries") } + if values.count > ManifestLimits.Values.entries { + throw fail("manifest.limit", "edit collection entries") + } children = values case .object(let fields), .node(_, _, let fields): - if fields.count > 10_000 { throw fail("manifest.limit", "edit dictionary entries") } + if fields.count > ManifestLimits.Values.entries { + throw fail("manifest.limit", "edit dictionary entries") + } strings = ValueCost.add(strings, fields.keys.reduce(0) { ValueCost.add($0, $1.utf8.count) }) children = Array(fields.values) case .version(let version): @@ -56,7 +61,9 @@ package final class DocumentEditor { case .range(let range): children = [.version(range.lowerBound), .version(range.upperBound)] default: children = [] } - if strings > 16_777_216 || pending.count + children.count > 100_000 { + if strings > ManifestLimits.Values.stringBytes + || pending.count + children.count > ManifestLimits.Values.nodes + { throw fail("manifest.limit", "edit expanded value bytes/nodes") } for child in children { pending.append((child, depth + 1)) } @@ -66,8 +73,10 @@ package final class DocumentEditor { return cost } - package func prepare(_ edits: [ManifestEdit]) throws -> DocumentChange { - if edits.count > 100 { throw fail("manifest.limit", "edit batch has more than 100 requests") } + func prepare(_ edits: [ManifestEdit]) throws -> DocumentChange { + if edits.count > ManifestLimits.Editing.requests { + throw fail("manifest.limit", "edit batch has more than 100 requests") + } for edit in edits { let before = history.count try apply(edit) @@ -91,7 +100,7 @@ package final class DocumentEditor { } let candidate = try DeclarationDocument(bytes: bytes, identity: original.source.identity) let actualCost = candidate.evaluation.root.cost - if expectedCost.nodes + actualCost.nodes > 200_000 { + if expectedCost.nodes + actualCost.nodes > ManifestLimits.Editing.comparisonPairs { throw fail("manifest.limit", "comparison node-pair budget") } try charge(expectedCost.nodes + actualCost.nodes) @@ -108,7 +117,7 @@ package final class DocumentEditor { delta: try semanticDelta()) } - private func semanticDelta() throws -> SemanticDelta { + func semanticDelta() throws -> SemanticDelta { var pending: [(DeclarationValue, DeclarationValue, String)] = [ (Lowering.lower(original.evaluation.root.value), Lowering.lower(expected), "") ] @@ -117,7 +126,9 @@ package final class DocumentEditor { while let (left, right, pointer) = pending.popLast() { try charge(1) visited += 1 - if visited > 200_000 { throw fail("manifest.limit", "semantic delta comparison node pairs") } + if visited > ManifestLimits.Editing.comparisonPairs { + throw fail("manifest.limit", "semantic delta comparison node pairs") + } switch (left, right) { case (.array(let a), .array(let b)) where a.count == b.count: for index in a.indices { pending.append((a[index], b[index], pointer + "/\(index)")) } @@ -128,96 +139,19 @@ package final class DocumentEditor { default: if left != right { pointers.append(pointer) } } - if pending.count > 200_000 - visited { + if pending.count > ManifestLimits.Editing.comparisonPairs - visited { throw fail("manifest.limit", "semantic delta scheduled pairs") } } return SemanticDelta(changedPointers: pointers.sorted()) } - private func apply(_ edit: ManifestEdit) throws { - switch edit { - case .setDefaultAgents(let agents): try setField("", "defaultAgents", agents.constructionValue) - case .setExports(let exports): try setField("", "exports", exports.constructionValue) - case .setWatch(let watch): try setField("", "watch", watch.constructionValue) - case .upsertSource(let source): - try upsert(source.constructionValue, collection: "/sources", key: "name") - case .removeSource(let alias): try removeNamed(alias, collection: "/sources", key: "name") - case .upsertGroup(let group): - try upsert(group.constructionValue, collection: "/groups", key: "name") - case .removeGroup(let name): try removeNamed(name, collection: "/groups", key: "name") - case .insertComponent(let component, let container, let position): - try insert( - component.constructionValue, into: containerPath(container) + "/components", at: position) - case .replaceComponent(let handle, let component): - let pointer = try resolve(handle) - try requireType(pointer, "Component") - try replace(pointer, with: component.constructionValue) - case .removeComponent(let handle): - let pointer = try resolve(handle) - try requireType(pointer, "Component") - try remove(pointer) - case .moveComponent(let handle, let container, let position): - let pointer = try resolve(handle) - try requireType(pointer, "Component") - try move(pointer, into: containerPath(container) + "/components", at: position) - case .setSkillSelection(let handle, let selection): - let pointer = try resolve(handle) - try requireType(pointer, "Component", member: "skills") - try setField(pointer, "select", selection.constructionValue) - case .upsertSkillOverride(let handle, let override): - let pointer = try resolve(handle) - try requireType(pointer, "Component", member: "skills") - try upsert(override.constructionValue, collection: pointer + "/overrides", key: "name") - case .removeSkillOverride(let handle, let name): - let pointer = try resolve(handle) - try requireType(pointer, "Component", member: "skills") - try removeNamed(name, collection: pointer + "/overrides", key: "name") - case .insertSection(let section, let handle, let position): - let pointer = try resolve(handle) - guard current.values[pointer]?.value.fields["sections"] != nil else { - throw fail("manifest.edit.readOnly", "target has no instruction sections") - } - try insert(section.constructionValue, into: pointer + "/sections", at: position) - case .removeSection(let handle): - let pointer = try resolve(handle) - try requireType(pointer, "SectionReference") - try remove(pointer) - case .moveSection(let handle, let position): - let pointer = try resolve(handle) - try requireType(pointer, "SectionReference") - try move(pointer, into: parent(pointer), at: position) - case .upsertPrompt(let handle, let prompt): - let pointer = try resolve(handle) - try requireType(pointer, "Component", member: "instructions") - try upsert(prompt.constructionValue, collection: pointer + "/chatGPT", key: "name") - case .removePrompt(let handle, let name): - let pointer = try resolve(handle) - try requireType(pointer, "Component", member: "instructions") - try removeNamed(name, collection: pointer + "/chatGPT", key: "name") - case .insertGroupReference(let reference, let container, let position): - try insert( - reference.constructionValue, into: containerPath(container) + "/uses", at: position) - case .removeGroupReference(let handle): - let pointer = try resolve(handle) - try requireType(pointer, "GroupReference") - try remove(pointer) - case .setDictionaryEntry(let handle, let key, let value): - let pointer = try resolve(handle) - try dictionary(pointer, key: key, value: value) - case .removeDictionaryEntry(let handle, let key): - try dictionary(resolve(handle), key: key, value: nil) - case .replaceConstant(let handle, let value, let accepted): - try constant(handle, value: value, accepted: accepted) - } - } - - private func requireType(_ pointer: String, _ type: String, member: String? = nil) throws { + func requireType(_ pointer: String, _ type: String, member: String? = nil) throws { guard current.values[pointer]?.type.unwrapped == .named(type), member == nil || current.values[pointer]?.value.member == member else { throw fail("manifest.edit.readOnly", "handle has the wrong domain kind") } } - private func resolve(_ handle: NodeID) throws -> String { + func resolve(_ handle: NodeID) throws -> String { guard handle.digest == original.digest, let originalValue = original.values[handle.pointer], originalValue.syntax == handle.syntax else { throw fail("manifest.edit.stale", "handle belongs to a different snapshot") } @@ -236,7 +170,10 @@ package final class DocumentEditor { else { throw fail("manifest.edit.stale", "the addressed occurrence was removed or replaced") } return pointer } - private func translated(_ originalRange: Range) throws -> Range { + /// History ranges use the snapshot immediately before each patch. Earlier siblings + /// translate both bounds; contained edits resize the owner. Crossing an owner boundary + /// cannot preserve occurrence identity and is rejected instead of guessing a pointer. + func translated(_ originalRange: Range) throws -> Range { var range = originalRange for patch in history { let delta = patch.replacement.count - patch.range.count @@ -259,11 +196,11 @@ package final class DocumentEditor { } return range } - private func direct(_ pointer: String) throws -> EvaluatedValue { + func direct(_ pointer: String) throws -> EvaluatedValue { guard let value = current.values[pointer], !value.defaulted, value.referent == nil, !current.hasAssembledAncestor(pointer), - current.admission.nodes[value.syntax].kind != "sequence", - current.admission.nodes[value.syntax].kind != "name" + current.admission.nodes[value.syntax].kind != .sequence, + current.admission.nodes[value.syntax].kind != .name else { throw fail( "manifest.edit.readOnly", @@ -271,7 +208,7 @@ package final class DocumentEditor { } return value } - private func containerPath(_ container: ContainerID) throws -> String { + func containerPath(_ container: ContainerID) throws -> String { switch container { case .root: return "" case .group(let handle): @@ -280,34 +217,30 @@ package final class DocumentEditor { return pointer } } - private func parent(_ pointer: String) -> String { + func parent(_ pointer: String) -> String { String(pointer[.. String { - String(pointer[pointer.index(after: pointer.lastIndex(of: "/")!)...]).replacingOccurrences( - of: "~1", with: "/" - ).replacingOccurrences(of: "~0", with: "~") + func key(_ pointer: String) -> String { + pointerUnescape(String(pointer[pointer.index(after: pointer.lastIndex(of: "/")!)...])) } - private func patch(_ range: Range, _ text: String) throws { + func patch(_ range: Range, _ text: String) throws { try patch(range, bytes: Array(text.utf8)) } - private func patch(_ range: Range, bytes: [UInt8]) throws { + func patch(_ range: Range, bytes: [UInt8]) throws { guard range.lowerBound >= 0, range.upperBound <= table.count else { throw fail("manifest.edit.overlap", "patch is outside the snapshot") } - if table.count - range.count + bytes.count > 2_097_152 { + if table.count - range.count + bytes.count > ManifestLimits.Input.bytes { throw fail("manifest.limit", "generated manifest input bytes") } if current.bytes[range].elementsEqual(bytes) { return } table.replace(range, with: bytes) history.append(SourcePatch(range: range, replacement: bytes)) } - private func mutate(_ pointer: String, _ replacement: ConstructionValue) throws { + func mutate(_ pointer: String, _ replacement: ConstructionValue) throws { _ = try valueCost(replacement) - let parts = pointer.split(separator: "/").map { - String($0).replacingOccurrences(of: "~1", with: "/").replacingOccurrences(of: "~0", with: "~") - } + let parts = pointerSegments(pointer) func update(_ value: ConstructionValue, _ depth: Int) throws -> ConstructionValue { try charge(1) if depth == parts.count { return replacement } @@ -338,100 +271,23 @@ package final class DocumentEditor { _ = try valueCost(expected) } - private func style(at range: Range) throws -> (PrintStyle, String) { - try charge(current.admission.nodes.count) - let bytes = current.bytes - var endings = Set() - var cursor = 0 - while cursor < bytes.count { - if bytes[cursor] == 13 { - if cursor + 1 < bytes.count && bytes[cursor + 1] == 10 { - endings.insert("\r\n") - cursor += 1 - } else { - endings.insert("\r") - } - } else if bytes[cursor] == 10 { - endings.insert("\n") - } - cursor += 1 - } - guard endings.count <= 1 else { - throw fail("manifest.edit.readOnly", "conflicting newline styles", range: range) - } - let indentation = indentation(at: range.lowerBound) - let candidates = current.admission.nodes.filter { node in - ["array", "dictionary", "call"].contains(node.kind) - && node.range.lowerBound <= range.lowerBound && node.range.upperBound >= range.upperBound - } - var unit: String? - var trailingComma = true - for container in candidates.sorted(by: { $0.range.count < $1.range.count }) { - var units = Set() - let base = self.indentation(at: container.range.lowerBound) - let offsets = - container.kind == "dictionary" - ? container.keys.map { $0.range.lowerBound } - : container.kind == "array" - ? container.children.map { current.admission.nodes[$0].range.lowerBound } - : container.arguments.map { - $0.labelRange?.lowerBound ?? current.admission.nodes[$0.value].range.lowerBound - } - for offset in offsets { - let start = lineStart(offset) - let prefix = current.source.spelling(start.. base.count else { - throw fail("manifest.edit.readOnly", "conflicting local indentation", range: range) - } - units.insert(String(prefix.dropFirst(base.count))) - } - guard units.count <= 1 else { - throw fail("manifest.edit.readOnly", "conflicting local indentation", range: range) - } - if let evidence = units.first { - unit = evidence - break - } - } - for container in candidates.sorted(by: { $0.range.count < $1.range.count }) - where container.kind == "array" || container.kind == "dictionary" { - guard let last = container.children.last, - let token = current.admission.tokens.first(where: { - $0.range.lowerBound >= current.admission.nodes[last].range.upperBound - }) - else { continue } - trailingComma = token.text == "," - break - } - return ( - PrintStyle( - indent: unit ?? " ", newline: endings.first ?? "\n", trailingComma: trailingComma), - indentation - ) - } - - private func indentation(at offset: Int) -> String { - String(current.source.spelling(lineStart(offset)..) throws -> String { + func replacementText(_ value: ConstructionValue, at range: Range) throws -> String { _ = try valueCost(value) let (style, indentation) = try style(at: range) var text = CanonicalPrinter(style: style).render(value, indentation: indentation) if text.hasPrefix("-"), range.lowerBound > 0 { let previous = current.bytes[range.lowerBound - 1] - if ![32, 9, 10, 13, 40, 91, 44, 58].contains(previous) { text = " " + text } + if ![ + UInt8(ascii: " "), UInt8(ascii: "\t"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), + UInt8(ascii: "("), UInt8(ascii: "["), UInt8(ascii: ","), UInt8(ascii: ":"), + ].contains(previous) { + text = " " + text + } } return text } - private func internalComments(_ range: Range) -> Bool { - current.admission.comments.contains { - $0.lowerBound >= range.lowerBound && $0.upperBound <= range.upperBound - } - } - private func replace(_ pointer: String, with value: ConstructionValue) throws { + func replace(_ pointer: String, with value: ConstructionValue) throws { let old = try direct(pointer) _ = try valueCost(value) if Lowering.lower(old.value) == Lowering.lower(value) { return } @@ -445,386 +301,7 @@ package final class DocumentEditor { try mutate(pointer, value) } - private func setField( - _ pointer: String, _ field: String, _ value: ConstructionValue, spelling: String? = nil - ) throws { - let owner = try direct(pointer) - let node = current.admission.nodes[owner.syntax] - guard node.kind == "call", let old = owner.value.fields[field] else { - throw fail("manifest.edit.readOnly", "target is not a direct construction") - } - _ = try valueCost(value) - if Lowering.lower(old) == Lowering.lower(value) { return } - if let child = owner.field(field), !child.defaulted { - try replace(pointer + "/" + pointerEscape(field), with: value) - return - } - let signatures = Vocabulary.signatures.filter { - $0.type == owner.type.name && $0.member == owner.value.member - } - guard - let signature = signatures.first(where: { - $0.parameters.contains(where: { $0.name == field }) - }), let position = signature.parameters.firstIndex(where: { $0.name == field }) - else { throw fail("manifest.edit.readOnly", "unknown construction field") } - let next = node.arguments.first { argument in - let index = signature.parameters.firstIndex { $0.label == argument.label } ?? -1 - return index > position - } - let (style, indentation) = try style(at: node.range) - let content = - field + ": " - + (spelling - ?? CanonicalPrinter(style: style).render(value, indentation: indentation + style.indent)) - let multiline = current.bytes[node.range].contains(10) || current.bytes[node.range].contains(13) - if let next { - let start = - next.labelRange?.lowerBound ?? current.admission.nodes[next.value].range.lowerBound - if multiline { - let line = lineStart(start) - if current.bytes[line.. Int - { - switch position { - case .first: return 0 - case .last: return count - case .before(let handle), .after(let handle): - let pointer = try resolve(handle) - guard parent(pointer) == collection, let index = Int(key(pointer)) else { - throw fail("manifest.edit.impact", "insertion anchor belongs to another container") - } - if case .after = position { return index + 1 } - return index - } - } - - private func insert( - _ value: ConstructionValue, into pointer: String, at position: InsertionPosition, - carried: [UInt8]? = nil - ) throws { - guard let collection = current.values[pointer], case .array(let previous) = collection.value - else { throw fail("manifest.edit.readOnly", "target is not an array") } - let incoming = try valueCost(value) - guard previous.count < 10_000 else { throw fail("manifest.limit", "edited array entries") } - let combined = ValueCost.container(collection.elementsForUse.map(\.cost) + [incoming]) - let total = current.evaluation.total - let projected = ValueCost( - nodes: total.nodes - collection.cost.nodes + combined.nodes, - strings: total.strings - collection.cost.strings + combined.strings, - encoded: total.encoded - collection.cost.encoded + combined.encoded, - depth: max(total.depth, incoming.depth + pointer.split(separator: "/").count + 1), - origins: total.origins - collection.cost.origins + combined.origins) - guard combined.fits, projected.fits else { - throw fail("manifest.limit", "edited expanded document budget") - } - let index = try self.position(position, collection: pointer, count: previous.count) - var expectedValues = previous - expectedValues.insert(value, at: index) - if collection.defaulted { - if let carried { - let owner = try direct(parent(pointer)) - let (style, indentation) = try style(at: current.admission.nodes[owner.syntax].range) - let text = - "[" + style.newline + indentation + style.indent + style.indent - + String(decoding: carried, as: UTF8.self) + style.newline + indentation + style.indent - + "]" - try setField(parent(pointer), key(pointer), .array(expectedValues), spelling: text) - } else { - try setField(parent(pointer), key(pointer), .array(expectedValues)) - } - return - } - _ = try direct(pointer) - let node = current.admission.nodes[collection.syntax] - guard node.kind == "array" else { - throw fail("manifest.edit.readOnly", "target is an assembled array") - } - let (style, indentation) = try style(at: node.range) - let multiline = - current.bytes[node.range].contains(10) || current.bytes[node.range].contains(13) - || carried?.contains(10) == true || carried?.contains(13) == true - let rendered = - carried.map { String(decoding: $0, as: UTF8.self) } - ?? CanonicalPrinter(style: style).render( - value, indentation: multiline ? indentation + style.indent : indentation) - if previous.isEmpty { - let interior = (node.range.lowerBound + 1)..<(node.range.upperBound - 1) - if !current.bytes[interior].allSatisfy({ [32, 9, 10, 13].contains($0) }) { - throw fail( - "manifest.edit.readOnly", "comment-only container insertion is ambiguous", range: interior - ) - } - try patch( - interior, - multiline - ? style.newline + indentation + style.indent + rendered + (carried == nil ? "," : "") - + style.newline + indentation : rendered) - } else if index < previous.count { - let child = collection.elementsForUse[index] - let owned = try ownedRange(child, container: node, index: index) - if multiline { - guard owned.lowerBound == lineStart(owned.lowerBound) else { - throw fail("manifest.edit.readOnly", "mixed inline and multiline collection layout") - } - try patch( - owned.lowerBound..= range.upperBound && $0.range.upperBound <= close - } - let gap = range.upperBound.. Int { - var result = offset - while result > 0 && current.bytes[result - 1] != 10 && current.bytes[result - 1] != 13 { - result -= 1 - } - return result - } - private func lineEnd(_ offset: Int) -> Int { - var result = offset - while result < current.bytes.count && current.bytes[result] != 10 && current.bytes[result] != 13 - { result += 1 } - return result - } - private func blankLine(_ range: Range) -> Bool { - let normalized = current.source.spelling(range).replacingOccurrences(of: "\r\n", with: "\n") - .replacingOccurrences(of: "\r", with: "\n") - return normalized.split(separator: "\n", omittingEmptySubsequences: false).dropFirst() - .dropLast().contains { $0.allSatisfy { $0 == " " || $0 == "\t" } } - } - private func ownedRange(_ value: EvaluatedValue, container: GrammarNode, index: Int) throws - -> Range - { - let expressionRange = current.admission.nodes[value.syntax].range - let range = - container.kind == "dictionary" - ? container.keys[index].range.lowerBound..= previous && $0.upperBound <= start - } - for comment in preceding.reversed() { - if blankLine(comment.upperBound..= previous, - current.bytes[line..= previous && current.bytes[line..= end && $0.range.upperBound <= next - } - if let comma { end = comma.range.upperBound } - for comment in current.admission.comments - where comment.lowerBound >= range.upperBound && comment.upperBound <= next { - if comment.lowerBound <= (comma?.range.lowerBound ?? range.upperBound) - || lineStart(comment.lowerBound) == lineStart(end) - { - end = max(end, comment.upperBound) - } - } - let ending = lineEnd(end) - if start == lineStart(start), ending <= next, - current.bytes[end..= current.admission.nodes[value.syntax].range.upperBound - && $0.range.upperBound <= range.upperBound - } - var patches = [SourcePatch(range: range, replacement: [])] - if !hasComma && index > 0 { - let previous = current.admission.nodes[node.children[index - 1]].range.upperBound - if let comma = current.admission.tokens.last(where: { - $0.text == "," && $0.range.lowerBound >= previous && $0.range.upperBound <= range.lowerBound - }) { - patches.append(SourcePatch(range: comma.range, replacement: [])) - } else { - throw fail("manifest.edit.readOnly", "ambiguous separator ownership", range: range) - } - } - values.remove(at: index) - for patch in patches.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { - try self.patch(patch.range, bytes: patch.replacement) - } - try mutate(collectionPointer, .array(values)) - } - - private func move(_ pointer: String, into collection: String, at position: InsertionPosition) - throws - { - let value = try direct(pointer) - let from = parent(pointer) - guard let old = current.values[from], let index = Int(key(pointer)), - let target = current.values[collection], case .array = target.value - else { throw fail("manifest.edit.readOnly", "move requires array containers") } - let destination = try self.position( - position, collection: collection, count: target.elementsForUse.count) - if from == collection && (destination == index || destination == index + 1) { return } - let node = current.admission.nodes[old.syntax] - let owned = try ownedRange(value, container: node, index: index) - let expression = current.admission.nodes[value.syntax].range - let leading = current.source.spelling(owned.lowerBound..= expression.upperBound - && $0.range.upperBound <= owned.upperBound - } - let beforeComma = - comma.map { current.source.spelling(expression.upperBound..<$0.range.lowerBound) } ?? "" - let afterComma = current.source.spelling( - (comma?.range.upperBound ?? expression.upperBound).. index ? destination - 1 : destination - let count = current.values[refreshed]?.elementsForUse.count ?? 0 - let insertion: InsertionPosition - if adjusted == 0 { - insertion = .first - } else if adjusted == count { - insertion = .last - } else { - // Use a current local anchor for the internal move only. - try insertAtIndex(value.value, pointer: refreshed, index: adjusted, carried: carried) - return - } - try insert(value.value, into: refreshed, at: insertion, carried: Array(carried.utf8)) - } - private func insertAtIndex( - _ value: ConstructionValue, pointer: String, index: Int, carried: String - ) throws { - // A direct byte anchor avoids manufacturing a public snapshot handle. - let collection = try direct(pointer) - let node = current.admission.nodes[collection.syntax] - let owned = try ownedRange(collection.elementsForUse[index], container: node, index: index) - let (style, indentation) = try style(at: node.range) - let multiline = current.bytes[node.range].contains(10) - try patch( - owned.lowerBound.. String - { - // Removing a root component cannot move a group definition, and group moves never nest groups. - if let value = current.values[pointer], value.type == previous.type { return pointer } - throw fail("manifest.edit.stale", "destination container changed during move") - } - - private func contextualValue(_ input: StaticValue, as context: ConstructionType) throws + func contextualValue(_ input: StaticValue, as context: ConstructionType) throws -> ConstructionValue { _ = try valueCost(input.value) @@ -832,231 +309,14 @@ package final class DocumentEditor { guard input.literal else { throw fail("manifest.type", "replacement has the wrong contextual type") } - func convert(_ value: ConstructionValue, _ context: ConstructionType) throws - -> ConstructionValue - { - try charge(1) - if case .optional(let wrapped) = context { - if value == .none { return .none } - return try convert(value, wrapped) - } - switch (value, context) { - case (.text, .named("String")), (.integer, .named("Int")), (.boolean, .named("Bool")): - return value - case (.array(let values), .array(let element)): - return .array(try values.map { try convert($0, element) }) - case (.object(let fields), .dictionary(let element)): - return .object(try fields.mapValues { try convert($0, element) }) - case (.text(let text), .named("Version")): - let version = Version(stringLiteral: text) - guard version.valid else { throw fail("manifest.domain", "invalid version replacement") } - return .version(version) - case (.text, .named("PromptContent")), (.text, .named("RuntimeValue")): - return .node(type: context.name, member: "literal", fields: ["value": value]) - case (.text, .named("SectionReference")), (.text, .named("GroupReference")): - return .node( - type: context.name, member: context.name == "SectionReference" ? "section" : "group", - fields: ["name": value, "source": .none, "condition": .none]) - case (.array(let values), .named("SkillSelection")): - return .node( - type: "SkillSelection", member: "names", - fields: ["names": .array(try values.map { try convert($0, .named("String")) })]) - case (_, .named("ConfigurationValue")): - let kind: String - let payload: ConstructionValue - switch value { - case .text: - kind = "string" - payload = value - case .integer: - kind = "integer" - payload = value - case .boolean: - kind = "boolean" - payload = value - case .none: return .node(type: "ConfigurationValue", member: "null", fields: [:]) - case .array(let values): - kind = "array" - payload = .array(try values.map { try convert($0, context) }) - case .object(let fields): - kind = "object" - payload = .object(try fields.mapValues { try convert($0, context) }) - case .node(let type, _, _) where type == "ConfigurationValue": return value - default: throw fail("manifest.type", "value cannot use configuration literal conversion") - } - return .node(type: "ConfigurationValue", member: kind, fields: ["value": payload]) - default: throw fail("manifest.type", "replacement has the wrong contextual type") - } + let result: ConstructionValue + do { + result = try LiteralConversion.convert(input.value, to: context) { try charge(1) } + } catch let error as LiteralConversionError { + throw fail(error.code, error.message) } - let result = try convert(input.value, context) _ = try valueCost(result) return result } - private func dictionary(_ pointer: String, key: String, value replacement: StaticValue?) throws { - let value = try direct(pointer) - if value.type == .named("ConfigurationValue"), value.value.member == "object" { - try dictionary(pointer + "/value", key: key, value: replacement) - return - } - let node = current.admission.nodes[value.syntax] - guard node.kind == "dictionary", case .dictionary(let elementType) = value.type.unwrapped, - case .object(var fields) = value.value - else { throw fail("manifest.edit.readOnly", "target is not a direct dictionary") } - if let replacement { - let replacementValue = try contextualValue(replacement, as: elementType) - if let index = node.keys.firstIndex(where: { $0.decoded == key }) { - let childPointer = pointer + "/" + pointerEscape(key) - try replace(childPointer, with: replacementValue) - _ = index - return - } - let close = node.range.upperBound - 1 - let (style, indentation) = try style(at: node.range) - let text = - quoted(key) + ": " - + CanonicalPrinter(style: style).render( - replacementValue, indentation: indentation + style.indent) - let multiline = current.bytes[node.range].contains(10) - if node.children.isEmpty { - let interior = (node.range.lowerBound + 1)..= end && $0.range.upperBound <= close - } - if multiline { - let at = comma?.range.upperBound ?? end - try patch( - at..= childEnd && $0.range.upperBound <= range.upperBound - } - var patches = [SourcePatch(range: range, replacement: [])] - if !hasComma && index > 0 { - let previous = current.admission.nodes[node.children[index - 1]].range.upperBound - guard - let comma = current.admission.tokens.last(where: { - $0.text == "," && $0.range.lowerBound >= previous - && $0.range.upperBound <= range.lowerBound - }) - else { throw fail("manifest.edit.readOnly", "dictionary separator is ambiguous") } - patches.append(SourcePatch(range: comma.range, replacement: [])) - } - for patch in patches.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { - try self.patch(patch.range, bytes: patch.replacement) - } - fields.removeValue(forKey: key) - if fields.isEmpty { - // The colon is necessary even if retained container whitespace/comments remain. - let opener = node.range.lowerBound + 1 - try patch(opener.. ConstructionValue - { - try charge(1) - if old == new { return expected } - switch (old, new, expected) { - case (.array(let a), .array(let b), .array(let e)) - where a.count == b.count && a.count == e.count: - return .array(try a.indices.map { try merge(a[$0], b[$0], e[$0]) }) - case (.node(let t, let m, let a), .node(let nt, let nm, let b), .node(_, _, let e)) - where t == nt && m == nm && a.keys == b.keys && a.keys == e.keys: - var result = e - for key in a.keys { result[key] = try merge(a[key]!, b[key]!, e[key]!) } - return .node(type: t, member: m, fields: result) - case (.object(let a), .object(let b), .object(let e)) - where a.keys == b.keys && a.keys == e.keys: - var result = e - for key in a.keys { result[key] = try merge(a[key]!, b[key]!, e[key]!) } - return .object(result) - default: return new - } - } - expected = try merge(current.evaluation.root.value, altered.root.value, expected) - impacted += uses - try patch(range, replacementText(replacementValue, at: range)) - if let declaration = current.admission.declarations.first(where: { $0.name == name }), - declaration.type == nil, - needsContext(replacementValue, type: old.type) - { - let offset = declaration.nameRange.upperBound - try patch(offset.. Bool { - switch (value, type) { - case (.text, .named("String")), (.integer, .named("Int")), (.boolean, .named("Bool")): - return false - case (.node(let type, _, _), _) where type == "Agents": return false - case (.array(let values), .array(let element)): - return values.first.map { needsContext($0, type: element) } ?? true - case (.object(let fields), .dictionary(let element)): - return fields.keys.sorted(by: utf8Less).first.map { needsContext(fields[$0]!, type: element) } - ?? true - default: return true - } - } - - private func typeSpelling(_ type: ConstructionType) -> String { - switch type { - case .named(let name): return name - case .array(let element): return "[" + typeSpelling(element) + "]" - case .dictionary(let element): return "[String: " + typeSpelling(element) + "]" - case .optional(let element): return typeSpelling(element) - } - } -} - -extension ConstructionType { - package var name: String { - if case .named(let name) = unwrapped { return name } - return "" - } } diff --git a/Sources/AgentsManifest/DocumentEdits.swift b/Sources/AgentsManifest/DocumentEdits.swift new file mode 100644 index 0000000..9964fca --- /dev/null +++ b/Sources/AgentsManifest/DocumentEdits.swift @@ -0,0 +1,559 @@ +import AgentsCore +import AgentsDescription +import Foundation + +extension DocumentEditor { + func apply(_ edit: ManifestEdit) throws { + switch edit { + case .setDefaultAgents(let agents): try setField("", "defaultAgents", agents.constructionValue) + case .setExports(let exports): try setField("", "exports", exports.constructionValue) + case .setWatch(let watch): try setField("", "watch", watch.constructionValue) + case .upsertSource(let source): + try upsert(source.constructionValue, collection: "/sources", key: "name") + case .removeSource(let alias): try removeNamed(alias, collection: "/sources", key: "name") + case .upsertGroup(let group): + try upsert(group.constructionValue, collection: "/groups", key: "name") + case .removeGroup(let name): try removeNamed(name, collection: "/groups", key: "name") + case .insertComponent(let component, let container, let position): + try insert( + component.constructionValue, into: containerPath(container) + "/components", at: position) + case .replaceComponent(let handle, let component): + let pointer = try resolve(handle) + try requireType(pointer, "Component") + try replace(pointer, with: component.constructionValue) + case .removeComponent(let handle): + let pointer = try resolve(handle) + try requireType(pointer, "Component") + try remove(pointer) + case .moveComponent(let handle, let container, let position): + let pointer = try resolve(handle) + try requireType(pointer, "Component") + try move(pointer, into: containerPath(container) + "/components", at: position) + case .setSkillSelection(let handle, let selection): + let pointer = try resolve(handle) + try requireType(pointer, "Component", member: "skills") + try setField(pointer, "select", selection.constructionValue) + case .upsertSkillOverride(let handle, let override): + let pointer = try resolve(handle) + try requireType(pointer, "Component", member: "skills") + try upsert(override.constructionValue, collection: pointer + "/overrides", key: "name") + case .removeSkillOverride(let handle, let name): + let pointer = try resolve(handle) + try requireType(pointer, "Component", member: "skills") + try removeNamed(name, collection: pointer + "/overrides", key: "name") + case .insertSection(let section, let handle, let position): + let pointer = try resolve(handle) + guard current.values[pointer]?.value.fields["sections"] != nil else { + throw fail("manifest.edit.readOnly", "target has no instruction sections") + } + try insert(section.constructionValue, into: pointer + "/sections", at: position) + case .removeSection(let handle): + let pointer = try resolve(handle) + try requireType(pointer, "SectionReference") + try remove(pointer) + case .moveSection(let handle, let position): + let pointer = try resolve(handle) + try requireType(pointer, "SectionReference") + try move(pointer, into: parent(pointer), at: position) + case .upsertPrompt(let handle, let prompt): + let pointer = try resolve(handle) + try requireType(pointer, "Component", member: "instructions") + try upsert(prompt.constructionValue, collection: pointer + "/chatGPT", key: "name") + case .removePrompt(let handle, let name): + let pointer = try resolve(handle) + try requireType(pointer, "Component", member: "instructions") + try removeNamed(name, collection: pointer + "/chatGPT", key: "name") + case .insertGroupReference(let reference, let container, let position): + try insert( + reference.constructionValue, into: containerPath(container) + "/uses", at: position) + case .removeGroupReference(let handle): + let pointer = try resolve(handle) + try requireType(pointer, "GroupReference") + try remove(pointer) + case .setDictionaryEntry(let handle, let key, let value): + let pointer = try resolve(handle) + try dictionary(pointer, key: key, value: value) + case .removeDictionaryEntry(let handle, let key): + try dictionary(resolve(handle), key: key, value: nil) + case .replaceConstant(let handle, let value, let accepted): + try constant(handle, value: value, accepted: accepted) + } + } + + func setField( + _ pointer: String, _ field: String, _ value: ConstructionValue, spelling: String? = nil + ) throws { + let owner = try direct(pointer) + let node = current.admission.nodes[owner.syntax] + guard node.kind == .call, let old = owner.value.fields[field] else { + throw fail("manifest.edit.readOnly", "target is not a direct construction") + } + _ = try valueCost(value) + if Lowering.lower(old) == Lowering.lower(value) { return } + if let child = owner.field(field), !child.defaulted { + try replace(pointer + "/" + pointerEscape(field), with: value) + return + } + guard case .named(let type) = owner.type.unwrapped else { + throw fail("manifest.edit.readOnly", "target has no named construction type") + } + let signatures = Vocabulary.signatures.filter { + $0.type == type && $0.member == owner.value.member + } + guard + let signature = signatures.first(where: { + $0.parameters.contains(where: { $0.name == field }) + }), let position = signature.parameters.firstIndex(where: { $0.name == field }) + else { throw fail("manifest.edit.readOnly", "unknown construction field") } + let next = node.arguments.first { argument in + let index = signature.parameters.firstIndex { $0.label == argument.label } ?? -1 + return index > position + } + let (style, indentation) = try style(at: node.range) + let content = + field + ": " + + (spelling + ?? CanonicalPrinter(style: style).render(value, indentation: indentation + style.indent)) + let multiline = hasNewline(node.range) + if let next { + let start = + next.labelRange?.lowerBound ?? current.admission.nodes[next.value].range.lowerBound + if multiline { + let line = lineStart(start) + if current.bytes[line.. Int { + switch position { + case .first: return 0 + case .last: return count + case .before(let handle), .after(let handle): + let pointer = try resolve(handle) + guard parent(pointer) == collection, let index = Int(key(pointer)) else { + throw fail("manifest.edit.impact", "insertion anchor belongs to another container") + } + if case .after = position { return index + 1 } + return index + } + } + + func insert( + _ value: ConstructionValue, into pointer: String, at position: InsertionPosition, + carried: CarriedElement? = nil + ) throws { + guard let collection = current.values[pointer], case .array(let previous) = collection.value + else { throw fail("manifest.edit.readOnly", "target is not an array") } + let incoming = try valueCost(value) + guard previous.count < ManifestLimits.Values.entries else { + throw fail("manifest.limit", "edited array entries") + } + let combined = ValueCost.container(collection.elementsForUse.map(\.cost) + [incoming]) + let total = current.evaluation.total + let projected = ValueCost( + nodes: total.nodes - collection.cost.nodes + combined.nodes, + strings: total.strings - collection.cost.strings + combined.strings, + encoded: total.encoded - collection.cost.encoded + combined.encoded, + depth: max(total.depth, incoming.depth + pointer.split(separator: "/").count + 1), + origins: total.origins - collection.cost.origins + combined.origins) + guard combined.fits, projected.fits else { + throw fail("manifest.limit", "edited expanded document budget") + } + let index = try self.position(position, collection: pointer, count: previous.count) + var expectedValues = previous + expectedValues.insert(value, at: index) + if collection.defaulted { + if let carried { + let owner = try direct(parent(pointer)) + let (style, indentation) = try style(at: current.admission.nodes[owner.syntax].range) + let text = + "[" + style.newline + indentation + style.indent + style.indent + + carried.render( + indentation: indentation + style.indent + style.indent, newline: style.newline) + + style.newline + indentation + style.indent + + "]" + try setField(parent(pointer), key(pointer), .array(expectedValues), spelling: text) + } else { + try setField(parent(pointer), key(pointer), .array(expectedValues)) + } + return + } + _ = try direct(pointer) + let node = current.admission.nodes[collection.syntax] + guard node.kind == .array else { + throw fail("manifest.edit.readOnly", "target is an assembled array") + } + let (style, indentation) = try style(at: node.range) + let multiline = + hasNewline(node.range) + || carried?.isMultiline == true + let rendered = + carried.map { $0.render(indentation: indentation + style.indent, newline: style.newline) } + ?? CanonicalPrinter(style: style).render( + value, indentation: multiline ? indentation + style.indent : indentation) + if previous.isEmpty { + let interior = (node.range.lowerBound + 1)..<(node.range.upperBound - 1) + if !current.bytes[interior].allSatisfy({ + [UInt8(ascii: " "), UInt8(ascii: "\t"), UInt8(ascii: "\n"), UInt8(ascii: "\r")].contains($0) + }) { + throw fail( + "manifest.edit.readOnly", "comment-only container insertion is ambiguous", range: interior + ) + } + try patch( + interior, + multiline + ? style.newline + indentation + style.indent + rendered + (carried == nil ? "," : "") + + style.newline + indentation : rendered) + } else if index < previous.count { + let child = collection.elementsForUse[index] + let owned = try ownedRange(child, container: node, index: index) + if multiline { + guard owned.lowerBound == lineStart(owned.lowerBound) else { + throw fail("manifest.edit.readOnly", "mixed inline and multiline collection layout") + } + try patch( + owned.lowerBound..= range.upperBound && $0.range.upperBound <= close + } + let gap = range.upperBound..= current.admission.nodes[value.syntax].range.upperBound + && $0.range.upperBound <= range.upperBound + } + var patches = [SourcePatch(range: range, replacement: [])] + if !hasComma && index > 0 { + let previous = current.admission.nodes[node.children[index - 1]].range.upperBound + if let comma = current.admission.tokens.last(where: { + $0.text == "," && $0.range.lowerBound >= previous && $0.range.upperBound <= range.lowerBound + }) { + patches.append(SourcePatch(range: comma.range, replacement: [])) + } else { + throw fail("manifest.edit.readOnly", "ambiguous separator ownership", range: range) + } + } + values.remove(at: index) + for patch in patches.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { + try self.patch(patch.range, bytes: patch.replacement) + } + try mutate(collectionPointer, .array(values)) + } + + func move(_ pointer: String, into collection: String, at position: InsertionPosition) + throws + { + let value = try direct(pointer) + let from = parent(pointer) + guard let old = current.values[from], let index = Int(key(pointer)), + let target = current.values[collection], case .array = target.value + else { throw fail("manifest.edit.readOnly", "move requires array containers") } + let destination = try self.position( + position, collection: collection, count: target.elementsForUse.count) + if from == collection && (destination == index || destination == index + 1) { return } + let node = current.admission.nodes[old.syntax] + let owned = try ownedRange(value, container: node, index: index) + let expression = current.admission.nodes[value.syntax].range + let leading = current.source.spelling(owned.lowerBound..= expression.upperBound + && $0.range.upperBound <= owned.upperBound + } + let beforeComma = + comma.map { current.source.spelling(expression.upperBound..<$0.range.lowerBound) } ?? "" + let afterComma = current.source.spelling( + (comma?.range.upperBound ?? expression.upperBound).. index ? destination - 1 : destination + let count = current.values[refreshed]?.elementsForUse.count ?? 0 + let insertion: InsertionPosition + if adjusted == 0 { + insertion = .first + } else if adjusted == count { + insertion = .last + } else { + // Use a current local anchor for the internal move only. + try insertAtIndex(value.value, pointer: refreshed, index: adjusted, carried: carried) + return + } + try insert(value.value, into: refreshed, at: insertion, carried: carried) + } + + func insertAtIndex( + _ value: ConstructionValue, pointer: String, index: Int, carried: CarriedElement + ) throws { + // A direct byte anchor avoids manufacturing a public snapshot handle. + let collection = try direct(pointer) + let node = current.admission.nodes[collection.syntax] + let owned = try ownedRange(collection.elementsForUse[index], container: node, index: index) + let (style, indentation) = try style(at: node.range) + let multiline = hasNewline(node.range) + try patch( + owned.lowerBound.. String + { + // Removing a root component cannot move a group definition, and group moves never nest groups. + if let value = current.values[pointer], value.type == previous.type { return pointer } + throw fail("manifest.edit.stale", "destination container changed during move") + } + + func dictionary(_ pointer: String, key: String, value replacement: StaticValue?) throws { + let value = try direct(pointer) + if value.type == .named("ConfigurationValue"), value.value.member == "object" { + try dictionary(pointer + "/value", key: key, value: replacement) + return + } + let node = current.admission.nodes[value.syntax] + guard node.kind == .dictionary, case .dictionary(let elementType) = value.type.unwrapped, + case .object(var fields) = value.value + else { throw fail("manifest.edit.readOnly", "target is not a direct dictionary") } + if let replacement { + let replacementValue = try contextualValue(replacement, as: elementType) + if node.keys.contains(where: { $0.decoded == key }) { + let childPointer = pointer + "/" + pointerEscape(key) + try replace(childPointer, with: replacementValue) + return + } + let close = node.range.upperBound - 1 + let (style, indentation) = try style(at: node.range) + let text = + quoted(key) + ": " + + CanonicalPrinter(style: style).render( + replacementValue, indentation: indentation + style.indent) + let multiline = hasNewline(node.range) + if node.children.isEmpty { + let interior = (node.range.lowerBound + 1)..= end && $0.range.upperBound <= close + } + if multiline { + let at = comma?.range.upperBound ?? end + try patch( + at..= childEnd && $0.range.upperBound <= range.upperBound + } + var patches = [SourcePatch(range: range, replacement: [])] + if !hasComma && index > 0 { + let previous = current.admission.nodes[node.children[index - 1]].range.upperBound + guard + let comma = current.admission.tokens.last(where: { + $0.text == "," && $0.range.lowerBound >= previous + && $0.range.upperBound <= range.lowerBound + }) + else { throw fail("manifest.edit.readOnly", "dictionary separator is ambiguous") } + patches.append(SourcePatch(range: comma.range, replacement: [])) + } + for patch in patches.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { + try self.patch(patch.range, bytes: patch.replacement) + } + fields.removeValue(forKey: key) + if fields.isEmpty { + // The colon is necessary even if retained container whitespace/comments remain. + let opener = node.range.lowerBound + 1 + try patch(opener.. ConstructionValue + { + try charge(1) + if old == new { return expected } + switch (old, new, expected) { + case (.array(let a), .array(let b), .array(let e)) + where a.count == b.count && a.count == e.count: + return .array(try a.indices.map { try merge(a[$0], b[$0], e[$0]) }) + case (.node(let t, let m, let a), .node(let nt, let nm, let b), .node(_, _, let e)) + where t == nt && m == nm && a.keys == b.keys && a.keys == e.keys: + var result = e + for key in a.keys { result[key] = try merge(a[key]!, b[key]!, e[key]!) } + return .node(type: t, member: m, fields: result) + case (.object(let a), .object(let b), .object(let e)) + where a.keys == b.keys && a.keys == e.keys: + var result = e + for key in a.keys { result[key] = try merge(a[key]!, b[key]!, e[key]!) } + return .object(result) + default: return new + } + } + expected = try merge(current.evaluation.root.value, altered.root.value, expected) + impacted += uses + try patch(range, replacementText(replacementValue, at: range)) + if let declaration = current.admission.declarations.first(where: { $0.name == name }), + declaration.type == nil, + needsContext(replacementValue, type: old.type) + { + let offset = declaration.nameRange.upperBound + try patch(offset.. Bool { + switch (value, type) { + case (.text, .named("String")), (.integer, .named("Int")), (.boolean, .named("Bool")): + return false + case (.node(let type, _, _), _) where type == "Agents": return false + case (.array(let values), .array(let element)): + return values.first.map { needsContext($0, type: element) } ?? true + case (.object(let fields), .dictionary(let element)): + return fields.keys.sorted(by: utf8Less).first.map { needsContext(fields[$0]!, type: element) } + ?? true + default: return true + } + } + + func typeSpelling(_ type: ConstructionType) throws -> String { + switch type { + case .untyped: throw fail("manifest.edit.readOnly", "value has no construction type") + case .named(let name): return name + case .array(let element): return "[" + (try typeSpelling(element)) + "]" + case .dictionary(let element): return "[String: " + (try typeSpelling(element)) + "]" + case .optional(let element): return try typeSpelling(element) + } + } +} diff --git a/Sources/AgentsManifest/DocumentModels.swift b/Sources/AgentsManifest/DocumentModels.swift index f7222c9..243e6cf 100644 --- a/Sources/AgentsManifest/DocumentModels.swift +++ b/Sources/AgentsManifest/DocumentModels.swift @@ -40,7 +40,7 @@ public struct StaticValue: Sendable { Self(value, type) } - public static var null: Self { Self(.none, .named(""), literal: true) } + public static var null: Self { Self(.none, .untyped, literal: true) } public static func string(_ value: String) -> Self { Self(.text(value), .named("String"), literal: true) @@ -51,93 +51,6 @@ public struct StaticValue: Sendable { public static func boolean(_ value: Bool) -> Self { Self(.boolean(value), .named("Bool"), literal: true) } - public static func configuration(_ value: ConfigurationValue) -> Self { - Self(value.constructionValue, .named("ConfigurationValue")) - } - public static func component(_ value: Component) -> Self { - Self(value.constructionValue, .named("Component")) - } - public static func source(_ value: Source) -> Self { - Self(value.constructionValue, .named("Source")) - } - public static func section(_ value: SectionReference) -> Self { - Self(value.constructionValue, .named("SectionReference")) - } - public static func groupReference(_ value: GroupReference) -> Self { - Self(value.constructionValue, .named("GroupReference")) - } - public static func version(_ value: Version) -> Self { - Self(value.constructionValue, .named("Version")) - } - public static func runtime(_ value: RuntimeValue) -> Self { - Self(value.constructionValue, .named("RuntimeValue")) - } - public static func condition(_ value: Condition) -> Self { - Self(value.constructionValue, .named("Condition")) - } - public static func selection(_ value: AgentsDescription.SkillSelection) -> Self { - Self(value.constructionValue, .named("SkillSelection")) - } - public static func skillOverride(_ value: AgentsDescription.SkillOverride) -> Self { - Self(value.constructionValue, .named("SkillOverride")) - } - public static func prompt(_ value: ChatGPTPrompt) -> Self { - Self(value.constructionValue, .named("ChatGPTPrompt")) - } - public static func resource(_ value: Resource) -> Self { - Self(value.constructionValue, .named("Resource")) - } - public static func promptContent(_ value: PromptContent) -> Self { - Self(value.constructionValue, .named("PromptContent")) - } - public static func executable(_ value: ExecutableInvocation) -> Self { - Self(value.constructionValue, .named("ExecutableInvocation")) - } - public static func transport(_ value: MCPTransport) -> Self { - Self(value.constructionValue, .named("MCPTransport")) - } - public static func parameter(_ value: PromptParameter) -> Self { - Self(value.constructionValue, .named("PromptParameter")) - } - public static func permissionRule(_ value: PermissionRule) -> Self { - Self(value.constructionValue, .named("PermissionRule")) - } - public static func agent(_ value: Agent) -> Self { - Self(value.constructionValue, .named("Agent")) - } - public static func scope(_ value: Scope) -> Self { - Self(value.constructionValue, .named("Scope")) - } - public static func platform(_ value: Platform) -> Self { - Self(value.constructionValue, .named("Platform")) - } - public static func installMode(_ value: AgentsDescription.InstallMode) -> Self { - Self(value.constructionValue, .named("InstallMode")) - } - public static func hookEvent(_ value: HookEvent) -> Self { - Self(value.constructionValue, .named("HookEvent")) - } - public static func permissionOperation(_ value: PermissionOperation) -> Self { - Self(value.constructionValue, .named("PermissionOperation")) - } - public static func ignorePurpose(_ value: IgnorePurpose) -> Self { - Self(value.constructionValue, .named("IgnorePurpose")) - } - public static func pluginMode(_ value: PluginMode) -> Self { - Self(value.constructionValue, .named("PluginMode")) - } - public static func componentKind(_ value: ComponentKind) -> Self { - Self(value.constructionValue, .named("ComponentKind")) - } - public static func componentReference(_ value: ComponentReference) -> Self { - Self(value.constructionValue, .named("ComponentReference")) - } - public static func group(_ value: ComponentGroup) -> Self { - Self(value.constructionValue, .named("ComponentGroup")) - } - public static func agents(_ value: Agents) -> Self { - Self(value.constructionValue, .named("Agents")) - } public static func array(_ values: [StaticValue]) -> Self { Self(.array(values.map(\.value)), .array(values.first?.type ?? .named("String")), literal: true) } diff --git a/Sources/AgentsManifest/DocumentStyle.swift b/Sources/AgentsManifest/DocumentStyle.swift new file mode 100644 index 0000000..e613144 --- /dev/null +++ b/Sources/AgentsManifest/DocumentStyle.swift @@ -0,0 +1,82 @@ +import AgentsCore +import AgentsDescription +import Foundation + +extension DocumentEditor { + func style(at range: Range) throws -> (PrintStyle, String) { + try charge(current.admission.nodes.count) + let bytes = current.bytes + var endings = Set() + var cursor = 0 + while cursor < bytes.count { + if bytes[cursor] == UInt8(ascii: "\r") { + if cursor + 1 < bytes.count && bytes[cursor + 1] == UInt8(ascii: "\n") { + endings.insert("\r\n") + cursor += 1 + } else { + endings.insert("\r") + } + } else if bytes[cursor] == UInt8(ascii: "\n") { + endings.insert("\n") + } + cursor += 1 + } + guard endings.count <= 1 else { + throw fail("manifest.edit.readOnly", "conflicting newline styles", range: range) + } + let indentation = indentation(at: range.lowerBound) + let candidates = current.admission.nodes.filter { node in + [.array, .dictionary, .call].contains(node.kind) + && node.range.lowerBound <= range.lowerBound && node.range.upperBound >= range.upperBound + } + var unit: String? + var trailingComma = true + for container in candidates.sorted(by: { $0.range.count < $1.range.count }) { + var units = Set() + let base = self.indentation(at: container.range.lowerBound) + let offsets = + container.kind == .dictionary + ? container.keys.map { $0.range.lowerBound } + : container.kind == .array + ? container.children.map { current.admission.nodes[$0].range.lowerBound } + : container.arguments.map { + $0.labelRange?.lowerBound ?? current.admission.nodes[$0.value].range.lowerBound + } + for offset in offsets { + let start = lineStart(offset) + let prefix = current.source.spelling(start.. base.count else { + throw fail("manifest.edit.readOnly", "conflicting local indentation", range: range) + } + units.insert(String(prefix.dropFirst(base.count))) + } + guard units.count <= 1 else { + throw fail("manifest.edit.readOnly", "conflicting local indentation", range: range) + } + if let evidence = units.first { + unit = evidence + break + } + } + for container in candidates.sorted(by: { $0.range.count < $1.range.count }) + where container.kind == .array || container.kind == .dictionary { + guard let last = container.children.last, + let token = current.admission.tokens.first(where: { + $0.range.lowerBound >= current.admission.nodes[last].range.upperBound + }) + else { continue } + trailingComma = token.text == "," + break + } + return ( + PrintStyle( + indent: unit ?? " ", newline: endings.first ?? "\n", trailingComma: trailingComma), + indentation + ) + } + + func indentation(at offset: Int) -> String { + String(current.source.spelling(lineStart(offset)..) -> Bool { + current.admission.comments.contains { + $0.lowerBound >= range.lowerBound && $0.upperBound <= range.upperBound + } + } + + func lineStart(_ offset: Int) -> Int { + var result = offset + while result > 0 && current.bytes[result - 1] != UInt8(ascii: "\n") + && current.bytes[result - 1] != UInt8(ascii: "\r") + { + result -= 1 + } + return result + } + + func lineEnd(_ offset: Int) -> Int { + var result = offset + while result < current.bytes.count && current.bytes[result] != UInt8(ascii: "\n") + && current.bytes[result] != UInt8(ascii: "\r") + { result += 1 } + return result + } + + func blankLine(_ range: Range) -> Bool { + let normalized = current.source.spelling(range).replacingOccurrences(of: "\r\n", with: "\n") + .replacingOccurrences(of: "\r", with: "\n") + return normalized.split(separator: "\n", omittingEmptySubsequences: false).dropFirst() + .dropLast().contains { $0.allSatisfy { $0 == " " || $0 == "\t" } } + } + + /// Own contiguous leading comment lines and same-line trailing comments, stopping + /// at blank lines and sibling boundaries. The separator and line ending travel together. + func ownedRange(_ value: EvaluatedValue, container: GrammarNode, index: Int) throws + -> Range + { + let expressionRange = current.admission.nodes[value.syntax].range + let range = + container.kind == .dictionary + ? container.keys[index].range.lowerBound..= previous && $0.upperBound <= start + } + for comment in preceding.reversed() { + if blankLine(comment.upperBound..= previous, + current.bytes[line..= previous + && current.bytes[line..= end && $0.range.upperBound <= next + } + if let comma { end = comma.range.upperBound } + for comment in current.admission.comments + where comment.lowerBound >= range.upperBound && comment.upperBound <= next { + if comment.lowerBound <= (comma?.range.lowerBound ?? range.upperBound) + || lineStart(comment.lowerBound) == lineStart(end) + { + end = max(end, comment.upperBound) + } + } + let ending = lineEnd(end) + if start == lineStart(start), ending <= next, + current.bytes[end..) -> Bool { + current.bytes[range].contains(UInt8(ascii: "\n")) + || current.bytes[range].contains(UInt8(ascii: "\r")) + } +} + +/// Relative indentation is carried with the element; the destination supplies the +/// common prefix and line ending. Empty lines stay empty, including inside strings. +struct CarriedElement { + let text: String + let indentation: String + + var isMultiline: Bool { text.contains("\n") || text.contains("\r") } + + func render(indentation target: String, newline: String) -> String { + let bytes = Array(text.utf8) + var lines: [String] = [] + var start = 0 + while start < bytes.count { + var end = start + while end < bytes.count && bytes[end] != UInt8(ascii: "\n") + && bytes[end] != UInt8(ascii: "\r") + { end += 1 } + let line = String(decoding: bytes[start.. [ManifestDiagnostic] { + func validate() throws -> [ManifestDiagnostic] { let root = evaluation.root let fields = root.value.fields var identities: [String: EvaluatedValue] = [:] @@ -48,14 +48,14 @@ package final class DomainValidator { if declaration.gitURL != url { let target = value.field("url") ?? value let range = admission.nodes[target.syntax].range - if diagnostics.count < 100 { + if diagnostics.count < ManifestLimits.Diagnostics.warnings { diagnostics.append( ManifestDiagnostic( code: "manifest.domain", severity: .warning, message: "use the complete Git transport URL", span: source.span(range), fixIt: SourcePatch( range: range, replacement: Array(quoted(declaration.gitURL).utf8)))) - } else if diagnostics.count == 100 { + } else if diagnostics.count == ManifestLimits.Diagnostics.warnings { diagnostics.append( ManifestDiagnostic( code: "manifest.diagnostics.truncated", severity: .warning, @@ -106,7 +106,9 @@ package final class DomainValidator { var pending = [(value, anchor)] while let (value, anchor) = pending.popLast() { work += 1 - if work > 100_000 { throw failure("domain traversal budget", anchor, code: "manifest.limit") } + if work > ManifestLimits.Domain.steps { + throw failure("domain traversal budget", anchor, code: "manifest.limit") + } if let referent = value.referent { pending.append((referent, value)) continue @@ -132,7 +134,9 @@ package final class DomainValidator { } for child in children { work += 1 - if work > 100_000 { throw failure("domain traversal budget", anchor, code: "manifest.limit") } + if work > ManifestLimits.Domain.steps { + throw failure("domain traversal budget", anchor, code: "manifest.limit") + } try check(child, at: anchor) try checkChildren(child, at: anchor) } @@ -180,6 +184,9 @@ package final class DomainValidator { } } } + case "SkillSelection": + if let names = f["names"]?.strings { try skillNames(names, anchor) } + case "SkillOverride": try skillNames([f["name"]?.text ?? ""], anchor) case "ComponentGroup": try name(f["name"]?.text ?? "", anchor) case "GroupReference": let group = f["name"]?.text ?? "" @@ -244,13 +251,11 @@ package final class DomainValidator { try sourceAlias(alias, anchor) let selection = f["select"]! let names = selection.fields["names"]?.strings - if let names { try skillNames(names, anchor) } try skillNames(f["exclude"]?.strings ?? [], anchor) let overrides = f["overrides"]?.array ?? [] try uniqueNames(overrides, anchor) for override in overrides { let n = override.fields["name"]?.text ?? "" - try skillNames([n], anchor) if let names, !names.contains(n) { throw failure("override is outside explicit skill selection", anchor) } @@ -309,11 +314,11 @@ package final class DomainValidator { while i < bytes.count { if bytes[i...].starts(with: escapedInput) { i += 2 - while i < bytes.count && bytes[i] != 125 { i += 1 } + while i < bytes.count && bytes[i] != UInt8(ascii: "}") { i += 1 } } else if bytes[i...].starts(with: input) { let first = i + 8 i = first - while i < bytes.count && bytes[i] != 125 { i += 1 } + while i < bytes.count && bytes[i] != UInt8(ascii: "}") { i += 1 } if i == bytes.count || !declared.contains(String(decoding: bytes[first.. EvaluatedValue? { referent?.field(name) ?? fields[name] } -} diff --git a/Sources/AgentsManifest/EvaluatedValue.swift b/Sources/AgentsManifest/EvaluatedValue.swift new file mode 100644 index 0000000..f877939 --- /dev/null +++ b/Sources/AgentsManifest/EvaluatedValue.swift @@ -0,0 +1,44 @@ +import AgentsDescription + +final class EvaluatedValue: Sendable { + enum Representation: Sendable { + case scalarLiteral, collectionLiteral, construction, reference, synthetic + } + let representation: Representation + let type: ConstructionType + let value: ConstructionValue + let cost: ValueCost + let syntax: Int + let fields: [String: EvaluatedValue] + let elements: [EvaluatedValue] + let referent: EvaluatedValue? + let defaulted: Bool + let referenceDepth: Int + + init( + type: ConstructionType, value: ConstructionValue, cost: ValueCost, syntax: Int, + fields: [String: EvaluatedValue] = [:], elements: [EvaluatedValue] = [], + referent: EvaluatedValue? = nil, defaulted: Bool = false, + representation: Representation = .construction + ) { + self.representation = representation + self.type = type + self.value = value + self.cost = cost + self.syntax = syntax + self.fields = fields + self.elements = elements + self.referent = referent + self.defaulted = defaulted + referenceDepth = (referent?.referenceDepth ?? 0) + (referent == nil ? 0 : 1) + } +} + +extension EvaluatedValue { + var elementsForUse: [EvaluatedValue] { + var value = self + while let next = value.referent { value = next } + return value.elements + } + func field(_ name: String) -> EvaluatedValue? { referent?.field(name) ?? fields[name] } +} diff --git a/Sources/AgentsManifest/Evaluation.swift b/Sources/AgentsManifest/Evaluation.swift index 2cc5f0a..476cacd 100644 --- a/Sources/AgentsManifest/Evaluation.swift +++ b/Sources/AgentsManifest/Evaluation.swift @@ -1,15 +1,15 @@ import AgentsDescription -package struct Evaluation: Sendable { - package let root: EvaluatedValue - package let constants: [String: EvaluatedValue] - package let expressions: [Int: EvaluatedValue] - package let references: [String: [Int]] - package let steps: Int - package let total: ValueCost +struct Evaluation: Sendable { + let root: EvaluatedValue + let constants: [String: EvaluatedValue] + let expressions: [Int: EvaluatedValue] + let references: [String: [Int]] + let steps: Int + let total: ValueCost } -package final class Evaluator { +final class Evaluator { private let source: SourceText private let admission: Admission private let replacements: [String: StaticValue] @@ -20,8 +20,7 @@ package final class Evaluator { private var frames = 0 private var total = ValueCost(nodes: 0, strings: 0, encoded: 0, depth: 0, origins: 0) - package init(source: SourceText, admission: Admission, replacements: [String: StaticValue] = [:]) - { + init(source: SourceText, admission: Admission, replacements: [String: StaticValue] = [:]) { self.source = source self.admission = admission self.replacements = replacements @@ -33,7 +32,7 @@ package final class Evaluator { ) } private func charge(_ amount: Int = 1, at id: Int) throws { - guard amount <= 100_000 - steps else { + guard amount <= ManifestLimits.Evaluation.steps - steps else { throw fail("manifest.limit", "evaluation work steps", id) } steps += amount @@ -44,7 +43,7 @@ package final class Evaluator { } } - package func evaluate() throws -> Evaluation { + func evaluate() throws -> Evaluation { for declaration in admission.declarations { if constants[declaration.name] != nil || Vocabulary.typeNames.contains(declaration.name) { throw source.failure( @@ -74,7 +73,7 @@ package final class Evaluator { } guard let root = constants["agents"], root.type == .named("Agents"), let declaration = admission.declarations.first(where: { $0.name == "agents" }), - admission.nodes[declaration.expression].kind == "call", + admission.nodes[declaration.expression].kind == .call, admission.nodes[declaration.expression].text == "Agents" else { throw source.failure( @@ -89,36 +88,39 @@ package final class Evaluator { try charge(at: id) frames += 1 defer { frames -= 1 } - guard frames <= 64 else { throw fail("manifest.limit", "evaluation frames", id) } + guard frames <= ManifestLimits.Evaluation.frames else { + throw fail("manifest.limit", "evaluation frames", id) + } let node = admission.nodes[id] let expected = context?.unwrapped let result: EvaluatedValue - if node.kind == "nil", case .optional = context { + if node.kind == .nilLiteral, case .optional = context { result = EvaluatedValue(type: context!, value: .none, cost: ValueCost(), syntax: id) } else { switch node.kind { - case "group": + case .group: let child = try evaluate(node.children[0], context: context) result = EvaluatedValue( - type: child.type, value: child.value, cost: child.cost, syntax: id, referent: child) - case "string": + type: child.type, value: child.value, cost: child.cost, syntax: id, referent: child, + representation: .reference) + case .string: result = try literal( - .text(node.text), kind: "string", inferred: "String", context: expected, id: id) - case "integer", "negative": - let raw = (node.kind == "negative" ? "-" : "") + node.text.filter { $0 != "_" } + .text(node.text), inferred: .named("String"), context: expected, id: id) + case .integer, .negative: + let raw = (node.kind == .negative ? "-" : "") + node.text.filter { $0 != "_" } guard let integer = Int(raw) else { throw fail("manifest.type", "integer literal must fit signed 64-bit Int", id) } result = try literal( - .integer(integer), kind: "integer", inferred: "Int", context: expected, id: id) - case "boolean": + .integer(integer), inferred: .named("Int"), context: expected, id: id) + case .boolean: result = try literal( - .boolean(node.text == "true"), kind: "boolean", inferred: "Bool", context: expected, + .boolean(node.text == "true"), inferred: .named("Bool"), context: expected, id: id) - case "nil": - result = try literal(.none, kind: "nil", inferred: "", context: expected, id: id) - case "array", "dictionary": result = try collection(id, context: expected) - case "sequence": + case .nilLiteral: + result = try literal(.none, inferred: .untyped, context: expected, id: id) + case .array, .dictionary: result = try collection(id, context: expected) + case .sequence: var arrayType = expected if let expected, case .array = expected { } else if expected != nil { @@ -134,7 +136,9 @@ package final class Evaluator { } arrayType = value.type count += value.elementsForUse.count - if count > 10_000 { throw fail("manifest.limit", "concatenation entries", id) } + if count > ManifestLimits.Values.entries { + throw fail("manifest.limit", "concatenation entries", id) + } // Cost is combined before copying any concatenated elements. operands.append(value) costs.append(contentsOf: value.elementsForUse.map(\.cost)) @@ -146,7 +150,7 @@ package final class Evaluator { result = EvaluatedValue( type: arrayType!, value: .array(elements.map(\.value)), cost: cost, syntax: id, elements: elements) - case "range": + case .range: let lower = try evaluate(node.children[0], context: .named("Version")) let upper = try evaluate(node.children[1], context: .named("Version")) guard case .version(let l) = lower.value, case .version(let u) = upper.value, l < u else { @@ -157,13 +161,13 @@ package final class Evaluator { result = EvaluatedValue( type: .named("VersionRange"), value: .range(l..= 63 { + if bound.referenceDepth >= ManifestLimits.Evaluation.frames - 1 { throw fail("manifest.limit", "active reference frames", id) } references[node.text, default: []].append(id) @@ -171,11 +175,11 @@ package final class Evaluator { cost.origins = ValueCost.add(cost.origins, cost.nodes) try check(cost, at: id) result = EvaluatedValue( - type: bound.type, value: bound.value, cost: cost, syntax: id, referent: bound) + type: bound.type, value: bound.value, cost: cost, syntax: id, referent: bound, + representation: .reference) } else { result = try call(id, context: expected) } - default: throw fail("manifest.syntax", "unhandled admitted production", id) } } try check(result.cost, at: id) @@ -190,65 +194,34 @@ package final class Evaluator { } private func literal( - _ value: ConstructionValue, kind: String, inferred: String, context: ConstructionType?, id: Int + _ value: ConstructionValue, inferred: ConstructionType, context: ConstructionType?, id: Int ) throws -> EvaluatedValue { - let type = context ?? .named(inferred) + let type = context ?? inferred let converted: ConstructionValue - if type == .named(inferred), !inferred.isEmpty { - converted = value - } else if case .named(let name) = type, Vocabulary.literalTypes[name]?.contains(kind) == true { - switch name { - case "Version": - guard case .text(let text) = value else { - throw fail("manifest.type", "version requires a string literal", id) - } - let version = Version(stringLiteral: text) - guard version.valid else { throw fail("manifest.domain", "invalid semantic version", id) } - converted = .version(version) - case "SectionReference", "GroupReference": - converted = .node( - type: name, member: name == "SectionReference" ? "section" : "group", - fields: ["name": value, "source": .none, "condition": .none]) - case "PromptContent", "RuntimeValue": - converted = .node(type: name, member: "literal", fields: ["value": value]) - case "ConfigurationValue": - converted = .node( - type: name, member: kind == "nil" ? "null" : kind, - fields: kind == "nil" ? [:] : ["value": value]) - default: throw fail("manifest.type", "unsupported literal conversion", id) - } - } else { - throw fail("manifest.type", "literal needs a compatible context", id) + do { + converted = try LiteralConversion.convert(value, to: type) + } catch let error as LiteralConversionError { + throw fail(error.code, error.message, id) } return EvaluatedValue( - type: type, value: converted, cost: constructionCost(converted), syntax: id) + type: type, value: converted, cost: constructionCost(converted), syntax: id, + representation: .scalarLiteral) } private func collection(_ id: Int, context: ConstructionType?) throws -> EvaluatedValue { let node = admission.nodes[id] - let dictionary = node.kind == "dictionary" - if node.children.count > 10_000 { throw fail("manifest.limit", "collection entries", id) } - let wrapper: String? + let dictionary = node.kind == .dictionary + if node.children.count > ManifestLimits.Values.entries { + throw fail("manifest.limit", "collection entries", id) + } var elementType: ConstructionType? - switch context { - case .array(let type) where !dictionary: - elementType = type - wrapper = nil - case .dictionary(let type) where dictionary: - elementType = type - wrapper = nil - case .named("NativeConfiguration") where dictionary: - elementType = .dictionary(.named("ConfigurationValue")) - wrapper = nil - case .named("ConfigurationValue"): - elementType = .named("ConfigurationValue") - wrapper = "ConfigurationValue" - case .named("SkillSelection") where !dictionary: - elementType = .named("String") - wrapper = "SkillSelection" - case nil: wrapper = nil - default: throw fail("manifest.type", "collection is incompatible with contextual type", id) + do { + elementType = try LiteralConversion.elementType( + for: dictionary ? .dictionary : .array, context: context) + } catch let error as LiteralConversionError { + throw fail(error.code, error.message, id) } + let wrapped = context.map { if case .named = $0 { true } else { false } } ?? false var values: [EvaluatedValue] = [] var fields: [String: EvaluatedValue] = [:] var keySpans: [String: Range] = [:] @@ -273,7 +246,7 @@ package final class Evaluator { } var cost = ValueCost.container( values.map(\.cost), keys: dictionary ? node.keys.map { $0.decoded! } : []) - if wrapper != nil { + if wrapped { cost.nodes += 1 cost.depth += 1 cost.encoded += 32 @@ -281,21 +254,17 @@ package final class Evaluator { try check(cost, at: id) let payload: ConstructionValue = dictionary ? .object(fields.mapValues(\.value)) : .array(values.map(\.value)) + let inferred: ConstructionType = dictionary ? .dictionary(elementType) : .array(elementType) + let type = context ?? inferred let value: ConstructionValue - let type: ConstructionType - if let wrapper { - type = .named(wrapper) - value = .node( - type: wrapper, - member: wrapper == "SkillSelection" ? "names" : (dictionary ? "object" : "array"), - fields: [wrapper == "SkillSelection" ? "names" : "value": payload]) - } else { - type = dictionary ? .dictionary(elementType) : .array(elementType) - value = payload + do { + value = try LiteralConversion.convert(payload, to: type) + } catch let error as LiteralConversionError { + throw fail(error.code, error.message, id) } return EvaluatedValue( type: type, value: value, cost: cost, syntax: id, fields: fields, - elements: dictionary ? [] : values) + elements: dictionary ? [] : values, representation: .collectionLiteral) } private func call(_ id: Int, context: ConstructionType?) throws -> EvaluatedValue { @@ -303,7 +272,7 @@ package final class Evaluator { let parts = node.text.split(separator: ".", omittingEmptySubsequences: false).map(String.init) let name: String let member: String - if node.text == "Agents", node.kind == "call" { + if node.text == "Agents", node.kind == .call { name = "Agents" member = "Agents" } else if parts.count == 2, parts[0].isEmpty { @@ -319,7 +288,7 @@ package final class Evaluator { throw fail("manifest.call", "unlisted call or member", id) } let candidates = Vocabulary.signatures.filter { - $0.type == name && $0.member == member && $0.callable == (node.kind == "call") + $0.type == name && $0.member == member && $0.callable == (node.kind == .call) } var match: ConstructionSignature? for signature in candidates { @@ -377,11 +346,3 @@ package final class Evaluator { return EvaluatedValue(type: .named(name), value: value, cost: cost, syntax: id, fields: fields) } } - -extension EvaluatedValue { - package var elementsForUse: [EvaluatedValue] { - var value = self - while let next = value.referent { value = next } - return value.elements - } -} diff --git a/Sources/AgentsManifest/JSONPointer.swift b/Sources/AgentsManifest/JSONPointer.swift new file mode 100644 index 0000000..53e8d03 --- /dev/null +++ b/Sources/AgentsManifest/JSONPointer.swift @@ -0,0 +1,17 @@ +import Foundation + +/// JSON Pointer segments escape tilde before slash; decoding reverses that order. +func pointerEscape(_ text: String) -> String { + text.replacingOccurrences(of: "~", with: "~0").replacingOccurrences(of: "/", with: "~1") +} + +func pointerUnescape(_ text: String) -> String { + text.replacingOccurrences(of: "~1", with: "/").replacingOccurrences(of: "~0", with: "~") +} + +func pointerSegments(_ pointer: String) -> [String] { + guard !pointer.isEmpty else { return [] } + return pointer.split(separator: "/", omittingEmptySubsequences: false).dropFirst().map { + pointerUnescape(String($0)) + } +} diff --git a/Sources/AgentsManifest/LiteralConversion.swift b/Sources/AgentsManifest/LiteralConversion.swift new file mode 100644 index 0000000..0bb7d81 --- /dev/null +++ b/Sources/AgentsManifest/LiteralConversion.swift @@ -0,0 +1,77 @@ +import AgentsDescription + +enum LiteralConversionError: Error { + case incompatible, invalidVersion + + var code: String { self == .invalidVersion ? "manifest.domain" : "manifest.type" } + var message: String { + self == .invalidVersion ? "invalid semantic version" : "literal needs a compatible context" + } +} + +/// Closed literal conversions shared by static evaluation and domain edits. +/// Already constructed children keep their type; referenced expressions never enter this algebra. +enum LiteralConversion { + static func kind(of value: ConstructionValue) -> LiteralKind? { + switch value { + case .text: .string + case .integer: .integer + case .boolean: .boolean + case .none: .nilLiteral + case .array: .array + case .object: .dictionary + default: nil + } + } + + static func elementType( + for kind: LiteralKind, context: ConstructionType? + ) throws -> ConstructionType? { + guard let context = context?.unwrapped else { return nil } + let payload: ConstructionType + if case .named(let name) = context { + guard let type = Vocabulary.literalConstructions[name]?[kind]?.payloadType else { + throw LiteralConversionError.incompatible + } + payload = type + } else { + payload = context + } + switch (kind, payload) { + case (.array, .array(let element)), (.dictionary, .dictionary(let element)): return element + default: throw LiteralConversionError.incompatible + } + } + + static func convert( + _ value: ConstructionValue, to context: ConstructionType, + charge: () throws -> Void = {} + ) throws -> ConstructionValue { + try charge() + if case .optional(let wrapped) = context { + return value == .none ? .none : try convert(value, to: wrapped, charge: charge) + } + switch (value, context) { + case (.text, .named("String")), (.integer, .named("Int")), (.boolean, .named("Bool")): + return value + case (.node(let type, _, _), .named(let expected)) where type == expected: return value + case (.array(let values), .array(let element)): + return .array(try values.map { try convert($0, to: element, charge: charge) }) + case (.object(let fields), .dictionary(let element)): + return .object(try fields.mapValues { try convert($0, to: element, charge: charge) }) + case (.text(let text), .named("Version")): + let version = Version(stringLiteral: text) + guard version.valid else { throw LiteralConversionError.invalidVersion } + return .version(version) + default: break + } + guard case .named(let name) = context, let kind = kind(of: value), + let construction = Vocabulary.literalConstructions[name]?[kind] + else { throw LiteralConversionError.incompatible } + var fields = construction.defaults + if let key = construction.payload, let type = construction.payloadType { + fields[key] = try convert(value, to: type, charge: charge) + } + return .node(type: name, member: construction.member, fields: fields) + } +} diff --git a/Sources/AgentsManifest/Lowering.swift b/Sources/AgentsManifest/Lowering.swift index d176c05..89b46dc 100644 --- a/Sources/AgentsManifest/Lowering.swift +++ b/Sources/AgentsManifest/Lowering.swift @@ -35,15 +35,8 @@ package enum Lowering { case .array(let values): return .array(values.map(lower)) case .object(let fields): return .dictionary(fields.mapValues(lower)) case .node(let type, let member, let fields): - let scalarEnums: Set = [ - "Agent", "Scope", "Platform", "InstallMode", "IgnorePurpose", "PluginMode", "ComponentKind", - ] - if scalarEnums.contains(type) { - let ids = [ - "claudeCode": "claude-code", "geminiCLI": "gemini-cli", "openCode": "opencode", - "macOS": "macos", - ] - return .string(ids[member] ?? member) + if let spelling = Vocabulary.scalarValues[type]?[member] { + return .string(spelling) } if type == "SkillSelection" { return member == "all" ? .string("all") : .array((fields["names"]?.array ?? []).map(lower)) diff --git a/Sources/AgentsManifest/ManifestDiagnostic.swift b/Sources/AgentsManifest/ManifestDiagnostic.swift index baa4c57..a4e7275 100644 --- a/Sources/AgentsManifest/ManifestDiagnostic.swift +++ b/Sources/AgentsManifest/ManifestDiagnostic.swift @@ -24,10 +24,15 @@ public struct ManifestDiagnostic: Sendable, Equatable { public struct ManifestFailure: Error, Sendable { public let diagnostics: [ManifestDiagnostic] - public let metrics: FrontEndMetrics - package init(_ diagnostic: ManifestDiagnostic, metrics: FrontEndMetrics = FrontEndMetrics()) { + package let metrics: FrontEndMetrics + package let stage: FrontEndStage + package init( + _ diagnostic: ManifestDiagnostic, metrics: FrontEndMetrics = FrontEndMetrics(), + stage: FrontEndStage = .admission + ) { diagnostics = [diagnostic] self.metrics = metrics + self.stage = stage } } @@ -40,70 +45,23 @@ public struct SourcePatch: Sendable, Equatable { } } -public struct FrontEndMetrics: Sendable, Codable { - public package(set) var parserCalls = 0 - public package(set) var tokens = 0 - public package(set) var syntaxReservation = 0 - public package(set) var syntaxNodes = 0 - public package(set) var syntaxDepth = 0 - public package(set) var evaluationSteps = 0 - public package(set) var expandedNodes = 0 - public package(set) var decodedBytes = 0 - public package(set) var admissionSeconds = 0.0 - public package(set) var parsingSeconds = 0.0 - public package(set) var guardSeconds = 0.0 - public package(set) var inspectionSeconds = 0.0 - public package(set) var evaluationSeconds = 0.0 - public package(set) var domainSeconds = 0.0 - public package(set) var loweringSeconds = 0.0 - public package(set) var sourceMapSeconds = 0.0 - public package(set) var teardownSeconds = 0.0 - public init() {} -} - -package struct SourceText: Sendable { - package let bytes: [UInt8] - package let identity: DocumentIdentity - private let lines: [Int] - - package init(_ bytes: [UInt8], identity: DocumentIdentity) { - self.bytes = bytes - self.identity = identity - var starts = [0] - var i = 0 - while i < min(bytes.count, 2_097_153) { - if bytes[i] == 13 { - if i + 1 < bytes.count && bytes[i + 1] == 10 { i += 1 } - starts.append(i + 1) - } else if bytes[i] == 10 { - starts.append(i + 1) - } - i += 1 - } - lines = starts - } - - package func span(_ range: Range) -> SourceSpan { - let start = min(max(0, range.lowerBound), bytes.count) - var lo = 0 - var hi = lines.count - while lo + 1 < hi { - let mid = (lo + hi) / 2 - if lines[mid] <= start { lo = mid } else { hi = mid } - } - return SourceSpan( - document: identity, start: start, end: min(max(start, range.upperBound), bytes.count), - line: lo + 1, column: start - lines[lo] + 1) - } - - package func failure(_ code: String, _ message: String, _ offset: Int, end: Int? = nil) - -> ManifestFailure - { - ManifestFailure( - ManifestDiagnostic(code: code, message: message, span: span(offset..<(end ?? offset)))) - } - - package func spelling(_ range: Range) -> String { - String(decoding: bytes[range], as: UTF8.self) - } +package struct FrontEndMetrics: Sendable, Codable { + package var parserCalls = 0 + package var tokens = 0 + package var syntaxReservation = 0 + package var syntaxNodes = 0 + package var syntaxDepth = 0 + package var evaluationSteps = 0 + package var expandedNodes = 0 + package var decodedBytes = 0 + package var admissionSeconds = 0.0 + package var parsingSeconds = 0.0 + package var guardSeconds = 0.0 + package var inspectionSeconds = 0.0 + package var evaluationSeconds = 0.0 + package var domainSeconds = 0.0 + package var loweringSeconds = 0.0 + package var sourceMapSeconds = 0.0 + package var teardownSeconds = 0.0 + package init() {} } diff --git a/Sources/AgentsManifest/ManifestFrontEnd.swift b/Sources/AgentsManifest/ManifestFrontEnd.swift new file mode 100644 index 0000000..bf67013 --- /dev/null +++ b/Sources/AgentsManifest/ManifestFrontEnd.swift @@ -0,0 +1,108 @@ +import AgentsCore +import AgentsDescription +import Foundation +import SwiftSyntax + +package enum FrontEndStage: String, Sendable, Codable { + case admission, parser, evaluation, domain, lowering, sourceMap, teardown, complete, editing +} + +package enum FrontEndCheck: Sendable, Equatable { + case syntax, declaration +} + +struct FrontEndDeclaration { + let evaluation: Evaluation + let ir: DeclarationIR + let diagnostics: [ManifestDiagnostic] + let digest: String + let map: BuiltMap +} + +struct FrontEndResult { + let source: SourceText + let admission: Admission + let syntax: SourceFileSyntax + let declaration: FrontEndDeclaration? + let metrics: FrontEndMetrics +} + +/// Owns phase ordering for document construction and bounded syntax inspection. +/// Observers receive phase-entry metrics; failures retain the phase and work already done. +enum ManifestFrontEnd { + static func run( + bytes: [UInt8], identity: DocumentIdentity, checking: FrontEndCheck, + validateDomain: Bool = true, observe: ((FrontEndStage, FrontEndMetrics) -> Void)? = nil + ) throws -> FrontEndResult { + let clock = ContinuousClock() + var stage = FrontEndStage.admission + var stageStart = clock.now + var metrics = FrontEndMetrics() + let source = SourceText(Array(bytes.prefix(ManifestLimits.Input.bytes + 1)), identity: identity) + func enter(_ next: FrontEndStage) { + stage = next + stageStart = clock.now + var progress = metrics + if next == .parser { progress.parserCalls += 1 } + observe?(next, progress) + } + enter(.admission) + do { + if bytes.count > ManifestLimits.Input.bytes { + throw source.failure("manifest.limit", "input byte limit", ManifestLimits.Input.bytes) + } + let admission = try Recognizer(source: source).recognize() + metrics.admissionSeconds = seconds(stageStart.duration(to: clock.now)) + metrics.tokens = admission.tokens.count + metrics.syntaxReservation = admission.reservation + enter(.parser) + let checked = try SyntaxValidation.parse(source, admission: admission, metrics: metrics) + metrics = checked.metrics + if checking == .syntax { + return FrontEndResult( + source: source, admission: admission, syntax: checked.tree, declaration: nil, + metrics: metrics) + } + enter(.evaluation) + let evaluation = try Evaluator(source: source, admission: admission).evaluate() + metrics.evaluationSeconds = seconds(stageStart.duration(to: clock.now)) + metrics.evaluationSteps = evaluation.steps + metrics.expandedNodes = evaluation.total.nodes + metrics.decodedBytes = evaluation.total.strings + enter(.domain) + let diagnostics = + validateDomain + ? try DomainValidator(source: source, admission: admission, evaluation: evaluation) + .validate() + : [] + metrics.domainSeconds = seconds(stageStart.duration(to: clock.now)) + enter(.lowering) + let ir = Lowering.declaration(evaluation.root.value) + metrics.loweringSeconds = seconds(stageStart.duration(to: clock.now)) + enter(.sourceMap) + let digest = "sha256:" + FileHash.sha256Hex(data: Data(bytes)) + let map = try MapBuilder(source: source, admission: admission, digest: digest).build( + evaluation) + metrics.sourceMapSeconds = seconds(stageStart.duration(to: clock.now)) + return FrontEndResult( + source: source, admission: admission, syntax: checked.tree, + declaration: FrontEndDeclaration( + evaluation: evaluation, ir: ir, diagnostics: diagnostics, digest: digest, map: map), + metrics: metrics) + } catch let failure as ManifestFailure { + let elapsed = seconds(stageStart.duration(to: clock.now)) + switch stage { + case .admission: + metrics = failure.metrics + metrics.admissionSeconds = elapsed + case .parser: metrics = failure.metrics + case .evaluation: metrics.evaluationSeconds = elapsed + case .domain: metrics.domainSeconds = elapsed + case .lowering: metrics.loweringSeconds = elapsed + case .sourceMap: metrics.sourceMapSeconds = elapsed + default: break + } + throw ManifestFailure(failure.diagnostics[0], metrics: metrics, stage: stage) + } + } +} diff --git a/Sources/AgentsManifest/ManifestLimits.swift b/Sources/AgentsManifest/ManifestLimits.swift new file mode 100644 index 0000000..60f52b1 --- /dev/null +++ b/Sources/AgentsManifest/ManifestLimits.swift @@ -0,0 +1,54 @@ +/// Language 1.0 front-end bounds, grouped by their owner in the manifest contract. +/// Counts are charged by occurrence, including unused definitions and repeated origins. +package enum ManifestLimits { + package enum Input { + package static let bytes = 2_097_152 + } + enum Admission { + static let tokens = 100_000 + static let syntaxReservation = 100_000 + static let reservationBase = 16 + static let reservationPerUnit = 4 + static let squareDepth = 8 + static let delimiterDepth = 20 + static let commentDepth = 20 + static let additiveTerms = 32 + } + enum Syntax { + static let parserNesting = 20 + static let depth = 128 + static let nodes = 100_000 + } + enum Evaluation { + static let frames = 64 + static let steps = 100_000 + } + enum Values { + static let nodes = 100_000 + static let stringBytes = 16_777_216 + static let entries = 10_000 + static let depth = 64 + } + enum Domain { + static let steps = 100_000 + } + enum Groups { + static let activeReferences = 64 + } + enum SourceMap { + static let locations = 100_000 + static let origins = 1_000_000 + static let encodedBytes = 16_777_216 + } + enum Output { + static let encodedBytes = 33_554_432 + } + enum Editing { + static let comparisonPairs = 200_000 + static let steps = 1_000_000 + static let requests = 100 + } + enum Diagnostics { + static let warnings = 100 + } +} diff --git a/Sources/AgentsManifest/MapBuilder.swift b/Sources/AgentsManifest/MapBuilder.swift new file mode 100644 index 0000000..d626ae5 --- /dev/null +++ b/Sources/AgentsManifest/MapBuilder.swift @@ -0,0 +1,213 @@ +import AgentsCore +import AgentsDescription + +struct BuiltMap { + var entries: [SourceMapEntry] = [] + var locations: [String: NodeID] = [:] + var values: [String: EvaluatedValue] = [:] +} + +final class MapBuilder { + private let source: SourceText + private let admission: Admission + private let digest: String + private var result = BuiltMap() + private var originCount = 0 + private var encodedBytes = 0 + + init(source: SourceText, admission: Admission, digest: String) { + self.source = source + self.admission = admission + self.digest = digest + } + + func build(_ evaluation: Evaluation) throws -> BuiltMap { + try append(evaluation.root, pointer: "", origins: [], use: nil) + // Constants are separately addressable; declaration locations remain language independent. + for (name, value) in evaluation.constants where name != "agents" { + let pointer = "/constants/" + pointerEscape(name) + result.locations[pointer] = NodeID(digest: digest, pointer: pointer, syntax: value.syntax) + result.values[pointer] = value + } + result.entries.sort { ($0.pointer, $0.span.start) < ($1.pointer, $1.span.start) } + return result + } + + private func append( + _ value: EvaluatedValue, pointer: String, origins: [SourceSpan], use: SourceSpan?, + ownOrigins: [SourceSpan] = [] + ) throws { + let range = admission.nodes[value.syntax].range + let span = use ?? source.span(range) + var inherited = origins + let definition = source.span(range) + if use != nil, definition != span, inherited.last != definition { inherited.append(definition) } + var resolved = value + while let next = resolved.referent { + inherited.append(source.span(admission.nodes[next.syntax].range)) + resolved = next + } + if value.referent != nil { + guard resolved.cost.nodes <= ManifestLimits.SourceMap.locations - result.entries.count, + value.cost.origins <= ManifestLimits.SourceMap.origins - originCount + else { + throw source.failure("manifest.limit", "reference source map expansion", range.lowerBound) + } + } + let recordedOrigins = inherited + ownOrigins + let estimate = + pointer.utf8.count + (source.identity.rawValue.utf8.count + 160) * (recordedOrigins.count + 1) + + 80 + guard result.entries.count < ManifestLimits.SourceMap.locations, + recordedOrigins.count <= ManifestLimits.SourceMap.origins - originCount, + estimate <= ManifestLimits.SourceMap.encodedBytes - encodedBytes + else { + throw source.failure( + "manifest.limit", "source map locations, origins or encoded bytes", range.lowerBound) + } + originCount += recordedOrigins.count + encodedBytes += estimate + result.entries.append( + SourceMapEntry( + pointer: pointer, span: span, origins: recordedOrigins, defaulted: value.defaulted)) + result.locations[pointer] = NodeID(digest: digest, pointer: pointer, syntax: value.syntax) + result.values[pointer] = value + let useSpan = value.referent != nil || use != nil ? span : nil + if case .node(let type, let member, let fields) = resolved.value { + if Vocabulary.taggedRecordTypes.contains(type), + case .record(let record) = Lowering.lower(resolved.value) + { + let discriminator = EvaluatedValue( + type: .untyped, value: .text(record.kind), cost: ValueCost.scalar(record.kind), + syntax: resolved.syntax, representation: .synthetic) + try append(discriminator, pointer: pointer + "/kind", origins: inherited, use: useSpan) + } + if type == "SkillSelection" { + for (offset, child) in resolved.elementsForUse.enumerated() { + try append(child, pointer: pointer + "/\(offset)", origins: inherited, use: useSpan) + } + return + } + if type == "ConfigurationValue", + resolved.representation == .scalarLiteral || resolved.representation == .collectionLiteral, + let payload = fields["value"] + { + guard + let childType = Vocabulary.literalConstructions[type]?.values.first(where: { + $0.member == member + })?.payloadType + else { + throw source.failure( + "manifest.type", "literal payload has no registered type", range.lowerBound) + } + let child = EvaluatedValue( + type: childType, value: payload, cost: resolved.cost, syntax: resolved.syntax, + fields: resolved.fields, elements: resolved.elements) + try append(child, pointer: pointer + "/value", origins: inherited, use: useSpan) + return + } + for (key, childValue) in fields { + if type == "Source", key == "requirement" { + let trace = ["from", "exact", "branch", "revision", "range"].compactMap { + resolved.fields[$0] + }.first + if let trace, childValue != .none { + let shape = requirementShape(childValue, trace: trace) + var definitions: [SourceSpan] = [] + var referent = trace.referent + while let definition = referent { + definitions.append(source.span(admission.nodes[definition.syntax].range)) + referent = definition.referent + } + try append( + shape, pointer: pointer + "/requirement", origins: inherited, use: useSpan, + ownOrigins: definitions) + } else { + let absent = EvaluatedValue( + type: .untyped, value: .none, cost: ValueCost(), syntax: resolved.syntax, + defaulted: true, representation: .synthetic) + try append(absent, pointer: pointer + "/requirement", origins: inherited, use: useSpan) + } + continue + } + let child: EvaluatedValue + if let field = resolved.fields[key] { + child = field + } else { + child = EvaluatedValue( + type: .untyped, value: childValue, cost: ValueCost(), syntax: resolved.syntax, + defaulted: (key == "source" || key == "condition") && childValue == .none + || resolved.defaulted, representation: .synthetic) + } + try append( + child, pointer: pointer + "/" + pointerEscape(key), origins: inherited, use: useSpan) + } + } else if !resolved.fields.isEmpty { + for (key, child) in resolved.fields { + try append( + child, pointer: pointer + "/" + pointerEscape(key), origins: inherited, use: useSpan) + } + } else if !resolved.elements.isEmpty { + for (offset, child) in resolved.elements.enumerated() { + try append(child, pointer: pointer + "/\(offset)", origins: inherited, use: useSpan) + } + } else { + try synthetic( + resolved.value, syntax: resolved.syntax, pointer: pointer, span: span, origins: inherited, + defaulted: value.defaulted) + } + } + + private func requirementShape(_ value: ConstructionValue, trace: EvaluatedValue) -> EvaluatedValue + { + let requirement = Lowering.lower(value) + var fields: [String: ConstructionValue] = [:] + var traces: [String: EvaluatedValue] = [:] + if case .requirement(let requirement) = requirement { + let lower = trace.field("from") ?? trace.elementsForUse.first ?? trace + switch requirement { + case .branch(let text): + fields["branch"] = .text(text) + traces["branch"] = trace + case .revision(let text): + fields["revision"] = .text(text) + traces["revision"] = trace + case .exact(let text): + fields["exact"] = .text(text) + traces["exact"] = trace + case .upToNextMajor(let text): + fields["from"] = .text(text) + traces["from"] = lower + case .upToNextMinor(let text): + fields["upToNextMinor"] = .text(text) + traces["upToNextMinor"] = lower + case .range(let from, let to): + fields["from"] = .text(from) + fields["to"] = .text(to) + traces["from"] = lower + traces["to"] = trace.elementsForUse.last ?? trace + } + } + return EvaluatedValue( + type: .named("Requirement"), value: .object(fields), cost: trace.cost, syntax: trace.syntax, + fields: traces, representation: .synthetic) + } + + private func synthetic( + _ value: ConstructionValue, syntax: Int, pointer: String, span: SourceSpan, + origins: [SourceSpan], defaulted: Bool + ) throws { + let fields: [(String, ConstructionValue)] + switch value { + case .node(_, _, let values), .object(let values): fields = Array(values) + case .array(let values): fields = values.enumerated().map { (String($0.offset), $0.element) } + default: return + } + for (key, child) in fields { + let v = EvaluatedValue( + type: .untyped, value: child, cost: ValueCost(), syntax: syntax, defaulted: defaulted, + representation: .synthetic) + try append(v, pointer: pointer + "/" + pointerEscape(key), origins: origins, use: span) + } + } +} diff --git a/Sources/AgentsManifest/SourceText.swift b/Sources/AgentsManifest/SourceText.swift new file mode 100644 index 0000000..4fac150 --- /dev/null +++ b/Sources/AgentsManifest/SourceText.swift @@ -0,0 +1,48 @@ +import AgentsCore + +struct SourceText: Sendable { + let bytes: [UInt8] + let identity: DocumentIdentity + private let lines: [Int] + + init(_ bytes: [UInt8], identity: DocumentIdentity) { + self.bytes = bytes + self.identity = identity + var starts = [0] + var i = 0 + while i < min(bytes.count, ManifestLimits.Input.bytes + 1) { + if bytes[i] == UInt8(ascii: "\r") { + if i + 1 < bytes.count && bytes[i + 1] == UInt8(ascii: "\n") { i += 1 } + starts.append(i + 1) + } else if bytes[i] == UInt8(ascii: "\n") { + starts.append(i + 1) + } + i += 1 + } + lines = starts + } + + func span(_ range: Range) -> SourceSpan { + let start = min(max(0, range.lowerBound), bytes.count) + var lo = 0 + var hi = lines.count + while lo + 1 < hi { + let mid = (lo + hi) / 2 + if lines[mid] <= start { lo = mid } else { hi = mid } + } + return SourceSpan( + document: identity, start: start, end: min(max(start, range.upperBound), bytes.count), + line: lo + 1, column: start - lines[lo] + 1) + } + + func failure(_ code: String, _ message: String, _ offset: Int, end: Int? = nil) + -> ManifestFailure + { + ManifestFailure( + ManifestDiagnostic(code: code, message: message, span: span(offset..<(end ?? offset)))) + } + + func spelling(_ range: Range) -> String { + String(decoding: bytes[range], as: UTF8.self) + } +} diff --git a/Sources/AgentsManifest/StaticValueVocabulary.swift b/Sources/AgentsManifest/StaticValueVocabulary.swift new file mode 100644 index 0000000..9f21406 --- /dev/null +++ b/Sources/AgentsManifest/StaticValueVocabulary.swift @@ -0,0 +1,93 @@ +// Generated from Scripts/ManifestVocabulary.json. Run Scripts/generate-manifest-vocabulary.py. + +import AgentsDescription + +extension StaticValue { + public static func configuration(_ value: AgentsDescription.ConfigurationValue) -> Self { + Self.checked(value.constructionValue, type: .named("ConfigurationValue")) + } + public static func component(_ value: AgentsDescription.Component) -> Self { + Self.checked(value.constructionValue, type: .named("Component")) + } + public static func source(_ value: AgentsDescription.Source) -> Self { + Self.checked(value.constructionValue, type: .named("Source")) + } + public static func section(_ value: AgentsDescription.SectionReference) -> Self { + Self.checked(value.constructionValue, type: .named("SectionReference")) + } + public static func groupReference(_ value: AgentsDescription.GroupReference) -> Self { + Self.checked(value.constructionValue, type: .named("GroupReference")) + } + public static func version(_ value: AgentsDescription.Version) -> Self { + Self.checked(value.constructionValue, type: .named("Version")) + } + public static func runtime(_ value: AgentsDescription.RuntimeValue) -> Self { + Self.checked(value.constructionValue, type: .named("RuntimeValue")) + } + public static func condition(_ value: AgentsDescription.Condition) -> Self { + Self.checked(value.constructionValue, type: .named("Condition")) + } + public static func selection(_ value: AgentsDescription.SkillSelection) -> Self { + Self.checked(value.constructionValue, type: .named("SkillSelection")) + } + public static func skillOverride(_ value: AgentsDescription.SkillOverride) -> Self { + Self.checked(value.constructionValue, type: .named("SkillOverride")) + } + public static func prompt(_ value: AgentsDescription.ChatGPTPrompt) -> Self { + Self.checked(value.constructionValue, type: .named("ChatGPTPrompt")) + } + public static func resource(_ value: AgentsDescription.Resource) -> Self { + Self.checked(value.constructionValue, type: .named("Resource")) + } + public static func promptContent(_ value: AgentsDescription.PromptContent) -> Self { + Self.checked(value.constructionValue, type: .named("PromptContent")) + } + public static func executable(_ value: AgentsDescription.ExecutableInvocation) -> Self { + Self.checked(value.constructionValue, type: .named("ExecutableInvocation")) + } + public static func transport(_ value: AgentsDescription.MCPTransport) -> Self { + Self.checked(value.constructionValue, type: .named("MCPTransport")) + } + public static func parameter(_ value: AgentsDescription.PromptParameter) -> Self { + Self.checked(value.constructionValue, type: .named("PromptParameter")) + } + public static func permissionRule(_ value: AgentsDescription.PermissionRule) -> Self { + Self.checked(value.constructionValue, type: .named("PermissionRule")) + } + public static func agent(_ value: AgentsDescription.Agent) -> Self { + Self.checked(value.constructionValue, type: .named("Agent")) + } + public static func scope(_ value: AgentsDescription.Scope) -> Self { + Self.checked(value.constructionValue, type: .named("Scope")) + } + public static func platform(_ value: AgentsDescription.Platform) -> Self { + Self.checked(value.constructionValue, type: .named("Platform")) + } + public static func installMode(_ value: AgentsDescription.InstallMode) -> Self { + Self.checked(value.constructionValue, type: .named("InstallMode")) + } + public static func hookEvent(_ value: AgentsDescription.HookEvent) -> Self { + Self.checked(value.constructionValue, type: .named("HookEvent")) + } + public static func permissionOperation(_ value: AgentsDescription.PermissionOperation) -> Self { + Self.checked(value.constructionValue, type: .named("PermissionOperation")) + } + public static func ignorePurpose(_ value: AgentsDescription.IgnorePurpose) -> Self { + Self.checked(value.constructionValue, type: .named("IgnorePurpose")) + } + public static func pluginMode(_ value: AgentsDescription.PluginMode) -> Self { + Self.checked(value.constructionValue, type: .named("PluginMode")) + } + public static func componentKind(_ value: AgentsDescription.ComponentKind) -> Self { + Self.checked(value.constructionValue, type: .named("ComponentKind")) + } + public static func componentReference(_ value: AgentsDescription.ComponentReference) -> Self { + Self.checked(value.constructionValue, type: .named("ComponentReference")) + } + public static func group(_ value: AgentsDescription.ComponentGroup) -> Self { + Self.checked(value.constructionValue, type: .named("ComponentGroup")) + } + public static func agents(_ value: AgentsDescription.Agents) -> Self { + Self.checked(value.constructionValue, type: .named("Agents")) + } +} diff --git a/Sources/AgentsManifest/SyntaxValidation.swift b/Sources/AgentsManifest/SyntaxValidation.swift index ec2ad65..2383fdc 100644 --- a/Sources/AgentsManifest/SyntaxValidation.swift +++ b/Sources/AgentsManifest/SyntaxValidation.swift @@ -3,14 +3,14 @@ import Foundation import SwiftParser import SwiftSyntax -package struct CheckedSyntax: Sendable { - package let tree: SourceFileSyntax - package let metrics: FrontEndMetrics +struct CheckedSyntax: Sendable { + let tree: SourceFileSyntax + let metrics: FrontEndMetrics } -package enum SyntaxValidation { +enum SyntaxValidation { /// All-nodes view, with cached lengths only until the complete tree fits. - package static func guardTree(_ root: Syntax, source: SourceText) throws -> ( + static func guardTree(_ root: Syntax, source: SourceText) throws -> ( nodes: Int, depth: Int ) { var pending: [(Syntax, Int, Int)] = [(root, 1, 0)] @@ -18,15 +18,19 @@ package enum SyntaxValidation { var count = 0 var maximum = 0 while let (node, depth, offset) = pending.popLast() { - if depth > 128 { throw source.failure("manifest.limit", "syntax tree depth", offset) } + if depth > ManifestLimits.Syntax.depth { + throw source.failure("manifest.limit", "syntax tree depth", offset) + } count += 1 maximum = max(maximum, depth) var childOffset = offset for child in node.children(viewMode: .all) { - if scheduled == 100_000 { + if scheduled == ManifestLimits.Syntax.nodes { throw source.failure("manifest.limit", "syntax tree nodes", childOffset) } - if depth == 128 { throw source.failure("manifest.limit", "syntax tree depth", childOffset) } + if depth == ManifestLimits.Syntax.depth { + throw source.failure("manifest.limit", "syntax tree depth", childOffset) + } scheduled += 1 pending.append((child, depth + 1, childOffset)) childOffset += child.totalLength.utf8Length @@ -35,14 +39,14 @@ package enum SyntaxValidation { return (count, maximum) } - package static func parse( + static func parse( _ source: SourceText, admission: Admission, metrics initial: FrontEndMetrics ) throws -> CheckedSyntax { var metrics = initial let clock = ContinuousClock() let parseStart = clock.now let tree = source.bytes.withUnsafeBufferPointer { - Parser.parse(source: $0, maximumNestingLevel: 20) + Parser.parse(source: $0, maximumNestingLevel: ManifestLimits.Syntax.parserNesting) } metrics.parserCalls += 1 metrics.parsingSeconds = seconds(parseStart.duration(to: clock.now)) @@ -52,11 +56,13 @@ package enum SyntaxValidation { metrics.syntaxNodes = bounds.nodes metrics.syntaxDepth = bounds.depth } catch let failure as ManifestFailure { + metrics.guardSeconds = seconds(guardStart.duration(to: clock.now)) throw ManifestFailure(failure.diagnostics[0], metrics: metrics) } metrics.guardSeconds = seconds(guardStart.duration(to: clock.now)) let inspectionStart = clock.now if tree.hasError { + metrics.inspectionSeconds = seconds(inspectionStart.duration(to: clock.now)) throw ManifestFailure( ManifestDiagnostic( code: "manifest.syntax", message: "SwiftParser disagreed with grammar admission", @@ -64,6 +70,7 @@ package enum SyntaxValidation { } // This independent projection is also a dependency-upgrade regression gate. let actual = projection(Syntax(tree), source: source) + metrics.inspectionSeconds = seconds(inspectionStart.duration(to: clock.now)) guard actual == admission.projection, metrics.syntaxNodes <= admission.reservation else { let offset = zip(actual, admission.projection).first(where: { $0 != $1 })?.0.start ?? 0 throw ManifestFailure( @@ -76,7 +83,7 @@ package enum SyntaxValidation { return CheckedSyntax(tree: tree, metrics: metrics) } - package static func projection(_ root: Syntax, source: SourceText) -> [ProjectionEvent] { + static func projection(_ root: Syntax, source: SourceText) -> [ProjectionEvent] { var pending = [root] var events: [ProjectionEvent] = [] func emit(_ node: Syntax, _ kind: String, _ detail: String = "") { @@ -142,6 +149,6 @@ package enum SyntaxValidation { } } -package func seconds(_ duration: Duration) -> Double { +func seconds(_ duration: Duration) -> Double { Double(duration.components.seconds) + Double(duration.components.attoseconds) / 1e18 } diff --git a/Sources/AgentsManifest/ValueBudget.swift b/Sources/AgentsManifest/ValueBudget.swift index 101e568..7f7569a 100644 --- a/Sources/AgentsManifest/ValueBudget.swift +++ b/Sources/AgentsManifest/ValueBudget.swift @@ -1,21 +1,23 @@ import AgentsDescription -package struct ValueCost: Sendable { - package var nodes = 1 - package var strings = 0 - package var encoded = 16 - package var depth = 1 - package var origins = 1 +struct ValueCost: Sendable { + var nodes = 1 + var strings = 0 + var encoded = 16 + var depth = 1 + var origins = 1 - package static func scalar(_ text: String = "") -> Self { + static func scalar(_ text: String = "") -> Self { var encoded = 2 for byte in text.utf8 { - encoded += byte < 32 ? 6 : (byte == 34 || byte == 92 ? 2 : 1) + encoded += + byte < UInt8(ascii: " ") + ? 6 : (byte == UInt8(ascii: "\"") || byte == UInt8(ascii: "\\") ? 2 : 1) } return Self(strings: text.utf8.count, encoded: encoded) } - package static func container(_ children: [ValueCost], keys: [String] = []) -> Self { + static func container(_ children: [ValueCost], keys: [String] = []) -> Self { var result = Self() for child in children { result.nodes = add(result.nodes, child.nodes) @@ -32,46 +34,21 @@ package struct ValueCost: Sendable { return result } - package var fits: Bool { - nodes <= 100_000 && strings <= 16_777_216 && encoded <= 33_554_432 - && depth <= 64 && origins <= 1_000_000 + var fits: Bool { + nodes <= ManifestLimits.Values.nodes && strings <= ManifestLimits.Values.stringBytes + && encoded <= ManifestLimits.Output.encodedBytes + && depth <= ManifestLimits.Values.depth && origins <= ManifestLimits.SourceMap.origins } - package static func add(_ lhs: Int, _ rhs: Int) -> Int { + static func add(_ lhs: Int, _ rhs: Int) -> Int { let (result, overflow) = lhs.addingReportingOverflow(rhs) - return overflow ? 33_554_433 : min(result, 33_554_433) + return overflow + ? (ManifestLimits.Output.encodedBytes + 1) + : min(result, (ManifestLimits.Output.encodedBytes + 1)) } } -package final class EvaluatedValue: Sendable { - package let type: ConstructionType - package let value: ConstructionValue - package let cost: ValueCost - package let syntax: Int - package let fields: [String: EvaluatedValue] - package let elements: [EvaluatedValue] - package let referent: EvaluatedValue? - package let defaulted: Bool - package let referenceDepth: Int - - package init( - type: ConstructionType, value: ConstructionValue, cost: ValueCost, syntax: Int, - fields: [String: EvaluatedValue] = [:], elements: [EvaluatedValue] = [], - referent: EvaluatedValue? = nil, defaulted: Bool = false - ) { - self.type = type - self.value = value - self.cost = cost - self.syntax = syntax - self.fields = fields - self.elements = elements - self.referent = referent - self.defaulted = defaulted - referenceDepth = (referent?.referenceDepth ?? 0) + (referent == nil ? 0 : 1) - } -} - -package func constructionCost(_ value: ConstructionValue) -> ValueCost { +func constructionCost(_ value: ConstructionValue) -> ValueCost { switch value { case .text(let text): return .scalar(text) case .version(let version): return .scalar(version.normalized) diff --git a/Tests/AgentsManifestTests/AdversarialTests.swift b/Tests/AgentsManifestTests/AdversarialTests.swift index f160b4b..c9c9d55 100644 --- a/Tests/AgentsManifestTests/AdversarialTests.swift +++ b/Tests/AgentsManifestTests/AdversarialTests.swift @@ -1,5 +1,6 @@ import AgentsCore import Foundation +import ManifestTestSupport import SwiftSyntax import Testing @@ -216,6 +217,15 @@ func fixedAdmissionCases() -> [AdmissionCase] { "byte-boundary-comment", bytes: comment + Array(repeating: 91, count: 2_097_152 - comment.count), expected: "accepted") ) + for (name, suffix) in [ + ("eof", ""), ("import", "import AgentsDescription\nlet agents = Agents()"), + ] { + cases.append( + AdmissionCase( + "directive-bare-cr-" + name, + "// agents-tools-version: 1.0\r" + suffix, + expected: "manifest.version.invalid", complete: true)) + } return cases } @@ -246,7 +256,7 @@ struct AdversarialTests { #expect(result.report.offset == fixture.bytes.firstIndex(of: 35)) #expect(result.report.metrics.parserCalls == 0) } - if result.report.stage == "admission" { + if result.report.stage == .admission { var line = 1 var column = 1 var index = 0 diff --git a/Tests/AgentsManifestTests/CompiledFixtures.swift b/Tests/AgentsManifestTests/CompiledFixtures.swift index 84d6a6c..3e0a1b2 100644 --- a/Tests/AgentsManifestTests/CompiledFixtures.swift +++ b/Tests/AgentsManifestTests/CompiledFixtures.swift @@ -15,26 +15,26 @@ struct CompiledManifestFixture { func compiledFixtures() -> [CompiledManifestFixture] { [ - fixture0(), - fixture1(), - fixture2(), - fixture3(), - fixture4(), - fixture5(), - fixture6(), - fixture7(), - fixture8(), - fixture9(), - fixture10(), - fixture11(), - fixture12(), - fixture13(), - fixture14(), - fixture15(), + compiledConsumerExample(), + compiledCoreExample(), + compiledExportedGroup(), + compiledInstructionRecipients(), + compiledLiteralCoverage(), + compiledMigrationEdgeExample(), + compiledProducerExample(), + compiledRecipientConditions(), + compiledRequirementValues(), + compiledRequirementsExample(), + compiledSectionConcatenation(), + compiledSharedRules(), + compiledSketchExample(), + compiledSkillsExample(), + compiledTeamConfiguration(), + compiledVocabularyDepthExample(), ] } -private func fixture0() -> CompiledManifestFixture { +private func compiledConsumerExample() -> CompiledManifestFixture { // agents-tools-version: 1.0 let base: [SectionReference] = ["guide"] @@ -141,7 +141,7 @@ private func fixture0() -> CompiledManifestFixture { ]) } -private func fixture1() -> CompiledManifestFixture { +private func compiledCoreExample() -> CompiledManifestFixture { // agents-tools-version: 1.0 let agents = Agents( @@ -165,54 +165,13 @@ private func fixture1() -> CompiledManifestFixture { ] ) return CompiledManifestFixture( - name: "Contract00.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func fixture2() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - defaultAgents: [.cursor], - sources: [.source(name: "team", path: "./team")], - components: [ - .ignore( - name: "build-products", patterns: [".build/"], purpose: .indexing, - condition: .when(scopes: [.project]) - ) - ], - uses: [ - .group(name: "review", source: "team", condition: .when(agents: [.codex])) - ] - ) - return CompiledManifestFixture( - name: "Contract01.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func fixture3() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - components: [ - .instructions( - sections: ["guide", "code-review-rules"], - agents: [.claudeCode, .codex] - ) - ] - ) - return CompiledManifestFixture( - name: "Contract05.swift.txt", agents: agents, + name: "CoreExample.swift.txt", agents: agents, constants: [ "agents": agents.constructionValue ]) } -private func fixture4() -> CompiledManifestFixture { +private func compiledExportedGroup() -> CompiledManifestFixture { // agents-tools-version: 1.0 let agents = Agents( @@ -229,150 +188,31 @@ private func fixture4() -> CompiledManifestFixture { ] ) return CompiledManifestFixture( - name: "Contract06.swift.txt", agents: agents, + name: "ExportedGroup.swift.txt", agents: agents, constants: [ "agents": agents.constructionValue ]) } -private func fixture5() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let base: [SectionReference] = ["guide"] - let sections = base + [.section(name: "engineering", source: "rules")] - let reviewer: Component = .subagent( - name: "reviewer", - description: "Review correctness and tests.", - prompt: "Check invariants and explain concrete failures.", - agents: [.claudeCode], - condition: .when(platforms: [.macOS]), - native: ["claude-code/subagent@1": ["memory": "project"]] - ) - - let agents = Agents( - sources: [ - .source(name: "team", path: "./team"), - .source(name: "drafts", path: "./draft-skills"), - .source(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), - .source(name: "catalog", index: "https://example.org/skills/index.json"), - .source(name: "vendor", url: "https://example.org/vendor/tools.git", exact: "2.1.0"), - ], - components: [ - .skills( - source: "rules", exclude: ["experimental"], mode: .copy, - overrides: [.skill(name: "testing", mode: .link, agents: [.codex])] - ), - .skills( - source: "drafts", select: ["draft"], mode: .edit, - condition: .when(agents: [.claudeCode], scopes: [.project]) - ), - .instructions( - sections: sections, - chatGPT: [.prompt(name: "weekly", sections: base, append: "notes/weekly.md")] - ), - .mcpServer( - name: "workspace", - transport: .stdio( - "workspace-tools", arguments: ["serve"], - environment: ["TOKEN": .secret("workspace-token"), "LOG_LEVEL": "info"] - ), - agents: [.claudeCode] - ), - .mcpServer( - name: "reference", - transport: .streamableHTTP( - url: "https://example.org/mcp", headers: ["Authorization": .environment("MCP_AUTH")] - ), - agents: [.openCode] - ), - .hook( - name: "format", event: .afterTool, - run: .executable( - "swift", arguments: ["format", "--in-place", "Sources"], - workingDirectory: .path("tools", source: "rules") - ), - timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) - ), - .command( - name: "review/change", description: "Review a selected change.", - prompt: "Review ${input:change} and cite evidence.", - parameters: [.parameter(name: "change", description: "The change to review.")], - agents: [.claudeCode] - ), - .lspServer( - name: "swift", run: .executable("sourcekit-lsp"), - languages: [".swift": "swift"], - initializationOptions: ["backgroundIndexing": true], - agents: [.claudeCode], condition: .when(platforms: [.macOS]) - ), - .permissions( - name: "private-files", - rules: [.deny(.read, "secrets/**")], - agents: [.claudeCode], condition: .when(scopes: [.project]) - ), - .ignore( - name: "build-products", patterns: [".build/", "DerivedData/"], purpose: .indexing, - agents: [.cursor], condition: .when(scopes: [.project]) - ), - .plugin( - name: "vendor-tools", path: "plugins/tools", source: "vendor", mode: .native, - agents: [.claudeCode], condition: .when(scopes: [.user]) - ), - .plugin( - name: "shared-tools", path: "plugins/shared", source: "vendor", - exclude: [.hook(name: "format")], condition: .when(scopes: [.project]) - ), - ], - groups: [ - .group( - name: "review-tools", components: [reviewer], - uses: [.group(name: "review", source: "team", condition: .when(agents: [.codex]))] - ) - ], - uses: ["review-tools"], - watch: ["rules", "catalog"] - ) - return CompiledManifestFixture( - name: "Contract07.swift.txt", agents: agents, - constants: [ - "base": base.constructionValue, - "sections": sections.constructionValue, - "reviewer": reviewer.constructionValue, - "agents": agents.constructionValue, - ]) -} - -private func fixture6() -> CompiledManifestFixture { +private func compiledInstructionRecipients() -> CompiledManifestFixture { // agents-tools-version: 1.0 let agents = Agents( - sources: [ - .source( - name: "agents-tools", - url: "https://github.com/agents-tools/.github", - branch: "master", - subpath: ".agent" - ) - ], components: [ .instructions( - sections: [ - "guide", - .section(name: "shared/swift-package-route", source: "agents-tools"), - .section(name: "shared/swift-package-tests", source: "agents-tools"), - ], + sections: ["guide", "code-review-rules"], agents: [.claudeCode, .codex] ) ] ) return CompiledManifestFixture( - name: "CoreExample.swift.txt", agents: agents, + name: "InstructionRecipients.swift.txt", agents: agents, constants: [ "agents": agents.constructionValue ]) } -private func fixture7() -> CompiledManifestFixture { +private func compiledLiteralCoverage() -> CompiledManifestFixture { // agents-tools-version: 1.0 let text: PromptContent = "Review invariants." @@ -463,7 +303,7 @@ private func fixture7() -> CompiledManifestFixture { ]) } -private func fixture8() -> CompiledManifestFixture { +private func compiledMigrationEdgeExample() -> CompiledManifestFixture { // agents-tools-version: 1.0 let agents = Agents( @@ -521,7 +361,7 @@ private func fixture8() -> CompiledManifestFixture { ]) } -private func fixture9() -> CompiledManifestFixture { +private func compiledProducerExample() -> CompiledManifestFixture { // agents-tools-version: 1.0 let agents = Agents( @@ -544,7 +384,30 @@ private func fixture9() -> CompiledManifestFixture { ]) } -private func fixture10() -> CompiledManifestFixture { +private func compiledRecipientConditions() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + defaultAgents: [.cursor], + sources: [.source(name: "team", path: "./team")], + components: [ + .ignore( + name: "build-products", patterns: [".build/"], purpose: .indexing, + condition: .when(scopes: [.project]) + ) + ], + uses: [ + .group(name: "review", source: "team", condition: .when(agents: [.codex])) + ] + ) + return CompiledManifestFixture( + name: "RecipientConditions.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func compiledRequirementValues() -> CompiledManifestFixture { // agents-tools-version: 1.0 let majorFrom: Source = .source( @@ -599,7 +462,7 @@ private func fixture10() -> CompiledManifestFixture { ]) } -private func fixture11() -> CompiledManifestFixture { +private func compiledRequirementsExample() -> CompiledManifestFixture { // agents-tools-version: 1.0 let minimum: Version = "1.2.0" @@ -658,7 +521,144 @@ private func fixture11() -> CompiledManifestFixture { ]) } -private func fixture12() -> CompiledManifestFixture { +private func compiledSectionConcatenation() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let base: [SectionReference] = ["guide"] + let sections = base + [.section(name: "engineering", source: "rules")] + let reviewer: Component = .subagent( + name: "reviewer", + description: "Review correctness and tests.", + prompt: "Check invariants and explain concrete failures.", + agents: [.claudeCode], + condition: .when(platforms: [.macOS]), + native: ["claude-code/subagent@1": ["memory": "project"]] + ) + + let agents = Agents( + sources: [ + .source(name: "team", path: "./team"), + .source(name: "drafts", path: "./draft-skills"), + .source(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), + .source(name: "catalog", index: "https://example.org/skills/index.json"), + .source(name: "vendor", url: "https://example.org/vendor/tools.git", exact: "2.1.0"), + ], + components: [ + .skills( + source: "rules", exclude: ["experimental"], mode: .copy, + overrides: [.skill(name: "testing", mode: .link, agents: [.codex])] + ), + .skills( + source: "drafts", select: ["draft"], mode: .edit, + condition: .when(agents: [.claudeCode], scopes: [.project]) + ), + .instructions( + sections: sections, + chatGPT: [.prompt(name: "weekly", sections: base, append: "notes/weekly.md")] + ), + .mcpServer( + name: "workspace", + transport: .stdio( + "workspace-tools", arguments: ["serve"], + environment: ["TOKEN": .secret("workspace-token"), "LOG_LEVEL": "info"] + ), + agents: [.claudeCode] + ), + .mcpServer( + name: "reference", + transport: .streamableHTTP( + url: "https://example.org/mcp", headers: ["Authorization": .environment("MCP_AUTH")] + ), + agents: [.openCode] + ), + .hook( + name: "format", event: .afterTool, + run: .executable( + "swift", arguments: ["format", "--in-place", "Sources"], + workingDirectory: .path("tools", source: "rules") + ), + timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) + ), + .command( + name: "review/change", description: "Review a selected change.", + prompt: "Review ${input:change} and cite evidence.", + parameters: [.parameter(name: "change", description: "The change to review.")], + agents: [.claudeCode] + ), + .lspServer( + name: "swift", run: .executable("sourcekit-lsp"), + languages: [".swift": "swift"], + initializationOptions: ["backgroundIndexing": true], + agents: [.claudeCode], condition: .when(platforms: [.macOS]) + ), + .permissions( + name: "private-files", + rules: [.deny(.read, "secrets/**")], + agents: [.claudeCode], condition: .when(scopes: [.project]) + ), + .ignore( + name: "build-products", patterns: [".build/", "DerivedData/"], purpose: .indexing, + agents: [.cursor], condition: .when(scopes: [.project]) + ), + .plugin( + name: "vendor-tools", path: "plugins/tools", source: "vendor", mode: .native, + agents: [.claudeCode], condition: .when(scopes: [.user]) + ), + .plugin( + name: "shared-tools", path: "plugins/shared", source: "vendor", + exclude: [.hook(name: "format")], condition: .when(scopes: [.project]) + ), + ], + groups: [ + .group( + name: "review-tools", components: [reviewer], + uses: [.group(name: "review", source: "team", condition: .when(agents: [.codex]))] + ) + ], + uses: ["review-tools"], + watch: ["rules", "catalog"] + ) + return CompiledManifestFixture( + name: "SectionConcatenation.swift.txt", agents: agents, + constants: [ + "base": base.constructionValue, + "sections": sections.constructionValue, + "reviewer": reviewer.constructionValue, + "agents": agents.constructionValue, + ]) +} + +private func compiledSharedRules() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + sources: [ + .source( + name: "agents-tools", + url: "https://github.com/agents-tools/.github", + branch: "master", + subpath: ".agent" + ) + ], + components: [ + .instructions( + sections: [ + "guide", + .section(name: "shared/swift-package-route", source: "agents-tools"), + .section(name: "shared/swift-package-tests", source: "agents-tools"), + ], + agents: [.claudeCode, .codex] + ) + ] + ) + return CompiledManifestFixture( + name: "SharedRules.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func compiledSketchExample() -> CompiledManifestFixture { // agents-tools-version: 1.0 let agents = Agents( @@ -681,7 +681,7 @@ private func fixture12() -> CompiledManifestFixture { ]) } -private func fixture13() -> CompiledManifestFixture { +private func compiledSkillsExample() -> CompiledManifestFixture { // agents-tools-version: 1.0 let agents = Agents( @@ -699,7 +699,7 @@ private func fixture13() -> CompiledManifestFixture { ]) } -private func fixture14() -> CompiledManifestFixture { +private func compiledTeamConfiguration() -> CompiledManifestFixture { // agents-tools-version: 1.0 // A team repository's .agent/Agents.swift. @@ -782,14 +782,14 @@ private func fixture14() -> CompiledManifestFixture { watch: ["rules"] ) return CompiledManifestFixture( - name: "TasteSample.swift.txt", agents: agents, + name: "TeamConfiguration.swift.txt", agents: agents, constants: [ "reviewer": reviewer.constructionValue, "agents": agents.constructionValue, ]) } -private func fixture15() -> CompiledManifestFixture { +private func compiledVocabularyDepthExample() -> CompiledManifestFixture { // agents-tools-version: 1.0 let agents = Agents( diff --git a/Tests/AgentsManifestTests/DifferentialFuzzTests.swift b/Tests/AgentsManifestTests/DifferentialFuzzTests.swift index 8972a33..a83f699 100644 --- a/Tests/AgentsManifestTests/DifferentialFuzzTests.swift +++ b/Tests/AgentsManifestTests/DifferentialFuzzTests.swift @@ -1,4 +1,5 @@ import Foundation +import ManifestTestSupport import Testing @testable import AgentsManifest @@ -105,7 +106,7 @@ struct DifferentialFuzzTests { ) for fixture in fuzzAdmissionCases() { let result = try probe(fixture.name, fixture.bytes, in: directory) - if result.report.stage == "parser" { + if result.report.stage == .parser { let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent() .deletingLastPathComponent().deletingLastPathComponent() let retained = root.appendingPathComponent(".build/manifest-counterexamples") @@ -122,7 +123,7 @@ struct DifferentialFuzzTests { candidate.removeSubrange(offset..<(offset + chunk)) attempts += 1 let check = try probe("minimize", candidate, in: directory) - if check.report.stage == "parser" { + if check.report.stage == .parser { minimized = candidate found = true break diff --git a/Tests/AgentsManifestTests/EditingTests.swift b/Tests/AgentsManifestTests/EditingTests.swift index cbd54e7..8e2bacf 100644 --- a/Tests/AgentsManifestTests/EditingTests.swift +++ b/Tests/AgentsManifestTests/EditingTests.swift @@ -119,7 +119,7 @@ struct EditingTests { doc, [.removeDictionaryEntry(doc.node(at: "/components/0/initializationOptions")!, key: "added")]) #expect(String(decoding: doc.bytes, as: UTF8.self).contains("\"other\": true")) - #expect(throws: ManifestFailure.self) { + expectManifestFailure("manifest.type") { try doc.preparing([ .setDictionaryEntry( doc.node(at: "/components/0/languages")!, key: ".js", value: .integer(3)) @@ -134,7 +134,7 @@ struct EditingTests { let handle = doc.constant(named: "base")! let uses = doc.uses(ofConstant: "base") #expect(uses.count == 3) - #expect(throws: ManifestFailure.self) { + expectManifestFailure("manifest.edit.impact") { try doc.preparing([ .replaceConstant(handle, with: .array([.string("two")]), acceptingUses: []) ]) @@ -177,11 +177,11 @@ struct EditingTests { ]) #expect(noOp.bytes == doc.bytes) #expect(noOp.patches.isEmpty) - #expect(throws: ManifestFailure.self) { + expectManifestFailure("manifest.edit.readOnly") { try doc.preparing([.insertComponent(.instructions(), into: .root, at: .first)]) } let unrelated = try document("let agents = Agents()") - #expect(throws: ManifestFailure.self) { + expectManifestFailure("manifest.edit.stale") { try unrelated.preparing([.removeComponent(doc.node(at: "/sources/0")!)]) } #expect(doc.bytes == noOp.bytes) @@ -191,8 +191,8 @@ struct EditingTests { let doc = try document( "let agents = Agents(exports: [\"g\"], sources: [.source(name: \"s\", path: \"s\")], groups: [.group(name: \"g\", components: [.skills(source: \"s\")])], uses: [\"g\"], watch: [\"s\"])" ) - #expect(throws: ManifestFailure.self) { try doc.preparing([.removeSource(alias: "s")]) } - #expect(throws: ManifestFailure.self) { try doc.preparing([.removeGroup(name: "g")]) } + expectManifestFailure("manifest.domain") { try doc.preparing([.removeSource(alias: "s")]) } + expectManifestFailure("manifest.group.missing") { try doc.preparing([.removeGroup(name: "g")]) } let repaired = try edited( doc, [ @@ -222,7 +222,7 @@ struct EditingTests { scalar, [.replaceConstant(scalar.constant(named: "number")!, with: .integer(-1), acceptingUses: [])]) #expect(String(decoding: negative.bytes, as: UTF8.self).contains("let number = -1")) - #expect(throws: ManifestFailure.self) { + expectManifestFailure("manifest.edit.readOnly") { try n.preparing([ .replaceConstant( n.constant(named: "number")!, with: .array([.integer(-1)]), acceptingUses: []) @@ -276,4 +276,261 @@ struct EditingTests { #expect(result.contains("keep with y")) } + @Test func inferredConstantsRetainContextDuringReplacement() throws { + let doc = try document( + "let recipient = Agent.codex\nlet agents = Agents(defaultAgents: [recipient])") + let change = try edited( + doc, + [ + .replaceConstant( + doc.constant(named: "recipient")!, with: .agent(.cursor), + acceptingUses: doc.uses(ofConstant: "recipient")) + ]) + #expect(change.declaration.defaultAgents == ["cursor"]) + let array = try document( + "let recipients = [Agent.codex]\nlet agents = Agents(defaultAgents: recipients)") + let changed = try edited( + array, + [ + .replaceConstant( + array.constant(named: "recipients")!, with: .array([.agent(.cursor)]), + acceptingUses: array.uses(ofConstant: "recipients")) + ]) + #expect(changed.declaration.defaultAgents == ["cursor"]) + let unused = try document("let recipient = Agent.codex\nlet agents = Agents()") + let unusedChange = try unused.preparing([ + .replaceConstant( + unused.constant(named: "recipient")!, with: .agent(.cursor), acceptingUses: []) + ]) + #expect(unusedChange.delta.changedPointers.isEmpty) + #expect(!unusedChange.patches.isEmpty) + let changedDefault = try doc.preparing([ + .replaceConstant( + doc.constant(named: "recipient")!, with: .agent(.cursor), + acceptingUses: doc.uses(ofConstant: "recipient")) + ]) + #expect(changedDefault.delta.changedPointers == ["/defaultAgents/0"]) + } + + @Test func consistentFourSpaceIndentationIsInheritedAndConflictsAreRejected() throws { + let doc = try document( + """ + let agents = Agents( + components: [ + .ignore(name: "first", patterns: []), + ] + ) + """) + let change = try edited(doc, [.insertComponent(.instructions(), into: .root, at: .last)]) + #expect(String(decoding: change.bytes, as: UTF8.self).contains("\n .instructions(),")) + let replacement = try edited( + doc, + [.replaceComponent(doc.node(at: "/components/0")!, with: .ignore(name: "new", patterns: []))]) + #expect( + String(decoding: replacement.bytes, as: UTF8.self).contains("\n name: \"new\",")) + let withoutComma = try document( + """ + let agents = Agents( + components: [ + .ignore(name: "first", patterns: []) + ] + ) + """) + let longPattern = String(repeating: "x", count: 80) + let replaced = try edited( + withoutComma, + [ + .replaceComponent( + withoutComma.node(at: "/components/0")!, + with: .ignore(name: "new", patterns: [longPattern])) + ]) + #expect(String(decoding: replaced.bytes, as: UTF8.self).contains("\"\(longPattern)\"\n")) + let multiline = try document( + """ + let agents = Agents( + components: [ + .ignore( + name: "first", + patterns: [ + "first", + ] + ), + ] + ) + """) + let withComma = try edited( + multiline, + [ + .replaceComponent( + multiline.node(at: "/components/0")!, + with: .ignore(name: "new", patterns: [longPattern])) + ]) + #expect(String(decoding: withComma.bytes, as: UTF8.self).contains("\"\(longPattern)\",\n")) + let mixed = try document( + """ + let agents = Agents( + components: [ + .ignore(name: "first", patterns: []), + .ignore(name: "second", patterns: []), + ] + ) + """) + expectManifestFailure("manifest.edit.readOnly") { + try mixed.preparing([.insertComponent(.instructions(), into: .root, at: .last)]) + } + } + + @Test func configurationDictionariesKeepValueKeysAndAllowEntryEdits() throws { + for expression in ["[\"value\": 1, \"other\": 2]", ".object([\"value\": 1, \"other\": 2])"] { + let body = + "let agents = Agents(components: [.lspServer(name: \"s\", run: .executable(\"tool\"), languages: [\".swift\": \"swift\"], initializationOptions: [\"options\": " + + expression + "])])" + let doc = try document(body) + let handle = try #require(doc.node(at: "/components/0/initializationOptions/options")) + #expect(doc.editability(of: handle) == .direct) + let changed = try edited(doc, [.setDictionaryEntry(handle, key: "other", value: .integer(3))]) + #expect( + changed.bytes + == Array( + (manifestHeader + body.replacingOccurrences(of: "\"other\": 2", with: "\"other\": 3")) + .utf8)) + let removed = try edited( + changed, + [ + .removeDictionaryEntry( + changed.node(at: "/components/0/initializationOptions/options")!, key: "value") + ]) + #expect(removed.node(at: "/components/0/initializationOptions/options/value/other") != nil) + } + } + + @Test func replacingAnOwnerRejectsAnOverlappingChildHandle() throws { + let doc = try document( + "let agents = Agents(components: [.instructions(sections: [\"guide\"])])") + expectManifestFailure("manifest.edit.overlap") { + try doc.preparing([ + .replaceComponent(doc.node(at: "/components/0")!, with: .ignore(name: "x", patterns: [])), + .removeSection(doc.node(at: "/components/0/sections/0")!), + ]) + } + } + + @Test func movesPreserveCRLFAndIndentEveryOwnedCommentLine() throws { + let before = """ + let agents = Agents( + components: [ + // first owner + .ignore(name: "first", patterns: []), // inline owner + // second owner + .ignore(name: "second", patterns: []), + .instructions(), + ] + ) + """ + let expected = """ + let agents = Agents( + components: [ + // second owner + .ignore(name: "second", patterns: []), + // first owner + .ignore(name: "first", patterns: []), // inline owner + .instructions(), + ] + ) + """ + for newline in ["\n", "\r\n"] { + let bytes = Array( + (manifestHeader + before).replacingOccurrences(of: "\n", with: newline).utf8) + let doc = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) + let moved = try edited( + doc, + [ + .moveComponent( + doc.node(at: "/components/0")!, into: .root, at: .before(doc.node(at: "/components/2")!) + ) + ]) + #expect( + moved.bytes + == Array((manifestHeader + expected).replacingOccurrences(of: "\n", with: newline).utf8)) + } + } + + @Test func movesReindentOwnedTriviaAtADifferentContainerDepth() throws { + let before = """ + let agents = Agents( + components: [ + // follows first + .ignore(name: "first", patterns: []), // inline owner + ], + groups: [ + .group( + name: "g", + components: [ + .instructions(), + ] + ), + ] + ) + """ + let expected = """ + let agents = Agents( + components: [ + ], + groups: [ + .group( + name: "g", + components: [ + .instructions(), + // follows first + .ignore(name: "first", patterns: []), // inline owner + ] + ), + ] + ) + """ + let doc = try DeclarationDocument( + bytes: Array((manifestHeader + before).replacingOccurrences(of: "\n", with: "\r\n").utf8), + identity: DocumentIdentity("manifest")) + let moved = try edited( + doc, + [ + .moveComponent( + doc.node(at: "/components/0")!, into: .group(doc.node(at: "/groups/0")!), at: .last) + ]) + #expect( + moved.bytes + == Array((manifestHeader + expected).replacingOccurrences(of: "\n", with: "\r\n").utf8)) + } + + @Test func dictionaryPointersPreserveEscapedAndEmptyKeySegments() throws { + let doc = try document( + "let agents = Agents(components: [.lspServer(name: \"s\", run: .executable(\"tool\"), languages: [\".swift\": \"swift\"], initializationOptions: [\"\": 1, \"a/b~c\": 2])])" + ) + let root = "/components/0/initializationOptions" + #expect(doc.node(at: root + "/") != nil) + #expect(doc.node(at: root + "/a~1b~0c") != nil) + let changed = try edited( + doc, + [ + .setDictionaryEntry(doc.node(at: root)!, key: "", value: .integer(3)), + .setDictionaryEntry(doc.node(at: root)!, key: "a/b~c", value: .integer(4)), + ]) + #expect( + changed.bytes + == Array( + String(decoding: doc.bytes, as: UTF8.self).replacingOccurrences( + of: "\"\": 1", with: "\"\": 3" + ).replacingOccurrences(of: "\"a/b~c\": 2", with: "\"a/b~c\": 4").utf8)) + } + + @Test func expectedDeclarationComparisonRejectsDivergentIntent() throws { + let doc = try document("let agents = Agents()") + for edits: [ManifestEdit] in [[], [.insertComponent(.instructions(), into: .root, at: .last)]] { + let editor = DocumentEditor(document: doc) + editor.expected = Agents(defaultAgents: [.codex]).constructionValue + expectManifestFailure("manifest.edit.mismatch") { try editor.prepare(edits) } + #expect(doc.bytes == Array((manifestHeader + "let agents = Agents()").utf8)) + } + } + } diff --git a/Tests/AgentsManifestTests/Fixtures/Contract06.swift.txt b/Tests/AgentsManifestTests/Fixtures/ExportedGroup.swift.txt similarity index 100% rename from Tests/AgentsManifestTests/Fixtures/Contract06.swift.txt rename to Tests/AgentsManifestTests/Fixtures/ExportedGroup.swift.txt diff --git a/Tests/AgentsManifestTests/Fixtures/Contract05.swift.txt b/Tests/AgentsManifestTests/Fixtures/InstructionRecipients.swift.txt similarity index 100% rename from Tests/AgentsManifestTests/Fixtures/Contract05.swift.txt rename to Tests/AgentsManifestTests/Fixtures/InstructionRecipients.swift.txt diff --git a/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json b/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json index 58eeb81..b1c65be 100644 --- a/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json +++ b/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json @@ -1,102 +1,102 @@ { - "swiftSyntax": "604.0.0", - "toolchain": "Apple Swift 6.4 (swiftlang-6.4.0.34.1), arm64 macOS 27", "fixtures": { "ConsumerExample.swift.txt": { - "tokens": 741, - "syntaxReservation": 2980, + "syntaxDepth": 31, "syntaxNodes": 1707, - "syntaxDepth": 31 + "syntaxReservation": 2980, + "tokens": 741 }, - "Contract00.swift.txt": { - "tokens": 82, - "syntaxReservation": 344, + "CoreExample.swift.txt": { + "syntaxDepth": 26, "syntaxNodes": 199, - "syntaxDepth": 26 - }, - "Contract01.swift.txt": { - "tokens": 97, - "syntaxReservation": 404, - "syntaxNodes": 217, - "syntaxDepth": 25 - }, - "Contract05.swift.txt": { - "tokens": 34, - "syntaxReservation": 152, - "syntaxNodes": 88, - "syntaxDepth": 23 + "syntaxReservation": 344, + "tokens": 82 }, - "Contract06.swift.txt": { - "tokens": 93, - "syntaxReservation": 388, + "ExportedGroup.swift.txt": { + "syntaxDepth": 29, "syntaxNodes": 210, - "syntaxDepth": 29 + "syntaxReservation": 388, + "tokens": 93 }, - "Contract07.swift.txt": { - "tokens": 741, - "syntaxReservation": 2980, - "syntaxNodes": 1707, - "syntaxDepth": 31 + "InstructionRecipients.swift.txt": { + "syntaxDepth": 23, + "syntaxNodes": 88, + "syntaxReservation": 152, + "tokens": 34 }, - "CoreExample.swift.txt": { - "tokens": 82, - "syntaxReservation": 344, - "syntaxNodes": 199, - "syntaxDepth": 26 + "LiteralCoverage.swift.txt": { + "syntaxDepth": 29, + "syntaxNodes": 1805, + "syntaxReservation": 2932, + "tokens": 729 }, "MigrationEdgeExample.swift.txt": { - "tokens": 191, - "syntaxReservation": 780, + "syntaxDepth": 32, "syntaxNodes": 446, - "syntaxDepth": 32 + "syntaxReservation": 780, + "tokens": 191 }, "ProducerExample.swift.txt": { - "tokens": 93, - "syntaxReservation": 388, + "syntaxDepth": 29, "syntaxNodes": 210, - "syntaxDepth": 29 + "syntaxReservation": 388, + "tokens": 93 + }, + "RecipientConditions.swift.txt": { + "syntaxDepth": 25, + "syntaxNodes": 217, + "syntaxReservation": 404, + "tokens": 97 }, "RequirementValues.swift.txt": { - "tokens": 304, - "syntaxReservation": 1232, + "syntaxDepth": 26, "syntaxNodes": 823, - "syntaxDepth": 26 + "syntaxReservation": 1232, + "tokens": 304 }, "RequirementsExample.swift.txt": { - "tokens": 503, - "syntaxReservation": 2028, + "syntaxDepth": 29, "syntaxNodes": 1251, - "syntaxDepth": 29 + "syntaxReservation": 2028, + "tokens": 503 + }, + "SectionConcatenation.swift.txt": { + "syntaxDepth": 31, + "syntaxNodes": 1707, + "syntaxReservation": 2980, + "tokens": 741 + }, + "SharedRules.swift.txt": { + "syntaxDepth": 26, + "syntaxNodes": 199, + "syntaxReservation": 344, + "tokens": 82 }, "SketchExample.swift.txt": { - "tokens": 97, - "syntaxReservation": 404, + "syntaxDepth": 25, "syntaxNodes": 217, - "syntaxDepth": 25 + "syntaxReservation": 404, + "tokens": 97 }, "SkillsExample.swift.txt": { - "tokens": 34, - "syntaxReservation": 152, + "syntaxDepth": 23, "syntaxNodes": 88, - "syntaxDepth": 23 + "syntaxReservation": 152, + "tokens": 34 }, - "TasteSample.swift.txt": { - "tokens": 414, - "syntaxReservation": 1672, + "TeamConfiguration.swift.txt": { + "syntaxDepth": 29, "syntaxNodes": 961, - "syntaxDepth": 29 + "syntaxReservation": 1672, + "tokens": 414 }, "VocabularyDepthExample.swift.txt": { - "tokens": 68, - "syntaxReservation": 288, + "syntaxDepth": 43, "syntaxNodes": 155, - "syntaxDepth": 43 - }, - "LiteralCoverage.swift.txt": { - "tokens": 729, - "syntaxReservation": 2932, - "syntaxNodes": 1805, - "syntaxDepth": 29 + "syntaxReservation": 288, + "tokens": 68 } - } + }, + "swiftSyntax": "604.0.0", + "toolchain": "Apple Swift 6.4 (swiftlang-6.4.0.34.1), arm64 macOS 27" } diff --git a/Tests/AgentsManifestTests/Fixtures/Contract01.swift.txt b/Tests/AgentsManifestTests/Fixtures/RecipientConditions.swift.txt similarity index 100% rename from Tests/AgentsManifestTests/Fixtures/Contract01.swift.txt rename to Tests/AgentsManifestTests/Fixtures/RecipientConditions.swift.txt diff --git a/Tests/AgentsManifestTests/Fixtures/Contract07.swift.txt b/Tests/AgentsManifestTests/Fixtures/SectionConcatenation.swift.txt similarity index 100% rename from Tests/AgentsManifestTests/Fixtures/Contract07.swift.txt rename to Tests/AgentsManifestTests/Fixtures/SectionConcatenation.swift.txt diff --git a/Tests/AgentsManifestTests/Fixtures/Contract00.swift.txt b/Tests/AgentsManifestTests/Fixtures/SharedRules.swift.txt similarity index 100% rename from Tests/AgentsManifestTests/Fixtures/Contract00.swift.txt rename to Tests/AgentsManifestTests/Fixtures/SharedRules.swift.txt diff --git a/Tests/AgentsManifestTests/Fixtures/TasteSample.swift.txt b/Tests/AgentsManifestTests/Fixtures/TeamConfiguration.swift.txt similarity index 100% rename from Tests/AgentsManifestTests/Fixtures/TasteSample.swift.txt rename to Tests/AgentsManifestTests/Fixtures/TeamConfiguration.swift.txt diff --git a/Tests/AgentsManifestTests/FrontEndTests.swift b/Tests/AgentsManifestTests/FrontEndTests.swift index 3e32aec..a55f54a 100644 --- a/Tests/AgentsManifestTests/FrontEndTests.swift +++ b/Tests/AgentsManifestTests/FrontEndTests.swift @@ -29,6 +29,11 @@ struct FrontEndTests { let syntaxPin = pins.first { $0["identity"] as? String == "swift-syntax" }! #expect( (syntaxPin["state"] as! [String: String])["version"] == baseline["swiftSyntax"] as? String) + let fixtureDirectory = Bundle.module.resourceURL!.appendingPathComponent("Fixtures") + let sourceNames = try FileManager.default.contentsOfDirectory(atPath: fixtureDirectory.path) + .filter { $0.hasSuffix(".swift.txt") }.sorted() + #expect(compiledFixtures().map(\.name).sorted() == sourceNames) + #expect(baselineFixtures.keys.sorted() == sourceNames) for fixture in compiledFixtures() { let name = fixture.name let url = Bundle.module.resourceURL!.appendingPathComponent("Fixtures/" + name) @@ -73,24 +78,6 @@ struct FrontEndTests { } } - @Test func rangeValuesAndLiteralGroupReferencesAreEqual() throws { - let fixtures = compiledFixtures().first { $0.name == "RequirementValues.swift.txt" }! - let url = Bundle.module.resourceURL!.appendingPathComponent("Fixtures/" + fixtures.name) - let doc = try DeclarationDocument( - bytes: Array(Data(contentsOf: url)), identity: DocumentIdentity("manifest")) - let constants = doc.evaluation.constants - for pair in [ - ("majorFrom", "majorHelper"), ("majorFrom", "majorRange"), ("minorHelper", "minorRange"), - ("prereleaseFrom", "prereleaseHelper"), ("prereleaseFrom", "prereleaseRange"), - ("prereleaseMinor", "prereleaseMinorRange"), ("localLiteral", "localFactory"), - ] { - #expect(constants[pair.0]!.value == constants[pair.1]!.value, "\(pair)") - #expect( - Lowering.lower(constants[pair.0]!.value) == Lowering.lower(constants[pair.1]!.value), - "\(pair)") - } - } - @Test func domainValidationIsOfflineAndIncludesUnusedValues() throws { let bad = [ "let bad: Condition = .when(agents: [.codex, .codex])\nlet agents = Agents()", @@ -150,4 +137,35 @@ struct FrontEndTests { #expect(doc.sourceMap.locations(at: "/components/0/agents").first?.defaulted == true) #expect(doc.sourceMap.locations(at: "/components/0/sections/0").first?.origins.isEmpty == false) } + @Test func unusedSkillValuesReceiveTheirOwnDomainChecks() throws { + for body in [ + "let selection: SkillSelection = [\"duplicate\", \"duplicate\"]", + "let selection: SkillSelection = [\"../escape\"]", + "let override: SkillOverride = .skill(name: \"../escape\")", + ] { + expectManifestFailure("manifest.domain") { try document(body + "\nlet agents = Agents()") } + } + _ = try document( + "let selection: SkillSelection = [\"one\", \"two\"]\nlet override: SkillOverride = .skill(name: \"one\")\nlet agents = Agents()" + ) + } + + @Test func inspectionAndDocumentConstructionUseTheSameObservedPhases() throws { + let bytes = Array((manifestHeader + "let agents = Agents()").utf8) + var documentStages: [FrontEndStage] = [] + let doc = try DeclarationDocument( + bytes: bytes, identity: DocumentIdentity("manifest"), validateDomain: true + ) { stage, _ in documentStages.append(stage) } + var inspectionStages: [FrontEndStage] = [] + let metrics = try DeclarationDocument.inspect( + bytes: bytes, identity: DocumentIdentity("manifest"), checking: .declaration + ) { stage, _ in inspectionStages.append(stage) } + #expect(documentStages == [.admission, .parser, .evaluation, .domain, .lowering, .sourceMap]) + #expect(inspectionStages == documentStages + [.teardown, .complete]) + #expect(metrics.parserCalls == doc.metrics.parserCalls) + #expect(metrics.syntaxNodes == doc.metrics.syntaxNodes) + #expect(metrics.evaluationSteps == doc.metrics.evaluationSteps) + #expect(metrics.expandedNodes == doc.metrics.expandedNodes) + } + } diff --git a/Tests/AgentsManifestTests/InventoryTests.swift b/Tests/AgentsManifestTests/InventoryTests.swift index 1999770..a5c97c6 100644 --- a/Tests/AgentsManifestTests/InventoryTests.swift +++ b/Tests/AgentsManifestTests/InventoryTests.swift @@ -24,12 +24,28 @@ struct InventoryTests { }.filter { $0.hasPrefix("public ") } var signatures: [String] = [] var namedTypes = Set(["String", "Int", "Bool"]) - var literalTypes: [String: Set] = [:] - let protocolKinds = [ - "ExpressibleByStringLiteral": "string", "ExpressibleByIntegerLiteral": "integer", - "ExpressibleByBooleanLiteral": "boolean", "ExpressibleByNilLiteral": "nil", - "ExpressibleByArrayLiteral": "array", "ExpressibleByDictionaryLiteral": "dictionary", + var literalTypes: [String: Set] = [:] + let protocolKinds: [String: LiteralKind] = [ + "ExpressibleByStringLiteral": .string, "ExpressibleByIntegerLiteral": .integer, + "ExpressibleByBooleanLiteral": .boolean, "ExpressibleByNilLiteral": .nilLiteral, + "ExpressibleByArrayLiteral": .array, "ExpressibleByDictionaryLiteral": .dictionary, ] + func typeSpelling(_ raw: String) -> String { + var value = raw + for (alias, type) in Vocabulary.typeAliases { + value = value.replacingOccurrences(of: alias, with: type) + } + return value.replacingOccurrences(of: "Range", with: "VersionRange") + .filter { !$0.isWhitespace } + } + func signature( + _ owner: String, _ member: String, _ parameters: [(String, String, String?)], callable: Bool + ) -> String { + owner + "." + member + "(" + + parameters.map { + $0.0 + ":" + typeSpelling($0.1) + "=" + ($0.2?.filter { !$0.isWhitespace } ?? "required") + }.joined(separator: ",") + ")" + (callable ? " call" : " member") + } for block in blocks { let tree = Parser.parse(source: block) let source = SourceText(Array(block.utf8), identity: DocumentIdentity("interface")) @@ -37,66 +53,111 @@ struct InventoryTests { var pending: [(Syntax, String)] = [(Syntax(tree), "")] while let (node, owner) = pending.popLast() { var name = owner + let inheritance: InheritanceClauseSyntax? if let declaration = node.as(StructDeclSyntax.self) { name = declaration.name.text namedTypes.insert(name) - for inherited in declaration.inheritanceClause?.inheritedTypes ?? [] { - if let kind = protocolKinds[inherited.type.trimmedDescription] { - literalTypes[name, default: []].insert(kind) - } - } + inheritance = declaration.inheritanceClause } else if let declaration = node.as(EnumDeclSyntax.self) { name = declaration.name.text namedTypes.insert(name) - for inherited in declaration.inheritanceClause?.inheritedTypes ?? [] { - if let kind = protocolKinds[inherited.type.trimmedDescription] { - literalTypes[name, default: []].insert(kind) - } + inheritance = declaration.inheritanceClause + } else { + inheritance = nil + } + for inherited in inheritance?.inheritedTypes ?? [] { + if let kind = protocolKinds[inherited.type.trimmedDescription] { + literalTypes[name, default: []].insert(kind) } + } + if let declaration = node.as(ExtensionDeclSyntax.self), + declaration.extendedType.trimmedDescription == "Range" + { + name = "VersionRange" } else if let declaration = node.as(TypeAliasDeclSyntax.self) { namedTypes.insert(declaration.name.text) } else if let method = node.as(FunctionDeclSyntax.self), name != "Version" { - let parameters = method.signature.parameterClause.parameters.map { parameter in - let defaultValue = parameter.defaultValue?.value.trimmedDescription ?? "required" - return parameter.firstName.text + ":" - + parameter.type.trimmedDescription.replacingOccurrences(of: " ", with: "") + "=" - + defaultValue - }.joined(separator: ",") - signatures.append(name + "." + method.name.text + "(" + parameters + ")") + let parameters = method.signature.parameterClause.parameters.map { + ( + $0.firstName.text, $0.type.trimmedDescription, + $0.defaultValue?.value.trimmedDescription + ) + } + signatures.append(signature(name, method.name.text, parameters, callable: true)) } else if let initializer = node.as(InitializerDeclSyntax.self), name == "Agents" { - let parameters = initializer.signature.parameterClause.parameters.map { parameter in - parameter.firstName.text + ":" - + parameter.type.trimmedDescription.replacingOccurrences(of: " ", with: "") + "=" - + (parameter.defaultValue?.value.trimmedDescription ?? "required") - }.joined(separator: ",") - signatures.append("Agents.Agents(" + parameters + ")") + let parameters = initializer.signature.parameterClause.parameters.map { + ( + $0.firstName.text, $0.type.trimmedDescription, + $0.defaultValue?.value.trimmedDescription + ) + } + signatures.append(signature(name, "Agents", parameters, callable: true)) + } else if let declaration = node.as(EnumCaseDeclSyntax.self) { + for element in declaration.elements { + let parameters = (element.parameterClause?.parameters ?? []).map { + ( + $0.firstName?.text ?? "_", $0.type.trimmedDescription, + $0.defaultValue?.value.trimmedDescription + ) + } + signatures.append( + signature(name, element.name.text, parameters, callable: !parameters.isEmpty)) + } + } else if let declaration = node.as(VariableDeclSyntax.self), + declaration.modifiers.contains(where: { $0.name.text == "static" }) + { + for binding in declaration.bindings { + let member = try #require( + binding.pattern.as(IdentifierPatternSyntax.self)?.identifier.text) + signatures.append(signature(name, member, [], callable: false)) + } } for child in node.children(viewMode: .sourceAccurate) { pending.append((child, name)) } } } + func registeredType(_ type: ConstructionType) -> String { + switch type { + case .untyped: return "untyped" + case .named(let name): return name + case .array(let element): return "[" + registeredType(element) + "]" + case .dictionary(let element): return "[String:" + registeredType(element) + "]" + case .optional(let element): return registeredType(element) + "?" + } + } + let registered = Vocabulary.signatures.map { value in + signature( + value.type, value.member, + value.parameters.map { + ($0.label, registeredType($0.type), $0.defaultExpression) + }, callable: value.callable) + } #expect(namedTypes == Vocabulary.typeNames) #expect(literalTypes == Vocabulary.literalTypes) - let inventory = - try JSONSerialization.jsonObject( - with: Data(contentsOf: root.appendingPathComponent("Scripts/ManifestVocabulary.json"))) - as! [String: Any] - let factories = inventory["factories"] as! [[String: Any]] - let registered = factories.filter { $0["property"] == nil }.map { method in - let parameters = (method["parameters"] as! [[String: String]]).map { parameter in - parameter["label"]! + ":" + parameter["type"]!.replacingOccurrences(of: " ", with: "") + "=" - + (parameter["default"] ?? "required") - }.joined(separator: ",") - return (method["type"] as! String) + "." + (method["name"] as! String) + "(" + parameters - + ")" + #expect(signatures.sorted() == registered.sorted()) + #expect(Set(Vocabulary.scalarValues["Agent"]!.values) == Set(AgentID.allCases.map(\.rawValue))) + } + + @Test func generatedVocabularyAndCompilerFixturesMatchTheirSourcesByteForByte() throws { + let directory = try temporaryManifestDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + for script in ["generate-manifest-vocabulary.py", "generate-manifest-fixtures.py"] { + _ = try ProcessRunner.run( + "/usr/bin/env", + arguments: [ + "python3", root.appendingPathComponent("Scripts/" + script).path, + "--output-root", directory.path, + ]) } - #expect(Set(signatures.filter { !$0.hasPrefix(".upToNext") }) == Set(registered)) - let enumCount = (inventory["enums"] as! [String: [[String: Any]]]).values.reduce(0) { - $0 + $1.count + for path in [ + "Sources/AgentsDescription/Vocabulary.swift", + "Sources/AgentsDescription/VocabularyInventory.swift", + "Sources/AgentsManifest/StaticValueVocabulary.swift", + "Tests/AgentsManifestTests/CompiledFixtures.swift", + ] { + #expect( + try Data(contentsOf: root.appendingPathComponent(path)) + == Data(contentsOf: directory.appendingPathComponent(path)), "generated drift: \(path)") } - #expect(Vocabulary.signatures.count == factories.count + enumCount + 2) - #expect(Vocabulary.signatures.filter { $0.type == "VersionRange" }.count == 2) - #expect( - Vocabulary.signatures.filter { $0.type == "SkillSelection" && $0.member == "all" }.count == 1) } @Test func allContractSwiftBlocksPassTheRealParser() throws { diff --git a/Tests/AgentsManifestTests/ManifestExpectations.swift b/Tests/AgentsManifestTests/ManifestExpectations.swift new file mode 100644 index 0000000..90e60b3 --- /dev/null +++ b/Tests/AgentsManifestTests/ManifestExpectations.swift @@ -0,0 +1,17 @@ +import Testing + +@testable import AgentsManifest + +func expectManifestFailure( + _ code: String, sourceLocation: SourceLocation = #_sourceLocation, + _ operation: () throws -> T +) { + do { + _ = try operation() + Issue.record("expected diagnostic \(code)", sourceLocation: sourceLocation) + } catch let failure as ManifestFailure { + #expect(failure.diagnostics.map(\.code) == [code], sourceLocation: sourceLocation) + } catch { + Issue.record(error, sourceLocation: sourceLocation) + } +} diff --git a/Tests/AgentsManifestTests/ResourceAndVersionTests.swift b/Tests/AgentsManifestTests/ResourceTests.swift similarity index 62% rename from Tests/AgentsManifestTests/ResourceAndVersionTests.swift rename to Tests/AgentsManifestTests/ResourceTests.swift index 34557ae..2ef2f15 100644 --- a/Tests/AgentsManifestTests/ResourceAndVersionTests.swift +++ b/Tests/AgentsManifestTests/ResourceTests.swift @@ -5,8 +5,8 @@ import Testing @testable import AgentsManifest -@Suite("Manifest resources and language versions") -struct ResourceAndVersionTests { +@Suite("Manifest resources") +struct ResourceTests { @Test func directiveDiagnosticsAreLexicalAndDistinct() throws { for (text, code) in [ ("import AgentsDescription\nlet agents = Agents()", "manifest.version.missing"), @@ -48,7 +48,7 @@ struct ResourceAndVersionTests { let report = try probe( "unused-exponential-reuse", Array((manifestHeader + body + "let agents = Agents()").utf8), semantics: true, in: directory) - #expect(report.report.stage == "evaluation") + #expect(report.report.stage == .evaluation) #expect(report.report.status == "manifest.limit") var aliases = "let seed: ConfigurationValue = 0\n" var tail = "seed" @@ -81,12 +81,12 @@ struct ResourceAndVersionTests { "domain-reference-work", Array((manifestHeader + flatAliases + "let agents = Agents()").utf8), semantics: true, in: directory) - #expect(domainReport.report.stage == "domain") + #expect(domainReport.report.stage == .domain) #expect(domainReport.report.status == "manifest.limit") var deep = "let v0: ConfigurationValue = 0\n" for index in 1...65 { deep += "let v\(index): ConfigurationValue = .array([v\(index - 1)])\n" } - #expect(throws: ManifestFailure.self) { try document(deep + "let agents = Agents()") } - #expect(throws: ManifestFailure.self) { + expectManifestFailure("manifest.limit") { try document(deep + "let agents = Agents()") } + expectManifestFailure("manifest.limit") { try document( "let values: [Int] = [" + Array(repeating: "0", count: 10_001).joined(separator: ",") + "]\nlet agents = Agents()") @@ -105,44 +105,15 @@ struct ResourceAndVersionTests { #expect(doc.sourceMap.entries.reduce(0) { $0 + $1.origins.count } <= 1_000_000) let unchanged = try doc.preparing([.setWatch([])]) #expect(unchanged.patches.isEmpty) - #expect(throws: ManifestFailure.self) { + expectManifestFailure("manifest.limit") { try doc.preparing(Array(repeating: .setWatch([]), count: 101)) } let tiny = try document("let agents = Agents()") - #expect(throws: ManifestFailure.self) { + expectManifestFailure("manifest.limit") { try tiny.preparing([.setWatch(Array(repeating: "x", count: 10_001))]) } } - @Test func checkedSuccessorsCanonicalizeRangesAndKeepExactMetadata() throws { - let doc = try document( - """ - let agents = Agents(sources: [ - .source(name: "major", path: "major", " v1.2.0+lower "..<"2.0.0+upper"), - .source(name: "minor", path: "minor", "1.2.0"..<"1.3.0+meta"), - .source(name: "exact", path: "exact", exact: "V1.2.0+meta") - ]) - """) - #expect( - doc.declaration.sources[0]["requirement"] == .requirement(.upToNextMajor(from: "1.2.0+lower")) - ) - #expect( - doc.declaration.sources[1]["requirement"] == .requirement(.upToNextMinor(from: "1.2.0"))) - #expect(doc.declaration.sources[2]["requirement"] == .requirement(.exact("1.2.0+meta"))) - _ = try document( - "let agents = Agents(sources: [.source(name: \"s\", path: \"s\", \"\(Int.max).0.0\"..<\"\(Int.max).1.0\")])" - ) - for requirement in [ - "from: \"\(Int.max).0.0\"", ".upToNextMinor(from: \"1.\(Int.max).0\")", - "\"2.0.0\"..<\"1.0.0\"", "exact: \"1.0\"", - ] { - #expect(throws: ManifestFailure.self) { - try document( - "let agents = Agents(sources: [.source(name: \"s\", path: \"s\", \(requirement))])") - } - } - } - @Test func valueLiteralExamplesMatchTheRealCompiler() throws { let values: [(String, ConfigurationValue)] = [ ("nil", nil), ("true", true), ("-9_223_372_036_854_775_808", .integer(Int.min)), @@ -157,4 +128,61 @@ struct ResourceAndVersionTests { #expect(doc.evaluation.constants["value"]!.value == compiled.constructionValue) } } + @Test func editorLiteralConversionsMatchCompiledConfigurationValues() throws { + let values: [(StaticValue, ConfigurationValue)] = [ + (.null, nil), (.boolean(true), true), (.integer(Int.min), .integer(Int.min)), + (.string("first\n\nlast"), "first\n\nlast"), + (.array([.integer(1), .boolean(true), .null, .string("x")]), [1, true, nil, "x"]), + ( + .dictionary(["x": .dictionary(["y": .configuration(.decimal("1.25"))])]), + ["x": ["y": .decimal("1.25")]] + ), + ] + for (literal, compiled) in values { + let doc = try document("let value: ConfigurationValue = 0\nlet agents = Agents()") + let changed = try edited( + doc, [.replaceConstant(doc.constant(named: "value")!, with: literal, acceptingUses: [])]) + #expect(changed.evaluation.constants["value"]?.value == compiled.constructionValue) + } + } + + @Test func oversizedExplicitInsertionIsRejectedBeforeRendering() throws { + let directory = try temporaryManifestDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let result = try probe( + "oversized-direct-insert", + Array((manifestHeader + "let agents = Agents(components: [])").utf8), + extraArguments: ["--edit-oversized"], in: directory) + #expect(result.report.status == "manifest.limit") + #expect(result.report.stage == .editing) + #expect(result.report.peakMemoryBytes < 67_108_864) + } + + @Test func versionDirectiveRejectsBareCRBeforeTheParser() throws { + let directive = "// agents-tools-version: 1.0" + for suffix in ["\r", "\rimport AgentsDescription\nlet agents = Agents()"] { + do { + _ = try DeclarationDocument( + bytes: Array((directive + suffix).utf8), identity: DocumentIdentity("manifest")) + Issue.record("bare CR directive accepted") + } catch let failure as ManifestFailure { + #expect(failure.diagnostics[0].code == "manifest.version.invalid") + #expect(failure.metrics.parserCalls == 0) + #expect(failure.diagnostics[0].span.start == directive.utf8.count) + #expect(failure.diagnostics[0].span.line == 1) + #expect(failure.diagnostics[0].span.column == directive.utf8.count + 1) + } + } + for newline in ["\n", "\r\n"] { + _ = try DeclarationDocument( + bytes: Array( + (directive + newline + "import AgentsDescription" + newline + "let agents = Agents()") + .utf8), identity: DocumentIdentity("manifest")) + } + // EOF terminates the directive; the remaining grammar still requires an import. + expectManifestFailure("manifest.syntax") { + try DeclarationDocument(bytes: Array(directive.utf8), identity: DocumentIdentity("manifest")) + } + } + } diff --git a/Tests/AgentsManifestTests/ReviewRegressionTests.swift b/Tests/AgentsManifestTests/ReviewRegressionTests.swift deleted file mode 100644 index 00f1940..0000000 --- a/Tests/AgentsManifestTests/ReviewRegressionTests.swift +++ /dev/null @@ -1,144 +0,0 @@ -import AgentsCore -import AgentsDescription -import Foundation -import Testing - -@testable import AgentsManifest - -@Suite("Manifest review regressions") -struct ReviewRegressionTests { - @Test func oversizedExplicitInsertionIsRejectedBeforeRendering() throws { - let directory = try temporaryManifestDirectory() - defer { try? FileManager.default.removeItem(at: directory) } - let result = try probe( - "oversized-direct-insert", - Array((manifestHeader + "let agents = Agents(components: [])").utf8), - extraArguments: ["--edit-oversized"], in: directory) - #expect(result.report.status == "manifest.limit") - #expect(result.report.stage == "editing") - #expect(result.report.peakMemoryBytes < 67_108_864) - } - - @Test func inferredConstantsRetainContextDuringReplacement() throws { - let doc = try document( - "let recipient = Agent.codex\nlet agents = Agents(defaultAgents: [recipient])") - let change = try edited( - doc, - [ - .replaceConstant( - doc.constant(named: "recipient")!, with: .agent(.cursor), - acceptingUses: doc.uses(ofConstant: "recipient")) - ]) - #expect(change.declaration.defaultAgents == ["cursor"]) - let array = try document( - "let recipients = [Agent.codex]\nlet agents = Agents(defaultAgents: recipients)") - let changed = try edited( - array, - [ - .replaceConstant( - array.constant(named: "recipients")!, with: .array([.agent(.cursor)]), - acceptingUses: array.uses(ofConstant: "recipients")) - ]) - #expect(changed.declaration.defaultAgents == ["cursor"]) - let unused = try document("let recipient = Agent.codex\nlet agents = Agents()") - let unusedChange = try unused.preparing([ - .replaceConstant( - unused.constant(named: "recipient")!, with: .agent(.cursor), acceptingUses: []) - ]) - #expect(unusedChange.delta.changedPointers.isEmpty) - #expect(!unusedChange.patches.isEmpty) - let changedDefault = try doc.preparing([ - .replaceConstant( - doc.constant(named: "recipient")!, with: .agent(.cursor), - acceptingUses: doc.uses(ofConstant: "recipient")) - ]) - #expect(changedDefault.delta.changedPointers == ["/defaultAgents/0"]) - } - - @Test func consistentFourSpaceIndentationIsInheritedAndConflictsAreRejected() throws { - let doc = try document( - """ - let agents = Agents( - components: [ - .ignore(name: "first", patterns: []), - ] - ) - """) - let change = try edited(doc, [.insertComponent(.instructions(), into: .root, at: .last)]) - #expect(String(decoding: change.bytes, as: UTF8.self).contains("\n .instructions(),")) - let replacement = try edited( - doc, - [.replaceComponent(doc.node(at: "/components/0")!, with: .ignore(name: "new", patterns: []))]) - #expect( - String(decoding: replacement.bytes, as: UTF8.self).contains("\n name: \"new\",")) - let withoutComma = try document( - """ - let agents = Agents( - components: [ - .ignore(name: "first", patterns: []) - ] - ) - """) - let longPattern = String(repeating: "x", count: 80) - let replaced = try edited( - withoutComma, - [ - .replaceComponent( - withoutComma.node(at: "/components/0")!, - with: .ignore(name: "new", patterns: [longPattern])) - ]) - #expect(String(decoding: replaced.bytes, as: UTF8.self).contains("\"\(longPattern)\"\n")) - let multiline = try document( - """ - let agents = Agents( - components: [ - .ignore( - name: "first", - patterns: [ - "first", - ] - ), - ] - ) - """) - let withComma = try edited( - multiline, - [ - .replaceComponent( - multiline.node(at: "/components/0")!, - with: .ignore(name: "new", patterns: [longPattern])) - ]) - #expect(String(decoding: withComma.bytes, as: UTF8.self).contains("\"\(longPattern)\",\n")) - let mixed = try document( - """ - let agents = Agents( - components: [ - .ignore(name: "first", patterns: []), - .ignore(name: "second", patterns: []), - ] - ) - """) - #expect(throws: ManifestFailure.self) { - try mixed.preparing([.insertComponent(.instructions(), into: .root, at: .last)]) - } - } - - @Test func normalizedRequirementParentsKeepTheCompleteReferenceOriginChain() throws { - let doc = try document( - """ - let minimum: Version = "1.2.0" - let alias: Version = minimum - let agents = Agents(sources: [.source(name: "s", path: "s", from: alias)]) - """) - for pointer in ["/sources/0/requirement", "/sources/0/requirement/from"] { - let location = try #require(doc.sourceMap.locations(at: pointer).first) - #expect( - String(decoding: doc.bytes[location.span.start.. UInt64 { #endif } -func run(_ bytes: [UInt8], semantics: Bool) -> Report { - var metrics = FrontEndMetrics() - let clock = ContinuousClock() - let start = clock.now - let source = SourceText(Array(bytes.prefix(2_097_153)), identity: DocumentIdentity("manifest")) - var stage = "admission" - var stageStart = clock.now - progress(stage, metrics) +func run(_ bytes: [UInt8], semantics: Bool) -> ProbeReport { + var stage = FrontEndStage.admission do { - let admission = try Recognizer(source: source).recognize() - metrics.admissionSeconds = seconds(start.duration(to: clock.now)) - metrics.tokens = admission.tokens.count - metrics.syntaxReservation = admission.reservation - stage = "parser" - var enteringParser = metrics - enteringParser.parserCalls = 1 - progress(stage, enteringParser) - var syntax: CheckedSyntax? = try SyntaxValidation.parse( - source, admission: admission, metrics: metrics) - metrics = syntax!.metrics - if semantics { - stage = "evaluation" - stageStart = clock.now - progress(stage, metrics) - let evaluation = try Evaluator(source: source, admission: admission).evaluate() - metrics.evaluationSeconds = seconds(stageStart.duration(to: clock.now)) - metrics.evaluationSteps = evaluation.steps - metrics.expandedNodes = evaluation.total.nodes - metrics.decodedBytes = evaluation.total.strings - stage = "domain" - stageStart = clock.now - progress(stage, metrics) - _ = try DomainValidator(source: source, admission: admission, evaluation: evaluation) - .validate() - metrics.domainSeconds = seconds(stageStart.duration(to: clock.now)) - stage = "lowering" - stageStart = clock.now - progress(stage, metrics) - _ = Lowering.declaration(evaluation.root.value) - metrics.loweringSeconds = seconds(stageStart.duration(to: clock.now)) - stage = "sourceMap" - stageStart = clock.now - progress(stage, metrics) - _ = try MapBuilder(source: source, admission: admission, digest: "probe").build(evaluation) - metrics.sourceMapSeconds = seconds(stageStart.duration(to: clock.now)) - } - stage = "teardown" - let teardown = clock.now - syntax = nil - metrics.teardownSeconds = seconds(teardown.duration(to: clock.now)) - return Report( - status: "accepted", stage: "complete", offset: 0, line: 1, column: 1, message: "", - metrics: metrics, peakMemoryBytes: peakMemory()) - } catch let error as ManifestFailure { - let diagnostic = error.diagnostics[0] - if stage == "admission" { - metrics = error.metrics - metrics.admissionSeconds = seconds(start.duration(to: clock.now)) - } else if stage == "parser" { - metrics = error.metrics - } else { - let elapsed = seconds(stageStart.duration(to: clock.now)) - switch stage { - case "evaluation": metrics.evaluationSeconds = elapsed - case "domain": metrics.domainSeconds = elapsed - case "sourceMap": metrics.sourceMapSeconds = elapsed - default: break - } + let metrics = try DeclarationDocument.inspect( + bytes: bytes, identity: DocumentIdentity("manifest"), + checking: semantics ? .declaration : .syntax + ) { next, metrics in + stage = next + progress(next, metrics) } - return Report( - status: diagnostic.code, stage: stage, offset: diagnostic.span.start, + return ProbeReport( + status: "accepted", stage: .complete, metrics: metrics, peakMemoryBytes: peakMemory()) + } catch let failure as ManifestFailure { + let diagnostic = failure.diagnostics[0] + return ProbeReport( + status: diagnostic.code, stage: failure.stage, offset: diagnostic.span.start, line: diagnostic.span.line, column: diagnostic.span.column, message: diagnostic.message, - metrics: metrics, peakMemoryBytes: peakMemory()) + metrics: failure.metrics, peakMemoryBytes: peakMemory()) } catch { - return Report( - status: "unexpected", stage: stage, offset: 0, line: 0, column: 0, - message: String(describing: error), metrics: metrics, peakMemoryBytes: peakMemory()) + return ProbeReport( + status: "unexpected", stage: stage, message: String(describing: error), + metrics: FrontEndMetrics(), peakMemoryBytes: peakMemory()) } } let path = CommandLine.arguments[1] let handle = try FileHandle(forReadingFrom: URL(fileURLWithPath: path)) var bytes: [UInt8] = [] -while bytes.count < 2_097_153 { - let data = try handle.read(upToCount: 2_097_153 - bytes.count) ?? Data() +while bytes.count < (ManifestLimits.Input.bytes + 1) { + let data = try handle.read(upToCount: (ManifestLimits.Input.bytes + 1) - bytes.count) ?? Data() if data.isEmpty { break } bytes.append(contentsOf: data) } try handle.close() -let report: Report +let report: ProbeReport if CommandLine.arguments.contains("--edit-oversized") { do { let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) let component = Component.ignore( name: "large", patterns: [String(repeating: "x", count: 20_000_000)]) _ = try document.preparing([.insertComponent(component, into: .root, at: .first)]) - report = Report( - status: "accepted", stage: "editing", offset: 0, line: 1, column: 1, message: "", + report = ProbeReport( + status: "accepted", stage: .editing, offset: 0, line: 1, column: 1, message: "", metrics: document.metrics, peakMemoryBytes: peakMemory()) } catch let error as ManifestFailure { let diagnostic = error.diagnostics[0] - report = Report( - status: diagnostic.code, stage: "editing", offset: diagnostic.span.start, + report = ProbeReport( + status: diagnostic.code, stage: .editing, offset: diagnostic.span.start, line: diagnostic.span.line, column: diagnostic.span.column, message: diagnostic.message, metrics: error.metrics, peakMemoryBytes: peakMemory()) } diff --git a/Tests/ManifestTestSupport/ProbeReport.swift b/Tests/ManifestTestSupport/ProbeReport.swift new file mode 100644 index 0000000..f4ea3eb --- /dev/null +++ b/Tests/ManifestTestSupport/ProbeReport.swift @@ -0,0 +1,37 @@ +import AgentsManifest + +#if DEBUG + package let probeConfiguration = "debug" + package let probeWatchdogSeconds = 30.0 +#else + package let probeConfiguration = "release" + package let probeWatchdogSeconds = 2.0 +#endif + +/// Wire format shared by the watchdog parent and its isolated child. +package struct ProbeReport: Codable { + package let configuration: String + package let status: String + package let stage: FrontEndStage + package let offset: Int + package let line: Int + package let column: Int + package let message: String + package let metrics: FrontEndMetrics + package let peakMemoryBytes: UInt64 + + package init( + status: String, stage: FrontEndStage, offset: Int = 0, line: Int = 1, column: Int = 1, + message: String = "", metrics: FrontEndMetrics, peakMemoryBytes: UInt64 + ) { + configuration = probeConfiguration + self.status = status + self.stage = stage + self.offset = offset + self.line = line + self.column = column + self.message = message + self.metrics = metrics + self.peakMemoryBytes = peakMemoryBytes + } +} From 8da41c04b77b7d31d739e61a6a7fc30fd4b43503 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:16:27 +0800 Subject: [PATCH 010/171] fix: preserve typed collection elements and charge conversion work Already typed collection elements keep their values, and the evaluator charges collection conversion to the evaluation work budget. Generated vocabulary and fixtures are checked for drift by a CI command instead of inside swift test. The oversized edit test measures the memory added by the edit, the pipeline stages are separated from probe outcomes, and registries no longer carry test-only metadata. --- .github/swift-package.json | 6 + Documentation/Architecture/Package.md | 8 +- README.md | 19 +- Scripts/generate-manifest-fixtures.py | 15 +- Scripts/generate-manifest-vocabulary.py | 19 +- Scripts/manifest_generation.py | 37 ++ .../AgentsDescription/ConstructionValue.swift | 1 - .../VocabularyInventory.swift | 512 +++++++----------- Sources/AgentsManifest/Admission.swift | 76 ++- Sources/AgentsManifest/CanonicalPrinter.swift | 28 +- .../AgentsManifest/DeclarationDocument.swift | 20 - Sources/AgentsManifest/DocumentModels.swift | 8 +- Sources/AgentsManifest/DomainValidation.swift | 2 +- Sources/AgentsManifest/Evaluation.swift | 9 +- .../AgentsManifest/LiteralConversion.swift | 44 +- Sources/AgentsManifest/Lowering.swift | 8 +- Sources/AgentsManifest/ManifestFrontEnd.swift | 23 +- Sources/AgentsManifest/MapBuilder.swift | 4 +- Sources/AgentsManifest/PieceTable.swift | 12 +- .../AgentsManifest/SourceRequirements.swift | 14 + Sources/AgentsManifest/SyntaxValidation.swift | 42 +- .../AdversarialTests.swift | 4 +- .../CompiledFixtures.swift | 20 + .../Fixtures/ParserBaseline.json | 6 + .../Fixtures/VersionCollections.swift.txt | 8 + Tests/AgentsManifestTests/FrontEndTests.swift | 106 ++-- .../AgentsManifestTests/InventoryTests.swift | 32 +- .../LanguageVersionTests.swift | 65 +++ .../LiteralConversionTests.swift | 49 ++ Tests/AgentsManifestTests/ResourceTests.swift | 133 ++--- Tests/AgentsManifestTests/Watchdog.swift | 6 +- Tests/ManifestTestProcess/main.swift | 16 +- Tests/ManifestTestSupport/ProbeReport.swift | 20 +- 33 files changed, 761 insertions(+), 611 deletions(-) create mode 100644 Scripts/manifest_generation.py create mode 100644 Sources/AgentsManifest/SourceRequirements.swift create mode 100644 Tests/AgentsManifestTests/Fixtures/VersionCollections.swift.txt create mode 100644 Tests/AgentsManifestTests/LanguageVersionTests.swift create mode 100644 Tests/AgentsManifestTests/LiteralConversionTests.swift diff --git a/.github/swift-package.json b/.github/swift-package.json index 9c4a8bc..6a1180d 100644 --- a/.github/swift-package.json +++ b/.github/swift-package.json @@ -1,4 +1,10 @@ { + "commands": [ + { + "name": "manifest-generation", + "run": "python3 Scripts/generate-manifest-vocabulary.py --check\npython3 Scripts/generate-manifest-fixtures.py --check" + } + ], "test_configurations": ["debug", "release"], "compilers": [ {"name": "macos-26-xcode-26.6", "runner": "macos-26", "xcode": "26.6"} diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 1c4be86..7f8fe6e 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -68,8 +68,12 @@ only the standard library, with private payload storage and closed literal conformances. `Scripts/ManifestVocabulary.json` is the construction signature and literal inventory; `Scripts/generate-manifest-vocabulary.py` generates the public factories, literal conversions, package-only registrations and `StaticValue` factories -together. Byte-for-byte generation checks and exact contract signature comparisons -cover factories and enum cases; compiler-backed fixture tests check ordinary values. +together. The `manifest-generation` command in `.github/swift-package.json` checks +generated bytes on the macOS compiler runner, where Python and the Swift formatter +are available. Locally, run both generators with `python3 Scripts/ --check`. +`swift test` needs neither Python nor the formatter: it compares every registered +factory, enum case and default with the contract, and checks the complete fixture +inventory against compiler-backed values and the parser baseline. `AgentsManifest.DeclarationDocument` parses and statically evaluates supplied UTF-8 bytes without executing code or reading sources. Version selection, strict lexing and bounded diff --git a/README.md b/README.md index bff4087..a036b25 100644 --- a/README.md +++ b/README.md @@ -287,8 +287,17 @@ Read the [organization contributing guide][contributing] and the ### Development -Manifest generation checks require `python3` and `swift format` from the toolchain. -They regenerate into a temporary directory and leave checked-in sources unchanged. +The `manifest-generation` CI command runs on the macOS compiler runner with +`python3` and the toolchain's `swift format`. It regenerates into a temporary +directory and checks committed bytes. Run the same check locally with: + +```bash +python3 Scripts/generate-manifest-vocabulary.py --check +python3 Scripts/generate-manifest-fixtures.py --check +``` + +`swift test` checks contract signatures and the complete compiler-backed fixture +inventory without invoking these generators. Run the package's build, test, release and formatting checks: @@ -305,10 +314,10 @@ The required checks are `policy / policy` and `validate / result`, provided by full-SHA-pinned reusable workflows from `agents-tools/github-workflows`. Source policy validates PR titles, new commit messages and added lines. [Package validation configuration](.github/swift-package.json) selects Xcode 26.6 on `macos-26` and a digest-pinned official Swift Linux -container. macOS validation runs tests and a release build, plus strict +container. macOS and Linux validation run the full Debug and Release test suites. macOS also +runs a release build and generation checks, plus strict formatting with `.swift-format` over `Package.swift`, `Sources` and `Tests`. -Linux runs the full test suite, including the subprocess recovery tests. The -configuration owns the Linux compiler version and image digest. Tests also +The test suites include subprocess recovery tests. The configuration owns the Linux compiler version and image digest. Tests also require Perl, which is included by the Linux image's Git dependencies. Render and check the committed diff --git a/Scripts/generate-manifest-fixtures.py b/Scripts/generate-manifest-fixtures.py index dbe3b3c..4b0b282 100644 --- a/Scripts/generate-manifest-fixtures.py +++ b/Scripts/generate-manifest-fixtures.py @@ -3,9 +3,10 @@ import argparse import json import re -import subprocess from pathlib import Path +from manifest_generation import write_generated + ROOT = Path(__file__).resolve().parent.parent FIXTURES = ROOT / "Tests/AgentsManifestTests/Fixtures" DESTINATION = Path("Tests/AgentsManifestTests/CompiledFixtures.swift") @@ -43,14 +44,14 @@ def generated_source(paths): def main(): parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--output-root", type=Path, default=ROOT) + mode = parser.add_mutually_exclusive_group() + mode.add_argument("--output-root", type=Path, default=ROOT) + mode.add_argument("--check", action="store_true", help="fail on committed source drift") arguments = parser.parse_args() paths = sorted(FIXTURES.glob("*.swift.txt")) - destination = arguments.output_root / DESTINATION - destination.parent.mkdir(parents=True, exist_ok=True) - destination.write_text(generated_source(paths)) - subprocess.run(["swift", "format", "format", "--in-place", "--configuration", - str(ROOT / ".swift-format"), str(destination)], check=True) + write_generated( + {DESTINATION: generated_source(paths)}, arguments.output_root, check=arguments.check + ) if __name__ == "__main__": diff --git a/Scripts/generate-manifest-vocabulary.py b/Scripts/generate-manifest-vocabulary.py index a479b97..78dfa33 100644 --- a/Scripts/generate-manifest-vocabulary.py +++ b/Scripts/generate-manifest-vocabulary.py @@ -2,9 +2,10 @@ """Generate authoring types, evaluation metadata and editor factories from one inventory.""" import argparse import json -import subprocess from pathlib import Path +from manifest_generation import write_generated + ROOT = Path(__file__).resolve().parent.parent SPEC = json.loads((ROOT / "Scripts/ManifestVocabulary.json").read_text()) HEADER = "// Generated from Scripts/ManifestVocabulary.json. Run Scripts/generate-manifest-vocabulary.py.\n" @@ -130,7 +131,7 @@ def registration_source(): for parameter in factory.get("parameters", []): default = parameter.get("default") value = "nil" if default is None else "(" + default + " as " + parameter["type"] + ").constructionValue" - parameters.append("ConstructionParameter(label: " + quoted(parameter["label"]) + ", name: " + quoted(parameter["name"]) + ", type: " + type_expression(parameter["type"]) + ", defaultValue: " + value + ", defaultExpression: " + (quoted(default) if default is not None else "nil") + ")") + parameters.append("ConstructionParameter(label: " + quoted(parameter["label"]) + ", name: " + quoted(parameter["name"]) + ", type: " + type_expression(parameter["type"]) + ", defaultValue: " + value + ")") callable_member = not factory.get("property") and (not factory.get("enumCase") or bool(factory.get("parameters"))) lines.append(" ConstructionSignature(type: " + quoted(factory["type"]) + ", member: " + quoted(factory["name"]) + ", parameters: [" + ", ".join(parameters) + "], callable: " + str(callable_member).lower() + "),") lines += [" ]", " package static let literalTypes: [String: Set] = ["] @@ -151,7 +152,7 @@ def registration_source(): if all(not case.get("parameters") for case in cases): fields = {case["name"]: quoted(case.get("loweredValue", case["name"])) for case in cases} lines.append(" " + quoted(name) + ": " + dictionary_expression(fields) + ",") - lines += [" ]", " package static let taggedRecordTypes: Set = [" + ", ".join(map(quoted, SPEC["taggedRecordTypes"])) + "]", " package static let aliasTypes: [String: ConstructionType] = " + dictionary_expression({k: type_expression(v) for k, v in SPEC["aliases"].items()}), " package static let typeAliases: [String: String] = " + dictionary_expression({k: quoted(v) for k, v in SPEC["aliases"].items()}), "}", ""] + lines += [" ]", " package static let taggedRecordTypes: Set = [" + ", ".join(map(quoted, SPEC["taggedRecordTypes"])) + "]", " package static let aliasTypes: [String: ConstructionType] = " + dictionary_expression({k: type_expression(v) for k, v in SPEC["aliases"].items()}), "}", ""] return "\n".join(lines) @@ -165,20 +166,16 @@ def editor_factories_source(): def main(): parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--output-root", type=Path, default=ROOT) + mode = parser.add_mutually_exclusive_group() + mode.add_argument("--output-root", type=Path, default=ROOT) + mode.add_argument("--check", action="store_true", help="fail on committed source drift") arguments = parser.parse_args() outputs = { "Sources/AgentsDescription/Vocabulary.swift": authoring_source(), "Sources/AgentsDescription/VocabularyInventory.swift": registration_source(), "Sources/AgentsManifest/StaticValueVocabulary.swift": editor_factories_source(), } - paths = [] - for relative, source in outputs.items(): - path = arguments.output_root / relative - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(source) - paths.append(str(path)) - subprocess.run(["swift", "format", "format", "--in-place", "--configuration", str(ROOT / ".swift-format"), *paths], check=True) + write_generated(outputs, arguments.output_root, check=arguments.check) if __name__ == "__main__": diff --git a/Scripts/manifest_generation.py b/Scripts/manifest_generation.py new file mode 100644 index 0000000..bffe8bf --- /dev/null +++ b/Scripts/manifest_generation.py @@ -0,0 +1,37 @@ +"""Format generated Swift sources and optionally check committed bytes without writing them.""" +import subprocess +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent + + +def write_generated(outputs, output_root, *, check): + def render(directory): + paths = [] + for relative, source in outputs.items(): + path = directory / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(source) + paths.append(str(path)) + subprocess.run([ + "swift", "format", "format", "--in-place", "--configuration", + str(ROOT / ".swift-format"), *paths, + ], check=True) + + if not check: + render(output_root) + return + + scratch = ROOT / ".build/manifest-generation" + scratch.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=scratch) as directory: + generated = Path(directory) + render(generated) + drift = [relative for relative in outputs + if not (ROOT / relative).exists() + or (ROOT / relative).read_bytes() != (generated / relative).read_bytes()] + if drift: + for relative in drift: + print(f"generated drift: {relative}") + raise SystemExit(1) diff --git a/Sources/AgentsDescription/ConstructionValue.swift b/Sources/AgentsDescription/ConstructionValue.swift index a6659ee..8eb46fb 100644 --- a/Sources/AgentsDescription/ConstructionValue.swift +++ b/Sources/AgentsDescription/ConstructionValue.swift @@ -17,7 +17,6 @@ package struct ConstructionParameter: Sendable { package let name: String package let type: ConstructionType package let defaultValue: ConstructionValue? - package let defaultExpression: String? } package struct ConstructionSignature: Sendable { diff --git a/Sources/AgentsDescription/VocabularyInventory.swift b/Sources/AgentsDescription/VocabularyInventory.swift index c40f99a..f72ee30 100644 --- a/Sources/AgentsDescription/VocabularyInventory.swift +++ b/Sources/AgentsDescription/VocabularyInventory.swift @@ -15,692 +15,601 @@ package enum Vocabulary { parameters: [ ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [Agent]?).constructionValue), ConstructionParameter( label: "scopes", name: "scopes", type: .optional(.array(.named("Scope"))), - defaultValue: (nil as [Scope]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [Scope]?).constructionValue), ConstructionParameter( label: "platforms", name: "platforms", type: .optional(.array(.named("Platform"))), - defaultValue: (nil as [Platform]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [Platform]?).constructionValue), ], callable: true), ConstructionSignature( type: "Agents", member: "Agents", parameters: [ ConstructionParameter( label: "defaultAgents", name: "defaultAgents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [Agent]?).constructionValue), ConstructionParameter( label: "exports", name: "exports", type: .array(.named("String")), - defaultValue: ([] as [String]).constructionValue, defaultExpression: "[]"), + defaultValue: ([] as [String]).constructionValue), ConstructionParameter( label: "sources", name: "sources", type: .array(.named("Source")), - defaultValue: ([] as [Source]).constructionValue, defaultExpression: "[]"), + defaultValue: ([] as [Source]).constructionValue), ConstructionParameter( label: "components", name: "components", type: .array(.named("Component")), - defaultValue: ([] as [Component]).constructionValue, defaultExpression: "[]"), + defaultValue: ([] as [Component]).constructionValue), ConstructionParameter( label: "groups", name: "groups", type: .array(.named("ComponentGroup")), - defaultValue: ([] as [ComponentGroup]).constructionValue, defaultExpression: "[]"), + defaultValue: ([] as [ComponentGroup]).constructionValue), ConstructionParameter( label: "uses", name: "uses", type: .array(.named("GroupReference")), - defaultValue: ([] as [GroupReference]).constructionValue, defaultExpression: "[]"), + defaultValue: ([] as [GroupReference]).constructionValue), ConstructionParameter( label: "watch", name: "watch", type: .array(.named("String")), - defaultValue: ([] as [String]).constructionValue, defaultExpression: "[]"), + defaultValue: ([] as [String]).constructionValue), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), - ConstructionParameter( - label: "url", name: "url", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), - ConstructionParameter( - label: "url", name: "url", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "from", name: "from", type: .named("Version"), defaultValue: nil, - defaultExpression: nil), + label: "from", name: "from", type: .named("Version"), defaultValue: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), - ConstructionParameter( - label: "url", name: "url", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "exact", name: "exact", type: .named("Version"), defaultValue: nil, - defaultExpression: nil), + label: "exact", name: "exact", type: .named("Version"), defaultValue: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "url", name: "url", type: .named("String"), defaultValue: nil, - defaultExpression: nil), - ConstructionParameter( - label: "branch", name: "branch", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "branch", name: "branch", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), - ConstructionParameter( - label: "url", name: "url", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "revision", name: "revision", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "revision", name: "revision", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), + ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "url", name: "url", type: .named("String"), defaultValue: nil, - defaultExpression: nil), - ConstructionParameter( - label: "_", name: "range", type: .named("VersionRange"), defaultValue: nil, - defaultExpression: nil), + label: "_", name: "range", type: .named("VersionRange"), defaultValue: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "path", name: "path", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "path", name: "path", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "from", name: "from", type: .named("Version"), defaultValue: nil, - defaultExpression: nil), + label: "from", name: "from", type: .named("Version"), defaultValue: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "path", name: "path", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "exact", name: "exact", type: .named("Version"), defaultValue: nil, - defaultExpression: nil), + label: "exact", name: "exact", type: .named("Version"), defaultValue: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "path", name: "path", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "branch", name: "branch", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "branch", name: "branch", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "path", name: "path", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "revision", name: "revision", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "revision", name: "revision", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "path", name: "path", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "_", name: "range", type: .named("VersionRange"), defaultValue: nil, - defaultExpression: nil), + label: "_", name: "range", type: .named("VersionRange"), defaultValue: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ], callable: true), ConstructionSignature( type: "Source", member: "source", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "index", name: "index", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "index", name: "index", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ], callable: true), ConstructionSignature( type: "ComponentGroup", member: "group", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "components", name: "components", type: .array(.named("Component")), - defaultValue: ([] as [Component]).constructionValue, defaultExpression: "[]"), + defaultValue: ([] as [Component]).constructionValue), ConstructionParameter( label: "uses", name: "uses", type: .array(.named("GroupReference")), - defaultValue: ([] as [GroupReference]).constructionValue, defaultExpression: "[]"), + defaultValue: ([] as [GroupReference]).constructionValue), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Condition?).constructionValue), ], callable: true), ConstructionSignature( type: "GroupReference", member: "group", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Condition?).constructionValue), ], callable: true), ConstructionSignature( type: "GroupReference", member: "group", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "source", name: "source", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "source", name: "source", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Condition?).constructionValue), ], callable: true), ConstructionSignature(type: "SkillSelection", member: "all", parameters: [], callable: false), ConstructionSignature( type: "SkillOverride", member: "skill", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "mode", name: "mode", type: .optional(.named("InstallMode")), - defaultValue: (nil as InstallMode?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as InstallMode?).constructionValue), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [Agent]?).constructionValue), ], callable: true), ConstructionSignature( type: "SectionReference", member: "section", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "source", name: "source", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Condition?).constructionValue), ], callable: true), ConstructionSignature( type: "ChatGPTPrompt", member: "prompt", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "sections", name: "sections", type: .array(.named("SectionReference")), - defaultValue: nil, defaultExpression: nil), + defaultValue: nil), ConstructionParameter( label: "append", name: "append", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Condition?).constructionValue), ], callable: true), ConstructionSignature( type: "Resource", member: "path", parameters: [ - ConstructionParameter( - label: "_", name: "path", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + ConstructionParameter(label: "_", name: "path", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "source", name: "source", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ], callable: true), ConstructionSignature( type: "PromptContent", member: "file", parameters: [ - ConstructionParameter( - label: "_", name: "path", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + ConstructionParameter(label: "_", name: "path", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "source", name: "source", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ], callable: true), ConstructionSignature( type: "ExecutableInvocation", member: "executable", parameters: [ ConstructionParameter( - label: "_", name: "executable", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "_", name: "executable", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "arguments", name: "arguments", type: .array(.named("String")), - defaultValue: ([] as [String]).constructionValue, defaultExpression: "[]"), + defaultValue: ([] as [String]).constructionValue), ConstructionParameter( label: "environment", name: "environment", type: .dictionary(.named("RuntimeValue")), - defaultValue: ([:] as [String: RuntimeValue]).constructionValue, defaultExpression: "[:]"), + defaultValue: ([:] as [String: RuntimeValue]).constructionValue), ConstructionParameter( label: "workingDirectory", name: "workingDirectory", type: .optional(.named("Resource")), - defaultValue: (nil as Resource?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Resource?).constructionValue), ], callable: true), ConstructionSignature( type: "MCPTransport", member: "stdio", parameters: [ ConstructionParameter( - label: "_", name: "executable", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "_", name: "executable", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "arguments", name: "arguments", type: .array(.named("String")), - defaultValue: ([] as [String]).constructionValue, defaultExpression: "[]"), + defaultValue: ([] as [String]).constructionValue), ConstructionParameter( label: "environment", name: "environment", type: .dictionary(.named("RuntimeValue")), - defaultValue: ([:] as [String: RuntimeValue]).constructionValue, defaultExpression: "[:]"), + defaultValue: ([:] as [String: RuntimeValue]).constructionValue), ConstructionParameter( label: "workingDirectory", name: "workingDirectory", type: .optional(.named("Resource")), - defaultValue: (nil as Resource?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Resource?).constructionValue), ], callable: true), ConstructionSignature( type: "MCPTransport", member: "streamableHTTP", parameters: [ - ConstructionParameter( - label: "url", name: "url", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "headers", name: "headers", type: .dictionary(.named("RuntimeValue")), - defaultValue: ([:] as [String: RuntimeValue]).constructionValue, defaultExpression: "[:]"), + defaultValue: ([:] as [String: RuntimeValue]).constructionValue), ], callable: true), ConstructionSignature( type: "MCPTransport", member: "sse", parameters: [ - ConstructionParameter( - label: "url", name: "url", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "headers", name: "headers", type: .dictionary(.named("RuntimeValue")), - defaultValue: ([:] as [String: RuntimeValue]).constructionValue, defaultExpression: "[:]"), + defaultValue: ([:] as [String: RuntimeValue]).constructionValue), ], callable: true), ConstructionSignature( type: "PromptParameter", member: "parameter", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "description", name: "description", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "description", name: "description", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "defaultValue", name: "defaultValue", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ], callable: true), ConstructionSignature( type: "PermissionRule", member: "allow", parameters: [ ConstructionParameter( - label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil, - defaultExpression: nil), + label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil), ConstructionParameter( - label: "_", name: "pattern", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "_", name: "pattern", type: .named("String"), defaultValue: nil), ], callable: true), ConstructionSignature( type: "PermissionRule", member: "ask", parameters: [ ConstructionParameter( - label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil, - defaultExpression: nil), + label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil), ConstructionParameter( - label: "_", name: "pattern", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "_", name: "pattern", type: .named("String"), defaultValue: nil), ], callable: true), ConstructionSignature( type: "PermissionRule", member: "deny", parameters: [ ConstructionParameter( - label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil, - defaultExpression: nil), + label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil), ConstructionParameter( - label: "_", name: "pattern", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "_", name: "pattern", type: .named("String"), defaultValue: nil), ], callable: true), ConstructionSignature( type: "Component", member: "skills", parameters: [ ConstructionParameter( - label: "source", name: "source", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "source", name: "source", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "select", name: "select", type: .named("SkillSelection"), - defaultValue: (.all as SkillSelection).constructionValue, defaultExpression: ".all"), + defaultValue: (.all as SkillSelection).constructionValue), ConstructionParameter( label: "exclude", name: "exclude", type: .array(.named("String")), - defaultValue: ([] as [String]).constructionValue, defaultExpression: "[]"), + defaultValue: ([] as [String]).constructionValue), ConstructionParameter( label: "mode", name: "mode", type: .optional(.named("InstallMode")), - defaultValue: (nil as InstallMode?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as InstallMode?).constructionValue), ConstructionParameter( label: "overrides", name: "overrides", type: .array(.named("SkillOverride")), - defaultValue: ([] as [SkillOverride]).constructionValue, defaultExpression: "[]"), + defaultValue: ([] as [SkillOverride]).constructionValue), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [Agent]?).constructionValue), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Condition?).constructionValue), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), + defaultValue: ([:] as NativeConfiguration).constructionValue), ], callable: true), ConstructionSignature( type: "Component", member: "instructions", parameters: [ ConstructionParameter( label: "sections", name: "sections", type: .array(.named("SectionReference")), - defaultValue: ([] as [SectionReference]).constructionValue, defaultExpression: "[]"), + defaultValue: ([] as [SectionReference]).constructionValue), ConstructionParameter( label: "chatGPT", name: "chatGPT", type: .array(.named("ChatGPTPrompt")), - defaultValue: ([] as [ChatGPTPrompt]).constructionValue, defaultExpression: "[]"), + defaultValue: ([] as [ChatGPTPrompt]).constructionValue), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [Agent]?).constructionValue), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Condition?).constructionValue), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), + defaultValue: ([:] as NativeConfiguration).constructionValue), ], callable: true), ConstructionSignature( type: "Component", member: "mcpServer", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "transport", name: "transport", type: .named("MCPTransport"), defaultValue: nil, - defaultExpression: nil), + label: "transport", name: "transport", type: .named("MCPTransport"), defaultValue: nil), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [Agent]?).constructionValue), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Condition?).constructionValue), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), + defaultValue: ([:] as NativeConfiguration).constructionValue), ], callable: true), ConstructionSignature( type: "Component", member: "hook", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "event", name: "event", type: .named("HookEvent"), defaultValue: nil, - defaultExpression: nil), + label: "event", name: "event", type: .named("HookEvent"), defaultValue: nil), ConstructionParameter( - label: "run", name: "run", type: .named("ExecutableInvocation"), defaultValue: nil, - defaultExpression: nil), + label: "run", name: "run", type: .named("ExecutableInvocation"), defaultValue: nil), ConstructionParameter( label: "matcher", name: "matcher", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ConstructionParameter( label: "timeoutSeconds", name: "timeoutSeconds", type: .optional(.named("Int")), - defaultValue: (nil as Int?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Int?).constructionValue), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [Agent]?).constructionValue), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Condition?).constructionValue), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), + defaultValue: ([:] as NativeConfiguration).constructionValue), ], callable: true), ConstructionSignature( type: "Component", member: "subagent", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "description", name: "description", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "description", name: "description", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "prompt", name: "prompt", type: .named("PromptContent"), defaultValue: nil, - defaultExpression: nil), + label: "prompt", name: "prompt", type: .named("PromptContent"), defaultValue: nil), ConstructionParameter( label: "model", name: "model", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as String?).constructionValue), ConstructionParameter( label: "tools", name: "tools", type: .optional(.array(.named("String"))), - defaultValue: (nil as [String]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [String]?).constructionValue), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [Agent]?).constructionValue), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Condition?).constructionValue), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), + defaultValue: ([:] as NativeConfiguration).constructionValue), ], callable: true), ConstructionSignature( type: "Component", member: "command", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "description", name: "description", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "description", name: "description", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "prompt", name: "prompt", type: .named("PromptContent"), defaultValue: nil, - defaultExpression: nil), + label: "prompt", name: "prompt", type: .named("PromptContent"), defaultValue: nil), ConstructionParameter( label: "parameters", name: "parameters", type: .array(.named("PromptParameter")), - defaultValue: ([] as [PromptParameter]).constructionValue, defaultExpression: "[]"), + defaultValue: ([] as [PromptParameter]).constructionValue), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [Agent]?).constructionValue), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Condition?).constructionValue), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), + defaultValue: ([:] as NativeConfiguration).constructionValue), ], callable: true), ConstructionSignature( type: "Component", member: "lspServer", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "run", name: "run", type: .named("ExecutableInvocation"), defaultValue: nil, - defaultExpression: nil), + label: "run", name: "run", type: .named("ExecutableInvocation"), defaultValue: nil), ConstructionParameter( label: "languages", name: "languages", type: .dictionary(.named("String")), - defaultValue: nil, defaultExpression: nil), + defaultValue: nil), ConstructionParameter( label: "initializationOptions", name: "initializationOptions", type: .dictionary(.named("ConfigurationValue")), - defaultValue: ([:] as [String: ConfigurationValue]).constructionValue, - defaultExpression: "[:]"), + defaultValue: ([:] as [String: ConfigurationValue]).constructionValue), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [Agent]?).constructionValue), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Condition?).constructionValue), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), + defaultValue: ([:] as NativeConfiguration).constructionValue), ], callable: true), ConstructionSignature( type: "Component", member: "permissions", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "rules", name: "rules", type: .array(.named("PermissionRule")), defaultValue: nil, - defaultExpression: nil), + label: "rules", name: "rules", type: .array(.named("PermissionRule")), defaultValue: nil), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [Agent]?).constructionValue), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Condition?).constructionValue), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), + defaultValue: ([:] as NativeConfiguration).constructionValue), ], callable: true), ConstructionSignature( type: "Component", member: "ignore", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "patterns", name: "patterns", type: .array(.named("String")), defaultValue: nil, - defaultExpression: nil), + label: "patterns", name: "patterns", type: .array(.named("String")), defaultValue: nil), ConstructionParameter( label: "purpose", name: "purpose", type: .named("IgnorePurpose"), - defaultValue: (.context as IgnorePurpose).constructionValue, defaultExpression: ".context" - ), + defaultValue: (.context as IgnorePurpose).constructionValue), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [Agent]?).constructionValue), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Condition?).constructionValue), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), + defaultValue: ([:] as NativeConfiguration).constructionValue), ], callable: true), ConstructionSignature( type: "Component", member: "plugin", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "name", name: "name", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "path", name: "path", type: .named("String"), defaultValue: nil), ConstructionParameter( - label: "source", name: "source", type: .named("String"), defaultValue: nil, - defaultExpression: nil), + label: "source", name: "source", type: .named("String"), defaultValue: nil), ConstructionParameter( label: "mode", name: "mode", type: .named("PluginMode"), - defaultValue: (.components as PluginMode).constructionValue, - defaultExpression: ".components"), + defaultValue: (.components as PluginMode).constructionValue), ConstructionParameter( label: "select", name: "select", type: .optional(.array(.named("ComponentKind"))), - defaultValue: (nil as [ComponentKind]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [ComponentKind]?).constructionValue), ConstructionParameter( label: "exclude", name: "exclude", type: .array(.named("ComponentReference")), - defaultValue: ([] as [ComponentReference]).constructionValue, defaultExpression: "[]"), + defaultValue: ([] as [ComponentReference]).constructionValue), ConstructionParameter( label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as [Agent]?).constructionValue), ConstructionParameter( label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue, defaultExpression: "nil"), + defaultValue: (nil as Condition?).constructionValue), ConstructionParameter( label: "native", name: "native", type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue, defaultExpression: "[:]"), + defaultValue: ([:] as NativeConfiguration).constructionValue), ], callable: true), ConstructionSignature(type: "Agent", member: "claudeCode", parameters: [], callable: false), ConstructionSignature(type: "Agent", member: "codex", parameters: [], callable: false), @@ -717,50 +626,37 @@ package enum Vocabulary { ConstructionSignature( type: "RuntimeValue", member: "literal", parameters: [ - ConstructionParameter( - label: "_", name: "value", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "RuntimeValue", member: "environment", parameters: [ - ConstructionParameter( - label: "_", name: "value", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "RuntimeValue", member: "secret", parameters: [ - ConstructionParameter( - label: "_", name: "value", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "ConfigurationValue", member: "string", parameters: [ - ConstructionParameter( - label: "_", name: "value", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "ConfigurationValue", member: "integer", parameters: [ - ConstructionParameter( - label: "_", name: "value", type: .named("Int"), defaultValue: nil, defaultExpression: nil) + ConstructionParameter(label: "_", name: "value", type: .named("Int"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "ConfigurationValue", member: "decimal", parameters: [ - ConstructionParameter( - label: "_", name: "value", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "ConfigurationValue", member: "boolean", parameters: [ - ConstructionParameter( - label: "_", name: "value", type: .named("Bool"), defaultValue: nil, defaultExpression: nil - ) + ConstructionParameter(label: "_", name: "value", type: .named("Bool"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "ConfigurationValue", member: "null", parameters: [], callable: false), @@ -768,15 +664,14 @@ package enum Vocabulary { type: "ConfigurationValue", member: "array", parameters: [ ConstructionParameter( - label: "_", name: "value", type: .array(.named("ConfigurationValue")), defaultValue: nil, - defaultExpression: nil) + label: "_", name: "value", type: .array(.named("ConfigurationValue")), defaultValue: nil) ], callable: true), ConstructionSignature( type: "ConfigurationValue", member: "object", parameters: [ ConstructionParameter( label: "_", name: "value", type: .dictionary(.named("ConfigurationValue")), - defaultValue: nil, defaultExpression: nil) + defaultValue: nil) ], callable: true), ConstructionSignature(type: "HookEvent", member: "beforeTool", parameters: [], callable: false), ConstructionSignature(type: "HookEvent", member: "afterTool", parameters: [], callable: false), @@ -786,9 +681,7 @@ package enum Vocabulary { ConstructionSignature( type: "HookEvent", member: "native", parameters: [ - ConstructionParameter( - label: "_", name: "value", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "PermissionOperation", member: "read", parameters: [], callable: false), @@ -799,9 +692,7 @@ package enum Vocabulary { ConstructionSignature( type: "PermissionOperation", member: "tool", parameters: [ - ConstructionParameter( - label: "_", name: "value", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "IgnorePurpose", member: "context", parameters: [], callable: false), @@ -830,85 +721,73 @@ package enum Vocabulary { type: "ComponentReference", member: "skill", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "instruction", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "mcpServer", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "hook", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "subagent", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "command", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "lspServer", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "permissions", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "ignore", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "ComponentReference", member: "plugin", parameters: [ ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil, - defaultExpression: nil) + label: "name", name: "name", type: .named("String"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "VersionRange", member: "upToNextMajor", parameters: [ ConstructionParameter( - label: "from", name: "from", type: .named("Version"), defaultValue: nil, - defaultExpression: nil) + label: "from", name: "from", type: .named("Version"), defaultValue: nil) ], callable: true), ConstructionSignature( type: "VersionRange", member: "upToNextMinor", parameters: [ ConstructionParameter( - label: "from", name: "from", type: .named("Version"), defaultValue: nil, - defaultExpression: nil) + label: "from", name: "from", type: .named("Version"), defaultValue: nil) ], callable: true), ] package static let literalTypes: [String: Set] = [ @@ -984,7 +863,4 @@ package enum Vocabulary { package static let aliasTypes: [String: ConstructionType] = [ "NativeConfiguration": .dictionary(.dictionary(.named("ConfigurationValue"))) ] - package static let typeAliases: [String: String] = [ - "NativeConfiguration": "[String: [String: ConfigurationValue]]" - ] } diff --git a/Sources/AgentsManifest/Admission.swift b/Sources/AgentsManifest/Admission.swift index 48822fa..43815f4 100644 --- a/Sources/AgentsManifest/Admission.swift +++ b/Sources/AgentsManifest/Admission.swift @@ -1,15 +1,25 @@ import AgentsDescription import Foundation +private let utf8ByteOrderMark: [UInt8] = [0xEF, 0xBB, 0xBF] + +enum ProjectionKind: String, Sendable, Codable { + case string, integer, negative, boolean, array, dictionary, sequence, call, group + case member, reference, label, type, arrayType, dictionaryType + case importDeclaration = "import" + case letDeclaration = "let" + case nilLiteral = "nil" +} + struct ProjectionEvent: Sendable, Equatable, Comparable, Codable { let start: Int let end: Int - let kind: String + let kind: ProjectionKind let detail: String static func < (lhs: Self, rhs: Self) -> Bool { if lhs.start != rhs.start { return lhs.start < rhs.start } if lhs.end != rhs.end { return lhs.end < rhs.end } - if lhs.kind != rhs.kind { return lhs.kind < rhs.kind } + if lhs.kind != rhs.kind { return lhs.kind.rawValue < rhs.kind.rawValue } return lhs.detail < rhs.detail } } @@ -35,6 +45,24 @@ enum GrammarNodeKind: String, Sendable { case nilLiteral = "nil" } +extension GrammarNodeKind { + var projection: ProjectionKind { + switch self { + case .string: .string + case .integer: .integer + case .negative: .negative + case .boolean: .boolean + case .array: .array + case .dictionary: .dictionary + case .sequence, .range: .sequence + case .name: .reference + case .call: .call + case .group: .group + case .nilLiteral: .nilLiteral + } + } +} + struct Lexeme: Sendable { let text: String let range: Range @@ -113,12 +141,12 @@ final class Recognizer { throw fail("input byte limit", at: ManifestLimits.Input.bytes, code: "manifest.limit") } try validateUTF8() - let header = bytes.starts(with: [239, 187, 191]) ? 3 : 0 + let header = bytes.starts(with: utf8ByteOrderMark) ? utf8ByteOrderMark.count : 0 try version(at: header) try lex(from: header) let start = try take("import").range.lowerBound let module = try take("AgentsDescription") - emit("import", start.., _ detail: String = "") { + private func emit(_ kind: ProjectionKind, _ range: Range, _ detail: String = "") { events.append( ProjectionEvent(start: range.lowerBound, end: range.upperBound, kind: kind, detail: detail)) } private func node(_ value: GrammarNode, projection: Bool = true) -> Int { let id = nodes.count nodes.append(value) - if projection { emit(value.kind.rawValue, value.range, value.text) } + if projection { emit(value.kind.projection, value.range, value.text) } return id } @@ -587,17 +615,17 @@ final class Recognizer { let start = try open("[") let first = try type() let result: ConstructionType - let kind: String + let kind: ProjectionKind if peek(":") { guard first == .named("String") else { throw fail("dictionary key type must be String", at: start) } _ = try take(":") result = .dictionary(try type()) - kind = "dictionaryType" + kind = .dictionaryType } else { result = .array(first) - kind = "arrayType" + kind = .arrayType } emit(kind, start..<(try close("]"))) return result @@ -606,7 +634,7 @@ final class Recognizer { guard Vocabulary.typeNames.contains(token.text) else { throw fail("type outside construction vocabulary", at: token.range.lowerBound) } - emit("type", token.range, token.text) + emit(.type, token.range, token.text) return Vocabulary.aliasTypes[token.text] ?? .named(token.text) } @@ -640,7 +668,7 @@ final class Recognizer { token.kind == .identifier ? (token.text == "nil" ? .nilLiteral : .boolean) : (token.kind == .string ? .string : .integer) - emit(kind.rawValue, token.range, token.text) + emit(kind.projection, token.range, token.text) return node( GrammarNode(kind: kind, range: token.range, text: token.decoded ?? token.text), projection: false) @@ -651,8 +679,8 @@ final class Recognizer { guard integer.kind == .integer, integer.range.lowerBound == token.range.upperBound else { throw fail("minus requires adjacent decimal digits", at: integer.range.lowerBound) } - emit("integer", integer.range, integer.text) - emit("negative", start.. GrammarArgument { let token = try take(label) - emit("label", token.range, token.text) + emit(.label, token.range, token.text) _ = try take(":") return GrammarArgument(label: label, labelRange: token.range, value: try expression()) } @@ -787,18 +815,18 @@ final class Recognizer { if location == "index" { throw fail("index source has no requirement", at: peek().range.lowerBound) } - if ["from", "exact", "branch", "revision"].contains(peek().text) { + if SourceRequirements.labels.contains(peek().text) { args.append(try argument(label: peek().text)) } else if peek().kind == .string { let first = try primary() let op = try take("..<") - emit("reference", op.range, "..<") + emit(.reference, op.range, "..<") guard peek().kind == .string else { throw fail("range endpoint must be a string literal", at: peek().range.lowerBound) } let second = try primary() let range = nodes[first].range.lowerBound.. String { +func quoted(_ string: String) -> String { var result = "\"" for scalar in string.unicodeScalars { switch scalar.value { - case 34: result += "\\\"" - case 92: result += "\\\\" - case 10: result += "\\n" - case 13: result += "\\r" - case 9: result += "\\t" + case UInt32(UInt8(ascii: "\"")): result += "\\\"" + case UInt32(UInt8(ascii: "\\")): result += "\\\\" + case UInt32(UInt8(ascii: "\n")): result += "\\n" + case UInt32(UInt8(ascii: "\r")): result += "\\r" + case UInt32(UInt8(ascii: "\t")): result += "\\t" case 0..<32, 127: result += "\\u{" + String(scalar.value, radix: 16) + "}" default: result.unicodeScalars.append(scalar) } @@ -18,16 +18,16 @@ package func quoted(_ string: String) -> String { return result + "\"" } -package struct PrintStyle { - package var indent = " " - package var newline = "\n" - package var trailingComma = true +struct PrintStyle { + var indent = " " + var newline = "\n" + var trailingComma = true } -package struct CanonicalPrinter { - package var style = PrintStyle() +struct CanonicalPrinter { + var style = PrintStyle() - package func render(_ value: ConstructionValue, indentation: String = "") -> String { + func render(_ value: ConstructionValue, indentation: String = "") -> String { switch value { case .text(let text): return quoted(text) case .integer(let value): return String(value) @@ -174,6 +174,6 @@ package struct CanonicalPrinter { } } -package func utf8Less(_ lhs: String, _ rhs: String) -> Bool { +func utf8Less(_ lhs: String, _ rhs: String) -> Bool { lhs.utf8.lexicographicallyPrecedes(rhs.utf8) } diff --git a/Sources/AgentsManifest/DeclarationDocument.swift b/Sources/AgentsManifest/DeclarationDocument.swift index c4b9010..36e4a8c 100644 --- a/Sources/AgentsManifest/DeclarationDocument.swift +++ b/Sources/AgentsManifest/DeclarationDocument.swift @@ -42,26 +42,6 @@ public struct DeclarationDocument: Sendable { metrics = result.metrics } - /// Exercises the production pipeline through the selected phase and releases its tree. - /// The syntax projection corpus intentionally stops before contextual type checking. - package static func inspect( - bytes: [UInt8], identity: DocumentIdentity, checking: FrontEndCheck, - observe: ((FrontEndStage, FrontEndMetrics) -> Void)? = nil - ) throws -> FrontEndMetrics { - var result: FrontEndResult? = try ManifestFrontEnd.run( - bytes: bytes, identity: identity, checking: checking, observe: observe) - var metrics = result!.metrics - observe?(.teardown, metrics) - let clock = ContinuousClock() - let start = clock.now - // Keep ARC from releasing the tree before teardown timing starts. - withExtendedLifetime(result) {} - result = nil - metrics.teardownSeconds = seconds(start.duration(to: clock.now)) - observe?(.complete, metrics) - return metrics - } - /// A JSON Pointer into the lowered declaration: empty string denotes the root, /// arrays use decimal indexes, and object keys escape `~` as `~0` and `/` as `~1`. /// Source requirements and literal wrappers use their lowered fields (for example `/value`). diff --git a/Sources/AgentsManifest/DocumentModels.swift b/Sources/AgentsManifest/DocumentModels.swift index 243e6cf..1ca0489 100644 --- a/Sources/AgentsManifest/DocumentModels.swift +++ b/Sources/AgentsManifest/DocumentModels.swift @@ -28,15 +28,15 @@ public enum Editability: Sendable, Equatable { /// Checked values are constructed from the vocabulary or literal algebra, never source text. public struct StaticValue: Sendable { - package let value: ConstructionValue - package let type: ConstructionType - package let literal: Bool + let value: ConstructionValue + let type: ConstructionType + let literal: Bool private init(_ value: ConstructionValue, _ type: ConstructionType, literal: Bool = false) { self.value = value self.type = type self.literal = literal } - package static func checked(_ value: ConstructionValue, type: ConstructionType) -> Self { + static func checked(_ value: ConstructionValue, type: ConstructionType) -> Self { Self(value, type) } diff --git a/Sources/AgentsManifest/DomainValidation.swift b/Sources/AgentsManifest/DomainValidation.swift index a614f94..e27de3e 100644 --- a/Sources/AgentsManifest/DomainValidation.swift +++ b/Sources/AgentsManifest/DomainValidation.swift @@ -316,7 +316,7 @@ final class DomainValidator { i += 2 while i < bytes.count && bytes[i] != UInt8(ascii: "}") { i += 1 } } else if bytes[i...].starts(with: input) { - let first = i + 8 + let first = i + input.count i = first while i < bytes.count && bytes[i] != UInt8(ascii: "}") { i += 1 } if i == bytes.count diff --git a/Sources/AgentsManifest/Evaluation.swift b/Sources/AgentsManifest/Evaluation.swift index 476cacd..3186aef 100644 --- a/Sources/AgentsManifest/Evaluation.swift +++ b/Sources/AgentsManifest/Evaluation.swift @@ -199,7 +199,7 @@ final class Evaluator { let type = context ?? inferred let converted: ConstructionValue do { - converted = try LiteralConversion.convert(value, to: type) + converted = try LiteralConversion.convert(value, to: type) { try charge(at: id) } } catch let error as LiteralConversionError { throw fail(error.code, error.message, id) } @@ -252,13 +252,14 @@ final class Evaluator { cost.encoded += 32 } try check(cost, at: id) - let payload: ConstructionValue = - dictionary ? .object(fields.mapValues(\.value)) : .array(values.map(\.value)) let inferred: ConstructionType = dictionary ? .dictionary(elementType) : .array(elementType) let type = context ?? inferred let value: ConstructionValue do { - value = try LiteralConversion.convert(payload, to: type) + value = try LiteralConversion.collection( + dictionary ? .object(fields.mapValues(\.value)) : .array(values.map(\.value)), + kind: dictionary ? .dictionary : .array, to: type + ) { try charge(at: id) } } catch let error as LiteralConversionError { throw fail(error.code, error.message, id) } diff --git a/Sources/AgentsManifest/LiteralConversion.swift b/Sources/AgentsManifest/LiteralConversion.swift index 0bb7d81..17cdf02 100644 --- a/Sources/AgentsManifest/LiteralConversion.swift +++ b/Sources/AgentsManifest/LiteralConversion.swift @@ -10,7 +10,8 @@ enum LiteralConversionError: Error { } /// Closed literal conversions shared by static evaluation and domain edits. -/// Already constructed children keep their type; referenced expressions never enter this algebra. +/// Contextually evaluated collections retain their typed descendants; untyped edit +/// payloads use recursive conversion with an explicit work budget. enum LiteralConversion { static func kind(of value: ConstructionValue) -> LiteralKind? { switch value { @@ -45,7 +46,7 @@ enum LiteralConversion { static func convert( _ value: ConstructionValue, to context: ConstructionType, - charge: () throws -> Void = {} + charge: () throws -> Void ) throws -> ConstructionValue { try charge() if case .optional(let wrapped) = context { @@ -54,6 +55,7 @@ enum LiteralConversion { switch (value, context) { case (.text, .named("String")), (.integer, .named("Int")), (.boolean, .named("Bool")): return value + case (.version, .named("Version")), (.range, .named("VersionRange")): return value case (.node(let type, _, _), .named(let expected)) where type == expected: return value case (.array(let values), .array(let element)): return .array(try values.map { try convert($0, to: element, charge: charge) }) @@ -68,10 +70,42 @@ enum LiteralConversion { guard case .named(let name) = context, let kind = kind(of: value), let construction = Vocabulary.literalConstructions[name]?[kind] else { throw LiteralConversionError.incompatible } - var fields = construction.defaults - if let key = construction.payload, let type = construction.payloadType { - fields[key] = try convert(value, to: type, charge: charge) + let payload: ConstructionValue + if let type = construction.payloadType { + payload = try convert(value, to: type, charge: charge) + } else { + payload = value + } + return try construct(payload, name: name, using: construction, charge: charge) + } + + /// Elements have already been checked in their payload context. Only the new + /// container and its optional vocabulary wrapper need work; descendants stay shared. + static func collection( + _ payload: @autoclosure () -> ConstructionValue, kind: LiteralKind, + to context: ConstructionType, + charge: () throws -> Void + ) throws -> ConstructionValue { + try charge() + let context = context.unwrapped + switch (kind, context) { + case (.array, .array), (.dictionary, .dictionary): return payload() + default: break } + guard case .named(let name) = context, + let construction = Vocabulary.literalConstructions[name]?[kind] + else { throw LiteralConversionError.incompatible } + return try construct(payload(), name: name, using: construction, charge: charge) + } + + private static func construct( + _ payload: ConstructionValue, name: String, using construction: LiteralConstruction, + charge: () throws -> Void + ) throws -> ConstructionValue { + try charge() + var fields = construction.defaults + for _ in fields { try charge() } + if let key = construction.payload { fields[key] = payload } return .node(type: name, member: construction.member, fields: fields) } } diff --git a/Sources/AgentsManifest/Lowering.swift b/Sources/AgentsManifest/Lowering.swift index 89b46dc..d04bb75 100644 --- a/Sources/AgentsManifest/Lowering.swift +++ b/Sources/AgentsManifest/Lowering.swift @@ -1,8 +1,8 @@ import AgentsCore import AgentsDescription -package enum Lowering { - package static func declaration(_ value: ConstructionValue) -> DeclarationIR { +enum Lowering { + static func declaration(_ value: ConstructionValue) -> DeclarationIR { let fields = value.fields return DeclarationIR( defaultAgents: fields["defaultAgents"]?.array?.compactMap { lower($0).string }, @@ -14,7 +14,7 @@ package enum Lowering { watch: fields["watch"]?.strings ?? []) } - package static func requirement(_ range: Range) -> SourceRequirement { + static func requirement(_ range: Range) -> SourceRequirement { let lower = range.lowerBound let upper = range.upperBound let major = lower.successor(major: true) @@ -24,7 +24,7 @@ package enum Lowering { return .range(from: lower.normalized, to: upper.normalized) } - package static func lower(_ value: ConstructionValue) -> DeclarationValue { + static func lower(_ value: ConstructionValue) -> DeclarationValue { switch value { case .text(let text): return .string(text) case .integer(let integer): return .integer(integer) diff --git a/Sources/AgentsManifest/ManifestFrontEnd.swift b/Sources/AgentsManifest/ManifestFrontEnd.swift index bf67013..4edce7b 100644 --- a/Sources/AgentsManifest/ManifestFrontEnd.swift +++ b/Sources/AgentsManifest/ManifestFrontEnd.swift @@ -4,7 +4,7 @@ import Foundation import SwiftSyntax package enum FrontEndStage: String, Sendable, Codable { - case admission, parser, evaluation, domain, lowering, sourceMap, teardown, complete, editing + case admission, parser, evaluation, domain, lowering, sourceMap, teardown } package enum FrontEndCheck: Sendable, Equatable { @@ -29,7 +29,26 @@ struct FrontEndResult { /// Owns phase ordering for document construction and bounded syntax inspection. /// Observers receive phase-entry metrics; failures retain the phase and work already done. -enum ManifestFrontEnd { +package enum ManifestFrontEnd { + /// Exercises the production pipeline through the selected phase and releases its tree. + /// The syntax projection corpus intentionally stops before contextual type checking. + package static func inspect( + bytes: [UInt8], identity: DocumentIdentity, checking: FrontEndCheck, + observe: ((FrontEndStage, FrontEndMetrics) -> Void)? = nil + ) throws -> FrontEndMetrics { + var result: FrontEndResult? = try run( + bytes: bytes, identity: identity, checking: checking, observe: observe) + var metrics = result!.metrics + observe?(.teardown, metrics) + let clock = ContinuousClock() + let start = clock.now + // Keep ARC from releasing the tree before teardown timing starts. + withExtendedLifetime(result) {} + result = nil + metrics.teardownSeconds = seconds(start.duration(to: clock.now)) + return metrics + } + static func run( bytes: [UInt8], identity: DocumentIdentity, checking: FrontEndCheck, validateDomain: Bool = true, observe: ((FrontEndStage, FrontEndMetrics) -> Void)? = nil diff --git a/Sources/AgentsManifest/MapBuilder.swift b/Sources/AgentsManifest/MapBuilder.swift index d626ae5..b7ae713 100644 --- a/Sources/AgentsManifest/MapBuilder.swift +++ b/Sources/AgentsManifest/MapBuilder.swift @@ -108,8 +108,8 @@ final class MapBuilder { } for (key, childValue) in fields { if type == "Source", key == "requirement" { - let trace = ["from", "exact", "branch", "revision", "range"].compactMap { - resolved.fields[$0] + let trace = SourceRequirements.parameters.compactMap { + resolved.fields[$0.name] }.first if let trace, childValue != .none { let shape = requirementShape(childValue, trace: trace) diff --git a/Sources/AgentsManifest/PieceTable.swift b/Sources/AgentsManifest/PieceTable.swift index 8a0431f..612eb9e 100644 --- a/Sources/AgentsManifest/PieceTable.swift +++ b/Sources/AgentsManifest/PieceTable.swift @@ -1,4 +1,4 @@ -package struct PieceTable { +struct PieceTable { private enum Piece { case original(Range) case inserted([UInt8]) @@ -19,12 +19,12 @@ package struct PieceTable { } private let original: [UInt8] private var pieces: [Piece] - package init(_ bytes: [UInt8]) { + init(_ bytes: [UInt8]) { original = bytes pieces = [.original(0.., with replacement: [UInt8]) { + mutating func replace(_ range: Range, with replacement: [UInt8]) { var result: [Piece] = [] var offset = 0 var inserted = false @@ -55,7 +55,7 @@ package struct PieceTable { if !inserted && !replacement.isEmpty { result.append(.inserted(replacement)) } pieces = result } - package func patches() -> [SourcePatch] { + func patches() -> [SourcePatch] { var result: [SourcePatch] = [] var consumed = 0 var replacement: [UInt8] = [] diff --git a/Sources/AgentsManifest/SourceRequirements.swift b/Sources/AgentsManifest/SourceRequirements.swift new file mode 100644 index 0000000..2f927b6 --- /dev/null +++ b/Sources/AgentsManifest/SourceRequirements.swift @@ -0,0 +1,14 @@ +import AgentsDescription + +/// Source overloads share their first two location parameters and defaulted subpath. +/// Their remaining required parameters define the admitted requirement slots. +enum SourceRequirements { + static let parameters: [ConstructionParameter] = { + var names = Set() + return Vocabulary.signatures.filter { $0.type == "Source" }.flatMap { + $0.parameters.dropFirst(2) + }.filter { $0.defaultValue == nil && names.insert($0.name).inserted } + }() + + static let labels = Set(parameters.map(\.label).filter { $0 != "_" }) +} diff --git a/Sources/AgentsManifest/SyntaxValidation.swift b/Sources/AgentsManifest/SyntaxValidation.swift index 2383fdc..912d1e0 100644 --- a/Sources/AgentsManifest/SyntaxValidation.swift +++ b/Sources/AgentsManifest/SyntaxValidation.swift @@ -86,13 +86,13 @@ enum SyntaxValidation { static func projection(_ root: Syntax, source: SourceText) -> [ProjectionEvent] { var pending = [root] var events: [ProjectionEvent] = [] - func emit(_ node: Syntax, _ kind: String, _ detail: String = "") { + func emit(_ node: Syntax, _ kind: ProjectionKind, _ detail: String = "") { events.append( ProjectionEvent( start: node.positionAfterSkippingLeadingTrivia.utf8Offset, end: node.endPositionBeforeTrailingTrivia.utf8Offset, kind: kind, detail: detail)) } - func literal(_ node: Syntax, _ kind: String) { + func literal(_ node: Syntax, _ kind: ProjectionKind) { emit( node, kind, source.spelling( @@ -101,47 +101,47 @@ enum SyntaxValidation { } while let node = pending.popLast() { if let value = node.as(ImportDeclSyntax.self) { - emit(node, "import", value.path.first?.name.text ?? "") + emit(node, .importDeclaration, value.path.first?.name.text ?? "") } else if let value = node.as(VariableDeclSyntax.self) { emit( - node, "let", + node, .letDeclaration, value.bindings.first?.pattern.as(IdentifierPatternSyntax.self)?.identifier.text ?? "") } else if let value = node.as(MemberAccessExprSyntax.self) { - emit(node, "member", value.declName.baseName.text) + emit(node, .member, value.declName.baseName.text) if let base = value.base { pending.append(Syntax(base)) } continue } else if let value = node.as(DeclReferenceExprSyntax.self) { - emit(node, "reference", value.baseName.text) + emit(node, .reference, value.baseName.text) } else if let value = node.as(BinaryOperatorExprSyntax.self), value.operator.text == "..<" { - emit(node, "reference", "..<") + emit(node, .reference, "..<") } else if let value = node.as(LabeledExprSyntax.self), let label = value.label { - emit(Syntax(label), "label", label.text) + emit(Syntax(label), .label, label.text) } else if let value = node.as(IdentifierTypeSyntax.self) { - emit(node, "type", value.name.text) + emit(node, .type, value.name.text) } else if node.is(ArrayTypeSyntax.self) { - emit(node, "arrayType") + emit(node, .arrayType) } else if node.is(DictionaryTypeSyntax.self) { - emit(node, "dictionaryType") + emit(node, .dictionaryType) } else if node.is(FunctionCallExprSyntax.self) { - emit(node, "call") + emit(node, .call) } else if node.is(ArrayExprSyntax.self) { - emit(node, "array") + emit(node, .array) } else if node.is(DictionaryExprSyntax.self) { - emit(node, "dictionary") + emit(node, .dictionary) } else if node.is(TupleExprSyntax.self) { - emit(node, "group") + emit(node, .group) } else if node.is(SequenceExprSyntax.self) { - emit(node, "sequence") + emit(node, .sequence) } else if node.is(PrefixOperatorExprSyntax.self) { - emit(node, "negative") + emit(node, .negative) } else if node.is(IntegerLiteralExprSyntax.self) { - literal(node, "integer") + literal(node, .integer) } else if node.is(StringLiteralExprSyntax.self) { - literal(node, "string") + literal(node, .string) } else if node.is(BooleanLiteralExprSyntax.self) { - literal(node, "boolean") + literal(node, .boolean) } else if node.is(NilLiteralExprSyntax.self) { - literal(node, "nil") + literal(node, .nilLiteral) } pending.append(contentsOf: node.children(viewMode: .all)) } diff --git a/Tests/AgentsManifestTests/AdversarialTests.swift b/Tests/AgentsManifestTests/AdversarialTests.swift index c9c9d55..bfe7482 100644 --- a/Tests/AgentsManifestTests/AdversarialTests.swift +++ b/Tests/AgentsManifestTests/AdversarialTests.swift @@ -296,7 +296,7 @@ struct AdversarialTests { #expect(try SyntaxValidation.guardTree(Syntax(deep), source: source).depth == 128) } } - #expect(throws: ManifestFailure.self) { + expectManifestFailure("manifest.limit") { try SyntaxValidation.guardTree(Syntax(deep), source: source) } let atLimit = ArrayExprSyntax( @@ -314,7 +314,7 @@ struct AdversarialTests { expression: IntegerLiteralExprSyntax(literal: .integerLiteral("0")), trailingComma: .commaToken()) })) - #expect(throws: ManifestFailure.self) { + expectManifestFailure("manifest.limit") { try SyntaxValidation.guardTree(Syntax(wide), source: source) } } diff --git a/Tests/AgentsManifestTests/CompiledFixtures.swift b/Tests/AgentsManifestTests/CompiledFixtures.swift index 3e0a1b2..958c00c 100644 --- a/Tests/AgentsManifestTests/CompiledFixtures.swift +++ b/Tests/AgentsManifestTests/CompiledFixtures.swift @@ -30,6 +30,7 @@ func compiledFixtures() -> [CompiledManifestFixture] { compiledSketchExample(), compiledSkillsExample(), compiledTeamConfiguration(), + compiledVersionCollections(), compiledVocabularyDepthExample(), ] } @@ -789,6 +790,25 @@ private func compiledTeamConfiguration() -> CompiledManifestFixture { ]) } +private func compiledVersionCollections() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let versions: [Version] = ["1.2.3"] + let namedVersions: [String: Version] = ["stable": "1.2.3"] + let version: Version = "1.2.3" + let referencedVersions: [Version] = [version] + let agents = Agents() + return CompiledManifestFixture( + name: "VersionCollections.swift.txt", agents: agents, + constants: [ + "versions": versions.constructionValue, + "namedVersions": namedVersions.constructionValue, + "version": version.constructionValue, + "referencedVersions": referencedVersions.constructionValue, + "agents": agents.constructionValue, + ]) +} + private func compiledVocabularyDepthExample() -> CompiledManifestFixture { // agents-tools-version: 1.0 diff --git a/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json b/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json index b1c65be..afec5bd 100644 --- a/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json +++ b/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json @@ -90,6 +90,12 @@ "syntaxReservation": 1672, "tokens": 414 }, + "VersionCollections.swift.txt": { + "syntaxDepth": 14, + "syntaxNodes": 143, + "syntaxReservation": 208, + "tokens": 48 + }, "VocabularyDepthExample.swift.txt": { "syntaxDepth": 43, "syntaxNodes": 155, diff --git a/Tests/AgentsManifestTests/Fixtures/VersionCollections.swift.txt b/Tests/AgentsManifestTests/Fixtures/VersionCollections.swift.txt new file mode 100644 index 0000000..cd9dc64 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/VersionCollections.swift.txt @@ -0,0 +1,8 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let versions: [Version] = ["1.2.3"] +let namedVersions: [String: Version] = ["stable": "1.2.3"] +let version: Version = "1.2.3" +let referencedVersions: [Version] = [version] +let agents = Agents() diff --git a/Tests/AgentsManifestTests/FrontEndTests.swift b/Tests/AgentsManifestTests/FrontEndTests.swift index a55f54a..8988350 100644 --- a/Tests/AgentsManifestTests/FrontEndTests.swift +++ b/Tests/AgentsManifestTests/FrontEndTests.swift @@ -61,41 +61,85 @@ struct FrontEndTests { @Test func closedLiteralTyping() throws { let bodies = [ - "let text = \"x\"\nlet value: SectionReference = text", - "let text = \"x\"\nlet value: PromptContent = text", - "let text = \"x\"\nlet value: RuntimeValue = text", - "let text = \"1.2.0\"\nlet value: Version = text", - "let text = \"review\"\nlet value: GroupReference = text", - "let names = [\"x\"]\nlet value: SkillSelection = names", - "let text = \"x\"\nlet value: ConfigurationValue = text", - "let value = .copy", "let value = []", "let value = [:]", "let value = nil", - "let value = \"a\" + \"b\"", "let value: SkillSelection = [\"a\"] + [\"b\"]", - "let value: ConfigurationValue = [1] + [2]", "let value = Version(\"1.2.0\")", - "let value = String(stringLiteral: \"x\")", "let value = future\nlet future = 1", + ("let text = \"x\"\nlet value: SectionReference = text", "manifest.type"), + ("let text = \"x\"\nlet value: PromptContent = text", "manifest.type"), + ("let text = \"x\"\nlet value: RuntimeValue = text", "manifest.type"), + ("let text = \"1.2.0\"\nlet value: Version = text", "manifest.type"), + ("let text = \"review\"\nlet value: GroupReference = text", "manifest.type"), + ("let names = [\"x\"]\nlet value: SkillSelection = names", "manifest.type"), + ("let text = \"x\"\nlet value: ConfigurationValue = text", "manifest.type"), + ("let value = .copy", "manifest.type"), + ("let value = []", "manifest.type"), + ("let value = [:]", "manifest.type"), + ("let value = nil", "manifest.type"), + ("let value = \"a\" + \"b\"", "manifest.operator"), + ("let value: SkillSelection = [\"a\"] + [\"b\"]", "manifest.operator"), + ("let value: ConfigurationValue = [1] + [2]", "manifest.operator"), + ("let value = Version(\"1.2.0\")", "manifest.call"), + ("let value = String(stringLiteral: \"x\")", "manifest.call"), + ("let value = future\nlet future = 1", "manifest.reference"), ] - for body in bodies { - #expect(throws: ManifestFailure.self) { try document(body + "\nlet agents = Agents()") } + for (body, code) in bodies { + expectManifestFailure(code) { try document(body + "\nlet agents = Agents()") } } } @Test func domainValidationIsOfflineAndIncludesUnusedValues() throws { let bad = [ - "let bad: Condition = .when(agents: [.codex, .codex])\nlet agents = Agents()", - "let agents = Agents(sources: [.source(name: \".\", path: \"a\")])", - "let agents = Agents(sources: [.source(name: \"a\", url: \"https://EXAMPLE.org/r.git\"), .source(name: \"b\", url: \"https://example.org/r/\")])", - "let agents = Agents(components: [.hook(name: \"h\", event: .native(\"x\"), run: .executable(\"tool\"))])", - "let agents = Agents(components: [.hook(name: \"h\", event: .beforeTool, run: .executable(\"tool\"), timeoutSeconds: 0)])", - "let agents = Agents(components: [.subagent(name: \"../bad\", description: \"x\", prompt: \"x\")])", - "let agents = Agents(components: [.mcpServer(name: \"x\", transport: .sse(url: \"https://user:pw@example.org/mcp\"))])", - "let agents = Agents(components: [.command(name: \"x\", description: \"x\", prompt: \"${input:missing}\")])", - "let value: ConfigurationValue = .decimal(\"1e99999\")\nlet agents = Agents()", - "let value: Resource = .path(\"../escape\")\nlet agents = Agents()", - "let value: PermissionRule = .allow(.read, \"/private/**\")\nlet agents = Agents()", - "let value: PermissionRule = .deny(.write, \"../**\")\nlet agents = Agents()", - "let agents = Agents(groups: [.group(name: \"a\", uses: [\"b\"]), .group(name: \"b\", uses: [\"a\"])])", - "let agents = Agents(groups: [.group(name: \"unused\", uses: [\"missing\"])])", + ( + "let bad: Condition = .when(agents: [.codex, .codex])\nlet agents = Agents()", + "manifest.domain" + ), + ("let agents = Agents(sources: [.source(name: \".\", path: \"a\")])", "manifest.domain"), + ( + "let agents = Agents(sources: [.source(name: \"a\", url: \"https://EXAMPLE.org/r.git\"), .source(name: \"b\", url: \"https://example.org/r/\")])", + "manifest.domain" + ), + ( + "let agents = Agents(components: [.hook(name: \"h\", event: .native(\"x\"), run: .executable(\"tool\"))])", + "manifest.domain" + ), + ( + "let agents = Agents(components: [.hook(name: \"h\", event: .beforeTool, run: .executable(\"tool\"), timeoutSeconds: 0)])", + "manifest.domain" + ), + ( + "let agents = Agents(components: [.subagent(name: \"../bad\", description: \"x\", prompt: \"x\")])", + "manifest.domain" + ), + ( + "let agents = Agents(components: [.mcpServer(name: \"x\", transport: .sse(url: \"https://user:pw@example.org/mcp\"))])", + "manifest.domain" + ), + ( + "let agents = Agents(components: [.command(name: \"x\", description: \"x\", prompt: \"${input:missing}\")])", + "manifest.domain" + ), + ( + "let value: ConfigurationValue = .decimal(\"1e99999\")\nlet agents = Agents()", + "manifest.domain" + ), + ("let value: Resource = .path(\"../escape\")\nlet agents = Agents()", "manifest.domain"), + ( + "let value: PermissionRule = .allow(.read, \"/private/**\")\nlet agents = Agents()", + "manifest.domain" + ), + ( + "let value: PermissionRule = .deny(.write, \"../**\")\nlet agents = Agents()", + "manifest.domain" + ), + ( + "let agents = Agents(groups: [.group(name: \"a\", uses: [\"b\"]), .group(name: \"b\", uses: [\"a\"])])", + "manifest.group.cycle" + ), + ( + "let agents = Agents(groups: [.group(name: \"unused\", uses: [\"missing\"])])", + "manifest.group.missing" + ), ] - for input in bad { #expect(throws: ManifestFailure.self) { try document(input) } } + for (input, code) in bad { + expectManifestFailure(code) { try document(input) } + } let doc = try document( "let agents = Agents(sources: [.source(name: \"r\", url: \"intranet/team\")])") #expect(doc.diagnostics.first?.code == "manifest.domain") @@ -120,7 +164,7 @@ struct FrontEndTests { #expect(error.diagnostics[0].span.start > error.diagnostics[0].related[0].start) } } - #expect(throws: ManifestFailure.self) { + expectManifestFailure("manifest.dictionary.duplicateKey") { try document( "let value: ConfigurationValue = [\"é\": 1, \"e\\u{301}\": 2]\nlet agents = Agents()") } @@ -157,11 +201,11 @@ struct FrontEndTests { bytes: bytes, identity: DocumentIdentity("manifest"), validateDomain: true ) { stage, _ in documentStages.append(stage) } var inspectionStages: [FrontEndStage] = [] - let metrics = try DeclarationDocument.inspect( + let metrics = try ManifestFrontEnd.inspect( bytes: bytes, identity: DocumentIdentity("manifest"), checking: .declaration ) { stage, _ in inspectionStages.append(stage) } #expect(documentStages == [.admission, .parser, .evaluation, .domain, .lowering, .sourceMap]) - #expect(inspectionStages == documentStages + [.teardown, .complete]) + #expect(inspectionStages == documentStages + [.teardown]) #expect(metrics.parserCalls == doc.metrics.parserCalls) #expect(metrics.syntaxNodes == doc.metrics.syntaxNodes) #expect(metrics.evaluationSteps == doc.metrics.evaluationSteps) diff --git a/Tests/AgentsManifestTests/InventoryTests.swift b/Tests/AgentsManifestTests/InventoryTests.swift index a5c97c6..d999c63 100644 --- a/Tests/AgentsManifestTests/InventoryTests.swift +++ b/Tests/AgentsManifestTests/InventoryTests.swift @@ -15,6 +15,11 @@ struct InventoryTests { } @Test func contractSignaturesDefaultsAndLiteralProtocolsMatchRegistration() throws { + let inventory = try #require( + JSONSerialization.jsonObject( + with: Data(contentsOf: root.appendingPathComponent("Scripts/ManifestVocabulary.json"))) + as? [String: Any]) + let aliases = try #require(inventory["aliases"] as? [String: String]) let contract = try String( contentsOf: root.appendingPathComponent("Documentation/Proposals/AgentsManifest.md"), encoding: .utf8) @@ -32,7 +37,7 @@ struct InventoryTests { ] func typeSpelling(_ raw: String) -> String { var value = raw - for (alias, type) in Vocabulary.typeAliases { + for (alias, type) in aliases { value = value.replacingOccurrences(of: alias, with: type) } return value.replacingOccurrences(of: "Range", with: "VersionRange") @@ -128,7 +133,7 @@ struct InventoryTests { signature( value.type, value.member, value.parameters.map { - ($0.label, registeredType($0.type), $0.defaultExpression) + ($0.label, registeredType($0.type), $0.defaultValue.map { CanonicalPrinter().render($0) }) }, callable: value.callable) } #expect(namedTypes == Vocabulary.typeNames) @@ -137,29 +142,6 @@ struct InventoryTests { #expect(Set(Vocabulary.scalarValues["Agent"]!.values) == Set(AgentID.allCases.map(\.rawValue))) } - @Test func generatedVocabularyAndCompilerFixturesMatchTheirSourcesByteForByte() throws { - let directory = try temporaryManifestDirectory() - defer { try? FileManager.default.removeItem(at: directory) } - for script in ["generate-manifest-vocabulary.py", "generate-manifest-fixtures.py"] { - _ = try ProcessRunner.run( - "/usr/bin/env", - arguments: [ - "python3", root.appendingPathComponent("Scripts/" + script).path, - "--output-root", directory.path, - ]) - } - for path in [ - "Sources/AgentsDescription/Vocabulary.swift", - "Sources/AgentsDescription/VocabularyInventory.swift", - "Sources/AgentsManifest/StaticValueVocabulary.swift", - "Tests/AgentsManifestTests/CompiledFixtures.swift", - ] { - #expect( - try Data(contentsOf: root.appendingPathComponent(path)) - == Data(contentsOf: directory.appendingPathComponent(path)), "generated drift: \(path)") - } - } - @Test func allContractSwiftBlocksPassTheRealParser() throws { let contract = try String( contentsOf: root.appendingPathComponent("Documentation/Proposals/AgentsManifest.md"), diff --git a/Tests/AgentsManifestTests/LanguageVersionTests.swift b/Tests/AgentsManifestTests/LanguageVersionTests.swift new file mode 100644 index 0000000..56a0a64 --- /dev/null +++ b/Tests/AgentsManifestTests/LanguageVersionTests.swift @@ -0,0 +1,65 @@ +import AgentsCore +import Testing + +@testable import AgentsManifest + +@Suite("Manifest language version") +struct LanguageVersionTests { + @Test func directiveDiagnosticsAreLexicalAndDistinct() throws { + for (text, code) in [ + ("import AgentsDescription\nlet agents = Agents()", "manifest.version.missing"), + ( + "// agents-tools-version: 01.0\nimport AgentsDescription\nlet agents = Agents()", + "manifest.version.invalid" + ), + ( + "// agents-tools-version: 1.0 \nimport AgentsDescription\nlet agents = Agents()", + "manifest.version.invalid" + ), + ( + "// agents-tools-version: 2.0\nimport AgentsDescription\nlet agents = Agents()", + "manifest.version.unsupported" + ), + ( + manifestHeader + "// agents-tools-version: 1.0\nlet agents = Agents()", + "manifest.version.duplicate" + ), + ] { + do { + _ = try DeclarationDocument(bytes: Array(text.utf8), identity: DocumentIdentity("manifest")) + Issue.record("directive accepted") + } catch let failure as ManifestFailure { + #expect(failure.diagnostics[0].code == code) + #expect(failure.metrics.parserCalls == 0) + } + } + _ = try document("let text = \"// agents-tools-version: 1.0\"\nlet agents = Agents()") + } + + @Test func versionDirectiveRejectsBareCRBeforeTheParser() throws { + let directive = "// agents-tools-version: 1.0" + for suffix in ["\r", "\rimport AgentsDescription\nlet agents = Agents()"] { + do { + _ = try DeclarationDocument( + bytes: Array((directive + suffix).utf8), identity: DocumentIdentity("manifest")) + Issue.record("bare CR directive accepted") + } catch let failure as ManifestFailure { + #expect(failure.diagnostics[0].code == "manifest.version.invalid") + #expect(failure.metrics.parserCalls == 0) + #expect(failure.diagnostics[0].span.start == directive.utf8.count) + #expect(failure.diagnostics[0].span.line == 1) + #expect(failure.diagnostics[0].span.column == directive.utf8.count + 1) + } + } + for newline in ["\n", "\r\n"] { + _ = try DeclarationDocument( + bytes: Array( + (directive + newline + "import AgentsDescription" + newline + "let agents = Agents()") + .utf8), identity: DocumentIdentity("manifest")) + } + // EOF terminates the directive; the remaining grammar still requires an import. + expectManifestFailure("manifest.syntax") { + try DeclarationDocument(bytes: Array(directive.utf8), identity: DocumentIdentity("manifest")) + } + } +} diff --git a/Tests/AgentsManifestTests/LiteralConversionTests.swift b/Tests/AgentsManifestTests/LiteralConversionTests.swift new file mode 100644 index 0000000..823d0cb --- /dev/null +++ b/Tests/AgentsManifestTests/LiteralConversionTests.swift @@ -0,0 +1,49 @@ +import AgentsCore +import AgentsDescription +import Testing + +@testable import AgentsManifest + +@Suite("Manifest literal conversion") +struct LiteralConversionTests { + @Test(arguments: [ + "let versions: [Version] = [\"1.2.3\"]", + "let versions: [String: Version] = [\"stable\": \"1.2.3\"]", + "let version: Version = \"1.2.3\"\nlet versions: [Version] = [version]", + ]) + func versionCollectionsPreserveContextuallyTypedElements(_ body: String) throws { + _ = try document(body + "\nlet agents = Agents()") + } + @Test func valueLiteralExamplesMatchTheRealCompiler() throws { + let values: [(String, ConfigurationValue)] = [ + ("nil", nil), ("true", true), ("-9_223_372_036_854_775_808", .integer(Int.min)), + ("[1, true, nil, \"x\"]", [1, true, nil, "x"]), + ("[\"x\": [\"y\": .decimal(\"1.25\")]]", ["x": ["y": .decimal("1.25")]]), + ("\"\\0\\t\\n\\r\\\"\\'\\\\\\u{1F600}\"", "\0\t\n\r\"'\\😀"), + ("\"\"\"\n first\n\n last\n \"\"\"", "first\n\nlast"), + ] + for (expression, compiled) in values { + let doc = try document( + "let value: ConfigurationValue = " + expression + "\nlet agents = Agents()") + #expect(doc.evaluation.constants["value"]!.value == compiled.constructionValue) + } + } + @Test func editorLiteralConversionsMatchCompiledConfigurationValues() throws { + let values: [(StaticValue, ConfigurationValue)] = [ + (.null, nil), (.boolean(true), true), (.integer(Int.min), .integer(Int.min)), + (.string("first\n\nlast"), "first\n\nlast"), + (.array([.integer(1), .boolean(true), .null, .string("x")]), [1, true, nil, "x"]), + ( + .dictionary(["x": .dictionary(["y": .configuration(.decimal("1.25"))])]), + ["x": ["y": .decimal("1.25")]] + ), + ] + for (literal, compiled) in values { + let doc = try document("let value: ConfigurationValue = 0\nlet agents = Agents()") + let changed = try edited( + doc, [.replaceConstant(doc.constant(named: "value")!, with: literal, acceptingUses: [])]) + #expect(changed.evaluation.constants["value"]?.value == compiled.constructionValue) + } + } + +} diff --git a/Tests/AgentsManifestTests/ResourceTests.swift b/Tests/AgentsManifestTests/ResourceTests.swift index 2ef2f15..8711c21 100644 --- a/Tests/AgentsManifestTests/ResourceTests.swift +++ b/Tests/AgentsManifestTests/ResourceTests.swift @@ -7,37 +7,6 @@ import Testing @Suite("Manifest resources") struct ResourceTests { - @Test func directiveDiagnosticsAreLexicalAndDistinct() throws { - for (text, code) in [ - ("import AgentsDescription\nlet agents = Agents()", "manifest.version.missing"), - ( - "// agents-tools-version: 01.0\nimport AgentsDescription\nlet agents = Agents()", - "manifest.version.invalid" - ), - ( - "// agents-tools-version: 1.0 \nimport AgentsDescription\nlet agents = Agents()", - "manifest.version.invalid" - ), - ( - "// agents-tools-version: 2.0\nimport AgentsDescription\nlet agents = Agents()", - "manifest.version.unsupported" - ), - ( - manifestHeader + "// agents-tools-version: 1.0\nlet agents = Agents()", - "manifest.version.duplicate" - ), - ] { - do { - _ = try DeclarationDocument(bytes: Array(text.utf8), identity: DocumentIdentity("manifest")) - Issue.record("directive accepted") - } catch let failure as ManifestFailure { - #expect(failure.diagnostics[0].code == code) - #expect(failure.metrics.parserCalls == 0) - } - } - _ = try document("let text = \"// agents-tools-version: 1.0\"\nlet agents = Agents()") - } - @Test func everyConstantChargesItsFullExpandedCostBeforeUseOrMapping() throws { let directory = try temporaryManifestDirectory() defer { try? FileManager.default.removeItem(at: directory) } @@ -93,6 +62,41 @@ struct ResourceTests { } } + @Test func nestedCollectionsReuseTypedReferencedDescendants() throws { + let base = Array(repeating: "[0]", count: 5_000).joined(separator: ",") + var body = "let base: [[Int]] = [" + base + "]\n" + for index in 0..<4 { + body += "let nested\(index) = [[[[[[base]]]]]]\n" + } + let doc = try document(body + "let agents = Agents()") + let original = try #require(doc.evaluation.constants["base"]) + guard case .array(let originalElements) = original.value else { + Issue.record("base is not an array") + return + } + #expect(doc.evaluation.steps < ManifestLimits.Evaluation.steps) + for index in 0..<4 { + var descendant = try #require(doc.evaluation.constants["nested\(index)"]).value + for _ in 0..<6 { + guard case .array(let layer) = descendant, layer.count == 1 else { + Issue.record("missing collection layer") + return + } + descendant = layer[0] + } + guard case .array(let elements) = descendant else { + Issue.record("missing referenced array") + return + } + // Reusing the array storage keeps all 5,000 typed descendants out of conversion work. + originalElements.withUnsafeBufferPointer { original in + elements.withUnsafeBufferPointer { reused in + #expect(reused.baseAddress == original.baseAddress) + } + } + } + } + @Test func mapOriginsAndComparisonHaveIndependentBudgets() throws { let base = "let sections: [SectionReference] = [" @@ -114,38 +118,6 @@ struct ResourceTests { } } - @Test func valueLiteralExamplesMatchTheRealCompiler() throws { - let values: [(String, ConfigurationValue)] = [ - ("nil", nil), ("true", true), ("-9_223_372_036_854_775_808", .integer(Int.min)), - ("[1, true, nil, \"x\"]", [1, true, nil, "x"]), - ("[\"x\": [\"y\": .decimal(\"1.25\")]]", ["x": ["y": .decimal("1.25")]]), - ("\"\\0\\t\\n\\r\\\"\\'\\\\\\u{1F600}\"", "\0\t\n\r\"'\\😀"), - ("\"\"\"\n first\n\n last\n \"\"\"", "first\n\nlast"), - ] - for (expression, compiled) in values { - let doc = try document( - "let value: ConfigurationValue = " + expression + "\nlet agents = Agents()") - #expect(doc.evaluation.constants["value"]!.value == compiled.constructionValue) - } - } - @Test func editorLiteralConversionsMatchCompiledConfigurationValues() throws { - let values: [(StaticValue, ConfigurationValue)] = [ - (.null, nil), (.boolean(true), true), (.integer(Int.min), .integer(Int.min)), - (.string("first\n\nlast"), "first\n\nlast"), - (.array([.integer(1), .boolean(true), .null, .string("x")]), [1, true, nil, "x"]), - ( - .dictionary(["x": .dictionary(["y": .configuration(.decimal("1.25"))])]), - ["x": ["y": .decimal("1.25")]] - ), - ] - for (literal, compiled) in values { - let doc = try document("let value: ConfigurationValue = 0\nlet agents = Agents()") - let changed = try edited( - doc, [.replaceConstant(doc.constant(named: "value")!, with: literal, acceptingUses: [])]) - #expect(changed.evaluation.constants["value"]?.value == compiled.constructionValue) - } - } - @Test func oversizedExplicitInsertionIsRejectedBeforeRendering() throws { let directory = try temporaryManifestDirectory() defer { try? FileManager.default.removeItem(at: directory) } @@ -154,35 +126,12 @@ struct ResourceTests { Array((manifestHeader + "let agents = Agents(components: [])").utf8), extraArguments: ["--edit-oversized"], in: directory) #expect(result.report.status == "manifest.limit") - #expect(result.report.stage == .editing) - #expect(result.report.peakMemoryBytes < 67_108_864) - } - - @Test func versionDirectiveRejectsBareCRBeforeTheParser() throws { - let directive = "// agents-tools-version: 1.0" - for suffix in ["\r", "\rimport AgentsDescription\nlet agents = Agents()"] { - do { - _ = try DeclarationDocument( - bytes: Array((directive + suffix).utf8), identity: DocumentIdentity("manifest")) - Issue.record("bare CR directive accepted") - } catch let failure as ManifestFailure { - #expect(failure.diagnostics[0].code == "manifest.version.invalid") - #expect(failure.metrics.parserCalls == 0) - #expect(failure.diagnostics[0].span.start == directive.utf8.count) - #expect(failure.diagnostics[0].span.line == 1) - #expect(failure.diagnostics[0].span.column == directive.utf8.count + 1) - } - } - for newline in ["\n", "\r\n"] { - _ = try DeclarationDocument( - bytes: Array( - (directive + newline + "import AgentsDescription" + newline + "let agents = Agents()") - .utf8), identity: DocumentIdentity("manifest")) - } - // EOF terminates the directive; the remaining grammar still requires an import. - expectManifestFailure("manifest.syntax") { - try DeclarationDocument(bytes: Array(directive.utf8), identity: DocumentIdentity("manifest")) - } + #expect(result.report.operation == .editing) + #expect(result.report.preparationBaselineBytes != nil) + // Rendering the 20 MB pattern needs at least one 20 MB output buffer. Allow + // 8 MiB for allocator/runtime variation after the component is already in memory. + #expect(try #require(result.report.preparationPeakGrowthBytes) < 8 * 1_024 * 1_024) + try recordProbeResults([result], name: "oversized-insert-run") } } diff --git a/Tests/AgentsManifestTests/Watchdog.swift b/Tests/AgentsManifestTests/Watchdog.swift index 91bae8d..f25c827 100644 --- a/Tests/AgentsManifestTests/Watchdog.swift +++ b/Tests/AgentsManifestTests/Watchdog.swift @@ -80,11 +80,15 @@ func probe( #expect(elapsed < probeWatchdogSeconds, "\(name): launch-to-exit deadline") let report = try JSONDecoder().decode(ProbeReport.self, from: Data(contentsOf: output)) #expect(report.configuration == probeConfiguration, "\(name): child build configuration") + // A loose runaway-process guard, not a platform-specific memory promise. 512 MiB + // leaves room for the Swift runtime, Debug SwiftSyntax and bounded source/IR copies; + // it is well above the contract's 2 MiB input, 16 MiB values and 32 MiB encoding caps. #expect(report.peakMemoryBytes < 536_870_912, "\(name): peak memory \(report.peakMemoryBytes)") #expect(report.status != "unexpected", "\(report.message)") if report.stage == .admission { #expect(report.metrics.parserCalls == 0) } if report.status == "accepted" { - #expect(report.stage == .complete) + #expect(report.operation == .frontEnd) + #expect(report.stage == .teardown) #expect(report.metrics.parserCalls == 1) #expect(report.metrics.syntaxNodes <= report.metrics.syntaxReservation) } diff --git a/Tests/ManifestTestProcess/main.swift b/Tests/ManifestTestProcess/main.swift index 92f06d4..30b01f2 100644 --- a/Tests/ManifestTestProcess/main.swift +++ b/Tests/ManifestTestProcess/main.swift @@ -37,7 +37,7 @@ func peakMemory() -> UInt64 { func run(_ bytes: [UInt8], semantics: Bool) -> ProbeReport { var stage = FrontEndStage.admission do { - let metrics = try DeclarationDocument.inspect( + let metrics = try ManifestFrontEnd.inspect( bytes: bytes, identity: DocumentIdentity("manifest"), checking: semantics ? .declaration : .syntax ) { next, metrics in @@ -45,7 +45,7 @@ func run(_ bytes: [UInt8], semantics: Bool) -> ProbeReport { progress(next, metrics) } return ProbeReport( - status: "accepted", stage: .complete, metrics: metrics, peakMemoryBytes: peakMemory()) + status: "accepted", stage: .teardown, metrics: metrics, peakMemoryBytes: peakMemory()) } catch let failure as ManifestFailure { let diagnostic = failure.diagnostics[0] return ProbeReport( @@ -70,20 +70,24 @@ while bytes.count < (ManifestLimits.Input.bytes + 1) { try handle.close() let report: ProbeReport if CommandLine.arguments.contains("--edit-oversized") { + var preparationBaselineBytes: UInt64? do { let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) let component = Component.ignore( name: "large", patterns: [String(repeating: "x", count: 20_000_000)]) + preparationBaselineBytes = peakMemory() _ = try document.preparing([.insertComponent(component, into: .root, at: .first)]) report = ProbeReport( - status: "accepted", stage: .editing, offset: 0, line: 1, column: 1, message: "", - metrics: document.metrics, peakMemoryBytes: peakMemory()) + status: "accepted", operation: .editing, offset: 0, line: 1, column: 1, message: "", + metrics: document.metrics, peakMemoryBytes: peakMemory(), + preparationBaselineBytes: preparationBaselineBytes) } catch let error as ManifestFailure { let diagnostic = error.diagnostics[0] report = ProbeReport( - status: diagnostic.code, stage: .editing, offset: diagnostic.span.start, + status: diagnostic.code, operation: .editing, offset: diagnostic.span.start, line: diagnostic.span.line, column: diagnostic.span.column, message: diagnostic.message, - metrics: error.metrics, peakMemoryBytes: peakMemory()) + metrics: error.metrics, peakMemoryBytes: peakMemory(), + preparationBaselineBytes: preparationBaselineBytes) } } else { report = run(bytes, semantics: CommandLine.arguments.contains("--semantics")) diff --git a/Tests/ManifestTestSupport/ProbeReport.swift b/Tests/ManifestTestSupport/ProbeReport.swift index f4ea3eb..60eceeb 100644 --- a/Tests/ManifestTestSupport/ProbeReport.swift +++ b/Tests/ManifestTestSupport/ProbeReport.swift @@ -8,24 +8,34 @@ import AgentsManifest package let probeWatchdogSeconds = 2.0 #endif +package enum ProbeOperation: String, Codable { + case frontEnd, editing +} + /// Wire format shared by the watchdog parent and its isolated child. package struct ProbeReport: Codable { package let configuration: String package let status: String - package let stage: FrontEndStage + package let operation: ProbeOperation + package let stage: FrontEndStage? package let offset: Int package let line: Int package let column: Int package let message: String package let metrics: FrontEndMetrics package let peakMemoryBytes: UInt64 + package let preparationBaselineBytes: UInt64? + package let preparationPeakGrowthBytes: UInt64? package init( - status: String, stage: FrontEndStage, offset: Int = 0, line: Int = 1, column: Int = 1, - message: String = "", metrics: FrontEndMetrics, peakMemoryBytes: UInt64 + status: String, operation: ProbeOperation = .frontEnd, stage: FrontEndStage? = nil, + offset: Int = 0, line: Int = 1, column: Int = 1, + message: String = "", metrics: FrontEndMetrics, peakMemoryBytes: UInt64, + preparationBaselineBytes: UInt64? = nil ) { configuration = probeConfiguration self.status = status + self.operation = operation self.stage = stage self.offset = offset self.line = line @@ -33,5 +43,9 @@ package struct ProbeReport: Codable { self.message = message self.metrics = metrics self.peakMemoryBytes = peakMemoryBytes + self.preparationBaselineBytes = preparationBaselineBytes + preparationPeakGrowthBytes = preparationBaselineBytes.map { + peakMemoryBytes > $0 ? peakMemoryBytes - $0 : 0 + } } } From 87069511482d2f352690af069217d9fc1a7fd0af Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:06:57 +0800 Subject: [PATCH 011/171] refactor: tidy manifest generation checks and recognizer projections Each generator has its own CI check that reports drift on stderr with the command that fixes it, and generation leaves no bytecode in the tree. Source location labels and requirement slots come from the registered signatures, recognizer projections are optional per node kind, and probe reports state that memory baselines are high-water marks. --- .github/swift-package.json | 8 ++- Documentation/Architecture/Package.md | 11 ++-- README.md | 27 +++++----- Scripts/generate-manifest-fixtures.py | 17 +++--- Scripts/generate-manifest-vocabulary.py | 21 ++++---- Scripts/manifest_generation.py | 54 +++++++++++-------- Sources/AgentsManifest/Admission.swift | 53 +++++++++--------- Sources/AgentsManifest/CanonicalPrinter.swift | 14 ++--- Sources/AgentsManifest/DomainValidation.swift | 5 +- Sources/AgentsManifest/Evaluation.swift | 2 +- .../AgentsManifest/LiteralConversion.swift | 13 +++-- Sources/AgentsManifest/ManifestFrontEnd.swift | 5 +- .../AgentsManifest/SourceRequirements.swift | 15 ++++-- .../AgentsManifestTests/InventoryTests.swift | 35 ++++++++++++ .../LiteralConversionTests.swift | 11 +--- Tests/AgentsManifestTests/ResourceTests.swift | 19 +++++-- Tests/AgentsManifestTests/Watchdog.swift | 3 +- Tests/ManifestTestProcess/main.swift | 8 +-- Tests/ManifestTestSupport/ProbeReport.swift | 17 +++--- 19 files changed, 205 insertions(+), 133 deletions(-) diff --git a/.github/swift-package.json b/.github/swift-package.json index 6a1180d..22e5cd5 100644 --- a/.github/swift-package.json +++ b/.github/swift-package.json @@ -1,8 +1,12 @@ { "commands": [ { - "name": "manifest-generation", - "run": "python3 Scripts/generate-manifest-vocabulary.py --check\npython3 Scripts/generate-manifest-fixtures.py --check" + "name": "manifest-vocabulary-generation", + "run": "python3 Scripts/generate-manifest-vocabulary.py --check" + }, + { + "name": "manifest-fixture-generation", + "run": "python3 Scripts/generate-manifest-fixtures.py --check" } ], "test_configurations": ["debug", "release"], diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 7f8fe6e..95c7871 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -68,12 +68,11 @@ only the standard library, with private payload storage and closed literal conformances. `Scripts/ManifestVocabulary.json` is the construction signature and literal inventory; `Scripts/generate-manifest-vocabulary.py` generates the public factories, literal conversions, package-only registrations and `StaticValue` factories -together. The `manifest-generation` command in `.github/swift-package.json` checks -generated bytes on the macOS compiler runner, where Python and the Swift formatter -are available. Locally, run both generators with `python3 Scripts/ --check`. -`swift test` needs neither Python nor the formatter: it compares every registered -factory, enum case and default with the contract, and checks the complete fixture -inventory against compiler-backed values and the parser baseline. +together. CI commands in `.github/swift-package.json` compare generated bytes on +the last compiler entry's runner. SwiftPM tests compare registered signatures, +defaults and literal protocols with the contract, and the complete fixture +inventory with compiler-backed values and the parser baseline. See +[Development](../../README.md#development) for local validation commands. `AgentsManifest.DeclarationDocument` parses and statically evaluates supplied UTF-8 bytes without executing code or reading sources. Version selection, strict lexing and bounded diff --git a/README.md b/README.md index a036b25..1df85fb 100644 --- a/README.md +++ b/README.md @@ -287,25 +287,21 @@ Read the [organization contributing guide][contributing] and the ### Development -The `manifest-generation` CI command runs on the macOS compiler runner with -`python3` and the toolchain's `swift format`. It regenerates into a temporary -directory and checks committed bytes. Run the same check locally with: - -```bash -python3 Scripts/generate-manifest-vocabulary.py --check -python3 Scripts/generate-manifest-fixtures.py --check -``` - +The generation commands in `.github/swift-package.json` run on the last +compiler entry's runner, using `python3` and the toolchain's `swift format`. +They regenerate into temporary directories and compare committed bytes. `swift test` checks contract signatures and the complete compiler-backed fixture inventory without invoking these generators. -Run the package's build, test, release and formatting checks: +Run the package's build, test, generation and formatting checks: ```bash swift build env -u CODEX_HOME -u CLAUDE_CONFIG_DIR -u XDG_CONFIG_HOME \ -u XDG_STATE_HOME -u XDG_CACHE_HOME swift test swift build -c release +python3 Scripts/generate-manifest-vocabulary.py --check +python3 Scripts/generate-manifest-fixtures.py --check swift format lint --strict --configuration .swift-format \ --recursive Package.swift Sources Tests ``` @@ -313,11 +309,12 @@ swift format lint --strict --configuration .swift-format \ The required checks are `policy / policy` and `validate / result`, provided by full-SHA-pinned reusable workflows from `agents-tools/github-workflows`. Source policy validates PR titles, new commit messages and added lines. -[Package validation configuration](.github/swift-package.json) selects Xcode 26.6 on `macos-26` and a digest-pinned official Swift Linux -container. macOS and Linux validation run the full Debug and Release test suites. macOS also -runs a release build and generation checks, plus strict -formatting with `.swift-format` over `Package.swift`, `Sources` and `Tests`. -The test suites include subprocess recovery tests. The configuration owns the Linux compiler version and image digest. Tests also +[Package validation configuration](.github/swift-package.json) selects Xcode +26.6 on `macos-26` and a digest-pinned official Swift Linux container. macOS and +Linux validation run the full Debug and Release test suites. macOS also runs a +release build and strict formatting with `.swift-format` over `Package.swift`, +`Sources` and `Tests`. The test suites include subprocess recovery tests. The +configuration owns the Linux compiler version and image digest. Tests also require Perl, which is included by the Linux image's Git dependencies. Render and check the committed diff --git a/Scripts/generate-manifest-fixtures.py b/Scripts/generate-manifest-fixtures.py index 4b0b282..98c088d 100644 --- a/Scripts/generate-manifest-fixtures.py +++ b/Scripts/generate-manifest-fixtures.py @@ -1,11 +1,15 @@ #!/usr/bin/env python3 """Generate compiler-backed values for every complete positive manifest fixture.""" -import argparse +import sys + +# Imports must not leave bytecode caches in the source tree. +sys.dont_write_bytecode = True + import json import re from pathlib import Path -from manifest_generation import write_generated +from manifest_generation import run_generator ROOT = Path(__file__).resolve().parent.parent FIXTURES = ROOT / "Tests/AgentsManifestTests/Fixtures" @@ -43,14 +47,9 @@ def generated_source(paths): def main(): - parser = argparse.ArgumentParser(description=__doc__) - mode = parser.add_mutually_exclusive_group() - mode.add_argument("--output-root", type=Path, default=ROOT) - mode.add_argument("--check", action="store_true", help="fail on committed source drift") - arguments = parser.parse_args() paths = sorted(FIXTURES.glob("*.swift.txt")) - write_generated( - {DESTINATION: generated_source(paths)}, arguments.output_root, check=arguments.check + run_generator( + {DESTINATION: generated_source(paths)}, repository=ROOT, generator=Path(__file__).resolve() ) diff --git a/Scripts/generate-manifest-vocabulary.py b/Scripts/generate-manifest-vocabulary.py index 78dfa33..acad9a7 100644 --- a/Scripts/generate-manifest-vocabulary.py +++ b/Scripts/generate-manifest-vocabulary.py @@ -1,10 +1,14 @@ #!/usr/bin/env python3 """Generate authoring types, evaluation metadata and editor factories from one inventory.""" -import argparse +import sys + +# Imports must not leave bytecode caches in the source tree. +sys.dont_write_bytecode = True + import json from pathlib import Path -from manifest_generation import write_generated +from manifest_generation import run_generator ROOT = Path(__file__).resolve().parent.parent SPEC = json.loads((ROOT / "Scripts/ManifestVocabulary.json").read_text()) @@ -165,17 +169,12 @@ def editor_factories_source(): def main(): - parser = argparse.ArgumentParser(description=__doc__) - mode = parser.add_mutually_exclusive_group() - mode.add_argument("--output-root", type=Path, default=ROOT) - mode.add_argument("--check", action="store_true", help="fail on committed source drift") - arguments = parser.parse_args() outputs = { - "Sources/AgentsDescription/Vocabulary.swift": authoring_source(), - "Sources/AgentsDescription/VocabularyInventory.swift": registration_source(), - "Sources/AgentsManifest/StaticValueVocabulary.swift": editor_factories_source(), + Path("Sources/AgentsDescription/Vocabulary.swift"): authoring_source(), + Path("Sources/AgentsDescription/VocabularyInventory.swift"): registration_source(), + Path("Sources/AgentsManifest/StaticValueVocabulary.swift"): editor_factories_source(), } - write_generated(outputs, arguments.output_root, check=arguments.check) + run_generator(outputs, repository=ROOT, generator=Path(__file__).resolve()) if __name__ == "__main__": diff --git a/Scripts/manifest_generation.py b/Scripts/manifest_generation.py index bffe8bf..ae4f992 100644 --- a/Scripts/manifest_generation.py +++ b/Scripts/manifest_generation.py @@ -1,37 +1,45 @@ -"""Format generated Swift sources and optionally check committed bytes without writing them.""" +"""Write formatted Swift sources or check committed sources for generation drift.""" +import argparse import subprocess +import sys import tempfile from pathlib import Path -ROOT = Path(__file__).resolve().parent.parent +def write_generated(outputs: dict[Path, str], destination: Path, *, configuration: Path): + paths = [] + for relative, source in outputs.items(): + path = destination / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(source) + paths.append(str(path)) + subprocess.run([ + "swift", "format", "format", "--in-place", "--configuration", + str(configuration), *paths, + ], check=True) -def write_generated(outputs, output_root, *, check): - def render(directory): - paths = [] - for relative, source in outputs.items(): - path = directory / relative - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(source) - paths.append(str(path)) - subprocess.run([ - "swift", "format", "format", "--in-place", "--configuration", - str(ROOT / ".swift-format"), *paths, - ], check=True) - if not check: - render(output_root) - return - - scratch = ROOT / ".build/manifest-generation" +def check_generated(outputs: dict[Path, str], repository: Path, *, generator: Path): + scratch = repository / ".build/manifest-generation" scratch.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(dir=scratch) as directory: generated = Path(directory) - render(generated) + write_generated(outputs, generated, configuration=repository / ".swift-format") drift = [relative for relative in outputs - if not (ROOT / relative).exists() - or (ROOT / relative).read_bytes() != (generated / relative).read_bytes()] + if not (repository / relative).exists() + or (repository / relative).read_bytes() != (generated / relative).read_bytes()] if drift: for relative in drift: - print(f"generated drift: {relative}") + print(f"generated drift: {relative}", file=sys.stderr) + print(f"Regenerate with: python3 {generator.relative_to(repository)}", file=sys.stderr) raise SystemExit(1) + + +def run_generator(outputs: dict[Path, str], *, repository: Path, generator: Path): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true", help="fail on committed source drift") + arguments = parser.parse_args() + if arguments.check: + check_generated(outputs, repository, generator=generator) + else: + write_generated(outputs, repository, configuration=repository / ".swift-format") diff --git a/Sources/AgentsManifest/Admission.swift b/Sources/AgentsManifest/Admission.swift index 43815f4..35c9139 100644 --- a/Sources/AgentsManifest/Admission.swift +++ b/Sources/AgentsManifest/Admission.swift @@ -3,7 +3,7 @@ import Foundation private let utf8ByteOrderMark: [UInt8] = [0xEF, 0xBB, 0xBF] -enum ProjectionKind: String, Sendable, Codable { +enum ProjectionKind: String, Sendable { case string, integer, negative, boolean, array, dictionary, sequence, call, group case member, reference, label, type, arrayType, dictionaryType case importDeclaration = "import" @@ -11,7 +11,7 @@ enum ProjectionKind: String, Sendable, Codable { case nilLiteral = "nil" } -struct ProjectionEvent: Sendable, Equatable, Comparable, Codable { +struct ProjectionEvent: Sendable, Equatable, Comparable { let start: Int let end: Int let kind: ProjectionKind @@ -40,13 +40,13 @@ enum LexemeKind: String, Sendable { case endOfFile = "eof" } -enum GrammarNodeKind: String, Sendable { +enum GrammarNodeKind: Sendable { case string, integer, negative, boolean, array, dictionary, sequence, range, name, call, group - case nilLiteral = "nil" + case nilLiteral } extension GrammarNodeKind { - var projection: ProjectionKind { + var projection: ProjectionKind? { switch self { case .string: .string case .integer: .integer @@ -54,8 +54,8 @@ extension GrammarNodeKind { case .boolean: .boolean case .array: .array case .dictionary: .dictionary - case .sequence, .range: .sequence - case .name: .reference + case .sequence: .sequence + case .name, .range: nil case .call: .call case .group: .group case .nilLiteral: .nilLiteral @@ -603,10 +603,17 @@ final class Recognizer { events.append( ProjectionEvent(start: range.lowerBound, end: range.upperBound, kind: kind, detail: detail)) } - private func node(_ value: GrammarNode, projection: Bool = true) -> Int { + private func node(_ value: GrammarNode) -> Int { let id = nodes.count nodes.append(value) - if projection { emit(value.kind.projection, value.range, value.text) } + if let kind = value.kind.projection { + let detail: String + switch kind { + case .string, .integer, .boolean, .nilLiteral: detail = source.spelling(value.range) + default: detail = "" + } + emit(kind, value.range, detail) + } return id } @@ -668,10 +675,8 @@ final class Recognizer { token.kind == .identifier ? (token.text == "nil" ? .nilLiteral : .boolean) : (token.kind == .string ? .string : .integer) - emit(kind.projection, token.range, token.text) return node( - GrammarNode(kind: kind, range: token.range, text: token.decoded ?? token.text), - projection: false) + GrammarNode(kind: kind, range: token.range, text: token.decoded ?? token.text)) } if peek("-") { _ = try take("-") @@ -680,10 +685,8 @@ final class Recognizer { throw fail("minus requires adjacent decimal digits", at: integer.range.lowerBound) } emit(.integer, integer.range, integer.text) - emit(.negative, start.. GrammarArgument { @@ -802,8 +803,11 @@ final class Recognizer { var args = [try argument(label: "name")] _ = try take(",") let location = peek().text - guard ["url", "path", "index"].contains(location) else { - throw fail("source requires url:, path: or index:", at: peek().range.lowerBound) + guard SourceRequirements.locations.contains(location) else { + throw fail( + "source requires a location label: " + + SourceRequirements.locations.sorted().joined(separator: ", "), + at: peek().range.lowerBound) } args.append(try argument(label: location)) if !peek(",") { return args } @@ -812,8 +816,8 @@ final class Recognizer { args.append(try argument(label: "subpath")) return args } - if location == "index" { - throw fail("index source has no requirement", at: peek().range.lowerBound) + if !SourceRequirements.locationsWithRequirements.contains(location) { + throw fail("source location has no registered requirement", at: peek().range.lowerBound) } if SourceRequirements.labels.contains(peek().text) { args.append(try argument(label: peek().text)) @@ -828,8 +832,7 @@ final class Recognizer { let range = nodes[first].range.lowerBound.. String { var result = "\"" for scalar in string.unicodeScalars { - switch scalar.value { - case UInt32(UInt8(ascii: "\"")): result += "\\\"" - case UInt32(UInt8(ascii: "\\")): result += "\\\\" - case UInt32(UInt8(ascii: "\n")): result += "\\n" - case UInt32(UInt8(ascii: "\r")): result += "\\r" - case UInt32(UInt8(ascii: "\t")): result += "\\t" - case 0..<32, 127: result += "\\u{" + String(scalar.value, radix: 16) + "}" + switch scalar { + case "\"": result += "\\\"" + case "\\": result += "\\\\" + case "\n": result += "\\n" + case "\r": result += "\\r" + case "\t": result += "\\t" + case "\0"..<" ", "\u{7F}": result += "\\u{" + String(scalar.value, radix: 16) + "}" default: result.unicodeScalars.append(scalar) } } diff --git a/Sources/AgentsManifest/DomainValidation.swift b/Sources/AgentsManifest/DomainValidation.swift index e27de3e..4cefc9c 100644 --- a/Sources/AgentsManifest/DomainValidation.swift +++ b/Sources/AgentsManifest/DomainValidation.swift @@ -309,11 +309,12 @@ final class DomainValidator { if f["prompt"]?.member == "literal", let prompt = f["prompt"]?.fields["value"]?.text { let bytes = Array(prompt.utf8) var i = 0 - let escapedInput = Array("$${input:".utf8) + let escapedDollars = Array("$$".utf8) let input = Array("${input:".utf8) + let escapedInput = escapedDollars + input.dropFirst() while i < bytes.count { if bytes[i...].starts(with: escapedInput) { - i += 2 + i += escapedDollars.count while i < bytes.count && bytes[i] != UInt8(ascii: "}") { i += 1 } } else if bytes[i...].starts(with: input) { let first = i + input.count diff --git a/Sources/AgentsManifest/Evaluation.swift b/Sources/AgentsManifest/Evaluation.swift index 3186aef..9932f51 100644 --- a/Sources/AgentsManifest/Evaluation.swift +++ b/Sources/AgentsManifest/Evaluation.swift @@ -258,7 +258,7 @@ final class Evaluator { do { value = try LiteralConversion.collection( dictionary ? .object(fields.mapValues(\.value)) : .array(values.map(\.value)), - kind: dictionary ? .dictionary : .array, to: type + to: type ) { try charge(at: id) } } catch let error as LiteralConversionError { throw fail(error.code, error.message, id) diff --git a/Sources/AgentsManifest/LiteralConversion.swift b/Sources/AgentsManifest/LiteralConversion.swift index 17cdf02..6779a06 100644 --- a/Sources/AgentsManifest/LiteralConversion.swift +++ b/Sources/AgentsManifest/LiteralConversion.swift @@ -82,20 +82,27 @@ enum LiteralConversion { /// Elements have already been checked in their payload context. Only the new /// container and its optional vocabulary wrapper need work; descendants stay shared. static func collection( - _ payload: @autoclosure () -> ConstructionValue, kind: LiteralKind, + _ payload: @autoclosure () -> ConstructionValue, to context: ConstructionType, charge: () throws -> Void ) throws -> ConstructionValue { try charge() + let value = payload() + let kind: LiteralKind + switch value { + case .array: kind = .array + case .object: kind = .dictionary + default: throw LiteralConversionError.incompatible + } let context = context.unwrapped switch (kind, context) { - case (.array, .array), (.dictionary, .dictionary): return payload() + case (.array, .array), (.dictionary, .dictionary): return value default: break } guard case .named(let name) = context, let construction = Vocabulary.literalConstructions[name]?[kind] else { throw LiteralConversionError.incompatible } - return try construct(payload(), name: name, using: construction, charge: charge) + return try construct(value, name: name, using: construction, charge: charge) } private static func construct( diff --git a/Sources/AgentsManifest/ManifestFrontEnd.swift b/Sources/AgentsManifest/ManifestFrontEnd.swift index 4edce7b..c541347 100644 --- a/Sources/AgentsManifest/ManifestFrontEnd.swift +++ b/Sources/AgentsManifest/ManifestFrontEnd.swift @@ -30,8 +30,9 @@ struct FrontEndResult { /// Owns phase ordering for document construction and bounded syntax inspection. /// Observers receive phase-entry metrics; failures retain the phase and work already done. package enum ManifestFrontEnd { - /// Exercises the production pipeline through the selected phase and releases its tree. - /// The syntax projection corpus intentionally stops before contextual type checking. + /// `.syntax` runs admission, parsing, tree guards and projection comparison. + /// `.declaration` also evaluates and validates values, lowers IR and builds source maps. + /// Both release the retained syntax tree before returning. package static func inspect( bytes: [UInt8], identity: DocumentIdentity, checking: FrontEndCheck, observe: ((FrontEndStage, FrontEndMetrics) -> Void)? = nil diff --git a/Sources/AgentsManifest/SourceRequirements.swift b/Sources/AgentsManifest/SourceRequirements.swift index 2f927b6..e524c17 100644 --- a/Sources/AgentsManifest/SourceRequirements.swift +++ b/Sources/AgentsManifest/SourceRequirements.swift @@ -1,11 +1,20 @@ import AgentsDescription -/// Source overloads share their first two location parameters and defaulted subpath. -/// Their remaining required parameters define the admitted requirement slots. +/// Each Source overload begins with name followed by one location argument. +/// The remaining required parameters define the admitted requirement slots. enum SourceRequirements { + private static let signatures = Vocabulary.signatures.filter { $0.type == "Source" } + + static let locations = Set(signatures.compactMap { $0.parameters.dropFirst().first?.label }) + static let locationsWithRequirements = Set( + signatures.compactMap { signature in + signature.parameters.dropFirst(2).contains { $0.defaultValue == nil } + ? signature.parameters.dropFirst().first?.label : nil + }) + static let parameters: [ConstructionParameter] = { var names = Set() - return Vocabulary.signatures.filter { $0.type == "Source" }.flatMap { + return signatures.flatMap { $0.parameters.dropFirst(2) }.filter { $0.defaultValue == nil && names.insert($0.name).inserted } }() diff --git a/Tests/AgentsManifestTests/InventoryTests.swift b/Tests/AgentsManifestTests/InventoryTests.swift index d999c63..d8970df 100644 --- a/Tests/AgentsManifestTests/InventoryTests.swift +++ b/Tests/AgentsManifestTests/InventoryTests.swift @@ -142,6 +142,41 @@ struct InventoryTests { #expect(Set(Vocabulary.scalarValues["Agent"]!.values) == Set(AgentID.allCases.map(\.rawValue))) } + @Test func sourceSignaturesDefineLocationAndRequirementSlots() throws { + let locations: Set = ["url", "path", "index"] + #expect(SourceRequirements.locations == locations) + #expect(SourceRequirements.locationsWithRequirements == ["url", "path"]) + #expect(SourceRequirements.labels == ["from", "exact", "branch", "revision"]) + for signature in Vocabulary.signatures where signature.type == "Source" { + try #require(signature.parameters.count >= 2) + #expect(signature.parameters[0].label == "name") + #expect(signature.parameters[0].name == "name") + #expect(signature.parameters[0].defaultValue == nil) + #expect(locations.contains(signature.parameters[1].label)) + #expect(signature.parameters[1].defaultValue == nil) + } + for location in locations { + let text = + manifestHeader + "let agents = Agents(sources: [.source(name: \"r\", " + + location + ": \"example.org/r\", from: \"1.2.3\")])" + if SourceRequirements.locationsWithRequirements.contains(location) { + _ = try Recognizer( + source: SourceText(Array(text.utf8), identity: DocumentIdentity("manifest")) + ) + .recognize() + } else { + do { + _ = try DeclarationDocument( + bytes: Array(text.utf8), identity: DocumentIdentity("manifest")) + Issue.record("unsupported source requirement was accepted") + } catch let failure as ManifestFailure { + #expect(failure.diagnostics[0].code == "manifest.syntax") + #expect(failure.metrics.parserCalls == 0) + } + } + } + } + @Test func allContractSwiftBlocksPassTheRealParser() throws { let contract = try String( contentsOf: root.appendingPathComponent("Documentation/Proposals/AgentsManifest.md"), diff --git a/Tests/AgentsManifestTests/LiteralConversionTests.swift b/Tests/AgentsManifestTests/LiteralConversionTests.swift index 823d0cb..e72f78d 100644 --- a/Tests/AgentsManifestTests/LiteralConversionTests.swift +++ b/Tests/AgentsManifestTests/LiteralConversionTests.swift @@ -6,14 +6,6 @@ import Testing @Suite("Manifest literal conversion") struct LiteralConversionTests { - @Test(arguments: [ - "let versions: [Version] = [\"1.2.3\"]", - "let versions: [String: Version] = [\"stable\": \"1.2.3\"]", - "let version: Version = \"1.2.3\"\nlet versions: [Version] = [version]", - ]) - func versionCollectionsPreserveContextuallyTypedElements(_ body: String) throws { - _ = try document(body + "\nlet agents = Agents()") - } @Test func valueLiteralExamplesMatchTheRealCompiler() throws { let values: [(String, ConfigurationValue)] = [ ("nil", nil), ("true", true), ("-9_223_372_036_854_775_808", .integer(Int.min)), @@ -28,9 +20,11 @@ struct LiteralConversionTests { #expect(doc.evaluation.constants["value"]!.value == compiled.constructionValue) } } + @Test func editorLiteralConversionsMatchCompiledConfigurationValues() throws { let values: [(StaticValue, ConfigurationValue)] = [ (.null, nil), (.boolean(true), true), (.integer(Int.min), .integer(Int.min)), + (.string("\0\u{1F} \u{7F}😀"), "\0\u{1F} \u{7F}😀"), (.string("first\n\nlast"), "first\n\nlast"), (.array([.integer(1), .boolean(true), .null, .string("x")]), [1, true, nil, "x"]), ( @@ -45,5 +39,4 @@ struct LiteralConversionTests { #expect(changed.evaluation.constants["value"]?.value == compiled.constructionValue) } } - } diff --git a/Tests/AgentsManifestTests/ResourceTests.swift b/Tests/AgentsManifestTests/ResourceTests.swift index 8711c21..65af9f7 100644 --- a/Tests/AgentsManifestTests/ResourceTests.swift +++ b/Tests/AgentsManifestTests/ResourceTests.swift @@ -1,6 +1,7 @@ import AgentsCore import AgentsDescription import Foundation +import ManifestTestSupport import Testing @testable import AgentsManifest @@ -118,6 +119,18 @@ struct ResourceTests { } } + @Test func memoryReportsDeriveGrowthFromStoredHighWaterMarks() throws { + let report = ProbeReport( + status: "manifest.limit", operation: .editing, metrics: FrontEndMetrics(), + peakMemoryBytes: 2_048, preparationBaselinePeakBytes: 1_024) + let data = try JSONEncoder().encode(report) + let fields = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + #expect(fields["preparationPeakGrowthBytes"] == nil) + let decoded = try JSONDecoder().decode(ProbeReport.self, from: data) + #expect(decoded.preparationBaselinePeakBytes == 1_024) + #expect(decoded.preparationPeakGrowthBytes == 1_024) + } + @Test func oversizedExplicitInsertionIsRejectedBeforeRendering() throws { let directory = try temporaryManifestDirectory() defer { try? FileManager.default.removeItem(at: directory) } @@ -127,9 +140,9 @@ struct ResourceTests { extraArguments: ["--edit-oversized"], in: directory) #expect(result.report.status == "manifest.limit") #expect(result.report.operation == .editing) - #expect(result.report.preparationBaselineBytes != nil) - // Rendering the 20 MB pattern needs at least one 20 MB output buffer. Allow - // 8 MiB for allocator/runtime variation after the component is already in memory. + #expect(result.report.preparationBaselinePeakBytes != nil) + // Compare RSS high-water marks after constructing the component, including earlier peaks. + // Allow 8 MiB of growth for allocator/runtime variation, below one 20 MB render buffer. #expect(try #require(result.report.preparationPeakGrowthBytes) < 8 * 1_024 * 1_024) try recordProbeResults([result], name: "oversized-insert-run") } diff --git a/Tests/AgentsManifestTests/Watchdog.swift b/Tests/AgentsManifestTests/Watchdog.swift index f25c827..45a46c2 100644 --- a/Tests/AgentsManifestTests/Watchdog.swift +++ b/Tests/AgentsManifestTests/Watchdog.swift @@ -83,7 +83,8 @@ func probe( // A loose runaway-process guard, not a platform-specific memory promise. 512 MiB // leaves room for the Swift runtime, Debug SwiftSyntax and bounded source/IR copies; // it is well above the contract's 2 MiB input, 16 MiB values and 32 MiB encoding caps. - #expect(report.peakMemoryBytes < 536_870_912, "\(name): peak memory \(report.peakMemoryBytes)") + #expect( + report.peakMemoryBytes < 512 * 1_024 * 1_024, "\(name): peak memory \(report.peakMemoryBytes)") #expect(report.status != "unexpected", "\(report.message)") if report.stage == .admission { #expect(report.metrics.parserCalls == 0) } if report.status == "accepted" { diff --git a/Tests/ManifestTestProcess/main.swift b/Tests/ManifestTestProcess/main.swift index 30b01f2..af3f0fa 100644 --- a/Tests/ManifestTestProcess/main.swift +++ b/Tests/ManifestTestProcess/main.swift @@ -70,24 +70,24 @@ while bytes.count < (ManifestLimits.Input.bytes + 1) { try handle.close() let report: ProbeReport if CommandLine.arguments.contains("--edit-oversized") { - var preparationBaselineBytes: UInt64? + var preparationBaselinePeakBytes: UInt64? do { let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) let component = Component.ignore( name: "large", patterns: [String(repeating: "x", count: 20_000_000)]) - preparationBaselineBytes = peakMemory() + preparationBaselinePeakBytes = peakMemory() _ = try document.preparing([.insertComponent(component, into: .root, at: .first)]) report = ProbeReport( status: "accepted", operation: .editing, offset: 0, line: 1, column: 1, message: "", metrics: document.metrics, peakMemoryBytes: peakMemory(), - preparationBaselineBytes: preparationBaselineBytes) + preparationBaselinePeakBytes: preparationBaselinePeakBytes) } catch let error as ManifestFailure { let diagnostic = error.diagnostics[0] report = ProbeReport( status: diagnostic.code, operation: .editing, offset: diagnostic.span.start, line: diagnostic.span.line, column: diagnostic.span.column, message: diagnostic.message, metrics: error.metrics, peakMemoryBytes: peakMemory(), - preparationBaselineBytes: preparationBaselineBytes) + preparationBaselinePeakBytes: preparationBaselinePeakBytes) } } else { report = run(bytes, semantics: CommandLine.arguments.contains("--semantics")) diff --git a/Tests/ManifestTestSupport/ProbeReport.swift b/Tests/ManifestTestSupport/ProbeReport.swift index 60eceeb..8419a1f 100644 --- a/Tests/ManifestTestSupport/ProbeReport.swift +++ b/Tests/ManifestTestSupport/ProbeReport.swift @@ -24,14 +24,20 @@ package struct ProbeReport: Codable { package let message: String package let metrics: FrontEndMetrics package let peakMemoryBytes: UInt64 - package let preparationBaselineBytes: UInt64? - package let preparationPeakGrowthBytes: UInt64? + /// Process RSS high-water mark before preparation, including earlier allocations. + package let preparationBaselinePeakBytes: UInt64? + + package var preparationPeakGrowthBytes: UInt64? { + preparationBaselinePeakBytes.map { baseline in + peakMemoryBytes > baseline ? peakMemoryBytes - baseline : 0 + } + } package init( status: String, operation: ProbeOperation = .frontEnd, stage: FrontEndStage? = nil, offset: Int = 0, line: Int = 1, column: Int = 1, message: String = "", metrics: FrontEndMetrics, peakMemoryBytes: UInt64, - preparationBaselineBytes: UInt64? = nil + preparationBaselinePeakBytes: UInt64? = nil ) { configuration = probeConfiguration self.status = status @@ -43,9 +49,6 @@ package struct ProbeReport: Codable { self.message = message self.metrics = metrics self.peakMemoryBytes = peakMemoryBytes - self.preparationBaselineBytes = preparationBaselineBytes - preparationPeakGrowthBytes = preparationBaselineBytes.map { - peakMemoryBytes > $0 ? peakMemoryBytes - $0 : 0 - } + self.preparationBaselinePeakBytes = preparationBaselinePeakBytes } } From 3d4e33358537dc249f7d3fef4ff6c5be6950d5f6 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:13:52 +0800 Subject: [PATCH 012/171] feat: migrate agents.json to Agents.swift and dump evaluated manifests Adds the compatibility projection from the JSON declaration to the declaration IR, the migration generator that prints canonical Agents.swift through the shared printer and checks it against the full front end, the evaluated JSON dump model and encoding, and semantic requirement comparison at every source selection, session reuse, cache, lock producer and update-plan site so equal range spellings keep pins and lock bytes. --- Sources/AgentsCore/Declaration.swift | 6 +- .../AgentsCore/DeclarationCompatibility.swift | 94 + Sources/AgentsCore/ResolvedState.swift | 27 +- .../AgentsCore/ResolvedStateEncoding.swift | 13 + Sources/AgentsCore/SourceArgument.swift | 10 +- Sources/AgentsCore/SourceRequirement.swift | 22 + .../InstructionOperations.swift | 14 +- Sources/AgentsManifest/CanonicalPrinter.swift | 265 +- Sources/AgentsManifest/DocumentEditor.swift | 7 +- Sources/AgentsManifest/Lowering.swift | 24 +- Sources/AgentsManifest/ManifestDump.swift | 209 + .../AgentsManifest/ManifestJSONValue.swift | 101 + .../AgentsManifest/ManifestMigration.swift | 290 + Sources/AgentsSkills/SkillLifecycle.swift | 7 +- Sources/AgentsSkills/SkillOperations.swift | 7 +- Sources/AgentsUpdates/UpdatePlan.swift | 34 +- .../RequirementSemanticsTests.swift | 146 + .../TargetLifecycleTests.swift | 10 +- .../CompiledFixtures.swift | 343 + Tests/AgentsManifestTests/DumpTests.swift | 150 + .../Fixtures/ConsumerExample.dump.json | 5690 ++++++++++++++ .../Fixtures/DumpSymbolic.dump.json | 3037 ++++++++ .../Fixtures/DumpSymbolic.swift.txt | 20 + .../Fixtures/LiteralCoverage.dump.json | 6707 +++++++++++++++++ .../Fixtures/MigrationAliasGap.migration.json | 18 + .../Fixtures/MigrationAliasGap.swift.txt | 17 + .../Fixtures/MigrationAliases.migration.json | 48 + .../Fixtures/MigrationAliases.swift.txt | 37 + .../Fixtures/MigrationEmpty.dump.json | 145 + .../Fixtures/MigrationEmpty.migration.json | 1 + .../Fixtures/MigrationEmpty.swift.txt | 4 + .../Fixtures/MigrationEscapes.migration.json | 31 + .../Fixtures/MigrationEscapes.swift.txt | 27 + .../MigrationExplicitEmpty.migration.json | 11 + .../Fixtures/MigrationExplicitEmpty.swift.txt | 11 + .../Fixtures/MigrationFields.dump.json | 2334 ++++++ .../Fixtures/MigrationFields.migration.json | 100 + .../Fixtures/MigrationFields.swift.txt | 76 + .../Fixtures/MigrationRanges.migration.json | 47 + .../Fixtures/MigrationRanges.swift.txt | 43 + .../Fixtures/MigrationWidth.migration.json | 26 + .../Fixtures/MigrationWidth.swift.txt | 24 + .../Fixtures/ParserBaseline.json | 54 + .../AgentsManifestTests/MigrationTests.swift | 189 + .../RequirementUpdateTests.swift | 95 + 45 files changed, 20471 insertions(+), 100 deletions(-) create mode 100644 Sources/AgentsCore/DeclarationCompatibility.swift create mode 100644 Sources/AgentsCore/ResolvedStateEncoding.swift create mode 100644 Sources/AgentsManifest/ManifestDump.swift create mode 100644 Sources/AgentsManifest/ManifestJSONValue.swift create mode 100644 Sources/AgentsManifest/ManifestMigration.swift create mode 100644 Tests/AgentsCoreTests/RequirementSemanticsTests.swift create mode 100644 Tests/AgentsManifestTests/DumpTests.swift create mode 100644 Tests/AgentsManifestTests/Fixtures/ConsumerExample.dump.json create mode 100644 Tests/AgentsManifestTests/Fixtures/DumpSymbolic.dump.json create mode 100644 Tests/AgentsManifestTests/Fixtures/DumpSymbolic.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/LiteralCoverage.dump.json create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationAliasGap.migration.json create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationAliasGap.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationAliases.migration.json create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationAliases.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationEmpty.dump.json create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationEmpty.migration.json create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationEmpty.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationEscapes.migration.json create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationEscapes.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationExplicitEmpty.migration.json create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationExplicitEmpty.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationFields.dump.json create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationFields.migration.json create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationFields.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationRanges.migration.json create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationRanges.swift.txt create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationWidth.migration.json create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationWidth.swift.txt create mode 100644 Tests/AgentsManifestTests/MigrationTests.swift create mode 100644 Tests/AgentsUpdatesTests/RequirementUpdateTests.swift diff --git a/Sources/AgentsCore/Declaration.swift b/Sources/AgentsCore/Declaration.swift index 7c37ee1..7bf232f 100644 --- a/Sources/AgentsCore/Declaration.swift +++ b/Sources/AgentsCore/Declaration.swift @@ -108,7 +108,11 @@ public struct SourceDeclaration: Codable, Equatable, Sendable { } package var gitURL: String { - location.contains("://") || location.contains("@") ? location : "https://" + location + if location.contains("://") { return location } + if let colon = location.firstIndex(of: ":"), location[.. DeclarationIR { + func strings(_ values: [String]) -> DeclarationValue { .array(values.map { .string($0) }) } + func recipients(_ values: [AgentID]?) -> DeclarationValue { + values.map { strings($0.map(\.rawValue).sorted(by: compatibilityUTF8Less)) } ?? .null + } + func sections(_ values: [String]) -> DeclarationValue { + .array( + values.map { reference in + let parts = reference.split(separator: ":", maxSplits: 1).map(String.init) + return .record( + DeclarationRecord( + kind: "section", + fields: [ + "name": .string(parts.last!), + "source": parts.count == 2 ? .string(parts[0]) : .null, + "condition": .null, + ])) + }) + } + let sources = try self.sources.keys.sorted(by: compatibilityUTF8Less).map { alias in + let source = self.sources[alias]! + let location = source.kind == .git ? "url" : source.kind == .local ? "path" : "index" + return DeclarationRecord( + kind: source.kind == .wellKnown ? "index" : source.kind.rawValue, + fields: [ + "name": .string(alias), + location: .string(source.kind == .git ? source.gitURL : source.location), + "subpath": source.path.map { .string($0) } ?? .null, + "requirement": try source.requirement.map { .requirement(try $0.canonicalized()) } + ?? .null, + ]) + } + var components = (skills ?? [:]).keys.sorted(by: compatibilityUTF8Less).map { alias in + let selection = skills![alias]! + let select: DeclarationValue + switch selection.select { + case .all: select = .string("all") + case .names(let names): select = strings(names.sorted(by: compatibilityUTF8Less)) + } + let overrides = (selection.overrides ?? [:]).keys.sorted(by: compatibilityUTF8Less).map { + name in + let override = selection.overrides![name]! + return DeclarationValue.record( + DeclarationRecord( + kind: "skill", + fields: [ + "name": .string(name), "mode": override.mode.map { .string($0.rawValue) } ?? .null, + "agents": recipients(override.agents), + ])) + } + return DeclarationRecord( + kind: "skills", + fields: [ + "source": .string(alias), "select": select, + "exclude": strings((selection.exclude ?? []).sorted(by: compatibilityUTF8Less)), + "mode": selection.mode.map { .string($0.rawValue) } ?? .null, + "agents": recipients(selection.agents), "overrides": .array(overrides), + "condition": .null, "native": .dictionary([:]), + ]) + } + if let instructions { + let prompts = (instructions.chatgpt ?? [:]).keys.sorted(by: compatibilityUTF8Less).map { + name in + let prompt = instructions.chatgpt![name]! + return DeclarationValue.record( + DeclarationRecord( + kind: "prompt", + fields: [ + "name": .string(name), "sections": sections(prompt.sections), + "append": prompt.append.map { .string($0) } ?? .null, "condition": .null, + ])) + } + components.append( + DeclarationRecord( + kind: "instructions", + fields: [ + "sections": sections(instructions.sections), "chatGPT": .array(prompts), + "agents": recipients(instructions.agents), "condition": .null, + "native": .dictionary([:]), + ])) + } + return DeclarationIR( + defaultAgents: agents.map { $0.map(\.rawValue).sorted(by: compatibilityUTF8Less) }, + sources: sources, components: components, + watch: (watch ?? []).sorted(by: compatibilityUTF8Less)) + } +} + +private func compatibilityUTF8Less(_ lhs: String, _ rhs: String) -> Bool { + lhs.utf8.lexicographicallyPrecedes(rhs.utf8) +} diff --git a/Sources/AgentsCore/ResolvedState.swift b/Sources/AgentsCore/ResolvedState.swift index 28299ef..fbe49b8 100644 --- a/Sources/AgentsCore/ResolvedState.swift +++ b/Sources/AgentsCore/ResolvedState.swift @@ -11,9 +11,30 @@ public struct LockedSource: Codable, Equatable, Sendable { ) { self.kind = kind self.url = url - self.requirement = requirement + self.requirement = requirement?.canonical self.path = path } + + /// Location spelling is not identity; range spelling is not selection intent. + public static func == (lhs: LockedSource, rhs: LockedSource) -> Bool { + guard lhs.kind == rhs.kind, lhs.discoveryRoot == rhs.discoveryRoot else { return false } + if lhs.kind == .git, let left = lhs.url, let right = rhs.url { + let a = try? SourceDeclaration(kind: .git, location: left).transportIdentity() + let b = try? SourceDeclaration(kind: .git, location: right).transportIdentity() + guard a != nil && b != nil ? a == b : left == right else { return false } + } else if lhs.url != rhs.url { + return false + } + switch (lhs.requirement, rhs.requirement) { + case (nil, nil): return true + case (.some(let a), .some(let b)): return a == b || a.declarationEquivalent(to: b) + default: return false + } + } + + private var discoveryRoot: String { + (try? PathSafety.sanitizeSubpath(path ?? ".")) ?? (path ?? ".") + } } public struct ArtifactFile: Codable, Equatable, Sendable { @@ -284,6 +305,10 @@ public struct ResolvedState: Codable, Equatable, Sendable { package var normalized: ResolvedState { var result = self + for id in result.sources.keys { + let requirement = result.sources[id]?.requirement?.canonical + result.sources[id]?.requirement = requirement + } for name in result.skills.keys { result.skills[name]?.artifact?.files?.sort { $0.path < $1.path } } diff --git a/Sources/AgentsCore/ResolvedStateEncoding.swift b/Sources/AgentsCore/ResolvedStateEncoding.swift new file mode 100644 index 0000000..55b5633 --- /dev/null +++ b/Sources/AgentsCore/ResolvedStateEncoding.swift @@ -0,0 +1,13 @@ +import Foundation + +extension ResolvedState { + /// Producers compare the complete ledger before serializing. An unchanged ledger retains + /// its original bytes even when a declaration or physical target needs a transaction. + package func replacementData(comparedTo existing: Data?) throws -> Data? { + if let existing { + let previous = try StateStore.decode(existing, as: ResolvedState.self) + if normalized == previous.normalized { return nil } + } + return try StateStore.encodeState(normalized) + } +} diff --git a/Sources/AgentsCore/SourceArgument.swift b/Sources/AgentsCore/SourceArgument.swift index e749283..cdfbc45 100644 --- a/Sources/AgentsCore/SourceArgument.swift +++ b/Sources/AgentsCore/SourceArgument.swift @@ -69,21 +69,23 @@ package struct SourceArgument: Equatable, Sendable { ) throws -> SourceSelection { let requirements = [requirement, explicitRequirement].compactMap { $0 } let paths = try [path, explicitPath.map(PathSafety.sanitizeSubpath)].compactMap { $0 } - guard requirements.allSatisfy({ $0 == requirements.first }) else { + guard requirements.allSatisfy({ $0.declarationEquivalent(to: requirements[0]) }) else { throw CoreError.invalidSource("the source selector and option give different requirements") } guard paths.allSatisfy({ $0 == paths.first }) else { throw CoreError.invalidSource("the source selector and option give different paths") } if let declared = declaration.sources[location] { - return SourceSelection(source: declared, requirement: requirements.first, path: paths.first) + return SourceSelection( + source: declared, requirement: requirements.first?.canonical, path: paths.first) } let parsed = try SourceParser.parse( location, currentDirectory: environment.projectDirectory, homeDirectory: environment.homeDirectory) return SourceSelection( source: SourceDeclaration(kind: parsed.type, location: parsed.localPath ?? parsed.url), - requirement: requirements.first ?? parsed.requirement, path: paths.first ?? parsed.subpath) + requirement: (requirements.first ?? parsed.requirement)?.canonical, + path: paths.first ?? parsed.subpath) } private static func selectorStart(in input: String) -> String.Index? { @@ -109,7 +111,7 @@ package struct SourceSelection: Equatable, Sendable { /// `declared` with the command's requirement and path replacing its own. package func applied(to declared: SourceDeclaration) -> SourceDeclaration { var result = declared - if let requirement { result.requirement = requirement } + if let requirement { result.requirement = requirement.canonical } if let path { result.path = path } return result } diff --git a/Sources/AgentsCore/SourceRequirement.swift b/Sources/AgentsCore/SourceRequirement.swift index 8351048..9770925 100644 --- a/Sources/AgentsCore/SourceRequirement.swift +++ b/Sources/AgentsCore/SourceRequirement.swift @@ -227,6 +227,28 @@ struct SemanticVersion: Comparable, Equatable, Sendable, CustomStringConvertible } extension SourceRequirement { + /// Canonical spelling for new declaration and ledger fields. Decoding keeps stored spelling. + public func canonicalized() throws -> SourceRequirement { + try validate() + switch self { + case .branch, .revision: return self + case .exact(let version): return .exact(SemanticVersion(version)!.description) + default: + let (lower, upper) = declarationBounds! + let (major, majorOverflow) = lower.major.addingReportingOverflow(1) + if !majorOverflow, upper == SemanticVersion(major: major, minor: 0, patch: 0) { + return .upToNextMajor(from: lower.description) + } + let (minor, minorOverflow) = lower.minor.addingReportingOverflow(1) + if !minorOverflow, upper == SemanticVersion(major: lower.major, minor: minor, patch: 0) { + return .upToNextMinor(from: lower.description) + } + return .range(from: lower.description, to: upper.description) + } + } + + package var canonical: SourceRequirement { (try? canonicalized()) ?? self } + /// Declaration comparison expands range spellings; exact requirements retain metadata. package func declarationEquivalent(to other: SourceRequirement) -> Bool { switch (self, other) { diff --git a/Sources/AgentsInstructions/InstructionOperations.swift b/Sources/AgentsInstructions/InstructionOperations.swift index 7b3f9ad..f69c00c 100644 --- a/Sources/AgentsInstructions/InstructionOperations.swift +++ b/Sources/AgentsInstructions/InstructionOperations.swift @@ -168,8 +168,11 @@ public enum InstructionOperations { let transaction = FileTransaction(store: store) try plan.stage(transaction: transaction) try store.stageDeclaration(declaration, in: transaction) - try transaction.replace( - store.resolvedURL, content: nil, data: StateStore.encodeState(plan.next.normalized)) + if let data = try plan.next.replacementData( + comparedTo: store.existingData(store.resolvedURL)) + { + try transaction.replace(store.resolvedURL, content: nil, data: data) + } try SourceCache(store: store).prune(referencedBy: plan.next, transaction: transaction) try transaction.commit() } @@ -432,8 +435,11 @@ public enum InstructionOperations { } if writeState { try store.stageDeclaration(declaration, in: transaction) - try transaction.replace( - store.resolvedURL, content: nil, data: StateStore.encodeState(next.normalized)) + if let data = try next.replacementData( + comparedTo: store.existingData(store.resolvedURL)) + { + try transaction.replace(store.resolvedURL, content: nil, data: data) + } } try sources.cache.prune(referencedBy: next, transaction: transaction) try transaction.commit() diff --git a/Sources/AgentsManifest/CanonicalPrinter.swift b/Sources/AgentsManifest/CanonicalPrinter.swift index 76cdb90..97065f0 100644 --- a/Sources/AgentsManifest/CanonicalPrinter.swift +++ b/Sources/AgentsManifest/CanonicalPrinter.swift @@ -11,7 +11,8 @@ func quoted(_ string: String) -> String { case "\n": result += "\\n" case "\r": result += "\\r" case "\t": result += "\\t" - case "\0"..<" ", "\u{7F}": result += "\\u{" + String(scalar.value, radix: 16) + "}" + case "\0"..<" ", "\u{7F}"..."\u{9F}": + result += "\\u{" + String(scalar.value, radix: 16) + "}" default: result.unicodeScalars.append(scalar) } } @@ -24,58 +25,157 @@ struct PrintStyle { var trailingComma = true } +/// A layout reserves its exact UTF-8 size before allocating emitted source bytes. +private struct Printed { + private indirect enum Content { + case text(String) + case quoted(String) + case parts([Printed]) + } + private let content: Content + let count: Int + + init(_ text: String) { + content = .text(text) + count = text.utf8.count + } + init(quoting text: String) { + content = .quoted(text) + var size = 2 + for scalar in text.unicodeScalars { + switch scalar { + case "\"", "\\", "\n", "\r", "\t": size = ValueCost.add(size, 2) + case "\0"..<" ", "\u{7F}"..."\u{9F}": + size = ValueCost.add(size, 4 + String(scalar.value, radix: 16).utf8.count) + default: size = ValueCost.add(size, scalar.utf8.count) + } + } + count = size + } + init(_ parts: [Printed]) { + content = .parts(parts) + count = parts.reduce(0) { ValueCost.add($0, $1.count) } + } + func append(to result: inout String) { + switch content { + case .text(let text): result += text + case .quoted(let text): result += quoted(text) + case .parts(let parts): for part in parts { part.append(to: &result) } + } + } + var string: String { + var result = "" + result.reserveCapacity(count) + append(to: &result) + return result + } +} + struct CanonicalPrinter { var style = PrintStyle() - func render(_ value: ConstructionValue, indentation: String = "") -> String { + func render( + _ value: ConstructionValue, indentation: String = "", column: Int? = nil, trailing: Int = 1 + ) -> String { + layout( + value, indentation: indentation, column: column ?? indentation.utf8.count, + trailing: trailing + ).string + } + + func manifest(_ value: ConstructionValue) throws -> [UInt8] { + let prefix = "// agents-tools-version: 1.0\nimport AgentsDescription\n\nlet agents = " + let result = Printed([ + Printed(prefix), layout(value, indentation: "", column: 13, trailing: 0), Printed("\n"), + ]) + guard result.count <= ManifestLimits.Input.bytes else { + throw MigrationFailure.limit("generated source bytes") + } + return Array(result.string.utf8) + } + + private func layout( + _ value: ConstructionValue, indentation: String, column: Int, trailing: Int + ) -> Printed { switch value { - case .text(let text): return quoted(text) - case .integer(let value): return String(value) - case .boolean(let value): return value ? "true" : "false" - case .none: return "nil" - case .version(let version): return quoted(version.normalized) + case .text(let text): return Printed(quoting: text) + case .integer(let value): return Printed(String(value)) + case .boolean(let value): return Printed(value ? "true" : "false") + case .none: return Printed("nil") + case .version(let version): return Printed(quoting: version.normalized) case .range(let range): let requirement = Lowering.requirement(range) if case .upToNextMajor(let lower) = requirement { - return ".upToNextMajor(from: \(quoted(lower)))" + return call( + ".upToNextMajor", arguments: [("from", .text(lower))], + indentation: indentation, column: column, trailing: trailing) } if case .upToNextMinor(let lower) = requirement { - return ".upToNextMinor(from: \(quoted(lower)))" + return call( + ".upToNextMinor", arguments: [("from", .text(lower))], + indentation: indentation, column: column, trailing: trailing) } - return quoted(range.lowerBound.normalized) + "..<" + quoted(range.upperBound.normalized) + return Printed([ + Printed(quoting: range.lowerBound.normalized), Printed("..<"), + Printed(quoting: range.upperBound.normalized), + ]) case .array(let values): + let parts = values.enumerated().map { index, value in + layout( + value, indentation: indentation + style.indent, + column: (indentation + style.indent).utf8.count, + trailing: style.trailingComma || index < values.count - 1 ? 1 : 0) + } return collection( - values.map { render($0, indentation: indentation + style.indent) }, dictionary: false, - forceMultiline: values.contains(where: nested), indentation: indentation) + parts, dictionary: false, forceMultiline: values.contains(where: nested), + indentation: indentation, column: column, trailing: trailing) case .object(let fields): let keys = fields.keys.sorted(by: utf8Less) + let parts = keys.enumerated().map { index, key in + let prefix = Printed([Printed(quoting: key), Printed(": ")]) + return Printed([ + prefix, + layout( + fields[key]!, indentation: indentation + style.indent, + column: (indentation + style.indent).utf8.count + prefix.count, + trailing: style.trailingComma || index < keys.count - 1 ? 1 : 0), + ]) + } return collection( - keys.map { - quoted($0) + ": " + render(fields[$0]!, indentation: indentation + style.indent) - }, dictionary: true, forceMultiline: fields.values.contains(where: nested), - indentation: indentation) + parts, dictionary: true, forceMultiline: fields.values.contains(where: nested), + indentation: indentation, column: column, trailing: trailing) case .node(let type, let member, let fields): if type == "SkillSelection" { - return member == "all" ? ".all" : render(fields["names"]!, indentation: indentation) + return member == "all" + ? Printed(".all") + : layout(fields["names"]!, indentation: indentation, column: column, trailing: trailing) } if type == "VersionRange", let lower = fields["from"] { - return ".\(member)(from: \(render(lower, indentation: indentation)))" + return call( + "." + member, arguments: [("from", lower)], + indentation: indentation, column: column, trailing: trailing) } if type == "PromptContent" && member == "literal" || type == "RuntimeValue" && member == "literal" { - return render(fields["value"]!, indentation: indentation) + return layout( + fields["value"]!, indentation: indentation, column: column, trailing: trailing) } if ["SectionReference", "GroupReference"].contains(type), fields["source"] == ConstructionValue.none, fields["condition"] == ConstructionValue.none { - return render(fields["name"]!, indentation: indentation) + return layout(fields["name"]!, indentation: indentation, column: column, trailing: trailing) } if type == "ConfigurationValue" { - if member == "null" { return "nil" } - if member != "decimal" { return render(fields["value"]!, indentation: indentation) } + if member == "null" { return Printed("nil") } + if member != "decimal" { + return layout( + fields["value"]!, indentation: indentation, column: column, trailing: trailing) + } + } + if type == "Source" { + return source(fields, indentation: indentation, column: column, trailing: trailing) } - if type == "Source" { return source(fields, indentation: indentation) } let signature = Vocabulary.signatures.first { signature in guard signature.type == type, signature.member == member else { return false } let names = Set(signature.parameters.map(\.name)) @@ -91,28 +191,32 @@ struct CanonicalPrinter { return true } } - guard let signature else { return ".\(member)" } + guard let signature else { return Printed(".\(member)") } var arguments: [(String, ConstructionValue)] = [] for parameter in signature.parameters { guard let value = fields[parameter.name] else { continue } if let fallback = parameter.defaultValue, fallback == value { continue } arguments.append((parameter.label, value)) } - if !signature.callable { return ".\(member)" } + if !signature.callable { return Printed(".\(member)") } return call( - type == "Agents" ? "Agents" : "." + member, arguments: arguments, indentation: indentation) + type == "Agents" ? "Agents" : "." + member, arguments: arguments, + indentation: indentation, column: column, trailing: trailing) } } - private func source(_ fields: [String: ConstructionValue], indentation: String) -> String { + private func source( + _ fields: [String: ConstructionValue], indentation: String, column: Int, trailing: Int + ) -> Printed { var args: [(String, ConstructionValue)] = [("name", fields["name"]!)] for key in ["url", "path", "index"] { if let value = fields[key] { - if key == "url", let url = value.text { - args.append((key, .text(SourceDeclaration(kind: .git, location: url).gitURL))) - } else { - args.append((key, value)) - } + args.append( + ( + key, + key == "url" + ? .text(SourceDeclaration(kind: .git, location: value.text!).gitURL) : value + )) } } if let requirement = fields["requirement"], requirement != .none { @@ -127,47 +231,90 @@ struct CanonicalPrinter { } } if let subpath = fields["subpath"], subpath != .none { args.append(("subpath", subpath)) } - return call(".source", arguments: args, indentation: indentation) + return call( + ".source", arguments: args, indentation: indentation, column: column, trailing: trailing) } - private func call(_ callee: String, arguments: [(String, ConstructionValue)], indentation: String) - -> String - { - let parts = arguments.map { label, value in - (label == "_" ? "" : label + ": ") + render(value, indentation: indentation + style.indent) + private func call( + _ callee: String, arguments: [(String, ConstructionValue)], indentation: String, + column: Int, trailing: Int + ) -> Printed { + let parts = arguments.enumerated().map { index, argument in + let (label, value) = argument + let prefix = label == "_" ? "" : label + ": " + return Printed([ + Printed(prefix), + layout( + value, indentation: indentation + style.indent, + column: (indentation + style.indent).utf8.count + prefix.utf8.count, + trailing: index < arguments.count - 1 ? 1 : 0), + ]) } - let inline = callee + "(" + parts.joined(separator: ", ") + ")" - if !arguments.contains(where: { nested($0.1) }) - && indentation.utf8.count + inline.utf8.count + 1 <= 80 + let inline = joined(parts, open: callee + "(", close: ")", separator: ", ") + if parts.isEmpty + || !arguments.contains(where: { nested($0.1) }) + && column + inline.count + trailing <= 80 { return inline } - if parts.isEmpty { return inline } - return callee + "(" + style.newline - + parts.enumerated().map { index, part in - indentation + style.indent + part + (index == parts.count - 1 ? "" : ",") - }.joined(separator: style.newline) + style.newline + indentation + ")" + return multiline( + parts, open: callee + "(", close: ")", indentation: indentation, collection: false) } private func collection( - _ parts: [String], dictionary: Bool, forceMultiline: Bool, indentation: String - ) -> String { - if parts.isEmpty { return dictionary ? "[:]" : "[]" } - let inline = "[" + parts.joined(separator: ", ") + "]" - if !forceMultiline && indentation.utf8.count + inline.utf8.count + 1 <= 80 { return inline } - return "[" + style.newline - + parts.enumerated().map { index, part in - indentation + style.indent + part - + (style.trailingComma || index < parts.count - 1 ? "," : "") - }.joined(separator: style.newline) + style.newline + indentation + "]" + _ parts: [Printed], dictionary: Bool, forceMultiline: Bool, indentation: String, + column: Int, trailing: Int + ) -> Printed { + if parts.isEmpty { return Printed(dictionary ? "[:]" : "[]") } + let inline = joined(parts, open: "[", close: "]", separator: ", ") + if !forceMultiline && column + inline.count + trailing <= 80 { return inline } + return multiline(parts, open: "[", close: "]", indentation: indentation, collection: true) + } + + private func joined(_ parts: [Printed], open: String, close: String, separator: String) -> Printed + { + var output = [Printed(open)] + for (index, part) in parts.enumerated() { + if index > 0 { output.append(Printed(separator)) } + output.append(part) + } + output.append(Printed(close)) + return Printed(output) + } + + private func multiline( + _ parts: [Printed], open: String, close: String, indentation: String, collection: Bool + ) -> Printed { + var output = [Printed(open + style.newline)] + for (index, part) in parts.enumerated() { + output += [Printed(indentation + style.indent), part] + if index < parts.count - 1 || collection && style.trailingComma { + output.append(Printed(",")) + } + output.append(Printed(style.newline)) + } + output.append(Printed(indentation + close)) + return Printed(output) } private func nested(_ value: ConstructionValue) -> Bool { switch value { case .array, .object: return true - case .node(let type, let member, _): - return Vocabulary.scalarValues[type] == nil - && !(type == "SkillSelection" && member == "all") + case .node(let type, let member, let fields): + if Vocabulary.scalarValues[type] != nil || type == "SkillSelection" && member == "all" { + return false + } + if ["SectionReference", "GroupReference"].contains(type), + fields["source"] == ConstructionValue.none, fields["condition"] == ConstructionValue.none + { + return false + } + if ["PromptContent", "RuntimeValue"].contains(type), member == "literal" { return false } + if type == "ConfigurationValue" { + if member == "null" { return false } + if member != "decimal", let payload = fields["value"] { return nested(payload) } + } + return true case .range: return true default: return false } diff --git a/Sources/AgentsManifest/DocumentEditor.swift b/Sources/AgentsManifest/DocumentEditor.swift index e2f6460..ccff7eb 100644 --- a/Sources/AgentsManifest/DocumentEditor.swift +++ b/Sources/AgentsManifest/DocumentEditor.swift @@ -274,7 +274,12 @@ final class DocumentEditor { func replacementText(_ value: ConstructionValue, at range: Range) throws -> String { _ = try valueCost(value) let (style, indentation) = try style(at: range) - var text = CanonicalPrinter(style: style).render(value, indentation: indentation) + let lineEnd = + current.bytes[range.upperBound...].firstIndex(where: { $0 == 10 || $0 == 13 }) + ?? current.bytes.count + var text = CanonicalPrinter(style: style).render( + value, indentation: indentation, column: range.lowerBound - lineStart(range.lowerBound), + trailing: lineEnd - range.upperBound) if text.hasPrefix("-"), range.lowerBound > 0 { let previous = current.bytes[range.lowerBound - 1] if ![ diff --git a/Sources/AgentsManifest/Lowering.swift b/Sources/AgentsManifest/Lowering.swift index d04bb75..2328de3 100644 --- a/Sources/AgentsManifest/Lowering.swift +++ b/Sources/AgentsManifest/Lowering.swift @@ -15,13 +15,19 @@ enum Lowering { } static func requirement(_ range: Range) -> SourceRequirement { - let lower = range.lowerBound - let upper = range.upperBound - let major = lower.successor(major: true) - let minor = lower.successor(major: false) - if major.valid && upper == major { return .upToNextMajor(from: lower.normalized) } - if minor.valid && upper == minor { return .upToNextMinor(from: lower.normalized) } - return .range(from: lower.normalized, to: upper.normalized) + SourceRequirement.range( + from: range.lowerBound.normalized, to: range.upperBound.normalized + ).canonical + } + + static func recordKind( + type: String, member: String, fields: [String: ConstructionValue] + ) -> String { + if type == "Source" { + return fields["url"] != nil ? "git" : fields["path"] != nil ? "local" : "index" + } + if type == "GroupReference" { return fields["source"]?.text == nil ? "local" : "exported" } + return member } static func lower(_ value: ConstructionValue) -> DeclarationValue { @@ -46,14 +52,12 @@ enum Lowering { member == "exact" ? .exact(text) : member == "branch" ? .branch(text) : .revision(text)) } var lowered = fields.mapValues(lower) - var kind = member + let kind = recordKind(type: type, member: member, fields: fields) if type == "Source" { - kind = fields["url"] != nil ? "git" : fields["path"] != nil ? "local" : "index" if let url = fields["url"]?.text { lowered["url"] = .string(SourceDeclaration(kind: .git, location: url).gitURL) } } - if type == "GroupReference" { kind = fields["source"]?.text == nil ? "local" : "exported" } return .record(DeclarationRecord(kind: kind, fields: lowered)) } } diff --git a/Sources/AgentsManifest/ManifestDump.swift b/Sources/AgentsManifest/ManifestDump.swift new file mode 100644 index 0000000..496dab8 --- /dev/null +++ b/Sources/AgentsManifest/ManifestDump.swift @@ -0,0 +1,209 @@ +import AgentsCore +import AgentsDescription + +/// Local evaluated values and source coordinates. Construction performs no linking or source I/O. +public struct ManifestDump: Sendable { + public struct Location: Sendable { + public let pointer: String + public let span: SourceSpan + public let origins: [SourceSpan] + public let defaulted: Bool + public let editability: ManifestJSONValue + } + + public let schemaVersion = 1 + public let kind = "manifest" + public let languageVersion = "1.0" + public let sourceDigest: String + public let declaration: ManifestJSONValue + public let locations: [Location] + public let diagnostics: [ManifestDiagnostic] + + public init(bytes: [UInt8]) throws { + try self.init( + document: DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest"))) + } + + public init(document: DeclarationDocument) throws { + var projection = DumpProjection() + declaration = projection.value(document.evaluation.root.value, old: "", new: "") + sourceDigest = document.digest + locations = try document.sourceMap.entries.map { entry -> Location in + guard let pointer = projection.pointers[entry.pointer], + let node = document.node(at: entry.pointer) + else { + throw document.source.failure( + "manifest.dump.mismatch", "source map pointer is absent from the evaluated declaration", + entry.span.start) + } + let editability: ManifestJSONValue + switch document.editability(of: node) { + case .direct: editability = .object(["kind": .string("direct")]) + case .readOnly(let reason): + editability = .object(["kind": .string("readOnly"), "reason": .string(reason)]) + case .sharedConstant(let uses): + editability = .object([ + "kind": .string("sharedConstant"), + "uses": .array( + uses.map { spanJSON(document.source.span(document.admission.nodes[$0.syntax].range)) }), + ]) + } + return Location( + pointer: pointer, span: manifestSpan(entry.span), origins: entry.origins.map(manifestSpan), + defaulted: entry.defaulted, editability: editability) + }.sorted { + $0.pointer == $1.pointer ? $0.span.start < $1.span.start : utf8Less($0.pointer, $1.pointer) + } + diagnostics = document.diagnostics.map { + ManifestDiagnostic( + code: $0.code, severity: $0.severity, message: $0.message, span: manifestSpan($0.span), + related: $0.related.map(manifestSpan)) + }.sorted { ($0.span.start, $0.code) < ($1.span.start, $1.code) } + _ = try locationJSON.encodedCount( + limit: ManifestLimits.SourceMap.encodedBytes, budget: "source map encoded bytes") + _ = try json.encodedCount(limit: ManifestLimits.Output.encodedBytes - 1) + } + + public func encodedJSON() throws -> [UInt8] { try json.encodedJSON() } + + private var locationJSON: ManifestJSONValue { + .array( + locations.map { location in + .object([ + "pointer": .string(location.pointer), "span": spanJSON(location.span), + "origins": .array(location.origins.map(spanJSON)), + "defaulted": .boolean(location.defaulted), + "editability": location.editability, + ]) + }) + } + + private var json: ManifestJSONValue { + .object([ + "schemaVersion": .integer(schemaVersion), "kind": .string(kind), + "languageVersion": .string(languageVersion), + "sourceDigest": .string(sourceDigest), "declaration": declaration, "locations": locationJSON, + "diagnostics": .array( + diagnostics.map { + .object([ + "code": .string($0.code), "severity": .string($0.severity.rawValue), + "message": .string($0.message), + "span": spanJSON($0.span), "related": .array($0.related.map(spanJSON)), + ]) + }), + ]) + } +} + +private func manifestSpan(_ span: SourceSpan) -> SourceSpan { + SourceSpan( + document: DocumentIdentity("manifest"), start: span.start, end: span.end, line: span.line, + column: span.column) +} + +private func spanJSON(_ span: SourceSpan) -> ManifestJSONValue { + .object([ + "document": .string("manifest"), "start": .integer(span.start), "end": .integer(span.end), + "line": .integer(span.line), "column": .integer(span.column), + ]) +} + +private struct DumpProjection { + var pointers: [String: String] = [:] + + mutating func value(_ value: ConstructionValue, old: String, new: String) -> ManifestJSONValue { + pointers[old] = new + switch value { + case .text(let text): return .string(text) + case .integer(let number): return .integer(number) + case .boolean(let flag): return .boolean(flag) + case .none: return .null + case .version(let version): return .string(version.normalized) + case .range(let range): return requirement(Lowering.requirement(range), old: old, new: new) + case .object(let fields): + var result: [String: ManifestJSONValue] = [:] + for key in fields.keys.sorted(by: utf8Less) { + let suffix = "/" + pointerEscape(key) + result[key] = self.value(fields[key]!, old: old + suffix, new: new + suffix) + } + return .object(result) + case .array(let values): + return array(values, old: old, new: new, sort: nil) + case .node(let type, let member, let fields): + if let spelling = Vocabulary.scalarValues[type]?[member] { return .string(spelling) } + if type == "SkillSelection" { + return member == "all" + ? .string("all") : array(fields["names"]!.array!, old: old, new: new, sort: scalarKey) + } + if type == "Requirement", case .requirement(let requirement) = Lowering.lower(value) { + return self.requirement(requirement, old: old, new: new) + } + var result: [String: ManifestJSONValue] = [:] + if Vocabulary.taggedRecordTypes.contains(type) { + let kind = Lowering.recordKind(type: type, member: member, fields: fields) + pointers[old + "/kind"] = new + "/kind" + result["kind"] = .string(kind) + } + for key in fields.keys.sorted(by: utf8Less) { + let suffix = "/" + pointerEscape(key) + let field = fields[key]! + if type == "Source", key == "url", let url = field.text { + pointers[old + suffix] = new + suffix + result[key] = .string(SourceDeclaration(kind: .git, location: url).gitURL) + } else if case .array(let values) = field { + let sort: ((ConstructionValue) -> String)? + if ["agents", "defaultAgents", "exports", "watch", "scopes", "platforms", "exclude"] + .contains(key) + { + sort = scalarKey + } else if ["sources", "groups", "chatGPT", "overrides"].contains(key) { + sort = { $0.fields["name"]?.text ?? "" } + } else { + sort = nil + } + pointers[old + suffix] = new + suffix + result[key] = array(values, old: old + suffix, new: new + suffix, sort: sort) + } else { + result[key] = self.value(field, old: old + suffix, new: new + suffix) + } + } + return .object(result) + } + } + + private mutating func array( + _ values: [ConstructionValue], old: String, new: String, sort: ((ConstructionValue) -> String)? + ) -> ManifestJSONValue { + var entries = Array(values.enumerated()) + if let sort { entries.sort { utf8Less(sort($0.element), sort($1.element)) } } + var result: [ManifestJSONValue] = [] + for (index, entry) in entries.enumerated() { + result.append(value(entry.element, old: old + "/\(entry.offset)", new: new + "/\(index)")) + } + return .array(result) + } + + private mutating func requirement(_ requirement: SourceRequirement, old: String, new: String) + -> ManifestJSONValue + { + let fields: [String: ManifestJSONValue] + switch requirement { + case .branch(let text): fields = ["branch": .string(text)] + case .revision(let text): fields = ["revision": .string(text)] + case .exact(let text): fields = ["exact": .string(text)] + case .upToNextMajor(let text): fields = ["from": .string(text)] + case .upToNextMinor(let text): fields = ["upToNextMinor": .string(text)] + case .range(let lower, let upper): fields = ["from": .string(lower), "to": .string(upper)] + } + for key in fields.keys { pointers[old + "/" + key] = new + "/" + key } + return .object(fields) + } + + private func scalarKey(_ value: ConstructionValue) -> String { + if let text = Lowering.lower(value).string { return text } + if case .node("ComponentReference", let kind, let fields) = value { + return kind + "\0" + (fields["name"]?.text ?? "") + } + return (value.fields["kind"]?.member ?? "") + "\0" + (value.fields["name"]?.text ?? "") + } +} diff --git a/Sources/AgentsManifest/ManifestJSONValue.swift b/Sources/AgentsManifest/ManifestJSONValue.swift new file mode 100644 index 0000000..3228d8c --- /dev/null +++ b/Sources/AgentsManifest/ManifestJSONValue.swift @@ -0,0 +1,101 @@ +import AgentsCore +import Foundation + +/// JSON data for the evaluated manifest schema. Decimal configuration payloads remain strings. +public indirect enum ManifestJSONValue: Sendable, Equatable { + case string(String) + case integer(Int) + case boolean(Bool) + case null + case array([ManifestJSONValue]) + case object([String: ManifestJSONValue]) + + static func json(_ input: Any) throws -> Self { + switch input { + case let string as String: return .string(string) + case is NSNull: return .null + case let array as [Any]: return .array(try array.map(json)) + case let fields as [String: Any]: return .object(try fields.mapValues(json)) + default: throw CoreError.invalidState("unexpected migration diagnostic value") + } + } + + func encodedCount(limit: Int, budget: String = "encoded JSON output bytes") throws -> Int { + var count = 0 + try write(indentation: "") { text in + guard text.utf8.count <= limit - count else { + throw ManifestFailure( + ManifestDiagnostic( + code: "manifest.limit", message: budget, + span: SourceSpan( + document: DocumentIdentity("manifest"), start: 0, end: 0, line: 1, column: 1))) + } + count += text.utf8.count + } + return count + } + + func encodedJSON(limit: Int = ManifestLimits.Output.encodedBytes) throws -> [UInt8] { + let count = try encodedCount(limit: limit - 1) + var result = "" + result.reserveCapacity(count + 1) + try write(indentation: "") { result += $0 } + result += "\n" + return Array(result.utf8) + } + + private func write(indentation: String, emit: (String) throws -> Void) throws { + func string(_ text: String) throws { + try emit("\"") + for scalar in text.unicodeScalars { + switch scalar { + case "\"": try emit("\\\"") + case "\\": try emit("\\\\") + case "\n": try emit("\\n") + case "\r": try emit("\\r") + case "\t": try emit("\\t") + case "\u{8}": try emit("\\b") + case "\u{C}": try emit("\\f") + case "\0"..<" ": + let hex = String(scalar.value, radix: 16) + try emit("\\u" + String(repeating: "0", count: 4 - hex.count) + hex) + default: try emit(String(scalar)) + } + } + try emit("\"") + } + switch self { + case .null: try emit("null") + case .integer(let value): try emit(String(value)) + case .boolean(let value): try emit(value ? "true" : "false") + case .string(let value): try string(value) + case .array(let values): + if values.isEmpty { + try emit("[]") + return + } + try emit("[\n") + for (index, value) in values.enumerated() { + try emit(indentation + " ") + try value.write(indentation: indentation + " ", emit: emit) + try emit((index < values.count - 1 ? "," : "") + "\n") + } + try emit(indentation + "]") + case .object(let fields): + if fields.isEmpty { + try emit("{}") + return + } + try emit("{\n") + let keys = fields.keys.sorted(by: utf8Less) + for (index, key) in keys.enumerated() { + try emit(indentation + " ") + try string(key) + try emit(": ") + try fields[key]!.write(indentation: indentation + " ", emit: emit) + try emit((index < keys.count - 1 ? "," : "") + "\n") + } + try emit(indentation + "}") + } + } +} diff --git a/Sources/AgentsManifest/ManifestMigration.swift b/Sources/AgentsManifest/ManifestMigration.swift new file mode 100644 index 0000000..5c5880b --- /dev/null +++ b/Sources/AgentsManifest/ManifestMigration.swift @@ -0,0 +1,290 @@ +import AgentsCore +import AgentsDescription +import Foundation + +public struct MigrationDiagnostic: Sendable, Equatable { + public let pointer: String + public let code: String + public let message: String + public let value: ManifestJSONValue? + public let oldAlias: String? + public let newAlias: String? + public let budget: String? + + init( + pointer: String, code: String, message: String, value: ManifestJSONValue? = nil, + oldAlias: String? = nil, newAlias: String? = nil, budget: String? = nil + ) { + self.pointer = pointer + self.code = code + self.message = message + self.value = value + self.oldAlias = oldAlias + self.newAlias = newAlias + self.budget = budget + } +} + +public struct MigrationFailure: Error, Sendable { + public let diagnostics: [MigrationDiagnostic] + + static func limit(_ budget: String) -> Self { + Self(diagnostics: [ + MigrationDiagnostic( + pointer: "", code: "migration.limit", message: "migration exceeds \(budget)", budget: budget + ) + ]) + } +} + +public struct ManifestMigrationResult: Sendable { + public let bytes: [UInt8] + public let declaration: DeclarationIR + public let diagnostics: [MigrationDiagnostic] +} + +/// Pure generation: callers own declaration-file creation, removal and every state transaction. +public enum ManifestMigration { + public static func generate( + json bytes: [UInt8], environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> ManifestMigrationResult { + try generate(json: bytes, environment: environment, checking: { $0 }) + } + + // A private-to-the-module comparison seam exercises self-check failures without changing output. + static func generate( + json bytes: [UInt8], environment: RuntimeEnvironment, + checking expected: (DeclarationIR) -> DeclarationIR + ) throws -> ManifestMigrationResult { + var legacy = try StateStore.decode(Data(bytes), as: Declaration.self) + try legacy.validate(environment: environment) + // The strict decoder checks duplicates, UTF-8 and discarded values. Check field names + // independently as well, including unknown fields whose value is JSON null. + let input = try JSONSerialization.jsonObject(with: Data(bytes)) as! [String: Any] + try validateKeys(input) + var diagnostics: [MigrationDiagnostic] = [] + for alias in (legacy.skills ?? [:]).keys.sorted(by: utf8Less) { + guard let selection = legacy.skills?[alias], case .names(let names) = selection.select else { + continue + } + let selected = Set(names) + for name in (selection.overrides ?? [:]).keys.sorted(by: utf8Less) + where !selected.contains(name) { + let pointer = "/skills/" + pointerEscape(alias) + "/overrides/" + pointerEscape(name) + let full = + ((input["skills"] as! [String: Any])[alias] as! [String: Any])["overrides"] + as! [String: Any] + diagnostics.append( + MigrationDiagnostic( + pointer: pointer, code: "migration.inertOverride", + message: + "override is outside the explicit skill selection and cannot affect installation", + value: try ManifestJSONValue.json(full[name]!))) + legacy.skills?[alias]?.overrides?.removeValue(forKey: name) + } + } + if let dot = legacy.sources.removeValue(forKey: ".") { + var alias = "source" + var suffix = 2 + while legacy.sources[alias] != nil { + alias = "source-\(suffix)" + suffix += 1 + } + legacy.sources[alias] = dot + if let selection = legacy.skills?.removeValue(forKey: ".") { + legacy.skills?[alias] = selection + } + legacy.watch = legacy.watch?.map { $0 == "." ? alias : $0 } + func rewrite(_ references: [String]) -> [String] { + references.map { $0.hasPrefix(".:") ? alias + $0.dropFirst() : $0 } + } + if let instructions = legacy.instructions { + legacy.instructions?.sections = rewrite(instructions.sections) + for name in (instructions.chatgpt ?? [:]).keys { + legacy.instructions?.chatgpt?[name]?.sections = rewrite( + instructions.chatgpt![name]!.sections) + } + } + diagnostics.append( + MigrationDiagnostic( + pointer: "/sources/.", code: "migration.sourceAliasRenamed", + message: "reserved source alias renamed", oldAlias: ".", newAlias: alias)) + } + diagnostics.sort { + $0.pointer == $1.pointer ? utf8Less($0.code, $1.code) : utf8Less($0.pointer, $1.pointer) + } + let projection = try legacy.compatibilityProjection() + let construction = MigrationConstruction.root(projection) + try preflight(construction) + let output = try CanonicalPrinter().manifest(construction) + let document: DeclarationDocument + do { + document = try DeclarationDocument(bytes: output, identity: DocumentIdentity("manifest")) + } catch let failure as ManifestFailure { + if let limit = failure.diagnostics.first(where: { $0.code == "manifest.limit" }) { + throw MigrationFailure.limit(limit.message) + } + throw failure + } + guard document.declaration == expected(projection) else { + throw MigrationFailure(diagnostics: [ + MigrationDiagnostic( + pointer: "", code: "migration.mismatch", + message: "generated declaration differs from compatibility projection") + ]) + } + return ManifestMigrationResult(bytes: output, declaration: projection, diagnostics: diagnostics) + } + + static func preflight(_ value: ConstructionValue) throws { + var pending = [(value, 1)] + var nodes = 0 + var strings = 0 + while let (value, depth) = pending.popLast() { + nodes += 1 + guard nodes <= ManifestLimits.Values.nodes else { + throw MigrationFailure.limit("expanded nodes") + } + guard depth <= ManifestLimits.Values.depth else { + throw MigrationFailure.limit("expanded depth") + } + let children: [ConstructionValue] + switch value { + case .array(let values): children = values + case .object(let fields), .node(_, _, let fields): + strings = fields.keys.reduce(strings) { ValueCost.add($0, $1.utf8.count) } + children = fields.keys.sorted(by: utf8Less).map { fields[$0]! } + case .text(let text): + strings = ValueCost.add(strings, text.utf8.count) + children = [] + case .version(let version): + strings = ValueCost.add(strings, version.normalized.utf8.count) + children = [] + case .range(let range): children = [.version(range.lowerBound), .version(range.upperBound)] + default: children = [] + } + guard children.count <= ManifestLimits.Values.entries else { + throw MigrationFailure.limit("collection entries") + } + guard strings <= ManifestLimits.Values.stringBytes else { + throw MigrationFailure.limit("decoded string bytes") + } + guard children.count <= ManifestLimits.Values.nodes - nodes - pending.count else { + throw MigrationFailure.limit("expanded nodes") + } + pending += children.map { ($0, depth + 1) } + } + let cost = constructionCost(value) + guard cost.encoded <= ManifestLimits.Output.encodedBytes else { + throw MigrationFailure.limit("encoded output bytes") + } + } + + private static func validateKeys(_ root: [String: Any]) throws { + func keys(_ value: [String: Any], _ allowed: Set) throws { + if let unknown = value.keys.sorted(by: utf8Less).first(where: { !allowed.contains($0) }) { + throw CoreError.invalidState("unknown state field: \(unknown)") + } + } + try keys(root, ["agents", "sources", "skills", "instructions", "watch"]) + for source in (root["sources"] as? [String: [String: Any]] ?? [:]).values { + try keys( + source, + [ + "git", "local", "well-known", "path", "branch", "revision", "exact", "from", "to", + "upToNextMinor", + ]) + } + for selection in (root["skills"] as? [String: [String: Any]] ?? [:]).values { + try keys(selection, ["select", "exclude", "agents", "mode", "overrides"]) + for override in (selection["overrides"] as? [String: [String: Any]] ?? [:]).values { + try keys(override, ["agents", "mode"]) + } + } + if let instructions = root["instructions"] as? [String: Any] { + try keys(instructions, ["agents", "sections", "chatgpt"]) + for prompt in (instructions["chatgpt"] as? [String: [String: Any]] ?? [:]).values { + try keys(prompt, ["sections", "append"]) + } + } + } +} + +private enum MigrationConstruction { + static func root(_ ir: DeclarationIR) -> ConstructionValue { + record( + DeclarationRecord( + kind: "Agents", + fields: [ + "defaultAgents": ir.defaultAgents.map { .array($0.map { .string($0) }) } ?? .null, + "exports": .array(ir.exports.map { .string($0) }), + "sources": .array(ir.sources.map { .record($0) }), + "components": .array(ir.components.map { .record($0) }), + "groups": .array(ir.groups.map { .record($0) }), + "uses": .array(ir.uses.map { .record($0) }), + "watch": .array(ir.watch.map { .string($0) }), + ]), as: "Agents") + } + + private static func record(_ record: DeclarationRecord, as type: String) -> ConstructionValue { + if type == "Source" { + return .node( + type: type, member: "source", + fields: record.fields.mapValues { value($0, as: .named("String")) }) + } + let signature = Vocabulary.signatures.first { $0.type == type && $0.member == record.kind }! + return .node( + type: type, member: record.kind, + fields: record.fields.reduce(into: [:]) { result, field in + let parameter = signature.parameters.first { $0.name == field.key }! + result[field.key] = value(field.value, as: parameter.type) + }) + } + + private static func value(_ input: DeclarationValue, as type: ConstructionType) + -> ConstructionValue + { + switch input { + case .null: return .none + case .string(let text): + if case .named(let name) = type.unwrapped { + if let member = Vocabulary.scalarValues[name]?.first(where: { $0.value == text })?.key { + return .node(type: name, member: member, fields: [:]) + } + if name == "SkillSelection" { return .node(type: name, member: "all", fields: [:]) } + } + return .text(text) + case .integer(let number): return .integer(number) + case .boolean(let flag): return .boolean(flag) + case .array(let values): + if case .named("SkillSelection") = type.unwrapped { + return .node( + type: "SkillSelection", member: "names", + fields: ["names": .array(values.map { value($0, as: .named("String")) })]) + } + guard case .array(let element) = type.unwrapped else { + preconditionFailure("projection array type") + } + return .array(values.map { value($0, as: element) }) + case .dictionary(let fields): + guard case .dictionary(let element) = type.unwrapped else { + preconditionFailure("projection dictionary type") + } + return .object(fields.mapValues { value($0, as: element) }) + case .record(let node): + guard case .named(let name) = type.unwrapped else { + preconditionFailure("projection record type") + } + return record(node, as: name) + case .requirement(let requirement): + func version(_ text: String) -> Version { Version(stringLiteral: text) } + switch requirement { + case .upToNextMajor(let lower): return .range(.upToNextMajor(from: version(lower))) + case .upToNextMinor(let lower): return .range(.upToNextMinor(from: version(lower))) + case .range(let lower, let upper): return .range(version(lower).. [String: LockedSource] { + var next = previous + for (id, source) in skills where source != previous[id] { next[id] = source } + for id in instructions.keys.sorted() { + let source = instructions[id]! + guard source != previous[id] else { continue } + if let other = skills[id], other != previous[id], other != source { + throw CoreError.invalidState("incompatible planned source records: \(id)") + } + next[id] = source + } + return next + } + func apply(outcome: TransactionOutcome) throws -> UpdateApplyResult { try validate() if report.hasChanges { @@ -81,8 +92,9 @@ 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.encodeState(next.normalized) - if try store.existingData(store.resolvedURL) != resolvedBytes { + if let resolvedBytes = try next.replacementData( + comparedTo: store.existingData(store.resolvedURL)) + { try transaction.replace(store.resolvedURL, content: nil, data: resolvedBytes) } try SourceCache(store: store).prune( diff --git a/Tests/AgentsCoreTests/RequirementSemanticsTests.swift b/Tests/AgentsCoreTests/RequirementSemanticsTests.swift new file mode 100644 index 0000000..fecdfc9 --- /dev/null +++ b/Tests/AgentsCoreTests/RequirementSemanticsTests.swift @@ -0,0 +1,146 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Requirement semantics") +struct RequirementSemanticsTests { + @Test(arguments: [ + ( + SourceRequirement.range(from: "v1.2.0+lower", to: "2.0.0+upper"), + SourceRequirement.upToNextMajor(from: "1.2.0") + ), + (.range(from: "1.2.0-beta+lower", to: "1.3.0+upper"), .upToNextMinor(from: "v1.2.0-beta")), + (.exact(" V1.2.3+build "), .exact("1.2.3+build")), + (.branch("main"), .branch("main")), (.revision("abc"), .revision("abc")), + ]) + func selectionsCompareSemanticValues(_ legacy: SourceRequirement, _ modern: SourceRequirement) + throws + { + #expect(legacy.declarationEquivalent(to: modern)) + let decoded = try JSONDecoder().decode( + SourceRequirement.self, from: JSONEncoder().encode(legacy)) + #expect(decoded == legacy) + #expect(try decoded.canonicalized().declarationEquivalent(to: modern)) + } + + @Test func absenceExactMetadataPrereleasesAndDifferentRangesStayDistinct() { + for (left, right) in [ + (SourceRequirement.exact("1.2.3+one"), SourceRequirement.exact("1.2.3+two")), + (.upToNextMajor(from: "1.2.0-beta"), .upToNextMajor(from: "1.2.0")), + (.upToNextMajor(from: "1.2.0"), .upToNextMinor(from: "1.2.0")), + (.branch("main"), .revision("main")), + ] { #expect(!left.declarationEquivalent(to: right)) } + #expect(LockedSource(kind: .local) != LockedSource(kind: .local, requirement: .branch("main"))) + } + + @Test func argumentSelectorsAcceptEqualBoundsAndRejectDifferentIntent() throws { + let environment = RuntimeEnvironment(environment: [:]) + let declaration = Declaration(sources: ["s": SourceDeclaration(kind: .local, location: "local")] + ) + let selected = try SourceArgument("s@from:1.2.0").selection( + in: declaration, requirement: .range(from: "v1.2.0+meta", to: "2.0.0"), path: nil, + environment: environment) + #expect(selected.requirement == .upToNextMajor(from: "1.2.0")) + #expect(selected.requirement?.declarationEquivalent(to: .upToNextMajor(from: "1.2.0")) == true) + #expect(throws: CoreError.self) { + try SourceArgument("s@minor:1.2.0").selection( + in: declaration, requirement: .range(from: "1.2.0", to: "2.0.0"), path: nil, + environment: environment) + } + } + + @Test func descriptorComparisonUsesIdentityRootAndSemanticRequirementWithoutRewritingReads() + throws + { + let bytes = Data( + #"{"kind":"git","url":"https://EXAMPLE.org:2222/team.git/","path":"skills","requirement":{"from":"v1.2.0","to":"2.0.0+meta"}}"# + .utf8) + let old = try JSONDecoder().decode(LockedSource.self, from: bytes) + let new = LockedSource( + kind: .git, url: "ssh://user@example.org:2222/team", + requirement: .upToNextMajor(from: "1.2.0"), path: "skills") + #expect(old == new) + var equivalentRoot = new + equivalentRoot.path = "./skills/" + #expect(old == equivalentRoot) + #expect(LockedSource(kind: .local) == LockedSource(kind: .local, path: ".")) + #expect(old.requirement == .range(from: "v1.2.0", to: "2.0.0+meta")) + var changed = new + changed.path = "instructions" + #expect(old != changed) + changed = new + changed.url = "https://example.org:2223/team" + #expect(old != changed) + #expect( + LockedSource(kind: .local, requirement: .range(from: "v1.2.0", to: "1.3.0")).requirement + == .upToNextMinor(from: "1.2.0")) + } + + @Test func fullLedgerComparisonPreservesBytesAndCanonicalizesOnlyRequiredRewrites() throws { + let bytes = Data( + #"{ "version":1,"sources":{"intranet/team":{"kind":"git","url":"https://intranet/team.git","requirement":{"from":"v1.2.0","to":"2.0.0+meta"}}},"skills":{},"instructions":{"sections":[],"chatgpt":{},"targets":{}}}"# + .utf8) + let old = try StateStore.decode(bytes, as: ResolvedState.self) + try old.validate() + var next = old + next.sources["intranet/team"] = LockedSource( + kind: .git, url: "https://intranet/team.git", requirement: .upToNextMajor(from: "1.2.0")) + #expect(try next.replacementData(comparedTo: bytes) == nil) + #expect(old.sources["intranet/team"]?.requirement == .range(from: "v1.2.0", to: "2.0.0+meta")) + next.sources["other/team"] = LockedSource( + kind: .git, url: "https://other/team.git", requirement: .range(from: "v1.2.0", to: "1.3.0")) + let rewritten = try #require(try next.replacementData(comparedTo: bytes)) + let root = try #require(JSONSerialization.jsonObject(with: rewritten) as? [String: Any]) + let sources = try #require(root["sources"] as? [String: [String: Any]]) + #expect(sources["intranet/team"]?["requirement"] as? [String: String] == ["from": "1.2.0"]) + #expect( + sources["other/team"]?["requirement"] as? [String: String] == ["upToNextMinor": "1.2.0"]) + #expect(try ResolvedState().replacementData(comparedTo: nil) != nil) + } + + @Test func resolutionSessionsReuseEqualRequirementsAndCacheKeysKeepExactPins() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let repo = root.appendingPathComponent("repo") + try FileManager.default.createDirectory(at: repo, withIntermediateDirectories: true) + try Data("old".utf8).write(to: repo.appendingPathComponent("content")) + try initGitRepo(repo) + func git(_ args: [String]) throws { + _ = try ProcessRunner.run("/usr/bin/env", arguments: ["git", "-C", repo.path] + args) + } + try git(["tag", "1.2.0"]) + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment(projectDirectory: root, homeDirectory: root, environment: [:]) + ) + let session = try SourceResolutionSession(store: store) + var source = SourceDeclaration( + kind: .local, location: repo.path, requirement: .range(from: "v1.2.0+lower", to: "2.0.0+meta") + ) + let first = try session.withSnapshot(source) { ($0, $1) } + try Data("new".utf8).write(to: repo.appendingPathComponent("content")) + try git(["commit", "-am", "new"]) + try git(["tag", "1.3.0"]) + source.requirement = .upToNextMajor(from: "1.2.0") + let second = try session.withSnapshot(source) { ($0, $1) } + #expect(first.0 == second.0 && first.1 == second.1) + #expect( + try String(contentsOf: second.1.appendingPathComponent("content"), encoding: .utf8) == "old") + let cache = SourceCache(store: store) + let newer = try cache.resolve(source) + #expect(newer != first.0) + let id = try source.identity(environment: store.environment) + let oldDescriptor = try JSONDecoder().decode( + LockedSource.self, + from: Data(#"{"kind":"local","requirement":{"from":"v1.2.0","to":"2.0.0"}}"#.utf8)) + let newDescriptor = LockedSource(kind: .local, requirement: source.requirement) + let before = try cache.materialize( + sourceID: id, source: oldDescriptor, revision: first.0.revision) + let after = try cache.materialize( + sourceID: id, source: newDescriptor, revision: first.0.revision) + #expect(before == after) + #expect( + try String(contentsOf: after.appendingPathComponent("content"), encoding: .utf8) == "old") + } +} diff --git a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift index 27d9c52..4dd8a4c 100644 --- a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift @@ -58,7 +58,7 @@ struct TargetLifecycleTests { }) } - @Test func updateApplyWritesStateInTheStandardLayout() throws { + @Test func updateApplyFormatsDeclarationAndPreservesUnchangedLedger() throws { let fixture = try InstructionFixture() try fixture.own("guide") try fixture.addOwn(names: ["guide"], agents: [.codex]) @@ -73,15 +73,15 @@ struct TargetLifecycleTests { 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) + let existingLockBytes = try StateStore.encode(fixture.store().loadResolved()) + try existingLockBytes.write(to: lockFile) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) #expect(try Data(contentsOf: declarationFile) == declaration) - #expect(try Data(contentsOf: lockFile) == lock) + #expect(try Data(contentsOf: lockFile) == existingLockBytes) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) #expect(try Data(contentsOf: declarationFile) == declaration) - #expect(try Data(contentsOf: lockFile) == lock) + #expect(try Data(contentsOf: lockFile) == existingLockBytes) } @Test func pathsPlaceSectionsInNestedTargets() throws { diff --git a/Tests/AgentsManifestTests/CompiledFixtures.swift b/Tests/AgentsManifestTests/CompiledFixtures.swift index 958c00c..a2357ec 100644 --- a/Tests/AgentsManifestTests/CompiledFixtures.swift +++ b/Tests/AgentsManifestTests/CompiledFixtures.swift @@ -17,10 +17,19 @@ func compiledFixtures() -> [CompiledManifestFixture] { [ compiledConsumerExample(), compiledCoreExample(), + compiledDumpSymbolic(), compiledExportedGroup(), compiledInstructionRecipients(), compiledLiteralCoverage(), + compiledMigrationAliasGap(), + compiledMigrationAliases(), compiledMigrationEdgeExample(), + compiledMigrationEmpty(), + compiledMigrationEscapes(), + compiledMigrationExplicitEmpty(), + compiledMigrationFields(), + compiledMigrationRanges(), + compiledMigrationWidth(), compiledProducerExample(), compiledRecipientConditions(), compiledRequirementValues(), @@ -172,6 +181,44 @@ private func compiledCoreExample() -> CompiledManifestFixture { ]) } +private func compiledDumpSymbolic() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let shared: Condition = .when( + agents: [.openCode, .codex], scopes: [.user, .project], platforms: [.linux, .macOS]) + let agents = Agents( + defaultAgents: [], + exports: ["z", "a"], + sources: [ + .source(name: "z", url: "intranet/team.git", "1.2.0"..<"1.3.0"), + .source(name: "a", path: "./a"), + ], + components: [ + .instructions( + sections: ["own", .section(name: "rule", source: "z", condition: shared)], + chatGPT: [.prompt(name: "z", sections: []), .prompt(name: "a", sections: ["own"])], + agents: []), + .skills( + source: "z", select: ["z", "a"], exclude: ["z", "a"], + overrides: [.skill(name: "z", agents: []), .skill(name: "a")]), + .plugin( + name: "bundle", path: "bundle", source: "z", + exclude: [ + .hook(name: "aaa"), .command(name: "zzz"), .hook(name: "bbb"), .skill(name: "ccc"), + ]), + ], + groups: [.group(name: "z", condition: shared), .group(name: "a")], + uses: [.group(name: "review", source: "z", condition: shared), "a"], + watch: ["z", "a"] + ) + return CompiledManifestFixture( + name: "DumpSymbolic.swift.txt", agents: agents, + constants: [ + "shared": shared.constructionValue, + "agents": agents.constructionValue, + ]) +} + private func compiledExportedGroup() -> CompiledManifestFixture { // agents-tools-version: 1.0 @@ -304,6 +351,74 @@ private func compiledLiteralCoverage() -> CompiledManifestFixture { ]) } +private func compiledMigrationAliasGap() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + sources: [ + .source(name: "source", path: "live"), + .source(name: "source-2", path: "other"), + ], + components: [ + .skills( + source: "source", + overrides: [ + .skill(name: "future") + ] + ) + ] + ) + return CompiledManifestFixture( + name: "MigrationAliasGap.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func compiledMigrationAliases() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + sources: [ + .source(name: "source", path: "./s"), + .source(name: "source-2", path: "./s2"), + .source(name: "source-3", url: "git@Intranet:team/rules.git"), + ], + components: [ + .skills( + source: "source-3", + select: ["a"], + exclude: ["a"], + overrides: [ + .skill(name: "a", mode: .copy) + ] + ), + .instructions( + sections: [ + "guide", + .section(name: "rule", source: "source-3"), + .section(name: "rule", source: "source-3"), + ], + chatGPT: [ + .prompt( + name: "", + sections: [ + .section(name: "rule", source: "source-3"), + "guide", + ] + ) + ] + ), + ], + watch: ["source", "source-3"] + ) + return CompiledManifestFixture( + name: "MigrationAliases.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + private func compiledMigrationEdgeExample() -> CompiledManifestFixture { // agents-tools-version: 1.0 @@ -362,6 +477,234 @@ private func compiledMigrationEdgeExample() -> CompiledManifestFixture { ]) } +private func compiledMigrationEmpty() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents() + return CompiledManifestFixture( + name: "MigrationEmpty.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func compiledMigrationEscapes() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + defaultAgents: [], + sources: [ + .source( + name: "é/别名~\"\\\n\r\t\u{1}\u{7f}\u{85}", + url: "https://example.org/escape.git" + ) + ], + components: [ + .skills( + source: "é/别名~\"\\\n\r\t\u{1}\u{7f}\u{85}", + select: ["selected"] + ), + .instructions( + chatGPT: [ + .prompt( + name: "\"\\\n\r\t\u{1}\u{7f}\u{85} é 😀", + sections: ["own"], + append: "notes/内容.md" + ) + ] + ), + ] + ) + return CompiledManifestFixture( + name: "MigrationEscapes.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func compiledMigrationExplicitEmpty() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + defaultAgents: [], + components: [ + .instructions( + agents: [] + ) + ] + ) + return CompiledManifestFixture( + name: "MigrationExplicitEmpty.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func compiledMigrationFields() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + defaultAgents: [.claudeCode, .codex, .openCode], + sources: [ + .source(name: "empty", path: "./live"), + .source( + name: "git", + url: "https://intranet/team.git", + branch: "main", + subpath: "skills" + ), + .source( + name: "index", + index: "https://example.org/.well-known/skills/index.json", + subpath: "bundle" + ), + .source(name: "local", path: "./drafts", revision: "abc123"), + ], + components: [ + .skills(source: "empty", mode: .edit), + .skills( + source: "git", + select: ["a", "b"], + exclude: ["b"], + mode: .copy, + overrides: [ + .skill( + name: "a", + mode: .link, + agents: [.codex] + ), + .skill( + name: "b", + agents: [] + ), + ], + agents: [] + ), + .skills( + source: "index", + select: [] + ), + .skills( + source: "local", + overrides: [ + .skill(name: "future", mode: .copy) + ] + ), + .instructions( + sections: [ + "own", + .section(name: "rule", source: "git"), + "own", + .section(name: "nested/rule", source: "local"), + ], + chatGPT: [ + .prompt( + name: "", + sections: [] + ), + .prompt( + name: "周报", + sections: [ + .section(name: "rule", source: "git"), + "own", + ], + append: "notes/周报.md" + ), + ], + agents: [.codex, .geminiCLI] + ), + ], + watch: ["git", "index", "local"] + ) + return CompiledManifestFixture( + name: "MigrationFields.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func compiledMigrationRanges() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + sources: [ + .source(name: "a", url: "https://Example.org/a.git", exact: "1.2.3+build"), + .source(name: "b", path: "./b", from: "1.2.0"), + .source( + name: "c", + path: "./c", + .upToNextMinor(from: "1.2.0-beta+build") + ), + .source(name: "d", path: "./d", from: "1.2.0"), + .source( + name: "e", + path: "./e", + .upToNextMinor(from: "1.2.0+lower") + ), + .source( + name: "f", + path: "./f", + "1.2.0"..<"1.8.0-beta+bound" + ), + .source( + name: "g", + path: "./g", + .upToNextMinor(from: "9223372036854775807.1.0") + ), + .source( + name: "h", + url: "ssh://User@INTRANET:2222/team/h.git", + revision: "abc123" + ), + .source( + name: "i", + path: "./i", + .upToNextMinor( + from: + "1.2.0-alphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalpha" + ) + ), + .source(name: "j", url: "https://intranet/team@variant"), + ] + ) + return CompiledManifestFixture( + name: "MigrationRanges.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + +private func compiledMigrationWidth() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + sources: [ + .source(name: "s", path: "./s"), + .source(name: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", path: "p"), + .source( + name: "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy", + path: "p2" + ), + ], + components: [ + .skills( + source: "s", + select: ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbb"], + exclude: [ + "ccccccccccccccccccccccccccccccccc", + "dddddddddddddddddddddddd", + ], + mode: .link + ) + ] + ) + return CompiledManifestFixture( + name: "MigrationWidth.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + private func compiledProducerExample() -> CompiledManifestFixture { // agents-tools-version: 1.0 diff --git a/Tests/AgentsManifestTests/DumpTests.swift b/Tests/AgentsManifestTests/DumpTests.swift new file mode 100644 index 0000000..ac12fa9 --- /dev/null +++ b/Tests/AgentsManifestTests/DumpTests.swift @@ -0,0 +1,150 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsManifest + +@Suite("Evaluated manifest dump") +struct DumpTests { + @Test(arguments: [ + "MigrationEmpty", "MigrationFields", "DumpSymbolic", "ConsumerExample", "LiteralCoverage", + ]) + func completeGoldenObjectsAndLocationsAreByteExact(_ name: String) throws { + let bytes = try manifestFixture(name + ".swift.txt") + let dump = try ManifestDump(bytes: bytes) + let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) + #expect(dump.locations.count == document.sourceMap.entries.count) + let output = try dump.encodedJSON() + #expect(try output == manifestFixture(name + ".dump.json")) + #expect(try output == dump.encodedJSON()) + #expect(output.last == 10) + #expect(dump.sourceDigest == "sha256:" + FileHash.sha256Hex(data: Data(bytes))) + let root = try #require(JSONSerialization.jsonObject(with: Data(output)) as? [String: Any]) + #expect( + root.keys.sorted() == [ + "declaration", "diagnostics", "kind", "languageVersion", "locations", "schemaVersion", + "sourceDigest", + ]) + #expect(root["schemaVersion"] as? Int == 1) + let declaration = try #require(root["declaration"]) + for location in dump.locations { + #expect(resolve(location.pointer, in: declaration) != nil, "\(name): \(location.pointer)") + #expect(location.span.document.rawValue == "manifest") + #expect(location.origins.allSatisfy { $0.document.rawValue == "manifest" }) + } + } + + @Test func symbolicConditionsGroupsExplicitRecipientsAndNormalizedPointersSurvive() throws { + let bytes = try manifestFixture("DumpSymbolic.swift.txt") + let dump = try ManifestDump(bytes: bytes) + let root = try #require( + JSONSerialization.jsonObject(with: Data(dump.encodedJSON())) as? [String: Any]) + let declaration = try #require(root["declaration"]) + #expect(resolve("/defaultAgents", in: declaration) as? [String] == []) + #expect(resolve("/components/0/agents", in: declaration) as? [String] == []) + #expect(resolve("/components/1/agents", in: declaration) is NSNull) + #expect(resolve("/sources/0/name", in: declaration) as? String == "a") + #expect(resolve("/sources/1/url", in: declaration) as? String == "https://intranet/team.git") + #expect(resolve("/sources/1/requirement/upToNextMinor", in: declaration) as? String == "1.2.0") + #expect(resolve("/components/1/select", in: declaration) as? [String] == ["a", "z"]) + #expect(resolve("/components/1/overrides/0/name", in: declaration) as? String == "a") + #expect(resolve("/components/2/exclude/0/kind", in: declaration) as? String == "command") + #expect(resolve("/components/2/exclude/0/name", in: declaration) as? String == "zzz") + #expect(resolve("/components/2/exclude/1/kind", in: declaration) as? String == "hook") + #expect(resolve("/components/2/exclude/1/name", in: declaration) as? String == "aaa") + #expect(resolve("/components/2/exclude/2/name", in: declaration) as? String == "bbb") + #expect(resolve("/components/2/exclude/3/kind", in: declaration) as? String == "skill") + #expect(resolve("/components/0/chatGPT/0/name", in: declaration) as? String == "a") + #expect(resolve("/uses/0/kind", in: declaration) as? String == "exported") + #expect(resolve("/uses/0/source", in: declaration) as? String == "z") + #expect(resolve("/uses/1/kind", in: declaration) as? String == "local") + #expect(resolve("/uses/1/source", in: declaration) is NSNull) + #expect( + resolve("/uses/0/condition/agents", in: declaration) as? [String] == ["codex", "opencode"]) + let location = try #require(dump.locations.first { $0.pointer == "/sources/1/name" }) + #expect( + String(decoding: bytes[location.span.start.. Any? { + if pointer.isEmpty { return value } + var current = value + for segment in pointer.dropFirst().split(separator: "/", omittingEmptySubsequences: false) { + let key = pointerUnescape(String(segment)) + if let fields = current as? [String: Any], let child = fields[key] { + current = child + } else if let values = current as? [Any], let index = Int(key), values.indices.contains(index) + { + current = values[index] + } else { + return nil + } + } + return current + } +} diff --git a/Tests/AgentsManifestTests/Fixtures/ConsumerExample.dump.json b/Tests/AgentsManifestTests/Fixtures/ConsumerExample.dump.json new file mode 100644 index 0000000..d9689e7 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/ConsumerExample.dump.json @@ -0,0 +1,5690 @@ +{ + "declaration": { + "components": [ + { + "agents": null, + "condition": null, + "exclude": [ + "experimental" + ], + "kind": "skills", + "mode": "copy", + "native": {}, + "overrides": [ + { + "agents": [ + "codex" + ], + "mode": "link", + "name": "testing" + } + ], + "select": "all", + "source": "rules" + }, + { + "agents": null, + "condition": { + "agents": [ + "claude-code" + ], + "platforms": null, + "scopes": [ + "project" + ] + }, + "exclude": [], + "kind": "skills", + "mode": "edit", + "native": {}, + "overrides": [], + "select": [ + "draft" + ], + "source": "drafts" + }, + { + "agents": null, + "chatGPT": [ + { + "append": "notes/weekly.md", + "condition": null, + "name": "weekly", + "sections": [ + { + "condition": null, + "name": "guide", + "source": null + } + ] + } + ], + "condition": null, + "kind": "instructions", + "native": {}, + "sections": [ + { + "condition": null, + "name": "guide", + "source": null + }, + { + "condition": null, + "name": "engineering", + "source": "rules" + } + ] + }, + { + "agents": [ + "claude-code" + ], + "condition": null, + "kind": "mcpServer", + "name": "workspace", + "native": {}, + "transport": { + "arguments": [ + "serve" + ], + "environment": { + "LOG_LEVEL": { + "kind": "literal", + "value": "info" + }, + "TOKEN": { + "kind": "secret", + "value": "workspace-token" + } + }, + "executable": "workspace-tools", + "kind": "stdio", + "workingDirectory": null + } + }, + { + "agents": [ + "opencode" + ], + "condition": null, + "kind": "mcpServer", + "name": "reference", + "native": {}, + "transport": { + "headers": { + "Authorization": { + "kind": "environment", + "value": "MCP_AUTH" + } + }, + "kind": "streamableHTTP", + "url": "https://example.org/mcp" + } + }, + { + "agents": [ + "claude-code" + ], + "condition": { + "agents": null, + "platforms": null, + "scopes": [ + "project" + ] + }, + "event": { + "kind": "afterTool" + }, + "kind": "hook", + "matcher": null, + "name": "format", + "native": {}, + "run": { + "arguments": [ + "format", + "--in-place", + "Sources" + ], + "environment": {}, + "executable": "swift", + "kind": "executable", + "workingDirectory": { + "path": "tools", + "source": "rules" + } + }, + "timeoutSeconds": 30 + }, + { + "agents": [ + "claude-code" + ], + "condition": null, + "description": "Review a selected change.", + "kind": "command", + "name": "review/change", + "native": {}, + "parameters": [ + { + "defaultValue": null, + "description": "The change to review.", + "name": "change" + } + ], + "prompt": { + "kind": "literal", + "value": "Review ${input:change} and cite evidence." + } + }, + { + "agents": [ + "claude-code" + ], + "condition": { + "agents": null, + "platforms": [ + "macos" + ], + "scopes": null + }, + "initializationOptions": { + "backgroundIndexing": { + "kind": "boolean", + "value": true + } + }, + "kind": "lspServer", + "languages": { + ".swift": "swift" + }, + "name": "swift", + "native": {}, + "run": { + "arguments": [], + "environment": {}, + "executable": "sourcekit-lsp", + "kind": "executable", + "workingDirectory": null + } + }, + { + "agents": [ + "claude-code" + ], + "condition": { + "agents": null, + "platforms": null, + "scopes": [ + "project" + ] + }, + "kind": "permissions", + "name": "private-files", + "native": {}, + "rules": [ + { + "kind": "deny", + "operation": { + "kind": "read" + }, + "pattern": "secrets/**" + } + ] + }, + { + "agents": [ + "cursor" + ], + "condition": { + "agents": null, + "platforms": null, + "scopes": [ + "project" + ] + }, + "kind": "ignore", + "name": "build-products", + "native": {}, + "patterns": [ + ".build/", + "DerivedData/" + ], + "purpose": "indexing" + }, + { + "agents": [ + "claude-code" + ], + "condition": { + "agents": null, + "platforms": null, + "scopes": [ + "user" + ] + }, + "exclude": [], + "kind": "plugin", + "mode": "native", + "name": "vendor-tools", + "native": {}, + "path": "plugins/tools", + "select": null, + "source": "vendor" + }, + { + "agents": null, + "condition": { + "agents": null, + "platforms": null, + "scopes": [ + "project" + ] + }, + "exclude": [ + { + "kind": "hook", + "name": "format" + } + ], + "kind": "plugin", + "mode": "components", + "name": "shared-tools", + "native": {}, + "path": "plugins/shared", + "select": null, + "source": "vendor" + } + ], + "defaultAgents": null, + "exports": [], + "groups": [ + { + "components": [ + { + "agents": [ + "claude-code" + ], + "condition": { + "agents": null, + "platforms": [ + "macos" + ], + "scopes": null + }, + "description": "Review correctness and tests.", + "kind": "subagent", + "model": null, + "name": "reviewer", + "native": { + "claude-code/subagent@1": { + "memory": { + "kind": "string", + "value": "project" + } + } + }, + "prompt": { + "kind": "literal", + "value": "Check invariants and explain concrete failures." + }, + "tools": null + } + ], + "condition": null, + "name": "review-tools", + "uses": [ + { + "condition": { + "agents": [ + "codex" + ], + "platforms": null, + "scopes": null + }, + "kind": "exported", + "name": "review", + "source": "team" + } + ] + } + ], + "sources": [ + { + "index": "https://example.org/skills/index.json", + "kind": "index", + "name": "catalog", + "requirement": null, + "subpath": null + }, + { + "kind": "local", + "name": "drafts", + "path": "./draft-skills", + "requirement": null, + "subpath": null + }, + { + "kind": "git", + "name": "rules", + "requirement": { + "from": "1.2.0" + }, + "subpath": null, + "url": "https://example.org/team/rules.git" + }, + { + "kind": "local", + "name": "team", + "path": "./team", + "requirement": null, + "subpath": null + }, + { + "kind": "git", + "name": "vendor", + "requirement": { + "exact": "2.1.0" + }, + "subpath": null, + "url": "https://example.org/vendor/tools.git" + } + ], + "uses": [ + { + "condition": null, + "kind": "local", + "name": "review-tools", + "source": null + } + ], + "watch": [ + "catalog", + "rules" + ] + }, + "diagnostics": [], + "kind": "manifest", + "languageVersion": "1.0", + "locations": [ + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "", + "span": { + "column": 14, + "document": "manifest", + "end": 3467, + "line": 15, + "start": 475 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components", + "span": { + "column": 15, + "document": "manifest", + "end": 3231, + "line": 23, + "start": 865 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0", + "span": { + "column": 5, + "document": "manifest", + "end": 1022, + "line": 24, + "start": 871 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 1022, + "line": 24, + "start": 871 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 1022, + "line": 24, + "start": 871 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/exclude", + "span": { + "column": 33, + "document": "manifest", + "end": 928, + "line": 25, + "start": 912 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/exclude/0", + "span": { + "column": 34, + "document": "manifest", + "end": 927, + "line": 25, + "start": 913 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 1022, + "line": 24, + "start": 871 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/0/mode", + "span": { + "column": 57, + "document": "manifest", + "end": 941, + "line": 25, + "start": 936 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/native", + "span": { + "column": 5, + "document": "manifest", + "end": 1022, + "line": 24, + "start": 871 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/overrides", + "span": { + "column": 18, + "document": "manifest", + "end": 1016, + "line": 26, + "start": 960 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/overrides/0", + "span": { + "column": 19, + "document": "manifest", + "end": 1015, + "line": 26, + "start": 961 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/overrides/0/agents", + "span": { + "column": 64, + "document": "manifest", + "end": 1014, + "line": 26, + "start": 1006 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/0/overrides/0/agents/0", + "span": { + "column": 65, + "document": "manifest", + "end": 1013, + "line": 26, + "start": 1007 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/0/overrides/0/mode", + "span": { + "column": 49, + "document": "manifest", + "end": 996, + "line": 26, + "start": 991 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/overrides/0/name", + "span": { + "column": 32, + "document": "manifest", + "end": 983, + "line": 26, + "start": 974 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/select", + "span": { + "column": 5, + "document": "manifest", + "end": 1022, + "line": 24, + "start": 871 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/source", + "span": { + "column": 15, + "document": "manifest", + "end": 901, + "line": 25, + "start": 894 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1", + "span": { + "column": 5, + "document": "manifest", + "end": 1164, + "line": 28, + "start": 1028 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 1164, + "line": 28, + "start": 1028 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/condition", + "span": { + "column": 18, + "document": "manifest", + "end": 1158, + "line": 30, + "start": 1110 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/condition/agents", + "span": { + "column": 32, + "document": "manifest", + "end": 1137, + "line": 30, + "start": 1124 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/1/condition/agents/0", + "span": { + "column": 33, + "document": "manifest", + "end": 1136, + "line": 30, + "start": 1125 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/condition/platforms", + "span": { + "column": 18, + "document": "manifest", + "end": 1158, + "line": 30, + "start": 1110 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/condition/scopes", + "span": { + "column": 55, + "document": "manifest", + "end": 1157, + "line": 30, + "start": 1147 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/1/condition/scopes/0", + "span": { + "column": 56, + "document": "manifest", + "end": 1156, + "line": 30, + "start": 1148 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/exclude", + "span": { + "column": 5, + "document": "manifest", + "end": 1164, + "line": 28, + "start": 1028 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 1164, + "line": 28, + "start": 1028 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/1/mode", + "span": { + "column": 50, + "document": "manifest", + "end": 1091, + "line": 29, + "start": 1086 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/native", + "span": { + "column": 5, + "document": "manifest", + "end": 1164, + "line": 28, + "start": 1028 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/overrides", + "span": { + "column": 5, + "document": "manifest", + "end": 1164, + "line": 28, + "start": 1028 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/select", + "span": { + "column": 33, + "document": "manifest", + "end": 1078, + "line": 29, + "start": 1069 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/select/0", + "span": { + "column": 34, + "document": "manifest", + "end": 1077, + "line": 29, + "start": 1070 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/source", + "span": { + "column": 15, + "document": "manifest", + "end": 1059, + "line": 29, + "start": 1051 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/10", + "span": { + "column": 5, + "document": "manifest", + "end": 3059, + "line": 80, + "start": 2898 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/10/agents", + "span": { + "column": 15, + "document": "manifest", + "end": 3018, + "line": 82, + "start": 3005 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/10/agents/0", + "span": { + "column": 16, + "document": "manifest", + "end": 3017, + "line": 82, + "start": 3006 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/10/condition", + "span": { + "column": 41, + "document": "manifest", + "end": 3053, + "line": 82, + "start": 3031 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/10/condition/agents", + "span": { + "column": 41, + "document": "manifest", + "end": 3053, + "line": 82, + "start": 3031 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/10/condition/platforms", + "span": { + "column": 41, + "document": "manifest", + "end": 3053, + "line": 82, + "start": 3031 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/10/condition/scopes", + "span": { + "column": 55, + "document": "manifest", + "end": 3052, + "line": 82, + "start": 3045 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/10/condition/scopes/0", + "span": { + "column": 56, + "document": "manifest", + "end": 3051, + "line": 82, + "start": 3046 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/10/exclude", + "span": { + "column": 5, + "document": "manifest", + "end": 3059, + "line": 80, + "start": 2898 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/10/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 3059, + "line": 80, + "start": 2898 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/10/mode", + "span": { + "column": 76, + "document": "manifest", + "end": 2989, + "line": 81, + "start": 2982 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/10/name", + "span": { + "column": 13, + "document": "manifest", + "end": 2933, + "line": 81, + "start": 2919 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/10/native", + "span": { + "column": 5, + "document": "manifest", + "end": 3059, + "line": 80, + "start": 2898 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/10/path", + "span": { + "column": 35, + "document": "manifest", + "end": 2956, + "line": 81, + "start": 2941 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/10/select", + "span": { + "column": 5, + "document": "manifest", + "end": 3059, + "line": 80, + "start": 2898 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/10/source", + "span": { + "column": 60, + "document": "manifest", + "end": 2974, + "line": 81, + "start": 2966 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/11", + "span": { + "column": 5, + "document": "manifest", + "end": 3226, + "line": 84, + "start": 3065 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/11/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 3226, + "line": 84, + "start": 3065 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/11/condition", + "span": { + "column": 52, + "document": "manifest", + "end": 3220, + "line": 86, + "start": 3195 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/11/condition/agents", + "span": { + "column": 52, + "document": "manifest", + "end": 3220, + "line": 86, + "start": 3195 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/11/condition/platforms", + "span": { + "column": 52, + "document": "manifest", + "end": 3220, + "line": 86, + "start": 3195 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/11/condition/scopes", + "span": { + "column": 66, + "document": "manifest", + "end": 3219, + "line": 86, + "start": 3209 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/11/condition/scopes/0", + "span": { + "column": 67, + "document": "manifest", + "end": 3218, + "line": 86, + "start": 3210 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/11/exclude", + "span": { + "column": 16, + "document": "manifest", + "end": 3182, + "line": 86, + "start": 3159 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/11/exclude/0", + "span": { + "column": 17, + "document": "manifest", + "end": 3181, + "line": 86, + "start": 3160 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/11/exclude/0/kind", + "span": { + "column": 17, + "document": "manifest", + "end": 3181, + "line": 86, + "start": 3160 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/11/exclude/0/name", + "span": { + "column": 29, + "document": "manifest", + "end": 3180, + "line": 86, + "start": 3172 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/11/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 3226, + "line": 84, + "start": 3065 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/11/mode", + "span": { + "column": 5, + "document": "manifest", + "end": 3226, + "line": 84, + "start": 3065 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/11/name", + "span": { + "column": 13, + "document": "manifest", + "end": 3100, + "line": 85, + "start": 3086 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/11/native", + "span": { + "column": 5, + "document": "manifest", + "end": 3226, + "line": 84, + "start": 3065 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/11/path", + "span": { + "column": 35, + "document": "manifest", + "end": 3124, + "line": 85, + "start": 3108 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/11/select", + "span": { + "column": 5, + "document": "manifest", + "end": 3226, + "line": 84, + "start": 3065 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/11/source", + "span": { + "column": 61, + "document": "manifest", + "end": 3142, + "line": 85, + "start": 3134 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2", + "span": { + "column": 5, + "document": "manifest", + "end": 1300, + "line": 32, + "start": 1170 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 1300, + "line": 32, + "start": 1170 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/chatGPT", + "span": { + "column": 16, + "document": "manifest", + "end": 1294, + "line": 34, + "start": 1226 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/chatGPT/0", + "span": { + "column": 17, + "document": "manifest", + "end": 1293, + "line": 34, + "start": 1227 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/chatGPT/0/append", + "span": { + "column": 65, + "document": "manifest", + "end": 1292, + "line": 34, + "start": 1275 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/chatGPT/0/condition", + "span": { + "column": 17, + "document": "manifest", + "end": 1293, + "line": 34, + "start": 1227 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/chatGPT/0/name", + "span": { + "column": 31, + "document": "manifest", + "end": 1249, + "line": 34, + "start": 1241 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 32, + "document": "manifest", + "end": 95, + "line": 4, + "start": 86 + } + ], + "pointer": "/components/2/chatGPT/0/sections", + "span": { + "column": 51, + "document": "manifest", + "end": 1265, + "line": 34, + "start": 1261 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 32, + "document": "manifest", + "end": 95, + "line": 4, + "start": 86 + }, + { + "column": 33, + "document": "manifest", + "end": 94, + "line": 4, + "start": 87 + } + ], + "pointer": "/components/2/chatGPT/0/sections/0", + "span": { + "column": 51, + "document": "manifest", + "end": 1265, + "line": 34, + "start": 1261 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 32, + "document": "manifest", + "end": 95, + "line": 4, + "start": 86 + }, + { + "column": 33, + "document": "manifest", + "end": 94, + "line": 4, + "start": 87 + } + ], + "pointer": "/components/2/chatGPT/0/sections/0/condition", + "span": { + "column": 51, + "document": "manifest", + "end": 1265, + "line": 34, + "start": 1261 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 32, + "document": "manifest", + "end": 95, + "line": 4, + "start": 86 + }, + { + "column": 33, + "document": "manifest", + "end": 94, + "line": 4, + "start": 87 + } + ], + "pointer": "/components/2/chatGPT/0/sections/0/name", + "span": { + "column": 51, + "document": "manifest", + "end": 1265, + "line": 34, + "start": 1261 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 32, + "document": "manifest", + "end": 95, + "line": 4, + "start": 86 + }, + { + "column": 33, + "document": "manifest", + "end": 94, + "line": 4, + "start": 87 + } + ], + "pointer": "/components/2/chatGPT/0/sections/0/source", + "span": { + "column": 51, + "document": "manifest", + "end": 1265, + "line": 34, + "start": 1261 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 1300, + "line": 32, + "start": 1170 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 1300, + "line": 32, + "start": 1170 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/native", + "span": { + "column": 5, + "document": "manifest", + "end": 1300, + "line": 32, + "start": 1170 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 16, + "document": "manifest", + "end": 166, + "line": 5, + "start": 111 + } + ], + "pointer": "/components/2/sections", + "span": { + "column": 17, + "document": "manifest", + "end": 1209, + "line": 33, + "start": 1201 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 16, + "document": "manifest", + "end": 166, + "line": 5, + "start": 111 + }, + { + "column": 33, + "document": "manifest", + "end": 94, + "line": 4, + "start": 87 + } + ], + "pointer": "/components/2/sections/0", + "span": { + "column": 17, + "document": "manifest", + "end": 1209, + "line": 33, + "start": 1201 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 16, + "document": "manifest", + "end": 166, + "line": 5, + "start": 111 + }, + { + "column": 33, + "document": "manifest", + "end": 94, + "line": 4, + "start": 87 + } + ], + "pointer": "/components/2/sections/0/condition", + "span": { + "column": 17, + "document": "manifest", + "end": 1209, + "line": 33, + "start": 1201 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 16, + "document": "manifest", + "end": 166, + "line": 5, + "start": 111 + }, + { + "column": 33, + "document": "manifest", + "end": 94, + "line": 4, + "start": 87 + } + ], + "pointer": "/components/2/sections/0/name", + "span": { + "column": 17, + "document": "manifest", + "end": 1209, + "line": 33, + "start": 1201 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 16, + "document": "manifest", + "end": 166, + "line": 5, + "start": 111 + }, + { + "column": 33, + "document": "manifest", + "end": 94, + "line": 4, + "start": 87 + } + ], + "pointer": "/components/2/sections/0/source", + "span": { + "column": 17, + "document": "manifest", + "end": 1209, + "line": 33, + "start": 1201 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 16, + "document": "manifest", + "end": 166, + "line": 5, + "start": 111 + }, + { + "column": 24, + "document": "manifest", + "end": 165, + "line": 5, + "start": 119 + } + ], + "pointer": "/components/2/sections/1", + "span": { + "column": 17, + "document": "manifest", + "end": 1209, + "line": 33, + "start": 1201 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 16, + "document": "manifest", + "end": 166, + "line": 5, + "start": 111 + }, + { + "column": 24, + "document": "manifest", + "end": 165, + "line": 5, + "start": 119 + } + ], + "pointer": "/components/2/sections/1/condition", + "span": { + "column": 17, + "document": "manifest", + "end": 1209, + "line": 33, + "start": 1201 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 16, + "document": "manifest", + "end": 166, + "line": 5, + "start": 111 + }, + { + "column": 24, + "document": "manifest", + "end": 165, + "line": 5, + "start": 119 + }, + { + "column": 39, + "document": "manifest", + "end": 147, + "line": 5, + "start": 134 + } + ], + "pointer": "/components/2/sections/1/name", + "span": { + "column": 17, + "document": "manifest", + "end": 1209, + "line": 33, + "start": 1201 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 16, + "document": "manifest", + "end": 166, + "line": 5, + "start": 111 + }, + { + "column": 24, + "document": "manifest", + "end": 165, + "line": 5, + "start": 119 + }, + { + "column": 62, + "document": "manifest", + "end": 164, + "line": 5, + "start": 157 + } + ], + "pointer": "/components/2/sections/1/source", + "span": { + "column": 17, + "document": "manifest", + "end": 1209, + "line": 33, + "start": 1201 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3", + "span": { + "column": 5, + "document": "manifest", + "end": 1539, + "line": 36, + "start": 1306 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3/agents", + "span": { + "column": 15, + "document": "manifest", + "end": 1533, + "line": 42, + "start": 1520 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/3/agents/0", + "span": { + "column": 16, + "document": "manifest", + "end": 1532, + "line": 42, + "start": 1521 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 1539, + "line": 36, + "start": 1306 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 1539, + "line": 36, + "start": 1306 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3/name", + "span": { + "column": 13, + "document": "manifest", + "end": 1341, + "line": 37, + "start": 1330 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/native", + "span": { + "column": 5, + "document": "manifest", + "end": 1539, + "line": 36, + "start": 1306 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3/transport", + "span": { + "column": 18, + "document": "manifest", + "end": 1504, + "line": 38, + "start": 1360 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3/transport/arguments", + "span": { + "column": 39, + "document": "manifest", + "end": 1415, + "line": 39, + "start": 1406 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3/transport/arguments/0", + "span": { + "column": 40, + "document": "manifest", + "end": 1414, + "line": 39, + "start": 1407 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3/transport/environment", + "span": { + "column": 22, + "document": "manifest", + "end": 1496, + "line": 40, + "start": 1438 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3/transport/environment/LOG_LEVEL", + "span": { + "column": 73, + "document": "manifest", + "end": 1495, + "line": 40, + "start": 1489 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/transport/environment/LOG_LEVEL/kind", + "span": { + "column": 73, + "document": "manifest", + "end": 1495, + "line": 40, + "start": 1489 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/transport/environment/LOG_LEVEL/value", + "span": { + "column": 73, + "document": "manifest", + "end": 1495, + "line": 40, + "start": 1489 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3/transport/environment/TOKEN", + "span": { + "column": 32, + "document": "manifest", + "end": 1474, + "line": 40, + "start": 1448 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/transport/environment/TOKEN/kind", + "span": { + "column": 32, + "document": "manifest", + "end": 1474, + "line": 40, + "start": 1448 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3/transport/environment/TOKEN/value", + "span": { + "column": 40, + "document": "manifest", + "end": 1473, + "line": 40, + "start": 1456 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3/transport/executable", + "span": { + "column": 9, + "document": "manifest", + "end": 1393, + "line": 39, + "start": 1376 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/transport/kind", + "span": { + "column": 18, + "document": "manifest", + "end": 1504, + "line": 38, + "start": 1360 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/transport/workingDirectory", + "span": { + "column": 18, + "document": "manifest", + "end": 1504, + "line": 38, + "start": 1360 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4", + "span": { + "column": 5, + "document": "manifest", + "end": 1749, + "line": 44, + "start": 1545 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/agents", + "span": { + "column": 15, + "document": "manifest", + "end": 1743, + "line": 49, + "start": 1732 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/4/agents/0", + "span": { + "column": 16, + "document": "manifest", + "end": 1742, + "line": 49, + "start": 1733 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 1749, + "line": 44, + "start": 1545 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 1749, + "line": 44, + "start": 1545 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/name", + "span": { + "column": 13, + "document": "manifest", + "end": 1580, + "line": 45, + "start": 1569 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/native", + "span": { + "column": 5, + "document": "manifest", + "end": 1749, + "line": 44, + "start": 1545 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/transport", + "span": { + "column": 18, + "document": "manifest", + "end": 1716, + "line": 46, + "start": 1599 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/transport/headers", + "span": { + "column": 50, + "document": "manifest", + "end": 1708, + "line": 47, + "start": 1665 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/transport/headers/Authorization", + "span": { + "column": 68, + "document": "manifest", + "end": 1707, + "line": 47, + "start": 1683 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/transport/headers/Authorization/kind", + "span": { + "column": 68, + "document": "manifest", + "end": 1707, + "line": 47, + "start": 1683 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/transport/headers/Authorization/value", + "span": { + "column": 81, + "document": "manifest", + "end": 1706, + "line": 47, + "start": 1696 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/transport/kind", + "span": { + "column": 18, + "document": "manifest", + "end": 1716, + "line": 46, + "start": 1599 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/transport/url", + "span": { + "column": 14, + "document": "manifest", + "end": 1654, + "line": 47, + "start": 1629 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5", + "span": { + "column": 5, + "document": "manifest", + "end": 2050, + "line": 51, + "start": 1755 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/agents", + "span": { + "column": 35, + "document": "manifest", + "end": 2006, + "line": 57, + "start": 1993 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/5/agents/0", + "span": { + "column": 36, + "document": "manifest", + "end": 2005, + "line": 57, + "start": 1994 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/condition", + "span": { + "column": 61, + "document": "manifest", + "end": 2044, + "line": 57, + "start": 2019 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/5/condition/agents", + "span": { + "column": 61, + "document": "manifest", + "end": 2044, + "line": 57, + "start": 2019 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/5/condition/platforms", + "span": { + "column": 61, + "document": "manifest", + "end": 2044, + "line": 57, + "start": 2019 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/condition/scopes", + "span": { + "column": 75, + "document": "manifest", + "end": 2043, + "line": 57, + "start": 2033 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/5/condition/scopes/0", + "span": { + "column": 76, + "document": "manifest", + "end": 2042, + "line": 57, + "start": 2034 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/5/event", + "span": { + "column": 30, + "document": "manifest", + "end": 1801, + "line": 52, + "start": 1791 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/5/event/kind", + "span": { + "column": 30, + "document": "manifest", + "end": 1801, + "line": 52, + "start": 1791 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/5/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 2050, + "line": 51, + "start": 1755 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/5/matcher", + "span": { + "column": 5, + "document": "manifest", + "end": 2050, + "line": 51, + "start": 1755 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/name", + "span": { + "column": 13, + "document": "manifest", + "end": 1782, + "line": 52, + "start": 1774 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/5/native", + "span": { + "column": 5, + "document": "manifest", + "end": 2050, + "line": 51, + "start": 1755 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/run", + "span": { + "column": 12, + "document": "manifest", + "end": 1957, + "line": 53, + "start": 1814 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/run/arguments", + "span": { + "column": 29, + "document": "manifest", + "end": 1890, + "line": 54, + "start": 1855 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/run/arguments/0", + "span": { + "column": 30, + "document": "manifest", + "end": 1864, + "line": 54, + "start": 1856 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/run/arguments/1", + "span": { + "column": 40, + "document": "manifest", + "end": 1878, + "line": 54, + "start": 1866 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/run/arguments/2", + "span": { + "column": 54, + "document": "manifest", + "end": 1889, + "line": 54, + "start": 1880 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/5/run/environment", + "span": { + "column": 12, + "document": "manifest", + "end": 1957, + "line": 53, + "start": 1814 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/run/executable", + "span": { + "column": 9, + "document": "manifest", + "end": 1842, + "line": 54, + "start": 1835 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/5/run/kind", + "span": { + "column": 12, + "document": "manifest", + "end": 1957, + "line": 53, + "start": 1814 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/run/workingDirectory", + "span": { + "column": 27, + "document": "manifest", + "end": 1949, + "line": 55, + "start": 1918 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/run/workingDirectory/path", + "span": { + "column": 33, + "document": "manifest", + "end": 1931, + "line": 55, + "start": 1924 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/run/workingDirectory/source", + "span": { + "column": 50, + "document": "manifest", + "end": 1948, + "line": 55, + "start": 1941 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/timeoutSeconds", + "span": { + "column": 23, + "document": "manifest", + "end": 1983, + "line": 57, + "start": 1981 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6", + "span": { + "column": 5, + "document": "manifest", + "end": 2315, + "line": 59, + "start": 2056 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/agents", + "span": { + "column": 15, + "document": "manifest", + "end": 2309, + "line": 63, + "start": 2296 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/6/agents/0", + "span": { + "column": 16, + "document": "manifest", + "end": 2308, + "line": 63, + "start": 2297 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 2315, + "line": 59, + "start": 2056 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/description", + "span": { + "column": 43, + "document": "manifest", + "end": 2135, + "line": 60, + "start": 2108 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 2315, + "line": 59, + "start": 2056 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/name", + "span": { + "column": 13, + "document": "manifest", + "end": 2093, + "line": 60, + "start": 2078 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/native", + "span": { + "column": 5, + "document": "manifest", + "end": 2315, + "line": 59, + "start": 2056 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/parameters", + "span": { + "column": 19, + "document": "manifest", + "end": 2280, + "line": 62, + "start": 2214 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/parameters/0", + "span": { + "column": 20, + "document": "manifest", + "end": 2279, + "line": 62, + "start": 2215 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/parameters/0/defaultValue", + "span": { + "column": 20, + "document": "manifest", + "end": 2279, + "line": 62, + "start": 2215 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/parameters/0/description", + "span": { + "column": 60, + "document": "manifest", + "end": 2278, + "line": 62, + "start": 2255 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/parameters/0/name", + "span": { + "column": 37, + "document": "manifest", + "end": 2240, + "line": 62, + "start": 2232 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/prompt", + "span": { + "column": 15, + "document": "manifest", + "end": 2194, + "line": 61, + "start": 2151 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/prompt/kind", + "span": { + "column": 15, + "document": "manifest", + "end": 2194, + "line": 61, + "start": 2151 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/prompt/value", + "span": { + "column": 15, + "document": "manifest", + "end": 2194, + "line": 61, + "start": 2151 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7", + "span": { + "column": 5, + "document": "manifest", + "end": 2558, + "line": 65, + "start": 2321 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/agents", + "span": { + "column": 15, + "document": "manifest", + "end": 2513, + "line": 69, + "start": 2500 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/7/agents/0", + "span": { + "column": 16, + "document": "manifest", + "end": 2512, + "line": 69, + "start": 2501 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/condition", + "span": { + "column": 41, + "document": "manifest", + "end": 2552, + "line": 69, + "start": 2526 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/condition/agents", + "span": { + "column": 41, + "document": "manifest", + "end": 2552, + "line": 69, + "start": 2526 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/condition/platforms", + "span": { + "column": 58, + "document": "manifest", + "end": 2551, + "line": 69, + "start": 2543 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/7/condition/platforms/0", + "span": { + "column": 59, + "document": "manifest", + "end": 2550, + "line": 69, + "start": 2544 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/condition/scopes", + "span": { + "column": 41, + "document": "manifest", + "end": 2552, + "line": 69, + "start": 2526 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/initializationOptions", + "span": { + "column": 30, + "document": "manifest", + "end": 2484, + "line": 68, + "start": 2456 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/initializationOptions/backgroundIndexing", + "span": { + "column": 53, + "document": "manifest", + "end": 2483, + "line": 68, + "start": 2479 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/initializationOptions/backgroundIndexing/kind", + "span": { + "column": 53, + "document": "manifest", + "end": 2483, + "line": 68, + "start": 2479 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/initializationOptions/backgroundIndexing/value", + "span": { + "column": 53, + "document": "manifest", + "end": 2483, + "line": 68, + "start": 2479 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 2558, + "line": 65, + "start": 2321 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/languages", + "span": { + "column": 18, + "document": "manifest", + "end": 2425, + "line": 67, + "start": 2406 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/languages/.swift", + "span": { + "column": 29, + "document": "manifest", + "end": 2424, + "line": 67, + "start": 2417 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/name", + "span": { + "column": 13, + "document": "manifest", + "end": 2352, + "line": 66, + "start": 2345 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/native", + "span": { + "column": 5, + "document": "manifest", + "end": 2558, + "line": 65, + "start": 2321 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/run", + "span": { + "column": 27, + "document": "manifest", + "end": 2387, + "line": 66, + "start": 2359 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/run/arguments", + "span": { + "column": 27, + "document": "manifest", + "end": 2387, + "line": 66, + "start": 2359 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/run/environment", + "span": { + "column": 27, + "document": "manifest", + "end": 2387, + "line": 66, + "start": 2359 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/run/executable", + "span": { + "column": 39, + "document": "manifest", + "end": 2386, + "line": 66, + "start": 2371 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/run/kind", + "span": { + "column": 27, + "document": "manifest", + "end": 2387, + "line": 66, + "start": 2359 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/run/workingDirectory", + "span": { + "column": 27, + "document": "manifest", + "end": 2387, + "line": 66, + "start": 2359 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/8", + "span": { + "column": 5, + "document": "manifest", + "end": 2721, + "line": 71, + "start": 2564 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/8/agents", + "span": { + "column": 15, + "document": "manifest", + "end": 2677, + "line": 74, + "start": 2664 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/8/agents/0", + "span": { + "column": 16, + "document": "manifest", + "end": 2676, + "line": 74, + "start": 2665 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/8/condition", + "span": { + "column": 41, + "document": "manifest", + "end": 2715, + "line": 74, + "start": 2690 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/8/condition/agents", + "span": { + "column": 41, + "document": "manifest", + "end": 2715, + "line": 74, + "start": 2690 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/8/condition/platforms", + "span": { + "column": 41, + "document": "manifest", + "end": 2715, + "line": 74, + "start": 2690 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/8/condition/scopes", + "span": { + "column": 55, + "document": "manifest", + "end": 2714, + "line": 74, + "start": 2704 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/8/condition/scopes/0", + "span": { + "column": 56, + "document": "manifest", + "end": 2713, + "line": 74, + "start": 2705 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/8/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 2721, + "line": 71, + "start": 2564 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/8/name", + "span": { + "column": 13, + "document": "manifest", + "end": 2605, + "line": 72, + "start": 2590 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/8/native", + "span": { + "column": 5, + "document": "manifest", + "end": 2721, + "line": 71, + "start": 2564 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/8/rules", + "span": { + "column": 14, + "document": "manifest", + "end": 2648, + "line": 73, + "start": 2620 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/8/rules/0", + "span": { + "column": 15, + "document": "manifest", + "end": 2647, + "line": 73, + "start": 2621 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/8/rules/0/kind", + "span": { + "column": 15, + "document": "manifest", + "end": 2647, + "line": 73, + "start": 2621 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/8/rules/0/operation", + "span": { + "column": 21, + "document": "manifest", + "end": 2632, + "line": 73, + "start": 2627 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/8/rules/0/operation/kind", + "span": { + "column": 21, + "document": "manifest", + "end": 2632, + "line": 73, + "start": 2627 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/8/rules/0/pattern", + "span": { + "column": 28, + "document": "manifest", + "end": 2646, + "line": 73, + "start": 2634 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/9", + "span": { + "column": 5, + "document": "manifest", + "end": 2892, + "line": 76, + "start": 2727 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/9/agents", + "span": { + "column": 15, + "document": "manifest", + "end": 2848, + "line": 78, + "start": 2839 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/9/agents/0", + "span": { + "column": 16, + "document": "manifest", + "end": 2847, + "line": 78, + "start": 2840 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/9/condition", + "span": { + "column": 37, + "document": "manifest", + "end": 2886, + "line": 78, + "start": 2861 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/9/condition/agents", + "span": { + "column": 37, + "document": "manifest", + "end": 2886, + "line": 78, + "start": 2861 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/9/condition/platforms", + "span": { + "column": 37, + "document": "manifest", + "end": 2886, + "line": 78, + "start": 2861 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/9/condition/scopes", + "span": { + "column": 51, + "document": "manifest", + "end": 2885, + "line": 78, + "start": 2875 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/9/condition/scopes/0", + "span": { + "column": 52, + "document": "manifest", + "end": 2884, + "line": 78, + "start": 2876 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/9/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 2892, + "line": 76, + "start": 2727 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/9/name", + "span": { + "column": 13, + "document": "manifest", + "end": 2764, + "line": 77, + "start": 2748 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/9/native", + "span": { + "column": 5, + "document": "manifest", + "end": 2892, + "line": 76, + "start": 2727 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/9/patterns", + "span": { + "column": 41, + "document": "manifest", + "end": 2803, + "line": 77, + "start": 2776 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/9/patterns/0", + "span": { + "column": 42, + "document": "manifest", + "end": 2786, + "line": 77, + "start": 2777 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/9/patterns/1", + "span": { + "column": 53, + "document": "manifest", + "end": 2802, + "line": 77, + "start": 2788 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/9/purpose", + "span": { + "column": 79, + "document": "manifest", + "end": 2823, + "line": 77, + "start": 2814 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/defaultAgents", + "span": { + "column": 14, + "document": "manifest", + "end": 3467, + "line": 15, + "start": 475 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/exports", + "span": { + "column": 14, + "document": "manifest", + "end": 3467, + "line": 15, + "start": 475 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups", + "span": { + "column": 11, + "document": "manifest", + "end": 3408, + "line": 89, + "start": 3243 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups/0", + "span": { + "column": 5, + "document": "manifest", + "end": 3403, + "line": 90, + "start": 3249 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups/0/components", + "span": { + "column": 41, + "document": "manifest", + "end": 3307, + "line": 91, + "start": 3297 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + } + ], + "pointer": "/groups/0/components/0", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 11, + "document": "manifest", + "end": 356, + "line": 10, + "start": 343 + } + ], + "pointer": "/groups/0/components/0/agents", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 11, + "document": "manifest", + "end": 356, + "line": 10, + "start": 343 + }, + { + "column": 12, + "document": "manifest", + "end": 355, + "line": 10, + "start": 344 + } + ], + "pointer": "/groups/0/components/0/agents/0", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 14, + "document": "manifest", + "end": 397, + "line": 11, + "start": 371 + } + ], + "pointer": "/groups/0/components/0/condition", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 14, + "document": "manifest", + "end": 397, + "line": 11, + "start": 371 + } + ], + "pointer": "/groups/0/components/0/condition/agents", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 14, + "document": "manifest", + "end": 397, + "line": 11, + "start": 371 + }, + { + "column": 31, + "document": "manifest", + "end": 396, + "line": 11, + "start": 388 + } + ], + "pointer": "/groups/0/components/0/condition/platforms", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 14, + "document": "manifest", + "end": 397, + "line": 11, + "start": 371 + }, + { + "column": 31, + "document": "manifest", + "end": 396, + "line": 11, + "start": 388 + }, + { + "column": 32, + "document": "manifest", + "end": 395, + "line": 11, + "start": 389 + } + ], + "pointer": "/groups/0/components/0/condition/platforms/0", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 14, + "document": "manifest", + "end": 397, + "line": 11, + "start": 371 + } + ], + "pointer": "/groups/0/components/0/condition/scopes", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 16, + "document": "manifest", + "end": 270, + "line": 8, + "start": 239 + } + ], + "pointer": "/groups/0/components/0/description", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + } + ], + "pointer": "/groups/0/components/0/kind", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + } + ], + "pointer": "/groups/0/components/0/model", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 9, + "document": "manifest", + "end": 222, + "line": 7, + "start": 212 + } + ], + "pointer": "/groups/0/components/0/name", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 11, + "document": "manifest", + "end": 458, + "line": 12, + "start": 409 + } + ], + "pointer": "/groups/0/components/0/native", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 11, + "document": "manifest", + "end": 458, + "line": 12, + "start": 409 + }, + { + "column": 38, + "document": "manifest", + "end": 457, + "line": 12, + "start": 436 + } + ], + "pointer": "/groups/0/components/0/native/claude-code~1subagent@1", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 11, + "document": "manifest", + "end": 458, + "line": 12, + "start": 409 + }, + { + "column": 38, + "document": "manifest", + "end": 457, + "line": 12, + "start": 436 + }, + { + "column": 49, + "document": "manifest", + "end": 456, + "line": 12, + "start": 447 + } + ], + "pointer": "/groups/0/components/0/native/claude-code~1subagent@1/memory", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 11, + "document": "manifest", + "end": 458, + "line": 12, + "start": 409 + }, + { + "column": 38, + "document": "manifest", + "end": 457, + "line": 12, + "start": 436 + }, + { + "column": 49, + "document": "manifest", + "end": 456, + "line": 12, + "start": 447 + } + ], + "pointer": "/groups/0/components/0/native/claude-code~1subagent@1/memory/kind", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 11, + "document": "manifest", + "end": 458, + "line": 12, + "start": 409 + }, + { + "column": 38, + "document": "manifest", + "end": 457, + "line": 12, + "start": 436 + }, + { + "column": 49, + "document": "manifest", + "end": 456, + "line": 12, + "start": 447 + } + ], + "pointer": "/groups/0/components/0/native/claude-code~1subagent@1/memory/value", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 11, + "document": "manifest", + "end": 331, + "line": 9, + "start": 282 + } + ], + "pointer": "/groups/0/components/0/prompt", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 11, + "document": "manifest", + "end": 331, + "line": 9, + "start": 282 + } + ], + "pointer": "/groups/0/components/0/prompt/kind", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + }, + { + "column": 11, + "document": "manifest", + "end": 331, + "line": 9, + "start": 282 + } + ], + "pointer": "/groups/0/components/0/prompt/value", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 460, + "line": 6, + "start": 193 + } + ], + "pointer": "/groups/0/components/0/tools", + "span": { + "column": 42, + "document": "manifest", + "end": 3306, + "line": 91, + "start": 3298 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/groups/0/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 3403, + "line": 90, + "start": 3249 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups/0/name", + "span": { + "column": 13, + "document": "manifest", + "end": 3283, + "line": 91, + "start": 3269 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups/0/uses", + "span": { + "column": 13, + "document": "manifest", + "end": 3397, + "line": 92, + "start": 3321 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups/0/uses/0", + "span": { + "column": 14, + "document": "manifest", + "end": 3396, + "line": 92, + "start": 3322 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups/0/uses/0/condition", + "span": { + "column": 64, + "document": "manifest", + "end": 3395, + "line": 92, + "start": 3372 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups/0/uses/0/condition/agents", + "span": { + "column": 78, + "document": "manifest", + "end": 3394, + "line": 92, + "start": 3386 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/groups/0/uses/0/condition/agents/0", + "span": { + "column": 79, + "document": "manifest", + "end": 3393, + "line": 92, + "start": 3387 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/groups/0/uses/0/condition/platforms", + "span": { + "column": 64, + "document": "manifest", + "end": 3395, + "line": 92, + "start": 3372 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/groups/0/uses/0/condition/scopes", + "span": { + "column": 64, + "document": "manifest", + "end": 3395, + "line": 92, + "start": 3372 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/groups/0/uses/0/kind", + "span": { + "column": 14, + "document": "manifest", + "end": 3396, + "line": 92, + "start": 3322 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups/0/uses/0/name", + "span": { + "column": 27, + "document": "manifest", + "end": 3343, + "line": 92, + "start": 3335 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups/0/uses/0/source", + "span": { + "column": 45, + "document": "manifest", + "end": 3359, + "line": 92, + "start": 3353 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources", + "span": { + "column": 12, + "document": "manifest", + "end": 849, + "line": 16, + "start": 494 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/0", + "span": { + "column": 5, + "document": "manifest", + "end": 754, + "line": 20, + "start": 682 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/0/index", + "span": { + "column": 37, + "document": "manifest", + "end": 753, + "line": 20, + "start": 714 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/0/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 754, + "line": 20, + "start": 682 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/0/name", + "span": { + "column": 19, + "document": "manifest", + "end": 705, + "line": 20, + "start": 696 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/0/requirement", + "span": { + "column": 5, + "document": "manifest", + "end": 754, + "line": 20, + "start": 682 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/0/subpath", + "span": { + "column": 5, + "document": "manifest", + "end": 754, + "line": 20, + "start": 682 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1", + "span": { + "column": 5, + "document": "manifest", + "end": 590, + "line": 18, + "start": 543 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/1/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 590, + "line": 18, + "start": 543 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1/name", + "span": { + "column": 19, + "document": "manifest", + "end": 565, + "line": 18, + "start": 557 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1/path", + "span": { + "column": 35, + "document": "manifest", + "end": 589, + "line": 18, + "start": 573 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/1/requirement", + "span": { + "column": 5, + "document": "manifest", + "end": 590, + "line": 18, + "start": 543 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/1/subpath", + "span": { + "column": 5, + "document": "manifest", + "end": 590, + "line": 18, + "start": 543 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/2", + "span": { + "column": 5, + "document": "manifest", + "end": 676, + "line": 19, + "start": 596 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/2/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 676, + "line": 19, + "start": 596 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/2/name", + "span": { + "column": 19, + "document": "manifest", + "end": 617, + "line": 19, + "start": 610 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/2/requirement", + "span": { + "column": 77, + "document": "manifest", + "end": 675, + "line": 19, + "start": 668 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/2/requirement/from", + "span": { + "column": 77, + "document": "manifest", + "end": 675, + "line": 19, + "start": 668 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/2/subpath", + "span": { + "column": 5, + "document": "manifest", + "end": 676, + "line": 19, + "start": 596 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/2/url", + "span": { + "column": 33, + "document": "manifest", + "end": 660, + "line": 19, + "start": 624 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/3", + "span": { + "column": 5, + "document": "manifest", + "end": 537, + "line": 17, + "start": 500 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/3/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 537, + "line": 17, + "start": 500 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/3/name", + "span": { + "column": 19, + "document": "manifest", + "end": 520, + "line": 17, + "start": 514 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/3/path", + "span": { + "column": 33, + "document": "manifest", + "end": 536, + "line": 17, + "start": 528 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/3/requirement", + "span": { + "column": 5, + "document": "manifest", + "end": 537, + "line": 17, + "start": 500 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/3/subpath", + "span": { + "column": 5, + "document": "manifest", + "end": 537, + "line": 17, + "start": 500 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/4", + "span": { + "column": 5, + "document": "manifest", + "end": 844, + "line": 21, + "start": 760 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/4/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 844, + "line": 21, + "start": 760 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/4/name", + "span": { + "column": 19, + "document": "manifest", + "end": 782, + "line": 21, + "start": 774 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/4/requirement", + "span": { + "column": 81, + "document": "manifest", + "end": 843, + "line": 21, + "start": 836 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/4/requirement/exact", + "span": { + "column": 81, + "document": "manifest", + "end": 843, + "line": 21, + "start": 836 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/4/subpath", + "span": { + "column": 5, + "document": "manifest", + "end": 844, + "line": 21, + "start": 760 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/4/url", + "span": { + "column": 34, + "document": "manifest", + "end": 827, + "line": 21, + "start": 789 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/uses", + "span": { + "column": 9, + "document": "manifest", + "end": 3434, + "line": 95, + "start": 3418 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/uses/0", + "span": { + "column": 10, + "document": "manifest", + "end": 3433, + "line": 95, + "start": 3419 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/uses/0/condition", + "span": { + "column": 10, + "document": "manifest", + "end": 3433, + "line": 95, + "start": 3419 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/uses/0/kind", + "span": { + "column": 10, + "document": "manifest", + "end": 3433, + "line": 95, + "start": 3419 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/uses/0/name", + "span": { + "column": 10, + "document": "manifest", + "end": 3433, + "line": 95, + "start": 3419 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/uses/0/source", + "span": { + "column": 10, + "document": "manifest", + "end": 3433, + "line": 95, + "start": 3419 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/watch", + "span": { + "column": 10, + "document": "manifest", + "end": 3465, + "line": 96, + "start": 3445 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/watch/0", + "span": { + "column": 20, + "document": "manifest", + "end": 3464, + "line": 96, + "start": 3455 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/watch/1", + "span": { + "column": 11, + "document": "manifest", + "end": 3453, + "line": 96, + "start": 3446 + } + } + ], + "schemaVersion": 1, + "sourceDigest": "sha256:62b31c7e40fb0b847ed6fb2fd5ef2b7895da18b8f65b4bbef90383be64eb061a" +} diff --git a/Tests/AgentsManifestTests/Fixtures/DumpSymbolic.dump.json b/Tests/AgentsManifestTests/Fixtures/DumpSymbolic.dump.json new file mode 100644 index 0000000..8aa7f49 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/DumpSymbolic.dump.json @@ -0,0 +1,3037 @@ +{ + "declaration": { + "components": [ + { + "agents": [], + "chatGPT": [ + { + "append": null, + "condition": null, + "name": "a", + "sections": [ + { + "condition": null, + "name": "own", + "source": null + } + ] + }, + { + "append": null, + "condition": null, + "name": "z", + "sections": [] + } + ], + "condition": null, + "kind": "instructions", + "native": {}, + "sections": [ + { + "condition": null, + "name": "own", + "source": null + }, + { + "condition": { + "agents": [ + "codex", + "opencode" + ], + "platforms": [ + "linux", + "macos" + ], + "scopes": [ + "project", + "user" + ] + }, + "name": "rule", + "source": "z" + } + ] + }, + { + "agents": null, + "condition": null, + "exclude": [ + "a", + "z" + ], + "kind": "skills", + "mode": null, + "native": {}, + "overrides": [ + { + "agents": null, + "mode": null, + "name": "a" + }, + { + "agents": [], + "mode": null, + "name": "z" + } + ], + "select": [ + "a", + "z" + ], + "source": "z" + }, + { + "agents": null, + "condition": null, + "exclude": [ + { + "kind": "command", + "name": "zzz" + }, + { + "kind": "hook", + "name": "aaa" + }, + { + "kind": "hook", + "name": "bbb" + }, + { + "kind": "skill", + "name": "ccc" + } + ], + "kind": "plugin", + "mode": "components", + "name": "bundle", + "native": {}, + "path": "bundle", + "select": null, + "source": "z" + } + ], + "defaultAgents": [], + "exports": [ + "a", + "z" + ], + "groups": [ + { + "components": [], + "condition": null, + "name": "a", + "uses": [] + }, + { + "components": [], + "condition": { + "agents": [ + "codex", + "opencode" + ], + "platforms": [ + "linux", + "macos" + ], + "scopes": [ + "project", + "user" + ] + }, + "name": "z", + "uses": [] + } + ], + "sources": [ + { + "kind": "local", + "name": "a", + "path": "./a", + "requirement": null, + "subpath": null + }, + { + "kind": "git", + "name": "z", + "requirement": { + "upToNextMinor": "1.2.0" + }, + "subpath": null, + "url": "https://intranet/team.git" + } + ], + "uses": [ + { + "condition": { + "agents": [ + "codex", + "opencode" + ], + "platforms": [ + "linux", + "macos" + ], + "scopes": [ + "project", + "user" + ] + }, + "kind": "exported", + "name": "review", + "source": "z" + }, + { + "condition": null, + "kind": "local", + "name": "a", + "source": null + } + ], + "watch": [ + "a", + "z" + ] + }, + "diagnostics": [ + { + "code": "manifest.domain", + "message": "use the complete Git transport URL", + "related": [], + "severity": "warning", + "span": { + "column": 29, + "document": "manifest", + "end": 295, + "line": 9, + "start": 276 + } + } + ], + "kind": "manifest", + "languageVersion": "1.0", + "locations": [ + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "", + "span": { + "column": 14, + "document": "manifest", + "end": 1014, + "line": 5, + "start": 183 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components", + "span": { + "column": 15, + "document": "manifest", + "end": 851, + "line": 12, + "start": 373 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0", + "span": { + "column": 5, + "document": "manifest", + "end": 563, + "line": 13, + "start": 379 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/agents", + "span": { + "column": 186, + "document": "manifest", + "end": 562, + "line": 13, + "start": 560 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/chatGPT", + "span": { + "column": 103, + "document": "manifest", + "end": 550, + "line": 13, + "start": 477 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/chatGPT/0", + "span": { + "column": 138, + "document": "manifest", + "end": 549, + "line": 13, + "start": 512 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/chatGPT/0/append", + "span": { + "column": 138, + "document": "manifest", + "end": 549, + "line": 13, + "start": 512 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/chatGPT/0/condition", + "span": { + "column": 138, + "document": "manifest", + "end": 549, + "line": 13, + "start": 512 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/chatGPT/0/name", + "span": { + "column": 152, + "document": "manifest", + "end": 529, + "line": 13, + "start": 526 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/chatGPT/0/sections", + "span": { + "column": 167, + "document": "manifest", + "end": 548, + "line": 13, + "start": 541 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/chatGPT/0/sections/0", + "span": { + "column": 168, + "document": "manifest", + "end": 547, + "line": 13, + "start": 542 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/chatGPT/0/sections/0/condition", + "span": { + "column": 168, + "document": "manifest", + "end": 547, + "line": 13, + "start": 542 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/chatGPT/0/sections/0/name", + "span": { + "column": 168, + "document": "manifest", + "end": 547, + "line": 13, + "start": 542 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/chatGPT/0/sections/0/source", + "span": { + "column": 168, + "document": "manifest", + "end": 547, + "line": 13, + "start": 542 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/chatGPT/1", + "span": { + "column": 104, + "document": "manifest", + "end": 510, + "line": 13, + "start": 478 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/chatGPT/1/append", + "span": { + "column": 104, + "document": "manifest", + "end": 510, + "line": 13, + "start": 478 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/chatGPT/1/condition", + "span": { + "column": 104, + "document": "manifest", + "end": 510, + "line": 13, + "start": 478 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/chatGPT/1/name", + "span": { + "column": 118, + "document": "manifest", + "end": 495, + "line": 13, + "start": 492 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/chatGPT/1/sections", + "span": { + "column": 133, + "document": "manifest", + "end": 509, + "line": 13, + "start": 507 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 563, + "line": 13, + "start": 379 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 563, + "line": 13, + "start": 379 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/native", + "span": { + "column": 5, + "document": "manifest", + "end": 563, + "line": 13, + "start": 379 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/sections", + "span": { + "column": 29, + "document": "manifest", + "end": 466, + "line": 13, + "start": 403 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/sections/0", + "span": { + "column": 30, + "document": "manifest", + "end": 409, + "line": 13, + "start": 404 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/sections/0/condition", + "span": { + "column": 30, + "document": "manifest", + "end": 409, + "line": 13, + "start": 404 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/sections/0/name", + "span": { + "column": 30, + "document": "manifest", + "end": 409, + "line": 13, + "start": 404 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/sections/0/source", + "span": { + "column": 30, + "document": "manifest", + "end": 409, + "line": 13, + "start": 404 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/sections/1", + "span": { + "column": 37, + "document": "manifest", + "end": 465, + "line": 13, + "start": 411 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + } + ], + "pointer": "/components/0/sections/1/condition", + "span": { + "column": 84, + "document": "manifest", + "end": 464, + "line": 13, + "start": 458 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 39, + "document": "manifest", + "end": 112, + "line": 4, + "start": 93 + } + ], + "pointer": "/components/0/sections/1/condition/agents", + "span": { + "column": 84, + "document": "manifest", + "end": 464, + "line": 13, + "start": 458 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 39, + "document": "manifest", + "end": 112, + "line": 4, + "start": 93 + }, + { + "column": 51, + "document": "manifest", + "end": 111, + "line": 4, + "start": 105 + } + ], + "pointer": "/components/0/sections/1/condition/agents/0", + "span": { + "column": 84, + "document": "manifest", + "end": 464, + "line": 13, + "start": 458 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 39, + "document": "manifest", + "end": 112, + "line": 4, + "start": 93 + }, + { + "column": 40, + "document": "manifest", + "end": 103, + "line": 4, + "start": 94 + } + ], + "pointer": "/components/0/sections/1/condition/agents/1", + "span": { + "column": 84, + "document": "manifest", + "end": 464, + "line": 13, + "start": 458 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 98, + "document": "manifest", + "end": 168, + "line": 4, + "start": 152 + } + ], + "pointer": "/components/0/sections/1/condition/platforms", + "span": { + "column": 84, + "document": "manifest", + "end": 464, + "line": 13, + "start": 458 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 98, + "document": "manifest", + "end": 168, + "line": 4, + "start": 152 + }, + { + "column": 99, + "document": "manifest", + "end": 159, + "line": 4, + "start": 153 + } + ], + "pointer": "/components/0/sections/1/condition/platforms/0", + "span": { + "column": 84, + "document": "manifest", + "end": 464, + "line": 13, + "start": 458 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 98, + "document": "manifest", + "end": 168, + "line": 4, + "start": 152 + }, + { + "column": 107, + "document": "manifest", + "end": 167, + "line": 4, + "start": 161 + } + ], + "pointer": "/components/0/sections/1/condition/platforms/1", + "span": { + "column": 84, + "document": "manifest", + "end": 464, + "line": 13, + "start": 458 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 68, + "document": "manifest", + "end": 139, + "line": 4, + "start": 122 + } + ], + "pointer": "/components/0/sections/1/condition/scopes", + "span": { + "column": 84, + "document": "manifest", + "end": 464, + "line": 13, + "start": 458 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 68, + "document": "manifest", + "end": 139, + "line": 4, + "start": 122 + }, + { + "column": 76, + "document": "manifest", + "end": 138, + "line": 4, + "start": 130 + } + ], + "pointer": "/components/0/sections/1/condition/scopes/0", + "span": { + "column": 84, + "document": "manifest", + "end": 464, + "line": 13, + "start": 458 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 68, + "document": "manifest", + "end": 139, + "line": 4, + "start": 122 + }, + { + "column": 69, + "document": "manifest", + "end": 128, + "line": 4, + "start": 123 + } + ], + "pointer": "/components/0/sections/1/condition/scopes/1", + "span": { + "column": 84, + "document": "manifest", + "end": 464, + "line": 13, + "start": 458 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/sections/1/name", + "span": { + "column": 52, + "document": "manifest", + "end": 432, + "line": 13, + "start": 426 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/sections/1/source", + "span": { + "column": 68, + "document": "manifest", + "end": 445, + "line": 13, + "start": 442 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1", + "span": { + "column": 5, + "document": "manifest", + "end": 693, + "line": 14, + "start": 569 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 693, + "line": 14, + "start": 569 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 693, + "line": 14, + "start": 569 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/exclude", + "span": { + "column": 55, + "document": "manifest", + "end": 629, + "line": 14, + "start": 619 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/exclude/0", + "span": { + "column": 61, + "document": "manifest", + "end": 628, + "line": 14, + "start": 625 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/exclude/1", + "span": { + "column": 56, + "document": "manifest", + "end": 623, + "line": 14, + "start": 620 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 693, + "line": 14, + "start": 569 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/mode", + "span": { + "column": 5, + "document": "manifest", + "end": 693, + "line": 14, + "start": 569 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/native", + "span": { + "column": 5, + "document": "manifest", + "end": 693, + "line": 14, + "start": 569 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/overrides", + "span": { + "column": 78, + "document": "manifest", + "end": 692, + "line": 14, + "start": 642 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/overrides/0", + "span": { + "column": 110, + "document": "manifest", + "end": 691, + "line": 14, + "start": 674 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/overrides/0/agents", + "span": { + "column": 110, + "document": "manifest", + "end": 691, + "line": 14, + "start": 674 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/overrides/0/mode", + "span": { + "column": 110, + "document": "manifest", + "end": 691, + "line": 14, + "start": 674 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/overrides/0/name", + "span": { + "column": 123, + "document": "manifest", + "end": 690, + "line": 14, + "start": 687 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/overrides/1", + "span": { + "column": 79, + "document": "manifest", + "end": 672, + "line": 14, + "start": 643 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/overrides/1/agents", + "span": { + "column": 105, + "document": "manifest", + "end": 671, + "line": 14, + "start": 669 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/overrides/1/mode", + "span": { + "column": 79, + "document": "manifest", + "end": 672, + "line": 14, + "start": 643 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/overrides/1/name", + "span": { + "column": 92, + "document": "manifest", + "end": 659, + "line": 14, + "start": 656 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/select", + "span": { + "column": 34, + "document": "manifest", + "end": 608, + "line": 14, + "start": 598 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/select/0", + "span": { + "column": 40, + "document": "manifest", + "end": 607, + "line": 14, + "start": 604 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/select/1", + "span": { + "column": 35, + "document": "manifest", + "end": 602, + "line": 14, + "start": 599 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/source", + "span": { + "column": 21, + "document": "manifest", + "end": 588, + "line": 14, + "start": 585 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2", + "span": { + "column": 5, + "document": "manifest", + "end": 846, + "line": 15, + "start": 699 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 846, + "line": 15, + "start": 699 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 846, + "line": 15, + "start": 699 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/exclude", + "span": { + "column": 67, + "document": "manifest", + "end": 845, + "line": 15, + "start": 761 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/exclude/0", + "span": { + "column": 88, + "document": "manifest", + "end": 803, + "line": 15, + "start": 782 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/exclude/0/kind", + "span": { + "column": 88, + "document": "manifest", + "end": 803, + "line": 15, + "start": 782 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/exclude/0/name", + "span": { + "column": 103, + "document": "manifest", + "end": 802, + "line": 15, + "start": 797 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/exclude/1", + "span": { + "column": 68, + "document": "manifest", + "end": 780, + "line": 15, + "start": 762 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/exclude/1/kind", + "span": { + "column": 68, + "document": "manifest", + "end": 780, + "line": 15, + "start": 762 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/exclude/1/name", + "span": { + "column": 80, + "document": "manifest", + "end": 779, + "line": 15, + "start": 774 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/exclude/2", + "span": { + "column": 111, + "document": "manifest", + "end": 823, + "line": 15, + "start": 805 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/exclude/2/kind", + "span": { + "column": 111, + "document": "manifest", + "end": 823, + "line": 15, + "start": 805 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/exclude/2/name", + "span": { + "column": 123, + "document": "manifest", + "end": 822, + "line": 15, + "start": 817 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/exclude/3", + "span": { + "column": 131, + "document": "manifest", + "end": 844, + "line": 15, + "start": 825 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/exclude/3/kind", + "span": { + "column": 131, + "document": "manifest", + "end": 844, + "line": 15, + "start": 825 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/exclude/3/name", + "span": { + "column": 144, + "document": "manifest", + "end": 843, + "line": 15, + "start": 838 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 846, + "line": 15, + "start": 699 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/mode", + "span": { + "column": 5, + "document": "manifest", + "end": 846, + "line": 15, + "start": 699 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/name", + "span": { + "column": 19, + "document": "manifest", + "end": 721, + "line": 15, + "start": 713 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/native", + "span": { + "column": 5, + "document": "manifest", + "end": 846, + "line": 15, + "start": 699 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/path", + "span": { + "column": 35, + "document": "manifest", + "end": 737, + "line": 15, + "start": 729 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/select", + "span": { + "column": 5, + "document": "manifest", + "end": 846, + "line": 15, + "start": 699 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/source", + "span": { + "column": 53, + "document": "manifest", + "end": 750, + "line": 15, + "start": 747 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/defaultAgents", + "span": { + "column": 18, + "document": "manifest", + "end": 210, + "line": 6, + "start": 208 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/exports", + "span": { + "column": 12, + "document": "manifest", + "end": 233, + "line": 7, + "start": 223 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/exports/0", + "span": { + "column": 18, + "document": "manifest", + "end": 232, + "line": 7, + "start": 229 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/exports/1", + "span": { + "column": 13, + "document": "manifest", + "end": 227, + "line": 7, + "start": 224 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups", + "span": { + "column": 11, + "document": "manifest", + "end": 920, + "line": 17, + "start": 863 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups/0", + "span": { + "column": 50, + "document": "manifest", + "end": 919, + "line": 17, + "start": 902 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/groups/0/components", + "span": { + "column": 50, + "document": "manifest", + "end": 919, + "line": 17, + "start": 902 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/groups/0/condition", + "span": { + "column": 50, + "document": "manifest", + "end": 919, + "line": 17, + "start": 902 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups/0/name", + "span": { + "column": 63, + "document": "manifest", + "end": 918, + "line": 17, + "start": 915 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/groups/0/uses", + "span": { + "column": 50, + "document": "manifest", + "end": 919, + "line": 17, + "start": 902 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups/1", + "span": { + "column": 12, + "document": "manifest", + "end": 900, + "line": 17, + "start": 864 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/groups/1/components", + "span": { + "column": 12, + "document": "manifest", + "end": 900, + "line": 17, + "start": 864 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + } + ], + "pointer": "/groups/1/condition", + "span": { + "column": 41, + "document": "manifest", + "end": 899, + "line": 17, + "start": 893 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 39, + "document": "manifest", + "end": 112, + "line": 4, + "start": 93 + } + ], + "pointer": "/groups/1/condition/agents", + "span": { + "column": 41, + "document": "manifest", + "end": 899, + "line": 17, + "start": 893 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 39, + "document": "manifest", + "end": 112, + "line": 4, + "start": 93 + }, + { + "column": 51, + "document": "manifest", + "end": 111, + "line": 4, + "start": 105 + } + ], + "pointer": "/groups/1/condition/agents/0", + "span": { + "column": 41, + "document": "manifest", + "end": 899, + "line": 17, + "start": 893 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 39, + "document": "manifest", + "end": 112, + "line": 4, + "start": 93 + }, + { + "column": 40, + "document": "manifest", + "end": 103, + "line": 4, + "start": 94 + } + ], + "pointer": "/groups/1/condition/agents/1", + "span": { + "column": 41, + "document": "manifest", + "end": 899, + "line": 17, + "start": 893 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 98, + "document": "manifest", + "end": 168, + "line": 4, + "start": 152 + } + ], + "pointer": "/groups/1/condition/platforms", + "span": { + "column": 41, + "document": "manifest", + "end": 899, + "line": 17, + "start": 893 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 98, + "document": "manifest", + "end": 168, + "line": 4, + "start": 152 + }, + { + "column": 99, + "document": "manifest", + "end": 159, + "line": 4, + "start": 153 + } + ], + "pointer": "/groups/1/condition/platforms/0", + "span": { + "column": 41, + "document": "manifest", + "end": 899, + "line": 17, + "start": 893 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 98, + "document": "manifest", + "end": 168, + "line": 4, + "start": 152 + }, + { + "column": 107, + "document": "manifest", + "end": 167, + "line": 4, + "start": 161 + } + ], + "pointer": "/groups/1/condition/platforms/1", + "span": { + "column": 41, + "document": "manifest", + "end": 899, + "line": 17, + "start": 893 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 68, + "document": "manifest", + "end": 139, + "line": 4, + "start": 122 + } + ], + "pointer": "/groups/1/condition/scopes", + "span": { + "column": 41, + "document": "manifest", + "end": 899, + "line": 17, + "start": 893 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 68, + "document": "manifest", + "end": 139, + "line": 4, + "start": 122 + }, + { + "column": 76, + "document": "manifest", + "end": 138, + "line": 4, + "start": 130 + } + ], + "pointer": "/groups/1/condition/scopes/0", + "span": { + "column": 41, + "document": "manifest", + "end": 899, + "line": 17, + "start": 893 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 68, + "document": "manifest", + "end": 139, + "line": 4, + "start": 122 + }, + { + "column": 69, + "document": "manifest", + "end": 128, + "line": 4, + "start": 123 + } + ], + "pointer": "/groups/1/condition/scopes/1", + "span": { + "column": 41, + "document": "manifest", + "end": 899, + "line": 17, + "start": 893 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups/1/name", + "span": { + "column": 25, + "document": "manifest", + "end": 880, + "line": 17, + "start": 877 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/groups/1/uses", + "span": { + "column": 12, + "document": "manifest", + "end": 900, + "line": 17, + "start": 864 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources", + "span": { + "column": 12, + "document": "manifest", + "end": 357, + "line": 8, + "start": 246 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/0", + "span": { + "column": 5, + "document": "manifest", + "end": 352, + "line": 10, + "start": 321 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/0/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 352, + "line": 10, + "start": 321 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/0/name", + "span": { + "column": 19, + "document": "manifest", + "end": 338, + "line": 10, + "start": 335 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/0/path", + "span": { + "column": 30, + "document": "manifest", + "end": 351, + "line": 10, + "start": 346 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/0/requirement", + "span": { + "column": 5, + "document": "manifest", + "end": 352, + "line": 10, + "start": 321 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/0/subpath", + "span": { + "column": 5, + "document": "manifest", + "end": 352, + "line": 10, + "start": 321 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1", + "span": { + "column": 5, + "document": "manifest", + "end": 315, + "line": 9, + "start": 252 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/1/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 315, + "line": 9, + "start": 252 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1/name", + "span": { + "column": 19, + "document": "manifest", + "end": 269, + "line": 9, + "start": 266 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1/requirement", + "span": { + "column": 50, + "document": "manifest", + "end": 314, + "line": 9, + "start": 297 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1/requirement/upToNextMinor", + "span": { + "column": 50, + "document": "manifest", + "end": 304, + "line": 9, + "start": 297 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/1/subpath", + "span": { + "column": 5, + "document": "manifest", + "end": 315, + "line": 9, + "start": 252 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1/url", + "span": { + "column": 29, + "document": "manifest", + "end": 295, + "line": 9, + "start": 276 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/uses", + "span": { + "column": 9, + "document": "manifest", + "end": 991, + "line": 18, + "start": 930 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/uses/0", + "span": { + "column": 10, + "document": "manifest", + "end": 985, + "line": 18, + "start": 931 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + } + ], + "pointer": "/uses/0/condition", + "span": { + "column": 57, + "document": "manifest", + "end": 984, + "line": 18, + "start": 978 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 39, + "document": "manifest", + "end": 112, + "line": 4, + "start": 93 + } + ], + "pointer": "/uses/0/condition/agents", + "span": { + "column": 57, + "document": "manifest", + "end": 984, + "line": 18, + "start": 978 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 39, + "document": "manifest", + "end": 112, + "line": 4, + "start": 93 + }, + { + "column": 51, + "document": "manifest", + "end": 111, + "line": 4, + "start": 105 + } + ], + "pointer": "/uses/0/condition/agents/0", + "span": { + "column": 57, + "document": "manifest", + "end": 984, + "line": 18, + "start": 978 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 39, + "document": "manifest", + "end": 112, + "line": 4, + "start": 93 + }, + { + "column": 40, + "document": "manifest", + "end": 103, + "line": 4, + "start": 94 + } + ], + "pointer": "/uses/0/condition/agents/1", + "span": { + "column": 57, + "document": "manifest", + "end": 984, + "line": 18, + "start": 978 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 98, + "document": "manifest", + "end": 168, + "line": 4, + "start": 152 + } + ], + "pointer": "/uses/0/condition/platforms", + "span": { + "column": 57, + "document": "manifest", + "end": 984, + "line": 18, + "start": 978 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 98, + "document": "manifest", + "end": 168, + "line": 4, + "start": 152 + }, + { + "column": 99, + "document": "manifest", + "end": 159, + "line": 4, + "start": 153 + } + ], + "pointer": "/uses/0/condition/platforms/0", + "span": { + "column": 57, + "document": "manifest", + "end": 984, + "line": 18, + "start": 978 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 98, + "document": "manifest", + "end": 168, + "line": 4, + "start": 152 + }, + { + "column": 107, + "document": "manifest", + "end": 167, + "line": 4, + "start": 161 + } + ], + "pointer": "/uses/0/condition/platforms/1", + "span": { + "column": 57, + "document": "manifest", + "end": 984, + "line": 18, + "start": 978 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 68, + "document": "manifest", + "end": 139, + "line": 4, + "start": 122 + } + ], + "pointer": "/uses/0/condition/scopes", + "span": { + "column": 57, + "document": "manifest", + "end": 984, + "line": 18, + "start": 978 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 68, + "document": "manifest", + "end": 139, + "line": 4, + "start": 122 + }, + { + "column": 76, + "document": "manifest", + "end": 138, + "line": 4, + "start": 130 + } + ], + "pointer": "/uses/0/condition/scopes/0", + "span": { + "column": 57, + "document": "manifest", + "end": 984, + "line": 18, + "start": 978 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 25, + "document": "manifest", + "end": 169, + "line": 4, + "start": 79 + }, + { + "column": 68, + "document": "manifest", + "end": 139, + "line": 4, + "start": 122 + }, + { + "column": 69, + "document": "manifest", + "end": 128, + "line": 4, + "start": 123 + } + ], + "pointer": "/uses/0/condition/scopes/1", + "span": { + "column": 57, + "document": "manifest", + "end": 984, + "line": 18, + "start": 978 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/uses/0/kind", + "span": { + "column": 10, + "document": "manifest", + "end": 985, + "line": 18, + "start": 931 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/uses/0/name", + "span": { + "column": 23, + "document": "manifest", + "end": 952, + "line": 18, + "start": 944 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/uses/0/source", + "span": { + "column": 41, + "document": "manifest", + "end": 965, + "line": 18, + "start": 962 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/uses/1", + "span": { + "column": 66, + "document": "manifest", + "end": 990, + "line": 18, + "start": 987 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/uses/1/condition", + "span": { + "column": 66, + "document": "manifest", + "end": 990, + "line": 18, + "start": 987 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/uses/1/kind", + "span": { + "column": 66, + "document": "manifest", + "end": 990, + "line": 18, + "start": 987 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/uses/1/name", + "span": { + "column": 66, + "document": "manifest", + "end": 990, + "line": 18, + "start": 987 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/uses/1/source", + "span": { + "column": 66, + "document": "manifest", + "end": 990, + "line": 18, + "start": 987 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/watch", + "span": { + "column": 10, + "document": "manifest", + "end": 1012, + "line": 19, + "start": 1002 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/watch/0", + "span": { + "column": 16, + "document": "manifest", + "end": 1011, + "line": 19, + "start": 1008 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/watch/1", + "span": { + "column": 11, + "document": "manifest", + "end": 1006, + "line": 19, + "start": 1003 + } + } + ], + "schemaVersion": 1, + "sourceDigest": "sha256:73195ad7498783349149ee18e3f9ce13fae38d8c682d449bdd9d2861bc6f1c74" +} diff --git a/Tests/AgentsManifestTests/Fixtures/DumpSymbolic.swift.txt b/Tests/AgentsManifestTests/Fixtures/DumpSymbolic.swift.txt new file mode 100644 index 0000000..84b18ae --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/DumpSymbolic.swift.txt @@ -0,0 +1,20 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let shared: Condition = .when(agents: [.openCode, .codex], scopes: [.user, .project], platforms: [.linux, .macOS]) +let agents = Agents( + defaultAgents: [], + exports: ["z", "a"], + sources: [ + .source(name: "z", url: "intranet/team.git", "1.2.0"..<"1.3.0"), + .source(name: "a", path: "./a"), + ], + components: [ + .instructions(sections: ["own", .section(name: "rule", source: "z", condition: shared)], chatGPT: [.prompt(name: "z", sections: []), .prompt(name: "a", sections: ["own"])], agents: []), + .skills(source: "z", select: ["z", "a"], exclude: ["z", "a"], overrides: [.skill(name: "z", agents: []), .skill(name: "a")]), + .plugin(name: "bundle", path: "bundle", source: "z", exclude: [.hook(name: "aaa"), .command(name: "zzz"), .hook(name: "bbb"), .skill(name: "ccc")]), + ], + groups: [.group(name: "z", condition: shared), .group(name: "a")], + uses: [.group(name: "review", source: "z", condition: shared), "a"], + watch: ["z", "a"] +) diff --git a/Tests/AgentsManifestTests/Fixtures/LiteralCoverage.dump.json b/Tests/AgentsManifestTests/Fixtures/LiteralCoverage.dump.json new file mode 100644 index 0000000..b0ccd53 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/LiteralCoverage.dump.json @@ -0,0 +1,6707 @@ +{ + "declaration": { + "components": [ + { + "agents": null, + "condition": null, + "kind": "mcpServer", + "name": "tools", + "native": {}, + "transport": { + "arguments": [], + "environment": { + "LEVEL": { + "kind": "literal", + "value": "info" + }, + "TOKEN": { + "kind": "secret", + "value": "token" + } + }, + "executable": "server", + "kind": "stdio", + "workingDirectory": null + } + }, + { + "agents": null, + "condition": null, + "kind": "mcpServer", + "name": "sse", + "native": {}, + "transport": { + "headers": {}, + "kind": "sse", + "url": "https://example.org/events" + } + }, + { + "agents": null, + "condition": null, + "description": "Review", + "kind": "command", + "name": "review", + "native": {}, + "parameters": [], + "prompt": { + "kind": "literal", + "value": "Review invariants." + } + }, + { + "agents": null, + "chatGPT": [], + "condition": null, + "kind": "instructions", + "native": {}, + "sections": [ + { + "condition": null, + "name": "guide", + "source": null + } + ] + }, + { + "agents": null, + "condition": null, + "exclude": [], + "kind": "skills", + "mode": null, + "native": {}, + "overrides": [ + { + "agents": [ + "codex" + ], + "mode": "copy", + "name": "review" + } + ], + "select": [ + "review", + "testing" + ], + "source": "team" + }, + { + "agents": null, + "condition": null, + "initializationOptions": { + "config": { + "kind": "object", + "value": { + "array": { + "kind": "array", + "value": [ + { + "kind": "integer", + "value": 1 + }, + { + "kind": "string", + "value": "two" + }, + { + "kind": "boolean", + "value": false + }, + { + "kind": "null" + } + ] + }, + "boolean": { + "kind": "boolean", + "value": true + }, + "decimal": { + "kind": "decimal", + "value": "1.25" + }, + "integer": { + "kind": "integer", + "value": -1 + }, + "null": { + "kind": "null" + }, + "object": { + "kind": "object", + "value": { + "enabled": { + "kind": "boolean", + "value": true + } + } + }, + "string": { + "kind": "string", + "value": "value" + } + } + } + }, + "kind": "lspServer", + "languages": { + ".swift": "swift" + }, + "name": "swift", + "native": {}, + "run": { + "arguments": [], + "environment": { + "LEVEL": { + "kind": "literal", + "value": "info" + }, + "TOKEN": { + "kind": "secret", + "value": "token" + } + }, + "executable": "server", + "kind": "executable", + "workingDirectory": { + "path": "tools", + "source": "vendor" + } + } + }, + { + "agents": null, + "condition": null, + "kind": "permissions", + "name": "policy", + "native": {}, + "rules": [ + { + "kind": "allow", + "operation": { + "kind": "read" + }, + "pattern": "Sources/**" + }, + { + "kind": "ask", + "operation": { + "kind": "write" + }, + "pattern": "**" + }, + { + "kind": "deny", + "operation": { + "kind": "execute" + }, + "pattern": "rm *" + }, + { + "kind": "deny", + "operation": { + "kind": "tool", + "value": "fetch" + }, + "pattern": "*" + } + ] + }, + { + "agents": null, + "condition": null, + "exclude": [ + { + "kind": "command", + "name": "a" + }, + { + "kind": "hook", + "name": "a" + }, + { + "kind": "ignore", + "name": "a" + }, + { + "kind": "instruction", + "name": "a" + }, + { + "kind": "lspServer", + "name": "a" + }, + { + "kind": "mcpServer", + "name": "a" + }, + { + "kind": "permissions", + "name": "a" + }, + { + "kind": "plugin", + "name": "a" + }, + { + "kind": "skill", + "name": "a" + }, + { + "kind": "subagent", + "name": "a" + } + ], + "kind": "plugin", + "mode": "components", + "name": "tools", + "native": {}, + "path": "plugins/tools", + "select": [ + "skills", + "instructions", + "mcpServer", + "hook", + "subagent", + "command", + "lspServer", + "permissions", + "ignore", + "plugin" + ], + "source": "vendor" + }, + { + "agents": [ + "codex" + ], + "condition": null, + "event": { + "kind": "native", + "value": "Event" + }, + "kind": "hook", + "matcher": null, + "name": "native", + "native": {}, + "run": { + "arguments": [], + "environment": { + "LEVEL": { + "kind": "literal", + "value": "info" + }, + "TOKEN": { + "kind": "secret", + "value": "token" + } + }, + "executable": "server", + "kind": "executable", + "workingDirectory": { + "path": "tools", + "source": "vendor" + } + }, + "timeoutSeconds": null + }, + { + "agents": [], + "condition": { + "agents": null, + "platforms": [ + "linux", + "macos" + ], + "scopes": [ + "project", + "user" + ] + }, + "kind": "ignore", + "name": "context", + "native": {}, + "patterns": [], + "purpose": "context" + }, + { + "agents": null, + "condition": null, + "description": "No tools", + "kind": "subagent", + "model": null, + "name": "empty-tools", + "native": {}, + "prompt": { + "kind": "literal", + "value": "Read" + }, + "tools": [] + } + ], + "defaultAgents": null, + "exports": [ + "review" + ], + "groups": [ + { + "components": [], + "condition": null, + "name": "review", + "uses": [] + } + ], + "sources": [ + { + "kind": "local", + "name": "team", + "path": "team", + "requirement": null, + "subpath": null + }, + { + "kind": "local", + "name": "vendor", + "path": "vendor", + "requirement": null, + "subpath": null + } + ], + "uses": [ + { + "condition": null, + "kind": "local", + "name": "review", + "source": null + }, + { + "condition": { + "agents": [ + "codex" + ], + "platforms": null, + "scopes": null + }, + "kind": "local", + "name": "review", + "source": null + } + ], + "watch": [] + }, + "diagnostics": [], + "kind": "manifest", + "languageVersion": "1.0", + "locations": [ + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "", + "span": { + "column": 14, + "document": "manifest", + "end": 2871, + "line": 25, + "start": 1285 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components", + "span": { + "column": 15, + "document": "manifest", + "end": 2756, + "line": 28, + "start": 1421 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0", + "span": { + "column": 5, + "document": "manifest", + "end": 1507, + "line": 29, + "start": 1427 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 1507, + "line": 29, + "start": 1427 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 1507, + "line": 29, + "start": 1427 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 1507, + "line": 29, + "start": 1427 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/name", + "span": { + "column": 22, + "document": "manifest", + "end": 1451, + "line": 29, + "start": 1444 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/native", + "span": { + "column": 5, + "document": "manifest", + "end": 1507, + "line": 29, + "start": 1427 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/transport", + "span": { + "column": 42, + "document": "manifest", + "end": 1506, + "line": 29, + "start": 1464 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/transport/arguments", + "span": { + "column": 42, + "document": "manifest", + "end": 1506, + "line": 29, + "start": 1464 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + } + ], + "pointer": "/components/0/transport/environment", + "span": { + "column": 72, + "document": "manifest", + "end": 1505, + "line": 29, + "start": 1494 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 53, + "document": "manifest", + "end": 493, + "line": 12, + "start": 487 + } + ], + "pointer": "/components/0/transport/environment/LEVEL", + "span": { + "column": 72, + "document": "manifest", + "end": 1505, + "line": 29, + "start": 1494 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 53, + "document": "manifest", + "end": 493, + "line": 12, + "start": 487 + } + ], + "pointer": "/components/0/transport/environment/LEVEL/kind", + "span": { + "column": 72, + "document": "manifest", + "end": 1505, + "line": 29, + "start": 1494 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 53, + "document": "manifest", + "end": 493, + "line": 12, + "start": 487 + } + ], + "pointer": "/components/0/transport/environment/LEVEL/value", + "span": { + "column": 72, + "document": "manifest", + "end": 1505, + "line": 29, + "start": 1494 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 70, + "document": "manifest", + "end": 520, + "line": 12, + "start": 504 + } + ], + "pointer": "/components/0/transport/environment/TOKEN", + "span": { + "column": 72, + "document": "manifest", + "end": 1505, + "line": 29, + "start": 1494 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 70, + "document": "manifest", + "end": 520, + "line": 12, + "start": 504 + } + ], + "pointer": "/components/0/transport/environment/TOKEN/kind", + "span": { + "column": 72, + "document": "manifest", + "end": 1505, + "line": 29, + "start": 1494 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 70, + "document": "manifest", + "end": 520, + "line": 12, + "start": 504 + }, + { + "column": 78, + "document": "manifest", + "end": 519, + "line": 12, + "start": 512 + } + ], + "pointer": "/components/0/transport/environment/TOKEN/value", + "span": { + "column": 72, + "document": "manifest", + "end": 1505, + "line": 29, + "start": 1494 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/transport/executable", + "span": { + "column": 49, + "document": "manifest", + "end": 1479, + "line": 29, + "start": 1471 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/transport/kind", + "span": { + "column": 42, + "document": "manifest", + "end": 1506, + "line": 29, + "start": 1464 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/transport/workingDirectory", + "span": { + "column": 42, + "document": "manifest", + "end": 1506, + "line": 29, + "start": 1464 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1", + "span": { + "column": 5, + "document": "manifest", + "end": 1588, + "line": 30, + "start": 1513 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 1588, + "line": 30, + "start": 1513 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 1588, + "line": 30, + "start": 1513 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 1588, + "line": 30, + "start": 1513 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/name", + "span": { + "column": 22, + "document": "manifest", + "end": 1535, + "line": 30, + "start": 1530 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/native", + "span": { + "column": 5, + "document": "manifest", + "end": 1588, + "line": 30, + "start": 1513 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/transport", + "span": { + "column": 40, + "document": "manifest", + "end": 1587, + "line": 30, + "start": 1548 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/transport/headers", + "span": { + "column": 40, + "document": "manifest", + "end": 1587, + "line": 30, + "start": 1548 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/transport/kind", + "span": { + "column": 40, + "document": "manifest", + "end": 1587, + "line": 30, + "start": 1548 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/transport/url", + "span": { + "column": 50, + "document": "manifest", + "end": 1586, + "line": 30, + "start": 1558 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 754, + "line": 16, + "start": 672 + } + ], + "pointer": "/components/10", + "span": { + "column": 5, + "document": "manifest", + "end": 2752, + "line": 39, + "start": 2742 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 754, + "line": 16, + "start": 672 + } + ], + "pointer": "/components/10/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 2752, + "line": 39, + "start": 2742 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 754, + "line": 16, + "start": 672 + } + ], + "pointer": "/components/10/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 2752, + "line": 39, + "start": 2742 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 754, + "line": 16, + "start": 672 + }, + { + "column": 73, + "document": "manifest", + "end": 726, + "line": 16, + "start": 716 + } + ], + "pointer": "/components/10/description", + "span": { + "column": 5, + "document": "manifest", + "end": 2752, + "line": 39, + "start": 2742 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 754, + "line": 16, + "start": 672 + } + ], + "pointer": "/components/10/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 2752, + "line": 39, + "start": 2742 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 754, + "line": 16, + "start": 672 + } + ], + "pointer": "/components/10/model", + "span": { + "column": 5, + "document": "manifest", + "end": 2752, + "line": 39, + "start": 2742 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 754, + "line": 16, + "start": 672 + }, + { + "column": 45, + "document": "manifest", + "end": 701, + "line": 16, + "start": 688 + } + ], + "pointer": "/components/10/name", + "span": { + "column": 5, + "document": "manifest", + "end": 2752, + "line": 39, + "start": 2742 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 754, + "line": 16, + "start": 672 + } + ], + "pointer": "/components/10/native", + "span": { + "column": 5, + "document": "manifest", + "end": 2752, + "line": 39, + "start": 2742 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 754, + "line": 16, + "start": 672 + }, + { + "column": 93, + "document": "manifest", + "end": 742, + "line": 16, + "start": 736 + } + ], + "pointer": "/components/10/prompt", + "span": { + "column": 5, + "document": "manifest", + "end": 2752, + "line": 39, + "start": 2742 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 754, + "line": 16, + "start": 672 + }, + { + "column": 93, + "document": "manifest", + "end": 742, + "line": 16, + "start": 736 + } + ], + "pointer": "/components/10/prompt/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 2752, + "line": 39, + "start": 2742 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 754, + "line": 16, + "start": 672 + }, + { + "column": 93, + "document": "manifest", + "end": 742, + "line": 16, + "start": 736 + } + ], + "pointer": "/components/10/prompt/value", + "span": { + "column": 5, + "document": "manifest", + "end": 2752, + "line": 39, + "start": 2742 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 754, + "line": 16, + "start": 672 + }, + { + "column": 108, + "document": "manifest", + "end": 753, + "line": 16, + "start": 751 + } + ], + "pointer": "/components/10/tools", + "span": { + "column": 5, + "document": "manifest", + "end": 2752, + "line": 39, + "start": 2742 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2", + "span": { + "column": 5, + "document": "manifest", + "end": 1655, + "line": 31, + "start": 1594 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 1655, + "line": 31, + "start": 1594 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 1655, + "line": 31, + "start": 1594 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/description", + "span": { + "column": 43, + "document": "manifest", + "end": 1640, + "line": 31, + "start": 1632 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 1655, + "line": 31, + "start": 1594 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/name", + "span": { + "column": 20, + "document": "manifest", + "end": 1617, + "line": 31, + "start": 1609 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/native", + "span": { + "column": 5, + "document": "manifest", + "end": 1655, + "line": 31, + "start": 1594 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/parameters", + "span": { + "column": 5, + "document": "manifest", + "end": 1655, + "line": 31, + "start": 1594 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 101, + "line": 4, + "start": 81 + } + ], + "pointer": "/components/2/prompt", + "span": { + "column": 61, + "document": "manifest", + "end": 1654, + "line": 31, + "start": 1650 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 101, + "line": 4, + "start": 81 + } + ], + "pointer": "/components/2/prompt/kind", + "span": { + "column": 61, + "document": "manifest", + "end": 1654, + "line": 31, + "start": 1650 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 27, + "document": "manifest", + "end": 101, + "line": 4, + "start": 81 + } + ], + "pointer": "/components/2/prompt/value", + "span": { + "column": 61, + "document": "manifest", + "end": 1654, + "line": 31, + "start": 1650 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3", + "span": { + "column": 5, + "document": "manifest", + "end": 1695, + "line": 32, + "start": 1661 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 1695, + "line": 32, + "start": 1661 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/chatGPT", + "span": { + "column": 5, + "document": "manifest", + "end": 1695, + "line": 32, + "start": 1661 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 1695, + "line": 32, + "start": 1661 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 1695, + "line": 32, + "start": 1661 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/native", + "span": { + "column": 5, + "document": "manifest", + "end": 1695, + "line": 32, + "start": 1661 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3/sections", + "span": { + "column": 29, + "document": "manifest", + "end": 1694, + "line": 32, + "start": 1685 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 33, + "document": "manifest", + "end": 141, + "line": 5, + "start": 134 + } + ], + "pointer": "/components/3/sections/0", + "span": { + "column": 30, + "document": "manifest", + "end": 1693, + "line": 32, + "start": 1686 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 33, + "document": "manifest", + "end": 141, + "line": 5, + "start": 134 + } + ], + "pointer": "/components/3/sections/0/condition", + "span": { + "column": 30, + "document": "manifest", + "end": 1693, + "line": 32, + "start": 1686 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 33, + "document": "manifest", + "end": 141, + "line": 5, + "start": 134 + } + ], + "pointer": "/components/3/sections/0/name", + "span": { + "column": 30, + "document": "manifest", + "end": 1693, + "line": 32, + "start": 1686 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 33, + "document": "manifest", + "end": 141, + "line": 5, + "start": 134 + } + ], + "pointer": "/components/3/sections/0/source", + "span": { + "column": 30, + "document": "manifest", + "end": 1693, + "line": 32, + "start": 1686 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4", + "span": { + "column": 5, + "document": "manifest", + "end": 1811, + "line": 33, + "start": 1701 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 1811, + "line": 33, + "start": 1701 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 1811, + "line": 33, + "start": 1701 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/exclude", + "span": { + "column": 5, + "document": "manifest", + "end": 1811, + "line": 33, + "start": 1701 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 1811, + "line": 33, + "start": 1701 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/mode", + "span": { + "column": 5, + "document": "manifest", + "end": 1811, + "line": 33, + "start": 1701 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/native", + "span": { + "column": 5, + "document": "manifest", + "end": 1811, + "line": 33, + "start": 1701 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/overrides", + "span": { + "column": 59, + "document": "manifest", + "end": 1810, + "line": 33, + "start": 1755 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/overrides/0", + "span": { + "column": 60, + "document": "manifest", + "end": 1809, + "line": 33, + "start": 1756 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/overrides/0/agents", + "span": { + "column": 104, + "document": "manifest", + "end": 1808, + "line": 33, + "start": 1800 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/4/overrides/0/agents/0", + "span": { + "column": 105, + "document": "manifest", + "end": 1807, + "line": 33, + "start": 1801 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/4/overrides/0/mode", + "span": { + "column": 89, + "document": "manifest", + "end": 1790, + "line": 33, + "start": 1785 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/overrides/0/name", + "span": { + "column": 73, + "document": "manifest", + "end": 1777, + "line": 33, + "start": 1769 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 33, + "document": "manifest", + "end": 232, + "line": 7, + "start": 211 + } + ], + "pointer": "/components/4/select", + "span": { + "column": 37, + "document": "manifest", + "end": 1742, + "line": 33, + "start": 1733 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 33, + "document": "manifest", + "end": 232, + "line": 7, + "start": 211 + }, + { + "column": 34, + "document": "manifest", + "end": 220, + "line": 7, + "start": 212 + } + ], + "pointer": "/components/4/select/0", + "span": { + "column": 37, + "document": "manifest", + "end": 1742, + "line": 33, + "start": 1733 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 33, + "document": "manifest", + "end": 232, + "line": 7, + "start": 211 + }, + { + "column": 44, + "document": "manifest", + "end": 231, + "line": 7, + "start": 222 + } + ], + "pointer": "/components/4/select/1", + "span": { + "column": 37, + "document": "manifest", + "end": 1742, + "line": 33, + "start": 1733 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/source", + "span": { + "column": 21, + "document": "manifest", + "end": 1723, + "line": 33, + "start": 1717 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5", + "span": { + "column": 5, + "document": "manifest", + "end": 1941, + "line": 34, + "start": 1817 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/5/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 1941, + "line": 34, + "start": 1817 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/5/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 1941, + "line": 34, + "start": 1817 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/initializationOptions", + "span": { + "column": 103, + "document": "manifest", + "end": 1940, + "line": 34, + "start": 1915 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + } + ], + "pointer": "/components/5/initializationOptions/config", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + } + ], + "pointer": "/components/5/initializationOptions/config/kind", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + } + ], + "pointer": "/components/5/initializationOptions/config/value", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 12, + "document": "manifest", + "end": 374, + "line": 10, + "start": 352 + } + ], + "pointer": "/components/5/initializationOptions/config/value/array", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 12, + "document": "manifest", + "end": 374, + "line": 10, + "start": 352 + } + ], + "pointer": "/components/5/initializationOptions/config/value/array/kind", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 12, + "document": "manifest", + "end": 374, + "line": 10, + "start": 352 + } + ], + "pointer": "/components/5/initializationOptions/config/value/array/value", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 12, + "document": "manifest", + "end": 374, + "line": 10, + "start": 352 + }, + { + "column": 13, + "document": "manifest", + "end": 354, + "line": 10, + "start": 353 + } + ], + "pointer": "/components/5/initializationOptions/config/value/array/value/0", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 12, + "document": "manifest", + "end": 374, + "line": 10, + "start": 352 + }, + { + "column": 13, + "document": "manifest", + "end": 354, + "line": 10, + "start": 353 + } + ], + "pointer": "/components/5/initializationOptions/config/value/array/value/0/kind", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 12, + "document": "manifest", + "end": 374, + "line": 10, + "start": 352 + }, + { + "column": 13, + "document": "manifest", + "end": 354, + "line": 10, + "start": 353 + } + ], + "pointer": "/components/5/initializationOptions/config/value/array/value/0/value", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 12, + "document": "manifest", + "end": 374, + "line": 10, + "start": 352 + }, + { + "column": 16, + "document": "manifest", + "end": 361, + "line": 10, + "start": 356 + } + ], + "pointer": "/components/5/initializationOptions/config/value/array/value/1", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 12, + "document": "manifest", + "end": 374, + "line": 10, + "start": 352 + }, + { + "column": 16, + "document": "manifest", + "end": 361, + "line": 10, + "start": 356 + } + ], + "pointer": "/components/5/initializationOptions/config/value/array/value/1/kind", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 12, + "document": "manifest", + "end": 374, + "line": 10, + "start": 352 + }, + { + "column": 16, + "document": "manifest", + "end": 361, + "line": 10, + "start": 356 + } + ], + "pointer": "/components/5/initializationOptions/config/value/array/value/1/value", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 12, + "document": "manifest", + "end": 374, + "line": 10, + "start": 352 + }, + { + "column": 23, + "document": "manifest", + "end": 368, + "line": 10, + "start": 363 + } + ], + "pointer": "/components/5/initializationOptions/config/value/array/value/2", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 12, + "document": "manifest", + "end": 374, + "line": 10, + "start": 352 + }, + { + "column": 23, + "document": "manifest", + "end": 368, + "line": 10, + "start": 363 + } + ], + "pointer": "/components/5/initializationOptions/config/value/array/value/2/kind", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 12, + "document": "manifest", + "end": 374, + "line": 10, + "start": 352 + }, + { + "column": 23, + "document": "manifest", + "end": 368, + "line": 10, + "start": 363 + } + ], + "pointer": "/components/5/initializationOptions/config/value/array/value/2/value", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 12, + "document": "manifest", + "end": 374, + "line": 10, + "start": 352 + }, + { + "column": 30, + "document": "manifest", + "end": 373, + "line": 10, + "start": 370 + } + ], + "pointer": "/components/5/initializationOptions/config/value/array/value/3", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 12, + "document": "manifest", + "end": 374, + "line": 10, + "start": 352 + }, + { + "column": 30, + "document": "manifest", + "end": 373, + "line": 10, + "start": 370 + } + ], + "pointer": "/components/5/initializationOptions/config/value/array/value/3/kind", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 48, + "document": "manifest", + "end": 326, + "line": 9, + "start": 322 + } + ], + "pointer": "/components/5/initializationOptions/config/value/boolean", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 48, + "document": "manifest", + "end": 326, + "line": 9, + "start": 322 + } + ], + "pointer": "/components/5/initializationOptions/config/value/boolean/kind", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 48, + "document": "manifest", + "end": 326, + "line": 9, + "start": 322 + } + ], + "pointer": "/components/5/initializationOptions/config/value/boolean/value", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 76, + "document": "manifest", + "end": 432, + "line": 10, + "start": 416 + } + ], + "pointer": "/components/5/initializationOptions/config/value/decimal", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 76, + "document": "manifest", + "end": 432, + "line": 10, + "start": 416 + } + ], + "pointer": "/components/5/initializationOptions/config/value/decimal/kind", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 76, + "document": "manifest", + "end": 432, + "line": 10, + "start": 416 + }, + { + "column": 85, + "document": "manifest", + "end": 431, + "line": 10, + "start": 425 + } + ], + "pointer": "/components/5/initializationOptions/config/value/decimal/value", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 33, + "document": "manifest", + "end": 309, + "line": 9, + "start": 307 + } + ], + "pointer": "/components/5/initializationOptions/config/value/integer", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 33, + "document": "manifest", + "end": 309, + "line": 9, + "start": 307 + } + ], + "pointer": "/components/5/initializationOptions/config/value/integer/kind", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 33, + "document": "manifest", + "end": 309, + "line": 9, + "start": 307 + } + ], + "pointer": "/components/5/initializationOptions/config/value/integer/value", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 62, + "document": "manifest", + "end": 339, + "line": 9, + "start": 336 + } + ], + "pointer": "/components/5/initializationOptions/config/value/null", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 62, + "document": "manifest", + "end": 339, + "line": 9, + "start": 336 + } + ], + "pointer": "/components/5/initializationOptions/config/value/null/kind", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 46, + "document": "manifest", + "end": 403, + "line": 10, + "start": 386 + } + ], + "pointer": "/components/5/initializationOptions/config/value/object", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 46, + "document": "manifest", + "end": 403, + "line": 10, + "start": 386 + } + ], + "pointer": "/components/5/initializationOptions/config/value/object/kind", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 46, + "document": "manifest", + "end": 403, + "line": 10, + "start": 386 + } + ], + "pointer": "/components/5/initializationOptions/config/value/object/value", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 46, + "document": "manifest", + "end": 403, + "line": 10, + "start": 386 + }, + { + "column": 58, + "document": "manifest", + "end": 402, + "line": 10, + "start": 398 + } + ], + "pointer": "/components/5/initializationOptions/config/value/object/value/enabled", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 46, + "document": "manifest", + "end": 403, + "line": 10, + "start": 386 + }, + { + "column": 58, + "document": "manifest", + "end": 402, + "line": 10, + "start": 398 + } + ], + "pointer": "/components/5/initializationOptions/config/value/object/value/enabled/kind", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 46, + "document": "manifest", + "end": 403, + "line": 10, + "start": 386 + }, + { + "column": 58, + "document": "manifest", + "end": 402, + "line": 10, + "start": 398 + } + ], + "pointer": "/components/5/initializationOptions/config/value/object/value/enabled/value", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 13, + "document": "manifest", + "end": 294, + "line": 9, + "start": 287 + } + ], + "pointer": "/components/5/initializationOptions/config/value/string", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 13, + "document": "manifest", + "end": 294, + "line": 9, + "start": 287 + } + ], + "pointer": "/components/5/initializationOptions/config/value/string/kind", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 41, + "document": "manifest", + "end": 434, + "line": 8, + "start": 273 + }, + { + "column": 13, + "document": "manifest", + "end": 294, + "line": 9, + "start": 287 + } + ], + "pointer": "/components/5/initializationOptions/config/value/string/value", + "span": { + "column": 114, + "document": "manifest", + "end": 1939, + "line": 34, + "start": 1926 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/5/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 1941, + "line": 34, + "start": 1817 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/languages", + "span": { + "column": 59, + "document": "manifest", + "end": 1890, + "line": 34, + "start": 1871 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/languages/.swift", + "span": { + "column": 70, + "document": "manifest", + "end": 1889, + "line": 34, + "start": 1882 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/5/name", + "span": { + "column": 22, + "document": "manifest", + "end": 1841, + "line": 34, + "start": 1834 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/5/native", + "span": { + "column": 5, + "document": "manifest", + "end": 1941, + "line": 34, + "start": 1817 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + } + ], + "pointer": "/components/5/run", + "span": { + "column": 36, + "document": "manifest", + "end": 1858, + "line": 34, + "start": 1848 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + } + ], + "pointer": "/components/5/run/arguments", + "span": { + "column": 36, + "document": "manifest", + "end": 1858, + "line": 34, + "start": 1848 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 75, + "document": "manifest", + "end": 840, + "line": 17, + "start": 829 + }, + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + } + ], + "pointer": "/components/5/run/environment", + "span": { + "column": 36, + "document": "manifest", + "end": 1858, + "line": 34, + "start": 1848 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 75, + "document": "manifest", + "end": 840, + "line": 17, + "start": 829 + }, + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 53, + "document": "manifest", + "end": 493, + "line": 12, + "start": 487 + } + ], + "pointer": "/components/5/run/environment/LEVEL", + "span": { + "column": 36, + "document": "manifest", + "end": 1858, + "line": 34, + "start": 1848 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 75, + "document": "manifest", + "end": 840, + "line": 17, + "start": 829 + }, + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 53, + "document": "manifest", + "end": 493, + "line": 12, + "start": 487 + } + ], + "pointer": "/components/5/run/environment/LEVEL/kind", + "span": { + "column": 36, + "document": "manifest", + "end": 1858, + "line": 34, + "start": 1848 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 75, + "document": "manifest", + "end": 840, + "line": 17, + "start": 829 + }, + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 53, + "document": "manifest", + "end": 493, + "line": 12, + "start": 487 + } + ], + "pointer": "/components/5/run/environment/LEVEL/value", + "span": { + "column": 36, + "document": "manifest", + "end": 1858, + "line": 34, + "start": 1848 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 75, + "document": "manifest", + "end": 840, + "line": 17, + "start": 829 + }, + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 70, + "document": "manifest", + "end": 520, + "line": 12, + "start": 504 + } + ], + "pointer": "/components/5/run/environment/TOKEN", + "span": { + "column": 36, + "document": "manifest", + "end": 1858, + "line": 34, + "start": 1848 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 75, + "document": "manifest", + "end": 840, + "line": 17, + "start": 829 + }, + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 70, + "document": "manifest", + "end": 520, + "line": 12, + "start": 504 + } + ], + "pointer": "/components/5/run/environment/TOKEN/kind", + "span": { + "column": 36, + "document": "manifest", + "end": 1858, + "line": 34, + "start": 1848 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 75, + "document": "manifest", + "end": 840, + "line": 17, + "start": 829 + }, + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 70, + "document": "manifest", + "end": 520, + "line": 12, + "start": 504 + }, + { + "column": 78, + "document": "manifest", + "end": 519, + "line": 12, + "start": 512 + } + ], + "pointer": "/components/5/run/environment/TOKEN/value", + "span": { + "column": 36, + "document": "manifest", + "end": 1858, + "line": 34, + "start": 1848 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 52, + "document": "manifest", + "end": 814, + "line": 17, + "start": 806 + } + ], + "pointer": "/components/5/run/executable", + "span": { + "column": 36, + "document": "manifest", + "end": 1858, + "line": 34, + "start": 1848 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + } + ], + "pointer": "/components/5/run/kind", + "span": { + "column": 36, + "document": "manifest", + "end": 1858, + "line": 34, + "start": 1848 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 106, + "document": "manifest", + "end": 892, + "line": 17, + "start": 860 + } + ], + "pointer": "/components/5/run/workingDirectory", + "span": { + "column": 36, + "document": "manifest", + "end": 1858, + "line": 34, + "start": 1848 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 106, + "document": "manifest", + "end": 892, + "line": 17, + "start": 860 + }, + { + "column": 112, + "document": "manifest", + "end": 873, + "line": 17, + "start": 866 + } + ], + "pointer": "/components/5/run/workingDirectory/path", + "span": { + "column": 36, + "document": "manifest", + "end": 1858, + "line": 34, + "start": 1848 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 106, + "document": "manifest", + "end": 892, + "line": 17, + "start": 860 + }, + { + "column": 129, + "document": "manifest", + "end": 891, + "line": 17, + "start": 883 + } + ], + "pointer": "/components/5/run/workingDirectory/source", + "span": { + "column": 36, + "document": "manifest", + "end": 1858, + "line": 34, + "start": 1848 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6", + "span": { + "column": 5, + "document": "manifest", + "end": 2086, + "line": 35, + "start": 1947 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 2086, + "line": 35, + "start": 1947 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 2086, + "line": 35, + "start": 1947 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 2086, + "line": 35, + "start": 1947 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/name", + "span": { + "column": 24, + "document": "manifest", + "end": 1974, + "line": 35, + "start": 1966 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/native", + "span": { + "column": 5, + "document": "manifest", + "end": 2086, + "line": 35, + "start": 1947 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/rules", + "span": { + "column": 41, + "document": "manifest", + "end": 2085, + "line": 35, + "start": 1983 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/rules/0", + "span": { + "column": 42, + "document": "manifest", + "end": 2011, + "line": 35, + "start": 1984 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/rules/0/kind", + "span": { + "column": 42, + "document": "manifest", + "end": 2011, + "line": 35, + "start": 1984 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/6/rules/0/operation", + "span": { + "column": 49, + "document": "manifest", + "end": 1996, + "line": 35, + "start": 1991 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/rules/0/operation/kind", + "span": { + "column": 49, + "document": "manifest", + "end": 1996, + "line": 35, + "start": 1991 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/rules/0/pattern", + "span": { + "column": 56, + "document": "manifest", + "end": 2010, + "line": 35, + "start": 1998 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/rules/1", + "span": { + "column": 71, + "document": "manifest", + "end": 2031, + "line": 35, + "start": 2013 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/rules/1/kind", + "span": { + "column": 71, + "document": "manifest", + "end": 2031, + "line": 35, + "start": 2013 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/6/rules/1/operation", + "span": { + "column": 76, + "document": "manifest", + "end": 2024, + "line": 35, + "start": 2018 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/rules/1/operation/kind", + "span": { + "column": 76, + "document": "manifest", + "end": 2024, + "line": 35, + "start": 2018 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/rules/1/pattern", + "span": { + "column": 84, + "document": "manifest", + "end": 2030, + "line": 35, + "start": 2026 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/rules/2", + "span": { + "column": 91, + "document": "manifest", + "end": 2056, + "line": 35, + "start": 2033 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/rules/2/kind", + "span": { + "column": 91, + "document": "manifest", + "end": 2056, + "line": 35, + "start": 2033 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/6/rules/2/operation", + "span": { + "column": 97, + "document": "manifest", + "end": 2047, + "line": 35, + "start": 2039 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/rules/2/operation/kind", + "span": { + "column": 97, + "document": "manifest", + "end": 2047, + "line": 35, + "start": 2039 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/rules/2/pattern", + "span": { + "column": 107, + "document": "manifest", + "end": 2055, + "line": 35, + "start": 2049 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/rules/3", + "span": { + "column": 116, + "document": "manifest", + "end": 2084, + "line": 35, + "start": 2058 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/rules/3/kind", + "span": { + "column": 116, + "document": "manifest", + "end": 2084, + "line": 35, + "start": 2058 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/rules/3/operation", + "span": { + "column": 122, + "document": "manifest", + "end": 2078, + "line": 35, + "start": 2064 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/6/rules/3/operation/kind", + "span": { + "column": 122, + "document": "manifest", + "end": 2078, + "line": 35, + "start": 2064 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/rules/3/operation/value", + "span": { + "column": 128, + "document": "manifest", + "end": 2077, + "line": 35, + "start": 2070 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/6/rules/3/pattern", + "span": { + "column": 138, + "document": "manifest", + "end": 2083, + "line": 35, + "start": 2080 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7", + "span": { + "column": 5, + "document": "manifest", + "end": 2500, + "line": 36, + "start": 2092 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 2500, + "line": 36, + "start": 2092 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 2500, + "line": 36, + "start": 2092 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude", + "span": { + "column": 196, + "document": "manifest", + "end": 2499, + "line": 36, + "start": 2283 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/0", + "span": { + "column": 304, + "document": "manifest", + "end": 2410, + "line": 36, + "start": 2391 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/exclude/0/kind", + "span": { + "column": 304, + "document": "manifest", + "end": 2410, + "line": 36, + "start": 2391 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/0/name", + "span": { + "column": 319, + "document": "manifest", + "end": 2409, + "line": 36, + "start": 2406 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/1", + "span": { + "column": 264, + "document": "manifest", + "end": 2367, + "line": 36, + "start": 2351 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/exclude/1/kind", + "span": { + "column": 264, + "document": "manifest", + "end": 2367, + "line": 36, + "start": 2351 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/1/name", + "span": { + "column": 276, + "document": "manifest", + "end": 2366, + "line": 36, + "start": 2363 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/2", + "span": { + "column": 373, + "document": "manifest", + "end": 2478, + "line": 36, + "start": 2460 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/exclude/2/kind", + "span": { + "column": 373, + "document": "manifest", + "end": 2478, + "line": 36, + "start": 2460 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/2/name", + "span": { + "column": 387, + "document": "manifest", + "end": 2477, + "line": 36, + "start": 2474 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/3", + "span": { + "column": 216, + "document": "manifest", + "end": 2326, + "line": 36, + "start": 2303 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/exclude/3/kind", + "span": { + "column": 216, + "document": "manifest", + "end": 2326, + "line": 36, + "start": 2303 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/3/name", + "span": { + "column": 235, + "document": "manifest", + "end": 2325, + "line": 36, + "start": 2322 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/4", + "span": { + "column": 325, + "document": "manifest", + "end": 2433, + "line": 36, + "start": 2412 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/exclude/4/kind", + "span": { + "column": 325, + "document": "manifest", + "end": 2433, + "line": 36, + "start": 2412 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/4/name", + "span": { + "column": 342, + "document": "manifest", + "end": 2432, + "line": 36, + "start": 2429 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/5", + "span": { + "column": 241, + "document": "manifest", + "end": 2349, + "line": 36, + "start": 2328 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/exclude/5/kind", + "span": { + "column": 241, + "document": "manifest", + "end": 2349, + "line": 36, + "start": 2328 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/5/name", + "span": { + "column": 258, + "document": "manifest", + "end": 2348, + "line": 36, + "start": 2345 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/6", + "span": { + "column": 348, + "document": "manifest", + "end": 2458, + "line": 36, + "start": 2435 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/exclude/6/kind", + "span": { + "column": 348, + "document": "manifest", + "end": 2458, + "line": 36, + "start": 2435 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/6/name", + "span": { + "column": 367, + "document": "manifest", + "end": 2457, + "line": 36, + "start": 2454 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/7", + "span": { + "column": 393, + "document": "manifest", + "end": 2498, + "line": 36, + "start": 2480 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/exclude/7/kind", + "span": { + "column": 393, + "document": "manifest", + "end": 2498, + "line": 36, + "start": 2480 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/7/name", + "span": { + "column": 407, + "document": "manifest", + "end": 2497, + "line": 36, + "start": 2494 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/8", + "span": { + "column": 197, + "document": "manifest", + "end": 2301, + "line": 36, + "start": 2284 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/exclude/8/kind", + "span": { + "column": 197, + "document": "manifest", + "end": 2301, + "line": 36, + "start": 2284 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/8/name", + "span": { + "column": 210, + "document": "manifest", + "end": 2300, + "line": 36, + "start": 2297 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/9", + "span": { + "column": 282, + "document": "manifest", + "end": 2389, + "line": 36, + "start": 2369 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/exclude/9/kind", + "span": { + "column": 282, + "document": "manifest", + "end": 2389, + "line": 36, + "start": 2369 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/exclude/9/name", + "span": { + "column": 298, + "document": "manifest", + "end": 2388, + "line": 36, + "start": 2385 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 2500, + "line": 36, + "start": 2092 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/mode", + "span": { + "column": 5, + "document": "manifest", + "end": 2500, + "line": 36, + "start": 2092 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/name", + "span": { + "column": 19, + "document": "manifest", + "end": 2113, + "line": 36, + "start": 2106 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/7/native", + "span": { + "column": 5, + "document": "manifest", + "end": 2500, + "line": 36, + "start": 2092 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/path", + "span": { + "column": 34, + "document": "manifest", + "end": 2136, + "line": 36, + "start": 2121 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/select", + "span": { + "column": 77, + "document": "manifest", + "end": 2272, + "line": 36, + "start": 2164 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/7/select/0", + "span": { + "column": 78, + "document": "manifest", + "end": 2172, + "line": 36, + "start": 2165 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/7/select/1", + "span": { + "column": 87, + "document": "manifest", + "end": 2187, + "line": 36, + "start": 2174 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/7/select/2", + "span": { + "column": 102, + "document": "manifest", + "end": 2199, + "line": 36, + "start": 2189 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/7/select/3", + "span": { + "column": 114, + "document": "manifest", + "end": 2206, + "line": 36, + "start": 2201 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/7/select/4", + "span": { + "column": 121, + "document": "manifest", + "end": 2217, + "line": 36, + "start": 2208 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/7/select/5", + "span": { + "column": 132, + "document": "manifest", + "end": 2227, + "line": 36, + "start": 2219 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/7/select/6", + "span": { + "column": 142, + "document": "manifest", + "end": 2239, + "line": 36, + "start": 2229 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/7/select/7", + "span": { + "column": 154, + "document": "manifest", + "end": 2253, + "line": 36, + "start": 2241 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/7/select/8", + "span": { + "column": 168, + "document": "manifest", + "end": 2262, + "line": 36, + "start": 2255 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/7/select/9", + "span": { + "column": 177, + "document": "manifest", + "end": 2271, + "line": 36, + "start": 2264 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/7/source", + "span": { + "column": 59, + "document": "manifest", + "end": 2154, + "line": 36, + "start": 2146 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/8", + "span": { + "column": 5, + "document": "manifest", + "end": 2587, + "line": 37, + "start": 2506 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/8/agents", + "span": { + "column": 77, + "document": "manifest", + "end": 2586, + "line": 37, + "start": 2578 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/8/agents/0", + "span": { + "column": 78, + "document": "manifest", + "end": 2585, + "line": 37, + "start": 2579 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/8/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 2587, + "line": 37, + "start": 2506 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/8/event", + "span": { + "column": 34, + "document": "manifest", + "end": 2551, + "line": 37, + "start": 2535 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/8/event/kind", + "span": { + "column": 34, + "document": "manifest", + "end": 2551, + "line": 37, + "start": 2535 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/8/event/value", + "span": { + "column": 42, + "document": "manifest", + "end": 2550, + "line": 37, + "start": 2543 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/8/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 2587, + "line": 37, + "start": 2506 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/8/matcher", + "span": { + "column": 5, + "document": "manifest", + "end": 2587, + "line": 37, + "start": 2506 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/8/name", + "span": { + "column": 17, + "document": "manifest", + "end": 2526, + "line": 37, + "start": 2518 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/8/native", + "span": { + "column": 5, + "document": "manifest", + "end": 2587, + "line": 37, + "start": 2506 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + } + ], + "pointer": "/components/8/run", + "span": { + "column": 57, + "document": "manifest", + "end": 2568, + "line": 37, + "start": 2558 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + } + ], + "pointer": "/components/8/run/arguments", + "span": { + "column": 57, + "document": "manifest", + "end": 2568, + "line": 37, + "start": 2558 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 75, + "document": "manifest", + "end": 840, + "line": 17, + "start": 829 + }, + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + } + ], + "pointer": "/components/8/run/environment", + "span": { + "column": 57, + "document": "manifest", + "end": 2568, + "line": 37, + "start": 2558 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 75, + "document": "manifest", + "end": 840, + "line": 17, + "start": 829 + }, + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 53, + "document": "manifest", + "end": 493, + "line": 12, + "start": 487 + } + ], + "pointer": "/components/8/run/environment/LEVEL", + "span": { + "column": 57, + "document": "manifest", + "end": 2568, + "line": 37, + "start": 2558 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 75, + "document": "manifest", + "end": 840, + "line": 17, + "start": 829 + }, + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 53, + "document": "manifest", + "end": 493, + "line": 12, + "start": 487 + } + ], + "pointer": "/components/8/run/environment/LEVEL/kind", + "span": { + "column": 57, + "document": "manifest", + "end": 2568, + "line": 37, + "start": 2558 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 75, + "document": "manifest", + "end": 840, + "line": 17, + "start": 829 + }, + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 53, + "document": "manifest", + "end": 493, + "line": 12, + "start": 487 + } + ], + "pointer": "/components/8/run/environment/LEVEL/value", + "span": { + "column": 57, + "document": "manifest", + "end": 2568, + "line": 37, + "start": 2558 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 75, + "document": "manifest", + "end": 840, + "line": 17, + "start": 829 + }, + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 70, + "document": "manifest", + "end": 520, + "line": 12, + "start": 504 + } + ], + "pointer": "/components/8/run/environment/TOKEN", + "span": { + "column": 57, + "document": "manifest", + "end": 2568, + "line": 37, + "start": 2558 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 75, + "document": "manifest", + "end": 840, + "line": 17, + "start": 829 + }, + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 70, + "document": "manifest", + "end": 520, + "line": 12, + "start": 504 + } + ], + "pointer": "/components/8/run/environment/TOKEN/kind", + "span": { + "column": 57, + "document": "manifest", + "end": 2568, + "line": 37, + "start": 2558 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 75, + "document": "manifest", + "end": 840, + "line": 17, + "start": 829 + }, + { + "column": 43, + "document": "manifest", + "end": 521, + "line": 12, + "start": 477 + }, + { + "column": 70, + "document": "manifest", + "end": 520, + "line": 12, + "start": 504 + }, + { + "column": 78, + "document": "manifest", + "end": 519, + "line": 12, + "start": 512 + } + ], + "pointer": "/components/8/run/environment/TOKEN/value", + "span": { + "column": 57, + "document": "manifest", + "end": 2568, + "line": 37, + "start": 2558 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 52, + "document": "manifest", + "end": 814, + "line": 17, + "start": 806 + } + ], + "pointer": "/components/8/run/executable", + "span": { + "column": 57, + "document": "manifest", + "end": 2568, + "line": 37, + "start": 2558 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + } + ], + "pointer": "/components/8/run/kind", + "span": { + "column": 57, + "document": "manifest", + "end": 2568, + "line": 37, + "start": 2558 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 106, + "document": "manifest", + "end": 892, + "line": 17, + "start": 860 + } + ], + "pointer": "/components/8/run/workingDirectory", + "span": { + "column": 57, + "document": "manifest", + "end": 2568, + "line": 37, + "start": 2558 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 106, + "document": "manifest", + "end": 892, + "line": 17, + "start": 860 + }, + { + "column": 112, + "document": "manifest", + "end": 873, + "line": 17, + "start": 866 + } + ], + "pointer": "/components/8/run/workingDirectory/path", + "span": { + "column": 57, + "document": "manifest", + "end": 2568, + "line": 37, + "start": 2558 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 40, + "document": "manifest", + "end": 893, + "line": 17, + "start": 794 + }, + { + "column": 106, + "document": "manifest", + "end": 892, + "line": 17, + "start": 860 + }, + { + "column": 129, + "document": "manifest", + "end": 891, + "line": 17, + "start": 883 + } + ], + "pointer": "/components/8/run/workingDirectory/source", + "span": { + "column": 57, + "document": "manifest", + "end": 2568, + "line": 37, + "start": 2558 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/8/timeoutSeconds", + "span": { + "column": 5, + "document": "manifest", + "end": 2587, + "line": 37, + "start": 2506 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/9", + "span": { + "column": 5, + "document": "manifest", + "end": 2736, + "line": 38, + "start": 2593 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/9/agents", + "span": { + "column": 71, + "document": "manifest", + "end": 2661, + "line": 38, + "start": 2659 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/9/condition", + "span": { + "column": 86, + "document": "manifest", + "end": 2735, + "line": 38, + "start": 2674 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/9/condition/agents", + "span": { + "column": 86, + "document": "manifest", + "end": 2735, + "line": 38, + "start": 2674 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/9/condition/platforms", + "span": { + "column": 130, + "document": "manifest", + "end": 2734, + "line": 38, + "start": 2718 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/9/condition/platforms/0", + "span": { + "column": 139, + "document": "manifest", + "end": 2733, + "line": 38, + "start": 2727 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/9/condition/platforms/1", + "span": { + "column": 131, + "document": "manifest", + "end": 2725, + "line": 38, + "start": 2719 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/9/condition/scopes", + "span": { + "column": 100, + "document": "manifest", + "end": 2705, + "line": 38, + "start": 2688 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/9/condition/scopes/0", + "span": { + "column": 101, + "document": "manifest", + "end": 2697, + "line": 38, + "start": 2689 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/9/condition/scopes/1", + "span": { + "column": 111, + "document": "manifest", + "end": 2704, + "line": 38, + "start": 2699 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/9/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 2736, + "line": 38, + "start": 2593 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/9/name", + "span": { + "column": 19, + "document": "manifest", + "end": 2616, + "line": 38, + "start": 2607 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/9/native", + "span": { + "column": 5, + "document": "manifest", + "end": 2736, + "line": 38, + "start": 2593 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/9/patterns", + "span": { + "column": 40, + "document": "manifest", + "end": 2630, + "line": 38, + "start": 2628 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/9/purpose", + "span": { + "column": 53, + "document": "manifest", + "end": 2649, + "line": 38, + "start": 2641 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/defaultAgents", + "span": { + "column": 14, + "document": "manifest", + "end": 2871, + "line": 25, + "start": 1285 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/exports", + "span": { + "column": 12, + "document": "manifest", + "end": 1314, + "line": 26, + "start": 1304 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/exports/0", + "span": { + "column": 13, + "document": "manifest", + "end": 1313, + "line": 26, + "start": 1305 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups", + "span": { + "column": 11, + "document": "manifest", + "end": 2792, + "line": 41, + "start": 2768 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups/0", + "span": { + "column": 12, + "document": "manifest", + "end": 2791, + "line": 41, + "start": 2769 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/groups/0/components", + "span": { + "column": 12, + "document": "manifest", + "end": 2791, + "line": 41, + "start": 2769 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/groups/0/condition", + "span": { + "column": 12, + "document": "manifest", + "end": 2791, + "line": 41, + "start": 2769 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/groups/0/name", + "span": { + "column": 25, + "document": "manifest", + "end": 2790, + "line": 41, + "start": 2782 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/groups/0/uses", + "span": { + "column": 12, + "document": "manifest", + "end": 2791, + "line": 41, + "start": 2769 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources", + "span": { + "column": 12, + "document": "manifest", + "end": 1405, + "line": 27, + "start": 1327 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/0", + "span": { + "column": 13, + "document": "manifest", + "end": 1363, + "line": 27, + "start": 1328 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/0/kind", + "span": { + "column": 13, + "document": "manifest", + "end": 1363, + "line": 27, + "start": 1328 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/0/name", + "span": { + "column": 27, + "document": "manifest", + "end": 1348, + "line": 27, + "start": 1342 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/0/path", + "span": { + "column": 41, + "document": "manifest", + "end": 1362, + "line": 27, + "start": 1356 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/0/requirement", + "span": { + "column": 13, + "document": "manifest", + "end": 1363, + "line": 27, + "start": 1328 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/0/subpath", + "span": { + "column": 13, + "document": "manifest", + "end": 1363, + "line": 27, + "start": 1328 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1", + "span": { + "column": 50, + "document": "manifest", + "end": 1404, + "line": 27, + "start": 1365 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/1/kind", + "span": { + "column": 50, + "document": "manifest", + "end": 1404, + "line": 27, + "start": 1365 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1/name", + "span": { + "column": 64, + "document": "manifest", + "end": 1387, + "line": 27, + "start": 1379 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1/path", + "span": { + "column": 80, + "document": "manifest", + "end": 1403, + "line": 27, + "start": 1395 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/1/requirement", + "span": { + "column": 50, + "document": "manifest", + "end": 1404, + "line": 27, + "start": 1365 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/1/subpath", + "span": { + "column": 50, + "document": "manifest", + "end": 1404, + "line": 27, + "start": 1365 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/uses", + "span": { + "column": 9, + "document": "manifest", + "end": 2869, + "line": 42, + "start": 2802 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "shared constant or assembled value; replace its definition explicitly" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 178, + "line": 6, + "start": 170 + } + ], + "pointer": "/uses/0", + "span": { + "column": 10, + "document": "manifest", + "end": 2808, + "line": 42, + "start": 2803 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 178, + "line": 6, + "start": 170 + } + ], + "pointer": "/uses/0/condition", + "span": { + "column": 10, + "document": "manifest", + "end": 2808, + "line": 42, + "start": 2803 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 178, + "line": 6, + "start": 170 + } + ], + "pointer": "/uses/0/kind", + "span": { + "column": 10, + "document": "manifest", + "end": 2808, + "line": 42, + "start": 2803 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 178, + "line": 6, + "start": 170 + } + ], + "pointer": "/uses/0/name", + "span": { + "column": 10, + "document": "manifest", + "end": 2808, + "line": 42, + "start": 2803 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [ + { + "column": 29, + "document": "manifest", + "end": 178, + "line": 6, + "start": 170 + } + ], + "pointer": "/uses/0/source", + "span": { + "column": 10, + "document": "manifest", + "end": 2808, + "line": 42, + "start": 2803 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/uses/1", + "span": { + "column": 17, + "document": "manifest", + "end": 2868, + "line": 42, + "start": 2810 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/uses/1/condition", + "span": { + "column": 51, + "document": "manifest", + "end": 2867, + "line": 42, + "start": 2844 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/uses/1/condition/agents", + "span": { + "column": 65, + "document": "manifest", + "end": 2866, + "line": 42, + "start": 2858 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/uses/1/condition/agents/0", + "span": { + "column": 66, + "document": "manifest", + "end": 2865, + "line": 42, + "start": 2859 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/uses/1/condition/platforms", + "span": { + "column": 51, + "document": "manifest", + "end": 2867, + "line": 42, + "start": 2844 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/uses/1/condition/scopes", + "span": { + "column": 51, + "document": "manifest", + "end": 2867, + "line": 42, + "start": 2844 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/uses/1/kind", + "span": { + "column": 17, + "document": "manifest", + "end": 2868, + "line": 42, + "start": 2810 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/uses/1/name", + "span": { + "column": 30, + "document": "manifest", + "end": 2831, + "line": 42, + "start": 2823 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/uses/1/source", + "span": { + "column": 17, + "document": "manifest", + "end": 2868, + "line": 42, + "start": 2810 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/watch", + "span": { + "column": 14, + "document": "manifest", + "end": 2871, + "line": 25, + "start": 1285 + } + } + ], + "schemaVersion": 1, + "sourceDigest": "sha256:1532a48a6cf3953edc7e28a77b761ac216863bc521775beed798cb3a8cacbe76" +} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationAliasGap.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationAliasGap.migration.json new file mode 100644 index 0000000..cbec071 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationAliasGap.migration.json @@ -0,0 +1,18 @@ +{ + "sources": { + ".": { + "local": "live" + }, + "source-2": { + "local": "other" + } + }, + "skills": { + ".": { + "select": "all", + "overrides": { + "future": {} + } + } + } +} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationAliasGap.swift.txt b/Tests/AgentsManifestTests/Fixtures/MigrationAliasGap.swift.txt new file mode 100644 index 0000000..914c704 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationAliasGap.swift.txt @@ -0,0 +1,17 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + sources: [ + .source(name: "source", path: "live"), + .source(name: "source-2", path: "other"), + ], + components: [ + .skills( + source: "source", + overrides: [ + .skill(name: "future"), + ] + ), + ] +) diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationAliases.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationAliases.migration.json new file mode 100644 index 0000000..691d375 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationAliases.migration.json @@ -0,0 +1,48 @@ +{ + "sources": { + ".": { + "git": "git@Intranet:team/rules.git" + }, + "source": { + "local": "./s" + }, + "source-2": { + "local": "./s2" + } + }, + "skills": { + ".": { + "select": [ + "a" + ], + "exclude": [ + "a" + ], + "overrides": { + "a": { + "mode": "copy" + }, + "b": {} + } + } + }, + "instructions": { + "sections": [ + "guide", + ".:rule", + ".:rule" + ], + "chatgpt": { + "": { + "sections": [ + ".:rule", + "guide" + ] + } + } + }, + "watch": [ + ".", + "source" + ] +} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationAliases.swift.txt b/Tests/AgentsManifestTests/Fixtures/MigrationAliases.swift.txt new file mode 100644 index 0000000..ccaf17a --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationAliases.swift.txt @@ -0,0 +1,37 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + sources: [ + .source(name: "source", path: "./s"), + .source(name: "source-2", path: "./s2"), + .source(name: "source-3", url: "git@Intranet:team/rules.git"), + ], + components: [ + .skills( + source: "source-3", + select: ["a"], + exclude: ["a"], + overrides: [ + .skill(name: "a", mode: .copy), + ] + ), + .instructions( + sections: [ + "guide", + .section(name: "rule", source: "source-3"), + .section(name: "rule", source: "source-3"), + ], + chatGPT: [ + .prompt( + name: "", + sections: [ + .section(name: "rule", source: "source-3"), + "guide", + ] + ), + ] + ), + ], + watch: ["source", "source-3"] +) diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationEmpty.dump.json b/Tests/AgentsManifestTests/Fixtures/MigrationEmpty.dump.json new file mode 100644 index 0000000..24fcf74 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationEmpty.dump.json @@ -0,0 +1,145 @@ +{ + "declaration": { + "components": [], + "defaultAgents": null, + "exports": [], + "groups": [], + "sources": [], + "uses": [], + "watch": [] + }, + "diagnostics": [], + "kind": "manifest", + "languageVersion": "1.0", + "locations": [ + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "", + "span": { + "column": 14, + "document": "manifest", + "end": 76, + "line": 4, + "start": 68 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components", + "span": { + "column": 14, + "document": "manifest", + "end": 76, + "line": 4, + "start": 68 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/defaultAgents", + "span": { + "column": 14, + "document": "manifest", + "end": 76, + "line": 4, + "start": 68 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/exports", + "span": { + "column": 14, + "document": "manifest", + "end": 76, + "line": 4, + "start": 68 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/groups", + "span": { + "column": 14, + "document": "manifest", + "end": 76, + "line": 4, + "start": 68 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources", + "span": { + "column": 14, + "document": "manifest", + "end": 76, + "line": 4, + "start": 68 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/uses", + "span": { + "column": 14, + "document": "manifest", + "end": 76, + "line": 4, + "start": 68 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/watch", + "span": { + "column": 14, + "document": "manifest", + "end": 76, + "line": 4, + "start": 68 + } + } + ], + "schemaVersion": 1, + "sourceDigest": "sha256:65bce43a6e2a03e2cc8f774f710c7011b02d7d08a5be1bd49035100854cfa3ac" +} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationEmpty.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationEmpty.migration.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationEmpty.migration.json @@ -0,0 +1 @@ +{} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationEmpty.swift.txt b/Tests/AgentsManifestTests/Fixtures/MigrationEmpty.swift.txt new file mode 100644 index 0000000..8162099 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationEmpty.swift.txt @@ -0,0 +1,4 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents() diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationEscapes.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationEscapes.migration.json new file mode 100644 index 0000000..352a9a1 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationEscapes.migration.json @@ -0,0 +1,31 @@ +{ + "agents": [], + "sources": { + "é/别名~\"\\\n\r\t\u0001…": { + "git": "https://example.org/escape.git" + } + }, + "skills": { + "é/别名~\"\\\n\r\t\u0001…": { + "select": [ + "selected" + ], + "overrides": { + "unused": { + "agents": [] + } + } + } + }, + "instructions": { + "chatgpt": { + "\"\\\n\r\t\u0001… é 😀": { + "sections": [ + "own" + ], + "append": "notes/内容.md" + } + }, + "sections": [] + } +} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationEscapes.swift.txt b/Tests/AgentsManifestTests/Fixtures/MigrationEscapes.swift.txt new file mode 100644 index 0000000..b008e9e --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationEscapes.swift.txt @@ -0,0 +1,27 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + defaultAgents: [], + sources: [ + .source( + name: "é/别名~\"\\\n\r\t\u{1}\u{7f}\u{85}", + url: "https://example.org/escape.git" + ), + ], + components: [ + .skills( + source: "é/别名~\"\\\n\r\t\u{1}\u{7f}\u{85}", + select: ["selected"] + ), + .instructions( + chatGPT: [ + .prompt( + name: "\"\\\n\r\t\u{1}\u{7f}\u{85} é 😀", + sections: ["own"], + append: "notes/内容.md" + ), + ] + ), + ] +) diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationExplicitEmpty.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationExplicitEmpty.migration.json new file mode 100644 index 0000000..4e9f762 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationExplicitEmpty.migration.json @@ -0,0 +1,11 @@ +{ + "agents": [], + "sources": {}, + "skills": {}, + "instructions": { + "agents": [], + "sections": [], + "chatgpt": {} + }, + "watch": [] +} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationExplicitEmpty.swift.txt b/Tests/AgentsManifestTests/Fixtures/MigrationExplicitEmpty.swift.txt new file mode 100644 index 0000000..a221151 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationExplicitEmpty.swift.txt @@ -0,0 +1,11 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + defaultAgents: [], + components: [ + .instructions( + agents: [] + ), + ] +) diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationFields.dump.json b/Tests/AgentsManifestTests/Fixtures/MigrationFields.dump.json new file mode 100644 index 0000000..7fe46c1 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationFields.dump.json @@ -0,0 +1,2334 @@ +{ + "declaration": { + "components": [ + { + "agents": null, + "condition": null, + "exclude": [], + "kind": "skills", + "mode": "edit", + "native": {}, + "overrides": [], + "select": "all", + "source": "empty" + }, + { + "agents": [], + "condition": null, + "exclude": [ + "b" + ], + "kind": "skills", + "mode": "copy", + "native": {}, + "overrides": [ + { + "agents": [ + "codex" + ], + "mode": "link", + "name": "a" + }, + { + "agents": [], + "mode": null, + "name": "b" + } + ], + "select": [ + "a", + "b" + ], + "source": "git" + }, + { + "agents": null, + "condition": null, + "exclude": [], + "kind": "skills", + "mode": null, + "native": {}, + "overrides": [], + "select": [], + "source": "index" + }, + { + "agents": null, + "condition": null, + "exclude": [], + "kind": "skills", + "mode": null, + "native": {}, + "overrides": [ + { + "agents": null, + "mode": "copy", + "name": "future" + } + ], + "select": "all", + "source": "local" + }, + { + "agents": [ + "codex", + "gemini-cli" + ], + "chatGPT": [ + { + "append": null, + "condition": null, + "name": "", + "sections": [] + }, + { + "append": "notes/周报.md", + "condition": null, + "name": "周报", + "sections": [ + { + "condition": null, + "name": "rule", + "source": "git" + }, + { + "condition": null, + "name": "own", + "source": null + } + ] + } + ], + "condition": null, + "kind": "instructions", + "native": {}, + "sections": [ + { + "condition": null, + "name": "own", + "source": null + }, + { + "condition": null, + "name": "rule", + "source": "git" + }, + { + "condition": null, + "name": "own", + "source": null + }, + { + "condition": null, + "name": "nested/rule", + "source": "local" + } + ] + } + ], + "defaultAgents": [ + "claude-code", + "codex", + "opencode" + ], + "exports": [], + "groups": [], + "sources": [ + { + "kind": "local", + "name": "empty", + "path": "./live", + "requirement": null, + "subpath": null + }, + { + "kind": "git", + "name": "git", + "requirement": { + "branch": "main" + }, + "subpath": "skills", + "url": "https://intranet/team.git" + }, + { + "index": "https://example.org/.well-known/skills/index.json", + "kind": "index", + "name": "index", + "requirement": null, + "subpath": "bundle" + }, + { + "kind": "local", + "name": "local", + "path": "./drafts", + "requirement": { + "revision": "abc123" + }, + "subpath": null + } + ], + "uses": [], + "watch": [ + "git", + "index", + "local" + ] + }, + "diagnostics": [], + "kind": "manifest", + "languageVersion": "1.0", + "locations": [ + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "", + "span": { + "column": 14, + "document": "manifest", + "end": 1619, + "line": 4, + "start": 68 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components", + "span": { + "column": 15, + "document": "manifest", + "end": 1581, + "line": 21, + "start": 525 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0", + "span": { + "column": 5, + "document": "manifest", + "end": 568, + "line": 22, + "start": 531 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 568, + "line": 22, + "start": 531 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 568, + "line": 22, + "start": 531 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/exclude", + "span": { + "column": 5, + "document": "manifest", + "end": 568, + "line": 22, + "start": 531 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 568, + "line": 22, + "start": 531 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/0/mode", + "span": { + "column": 36, + "document": "manifest", + "end": 567, + "line": 22, + "start": 562 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/native", + "span": { + "column": 5, + "document": "manifest", + "end": 568, + "line": 22, + "start": 531 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/overrides", + "span": { + "column": 5, + "document": "manifest", + "end": 568, + "line": 22, + "start": 531 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/0/select", + "span": { + "column": 5, + "document": "manifest", + "end": 568, + "line": 22, + "start": 531 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/0/source", + "span": { + "column": 21, + "document": "manifest", + "end": 554, + "line": 22, + "start": 547 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1", + "span": { + "column": 5, + "document": "manifest", + "end": 888, + "line": 23, + "start": 574 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/agents", + "span": { + "column": 15, + "document": "manifest", + "end": 882, + "line": 39, + "start": 880 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 888, + "line": 23, + "start": 574 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/exclude", + "span": { + "column": 16, + "document": "manifest", + "end": 650, + "line": 26, + "start": 645 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/exclude/0", + "span": { + "column": 17, + "document": "manifest", + "end": 649, + "line": 26, + "start": 646 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 888, + "line": 23, + "start": 574 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/1/mode", + "span": { + "column": 13, + "document": "manifest", + "end": 669, + "line": 27, + "start": 664 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/native", + "span": { + "column": 5, + "document": "manifest", + "end": 888, + "line": 23, + "start": 574 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/overrides", + "span": { + "column": 18, + "document": "manifest", + "end": 864, + "line": 28, + "start": 688 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/overrides/0", + "span": { + "column": 9, + "document": "manifest", + "end": 786, + "line": 29, + "start": 698 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/overrides/0/agents", + "span": { + "column": 19, + "document": "manifest", + "end": 776, + "line": 32, + "start": 768 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/1/overrides/0/agents/0", + "span": { + "column": 20, + "document": "manifest", + "end": 775, + "line": 32, + "start": 769 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/1/overrides/0/mode", + "span": { + "column": 17, + "document": "manifest", + "end": 748, + "line": 31, + "start": 743 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/overrides/0/name", + "span": { + "column": 17, + "document": "manifest", + "end": 725, + "line": 30, + "start": 722 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/overrides/1", + "span": { + "column": 9, + "document": "manifest", + "end": 855, + "line": 34, + "start": 796 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/overrides/1/agents", + "span": { + "column": 19, + "document": "manifest", + "end": 845, + "line": 36, + "start": 843 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/1/overrides/1/mode", + "span": { + "column": 9, + "document": "manifest", + "end": 855, + "line": 34, + "start": 796 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/overrides/1/name", + "span": { + "column": 17, + "document": "manifest", + "end": 823, + "line": 35, + "start": 820 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/select", + "span": { + "column": 15, + "document": "manifest", + "end": 628, + "line": 25, + "start": 618 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/select/0", + "span": { + "column": 16, + "document": "manifest", + "end": 622, + "line": 25, + "start": 619 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/select/1", + "span": { + "column": 21, + "document": "manifest", + "end": 627, + "line": 25, + "start": 624 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/1/source", + "span": { + "column": 15, + "document": "manifest", + "end": 602, + "line": 24, + "start": 597 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2", + "span": { + "column": 5, + "document": "manifest", + "end": 948, + "line": 41, + "start": 894 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 948, + "line": 41, + "start": 894 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 948, + "line": 41, + "start": 894 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/exclude", + "span": { + "column": 5, + "document": "manifest", + "end": 948, + "line": 41, + "start": 894 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 948, + "line": 41, + "start": 894 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/mode", + "span": { + "column": 5, + "document": "manifest", + "end": 948, + "line": 41, + "start": 894 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/native", + "span": { + "column": 5, + "document": "manifest", + "end": 948, + "line": 41, + "start": 894 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/2/overrides", + "span": { + "column": 5, + "document": "manifest", + "end": 948, + "line": 41, + "start": 894 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/select", + "span": { + "column": 15, + "document": "manifest", + "end": 942, + "line": 43, + "start": 940 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/2/source", + "span": { + "column": 15, + "document": "manifest", + "end": 924, + "line": 42, + "start": 917 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3", + "span": { + "column": 5, + "document": "manifest", + "end": 1063, + "line": 45, + "start": 954 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/agents", + "span": { + "column": 5, + "document": "manifest", + "end": 1063, + "line": 45, + "start": 954 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 1063, + "line": 45, + "start": 954 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/exclude", + "span": { + "column": 5, + "document": "manifest", + "end": 1063, + "line": 45, + "start": 954 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 1063, + "line": 45, + "start": 954 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/mode", + "span": { + "column": 5, + "document": "manifest", + "end": 1063, + "line": 45, + "start": 954 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/native", + "span": { + "column": 5, + "document": "manifest", + "end": 1063, + "line": 45, + "start": 954 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3/overrides", + "span": { + "column": 18, + "document": "manifest", + "end": 1057, + "line": 47, + "start": 1003 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3/overrides/0", + "span": { + "column": 9, + "document": "manifest", + "end": 1048, + "line": 48, + "start": 1013 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/overrides/0/agents", + "span": { + "column": 9, + "document": "manifest", + "end": 1048, + "line": 48, + "start": 1013 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/3/overrides/0/mode", + "span": { + "column": 38, + "document": "manifest", + "end": 1047, + "line": 48, + "start": 1042 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3/overrides/0/name", + "span": { + "column": 22, + "document": "manifest", + "end": 1034, + "line": 48, + "start": 1026 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/3/select", + "span": { + "column": 5, + "document": "manifest", + "end": 1063, + "line": 45, + "start": 954 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/3/source", + "span": { + "column": 15, + "document": "manifest", + "end": 984, + "line": 46, + "start": 977 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4", + "span": { + "column": 5, + "document": "manifest", + "end": 1576, + "line": 51, + "start": 1069 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/agents", + "span": { + "column": 15, + "document": "manifest", + "end": 1570, + "line": 72, + "start": 1550 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/4/agents/0", + "span": { + "column": 16, + "document": "manifest", + "end": 1557, + "line": 72, + "start": 1551 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/components/4/agents/1", + "span": { + "column": 24, + "document": "manifest", + "end": 1569, + "line": 72, + "start": 1559 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/chatGPT", + "span": { + "column": 16, + "document": "manifest", + "end": 1534, + "line": 58, + "start": 1259 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/chatGPT/0", + "span": { + "column": 9, + "document": "manifest", + "end": 1330, + "line": 59, + "start": 1269 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/chatGPT/0/append", + "span": { + "column": 9, + "document": "manifest", + "end": 1330, + "line": 59, + "start": 1269 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/chatGPT/0/condition", + "span": { + "column": 9, + "document": "manifest", + "end": 1330, + "line": 59, + "start": 1269 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/chatGPT/0/name", + "span": { + "column": 17, + "document": "manifest", + "end": 1296, + "line": 60, + "start": 1294 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/chatGPT/0/sections", + "span": { + "column": 21, + "document": "manifest", + "end": 1320, + "line": 61, + "start": 1318 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/chatGPT/1", + "span": { + "column": 9, + "document": "manifest", + "end": 1525, + "line": 63, + "start": 1340 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/chatGPT/1/append", + "span": { + "column": 19, + "document": "manifest", + "end": 1515, + "line": 69, + "start": 1498 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/chatGPT/1/condition", + "span": { + "column": 9, + "document": "manifest", + "end": 1525, + "line": 63, + "start": 1340 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/chatGPT/1/name", + "span": { + "column": 17, + "document": "manifest", + "end": 1373, + "line": 64, + "start": 1365 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/chatGPT/1/sections", + "span": { + "column": 21, + "document": "manifest", + "end": 1478, + "line": 65, + "start": 1395 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/chatGPT/1/sections/0", + "span": { + "column": 13, + "document": "manifest", + "end": 1446, + "line": 66, + "start": 1409 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/chatGPT/1/sections/0/condition", + "span": { + "column": 13, + "document": "manifest", + "end": 1446, + "line": 66, + "start": 1409 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/chatGPT/1/sections/0/name", + "span": { + "column": 28, + "document": "manifest", + "end": 1430, + "line": 66, + "start": 1424 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/chatGPT/1/sections/0/source", + "span": { + "column": 44, + "document": "manifest", + "end": 1445, + "line": 66, + "start": 1440 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/chatGPT/1/sections/1", + "span": { + "column": 13, + "document": "manifest", + "end": 1465, + "line": 67, + "start": 1460 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/chatGPT/1/sections/1/condition", + "span": { + "column": 13, + "document": "manifest", + "end": 1465, + "line": 67, + "start": 1460 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/chatGPT/1/sections/1/name", + "span": { + "column": 13, + "document": "manifest", + "end": 1465, + "line": 67, + "start": 1460 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/chatGPT/1/sections/1/source", + "span": { + "column": 13, + "document": "manifest", + "end": 1465, + "line": 67, + "start": 1460 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/condition", + "span": { + "column": 5, + "document": "manifest", + "end": 1576, + "line": 51, + "start": 1069 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 1576, + "line": 51, + "start": 1069 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/native", + "span": { + "column": 5, + "document": "manifest", + "end": 1576, + "line": 51, + "start": 1069 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/sections", + "span": { + "column": 17, + "document": "manifest", + "end": 1242, + "line": 52, + "start": 1100 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/sections/0", + "span": { + "column": 9, + "document": "manifest", + "end": 1115, + "line": 53, + "start": 1110 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/sections/0/condition", + "span": { + "column": 9, + "document": "manifest", + "end": 1115, + "line": 53, + "start": 1110 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/sections/0/name", + "span": { + "column": 9, + "document": "manifest", + "end": 1115, + "line": 53, + "start": 1110 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/sections/0/source", + "span": { + "column": 9, + "document": "manifest", + "end": 1115, + "line": 53, + "start": 1110 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/sections/1", + "span": { + "column": 9, + "document": "manifest", + "end": 1162, + "line": 54, + "start": 1125 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/sections/1/condition", + "span": { + "column": 9, + "document": "manifest", + "end": 1162, + "line": 54, + "start": 1125 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/sections/1/name", + "span": { + "column": 24, + "document": "manifest", + "end": 1146, + "line": 54, + "start": 1140 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/sections/1/source", + "span": { + "column": 40, + "document": "manifest", + "end": 1161, + "line": 54, + "start": 1156 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/sections/2", + "span": { + "column": 9, + "document": "manifest", + "end": 1177, + "line": 55, + "start": 1172 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/sections/2/condition", + "span": { + "column": 9, + "document": "manifest", + "end": 1177, + "line": 55, + "start": 1172 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/sections/2/name", + "span": { + "column": 9, + "document": "manifest", + "end": 1177, + "line": 55, + "start": 1172 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/sections/2/source", + "span": { + "column": 9, + "document": "manifest", + "end": 1177, + "line": 55, + "start": 1172 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/sections/3", + "span": { + "column": 9, + "document": "manifest", + "end": 1233, + "line": 56, + "start": 1187 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/components/4/sections/3/condition", + "span": { + "column": 9, + "document": "manifest", + "end": 1233, + "line": 56, + "start": 1187 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/sections/3/name", + "span": { + "column": 24, + "document": "manifest", + "end": 1215, + "line": 56, + "start": 1202 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/components/4/sections/3/source", + "span": { + "column": 47, + "document": "manifest", + "end": 1232, + "line": 56, + "start": 1225 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/defaultAgents", + "span": { + "column": 18, + "document": "manifest", + "end": 125, + "line": 5, + "start": 93 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/defaultAgents/0", + "span": { + "column": 19, + "document": "manifest", + "end": 105, + "line": 5, + "start": 94 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/defaultAgents/1", + "span": { + "column": 32, + "document": "manifest", + "end": 113, + "line": 5, + "start": 107 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "expanded value has no independent source range" + }, + "origins": [], + "pointer": "/defaultAgents/2", + "span": { + "column": 40, + "document": "manifest", + "end": 124, + "line": 5, + "start": 115 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/exports", + "span": { + "column": 14, + "document": "manifest", + "end": 1619, + "line": 4, + "start": 68 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/groups", + "span": { + "column": 14, + "document": "manifest", + "end": 1619, + "line": 4, + "start": 68 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources", + "span": { + "column": 12, + "document": "manifest", + "end": 509, + "line": 6, + "start": 138 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/0", + "span": { + "column": 5, + "document": "manifest", + "end": 182, + "line": 7, + "start": 144 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/0/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 182, + "line": 7, + "start": 144 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/0/name", + "span": { + "column": 19, + "document": "manifest", + "end": 165, + "line": 7, + "start": 158 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/0/path", + "span": { + "column": 34, + "document": "manifest", + "end": 181, + "line": 7, + "start": 173 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/0/requirement", + "span": { + "column": 5, + "document": "manifest", + "end": 182, + "line": 7, + "start": 144 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/0/subpath", + "span": { + "column": 5, + "document": "manifest", + "end": 182, + "line": 7, + "start": 144 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1", + "span": { + "column": 5, + "document": "manifest", + "end": 307, + "line": 8, + "start": 188 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/1/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 307, + "line": 8, + "start": 188 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1/name", + "span": { + "column": 13, + "document": "manifest", + "end": 214, + "line": 9, + "start": 209 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1/requirement", + "span": { + "column": 15, + "document": "manifest", + "end": 276, + "line": 11, + "start": 270 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1/requirement/branch", + "span": { + "column": 15, + "document": "manifest", + "end": 276, + "line": 11, + "start": 270 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1/subpath", + "span": { + "column": 16, + "document": "manifest", + "end": 301, + "line": 12, + "start": 293 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/1/url", + "span": { + "column": 12, + "document": "manifest", + "end": 254, + "line": 10, + "start": 227 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/2", + "span": { + "column": 5, + "document": "manifest", + "end": 438, + "line": 14, + "start": 313 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/2/index", + "span": { + "column": 14, + "document": "manifest", + "end": 407, + "line": 16, + "start": 356 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/2/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 438, + "line": 14, + "start": 313 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/2/name", + "span": { + "column": 13, + "document": "manifest", + "end": 341, + "line": 15, + "start": 334 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/2/requirement", + "span": { + "column": 5, + "document": "manifest", + "end": 438, + "line": 14, + "start": 313 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/2/subpath", + "span": { + "column": 16, + "document": "manifest", + "end": 432, + "line": 17, + "start": 424 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/3", + "span": { + "column": 5, + "document": "manifest", + "end": 504, + "line": 19, + "start": 444 + } + }, + { + "defaulted": false, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/3/kind", + "span": { + "column": 5, + "document": "manifest", + "end": 504, + "line": 19, + "start": 444 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/3/name", + "span": { + "column": 19, + "document": "manifest", + "end": 465, + "line": 19, + "start": 458 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/3/path", + "span": { + "column": 34, + "document": "manifest", + "end": 483, + "line": 19, + "start": 473 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/3/requirement", + "span": { + "column": 56, + "document": "manifest", + "end": 503, + "line": 19, + "start": 495 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/sources/3/requirement/revision", + "span": { + "column": 56, + "document": "manifest", + "end": 503, + "line": 19, + "start": 495 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/sources/3/subpath", + "span": { + "column": 5, + "document": "manifest", + "end": 504, + "line": 19, + "start": 444 + } + }, + { + "defaulted": true, + "editability": { + "kind": "readOnly", + "reason": "default field has no source range" + }, + "origins": [], + "pointer": "/uses", + "span": { + "column": 14, + "document": "manifest", + "end": 1619, + "line": 4, + "start": 68 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/watch", + "span": { + "column": 10, + "document": "manifest", + "end": 1617, + "line": 75, + "start": 1592 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/watch/0", + "span": { + "column": 11, + "document": "manifest", + "end": 1598, + "line": 75, + "start": 1593 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/watch/1", + "span": { + "column": 18, + "document": "manifest", + "end": 1607, + "line": 75, + "start": 1600 + } + }, + { + "defaulted": false, + "editability": { + "kind": "direct" + }, + "origins": [], + "pointer": "/watch/2", + "span": { + "column": 27, + "document": "manifest", + "end": 1616, + "line": 75, + "start": 1609 + } + } + ], + "schemaVersion": 1, + "sourceDigest": "sha256:2b0afd8fd9775033934edb314622cbc706cf2e8c139d07c9f52e8bddb37d3e03" +} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationFields.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationFields.migration.json new file mode 100644 index 0000000..357f558 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationFields.migration.json @@ -0,0 +1,100 @@ +{ + "agents": [ + "opencode", + "claude-code", + "codex" + ], + "sources": { + "git": { + "git": "intranet/team.git", + "branch": "main", + "path": "skills" + }, + "local": { + "local": "./drafts", + "revision": "abc123" + }, + "index": { + "well-known": "https://example.org/.well-known/skills/index.json", + "path": "bundle" + }, + "empty": { + "local": "./live" + } + }, + "skills": { + "git": { + "select": [ + "b", + "a" + ], + "exclude": [ + "b" + ], + "agents": [], + "mode": "copy", + "overrides": { + "a": { + "mode": "link", + "agents": [ + "codex" + ] + }, + "b": { + "agents": [] + }, + "unused": { + "mode": "copy", + "agents": [ + "opencode", + "codex" + ] + } + } + }, + "local": { + "select": "all", + "overrides": { + "future": { + "mode": "copy" + } + } + }, + "index": { + "select": [] + }, + "empty": { + "select": "all", + "mode": "edit" + } + }, + "instructions": { + "agents": [ + "gemini-cli", + "codex" + ], + "sections": [ + "own", + "git:rule", + "own", + "local:nested/rule" + ], + "chatgpt": { + "周报": { + "sections": [ + "git:rule", + "own" + ], + "append": "notes/周报.md" + }, + "": { + "sections": [] + } + } + }, + "watch": [ + "local", + "git", + "index" + ] +} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationFields.swift.txt b/Tests/AgentsManifestTests/Fixtures/MigrationFields.swift.txt new file mode 100644 index 0000000..aed9e70 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationFields.swift.txt @@ -0,0 +1,76 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + defaultAgents: [.claudeCode, .codex, .openCode], + sources: [ + .source(name: "empty", path: "./live"), + .source( + name: "git", + url: "https://intranet/team.git", + branch: "main", + subpath: "skills" + ), + .source( + name: "index", + index: "https://example.org/.well-known/skills/index.json", + subpath: "bundle" + ), + .source(name: "local", path: "./drafts", revision: "abc123"), + ], + components: [ + .skills(source: "empty", mode: .edit), + .skills( + source: "git", + select: ["a", "b"], + exclude: ["b"], + mode: .copy, + overrides: [ + .skill( + name: "a", + mode: .link, + agents: [.codex] + ), + .skill( + name: "b", + agents: [] + ), + ], + agents: [] + ), + .skills( + source: "index", + select: [] + ), + .skills( + source: "local", + overrides: [ + .skill(name: "future", mode: .copy), + ] + ), + .instructions( + sections: [ + "own", + .section(name: "rule", source: "git"), + "own", + .section(name: "nested/rule", source: "local"), + ], + chatGPT: [ + .prompt( + name: "", + sections: [] + ), + .prompt( + name: "周报", + sections: [ + .section(name: "rule", source: "git"), + "own", + ], + append: "notes/周报.md" + ), + ], + agents: [.codex, .geminiCLI] + ), + ], + watch: ["git", "index", "local"] +) diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationRanges.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationRanges.migration.json new file mode 100644 index 0000000..6b23d8d --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationRanges.migration.json @@ -0,0 +1,47 @@ +{ + "sources": { + "a": { + "git": "https://Example.org/a.git", + "exact": " V1.2.3+build " + }, + "b": { + "local": "./b", + "from": "v1.2.0" + }, + "c": { + "local": "./c", + "upToNextMinor": "1.2.0-beta+build" + }, + "d": { + "local": "./d", + "from": "1.2.0", + "to": "2.0.0+meta" + }, + "e": { + "local": "./e", + "from": "1.2.0+lower", + "to": "1.3.0+upper" + }, + "f": { + "local": "./f", + "from": "1.2.0", + "to": "1.8.0-beta+bound" + }, + "g": { + "local": "./g", + "from": "9223372036854775807.1.0", + "to": "9223372036854775807.2.0" + }, + "h": { + "git": "ssh://User@INTRANET:2222/team/h.git", + "revision": "abc123" + }, + "i": { + "local": "./i", + "upToNextMinor": "1.2.0-alphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalpha" + }, + "j": { + "git": "intranet/team@variant" + } + } +} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationRanges.swift.txt b/Tests/AgentsManifestTests/Fixtures/MigrationRanges.swift.txt new file mode 100644 index 0000000..b4757f4 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationRanges.swift.txt @@ -0,0 +1,43 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + sources: [ + .source(name: "a", url: "https://Example.org/a.git", exact: "1.2.3+build"), + .source(name: "b", path: "./b", from: "1.2.0"), + .source( + name: "c", + path: "./c", + .upToNextMinor(from: "1.2.0-beta+build") + ), + .source(name: "d", path: "./d", from: "1.2.0"), + .source( + name: "e", + path: "./e", + .upToNextMinor(from: "1.2.0+lower") + ), + .source( + name: "f", + path: "./f", + "1.2.0"..<"1.8.0-beta+bound" + ), + .source( + name: "g", + path: "./g", + .upToNextMinor(from: "9223372036854775807.1.0") + ), + .source( + name: "h", + url: "ssh://User@INTRANET:2222/team/h.git", + revision: "abc123" + ), + .source( + name: "i", + path: "./i", + .upToNextMinor( + from: "1.2.0-alphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalpha" + ) + ), + .source(name: "j", url: "https://intranet/team@variant"), + ] +) diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationWidth.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationWidth.migration.json new file mode 100644 index 0000000..9100533 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationWidth.migration.json @@ -0,0 +1,26 @@ +{ + "sources": { + "s": { + "local": "./s" + }, + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": { + "local": "p" + }, + "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy": { + "local": "p2" + } + }, + "skills": { + "s": { + "select": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "bbbbbbbbbbbbbbbbbbbbbbbb" + ], + "exclude": [ + "ccccccccccccccccccccccccccccccccc", + "dddddddddddddddddddddddd" + ], + "mode": "link" + } + } +} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationWidth.swift.txt b/Tests/AgentsManifestTests/Fixtures/MigrationWidth.swift.txt new file mode 100644 index 0000000..a5752f0 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationWidth.swift.txt @@ -0,0 +1,24 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + sources: [ + .source(name: "s", path: "./s"), + .source(name: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", path: "p"), + .source( + name: "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy", + path: "p2" + ), + ], + components: [ + .skills( + source: "s", + select: ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbb"], + exclude: [ + "ccccccccccccccccccccccccccccccccc", + "dddddddddddddddddddddddd", + ], + mode: .link + ), + ] +) diff --git a/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json b/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json index afec5bd..ff7f73e 100644 --- a/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json +++ b/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json @@ -12,6 +12,12 @@ "syntaxReservation": 344, "tokens": 82 }, + "DumpSymbolic.swift.txt": { + "syntaxDepth": 29, + "syntaxNodes": 747, + "syntaxReservation": 1268, + "tokens": 313 + }, "ExportedGroup.swift.txt": { "syntaxDepth": 29, "syntaxNodes": 210, @@ -30,12 +36,60 @@ "syntaxReservation": 2932, "tokens": 729 }, + "MigrationAliasGap.swift.txt": { + "syntaxDepth": 26, + "syntaxNodes": 152, + "syntaxReservation": 264, + "tokens": 62 + }, + "MigrationAliases.swift.txt": { + "syntaxDepth": 32, + "syntaxNodes": 403, + "syntaxReservation": 680, + "tokens": 166 + }, "MigrationEdgeExample.swift.txt": { "syntaxDepth": 32, "syntaxNodes": 446, "syntaxReservation": 780, "tokens": 191 }, + "MigrationEmpty.swift.txt": { + "syntaxDepth": 10, + "syntaxNodes": 29, + "syntaxReservation": 48, + "tokens": 8 + }, + "MigrationEscapes.swift.txt": { + "syntaxDepth": 29, + "syntaxNodes": 192, + "syntaxReservation": 424, + "tokens": 75 + }, + "MigrationExplicitEmpty.swift.txt": { + "syntaxDepth": 18, + "syntaxNodes": 62, + "syntaxReservation": 120, + "tokens": 26 + }, + "MigrationFields.swift.txt": { + "syntaxDepth": 32, + "syntaxNodes": 748, + "syntaxReservation": 1304, + "tokens": 322 + }, + "MigrationRanges.swift.txt": { + "syntaxDepth": 23, + "syntaxNodes": 474, + "syntaxReservation": 752, + "tokens": 184 + }, + "MigrationWidth.swift.txt": { + "syntaxDepth": 23, + "syntaxNodes": 209, + "syntaxReservation": 348, + "tokens": 83 + }, "ProducerExample.swift.txt": { "syntaxDepth": 29, "syntaxNodes": 210, diff --git a/Tests/AgentsManifestTests/MigrationTests.swift b/Tests/AgentsManifestTests/MigrationTests.swift new file mode 100644 index 0000000..c6b684e --- /dev/null +++ b/Tests/AgentsManifestTests/MigrationTests.swift @@ -0,0 +1,189 @@ +import AgentsCore +import AgentsDescription +import Foundation +import Testing + +@testable import AgentsManifest + +private let migrationCases = [ + "MigrationEmpty", "MigrationExplicitEmpty", "MigrationFields", "MigrationAliases", + "MigrationRanges", "MigrationEscapes", "MigrationWidth", "MigrationAliasGap", +] + +func manifestFixture(_ name: String) throws -> [UInt8] { + Array(try Data(contentsOf: Bundle.module.resourceURL!.appendingPathComponent("Fixtures/" + name))) +} + +@Suite("Manifest migration") +struct MigrationTests { + @Test(arguments: migrationCases) + func canonicalFixturesAreByteExactDeterministicAndStableUnderEqualEdits(_ name: String) throws { + let input = try manifestFixture(name + ".migration.json") + let first = try ManifestMigration.generate(json: input) + let second = try ManifestMigration.generate(json: input) + #expect(try first.bytes == manifestFixture(name + ".swift.txt")) + #expect(first.bytes == second.bytes) + #expect(first.diagnostics == second.diagnostics) + #expect(first.bytes.last == 10 && !first.bytes.dropLast().suffix(1).contains(10)) + #expect(!first.bytes.starts(with: [0xEF, 0xBB, 0xBF]) && !first.bytes.contains(13)) + let doc = try DeclarationDocument(bytes: first.bytes, identity: DocumentIdentity("manifest")) + #expect(doc.declaration == first.declaration) + let edited = try doc.preparing([.setWatch(first.declaration.watch)]) + #expect(edited.bytes == first.bytes && edited.patches.isEmpty) + } + + @Test func transformationsReportOriginalPointersFullValuesAndPreserveExcludedOverrides() throws { + let result = try ManifestMigration.generate( + json: manifestFixture("MigrationAliases.migration.json")) + #expect( + result.diagnostics.map(\.code) == ["migration.inertOverride", "migration.sourceAliasRenamed"]) + #expect(result.diagnostics.map(\.pointer) == ["/skills/./overrides/b", "/sources/."]) + #expect(result.diagnostics[0].value == .object([:])) + #expect(result.diagnostics[1].oldAlias == "." && result.diagnostics[1].newAlias == "source-3") + #expect( + result.declaration.sources.map { $0["name"]?.string } == ["source", "source-2", "source-3"]) + #expect(result.declaration.components[0]["overrides"]?.elements?.count == 1) + let instructions = result.declaration.components[1] + let sections = try #require(instructions["sections"]?.elements) + #expect( + sections.map { $0.record?["source"] } == [.null, .string("source-3"), .string("source-3")]) + let prompts = try #require(instructions["chatGPT"]?.elements) + #expect(prompts[0].record?["sections"]?.elements?[0].record?["source"] == .string("source-3")) + #expect(result.declaration.watch == ["source", "source-3"]) + let fields = try ManifestMigration.generate( + json: manifestFixture("MigrationFields.migration.json")) + #expect(fields.diagnostics.count == 1) + #expect( + fields.diagnostics[0].value + == .object([ + "agents": .array([.string("opencode"), .string("codex")]), "mode": .string("copy"), + ])) + #expect(fields.declaration.components[3]["overrides"]?.elements?.count == 1) + let escaped = try ManifestMigration.generate( + json: manifestFixture("MigrationEscapes.migration.json")) + #expect( + escaped.diagnostics[0].pointer.contains("~1") && escaped.diagnostics[0].pointer.contains("~0") + ) + } + + @Test func firstUnusedAliasAndInertRulesDoNotDependOnDiscovery() throws { + let result = try ManifestMigration.generate( + json: manifestFixture("MigrationAliasGap.migration.json")) + #expect(result.diagnostics.count == 1 && result.diagnostics[0].newAlias == "source") + #expect(result.declaration.components[0]["overrides"]?.elements?.count == 1) + } + + @Test func compatibilityProjectionRetainsInheritanceAndCanonicalizesCoreRequirements() throws { + let legacy = Declaration( + agents: [], + sources: [ + "a": SourceDeclaration( + kind: .git, location: "intranet/team.git", + requirement: .range(from: "v1.2.0", to: "2.0.0+meta")) + ], + skills: [ + "a": SkillDeclaration( + select: .names([]), agents: [], mode: .link, + overrides: ["future": SkillOverride(agents: [])]) + ], + instructions: InstructionsDeclaration()) + let projection = try legacy.compatibilityProjection() + #expect(projection.defaultAgents == []) + #expect(projection.sources[0]["url"] == .string("https://intranet/team.git")) + #expect(projection.sources[0]["requirement"] == .requirement(.upToNextMajor(from: "1.2.0"))) + #expect(projection.components[0]["agents"] == .array([])) + #expect(projection.components[0]["mode"] == .string("link")) + #expect(projection.components[0]["overrides"]?.elements?.count == 1) + #expect(projection.components[1]["agents"] == .null) + #expect(try Declaration().compatibilityProjection() == DeclarationIR()) + let migration = try ManifestMigration.generate( + json: manifestFixture("MigrationRanges.migration.json")) + let doc = try DeclarationDocument( + bytes: migration.bytes, identity: DocumentIdentity("manifest")) + let change = try doc.preparing([ + .upsertSource(.source(name: "b", path: "./b", "1.2.0"..<"2.0.0")) + ]) + #expect(change.bytes == doc.bytes && change.patches.isEmpty) + } + + @Test(arguments: [ + #"{"unknown":null}"#, #"{"sources":{"x":{"git":"intranet/team","unknown":null}}}"#, + #"{"sources":{},"sources":{}}"#, #"{"agents":["unknown"]}"#, + #"{"sources":{"x":{"local":"a"}},"skills":{"x":{"select":"all","overrides":{"a":{"unknown":null}}}}}"#, + ]) + func strictJSONFailuresNeverProduceSource(_ input: String) { + #expect(throws: (any Error).self) { try ManifestMigration.generate(json: Array(input.utf8)) } + } + + @Test func invalidUTF8AndSelfCheckFailuresHaveNoPartialResult() throws { + #expect(throws: (any Error).self) { try ManifestMigration.generate(json: [0xFF]) } + var result: ManifestMigrationResult? + do { + result = try ManifestMigration.generate( + json: Array("{}".utf8), environment: RuntimeEnvironment(), + checking: { _ in DeclarationIR(watch: ["wrong"]) }) + Issue.record("self-check did not reject mismatching projection") + } catch let failure as MigrationFailure { + #expect(failure.diagnostics.map(\.code) == ["migration.mismatch"]) + } + #expect(result == nil) + } + + @Test func byteWidthIncludesLabelsCommasAndUTF8() throws { + let printer = CanonicalPrinter() + let atBoundary = Source.source(name: String(repeating: "a", count: 47), path: "p") + .constructionValue + let overBoundary = Source.source(name: String(repeating: "a", count: 48), path: "p") + .constructionValue + #expect(!printer.render(atBoundary, indentation: " ").contains("\n")) + #expect(printer.render(overBoundary, indentation: " ").contains("\n")) + let unicode = Source.source(name: String(repeating: "é", count: 24), path: "p") + .constructionValue + #expect(printer.render(unicode, indentation: " ").contains("\n")) + let doc = try ManifestMigration.generate(json: manifestFixture("MigrationWidth.migration.json")) + let text = String(decoding: doc.bytes, as: UTF8.self) + #expect(text.contains("select: [")) + #expect(text.split(separator: "\n").allSatisfy { $0.utf8.count <= 80 }) + } + + @Test func migrationLimitsAreNamedAndNeverReturnTruncatedResults() throws { + func limit(_ budget: String, _ operation: () throws -> Void) { + do { + try operation() + Issue.record("expected migration.limit: \(budget)") + } catch let failure as MigrationFailure { + #expect(failure.diagnostics.map(\.code) == ["migration.limit"]) + #expect(failure.diagnostics[0].budget?.contains(budget) == true) + } catch { Issue.record(error) } + } + limit("collection entries") { + try ManifestMigration.preflight(.array(Array(repeating: .none, count: 10_001))) + } + var deep: ConstructionValue = .none + for _ in 0..<64 { deep = .array([deep]) } + limit("expanded depth") { try ManifestMigration.preflight(deep) } + let nodes = ConstructionValue.array( + Array(repeating: .array(Array(repeating: .none, count: 100)), count: 1_000)) + limit("expanded nodes") { try ManifestMigration.preflight(nodes) } + limit("decoded string bytes") { + try ManifestMigration.preflight( + .text(String(repeating: "x", count: ManifestLimits.Values.stringBytes + 1))) + } + limit("encoded output bytes") { + try ManifestMigration.preflight(.text(String(repeating: "\0", count: 6_000_000))) + } + let oversized = Declaration(sources: [ + "s": SourceDeclaration( + kind: .local, location: String(repeating: "x", count: ManifestLimits.Input.bytes)) + ]) + limit("source bytes") { + _ = try ManifestMigration.generate(json: Array(JSONEncoder().encode(oversized))) + } + let many = Declaration( + sources: ["s": SourceDeclaration(kind: .local, location: "s")], + instructions: InstructionsDeclaration(sections: Array(repeating: "s:guide", count: 3_600))) + limit("reservation") { + _ = try ManifestMigration.generate(json: Array(JSONEncoder().encode(many))) + } + } +} diff --git a/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift b/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift new file mode 100644 index 0000000..9e2bd8e --- /dev/null +++ b/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift @@ -0,0 +1,95 @@ +import AgentsCore +import AgentsInstructions +import AgentsSkills +import Foundation +import Testing + +@testable import AgentsUpdates + +@Suite("Semantic requirement updates") +struct RequirementUpdateTests { + @Test func sourceMergingAcceptsEqualRangesAndRejectsDifferentRootsAndRequirements() throws { + let old = LockedSource( + kind: .git, url: "https://example.org/team.git", requirement: .branch("main")) + var legacy = old + legacy.requirement = .range(from: "v1.2.0+lower", to: "2.0.0+upper") + let canonical = LockedSource( + kind: .git, url: "ssh://user@EXAMPLE.org/team", requirement: .upToNextMajor(from: "1.2.0")) + let merged = try UpdatePlan.mergedSources( + previous: ["id": old], skills: ["id": legacy], instructions: ["id": canonical]) + #expect(merged["id"] == canonical) + let unchanged = try UpdatePlan.mergedSources( + previous: ["id": legacy], skills: ["id": canonical], instructions: ["id": legacy]) + #expect(unchanged["id"]?.requirement == legacy.requirement) + var different = canonical + different.path = "other" + #expect(throws: CoreError.self) { + try UpdatePlan.mergedSources( + previous: ["id": old], skills: ["id": legacy], instructions: ["id": different]) + } + different = canonical + different.requirement = .upToNextMinor(from: "1.2.0") + #expect(throws: CoreError.self) { + try UpdatePlan.mergedSources( + previous: ["id": old], skills: ["id": legacy], instructions: ["id": different]) + } + } + + @Test func skillInstructionAndCombinedUpdatesKeepPinsAndOriginalLedgerBytes() throws { + let fixture = try UpdateFixture() + try fixture.git(["tag", "1.2.0"]) + try fixture.declare(agents: [.codex]) + var declaration = try fixture.store.loadDeclaration() + declaration.agents = [.codex] + declaration.instructions?.agents = nil + declaration.sources["fixture"]?.requirement = .upToNextMajor(from: "1.2.0") + try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + _ = try fixture.apply() + let original = try fixture.store.loadResolved() + var object = try #require( + JSONSerialization.jsonObject(with: fixture.bytes(fixture.store.resolvedURL)) as? [String: Any] + ) + var sources = try #require(object["sources"] as? [String: [String: Any]]) + let id = try #require(sources.keys.first) + sources[id]?["requirement"] = ["from": "v1.2.0+lower", "to": "2.0.0+upper"] + object["sources"] = sources + let legacyBytes = try JSONSerialization.data( + withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes]) + try legacyBytes.write(to: fixture.store.resolvedURL) + let beforeAttributes = try FileManager.default.attributesOfItem( + atPath: fixture.store.resolvedURL.path) + #expect(try !fixture.preview().hasChanges) + let skills = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(skills.allSatisfy { !$0.changed }) + let instructions = try InstructionOperations.updateInstalled( + environment: fixture.environment, apply: true) + #expect(!instructions.hasChanges) + let combined = try fixture.apply() + #expect(!combined.report.hasChanges) + #expect(try fixture.bytes(fixture.store.resolvedURL) == legacyBytes) + #expect(try fixture.store.loadResolved() == original) + let afterAttributes = try FileManager.default.attributesOfItem( + atPath: fixture.store.resolvedURL.path) + #expect( + beforeAttributes[.systemFileNumber] as? UInt64 == afterAttributes[.systemFileNumber] + as? UInt64) + #expect( + beforeAttributes[.modificationDate] as? Date == afterAttributes[.modificationDate] as? Date) + let intentOnly = try InstructionOperations.updateInstalled( + agents: [.codex], environment: fixture.environment, apply: true) + #expect(intentOnly.hasChanges) + #expect(try fixture.store.loadDeclaration().instructions?.agents == [.codex]) + #expect(try fixture.bytes(fixture.store.resolvedURL) == legacyBytes) + try fixture.advance() + try fixture.git(["tag", "1.3.0"]) + _ = try fixture.apply() + let changed = try fixture.bytes(fixture.store.resolvedURL) + #expect(changed != legacyBytes) + let rewritten = try #require(JSONSerialization.jsonObject(with: changed) as? [String: Any]) + let rewrittenSources = try #require(rewritten["sources"] as? [String: [String: Any]]) + #expect(rewrittenSources[id]?["requirement"] as? [String: String] == ["from": "1.2.0+lower"]) + #expect( + try fixture.store.loadResolved().skills["demo"]?.revision + == fixture.git(["rev-parse", "HEAD"])) + } +} From 5fc2595b94d57bec01f4d5cfad664422f8389335 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:44:20 +0800 Subject: [PATCH 013/171] feat: remove duplicate recipients during migration The JSON validator accepts repeated recipient IDs while the manifest domain rejects them. Migration keeps the first occurrence in each agents array and reports every removed element as migration.duplicateRecipient, so every valid declaration still has a deterministic conversion. --- Documentation/Proposals/AgentsManifest.md | 11 +++- .../AgentsManifest/ManifestMigration.swift | 42 ++++++++++++ .../CompiledFixtures.swift | 57 ++++++++++++++++ ...igrationDuplicateRecipients.migration.json | 34 ++++++++++ .../MigrationDuplicateRecipients.swift.txt | 49 ++++++++++++++ .../Fixtures/ParserBaseline.json | 6 ++ .../AgentsManifestTests/MigrationTests.swift | 66 +++++++++++++++++++ 7 files changed, 262 insertions(+), 3 deletions(-) create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationDuplicateRecipients.migration.json create mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationDuplicateRecipients.swift.txt diff --git a/Documentation/Proposals/AgentsManifest.md b/Documentation/Proposals/AgentsManifest.md index fc3e3c2..a192c6e 100644 --- a/Documentation/Proposals/AgentsManifest.md +++ b/Documentation/Proposals/AgentsManifest.md @@ -1520,7 +1520,7 @@ never triggers truncation or partial migration. ### Compatibility transformations -Two explicit transformations precede printing and are included in the migration +Three explicit transformations precede printing and are included in the migration result's ordered diagnostics: 1. For an explicit skill selection, an override whose name is not in `select` is @@ -1536,10 +1536,15 @@ result's ordered diagnostics: in both native instructions and ChatGPT prompts. Bare section names still mean own sections and are not rewritten. Normalized source identities and pins do not change. +3. In each `agents` array at the root, in instructions, in a skill selection or + in a skill override, retain the first occurrence of each recipient ID and remove + subsequent occurrences. Report `migration.duplicateRecipient` for every removed + element with its original JSON Pointer and recipient ID. A nonempty array stays + nonempty, and explicit versus inherited recipients remain distinct. Diagnostics sort by original JSON Pointer and code. They are returned in preview -and apply reports; conversion never silently discards the removed override or -hides a rename. The compatibility projection compares effective selections, +and apply reports; conversion never silently discards a removed override or +recipient, or hides a rename. The compatibility projection compares effective selections, recipients, modes, ordered content, subscriptions and source identities after applying precisely those reported transformations. Apart from them, explicit versus inherited intent and every field above are preserved. No groups, native diff --git a/Sources/AgentsManifest/ManifestMigration.swift b/Sources/AgentsManifest/ManifestMigration.swift index 5c5880b..a58b366 100644 --- a/Sources/AgentsManifest/ManifestMigration.swift +++ b/Sources/AgentsManifest/ManifestMigration.swift @@ -63,6 +63,7 @@ public enum ManifestMigration { let input = try JSONSerialization.jsonObject(with: Data(bytes)) as! [String: Any] try validateKeys(input) var diagnostics: [MigrationDiagnostic] = [] + removeDuplicateRecipients(from: &legacy, diagnostics: &diagnostics) for alias in (legacy.skills ?? [:]).keys.sorted(by: utf8Less) { guard let selection = legacy.skills?[alias], case .names(let names) = selection.select else { continue @@ -136,6 +137,47 @@ public enum ManifestMigration { return ManifestMigrationResult(bytes: output, declaration: projection, diagnostics: diagnostics) } + private static func removeDuplicateRecipients( + from legacy: inout Declaration, diagnostics: inout [MigrationDiagnostic] + ) { + func recipients(_ agents: [AgentID]?, at pointer: String) -> [AgentID]? { + guard let agents else { return nil } + var seen = Set() + var unique: [AgentID] = [] + for (index, agent) in agents.enumerated() { + if seen.insert(agent).inserted { + unique.append(agent) + } else { + diagnostics.append( + MigrationDiagnostic( + pointer: pointer + "/\(index)", code: "migration.duplicateRecipient", + message: "recipient repeats an earlier entry in the same agents array", + value: .string(agent.rawValue))) + } + } + return unique + } + // Preserve original element indices and aliases before any other transformation removes + // overrides or renames sources. Optional arrays retain their inheritance boundary. + legacy.agents = recipients(legacy.agents, at: "/agents") + if var instructions = legacy.instructions { + instructions.agents = recipients(instructions.agents, at: "/instructions/agents") + legacy.instructions = instructions + } + for alias in (legacy.skills ?? [:]).keys.sorted(by: utf8Less) { + var selection = legacy.skills![alias]! + let pointer = "/skills/" + pointerEscape(alias) + selection.agents = recipients(selection.agents, at: pointer + "/agents") + for name in (selection.overrides ?? [:]).keys.sorted(by: utf8Less) { + var override = selection.overrides![name]! + override.agents = recipients( + override.agents, at: pointer + "/overrides/" + pointerEscape(name) + "/agents") + selection.overrides?[name] = override + } + legacy.skills?[alias] = selection + } + } + static func preflight(_ value: ConstructionValue) throws { var pending = [(value, 1)] var nodes = 0 diff --git a/Tests/AgentsManifestTests/CompiledFixtures.swift b/Tests/AgentsManifestTests/CompiledFixtures.swift index a2357ec..639e7f8 100644 --- a/Tests/AgentsManifestTests/CompiledFixtures.swift +++ b/Tests/AgentsManifestTests/CompiledFixtures.swift @@ -23,6 +23,7 @@ func compiledFixtures() -> [CompiledManifestFixture] { compiledLiteralCoverage(), compiledMigrationAliasGap(), compiledMigrationAliases(), + compiledMigrationDuplicateRecipients(), compiledMigrationEdgeExample(), compiledMigrationEmpty(), compiledMigrationEscapes(), @@ -419,6 +420,62 @@ private func compiledMigrationAliases() -> CompiledManifestFixture { ]) } +private func compiledMigrationDuplicateRecipients() -> CompiledManifestFixture { + // agents-tools-version: 1.0 + + let agents = Agents( + defaultAgents: [.claudeCode, .codex], + sources: [ + .source(name: "a~/b", path: "./other"), + .source(name: "source", path: "./inherited"), + .source(name: "source-2", path: "./rules"), + ], + components: [ + .skills( + source: "a~/b", + overrides: [ + .skill( + name: "future", + agents: [.openCode] + ) + ], + agents: [] + ), + .skills(source: "source"), + .skills( + source: "source-2", + select: ["empty", "inherited", "review"], + exclude: ["review"], + overrides: [ + .skill( + name: "empty", + agents: [] + ), + .skill(name: "inherited", mode: .copy), + .skill( + name: "review", + agents: [.codex, .cursor] + ), + ], + agents: [.claudeCode, .openCode] + ), + .instructions( + sections: [ + "guide", + .section(name: "rule", source: "source-2"), + ], + agents: [.codex, .geminiCLI] + ), + ], + watch: ["source-2"] + ) + return CompiledManifestFixture( + name: "MigrationDuplicateRecipients.swift.txt", agents: agents, + constants: [ + "agents": agents.constructionValue + ]) +} + private func compiledMigrationEdgeExample() -> CompiledManifestFixture { // agents-tools-version: 1.0 diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationDuplicateRecipients.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationDuplicateRecipients.migration.json new file mode 100644 index 0000000..c60e2a0 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationDuplicateRecipients.migration.json @@ -0,0 +1,34 @@ +{ + "agents": ["codex", "claude-code", "codex", "codex", "claude-code"], + "sources": { + ".": {"local": "./rules"}, + "a~/b": {"local": "./other"}, + "source": {"local": "./inherited"} + }, + "skills": { + ".": { + "select": ["review", "empty", "inherited"], + "exclude": ["review"], + "agents": ["opencode", "claude-code", "opencode", "claude-code"], + "overrides": { + "review": {"agents": ["cursor", "codex", "cursor", "codex"]}, + "empty": {"agents": []}, + "inherited": {"mode": "copy"}, + "unused": {"agents": ["gemini-cli", "gemini-cli"], "mode": "copy"} + } + }, + "a~/b": { + "select": "all", + "agents": [], + "overrides": { + "future": {"agents": ["opencode", "opencode"]} + } + }, + "source": {"select": "all"} + }, + "instructions": { + "agents": ["gemini-cli", "codex", "gemini-cli", "codex"], + "sections": ["guide", ".:rule"] + }, + "watch": ["."] +} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationDuplicateRecipients.swift.txt b/Tests/AgentsManifestTests/Fixtures/MigrationDuplicateRecipients.swift.txt new file mode 100644 index 0000000..8b919e6 --- /dev/null +++ b/Tests/AgentsManifestTests/Fixtures/MigrationDuplicateRecipients.swift.txt @@ -0,0 +1,49 @@ +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + defaultAgents: [.claudeCode, .codex], + sources: [ + .source(name: "a~/b", path: "./other"), + .source(name: "source", path: "./inherited"), + .source(name: "source-2", path: "./rules"), + ], + components: [ + .skills( + source: "a~/b", + overrides: [ + .skill( + name: "future", + agents: [.openCode] + ), + ], + agents: [] + ), + .skills(source: "source"), + .skills( + source: "source-2", + select: ["empty", "inherited", "review"], + exclude: ["review"], + overrides: [ + .skill( + name: "empty", + agents: [] + ), + .skill(name: "inherited", mode: .copy), + .skill( + name: "review", + agents: [.codex, .cursor] + ), + ], + agents: [.claudeCode, .openCode] + ), + .instructions( + sections: [ + "guide", + .section(name: "rule", source: "source-2"), + ], + agents: [.codex, .geminiCLI] + ), + ], + watch: ["source-2"] +) diff --git a/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json b/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json index ff7f73e..bc4540b 100644 --- a/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json +++ b/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json @@ -48,6 +48,12 @@ "syntaxReservation": 680, "tokens": 166 }, + "MigrationDuplicateRecipients.swift.txt": { + "syntaxDepth": 28, + "syntaxNodes": 520, + "syntaxReservation": 920, + "tokens": 226 + }, "MigrationEdgeExample.swift.txt": { "syntaxDepth": 32, "syntaxNodes": 446, diff --git a/Tests/AgentsManifestTests/MigrationTests.swift b/Tests/AgentsManifestTests/MigrationTests.swift index c6b684e..f66acd4 100644 --- a/Tests/AgentsManifestTests/MigrationTests.swift +++ b/Tests/AgentsManifestTests/MigrationTests.swift @@ -8,6 +8,7 @@ import Testing private let migrationCases = [ "MigrationEmpty", "MigrationExplicitEmpty", "MigrationFields", "MigrationAliases", "MigrationRanges", "MigrationEscapes", "MigrationWidth", "MigrationAliasGap", + "MigrationDuplicateRecipients", ] func manifestFixture(_ name: String) throws -> [UInt8] { @@ -73,6 +74,71 @@ struct MigrationTests { #expect(result.declaration.components[0]["overrides"]?.elements?.count == 1) } + @Test func duplicateRecipientsReportOriginalElementsAndRoundtripTheTransformedProjection() throws + { + let input = try manifestFixture("MigrationDuplicateRecipients.migration.json") + let legacy = try StateStore.decode(Data(input), as: Declaration.self) + try legacy.validate(environment: RuntimeEnvironment()) + #expect(legacy.agents == [.codex, .claudeCode, .codex, .codex, .claudeCode]) + let result = try ManifestMigration.generate(json: input) + #expect( + result.diagnostics.map(\.pointer) == [ + "/agents/2", "/agents/3", "/agents/4", + "/instructions/agents/2", "/instructions/agents/3", + "/skills/./agents/2", "/skills/./agents/3", + "/skills/./overrides/review/agents/2", "/skills/./overrides/review/agents/3", + "/skills/./overrides/unused", "/skills/./overrides/unused/agents/1", + "/skills/a~0~1b/overrides/future/agents/1", "/sources/.", + ]) + #expect( + result.diagnostics.map(\.code) + == Array(repeating: "migration.duplicateRecipient", count: 9) + + [ + "migration.inertOverride", "migration.duplicateRecipient", + "migration.duplicateRecipient", "migration.sourceAliasRenamed", + ]) + #expect( + result.diagnostics.filter { $0.code == "migration.duplicateRecipient" }.map(\.value) + == [ + .string("codex"), .string("codex"), .string("claude-code"), + .string("gemini-cli"), .string("codex"), + .string("opencode"), .string("claude-code"), + .string("cursor"), .string("codex"), .string("gemini-cli"), .string("opencode"), + ]) + #expect( + result.diagnostics[9].value + == .object([ + "agents": .array([.string("gemini-cli"), .string("gemini-cli")]), + "mode": .string("copy"), + ])) + #expect(result.diagnostics[12].oldAlias == "." && result.diagnostics[12].newAlias == "source-2") + + var transformed = legacy + transformed.agents = [.codex, .claudeCode] + transformed.instructions?.agents = [.geminiCLI, .codex] + transformed.instructions?.sections = ["guide", "source-2:rule"] + let originalSelection = transformed.skills?.removeValue(forKey: ".") + var selection = try #require(originalSelection) + selection.agents = [.opencode, .claudeCode] + selection.overrides?["review"]?.agents = [.cursor, .codex] + selection.overrides?.removeValue(forKey: "unused") + transformed.skills?["source-2"] = selection + transformed.skills?["a~/b"]?.overrides?["future"]?.agents = [.opencode] + let source = transformed.sources.removeValue(forKey: ".") + transformed.sources["source-2"] = source + transformed.watch = ["source-2"] + let projection = try transformed.compatibilityProjection() + let doc = try DeclarationDocument(bytes: result.bytes, identity: DocumentIdentity("manifest")) + #expect(doc.declaration == projection) + #expect(result.declaration == projection) + #expect(projection.defaultAgents == ["claude-code", "codex"]) + #expect(projection.components[0]["agents"] == .array([])) + #expect(projection.components[1]["agents"] == .null) + let overrides = try #require(projection.components[2]["overrides"]?.elements) + #expect(overrides[0].record?["agents"] == .array([])) + #expect(overrides[1].record?["agents"] == .null) + } + @Test func compatibilityProjectionRetainsInheritanceAndCanonicalizesCoreRequirements() throws { let legacy = Declaration( agents: [], From 84d88d4e4b7a201fd8a5aecab31672bb48a31a90 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:28:56 +0800 Subject: [PATCH 014/171] feat: publish state transactions with verified identity and digest The scope journal records each operation's expected preimage, staged object and intended postimage before publication. Absent destinations publish with atomic no-replace rename, existing ones by exchange with preimage verification, and deletions through journal quarantine. Recovery classifies objects by recorded physical identity and digest, keeps external objects and reports unresolved conflicts, and apply rechecks preparation conditions before retention and before publication. --- Documentation/Architecture/State.md | 191 +++-- Documentation/Proposals/AgentsManifest.md | 68 +- Sources/AgentsCore/DirectoryHandle.swift | 58 +- Sources/AgentsCore/FileTransaction.swift | 715 ++++++++++++++---- Sources/AgentsCore/StateStore.swift | 3 +- Sources/AgentsCore/TransactionPaths.swift | 6 +- Sources/AgentsCore/UpdatePreconditions.swift | 190 ++++- .../InstructionOperations.swift | 11 +- Sources/AgentsSkills/SkillOperations.swift | 9 +- Sources/AgentsUpdates/UpdatePlan.swift | 1 + Sources/CPlatform/CPlatform.c | 24 + Sources/CPlatform/include/CPlatform.h | 2 + .../DirectoryHandleTests.swift | 25 + Tests/AgentsCoreTests/PublicationTests.swift | 552 ++++++++++++++ Tests/StateTestProcess/main.swift | 41 +- 15 files changed, 1612 insertions(+), 284 deletions(-) create mode 100644 Tests/AgentsCoreTests/PublicationTests.swift diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index c8ed937..36acedd 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -114,6 +114,27 @@ the any-execute-bit Boolean separately for regular files. Preparation, retention and transaction staging verify that dimension without changing stored hashes, pins or the version 1 declaration, lock and watch schemas. +## State Transaction and Recovery + +The scope's existing `transaction.json` is the sole persistent transaction owner +for target changes, declaration, lock, watch state, cache publication and pruning. +The protocol accepts regular files, directories and symbolic links independently +of the declaration format. Declaration and lock retain their state encoders; +watch state retains its fixed encoder. + +### Preparation and preconditions + +Prepare records presence, physical identity and content digest for declaration, +lock, watch state and affected targets. `UpdatePreconditions` binds final entries +and existing ancestry; state snapshots also record bytes through their digest. +Skill and instruction plans validate source snapshots, target content and +executable flags. The scope writer lock covers recovery, preparation, retention +and publication. Recovery runs first. Apply re-reads preparation conditions before +retention and again immediately before publication, including after transaction +staging. Any changed bytes, including declaration whitespace or comments in a +rendered target, or another inode with equal bytes invalidates that preparation. +Apply requires a newly prepared plan rather than rebasing an old edit. + Readers and writers serialize through `.agents.lock`. Missing scope and target ancestry is created with descriptor-relative operations; each parent directory is fsynced before target mutation, including when an interrupted creator left a @@ -128,36 +149,108 @@ message to check directory permissions and default ACLs; retries remain denied until the environment is corrected. This is a filesystem requirement, not a transaction recovery case. Existing user content and metadata are preserved. -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 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. -Symlinked journals, symlinked descendants, unregistered destinations and journals -copied or moved from another scope location are rejected before replay. All -parents are validated and their directory descriptors retained throughout -recovery. Backup and staging basenames are derived from the transaction ID, -never accepted as arbitrary journal paths. - -Backups and staged data are fsynced before applying changes. macOS `fcopyfile` -preserves original bytes, permissions, ACLs and extended attributes in backups -and restores. Data replacements inherit the existing regular file's metadata -from its backup before publication; new files default to `0600`. Final modes -are applied explicitly rather than through the umask. -`renameatx_np(RENAME_SWAP)` atomically exchanges existing directories, files and -links with their replacements; installations always retain a directory entry. -Discarding transaction-owned trees grants owner access through pinned directory -descriptors so read-only backups and staging can be removed. This never changes -the metadata of the installed or restored tree, nor of a backup still needed -for rollback; symbolic links are unlinked without following their destinations. - -After a process kill or power loss at any point, the next mutating state access -recovers one consistent generation of targets, declaration, lock, watch state and -cache references. +Journal 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 files in the project's own instructions container. The journal binds the +state directory, each used root and every destination parent to its physical +location and filesystem identity. Configured agent containers resolve at the +registry boundary; descendants open without following links. Symlinked journals, +symlinked descendants, unregistered destinations, overlapping targets and journals +copied or moved from another location are rejected before replay. Directory +descriptors remain pinned. Recovery names derive from the transaction UUID and +entry index, never from arbitrary paths in journal input. + +Each operation records its expected presence and preimage, staged object and +intended postimage before publication. Object evidence includes device, inode, +entry type, SHA-256 digest and executable status; directory snapshots include +child identities and digests. Staging and extraction scratch have recorded +ownership and are sealed before publication. The journal records per-operation +`queued`, `verifying`, `ready`, `publishing`, `applied`, `restoring`, `restored` or `cancelled` +progress, plus cleanup evidence and unresolved conflicts. File contents, +metadata, read preimages, journal records and parent directories are synchronized +in dependency order. Data replacements inherit the existing regular file's metadata. Copies +preserve modes, ACLs and extended attributes on macOS and Linux; rollback restores +the retained original object and its metadata. + +### Publication and concurrent writers + +Before changing any destination, capability checks require atomic exchange and +atomic no-replace rename. Filesystem probes use recorded private objects within +the same journal; unsupported primitives fail before any destination publication. +There is no replacing-rename fallback for managed destinations, including newly +created declaration, lock and watch files. + +| Expected destination | Publication | +| --- | --- | +| Absent | Persist staging identity and digest, then publish with `renameat2(RENAME_NOREPLACE)` on Linux or `renameatx_np(RENAME_EXCL)` on macOS. An existence conflict preserves the concurrent creator's bytes and inode. | +| Existing | Revalidate the exact read preimage and atomically exchange it with staging. Retain the displaced object, read and compare its identity and digest, and retain it as the rollback preimage. Unexpected content is a conflict preimage and cannot count as a successful replacement. | +| Deletion | Revalidate the preimage and move it without replacement into the journal's unique quarantine. Verify the quarantined object's identity and digest before confirming the operation or disposing of it. | + +Publication intent is durable before the atomic operation. The destination parent +is synchronized before `applied` is persisted. The retained preimage and the +published object must both match before a replacement is confirmed. Every +postimage is checked again before the commit marker. The scope lock excludes +cooperating writers; these publication checks also preserve objects changed by +editors that ignore the lock. + +### Recovery outcomes + +An applying journal reverses verified publications in reverse order. A committed +journal completes terminal cleanup. Recovery uses recorded physical identity and +digest, including when a process died between rename and recording `applied`. +Another inode with identical bytes remains external. Missing or changed evidence +leaves an unresolved conflict rather than establishing ownership by name or +content equality. Other verified operations can roll back while conflicted +objects and their journal remain available for owner resolution. + +Replacement rollback exchanges the retained preimage only with the verified +transaction-owned postimage and verifies the displaced object again. If an +external writer changes the destination before or during restoration, both +available versions remain and recovery stops. Deletion restoration uses atomic +no-replace rename; an occupied original name remains untouched. Creation rollback +moves only the verified published object into quarantine and verifies it there; +it never unlinks an external creator's object. A reverse rename is synchronized +even when a retry recognizes that it already happened. + +Before deleting staging, probes, scratch or preimages, the journal persists a +terminal `committed` or `rolledBack` phase with each disposal object's identity +and digest. The observed terminal journal and its parent are synchronized even +when the phase was already visible on entry. Per-entry discard intent is durable +before deletion. Cleanup verifies ownership, records descendant evidence and +accepts only already removed descendants on retry; changed or newly introduced +objects remain conflicts. Discarded directories may receive owner access through +pinned descriptors without changing the installed or restored tree's metadata. +Symbolic links are removed without following their destinations. Parent deletion +barriers also run for already absent entries. On macOS synchronization also uses +`F_FULLFSYNC` to request a storage flush. + +Recovery is repeatable across interruption. The next recovering state access +reports `CoreError.transactionRecovered` after it establishes a consistent +generation; callers retry the whole preparation. Outcome tracking belongs to the +transaction UUID: recovering a cache publication cannot mark a later combined +update committed. Failures distinguish confirmed unchanged, confirmed committed +and unresolved recovery. A commit marker alone does not establish successful +cleanup: changed recovery evidence after that marker reports unresolved recovery +and retains the journal and remaining recovery material. A committed failure +must not be described as rollback. + +### Read-only access + +Non-applying skill and instruction operations, listings, previews, watch status +and watch diff take an existing shared lock, report pending recovery and never +replay it or create state files. When the lock is absent, inspection reads and +then checks for a newly created lock or recovery marker before returning either +its result or its error. If a writer appeared, inspection discards that attempt +and retries under the shared lock. Writers create the scope lock before mutation +and never remove it. Pending journals and watch-reference cleanup markers cause +`CoreError.invalidState`; doctor reports one pending-recovery diagnostic per +affected scope and skips checks requiring a consistent generation. Explicit +multi-root instruction audits never write. Corrupt journals stop recovery without +guessing a plan. + +### Watch references and mirror locks + Mirror Git invocations pass `-c core.fsync=objects,reference,pack-metadata` and `-c core.fsyncMethod=fsync`; durability settings never rewrite configuration. Mirror configuration must be a regular file, checked before invoking Git. @@ -211,39 +304,11 @@ and source location rather than its mirror, staging or extraction paths; see [process execution and errors](Package.md#process-execution-and-errors) for the consumer error contract. -Each mutating state operation first checks for an abandoned journal under the -scope lock, then validates watch state and finishes pending ref cleanup before -proceeding. An applying journal rolls back every replacement, including watch -baselines; a committed journal -finishes cleanup. Recovery is repeatable if interrupted. Before deleting any -recovery material, both the terminal journal file and its parent directory are -fsynced, even when that phase was already visible on entry. State and backup -files and their parent directories are synced before publishing the terminal -phase. Replayed deletions sync their own parent directories even when the entry -is already absent; a visible unlink alone does not establish durability on that -target's volume. On macOS these barriers also use `F_FULLFSYNC` to request a -storage flush. - -Recovery throws `CoreError.transactionRecovered` after completing, reporting -the scope and asking the caller to retry against the recovered generation. -This includes recovery of pending watch refs even when no journal remains. -Non-applying skill and instruction operations and watch status and diff take an -existing shared lock without creating scope state files or replaying recovery. -When the scope lock is absent, inspection reads without a lock, then checks again -for a lock or pending recovery before returning either a result or an error. -If a writer appeared, inspection discards that attempt and retries under the -shared lock. Writers create the scope lock before mutation and never remove it. -Listings, previews, watch status and watch diff fail with `CoreError.invalidState` -when a transaction journal or watch-ref cleanup marker is pending. Inspection -leaves recovery material, state and retained refs untouched; pending Git ref -cleanup can also leave mirror locks that prevent fetching safely. -Each doctor instead reports one pending-recovery diagnostic per affected scope -and skips checks that require that scope's consistent state. The diagnostic -explains that the next command changing the scope will recover it. Explicit -multi-root instruction audits never write. Corrupt journals stop mutations -without guessing a recovery plan. -Tests interrupt writers between rename and parent fsync, interrupt rollback and terminal cleanup, and verify -that a competing reader waits for the recovering process's lock. +Each mutating state operation checks for an abandoned journal under the scope +lock, validates watch state and finishes pending reference cleanup before +proceeding. Recovery of pending watch references also reports +`CoreError.transactionRecovered` when no journal remains. Retained refs remain +available while any journal conflict is unresolved. ## Materialization and Installation diff --git a/Documentation/Proposals/AgentsManifest.md b/Documentation/Proposals/AgentsManifest.md index a192c6e..0d00157 100644 --- a/Documentation/Proposals/AgentsManifest.md +++ b/Documentation/Proposals/AgentsManifest.md @@ -1407,70 +1407,10 @@ syntax; editability remains a document-layer capability. ## State Transaction and Recovery -These guarantees extend [State and Source Cache](../Architecture/State.md) when -implemented. The existing journal remains the sole persistence owner. Validated -source bytes replace declaration re-encoding; lock/watch retain their encoders. -One transaction includes source, ledger, affected watch state, native artifacts, -cache retention and pruning. Source-only changes use the same protocol. - -Prepare records presence, physical identity and byte digest for the manifest, -ledger, watch state and relevant targets, plus source snapshot identities. -Under the scope writer lock, recover first, re-read/compare preconditions before -retention and again immediately before publication. A changed comment invalidates -a preview even when semantics are equal. Apply never rebases a stale source patch. -Descriptor-relative operations retain validated ancestors and reject symlinked or -unregistered paths. Staging, backups, journal records and parent directories follow -the existing fsync/metadata rules. - -### Publication and concurrent writers - -The transaction must read the exact preimage of any committed replacement. -Presence checks alone never authorize a blind overwrite. Each journal operation -records its expected presence/identity/hash, transaction-owned staging identity -and intended postimage before publication: - -| Expected destination | Atomic operation and conflict handling | -| --- | --- | -| Absent | Publish with atomic no-replace semantics: Linux `renameat2(RENAME_NOREPLACE)`, macOS `renamex_np(RENAME_EXCL)` or a descriptor-relative/link-based equivalent with the same guarantee. A concurrent creator causes an existence conflict; its bytes and identity remain untouched. Ordinary replacing rename is never a fallback. | -| Existing | Revalidate the read preimage, exchange atomically with staging and retain the displaced object. Read/compare that displaced object before confirming publication. Unexpected bytes are preserved as a conflict preimage; the operation cannot commit as a successful replacement. | -| Deletion | Move the entry into unique journal-owned quarantine without replacing another entry; verify its identity/digest before destructive cleanup. Unexpected content remains recoverable, and restoration uses no-replace semantics if the original name is occupied. | - -For an absent destination, the staged inode identity and content digest are -recorded durably before no-replace publication. After successful publication, -sync the destination's parent before marking the operation applied. Recovery -classifies the destination using that recorded physical identity and digest, -not just its filename or equal content. In a link-based implementation it also -accounts for the retained staging link until cleanup. - -If another file appeared and publication failed, the transaction rolls back its -other verified changes, preserves the concurrent file, and reports a conflict. -During migration, `agents.json` remains available or is restored through the -same protected rollback; the tool does not accept the newly appeared Swift file -as its own migration output. If a crash occurred before recording publication's -result, recovery can recognize its own published inode. Any other inode, even -with equal bytes, is external and must be preserved. Missing/changed evidence -produces an unresolved conflict rather than guessed ownership. - -Recovery verifies exchanged/quarantined preimages even if a crash preceded the -conflict marker. An unexpected preimage is never disposable staging. Restoring a -preimage may replace only the verified transaction-owned postimage; if an external -writer changed that path again, retain both versions and stop for owner resolution. -Creation rollback removes only its verified transaction-owned object; it never -unlinks a concurrent creator's file. Unsupported atomic primitives cause failure -before mutation. These rules also protect creation/replacement of the ledger and -other transaction destinations; there is no unguarded creation path. - -### Recovery outcomes and approvals - -An applying journal restores the previous verified generation; a committed journal -finishes cleanup. Conflicted journals retain all data needed for resolution. -Backup/staging cleanup requires both a durable terminal phase and verified -ownership. Read-only operations report pending recovery and never replay it. -Recovery remains repeatable across interruption and reports -`CoreError.transactionRecovered`; consumers retry preparation. Outcome reporting -distinguishes unchanged, committed and unresolved recovery, including failures -after the commit marker. The scope lock serializes cooperating tools; the -publication rules protect retained data when external editors ignore that lock. +[State Transaction and Recovery](../Architecture/State.md#state-transaction-and-recovery) +owns the current publication, precondition and recovery guarantees. + +### Approvals Approval identity covers declarations, commands and shipped content, excluding comments and formatting. Approval is machine-local; a copied ledger disposition diff --git a/Sources/AgentsCore/DirectoryHandle.swift b/Sources/AgentsCore/DirectoryHandle.swift index 707e528..8b5e74f 100644 --- a/Sources/AgentsCore/DirectoryHandle.swift +++ b/Sources/AgentsCore/DirectoryHandle.swift @@ -121,12 +121,53 @@ final class DirectoryHandle { ? platform_exchange(descriptor, name, destination) : renameat(descriptor, name, descriptor, destination) guard result == 0 else { + if swap, errno == ENOSYS || errno == ENOTSUP || errno == EINVAL { + throw CoreError.unsupported("atomic exchange is required: \(errno)") + } throw CoreError.invalidState("cannot replace \(destination): \(errno)") } try afterRename() try sync() } + func renameExclusive( + _ name: String, to destination: String, afterRename: () throws -> Void = {} + ) throws { + guard platform_rename_exclusive(descriptor, name, destination) == 0 else { + let code = errno + if code == EEXIST || code == ENOTEMPTY { + throw CoreError.invalidState("transaction destination already exists: \(destination)") + } + if code == ENOSYS || code == ENOTSUP || code == EINVAL { + throw CoreError.unsupported("atomic no-replace publication is required: \(code)") + } + throw CoreError.invalidState("cannot publish exclusively \(destination): \(code)") + } + try afterRename() + try sync() + } + + /// Checks flag admission without creating any object. FileTransaction also probes + /// the actual filesystem with journal-owned objects before publishing targets. + static func requireAtomicRenames(at destination: URL) throws { + var ancestor = destination.deletingLastPathComponent() + while !FileManager.default.fileExists(atPath: ancestor.path), ancestor.path != "/" { + ancestor.deleteLastPathComponent() + } + let directory = try DirectoryHandle(at: ancestor.resolvingSymlinksInPath()) + let prefix = ".agents-probe-" + UUID().uuidString + for exclusive in [false, true] { + let result = + exclusive + ? platform_rename_exclusive(directory.descriptor, prefix + ".a", prefix + ".b") + : platform_exchange(directory.descriptor, prefix + ".a", prefix + ".b") + guard result < 0, errno == ENOENT else { + throw CoreError.unsupported( + "atomic exchange and no-replace publication are required: \(errno)") + } + } + } + func makeDirectory(_ name: String) throws { if try info(name) != nil { try FileSystem.requireAccess( @@ -196,9 +237,16 @@ final class DirectoryHandle { try sync() } - func read(_ name: String) throws -> Data { + func read(_ name: String, matching expected: stat? = nil) throws -> Data { let file = try regularFile(name) defer { close(file) } + var before = stat() + guard fstat(file, &before) == 0 else { + throw CoreError.invalidState("cannot identify opened file: \(name)") + } + if var expected, !platform_same_generation(&expected, &before) { + throw CoreError.invalidState("file changed before reading: \(name)") + } var data = Data() var buffer = [UInt8](repeating: 0, count: 65536) while true { @@ -209,7 +257,13 @@ final class DirectoryHandle { errno, at: url.appendingPathComponent(name), otherwise: .invalidState("cannot read \(name)")) } - if count == 0 { return data } + if count == 0 { + var after = stat() + guard fstat(file, &after) == 0, platform_same_generation(&before, &after) else { + throw CoreError.invalidState("file changed while reading: \(name)") + } + return data + } data.append(contentsOf: buffer.prefix(count)) } } diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 57c063b..8cecb66 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -1,12 +1,26 @@ +import CPlatform import Foundation /// A durable undo journal covers targets, scope state files and cache pruning. /// The scope writer lock must be held through planning, commit and recovery. package final class FileTransaction { + private enum Progress: String, Codable { + case queued, verifying, ready, publishing, applied, restoring, restored, cancelled + } private struct Entry: Codable { var path: String var existed: Bool var replacement: Bool + var preimage: FileSnapshot? + var parentIdentity = "" + var staging: FileSnapshot? + var staged: FileSnapshot? + var work: FileSnapshot? + var probes: [FileSnapshot] = [] + var progress: Progress = .queued + var cleanup: [String: FileSnapshot] = [:] + var discarding = false + var conflict = false var name: String { String(path.split(separator: "/").last!) } } private struct Journal: Codable { @@ -27,9 +41,13 @@ package final class FileTransaction { } private let store: StateStore private let checkpoint: (String) throws -> Void + package var validateBeforePublication: () throws -> Void = {} + var atomicPreflight: (URL) throws -> Void = { try DirectoryHandle.requireAtomicRenames(at: $0) } private let outcome: TransactionOutcome private var entries: [Entry] = [] private var contents: [Content] = [] + private var preconditions: [PathIdentity] = [] + private var statePrecondition: StatePrecondition? package init( store: StateStore, outcome: TransactionOutcome = TransactionOutcome(), @@ -54,7 +72,15 @@ package final class FileTransaction { guard !entries.contains(where: { $0.path == path }) else { throw CoreError.invalidState("duplicate transaction destination") } - entries.append(Entry(path: path, existed: false, replacement: content != nil || data != nil)) + if statePrecondition == nil { statePrecondition = try StatePrecondition(store: store) } + let identity = try PathIdentity(destination) + let preimage = try FileSnapshot.read(at: destination) + try identity.validate() + entries.append( + Entry( + path: path, existed: preimage != nil, replacement: content != nil || data != nil, + preimage: preimage)) + preconditions.append(identity) contents.append( Content( url: content, link: link, data: data, expectedHash: expectedHash, @@ -74,9 +100,16 @@ package final class FileTransaction { package func commit() throws { guard let directory = try store.openDirectoryIfPresent(), - try directory.info("transaction.json") == nil - else { - throw CoreError.invalidState("transaction recovery is required") + try directory.info("transaction.json") == nil, try directory.info("transaction.new") == nil + else { throw CoreError.invalidState("transaction recovery is required") } + guard !entries.isEmpty else { return } + for identity in preconditions { try identity.validate() } + try statePrecondition?.validate() + try validateBeforePublication() + // No destination, ancestry or journal mutation precedes capability checks. + for entry in entries { + let destination = try destinationURL(entry.path) + try atomicPreflight(destination) } let paths = TransactionPaths(store: store) var roots: [String: DirectoryHandle] = [:] @@ -90,14 +123,15 @@ package final class FileTransaction { try paths.parent(for: $0.path, roots: roots, create: true, checkpoint: checkpoint) } try Self.validateDestinations(entries, parents: parents) + for index in entries.indices { + entries[index].parentIdentity = try parents[index].identity + try Self.requirePreimage(entries[index], parent: parents[index]) + } if entries.contains(where: { ["state/agents.watch", "state/agents.resolved"].contains($0.path) }) { try SourceCache(store: store, checkpoint: checkpoint).beginWatchReferenceUpdate() } - for index in entries.indices { - entries[index].existed = try parents[index].info(entries[index].name) != nil - } var journal = Journal( id: UUID(), scope: try directory.identity, roots: try roots.mapValues { try $0.identity }, phase: .preparing, entries: entries) @@ -105,96 +139,65 @@ package final class FileTransaction { do { try Self.persist(journal, directory: directory, checkpoint: checkpoint) try checkpoint("journal.preparing") - for (index, entry) in entries.enumerated() { - let parent = parents[index] - let backup = Self.temporaryName(journal, index, "old") - let staged = Self.temporaryName(journal, index, "new") - if entry.existed { try parent.copy(backup, from: parent, named: entry.name) } - try checkpoint("backup.\(index)") - var content = contents[index] - if let prepare = content.prepare { - let work = Self.temporaryName(journal, index, "work") - try parent.makeDirectory(work) - try checkpoint("prepare.\(index).directory") - let root = parent.url.appendingPathComponent(work) - let source = try prepare(root) - guard PathSafety.isContained(source.resolvingSymlinksInPath(), in: root) else { - throw CoreError.unsafePath("prepared content escapes transaction staging") - } - content.url = source - content.expectedHash = "sha256:" + (try FileHash.folderHash(source)) - content.executableFlags = try FileHash.executableFlags(source) - try checkpoint("prepare.\(index).ready") + var probedDevices: Set = [] + for index in entries.indices { + var info = stat() + guard fstat(parents[index].descriptor, &info) == 0 else { + throw CoreError.invalidState("cannot identify publication filesystem") } - if let data = content.data { - try parent.write(staged, data: data, preservingMetadataOf: entry.existed ? backup : nil) - try checkpoint("stage.\(index).written") - } else if let source = content.url { - if content.link { - try parent.link( - staged, destination: Self.linkDestination(source, parent: parent.url, store: store)) - } else { - try Self.validateCopy(source) - let origin = source.resolvingSymlinksInPath() - try parent.copy( - staged, from: DirectoryHandle(at: origin.deletingLastPathComponent()), - named: origin.lastPathComponent, - checkpoint: { try checkpoint("stage.\(index).copy.\($0)") }) - } + if probedDevices.insert(UInt64(info.st_dev)).inserted { + try probeAtomics(index, journal: &journal, directory: directory, parent: parents[index]) } - try checkpoint("stage.\(index).ready") - if let expectedHash = content.expectedHash { - let hash: String - if content.link, let source = content.url { - hash = try FileHash.folderHash(source) - } else if content.data == nil { - hash = try FileHash.folderHash(parent.child(staged)) - } else { - hash = try FileHash.sha256Hex(data: parent.read(staged)) - } - guard "sha256:" + hash == expectedHash else { - throw CoreError.invalidState("staged content digest mismatch") - } - try checkpoint("stage.\(index).verified") - } - if let flags = content.executableFlags { - let actual = - try content.link - ? FileHash.executableFlags(content.url!) - : FileHash.executableFlags(parent.child(staged)) - guard actual == flags else { - throw CoreError.invalidState("staged content executable mode mismatch") + } + for index in entries.indices { + do { + try stage(index, journal: &journal, directory: directory, parent: parents[index]) + } catch { + // A live producer can seal its incomplete scratch on failure. Recovery + // after process death uses only evidence already persisted by that producer. + if [.queued, .verifying].contains(journal.entries[index].progress) { + try? sealIncompleteScratch( + index, journal: &journal, directory: directory, parent: parents[index]) } + throw error } - try checkpoint("stage.\(index)") + } + try checkpoint("publication.preconditions") + try statePrecondition?.validate() + for identity in preconditions { try identity.validate() } + try validateBeforePublication() + for (index, entry) in journal.entries.enumerated() { + try Self.requirePreimage(entry, parent: parents[index]) } journal.phase = .applying outcome.disposition = .recoveryRequired try Self.persist(journal, directory: directory, checkpoint: checkpoint) try checkpoint("journal.applying") - for (index, entry) in entries.enumerated() { - let parent = parents[index] - if entry.replacement { - try parent.rename( - Self.temporaryName(journal, index, "new"), to: entry.name, swap: entry.existed - ) { - try checkpoint("replace.\(index).renamed") - } - } else if entry.existed { - try parent.rename(entry.name, to: Self.temporaryName(journal, index, "removed")) { - try checkpoint("replace.\(index).renamed") - } - } - try checkpoint("replace.\(index)") + for index in entries.indices { + try preconditions[index].validate() + try publish(index, journal: &journal, directory: directory, parent: parents[index]) } + try validateRemainingState(journal) + try Self.verifyFinal(journal, parents: parents) + try Self.prepareCleanup(&journal, parents: parents) journal.phase = .committed + try checkpoint("journal.committing") try Self.persist(journal, directory: directory, checkpoint: checkpoint) outcome.disposition = .committed try checkpoint("journal.committed") - try Self.cleanup(journal, directory: directory, parents: parents, checkpoint: checkpoint) + try Self.cleanup(&journal, directory: directory, parents: parents, checkpoint: checkpoint) } catch { do { _ = try Self.recover(store: store, outcome: outcome) + var retained = try directory.info("transaction.json") != nil + for index in journal.entries.indices { + for suffix in Self.scratchSuffixes { + if try parents[index].info(Self.temporaryName(journal, index, suffix)) != nil { + retained = true + } + } + } + if retained { outcome.disposition = .recoveryRequired } } catch { outcome.disposition = .recoveryRequired } @@ -202,13 +205,238 @@ package final class FileTransaction { } } - /// Recovers only after validating and pinning every parent in the journal. + private func probeAtomics( + _ index: Int, journal: inout Journal, directory: DirectoryHandle, parent: DirectoryHandle + ) throws { + let first = Self.temporaryName(journal, index, "probe-a") + let second = Self.temporaryName(journal, index, "probe-b") + let third = Self.temporaryName(journal, index, "probe-c") + for name in [first, second] { + try parent.write(name, data: Data()) + guard let snapshot = try FileSnapshot.read(name, from: parent) else { + throw CoreError.invalidState("missing atomic capability probe") + } + journal.entries[index].probes.append(snapshot) + try Self.persist(journal, directory: directory, checkpoint: checkpoint) + try checkpoint("atomic.\(index).created.\(journal.entries[index].probes.count)") + } + try parent.rename(first, to: second, swap: true) { + try checkpoint("atomic.\(index).exchanged") + } + guard platform_rename_exclusive(parent.descriptor, first, second) != 0, + errno == EEXIST || errno == ENOTEMPTY + else { throw CoreError.unsupported("atomic no-replace publication is required") } + try parent.renameExclusive(first, to: third) { + try checkpoint("atomic.\(index).exclusive") + } + let probes = journal.entries[index].probes + guard try FileSnapshot.read(second, from: parent) == probes[0], + try FileSnapshot.read(third, from: parent) == probes[1], + try parent.info(first) == nil + else { throw Self.conflict(journal.entries[index], "atomic probe ownership changed") } + try checkpoint("atomic.\(index).verified") + } + + private func destinationURL(_ path: String) throws -> URL { + let paths = TransactionPaths(store: store) + let components = try paths.components(path) + // Root resolution is configuration-owned and does not create directories. + return try paths.rootURL(components.root).appendingPathComponent( + components.descendants.joined(separator: "/")) + } + + private func stage( + _ index: Int, journal: inout Journal, directory: DirectoryHandle, parent: DirectoryHandle + ) throws { + let entry = journal.entries[index] + let staged = Self.temporaryName(journal, index, "new") + try entry.preimage?.synchronize(entry.name, from: parent) + try checkpoint("stage.\(index).preimage") + var content = contents[index] + if let prepare = content.prepare { + let work = Self.temporaryName(journal, index, "work") + try parent.makeDirectory(work) + journal.entries[index].work = try Self.mutableSnapshot( + work, from: parent, previous: journal.entries[index].work) + try Self.persist(journal, directory: directory, checkpoint: checkpoint) + try checkpoint("prepare.\(index).directory") + let root = parent.url.appendingPathComponent(work) + let source = try prepare(root) + guard PathSafety.isContained(source.resolvingSymlinksInPath(), in: root) else { + throw CoreError.unsafePath("prepared content escapes transaction staging") + } + journal.entries[index].work = try Self.mutableSnapshot( + work, from: parent, previous: journal.entries[index].work) + try Self.persist(journal, directory: directory, checkpoint: checkpoint) + content.url = source + content.expectedHash = "sha256:" + (try FileHash.folderHash(source)) + content.executableFlags = try FileHash.executableFlags(source) + try checkpoint("prepare.\(index).ready") + } + if let data = content.data { + try parent.write( + staged, data: data, + preservingMetadataOf: entry.preimage?.identity.kind == UInt32(S_IFREG) ? entry.name : nil) + journal.entries[index].staging = try FileSnapshot.read(staged, from: parent) + try Self.persist(journal, directory: directory, checkpoint: checkpoint) + try checkpoint("stage.\(index).written") + } else if let source = content.url { + if content.link { + try parent.link( + staged, destination: Self.linkDestination(source, parent: parent.url, store: store)) + } else { + try Self.validateCopy(source) + let origin = source.resolvingSymlinksInPath() + try parent.copy( + staged, from: DirectoryHandle(at: origin.deletingLastPathComponent()), + named: origin.lastPathComponent, + checkpoint: { step in + journal.entries[index].staging = try Self.mutableSnapshot( + staged, from: parent, previous: journal.entries[index].staging) + try Self.persist(journal, directory: directory, checkpoint: checkpoint) + try checkpoint("stage.\(index).copy.\(step)") + }) + } + } + // Completed construction remains private and mutable until verification seals it. + if entry.replacement { + journal.entries[index].staging = try Self.mutableSnapshot( + staged, from: parent, previous: journal.entries[index].staging) + } + journal.entries[index].progress = .verifying + try Self.persist(journal, directory: directory, checkpoint: checkpoint) + try checkpoint("stage.\(index).ready") + if let data = content.data, try parent.read(staged) != data { + throw CoreError.invalidState("staged content bytes mismatch") + } + if let expectedHash = content.expectedHash { + let hash: String + if content.link, let source = content.url { + hash = try FileHash.folderHash(source) + } else if content.data == nil { + hash = try FileHash.folderHash(parent.child(staged)) + } else { + hash = try FileHash.sha256Hex(data: parent.read(staged)) + } + guard "sha256:" + hash == expectedHash else { + throw CoreError.invalidState("staged content digest mismatch") + } + try checkpoint("stage.\(index).verified") + } + if let flags = content.executableFlags { + let actual = + try content.link + ? FileHash.executableFlags(content.url!) : FileHash.executableFlags(parent.child(staged)) + guard actual == flags else { + throw CoreError.invalidState("staged content executable mode mismatch") + } + } + guard try FileSnapshot.read(staged, from: parent) == journal.entries[index].staging else { + throw CoreError.invalidState("staged content changed during verification") + } + journal.entries[index].staged = journal.entries[index].staging + journal.entries[index].progress = .ready + try Self.persist(journal, directory: directory, checkpoint: checkpoint) + try checkpoint("stage.\(index).sealed") + try checkpoint("stage.\(index)") + } + + private static func mutableSnapshot( + _ name: String, from parent: DirectoryHandle, previous: FileSnapshot? + ) throws -> FileSnapshot? { + let actual = try FileSnapshot.read(name, from: parent) + if let previous, previous.identity != actual?.identity { + throw CoreError.invalidState("transaction scratch identity changed: \(name)") + } + return actual + } + + private func sealIncompleteScratch( + _ index: Int, journal: inout Journal, directory: DirectoryHandle, parent: DirectoryHandle + ) throws { + if let work = journal.entries[index].work { + journal.entries[index].work = try Self.mutableSnapshot( + Self.temporaryName(journal, index, "work"), from: parent, previous: work) + } + if let staging = journal.entries[index].staging { + let actual = try Self.mutableSnapshot( + Self.temporaryName(journal, index, "new"), from: parent, previous: staging) + if journal.entries[index].progress == .verifying, + actual.map({ staging.sameObjects(as: $0) }) != true + { + throw CoreError.invalidState("staging ownership changed during verification") + } + journal.entries[index].staging = actual + } + try Self.persist(journal, directory: directory, checkpoint: { _ in }) + } + + private func publish( + _ index: Int, journal: inout Journal, directory: DirectoryHandle, parent: DirectoryHandle + ) throws { + var entry = journal.entries[index] + let staged = Self.temporaryName(journal, index, "new") + let backup = Self.temporaryName(journal, index, "old") + try Self.requirePreimage(entry, parent: parent) + guard try FileSnapshot.read(staged, from: parent) == entry.staged, + !entry.replacement || entry.staged != nil + else { throw Self.conflict(entry, "staged object changed") } + entry.progress = .publishing + journal.entries[index] = entry + try Self.persist(journal, directory: directory, checkpoint: checkpoint) + try checkpoint("publish.\(index).intent") + try validateRemainingState(journal) + try Self.requirePreimage(entry, parent: parent) + try checkpoint("publish.\(index).validated") + if entry.replacement { + if entry.existed { + try parent.rename(staged, to: entry.name, swap: true) { + try checkpoint("replace.\(index).renamed") + } + try checkpoint("publish.\(index).synced") + guard try FileSnapshot.read(staged, from: parent) == entry.preimage else { + throw Self.conflict(entry, "displaced preimage changed") + } + try checkpoint("publish.\(index).displaced") + try parent.renameExclusive(staged, to: backup) { + try checkpoint("publish.\(index).retained") + } + } else { + try parent.renameExclusive(staged, to: entry.name) { + try checkpoint("replace.\(index).renamed") + } + try checkpoint("publish.\(index).synced") + } + } else if entry.existed { + try parent.renameExclusive(entry.name, to: backup) { + try checkpoint("replace.\(index).renamed") + } + try checkpoint("publish.\(index).synced") + guard try FileSnapshot.read(backup, from: parent) == entry.preimage else { + throw Self.conflict(entry, "quarantined preimage changed") + } + } + guard try FileSnapshot.read(entry.name, from: parent) == entry.staged else { + throw Self.conflict(entry, "published object changed") + } + journal.entries[index].progress = .applied + try Self.persist(journal, directory: directory, checkpoint: checkpoint) + try checkpoint("replace.\(index)") + } + + private func validateRemainingState(_ journal: Journal) throws { + let published = Set( + journal.entries.filter { + $0.progress == .applied && $0.path.hasPrefix("state/") + }.map(\.name)) + try statePrecondition?.validate(excluding: published) + } + + /// Recovers only after validating and pinning every root, parent and object record. package static func recover( store: StateStore, outcome: TransactionOutcome? = nil, checkpoint: (String) throws -> Void = { _ in } - ) - throws -> Bool - { + ) throws -> Bool { guard let directory = try store.openDirectoryIfPresent() else { return false } guard try directory.info("transaction.json") != nil else { guard try directory.info("transaction.new") != nil else { return false } @@ -216,16 +444,65 @@ package final class FileTransaction { try directory.remove("transaction.new") return true } - var journal = try StateStore.decode(directory.read("transaction.json"), as: Journal.self) + var journal: Journal + do { + journal = try StateStore.decode(directory.read("transaction.json"), as: Journal.self) + } catch { + outcome?.disposition = .recoveryRequired + throw CoreError.invalidState("unresolved transaction journal: \(error)") + } + do { + let parents = try recoveryParents(journal, store: store, directory: directory) + if try directory.info("transaction.new") != nil { _ = try directory.read("transaction.new") } + if journal.phase == .applying { + var conflicts: [String] = [] + for index in journal.entries.indices.reversed() { + do { + try rollback( + index, journal: &journal, directory: directory, parent: parents[index], + checkpoint: checkpoint) + journal.entries[index].conflict = false + } catch { + journal.entries[index].conflict = true + conflicts.append("\(journal.entries[index].path): \(error)") + } + try persist(journal, directory: directory, checkpoint: checkpoint) + } + guard conflicts.isEmpty else { + throw CoreError.invalidState( + "unresolved transaction conflicts: " + conflicts.joined(separator: "; ")) + } + } + if journal.phase == .applying || journal.phase == .preparing { + if journal.phase == .applying { try verifyFinal(journal, parents: parents, rollback: true) } + try prepareCleanup(&journal, parents: parents) + journal.phase = .rolledBack + try persist(journal, directory: directory, checkpoint: checkpoint) + } + try verifyFinal(journal, parents: parents, rollback: journal.phase == .rolledBack) + try cleanup(&journal, directory: directory, parents: parents, checkpoint: checkpoint) + if outcome?.journalID == journal.id { + outcome?.disposition = journal.phase == .committed ? .committed : .unchanged + } + return true + } catch { + if outcome?.journalID == journal.id { outcome?.disposition = .recoveryRequired } + throw error + } + } + + private static func recoveryParents( + _ journal: Journal, store: StateStore, directory: DirectoryHandle + ) throws -> [DirectoryHandle] { guard journal.scope == (try directory.identity) else { throw CoreError.invalidState("transaction journal belongs to another scope location") } let paths = TransactionPaths(store: store) - var roots: [String: DirectoryHandle] = [:] let keys = try Set(journal.entries.map { try paths.components($0.path).root }) guard keys == Set(journal.roots.keys) else { throw CoreError.invalidState("invalid transaction roots") } + var roots: [String: DirectoryHandle] = [:] for key in keys { let root = try paths.root(key) guard try root.identity == journal.roots[key] else { @@ -236,68 +513,220 @@ package final class FileTransaction { let parents = try journal.entries.map { try paths.parent(for: $0.path, roots: roots) } try validateDestinations(journal.entries, parents: parents) for (index, entry) in journal.entries.enumerated() { - if journal.phase == .applying, entry.existed, - try parents[index].info(temporaryName(journal, index, "old")) == nil - { - throw CoreError.invalidState("missing transaction backup") - } - } - // Validate the journal's scratch file before any recovery mutation as well. - if try directory.info("transaction.new") != nil { _ = try directory.read("transaction.new") } - if journal.phase == .applying { - for (index, entry) in journal.entries.enumerated().reversed() { - let parent = parents[index] - if entry.existed { - let restore = temporaryName(journal, index, "restore") - try parent.remove(restore) - try parent.copy(restore, from: parent, named: temporaryName(journal, index, "old")) - try parent.rename(restore, to: entry.name, swap: try parent.info(entry.name) != nil) { + guard entry.parentIdentity == (try parents[index].identity), + entry.existed == (entry.preimage != nil), + entry.cleanup.keys.allSatisfy({ scratchSuffixes.contains($0) }) + else { throw conflict(entry, "invalid parent or object evidence") } + let allowed: [Progress] + switch journal.phase { + case .preparing: allowed = [.queued, .verifying, .ready] + case .applying: allowed = [.ready, .publishing, .applied, .restoring, .restored, .cancelled] + case .committed: allowed = [.applied] + case .rolledBack: allowed = [.queued, .verifying, .ready, .restored, .cancelled] + } + guard allowed.contains(entry.progress) else { + throw conflict(entry, "operation progress contradicts the journal phase") + } + for snapshot in [entry.preimage, entry.staging, entry.staged, entry.work].compactMap({ $0 }) + + Array(entry.cleanup.values) + entry.probes + { try snapshot.validate() } + if ![.queued, .verifying].contains(entry.progress), entry.replacement, entry.staged == nil { + throw conflict(entry, "missing staged identity") + } + } + return parents + } + + private static func rollback( + _ index: Int, journal: inout Journal, directory: DirectoryHandle, parent: DirectoryHandle, + checkpoint: (String) throws -> Void + ) throws { + let entry = journal.entries[index] + if [.queued, .verifying, .ready, .cancelled].contains(entry.progress) { + journal.entries[index].progress = .cancelled + } else if entry.progress != .restored { + journal.entries[index].progress = .restoring + try persist(journal, directory: directory, checkpoint: checkpoint) + try checkpoint("restore.\(index).intent") + let target = try FileSnapshot.read(entry.name, from: parent) + let stagedName = temporaryName(journal, index, "new") + let backup = temporaryName(journal, index, "old") + let staged = try FileSnapshot.read(stagedName, from: parent) + let old = try FileSnapshot.read(backup, from: parent) + if let preimage = entry.preimage { + if target == preimage { + // Before publication, or after an interrupted restoration exchange. + guard !entry.replacement || staged == entry.staged || old == entry.staged else { + throw conflict(entry, "missing transaction postimage") + } + } else if entry.replacement { + guard let postimage = entry.staged, target == postimage else { + throw conflict(entry, "recovery destination is external or changed") + } + let original: String + if staged == preimage, old == nil { + original = stagedName + } else if old == preimage, staged == nil { + original = backup + } else { + throw conflict(entry, "missing or changed displaced preimage") + } + try checkpoint("restore.\(index).validated") + try parent.rename(original, to: entry.name, swap: true) { try checkpoint("restore.\(index).renamed") } - try parent.remove(restore) + guard try FileSnapshot.read(original, from: parent) == postimage, + try FileSnapshot.read(entry.name, from: parent) == preimage + else { throw conflict(entry, "recovery exchange displaced an external object") } } else { - try parent.remove(entry.name) { try checkpoint("restore.\(index).remove.\($0)") } + guard target == nil, old == preimage else { + throw conflict(entry, "quarantine or recovery destination changed") + } + try checkpoint("restore.\(index).validated") + try parent.renameExclusive(backup, to: entry.name) { + try checkpoint("restore.\(index).renamed") + } + guard try FileSnapshot.read(entry.name, from: parent) == preimage else { + throw conflict(entry, "restored preimage changed") + } } - try checkpoint("restore.\(index)") + } else if let postimage = entry.staged { + let removed = temporaryName(journal, index, "removed") + let quarantined = try FileSnapshot.read(removed, from: parent) + if staged == postimage, quarantined == nil, target != postimage { + // No-replace never consumed staging; a concurrent creator is untouched. + journal.entries[index].progress = .cancelled + } else if target == postimage, staged == nil, quarantined == nil { + try checkpoint("restore.\(index).validated") + try parent.renameExclusive(entry.name, to: removed) { + try checkpoint("restore.\(index).remove.unlinked") + } + guard try FileSnapshot.read(removed, from: parent) == postimage else { + throw conflict(entry, "creation rollback quarantined an external object") + } + } else if quarantined != postimage || staged != nil || target == postimage { + throw conflict(entry, "missing or changed creation evidence") + } + try parent.sync() + try checkpoint("restore.\(index).remove.synced") + } + if journal.entries[index].progress != .cancelled { + journal.entries[index].progress = .restored } } - if journal.phase == .applying || journal.phase == .preparing { - journal.phase = .rolledBack - try persist(journal, directory: directory, checkpoint: checkpoint) + // A visible reverse rename is not a durability barrier, including on retry. + try parent.sync() + try checkpoint("restore.\(index).synced") + try persist(journal, directory: directory, checkpoint: checkpoint) + try checkpoint("restore.\(index)") + } + + private static func requirePreimage(_ entry: Entry, parent: DirectoryHandle) throws { + guard try FileSnapshot.read(entry.name, from: parent) == entry.preimage else { + throw conflict(entry, "preparation is stale; prepare again") } - try cleanup(journal, directory: directory, parents: parents, checkpoint: checkpoint) - if outcome?.journalID == journal.id { - outcome?.disposition = journal.phase == .committed ? .committed : .unchanged + } + + private static func verifyFinal( + _ journal: Journal, parents: [DirectoryHandle], rollback: Bool = false + ) throws { + for (index, entry) in journal.entries.enumerated() { + try requireParent(entry, parent: parents[index]) + if rollback { + if entry.progress == .restored, entry.preimage != nil { + try requirePreimage(entry, parent: parents[index]) + } else if let staged = entry.staged, + try FileSnapshot.read(entry.name, from: parents[index])?.identity == staged.identity + { + throw conflict(entry, "creation is still published") + } + } else { + guard try FileSnapshot.read(entry.name, from: parents[index]) == entry.staged else { + throw conflict(entry, "committed destination changed") + } + } } - return true } - private static func validateDestinations(_ entries: [Entry], parents: [DirectoryHandle]) throws { - var paths: [URL] = [] - for (index, entry) in entries.enumerated() { - let path = parents[index].url.appendingPathComponent(entry.name) - guard - !paths.contains(where: { - PathSafety.isContained(path, in: $0) || PathSafety.isContained($0, in: path) - }) - else { - throw CoreError.invalidState("overlapping transaction destinations") + private static func requireParent(_ entry: Entry, parent: DirectoryHandle) throws { + guard try DirectoryHandle(at: parent.url).identity == entry.parentIdentity else { + throw conflict(entry, "destination parent changed") + } + } + + private static func prepareCleanup(_ journal: inout Journal, parents: [DirectoryHandle]) throws { + for index in journal.entries.indices { + let entry = journal.entries[index] + var cleanup: [String: FileSnapshot] = [:] + for suffix in scratchSuffixes { + guard + let actual = try FileSnapshot.read( + temporaryName(journal, index, suffix), from: parents[index]) + else { continue } + let candidates: [FileSnapshot?] + switch suffix { + case "probe-a", "probe-b", "probe-c": candidates = entry.probes.map(Optional.some) + case "work": candidates = [entry.work] + case "removed": candidates = [entry.staged] + case "old": candidates = [entry.preimage, entry.staged] + default: candidates = [entry.staged ?? entry.staging, entry.preimage] + } + guard candidates.contains(where: { $0 == actual }) else { + throw conflict(entry, "unverified recovery object: \(suffix)") + } + cleanup[suffix] = actual } - paths.append(path) + if journal.phase == .preparing { + if let staged = entry.staging, cleanup["new"] != staged { + throw conflict(entry, "missing staging evidence") + } + } + if entry.progress == .cancelled, let staged = entry.staged, cleanup["new"] != staged { + throw conflict(entry, "missing unpublished staging evidence") + } + if let work = entry.work, cleanup["work"] != work { + throw conflict(entry, "missing scratch evidence") + } + guard entry.probes.allSatisfy({ cleanup.values.contains($0) }) else { + throw conflict(entry, "missing atomic probe evidence") + } + journal.entries[index].cleanup = cleanup } } private static func cleanup( - _ journal: Journal, directory: DirectoryHandle, parents: [DirectoryHandle], + _ journal: inout Journal, directory: DirectoryHandle, parents: [DirectoryHandle], checkpoint: (String) throws -> Void ) throws { - // A visible terminal phase may have been renamed but not synced by a killed - // writer. Make that observed generation durable before deleting any backup. + try requireScope(journal, directory: directory) try directory.syncFile("transaction.json") try checkpoint("journal.terminalSynced") - for (index, _) in journal.entries.enumerated() { - for suffix in ["old", "new", "removed", "restore", "work"] { - try parents[index].remove(temporaryName(journal, index, suffix)) + try requireScope(journal, directory: directory) + // Validate the whole disposal plan before deleting the first resource. + for (index, entry) in journal.entries.enumerated() { + try requireParent(entry, parent: parents[index]) + for suffix in scratchSuffixes { + let actual = try FileSnapshot.read( + temporaryName(journal, index, suffix), from: parents[index]) + if let expected = entry.cleanup[suffix] { + guard + entry.discarding ? actual.map(expected.containsRemaining) ?? true : actual == expected + else { throw conflict(entry, "cleanup evidence changed: \(suffix)") } + } else if actual != nil { + throw conflict(entry, "unrecorded cleanup object: \(suffix)") + } + } + } + for index in journal.entries.indices { + journal.entries[index].discarding = true + try persist(journal, directory: directory, checkpoint: checkpoint) + try checkpoint("cleanup.\(index).intent") + try requireScope(journal, directory: directory) + try requireParent(journal.entries[index], parent: parents[index]) + for suffix in journal.entries[index].cleanup.keys.sorted() { + try journal.entries[index].cleanup[suffix]!.remove( + temporaryName(journal, index, suffix), from: parents[index], + checkpoint: { try checkpoint("cleanup.\(index).\(suffix).\($0)") }) } try checkpoint("cleanup.\(index)") } @@ -306,10 +735,37 @@ package final class FileTransaction { try checkpoint("journal.removed") } + private static func requireScope(_ journal: Journal, directory: DirectoryHandle) throws { + guard try DirectoryHandle(at: directory.url).identity == journal.scope else { + throw CoreError.invalidState("transaction scope identity changed") + } + } + + private static func validateDestinations(_ entries: [Entry], parents: [DirectoryHandle]) throws { + var paths: [URL] = [] + for (index, entry) in entries.enumerated() { + let path = parents[index].url.appendingPathComponent(entry.name) + guard + !paths.contains(where: { + PathSafety.isContained(path, in: $0) || PathSafety.isContained($0, in: path) + }) + else { throw CoreError.invalidState("overlapping transaction destinations") } + paths.append(path) + } + } + + private static func conflict(_ entry: Entry, _ reason: String) -> CoreError { + .invalidState("transaction conflict at \(entry.path): \(reason)") + } + private static func temporaryName(_ journal: Journal, _ index: Int, _ suffix: String) -> String { ".agents-\(journal.id.uuidString)-\(index).\(suffix)" } + private static let scratchSuffixes = [ + "old", "new", "removed", "work", "probe-a", "probe-b", "probe-c", + ] + private static func persist( _ journal: Journal, directory: DirectoryHandle, checkpoint: (String) throws -> Void @@ -320,7 +776,6 @@ package final class FileTransaction { try checkpoint("journal.\(journal.phase.rawValue).renamed") } } - package static func linkDestination(_ source: URL, parent: URL, store: StateStore) -> String { let root = (store.scope == .project ? store.environment.projectDirectory : store.directory) .resolvingSymlinksInPath() diff --git a/Sources/AgentsCore/StateStore.swift b/Sources/AgentsCore/StateStore.swift index f2cd90e..fe35ed4 100644 --- a/Sources/AgentsCore/StateStore.swift +++ b/Sources/AgentsCore/StateStore.swift @@ -101,7 +101,8 @@ public struct StateStore: Sendable { let physicalDirectory = base.resolvingSymlinksInPath().appendingPathComponent( directory.lastPathComponent) return try FileLock.withLock(at: physicalDirectory.appendingPathComponent(".agents.lock")) { - let recovered = try FileTransaction.recover(store: self, checkpoint: checkpoint) + let recovered = try FileTransaction.recover( + store: self, outcome: outcome, checkpoint: checkpoint) _ = try readWatch() let cache = SourceCache(store: self, checkpoint: checkpoint) let referencesRecovered = try cache.recoverWatchReferences() diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index 6a6b34e..03b5522 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -53,6 +53,10 @@ struct TransactionPaths { func root(_ key: String, create: Bool = false, checkpoint: (String) throws -> Void = { _ in }) throws -> DirectoryHandle { + try DirectoryHandle(at: rootURL(key), create: create, checkpoint: checkpoint) + } + + func rootURL(_ key: String) throws -> URL { let url: URL if key == "state" { let base = @@ -77,7 +81,7 @@ struct TransactionPaths { } else { throw CoreError.invalidState("unknown transaction root") } - return try DirectoryHandle(at: url, create: create, checkpoint: checkpoint) + return url } /// A top-level file in the project's own instructions container, `.agent/instructions/.md`. diff --git a/Sources/AgentsCore/UpdatePreconditions.swift b/Sources/AgentsCore/UpdatePreconditions.swift index 381dc9b..2bb6467 100644 --- a/Sources/AgentsCore/UpdatePreconditions.swift +++ b/Sources/AgentsCore/UpdatePreconditions.swift @@ -1,18 +1,173 @@ import CPlatform import Foundation +struct FileObjectIdentity: Codable, Equatable { + let device: UInt64 + let inode: UInt64 + let kind: UInt32 + + init(_ info: stat) { + device = UInt64(info.st_dev) + inode = UInt64(info.st_ino) + kind = UInt32(info.st_mode & S_IFMT) + } +} + +/// Content and physical ownership are separate evidence. Descendant identities let +/// terminal cleanup resume after partial deletion without adopting new entries. +struct FileSnapshot: Codable, Equatable { + let identity: FileObjectIdentity + let digest: String + let executable: Bool + let children: [String: FileSnapshot]? + + static func read(at url: URL) throws -> FileSnapshot? { + var info = stat() + if lstat(url.path, &info) != 0 { + if errno == ENOENT { return nil } + throw FileSystem.posixError(errno, at: url, otherwise: .unsafePath("cannot inspect target")) + } + let parent = try DirectoryHandle(at: url.deletingLastPathComponent().resolvingSymlinksInPath()) + return try read(url.lastPathComponent, from: parent) + } + + static func read(_ name: String, from parent: DirectoryHandle) throws -> FileSnapshot? { + guard var before = try parent.info(name) else { return nil } + let children: [String: FileSnapshot]? + let payload: Data + switch before.st_mode & S_IFMT { + case S_IFDIR: + let directory = try parent.child(name) + var opened = stat() + guard fstat(directory.descriptor, &opened) == 0, platform_same_generation(&before, &opened) + else { + throw CoreError.invalidState("directory changed before reading: \(name)") + } + var entries: [String: FileSnapshot] = [:] + for child in try directory.names() { + guard let value = try read(child, from: directory) else { + throw CoreError.invalidState("entry changed while reading: \(child)") + } + entries[child] = value + } + children = entries + // Only content enters the digest; ownership is compared independently. + payload = try StateStore.encode( + entries.mapValues { "\($0.identity.kind):\($0.executable):\($0.digest)" }) + case S_IFREG: + children = nil + payload = try parent.read(name, matching: before) + case S_IFLNK: + children = nil + payload = Data(try parent.readLink(name).utf8) + default: throw CoreError.unsafePath("unsupported transaction entry: \(name)") + } + guard var after = try parent.info(name), platform_same_generation(&before, &after) else { + throw CoreError.invalidState("entry changed while reading: \(name)") + } + return FileSnapshot( + identity: FileObjectIdentity(before), digest: FileHash.sha256Hex(data: payload), + executable: before.st_mode & S_IFMT == S_IFREG && before.st_mode & 0o111 != 0, + children: children) + } + + func validate() throws { + try StateValidation.digest("sha256:" + digest) + guard [UInt32(S_IFDIR), UInt32(S_IFREG), UInt32(S_IFLNK)].contains(identity.kind), + (identity.kind == S_IFDIR) == (children != nil) + else { throw CoreError.invalidState("invalid transaction object evidence") } + for (name, child) in children ?? [:] { + guard !name.isEmpty, name != ".", name != "..", !name.contains("/"), + !name.contains("\0") + else { throw CoreError.invalidState("invalid transaction descendant") } + try child.validate() + } + } + + func containsRemaining(_ current: FileSnapshot) -> Bool { + guard identity == current.identity else { return false } + guard let children, let remaining = current.children else { return self == current } + return remaining.allSatisfy { name, value in children[name]?.containsRemaining(value) == true } + } + + func sameObjects(as current: FileSnapshot) -> Bool { + guard identity == current.identity else { return false } + switch (children, current.children) { + case (nil, nil): return true + case (let expected?, let actual?): + return expected.keys == actual.keys + && expected.allSatisfy { name, value in actual[name].map(value.sameObjects) == true } + default: return false + } + } + + func synchronize(_ name: String, from parent: DirectoryHandle) throws { + guard try Self.read(name, from: parent) == self else { + throw CoreError.invalidState("transaction preimage changed before synchronization: \(name)") + } + try syncContents(name, from: parent) + try parent.sync() + guard try Self.read(name, from: parent) == self else { + throw CoreError.invalidState("transaction preimage changed during synchronization: \(name)") + } + } + + private func syncContents(_ name: String, from parent: DirectoryHandle) throws { + if let children { + let directory = try parent.child(name) + for child in children.keys.sorted() { + try children[child]!.syncContents(child, from: directory) + } + try directory.sync() + } else if identity.kind == S_IFREG { + try parent.syncFile(name) + } + } + + func remove( + _ name: String, from parent: DirectoryHandle, + checkpoint: (String) throws -> Void = { _ in } + ) throws { + guard let current = try Self.read(name, from: parent) else { + try parent.sync() + return + } + guard containsRemaining(current) else { + throw CoreError.invalidState("transaction cleanup ownership changed: \(name)") + } + if let children { + let directory = try parent.child(name) + if let info = try parent.info(name), info.st_mode & S_IRWXU != S_IRWXU { + guard fchmod(directory.descriptor, (info.st_mode & 0o7777) | S_IRWXU) == 0 else { + throw CoreError.invalidState("cannot make discarded directory writable: \(name)") + } + } + for child in try directory.names() { + guard let expected = children[child] else { + throw CoreError.invalidState("unexpected transaction descendant: \(child)") + } + try expected.remove(child, from: directory, checkpoint: checkpoint) + } + guard try parent.info(name).map(FileObjectIdentity.init) == identity else { + throw CoreError.invalidState("transaction cleanup identity changed: \(name)") + } + } + guard unlinkat(parent.descriptor, name, children == nil ? 0 : AT_REMOVEDIR) == 0 else { + throw CoreError.invalidState("cannot discard verified transaction object: \(name)") + } + try checkpoint("unlinked") + try parent.sync() + try checkpoint("synced") + } +} + /// Captures existing ancestry and the final entry without following that entry's link. /// Missing ancestors may be created, but existing ancestors cannot be exchanged. package struct PathIdentity { - private struct Entry: Equatable { - let device: UInt64 - let inode: UInt64 - let kind: UInt32 - } private let url: URL private let physical: URL - private let entry: Entry? - private let ancestors: [(URL, Entry)] + private let entry: FileObjectIdentity? + private let ancestors: [(URL, FileObjectIdentity)] package init(_ url: URL) throws { self.url = url @@ -20,7 +175,7 @@ package struct PathIdentity { url.deletingLastPathComponent().resolvingSymlinksInPath() .appendingPathComponent(url.lastPathComponent).standardizedFileURL entry = try Self.read(physical) - var ancestors: [(URL, Entry)] = [] + var ancestors: [(URL, FileObjectIdentity)] = [] var parent = physical.deletingLastPathComponent() while parent.path != "/" { if let value = try Self.read(parent) { ancestors.append((parent, value)) } @@ -40,34 +195,31 @@ package struct PathIdentity { } } - private static func read(_ url: URL) throws -> Entry? { + private static func read(_ url: URL) throws -> FileObjectIdentity? { var value = stat() guard lstat(url.path, &value) == 0 else { if errno == ENOENT { return nil } throw CoreError.unsafePath("cannot inspect path: \(url.path)") } - return Entry( - device: UInt64(value.st_dev), inode: UInt64(value.st_ino), - kind: UInt32(value.st_mode & 0o170000)) + return FileObjectIdentity(value) } } /// State bytes and presence belong to the same generation as the rendered targets. package struct StatePrecondition { - private let store: StateStore - private let files: [(URL, PathIdentity, Data?)] + private let files: [(URL, PathIdentity, FileSnapshot?)] package init(store: StateStore) throws { - self.store = store files = try [store.declarationURL, store.resolvedURL, store.watchURL].map { - ($0, try PathIdentity($0), try store.existingData($0)) + ($0, try PathIdentity($0), try FileSnapshot.read(at: $0)) } + try validate() } - package func validate() throws { - for (url, identity, bytes) in files { + package func validate(excluding filenames: Set = []) throws { + for (url, identity, snapshot) in files where !filenames.contains(url.lastPathComponent) { try identity.validate() - guard try store.existingData(url) == bytes else { + guard try FileSnapshot.read(at: url) == snapshot else { throw CoreError.invalidState("state changed during preparation: \(url.lastPathComponent)") } } diff --git a/Sources/AgentsInstructions/InstructionOperations.swift b/Sources/AgentsInstructions/InstructionOperations.swift index f69c00c..89b8c3a 100644 --- a/Sources/AgentsInstructions/InstructionOperations.swift +++ b/Sources/AgentsInstructions/InstructionOperations.swift @@ -144,19 +144,22 @@ public enum InstructionOperations { beforeApply: ((InstructionUpdateReport) throws -> Void)? = nil ) throws -> InstructionUpdateReport { let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: apply) { previousDeclaration, previous in + return try operate(store, apply: apply) { _, _ in + let baseline = try StatePrecondition(store: store) + let previousDeclaration = try store.readDeclaration() + let previous = try store.readResolved() var declaration = previousDeclaration if let agents { var instructions = declaration.instructions ?? InstructionsDeclaration() instructions.agents = agents declaration.instructions = instructions } - let baseline = try StatePrecondition(store: store) let resolutions = try SourceResolutionSession(store: store) let plan = try prepareUpdate( store: store, declaration: declaration, previousDeclaration: previousDeclaration, previous: previous, resolutions: resolutions, replace: replace) try plan.next.validate() + try baseline.validate() if apply { if !replace { try requireOwnership(plan.report) } try beforeApply?(plan.report) @@ -166,6 +169,10 @@ public enum InstructionOperations { try baseline.validate() try plan.validate() let transaction = FileTransaction(store: store) + transaction.validateBeforePublication = { + try baseline.validate() + try plan.validate() + } try plan.stage(transaction: transaction) try store.stageDeclaration(declaration, in: transaction) if let data = try plan.next.replacementData( diff --git a/Sources/AgentsSkills/SkillOperations.swift b/Sources/AgentsSkills/SkillOperations.swift index 94e3558..d5c4d5c 100644 --- a/Sources/AgentsSkills/SkillOperations.swift +++ b/Sources/AgentsSkills/SkillOperations.swift @@ -141,13 +141,16 @@ public enum SkillOperations { beforeApply: (([UpdateResult]) throws -> Void)? = nil, provider: WellKnownProvider ) throws -> [UpdateResult] { let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: apply) { declaration, previous in + return try operate(store, apply: apply) { _, _ in let baseline = try StatePrecondition(store: store) + let declaration = try store.readDeclaration() + let previous = try store.readResolved() let resolutions = try SourceResolutionSession(store: store) let plan = try prepareUpdate( store: store, declaration: declaration, previous: previous, resolutions: resolutions, skillNames: skillNames, provider: provider) try plan.next.validate() + try baseline.validate() var results = plan.results if apply { try plan.validateOwnership() @@ -158,6 +161,10 @@ public enum SkillOperations { try baseline.validate() try plan.validate() let transaction = FileTransaction(store: store) + transaction.validateBeforePublication = { + try baseline.validate() + try plan.validate() + } try plan.stage(retained: retained, transaction: transaction) try store.stageDeclaration(declaration, in: transaction) if let data = try plan.next.replacementData( diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index e8e6519..a9bc0f0 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -89,6 +89,7 @@ final class UpdatePlan { try checkpoint("apply.retained") try validate() let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) + transaction.validateBeforePublication = { try self.validate() } try skills.stage(retained: retained, transaction: transaction) try instructions.stage(transaction: transaction) try store.stageDeclaration(declaration, in: transaction) diff --git a/Sources/CPlatform/CPlatform.c b/Sources/CPlatform/CPlatform.c index fbde767..ab264d3 100644 --- a/Sources/CPlatform/CPlatform.c +++ b/Sources/CPlatform/CPlatform.c @@ -41,6 +41,30 @@ int platform_exchange(int directory, const char *name, const char *destination) #endif } +int platform_rename_exclusive(int directory, const char *name, const char *destination) { +#if defined(__APPLE__) + return renameatx_np(directory, name, directory, destination, RENAME_EXCL); +#else + return (int)syscall(SYS_renameat2, directory, name, directory, destination, 1 /* RENAME_NOREPLACE */); +#endif +} + +bool platform_same_generation(const struct stat *first, const struct stat *second) { +#if defined(__APPLE__) +#define MTIME st_mtimespec +#define CTIME st_ctimespec +#else +#define MTIME st_mtim +#define CTIME st_ctim +#endif + return first->st_dev == second->st_dev && first->st_ino == second->st_ino && + first->st_mode == second->st_mode && first->st_size == second->st_size && + first->MTIME.tv_sec == second->MTIME.tv_sec && first->MTIME.tv_nsec == second->MTIME.tv_nsec && + first->CTIME.tv_sec == second->CTIME.tv_sec && first->CTIME.tv_nsec == second->CTIME.tv_nsec; +#undef MTIME +#undef CTIME +} + int platform_sync(int descriptor) { int result; do { result = fsync(descriptor); } while (result < 0 && errno == EINTR); diff --git a/Sources/CPlatform/include/CPlatform.h b/Sources/CPlatform/include/CPlatform.h index 4e6d97e..203ded2 100644 --- a/Sources/CPlatform/include/CPlatform.h +++ b/Sources/CPlatform/include/CPlatform.h @@ -26,6 +26,8 @@ int platform_access(int directory, const char *name, int mode); const char *platform_entry_name(const struct dirent *entry); bool platform_system_alias(const char *name); int platform_exchange(int directory, const char *name, const char *destination); +int platform_rename_exclusive(int directory, const char *name, const char *destination); +bool platform_same_generation(const struct stat *first, const struct stat *second); int platform_sync(int descriptor); int platform_copy_data(int source, int destination); int platform_copy_metadata(int source, int destination, mode_t mode); diff --git a/Tests/AgentsCoreTests/DirectoryHandleTests.swift b/Tests/AgentsCoreTests/DirectoryHandleTests.swift index 718c54c..52538c2 100644 --- a/Tests/AgentsCoreTests/DirectoryHandleTests.swift +++ b/Tests/AgentsCoreTests/DirectoryHandleTests.swift @@ -65,6 +65,31 @@ struct DirectoryHandleTests { #expect(try directory.child("second").read("content") == Data("first".utf8)) } + @Test(arguments: ["file", "directory", "link"]) + func exclusiveRenamePreservesConcurrentObjects(_ kind: String) throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let directory = try DirectoryHandle(at: root) + for name in ["staged", "external"] { + if kind == "directory" { + try directory.makeDirectory(name) + try directory.child(name).write("content", data: Data(name.utf8)) + } else if kind == "link" { + try directory.link(name, destination: name + "-destination") + } else { + try directory.write(name, data: Data(name.utf8)) + } + } + let staged = try FileSnapshot.read("staged", from: directory) + let external = try FileSnapshot.read("external", from: directory) + #expect(throws: CoreError.self) { try directory.renameExclusive("staged", to: "external") } + #expect(try FileSnapshot.read("staged", from: directory) == staged) + #expect(try FileSnapshot.read("external", from: directory) == external) + try directory.renameExclusive("staged", to: "published") + #expect(try FileSnapshot.read("published", from: directory) == staged) + #expect(try directory.info("staged") == nil) + } + @Test func directoryAndRegularFileReadsRejectLinks() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } diff --git a/Tests/AgentsCoreTests/PublicationTests.swift b/Tests/AgentsCoreTests/PublicationTests.swift new file mode 100644 index 0000000..f385bd9 --- /dev/null +++ b/Tests/AgentsCoreTests/PublicationTests.swift @@ -0,0 +1,552 @@ +import CPlatform +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Journal publication and ownership") +struct PublicationTests { + @Test(arguments: ["create", "replace", "delete"]) + func killedPublicationAtEachStageRecoversPhysicalGeneration(_ operation: String) throws { + var points = [ + "journal.preparing", "atomic.0.created.1", "atomic.0.created.2", "atomic.0.exchanged", + "atomic.0.exclusive", "atomic.0.verified", "stage.1.ready", "journal.applying", + "stage.1.sealed", + "journal.applying.renamed", "stage.1.preimage", "stage.1", "publication.preconditions", + "publish.1.intent", + "publish.1.validated", "replace.1.renamed", "publish.1.synced", "replace.1", + "journal.committing", "journal.committed.renamed", "journal.committed", + "journal.terminalSynced", + "cleanup.0.intent", "cleanup.1.intent", "cleanup.1", + "cleanup.0.probe-b.unlinked", "cleanup.0.probe-c.synced", + ] + if operation == "replace" { points += ["publish.1.displaced", "publish.1.retained"] } + if operation != "delete" { points += ["stage.1.written"] } + if operation != "create" { points += ["cleanup.1.old.unlinked", "cleanup.1.old.synced"] } + for point in points { + let fixture = try PublicationFixture(operation: operation) + let original = try FileSnapshot.read(at: fixture.target) + let auxiliary = try FileSnapshot.read(at: fixture.auxiliary) + let child = try fixture.pause("publication", at: point) + terminateProcess(child) + let journal = try fixture.journal() + let entries = try #require(journal["entries"] as? [[String: Any]]) + let staged = try entries[1]["staged"].map { try fixture.snapshot($0) } + let committed = + point.hasPrefix("journal.committed") || point.hasPrefix("cleanup.") + || point == "journal.terminalSynced" + let outcome = try fixture.outcome() + #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { + try fixture.store.withLock(outcome: outcome, {}) + } + #expect( + outcome.disposition == (committed ? .committed : .unchanged), "\(operation): \(point)") + #expect(try FileSnapshot.read(at: fixture.target) == (committed ? staged : original)) + if committed { + #expect(try Data(contentsOf: fixture.auxiliary) == Data("auxiliary postimage".utf8)) + } else { + #expect(try FileSnapshot.read(at: fixture.auxiliary) == auxiliary) + } + try fixture.expectClean() + } + } + + @Test(arguments: ["create", "replace", "delete"]) + func recoveryCanBeKilledAtEachStageAndRepeated(_ operation: String) throws { + var points = [ + "restore.1.intent", "restore.1.validated", "restore.1.synced", "restore.1", + "restore.0.renamed", "journal.rolledBack.renamed", "journal.terminalSynced", + "cleanup.0.intent", "cleanup.1.intent", "cleanup.1", + ] + if operation == "create" { + points += [ + "restore.1.remove.unlinked", "restore.1.remove.synced", "cleanup.1.removed.unlinked", + ] + } else { + points += ["restore.1.renamed"] + if operation == "replace" { points += ["cleanup.1.old.unlinked"] } + } + for point in points { + let fixture = try PublicationFixture(operation: operation) + let target = try FileSnapshot.read(at: fixture.target) + let auxiliary = try FileSnapshot.read(at: fixture.auxiliary) + terminateProcess(try fixture.pause("publication", at: "replace.1")) + let outcome = try fixture.outcome() + terminateProcess(try fixture.pause("publication-recover", at: point)) + #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { + try fixture.store.withLock(outcome: outcome, {}) + } + #expect(outcome.disposition == .unchanged) + #expect(try FileSnapshot.read(at: fixture.target) == target, "\(operation): \(point)") + #expect(try FileSnapshot.read(at: fixture.auxiliary) == auxiliary) + #expect(try !FileTransaction.recover(store: fixture.store)) + try fixture.expectClean() + } + } + + @Test(arguments: ["external", "postimage"]) + func concurrentCreatorKeepsItsBytesAndInode(_ bytes: String) throws { + let fixture = try PublicationFixture(operation: "create") + let auxiliary = try FileSnapshot.read(at: fixture.auxiliary) + let child = try fixture.pause("publication", at: "publish.1.validated") + defer { terminateProcess(child) } + try Data(bytes.utf8).write(to: fixture.target) + let external = try FileSnapshot.read(at: fixture.target) + try fixture.resume(child) + #expect(try fixture.result("publication-result").hasPrefix("unchanged\n")) + #expect(try FileSnapshot.read(at: fixture.target) == external) + #expect(try FileSnapshot.read(at: fixture.auxiliary) == auxiliary) + try fixture.expectClean() + } + + @Test(arguments: [false, true], [false, true]) + func exchangedUnexpectedPreimageIsNeverDiscarded(_ inPlace: Bool, _ killAfterExchange: Bool) + throws + { + let fixture = try PublicationFixture(operation: "replace") + let auxiliary = try FileSnapshot.read(at: fixture.auxiliary) + let child = try fixture.pause("publication", at: "publish.1.validated") + defer { terminateProcess(child) } + let original = try FileSnapshot.read(at: fixture.target) + if !inPlace { + try FileManager.default.moveItem( + at: fixture.target, to: fixture.root.appendingPathComponent("saved-original")) + } + try Data("external preimage".utf8).write(to: fixture.target) + let external = try #require(try FileSnapshot.read(at: fixture.target)) + if killAfterExchange { + try fixture.restop(child, at: "replace.1.renamed") + terminateProcess(child) + } else { + try fixture.resume(child) + #expect(try fixture.result("publication-result").hasPrefix("unresolved\n")) + } + #expect(try Data(contentsOf: fixture.target) == Data("postimage".utf8)) + #expect(try fixture.scratch("new", index: 1) == external) + try fixture.expectUnresolved() + if !inPlace { + #expect( + try FileSnapshot.read(at: fixture.root.appendingPathComponent("saved-original")) == original + ) + } + #expect(try FileSnapshot.read(at: fixture.auxiliary) == auxiliary) + } + + @Test(arguments: ["postimage", "changed postimage"]) + func externalRecoveryDestinationEvenWithEqualBytesIsPreserved(_ bytes: String) throws { + let fixture = try PublicationFixture(operation: "replace") + let preimage = try FileSnapshot.read(at: fixture.target) + terminateProcess(try fixture.pause("publication", at: "replace.1")) + let published = try FileSnapshot.read(at: fixture.target) + try FileManager.default.moveItem( + at: fixture.target, to: fixture.root.appendingPathComponent("saved-postimage")) + try Data(bytes.utf8).write(to: fixture.target) + let external = try FileSnapshot.read(at: fixture.target) + #expect(external?.identity != published?.identity) + try fixture.expectUnresolved() + #expect(try FileSnapshot.read(at: fixture.target) == external) + #expect(try fixture.scratch("old", index: 1) == preimage) + #expect( + try FileSnapshot.read(at: fixture.root.appendingPathComponent("saved-postimage")) == published + ) + } + + @Test(arguments: ["replace", "delete", "create"]) + func externalWriterRacingRestorationRetainsBothVersions(_ operation: String) throws { + let fixture = try PublicationFixture(operation: operation) + let preimage = try FileSnapshot.read(at: fixture.target) + terminateProcess(try fixture.pause("publication", at: "replace.1")) + let recovery = try fixture.pause("publication-recover", at: "restore.1.validated") + defer { terminateProcess(recovery) } + if operation != "delete" { + try FileManager.default.moveItem( + at: fixture.target, to: fixture.root.appendingPathComponent("saved-postimage")) + } + try Data("postimage".utf8).write(to: fixture.target) + let external = try FileSnapshot.read(at: fixture.target) + try fixture.resume(recovery) + #expect(try fixture.result("recovery-result").hasPrefix("unresolved:")) + if operation == "delete" { + #expect(try FileSnapshot.read(at: fixture.target) == external) + #expect(try fixture.scratch("old", index: 1) == preimage) + } else if operation == "replace" { + #expect(try FileSnapshot.read(at: fixture.target) == preimage) + #expect(try fixture.scratch("old", index: 1) == external) + } else { + #expect(try FileSnapshot.read(at: fixture.target) == nil) + #expect(try fixture.scratch("removed", index: 1) == external) + } + try fixture.expectUnresolved() + } + + @Test(arguments: ["replace", "create"]) + func killedRecoveryBeforeVerificationRetainsUnexpectedDisplacedObject(_ operation: String) throws + { + let fixture = try PublicationFixture(operation: operation) + let preimage = try FileSnapshot.read(at: fixture.target) + terminateProcess(try fixture.pause("publication", at: "replace.1")) + let recovery = try fixture.pause("publication-recover", at: "restore.1.validated") + defer { terminateProcess(recovery) } + try FileManager.default.moveItem( + at: fixture.target, to: fixture.root.appendingPathComponent("saved-postimage")) + try Data("postimage".utf8).write(to: fixture.target) + let external = try FileSnapshot.read(at: fixture.target) + let point = operation == "replace" ? "restore.1.renamed" : "restore.1.remove.unlinked" + try fixture.restop(recovery, at: point, markerName: "recovery-ready") + terminateProcess(recovery) + try fixture.expectUnresolved() + #expect(try FileSnapshot.read(at: fixture.target) == preimage) + #expect(try fixture.scratch(operation == "replace" ? "old" : "removed", index: 1) == external) + } + + @Test func interruptedDirectoryCleanupPreservesNewExternalDescendants() throws { + let fixture = try TransactionFixture() + let child = try stateTestProcess(root: fixture.root, arguments: ["crash", "cleanup.0.intent"]) + defer { terminateProcess(child) } + let marker = fixture.root.appendingPathComponent("ready") + let deadline = Date().addingTimeInterval(10) + while !FileManager.default.fileExists(atPath: marker.path), child.isRunning, Date() < deadline { + Thread.sleep(forTimeInterval: 0.01) + } + try #require(FileManager.default.fileExists(atPath: marker.path)) + terminateProcess(child) + let json = try #require( + JSONSerialization.jsonObject( + with: Data(contentsOf: fixture.store.directory.appendingPathComponent("transaction.json"))) + as? [String: Any]) + let id = try #require(json["id"] as? String) + let original = fixture.root.appendingPathComponent(".agents/skills/.agents-\(id)-0.old") + let childURL = original.appendingPathComponent("external") + try Data("keep external descendant".utf8).write(to: childURL) + let before = try FileSnapshot.read(at: original) + let outcome = TransactionOutcome() + outcome.journalID = UUID(uuidString: id) + for _ in 0..<2 { + #expect(throws: CoreError.self) { try fixture.store.withLock(outcome: outcome, {}) } + #expect(outcome.disposition == .recoveryRequired) + #expect(try FileSnapshot.read(at: original) == before) + #expect( + try String(contentsOf: original.appendingPathComponent("SKILL.md"), encoding: .utf8) + == "target") + } + } + + @Test(arguments: ["new", "old", "missing"]) + func replacedOrMissingRecoveryEvidenceNeverGrantsOwnership(_ suffix: String) throws { + let fixture = try PublicationFixture(operation: suffix == "new" ? "create" : "replace") + let point = suffix == "new" ? "journal.applying" : "replace.1" + terminateProcess(try fixture.pause("publication", at: point)) + let actualSuffix = suffix == "missing" ? "old" : suffix + let path = try fixture.scratchURL(actualSuffix, index: 1) + let saved = fixture.root.appendingPathComponent("saved-evidence") + let original = try #require(try FileSnapshot.read(at: path)) + try FileManager.default.moveItem(at: path, to: saved) + var external: FileSnapshot? + if suffix != "missing" { + try Data(contentsOf: saved).write(to: path) + external = try FileSnapshot.read(at: path) + #expect(external?.identity != original.identity) + } + let target = try FileSnapshot.read(at: fixture.target) + try fixture.expectUnresolved() + #expect(try FileSnapshot.read(at: path) == external) + #expect(try FileSnapshot.read(at: saved) == original) + #expect(try FileSnapshot.read(at: fixture.target) == target) + } + + @Test func deletionNeverAdoptsAnUnexpectedStagingObject() throws { + let fixture = try PublicationFixture(operation: "delete") + let target = try FileSnapshot.read(at: fixture.target) + let outcome = TransactionOutcome() + var external: FileSnapshot? + #expect(throws: CoreError.self) { + try fixture.store.withLock(outcome: outcome) { + let transaction = FileTransaction(store: fixture.store, outcome: outcome) { step in + if step == "stage.0.preimage" { + let url = try fixture.scratchURL("new", index: 0) + try Data("external object".utf8).write(to: url) + external = try FileSnapshot.read(at: url) + } + } + try transaction.replace(fixture.target, content: nil) + try transaction.commit() + } + } + #expect(outcome.disposition == .recoveryRequired) + #expect(try FileSnapshot.read(at: fixture.target) == target) + #expect(try fixture.scratch("new", index: 0) == external) + try fixture.expectUnresolved() + } + + @Test(arguments: ["preparing", "committed", "rolledBack", "unsealed"]) + func inconsistentJournalStagesPreserveAllEvidence(_ phase: String) throws { + let fixture = try PublicationFixture(operation: "replace") + terminateProcess(try fixture.pause("publication", at: "replace.0")) + let outcome = try fixture.outcome() + var journal = try fixture.journal() + if phase == "unsealed" { + var entries = try #require(journal["entries"] as? [[String: Any]]) + entries[1]["progress"] = "verifying" + journal["entries"] = entries + } else { + journal["phase"] = phase + } + try JSONSerialization.data(withJSONObject: journal).write( + to: fixture.store.directory.appendingPathComponent("transaction.json")) + let before = try FileHash.folderHash(fixture.root) + let target = try FileSnapshot.read(at: fixture.target) + let auxiliary = try FileSnapshot.read(at: fixture.auxiliary) + #expect(throws: CoreError.self) { try fixture.store.withLock(outcome: outcome, {}) } + #expect(outcome.disposition == .recoveryRequired) + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(try FileSnapshot.read(at: fixture.target) == target) + #expect(try FileSnapshot.read(at: fixture.auxiliary) == auxiliary) + } + + @Test(arguments: ["preimage", "staged", "parentIdentity", "probes"]) + func missingJournalEvidenceReportsUnresolvedBeforeReplay(_ field: String) throws { + let fixture = try PublicationFixture(operation: "replace") + terminateProcess(try fixture.pause("publication", at: "replace.1")) + let outcome = try fixture.outcome() + var journal = try fixture.journal() + var entries = try #require(journal["entries"] as? [[String: Any]]) + entries[1].removeValue(forKey: field) + journal["entries"] = entries + try JSONSerialization.data(withJSONObject: journal).write( + to: fixture.store.directory.appendingPathComponent("transaction.json")) + let before = try FileHash.folderHash(fixture.root) + #expect(throws: CoreError.self) { try fixture.store.withLock(outcome: outcome, {}) } + #expect(outcome.disposition == .recoveryRequired) + #expect(try FileHash.folderHash(fixture.root) == before) + } + + @Test func cleanupConflictAfterCommitReportsUnresolvedAndKeepsPreimage() throws { + let fixture = try PublicationFixture(operation: "replace") + let preimage = try FileSnapshot.read(at: fixture.target) + let child = try fixture.pause("publication", at: "journal.committed") + defer { terminateProcess(child) } + let path = try fixture.scratchURL("old", index: 1) + let saved = fixture.root.appendingPathComponent("saved-preimage") + try FileManager.default.moveItem(at: path, to: saved) + try Data(contentsOf: saved).write(to: path) + let external = try FileSnapshot.read(at: path) + try fixture.resume(child) + #expect(try fixture.result("publication-result").hasPrefix("unresolved\n")) + #expect(try Data(contentsOf: fixture.target) == Data("postimage".utf8)) + #expect(try FileSnapshot.read(at: saved) == preimage) + #expect(try FileSnapshot.read(at: path) == external) + try fixture.expectUnresolved() + } + + @Test func movedScopeAfterCommitReportsUnresolvedUntilItsIdentityIsRestored() throws { + let fixture = try PublicationFixture(operation: "replace") + let moved = fixture.root.appendingPathComponent("moved-state") + let outcome = TransactionOutcome() + #expect(throws: CoreError.self) { + try fixture.store.withLock(outcome: outcome) { + let transaction = FileTransaction(store: fixture.store, outcome: outcome) { step in + if step == "journal.committed" { + try FileManager.default.moveItem(at: fixture.store.directory, to: moved) + throw CoreError.invalidState("scope moved") + } + } + try transaction.replace(fixture.target, content: nil, data: Data("postimage".utf8)) + try transaction.commit() + } + } + #expect(outcome.disposition == .recoveryRequired) + #expect(try Data(contentsOf: fixture.target) == Data("postimage".utf8)) + #expect( + FileManager.default.fileExists(atPath: moved.appendingPathComponent("transaction.json").path)) + try FileManager.default.moveItem(at: moved, to: fixture.store.directory) + #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { + try fixture.store.withLock(outcome: outcome, {}) + } + #expect(outcome.disposition == .committed) + try fixture.expectClean() + } + + @Test(arguments: ["create", "replace", "delete"]) + func unsupportedAtomicsFailBeforeAnyTransactionMutation(_ operation: String) throws { + let fixture = try PublicationFixture(operation: operation) + let before = try FileHash.folderHash(fixture.root) + let outcome = TransactionOutcome() + let transaction = FileTransaction(store: fixture.store, outcome: outcome) + transaction.atomicPreflight = { _ in throw CoreError.unsupported("injected atomic primitive") } + try transaction.replace( + fixture.target, content: nil, data: operation == "delete" ? nil : Data("postimage".utf8)) + #expect(throws: CoreError.unsupported("injected atomic primitive")) { try transaction.commit() } + #expect(outcome.disposition == .unchanged) + #expect(try FileHash.folderHash(fixture.root) == before) + try fixture.expectClean() + } + + @Test(arguments: ["agents.json", "agents.resolved", "agents.watch", "AGENTS.md"]) + func queuedPreconditionsRejectChangedBytesOrEqualByteExternalInodes(_ path: String) throws { + for equalBytes in [false, true] { + let fixture = try PublicationFixture(operation: "replace") + let target = + path == "AGENTS.md" ? fixture.target : fixture.store.directory.appendingPathComponent(path) + let transaction = FileTransaction(store: fixture.store) + try transaction.replace(fixture.target, content: nil, data: Data("postimage".utf8)) + let bytes = try Data(contentsOf: target) + if equalBytes { + try FileManager.default.moveItem( + at: target, to: fixture.root.appendingPathComponent("saved-input")) + } + try (equalBytes ? bytes : bytes + Data(" ".utf8)).write(to: target) + let external = try FileSnapshot.read(at: target) + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(try FileSnapshot.read(at: target) == external) + try fixture.expectClean() + } + } + + @Test(arguments: ["publication.preconditions", "publish.1.validated"], [false, true]) + func unchangedStateInputsAreRecheckedBeforePublicationAndCommit( + _ point: String, _ equalBytes: Bool + ) + throws + { + let fixture = try PublicationFixture(operation: "replace") + let target = try FileSnapshot.read(at: fixture.target) + let auxiliary = try FileSnapshot.read(at: fixture.auxiliary) + let outcome = TransactionOutcome() + var external: FileSnapshot? + try fixture.store.withLock(outcome: outcome) { + let transaction = FileTransaction(store: fixture.store, outcome: outcome) { step in + if step == point { + let bytes = try Data(contentsOf: fixture.store.watchURL) + if equalBytes { + try FileManager.default.moveItem( + at: fixture.store.watchURL, to: fixture.root.appendingPathComponent("saved-watch")) + } + try (equalBytes ? bytes : bytes + Data(" ".utf8)).write(to: fixture.store.watchURL) + external = try FileSnapshot.read(at: fixture.store.watchURL) + } + } + for file in [fixture.auxiliary, fixture.target] { + try transaction.replace(file, content: nil, data: Data("postimage".utf8)) + } + #expect(throws: CoreError.self) { try transaction.commit() } + } + #expect(outcome.disposition == .unchanged) + #expect(try FileSnapshot.read(at: fixture.target) == target) + #expect(try FileSnapshot.read(at: fixture.auxiliary) == auxiliary) + #expect(try FileSnapshot.read(at: fixture.store.watchURL) == external) + try fixture.expectClean() + } +} + +private final class PublicationFixture { + let root: URL + let store: StateStore + let operation: String + var target: URL { root.appendingPathComponent("AGENTS.md") } + var auxiliary: URL { root.appendingPathComponent("GEMINI.md") } + + init(operation: String) throws { + root = try temporaryDirectory() + self.operation = operation + store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: [:] + )) + do { + try store.save(declaration: Declaration(), resolved: ResolvedState(), watch: WatchState()) + if operation != "create" { try Data("preimage".utf8).write(to: target) } + try Data("auxiliary preimage".utf8).write(to: auxiliary) + } catch { + removeTemporaryDirectory(root) + throw error + } + } + + deinit { removeTemporaryDirectory(root) } + + func pause(_ command: String, at step: String) throws -> Process { + let marker = root.appendingPathComponent(command == "publication" ? "ready" : "recovery-ready") + try? FileManager.default.removeItem(at: marker) + try? FileManager.default.removeItem(at: root.appendingPathComponent("stop-at")) + let child = try stateTestProcess(root: root, arguments: [command, step, operation]) + let deadline = Date().addingTimeInterval(10) + while !FileManager.default.fileExists(atPath: marker.path), child.isRunning, Date() < deadline { + Thread.sleep(forTimeInterval: 0.01) + } + if !FileManager.default.fileExists(atPath: marker.path) { + terminateProcess(child) + throw CoreError.invalidState("publication subprocess did not reach \(step)") + } + return child + } + + func restop(_ child: Process, at step: String, markerName: String = "ready") throws { + let marker = root.appendingPathComponent(markerName) + try Data(step.utf8).write(to: root.appendingPathComponent("stop-at")) + try FileManager.default.removeItem(at: marker) + kill(child.processIdentifier, SIGCONT) + let deadline = Date().addingTimeInterval(10) + while !FileManager.default.fileExists(atPath: marker.path), child.isRunning, Date() < deadline { + Thread.sleep(forTimeInterval: 0.01) + } + try #require(FileManager.default.fileExists(atPath: marker.path)) + } + + func resume(_ child: Process) throws { + kill(child.processIdentifier, SIGCONT) + try finishProcesses([child]) + } + + func result(_ name: String) throws -> String { + try String(contentsOf: root.appendingPathComponent(name), encoding: .utf8) + } + + func journal() throws -> [String: Any] { + try #require( + JSONSerialization.jsonObject( + with: Data(contentsOf: store.directory.appendingPathComponent("transaction.json"))) + as? [String: Any]) + } + + func outcome() throws -> TransactionOutcome { + let result = TransactionOutcome() + result.journalID = try UUID(uuidString: #require(journal()["id"] as? String)) + return result + } + + func snapshot(_ json: Any) throws -> FileSnapshot { + try JSONDecoder().decode(FileSnapshot.self, from: JSONSerialization.data(withJSONObject: json)) + } + + func scratchURL(_ suffix: String, index: Int) throws -> URL { + let id = try #require(journal()["id"] as? String) + return root.appendingPathComponent(".agents-\(id)-\(index).\(suffix)") + } + + func scratch(_ suffix: String, index: Int) throws -> FileSnapshot? { + try FileSnapshot.read(at: scratchURL(suffix, index: index)) + } + + func expectUnresolved() throws { + let outcome = try outcome() + for _ in 0..<2 { + #expect(throws: CoreError.self) { + try store.withLock(outcome: outcome, {}) + } + #expect(outcome.disposition == .recoveryRequired) + let before = try FileHash.folderHash(root) + #expect(throws: CoreError.self) { + try store.withReadLock { Issue.record("must not inspect") } + } + #expect(try FileHash.folderHash(root) == before) + } + } + + func expectClean() throws { + #expect(try store.openDirectoryIfPresent()?.info("transaction.json") == nil) + #expect(try store.openDirectoryIfPresent()?.info("transaction.new") == nil) + let names = try FileManager.default.contentsOfDirectory(atPath: root.path) + #expect(!names.contains { $0.hasPrefix(".agents-") }) + } +} diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 29e24fb..67c1f7c 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -15,7 +15,10 @@ let store = StateStore( homeDirectory: root.appendingPathComponent("home"), environment: ["CLAUDE_CONFIG_DIR": root.appendingPathComponent("configured-claude").path])) func stop(_ step: String, marker: String = "ready") throws { - if step == arguments[3] { + let requested = + (try? String(contentsOf: root.appendingPathComponent("stop-at"), encoding: .utf8)) + ?? arguments[3] + if step == requested { try Data(step.utf8).write(to: root.appendingPathComponent(marker), options: .atomic) raise(SIGSTOP) } @@ -146,6 +149,42 @@ if arguments[2] == "git-environment" { } } else if arguments[2] == "watch-recover" { try store.withLock(checkpoint: { try stop($0) }, {}) +} else if arguments[2] == "publication-recover" { + let result: String + do { + try store.withLock(checkpoint: { try stop($0, marker: "recovery-ready") }, {}) + result = "clean" + } catch CoreError.transactionRecovered { + result = "recovered" + } catch { + result = "unresolved: \(error)" + } + try Data(result.utf8).write(to: root.appendingPathComponent("recovery-result")) +} else if arguments[2] == "publication" { + let outcome = TransactionOutcome() + var failure = "" + do { + try store.withLock(outcome: outcome) { + let transaction = FileTransaction(store: store, outcome: outcome) { try stop($0) } + try transaction.replace( + root.appendingPathComponent("GEMINI.md"), content: nil, + data: Data("auxiliary postimage".utf8)) + try transaction.replace( + root.appendingPathComponent("AGENTS.md"), content: nil, + data: arguments[4] == "delete" ? nil : Data("postimage".utf8)) + try transaction.commit() + } + } catch { + failure = String(describing: error) + } + let disposition: String + switch outcome.disposition { + case .unchanged: disposition = "unchanged" + case .committed: disposition = "committed" + case .recoveryRequired: disposition = "unresolved" + } + try Data((disposition + "\n" + failure).utf8).write( + to: root.appendingPathComponent("publication-result")) } else if arguments[2] == "recover" { try FileLock.withLock(at: store.directory.appendingPathComponent(".agents.lock")) { _ = try FileTransaction.recover(store: store) { try stop($0, marker: "recovery-ready") } From 574bdc5d020873f227b2c27eb62d711f45b3e5a1 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 29 Oct 2026 23:33:23 +0800 Subject: [PATCH 015/171] fix: compare transaction object kinds as mode_t on Linux CPlatform and Glibc both import the S_IF* macros on Linux with different types, so untyped conversions were ambiguous. Object kinds keep the st_mode type. --- Sources/AgentsCore/FileTransaction.swift | 2 +- Sources/AgentsCore/UpdatePreconditions.swift | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 8cecb66..5653f4f 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -276,7 +276,7 @@ package final class FileTransaction { if let data = content.data { try parent.write( staged, data: data, - preservingMetadataOf: entry.preimage?.identity.kind == UInt32(S_IFREG) ? entry.name : nil) + preservingMetadataOf: entry.preimage?.identity.kind == S_IFREG ? entry.name : nil) journal.entries[index].staging = try FileSnapshot.read(staged, from: parent) try Self.persist(journal, directory: directory, checkpoint: checkpoint) try checkpoint("stage.\(index).written") diff --git a/Sources/AgentsCore/UpdatePreconditions.swift b/Sources/AgentsCore/UpdatePreconditions.swift index 2bb6467..6c70766 100644 --- a/Sources/AgentsCore/UpdatePreconditions.swift +++ b/Sources/AgentsCore/UpdatePreconditions.swift @@ -4,12 +4,12 @@ import Foundation struct FileObjectIdentity: Codable, Equatable { let device: UInt64 let inode: UInt64 - let kind: UInt32 + let kind: mode_t init(_ info: stat) { device = UInt64(info.st_dev) inode = UInt64(info.st_ino) - kind = UInt32(info.st_mode & S_IFMT) + kind = info.st_mode & S_IFMT } } @@ -73,7 +73,8 @@ struct FileSnapshot: Codable, Equatable { func validate() throws { try StateValidation.digest("sha256:" + digest) - guard [UInt32(S_IFDIR), UInt32(S_IFREG), UInt32(S_IFLNK)].contains(identity.kind), + let kinds: [mode_t] = [S_IFDIR, S_IFREG, S_IFLNK] + guard kinds.contains(identity.kind), (identity.kind == S_IFDIR) == (children != nil) else { throw CoreError.invalidState("invalid transaction object evidence") } for (name, child) in children ?? [:] { From a4761256a6b5b288c767f7f195b845a670ce5404 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 30 Oct 2026 04:45:08 +0800 Subject: [PATCH 016/171] fix(state): stage publications in private transaction containers Each destination parent gets a transaction-private container whose name and identity are journaled before anything is created inside it. Staging is sealed once after construction, so recovery no longer rescans or adopts scratch content. Recovery checks the objects each operation kind and progress implies and reports a missing preimage or quarantine object as unresolved. Capability probes run inside the container, are cached per device and classify errno into unsupported, conflict and other failures. Cross-directory directory publication journals a temporary owner-write grant and restores the recorded mode by inode. Journal persistence is merged into one file sync, rename and parent sync; the journal carries a format version. --- Documentation/Architecture/Package.md | 32 +- Documentation/Architecture/State.md | 558 +++++---- Documentation/Proposals/AgentsManifest.md | 17 +- Package.swift | 10 +- Sources/AgentsCore/DirectoryHandle.swift | 388 ++++-- Sources/AgentsCore/FileHash.swift | 4 + Sources/AgentsCore/FileTransaction.swift | 1040 ++++++----------- Sources/AgentsCore/SourceCache.swift | 2 +- Sources/AgentsCore/StateStore.swift | 55 +- Sources/AgentsCore/TransactionEvidence.swift | 197 ++++ Sources/AgentsCore/TransactionJournal.swift | 238 ++++ .../AgentsCore/TransactionPermissions.swift | 118 ++ Sources/AgentsCore/TransactionRecovery.swift | 551 +++++++++ Sources/AgentsCore/UpdatePreconditions.swift | 240 ++-- .../InstructionDoctor.swift | 8 +- .../InstructionLifecycleModels.swift | 2 +- .../InstructionOperations.swift | 110 +- .../InstructionTargets.swift | 46 +- .../InstructionUpdatePlan.swift | 43 +- Sources/AgentsSkills/SkillLifecycle.swift | 45 +- Sources/AgentsSkills/SkillOperations.swift | 67 +- Sources/AgentsSkills/SkillUpdatePlan.swift | 33 +- Sources/AgentsUpdates/UpdatePlan.swift | 24 +- Sources/CPlatform/CPlatform.c | 12 +- Sources/CPlatform/include/CPlatform.h | 4 +- .../CachePublicationTests.swift | 77 +- Tests/AgentsCoreTests/CoreTestSupport.swift | 13 + .../DirectoryHandleTests.swift | 13 + .../FileLockProcessTests.swift | 32 +- .../InstructionTransactionTests.swift | 31 +- .../PreparationEvidenceTests.swift | 176 +++ .../AgentsCoreTests/ProcessTestSupport.swift | 12 +- Tests/AgentsCoreTests/PublicationTests.swift | 893 +++++++------- .../StateInspectionTests.swift | 4 +- .../StateTransactionTests.swift | 189 +-- .../TransactionCostTests.swift | 67 ++ .../TransactionMetadataTests.swift | 40 +- .../WatchDurabilityTests.swift | 11 +- Tests/AgentsCoreTests/WatchGitLockTests.swift | 8 +- .../WatchInspectionTests.swift | 2 +- .../WatchMirrorConcurrencyTests.swift | 6 +- .../AgentsCoreTests/WatchReferenceTests.swift | 4 +- Tests/AgentsCoreTests/WatchStateTests.swift | 13 +- .../DoctorLifecycleTests.swift | 6 +- .../AutomaticSelectionTests.swift | 7 +- .../LockedArtifactLifecycleTests.swift | 11 +- .../ReadOnlyInspectionTests.swift | 11 +- .../TransactionDoctorTests.swift | 101 ++ .../UpdateReportingTests.swift | 6 +- .../CombinedUpdateTests.swift | 6 +- .../UpdateTransactionTests.swift | 38 +- Tests/StateTestProcess/main.swift | 78 +- Tests/StateTestSupport/ProcessWait.swift | 69 ++ 53 files changed, 3760 insertions(+), 2008 deletions(-) create mode 100644 Sources/AgentsCore/TransactionEvidence.swift create mode 100644 Sources/AgentsCore/TransactionJournal.swift create mode 100644 Sources/AgentsCore/TransactionPermissions.swift create mode 100644 Sources/AgentsCore/TransactionRecovery.swift create mode 100644 Tests/AgentsCoreTests/PreparationEvidenceTests.swift create mode 100644 Tests/AgentsCoreTests/TransactionCostTests.swift create mode 100644 Tests/AgentsSkillsTests/TransactionDoctorTests.swift create mode 100644 Tests/StateTestSupport/ProcessWait.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 95c7871..acf9c0c 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -31,11 +31,12 @@ ManifestTestSupport ──> AgentsManifest ManifestTestProcess ──> AgentsManifest, AgentsCore, AgentsDescription, ManifestTestSupport AgentsManifestTests ──> AgentsManifest, AgentsDescription, AgentsCore, ManifestTestProcess, ManifestTestSupport, SwiftParser, SwiftSyntax +StateTestSupport (Foundation only) StateTestProcess ──> AgentsCore, AgentsSkills, AgentsInstructions, AgentsUpdates, CPlatform -AgentsCoreTests ──> AgentsCore, StateTestProcess, CPlatform -AgentsSkillsTests ──> AgentsSkills, AgentsCore, AgentsInstructions, Yams, StateTestProcess, CPlatform +AgentsCoreTests ──> AgentsCore, StateTestProcess, StateTestSupport, CPlatform +AgentsSkillsTests ──> AgentsSkills, AgentsCore, AgentsInstructions, Yams, StateTestProcess, StateTestSupport, CPlatform AgentsInstructionsTests ──> AgentsInstructions -AgentsUpdatesTests ──> AgentsUpdates, StateTestProcess, CPlatform +AgentsUpdatesTests ──> AgentsUpdates, StateTestProcess, StateTestSupport, CPlatform ``` `AgentsDescription`, `AgentsManifest`, `AgentsCore`, `AgentsSkills`, @@ -47,10 +48,11 @@ workflow APIs and the state and result models they need. `Package.swift` owns this dependency graph. `CPlatform` is an internal C target for filesystem and process differences. It -wraps file locks, access checks, atomic directory exchange, directory entry names, durable -synchronization, metadata copying and spawn actions. Linux uses -`renameat2(RENAME_EXCHANGE)`, `fsync`, descriptor-based mode/xattr copying -(including POSIX ACLs) and glibc's +wraps file locks, access checks, atomic exchange and no-replace rename, +filesystem-generation comparison, directory entry names, durable synchronization, +metadata copying and spawn actions. Linux uses +`renameat2(RENAME_EXCHANGE)` and `renameat2(RENAME_NOREPLACE)`, `fsync`, +descriptor-based mode/xattr copying (including POSIX ACLs) and glibc's `posix_spawn_file_actions_addclosefrom_np`. Symlink metadata uses no-follow calls through pinned parent paths in `/proc/self/fd`; Linux symlink modes remain 0777. Darwin keeps `renameatx_np`, `F_FULLFSYNC`, `fcopyfile` and its spawn inheritance @@ -61,6 +63,11 @@ bridges APIs missing from those overlays. `AgentsCore` hashes through swift-crypto's `Crypto` product, which delegates to CryptoKit on Apple platforms and supplies its own implementation on Linux. +`StateTestSupport` supplies the shared process-handshake deadline and diagnostics +for transaction, watch and update tests. `StateTestProcess` records actual +checkpoints and supports interruption and resumed recovery through the production +journal protocol. + ## AgentsDescription and AgentsManifest `AgentsDescription` owns the immutable language 1.0 authoring vocabulary. It uses @@ -141,13 +148,18 @@ baselines and seeds belong to the test corpus, not the runtime language. including the complete instruction section, prompt and physical-target models. - `StateStore` owns scope paths, validation, deterministic encoding and state persistence. `FileLock` serializes state access; `FileTransaction` durably - journals replacements across installations, state and cache. Mutating state - access recovers interrupted transactions before proceeding, as described in + journals replacements across installations, state and cache. `FileSnapshot` and + `FileObjectIdentity` own content and physical-object evidence, including directory + descendants and permission bits. `DirectoryHandle` owns verified deletion, + inode-checked directory permission updates and typed cross-directory rename + results. Mutating state access recovers interrupted transactions before + proceeding, as described in [State and cache](State.md). - `SourceCache` owns bare Git mirrors, requirement resolution, exact snapshots, digest-addressed downloads and pruning across skill, instruction and watch pins. `SourceResolutionSession` shares disposable exact snapshots between domain - planners during one update. `StatePrecondition` and `PathIdentity` validate + planners during one update. `StatePrecondition`, `TargetPrecondition` and + `PathIdentity` validate the rendered generation before application. `TransactionOutcome` follows its owning journal through commit and recovery. `ProcessRunner` executes subprocesses. diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index 36acedd..bb0e399 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -7,19 +7,20 @@ | Project | `.agent/agents.json` | `.agent/agents.resolved` | `.agent/agents.watch` | `.agent/cache/` | | 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. 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. +User paths are relative to `RuntimeEnvironment.homeDirectory`. State files +belong 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 `agents.json` records user intent. `agents` defaults to `codex` and `claude-code`. Source aliases name exactly one `git`, `local` or `well-known` 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 +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. `agents.json` and `agents.resolved` are written with sorted keys in Prettier's @@ -27,11 +28,10 @@ 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. +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 { @@ -53,9 +53,9 @@ layout. A skill selection is `"all"` or a name array, with optional exclusions, recipients, mode and per-skill overrides. `all` follows discovery membership on -an unnamed update. Removing a member adds an exclusion. Explicitly named -updates resolve only those members and fail if a requested member is missing. -Skill filesystem identities are unique within a scope across sources. +an unnamed update. Removing a member adds an exclusion. Explicitly named updates +resolve only those members and fail if a requested member is missing. Skill +filesystem identities are unique within a scope across sources. Requirements encode as `branch`, `revision`, `exact`, `from`, `upToNextMinor`, or `from` plus `to`. Ranges include their lower bound and exclude their upper @@ -68,10 +68,9 @@ 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 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. +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. ## Lock @@ -87,179 +86,265 @@ Updating one skill leaves other item pins unchanged. Well-known items record an artifact's `type`, `url` and SHA-256 `digest`. `files` artifacts additionally record every file's URL, path and digest. Their aggregate digest covers the sorted, deterministically encoded file records. -Restoration reads these recorded URLs or verified digest cache entries and -never reads an index. Missing pins or mismatched content stop restoration. +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; 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. +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. Maps are key sorted. Unordered selections and agent lists are sorted; section arrays and each prompt's section order are preserved. Files have a trailing newline and no timestamps. State and journal JSON must be UTF-8 without a byte order mark; validation consumes the entire document. Other encodings, invalid -state, duplicate JSON keys at any depth and -fields that would be discarded by decoding cause an error. Tree hashes use -length-prefixed paths and typed entry payloads, including empty -directories and symbolic link destinations. +state, duplicate JSON keys at any depth and fields that would be discarded by +decoding cause an error. Tree hashes use length-prefixed paths and typed entry +payloads, including empty directories and symbolic link destinations. Tree hashes intentionally exclude permissions. Skill update snapshots compare -the any-execute-bit Boolean separately for regular files. Preparation, -retention and transaction staging verify that dimension without changing -stored hashes, pins or the version 1 declaration, lock and watch schemas. +the any-execute-bit Boolean separately for regular files. Preparation, retention +and transaction staging verify that dimension without changing stored hashes, +pins or the version 1 declaration, lock and watch schemas. ## State Transaction and Recovery -The scope's existing `transaction.json` is the sole persistent transaction owner -for target changes, declaration, lock, watch state, cache publication and pruning. -The protocol accepts regular files, directories and symbolic links independently -of the declaration format. Declaration and lock retain their state encoders; -watch state retains its fixed encoder. +The scope's `transaction.json` is the sole persistent transaction owner for +installation targets, declaration, lock, watch state, cache publication and +pruning. Its protocol accepts regular files, directories and symbolic links +independently of the declaration format. Declaration and lock keep their state +encoders; watch state keeps its fixed encoder. ### Preparation and preconditions -Prepare records presence, physical identity and content digest for declaration, -lock, watch state and affected targets. `UpdatePreconditions` binds final entries -and existing ancestry; state snapshots also record bytes through their digest. -Skill and instruction plans validate source snapshots, target content and -executable flags. The scope writer lock covers recovery, preparation, retention -and publication. Recovery runs first. Apply re-reads preparation conditions before -retention and again immediately before publication, including after transaction -staging. Any changed bytes, including declaration whitespace or comments in a -rendered target, or another inode with equal bytes invalidates that preparation. -Apply requires a newly prepared plan rather than rebasing an old edit. +Prepare captures presence, physical identity and content digest for declaration, +lock, watch state and affected targets. `TargetPrecondition`, `PathIdentity` and +`StatePrecondition` in `UpdatePreconditions.swift` bind those snapshots and +existing ancestry. Directory target snapshots include descendant identities. +Linked non-edit content is checked separately from its link; live edit content +remains live. Domain plans also validate source content and executable flags. + +The scope writer lock covers recovery, preparation, retention and publication. +Recovery runs first. Apply checks the prepared evidence before retention, after +retention at commit entry, and after staging before publication. The journal +receives the plan's captured preimages rather than taking a later state +baseline. Transactions without a state plan, such as cache publication, do not +implicitly add declaration, lock or watch preconditions. Domain hooks check +related inputs that the journal does not replace. State parsing consumes the +captured raw bytes, so decoded inputs and journal evidence describe the same +generation. + +Changed bytes, including declaration whitespace or target comments, invalidate +preparation. Another inode with equal bytes also invalidates a captured target +entry or directory descendant. Apply requires a newly prepared plan and never +rebases an old edit onto changed inputs. Readers and writers serialize through `.agents.lock`. Missing scope and target -ancestry is created with descriptor-relative operations; each parent directory -is fsynced before target mutation, including when an interrupted creator left a -visible directory entry. Empty managed containers can remain after a failed -operation. +ancestry is created with descriptor-relative operations. Parent directories are +synced before target mutation, including when an interrupted creator left a +visible entry. Empty ancestor directories can remain after a failed operation. +Successful managed directory creation uses mode 0700; files and locks use 0600. +Final file modes are set explicitly rather than inherited from the process +umask. Copies preserve their source modes, ACLs and extended attributes. -Managed directories are created with mode 0700 and files/locks with mode 0600. Directory permissions, inherited/default ACLs and other filesystem policy must -allow the owner to use newly created entries. Core checks access without changing -that policy. Permission denial stops the operation with the affected path and a -message to check directory permissions and default ACLs; retries remain denied -until the environment is corrected. This is a filesystem requirement, not a -transaction recovery case. Existing user content and metadata are preserved. - -Journal 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 files in the project's own instructions container. The journal binds the -state directory, each used root and every destination parent to its physical -location and filesystem identity. Configured agent containers resolve at the -registry boundary; descendants open without following links. Symlinked journals, -symlinked descendants, unregistered destinations, overlapping targets and journals -copied or moved from another location are rejected before replay. Directory -descriptors remain pinned. Recovery names derive from the transaction UUID and -entry index, never from arbitrary paths in journal input. - -Each operation records its expected presence and preimage, staged object and -intended postimage before publication. Object evidence includes device, inode, -entry type, SHA-256 digest and executable status; directory snapshots include -child identities and digests. Staging and extraction scratch have recorded -ownership and are sealed before publication. The journal records per-operation -`queued`, `verifying`, `ready`, `publishing`, `applied`, `restoring`, `restored` or `cancelled` -progress, plus cleanup evidence and unresolved conflicts. File contents, -metadata, read preimages, journal records and parent directories are synchronized -in dependency order. Data replacements inherit the existing regular file's metadata. Copies -preserve modes, ACLs and extended attributes on macOS and Linux; rollback restores -the retained original object and its metadata. +allow owner access to newly created entries. Core checks that access without +repairing the policy. Permission denial reports the affected path and asks the +owner to check directory permissions and default ACLs. Retrying does not bypass +the denial. Existing user content and metadata are preserved. + +### Journal records + +Journal format version 1 is independent of declaration, lock and watch versions. +The root records its version, transaction UUID, scope identity, registered root +identities, transaction phase, operations, private containers and discard +intent. A journal without this version, or with another version, is retained +unchanged. Recovery reports that it was written by another version and must be +recovered with the version that wrote it; it does not guess a compatible replay. + +Paths are relative to named roots: scope state, registered agent installation +directories and registered instruction destinations. The journal binds the state +directory, each root and every destination parent to its physical location and +identity. Registry boundaries resolve configured containers; descendants open +without following links. Symlinked journals or descendants, overlapping targets, +unregistered paths and copied or moved journals are rejected before replay. +Directory descriptors remain pinned. + +Each operation records its path, install/delete action, expected preimage or +absence, parent identity, private container, sealed staged object, progress and +any conflict reason and retained locations. Object evidence contains device, +inode, type, SHA-256 digest, permission bits and executable status. Directory +evidence includes child identities and digests. Data replacements inherit the existing regular +file's metadata. Undo restores the original object and its metadata. + +Each used target parent has one private container with a UUID-derived name and +mode 0700 on the same filesystem as its targets. The journal records the name +before `mkdir`, then records the container's physical identity before inserting +anything. Probes, extraction work and staging stay inside it. An identified +container owns all construction before publication: incomplete objects can be +discarded as a whole without individual ownership evidence. Another writer has +no ownership claim on content inserted into this private transaction storage. An +unidentified container may only be removed with `rmdir` when empty; a nonempty +one is an unresolved conflict. + +Construction is sealed once. Snapshot and content verification consume the same +read bytes, and check the expected content hash and executable flags. `ready` +and that snapshot become durable together. Changes after sealing are conflicts; +recovery never refreshes a sealed snapshot to adopt changed content. +Construction checkpoints do not rewrite the journal or rescan a growing copy. + +Preimages displaced by exchange, deletion quarantines and published objects are +user data. Their identity and digest remain mandatory evidence even inside a +private container. A container holding such recovery objects receives complete +terminal disposal evidence after their expected distribution has been verified. + +| Progress | Durable evidence and possible distribution | +| --- | --- | +| `queued` | Expected preimage and container name; construction is private and unsealed. | +| `ready` | Verified staged snapshot for an install; no publication intent. | +| `publishing` | Publication and temporary directory-write intent; objects can be prepared or installed. | +| `applied` | Rename parents and original directory modes synced; postimage and preimage verified. | +| `restoring` | Undo and temporary directory-write intent; installed or reverted objects can be present. | +| `restored` | Undo parents and original modes synced; restored target and rollback quarantine verified. | +| `cancelled` | Original modes restored; publication did not consume private staging. | + +One operation-type/progress table defines every expected target and recovery +slot. Publication validation, rollback classification and disposal preparation +use that table. Before durable discard intent, an expected preimage or rollback +quarantine must exist and match; absence cannot be treated as completed cleanup. + +Journal publication orders the new journal file barrier before rename, then the +parent directory barrier. Ordinary preimage files are synced once with their +parent barrier; tree synchronization syncs file contents and concentrates each +level's directory barrier after its children. On macOS a synchronization barrier +also uses `F_FULLFSYNC` to request a storage flush. ### Publication and concurrent writers -Before changing any destination, capability checks require atomic exchange and -atomic no-replace rename. Filesystem probes use recorded private objects within -the same journal; unsupported primitives fail before any destination publication. -There is no replacing-rename fallback for managed destinations, including newly -created declaration, lock and watch files. +Atomic exchange and no-replace rename are checked before modifying any target, +preimage or state file. Before this check the transaction can only create +missing ancestry, its journal and its private containers. Probes run on +container objects on the actual publication device. Successful capability +results are cached by `st_dev` within the process. Unsupported primitives remove +the journal and containers; empty missing ancestry may remain. There is no +replacing-rename fallback, including for declaration, lock and watch creation. + +Only `EINVAL`, `ENOSYS`, `ENOTSUP` and `EOPNOTSUPP` mean unsupported. `EEXIST` +and `ENOTEMPTY` mean an existence conflict. Other failures retain their errno +and system reason. Probes and publication use the same classification. | Expected destination | Publication | | --- | --- | -| Absent | Persist staging identity and digest, then publish with `renameat2(RENAME_NOREPLACE)` on Linux or `renameatx_np(RENAME_EXCL)` on macOS. An existence conflict preserves the concurrent creator's bytes and inode. | -| Existing | Revalidate the exact read preimage and atomically exchange it with staging. Retain the displaced object, read and compare its identity and digest, and retain it as the rollback preimage. Unexpected content is a conflict preimage and cannot count as a successful replacement. | -| Deletion | Revalidate the preimage and move it without replacement into the journal's unique quarantine. Verify the quarantined object's identity and digest before confirming the operation or disposing of it. | - -Publication intent is durable before the atomic operation. The destination parent -is synchronized before `applied` is persisted. The retained preimage and the -published object must both match before a replacement is confirmed. Every -postimage is checked again before the commit marker. The scope lock excludes -cooperating writers; these publication checks also preserve objects changed by -editors that ignore the lock. +| Absent | Persist the sealed inode and digest, then move it from the container with Darwin `renameatx_np(RENAME_EXCL)` or Linux `renameat2(RENAME_NOREPLACE)`. A concurrent creator keeps its bytes and inode. | +| Existing | Recheck the preimage, then exchange it with staging using Darwin `RENAME_SWAP` or Linux `RENAME_EXCHANGE`. The displaced object stays inside the container and is compared before confirmation. A mismatched preimage is retained as a conflict. | +| Deletion | Move the entry without replacement into the container's quarantine, then verify its physical identity and digest. Destructive cleanup verifies that evidence again. | + +Publication intent is durable before rename. Both container and target parent +are synced before `applied` becomes durable. Replacement always retains a +directory entry at the installation path. The operation's complete target and +recovery-object distribution must match before confirmation and again before the +commit marker. The scope lock excludes cooperating writers; the atomic protocol +also preserves objects changed by editors that ignore it. + +Read-only directory roots retain their final modes. Darwin requires write access +to relocate a directory between parents. Before granting owner-write on a recorded +inode, `publishing` or `restoring` intent and the original permission bits are +durable. The transaction syncs the temporary mode, performs the atomic rename, +then restores and syncs the original mode before recording `applied`, `restored` +or `cancelled`. Only the recorded mode or that mode plus owner-write is admitted +while intent is active. Other modes and other inodes remain conflicts; ACL and +ownership denials are reported rather than bypassed. ### Recovery outcomes +Every mutating state operation first checks for an abandoned journal under the +scope lock, validates watch state and finishes pending reference cleanup before +proceeding. Journal recovery selects and syncs a consistent generation before +watch reconciliation can release any ref. Pending watch-reference recovery also +reports `CoreError.transactionRecovered` when no journal remains. Retained refs +remain available while a journal conflict is unresolved. + An applying journal reverses verified publications in reverse order. A committed -journal completes terminal cleanup. Recovery uses recorded physical identity and -digest, including when a process died between rename and recording `applied`. -Another inode with identical bytes remains external. Missing or changed evidence -leaves an unresolved conflict rather than establishing ownership by name or -content equality. Other verified operations can roll back while conflicted -objects and their journal remain available for owner resolution. - -Replacement rollback exchanges the retained preimage only with the verified -transaction-owned postimage and verifies the displaced object again. If an -external writer changes the destination before or during restoration, both -available versions remain and recovery stops. Deletion restoration uses atomic -no-replace rename; an occupied original name remains untouched. Creation rollback -moves only the verified published object into quarantine and verifies it there; -it never unlinks an external creator's object. A reverse rename is synchronized -even when a retry recognizes that it already happened. - -Before deleting staging, probes, scratch or preimages, the journal persists a -terminal `committed` or `rolledBack` phase with each disposal object's identity -and digest. The observed terminal journal and its parent are synchronized even -when the phase was already visible on entry. Per-entry discard intent is durable -before deletion. Cleanup verifies ownership, records descendant evidence and -accepts only already removed descendants on retry; changed or newly introduced -objects remain conflicts. Discarded directories may receive owner access through -pinned descriptors without changing the installed or restored tree's metadata. -Symbolic links are removed without following their destinations. Parent deletion -barriers also run for already absent entries. On macOS synchronization also uses -`F_FULLFSYNC` to request a storage flush. - -Recovery is repeatable across interruption. The next recovering state access -reports `CoreError.transactionRecovered` after it establishes a consistent -generation; callers retry the whole preparation. Outcome tracking belongs to the -transaction UUID: recovering a cache publication cannot mark a later combined -update committed. Failures distinguish confirmed unchanged, confirmed committed -and unresolved recovery. A commit marker alone does not establish successful -cleanup: changed recovery evidence after that marker reports unresolved recovery -and retains the journal and remaining recovery material. A committed failure -must not be described as rollback. +journal completes terminal cleanup. Physical identity and digest distinguish a +transaction's publication even after rename but before `applied`. Another inode +with identical bytes remains external. Missing or changed evidence causes an +unresolved conflict; names and equal bytes never establish ownership. Other +verified operations can roll back while conflicted objects remain available. + +Replacement undo exchanges a retained preimage only with the verified published +object and verifies the displaced object. An external replacement before or +during undo leaves both available versions and stops recovery. Deleted entries +return with no-replace rename, preserving an occupied original name. Creation +undo moves only a verified published object into rollback quarantine and checks +it there. A retry recognizing an interrupted reverse rename repeats both parent +barriers before recording restoration. + +Interrupted permission changes are restored by recorded inode, independently of +payload rollback. Changed payload bytes remain available. Restoration repeats the +mode barrier even when the original mode is already visible. A recorded directory +inode missing from all known locations, or a mode outside the original/temporary +pair, leaves an unresolved conflict with the original mode and intent retained. + +Before disposal the journal persists terminal `committed` or `rolledBack` state +and the complete recovery-object evidence. A terminal marker observed on entry +may have been renamed without its directory barrier: recovery syncs the marker +and its parent before deleting any resource. A separate global discard intent +then becomes durable. Only after that intent may missing objects or descendants +mean interrupted cleanup. Changed identities, digests or unexpected descendants +in sealed disposal evidence remain conflicts. Unpublished private construction +is discarded by verified container identity. Links are never followed during +deletion. Owner access may be granted to discarded directories without changing +installed or restored metadata. Absent entries still receive a parent barrier. + +Conflicts retain `transaction.json`, the available target objects and private +containers holding displaced preimages or rollback quarantines. Each conflicting +entry records the reason and scope-relative recovery locations. Doctor lists +those reasons and locations and asks for owner action; it does not promise that +another write will resolve them or provide a conflict-resolution command. + +Recovery can itself be interrupted and repeated. Successful recovery reports +`CoreError.transactionRecovered` and callers retry the whole preparation. +Outcomes distinguish unchanged, committed and unresolved recovery and belong to +their journal UUID: recovering a cache publication cannot mark a later combined +update committed. Failure after a commit marker can still be unresolved if +recovery material changed. A committed failure is never described as rollback. + +The public `StateStore.loadDeclaration`, `loadResolved` and `loadWatch` +accessors retain their writer-lock and recovering-loader semantics. ### Read-only access Non-applying skill and instruction operations, listings, previews, watch status and watch diff take an existing shared lock, report pending recovery and never -replay it or create state files. When the lock is absent, inspection reads and -then checks for a newly created lock or recovery marker before returning either -its result or its error. If a writer appeared, inspection discards that attempt -and retries under the shared lock. Writers create the scope lock before mutation -and never remove it. Pending journals and watch-reference cleanup markers cause -`CoreError.invalidState`; doctor reports one pending-recovery diagnostic per -affected scope and skips checks requiring a consistent generation. Explicit -multi-root instruction audits never write. Corrupt journals stop recovery without -guessing a plan. +replay it or create state files. With no lock, inspection rechecks for a new +lock or recovery marker before returning either its result or its error. A +writer causes that attempt to be discarded and retried under the shared lock. +Writers create the scope lock before mutation and never remove it. + +Pending journals and watch-reference markers stop inspection with +`CoreError.invalidState`. Doctor distinguishes pending automatic recovery from +an unresolved conflict requiring owner action, and skips checks needing a +consistent generation. Skill doctor uses `pending-recovery` or +`unresolved-transaction`; instruction doctor uses `pendingRecovery` or +`unresolvedTransaction`. Explicit multi-root instruction audits never write. +Corrupt or foreign-version journals remain available rather than being replayed. ### Watch references and mirror locks Mirror Git invocations pass `-c core.fsync=objects,reference,pack-metadata` and `-c core.fsyncMethod=fsync`; durability settings never rewrite configuration. -Mirror configuration must be a regular file, checked before invoking Git. -Before a Git acknowledgment publishes watch state, existing object bytes and -object directory entries are flushed as well. The retained ref, its parent, -Git config and HEAD, and mirror/cache directory entries are synced before the -scope journal can commit the baseline. This orders durable Git content before -the durable watch reference; power loss cannot publish a baseline ahead of its -retained content. +Mirror configuration must be a regular file, checked before invoking Git. Before +a Git acknowledgment publishes watch state, existing object bytes and object +directory entries are flushed as well. The retained ref, its parent, Git config +and HEAD, and mirror/cache directory entries are synced before the scope journal +can commit the baseline. This orders durable Git content before the durable +watch reference; power loss cannot publish a baseline ahead of its retained +content. Before preparing a watch ref or changing watch/lock pins, the scope writes and syncs `watch-refs.pending`. Under the scope lock, reconciliation runs only after @@ -268,35 +353,40 @@ consistent generation. It removes only `refs/agents-watch/` refs no longer named by watch state, skills, instruction sections or prompt sections. Loose-ref parents and packed refs are synced before the pending marker is removed and its parent synced. The marker survives interrupted preparation or -cleanup, so the next mutating access repeats reconciliation against the recovered -state; refs needed for rollback remain until that state is durable. +cleanup, so the next mutating access repeats reconciliation against the +recovered state; refs needed for rollback remain until that state is durable. Mirrors are exclusively owned by agents. Each mirror has a per-source lock at `cache/locks/.lock`, created before cloning or first access. All mirror reads and writes take this lock, including instruction listings and cached revision inspection. Doctor uses only existing mirror locks; when one is -absent, cached revision inspection falls back to remote refs without creating it. -Scope mutations take the scope lock first, then the mirror lock; mirror access never acquires the scope lock in reverse order. -An instruction listing can therefore populate a mirror before `.agents.lock` -exists while still excluding concurrent recovery and watch mutations. +absent, cached revision inspection falls back to remote refs without creating +it. Scope mutations take the scope lock first, then the mirror lock; mirror +access never acquires the scope lock in reverse order. An instruction listing +can therefore populate a mirror before `.agents.lock` exists while still +excluding concurrent recovery and watch mutations. + +Pending Git ref cleanup can leave mirror Git lock files that prevent safe fetch. +Recovery takes the mirror lock and validates and syncs their cleanup before Git +can proceed. Git children explicitly inherit a duplicate of the mirror lock descriptor allocated at 3 or above with `F_DUPFD_CLOEXEC`. Spawn file actions inherit that duplicate without changing the parent's close-on-exec flags. Output pipe sources also use descriptors above the standard streams before redirection; closed stdin is connected to `/dev/null` in the child. Unrelated descriptors remain closed, -and the parent closes the temporary duplicates immediately after spawning. -The parent closes its lock descriptor without explicitly unlocking the shared -open file description. If the Swift -parent is killed, a surviving Git child keeps the mirror locked until it exits. -Git automatic maintenance is disabled. Recovery must acquire this same mirror -lock before classifying Git `*.lock` files (including `packed-refs.lock`) and -the root `packed-refs.new` staging file as abandoned. Within each mirror it -validates all candidates as regular files through directory descriptors, -without following symlinks, before deleting any candidate. It syncs lock-file -deletions before retrying Git; the pending marker also covers interruption of -this cleanup. Live mirror users and surviving Git children block recovery, so -their Git locks and refs cannot be removed or recreated beneath them. +and the parent closes the temporary duplicates immediately after spawning. The +parent closes its lock descriptor without explicitly unlocking the shared open +file description. If the Swift parent is killed, a surviving Git child keeps the +mirror locked until it exits. Git automatic maintenance is disabled. Recovery +must acquire this same mirror lock before classifying Git `*.lock` files +(including `packed-refs.lock`) and the root `packed-refs.new` staging file as +abandoned. Within each mirror it validates all candidates as regular files +through directory descriptors, without following symlinks, before deleting any +candidate. It syncs lock-file deletions before retrying Git; the pending marker +also covers interruption of this cleanup. Live mirror users and surviving Git +children block recovery, so their Git locks and refs cannot be removed or +recreated beneath them. Git runs with terminal and Git Credential Manager prompting disabled while preserving the rest of the inherited environment. Failures identify the action @@ -304,23 +394,17 @@ and source location rather than its mirror, staging or extraction paths; see [process execution and errors](Package.md#process-execution-and-errors) for the consumer error contract. -Each mutating state operation checks for an abandoned journal under the scope -lock, validates watch state and finishes pending reference cleanup before -proceeding. Recovery of pending watch references also reports -`CoreError.transactionRecovered` when no journal remains. Retained refs remain -available while any journal conflict is unresolved. - ## Materialization and Installation Git materializations, downloaded artifact bytes and expanded artifact trees use private journal-owned staging. Exact Git commits are extracted there; expanded artifacts are checked against their locked tree hash. Copied trees are hashed through pinned directory descriptors and verified before publication. Files, -metadata and directory entries are synced before atomic publication of the -final cache name. Git extraction scratch also belongs to the journal, so -recovery cleans an incomplete copy or extraction without retaining a partial -final directory just because the lock references its pin. Cache publication -completes before the installation transaction references that content. +metadata and directory entries are synced before atomic publication of the final +cache name. Git extraction scratch also belongs to the journal, so recovery +cleans an incomplete copy or extraction without retaining a partial final +directory just because the lock references its pin. Cache publication completes +before the installation transaction references that content. Each scope's cache contains: @@ -333,76 +417,78 @@ cache/ locks/ ``` -A source key combines a readable prefix and the SHA-256 of its normalized ID. -A source has one bare mirror; requirement resolution reads its refs and tags. +A source key combines a readable prefix and the SHA-256 of its normalized ID. A +source has one bare mirror; requirement resolution reads its refs and tags. Exact trees are extracted with Git archive and contain no repository metadata. Read-only revision inspection uses local Git reads or remote ref advertisements -with the same requirement selection policy, without fetching or populating caches. -Consumers of the same source and revision share a materialized directory. +with the same requirement selection policy, without fetching or populating +caches. Consumers of the same source and revision share a materialized +directory. `link` points an agent's skill entry at verified cached content. `copy` installs that content as a directory and rejects links escaping the installed subtree. Links to content within the same project or user state root are relative, so -moving that root preserves them; external live edit links are absolute. -`edit` points directly at a live local skill -without pin or hash and requires a source without a requirement. Local -non-Git directories support edit mode. Git-backed link and copy operations read -committed trees, including when the source has uncommitted changes. - -An update preview or source listing can fetch into a mirror. -Inspection snapshots are disposable and do not move an installed tree or write -state or targets. Skill and instruction `add` discover choices through the read -path when no names or `all` are supplied, and for `listOnly`. Their discovery -uses disposable mirrors and locks, leaving the scope unchanged. Exact cached -commits can be extracted under an existing mirror lock without fetching. Pending -recovery stops selection discovery before source access. An automatic single-item -addition carries the normalized source ID and exact discovered name into the -writer path separately from user-entered names. Rediscovery must match that -identity or fail with an error asking the caller to retry; its content and pin -can refresh. Explicit names and `all` enter the writer path directly. -Applying prepares all selected content, computes differences, -stages replacements, and commits target changes and state under the scope lock. +moving that root preserves them; external live edit links are absolute. `edit` +points directly at a live local skill without pin or hash and requires a source +without a requirement. Local non-Git directories support edit mode. Git-backed +link and copy operations read committed trees, including when the source has +uncommitted changes. + +An update preview or source listing can fetch into a mirror. Inspection +snapshots are disposable and do not move an installed tree or write state or +targets. Skill and instruction `add` discover choices through the read path when +no names or `all` are supplied, and for `listOnly`. Their discovery uses +disposable mirrors and locks, leaving the scope unchanged. Exact cached commits +can be extracted under an existing mirror lock without fetching. Pending +recovery stops selection discovery before source access. An automatic +single-item addition carries the normalized source ID and exact discovered name +into the writer path separately from user-entered names. Rediscovery must match +that identity or fail with an error asking the caller to retry; its content and +pin can refresh. Explicit names and `all` enter the writer path directly. +Applying prepares all selected content, computes differences, stages +replacements, and commits target changes and state under the scope lock. Combined updates share a source-resolution session and baseline across skills and instructions. The coordinator merges their owned records and rejects incompatible source records and overlapping targets before exposing an apply handle. It holds the writer lock while the consumer renders, revalidates state-file bytes/presence and target/source identities, then retains pinned -content before the combined journal starts. Live edit content remains live; -its source identity and usable metadata are checked instead of a content pin. +content before the combined journal starts. Live edit content remains live; its +source identity and usable metadata are checked instead of a content pin. After retention, preconditions are checked again. One transaction queues -physical skill targets, instruction/forwarding targets, changed declaration -and lock files, and pruning against the merged lock and existing watch state. -Paths are sorted within target groups. No-change combined apply returns -receipts without rewriting state. Cancellation before apply publishes no -targets, state or retained trees; fetched mirror objects and the scope -container/lock may remain. - -Commit outcome tracking is bound to the combined journal's UUID. Recovering -a separate cache publication cannot claim that the combined generation -committed. An uncertain commit-marker write is classified by validated -recovery. `UpdateApplyError` distinguishes confirmed unchanged and committed -generations from unresolved recovery, including failures during enclosing -watch-reference cleanup. A committed error must not be described as rollback. -After process death the next writer recovers and raises -`CoreError.transactionRecovered`; consumers retry the whole preparation. -Previews reject pending recovery without replay. See [Updates](Updates.md) -for the public handle and error contracts. +physical skill targets, instruction/forwarding targets, changed declaration and +lock files, and pruning against the merged lock and existing watch state. Paths +are sorted within target groups. No-change combined apply returns receipts +without rewriting state. Cancellation before apply publishes no targets, state +or retained trees; fetched mirror objects and the scope container/lock may +remain. + +Commit outcome tracking is bound to the combined journal's UUID. Recovering a +separate cache publication cannot claim that the combined generation committed. +An uncertain commit-marker write is classified by validated recovery. +`UpdateApplyError` distinguishes confirmed unchanged and committed generations +from unresolved recovery, including failures during enclosing watch-reference +cleanup. A committed error must not be described as rollback. After process +death the next writer recovers and raises `CoreError.transactionRecovered`; +consumers retry the whole preparation. Previews reject pending recovery without +replay. See [Updates](Updates.md) for the public handle and error contracts. Pruning participates in that transaction. Pins referenced by skills, instruction -sections or prompt sections remain cached, as do artifact contents referenced -by watch state and trees containing live edit sources. Pruning opens directory -ancestry without following symlinks and uses -directory-relative enumeration, rename and deletion. It rejects symlinked cache -containers and never recursively follows a link during cleanup. -Mirrors remain available for source history and future resolution. Watch-owned -Git refs retain only revisions still referenced by watch state or installed -pins; obsolete histories can be collected by Git after those refs are released. +sections or prompt sections remain cached, as do artifact contents referenced by +watch state and trees containing live edit sources. Pruning opens directory +ancestry without following symlinks and uses directory-relative enumeration, +rename and deletion. It rejects symlinked cache containers and never recursively +follows a link during cleanup. Mirrors remain available for source history and +future resolution. Watch-owned Git refs retain only revisions still referenced +by watch state or installed pins; obsolete histories can be collected by Git +after those refs are released. Both doctors inspect cached objects, local Git refs or remote ref advertisements without fetching or populating caches. Local Git status disables optional locks to avoid index refresh writes. Skill doctor reports pending recovery as a -`DoctorCheck` with ID `pending-recovery` and warning status. It also reports -missing installs, changed content and broken links, newer matching Git resolutions, and uncommitted changes in selected local source -paths. `install` restores all recorded recipients and modes without changing -lock bytes. The consuming CLI controls presentation and user interaction. +`DoctorCheck` with ID `pending-recovery` and warning status. An unresolved +transaction uses `unresolved-transaction` and lists retained recovery locations. +It also reports missing installs, changed content and broken links, newer +matching Git resolutions and uncommitted changes in selected local source paths. +`install` restores all recorded recipients and modes without changing lock +bytes. The consuming CLI controls presentation and user interaction. \ No newline at end of file diff --git a/Documentation/Proposals/AgentsManifest.md b/Documentation/Proposals/AgentsManifest.md index 0d00157..3b71913 100644 --- a/Documentation/Proposals/AgentsManifest.md +++ b/Documentation/Proposals/AgentsManifest.md @@ -1410,6 +1410,18 @@ syntax; editability remains a document-layer capability. [State Transaction and Recovery](../Architecture/State.md#state-transaction-and-recovery) owns the current publication, precondition and recovery guarantees. +### Manifest integration + +Manifest orchestration must publish validated source bytes in place of declaration +re-encoding. The deployment ledger and watch state retain their own encoders. +One transaction includes the source, ledger, affected watch state, native outputs, +cache retention and cleanup. Source-only changes use the same protocol. + +Preparation records presence, physical identity and byte digest for the manifest, +ledger, watch state and related targets. A changed comment also invalidates the +prepared preview. These obligations belong to the integration that connects +`Agents.swift` to the state engine. + ### Approvals Approval identity covers declarations, commands and shipped content, excluding @@ -1522,8 +1534,9 @@ last argument. Empty collections are `[]` or `[:]`. No formatting pass touches an already migrated manifest. One transaction creates `Agents.swift`, upgrades an existing ledger as needed and -removes `agents.json`. Creation uses the no-replace protocol above. Existing native -files, cache content and watch-state bytes do not change. A missing ledger stays +removes `agents.json`. Creation uses the +[no-replace protocol](../Architecture/State.md#publication-and-concurrent-writers). +Existing native files, cache content and watch-state bytes do not change. A missing ledger stays missing. Repeating migration after success is unchanged. Both declaration files present is a conflict; Swift source with a version-1 lock permits a lock-only migration. Normal commands report required migration rather than converting diff --git a/Package.swift b/Package.swift index e515d69..c823cba 100644 --- a/Package.swift +++ b/Package.swift @@ -44,6 +44,7 @@ let package = Package( .target( name: "AgentsUpdates", dependencies: ["AgentsCore", "AgentsSkills", "AgentsInstructions", "CPlatform"]), + .target(name: "StateTestSupport", path: "Tests/StateTestSupport"), .executableTarget( name: "StateTestProcess", dependencies: [ @@ -51,7 +52,8 @@ let package = Package( ], path: "Tests/StateTestProcess"), .testTarget( - name: "AgentsCoreTests", dependencies: ["AgentsCore", "StateTestProcess", "CPlatform"]), + name: "AgentsCoreTests", + dependencies: ["AgentsCore", "StateTestProcess", "StateTestSupport", "CPlatform"]), .testTarget(name: "AgentsInstructionsTests", dependencies: ["AgentsInstructions"]), .target( name: "ManifestTestSupport", dependencies: ["AgentsManifest"], @@ -70,11 +72,13 @@ let package = Package( ], resources: [.copy("Fixtures")]), .testTarget( - name: "AgentsUpdatesTests", dependencies: ["AgentsUpdates", "StateTestProcess", "CPlatform"]), + name: "AgentsUpdatesTests", + dependencies: ["AgentsUpdates", "StateTestProcess", "StateTestSupport", "CPlatform"]), .testTarget( name: "AgentsSkillsTests", dependencies: [ - "AgentsSkills", "AgentsCore", "AgentsInstructions", "Yams", "StateTestProcess", "CPlatform", + "AgentsSkills", "AgentsCore", "AgentsInstructions", "Yams", "StateTestProcess", + "StateTestSupport", "CPlatform", ]), ], swiftLanguageModes: [.v6] diff --git a/Sources/AgentsCore/DirectoryHandle.swift b/Sources/AgentsCore/DirectoryHandle.swift index 8b5e74f..8b6a7a8 100644 --- a/Sources/AgentsCore/DirectoryHandle.swift +++ b/Sources/AgentsCore/DirectoryHandle.swift @@ -1,8 +1,10 @@ import CPlatform import Foundation +import Synchronization /// Pins directory ancestry. Child operations never traverse symbolic links. final class DirectoryHandle { + @TaskLocal static var synchronizationObserver: (@Sendable () -> Void)? let descriptor: Int32 let url: URL @@ -88,87 +90,276 @@ final class DirectoryHandle { return names.sorted() } - /// Deletes an owned subtree, granting owner access only to directories being discarded. - func remove(_ name: String, checkpoint: (String) throws -> Void = { _ in }) throws { - if let info = try info(name) { - if info.st_mode & S_IFMT == S_IFDIR { - let directory = try child(name) - if info.st_mode & S_IRWXU != S_IRWXU { - guard fchmod(directory.descriptor, (info.st_mode & 0o7777) | S_IRWXU) == 0 else { - throw CoreError.unsafePath("cannot make discarded directory writable: \(name)") - } + enum RemovalStep: String { case unlinked, synced } + struct RemovalPoint { + let path: String + let step: RemovalStep + } + + /// Missing descendants are accepted only by callers with a durable discard intent. + /// Private trees and verified user objects share the same descriptor-relative deleter. + func remove( + _ name: String, expecting expected: FileSnapshot? = nil, + identity expectedIdentity: FileObjectIdentity? = nil, + checkpoint: (RemovalPoint) throws -> Void = { _ in } + ) throws { + try removeContents( + name, expected: expected, identity: expectedIdentity, prefix: name, + checkpoint: checkpoint) + // An absent entry may be an interrupted unlink whose parent was not synced. + try sync() + try checkpoint(RemovalPoint(path: name, step: .synced)) + } + + private func removeContents( + _ name: String, expected: FileSnapshot?, identity: FileObjectIdentity?, prefix: String, + checkpoint: (RemovalPoint) throws -> Void + ) throws { + guard let info = try info(name) else { return } + let observed = FileObjectIdentity(info) + if let identity, observed != identity { + throw CoreError.invalidState("transaction cleanup identity changed: \(name)") + } + if let expected, observed != expected.identity { + throw CoreError.invalidState("transaction cleanup ownership changed: \(name)") + } + if info.st_mode & S_IFMT == S_IFDIR { + let directory = try child(name) + if info.st_mode & S_IRWXU != S_IRWXU { + guard fchmod(directory.descriptor, (info.st_mode & 0o7777) | S_IRWXU) == 0 else { + throw CoreError.unsafePath("cannot make discarded directory writable: \(name)") } - for entry in try directory.names() { try directory.remove(entry) } - guard unlinkat(descriptor, name, AT_REMOVEDIR) == 0 else { - throw CoreError.unsafePath("cannot remove directory: \(name)") + } + for child in try directory.names() { + if let expected, expected.children?[child] == nil { + throw CoreError.invalidState("unexpected transaction descendant: \(child)") } - } else if unlinkat(descriptor, name, 0) != 0 { - throw CoreError.unsafePath("cannot remove entry: \(name)") + try directory.removeContents( + child, expected: expected?.children?[child], identity: nil, + prefix: prefix + "/" + child, checkpoint: checkpoint) + } + try directory.sync() + } else if let expected, try FileSnapshot.read(name, from: self) != expected { + throw CoreError.invalidState("transaction cleanup content changed: \(name)") + } + guard try self.info(name).map(FileObjectIdentity.init) == observed else { + throw CoreError.invalidState("transaction cleanup identity changed: \(name)") + } + guard unlinkat(descriptor, name, info.st_mode & S_IFMT == S_IFDIR ? AT_REMOVEDIR : 0) == 0 + else { + throw CoreError.invalidState("cannot discard filesystem entry: \(name): \(errno)") + } + try checkpoint(RemovalPoint(path: prefix, step: .unlinked)) + } + + /// Only an empty unidentified container may be removed; rmdir never erases contents. + func removeEmptyDirectory(_ name: String) throws { + guard unlinkat(descriptor, name, AT_REMOVEDIR) == 0 || errno == ENOENT else { + throw CoreError.invalidState("unidentified transaction container is not empty: \(name)") + } + try sync() + } + + enum RenameMode: Sendable { case exchange, exclusive } + enum RenameResult: Equatable { + case success + case exists(Int32) + case unsupported(Int32) + case failure(Int32) + + init(code: Int32) { + if code == 0 { + self = .success + } else if code == EEXIST || code == ENOTEMPTY { + self = .exists(code) + } else if [EINVAL, ENOSYS, ENOTSUP, EOPNOTSUPP].contains(code) { + self = .unsupported(code) + } else { + self = .failure(code) + } + } + + func requireSuccess(_ operation: String) throws { + switch self { + case .success: return + case .exists(let code): + throw CoreError.invalidState( + "transaction destination already exists: \(operation): \(code) (\(String(cString: strerror(code))))" + ) + case .unsupported(let code): + throw CoreError.unsupported( + "atomic rename is required: \(operation): \(code) (\(String(cString: strerror(code))))") + case .failure(let code): + throw CoreError.invalidState( + "cannot \(operation): \(code) (\(String(cString: strerror(code))))") + } + } + } + + // A nil override delegates to the platform primitive; injected errno takes the same classifier. + @TaskLocal static var atomicRenameFailure: (@Sendable (RenameMode) -> Int32?)? + private static let capableDevices = Mutex>([]) + + var device: UInt64 { get throws { try objectIdentity.device } } + var objectIdentity: FileObjectIdentity { + get throws { + var info = stat() + guard fstat(descriptor, &info) == 0 else { + throw CoreError.invalidState("cannot identify directory") } - try checkpoint("unlinked") + return FileObjectIdentity(info) } - // An absent entry may reflect an interrupted unlink whose parent was never synced. + } + + enum PermissionStep: String { case changed, synced } + + /// Only a recorded directory inode may receive the journal's temporary owner-write bit. + func setPermissions( + _ mode: mode_t, expecting identity: FileObjectIdentity, + from original: mode_t, checkpoint: (PermissionStep) throws -> Void + ) throws { + let current = try checkedPermissions(expecting: identity, from: original) + if current != mode { + guard fchmod(descriptor, mode) == 0 else { + let code = errno + throw CoreError.invalidState( + "cannot set directory permissions: \(code) (\(String(cString: strerror(code))))") + } + try checkpoint(.changed) + } + // A visible mode may be an interrupted chmod whose metadata barrier did not complete. try sync() - try checkpoint("synced") + var value = stat() + guard fstat(descriptor, &value) == 0, value.st_mode & 0o7777 == mode else { + throw CoreError.invalidState("directory permissions changed before synchronization") + } + try checkpoint(.synced) + } + + func checkedPermissions(expecting identity: FileObjectIdentity, from original: mode_t) throws + -> mode_t + { + var value = stat() + guard fstat(descriptor, &value) == 0, FileObjectIdentity(value) == identity else { + throw CoreError.invalidState("recorded directory identity changed") + } + let current = value.st_mode & 0o7777 + guard current == original || current == original | 0o200 else { + throw CoreError.invalidState( + "directory permissions changed beyond transaction intent: \(url.path)") + } + return current + } + + func atomicRename( + _ name: String, to parent: DirectoryHandle, named destination: String, + mode: RenameMode + ) -> RenameResult { + if let code = Self.atomicRenameFailure?(mode) { return RenameResult(code: code) } + let result = + mode == .exchange + ? platform_exchange(descriptor, name, parent.descriptor, destination) + : platform_rename_exclusive(descriptor, name, parent.descriptor, destination) + return RenameResult(code: result == 0 ? 0 : errno) + } + + func move( + _ name: String, to parent: DirectoryHandle, named destination: String, + mode: RenameMode, afterRename: () throws -> Void = {} + ) throws { + try atomicRename(name, to: parent, named: destination, mode: mode).requireSuccess( + "rename \(destination)") + try afterRename() + try parent.sync() + if self !== parent { try sync() } } func rename( _ name: String, to destination: String, swap: Bool = false, afterRename: () throws -> Void = {} ) throws { - let result = - swap - ? platform_exchange(descriptor, name, destination) - : renameat(descriptor, name, descriptor, destination) - guard result == 0 else { - if swap, errno == ENOSYS || errno == ENOTSUP || errno == EINVAL { - throw CoreError.unsupported("atomic exchange is required: \(errno)") + if swap { + try move(name, to: self, named: destination, mode: .exchange, afterRename: afterRename) + } else { + guard renameat(descriptor, name, descriptor, destination) == 0 else { + throw CoreError.invalidState("cannot replace \(destination): \(errno)") } - throw CoreError.invalidState("cannot replace \(destination): \(errno)") + try afterRename() + try sync() } - try afterRename() - try sync() } func renameExclusive( - _ name: String, to destination: String, afterRename: () throws -> Void = {} + _ name: String, to destination: String, + afterRename: () throws -> Void = {} ) throws { - guard platform_rename_exclusive(descriptor, name, destination) == 0 else { - let code = errno - if code == EEXIST || code == ENOTEMPTY { - throw CoreError.invalidState("transaction destination already exists: \(destination)") - } - if code == ENOSYS || code == ENOTSUP || code == EINVAL { - throw CoreError.unsupported("atomic no-replace publication is required: \(code)") - } - throw CoreError.invalidState("cannot publish exclusively \(destination): \(code)") + try move(name, to: self, named: destination, mode: .exclusive, afterRename: afterRename) + } + + enum ProbeStep: String { + case firstCreated, secondCreated, exchanged, collisionChecked, moved, verified + } + + /// The descriptor is a journal-owned private container on the publication device. + func requireAtomicRenames(checkpoint: (ProbeStep) throws -> Void) throws { + if Self.atomicRenameFailure != nil { + try probeAtomicRenames(checkpoint: checkpoint) + return + } + let device = try device + // The lock spans probing so concurrent scopes check a device only once. + try Self.capableDevices.withLock { devices in + if devices.contains(device) { return } + try probeAtomicRenames(checkpoint: checkpoint) + devices.insert(device) } - try afterRename() - try sync() } - /// Checks flag admission without creating any object. FileTransaction also probes - /// the actual filesystem with journal-owned objects before publishing targets. - static func requireAtomicRenames(at destination: URL) throws { - var ancestor = destination.deletingLastPathComponent() - while !FileManager.default.fileExists(atPath: ancestor.path), ancestor.path != "/" { - ancestor.deleteLastPathComponent() - } - let directory = try DirectoryHandle(at: ancestor.resolvingSymlinksInPath()) - let prefix = ".agents-probe-" + UUID().uuidString - for exclusive in [false, true] { - let result = - exclusive - ? platform_rename_exclusive(directory.descriptor, prefix + ".a", prefix + ".b") - : platform_exchange(directory.descriptor, prefix + ".a", prefix + ".b") - guard result < 0, errno == ENOENT else { - throw CoreError.unsupported( - "atomic exchange and no-replace publication are required: \(errno)") - } + private func probeAtomicRenames(checkpoint: (ProbeStep) throws -> Void) throws { + let a = TransactionScratch.probeA.name + let b = TransactionScratch.probeB.name + let c = TransactionScratch.probeC.name + try write( + a, data: Data("a".utf8), syncParent: false, afterCreate: { try checkpoint(.firstCreated) }) + try write( + b, data: Data("b".utf8), syncParent: false, afterCreate: { try checkpoint(.secondCreated) }) + let first = try info(a).map(FileObjectIdentity.init) + let second = try info(b).map(FileObjectIdentity.init) + // Exchange must preserve both entries and exchange their physical identities. + try atomicRename(a, to: self, named: b, mode: .exchange).requireSuccess("exchange atomic probe") + try checkpoint(.exchanged) + guard try info(a).map(FileObjectIdentity.init) == second, + try info(b).map(FileObjectIdentity.init) == first + else { + throw CoreError.unsupported("atomic exchange did not preserve probe objects") + } + // An occupied destination must refuse publication and preserve both inodes. + let collision = atomicRename(a, to: self, named: b, mode: .exclusive) + switch collision { + case .exists: break + case .success: + throw CoreError.unsupported("exclusive rename replaced an occupied probe") + case .unsupported, .failure: + try collision.requireSuccess("check exclusive atomic probe collision") } + try checkpoint(.collisionChecked) + guard try info(a).map(FileObjectIdentity.init) == second, + try info(b).map(FileObjectIdentity.init) == first + else { + throw CoreError.unsupported("exclusive rename changed occupied probe objects") + } + // The same primitive must admit an absent destination, not merely reject all calls. + try atomicRename(a, to: self, named: c, mode: .exclusive).requireSuccess( + "move exclusive atomic probe") + try checkpoint(.moved) + guard try info(a) == nil, try info(c).map(FileObjectIdentity.init) == second else { + throw CoreError.unsupported("exclusive rename did not move the probe object") + } + try checkpoint(.verified) } - func makeDirectory(_ name: String) throws { + @discardableResult + func makeDirectory(_ name: String, syncParent: Bool = true) throws -> DirectoryHandle { if try info(name) != nil { try FileSystem.requireAccess( R_OK | W_OK | X_OK, at: url.appendingPathComponent(name), parent: descriptor) @@ -180,24 +371,31 @@ final class DirectoryHandle { } try FileSystem.requireAccess( R_OK | W_OK | X_OK, at: url.appendingPathComponent(name), parent: descriptor) - try sync() + let directory = try child(name) + guard fchmod(directory.descriptor, 0o700) == 0 else { + throw CoreError.invalidState("cannot set directory permissions") + } + if syncParent { try sync() } + return directory } func sync() throws { try Self.synchronize(descriptor) } - func link(_ name: String, destination: String) throws { + func link(_ name: String, destination: String, syncParent: Bool = true) throws { guard symlinkat(destination, descriptor, name) == 0 else { throw FileSystem.posixError( errno, at: url.appendingPathComponent(name), otherwise: .invalidState("cannot create link: \(name)")) } - try sync() + if syncParent { try sync() } } func write( - _ name: String, data: Data, mode: mode_t = 0o600, preservingMetadataOf original: String? = nil + _ name: String, data: Data, mode: mode_t = 0o600, preservingMetadataOf original: String? = nil, + originalParent: DirectoryHandle? = nil, syncParent: Bool = true, + afterCreate: () throws -> Void = {} ) throws { if try info(name) != nil { try FileSystem.requireAccess( @@ -210,6 +408,7 @@ final class DirectoryHandle { otherwise: .invalidState("cannot stage \(name)")) } defer { close(file) } + try afterCreate() try FileSystem.requireAccess( R_OK | W_OK, at: url.appendingPathComponent(name), parent: descriptor) try data.withUnsafeBytes { bytes in @@ -223,7 +422,7 @@ final class DirectoryHandle { } } if let original { - let source = try regularFile(original) + let source = try (originalParent ?? self).regularFile(original) defer { close(source) } var attributes = stat() guard fstat(source, &attributes) == 0 else { @@ -234,6 +433,33 @@ final class DirectoryHandle { guard fchmod(file, mode) == 0 else { throw CoreError.invalidState("cannot set permissions") } try Self.synchronize(file) } + if syncParent { try sync() } + } + + func writeJournal(_ data: Data, afterWrite: () throws -> Void, afterRename: () throws -> Void) + throws + { + if try info("transaction.new") != nil { + _ = try read("transaction.new") + guard unlinkat(descriptor, "transaction.new", 0) == 0 else { + throw CoreError.invalidState("cannot remove incomplete journal: \(errno)") + } + } + try write("transaction.new", data: data, syncParent: false) + try afterWrite() + try rename("transaction.new", to: "transaction.json", afterRename: afterRename) + } + + func removeJournal(afterUnlink: () throws -> Void = {}) throws { + for name in ["transaction.new", "transaction.json"] { + if try info(name) != nil { + _ = try read(name) + guard unlinkat(descriptor, name, 0) == 0 else { + throw CoreError.invalidState("cannot remove journal: \(errno)") + } + if name == "transaction.json" { try afterUnlink() } + } + } try sync() } @@ -269,6 +495,10 @@ final class DirectoryHandle { } func readLink(_ name: String) throws -> String { + String(decoding: try readLinkData(name), as: UTF8.self) + } + + func readLinkData(_ name: String) throws -> Data { var buffer = [CChar](repeating: 0, count: Int(PATH_MAX) + 1) let count = readlinkat(descriptor, name, &buffer, buffer.count - 1) guard count >= 0, count < buffer.count - 1 else { @@ -276,14 +506,14 @@ final class DirectoryHandle { count < 0 ? errno : 0, at: url.appendingPathComponent(name), otherwise: .unsafePath("invalid symbolic link")) } - return String(decoding: buffer.prefix(count).map { UInt8(bitPattern: $0) }, as: UTF8.self) + return Data(buffer.prefix(count).map { UInt8(bitPattern: $0) }) } - func syncFile(_ name: String) throws { + func syncFile(_ name: String, includingParent: Bool = true) throws { let file = try regularFile(name) defer { close(file) } try Self.synchronize(file) - try sync() + if includingParent { try sync() } } var identity: String { @@ -315,13 +545,22 @@ final class DirectoryHandle { guard platform_sync(file) == 0 else { throw CoreError.invalidState("cannot sync filesystem entry: \(errno)") } + synchronizationObserver?() + } + + enum CopyStep: String { case directoryCreated, fileCreated, linkCreated, entryCopied } + struct CopyPoint { + let path: String + let step: CopyStep } /// Copies through pinned descriptors, including modes, ACLs and extended attributes. func copy( _ name: String, from source: DirectoryHandle, named original: String, - checkpoint: (String) throws -> Void = { _ in } + prefix: String = "", syncParent: Bool = true, + checkpoint: (CopyPoint) throws -> Void = { _ in } ) throws { + let path = prefix.isEmpty ? name : prefix + "/" + name guard let info = try source.info(original) else { throw CoreError.notFound(original) } switch info.st_mode & S_IFMT { case S_IFDIR: @@ -336,15 +575,18 @@ final class DirectoryHandle { } try FileSystem.requireAccess( R_OK | W_OK | X_OK, at: url.appendingPathComponent(name), parent: descriptor) - try checkpoint("directory") + try checkpoint(CopyPoint(path: path, step: .directoryCreated)) let destination = try child(name) let origin = try source.child(original) for entry in try origin.names() { - try destination.copy(entry, from: origin, named: entry, checkpoint: checkpoint) + try destination.copy( + entry, from: origin, named: entry, prefix: path, syncParent: false, checkpoint: checkpoint + ) } try Self.copyMetadata(from: origin.descriptor, to: destination.descriptor, mode: info.st_mode) case S_IFLNK: - try link(name, destination: source.readLink(original)) + try link(name, destination: source.readLink(original), syncParent: false) + try checkpoint(CopyPoint(path: path, step: .linkCreated)) guard platform_copy_link_metadata(source.descriptor, original, descriptor, name) == 0 else { throw CoreError.invalidState("cannot preserve link metadata: \(errno)") } @@ -362,6 +604,7 @@ final class DirectoryHandle { errno, at: url.appendingPathComponent(name), otherwise: .unsafePath("cannot copy file")) } defer { close(destination) } + try checkpoint(CopyPoint(path: path, step: .fileCreated)) try FileSystem.requireAccess( R_OK | W_OK, at: url.appendingPathComponent(name), parent: descriptor) guard platform_copy_data(origin, destination) == 0 else { @@ -370,13 +613,14 @@ final class DirectoryHandle { try Self.copyMetadata(from: origin, to: destination, mode: info.st_mode) default: throw CoreError.unsafePath("unsupported filesystem entry: \(original)") } - try sync() - try checkpoint("entry") + if syncParent { try sync() } + if !prefix.isEmpty { try checkpoint(CopyPoint(path: path, step: .entryCopied)) } } private static func copyMetadata(from origin: Int32, to destination: Int32, mode: mode_t) throws { guard platform_copy_metadata(origin, destination, mode) == 0 else { throw CoreError.invalidState("cannot preserve filesystem metadata: \(errno)") } + synchronizationObserver?() } } diff --git a/Sources/AgentsCore/FileHash.swift b/Sources/AgentsCore/FileHash.swift index 2d68cf9..db5827e 100644 --- a/Sources/AgentsCore/FileHash.swift +++ b/Sources/AgentsCore/FileHash.swift @@ -56,6 +56,10 @@ package enum FileHash { } } try collect(directory, prefix: "") + return hashRecords(entries) + } + + static func hashRecords(_ entries: [(String, Data)]) -> String { var hasher = SHA256() // Each field has a fixed-width byte length, so arbitrary payload bytes cannot // impersonate paths, entry types or record boundaries. diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 5653f4f..a152c17 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -1,66 +1,46 @@ -import CPlatform import Foundation -/// A durable undo journal covers targets, scope state files and cache pruning. -/// The scope writer lock must be held through planning, commit and recovery. +/// The scope's sole durable undo journal owns private construction containers, +/// sealed publication evidence and terminal disposal. The scope writer lock spans +/// preparation, commit and recovery; external writers are identified by inode and digest. package final class FileTransaction { - private enum Progress: String, Codable { - case queued, verifying, ready, publishing, applied, restoring, restored, cancelled - } - private struct Entry: Codable { - var path: String - var existed: Bool - var replacement: Bool - var preimage: FileSnapshot? - var parentIdentity = "" - var staging: FileSnapshot? - var staged: FileSnapshot? - var work: FileSnapshot? - var probes: [FileSnapshot] = [] - var progress: Progress = .queued - var cleanup: [String: FileSnapshot] = [:] - var discarding = false - var conflict = false - var name: String { String(path.split(separator: "/").last!) } - } - private struct Journal: Codable { - var id: UUID - var scope: String - var roots: [String: String] - var phase: Phase - var entries: [Entry] - } - private enum Phase: String, Codable { case preparing, applying, committed, rolledBack } - private struct Content { + struct Content { var url: URL? var link: Bool + var linkDestination: String? var data: Data? var expectedHash: String? var executableFlags: [String: Bool]? + var expectedKind: mode_t? + var expectedMode: mode_t? var prepare: ((URL) throws -> URL)? } + private struct Request { + var action: TransactionJournal.Action + let path: String + let evidence: TargetPrecondition + var content: Content + } private let store: StateStore private let checkpoint: (String) throws -> Void - package var validateBeforePublication: () throws -> Void = {} - var atomicPreflight: (URL) throws -> Void = { try DirectoryHandle.requireAtomicRenames(at: $0) } private let outcome: TransactionOutcome - private var entries: [Entry] = [] - private var contents: [Content] = [] - private var preconditions: [PathIdentity] = [] - private var statePrecondition: StatePrecondition? + private var requests: [Request] = [] + package var validateBeforePublication: () throws -> Void = {} + package var targetPaths: Set { Set(requests.map { $0.evidence.url.path }) } package init( store: StateStore, outcome: TransactionOutcome = TransactionOutcome(), checkpoint: @escaping (String) throws -> Void = { _ in } ) { self.store = store - self.checkpoint = checkpoint self.outcome = outcome + self.checkpoint = checkpoint } package func replace( _ destination: URL, content: URL?, link: Bool = false, data: Data? = nil, - expectedHash: String? = nil, executableFlags: [String: Bool]? = nil + expectedHash: String? = nil, executableFlags: [String: Bool]? = nil, + expecting: TargetPrecondition? = nil ) throws { if let expectedHash { try StateValidation.digest(expectedHash) @@ -69,29 +49,60 @@ package final class FileTransaction { } } let path = try TransactionPaths(store: store).path(for: destination) - guard !entries.contains(where: { $0.path == path }) else { + guard !requests.contains(where: { $0.path == path }) else { throw CoreError.invalidState("duplicate transaction destination") } - if statePrecondition == nil { statePrecondition = try StatePrecondition(store: store) } - let identity = try PathIdentity(destination) - let preimage = try FileSnapshot.read(at: destination) - try identity.validate() - entries.append( - Entry( - path: path, existed: preimage != nil, replacement: content != nil || data != nil, - preimage: preimage)) - preconditions.append(identity) - contents.append( - Content( - url: content, link: link, data: data, expectedHash: expectedHash, - executableFlags: executableFlags, prepare: nil)) + let evidence = try expecting ?? TargetPrecondition(destination) + guard evidence.url.path == destination.standardizedFileURL.path else { + throw CoreError.invalidState("precondition belongs to another target") + } + var hash = expectedHash + var flags = executableFlags + var kind: mode_t? + var mode: mode_t? + if let content, data == nil, !link { + let expected = try Self.copyExpectation(content, hash: hash, flags: flags) + (hash, flags, kind, mode) = expected + } + requests.append( + Request( + action: content != nil || data != nil ? .install : .delete, + path: path, evidence: evidence, + content: Content( + url: content, link: link, + linkDestination: link + ? content.map { + Self.linkDestination( + $0, parent: destination.deletingLastPathComponent(), store: store) + } : nil, + data: data, expectedHash: hash, executableFlags: flags, expectedKind: kind, + expectedMode: mode))) + } + + fileprivate static func copyExpectation( + _ source: URL, hash: String?, flags: [String: Bool]? + ) throws -> (String?, [String: Bool]?, mode_t?, mode_t?) { + let physical = source.resolvingSymlinksInPath() + let parent = try DirectoryHandle(at: physical.deletingLastPathComponent()) + if let hash, let flags { + let info = try parent.info(physical.lastPathComponent) + return ( + hash, flags, info.map(FileObjectIdentity.init)?.kind, info.map { $0.st_mode & 0o7777 } + ) + } + let capture = try FileSnapshot.capture(physical.lastPathComponent, from: parent) + guard let snapshot = capture.snapshot else { throw CoreError.notFound(source.path) } + return ( + hash ?? "sha256:" + capture.contentHash, flags ?? capture.executableFlags, + snapshot.identity.kind, snapshot.mode + ) } - /// Builds source content inside journal-owned scratch storage before verified copying. + /// A producer may construct arbitrary intermediate objects only inside its private container. func prepare(_ destination: URL, content: @escaping (URL) throws -> URL) throws { try replace(destination, content: nil) - entries[entries.count - 1].replacement = true - contents[contents.count - 1].prepare = content + requests[requests.count - 1].action = .install + requests[requests.count - 1].content.prepare = content } func remove(_ name: String, from parent: DirectoryHandle) throws { @@ -99,695 +110,353 @@ package final class FileTransaction { } package func commit() throws { + guard !requests.isEmpty else { return } guard let directory = try store.openDirectoryIfPresent(), try directory.info("transaction.json") == nil, try directory.info("transaction.new") == nil - else { throw CoreError.invalidState("transaction recovery is required") } - guard !entries.isEmpty else { return } - for identity in preconditions { try identity.validate() } - try statePrecondition?.validate() - try validateBeforePublication() - // No destination, ancestry or journal mutation precedes capability checks. - for entry in entries { - let destination = try destinationURL(entry.path) - try atomicPreflight(destination) + else { + throw CoreError.invalidState("transaction recovery is required") } - let paths = TransactionPaths(store: store) - var roots: [String: DirectoryHandle] = [:] - for entry in entries { - let key = try paths.components(entry.path).root - if roots[key] == nil { - roots[key] = try paths.root(key, create: true, checkpoint: checkpoint) - } - } - let parents = try entries.map { - try paths.parent(for: $0.path, roots: roots, create: true, checkpoint: checkpoint) - } - try Self.validateDestinations(entries, parents: parents) - for index in entries.indices { - entries[index].parentIdentity = try parents[index].identity - try Self.requirePreimage(entries[index], parent: parents[index]) - } - if entries.contains(where: { - ["state/agents.watch", "state/agents.resolved"].contains($0.path) - }) { - try SourceCache(store: store, checkpoint: checkpoint).beginWatchReferenceUpdate() - } - var journal = Journal( - id: UUID(), scope: try directory.identity, - roots: try roots.mapValues { try $0.identity }, phase: .preparing, entries: entries) - outcome.journalID = journal.id + try validateBeforePublication() + for request in requests { try request.evidence.validate() } + try validateOverlap() + let session = try makeSession(directory) + outcome.journalID = session.journal.id do { - try Self.persist(journal, directory: directory, checkpoint: checkpoint) - try checkpoint("journal.preparing") - var probedDevices: Set = [] - for index in entries.indices { - var info = stat() - guard fstat(parents[index].descriptor, &info) == 0 else { - throw CoreError.invalidState("cannot identify publication filesystem") - } - if probedDevices.insert(UInt64(info.st_dev)).inserted { - try probeAtomics(index, journal: &journal, directory: directory, parent: parents[index]) - } - } - for index in entries.indices { - do { - try stage(index, journal: &journal, directory: directory, parent: parents[index]) - } catch { - // A live producer can seal its incomplete scratch on failure. Recovery - // after process death uses only evidence already persisted by that producer. - if [.queued, .verifying].contains(journal.entries[index].progress) { - try? sealIncompleteScratch( - index, journal: &journal, directory: directory, parent: parents[index]) - } - throw error - } - } - try checkpoint("publication.preconditions") - try statePrecondition?.validate() - for identity in preconditions { try identity.validate() } + try session.persist(.created) + try session.emit(.phase(.preparing)) + try session.createContainers() + try session.checkCapabilities() + // Capability probing may only touch missing ancestry, journal and private containers. + if session.journal.entries.contains(where: { + ["state/agents.watch", "state/agents.resolved"].contains($0.path) + }) { + try SourceCache(store: store, checkpoint: checkpoint).beginWatchReferenceUpdate() + } + for index in session.journal.entries.indices { + try session.stage(index, content: requests[index].content) + } + try session.emit(.preconditions) try validateBeforePublication() - for (index, entry) in journal.entries.enumerated() { - try Self.requirePreimage(entry, parent: parents[index]) - } - journal.phase = .applying + try session.validatePreimages() outcome.disposition = .recoveryRequired - try Self.persist(journal, directory: directory, checkpoint: checkpoint) - try checkpoint("journal.applying") - for index in entries.indices { - try preconditions[index].validate() - try publish(index, journal: &journal, directory: directory, parent: parents[index]) - } - try validateRemainingState(journal) - try Self.verifyFinal(journal, parents: parents) - try Self.prepareCleanup(&journal, parents: parents) - journal.phase = .committed - try checkpoint("journal.committing") - try Self.persist(journal, directory: directory, checkpoint: checkpoint) + for index in session.journal.entries.indices { try session.publish(index) } + try validateBeforePublication() + try session.prepareCleanup() + try session.emit(.commitValidated) + session.journal.phase = .committed + try session.persist(.terminal) outcome.disposition = .committed - try checkpoint("journal.committed") - try Self.cleanup(&journal, directory: directory, parents: parents, checkpoint: checkpoint) + try session.emit(.phase(.committed)) + try session.cleanup() } catch { - do { - _ = try Self.recover(store: store, outcome: outcome) - var retained = try directory.info("transaction.json") != nil - for index in journal.entries.indices { - for suffix in Self.scratchSuffixes { - if try parents[index].info(Self.temporaryName(journal, index, suffix)) != nil { - retained = true - } - } - } - if retained { outcome.disposition = .recoveryRequired } - } catch { + do { _ = try Self.recover(store: store, outcome: outcome) } catch { outcome.disposition = .recoveryRequired } throw error } } - private func probeAtomics( - _ index: Int, journal: inout Journal, directory: DirectoryHandle, parent: DirectoryHandle - ) throws { - let first = Self.temporaryName(journal, index, "probe-a") - let second = Self.temporaryName(journal, index, "probe-b") - let third = Self.temporaryName(journal, index, "probe-c") - for name in [first, second] { - try parent.write(name, data: Data()) - guard let snapshot = try FileSnapshot.read(name, from: parent) else { - throw CoreError.invalidState("missing atomic capability probe") + private func validateOverlap() throws { + var targets: [URL] = [] + for request in requests { + let target = request.evidence.physicalURL + guard + !targets.contains(where: { + PathSafety.isContained(target, in: $0) || PathSafety.isContained($0, in: target) + }) + else { + throw CoreError.invalidState("overlapping transaction destinations") } - journal.entries[index].probes.append(snapshot) - try Self.persist(journal, directory: directory, checkpoint: checkpoint) - try checkpoint("atomic.\(index).created.\(journal.entries[index].probes.count)") - } - try parent.rename(first, to: second, swap: true) { - try checkpoint("atomic.\(index).exchanged") - } - guard platform_rename_exclusive(parent.descriptor, first, second) != 0, - errno == EEXIST || errno == ENOTEMPTY - else { throw CoreError.unsupported("atomic no-replace publication is required") } - try parent.renameExclusive(first, to: third) { - try checkpoint("atomic.\(index).exclusive") - } - let probes = journal.entries[index].probes - guard try FileSnapshot.read(second, from: parent) == probes[0], - try FileSnapshot.read(third, from: parent) == probes[1], - try parent.info(first) == nil - else { throw Self.conflict(journal.entries[index], "atomic probe ownership changed") } - try checkpoint("atomic.\(index).verified") + targets.append(target) + } } - private func destinationURL(_ path: String) throws -> URL { + private func makeSession(_ directory: DirectoryHandle) throws -> TransactionSession { let paths = TransactionPaths(store: store) - let components = try paths.components(path) - // Root resolution is configuration-owned and does not create directories. - return try paths.rootURL(components.root).appendingPathComponent( - components.descendants.joined(separator: "/")) - } - - private func stage( - _ index: Int, journal: inout Journal, directory: DirectoryHandle, parent: DirectoryHandle - ) throws { - let entry = journal.entries[index] - let staged = Self.temporaryName(journal, index, "new") - try entry.preimage?.synchronize(entry.name, from: parent) - try checkpoint("stage.\(index).preimage") - var content = contents[index] - if let prepare = content.prepare { - let work = Self.temporaryName(journal, index, "work") - try parent.makeDirectory(work) - journal.entries[index].work = try Self.mutableSnapshot( - work, from: parent, previous: journal.entries[index].work) - try Self.persist(journal, directory: directory, checkpoint: checkpoint) - try checkpoint("prepare.\(index).directory") - let root = parent.url.appendingPathComponent(work) - let source = try prepare(root) - guard PathSafety.isContained(source.resolvingSymlinksInPath(), in: root) else { - throw CoreError.unsafePath("prepared content escapes transaction staging") - } - journal.entries[index].work = try Self.mutableSnapshot( - work, from: parent, previous: journal.entries[index].work) - try Self.persist(journal, directory: directory, checkpoint: checkpoint) - content.url = source - content.expectedHash = "sha256:" + (try FileHash.folderHash(source)) - content.executableFlags = try FileHash.executableFlags(source) - try checkpoint("prepare.\(index).ready") - } - if let data = content.data { - try parent.write( - staged, data: data, - preservingMetadataOf: entry.preimage?.identity.kind == S_IFREG ? entry.name : nil) - journal.entries[index].staging = try FileSnapshot.read(staged, from: parent) - try Self.persist(journal, directory: directory, checkpoint: checkpoint) - try checkpoint("stage.\(index).written") - } else if let source = content.url { - if content.link { - try parent.link( - staged, destination: Self.linkDestination(source, parent: parent.url, store: store)) - } else { - try Self.validateCopy(source) - let origin = source.resolvingSymlinksInPath() - try parent.copy( - staged, from: DirectoryHandle(at: origin.deletingLastPathComponent()), - named: origin.lastPathComponent, - checkpoint: { step in - journal.entries[index].staging = try Self.mutableSnapshot( - staged, from: parent, previous: journal.entries[index].staging) - try Self.persist(journal, directory: directory, checkpoint: checkpoint) - try checkpoint("stage.\(index).copy.\(step)") - }) + var roots: [String: DirectoryHandle] = [:] + for request in requests { + let key = try paths.components(request.path).root + if roots[key] == nil { + roots[key] = try paths.root(key, create: true, checkpoint: checkpoint) } } - // Completed construction remains private and mutable until verification seals it. - if entry.replacement { - journal.entries[index].staging = try Self.mutableSnapshot( - staged, from: parent, previous: journal.entries[index].staging) - } - journal.entries[index].progress = .verifying - try Self.persist(journal, directory: directory, checkpoint: checkpoint) - try checkpoint("stage.\(index).ready") - if let data = content.data, try parent.read(staged) != data { - throw CoreError.invalidState("staged content bytes mismatch") + let parents = try requests.map { + try paths.parent(for: $0.path, roots: roots, create: true, checkpoint: checkpoint) } - if let expectedHash = content.expectedHash { - let hash: String - if content.link, let source = content.url { - hash = try FileHash.folderHash(source) - } else if content.data == nil { - hash = try FileHash.folderHash(parent.child(staged)) + for request in requests { try request.evidence.validateIdentity() } + let id = UUID() + var containers: [TransactionJournal.Container] = [] + var identities: [String: Int] = [:] + var entries: [TransactionJournal.Entry] = [] + for (index, request) in requests.enumerated() { + let identity = try parents[index].identity + let container: Int + if let existing = identities[identity] { + container = existing } else { - hash = try FileHash.sha256Hex(data: parent.read(staged)) - } - guard "sha256:" + hash == expectedHash else { - throw CoreError.invalidState("staged content digest mismatch") - } - try checkpoint("stage.\(index).verified") - } - if let flags = content.executableFlags { - let actual = - try content.link - ? FileHash.executableFlags(content.url!) : FileHash.executableFlags(parent.child(staged)) - guard actual == flags else { - throw CoreError.invalidState("staged content executable mode mismatch") - } - } - guard try FileSnapshot.read(staged, from: parent) == journal.entries[index].staging else { - throw CoreError.invalidState("staged content changed during verification") - } - journal.entries[index].staged = journal.entries[index].staging - journal.entries[index].progress = .ready - try Self.persist(journal, directory: directory, checkpoint: checkpoint) - try checkpoint("stage.\(index).sealed") - try checkpoint("stage.\(index)") + container = containers.count + identities[identity] = container + containers.append(.init(entry: index, name: ".agents-\(id.uuidString)-\(container)")) + } + entries.append( + .init( + path: request.path, action: request.action, preimage: request.evidence.snapshot, + parentIdentity: identity, container: container)) + } + let journal = TransactionJournal( + id: id, scope: try directory.identity, + roots: try roots.mapValues { try $0.identity }, entries: entries, containers: containers) + let session = TransactionSession( + journal: journal, directory: directory, parents: parents, + checkpoint: checkpoint) + try session.validateRecords(store: store) + return session } - private static func mutableSnapshot( - _ name: String, from parent: DirectoryHandle, previous: FileSnapshot? - ) throws -> FileSnapshot? { - let actual = try FileSnapshot.read(name, from: parent) - if let previous, previous.identity != actual?.identity { - throw CoreError.invalidState("transaction scratch identity changed: \(name)") - } - return actual + package static func linkDestination(_ source: URL, parent: URL, store: StateStore) -> String { + let root = (store.scope == .project ? store.environment.projectDirectory : store.directory) + .resolvingSymlinksInPath() + let source = source.resolvingSymlinksInPath() + if PathSafety.isContained(source, in: root) { + let from = parent.pathComponents + let to = source.pathComponents + let common = zip(from, to).prefix(while: { $0 == $1 }).count + return (Array(repeating: "..", count: from.count - common) + to.dropFirst(common)).joined( + separator: "/") + } + return source.path } +} - private func sealIncompleteScratch( - _ index: Int, journal: inout Journal, directory: DirectoryHandle, parent: DirectoryHandle - ) throws { - if let work = journal.entries[index].work { - journal.entries[index].work = try Self.mutableSnapshot( - Self.temporaryName(journal, index, "work"), from: parent, previous: work) - } - if let staging = journal.entries[index].staging { - let actual = try Self.mutableSnapshot( - Self.temporaryName(journal, index, "new"), from: parent, previous: staging) - if journal.entries[index].progress == .verifying, - actual.map({ staging.sameObjects(as: $0) }) != true - { - throw CoreError.invalidState("staging ownership changed during verification") - } - journal.entries[index].staging = actual - } - try Self.persist(journal, directory: directory, checkpoint: { _ in }) +final class TransactionSession { + var journal: TransactionJournal + let directory: DirectoryHandle + let parents: [DirectoryHandle] + let checkpoint: (String) throws -> Void + + init( + journal: TransactionJournal, directory: DirectoryHandle, parents: [DirectoryHandle], + checkpoint: @escaping (String) throws -> Void + ) { + self.journal = journal + self.directory = directory + self.parents = parents + self.checkpoint = checkpoint } - private func publish( - _ index: Int, journal: inout Journal, directory: DirectoryHandle, parent: DirectoryHandle - ) throws { - var entry = journal.entries[index] - let staged = Self.temporaryName(journal, index, "new") - let backup = Self.temporaryName(journal, index, "old") - try Self.requirePreimage(entry, parent: parent) - guard try FileSnapshot.read(staged, from: parent) == entry.staged, - !entry.replacement || entry.staged != nil - else { throw Self.conflict(entry, "staged object changed") } - entry.progress = .publishing - journal.entries[index] = entry - try Self.persist(journal, directory: directory, checkpoint: checkpoint) - try checkpoint("publish.\(index).intent") - try validateRemainingState(journal) - try Self.requirePreimage(entry, parent: parent) - try checkpoint("publish.\(index).validated") - if entry.replacement { - if entry.existed { - try parent.rename(staged, to: entry.name, swap: true) { - try checkpoint("replace.\(index).renamed") - } - try checkpoint("publish.\(index).synced") - guard try FileSnapshot.read(staged, from: parent) == entry.preimage else { - throw Self.conflict(entry, "displaced preimage changed") - } - try checkpoint("publish.\(index).displaced") - try parent.renameExclusive(staged, to: backup) { - try checkpoint("publish.\(index).retained") - } - } else { - try parent.renameExclusive(staged, to: entry.name) { - try checkpoint("replace.\(index).renamed") - } - try checkpoint("publish.\(index).synced") - } - } else if entry.existed { - try parent.renameExclusive(entry.name, to: backup) { - try checkpoint("replace.\(index).renamed") - } - try checkpoint("publish.\(index).synced") - guard try FileSnapshot.read(backup, from: parent) == entry.preimage else { - throw Self.conflict(entry, "quarantined preimage changed") - } - } - guard try FileSnapshot.read(entry.name, from: parent) == entry.staged else { - throw Self.conflict(entry, "published object changed") - } - journal.entries[index].progress = .applied - try Self.persist(journal, directory: directory, checkpoint: checkpoint) - try checkpoint("replace.\(index)") + func emit(_ point: TransactionCheckpoint) throws { try checkpoint(point.name) } + func persist(_ change: TransactionCheckpoint.Change) throws { + try requireScope() + try directory.writeJournal( + StateStore.encode(journal), + afterWrite: { + try emit(.persisted(journal.phase, change, .written)) + }, + afterRename: { + try emit(.persisted(journal.phase, change, .renamed)) + }) } - private func validateRemainingState(_ journal: Journal) throws { - let published = Set( - journal.entries.filter { - $0.progress == .applied && $0.path.hasPrefix("state/") - }.map(\.name)) - try statePrecondition?.validate(excluding: published) + func createContainers() throws { + for index in journal.containers.indices { + let parent = parents[journal.containers[index].entry] + let created = try parent.makeDirectory(journal.containerName(index)) + let identity = try created.objectIdentity + try emit(.containerCreated(index)) + guard try parent.info(journal.containerName(index)).map(FileObjectIdentity.init) == identity + else { + throw conflict( + journal.containers[index].entry, + "private container changed before its identity was durable") + } + journal.containers[index].identity = identity + } + // No object enters any container until all newly created identities are durable. + try persist(.containers) + try emit(.containersIdentified) } - /// Recovers only after validating and pinning every root, parent and object record. - package static func recover( - store: StateStore, outcome: TransactionOutcome? = nil, - checkpoint: (String) throws -> Void = { _ in } - ) throws -> Bool { - guard let directory = try store.openDirectoryIfPresent() else { return false } - guard try directory.info("transaction.json") != nil else { - guard try directory.info("transaction.new") != nil else { return false } - _ = try directory.read("transaction.new") - try directory.remove("transaction.new") - return true - } - var journal: Journal - do { - journal = try StateStore.decode(directory.read("transaction.json"), as: Journal.self) - } catch { - outcome?.disposition = .recoveryRequired - throw CoreError.invalidState("unresolved transaction journal: \(error)") - } - do { - let parents = try recoveryParents(journal, store: store, directory: directory) - if try directory.info("transaction.new") != nil { _ = try directory.read("transaction.new") } - if journal.phase == .applying { - var conflicts: [String] = [] - for index in journal.entries.indices.reversed() { - do { - try rollback( - index, journal: &journal, directory: directory, parent: parents[index], - checkpoint: checkpoint) - journal.entries[index].conflict = false - } catch { - journal.entries[index].conflict = true - conflicts.append("\(journal.entries[index].path): \(error)") - } - try persist(journal, directory: directory, checkpoint: checkpoint) - } - guard conflicts.isEmpty else { - throw CoreError.invalidState( - "unresolved transaction conflicts: " + conflicts.joined(separator: "; ")) - } - } - if journal.phase == .applying || journal.phase == .preparing { - if journal.phase == .applying { try verifyFinal(journal, parents: parents, rollback: true) } - try prepareCleanup(&journal, parents: parents) - journal.phase = .rolledBack - try persist(journal, directory: directory, checkpoint: checkpoint) - } - try verifyFinal(journal, parents: parents, rollback: journal.phase == .rolledBack) - try cleanup(&journal, directory: directory, parents: parents, checkpoint: checkpoint) - if outcome?.journalID == journal.id { - outcome?.disposition = journal.phase == .committed ? .committed : .unchanged - } - return true - } catch { - if outcome?.journalID == journal.id { outcome?.disposition = .recoveryRequired } - throw error - } + func container(_ index: Int) throws -> DirectoryHandle { + let record = journal.containers[index] + let parent = parents[record.entry] + guard let expected = record.identity, + try parent.info(record.name).map(FileObjectIdentity.init) == expected + else { + throw conflict(record.entry, "private container identity changed or is missing") + } + let handle = try parent.child(record.name) + guard try handle.objectIdentity == expected else { + throw conflict(record.entry, "private container changed while opening") + } + return handle } - private static func recoveryParents( - _ journal: Journal, store: StateStore, directory: DirectoryHandle - ) throws -> [DirectoryHandle] { - guard journal.scope == (try directory.identity) else { - throw CoreError.invalidState("transaction journal belongs to another scope location") + func checkCapabilities() throws { + for index in journal.containers.indices { + try container(index).requireAtomicRenames { try emit(.probe(index, $0)) } } - let paths = TransactionPaths(store: store) - let keys = try Set(journal.entries.map { try paths.components($0.path).root }) - guard keys == Set(journal.roots.keys) else { - throw CoreError.invalidState("invalid transaction roots") - } - var roots: [String: DirectoryHandle] = [:] - for key in keys { - let root = try paths.root(key) - guard try root.identity == journal.roots[key] else { - throw CoreError.invalidState("transaction root identity changed") - } - roots[key] = root - } - let parents = try journal.entries.map { try paths.parent(for: $0.path, roots: roots) } - try validateDestinations(journal.entries, parents: parents) - for (index, entry) in journal.entries.enumerated() { - guard entry.parentIdentity == (try parents[index].identity), - entry.existed == (entry.preimage != nil), - entry.cleanup.keys.allSatisfy({ scratchSuffixes.contains($0) }) - else { throw conflict(entry, "invalid parent or object evidence") } - let allowed: [Progress] - switch journal.phase { - case .preparing: allowed = [.queued, .verifying, .ready] - case .applying: allowed = [.ready, .publishing, .applied, .restoring, .restored, .cancelled] - case .committed: allowed = [.applied] - case .rolledBack: allowed = [.queued, .verifying, .ready, .restored, .cancelled] - } - guard allowed.contains(entry.progress) else { - throw conflict(entry, "operation progress contradicts the journal phase") - } - for snapshot in [entry.preimage, entry.staging, entry.staged, entry.work].compactMap({ $0 }) - + Array(entry.cleanup.values) + entry.probes - { try snapshot.validate() } - if ![.queued, .verifying].contains(entry.progress), entry.replacement, entry.staged == nil { - throw conflict(entry, "missing staged identity") - } - } - return parents } - private static func rollback( - _ index: Int, journal: inout Journal, directory: DirectoryHandle, parent: DirectoryHandle, - checkpoint: (String) throws -> Void - ) throws { + func stage(_ index: Int, content input: FileTransaction.Content) throws { let entry = journal.entries[index] - if [.queued, .verifying, .ready, .cancelled].contains(entry.progress) { - journal.entries[index].progress = .cancelled - } else if entry.progress != .restored { - journal.entries[index].progress = .restoring - try persist(journal, directory: directory, checkpoint: checkpoint) - try checkpoint("restore.\(index).intent") - let target = try FileSnapshot.read(entry.name, from: parent) - let stagedName = temporaryName(journal, index, "new") - let backup = temporaryName(journal, index, "old") - let staged = try FileSnapshot.read(stagedName, from: parent) - let old = try FileSnapshot.read(backup, from: parent) - if let preimage = entry.preimage { - if target == preimage { - // Before publication, or after an interrupted restoration exchange. - guard !entry.replacement || staged == entry.staged || old == entry.staged else { - throw conflict(entry, "missing transaction postimage") - } - } else if entry.replacement { - guard let postimage = entry.staged, target == postimage else { - throw conflict(entry, "recovery destination is external or changed") - } - let original: String - if staged == preimage, old == nil { - original = stagedName - } else if old == preimage, staged == nil { - original = backup - } else { - throw conflict(entry, "missing or changed displaced preimage") - } - try checkpoint("restore.\(index).validated") - try parent.rename(original, to: entry.name, swap: true) { - try checkpoint("restore.\(index).renamed") - } - guard try FileSnapshot.read(original, from: parent) == postimage, - try FileSnapshot.read(entry.name, from: parent) == preimage - else { throw conflict(entry, "recovery exchange displaced an external object") } - } else { - guard target == nil, old == preimage else { - throw conflict(entry, "quarantine or recovery destination changed") - } - try checkpoint("restore.\(index).validated") - try parent.renameExclusive(backup, to: entry.name) { - try checkpoint("restore.\(index).renamed") - } - guard try FileSnapshot.read(entry.name, from: parent) == preimage else { - throw conflict(entry, "restored preimage changed") - } - } - } else if let postimage = entry.staged { - let removed = temporaryName(journal, index, "removed") - let quarantined = try FileSnapshot.read(removed, from: parent) - if staged == postimage, quarantined == nil, target != postimage { - // No-replace never consumed staging; a concurrent creator is untouched. - journal.entries[index].progress = .cancelled - } else if target == postimage, staged == nil, quarantined == nil { - try checkpoint("restore.\(index).validated") - try parent.renameExclusive(entry.name, to: removed) { - try checkpoint("restore.\(index).remove.unlinked") - } - guard try FileSnapshot.read(removed, from: parent) == postimage else { - throw conflict(entry, "creation rollback quarantined an external object") - } - } else if quarantined != postimage || staged != nil || target == postimage { - throw conflict(entry, "missing or changed creation evidence") - } - try parent.sync() - try checkpoint("restore.\(index).remove.synced") - } - if journal.entries[index].progress != .cancelled { - journal.entries[index].progress = .restored - } - } - // A visible reverse rename is not a durability barrier, including on retry. - try parent.sync() - try checkpoint("restore.\(index).synced") - try persist(journal, directory: directory, checkpoint: checkpoint) - try checkpoint("restore.\(index)") + let parent = parents[index] + let scratch = try container(entry.container) + try entry.preimage?.synchronize(entry.name, from: parent) + try emit(.stage(index, .preimageSynced)) + var content = try prepareContent(input, index: index, scratch: scratch) + if content.data != nil { + content.expectedMode = entry.preimage?.isRegular == true ? entry.preimage!.mode : 0o600 + } + let name = TransactionScratch.staged.name(index) + try construct(content, index: index, scratch: scratch, parent: parent) + try emit(.stage(index, .constructed)) + let capture = try FileSnapshot.capture(name, from: scratch) + try verify(content, capture: capture) + if entry.action == .install, capture.snapshot == nil { + throw conflict(index, "missing constructed object") + } + for slot in TransactionScratch.objectSlots + where entry.action == .delete || slot != .staged { + guard try scratch.info(slot.name(index)) == nil else { + throw CoreError.invalidState("unexpected private recovery slot before sealing") + } + } + try scratch.sync() + journal.entries[index].staged = capture.snapshot + try advance(index, to: .ready) } - private static func requirePreimage(_ entry: Entry, parent: DirectoryHandle) throws { - guard try FileSnapshot.read(entry.name, from: parent) == entry.preimage else { - throw conflict(entry, "preparation is stale; prepare again") - } + private func prepareContent( + _ input: FileTransaction.Content, index: Int, + scratch: DirectoryHandle + ) throws -> FileTransaction.Content { + guard let prepare = input.prepare else { return input } + var content = input + let name = TransactionScratch.work.name(index) + try scratch.makeDirectory(name, syncParent: false) + try emit(.stage(index, .workCreated)) + let root = scratch.url.appendingPathComponent(name) + let source = try prepare(root) + guard PathSafety.isContained(source.resolvingSymlinksInPath(), in: root) else { + throw CoreError.unsafePath("prepared content escapes transaction staging") + } + content.url = source + (content.expectedHash, content.executableFlags, content.expectedKind, content.expectedMode) = + try FileTransaction.copyExpectation( + source, hash: nil, flags: nil) + try emit(.stage(index, .workPrepared)) + return content } - private static func verifyFinal( - _ journal: Journal, parents: [DirectoryHandle], rollback: Bool = false + private func construct( + _ content: FileTransaction.Content, index: Int, + scratch: DirectoryHandle, parent: DirectoryHandle ) throws { - for (index, entry) in journal.entries.enumerated() { - try requireParent(entry, parent: parents[index]) - if rollback { - if entry.progress == .restored, entry.preimage != nil { - try requirePreimage(entry, parent: parents[index]) - } else if let staged = entry.staged, - try FileSnapshot.read(entry.name, from: parents[index])?.identity == staged.identity - { - throw conflict(entry, "creation is still published") - } + let entry = journal.entries[index] + let name = TransactionScratch.staged.name(index) + if let data = content.data { + try scratch.write( + name, data: data, + preservingMetadataOf: entry.preimage?.isRegular == true ? entry.name : nil, + originalParent: parent, syncParent: false, + afterCreate: { try emit(.stage(index, .writeCreated)) }) + } else if let source = content.url { + if content.link { + // The link is interpreted after publication, relative to the target parent. + let destination = content.linkDestination ?? source.path + try scratch.link(name, destination: destination, syncParent: false) } else { - guard try FileSnapshot.read(entry.name, from: parents[index]) == entry.staged else { - throw conflict(entry, "committed destination changed") - } + try Self.validateCopy(source) + let origin = source.resolvingSymlinksInPath() + try scratch.copy( + name, from: DirectoryHandle(at: origin.deletingLastPathComponent()), + named: origin.lastPathComponent, syncParent: false + ) { try emit(.copy(index, $0)) } } } } - private static func requireParent(_ entry: Entry, parent: DirectoryHandle) throws { - guard try DirectoryHandle(at: parent.url).identity == entry.parentIdentity else { - throw conflict(entry, "destination parent changed") + private func verify(_ content: FileTransaction.Content, capture: FileSnapshot.Capture) throws { + if let kind = content.expectedKind, capture.snapshot?.identity.kind != kind { + throw CoreError.invalidState("staged content type mismatch") } - } - - private static func prepareCleanup(_ journal: inout Journal, parents: [DirectoryHandle]) throws { - for index in journal.entries.indices { - let entry = journal.entries[index] - var cleanup: [String: FileSnapshot] = [:] - for suffix in scratchSuffixes { - guard - let actual = try FileSnapshot.read( - temporaryName(journal, index, suffix), from: parents[index]) - else { continue } - let candidates: [FileSnapshot?] - switch suffix { - case "probe-a", "probe-b", "probe-c": candidates = entry.probes.map(Optional.some) - case "work": candidates = [entry.work] - case "removed": candidates = [entry.staged] - case "old": candidates = [entry.preimage, entry.staged] - default: candidates = [entry.staged ?? entry.staging, entry.preimage] - } - guard candidates.contains(where: { $0 == actual }) else { - throw conflict(entry, "unverified recovery object: \(suffix)") - } - cleanup[suffix] = actual - } - if journal.phase == .preparing { - if let staged = entry.staging, cleanup["new"] != staged { - throw conflict(entry, "missing staging evidence") - } - } - if entry.progress == .cancelled, let staged = entry.staged, cleanup["new"] != staged { - throw conflict(entry, "missing unpublished staging evidence") - } - if let work = entry.work, cleanup["work"] != work { - throw conflict(entry, "missing scratch evidence") - } - guard entry.probes.allSatisfy({ cleanup.values.contains($0) }) else { - throw conflict(entry, "missing atomic probe evidence") - } - journal.entries[index].cleanup = cleanup + if content.data != nil, capture.snapshot?.isRegular != true { + throw CoreError.invalidState("staged content type mismatch") } - } - - private static func cleanup( - _ journal: inout Journal, directory: DirectoryHandle, parents: [DirectoryHandle], - checkpoint: (String) throws -> Void - ) throws { - try requireScope(journal, directory: directory) - try directory.syncFile("transaction.json") - try checkpoint("journal.terminalSynced") - try requireScope(journal, directory: directory) - // Validate the whole disposal plan before deleting the first resource. - for (index, entry) in journal.entries.enumerated() { - try requireParent(entry, parent: parents[index]) - for suffix in scratchSuffixes { - let actual = try FileSnapshot.read( - temporaryName(journal, index, suffix), from: parents[index]) - if let expected = entry.cleanup[suffix] { - guard - entry.discarding ? actual.map(expected.containsRemaining) ?? true : actual == expected - else { throw conflict(entry, "cleanup evidence changed: \(suffix)") } - } else if actual != nil { - throw conflict(entry, "unrecorded cleanup object: \(suffix)") - } - } + if let mode = content.expectedMode, capture.snapshot?.mode != mode { + throw CoreError.invalidState("staged content permissions mismatch") } - for index in journal.entries.indices { - journal.entries[index].discarding = true - try persist(journal, directory: directory, checkpoint: checkpoint) - try checkpoint("cleanup.\(index).intent") - try requireScope(journal, directory: directory) - try requireParent(journal.entries[index], parent: parents[index]) - for suffix in journal.entries[index].cleanup.keys.sorted() { - try journal.entries[index].cleanup[suffix]!.remove( - temporaryName(journal, index, suffix), from: parents[index], - checkpoint: { try checkpoint("cleanup.\(index).\(suffix).\($0)") }) - } - try checkpoint("cleanup.\(index)") + if content.link { + let destination = content.linkDestination ?? content.url!.path + guard capture.snapshot?.isSymbolicLink == true, + capture.snapshot?.digest == FileHash.sha256Hex(data: Data(destination.utf8)) + else { throw CoreError.invalidState("staged symbolic link destination mismatch") } } - try directory.remove("transaction.new") - try directory.remove("transaction.json") - try checkpoint("journal.removed") - } - - private static func requireScope(_ journal: Journal, directory: DirectoryHandle) throws { - guard try DirectoryHandle(at: directory.url).identity == journal.scope else { - throw CoreError.invalidState("transaction scope identity changed") + if let data = content.data, capture.snapshot?.digest != FileHash.sha256Hex(data: data) { + throw CoreError.invalidState("staged content bytes mismatch") } - } - - private static func validateDestinations(_ entries: [Entry], parents: [DirectoryHandle]) throws { - var paths: [URL] = [] - for (index, entry) in entries.enumerated() { - let path = parents[index].url.appendingPathComponent(entry.name) - guard - !paths.contains(where: { - PathSafety.isContained(path, in: $0) || PathSafety.isContained($0, in: path) - }) - else { throw CoreError.invalidState("overlapping transaction destinations") } - paths.append(path) + if let expected = content.expectedHash { + let actual = try content.link ? FileHash.folderHash(content.url!) : capture.contentHash + guard "sha256:" + actual == expected else { + throw CoreError.invalidState("staged content digest mismatch") + } + } + if let flags = content.executableFlags { + let actual = + try content.link ? FileHash.executableFlags(content.url!) : capture.executableFlags + guard actual == flags else { + throw CoreError.invalidState("staged content executable mode mismatch") + } } } - private static func conflict(_ entry: Entry, _ reason: String) -> CoreError { - .invalidState("transaction conflict at \(entry.path): \(reason)") + func validatePreimages() throws { + for index in journal.entries.indices { try requirePreimage(index) } } - private static func temporaryName(_ journal: Journal, _ index: Int, _ suffix: String) -> String { - ".agents-\(journal.id.uuidString)-\(index).\(suffix)" + func publish(_ index: Int) throws { + let entry = journal.entries[index] + let parent = parents[index] + let scratch = try container(entry.container) + let layout = try distribution(index) + guard layout.kind == .prepared else { + throw conflict(index, "operation is not prepared") + } + try advance(index, to: .publishing) + try requirePreimage(index) + try emit(.publication(index, .validated)) + try grantDirectoryPermissions(index, layout: layout, purpose: .publicationGrant) + if entry.action == .install { + let exchange = entry.preimage != nil + try scratch.move( + TransactionScratch.staged.name(index), to: parent, named: entry.name, + mode: exchange ? .exchange : .exclusive + ) { + try emit(.publication(index, exchange ? .exchanged : .created)) + } + } else if entry.preimage != nil { + try parent.move( + entry.name, to: scratch, named: TransactionScratch.preimage.name(index), mode: .exclusive + ) { + try emit(.publication(index, .quarantined)) + } + } + try emit(.publication(index, .synced)) + try restoreDirectoryPermissions(index, purpose: .publicationRestore) + guard try distribution(index, permittingDirectoryWrite: false).kind == .installed else { + throw conflict(index, "publication did not retain its preimage") + } + try advance(index, to: .applied) } - private static let scratchSuffixes = [ - "old", "new", "removed", "work", "probe-a", "probe-b", "probe-c", - ] - - private static func persist( - _ journal: Journal, directory: DirectoryHandle, - checkpoint: (String) throws -> Void - ) throws { - try directory.remove("transaction.new") - try directory.write("transaction.new", data: StateStore.encode(journal)) - try directory.rename("transaction.new", to: "transaction.json") { - try checkpoint("journal.\(journal.phase.rawValue).renamed") - } - } - package static func linkDestination(_ source: URL, parent: URL, store: StateStore) -> String { - let root = (store.scope == .project ? store.environment.projectDirectory : store.directory) - .resolvingSymlinksInPath() - let source = source.resolvingSymlinksInPath() - if PathSafety.isContained(source, in: root) { - let from = parent.pathComponents - let to = source.pathComponents - let common = zip(from, to).prefix(while: { $0 == $1 }).count - return (Array(repeating: "..", count: from.count - common) + to.dropFirst(common)).joined( - separator: "/") + func requirePreimage(_ index: Int) throws { + try requireParent(index) + guard + try FileSnapshot.read(journal.entries[index].name, from: parents[index]) + == journal.entries[index].preimage + else { + throw conflict(index, "preparation is stale; prepare again") } - return source.path } /// A copied subtree keeps relative links that stay inside it, dangling ones included. @@ -800,8 +469,7 @@ package final class FileTransaction { if try entry.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true { entries.skipDescendants() let destination = try FileManager.default.destinationOfSymbolicLink(atPath: entry.path) - guard !destination.hasPrefix("/"), try PathSafety.linkStaysInside(entry, root: root) - else { + 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/SourceCache.swift b/Sources/AgentsCore/SourceCache.swift index da3d126..1d6571c 100644 --- a/Sources/AgentsCore/SourceCache.swift +++ b/Sources/AgentsCore/SourceCache.swift @@ -276,7 +276,7 @@ package struct SourceCache { if !locks.isEmpty { try beginWatchReferenceUpdate() } guard try directory.info("watch-refs.pending") != nil else { return } for (parent, name) in locks { - try parent.remove(name) { try checkpoint("watch.git-lock.\($0)") } + try parent.remove(name) { try checkpoint("watch.git-lock.\($0.step.rawValue)") } } // A killed cleanup may have unlinked the last lock before syncing its parent. // The pending marker requires these barriers even if no lock remains visible. diff --git a/Sources/AgentsCore/StateStore.swift b/Sources/AgentsCore/StateStore.swift index fe35ed4..c535093 100644 --- a/Sources/AgentsCore/StateStore.swift +++ b/Sources/AgentsCore/StateStore.swift @@ -24,8 +24,8 @@ public struct StateStore: Sendable { try withLock(createIfMissing: false) { try readDeclaration() } } - package func readDeclaration() throws -> Declaration { - let declaration: Declaration = try load(declarationURL) ?? Declaration() + package func readDeclaration(prepared: StatePrecondition? = nil) throws -> Declaration { + let declaration: Declaration = try load(declarationURL, prepared: prepared) ?? Declaration() try declaration.validate(environment: environment) return declaration } @@ -34,8 +34,8 @@ public struct StateStore: Sendable { try withLock(createIfMissing: false) { try readResolved() } } - package func readResolved() throws -> ResolvedState { - let lock: ResolvedState = try load(resolvedURL) ?? ResolvedState() + package func readResolved(prepared: StatePrecondition? = nil) throws -> ResolvedState { + let lock: ResolvedState = try load(resolvedURL, prepared: prepared) ?? ResolvedState() try lock.validate() return lock } @@ -44,8 +44,8 @@ public struct StateStore: Sendable { try withLock(createIfMissing: false) { try readWatch() } } - package func readWatch() throws -> WatchState { - let watch: WatchState = try load(watchURL) ?? WatchState() + package func readWatch(prepared: StatePrecondition? = nil) throws -> WatchState { + let watch: WatchState = try load(watchURL, prepared: prepared) ?? WatchState() try watch.validate() return watch } @@ -58,14 +58,21 @@ public struct StateStore: Sendable { try declaration.validate(environment: environment) try resolved.validate() try watch?.validate() - _ = try readDeclaration() - _ = try readResolved() + let baseline = try StatePrecondition(store: self) + _ = try readDeclaration(prepared: baseline) + _ = try readResolved(prepared: baseline) let transaction = FileTransaction(store: self) - try stageDeclaration(declaration, in: transaction) + transaction.validateBeforePublication = { [unowned transaction] in + try baseline.validate(excludingTargets: transaction.targetPaths) + } + try stageDeclaration(declaration, in: transaction, prepared: baseline) try transaction.replace( - resolvedURL, content: nil, data: Self.encodeState(resolved.normalized)) + resolvedURL, content: nil, data: Self.encodeState(resolved.normalized), + expecting: baseline.evidence(for: resolvedURL)) if let watch { - try transaction.replace(watchURL, content: nil, data: Self.encode(watch)) + try transaction.replace( + watchURL, content: nil, data: Self.encode(watch), + expecting: baseline.evidence(for: watchURL)) } try transaction.commit() } @@ -73,11 +80,19 @@ public struct StateStore: Sendable { /// 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 - { + package func stageDeclaration( + _ declaration: Declaration, in transaction: FileTransaction, + prepared: StatePrecondition? = nil + ) throws { let data = try Self.encodeState(declaration.normalized) - guard try existingData(declarationURL) != data else { return } - try transaction.replace(declarationURL, content: nil, data: data) + let input: (bytes: Data?, evidence: TargetPrecondition) + if let prepared { + input = try (prepared.bytes(for: declarationURL), prepared.evidence(for: declarationURL)) + } else { + input = try TargetPrecondition.readingFile(declarationURL) + } + guard input.bytes != data else { return } + try transaction.replace(declarationURL, content: nil, data: data, expecting: input.evidence) } package func withLock( @@ -155,8 +170,14 @@ public struct StateStore: Sendable { return data } - private func load(_ url: URL) throws -> T? { - guard let data = try existingData(url) else { return nil } + private func load(_ url: URL, prepared: StatePrecondition?) throws -> T? { + let bytes: Data? + if let prepared { + bytes = try prepared.bytes(for: url) + } else { + bytes = try existingData(url) + } + guard let data = bytes else { return nil } do { return try Self.decode(data, as: T.self) } catch { diff --git a/Sources/AgentsCore/TransactionEvidence.swift b/Sources/AgentsCore/TransactionEvidence.swift new file mode 100644 index 0000000..417f0c9 --- /dev/null +++ b/Sources/AgentsCore/TransactionEvidence.swift @@ -0,0 +1,197 @@ +import CPlatform +import Foundation + +struct FileObjectIdentity: Codable, Equatable, Sendable { + let device: UInt64 + let inode: UInt64 + let kind: mode_t + + var isDirectory: Bool { kind == S_IFDIR } + + init(_ info: stat) { + device = UInt64(info.st_dev) + inode = UInt64(info.st_ino) + kind = info.st_mode & S_IFMT + } +} + +/// Content and physical ownership are separate evidence. Descendant identities let +/// terminal cleanup resume after partial deletion without adopting new entries. +struct FileSnapshot: Codable, Equatable, Sendable { + let identity: FileObjectIdentity + let digest: String + let executable: Bool + /// Final permission bits. Only publishing/restoring may temporarily add directory owner-write. + let mode: mode_t + let children: [String: FileSnapshot]? + + static func read(at url: URL) throws -> FileSnapshot? { + var info = stat() + if lstat(url.path, &info) != 0 { + if errno == ENOENT { return nil } + throw FileSystem.posixError(errno, at: url, otherwise: .unsafePath("cannot inspect target")) + } + let parent = try DirectoryHandle(at: url.deletingLastPathComponent().resolvingSymlinksInPath()) + return try read(url.lastPathComponent, from: parent) + } + + struct Capture { + let snapshot: FileSnapshot? + let contentHash: String + let executableFlags: [String: Bool] + let bytes: Data? + } + + static func captureFile(at url: URL) throws -> Capture { + var info = stat() + if lstat(url.path, &info) != 0 { + if errno == ENOENT { + return Capture( + snapshot: nil, contentHash: FileHash.hashRecords([]), executableFlags: [:], bytes: nil) + } + throw FileSystem.posixError(errno, at: url, otherwise: .unsafePath("cannot inspect target")) + } + guard info.st_mode & S_IFMT == S_IFREG else { + throw CoreError.unsafePath("expected regular file: \(url.path)") + } + let parent = try DirectoryHandle(at: url.deletingLastPathComponent().resolvingSymlinksInPath()) + return try capture(url.lastPathComponent, from: parent) + } + + /// The snapshot and content verification consume the same opened-file bytes. + static func capture(_ name: String, from parent: DirectoryHandle) throws -> Capture { + var records: [(String, Data)] = [] + var rootBytes: Data? + var flags: [String: Bool] = [:] + let value = try read(name, from: parent, relative: "") { path, kind, bytes, executable in + guard !path.isEmpty else { + if kind == S_IFREG { + rootBytes = bytes + flags[""] = executable + } + return + } + switch kind { + case S_IFDIR: records.append((path, Data("directory".utf8))) + case S_IFREG: + records.append((path, Data("file\0".utf8) + bytes)) + flags[path] = executable + case S_IFLNK: records.append((path, Data("link\0".utf8) + bytes)) + default: break + } + } + return Capture( + snapshot: value, + contentHash: value?.isRegular == true ? value!.digest : FileHash.hashRecords(records), + executableFlags: flags, bytes: rootBytes) + } + + static func read(_ name: String, from parent: DirectoryHandle) throws -> FileSnapshot? { + try read(name, from: parent, relative: "", collect: nil) + } + + private static func read( + _ name: String, from parent: DirectoryHandle, relative: String, + collect: ((String, mode_t, Data, Bool) -> Void)? + ) throws -> FileSnapshot? { + guard var before = try parent.info(name) else { return nil } + let children: [String: FileSnapshot]? + let payload: Data + switch before.st_mode & S_IFMT { + case S_IFDIR: + let directory = try parent.child(name) + var opened = stat() + guard fstat(directory.descriptor, &opened) == 0, platform_same_generation(&before, &opened) + else { + throw CoreError.invalidState("directory changed before reading: \(name)") + } + var entries: [String: FileSnapshot] = [:] + for child in try directory.names() { + guard + let value = try read( + child, from: directory, relative: relative.isEmpty ? child : relative + "/" + child, + collect: collect) + else { + throw CoreError.invalidState("entry changed while reading: \(child)") + } + entries[child] = value + } + children = entries + // Only content enters the digest; ownership is compared independently. + payload = try StateStore.encode( + entries.mapValues { "\($0.identity.kind):\($0.executable):\($0.digest)" }) + case S_IFREG: + children = nil + payload = try parent.read(name, matching: before) + case S_IFLNK: + children = nil + payload = try parent.readLinkData(name) + default: throw CoreError.unsafePath("unsupported transaction entry: \(name)") + } + guard var after = try parent.info(name), platform_same_generation(&before, &after) else { + throw CoreError.invalidState("entry changed while reading: \(name)") + } + collect?(relative, before.st_mode & S_IFMT, payload, before.st_mode & 0o111 != 0) + return FileSnapshot( + identity: FileObjectIdentity(before), digest: FileHash.sha256Hex(data: payload), + executable: before.st_mode & S_IFMT == S_IFREG && before.st_mode & 0o111 != 0, + mode: before.st_mode & 0o7777, + children: children) + } + + var needsDirectoryWriteLease: Bool { identity.isDirectory && mode & 0o200 == 0 } + + func matches(_ current: Self, permittingDirectoryWrite: Bool) -> Bool { + if self == current { return true } + guard permittingDirectoryWrite, needsDirectoryWriteLease, current.mode == mode | 0o200 else { + return false + } + return Self( + identity: identity, digest: digest, executable: executable, mode: mode | 0o200, + children: children) == current + } + + var isRegular: Bool { identity.kind == S_IFREG } + var isSymbolicLink: Bool { identity.kind == S_IFLNK } + + func validate() throws { + try StateValidation.digest("sha256:" + digest) + let kinds: [mode_t] = [S_IFDIR, S_IFREG, S_IFLNK] + guard kinds.contains(identity.kind), mode & ~0o7777 == 0, + (identity.kind == S_IFDIR) == (children != nil) + else { throw CoreError.invalidState("invalid transaction object evidence") } + for (name, child) in children ?? [:] { + guard !name.isEmpty, name != ".", name != "..", !name.contains("/"), + !name.contains("\0") + else { throw CoreError.invalidState("invalid transaction descendant") } + try child.validate() + } + } + + func containsRemaining(_ current: FileSnapshot) -> Bool { + guard identity == current.identity else { return false } + guard let children, let remaining = current.children else { return self == current } + return remaining.allSatisfy { name, value in children[name]?.containsRemaining(value) == true } + } + + func synchronize(_ name: String, from parent: DirectoryHandle) throws { + guard try Self.read(name, from: parent) == self else { + throw CoreError.invalidState("transaction preimage changed before synchronization: \(name)") + } + try syncContents(name, from: parent) + try parent.sync() + } + + private func syncContents(_ name: String, from parent: DirectoryHandle) throws { + if let children { + let directory = try parent.child(name) + for child in children.keys.sorted() { + try children[child]!.syncContents(child, from: directory) + } + try directory.sync() + } else if identity.kind == S_IFREG { + try parent.syncFile(name, includingParent: false) + } + } + +} diff --git a/Sources/AgentsCore/TransactionJournal.swift b/Sources/AgentsCore/TransactionJournal.swift new file mode 100644 index 0000000..6b1f1cb --- /dev/null +++ b/Sources/AgentsCore/TransactionJournal.swift @@ -0,0 +1,238 @@ +import Foundation + +/// The version is independent of declaration, resolved and watch formats. +struct TransactionJournal: Codable { + static let currentVersion = 1 + var version = currentVersion + var id: UUID + var scope: String + var roots: [String: String] + var phase: Phase = .preparing + var entries: [Entry] + var containers: [Container] + /// Only this durable intent permits absent or partially removed disposal objects. + var discarding = false + + enum Phase: String, Codable { case preparing, applying, committed, rolledBack } + enum Action: String, Codable { case install, delete } + enum Progress: String, Codable { + /// Preimage and container name are durable; construction has no per-object ownership claims. + case queued + /// Construction is verified; staged is sealed and other recovery slots are absent. + case ready + /// Publication and temporary directory-write intent are durable, with original modes. + case publishing + /// Rename parents and original modes are synced; the installed distribution is verified. + case applied + /// Undo and directory-write intent are durable; installed or reverted objects may be present. + case restoring + /// Undo parents and original modes are synced; reverted objects remain until discard intent. + case restored + /// Original modes are restored; publication did not consume private staging. + case cancelled + + var permitsDirectoryWrite: Bool { self == .publishing || self == .restoring } + } + + struct Conflict: Codable { + let reason: String + /// Scope-relative destinations and container locations, never executable input paths. + let locations: [String] + } + + struct Entry: Codable { + var path: String + var action: Action + var preimage: FileSnapshot? + var parentIdentity: String + var container: Int + /// Non-nil exactly when an install has reached ready; never refreshed after sealing. + /// Modes in both snapshots are the final modes, before any directory-write intent. + var staged: FileSnapshot? + var progress: Progress = .queued + var conflict: Conflict? + var name: String { String(path.split(separator: "/").last!) } + } + + struct Container: Codable { + /// A representative entry pins the parent; the name is derived from id and this array index. + var entry: Int + var name: String + /// Persisted before inserting any object. Without it only an empty rmdir is allowed. + var identity: FileObjectIdentity? + /// Present only for terminal disposal containing user data. Missing entries are admitted + /// only after discarding is durable; private unfinished construction needs no tree evidence. + var cleanup: FileSnapshot? + } + + func containerName(_ index: Int) -> String { containers[index].name } +} + +enum TransactionScratch: String, CaseIterable { + case staged, preimage, removed, work + case probeA = "probe-a" + case probeB = "probe-b" + case probeC = "probe-c" + var name: String { rawValue } + func name(_ index: Int) -> String { "entry.\(index).\(rawValue)" } + static let objectSlots: [Self] = [.staged, .preimage, .removed] +} + +/// The operation/progress table is the single authority for physical object distribution. +/// A nil expected object means the slot must be absent, not that ownership is unknown. +struct TransactionLayout { + enum Kind { case prepared, installed, reverted, construction } + enum Target { + case any, absent + case object(FileSnapshot) + case externalTo(FileObjectIdentity) + + func matches( + _ name: String, from parent: DirectoryHandle, permittingDirectoryWrite: Bool = false + ) throws -> Bool { + switch self { + case .any: return true + case .absent: return try parent.info(name) == nil + case .externalTo(let identity): + return try parent.info(name).map(FileObjectIdentity.init) != identity + case .object(let expected): + guard try parent.info(name).map(FileObjectIdentity.init) == expected.identity else { + return false + } + return try FileSnapshot.read(name, from: parent).map { + expected.matches($0, permittingDirectoryWrite: permittingDirectoryWrite) + } == true + } + } + } + let kind: Kind + let target: Target + let objects: [TransactionScratch: FileSnapshot] + + static func expected(_ entry: TransactionJournal.Entry) -> [Self] { + if entry.progress == .queued { return [Self(kind: .construction, target: .any, objects: [:])] } + let prepared = Self( + kind: .prepared, target: .any, + objects: entry.staged.map { [.staged: $0] } ?? [:]) + let installed: Self + let reverted: Self + switch (entry.action, entry.preimage) { + case (.install, .some(let original)): + installed = Self( + kind: .installed, target: .object(entry.staged!), objects: [.staged: original]) + reverted = Self(kind: .reverted, target: .object(original), objects: [.staged: entry.staged!]) + case (.install, .none): + installed = Self(kind: .installed, target: .object(entry.staged!), objects: [:]) + reverted = Self( + kind: .reverted, target: .externalTo(entry.staged!.identity), + objects: [.removed: entry.staged!]) + case (.delete, .some(let original)): + installed = Self(kind: .installed, target: .absent, objects: [.preimage: original]) + reverted = Self(kind: .reverted, target: .object(original), objects: [:]) + case (.delete, .none): + installed = Self(kind: .installed, target: .absent, objects: [:]) + reverted = Self(kind: .reverted, target: .any, objects: [:]) + } + switch entry.progress { + case .queued: return [Self(kind: .construction, target: .any, objects: [:])] + case .ready, .cancelled: return [prepared] + case .publishing: + if entry.action == .delete, let original = entry.preimage { + return [Self(kind: .prepared, target: .object(original), objects: [:]), installed] + } + return [installed, prepared] + case .applied: return [installed] + case .restoring: return [reverted, installed] + case .restored: return [reverted] + } + } +} + +enum TransactionCheckpoint { + enum Change { + case created, containers + case entry(Int, TransactionJournal.Progress) + case terminal, discard + case conflict(Int, TransactionJournal.Progress) + var name: String { + switch self { + case .created: "created" + case .containers: "containers" + case .entry(let index, let progress): "entry.\(index).\(progress.rawValue)" + case .terminal: "terminal" + case .discard: "discard" + case .conflict(let index, let progress): "entry.\(index).\(progress.rawValue).conflict" + } + } + } + enum Stage: String { case preimageSynced, workCreated, workPrepared, writeCreated, constructed } + enum Publication: String { case validated, exchanged, created, quarantined, synced } + enum Restoration: String { case validated, exchanged, returned, creationQuarantined, synced } + enum PersistenceStep: String { case written, renamed } + case persisted(TransactionJournal.Phase, Change, PersistenceStep) + case phase(TransactionJournal.Phase) + case progress(Int, TransactionJournal.Progress) + case containerCreated(Int) + case containersIdentified + case probe(Int, DirectoryHandle.ProbeStep) + case stage(Int, Stage) + case copy(Int, DirectoryHandle.CopyPoint) + case publication(Int, Publication) + case restoration(Int, Restoration) + case permissions( + Int, TransactionPermissionPurpose, TransactionObjectLocation, DirectoryHandle.PermissionStep) + case preconditions, commitValidated, terminalSynced, discardIntent + case disposal(Int, DirectoryHandle.RemovalPoint) + case containerRemoved(Int) + case journalUnlinked + case journalRemoved + + var name: String { + switch self { + case .persisted(let phase, let change, let step): + "journal.\(phase.rawValue).\(change.name).\(step.rawValue)" + case .phase(let phase): "journal.\(phase.rawValue)" + case .progress(let index, let progress): "entry.\(index).\(progress.rawValue)" + case .containerCreated(let index): "container.\(index).created" + case .containersIdentified: "containers.identified" + case .probe(let index, let point): "atomic.\(index).\(point.rawValue)" + case .stage(let index, let point): "stage.\(index).\(point.rawValue)" + case .copy(let index, let point): "stage.\(index).copy.\(point.path).\(point.step.rawValue)" + case .publication(let index, let point): "publish.\(index).\(point.rawValue)" + case .restoration(let index, let point): "restore.\(index).\(point.rawValue)" + case .permissions(let index, let purpose, let location, let point): + "permissions.\(index).\(purpose.rawValue).\(location.name).\(point.rawValue)" + case .preconditions: "publication.preconditions" + case .commitValidated: "publication.commitValidated" + case .terminalSynced: "journal.terminalSynced" + case .discardIntent: "cleanup.intent" + case .disposal(let index, let point): + "cleanup.\(index)." + + (["container"] + point.path.split(separator: "/").dropFirst().map(String.init)).joined( + separator: "/") + ".\(point.step.rawValue)" + case .containerRemoved(let index): "cleanup.\(index).removed" + case .journalUnlinked: "journal.unlinked" + case .journalRemoved: "journal.removed" + } + } +} + +extension TransactionSession { + /// Transitions and their durable evidence promises are changed together. + func advance(_ index: Int, to next: TransactionJournal.Progress) throws { + let previous = journal.entries[index].progress + let legal: [TransactionJournal.Progress: Set] = [ + .queued: [.ready], .ready: [.publishing, .cancelled], + .publishing: [.applied, .restoring, .cancelled], .applied: [.restoring], + .restoring: [.restored], .restored: [], .cancelled: [], + ] + guard legal[previous]?.contains(next) == true else { + throw conflict(index, "illegal progress transition: \(previous) -> \(next)") + } + if next == .publishing { journal.phase = .applying } + journal.entries[index].progress = next + journal.entries[index].conflict = nil + try persist(.entry(index, next)) + try emit(.progress(index, next)) + } +} diff --git a/Sources/AgentsCore/TransactionPermissions.swift b/Sources/AgentsCore/TransactionPermissions.swift new file mode 100644 index 0000000..26c4e61 --- /dev/null +++ b/Sources/AgentsCore/TransactionPermissions.swift @@ -0,0 +1,118 @@ +import Foundation + +enum TransactionObjectLocation { + case target + case scratch(TransactionScratch) + + var name: String { + switch self { + case .target: "target" + case .scratch(let slot): slot.rawValue + } + } +} + +enum TransactionPermissionPurpose: String { + case publicationGrant = "publish.grant" + case publicationRestore = "publish.restore" + case undoGrant = "undo.grant" + case undoRestore = "undo.restore" + case cancelRestore = "cancel.restore" + case conflictRestore = "conflict.restore" +} + +extension TransactionSession { + /// Publishing/restoring intent binds a temporary owner-write bit to the recorded + /// directory inode. It never grants access through an external replacement. + func grantDirectoryPermissions( + _ index: Int, layout: TransactionLayout, purpose: TransactionPermissionPurpose + ) throws { + let entry = journal.entries[index] + var objects: [(TransactionObjectLocation, FileSnapshot)] = [] + if case .object(let expected) = layout.target { + objects.append((.target, expected)) + } else if layout.kind == .prepared, let original = entry.preimage { + objects.append((.target, original)) + } + for slot in TransactionScratch.objectSlots { + if let expected = layout.objects[slot] { objects.append((.scratch(slot), expected)) } + } + for (location, expected) in objects where expected.needsDirectoryWriteLease { + try setDirectoryPermissions( + index, location: location, expected: expected, mode: expected.mode | 0o200, purpose: purpose + ) + } + } + + /// Mode restoration uses physical identity independently of byte rollback. A + /// changed payload is retained, while a known temporary permission can be undone. + /// Missing inodes or modes outside the recorded pair require owner action. + func restoreDirectoryPermissions(_ index: Int, purpose: TransactionPermissionPurpose) throws { + try forEachDirectoryPermission(index) { location, expected in + try setDirectoryPermissions( + index, location: location, expected: expected, mode: expected.mode, purpose: purpose) + } + } + + func inspectDirectoryPermissions(_ index: Int) throws { + guard journal.entries[index].progress.permitsDirectoryWrite else { return } + try forEachDirectoryPermission(index) { location, expected in + let (parent, name) = try permissionLocation(index, location) + _ = try parent.child(name).checkedPermissions( + expecting: expected.identity, from: expected.mode) + } + } + + private func forEachDirectoryPermission( + _ index: Int, body: (TransactionObjectLocation, FileSnapshot) throws -> Void + ) throws { + let entry = journal.entries[index] + let expected = [entry.preimage, entry.staged].compactMap { $0 } + .filter(\.needsDirectoryWriteLease) + guard !expected.isEmpty else { return } + var found: [FileObjectIdentity] = [] + var errors: [String] = [] + let locations: [TransactionObjectLocation] = + [.target] + + TransactionScratch.objectSlots.map { .scratch($0) } + for location in locations { + do { + let (parent, name) = try permissionLocation(index, location) + guard let identity = try parent.info(name).map(FileObjectIdentity.init), + let object = expected.first(where: { $0.identity == identity }) + else { continue } + found.append(identity) + try body(location, object) + } catch { errors.append(String(describing: error)) } + } + if expected.contains(where: { !found.contains($0.identity) }) { + errors.append("directory mode restoration is missing its recorded inode") + } + guard errors.isEmpty else { throw conflict(index, errors.joined(separator: "; ")) } + } + + private func permissionLocation(_ index: Int, _ location: TransactionObjectLocation) throws + -> (DirectoryHandle, String) + { + try requireParent(index) + switch location { + case .target: return (parents[index], journal.entries[index].name) + case .scratch(let slot): + return (try container(journal.entries[index].container), slot.name(index)) + } + } + + private func setDirectoryPermissions( + _ index: Int, location: TransactionObjectLocation, expected: FileSnapshot, mode: mode_t, + purpose: TransactionPermissionPurpose + ) throws { + guard journal.entries[index].progress.permitsDirectoryWrite else { + throw conflict(index, "directory permission change requires durable intent") + } + let (parent, name) = try permissionLocation(index, location) + let directory = try parent.child(name) + try directory.setPermissions(mode, expecting: expected.identity, from: expected.mode) { + try emit(.permissions(index, purpose, location, $0)) + } + } +} diff --git a/Sources/AgentsCore/TransactionRecovery.swift b/Sources/AgentsCore/TransactionRecovery.swift new file mode 100644 index 0000000..1a6a7ae --- /dev/null +++ b/Sources/AgentsCore/TransactionRecovery.swift @@ -0,0 +1,551 @@ +import Foundation + +package struct TransactionRecoveryDiagnostic { + package let requiresOwner: Bool + package let message: String +} + +extension FileTransaction { + package static func recover( + store: StateStore, outcome: TransactionOutcome? = nil, + checkpoint: @escaping (String) throws -> Void = { _ in } + ) throws -> Bool { + guard let directory = try store.openDirectoryIfPresent() else { return false } + guard try directory.info("transaction.json") != nil else { + guard try directory.info("transaction.new") != nil else { return false } + let bytes = try directory.read("transaction.new") + if (try? JSONSerialization.jsonObject(with: bytes)) != nil { + let journal = try readJournal(bytes) + guard journal.phase == .preparing, journal.containers.allSatisfy({ $0.identity == nil }), + journal.entries.allSatisfy({ $0.progress == .queued }) + else { + throw CoreError.invalidState( + "missing primary journal; retained transaction.new needs owner action") + } + } + try directory.remove("transaction.new") + return true + } + var recoveredID: UUID? + do { + let journal = try readJournal(directory.read("transaction.json")) + recoveredID = journal.id + let session = try recoverySession( + journal, store: store, directory: directory, checkpoint: checkpoint) + // Validate the journal's scratch file before any recovery mutation. + if try directory.info("transaction.new") != nil { _ = try directory.read("transaction.new") } + let observedTerminal = journal.phase == .committed || journal.phase == .rolledBack + if journal.phase == .applying { try session.rollback() } + if session.journal.phase == .applying || session.journal.phase == .preparing { + try session.prepareCleanup() + session.journal.phase = .rolledBack + try session.persist(.terminal) + try session.emit(.phase(.rolledBack)) + } + try session.cleanup(observedTerminal: observedTerminal) + if outcome?.journalID == journal.id { + outcome?.disposition = session.journal.phase == .committed ? .committed : .unchanged + } + return true + } catch { + // An unreadable journal cannot prove an unchanged or committed outcome. + if recoveredID == nil || outcome?.journalID == recoveredID { + outcome?.disposition = .recoveryRequired + } + throw error + } + } + + package static func recoveryDiagnostic(store: StateStore) -> TransactionRecoveryDiagnostic { + var retained = [store.directory.appendingPathComponent("transaction.json").path] + do { + guard let directory = try store.openDirectoryIfPresent() else { + return .init( + requiresOwner: false, + message: + "Transaction recovery is pending; the next command that changes this scope will recover it." + ) + } + if try directory.info("transaction.json") == nil { + if try directory.info("transaction.new") != nil { + let bytes = try directory.read("transaction.new") + if (try? JSONSerialization.jsonObject(with: bytes)) != nil { + let incomplete = try readJournal(bytes) + guard incomplete.phase == .preparing, + incomplete.containers.allSatisfy({ $0.identity == nil }), + incomplete.entries.allSatisfy({ $0.progress == .queued }) + else { + throw CoreError.invalidState( + "missing primary journal; retained transaction.new needs owner action") + } + } + } + return .init( + requiresOwner: false, + message: + "Transaction recovery is pending; the next command that changes this scope will recover it." + ) + } + let journal = try readJournal(directory.read("transaction.json")) + retained += journal.entries.compactMap { entry in + guard journal.containers.indices.contains(entry.container) else { return nil } + let container = journal.containers[entry.container] + guard container.name == ".agents-\(journal.id.uuidString)-\(entry.container)" else { + return nil + } + return entry.path.split(separator: "/").dropLast().joined(separator: "/") + + "/" + container.name + } + let session = try recoverySession( + journal, store: store, directory: directory, checkpoint: { _ in }) + let conflicts = journal.entries.compactMap(\.conflict) + if !conflicts.isEmpty { + let details = conflicts.map { + "\($0.reason); retained locations: \($0.locations.joined(separator: ", "))" + } + return .init( + requiresOwner: true, + message: "Unresolved transaction conflict; owner action is required. " + + details.joined(separator: "; ") + + "; journal: " + directory.url.appendingPathComponent("transaction.json").path) + } + try session.inspectRecoveryObjects() + return .init( + requiresOwner: false, + message: + "Transaction recovery is pending; the next command that changes this scope will recover it." + ) + } catch { + return .init( + requiresOwner: true, + message: + "Unresolved transaction conflict; owner action is required: \(error). Retained locations: \(Set(retained).sorted().joined(separator: ", "))." + ) + } + } + + private static func readJournal(_ bytes: Data) throws -> TransactionJournal { + try JSONKeys.validate(bytes) + let value = try JSONSerialization.jsonObject(with: bytes) as? [String: Any] + guard value?["version"] as? Int == TransactionJournal.currentVersion else { + throw CoreError.invalidState( + "transaction journal was written by another version; recover it with the version that wrote it (journal version: \(value?["version"].map(String.init(describing:)) ?? "missing"))" + ) + } + do { return try StateStore.decode(bytes, as: TransactionJournal.self) } catch { + throw CoreError.invalidState("unresolved transaction journal: \(error)") + } + } + + private static func recoverySession( + _ journal: TransactionJournal, store: StateStore, + directory: DirectoryHandle, checkpoint: @escaping (String) throws -> Void + ) throws -> TransactionSession { + let paths = TransactionPaths(store: store) + var roots: [String: DirectoryHandle] = [:] + for key in journal.roots.keys { + let root = try paths.root(key) + guard try root.identity == journal.roots[key] else { + throw CoreError.invalidState("transaction root identity changed") + } + roots[key] = root + } + let parents = try journal.entries.map { try paths.parent(for: $0.path, roots: roots) } + let session = TransactionSession( + journal: journal, directory: directory, parents: parents, checkpoint: checkpoint) + try session.validateRecords(store: store) + return session + } +} + +extension TransactionSession { + func requireScope() throws { + guard try DirectoryHandle(at: directory.url).identity == journal.scope else { + throw CoreError.invalidState("transaction scope identity changed") + } + } + + func requireParent(_ index: Int) throws { + guard + try DirectoryHandle(at: parents[index].url).identity == journal.entries[index].parentIdentity + else { + throw conflict(index, "destination parent changed") + } + } + + func conflict(_ index: Int, _ reason: String) -> CoreError { + .invalidState( + "transaction conflict at \(journal.entries[index].path): \(reason); retained container: \(containerLocation(index))" + ) + } + + func containerLocation(_ index: Int) -> String { + let entry = journal.entries[index] + guard journal.containers.indices.contains(entry.container) else { + return "" + } + return entry.path.split(separator: "/").dropLast().joined(separator: "/") + "/" + + journal.containerName(entry.container) + } + + func recordConflict(_ index: Int, _ error: Error) throws { + journal.entries[index].conflict = .init( + reason: String(describing: error), + locations: [journal.entries[index].path, containerLocation(index)]) + try persist(.conflict(index, journal.entries[index].progress)) + } + + func validateRecords(store: StateStore) throws { + try requireScope() + let paths = TransactionPaths(store: store) + let keys = try Set(journal.entries.map { try paths.components($0.path).root }) + guard keys == Set(journal.roots.keys), !journal.entries.isEmpty else { + throw CoreError.invalidState("invalid transaction roots") + } + var targets: [URL] = [] + for (index, entry) in journal.entries.enumerated() { + try requireParent(index) + let target = parents[index].url.appendingPathComponent(entry.name) + guard + !targets.contains(where: { + PathSafety.isContained(target, in: $0) || PathSafety.isContained($0, in: target) + }), + journal.containers.indices.contains(entry.container) + else { + throw conflict(index, "overlapping destinations or invalid container") + } + targets.append(target) + try validateProgress(index) + try entry.preimage?.validate() + try entry.staged?.validate() + } + for index in journal.containers.indices { try validateContainerRecord(index) } + for (index, entry) in journal.entries.enumerated() { + if let conflict = entry.conflict, + conflict.locations != [entry.path, containerLocation(index)] + { + throw CoreError.invalidState("invalid transaction conflict locations") + } + } + } + + private func validateContainerRecord(_ index: Int) throws { + let record = journal.containers[index] + guard journal.entries.indices.contains(record.entry), + journal.entries[record.entry].container == index, + record.name == ".agents-\(journal.id.uuidString)-\(index)", + record.identity?.isDirectory != false + else { + throw CoreError.invalidState("invalid private transaction container evidence") + } + for entry in journal.entries where entry.container == index { + guard entry.parentIdentity == journal.entries[record.entry].parentIdentity else { + throw CoreError.invalidState("private container belongs to another parent") + } + guard entry.progress == .queued || record.identity != nil else { + throw CoreError.invalidState("sealed operation is missing private container identity") + } + } + try record.cleanup?.validate() + if let cleanup = record.cleanup { + guard cleanup.identity == record.identity else { + throw CoreError.invalidState("terminal container evidence has another identity") + } + } + if journal.phase == .committed || journal.phase == .rolledBack { + let containsUserData = journal.entries.filter { $0.container == index }.contains { entry in + [.applied, .restored].contains(entry.progress) + && TransactionLayout.expected(entry).contains { !$0.objects.isEmpty } + } + guard !containsUserData || record.cleanup != nil else { + throw CoreError.invalidState("terminal container is missing user-object disposal evidence") + } + } + } + + private func validateProgress(_ index: Int) throws { + let entry = journal.entries[index] + let allowed: Set + switch journal.phase { + case .preparing: allowed = [.queued, .ready] + case .applying: allowed = [.ready, .publishing, .applied, .restoring, .restored, .cancelled] + case .committed: allowed = [.applied] + case .rolledBack: allowed = [.queued, .ready, .restored, .cancelled] + } + let requiresStaging = entry.action == .install && entry.progress != .queued + guard allowed.contains(entry.progress), + (entry.staged != nil) == requiresStaging, + !journal.discarding || journal.phase == .committed || journal.phase == .rolledBack + else { + throw conflict(index, "operation progress contradicts its evidence or journal phase") + } + } + + func distribution(_ index: Int, permittingDirectoryWrite: Bool = true) throws -> TransactionLayout + { + let entry = journal.entries[index] + try requireParent(index) + if entry.progress == .queued { return TransactionLayout.expected(entry)[0] } + let scratch = try container(entry.container) + let layouts = TransactionLayout.expected(entry) + var objects: [TransactionScratch: FileSnapshot] = [:] + for slot in TransactionScratch.objectSlots { + if let value = try FileSnapshot.read(slot.name(index), from: scratch) { + objects[slot] = value + } + } + let permitsWrite = permittingDirectoryWrite && entry.progress.permitsDirectoryWrite + for layout in layouts where Set(layout.objects.keys) == Set(objects.keys) { + guard + layout.objects.allSatisfy({ slot, expected in + expected.matches(objects[slot]!, permittingDirectoryWrite: permitsWrite) + }) + else { continue } + if try layout.target.matches( + entry.name, from: parents[index], permittingDirectoryWrite: permitsWrite) + { + return layout + } + } + throw conflict(index, "missing or changed expected target, preimage or rollback quarantine") + } + + func rollback() throws { + var errors: [String] = [] + for index in journal.entries.indices.reversed() { + do { try rollbackEntry(index) } catch { + var reasons = [String(describing: error)] + if journal.entries[index].progress.permitsDirectoryWrite { + do { try restoreDirectoryPermissions(index, purpose: .conflictRestore) } catch { + reasons.append(String(describing: error)) + } + } + let failure = CoreError.invalidState(reasons.joined(separator: "; ")) + try recordConflict(index, failure) + errors.append(String(describing: failure)) + } + } + guard errors.isEmpty else { + throw CoreError.invalidState( + "unresolved transaction conflicts: " + errors.joined(separator: "; ")) + } + } + + private func rollbackEntry(_ index: Int) throws { + let layout = try distribution(index) + let progress = journal.entries[index].progress + if progress == .ready { + try advance(index, to: .cancelled) + return + } + if progress == .cancelled || progress == .restored { return } + if layout.kind == .prepared { + try restoreDirectoryPermissions(index, purpose: .cancelRestore) + _ = try distribution(index, permittingDirectoryWrite: false) + try advance(index, to: .cancelled) + return + } + if progress != .restoring { try advance(index, to: .restoring) } + if layout.kind == .installed { + try grantDirectoryPermissions(index, layout: layout, purpose: .undoGrant) + try undo(index) + } else { + // A visible undo rename may have been interrupted before either parent barrier. + try parents[index].sync() + try container(journal.entries[index].container).sync() + } + try restoreDirectoryPermissions(index, purpose: .undoRestore) + try emit(.restoration(index, .synced)) + guard try distribution(index, permittingDirectoryWrite: false).kind == .reverted else { + throw conflict(index, "undo did not restore the expected objects") + } + try advance(index, to: .restored) + } + + private func undo(_ index: Int) throws { + let entry = journal.entries[index] + let parent = parents[index] + let scratch = try container(entry.container) + try emit(.restoration(index, .validated)) + if entry.preimage != nil { + if entry.action == .install { + try scratch.move( + TransactionScratch.staged.name(index), to: parent, named: entry.name, mode: .exchange + ) { + try emit(.restoration(index, .exchanged)) + } + } else { + try scratch.move( + TransactionScratch.preimage.name(index), to: parent, named: entry.name, mode: .exclusive + ) { + try emit(.restoration(index, .returned)) + } + } + } else if entry.action == .install { + try parent.move( + entry.name, to: scratch, named: TransactionScratch.removed.name(index), mode: .exclusive + ) { + try emit(.restoration(index, .creationQuarantined)) + } + } + } + + func prepareCleanup() throws { + var userContainers: Set = [] + var layouts: [Int: TransactionLayout] = [:] + for index in journal.entries.indices { + do { + let layout = try distribution(index) + layouts[index] = layout + if [.installed, .reverted].contains(layout.kind), !layout.objects.isEmpty { + userContainers.insert(journal.entries[index].container) + } + } catch { + try recordConflict(index, error) + throw error + } + } + for index in journal.containers.indices { + do { + try prepareContainerCleanup( + index, userData: userContainers.contains(index), layouts: layouts) + } catch { + try recordConflict(journal.containers[index].entry, error) + throw error + } + } + for index in journal.entries.indices { journal.entries[index].conflict = nil } + } + + private func prepareContainerCleanup( + _ index: Int, userData: Bool, layouts: [Int: TransactionLayout] + ) throws { + let record = journal.containers[index] + let parent = parents[record.entry] + if record.identity == nil { + if try parent.info(record.name) != nil, try !parent.child(record.name).names().isEmpty { + throw conflict(record.entry, "unidentified private container is not empty") + } + return + } + let handle = try container(index) + guard userData else { return } + let snapshot = try FileSnapshot.read(record.name, from: parent) + guard try handle.objectIdentity == snapshot?.identity else { + throw conflict(record.entry, "container changed while sealing disposal") + } + for entryIndex in journal.entries.indices where journal.entries[entryIndex].container == index { + for (slot, expected) in layouts[entryIndex]!.objects { + guard snapshot?.children?[slot.name(entryIndex)] == expected else { + throw conflict(entryIndex, "expected user object changed while sealing disposal") + } + } + } + journal.containers[index].cleanup = snapshot + } + + func inspectRecoveryObjects() throws { + if journal.discarding { + for index in journal.entries.indices { try verifyTarget(index) } + } else { + for index in journal.entries.indices { + _ = try distribution(index) + try inspectDirectoryPermissions(index) + } + } + try validateContainersForDisposal() + } + + func cleanup(observedTerminal: Bool = false) throws { + try requireScope() + if observedTerminal { + // An observed terminal rename may not have reached its parent barrier. + // Persist it before deleting any preimage or quarantine, including on retry. + try directory.syncFile("transaction.json") + try emit(.terminalSynced) + } + try validateCleanupOperations() + do { try validateContainersForDisposal() } catch { + if let index = journal.entries.indices.first { try recordConflict(index, error) } + throw error + } + if !journal.discarding { + journal.discarding = true + try persist(.discard) + try emit(.discardIntent) + } + for index in journal.containers.indices { try discardContainer(index) } + try requireScope() + try directory.removeJournal { try emit(.journalUnlinked) } + try emit(.journalRemoved) + } + + private func validateCleanupOperations() throws { + for index in journal.entries.indices { + do { + if journal.discarding { + try verifyTarget(index) + } else { + _ = try distribution(index) + } + } catch { + try recordConflict(index, error) + throw error + } + } + } + + private func verifyTarget(_ index: Int) throws { + let entry = journal.entries[index] + try requireParent(index) + // Terminal phases have a single distribution; disposal may have removed its scratch slots. + guard try TransactionLayout.expected(entry)[0].target.matches(entry.name, from: parents[index]) + else { + throw conflict( + index, + journal.phase == .committed + ? "committed destination changed" : "restored destination changed") + } + } + + private func validateContainersForDisposal() throws { + for index in journal.containers.indices { + let record = journal.containers[index] + let parent = parents[record.entry] + try requireParent(record.entry) + guard let actual = try parent.info(record.name) else { + if journal.discarding || record.identity == nil { continue } + throw conflict(record.entry, "private container disappeared before discard intent") + } + if let identity = record.identity { + guard FileObjectIdentity(actual) == identity else { + throw conflict(record.entry, "private container identity changed") + } + if let expected = record.cleanup { + let current = try FileSnapshot.read(record.name, from: parent) + let matches = + journal.discarding + ? current.map(expected.containsRemaining) == true : current == expected + guard matches else { throw conflict(record.entry, "terminal disposal evidence changed") } + } + } else if try !parent.child(record.name).names().isEmpty { + throw conflict(record.entry, "unidentified private container is not empty") + } + } + } + + private func discardContainer(_ index: Int) throws { + let record = journal.containers[index] + let parent = parents[record.entry] + try requireScope() + try requireParent(record.entry) + if let identity = record.identity { + try parent.remove(record.name, expecting: record.cleanup, identity: identity) { + try emit(.disposal(index, $0)) + } + } else { + try parent.removeEmptyDirectory(record.name) + } + try emit(.containerRemoved(index)) + } +} diff --git a/Sources/AgentsCore/UpdatePreconditions.swift b/Sources/AgentsCore/UpdatePreconditions.swift index 6c70766..b986050 100644 --- a/Sources/AgentsCore/UpdatePreconditions.swift +++ b/Sources/AgentsCore/UpdatePreconditions.swift @@ -1,167 +1,6 @@ import CPlatform import Foundation -struct FileObjectIdentity: Codable, Equatable { - let device: UInt64 - let inode: UInt64 - let kind: mode_t - - init(_ info: stat) { - device = UInt64(info.st_dev) - inode = UInt64(info.st_ino) - kind = info.st_mode & S_IFMT - } -} - -/// Content and physical ownership are separate evidence. Descendant identities let -/// terminal cleanup resume after partial deletion without adopting new entries. -struct FileSnapshot: Codable, Equatable { - let identity: FileObjectIdentity - let digest: String - let executable: Bool - let children: [String: FileSnapshot]? - - static func read(at url: URL) throws -> FileSnapshot? { - var info = stat() - if lstat(url.path, &info) != 0 { - if errno == ENOENT { return nil } - throw FileSystem.posixError(errno, at: url, otherwise: .unsafePath("cannot inspect target")) - } - let parent = try DirectoryHandle(at: url.deletingLastPathComponent().resolvingSymlinksInPath()) - return try read(url.lastPathComponent, from: parent) - } - - static func read(_ name: String, from parent: DirectoryHandle) throws -> FileSnapshot? { - guard var before = try parent.info(name) else { return nil } - let children: [String: FileSnapshot]? - let payload: Data - switch before.st_mode & S_IFMT { - case S_IFDIR: - let directory = try parent.child(name) - var opened = stat() - guard fstat(directory.descriptor, &opened) == 0, platform_same_generation(&before, &opened) - else { - throw CoreError.invalidState("directory changed before reading: \(name)") - } - var entries: [String: FileSnapshot] = [:] - for child in try directory.names() { - guard let value = try read(child, from: directory) else { - throw CoreError.invalidState("entry changed while reading: \(child)") - } - entries[child] = value - } - children = entries - // Only content enters the digest; ownership is compared independently. - payload = try StateStore.encode( - entries.mapValues { "\($0.identity.kind):\($0.executable):\($0.digest)" }) - case S_IFREG: - children = nil - payload = try parent.read(name, matching: before) - case S_IFLNK: - children = nil - payload = Data(try parent.readLink(name).utf8) - default: throw CoreError.unsafePath("unsupported transaction entry: \(name)") - } - guard var after = try parent.info(name), platform_same_generation(&before, &after) else { - throw CoreError.invalidState("entry changed while reading: \(name)") - } - return FileSnapshot( - identity: FileObjectIdentity(before), digest: FileHash.sha256Hex(data: payload), - executable: before.st_mode & S_IFMT == S_IFREG && before.st_mode & 0o111 != 0, - children: children) - } - - func validate() throws { - try StateValidation.digest("sha256:" + digest) - let kinds: [mode_t] = [S_IFDIR, S_IFREG, S_IFLNK] - guard kinds.contains(identity.kind), - (identity.kind == S_IFDIR) == (children != nil) - else { throw CoreError.invalidState("invalid transaction object evidence") } - for (name, child) in children ?? [:] { - guard !name.isEmpty, name != ".", name != "..", !name.contains("/"), - !name.contains("\0") - else { throw CoreError.invalidState("invalid transaction descendant") } - try child.validate() - } - } - - func containsRemaining(_ current: FileSnapshot) -> Bool { - guard identity == current.identity else { return false } - guard let children, let remaining = current.children else { return self == current } - return remaining.allSatisfy { name, value in children[name]?.containsRemaining(value) == true } - } - - func sameObjects(as current: FileSnapshot) -> Bool { - guard identity == current.identity else { return false } - switch (children, current.children) { - case (nil, nil): return true - case (let expected?, let actual?): - return expected.keys == actual.keys - && expected.allSatisfy { name, value in actual[name].map(value.sameObjects) == true } - default: return false - } - } - - func synchronize(_ name: String, from parent: DirectoryHandle) throws { - guard try Self.read(name, from: parent) == self else { - throw CoreError.invalidState("transaction preimage changed before synchronization: \(name)") - } - try syncContents(name, from: parent) - try parent.sync() - guard try Self.read(name, from: parent) == self else { - throw CoreError.invalidState("transaction preimage changed during synchronization: \(name)") - } - } - - private func syncContents(_ name: String, from parent: DirectoryHandle) throws { - if let children { - let directory = try parent.child(name) - for child in children.keys.sorted() { - try children[child]!.syncContents(child, from: directory) - } - try directory.sync() - } else if identity.kind == S_IFREG { - try parent.syncFile(name) - } - } - - func remove( - _ name: String, from parent: DirectoryHandle, - checkpoint: (String) throws -> Void = { _ in } - ) throws { - guard let current = try Self.read(name, from: parent) else { - try parent.sync() - return - } - guard containsRemaining(current) else { - throw CoreError.invalidState("transaction cleanup ownership changed: \(name)") - } - if let children { - let directory = try parent.child(name) - if let info = try parent.info(name), info.st_mode & S_IRWXU != S_IRWXU { - guard fchmod(directory.descriptor, (info.st_mode & 0o7777) | S_IRWXU) == 0 else { - throw CoreError.invalidState("cannot make discarded directory writable: \(name)") - } - } - for child in try directory.names() { - guard let expected = children[child] else { - throw CoreError.invalidState("unexpected transaction descendant: \(child)") - } - try expected.remove(child, from: directory, checkpoint: checkpoint) - } - guard try parent.info(name).map(FileObjectIdentity.init) == identity else { - throw CoreError.invalidState("transaction cleanup identity changed: \(name)") - } - } - guard unlinkat(parent.descriptor, name, children == nil ? 0 : AT_REMOVEDIR) == 0 else { - throw CoreError.invalidState("cannot discard verified transaction object: \(name)") - } - try checkpoint("unlinked") - try parent.sync() - try checkpoint("synced") - } -} - /// Captures existing ancestry and the final entry without following that entry's link. /// Missing ancestors may be created, but existing ancestors cannot be exchanged. package struct PathIdentity { @@ -208,21 +47,84 @@ package struct PathIdentity { /// State bytes and presence belong to the same generation as the rendered targets. package struct StatePrecondition { - private let files: [(URL, PathIdentity, FileSnapshot?)] + private let files: [(url: URL, evidence: TargetPrecondition, bytes: Data?)] package init(store: StateStore) throws { files = try [store.declarationURL, store.resolvedURL, store.watchURL].map { - ($0, try PathIdentity($0), try FileSnapshot.read(at: $0)) + let input = try TargetPrecondition.readingFile($0) + return ($0, input.evidence, input.bytes) } try validate() } - package func validate(excluding filenames: Set = []) throws { - for (url, identity, snapshot) in files where !filenames.contains(url.lastPathComponent) { - try identity.validate() - guard try FileSnapshot.read(at: url) == snapshot else { - throw CoreError.invalidState("state changed during preparation: \(url.lastPathComponent)") - } + package func evidence(for url: URL) throws -> TargetPrecondition { + try file(for: url).evidence + } + + package func bytes(for url: URL) throws -> Data? { + try file(for: url).bytes + } + + private func file(for url: URL) throws -> (url: URL, evidence: TargetPrecondition, bytes: Data?) { + guard let file = files.first(where: { $0.url.path == url.standardizedFileURL.path }) else { + throw CoreError.invalidState("state precondition does not include target") + } + return file + } + + package func validate(excludingTargets targets: Set = []) throws { + for (url, evidence, _) in files where !targets.contains(url.standardizedFileURL.path) { + try evidence.validate() + } + } +} + +/// The generation captured by a plan is also the journal's expected preimage. +package struct TargetPrecondition { + package let url: URL + let snapshot: FileSnapshot? + private let identity: PathIdentity + + var physicalURL: URL { + url.deletingLastPathComponent().resolvingSymlinksInPath().appendingPathComponent( + url.lastPathComponent + ).standardizedFileURL + } + + package init(_ url: URL) throws { + self.url = url.standardizedFileURL + identity = try PathIdentity(url) + snapshot = try FileSnapshot.read(at: url) + try identity.validate() + } + + private init(url: URL, snapshot: FileSnapshot?, identity: PathIdentity) { + self.url = url.standardizedFileURL + self.snapshot = snapshot + self.identity = identity + } + + /// Rendering and its expected preimage use the same opened-file bytes and inode. + package static func readingFile(_ url: URL) throws -> (bytes: Data?, evidence: Self) { + let identity = try PathIdentity(url) + let capture = try FileSnapshot.captureFile(at: url) + guard capture.snapshot?.isRegular != false else { + throw CoreError.unsafePath("expected regular file: \(url.path)") + } + try identity.validate() + return (capture.bytes, Self(url: url, snapshot: capture.snapshot, identity: identity)) + } + + package func sameGeneration(as other: Self) -> Bool { + url.path == other.url.path && snapshot == other.snapshot + } + + func validateIdentity() throws { try identity.validate() } + + package func validate() throws { + try validateIdentity() + guard try FileSnapshot.read(at: url) == snapshot else { + throw CoreError.invalidState("target changed during preparation: \(url.path)") } } } diff --git a/Sources/AgentsInstructions/InstructionDoctor.swift b/Sources/AgentsInstructions/InstructionDoctor.swift index 6853a49..f4efdc7 100644 --- a/Sources/AgentsInstructions/InstructionDoctor.swift +++ b/Sources/AgentsInstructions/InstructionDoctor.swift @@ -12,10 +12,10 @@ extension InstructionOperations { let store = StateStore(scope: scope, environment: environment) let other = StateStore(scope: scope == .project ? .user : .project, environment: environment) func pendingRecovery(_ store: StateStore) -> InstructionDiagnostic { - InstructionDiagnostic( - kind: .pendingRecovery, - message: - "Transaction recovery is pending; the next command that changes this scope will recover it.", + let recovery = FileTransaction.recoveryDiagnostic(store: store) + return InstructionDiagnostic( + kind: recovery.requiresOwner ? .unresolvedTransaction : .pendingRecovery, + message: recovery.message, path: store.directory) } let otherSections: [LockedSection]? = try other.withReadLock( diff --git a/Sources/AgentsInstructions/InstructionLifecycleModels.swift b/Sources/AgentsInstructions/InstructionLifecycleModels.swift index 3d97b97..dd644f6 100644 --- a/Sources/AgentsInstructions/InstructionLifecycleModels.swift +++ b/Sources/AgentsInstructions/InstructionLifecycleModels.swift @@ -112,7 +112,7 @@ public struct InstructionDiagnostic: Sendable, Equatable { case sourceResolutionFailed case invalidConfiguration case stateUnavailable - case pendingRecovery + case pendingRecovery, unresolvedTransaction } public let kind: Kind diff --git a/Sources/AgentsInstructions/InstructionOperations.swift b/Sources/AgentsInstructions/InstructionOperations.swift index 89b8c3a..327d044 100644 --- a/Sources/AgentsInstructions/InstructionOperations.swift +++ b/Sources/AgentsInstructions/InstructionOperations.swift @@ -24,7 +24,7 @@ public enum InstructionOperations { beforeApply: ((InstructionUpdateReport) throws -> Void)? ) throws -> InstructionAddOutcome { let store = StateStore(scope: options.scope, environment: options.environment) - return try operate(store, apply: apply) { previousDeclaration, previous in + return try operate(store, apply: apply) { previousDeclaration, previous, baseline in var declaration = previousDeclaration let selectionChanged = CoreError.invalidState( "automatic instruction selection changed during discovery; retry the command") @@ -101,7 +101,8 @@ public enum InstructionOperations { if !options.replace { try requireOwnership(plan.report) } try beforeApply?(plan.report) try Self.apply( - declaration: declaration, next: plan.lock, report: plan.report, sources: sources) + declaration: declaration, next: plan.lock, report: plan.report, sources: sources, + baseline: baseline, expectations: plan.expectations) return InstructionAddOutcome(sourceID: id, available: available, result: plan.report) } } @@ -144,10 +145,7 @@ public enum InstructionOperations { beforeApply: ((InstructionUpdateReport) throws -> Void)? = nil ) throws -> InstructionUpdateReport { let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: apply) { _, _ in - let baseline = try StatePrecondition(store: store) - let previousDeclaration = try store.readDeclaration() - let previous = try store.readResolved() + return try operate(store, apply: apply) { previousDeclaration, previous, baseline in var declaration = previousDeclaration if let agents { var instructions = declaration.instructions ?? InstructionsDeclaration() @@ -166,21 +164,24 @@ public enum InstructionOperations { try baseline.validate() try plan.validate() try plan.retain() - try baseline.validate() - try plan.validate() let transaction = FileTransaction(store: store) - transaction.validateBeforePublication = { - try baseline.validate() - try plan.validate() + transaction.validateBeforePublication = { [unowned transaction] in + try baseline.validate(excludingTargets: transaction.targetPaths) + try plan.validate(excludingTargets: transaction.targetPaths) } try plan.stage(transaction: transaction) - try store.stageDeclaration(declaration, in: transaction) + try store.stageDeclaration( + declaration, in: transaction, prepared: baseline) if let data = try plan.next.replacementData( - comparedTo: store.existingData(store.resolvedURL)) + comparedTo: baseline.bytes(for: store.resolvedURL)) { - try transaction.replace(store.resolvedURL, content: nil, data: data) + try transaction.replace( + store.resolvedURL, content: nil, data: data, + expecting: baseline.evidence(for: store.resolvedURL)) } - try SourceCache(store: store).prune(referencedBy: plan.next, transaction: transaction) + try SourceCache(store: store).prune( + referencedBy: plan.next, watch: store.readWatch(prepared: baseline), + transaction: transaction) try transaction.commit() } return plan.report @@ -199,7 +200,8 @@ public enum InstructionOperations { declaration: declaration, previousDeclaration: previousDeclaration, previous: previous, prepared: prepared, store: store) return try InstructionUpdatePlan( - next: plan.lock, report: plan.report, sources: sources, replace: replace) + next: plan.lock, report: plan.report, sources: sources, replace: replace, + expectedTargets: plan.expectations) } /// Restores only recorded pins and targets, without changing either state file. @@ -207,7 +209,7 @@ public enum InstructionOperations { scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> InstructionUpdateReport { let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: true) { declaration, lock in + return try operate(store, apply: true) { declaration, lock, baseline in let sources = InstructionSources(store: store) let sections = try sources.restore(lock.instructions.sections, sources: lock.sources) for prompt in lock.instructions.chatgpt.values { @@ -223,7 +225,8 @@ public enum InstructionOperations { hasChanges: targets.changes.contains(where: \.changed)) try requireOwnership(report) try apply( - declaration: declaration, next: lock, report: report, sources: sources, writeState: false) + declaration: declaration, next: lock, report: report, sources: sources, + baseline: baseline, expectations: targets.expectations, writeState: false) return report } } @@ -237,7 +240,7 @@ public enum InstructionOperations { beforeApply: ((InstructionUpdateReport) throws -> Void)? = nil ) throws -> InstructionUpdateReport { let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: true) { previousDeclaration, previous in + return try operate(store, apply: true) { previousDeclaration, previous, baseline in var declaration = previousDeclaration var instructions = declaration.instructions ?? InstructionsDeclaration() let references = Set( @@ -273,7 +276,9 @@ public enum InstructionOperations { try plan.lock.validate() try requireOwnership(plan.report) try beforeApply?(plan.report) - try apply(declaration: declaration, next: plan.lock, report: plan.report, sources: sources) + try apply( + declaration: declaration, next: plan.lock, report: plan.report, sources: sources, + baseline: baseline, expectations: plan.expectations) return plan.report } } @@ -372,7 +377,9 @@ public enum InstructionOperations { private static func plan( declaration: Declaration, previousDeclaration: Declaration, previous: ResolvedState, prepared: (lock: ResolvedState, sections: [InstructionSection]), store: StateStore - ) throws -> (lock: ResolvedState, report: InstructionUpdateReport) { + ) throws -> ( + lock: ResolvedState, report: InstructionUpdateReport, expectations: [String: TargetPrecondition] + ) { var next = prepared.lock let targets = try InstructionTargets(store: store).plan( sections: prepared.sections, @@ -405,7 +412,8 @@ public enum InstructionOperations { next, InstructionUpdateReport( sections: changes, targets: targets.changes, changedPrompts: prompts, - lockMissing: lockMissing, hasChanges: hasChanges) + lockMissing: lockMissing, hasChanges: hasChanges), + targets.expectations ) } @@ -417,38 +425,34 @@ public enum InstructionOperations { private static func apply( declaration: Declaration, next: ResolvedState, report: InstructionUpdateReport, - sources: InstructionSources, writeState: Bool = true + sources: InstructionSources, baseline: StatePrecondition, + expectations: [String: TargetPrecondition], writeState: Bool = true ) throws { let store = sources.store try declaration.validate(environment: store.environment) try next.validate() - // User callbacks can inspect or cancel, but cannot silently invalidate the prepared differences. - for change in report.targets { - guard try InstructionTargets.read(change.url) == change.before else { - throw CoreError.invalidState( - "instruction target changed during preparation: \(change.target)") - } - } - try InstructionTargets.validateSourceDirectories(report.targets, sources: next.sources) + let plan = try InstructionUpdatePlan( + next: next, report: report, sources: sources, replace: true, expectedTargets: expectations) + try baseline.validate() + try plan.validate() do { - try sources.retain(next) + try plan.retain() let transaction = FileTransaction(store: store) - for change in report.targets { - guard try InstructionTargets.read(change.url) == change.before else { - throw CoreError.invalidState( - "instruction target changed during preparation: \(change.target)") - } - if change.changed { try transaction.replace(change.url, content: nil, data: change.after) } + transaction.validateBeforePublication = { [unowned transaction] in + try baseline.validate(excludingTargets: transaction.targetPaths) + try plan.validate(excludingTargets: transaction.targetPaths) } + try plan.stage(transaction: transaction) if writeState { - try store.stageDeclaration(declaration, in: transaction) - if let data = try next.replacementData( - comparedTo: store.existingData(store.resolvedURL)) - { - try transaction.replace(store.resolvedURL, content: nil, data: data) + try store.stageDeclaration(declaration, in: transaction, prepared: baseline) + if let data = try next.replacementData(comparedTo: baseline.bytes(for: store.resolvedURL)) { + try transaction.replace( + store.resolvedURL, content: nil, data: data, + expecting: baseline.evidence(for: store.resolvedURL)) } } - try sources.cache.prune(referencedBy: next, transaction: transaction) + try sources.cache.prune( + referencedBy: next, watch: store.readWatch(prepared: baseline), transaction: transaction) try transaction.commit() } catch { if let recovered = try? store.readResolved() { @@ -458,6 +462,13 @@ public enum InstructionOperations { } } + private static func operate(_ store: StateStore, apply: Bool, _ body: () throws -> T) throws + -> T + { + if apply { return try store.withLock(body) } + return try store.withReadLock(body) + } + static func operate( _ store: StateStore, apply: Bool, _ body: (Declaration, ResolvedState) throws -> T ) throws -> T { @@ -467,6 +478,17 @@ public enum InstructionOperations { return try store.withReadLock { try body(store.readDeclaration(), store.readResolved()) } } + private static func operate( + _ store: StateStore, apply: Bool, + _ body: (Declaration, ResolvedState, StatePrecondition) throws -> T + ) throws -> T { + try operate(store, apply: apply) { + let baseline = try StatePrecondition(store: store) + return try body( + store.readDeclaration(prepared: baseline), store.readResolved(prepared: baseline), baseline) + } + } + private static func sourceDeclaration(_ options: InstructionAddOptions, declaration: Declaration) throws -> SourceDeclaration { diff --git a/Sources/AgentsInstructions/InstructionTargets.swift b/Sources/AgentsInstructions/InstructionTargets.swift index 57c2aff..a277855 100644 --- a/Sources/AgentsInstructions/InstructionTargets.swift +++ b/Sources/AgentsInstructions/InstructionTargets.swift @@ -10,7 +10,11 @@ struct InstructionTargets { func plan( sections: [InstructionSection], agents: [AgentID], previous: LockedInstructions, restoring: Bool = false - ) throws -> (targets: [String: LockedTarget], changes: [InstructionTargetChange]) { + ) throws -> ( + targets: [String: LockedTarget], changes: [InstructionTargetChange], + expectations: [String: TargetPrecondition] + ) { + var expectations: [String: TargetPrecondition] = [:] var targets: [String: LockedTarget] = [:] var rendered: [String: String] = [:] if !sections.isEmpty { @@ -43,16 +47,26 @@ struct InstructionTargets { } } if !restoring, store.scope == .project, recipients.contains(.claudeCode), - targets["AGENTS.md"] != nil, let path = try forwardingPath() + targets["AGENTS.md"] != nil { - 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") + for path in ClaudeInstructionPath.allCases { + let file = store.environment.projectDirectory.appendingPathComponent(path.rawValue) + expectations[file.path] = try TargetPrecondition(file) + let physical = file.resolvingSymlinksInPath() + if physical.path != file.path { + expectations[physical.path] = try TargetPrecondition(physical) + } + } + if 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) } - targets[key] = LockedTarget( - agents: [.claudeCode], import: String(path.importLine.dropFirst()), blockHash: "", - created: false) } } if restoring { @@ -65,7 +79,16 @@ struct InstructionTargets { 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 input = try TargetPrecondition.readingFile(file) + let before = input.bytes + if let earlier = expectations[file.path] { + guard earlier.sameGeneration(as: input.evidence) else { + throw CoreError.invalidState( + "instruction target changed during preparation: \(file.path)") + } + } else { + expectations[file.path] = input.evidence + } let old = previous.targets[key] var after: Data? var foreign = false @@ -116,7 +139,8 @@ struct InstructionTargets { afterAgents: targets[key]?.agents ?? [], drift: drift, foreign: foreign)) } guard problems.isEmpty else { throw InstructionError.invalidLinks(problems) } - return (targets, changes) + for evidence in expectations.values { try evidence.validate() } + return (targets, changes, expectations) } /// The file an agent reads for sections placed in `directory`, or nil when the agent has no file. diff --git a/Sources/AgentsInstructions/InstructionUpdatePlan.swift b/Sources/AgentsInstructions/InstructionUpdatePlan.swift index 327e62b..457ff77 100644 --- a/Sources/AgentsInstructions/InstructionUpdatePlan.swift +++ b/Sources/AgentsInstructions/InstructionUpdatePlan.swift @@ -6,13 +6,12 @@ package final class InstructionUpdatePlan { package let next: ResolvedState package let report: InstructionUpdateReport private let sources: InstructionSources - private let identities: [PathIdentity] - private let forwardingInputs: [(URL, Data?)] + private let identities: [TargetPrecondition] private let replace: Bool init( next: ResolvedState, report: InstructionUpdateReport, sources: InstructionSources, - replace: Bool + replace: Bool, expectedTargets: [String: TargetPrecondition] ) throws { self.next = next self.report = report @@ -34,30 +33,19 @@ package final class InstructionUpdatePlan { store.environment.projectDirectory.appendingPathComponent($0.rawValue) } paths.append(contentsOf: candidates) - forwardingInputs = try candidates.map { url in - let resolved = url.resolvingSymlinksInPath() - paths.append(resolved) - return (resolved, try InstructionTargets.read(resolved)) - } - } else { - forwardingInputs = [] + paths.append(contentsOf: candidates.map { $0.resolvingSymlinksInPath() }) + } + var evidence = expectedTargets + for path in Set(paths.map { $0.standardizedFileURL.path }) where evidence[path] == nil { + evidence[path] = try TargetPrecondition(URL(fileURLWithPath: path)) } - identities = try paths.map { try PathIdentity($0) } + identities = evidence.keys.sorted().map { evidence[$0]! } } - package func validate() throws { + package func validate(excludingTargets targets: Set = []) 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 { - throw CoreError.invalidState("Claude forwarding changed during preparation: \(url.path)") - } - } - for change in report.targets { - guard try InstructionTargets.read(change.url) == change.before else { - throw CoreError.invalidState( - "instruction target changed during preparation: \(change.target)") - } + for identity in identities where !targets.contains(identity.url.path) { + try identity.validate() } try InstructionTargets.validateSourceDirectories(report.targets, sources: next.sources) } @@ -66,7 +54,14 @@ package final class InstructionUpdatePlan { package func stage(transaction: FileTransaction) throws { for change in report.targets.sorted(by: { $0.url.path < $1.url.path }) where change.changed { - try transaction.replace(change.url, content: nil, data: change.after) + guard + let evidence = identities.first(where: { + $0.url.path == change.url.standardizedFileURL.path + }) + else { + throw CoreError.invalidState("instruction target has no prepared preimage") + } + try transaction.replace(change.url, content: nil, data: change.after, expecting: evidence) } } } diff --git a/Sources/AgentsSkills/SkillLifecycle.swift b/Sources/AgentsSkills/SkillLifecycle.swift index e4fe81d..fe0a166 100644 --- a/Sources/AgentsSkills/SkillLifecycle.swift +++ b/Sources/AgentsSkills/SkillLifecycle.swift @@ -214,25 +214,36 @@ final class SkillLifecycle { func apply( declaration: Declaration, previous: ResolvedState, next: ResolvedState, - prepared: [String: PreparedSkill], names: Set, writeState: Bool = true + prepared: [String: PreparedSkill], names: Set, baseline: StatePrecondition, + writeState: Bool = true ) throws -> [InstallResult] { try declaration.validate(environment: store.environment) try next.validate() - try validateOwnership(previous: previous, next: next, names: names) - let retained = try retain(prepared: prepared, next: next) + let plan = try SkillUpdatePlan( + lifecycle: self, previous: previous, next: next, prepared: prepared, names: names, results: [] + ) + try plan.validateOwnership() + try baseline.validate() + try plan.validate() + let retained = try plan.retain() let transaction = FileTransaction(store: store) - try stage( - previous: previous, next: next, prepared: prepared, retained: retained, - names: names, transaction: transaction) + transaction.validateBeforePublication = { [unowned transaction] in + try baseline.validate(excludingTargets: transaction.targetPaths) + try plan.validate(excludingTargets: transaction.targetPaths) + } + try plan.stage(retained: retained, transaction: transaction) if writeState { - try store.stageDeclaration(declaration, in: transaction) + try store.stageDeclaration(declaration, in: transaction, prepared: baseline) if let data = try next.replacementData( - comparedTo: store.existingData(store.resolvedURL)) + comparedTo: baseline.bytes(for: store.resolvedURL)) { - try transaction.replace(store.resolvedURL, content: nil, data: data) + try transaction.replace( + store.resolvedURL, content: nil, data: data, + expecting: baseline.evidence(for: store.resolvedURL)) } } - try cache.prune(referencedBy: next, transaction: transaction) + try cache.prune( + referencedBy: next, watch: store.readWatch(prepared: baseline), transaction: transaction) try transaction.commit() return receipts(next: next, names: names) } @@ -298,7 +309,8 @@ final class SkillLifecycle { func stage( previous: ResolvedState, next: ResolvedState, prepared: [String: PreparedSkill], - retained: [String: URL], names: Set, transaction: FileTransaction + retained: [String: URL], names: Set, transaction: FileTransaction, + expectations: [String: TargetPrecondition] ) throws { let oldTargets = try targets(previous) let newTargets = try targets(next) @@ -306,6 +318,9 @@ final class SkillLifecycle { if let target = newTargets[path], names.contains(target.name), let content = retained[target.name], let item = prepared[target.name] { + guard let evidence = expectations[path] else { + throw CoreError.invalidState("skill target has no prepared preimage") + } guard !PathSafety.isContained( content.resolvingSymlinksInPath(), in: URL(fileURLWithPath: path).standardizedFileURL) @@ -313,10 +328,14 @@ final class SkillLifecycle { try transaction.replace( URL(fileURLWithPath: path), content: content, link: target.mode != .copy, expectedHash: item.lock.hash, - executableFlags: item.executableFlags) + executableFlags: item.executableFlags, expecting: evidence) } else if let target = oldTargets[path], names.contains(target.name), newTargets[path] == nil { - try transaction.replace(URL(fileURLWithPath: path), content: nil) + guard let evidence = expectations[path] else { + throw CoreError.invalidState("skill target has no prepared preimage") + } + try transaction.replace( + URL(fileURLWithPath: path), content: nil, expecting: evidence) } } } diff --git a/Sources/AgentsSkills/SkillOperations.swift b/Sources/AgentsSkills/SkillOperations.swift index d5c4d5c..2cf5d36 100644 --- a/Sources/AgentsSkills/SkillOperations.swift +++ b/Sources/AgentsSkills/SkillOperations.swift @@ -28,7 +28,7 @@ public enum SkillOperations { automaticSelection: (sourceID: String, name: String)? = nil ) throws -> AddOutcome { let store = StateStore(scope: options.scope, environment: options.environment) - return try operate(store, apply: apply) { declaration, lock in + return try operate(store, apply: apply) { declaration, lock, baseline in let lifecycle = try SkillLifecycle(store: store, provider: provider) var declaration = declaration let selectionChanged = CoreError.invalidState( @@ -119,7 +119,8 @@ public enum SkillOperations { } try next.validate() let installed = try lifecycle.apply( - declaration: declaration, previous: lock, next: next, prepared: prepared, names: Set(names)) + declaration: declaration, previous: lock, next: next, prepared: prepared, names: Set(names), + baseline: baseline) return AddOutcome( source: source, sourceID: id, availableSkills: selected, installed: installed) } @@ -141,10 +142,7 @@ public enum SkillOperations { beforeApply: (([UpdateResult]) throws -> Void)? = nil, provider: WellKnownProvider ) throws -> [UpdateResult] { let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: apply) { _, _ in - let baseline = try StatePrecondition(store: store) - let declaration = try store.readDeclaration() - let previous = try store.readResolved() + return try operate(store, apply: apply) { declaration, previous, baseline in let resolutions = try SourceResolutionSession(store: store) let plan = try prepareUpdate( store: store, declaration: declaration, previous: previous, resolutions: resolutions, @@ -158,21 +156,24 @@ public enum SkillOperations { try baseline.validate() try plan.validate() let retained = try plan.retain() - try baseline.validate() - try plan.validate() let transaction = FileTransaction(store: store) - transaction.validateBeforePublication = { - try baseline.validate() - try plan.validate() + transaction.validateBeforePublication = { [unowned transaction] in + try baseline.validate(excludingTargets: transaction.targetPaths) + try plan.validate(excludingTargets: transaction.targetPaths) } try plan.stage(retained: retained, transaction: transaction) - try store.stageDeclaration(declaration, in: transaction) + try store.stageDeclaration( + declaration, in: transaction, prepared: baseline) if let data = try plan.next.replacementData( - comparedTo: store.existingData(store.resolvedURL)) + comparedTo: baseline.bytes(for: store.resolvedURL)) { - try transaction.replace(store.resolvedURL, content: nil, data: data) + try transaction.replace( + store.resolvedURL, content: nil, data: data, + expecting: baseline.evidence(for: store.resolvedURL)) } - try SourceCache(store: store).prune(referencedBy: plan.next, transaction: transaction) + try SourceCache(store: store).prune( + referencedBy: plan.next, watch: store.readWatch(prepared: baseline), + transaction: transaction) try transaction.commit() let installed = plan.receipts for index in results.indices { @@ -306,7 +307,7 @@ public enum SkillOperations { scope: InstallScope, environment: RuntimeEnvironment, provider: WellKnownProvider ) throws -> ResolvedInstallReport { let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: true) { declaration, lock in + return try operate(store, apply: true) { declaration, lock, baseline in let lifecycle = try SkillLifecycle(store: store, provider: provider) var prepared: [String: PreparedSkill] = [:] for (name, skill) in lock.skills { @@ -315,7 +316,7 @@ public enum SkillOperations { return ResolvedInstallReport( installed: try lifecycle.apply( declaration: declaration, previous: lock, next: lock, prepared: prepared, - names: Set(lock.skills.keys), writeState: false)) + names: Set(lock.skills.keys), baseline: baseline, writeState: false)) } } @@ -325,7 +326,7 @@ public enum SkillOperations { environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> [String] { let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: true) { declaration, lock in + return try operate(store, apply: true) { declaration, lock, baseline in var declaration = declaration var next = lock let names = Set(skillNames.map(PathSafety.sanitizeName)) @@ -363,7 +364,8 @@ public enum SkillOperations { } let lifecycle = try SkillLifecycle(store: store, provider: WellKnownProvider()) _ = try lifecycle.apply( - declaration: declaration, previous: lock, next: next, prepared: [:], names: names) + declaration: declaration, previous: lock, next: next, prepared: [:], names: names, + baseline: baseline) return names.sorted() } } @@ -471,11 +473,12 @@ public enum SkillOperations { let store = StateStore(scope: scope, environment: environment) return try store.withReadLock( onPendingRecovery: { - DoctorReport(checks: [ + let recovery = FileTransaction.recoveryDiagnostic(store: store) + return DoctorReport(checks: [ DoctorCheck( - id: "pending-recovery", status: .warning, - message: - "Transaction recovery is pending; the next command that changes this scope will recover it.", + id: recovery.requiresOwner ? "unresolved-transaction" : "pending-recovery", + status: .warning, + message: recovery.message, path: store.directory.path) ]) }, @@ -560,6 +563,13 @@ public enum SkillOperations { } } + private static func operate(_ store: StateStore, apply: Bool, _ body: () throws -> T) throws + -> T + { + if apply { return try store.withLock(body) } + return try store.withReadLock(body) + } + private static func operate( _ store: StateStore, apply: Bool, _ body: (Declaration, ResolvedState) throws -> T ) throws -> T { @@ -569,6 +579,17 @@ public enum SkillOperations { return try store.withReadLock { try body(store.readDeclaration(), store.readResolved()) } } + private static func operate( + _ store: StateStore, apply: Bool, + _ body: (Declaration, ResolvedState, StatePrecondition) throws -> T + ) throws -> T { + try operate(store, apply: apply) { + let baseline = try StatePrecondition(store: store) + return try body( + store.readDeclaration(prepared: baseline), store.readResolved(prepared: baseline), baseline) + } + } + private static func sourceDeclaration(_ options: AddOptions, declaration: Declaration) throws -> SourceDeclaration { diff --git a/Sources/AgentsSkills/SkillUpdatePlan.swift b/Sources/AgentsSkills/SkillUpdatePlan.swift index a6f8ce6..2b11c28 100644 --- a/Sources/AgentsSkills/SkillUpdatePlan.swift +++ b/Sources/AgentsSkills/SkillUpdatePlan.swift @@ -10,8 +10,9 @@ package final class SkillUpdatePlan { private let previous: ResolvedState private let prepared: [String: PreparedSkill] private let names: Set - private let before: [(URL, PathIdentity, Bool, [String: SkillFileEntry])] - private let recipientPaths: [PathIdentity] + private let before: [TargetPrecondition] + private let linkedInputs: [TargetPrecondition] + private let recipientPaths: [(URL, PathIdentity)] init( lifecycle: SkillLifecycle, previous: ResolvedState, next: ResolvedState, @@ -28,9 +29,11 @@ package final class SkillUpdatePlan { targetPaths = Set(oldTargets.keys).union(newTargets.keys).sorted().map { URL(fileURLWithPath: $0) } - before = try targetPaths.map { url in - let follow = oldTargets[url.path]?.mode != .edit - return (url, try PathIdentity(url), follow, try lifecycle.entries(url, followRoot: follow)) + before = try targetPaths.map { try TargetPrecondition($0) } + linkedInputs = try targetPaths.compactMap { url in + guard oldTargets[url.path]?.mode != .edit else { return nil } + let physical = url.resolvingSymlinksInPath() + return physical == url ? nil : try TargetPrecondition(physical) } recipientPaths = try names.sorted().flatMap { name in Set((previous.skills[name]?.installs ?? [:]).keys) @@ -39,7 +42,7 @@ package final class SkillUpdatePlan { SkillLifecycle.target(name: name, agent: $0, store: lifecycle.store) } } - }.map { try PathIdentity($0) } + }.map { (SkillLifecycle.physicalTarget($0), try PathIdentity($0)) } } package func validateOwnership() throws { @@ -53,13 +56,16 @@ package final class SkillUpdatePlan { } } - package func validate() throws { - for identity in recipientPaths { try identity.validate() } - for (url, identity, follow, entries) in before { + package func validate(excludingTargets targets: Set = []) throws { + for (url, identity) in recipientPaths where !targets.contains(url.path) { try identity.validate() - guard try lifecycle.entries(url, followRoot: follow) == entries else { - throw CoreError.invalidState("skill target changed during preparation: \(url.path)") - } + } + for evidence in before where !targets.contains(evidence.url.path) { try evidence.validate() } + for evidence in linkedInputs + where !targets.contains(where: { + PathSafety.isContained(evidence.url, in: URL(fileURLWithPath: $0)) + }) { + try evidence.validate() } for (name, item) in prepared { try lifecycle.validate(item, name: name) } } @@ -71,7 +77,8 @@ package final class SkillUpdatePlan { package func stage(retained: [String: URL], transaction: FileTransaction) throws { try lifecycle.stage( previous: previous, next: next, prepared: prepared, retained: retained, - names: names, transaction: transaction) + names: names, transaction: transaction, + expectations: Dictionary(uniqueKeysWithValues: zip(targetPaths.map(\.path), before))) } package var receipts: [InstallResult] { lifecycle.receipts(next: next, names: names) } diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index a9bc0f0..5c5bcc9 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -21,9 +21,9 @@ final class UpdatePlan { self.store = store self.checkpoint = checkpoint baseline = try StatePrecondition(store: store) - declaration = try store.readDeclaration() - previous = try store.readResolved() - watch = try store.readWatch() + declaration = try store.readDeclaration(prepared: baseline) + previous = try store.readResolved(prepared: baseline) + watch = try store.readWatch(prepared: baseline) resolutions = try SourceResolutionSession(store: store) skills = try SkillOperations.prepareUpdate( store: store, declaration: declaration, previous: previous, resolutions: resolutions) @@ -40,7 +40,7 @@ final class UpdatePlan { try declaration.validate(environment: store.environment) try next.validate() self.next = next - let lockMissing = try store.existingData(store.resolvedURL) == nil + let lockMissing = try baseline.bytes(for: store.resolvedURL) == nil report = CombinedUpdateReport( scope: store.scope, skills: skills.results, instructions: instructions.report, lockMissing: lockMissing, @@ -87,16 +87,22 @@ final class UpdatePlan { let retained = try skills.retain() try instructions.retain() try checkpoint("apply.retained") - try validate() let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) - transaction.validateBeforePublication = { try self.validate() } + transaction.validateBeforePublication = { [unowned transaction] in + try self.baseline.validate(excludingTargets: transaction.targetPaths) + try self.skills.validate(excludingTargets: transaction.targetPaths) + try self.instructions.validate(excludingTargets: transaction.targetPaths) + } try skills.stage(retained: retained, transaction: transaction) try instructions.stage(transaction: transaction) - try store.stageDeclaration(declaration, in: transaction) + try store.stageDeclaration( + declaration, in: transaction, prepared: baseline) if let resolvedBytes = try next.replacementData( - comparedTo: store.existingData(store.resolvedURL)) + comparedTo: baseline.bytes(for: store.resolvedURL)) { - try transaction.replace(store.resolvedURL, content: nil, data: resolvedBytes) + try transaction.replace( + store.resolvedURL, content: nil, data: resolvedBytes, + expecting: baseline.evidence(for: store.resolvedURL)) } try SourceCache(store: store).prune( referencedBy: next, watch: watch, transaction: transaction) diff --git a/Sources/CPlatform/CPlatform.c b/Sources/CPlatform/CPlatform.c index ab264d3..c221734 100644 --- a/Sources/CPlatform/CPlatform.c +++ b/Sources/CPlatform/CPlatform.c @@ -32,20 +32,20 @@ bool platform_system_alias(const char *name) { #endif } -int platform_exchange(int directory, const char *name, const char *destination) { +int platform_exchange(int sourceDirectory, const char *name, int destinationDirectory, const char *destination) { #if defined(__APPLE__) - return renameatx_np(directory, name, directory, destination, RENAME_SWAP); + return renameatx_np(sourceDirectory, name, destinationDirectory, destination, RENAME_SWAP); #else // Call the kernel primitive without relying on the libc Swift overlay. - return (int)syscall(SYS_renameat2, directory, name, directory, destination, 2 /* RENAME_EXCHANGE */); + return (int)syscall(SYS_renameat2, sourceDirectory, name, destinationDirectory, destination, 2 /* RENAME_EXCHANGE */); #endif } -int platform_rename_exclusive(int directory, const char *name, const char *destination) { +int platform_rename_exclusive(int sourceDirectory, const char *name, int destinationDirectory, const char *destination) { #if defined(__APPLE__) - return renameatx_np(directory, name, directory, destination, RENAME_EXCL); + return renameatx_np(sourceDirectory, name, destinationDirectory, destination, RENAME_EXCL); #else - return (int)syscall(SYS_renameat2, directory, name, directory, destination, 1 /* RENAME_NOREPLACE */); + return (int)syscall(SYS_renameat2, sourceDirectory, name, destinationDirectory, destination, 1 /* RENAME_NOREPLACE */); #endif } diff --git a/Sources/CPlatform/include/CPlatform.h b/Sources/CPlatform/include/CPlatform.h index 203ded2..436a04c 100644 --- a/Sources/CPlatform/include/CPlatform.h +++ b/Sources/CPlatform/include/CPlatform.h @@ -25,8 +25,8 @@ int platform_flock(int descriptor, int operation); int platform_access(int directory, const char *name, int mode); const char *platform_entry_name(const struct dirent *entry); bool platform_system_alias(const char *name); -int platform_exchange(int directory, const char *name, const char *destination); -int platform_rename_exclusive(int directory, const char *name, const char *destination); +int platform_exchange(int sourceDirectory, const char *name, int destinationDirectory, const char *destination); +int platform_rename_exclusive(int sourceDirectory, const char *name, int destinationDirectory, const char *destination); bool platform_same_generation(const struct stat *first, const struct stat *second); int platform_sync(int descriptor); int platform_copy_data(int source, int destination); diff --git a/Tests/AgentsCoreTests/CachePublicationTests.swift b/Tests/AgentsCoreTests/CachePublicationTests.swift index 7ae0ac1..9b75ecf 100644 --- a/Tests/AgentsCoreTests/CachePublicationTests.swift +++ b/Tests/AgentsCoreTests/CachePublicationTests.swift @@ -1,5 +1,6 @@ import CPlatform import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -9,14 +10,15 @@ struct CachePublicationTests { @Test( arguments: ["cache-content", "cache-git"], [ - "stage.0.copy.directory", "stage.0.copy.entry", "stage.0.verified", "replace.0.renamed", - "journal.committed.renamed", + "stage.0.copy.entry.0.staged.directoryCreated", + "stage.0.copy.entry.0.staged/SKILL.md.entryCopied", "entry.0.ready", "publish.0.created", + "journal.committed.terminal.renamed", ]) func interruptedTreePublicationRecoversAndRetries(_ kind: String, _ point: String) throws { let fixture = try CacheFixture(git: kind == "cache-git") try interrupt(fixture, kind: kind, point: point) - if point.hasPrefix("stage.") { - #expect(!FileManager.default.fileExists(atPath: fixture.destination.path)) + if point.hasPrefix("stage.") || point.hasPrefix("entry.") { + #expect(try FileSnapshot.read(at: fixture.destination) == nil) } else { #expect(try FileHash.folderHash(fixture.destination) == fixture.hash) } @@ -37,7 +39,8 @@ struct CachePublicationTests { } @Test(arguments: [ - "stage.0.written", "stage.0.verified", "replace.0.renamed", "journal.committed.renamed", + "stage.0.constructed", "entry.0.ready", "publish.0.created", + "journal.committed.terminal.renamed", ]) func interruptedArtifactBytesAreNeverPublishedPartially(_ point: String) throws { let fixture = try CacheFixture() @@ -54,11 +57,11 @@ struct CachePublicationTests { #expect(try Data(contentsOf: fixture.store.resolvedURL) == fixture.lockBytes) } - @Test(arguments: ["prepare.0.directory", "prepare.0.ready"]) + @Test(arguments: ["stage.0.workCreated", "stage.0.workPrepared"]) func interruptedExtractionCleansJournalOwnedScratch(_ point: String) throws { let fixture = try CacheFixture(git: true) try interrupt(fixture, kind: "cache-git", point: point) - #expect(!FileManager.default.fileExists(atPath: fixture.destination.path)) + #expect(try FileSnapshot.read(at: fixture.destination) == nil) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { try fixture.store.loadResolved() } @@ -73,23 +76,27 @@ struct CachePublicationTests { @Test func verifiesPrivateCopyBeforePublication() throws { let fixture = try CacheFixture() + let beforeState = try FileSnapshot.read(at: fixture.store.resolvedURL) let cache = SourceCache(store: fixture.store) { step in - if step == "stage.0.copy.entry" { + if step == "stage.0.constructed" { let parent = fixture.destination.deletingLastPathComponent() for name in try FileManager.default.contentsOfDirectory(atPath: parent.path) - where name.hasSuffix(".new") { - try Data("tampered".utf8).write(to: parent.appendingPathComponent(name + "/injected")) + where name.hasPrefix(".agents-") { + try Data("tampered".utf8).write( + to: parent.appendingPathComponent(name).appendingPathComponent( + "entry.0.staged/injected")) } } } - #expect(throws: CoreError.self) { + #expect(throws: CoreError.invalidState("staged content digest mismatch")) { try fixture.store.withLock { try cache.materializeArtifact( fixture.root.appendingPathComponent("new"), digest: fixture.digest, hash: "sha256:" + fixture.hash) } } - #expect(!FileManager.default.fileExists(atPath: fixture.destination.path)) + #expect(try FileSnapshot.read(at: fixture.destination) == nil) + #expect(try FileSnapshot.read(at: fixture.store.resolvedURL) == beforeState) #expect( try FileManager.default.contentsOfDirectory( atPath: fixture.destination.deletingLastPathComponent().path @@ -99,28 +106,58 @@ struct CachePublicationTests { @Test func verifiesPrivateBytesBeforePublication() throws { let fixture = try CacheFixture() + let beforeState = try FileSnapshot.read(at: fixture.store.resolvedURL) let cache = SourceCache(store: fixture.store) { step in - if step == "stage.0.written" { + if step == "stage.0.constructed" { let parent = fixture.store.cacheDirectory.appendingPathComponent("artifacts") for name in try FileManager.default.contentsOfDirectory(atPath: parent.path) - where name.hasSuffix(".new") { - try Data("tampered".utf8).write(to: parent.appendingPathComponent(name)) + where name.hasPrefix(".agents-") { + try Data("tampered".utf8).write( + to: parent.appendingPathComponent(name).appendingPathComponent("entry.0.staged")) } } } - #expect(throws: CoreError.self) { + #expect(throws: CoreError.invalidState("staged content bytes mismatch")) { try fixture.store.withLock { try cache.storeArtifact( Data(contentsOf: fixture.root.appendingPathComponent("payload")), digest: fixture.digest) } } let final = try cache.artifactURL(digest: fixture.digest) - #expect(!FileManager.default.fileExists(atPath: final.path)) + #expect(try FileSnapshot.read(at: final) == nil) + #expect(try FileSnapshot.read(at: fixture.store.resolvedURL) == beforeState) #expect( try FileManager.default.contentsOfDirectory(atPath: final.deletingLastPathComponent().path) .isEmpty) } + @Test(arguments: [false, true]) + func concurrentCacheCreatorKeepsItsBytesAndInode(_ equalBytes: Bool) throws { + let fixture = try CacheFixture() + let beforeState = try FileSnapshot.read(at: fixture.store.resolvedURL) + let payload = try Data(contentsOf: fixture.root.appendingPathComponent("payload")) + let final = try SourceCache(store: fixture.store).artifactURL(digest: fixture.digest) + var external: FileSnapshot? + let cache = SourceCache(store: fixture.store) { step in + if step == "publish.0.validated" { + try (equalBytes ? payload : Data("external cache bytes".utf8)).write(to: final) + external = try FileSnapshot.read(at: final) + } + } + #expect { + try fixture.store.withLock { try cache.storeArtifact(payload, digest: fixture.digest) } + } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("transaction destination already exists") + } + #expect(external != nil) + #expect(try FileSnapshot.read(at: final) == external) + #expect(try FileSnapshot.read(at: fixture.store.resolvedURL) == beforeState) + #expect( + try FileManager.default.contentsOfDirectory(atPath: final.deletingLastPathComponent().path) + == [final.lastPathComponent]) + } + private func interrupt(_ fixture: CacheFixture, kind: String, point: String) throws { let child = try stateTestProcess(root: fixture.root, arguments: [kind, point]) defer { @@ -130,11 +167,7 @@ struct CachePublicationTests { } } let marker = fixture.root.appendingPathComponent("ready") - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: marker.path), child.isRunning, Date() < deadline { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: marker.path)) + try ProcessWait.marker(marker, child: child, root: fixture.root) kill(child.processIdentifier, SIGKILL) child.waitUntilExit() } diff --git a/Tests/AgentsCoreTests/CoreTestSupport.swift b/Tests/AgentsCoreTests/CoreTestSupport.swift index 001d7ad..9ff8c59 100644 --- a/Tests/AgentsCoreTests/CoreTestSupport.swift +++ b/Tests/AgentsCoreTests/CoreTestSupport.swift @@ -19,6 +19,19 @@ func removeTemporaryDirectory(_ directory: URL) { } } +func makeDirectoriesWritable(_ root: URL) { + guard let entries = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil) + else { + return + } + for case let entry as URL in entries { + var info = stat() + if lstat(entry.path, &info) == 0, info.st_mode & S_IFMT == S_IFDIR { + _ = chmod(entry.path, (info.st_mode & 0o7777) | S_IRWXU) + } + } +} + func initGitRepo(_ repo: URL) throws { try ProcessRunner.run( "/usr/bin/env", arguments: ["git", "init", "--initial-branch=master", repo.path]) diff --git a/Tests/AgentsCoreTests/DirectoryHandleTests.swift b/Tests/AgentsCoreTests/DirectoryHandleTests.swift index 52538c2..c0ca90e 100644 --- a/Tests/AgentsCoreTests/DirectoryHandleTests.swift +++ b/Tests/AgentsCoreTests/DirectoryHandleTests.swift @@ -6,6 +6,19 @@ import Testing @Suite("Portable filesystem contracts") struct DirectoryHandleTests { + @Test func linkEvidenceHashesRawDestinationBytes() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let link = root.appendingPathComponent("link") + let bytes = [CChar(bitPattern: 0xff), 0] + try #require(bytes.withUnsafeBufferPointer { symlink($0.baseAddress!, link.path) } == 0) + let directory = try DirectoryHandle(at: root) + #expect(try directory.readLinkData("link") == Data([0xff])) + let snapshot = try #require(try FileSnapshot.read(at: link)) + #expect(snapshot.digest == FileHash.sha256Hex(data: Data([0xff]))) + #expect(snapshot.digest != FileHash.sha256Hex(data: Data("\u{fffd}".utf8))) + } + @Test func enumeratesHiddenUnicodeAndLongNamesAcrossRepeatedReads() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } diff --git a/Tests/AgentsCoreTests/FileLockProcessTests.swift b/Tests/AgentsCoreTests/FileLockProcessTests.swift index c0a615f..fc5fb7d 100644 --- a/Tests/AgentsCoreTests/FileLockProcessTests.swift +++ b/Tests/AgentsCoreTests/FileLockProcessTests.swift @@ -1,6 +1,7 @@ import AgentsCore import CPlatform import Foundation +import StateTestSupport import Testing @Suite("Inherited file locks") @@ -61,9 +62,11 @@ struct FileLockProcessTests { let identifier = Int32(output.stdout) let pid: Int32 = try #require(identifier) child = pid - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: ready.path), Date() < deadline { - Thread.sleep(forTimeInterval: 0.01) + try ProcessWait.condition( + processIdentifier: pid, root: root, description: "grandchild readiness", + isRunning: { CPlatform.kill(pid, 0) == 0 } + ) { + FileManager.default.fileExists(atPath: ready.path) } #expect(try String(contentsOf: ready, encoding: .utf8) == String(pid)) #expect(fcntl(descriptor, F_GETFD) & FD_CLOEXEC != 0) @@ -73,16 +76,15 @@ struct FileLockProcessTests { defer { close(contender) } #expect(platform_flock(contender, LOCK_EX | LOCK_NB) == -1) #expect(errno == EWOULDBLOCK) - CPlatform.kill(try #require(child), SIGCONT) - let deadline = Date().addingTimeInterval(10) - var acquired = false - repeat { - if let child { CPlatform.kill(child, SIGCONT) } - acquired = platform_flock(contender, LOCK_EX | LOCK_NB) == 0 - if !acquired { Thread.sleep(forTimeInterval: 0.01) } - } while !acquired && Date() < deadline - #expect(acquired) - if acquired { child = nil } + let pid = try #require(child) + try ProcessWait.condition( + processIdentifier: pid, root: root, description: "grandchild lock release", + isRunning: { CPlatform.kill(pid, 0) == 0 }, + ready: { + CPlatform.kill(pid, SIGCONT) + return platform_flock(contender, LOCK_EX | LOCK_NB) == 0 + }) + child = nil } @Test func lockedChildPreservesStreamsDirectoryAndEnvironment() throws { @@ -155,7 +157,7 @@ struct FileLockProcessTests { !FileManager.default.fileExists(atPath: root.appendingPathComponent("lock-acquired").path)) #expect(FileManager.default.fileExists(atPath: gitLock.path)) - try finishProcesses([contender], resuming: pause) + try finishProcesses([contender], root: root, resuming: pause) #expect( FileManager.default.fileExists(atPath: root.appendingPathComponent("lock-acquired").path)) #expect(!FileManager.default.fileExists(atPath: gitLock.path)) @@ -170,7 +172,7 @@ struct FileLockProcessTests { defer { removeTemporaryDirectory(root) } let parent = try stateTestProcess(root: root, arguments: ["closed-streams", String(mask)]) defer { terminateProcess(parent) } - try finishProcesses([parent]) + try finishProcesses([parent], root: root) #expect(try String(contentsOf: root.appendingPathComponent("stdout"), encoding: .utf8) == "out") #expect(try String(contentsOf: root.appendingPathComponent("stderr"), encoding: .utf8) == "err") } diff --git a/Tests/AgentsCoreTests/InstructionTransactionTests.swift b/Tests/AgentsCoreTests/InstructionTransactionTests.swift index e28f640..f7b56ae 100644 --- a/Tests/AgentsCoreTests/InstructionTransactionTests.swift +++ b/Tests/AgentsCoreTests/InstructionTransactionTests.swift @@ -30,7 +30,7 @@ struct InstructionTransactionTests { struct Interrupted: Error {} try store.withLock { let transaction = FileTransaction(store: store) { checkpoint in - if checkpoint == "replace.1" { throw Interrupted() } + if checkpoint == "entry.1.applied" { throw Interrupted() } } for file in files { try transaction.replace( @@ -54,16 +54,22 @@ struct InstructionTransactionTests { projectDirectory: root, homeDirectory: root, environment: [:]) let store = StateStore(scope: .project, environment: environment) let paths = TransactionPaths(store: store) - #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) { + #expect(throws: CoreError.unsafePath("unmanaged project instruction path")) { + try paths.components("instructions-project/other.md") + } + #expect(throws: CoreError.invalidState("invalid scope-relative transaction path")) { + try paths.components("instructions-project/../AGENTS.md") + } + #expect(throws: CoreError.unsafePath("unmanaged installation transaction path")) { + try paths.components("instructions-codex/AGENTS.md") + } + #expect(throws: CoreError.unsafePath("unmanaged project instruction path")) { try paths.components("instructions-project/.git/AGENTS.md") } - #expect(throws: (any Error).self) { + #expect(throws: CoreError.unsafePath("unmanaged project instruction path")) { try paths.components("instructions-project/.agent/instructions/AGENTS.md") } - #expect(throws: (any Error).self) { + #expect(throws: CoreError.unsafePath("unmanaged project instruction path")) { try paths.components("instructions-project/Sources/CLAUDE.md") } #expect(throws: Never.self) { @@ -79,7 +85,9 @@ struct InstructionTransactionTests { "instructions-authoring/.agent/instructions/Rules.md", "instructions-authoring/.agent/instructions/notes.txt", ] { - #expect(throws: (any Error).self) { try paths.components(path) } + #expect(throws: CoreError.unsafePath("invalid instruction authoring path")) { + try paths.components(path) + } } let outside = root.appendingPathComponent("outside") try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true) @@ -90,7 +98,12 @@ struct InstructionTransactionTests { let transaction = FileTransaction(store: store) try transaction.replace( root.appendingPathComponent(".claude/CLAUDE.md"), content: nil, data: Data("new".utf8)) - #expect(throws: (any Error).self) { try transaction.commit() } + #expect { + try transaction.commit() + } throws: { error in + guard case CoreError.unsafePath(let reason) = error else { return false } + return reason.contains("unsafe directory") && reason.contains(".claude") + } } #expect( try String(contentsOf: outside.appendingPathComponent("CLAUDE.md"), encoding: .utf8) diff --git a/Tests/AgentsCoreTests/PreparationEvidenceTests.swift b/Tests/AgentsCoreTests/PreparationEvidenceTests.swift new file mode 100644 index 0000000..842391a --- /dev/null +++ b/Tests/AgentsCoreTests/PreparationEvidenceTests.swift @@ -0,0 +1,176 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Prepared state evidence") +struct PreparationEvidenceTests { + @Test func dataSealingRejectsAnUnexpectedExecutableMode() throws { + let fixture = try PublicationFixture(.fileCreate) + let transaction = FileTransaction(store: fixture.store) { point in + if point == "stage.0.constructed" { + let name = try #require( + try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) + .first(where: { $0.hasPrefix(".agents-") })) + let staged = fixture.root.appendingPathComponent(name).appendingPathComponent( + "entry.0.staged") + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: staged.path) + } + } + try transaction.replace(fixture.target, content: nil, data: Data("postimage".utf8)) + #expect(throws: CoreError.invalidState("staged content permissions mismatch")) { + try transaction.commit() + } + try fixture.check(committed: false, journal: nil) + try fixture.expectClean() + } + + @Test func replacedContainerIsNotAdoptedBeforeIdentityPersistence() throws { + let fixture = try PublicationFixture(.fileCreate) + let saved = fixture.root.appendingPathComponent("saved-empty-container") + var external: FileSnapshot? + var original: FileSnapshot? + var location: URL? + let transaction = FileTransaction(store: fixture.store) { point in + if point == "container.0.created" { + let name = try #require( + try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) + .first(where: { $0.hasPrefix(".agents-") })) + let container = fixture.root.appendingPathComponent(name) + try FileManager.default.moveItem(at: container, to: saved) + original = try FileSnapshot.read(at: saved) + try FileManager.default.createDirectory(at: container, withIntermediateDirectories: false) + try Data("external container".utf8).write(to: container.appendingPathComponent("keep")) + external = try FileSnapshot.read(at: container) + location = container + } + } + try transaction.replace(fixture.target, content: nil, data: Data("postimage".utf8)) + #expect { try transaction.commit() } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("private container changed before its identity was durable") + } + try fixture.expectUnresolved(containing: "unidentified private container is not empty") + #expect(try FileSnapshot.read(at: #require(location)) == external) + #expect(try FileSnapshot.read(at: saved) == original) + #expect(try FileSnapshot.read(at: fixture.target) == fixture.beforeTarget) + } + + @Test(arguments: [PublicationOperation.fileCreate, .directoryDelete]) + func reservedScratchIsRejectedBeforeSealingAndDiscarded(_ operation: PublicationOperation) throws + { + let fixture = try PublicationFixture(operation) + let transaction = FileTransaction(store: fixture.store) { point in + if point == "stage.0.constructed" { + let name = try #require( + try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) + .first(where: { $0.hasPrefix(".agents-") })) + let slot = operation == .directoryDelete ? "staged" : "preimage" + try Data("private injection".utf8).write( + to: fixture.root.appendingPathComponent(name).appendingPathComponent("entry.0." + slot)) + } + } + try transaction.replace( + fixture.target, content: nil, data: operation == .fileCreate ? Data("postimage".utf8) : nil) + #expect(throws: CoreError.invalidState("unexpected private recovery slot before sealing")) { + try transaction.commit() + } + try fixture.check(committed: false, journal: nil) + try fixture.expectClean() + } + + @Test func equalDigestDoesNotTurnDataIntoASymbolicLink() throws { + let fixture = try PublicationFixture(.fileCreate) + let transaction = FileTransaction(store: fixture.store) { point in + if point == "stage.0.constructed" { + let name = try #require( + try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) + .first(where: { $0.hasPrefix(".agents-") })) + let staged = fixture.root.appendingPathComponent(name).appendingPathComponent( + "entry.0.staged") + try FileManager.default.removeItem(at: staged) + try FileManager.default.createSymbolicLink( + atPath: staged.path, withDestinationPath: "postimage") + } + } + try transaction.replace(fixture.target, content: nil, data: Data("postimage".utf8)) + #expect(throws: CoreError.invalidState("staged content type mismatch")) { + try transaction.commit() + } + try fixture.check(committed: false, journal: nil) + try fixture.expectClean() + } + + @Test(arguments: [false, true]) + func constructionMustMatchTheRequestedCopyOrLink(_ link: Bool) throws { + let fixture = try PublicationFixture(.fileCreate) + let transaction = FileTransaction(store: fixture.store) { point in + if point == "stage.0.constructed" { + let name = try #require( + try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) + .first(where: { $0.hasPrefix(".agents-") })) + let staged = fixture.root.appendingPathComponent(name).appendingPathComponent( + "entry.0.staged") + if link { + try FileManager.default.removeItem(at: staged) + try FileManager.default.createSymbolicLink( + atPath: staged.path, withDestinationPath: "external") + } else { + try Data("injected".utf8).write(to: staged.appendingPathComponent("injected")) + } + } + } + try transaction.replace( + fixture.target, content: fixture.root.appendingPathComponent("new"), link: link) + #expect( + throws: CoreError.invalidState( + link ? "staged symbolic link destination mismatch" : "staged content digest mismatch") + ) { try transaction.commit() } + try fixture.check(committed: false, journal: nil) + try fixture.expectClean() + } + + @Test func copyProtocolAlsoAcceptsARegularFile() throws { + let fixture = try PublicationFixture(.fileCreate) + let source = fixture.root.appendingPathComponent("new/nested/file") + let transaction = FileTransaction(store: fixture.store) + try transaction.replace(fixture.target, content: source) + try transaction.commit() + #expect(try Data(contentsOf: fixture.target) == Data(contentsOf: source)) + #expect( + try FileSnapshot.read(at: fixture.target)?.identity.kind + == FileSnapshot.read(at: source)?.identity.kind) + try fixture.expectClean() + } + + @Test func parsedBytesAndJournalPreimageUseThePreparedGeneration() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment(projectDirectory: root, homeDirectory: root, environment: [:]) + ) + try store.save(declaration: Declaration(), resolved: ResolvedState()) + try store.withLock { + let prepared = try StatePrecondition(store: store) + let original = try #require(try prepared.bytes(for: store.declarationURL)) + let declaration = try store.readDeclaration(prepared: prepared) + try (original + Data("\n".utf8)).write(to: store.declarationURL, options: .atomic) + let external = try FileSnapshot.read(at: store.declarationURL) + #expect(try store.readDeclaration(prepared: prepared) == declaration) + #expect(try prepared.bytes(for: store.declarationURL) == original) + let transaction = FileTransaction(store: store) + try transaction.replace( + store.declarationURL, content: nil, data: original, + expecting: prepared.evidence(for: store.declarationURL)) + #expect { + try transaction.commit() + } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("path changed during preparation") + } + #expect(try FileSnapshot.read(at: store.declarationURL) == external) + #expect(try store.openDirectoryIfPresent()?.info("transaction.json") == nil) + } + } +} diff --git a/Tests/AgentsCoreTests/ProcessTestSupport.swift b/Tests/AgentsCoreTests/ProcessTestSupport.swift index b34fd50..456f2df 100644 --- a/Tests/AgentsCoreTests/ProcessTestSupport.swift +++ b/Tests/AgentsCoreTests/ProcessTestSupport.swift @@ -1,16 +1,14 @@ import CPlatform import Foundation +import StateTestSupport import Testing -func finishProcesses(_ processes: [Process], resuming pause: GitTransactionPause? = nil) throws { +func finishProcesses( + _ processes: [Process], root: URL, resuming pause: GitTransactionPause? = nil +) throws { try pause?.resume() for process in processes { - let exited = DispatchSemaphore(value: 0) - process.terminationHandler = { _ in exited.signal() } - if process.isRunning { - try #require(exited.wait(timeout: .now() + 60) == .success) - } - process.waitUntilExit() + try ProcessWait.exit(process, root: root) #expect(process.terminationStatus == 0) } pause?.completed() diff --git a/Tests/AgentsCoreTests/PublicationTests.swift b/Tests/AgentsCoreTests/PublicationTests.swift index f385bd9..c9eff71 100644 --- a/Tests/AgentsCoreTests/PublicationTests.swift +++ b/Tests/AgentsCoreTests/PublicationTests.swift @@ -1,93 +1,40 @@ import CPlatform import Foundation +import StateTestSupport import Testing @testable import AgentsCore @Suite("Journal publication and ownership") struct PublicationTests { - @Test(arguments: ["create", "replace", "delete"]) - func killedPublicationAtEachStageRecoversPhysicalGeneration(_ operation: String) throws { - var points = [ - "journal.preparing", "atomic.0.created.1", "atomic.0.created.2", "atomic.0.exchanged", - "atomic.0.exclusive", "atomic.0.verified", "stage.1.ready", "journal.applying", - "stage.1.sealed", - "journal.applying.renamed", "stage.1.preimage", "stage.1", "publication.preconditions", - "publish.1.intent", - "publish.1.validated", "replace.1.renamed", "publish.1.synced", "replace.1", - "journal.committing", "journal.committed.renamed", "journal.committed", - "journal.terminalSynced", - "cleanup.0.intent", "cleanup.1.intent", "cleanup.1", - "cleanup.0.probe-b.unlinked", "cleanup.0.probe-c.synced", - ] - if operation == "replace" { points += ["publish.1.displaced", "publish.1.retained"] } - if operation != "delete" { points += ["stage.1.written"] } - if operation != "create" { points += ["cleanup.1.old.unlinked", "cleanup.1.old.synced"] } - for point in points { - let fixture = try PublicationFixture(operation: operation) - let original = try FileSnapshot.read(at: fixture.target) - let auxiliary = try FileSnapshot.read(at: fixture.auxiliary) - let child = try fixture.pause("publication", at: point) - terminateProcess(child) - let journal = try fixture.journal() - let entries = try #require(journal["entries"] as? [[String: Any]]) - let staged = try entries[1]["staged"].map { try fixture.snapshot($0) } - let committed = - point.hasPrefix("journal.committed") || point.hasPrefix("cleanup.") - || point == "journal.terminalSynced" - let outcome = try fixture.outcome() - #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.withLock(outcome: outcome, {}) - } - #expect( - outcome.disposition == (committed ? .committed : .unchanged), "\(operation): \(point)") - #expect(try FileSnapshot.read(at: fixture.target) == (committed ? staged : original)) - if committed { - #expect(try Data(contentsOf: fixture.auxiliary) == Data("auxiliary postimage".utf8)) - } else { - #expect(try FileSnapshot.read(at: fixture.auxiliary) == auxiliary) - } - try fixture.expectClean() - } + @Test(arguments: PublicationMatrix.publications) + func killedPublicationAtEachStageRecoversPhysicalGeneration(_ fault: PublicationFault) throws { + try fault.checkSetup() + let fixture = try PublicationFixture(fault.operation) + let child = try fixture.pause("publication", at: fault.point) + defer { terminateProcess(child) } + terminateProcess(child) + let journal = try fixture.lastJournal() + try fixture.recover(expected: fault.committed ? .committed : .unchanged) + try fixture.check(committed: fault.committed, journal: journal) + try fixture.expectClean() } - @Test(arguments: ["create", "replace", "delete"]) - func recoveryCanBeKilledAtEachStageAndRepeated(_ operation: String) throws { - var points = [ - "restore.1.intent", "restore.1.validated", "restore.1.synced", "restore.1", - "restore.0.renamed", "journal.rolledBack.renamed", "journal.terminalSynced", - "cleanup.0.intent", "cleanup.1.intent", "cleanup.1", - ] - if operation == "create" { - points += [ - "restore.1.remove.unlinked", "restore.1.remove.synced", "cleanup.1.removed.unlinked", - ] - } else { - points += ["restore.1.renamed"] - if operation == "replace" { points += ["cleanup.1.old.unlinked"] } - } - for point in points { - let fixture = try PublicationFixture(operation: operation) - let target = try FileSnapshot.read(at: fixture.target) - let auxiliary = try FileSnapshot.read(at: fixture.auxiliary) - terminateProcess(try fixture.pause("publication", at: "replace.1")) - let outcome = try fixture.outcome() - terminateProcess(try fixture.pause("publication-recover", at: point)) - #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.withLock(outcome: outcome, {}) - } - #expect(outcome.disposition == .unchanged) - #expect(try FileSnapshot.read(at: fixture.target) == target, "\(operation): \(point)") - #expect(try FileSnapshot.read(at: fixture.auxiliary) == auxiliary) - #expect(try !FileTransaction.recover(store: fixture.store)) - try fixture.expectClean() - } + @Test(arguments: PublicationMatrix.recoveries) + func recoveryCanBeKilledAtEachStageAndRepeated(_ fault: PublicationFault) throws { + try fault.checkSetup() + let fixture = try PublicationFixture(fault.operation) + terminateProcess(try fixture.pause("publication", at: fault.seed!)) + terminateProcess(try fixture.pause("publication-recover", at: fault.point)) + try fixture.recover(expected: .unchanged) + try fixture.check(committed: false, journal: nil) + #expect(try !FileTransaction.recover(store: fixture.store)) + try fixture.expectClean() } @Test(arguments: ["external", "postimage"]) func concurrentCreatorKeepsItsBytesAndInode(_ bytes: String) throws { - let fixture = try PublicationFixture(operation: "create") - let auxiliary = try FileSnapshot.read(at: fixture.auxiliary) + let fixture = try PublicationFixture(.fileCreate) let child = try fixture.pause("publication", at: "publish.1.validated") defer { terminateProcess(child) } try Data(bytes.utf8).write(to: fixture.target) @@ -95,458 +42,574 @@ struct PublicationTests { try fixture.resume(child) #expect(try fixture.result("publication-result").hasPrefix("unchanged\n")) #expect(try FileSnapshot.read(at: fixture.target) == external) - #expect(try FileSnapshot.read(at: fixture.auxiliary) == auxiliary) + #expect(try FileSnapshot.read(at: fixture.auxiliary) == fixture.beforeAuxiliary) try fixture.expectClean() } - @Test(arguments: [false, true], [false, true]) - func exchangedUnexpectedPreimageIsNeverDiscarded(_ inPlace: Bool, _ killAfterExchange: Bool) - throws - { - let fixture = try PublicationFixture(operation: "replace") - let auxiliary = try FileSnapshot.read(at: fixture.auxiliary) + @Test(arguments: [false, true]) + func exchangedUnexpectedPreimageIsNeverDiscarded(_ inPlace: Bool) throws { + let fixture = try PublicationFixture(.fileReplace) let child = try fixture.pause("publication", at: "publish.1.validated") defer { terminateProcess(child) } - let original = try FileSnapshot.read(at: fixture.target) if !inPlace { try FileManager.default.moveItem( - at: fixture.target, to: fixture.root.appendingPathComponent("saved-original")) + at: fixture.target, to: fixture.root.appendingPathComponent("original")) } try Data("external preimage".utf8).write(to: fixture.target) - let external = try #require(try FileSnapshot.read(at: fixture.target)) - if killAfterExchange { - try fixture.restop(child, at: "replace.1.renamed") - terminateProcess(child) - } else { - try fixture.resume(child) - #expect(try fixture.result("publication-result").hasPrefix("unresolved\n")) - } - #expect(try Data(contentsOf: fixture.target) == Data("postimage".utf8)) - #expect(try fixture.scratch("new", index: 1) == external) + let external = try FileSnapshot.read(at: fixture.target) + try fixture.restop(child, at: "publish.1.exchanged") + terminateProcess(child) + let journal = try #require(try fixture.lastJournal()) + let postimage = try #require(journal.entries[1].staged) + #expect(try FileSnapshot.read(at: fixture.target) == postimage) + #expect( + try FileSnapshot.read(at: fixture.scratch(.staged, entry: 1, journal: journal)) == external) try fixture.expectUnresolved() + #expect(try FileSnapshot.read(at: fixture.target) == postimage) + #expect( + try FileSnapshot.read(at: fixture.scratch(.staged, entry: 1, journal: journal)) == external) if !inPlace { #expect( - try FileSnapshot.read(at: fixture.root.appendingPathComponent("saved-original")) == original - ) + try FileSnapshot.read(at: fixture.root.appendingPathComponent("original")) + == fixture.beforeTarget) } - #expect(try FileSnapshot.read(at: fixture.auxiliary) == auxiliary) } - @Test(arguments: ["postimage", "changed postimage"]) - func externalRecoveryDestinationEvenWithEqualBytesIsPreserved(_ bytes: String) throws { - let fixture = try PublicationFixture(operation: "replace") - let preimage = try FileSnapshot.read(at: fixture.target) - terminateProcess(try fixture.pause("publication", at: "replace.1")) + @Test(arguments: [PublicationOperation.fileReplace, .directoryDelete]) + func missingAppliedPreimageIsUnresolvedBeforeTerminalIntent(_ operation: PublicationOperation) + throws + { + let fixture = try PublicationFixture(operation) + let child = try fixture.pause("publication", at: "entry.1.applied") + defer { terminateProcess(child) } + let journal = try #require(try fixture.lastJournal()) + let slot: TransactionScratch = operation == .directoryDelete ? .preimage : .staged + let original = fixture.scratch(slot, entry: 1, journal: journal) + let saved = fixture.root.appendingPathComponent("saved-preimage") + let before = try #require(fixture.beforeTarget) + if before.needsDirectoryWriteLease { + try FileManager.default.setAttributes( + [.posixPermissions: before.mode | 0o200], ofItemAtPath: original.path) + } + try FileManager.default.moveItem(at: original, to: saved) + if before.needsDirectoryWriteLease { + try FileManager.default.setAttributes( + [.posixPermissions: before.mode], ofItemAtPath: saved.path) + } let published = try FileSnapshot.read(at: fixture.target) - try FileManager.default.moveItem( - at: fixture.target, to: fixture.root.appendingPathComponent("saved-postimage")) - try Data(bytes.utf8).write(to: fixture.target) - let external = try FileSnapshot.read(at: fixture.target) - #expect(external?.identity != published?.identity) + terminateProcess(child) try fixture.expectUnresolved() - #expect(try FileSnapshot.read(at: fixture.target) == external) - #expect(try fixture.scratch("old", index: 1) == preimage) - #expect( - try FileSnapshot.read(at: fixture.root.appendingPathComponent("saved-postimage")) == published - ) + #expect(try FileSnapshot.read(at: fixture.target) == published) + #expect(try FileSnapshot.read(at: saved) == fixture.beforeTarget) + #expect(try fixture.lastJournal()?.phase == .applying) + } + + @Test func missingRollbackQuarantineIsUnresolvedBeforeTerminalIntent() throws { + let fixture = try PublicationFixture(.fileCreate) + terminateProcess(try fixture.pause("publication", at: "publish.1.created")) + let recovery = try fixture.pause("publication-recover", at: "entry.1.restored") + defer { terminateProcess(recovery) } + let journal = try #require(try fixture.lastJournal()) + let quarantined = fixture.scratch(.removed, entry: 1, journal: journal) + let saved = fixture.root.appendingPathComponent("saved-postimage") + try FileManager.default.moveItem(at: quarantined, to: saved) + terminateProcess(recovery) + try fixture.expectUnresolved() + #expect(try FileSnapshot.read(at: fixture.target) == nil) + #expect(try FileSnapshot.read(at: saved) == journal.entries[1].staged) } - @Test(arguments: ["replace", "delete", "create"]) - func externalWriterRacingRestorationRetainsBothVersions(_ operation: String) throws { - let fixture = try PublicationFixture(operation: operation) - let preimage = try FileSnapshot.read(at: fixture.target) - terminateProcess(try fixture.pause("publication", at: "replace.1")) + @Test(arguments: [PublicationOperation.fileCreate, .fileReplace, .directoryDelete]) + func externalRecoveryDestinationPreservesBothVersions(_ operation: PublicationOperation) throws { + let fixture = try PublicationFixture(operation) + terminateProcess(try fixture.pause("publication", at: "entry.1.applied")) let recovery = try fixture.pause("publication-recover", at: "restore.1.validated") defer { terminateProcess(recovery) } - if operation != "delete" { + let journal = try #require(try fixture.lastJournal()) + if try FileSnapshot.read(at: fixture.target) != nil { try FileManager.default.moveItem( at: fixture.target, to: fixture.root.appendingPathComponent("saved-postimage")) } - try Data("postimage".utf8).write(to: fixture.target) + try Data("external recovery writer".utf8).write(to: fixture.target) let external = try FileSnapshot.read(at: fixture.target) - try fixture.resume(recovery) + try fixture.resume(recovery, marker: "recovery-ready") #expect(try fixture.result("recovery-result").hasPrefix("unresolved:")) - if operation == "delete" { - #expect(try FileSnapshot.read(at: fixture.target) == external) - #expect(try fixture.scratch("old", index: 1) == preimage) - } else if operation == "replace" { - #expect(try FileSnapshot.read(at: fixture.target) == preimage) - #expect(try fixture.scratch("old", index: 1) == external) - } else { - #expect(try FileSnapshot.read(at: fixture.target) == nil) - #expect(try fixture.scratch("removed", index: 1) == external) + let location: URL + switch operation { + case .fileCreate: location = fixture.scratch(.removed, entry: 1, journal: journal) + case .fileReplace: location = fixture.scratch(.staged, entry: 1, journal: journal) + default: location = fixture.target + } + #expect(try FileSnapshot.read(at: location) == external) + if operation == .fileReplace { + #expect(try FileSnapshot.read(at: fixture.target) == fixture.beforeTarget) } try fixture.expectUnresolved() + #expect(try FileSnapshot.read(at: location) == external) + if operation == .directoryDelete { + #expect( + try FileSnapshot.read(at: fixture.scratch(.preimage, entry: 1, journal: journal)) + == fixture.beforeTarget) + } else { + #expect( + try FileSnapshot.read(at: fixture.root.appendingPathComponent("saved-postimage")) + == journal.entries[1].staged) + } } - @Test(arguments: ["replace", "create"]) - func killedRecoveryBeforeVerificationRetainsUnexpectedDisplacedObject(_ operation: String) throws - { - let fixture = try PublicationFixture(operation: operation) - let preimage = try FileSnapshot.read(at: fixture.target) - terminateProcess(try fixture.pause("publication", at: "replace.1")) - let recovery = try fixture.pause("publication-recover", at: "restore.1.validated") - defer { terminateProcess(recovery) } - try FileManager.default.moveItem( - at: fixture.target, to: fixture.root.appendingPathComponent("saved-postimage")) - try Data("postimage".utf8).write(to: fixture.target) + @Test func committedFailureRetainsUserDataAndRecordsConflict() throws { + let fixture = try PublicationFixture(.fileReplace) + let child = try fixture.pause("publication", at: "journal.committed") + defer { terminateProcess(child) } + let journal = try #require(try fixture.lastJournal()) + let saved = fixture.root.appendingPathComponent("saved-published") + try FileManager.default.moveItem(at: fixture.target, to: saved) + try Data("external committed target".utf8).write(to: fixture.target) let external = try FileSnapshot.read(at: fixture.target) - let point = operation == "replace" ? "restore.1.renamed" : "restore.1.remove.unlinked" - try fixture.restop(recovery, at: point, markerName: "recovery-ready") - terminateProcess(recovery) + terminateProcess(child) try fixture.expectUnresolved() - #expect(try FileSnapshot.read(at: fixture.target) == preimage) - #expect(try fixture.scratch(operation == "replace" ? "old" : "removed", index: 1) == external) + #expect(try FileSnapshot.read(at: fixture.target) == external) + #expect(try FileSnapshot.read(at: saved) == journal.entries[1].staged) + #expect( + try FileSnapshot.read(at: fixture.scratch(.staged, entry: 1, journal: journal)) + == fixture.beforeTarget) } - @Test func interruptedDirectoryCleanupPreservesNewExternalDescendants() throws { - let fixture = try TransactionFixture() - let child = try stateTestProcess(root: fixture.root, arguments: ["crash", "cleanup.0.intent"]) - defer { terminateProcess(child) } - let marker = fixture.root.appendingPathComponent("ready") - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: marker.path), child.isRunning, Date() < deadline { - Thread.sleep(forTimeInterval: 0.01) + @Test(arguments: [false, true]) + func plannedUnidentifiedContainerOnlyAdmitsEmptyRmdir(_ populate: Bool) throws { + let fixture = try PublicationFixture(.fileCreate) + terminateProcess(try fixture.pause("publication", at: "container.0.created")) + let journal = try #require(try fixture.lastJournal()) + #expect(journal.containers[0].identity == nil) + let container = fixture.root.appendingPathComponent(journal.containerName(0)) + if populate { + let file = container.appendingPathComponent("keep") + try Data("unidentified bytes".utf8).write(to: file) + let before = try FileSnapshot.read(at: file) + try fixture.expectUnresolved(containing: "unidentified private container is not empty") + #expect(try FileSnapshot.read(at: file) == before) + } else { + try fixture.recover(expected: .unchanged) + try fixture.expectClean() } - try #require(FileManager.default.fileExists(atPath: marker.path)) + #expect(try FileSnapshot.read(at: fixture.target) == fixture.beforeTarget) + } + + @Test func sealedPrivateObjectChangesAreUnresolved() throws { + let fixture = try PublicationFixture(.fileReplace) + terminateProcess(try fixture.pause("publication", at: "entry.1.ready")) + let journal = try #require(try fixture.lastJournal()) + let file = fixture.scratch(.staged, entry: 1, journal: journal) + try Data("changed after sealing".utf8).write(to: file) + let changed = try FileSnapshot.read(at: file) + try fixture.expectUnresolved() + #expect(try FileSnapshot.read(at: file) == changed) + #expect(try FileSnapshot.read(at: fixture.target) == fixture.beforeTarget) + } + + @Test func directoryPermissionChangesOutsideIntentRemainExternal() throws { + let fixture = try PublicationFixture(.directoryReplace) + let child = try fixture.pause("publication", at: "permissions.1.publish.grant.target.synced") + defer { terminateProcess(child) } + try FileManager.default.setAttributes( + [.posixPermissions: 0o770], ofItemAtPath: fixture.target.path) + let external = try FileSnapshot.read(at: fixture.target) terminateProcess(child) - let json = try #require( - JSONSerialization.jsonObject( - with: Data(contentsOf: fixture.store.directory.appendingPathComponent("transaction.json"))) - as? [String: Any]) - let id = try #require(json["id"] as? String) - let original = fixture.root.appendingPathComponent(".agents/skills/.agents-\(id)-0.old") - let childURL = original.appendingPathComponent("external") - try Data("keep external descendant".utf8).write(to: childURL) - let before = try FileSnapshot.read(at: original) + let beforeDiagnosis = try FileSnapshot.read(at: fixture.root) + let diagnosis = FileTransaction.recoveryDiagnostic(store: fixture.store) + #expect(diagnosis.requiresOwner) + #expect(diagnosis.message.contains("directory permissions changed beyond transaction intent")) + #expect(try FileSnapshot.read(at: fixture.root) == beforeDiagnosis) + try fixture.expectUnresolved( + containing: "directory permissions changed beyond transaction intent") + #expect(try FileSnapshot.read(at: fixture.target) == external) + } + + @Test( + arguments: [EINVAL, ENOSYS, ENOTSUP, EOPNOTSUPP, EIO], + [DirectoryHandle.RenameMode.exchange, .exclusive]) + func primitiveFailuresCleanPrivateResourcesBeforeChangingUserData( + _ code: Int32, _ mode: DirectoryHandle.RenameMode + ) throws { + let fixture = try PublicationFixture(.fileReplace) let outcome = TransactionOutcome() - outcome.journalID = UUID(uuidString: id) - for _ in 0..<2 { - #expect(throws: CoreError.self) { try fixture.store.withLock(outcome: outcome, {}) } - #expect(outcome.disposition == .recoveryRequired) - #expect(try FileSnapshot.read(at: original) == before) - #expect( - try String(contentsOf: original.appendingPathComponent("SKILL.md"), encoding: .utf8) - == "target") - } + let transaction = FileTransaction(store: fixture.store, outcome: outcome) + try transaction.replace(fixture.target, content: nil, data: Data("postimage".utf8)) + let operation = + mode == .exchange ? "exchange atomic probe" : "check exclusive atomic probe collision" + let expected: CoreError = + code == EIO + ? .invalidState("cannot \(operation): \(code) (\(String(cString: strerror(code))))") + : .unsupported( + "atomic rename is required: \(operation): \(code) (\(String(cString: strerror(code))))") + DirectoryHandle.$atomicRenameFailure.withValue( + { $0 == mode ? code : nil }, + operation: { #expect(throws: expected) { try transaction.commit() } }) + #expect(outcome.disposition == .unchanged) + try fixture.check(committed: false, journal: nil) + try fixture.expectClean() } - @Test(arguments: ["new", "old", "missing"]) - func replacedOrMissingRecoveryEvidenceNeverGrantsOwnership(_ suffix: String) throws { - let fixture = try PublicationFixture(operation: suffix == "new" ? "create" : "replace") - let point = suffix == "new" ? "journal.applying" : "replace.1" - terminateProcess(try fixture.pause("publication", at: point)) - let actualSuffix = suffix == "missing" ? "old" : suffix - let path = try fixture.scratchURL(actualSuffix, index: 1) - let saved = fixture.root.appendingPathComponent("saved-evidence") - let original = try #require(try FileSnapshot.read(at: path)) - try FileManager.default.moveItem(at: path, to: saved) - var external: FileSnapshot? - if suffix != "missing" { - try Data(contentsOf: saved).write(to: path) - external = try FileSnapshot.read(at: path) - #expect(external?.identity != original.identity) + @Test(arguments: ["staged", "parent", "container"]) + func missingJournalEvidenceReachesSemanticValidation(_ field: String) throws { + let fixture = try PublicationFixture(.fileReplace) + terminateProcess(try fixture.pause("publication", at: "entry.1.ready")) + var journal = try #require(try fixture.lastJournal()) + switch field { + case "staged": journal.entries[1].staged = nil + case "parent": journal.entries[1].parentIdentity = "" + default: journal.entries[1].container = journal.containers.count } - let target = try FileSnapshot.read(at: fixture.target) - try fixture.expectUnresolved() - #expect(try FileSnapshot.read(at: path) == external) - #expect(try FileSnapshot.read(at: saved) == original) - #expect(try FileSnapshot.read(at: fixture.target) == target) + // Encode a valid current-format value; failure cannot be a missing Decodable key. + try StateStore.encode(journal).write( + to: fixture.store.directory.appendingPathComponent("transaction.json")) + let before = try FileSnapshot.read(at: fixture.root) + let reason: String + switch field { + case "staged": reason = "operation progress contradicts its evidence or journal phase" + case "parent": reason = "destination parent changed" + default: reason = "overlapping destinations or invalid container" + } + let location = + field == "container" + ? "" + : "instructions-project/" + journal.containerName(0) + #expect( + throws: CoreError.invalidState( + "transaction conflict at instructions-project/AGENTS.md: \(reason); retained container: \(location)" + ) + ) { + try fixture.store.loadResolved() + } + #expect(try FileSnapshot.read(at: fixture.root) == before) } - @Test func deletionNeverAdoptsAnUnexpectedStagingObject() throws { - let fixture = try PublicationFixture(operation: "delete") - let target = try FileSnapshot.read(at: fixture.target) - let outcome = TransactionOutcome() - var external: FileSnapshot? - #expect(throws: CoreError.self) { - try fixture.store.withLock(outcome: outcome) { - let transaction = FileTransaction(store: fixture.store, outcome: outcome) { step in - if step == "stage.0.preimage" { - let url = try fixture.scratchURL("new", index: 0) - try Data("external object".utf8).write(to: url) - external = try FileSnapshot.read(at: url) - } - } - try transaction.replace(fixture.target, content: nil) - try transaction.commit() - } + @Test(arguments: [Optional.none, .some(999)]) + func oldJournalVersionRequiresItsWritingVersionWithoutMutation(_ version: Int?) throws { + let fixture = try PublicationFixture(.fileReplace) + // This is the unversioned Journal/Entry schema and scratch naming written by ed859e6. + let id = UUID() + let directory = try #require(try fixture.store.openDirectoryIfPresent()) + let backup = directory.url.appendingPathComponent(".agents-\(id.uuidString)-0.old") + try FileManager.default.moveItem(at: fixture.store.declarationURL, to: backup) + try Data("{\"agents\":[\"codex\"]}".utf8).write(to: fixture.store.declarationURL) + var old = try StateStore.encode( + LegacyJournal( + id: id, scope: directory.identity, + roots: ["state": directory.identity], phase: "applying", + entries: [.init(path: "state/agents.json", existed: true, replacement: true)])) + if let version { + var encoded = try #require(JSONSerialization.jsonObject(with: old) as? [String: Any]) + encoded["version"] = version + old = try JSONSerialization.data(withJSONObject: encoded) } - #expect(outcome.disposition == .recoveryRequired) - #expect(try FileSnapshot.read(at: fixture.target) == target) - #expect(try fixture.scratch("new", index: 0) == external) - try fixture.expectUnresolved() + try old.write(to: directory.url.appendingPathComponent("transaction.json")) + let before = try FileSnapshot.read(at: fixture.root) + #expect( + throws: CoreError.invalidState( + "transaction journal was written by another version; recover it with the version that wrote it (journal version: \(version.map(String.init) ?? "missing"))" + ) + ) { + try fixture.store.loadResolved() + } + #expect(try FileSnapshot.read(at: fixture.root) == before) + let diagnostic = FileTransaction.recoveryDiagnostic(store: fixture.store) + #expect(diagnostic.requiresOwner) + #expect(diagnostic.message.contains("version that wrote it")) } - @Test(arguments: ["preparing", "committed", "rolledBack", "unsealed"]) - func inconsistentJournalStagesPreserveAllEvidence(_ phase: String) throws { - let fixture = try PublicationFixture(operation: "replace") - terminateProcess(try fixture.pause("publication", at: "replace.0")) - let outcome = try fixture.outcome() - var journal = try fixture.journal() - if phase == "unsealed" { - var entries = try #require(journal["entries"] as? [[String: Any]]) - entries[1]["progress"] = "verifying" - journal["entries"] = entries + @Test(arguments: ["identity", "disposal"]) + func missingContainerEvidenceCannotAuthorizeTerminalDeletion(_ field: String) throws { + let fixture = try PublicationFixture(.fileReplace) + terminateProcess(try fixture.pause("publication", at: "journal.committed")) + var journal = try #require(try fixture.lastJournal()) + if field == "identity" { + journal.containers[0].identity = nil } else { - journal["phase"] = phase + journal.containers[0].cleanup = nil } - try JSONSerialization.data(withJSONObject: journal).write( + try StateStore.encode(journal).write( to: fixture.store.directory.appendingPathComponent("transaction.json")) - let before = try FileHash.folderHash(fixture.root) - let target = try FileSnapshot.read(at: fixture.target) - let auxiliary = try FileSnapshot.read(at: fixture.auxiliary) - #expect(throws: CoreError.self) { try fixture.store.withLock(outcome: outcome, {}) } - #expect(outcome.disposition == .recoveryRequired) - #expect(try FileHash.folderHash(fixture.root) == before) - #expect(try FileSnapshot.read(at: fixture.target) == target) - #expect(try FileSnapshot.read(at: fixture.auxiliary) == auxiliary) - } - - @Test(arguments: ["preimage", "staged", "parentIdentity", "probes"]) - func missingJournalEvidenceReportsUnresolvedBeforeReplay(_ field: String) throws { - let fixture = try PublicationFixture(operation: "replace") - terminateProcess(try fixture.pause("publication", at: "replace.1")) - let outcome = try fixture.outcome() - var journal = try fixture.journal() - var entries = try #require(journal["entries"] as? [[String: Any]]) - entries[1].removeValue(forKey: field) - journal["entries"] = entries - try JSONSerialization.data(withJSONObject: journal).write( - to: fixture.store.directory.appendingPathComponent("transaction.json")) - let before = try FileHash.folderHash(fixture.root) - #expect(throws: CoreError.self) { try fixture.store.withLock(outcome: outcome, {}) } - #expect(outcome.disposition == .recoveryRequired) - #expect(try FileHash.folderHash(fixture.root) == before) + let before = try FileSnapshot.read(at: fixture.root) + #expect( + throws: CoreError.invalidState( + field == "identity" + ? "sealed operation is missing private container identity" + : "terminal container is missing user-object disposal evidence") + ) { try fixture.store.loadResolved() } + #expect(try FileSnapshot.read(at: fixture.root) == before) } - @Test func cleanupConflictAfterCommitReportsUnresolvedAndKeepsPreimage() throws { - let fixture = try PublicationFixture(operation: "replace") - let preimage = try FileSnapshot.read(at: fixture.target) - let child = try fixture.pause("publication", at: "journal.committed") - defer { terminateProcess(child) } - let path = try fixture.scratchURL("old", index: 1) - let saved = fixture.root.appendingPathComponent("saved-preimage") - try FileManager.default.moveItem(at: path, to: saved) - try Data(contentsOf: saved).write(to: path) - let external = try FileSnapshot.read(at: path) - try fixture.resume(child) - #expect(try fixture.result("publication-result").hasPrefix("unresolved\n")) - #expect(try Data(contentsOf: fixture.target) == Data("postimage".utf8)) - #expect(try FileSnapshot.read(at: saved) == preimage) - #expect(try FileSnapshot.read(at: path) == external) - try fixture.expectUnresolved() + @Test func unchangedStateIsNotAnImplicitCachePrecondition() throws { + let fixture = try PublicationFixture(.fileCreate) + let cache = SourceCache(store: fixture.store) + let bytes = Data("artifact".utf8) + let digest = "sha256:" + FileHash.sha256Hex(data: Data("artifact".utf8)) + let transaction = FileTransaction(store: fixture.store) + let target = try cache.artifactURL(digest: digest) + try transaction.replace(target, content: nil, data: bytes, expectedHash: digest) + try Data("{\"agents\":[]}".utf8).write(to: fixture.store.declarationURL) + let state = try FileSnapshot.read(at: fixture.store.declarationURL) + try transaction.commit() + #expect(try Data(contentsOf: target) == bytes) + #expect(try FileSnapshot.read(at: fixture.store.declarationURL) == state) } +} - @Test func movedScopeAfterCommitReportsUnresolvedUntilItsIdentityIsRestored() throws { - let fixture = try PublicationFixture(operation: "replace") - let moved = fixture.root.appendingPathComponent("moved-state") - let outcome = TransactionOutcome() - #expect(throws: CoreError.self) { - try fixture.store.withLock(outcome: outcome) { - let transaction = FileTransaction(store: fixture.store, outcome: outcome) { step in - if step == "journal.committed" { - try FileManager.default.moveItem(at: fixture.store.directory, to: moved) - throw CoreError.invalidState("scope moved") - } - } - try transaction.replace(fixture.target, content: nil, data: Data("postimage".utf8)) - try transaction.commit() - } +enum PublicationOperation: String, CaseIterable, Sendable { + case fileReplace, directoryReplace, directoryDelete, symlinkCreate, fileCreate + var renamePoint: String { + switch self { + case .directoryDelete: "publish.1.quarantined" + case .fileReplace, .directoryReplace: "publish.1.exchanged" + default: "publish.1.created" } - #expect(outcome.disposition == .recoveryRequired) - #expect(try Data(contentsOf: fixture.target) == Data("postimage".utf8)) - #expect( - FileManager.default.fileExists(atPath: moved.appendingPathComponent("transaction.json").path)) - try FileManager.default.moveItem(at: moved, to: fixture.store.directory) - #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.withLock(outcome: outcome, {}) - } - #expect(outcome.disposition == .committed) - try fixture.expectClean() } +} - @Test(arguments: ["create", "replace", "delete"]) - func unsupportedAtomicsFailBeforeAnyTransactionMutation(_ operation: String) throws { - let fixture = try PublicationFixture(operation: operation) - let before = try FileHash.folderHash(fixture.root) - let outcome = TransactionOutcome() - let transaction = FileTransaction(store: fixture.store, outcome: outcome) - transaction.atomicPreflight = { _ in throw CoreError.unsupported("injected atomic primitive") } - try transaction.replace( - fixture.target, content: nil, data: operation == "delete" ? nil : Data("postimage".utf8)) - #expect(throws: CoreError.unsupported("injected atomic primitive")) { try transaction.commit() } - #expect(outcome.disposition == .unchanged) - #expect(try FileHash.folderHash(fixture.root) == before) - try fixture.expectClean() +struct PublicationFault: Sendable, CustomTestStringConvertible { + let operation: PublicationOperation + let point: String + var committed = false + var seed: String? + var setupFailure: String? + var testDescription: String { + "\(operation.rawValue), \(seed.map { "from \($0), " } ?? "")\(point)" } - - @Test(arguments: ["agents.json", "agents.resolved", "agents.watch", "AGENTS.md"]) - func queuedPreconditionsRejectChangedBytesOrEqualByteExternalInodes(_ path: String) throws { - for equalBytes in [false, true] { - let fixture = try PublicationFixture(operation: "replace") - let target = - path == "AGENTS.md" ? fixture.target : fixture.store.directory.appendingPathComponent(path) - let transaction = FileTransaction(store: fixture.store) - try transaction.replace(fixture.target, content: nil, data: Data("postimage".utf8)) - let bytes = try Data(contentsOf: target) - if equalBytes { - try FileManager.default.moveItem( - at: target, to: fixture.root.appendingPathComponent("saved-input")) - } - try (equalBytes ? bytes : bytes + Data(" ".utf8)).write(to: target) - let external = try FileSnapshot.read(at: target) - #expect(throws: CoreError.self) { try transaction.commit() } - #expect(try FileSnapshot.read(at: target) == external) - try fixture.expectClean() + func checkSetup() throws { + if let setupFailure { + throw CoreError.invalidState("checkpoint recording failed: " + setupFailure) } } +} - @Test(arguments: ["publication.preconditions", "publish.1.validated"], [false, true]) - func unchangedStateInputsAreRecheckedBeforePublicationAndCommit( - _ point: String, _ equalBytes: Bool - ) - throws - { - let fixture = try PublicationFixture(operation: "replace") - let target = try FileSnapshot.read(at: fixture.target) - let auxiliary = try FileSnapshot.read(at: fixture.auxiliary) - let outcome = TransactionOutcome() - var external: FileSnapshot? - try fixture.store.withLock(outcome: outcome) { - let transaction = FileTransaction(store: fixture.store, outcome: outcome) { step in - if step == point { - let bytes = try Data(contentsOf: fixture.store.watchURL) - if equalBytes { - try FileManager.default.moveItem( - at: fixture.store.watchURL, to: fixture.root.appendingPathComponent("saved-watch")) +private enum PublicationMatrix { + static let publications = record(recovery: false) + static let recoveries = record(recovery: true) + + private static func record(recovery: Bool) -> [PublicationFault] { + var cases: [PublicationFault] = [] + for operation in PublicationOperation.allCases { + var seeds: [String?] = recovery ? [operation.renamePoint, "entry.1.applied"] : [nil] + if recovery, operation == .directoryReplace || operation == .directoryDelete { + seeds.append("permissions.1.publish.grant.target.changed") + } + for seed in seeds { + do { + let fixture = try PublicationFixture(operation) + if let seed { terminateProcess(try fixture.pause("publication", at: seed)) } + let command = recovery ? "publication-recover" : "publication" + let child = try fixture.launch(command, at: "never") + defer { terminateProcess(child) } + try ProcessWait.exit(child, root: fixture.root) + guard child.terminationStatus == 0 else { + throw CoreError.invalidState("checkpoint recorder exited \(child.terminationStatus)") + } + let trace = try String( + contentsOf: fixture.root.appendingPathComponent( + "checkpoint-\(child.processIdentifier).log"), encoding: .utf8 + ) + .split(separator: "\n").map(String.init) + guard !trace.isEmpty, Set(trace).count == trace.count else { + throw CoreError.invalidState("checkpoint names are empty or repeated") } - try (equalBytes ? bytes : bytes + Data(" ".utf8)).write(to: fixture.store.watchURL) - external = try FileSnapshot.read(at: fixture.store.watchURL) + var committed = false + for point in trace { + if point == "journal.committed.terminal.renamed" { committed = true } + cases.append( + PublicationFault(operation: operation, point: point, committed: committed, seed: seed) + ) + } + } catch { + cases.append( + PublicationFault( + operation: operation, point: "recording", seed: seed, + setupFailure: String(describing: error))) } } - for file in [fixture.auxiliary, fixture.target] { - try transaction.replace(file, content: nil, data: Data("postimage".utf8)) - } - #expect(throws: CoreError.self) { try transaction.commit() } } - #expect(outcome.disposition == .unchanged) - #expect(try FileSnapshot.read(at: fixture.target) == target) - #expect(try FileSnapshot.read(at: fixture.auxiliary) == auxiliary) - #expect(try FileSnapshot.read(at: fixture.store.watchURL) == external) - try fixture.expectClean() + return cases } } -private final class PublicationFixture { +final class PublicationFixture { + let operation: PublicationOperation let root: URL let store: StateStore - let operation: String - var target: URL { root.appendingPathComponent("AGENTS.md") } - var auxiliary: URL { root.appendingPathComponent("GEMINI.md") } + let target: URL + let auxiliary: URL + let beforeTarget: FileSnapshot? + let beforeAuxiliary: FileSnapshot? + let state: [(URL, FileSnapshot?)] - init(operation: String) throws { - root = try temporaryDirectory() + init(_ operation: PublicationOperation) throws { self.operation = operation + root = try temporaryDirectory() store = StateStore( scope: .project, environment: RuntimeEnvironment( projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: [:] )) + target = root.appendingPathComponent("AGENTS.md") + auxiliary = root.appendingPathComponent("GEMINI.md") do { - try store.save(declaration: Declaration(), resolved: ResolvedState(), watch: WatchState()) - if operation != "create" { try Data("preimage".utf8).write(to: target) } + try store.save(declaration: Declaration(), resolved: ResolvedState()) try Data("auxiliary preimage".utf8).write(to: auxiliary) + let source = root.appendingPathComponent("new") + try FileManager.default.createDirectory( + at: source.appendingPathComponent("nested"), withIntermediateDirectories: true) + try Data("tree postimage".utf8).write(to: source.appendingPathComponent("nested/file")) + try FileManager.default.createSymbolicLink( + atPath: source.appendingPathComponent("link").path, withDestinationPath: "nested/file") + if operation == .fileReplace { try Data("preimage".utf8).write(to: target) } + if operation == .directoryReplace || operation == .directoryDelete { + try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true) + try Data("tree preimage".utf8).write(to: target.appendingPathComponent("file")) + try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: target.path) + } + if operation == .directoryReplace { + try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: source.path) + } + beforeTarget = try FileSnapshot.read(at: target) + beforeAuxiliary = try FileSnapshot.read(at: auxiliary) + state = try [store.declarationURL, store.resolvedURL, store.watchURL].map { + ($0, try FileSnapshot.read(at: $0)) + } } catch { + makeDirectoriesWritable(root) removeTemporaryDirectory(root) throw error } } + deinit { + makeDirectoriesWritable(root) + removeTemporaryDirectory(root) + } - deinit { removeTemporaryDirectory(root) } + func launch(_ command: String, at point: String) throws -> Process { + try stateTestProcess(root: root, arguments: [command, point, operation.rawValue]) + } - func pause(_ command: String, at step: String) throws -> Process { + func pause(_ command: String, at point: String) throws -> Process { let marker = root.appendingPathComponent(command == "publication" ? "ready" : "recovery-ready") try? FileManager.default.removeItem(at: marker) try? FileManager.default.removeItem(at: root.appendingPathComponent("stop-at")) - let child = try stateTestProcess(root: root, arguments: [command, step, operation]) - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: marker.path), child.isRunning, Date() < deadline { - Thread.sleep(forTimeInterval: 0.01) - } - if !FileManager.default.fileExists(atPath: marker.path) { + let child = try launch(command, at: point) + do { + try ProcessWait.marker(marker, child: child, root: root) + return child + } catch { terminateProcess(child) - throw CoreError.invalidState("publication subprocess did not reach \(step)") + throw error } - return child } - func restop(_ child: Process, at step: String, markerName: String = "ready") throws { - let marker = root.appendingPathComponent(markerName) - try Data(step.utf8).write(to: root.appendingPathComponent("stop-at")) - try FileManager.default.removeItem(at: marker) + func resume(_ child: Process, marker: String = "ready") throws { + try? FileManager.default.removeItem(at: root.appendingPathComponent(marker)) kill(child.processIdentifier, SIGCONT) - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: marker.path), child.isRunning, Date() < deadline { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: marker.path)) + try ProcessWait.exit(child, root: root) + #expect(child.terminationStatus == 0) } - func resume(_ child: Process) throws { + func restop(_ child: Process, at point: String) throws { + let marker = root.appendingPathComponent("ready") + try? FileManager.default.removeItem(at: marker) + try Data(point.utf8).write(to: root.appendingPathComponent("stop-at")) kill(child.processIdentifier, SIGCONT) - try finishProcesses([child]) + try ProcessWait.marker(marker, child: child, root: root) } func result(_ name: String) throws -> String { try String(contentsOf: root.appendingPathComponent(name), encoding: .utf8) } - func journal() throws -> [String: Any] { - try #require( - JSONSerialization.jsonObject( - with: Data(contentsOf: store.directory.appendingPathComponent("transaction.json"))) - as? [String: Any]) - } - - func outcome() throws -> TransactionOutcome { - let result = TransactionOutcome() - result.journalID = try UUID(uuidString: #require(journal()["id"] as? String)) - return result + func lastJournal() throws -> TransactionJournal? { + for url in [ + store.directory.appendingPathComponent("transaction.json"), + store.directory.appendingPathComponent("transaction.new"), + root.appendingPathComponent("last-journal"), + ] { + if FileManager.default.fileExists(atPath: url.path) { + return try StateStore.decode(Data(contentsOf: url), as: TransactionJournal.self) + } + } + return nil } - func snapshot(_ json: Any) throws -> FileSnapshot { - try JSONDecoder().decode(FileSnapshot.self, from: JSONSerialization.data(withJSONObject: json)) + func scratch(_ slot: TransactionScratch, entry index: Int, journal: TransactionJournal) -> URL { + root.appendingPathComponent(journal.containerName(journal.entries[index].container)) + .appendingPathComponent(slot.name(index)) } - func scratchURL(_ suffix: String, index: Int) throws -> URL { - let id = try #require(journal()["id"] as? String) - return root.appendingPathComponent(".agents-\(id)-\(index).\(suffix)") + func recover(expected: TransactionOutcome.Disposition) throws { + let outcome = TransactionOutcome() + outcome.journalID = try lastJournal()?.id + let directory = try #require(try store.openDirectoryIfPresent()) + let pending = + try directory.info("transaction.json") != nil || directory.info("transaction.new") != nil + if pending { + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { + try store.withLock(outcome: outcome, {}) + } + #expect(outcome.disposition == expected) + } else { + try store.withLock(outcome: outcome, {}) + if expected == .committed { #expect(try result("stopped-outcome") == "committed") } + } } - func scratch(_ suffix: String, index: Int) throws -> FileSnapshot? { - try FileSnapshot.read(at: scratchURL(suffix, index: index)) + func expectUnresolved( + containing expected: String = + "missing or changed expected target, preimage or rollback quarantine" + ) throws { + let outcome = TransactionOutcome() + outcome.journalID = try lastJournal()?.id + #expect { try store.withLock(outcome: outcome, {}) } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains(expected) + } + #expect(outcome.disposition == .recoveryRequired) + let diagnostic = FileTransaction.recoveryDiagnostic(store: store) + #expect(diagnostic.requiresOwner) + #expect(diagnostic.message.contains("owner action")) + let journal = try #require(try lastJournal()) + let conflicts = journal.entries.compactMap(\.conflict) + #expect(conflicts.contains { $0.reason.contains(expected) && !$0.locations.isEmpty }) + #expect(try store.openDirectoryIfPresent()?.info("transaction.json") != nil) + #expect( + try FileSnapshot.read(at: auxiliary) + == (journal.phase == .committed ? journal.entries[0].staged : beforeAuxiliary)) + for (url, before) in state { #expect(try FileSnapshot.read(at: url) == before) } } - func expectUnresolved() throws { - let outcome = try outcome() - for _ in 0..<2 { - #expect(throws: CoreError.self) { - try store.withLock(outcome: outcome, {}) - } - #expect(outcome.disposition == .recoveryRequired) - let before = try FileHash.folderHash(root) - #expect(throws: CoreError.self) { - try store.withReadLock { Issue.record("must not inspect") } - } - #expect(try FileHash.folderHash(root) == before) - } + func check(committed: Bool, journal: TransactionJournal?) throws { + #expect( + try FileSnapshot.read(at: target) == (committed ? journal?.entries[1].staged : beforeTarget)) + #expect( + try FileSnapshot.read(at: auxiliary) + == (committed ? journal?.entries[0].staged : beforeAuxiliary)) + for (url, before) in state { #expect(try FileSnapshot.read(at: url) == before) } } func expectClean() throws { #expect(try store.openDirectoryIfPresent()?.info("transaction.json") == nil) #expect(try store.openDirectoryIfPresent()?.info("transaction.new") == nil) - let names = try FileManager.default.contentsOfDirectory(atPath: root.path) - #expect(!names.contains { $0.hasPrefix(".agents-") }) + #expect( + try !FileManager.default.contentsOfDirectory(atPath: root.path).contains { + $0.hasPrefix(".agents-") + }) + } +} + +private struct LegacyJournal: Encodable { + let id: UUID + let scope: String + let roots: [String: String] + let phase: String + let entries: [Entry] + struct Entry: Encodable { + let path: String + let existed: Bool + let replacement: Bool } } diff --git a/Tests/AgentsCoreTests/StateInspectionTests.swift b/Tests/AgentsCoreTests/StateInspectionTests.swift index 966949f..170ef43 100644 --- a/Tests/AgentsCoreTests/StateInspectionTests.swift +++ b/Tests/AgentsCoreTests/StateInspectionTests.swift @@ -87,8 +87,8 @@ struct StateInspectionTests { try fixture.store.withReadLock { reads += 1 let child = try stateTestProcess( - root: fixture.root, arguments: ["watch-add", "replace.1.renamed"]) - try fixture.kill(child, at: "replace.1.renamed") + root: fixture.root, arguments: ["watch-add", "publish.1.created"]) + try fixture.kill(child, at: "publish.1.created") let declaration = try fixture.store.readDeclaration() let watch = try fixture.store.readWatch() try #require(declaration.watch == ["source"]) diff --git a/Tests/AgentsCoreTests/StateTransactionTests.swift b/Tests/AgentsCoreTests/StateTransactionTests.swift index 1df6c5b..456afbf 100644 --- a/Tests/AgentsCoreTests/StateTransactionTests.swift +++ b/Tests/AgentsCoreTests/StateTransactionTests.swift @@ -1,5 +1,6 @@ import CPlatform import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -13,7 +14,7 @@ struct StateTransactionTests { let moved = fixture.root.appendingPathComponent("displaced-cache") try fixture.store.withLock { let transaction = FileTransaction(store: fixture.store) { step in - if step == "journal.committed.renamed" { + if step == "journal.committed.terminal.renamed" { try FileManager.default.moveItem(at: parent, to: moved) throw CoreError.invalidState("cache cleanup interrupted") } @@ -21,7 +22,9 @@ struct StateTransactionTests { try transaction.replace( parent.appendingPathComponent("pruned"), content: fixture.root.appendingPathComponent("new")) - #expect(throws: CoreError.self) { try transaction.commit() } + #expect(throws: CoreError.invalidState("cache cleanup interrupted")) { + try transaction.commit() + } #expect( FileManager.default.fileExists( atPath: @@ -47,9 +50,9 @@ struct StateTransactionTests { for failure in Set(checkpoints).sorted() { let fixture = try TransactionFixture() var committed = false - #expect(throws: CoreError.self) { + #expect(throws: CoreError.invalidState("injected failure")) { try fixture.commit { step in - if step == "journal.committed.renamed" { committed = true } + if step == "journal.committed.terminal.renamed" { committed = true } if step == failure { throw CoreError.invalidState("injected failure") } } } @@ -61,12 +64,14 @@ struct StateTransactionTests { } @Test(arguments: [ - "journal.preparing", "journal.preparing.renamed", "stage.0", "stage.4", "journal.applying", - "replace.0", - "replace.1", "replace.2", - "replace.3", "replace.4", "replace.5", "replace.5.renamed", "replace.0.renamed", - "journal.applying.renamed", - "journal.committed.renamed", "journal.committed", "cleanup.0", + "journal.preparing", "journal.preparing.created.renamed", "entry.0.ready", "entry.4.ready", + "entry.0.publishing", + "entry.0.applied", + "entry.1.applied", "entry.2.applied", + "entry.3.applied", "entry.4.applied", "entry.5.applied", "publish.5.exchanged", + "publish.0.exchanged", + "journal.applying.entry.0.publishing.renamed", + "journal.committed.terminal.renamed", "journal.committed", "cleanup.0.removed", ]) func killedWriterRecoversOnNextStateRead(_ step: String) throws { let fixture = try TransactionFixture() @@ -77,14 +82,8 @@ struct StateTransactionTests { child.waitUntilExit() } } - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists( - atPath: fixture.root.appendingPathComponent("ready").path), Date() < deadline, child.isRunning - { - Thread.sleep(forTimeInterval: 0.01) - } - #expect( - FileManager.default.fileExists(atPath: fixture.root.appendingPathComponent("ready").path)) + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) // At every interruption point the replaced installation still has a directory entry. #expect( FileManager.default.fileExists( @@ -95,7 +94,7 @@ struct StateTransactionTests { #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { _ = try fixture.store.loadResolved() } - try fixture.check(committed: step.hasPrefix("journal.committed") || step == "cleanup.0") + try fixture.check(committed: step.hasPrefix("journal.committed") || step == "cleanup.0.removed") } @Test func serializesSeparateWriterProcesses() throws { @@ -208,7 +207,16 @@ extension StateTransactionTests { let before = try Data(contentsOf: store.resolvedURL) let journal = store.directory.appendingPathComponent("transaction.json") try Data(json.utf8).write(to: journal) - #expect(throws: (any Error).self) { try store.loadResolved() } + #expect { try store.loadResolved() } throws: { error in + if json == "{broken" { + let error = error as NSError + return error.domain == NSCocoaErrorDomain && error.code == 3840 + } + return error as? CoreError + == .invalidState( + "transaction journal was written by another version; recover it with the version that wrote it (journal version: missing)" + ) + } #expect(try Data(contentsOf: store.resolvedURL) == before) #expect(try Data(contentsOf: journal) == Data(json.utf8)) } @@ -216,20 +224,15 @@ extension StateTransactionTests { extension StateTransactionTests { private func waitFor(_ marker: String, root: URL, child: Process) throws { - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: root.appendingPathComponent(marker).path), - Date() < deadline, child.isRunning - { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: root.appendingPathComponent(marker).path)) + try ProcessWait.marker(root.appendingPathComponent(marker), child: child, root: root) } private func abandon( - _ fixture: TransactionFixture, at step: String = "replace.2", scope: InstallScope = .project + _ fixture: TransactionFixture, at step: String = "entry.2.applied", + scope: InstallScope = .project ) throws { let child = try stateTestProcess( - root: fixture.root, arguments: ["crash", step, scope.rawValue]) + root: fixture.root, arguments: ["crash", step, "--scope", scope.rawValue]) defer { if child.isRunning { kill(child.processIdentifier, SIGKILL) @@ -255,11 +258,12 @@ extension StateTransactionTests { let target = AgentRegistry.installSkillsDirectory( for: .claudeCode, scope: scope, environment: environment ).appendingPathComponent("created") - try abandon(fixture, at: "replace.4", scope: scope) + try abandon(fixture, at: "entry.4.applied", scope: scope) try #require(FileManager.default.fileExists(atPath: target.path)) let recovery = try stateTestProcess( - root: fixture.root, arguments: ["recover", "restore.4.remove.unlinked", scope.rawValue]) + root: fixture.root, + arguments: ["recover", "restore.4.creationQuarantined", "--scope", scope.rawValue]) defer { if recovery.isRunning { kill(recovery.processIdentifier, SIGKILL) @@ -277,10 +281,10 @@ extension StateTransactionTests { let recovered = try FileTransaction.recover(store: store) { steps.append($0) } #expect(recovered) } - #expect(!steps.contains("restore.4.remove.unlinked")) - let synced = try #require(steps.firstIndex(of: "restore.4.remove.synced")) - let terminal = try #require(steps.firstIndex(of: "journal.rolledBack.renamed")) - let cleanup = try #require(steps.firstIndex(of: "journal.terminalSynced")) + #expect(!steps.contains("restore.4.creationQuarantined")) + let synced = try #require(steps.firstIndex(of: "restore.4.synced")) + let terminal = try #require(steps.firstIndex(of: "journal.rolledBack.terminal.renamed")) + let cleanup = try #require(steps.firstIndex(of: "cleanup.intent")) #expect(synced < terminal && terminal < cleanup) #expect(try Data(contentsOf: store.declarationURL) == declaration) #expect(try Data(contentsOf: store.resolvedURL) == resolved) @@ -296,8 +300,9 @@ extension StateTransactionTests { } @Test(arguments: [ - "restore.2.renamed", "restore.0", "journal.rolledBack.renamed", "journal.terminalSynced", - "cleanup.0", + "restore.2.exchanged", "entry.0.restored", "journal.rolledBack.terminal.renamed", + "journal.rolledBack", + "cleanup.0.removed", ]) func interruptedRecoverySerializesCompetingReader(_ point: String) throws { let fixture = try TransactionFixture() @@ -330,10 +335,10 @@ extension StateTransactionTests { try fixture.check(committed: false) } - @Test(arguments: ["journal.terminalSynced", "cleanup.0"]) + @Test(arguments: ["journal.terminalSynced", "cleanup.0.removed"]) func committedRecoverySyncsObservedMarkerBeforeCleanup(_ point: String) throws { let fixture = try TransactionFixture() - try abandon(fixture, at: "journal.committed.renamed") + try abandon(fixture, at: "journal.committed.terminal.renamed") let recovery = try stateTestProcess(root: fixture.root, arguments: ["recover", point]) defer { if recovery.isRunning { @@ -345,7 +350,7 @@ extension StateTransactionTests { if point == "journal.terminalSynced" { let names = try FileManager.default.contentsOfDirectory( atPath: fixture.root.appendingPathComponent(".agents/skills").path) - #expect(names.contains { $0.hasSuffix(".old") }) + #expect(names.contains { $0.hasPrefix(".agents-") }) } kill(recovery.processIdentifier, SIGKILL) recovery.waitUntilExit() @@ -360,7 +365,7 @@ extension StateTransactionTests { try abandon(fixture) let journalURL = fixture.store.directory.appendingPathComponent("transaction.json") let original = try Data(contentsOf: journalURL) - let before = try FileHash.folderHash(fixture.root) + let before = try FileSnapshot.read(at: fixture.root) let victim = fixture.root.appendingPathComponent("Documents/victim") try FileManager.default.createDirectory(at: victim, withIntermediateDirectories: true) try Data("keep".utf8).write(to: victim.appendingPathComponent("sentinel")) @@ -376,28 +381,43 @@ extension StateTransactionTests { json["entries"] = entries let bytes = try JSONSerialization.data(withJSONObject: json, options: [.sortedKeys]) try bytes.write(to: journalURL) - let snapshot = try FileHash.folderHash(fixture.root) - #expect(throws: (any Error).self) { try fixture.store.loadResolved() } - #expect(try FileHash.folderHash(fixture.root) == snapshot) + let snapshot = try FileSnapshot.read(at: fixture.root) + let expected: CoreError + if path.contains("..") || path.hasPrefix("/") || path.hasPrefix("file://") { + expected = .invalidState("invalid scope-relative transaction path") + } else if path.hasPrefix("state/") { + expected = .unsafePath("unmanaged state transaction path") + } else { + expected = .unsafePath("unmanaged installation transaction path") + } + #expect(throws: expected) { try fixture.store.loadResolved() } + #expect(try FileSnapshot.read(at: fixture.root) == snapshot) } var directories = try #require(JSONSerialization.jsonObject(with: original) as? [String: Any]) directories["directories"] = [victim.absoluteString] try JSONSerialization.data(withJSONObject: directories).write(to: journalURL) - let directorySnapshot = try FileHash.folderHash(fixture.root) - #expect(throws: (any Error).self) { try fixture.store.loadResolved() } - #expect(try FileHash.folderHash(fixture.root) == directorySnapshot) + let directorySnapshot = try FileSnapshot.read(at: fixture.root) + #expect { try fixture.store.loadResolved() } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("unknown state field: directories") + } + #expect(try FileSnapshot.read(at: fixture.root) == directorySnapshot) // The absolute-parent counterexample is rejected as a foreign schema, too. let forged = #"{"id":"00000000-0000-0000-0000-000000000000","phase":"applying","entries":[{"parent":""# + victim.deletingLastPathComponent().absoluteString + #"","name":"victim","existed":false,"replacement":false}],"directories":[]}"# try Data(forged.utf8).write(to: journalURL) - #expect(throws: (any Error).self) { try fixture.store.loadResolved() } + #expect( + throws: CoreError.invalidState( + "transaction journal was written by another version; recover it with the version that wrote it (journal version: missing)" + ) + ) { try fixture.store.loadResolved() } #expect( try String(contentsOf: victim.appendingPathComponent("sentinel"), encoding: .utf8) == "keep") try FileManager.default.removeItem(at: victim.deletingLastPathComponent()) try original.write(to: journalURL) - #expect(try FileHash.folderHash(fixture.root) == before) + #expect(try FileSnapshot.read(at: fixture.root) == before) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { try fixture.store.loadResolved() } @@ -410,17 +430,22 @@ extension StateTransactionTests { try FileManager.default.createDirectory(at: pin, withIntermediateDirectories: true) try Data("keep".utf8).write(to: pin.appendingPathComponent("sentinel")) let url = fixture.store.directory.appendingPathComponent("transaction.json") - var journal = try #require( - JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) - var entries = try #require(journal["entries"] as? [[String: Any]]) + var journal = try StateStore.decode(Data(contentsOf: url), as: TransactionJournal.self) for path in ["state/cache/materialized/source", "state/cache/materialized/source/pin"] { - entries.append(["path": path, "existed": false, "replacement": false]) + let target = fixture.store.directory.appendingPathComponent(String(path.dropFirst(6))) + let parent = try DirectoryHandle(at: target.deletingLastPathComponent()) + journal.entries.append( + .init( + path: path, action: .delete, preimage: try FileSnapshot.read(at: target), + parentIdentity: try parent.identity, container: 0, progress: .ready)) + } + try StateStore.encode(journal).write(to: url) + let before = try FileSnapshot.read(at: fixture.root) + #expect { try fixture.store.loadResolved() } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("state/cache/materialized/source/pin: overlapping destinations") } - journal["entries"] = entries - try JSONSerialization.data(withJSONObject: journal).write(to: url) - let before = try FileHash.folderHash(fixture.root) - #expect(throws: (any Error).self) { try fixture.store.loadResolved() } - #expect(try FileHash.folderHash(fixture.root) == before) + #expect(try FileSnapshot.read(at: fixture.root) == before) } @Test func rejectsCopiedJournalWithoutTouchingEitherLocation() throws { @@ -430,12 +455,14 @@ extension StateTransactionTests { defer { removeTemporaryDirectory(container) } let copy = container.appendingPathComponent("copy") try FileManager.default.copyItem(at: fixture.root, to: copy) - let originalHash = try FileHash.folderHash(fixture.root) - let copyHash = try FileHash.folderHash(copy) + let originalHash = try FileSnapshot.read(at: fixture.root) + let copyHash = try FileSnapshot.read(at: copy) let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: copy)) - #expect(throws: (any Error).self) { try store.loadDeclaration() } - #expect(try FileHash.folderHash(fixture.root) == originalHash) - #expect(try FileHash.folderHash(copy) == copyHash) + #expect(throws: CoreError.invalidState("transaction root identity changed")) { + try store.loadDeclaration() + } + #expect(try FileSnapshot.read(at: fixture.root) == originalHash) + #expect(try FileSnapshot.read(at: copy) == copyHash) } @Test(arguments: ["journal", "scratch", "cache", "agent"]) @@ -454,9 +481,16 @@ extension StateTransactionTests { let external = fixture.root.appendingPathComponent("external") try FileManager.default.moveItem(at: original, to: external) try FileManager.default.createSymbolicLink(at: original, withDestinationURL: external) - let snapshot = try FileHash.folderHash(fixture.root) - #expect(throws: (any Error).self) { try fixture.store.loadResolved() } - #expect(try FileHash.folderHash(fixture.root) == snapshot) + let snapshot = try FileSnapshot.read(at: fixture.root) + #expect { try fixture.store.loadResolved() } throws: { error in + if component == "agent" { + return error as? CoreError == .invalidState("transaction root identity changed") + } + guard case CoreError.unsafePath(let reason) = error else { return false } + return reason.contains( + component == "journal" || component == "scratch" ? "cannot open file" : "unsafe directory") + } + #expect(try FileSnapshot.read(at: fixture.root) == snapshot) } @Test func journalEncodingAndDuplicateKeysCannotBypassRecoveryValidation() throws { @@ -474,15 +508,24 @@ extension StateTransactionTests { text.data(using: .utf16BigEndian)!, text.data(using: .utf32)!, Data(text.utf8) + Data(" {}".utf8), ] - for bytes in encodings { + for (index, bytes) in encodings.enumerated() { try bytes.write(to: url) - let snapshot = try FileHash.folderHash(fixture.root) - #expect(throws: (any Error).self) { try fixture.store.loadResolved() } - #expect(try FileHash.folderHash(fixture.root) == snapshot) + let snapshot = try FileSnapshot.read(at: fixture.root) + #expect { try fixture.store.loadResolved() } throws: { error in + if index < 4 { + return error as? CoreError + == .invalidState("JSON must be UTF-8 without a byte order mark") + } + let error = error as NSError + return error.domain == NSCocoaErrorDomain && error.code == 3840 + } + #expect(try FileSnapshot.read(at: fixture.root) == snapshot) } } try Data(duplicate.utf8).write(to: url) - #expect(throws: (any Error).self) { try fixture.store.loadResolved() } + #expect(throws: CoreError.invalidState("duplicate JSON key: phase")) { + try fixture.store.loadResolved() + } try original.write(to: url) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { try fixture.store.loadResolved() @@ -546,10 +589,10 @@ extension StateTransactionTests { try Data("original".utf8).write(to: target.appendingPathComponent("SKILL.md")) } let before = try Data(contentsOf: store.resolvedURL) - #expect(throws: CoreError.self) { + #expect(throws: CoreError.invalidState("interrupted user write")) { try store.withLock { let transaction = FileTransaction(store: store) { step in - if step == "replace.3.renamed" { + if step == "publish.3.exchanged" { let journal = try String( contentsOf: store.directory.appendingPathComponent("transaction.json"), encoding: .utf8) diff --git a/Tests/AgentsCoreTests/TransactionCostTests.swift b/Tests/AgentsCoreTests/TransactionCostTests.swift new file mode 100644 index 0000000..6bfd23d --- /dev/null +++ b/Tests/AgentsCoreTests/TransactionCostTests.swift @@ -0,0 +1,67 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Transaction I/O cost") +struct TransactionCostTests { + @Test(arguments: [false, true]) + func twoSmallFiles(_ coldDevice: Bool) throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment(projectDirectory: root, homeDirectory: root, environment: [:]) + ) + try store.save(declaration: Declaration(), resolved: ResolvedState()) + let targets = ["AGENTS.md", "GEMINI.md"].map { root.appendingPathComponent($0) } + for target in targets { try Data("before".utf8).write(to: target) } + let count = TransactionIOCount() + try store.withLock { + let transaction = FileTransaction(store: store) { step in + if step.hasPrefix("journal."), step.hasSuffix(".renamed") { count.persist() } + if step.hasPrefix("directory.synced.") { count.ancestor() } + } + for target in targets { + try transaction.replace(target, content: nil, data: Data("after".utf8)) + } + try DirectoryHandle.$synchronizationObserver.withValue({ count.sync() }) { + if coldDevice { + try DirectoryHandle.$atomicRenameFailure.withValue({ _ in nil }) { + try transaction.commit() + } + } else { + try transaction.commit() + } + } + } + print( + "TWO_SMALL_FILES cold=\(coldDevice) persists=\(count.persists) barriers=\(count.barriers) ancestry=\(count.ancestors)" + ) + #expect(count.persists == 10) + #expect(count.barriers - count.ancestors == (coldDevice ? 38 : 36)) + for target in targets { #expect(try Data(contentsOf: target) == Data("after".utf8)) } + } +} + +private final class TransactionIOCount: @unchecked Sendable { + private let lock = NSLock() + private(set) var persists = 0 + private(set) var barriers = 0 + private(set) var ancestors = 0 + func ancestor() { + lock.lock() + defer { lock.unlock() } + ancestors += 1 + } + func persist() { + lock.lock() + defer { lock.unlock() } + persists += 1 + } + func sync() { + lock.lock() + defer { lock.unlock() } + barriers += 1 + } +} diff --git a/Tests/AgentsCoreTests/TransactionMetadataTests.swift b/Tests/AgentsCoreTests/TransactionMetadataTests.swift index dcc9c93..4e89ab4 100644 --- a/Tests/AgentsCoreTests/TransactionMetadataTests.swift +++ b/Tests/AgentsCoreTests/TransactionMetadataTests.swift @@ -1,12 +1,13 @@ import CPlatform import Foundation +import StateTestSupport import Testing @testable import AgentsCore @Suite("Transaction metadata") struct TransactionMetadataTests { - @Test(arguments: ["complete", "journal.applying", "replace.1", "journal.committed"]) + @Test(arguments: ["complete", "entry.0.publishing", "entry.1.applied", "journal.committed"]) func dataReplacementPreservesPermissionsACLsAndExtendedAttributes(_ point: String) throws { let fixture = try TransactionFixture() let target = fixture.root.appendingPathComponent("AGENTS.md") @@ -29,7 +30,7 @@ struct TransactionMetadataTests { if point == "complete" { try transaction.commit() } else { - #expect(throws: CoreError.self) { try transaction.commit() } + #expect(throws: CoreError.invalidState("injected failure")) { try transaction.commit() } } } let committed = point == "complete" || point == "journal.committed" @@ -47,10 +48,10 @@ struct TransactionMetadataTests { try expectRecoveryMaterialRemoved(fixture) } - @Test(arguments: ["complete", "journal.committed", "cleanup.0"]) + @Test(arguments: ["complete", "journal.committed", "cleanup.0.removed"]) func committedCleanupDiscardsReadOnlyDirectories(_ point: String) throws { let fixture = try TransactionFixture() - defer { makeWritableForTeardown(fixture.root) } + defer { makeDirectoriesWritable(fixture.root) } let target = fixture.root.appendingPathComponent(".agents/skills/target") let source = fixture.root.appendingPathComponent("new") let targets = try makeReadOnlyTree(target) @@ -76,10 +77,12 @@ struct TransactionMetadataTests { try expectRecoveryMaterialRemoved(fixture) } - @Test(arguments: ["restore.3.renamed", "restore.0.renamed", "journal.rolledBack.renamed"]) + @Test(arguments: [ + "restore.3.returned", "restore.0.exchanged", "journal.rolledBack.terminal.renamed", + ]) func interruptedRollbackPreservesReadOnlyMetadata(_ point: String) throws { let fixture = try TransactionFixture() - defer { makeWritableForTeardown(fixture.root) } + defer { makeDirectoriesWritable(fixture.root) } let target = fixture.root.appendingPathComponent(".agents/skills/target") let pruned = fixture.store.cacheDirectory.appendingPathComponent("artifact-content/pruned") let originals = try makeReadOnlyTree(target) + makeReadOnlyTree(pruned) @@ -89,7 +92,7 @@ struct TransactionMetadataTests { let declaration = try Data(contentsOf: fixture.store.declarationURL) let resolved = try Data(contentsOf: fixture.store.resolvedURL) - try interrupt(fixture, command: "crash", at: "replace.4") + try interrupt(fixture, command: "crash", at: "entry.4.applied") try interrupt(fixture, command: "recover", at: point) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { try fixture.store.loadResolved() @@ -103,7 +106,7 @@ struct TransactionMetadataTests { try expectRecoveryMaterialRemoved(fixture) } - @Test(arguments: ["journal.applying", "replace.0", "replace.2"]) + @Test(arguments: ["entry.0.publishing", "entry.0.applied", "entry.2.applied"]) func rollbackPreservesPermissionsACLsAndExtendedAttributes(_ point: String) throws { let fixture = try TransactionFixture() let target = fixture.root.appendingPathComponent(".agents/skills/target") @@ -119,7 +122,7 @@ struct TransactionMetadataTests { } let before = try urls.map(metadata) let bytes = try FileHash.folderHash(target) - #expect(throws: CoreError.self) { + #expect(throws: CoreError.invalidState("injected failure")) { try fixture.commit { step in if step == point { throw CoreError.invalidState("injected failure") } } @@ -153,11 +156,7 @@ struct TransactionMetadataTests { } let marker = fixture.root.appendingPathComponent( command == "recover" ? "recovery-ready" : "ready") - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: marker.path), Date() < deadline, child.isRunning { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: marker.path)) + try ProcessWait.marker(marker, child: child, root: fixture.root) kill(child.processIdentifier, SIGKILL) child.waitUntilExit() #expect(child.terminationReason == .uncaughtSignal) @@ -175,19 +174,6 @@ struct TransactionMetadataTests { }) } - private func makeWritableForTeardown(_ root: URL) { - guard let entries = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil) - else { - return - } - for case let entry as URL in entries { - var info = stat() - if lstat(entry.path, &info) == 0, info.st_mode & S_IFMT == S_IFDIR { - _ = chmod(entry.path, (info.st_mode & 0o7777) | S_IRWXU) - } - } - } - private func metadata(_ url: URL) throws -> FixtureMetadata { try fixtureMetadata(url) } diff --git a/Tests/AgentsCoreTests/WatchDurabilityTests.swift b/Tests/AgentsCoreTests/WatchDurabilityTests.swift index 5aaa87a..a9d6271 100644 --- a/Tests/AgentsCoreTests/WatchDurabilityTests.swift +++ b/Tests/AgentsCoreTests/WatchDurabilityTests.swift @@ -1,6 +1,7 @@ import AgentsCore import CPlatform import Foundation +import StateTestSupport import Testing @Suite("Watch Git durability") @@ -10,8 +11,8 @@ struct WatchDurabilityTests { [ "watch.mirror.fetched", "watch.references.pending", "watch.objects.synced", "watch.ref.updated", "watch.ref.synced", - "watch.mirror.synced", "journal.applying", "replace.0.renamed", - "journal.committed.renamed", "journal.committed", "journal.removed", + "watch.mirror.synced", "entry.0.publishing", "publish.0.exchanged", + "journal.committed.terminal.renamed", "journal.committed", "journal.removed", ]) func interruptedAcknowledgmentRetainsTheRecoveredBaseline(_ advancing: Bool, _ step: String) throws @@ -236,11 +237,7 @@ final class WatchGitFixture { } } let marker = root.appendingPathComponent("ready") - let deadline = Date().addingTimeInterval(30) - while !FileManager.default.fileExists(atPath: marker.path), child.isRunning, Date() < deadline { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: marker.path), "did not reach \(step)") + try ProcessWait.marker(marker, child: child, root: root) #expect(try String(contentsOf: marker, encoding: .utf8) == step) CPlatform.kill(child.processIdentifier, SIGKILL) child.waitUntilExit() diff --git a/Tests/AgentsCoreTests/WatchGitLockTests.swift b/Tests/AgentsCoreTests/WatchGitLockTests.swift index 279cc9b..9dac569 100644 --- a/Tests/AgentsCoreTests/WatchGitLockTests.swift +++ b/Tests/AgentsCoreTests/WatchGitLockTests.swift @@ -1,6 +1,7 @@ import AgentsCore import CPlatform import Foundation +import StateTestSupport import Testing @Suite("Watch Git lock recovery") @@ -151,12 +152,7 @@ struct WatchGitLockTests { } private func waitFor(_ marker: URL, process: Process) throws { - let deadline = Date().addingTimeInterval(30) - while !FileManager.default.fileExists(atPath: marker.path), process.isRunning, Date() < deadline - { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: marker.path)) + try ProcessWait.marker(marker, child: process, root: marker.deletingLastPathComponent()) } private func terminate(_ process: Process) { diff --git a/Tests/AgentsCoreTests/WatchInspectionTests.swift b/Tests/AgentsCoreTests/WatchInspectionTests.swift index 078be13..74cf813 100644 --- a/Tests/AgentsCoreTests/WatchInspectionTests.swift +++ b/Tests/AgentsCoreTests/WatchInspectionTests.swift @@ -4,7 +4,7 @@ import Testing @Suite("Read-only watch inspection") struct WatchInspectionTests { - @Test(arguments: ["replace.0.renamed", "journal.committed"]) + @Test(arguments: ["publish.0.exchanged", "journal.committed"]) func pendingTransactionLeavesStateUnchanged(_ step: String) throws { let fixture = try WatchGitFixture() try fixture.watch.add("source", environment: fixture.environment) diff --git a/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift b/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift index 04bd666..f9e2790 100644 --- a/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift +++ b/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift @@ -42,7 +42,7 @@ struct WatchMirrorConcurrencyTests { #expect(currentLocks == locks) // Recovery and re-acknowledgment must follow the surviving Git child's completion. - try finishProcesses([acknowledger], resuming: pause) + try finishProcesses([acknowledger], root: fixture.root, resuming: pause) #expect(try fixture.store.loadWatch().sources[fixture.id]?.seen == .revision(first)) #expect(try fixture.watchRefs() == [first]) #expect(try gitLocks(fixture).isEmpty) @@ -60,7 +60,7 @@ struct WatchMirrorConcurrencyTests { if existingMirror { let listing = try stateTestProcess(root: fixture.root, arguments: ["instruction-list", ""]) defer { terminateProcess(listing) } - try finishProcesses([listing]) + try finishProcesses([listing], root: fixture.root) try #require(exists(fixture.mirror)) try #require(!exists(scopeLock)) try FileManager.default.removeItem( @@ -93,7 +93,7 @@ struct WatchMirrorConcurrencyTests { #expect(!exists(fixture.store.watchURL)) #expect(!exists(fixture.root.appendingPathComponent("writer-finished"))) - try finishProcesses([listing, writer], resuming: pause) + try finishProcesses([listing, writer], root: fixture.root, resuming: pause) #expect( try String( contentsOf: fixture.root.appendingPathComponent("listing-finished"), encoding: .utf8) diff --git a/Tests/AgentsCoreTests/WatchReferenceTests.swift b/Tests/AgentsCoreTests/WatchReferenceTests.swift index 3735a04..4d6838c 100644 --- a/Tests/AgentsCoreTests/WatchReferenceTests.swift +++ b/Tests/AgentsCoreTests/WatchReferenceTests.swift @@ -48,8 +48,8 @@ struct WatchReferenceTests { try fixture.rewrite("replacement") let replacement = try fixture.head() let writer = try stateTestProcess( - root: fixture.root, arguments: ["watch-seen", "replace.0.renamed"]) - try fixture.kill(writer, at: "replace.0.renamed") + root: fixture.root, arguments: ["watch-seen", "publish.0.exchanged"]) + try fixture.kill(writer, at: "publish.0.exchanged") #expect(try fixture.watchRefs() == [first, replacement]) let recovery = try stateTestProcess( root: fixture.root, arguments: ["watch-recover", "watch.references.deleted"]) diff --git a/Tests/AgentsCoreTests/WatchStateTests.swift b/Tests/AgentsCoreTests/WatchStateTests.swift index ba320c3..0319960 100644 --- a/Tests/AgentsCoreTests/WatchStateTests.swift +++ b/Tests/AgentsCoreTests/WatchStateTests.swift @@ -1,6 +1,7 @@ import AgentsCore import CPlatform import Foundation +import StateTestSupport import Testing @Suite("Watch state") @@ -109,7 +110,9 @@ struct WatchStateTests { #expect(throws: CoreError.self) { try declaration.validate(environment: environment) } } - @Test(arguments: ["replace.0.renamed", "replace.1.renamed", "journal.committed", "cleanup.0"]) + @Test(arguments: [ + "publish.0.exchanged", "publish.1.exchanged", "journal.committed", "cleanup.0.removed", + ]) func interruptedWatchAndDeclarationRecoverTogether(_ checkpoint: String) throws { let root = try temporaryDirectory() defer { try? FileManager.default.removeItem(at: root) } @@ -131,15 +134,11 @@ struct WatchStateTests { } } let marker = root.appendingPathComponent("ready") - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: marker.path), child.isRunning, Date() < deadline { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: marker.path)) + try ProcessWait.marker(marker, child: child, root: root) kill(child.processIdentifier, SIGKILL) child.waitUntilExit() #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.loadWatch() } - let committed = checkpoint == "journal.committed" || checkpoint == "cleanup.0" + let committed = checkpoint == "journal.committed" || checkpoint == "cleanup.0.removed" #expect(try store.loadDeclaration().watch == (committed ? ["source"] : nil)) #expect(try store.loadWatch().sources.isEmpty == !committed) #expect(try Data(contentsOf: store.resolvedURL) == lockBytes) diff --git a/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift b/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift index b20303f..555768d 100644 --- a/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift @@ -24,11 +24,11 @@ struct InstructionDoctorTests { let before = try fixture.snapshot() let report = try InstructionOperations.doctor( scope: pendingScope, environment: fixture.environment) - #expect(report.diagnostics.map(\.kind) == [.pendingRecovery]) + #expect(report.diagnostics.map(\.kind) == [.unresolvedTransaction]) #expect(report.diagnostics.first?.path == pending.directory) let healthy = try InstructionOperations.doctor( scope: healthyScope, environment: fixture.environment) - #expect(healthy.diagnostics.filter { $0.kind == .pendingRecovery }.count == 1) + #expect(healthy.diagnostics.filter { $0.kind == .unresolvedTransaction }.count == 1) #expect(healthy.diagnostics.contains { $0.kind == .missingTarget && $0.path == healthyFile }) #expect(!healthy.diagnostics.contains { $0.kind == .duplicateScope }) #expect(try fixture.snapshot() == before) @@ -180,7 +180,7 @@ struct InstructionDoctorTests { projectRoots: [fixture.project, empty, pending], environment: fixture.environment) #expect(reports.count == 3) #expect(reports[0].diagnostics.contains { $0.kind == .missingTarget }) - #expect(reports[2].diagnostics.map(\.kind) == [.pendingRecovery]) + #expect(reports[2].diagnostics.map(\.kind) == [.unresolvedTransaction]) #expect(try fixture.snapshot() == before) #expect(!FileManager.default.fileExists(atPath: empty.appendingPathComponent(".agent").path)) #expect( diff --git a/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift b/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift index 7bb3fdf..d5a16b2 100644 --- a/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift +++ b/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift @@ -1,6 +1,7 @@ import AgentsCore import CPlatform import Foundation +import StateTestSupport import Testing @Suite("Automatic add selection") @@ -147,9 +148,9 @@ struct AutomaticSelectionTests { } private func wait(for process: Process, until ready: () -> Bool) throws { - let deadline = Date().addingTimeInterval(20) - while !ready(), process.isRunning, Date() < deadline { Thread.sleep(forTimeInterval: 0.01) } - try #require(ready()) + try ProcessWait.condition( + process, root: URL(fileURLWithPath: process.arguments![0]), + description: "automatic selection handshake", ready: ready) } } diff --git a/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift b/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift index 7f52db1..7180a42 100644 --- a/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift @@ -1,6 +1,7 @@ import AgentsCore import CPlatform import Foundation +import StateTestSupport import Testing @testable import AgentsSkills @@ -182,11 +183,7 @@ extension LockedArtifactLifecycleTests { } } let marker = project.appendingPathComponent("ready") - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: marker.path), child.isRunning, Date() < deadline { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: marker.path)) + try ProcessWait.marker(marker, child: child, root: fixture.root) let final = store.cacheDirectory.appendingPathComponent( "artifact-content/" + digest.dropFirst(7)) #expect(!FileManager.default.fileExists(atPath: final.path)) @@ -220,7 +217,9 @@ extension LockedArtifactLifecycleTests { } let process = Process() process.executableURL = directory.appendingPathComponent("StateTestProcess") - process.arguments = [root.path, "cache-content", "stage.0.copy.entry"] + process.arguments = [ + root.path, "cache-content", "stage.0.copy.entry.0.staged/SKILL.md.entryCopied", + ] try process.run() return process } diff --git a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift index a3419db..0dde41b 100644 --- a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift +++ b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift @@ -3,6 +3,7 @@ import AgentsInstructions import AgentsSkills import CPlatform import Foundation +import StateTestSupport import Testing @Suite("Read-only skill inspection") @@ -103,11 +104,7 @@ struct ReadOnlyInspectionTests { } } let marker = root.appendingPathComponent("ready") - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: marker.path), child.isRunning, Date() < deadline { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: marker.path)) + try ProcessWait.marker(marker, child: child, root: root) kill(child.processIdentifier, SIGKILL) child.waitUntilExit() #expect(!FileManager.default.fileExists(atPath: instructions.path)) @@ -424,7 +421,9 @@ struct ReadOnlyInspectionTests { } let process = Process() process.executableURL = directory.appendingPathComponent("StateTestProcess") - process.arguments = [root.path, "inspection-transaction", "replace.4", scope.rawValue] + process.arguments = [ + root.path, "inspection-transaction", "entry.4.applied", "--scope", scope.rawValue, + ] try process.run() return process } diff --git a/Tests/AgentsSkillsTests/TransactionDoctorTests.swift b/Tests/AgentsSkillsTests/TransactionDoctorTests.swift new file mode 100644 index 0000000..c78bc20 --- /dev/null +++ b/Tests/AgentsSkillsTests/TransactionDoctorTests.swift @@ -0,0 +1,101 @@ +import AgentsInstructions +import AgentsSkills +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Transaction conflict diagnostics") +struct TransactionDoctorTests { + @Test func bothDoctorsReportOwnerActionAndPreservedLocationsWithoutReplay() throws { + let fixture = try SkillFixture() + let store = fixture.store() + try store.save(declaration: Declaration(), resolved: ResolvedState()) + let target = fixture.environment.projectDirectory.appendingPathComponent("AGENTS.md") + try Data("original".utf8).write(to: target) + let saved = fixture.root.appendingPathComponent("saved-original") + #expect(throws: CoreError.invalidState("interrupt after removing preimage")) { + try store.withLock { + let transaction = FileTransaction(store: store) { point in + if point == "entry.0.applied" { + let journal = try StateStore.decode( + Data(contentsOf: store.directory.appendingPathComponent("transaction.json")), + as: TransactionJournal.self) + let backup = target.deletingLastPathComponent().appendingPathComponent( + journal.containerName(0) + ).appendingPathComponent("entry.0.staged") + try FileManager.default.moveItem(at: backup, to: saved) + throw CoreError.invalidState("interrupt after removing preimage") + } + } + try transaction.replace(target, content: nil, data: Data("published".utf8)) + try transaction.commit() + } + } + let before = try FileSnapshot.read(at: fixture.root) + let skills = try SkillOperations.doctor(environment: fixture.environment) + #expect(skills.checks.map(\.id) == ["unresolved-transaction"]) + let instructions = try InstructionOperations.doctor(environment: fixture.environment) + #expect(instructions.diagnostics.map(\.kind) == [.unresolvedTransaction]) + for message in skills.checks.map(\.message) + instructions.diagnostics.map(\.message) { + #expect(message.contains("owner action is required")) + #expect(message.contains("preimage")) + #expect(message.contains("instructions-project/AGENTS.md")) + #expect(message.contains(".agents-")) + } + #expect(try FileSnapshot.read(at: fixture.root) == before) + } + + @Test func equalBytesInAnotherTargetDescendantInvalidatePreparation() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "original") + try fixture.commit() + _ = try fixture.add(mode: .copy) + let target = fixture.target("demo").appendingPathComponent("SKILL.md") + let state = try FileSnapshot.read(at: fixture.store().resolvedURL) + var replacement: FileSnapshot? + #expect { + try SkillOperations.updateInstalled( + environment: fixture.environment, apply: true, + beforeApply: { _ in + let bytes = try Data(contentsOf: target) + try bytes.write(to: target, options: .atomic) + replacement = try FileSnapshot.read(at: target) + }) + } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("target changed during preparation") + } + #expect(replacement != nil) + #expect(try FileSnapshot.read(at: target) == replacement) + #expect(try FileSnapshot.read(at: fixture.store().resolvedURL) == state) + } + + @Test func instructionCallbackCannotReplacePreparedInodeWithEqualBytes() throws { + let fixture = try SkillFixture() + let root = fixture.environment.projectDirectory + let own = root.appendingPathComponent(".agent/instructions") + try FileManager.default.createDirectory(at: own, withIntermediateDirectories: true) + try Data("---\ndescription: Rules\n---\n\n# Rules\n\nOriginal\n".utf8) + .write(to: own.appendingPathComponent("rules.md")) + _ = try InstructionOperations.add( + InstructionAddOptions( + source: ".", names: ["rules"], agents: [.codex], + environment: fixture.environment)) + let target = root.appendingPathComponent("AGENTS.md") + let state = try FileSnapshot.read(at: fixture.store().resolvedURL) + var external: FileSnapshot? + #expect { + try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) { + _ in + try Data(contentsOf: target).write(to: target, options: .atomic) + external = try FileSnapshot.read(at: target) + } + } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("path changed during preparation") + } + #expect(try FileSnapshot.read(at: target) == external) + #expect(try FileSnapshot.read(at: fixture.store().resolvedURL) == state) + } +} diff --git a/Tests/AgentsSkillsTests/UpdateReportingTests.swift b/Tests/AgentsSkillsTests/UpdateReportingTests.swift index b7e5bf0..98d8b35 100644 --- a/Tests/AgentsSkillsTests/UpdateReportingTests.swift +++ b/Tests/AgentsSkillsTests/UpdateReportingTests.swift @@ -126,13 +126,15 @@ struct UpdateReportingTests { } else { let retained = try plan.retain() let transaction = FileTransaction(store: store) { step in - if step == "stage.0.ready" { + if step == "stage.0.constructed" { let parent = fixture.target("demo").deletingLastPathComponent() let staged = try #require( FileManager.default.contentsOfDirectory( at: parent, includingPropertiesForKeys: nil - ).first { $0.lastPathComponent.hasSuffix(".new") }) + ).first { $0.lastPathComponent.hasPrefix(".agents-") } + ) + .appendingPathComponent("entry.0.staged") try FileManager.default.setAttributes( [.posixPermissions: 0o755], ofItemAtPath: staged.appendingPathComponent("SKILL.md").path) diff --git a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift index c55bffc..cc43566 100644 --- a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift +++ b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift @@ -180,8 +180,8 @@ struct CombinedUpdateTests { environment: fixture.environment, checkpoint: { step in // Pruning is queued after both kinds and the merged state; rollback restores it too. - if step == "journal.committed.renamed" { return } - if step.hasPrefix("replace."), !step.hasSuffix(".renamed"), + if step == "journal.committed.terminal.renamed" { return } + if step.hasPrefix("entry."), step.hasSuffix(".applied"), !FileManager.default.fileExists(atPath: unused.path) { throw CoreError.invalidState("pruning interrupted") @@ -335,7 +335,7 @@ struct CombinedUpdateTests { try UpdateOperations.withPreparedUpdate( environment: fixture.environment, checkpoint: { step in - if step == "stage.0.ready" { + if step == "stage.0.constructed" { let file = cache.appendingPathComponent("skills/demo/run.sh") if dimension == "bytes" { try fixture.write("corrupt", to: file) diff --git a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift index 87fbc57..3d8f61f 100644 --- a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift +++ b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift @@ -2,6 +2,7 @@ import AgentsCore import AgentsSkills import CPlatform import Foundation +import StateTestSupport import Testing @testable import AgentsUpdates @@ -19,7 +20,7 @@ struct UpdateTransactionTests { _ = try UpdateOperations.withPreparedUpdate( environment: fixture.environment, checkpoint: { step in - if step == "replace.0" { + if step == "entry.0.applied" { // Exchange a journal-bound root so every automatic recovery attempt must stop. try FileManager.default.moveItem(at: root, to: moved) try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) @@ -34,8 +35,10 @@ struct UpdateTransactionTests { let journal = fixture.store.directory.appendingPathComponent("transaction.json") #expect(FileManager.default.fileExists(atPath: journal.path)) let retained = try FileManager.default.contentsOfDirectory(atPath: moved.path) - #expect(retained.contains { $0.hasSuffix(".old") }) - #expect(throws: CoreError.self) { try fixture.store.loadResolved() } + #expect(retained.contains { $0.hasPrefix(".agents-") }) + #expect(throws: CoreError.invalidState("transaction root identity changed")) { + try fixture.store.loadResolved() + } #expect(try FileManager.default.contentsOfDirectory(atPath: moved.path) == retained) try FileManager.default.removeItem(at: root) try FileManager.default.moveItem(at: moved, to: root) @@ -48,8 +51,9 @@ struct UpdateTransactionTests { } @Test(arguments: [ - "between-kinds", "journal.preparing", "journal.applying.renamed", - "journal.committed.renamed", "journal.committed", "cleanup.0", "journal.removed", + "between-kinds", "journal.preparing", "journal.applying.entry.0.publishing.renamed", + "journal.committed.terminal.renamed", "journal.committed", "cleanup.0.removed", + "journal.removed", ]) func failuresReportTheRecoveredGeneration(_ failure: String) throws { let fixture = try UpdateFixture() @@ -70,7 +74,7 @@ struct UpdateTransactionTests { lastSkill = try lastSkillIndex(fixture.store) } if step == failure - || (failure == "between-kinds" && step == lastSkill.map { "replace.\($0)" }) + || (failure == "between-kinds" && step == lastSkill.map { "entry.\($0).applied" }) { failed = true throw CoreError.invalidState("injected update failure") @@ -80,7 +84,7 @@ struct UpdateTransactionTests { Issue.record("failure checkpoint was not reached") } catch let error as UpdateApplyError { let committed = - failure.hasPrefix("journal.committed") || failure == "cleanup.0" + failure.hasPrefix("journal.committed") || failure == "cleanup.0.removed" || failure == "journal.removed" #expect(error.disposition == (committed ? .committed : .unchanged)) #expect(error.underlyingError as? CoreError == .invalidState("injected update failure")) @@ -98,8 +102,8 @@ struct UpdateTransactionTests { } @Test(arguments: [ - "between-kinds", "journal.preparing", "journal.applying.renamed", - "journal.committed.renamed", "cleanup.0", + "between-kinds", "journal.preparing", "journal.applying.entry.0.publishing.renamed", + "journal.committed.terminal.renamed", "cleanup.0.removed", ]) func killedCombinedWriterRecoversThenPreparesTheWholeUpdate(_ checkpoint: String) throws { let fixture = try UpdateFixture() @@ -110,11 +114,13 @@ struct UpdateTransactionTests { defer { terminate(child) } try waitFor("ready", fixture: fixture, child: child) terminate(child) - #expect(throws: CoreError.self) { try fixture.preview() } + #expect(throws: CoreError.invalidState("transaction recovery is required before inspection")) { + try fixture.preview() + } #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { try fixture.apply() } - let committed = checkpoint.hasPrefix("journal.committed") || checkpoint == "cleanup.0" + let committed = checkpoint.hasPrefix("journal.committed") || checkpoint == "cleanup.0.removed" if !committed { #expect(try fixture.snapshot() == before) } var displayed = 0 _ = try UpdateOperations.withPreparedUpdate(environment: fixture.environment) { update in @@ -200,18 +206,16 @@ private func launch(_ fixture: UpdateFixture, command: String, argument: String) { directory.deleteLastPathComponent() } let process = Process() process.executableURL = directory.appendingPathComponent("StateTestProcess") - process.arguments = [fixture.root.path, command, argument, fixture.store.scope.rawValue] + process.arguments = [ + fixture.root.path, command, argument, "--scope", fixture.store.scope.rawValue, + ] try process.run() return process } private func waitFor(_ name: String, fixture: UpdateFixture, child: Process) throws { let file = fixture.root.appendingPathComponent(name) - let deadline = Date().addingTimeInterval(20) - while !FileManager.default.fileExists(atPath: file.path), Date() < deadline, child.isRunning { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: file.path)) + try ProcessWait.marker(file, child: child, root: fixture.root) } private func terminate(_ process: Process) { diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 67c1f7c..8bd3881 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -4,23 +4,46 @@ import AgentsSkills import AgentsUpdates import CPlatform import Foundation +import Synchronization let arguments = CommandLine.arguments let root = URL(fileURLWithPath: arguments[1]) -let scope: InstallScope = arguments.count > 4 && arguments[4] == "user" ? .user : .project +let scopeIndex = arguments.firstIndex(of: "--scope") +let scope: InstallScope = + scopeIndex.flatMap { InstallScope(rawValue: arguments[$0 + 1]) } ?? .project let store = StateStore( scope: scope, environment: RuntimeEnvironment( projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: ["CLAUDE_CONFIG_DIR": root.appendingPathComponent("configured-claude").path])) +let checkpointState = Mutex( + (requested: arguments.count > 3 ? arguments[3] : "", counts: [String: Int]())) +let traceURL = root.appendingPathComponent( + "checkpoint-\(ProcessInfo.processInfo.processIdentifier).log") +FileManager.default.createFile(atPath: traceURL.path, contents: nil) +let trace = try FileHandle(forWritingTo: traceURL) func stop(_ step: String, marker: String = "ready") throws { - let requested = - (try? String(contentsOf: root.appendingPathComponent("stop-at"), encoding: .utf8)) - ?? arguments[3] - if step == requested { - try Data(step.utf8).write(to: root.appendingPathComponent(marker), options: .atomic) + let normalized = step.replacingOccurrences(of: root.lastPathComponent, with: "$ROOT") + let (point, shouldStop) = checkpointState.withLock { state in + state.counts[normalized, default: 0] += 1 + let count = state.counts[normalized]! + let point = count == 1 ? normalized : normalized + "#\(count)" + return (point, point == state.requested) + } + try trace.write(contentsOf: Data((point + "\n").utf8)) + if step.hasPrefix("journal."), step.hasSuffix(".renamed"), + let bytes = try? Data(contentsOf: store.directory.appendingPathComponent("transaction.json")) + { + try bytes.write(to: root.appendingPathComponent("last-journal")) + } + if shouldStop { + try Data(point.utf8).write(to: root.appendingPathComponent(marker), options: .atomic) raise(SIGSTOP) + // A resumed handshake may select the next stop once, rather than reading on every checkpoint. + let next = + (try? String(contentsOf: root.appendingPathComponent("stop-at"), encoding: .utf8)) ?? "" + checkpointState.withLock { $0.requested = next } } } func signalContention() throws { @@ -150,13 +173,12 @@ if arguments[2] == "git-environment" { } else if arguments[2] == "watch-recover" { try store.withLock(checkpoint: { try stop($0) }, {}) } else if arguments[2] == "publication-recover" { + let outcome = TransactionOutcome() let result: String do { - try store.withLock(checkpoint: { try stop($0, marker: "recovery-ready") }, {}) + try store.withLock(checkpoint: { try stop($0, marker: "recovery-ready") }, outcome: outcome, {}) result = "clean" - } catch CoreError.transactionRecovered { - result = "recovered" - } catch { + } catch CoreError.transactionRecovered { result = "recovered" } catch { result = "unresolved: \(error)" } try Data(result.utf8).write(to: root.appendingPathComponent("recovery-result")) @@ -165,25 +187,29 @@ if arguments[2] == "git-environment" { var failure = "" do { try store.withLock(outcome: outcome) { - let transaction = FileTransaction(store: store, outcome: outcome) { try stop($0) } + let transaction = FileTransaction(store: store, outcome: outcome) { + try Data(String(describing: outcome.disposition).utf8).write( + to: root.appendingPathComponent("stopped-outcome")) + try stop($0) + } try transaction.replace( root.appendingPathComponent("GEMINI.md"), content: nil, data: Data("auxiliary postimage".utf8)) - try transaction.replace( - root.appendingPathComponent("AGENTS.md"), content: nil, - data: arguments[4] == "delete" ? nil : Data("postimage".utf8)) + let target = root.appendingPathComponent("AGENTS.md") + switch arguments[4] { + case "directoryReplace": + let source = root.appendingPathComponent("new") + try transaction.replace( + target, content: source, expectedHash: "sha256:" + FileHash.folderHash(source)) + case "directoryDelete": try transaction.replace(target, content: nil) + case "symlinkCreate": + try transaction.replace(target, content: root.appendingPathComponent("new"), link: true) + default: try transaction.replace(target, content: nil, data: Data("postimage".utf8)) + } try transaction.commit() } - } catch { - failure = String(describing: error) - } - let disposition: String - switch outcome.disposition { - case .unchanged: disposition = "unchanged" - case .committed: disposition = "committed" - case .recoveryRequired: disposition = "unresolved" - } - try Data((disposition + "\n" + failure).utf8).write( + } catch { failure = String(describing: error) } + try Data((String(describing: outcome.disposition) + "\n" + failure).utf8).write( to: root.appendingPathComponent("publication-result")) } else if arguments[2] == "recover" { try FileLock.withLock(at: store.directory.appendingPathComponent(".agents.lock")) { @@ -199,7 +225,7 @@ if arguments[2] == "git-environment" { _ = try UpdateOperations.withPreparedUpdate( scope: scope, environment: store.environment, checkpoint: { step in - if arguments[3] == "between-kinds", step.hasPrefix("replace.") { + if arguments[3] == "between-kinds", step.hasPrefix("entry.") && step.hasSuffix(".applied") { let journal = try JSONSerialization.jsonObject( with: Data(contentsOf: store.directory.appendingPathComponent("transaction.json"))) @@ -208,7 +234,7 @@ if arguments[2] == "git-environment" { let firstInstruction = entries.firstIndex { ($0["path"] as! String).hasPrefix("instructions-") }! - if step == "replace.\(firstInstruction - 1)" { try stop("between-kinds") } + if step == "entry.\(firstInstruction - 1).applied" { try stop("between-kinds") } } else { try stop(step) } diff --git a/Tests/StateTestSupport/ProcessWait.swift b/Tests/StateTestSupport/ProcessWait.swift new file mode 100644 index 0000000..0b5e745 --- /dev/null +++ b/Tests/StateTestSupport/ProcessWait.swift @@ -0,0 +1,69 @@ +import Foundation + +/// One deadline and one diagnostic format for filesystem handshakes and process completion. +package enum ProcessWait { + package static func marker(_ file: URL, child: Process, root: URL, timeout: TimeInterval = 120) + throws + { + try until(child, root: root, timeout: timeout, description: file.lastPathComponent) { + FileManager.default.fileExists(atPath: file.path) + } + } + + package static func exit(_ child: Process, root: URL, timeout: TimeInterval = 120) throws { + try until(child, root: root, timeout: timeout, description: "process exit") { !child.isRunning } + child.waitUntilExit() + } + + package static func condition(_ child: Process, root: URL, description: String, ready: () -> Bool) + throws + { + try until(child, root: root, timeout: 120, description: description, ready: ready) + } + + /// A grandchild has no waitable exit status in this process; its parent owns that status. + package static func condition( + processIdentifier: Int32, root: URL, description: String, + isRunning: () -> Bool, ready: () -> Bool + ) throws { + try until( + processIdentifier: processIdentifier, root: root, timeout: 120, description: description, + isRunning: isRunning, status: { "unavailable: not a direct child" }, ready: ready) + } + + private static func until( + _ child: Process, root: URL, timeout: TimeInterval, + description: String, ready: () -> Bool + ) throws { + try until( + processIdentifier: child.processIdentifier, root: root, timeout: timeout, + description: description, isRunning: { child.isRunning }, + status: { + child.isRunning + ? "unavailable while running" : "\(child.terminationStatus) (\(child.terminationReason))" + }, ready: ready) + } + + private static func until( + processIdentifier: Int32, root: URL, timeout: TimeInterval, description: String, + isRunning: () -> Bool, status: () -> String, ready: () -> Bool + ) throws { + let deadline = Date().addingTimeInterval(timeout) + while !ready(), isRunning(), Date() < deadline { Thread.sleep(forTimeInterval: 0.01) } + guard ready() else { + let trace = root.appendingPathComponent("checkpoint-\(processIdentifier).log") + let last = + (try? String(contentsOf: trace, encoding: .utf8))?.split(separator: "\n").last.map( + String.init) ?? "none" + throw WaitFailure( + message: + "Timed out or exited before \(description); alive=\(isRunning()), exit=\(status()), last checkpoint=\(last)" + ) + } + } + + private struct WaitFailure: Error, CustomStringConvertible { + let message: String + var description: String { message } + } +} From c4046c1dd2bff140ecf8f2d43b642d5d40bd4299 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:00:38 +0800 Subject: [PATCH 017/171] feat(manifest): project and plan Agents.swift declaration edits Project evaluated manifests onto the deployable declaration subset and report unsupported structure with its source span. Plan declaration changes as minimal, comment-preserving document operations, printing a new manifest canonically when none exists. Remove the agents.json migration generator, its compatibility projection and its fixtures; the printed manifests remain as printer goldens. --- .../AgentsCore/DeclarationCompatibility.swift | 94 --- Sources/AgentsManifest/CanonicalPrinter.swift | 14 +- .../DeclarationConstruction.swift | 141 ++++ .../AgentsManifest/DeclarationDocument.swift | 4 + .../AgentsManifest/DeclarationEditPlan.swift | 353 ++++++++++ Sources/AgentsManifest/DocumentEditor.swift | 14 +- Sources/AgentsManifest/DocumentEdits.swift | 103 ++- Sources/AgentsManifest/DocumentModels.swift | 12 + .../AgentsManifest/ManifestJSONValue.swift | 11 - .../AgentsManifest/ManifestMigration.swift | 332 ---------- .../AgentsManifest/ManifestProjection.swift | 210 ++++++ .../CompiledFixtures.swift | 222 +------ .../DeclarationPropertyTests.swift | 207 ++++++ Tests/AgentsManifestTests/DumpTests.swift | 2 +- Tests/AgentsManifestTests/EditPlanTests.swift | 619 ++++++++++++++++++ Tests/AgentsManifestTests/EditingTests.swift | 22 + .../Fixtures/MigrationAliasGap.migration.json | 18 - .../Fixtures/MigrationAliasGap.swift.txt | 17 - .../Fixtures/MigrationAliases.migration.json | 48 -- .../Fixtures/MigrationAliases.swift.txt | 37 -- ...igrationDuplicateRecipients.migration.json | 34 - .../MigrationDuplicateRecipients.swift.txt | 49 -- .../Fixtures/MigrationEdgeExample.swift.txt | 51 -- .../Fixtures/MigrationEmpty.migration.json | 1 - .../Fixtures/MigrationEscapes.migration.json | 31 - .../MigrationExplicitEmpty.migration.json | 11 - .../Fixtures/MigrationFields.migration.json | 100 --- .../Fixtures/MigrationRanges.migration.json | 47 -- .../Fixtures/MigrationWidth.migration.json | 26 - .../Fixtures/ParserBaseline.json | 36 +- ...Empty.dump.json => PrintedEmpty.dump.json} | 0 ...Empty.swift.txt => PrintedEmpty.swift.txt} | 0 ...pes.swift.txt => PrintedEscapes.swift.txt} | 0 ...ift.txt => PrintedExplicitEmpty.swift.txt} | 0 ...elds.dump.json => PrintedFields.dump.json} | 0 ...elds.swift.txt => PrintedFields.swift.txt} | 0 ...nges.swift.txt => PrintedRanges.swift.txt} | 0 ...Width.swift.txt => PrintedWidth.swift.txt} | 0 Tests/AgentsManifestTests/FrontEndTests.swift | 4 + .../AgentsManifestTests/MigrationTests.swift | 255 -------- Tests/AgentsManifestTests/PrintingTests.swift | 166 +++++ .../AgentsManifestTests/ProjectionTests.swift | 226 +++++++ 42 files changed, 2104 insertions(+), 1413 deletions(-) delete mode 100644 Sources/AgentsCore/DeclarationCompatibility.swift create mode 100644 Sources/AgentsManifest/DeclarationConstruction.swift create mode 100644 Sources/AgentsManifest/DeclarationEditPlan.swift delete mode 100644 Sources/AgentsManifest/ManifestMigration.swift create mode 100644 Sources/AgentsManifest/ManifestProjection.swift create mode 100644 Tests/AgentsManifestTests/DeclarationPropertyTests.swift create mode 100644 Tests/AgentsManifestTests/EditPlanTests.swift delete mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationAliasGap.migration.json delete mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationAliasGap.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationAliases.migration.json delete mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationAliases.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationDuplicateRecipients.migration.json delete mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationDuplicateRecipients.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationEdgeExample.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationEmpty.migration.json delete mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationEscapes.migration.json delete mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationExplicitEmpty.migration.json delete mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationFields.migration.json delete mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationRanges.migration.json delete mode 100644 Tests/AgentsManifestTests/Fixtures/MigrationWidth.migration.json rename Tests/AgentsManifestTests/Fixtures/{MigrationEmpty.dump.json => PrintedEmpty.dump.json} (100%) rename Tests/AgentsManifestTests/Fixtures/{MigrationEmpty.swift.txt => PrintedEmpty.swift.txt} (100%) rename Tests/AgentsManifestTests/Fixtures/{MigrationEscapes.swift.txt => PrintedEscapes.swift.txt} (100%) rename Tests/AgentsManifestTests/Fixtures/{MigrationExplicitEmpty.swift.txt => PrintedExplicitEmpty.swift.txt} (100%) rename Tests/AgentsManifestTests/Fixtures/{MigrationFields.dump.json => PrintedFields.dump.json} (100%) rename Tests/AgentsManifestTests/Fixtures/{MigrationFields.swift.txt => PrintedFields.swift.txt} (100%) rename Tests/AgentsManifestTests/Fixtures/{MigrationRanges.swift.txt => PrintedRanges.swift.txt} (100%) rename Tests/AgentsManifestTests/Fixtures/{MigrationWidth.swift.txt => PrintedWidth.swift.txt} (100%) delete mode 100644 Tests/AgentsManifestTests/MigrationTests.swift create mode 100644 Tests/AgentsManifestTests/PrintingTests.swift create mode 100644 Tests/AgentsManifestTests/ProjectionTests.swift diff --git a/Sources/AgentsCore/DeclarationCompatibility.swift b/Sources/AgentsCore/DeclarationCompatibility.swift deleted file mode 100644 index 8025fd0..0000000 --- a/Sources/AgentsCore/DeclarationCompatibility.swift +++ /dev/null @@ -1,94 +0,0 @@ -extension Declaration { - /// Projects validated legacy intent without choosing recipients, resolving sources or - /// applying migration transformations. Optional values retain inheritance boundaries. - public func compatibilityProjection() throws -> DeclarationIR { - func strings(_ values: [String]) -> DeclarationValue { .array(values.map { .string($0) }) } - func recipients(_ values: [AgentID]?) -> DeclarationValue { - values.map { strings($0.map(\.rawValue).sorted(by: compatibilityUTF8Less)) } ?? .null - } - func sections(_ values: [String]) -> DeclarationValue { - .array( - values.map { reference in - let parts = reference.split(separator: ":", maxSplits: 1).map(String.init) - return .record( - DeclarationRecord( - kind: "section", - fields: [ - "name": .string(parts.last!), - "source": parts.count == 2 ? .string(parts[0]) : .null, - "condition": .null, - ])) - }) - } - let sources = try self.sources.keys.sorted(by: compatibilityUTF8Less).map { alias in - let source = self.sources[alias]! - let location = source.kind == .git ? "url" : source.kind == .local ? "path" : "index" - return DeclarationRecord( - kind: source.kind == .wellKnown ? "index" : source.kind.rawValue, - fields: [ - "name": .string(alias), - location: .string(source.kind == .git ? source.gitURL : source.location), - "subpath": source.path.map { .string($0) } ?? .null, - "requirement": try source.requirement.map { .requirement(try $0.canonicalized()) } - ?? .null, - ]) - } - var components = (skills ?? [:]).keys.sorted(by: compatibilityUTF8Less).map { alias in - let selection = skills![alias]! - let select: DeclarationValue - switch selection.select { - case .all: select = .string("all") - case .names(let names): select = strings(names.sorted(by: compatibilityUTF8Less)) - } - let overrides = (selection.overrides ?? [:]).keys.sorted(by: compatibilityUTF8Less).map { - name in - let override = selection.overrides![name]! - return DeclarationValue.record( - DeclarationRecord( - kind: "skill", - fields: [ - "name": .string(name), "mode": override.mode.map { .string($0.rawValue) } ?? .null, - "agents": recipients(override.agents), - ])) - } - return DeclarationRecord( - kind: "skills", - fields: [ - "source": .string(alias), "select": select, - "exclude": strings((selection.exclude ?? []).sorted(by: compatibilityUTF8Less)), - "mode": selection.mode.map { .string($0.rawValue) } ?? .null, - "agents": recipients(selection.agents), "overrides": .array(overrides), - "condition": .null, "native": .dictionary([:]), - ]) - } - if let instructions { - let prompts = (instructions.chatgpt ?? [:]).keys.sorted(by: compatibilityUTF8Less).map { - name in - let prompt = instructions.chatgpt![name]! - return DeclarationValue.record( - DeclarationRecord( - kind: "prompt", - fields: [ - "name": .string(name), "sections": sections(prompt.sections), - "append": prompt.append.map { .string($0) } ?? .null, "condition": .null, - ])) - } - components.append( - DeclarationRecord( - kind: "instructions", - fields: [ - "sections": sections(instructions.sections), "chatGPT": .array(prompts), - "agents": recipients(instructions.agents), "condition": .null, - "native": .dictionary([:]), - ])) - } - return DeclarationIR( - defaultAgents: agents.map { $0.map(\.rawValue).sorted(by: compatibilityUTF8Less) }, - sources: sources, components: components, - watch: (watch ?? []).sorted(by: compatibilityUTF8Less)) - } -} - -private func compatibilityUTF8Less(_ lhs: String, _ rhs: String) -> Bool { - lhs.utf8.lexicographicallyPrecedes(rhs.utf8) -} diff --git a/Sources/AgentsManifest/CanonicalPrinter.swift b/Sources/AgentsManifest/CanonicalPrinter.swift index 97065f0..5f71bf4 100644 --- a/Sources/AgentsManifest/CanonicalPrinter.swift +++ b/Sources/AgentsManifest/CanonicalPrinter.swift @@ -89,11 +89,23 @@ struct CanonicalPrinter { Printed(prefix), layout(value, indentation: "", column: 13, trailing: 0), Printed("\n"), ]) guard result.count <= ManifestLimits.Input.bytes else { - throw MigrationFailure.limit("generated source bytes") + throw ManifestFailure( + ManifestDiagnostic( + code: "manifest.limit", message: "generated source bytes", + span: SourceSpan( + document: DocumentIdentity("manifest"), start: 0, end: 0, line: 1, column: 1))) } return Array(result.string.utf8) } + /// The parenthesized argument list of a call whose opening parenthesis is at `column`. + func argumentList( + _ arguments: [(String, ConstructionValue)], indentation: String, column: Int, trailing: Int + ) -> String { + call("", arguments: arguments, indentation: indentation, column: column, trailing: trailing) + .string + } + private func layout( _ value: ConstructionValue, indentation: String, column: Int, trailing: Int ) -> Printed { diff --git a/Sources/AgentsManifest/DeclarationConstruction.swift b/Sources/AgentsManifest/DeclarationConstruction.swift new file mode 100644 index 0000000..b943a19 --- /dev/null +++ b/Sources/AgentsManifest/DeclarationConstruction.swift @@ -0,0 +1,141 @@ +import AgentsCore +import AgentsDescription + +/// Maps declaration values to construction vocabulary in canonical order: sources, skills +/// components, overrides, prompts, names and watch subscriptions by UTF-8 name, recipients by +/// agent ID without duplicates, and skills components before the instructions component. +package enum DeclarationConstruction { + package static func root(_ declaration: Declaration) throws -> Agents { + let skills = declaration.skills ?? [:] + return Agents( + defaultAgents: recipients(declaration.agents), + sources: try declaration.sources.keys.sorted(by: utf8Less).map { + try source(alias: $0, declaration.sources[$0]!) + }, + components: skills.keys.sorted(by: utf8Less).map { self.skills(alias: $0, skills[$0]!) } + + (declaration.instructions.map { [instructions($0)] } ?? []), + watch: (declaration.watch ?? []).sorted(by: utf8Less)) + } + + /// Git sources use complete transport URLs. Version ranges are checked before construction. + package static func source(alias: String, _ source: SourceDeclaration) throws -> Source { + let subpath = source.path + guard source.kind != .wellKnown else { + guard source.requirement == nil else { + throw CoreError.invalidState("well-known sources take no Git requirement") + } + return .source(name: alias, index: source.location, subpath: subpath) + } + let git = source.kind == .git + let location = git ? source.gitURL : source.location + guard let requirement = source.requirement else { + return git + ? .source(name: alias, url: location, subpath: subpath) + : .source(name: alias, path: location, subpath: subpath) + } + switch requirement { + case .branch(let branch): + return git + ? .source(name: alias, url: location, branch: branch, subpath: subpath) + : .source(name: alias, path: location, branch: branch, subpath: subpath) + case .revision(let revision): + return git + ? .source(name: alias, url: location, revision: revision, subpath: subpath) + : .source(name: alias, path: location, revision: revision, subpath: subpath) + case .exact(let version): + let exact = Version(stringLiteral: version) + return git + ? .source(name: alias, url: location, exact: exact, subpath: subpath) + : .source(name: alias, path: location, exact: exact, subpath: subpath) + case .upToNextMajor(let lower): + let from = Version(stringLiteral: lower) + return git + ? .source(name: alias, url: location, from: from, subpath: subpath) + : .source(name: alias, path: location, from: from, subpath: subpath) + case .upToNextMinor(let lower), .range(let lower, _): + let range: Range + if case .range(_, let upper) = requirement { + let (from, to) = (Version(stringLiteral: lower), Version(stringLiteral: upper)) + guard from < to else { throw CoreError.invalidState("invalid version range") } + range = from.. Component { + let overrides = skills.overrides ?? [:] + return .skills( + source: alias, select: selection(skills.select), + exclude: (skills.exclude ?? []).sorted(by: utf8Less), mode: skills.mode.map(mode), + overrides: overrides.keys.sorted(by: utf8Less).map { override(name: $0, overrides[$0]!) }, + agents: recipients(skills.agents)) + } + + package static func selection( + _ selection: AgentsCore.SkillSelection + ) -> AgentsDescription.SkillSelection { + switch selection { + case .all: return .all + case .names(let names): + return AgentsDescription.SkillSelection( + value: .construct( + type: "SkillSelection", member: "names", + fields: ["names": names.sorted(by: utf8Less).constructionValue])) + } + } + + package static func override( + name: String, _ override: AgentsCore.SkillOverride + ) -> AgentsDescription.SkillOverride { + .skill(name: name, mode: override.mode.map(mode), agents: recipients(override.agents)) + } + + package static func instructions(_ instructions: InstructionsDeclaration) -> Component { + let prompts = instructions.chatgpt ?? [:] + return .instructions( + sections: instructions.sections.map(section), + chatGPT: prompts.keys.sorted(by: utf8Less).map { prompt(name: $0, prompts[$0]!) }, + agents: recipients(instructions.agents)) + } + + package static func prompt(name: String, _ prompt: PromptDeclaration) -> ChatGPTPrompt { + .prompt(name: name, sections: prompt.sections.map(section), append: prompt.append) + } + + /// `alias:name` names a source section; a bare name is the declaring project's own section. + package static func section(_ reference: String) -> SectionReference { + guard let colon = reference.firstIndex(of: ":") else { + return SectionReference(stringLiteral: reference) + } + return .section( + name: String(reference[reference.index(after: colon)...]), + source: String(reference[.. [Agent]? { + agents.map { Set($0).sorted { utf8Less($0.rawValue, $1.rawValue) }.map(agent) } + } + + package static func agent(_ agent: AgentID) -> Agent { + switch agent { + case .claudeCode: .claudeCode + case .codex: .codex + case .cursor: .cursor + case .geminiCLI: .geminiCLI + case .opencode: .openCode + } + } + + package static func mode(_ mode: AgentsCore.InstallMode) -> AgentsDescription.InstallMode { + switch mode { + case .link: .link + case .copy: .copy + case .edit: .edit + } + } +} diff --git a/Sources/AgentsManifest/DeclarationDocument.swift b/Sources/AgentsManifest/DeclarationDocument.swift index 36e4a8c..3eccb37 100644 --- a/Sources/AgentsManifest/DeclarationDocument.swift +++ b/Sources/AgentsManifest/DeclarationDocument.swift @@ -110,4 +110,8 @@ public struct DeclarationDocument: Sendable { public func preparing(_ edits: [ManifestEdit]) throws -> DocumentChange { try DocumentEditor(document: self).prepare(edits) } + + package func preparing(operations: [DocumentOperation]) throws -> DocumentChange { + try DocumentEditor(document: self).prepare(operations: operations) + } } diff --git a/Sources/AgentsManifest/DeclarationEditPlan.swift b/Sources/AgentsManifest/DeclarationEditPlan.swift new file mode 100644 index 0000000..067d2f7 --- /dev/null +++ b/Sources/AgentsManifest/DeclarationEditPlan.swift @@ -0,0 +1,353 @@ +import AgentsCore +import AgentsDescription + +/// Turns a declaration change into source bytes. Existing documents receive the smallest edits +/// that express the semantic difference, without reordering; bytes outside the edited ranges, +/// including comments, are unchanged. Batches hold at most 100 requests and are replanned +/// against the bytes each batch produces. The final document must project to `next`. +package enum DeclarationEditPlan { + /// Returns `nil` when `next` is semantically equal to `previous`. Without existing bytes, the + /// canonical printer writes the complete document, and a semantically empty `next` writes none. + /// `previous` must equal the projection of `bytes`; `manifest.edit.baseline` reports a caller + /// whose preparation no longer describes the document. + package static func bytes( + replacing previous: Declaration, with next: Declaration, in bytes: [UInt8]?, + identity: DocumentIdentity, environment: RuntimeEnvironment + ) throws -> [UInt8]? { + try self.bytes( + replacing: previous, with: next, in: bytes, identity: identity, environment: environment, + planning: { $0 }) + } + + // A module-internal seam alters planned batches to exercise the final comparison. + static func bytes( + replacing previous: Declaration, with next: Declaration, in bytes: [UInt8]?, + identity: DocumentIdentity, environment: RuntimeEnvironment, + planning adjust: ([DocumentOperation]) -> [DocumentOperation] + ) throws -> [UInt8]? { + func equivalent(_ lhs: Declaration, _ rhs: Declaration) -> Bool { + ManifestProjection.equivalent(lhs, rhs, environment: environment) + } + guard let bytes else { + guard equivalent(previous, Declaration()) else { + throw failure( + "manifest.edit.baseline", "the declaration has no document to edit", + span: SourceSpan(document: identity, start: 0, end: 0, line: 1, column: 1)) + } + if equivalent(next, Declaration()) { return nil } + let output = try CanonicalPrinter().manifest( + DeclarationConstruction.root(next).constructionValue) + try verify( + DeclarationDocument(bytes: output, identity: identity), next, environment: environment) + return output + } + var document = try DeclarationDocument(bytes: bytes, identity: identity) + var current = try ManifestProjection.declaration(of: document, environment: environment) + guard equivalent(current, previous) else { + throw failure( + "manifest.edit.baseline", "the document changed after the declaration was read", + span: document.source.span(0..<0)) + } + if equivalent(previous, next) { return nil } + var remaining = Int.max + while true { + var planner = Planner( + document: document, current: current, next: next, environment: environment) + let operations = adjust(try planner.plan()) + if operations.isEmpty { break } + let change = try document.preparing( + operations: Array(operations.prefix(ManifestLimits.Editing.requests))) + guard change.bytes != document.bytes, operations.count < remaining else { + throw failure( + "manifest.edit.mismatch", "an edit batch made no progress", + span: document.source.span(0..<0)) + } + remaining = operations.count + document = try DeclarationDocument(bytes: change.bytes, identity: identity) + current = try ManifestProjection.declaration(of: document, environment: environment) + } + try verify(document, next, environment: environment) + return document.bytes + } + + private static func verify( + _ document: DeclarationDocument, _ next: Declaration, environment: RuntimeEnvironment + ) throws { + let result = try ManifestProjection.declaration(of: document, environment: environment) + guard ManifestProjection.equivalent(result, next, environment: environment) else { + throw failure( + "manifest.edit.mismatch", "the edited document differs from the intended declaration", + span: document.source.span(0..<0)) + } + } + + static func failure(_ code: String, _ message: String, span: SourceSpan) -> ManifestFailure { + ManifestFailure(ManifestDiagnostic(code: code, message: message, span: span)) + } +} + +/// Plans one batch over one snapshot. Sources are added before references to them and removed +/// after every reference. Each collection receives insertions before removals, so a retained +/// element stays the insertion anchor. Selections grow before overrides arrive and shrink after +/// overrides leave, so every prefix of a split plan keeps overrides inside the selection. +private struct Planner { + let document: DeclarationDocument + let current: Declaration + let next: Declaration + let environment: RuntimeEnvironment + var operations: [DocumentOperation] = [] + + mutating func plan() throws -> [DocumentOperation] { + var skillComponents: [String: Int] = [:] + var instructionsComponent: Int? + for (index, component) in document.declaration.components.enumerated() { + if component.kind == "skills", let alias = component["source"]?.string { + skillComponents[alias] = index + } else if component.kind == "instructions" { + instructionsComponent = index + } + } + for alias in next.sources.keys.sorted(by: utf8Less) { + let source = next.sources[alias]! + if let existing = current.sources[alias], + ManifestProjection.equivalent(existing, source, environment: environment) + { + continue + } + operations.append( + .edit(.upsertSource(try DeclarationConstruction.source(alias: alias, source)))) + } + try recipients(owner: "", field: "defaultAgents", current.agents, next.agents) + + let currentSkills = current.skills ?? [:] + let nextSkills = next.skills ?? [:] + let retainedInstructions = + next.instructions == nil + ? nil : try instructionsComponent.map { try handle("/components/\($0)") } + for alias in nextSkills.keys.sorted(by: utf8Less) { + if let existing = currentSkills[alias] { + try skills(at: "/components/\(skillComponents[alias]!)", existing, nextSkills[alias]!) + } else { + operations.append( + .edit( + .insertComponent( + DeclarationConstruction.skills(alias: alias, nextSkills[alias]!), into: .root, + at: retainedInstructions.map { .before($0) } ?? .last))) + } + } + switch (instructionsComponent, next.instructions) { + case (let index?, let instructions?): + try self.instructions(at: "/components/\(index)", current.instructions!, instructions) + case (nil, let instructions?): + operations.append( + .edit( + .insertComponent( + DeclarationConstruction.instructions(instructions), into: .root, at: .last))) + case (let index?, nil): + operations.append(.edit(.removeComponent(try handle("/components/\(index)")))) + case (nil, nil): break + } + for alias in currentSkills.keys.sorted(by: utf8Less) where nextSkills[alias] == nil { + operations.append( + .edit(.removeComponent(try handle("/components/\(skillComponents[alias]!)")))) + } + + let watch = (next.watch ?? []).sorted(by: utf8Less) + if Set(current.watch ?? []) != Set(watch) { + if explicit("/watch") { + let changes = try elements(at: "/watch", watch, value: { .text($0) }) + operations += changes.insertions + changes.removals + } else { + operations.append(.edit(.setWatch(watch))) + } + } + for alias in current.sources.keys.sorted(by: utf8Less) where next.sources[alias] == nil { + operations.append(.edit(.removeSource(alias: alias))) + } + return operations + } + + mutating func skills( + at pointer: String, _ current: SkillDeclaration, _ next: SkillDeclaration + ) throws { + let owner = try handle(pointer) + var reductions: [DocumentOperation] = [] + switch (current.select, next.select) { + case (.all, .all): break + case (.names(let old), .names(let new)) where Set(old) == Set(new): break + case (.names, .names(let names)): + let changes = try elements( + at: pointer + "/select", names.sorted(by: utf8Less), value: { .text($0) }) + operations += changes.insertions + reductions = changes.removals + case (.names, .all): + operations.append(.edit(.setSkillSelection(owner, .all))) + case (.all, .names): + reductions = [ + .edit(.setSkillSelection(owner, DeclarationConstruction.selection(next.select))) + ] + } + let currentOverrides = current.overrides ?? [:] + let nextOverrides = next.overrides ?? [:] + for name in nextOverrides.keys.sorted(by: utf8Less) { + let override = nextOverrides[name]! + if let existing = currentOverrides[name], ManifestProjection.equivalent(existing, override) { + continue + } + operations.append( + .edit( + .upsertSkillOverride(owner, DeclarationConstruction.override(name: name, override)))) + } + for name in currentOverrides.keys.sorted(by: utf8Less) where nextOverrides[name] == nil { + operations.append(.edit(.removeSkillOverride(owner, name: name))) + } + operations += reductions + let exclude = (next.exclude ?? []).sorted(by: utf8Less) + if Set(current.exclude ?? []) != Set(exclude) { + if explicit(pointer + "/exclude") { + let changes = try elements(at: pointer + "/exclude", exclude, value: { .text($0) }) + operations += changes.insertions + changes.removals + } else { + operations.append( + .setArgument(owner, field: "exclude", value: exclude.constructionValue)) + } + } + if current.mode != next.mode { + operations.append( + .setArgument( + owner, field: "mode", value: next.mode.map(DeclarationConstruction.mode).constructionValue + )) + } + try recipients(owner: pointer, field: "agents", current.agents, next.agents) + } + + mutating func instructions( + at pointer: String, _ current: InstructionsDeclaration, _ next: InstructionsDeclaration + ) throws { + let owner = try handle(pointer) + try recipients(owner: pointer, field: "agents", current.agents, next.agents) + if current.sections != next.sections { + let kept = try commonSubsequence(current.sections, next.sections) + let keptCurrent = Set(kept.map(\.0)) + let keptNext = Set(kept.map(\.1)) + for index in next.sections.indices where !keptNext.contains(index) { + // Inserting before the next retained section keeps several insertions in order. + let anchor = try kept.first { $0.1 > index }.map { + InsertionPosition.before(try handle(pointer + "/sections/\($0.0)")) + } + operations.append( + .edit( + .insertSection( + DeclarationConstruction.section(next.sections[index]), into: owner, + at: anchor ?? .last))) + } + for index in current.sections.indices where !keptCurrent.contains(index) { + operations.append(.edit(.removeSection(try handle(pointer + "/sections/\(index)")))) + } + } + let currentPrompts = current.chatgpt ?? [:] + let nextPrompts = next.chatgpt ?? [:] + for name in nextPrompts.keys.sorted(by: utf8Less) + where currentPrompts[name] != nextPrompts[name] { + operations.append( + .edit(.upsertPrompt(owner, DeclarationConstruction.prompt(name: name, nextPrompts[name]!)))) + } + for name in currentPrompts.keys.sorted(by: utf8Less) where nextPrompts[name] == nil { + operations.append(.edit(.removePrompt(owner, name: name))) + } + } + + /// Present arrays change element by element; inheritance and its replacement change the + /// whole argument. + mutating func recipients( + owner: String, field: String, _ current: [AgentID]?, _ next: [AgentID]? + ) throws { + guard !ManifestProjection.sameRecipients(current, next) else { return } + let pointer = owner + "/" + field + let agents = DeclarationConstruction.recipients(next) + if current != nil, let agents, explicit(pointer) { + let changes = try elements( + at: pointer, agents.map { Lowering.lower($0.constructionValue).string! }, + value: { DeclarationConstruction.agent(AgentID(rawValue: $0)!).constructionValue }) + operations += changes.insertions + changes.removals + } else if owner.isEmpty { + operations.append(.edit(.setDefaultAgents(agents))) + } else { + operations.append( + .setArgument(try handle(owner), field: field, value: agents.constructionValue)) + } + } + + /// Element edits that turn the array at `pointer` into canonically ordered `desired`. + /// Insertions keep canonical order when the retained elements already have it. + func elements( + at pointer: String, _ desired: [String], value: (String) -> ConstructionValue + ) throws -> (insertions: [DocumentOperation], removals: [DocumentOperation]) { + let wanted = Set(desired) + let existing = + document.values[pointer].map { Lowering.lower($0.value).elements ?? [] }? + .compactMap(\.string) ?? [] + let kept = existing.enumerated().filter { wanted.contains($0.element) } + let present = Set(kept.map(\.element)) + let ordered = zip(kept, kept.dropFirst()).allSatisfy { utf8Less($0.element, $1.element) } + let container = try handle(pointer) + var insertions: [DocumentOperation] = [] + for element in desired where !present.contains(element) { + let anchor = ordered ? kept.first { utf8Less(element, $0.element) } : nil + insertions.append( + .insertElement( + value(element), into: container, + at: try anchor.map { .before(try handle(pointer + "/\($0.offset)")) } ?? .last)) + } + let removals = try existing.indices.filter { !wanted.contains(existing[$0]) }.map { + DocumentOperation.removeElement(try handle(pointer + "/\($0)")) + } + return (insertions, removals) + } + + func explicit(_ pointer: String) -> Bool { + document.values[pointer].map { !$0.defaulted } ?? false + } + + func handle(_ pointer: String) throws -> NodeID { + guard let node = document.node(at: pointer) else { + throw DeclarationEditPlan.failure( + "manifest.edit.mismatch", "planned edit has no source location", + span: document.source.span(0..<0)) + } + return node + } + + /// Index pairs of a longest common subsequence; duplicates are matched in order. + func commonSubsequence(_ lhs: [String], _ rhs: [String]) throws -> [(Int, Int)] { + let (pairs, overflow) = (lhs.count + 1).multipliedReportingOverflow(by: rhs.count + 1) + guard !overflow, pairs <= ManifestLimits.Editing.comparisonPairs else { + throw DeclarationEditPlan.failure( + "manifest.limit", "section comparison pairs", span: document.source.span(0..<0)) + } + let width = rhs.count + 1 + var lengths = [Int](repeating: 0, count: (lhs.count + 1) * width) + for i in stride(from: lhs.count - 1, through: 0, by: -1) { + for j in stride(from: rhs.count - 1, through: 0, by: -1) { + lengths[i * width + j] = + lhs[i] == rhs[j] + ? lengths[(i + 1) * width + j + 1] + 1 + : max(lengths[(i + 1) * width + j], lengths[i * width + j + 1]) + } + } + var kept: [(Int, Int)] = [] + var (i, j) = (0, 0) + while i < lhs.count && j < rhs.count { + if lhs[i] == rhs[j] { + kept.append((i, j)) + i += 1 + j += 1 + } else if lengths[(i + 1) * width + j] >= lengths[i * width + j + 1] { + i += 1 + } else { + j += 1 + } + } + return kept + } +} diff --git a/Sources/AgentsManifest/DocumentEditor.swift b/Sources/AgentsManifest/DocumentEditor.swift index ccff7eb..ebc882e 100644 --- a/Sources/AgentsManifest/DocumentEditor.swift +++ b/Sources/AgentsManifest/DocumentEditor.swift @@ -74,12 +74,16 @@ final class DocumentEditor { } func prepare(_ edits: [ManifestEdit]) throws -> DocumentChange { - if edits.count > ManifestLimits.Editing.requests { + try prepare(operations: edits.map(DocumentOperation.edit)) + } + + func prepare(operations: [DocumentOperation]) throws -> DocumentChange { + if operations.count > ManifestLimits.Editing.requests { throw fail("manifest.limit", "edit batch has more than 100 requests") } - for edit in edits { + for operation in operations { let before = history.count - try apply(edit) + try apply(operation) if before != history.count { current = try DeclarationDocument( bytes: table.bytes, identity: original.source.identity, validateDomain: false) @@ -196,11 +200,11 @@ final class DocumentEditor { } return range } + /// Member values such as `.copy` are direct; bare names are references and have referents. func direct(_ pointer: String) throws -> EvaluatedValue { guard let value = current.values[pointer], !value.defaulted, value.referent == nil, !current.hasAssembledAncestor(pointer), - current.admission.nodes[value.syntax].kind != .sequence, - current.admission.nodes[value.syntax].kind != .name + current.admission.nodes[value.syntax].kind != .sequence else { throw fail( "manifest.edit.readOnly", diff --git a/Sources/AgentsManifest/DocumentEdits.swift b/Sources/AgentsManifest/DocumentEdits.swift index 9964fca..1c525ef 100644 --- a/Sources/AgentsManifest/DocumentEdits.swift +++ b/Sources/AgentsManifest/DocumentEdits.swift @@ -3,6 +3,16 @@ import AgentsDescription import Foundation extension DocumentEditor { + func apply(_ operation: DocumentOperation) throws { + switch operation { + case .edit(let edit): try apply(edit) + case .setArgument(let handle, let field, let value): try setField(resolve(handle), field, value) + case .insertElement(let value, let handle, let position): + try insert(value, into: resolve(handle), at: position) + case .removeElement(let handle): try remove(resolve(handle)) + } + } + func apply(_ edit: ManifestEdit) throws { switch edit { case .setDefaultAgents(let agents): try setField("", "defaultAgents", agents.constructionValue) @@ -110,11 +120,15 @@ extension DocumentEditor { return index > position } let (style, indentation) = try style(at: node.range) + let multiline = hasNewline(node.range) + let label = field + ": " let content = - field + ": " + label + (spelling - ?? CanonicalPrinter(style: style).render(value, indentation: indentation + style.indent)) - let multiline = hasNewline(node.range) + ?? CanonicalPrinter(style: style).render( + value, indentation: indentation + style.indent, + column: (indentation + style.indent + label).utf8.count, + trailing: multiline && next == nil ? 0 : 1)) if let next { let start = next.labelRange?.lowerBound ?? current.admission.nodes[next.value].range.lowerBound @@ -131,7 +145,9 @@ extension DocumentEditor { } else { let close = node.range.upperBound - 1 if node.arguments.isEmpty { - try patch(close.., + style: PrintStyle, indentation: String + ) throws { + let close = range.upperBound - 1 + guard + let open = current.admission.tokens.last(where: { + $0.text == "(" && $0.range.lowerBound >= range.lowerBound && $0.range.upperBound <= close + }) + else { throw fail("manifest.edit.readOnly", "call has no argument list", range: range) } + let interior = open.range.upperBound..= current.admission.nodes[value.syntax].range.upperBound && $0.range.upperBound <= range.upperBound } + // An inline element also takes the spacing that separates it from its neighbor. + let inline = !hasNewline(range) + let following = + index + 1 < node.children.count + ? current.admission.nodes[node.children[index + 1]].range.lowerBound + : node.range.upperBound - 1 + while inline && hasComma && range.upperBound < following && blank(range.upperBound) { + range = range.lowerBound..<(range.upperBound + 1) + } var patches = [SourcePatch(range: range, replacement: [])] if !hasComma && index > 0 { let previous = current.admission.nodes[node.children[index - 1]].range.upperBound if let comma = current.admission.tokens.last(where: { $0.text == "," && $0.range.lowerBound >= previous && $0.range.upperBound <= range.lowerBound }) { - patches.append(SourcePatch(range: comma.range, replacement: [])) + if inline && (comma.range.upperBound.. $1.range.lowerBound }) { try self.patch(patch.range, bytes: patch.replacement) } - try mutate(collectionPointer, .array(values)) + try mutate(collectionPointer, replacingElements(collection.value, with: values)) + } + + func blank(_ offset: Int) -> Bool { + current.bytes[offset] == UInt8(ascii: " ") || current.bytes[offset] == UInt8(ascii: "\t") + } + + /// Array literals evaluate to arrays, except explicit skill selections, whose names they hold. + func arrayElements(_ value: ConstructionValue) -> [ConstructionValue]? { + if case .node("SkillSelection", "names", let fields) = value { return fields["names"]?.array } + return value.array + } + func replacingElements(_ value: ConstructionValue, with elements: [ConstructionValue]) + -> ConstructionValue + { + if case .node("SkillSelection", "names", _) = value { + return .node(type: "SkillSelection", member: "names", fields: ["names": .array(elements)]) + } + return .array(elements) } func move(_ pointer: String, into collection: String, at position: InsertionPosition) diff --git a/Sources/AgentsManifest/DocumentModels.swift b/Sources/AgentsManifest/DocumentModels.swift index 1ca0489..4d42813 100644 --- a/Sources/AgentsManifest/DocumentModels.swift +++ b/Sources/AgentsManifest/DocumentModels.swift @@ -89,6 +89,18 @@ public enum ManifestEdit: Sendable { case replaceConstant(NodeID, with: StaticValue, acceptingUses: [NodeID]) } +/// Edits below component granularity. Argument and element handles address direct +/// constructions and array literals, including explicit skill selections; comments follow the +/// ownership rules of the other edits. +package enum DocumentOperation: Sendable { + case edit(ManifestEdit) + /// Replaces a present argument, writing an explicit default rather than removing it, or + /// inserts a missing one in signature order. A missing argument set to its default is a no-op. + case setArgument(NodeID, field: String, value: ConstructionValue) + case insertElement(ConstructionValue, into: NodeID, at: InsertionPosition) + case removeElement(NodeID) +} + public struct SemanticDelta: Sendable, Equatable { public let changedPointers: [String] } diff --git a/Sources/AgentsManifest/ManifestJSONValue.swift b/Sources/AgentsManifest/ManifestJSONValue.swift index 3228d8c..7a03e36 100644 --- a/Sources/AgentsManifest/ManifestJSONValue.swift +++ b/Sources/AgentsManifest/ManifestJSONValue.swift @@ -1,5 +1,4 @@ import AgentsCore -import Foundation /// JSON data for the evaluated manifest schema. Decimal configuration payloads remain strings. public indirect enum ManifestJSONValue: Sendable, Equatable { @@ -10,16 +9,6 @@ public indirect enum ManifestJSONValue: Sendable, Equatable { case array([ManifestJSONValue]) case object([String: ManifestJSONValue]) - static func json(_ input: Any) throws -> Self { - switch input { - case let string as String: return .string(string) - case is NSNull: return .null - case let array as [Any]: return .array(try array.map(json)) - case let fields as [String: Any]: return .object(try fields.mapValues(json)) - default: throw CoreError.invalidState("unexpected migration diagnostic value") - } - } - func encodedCount(limit: Int, budget: String = "encoded JSON output bytes") throws -> Int { var count = 0 try write(indentation: "") { text in diff --git a/Sources/AgentsManifest/ManifestMigration.swift b/Sources/AgentsManifest/ManifestMigration.swift deleted file mode 100644 index a58b366..0000000 --- a/Sources/AgentsManifest/ManifestMigration.swift +++ /dev/null @@ -1,332 +0,0 @@ -import AgentsCore -import AgentsDescription -import Foundation - -public struct MigrationDiagnostic: Sendable, Equatable { - public let pointer: String - public let code: String - public let message: String - public let value: ManifestJSONValue? - public let oldAlias: String? - public let newAlias: String? - public let budget: String? - - init( - pointer: String, code: String, message: String, value: ManifestJSONValue? = nil, - oldAlias: String? = nil, newAlias: String? = nil, budget: String? = nil - ) { - self.pointer = pointer - self.code = code - self.message = message - self.value = value - self.oldAlias = oldAlias - self.newAlias = newAlias - self.budget = budget - } -} - -public struct MigrationFailure: Error, Sendable { - public let diagnostics: [MigrationDiagnostic] - - static func limit(_ budget: String) -> Self { - Self(diagnostics: [ - MigrationDiagnostic( - pointer: "", code: "migration.limit", message: "migration exceeds \(budget)", budget: budget - ) - ]) - } -} - -public struct ManifestMigrationResult: Sendable { - public let bytes: [UInt8] - public let declaration: DeclarationIR - public let diagnostics: [MigrationDiagnostic] -} - -/// Pure generation: callers own declaration-file creation, removal and every state transaction. -public enum ManifestMigration { - public static func generate( - json bytes: [UInt8], environment: RuntimeEnvironment = RuntimeEnvironment() - ) throws -> ManifestMigrationResult { - try generate(json: bytes, environment: environment, checking: { $0 }) - } - - // A private-to-the-module comparison seam exercises self-check failures without changing output. - static func generate( - json bytes: [UInt8], environment: RuntimeEnvironment, - checking expected: (DeclarationIR) -> DeclarationIR - ) throws -> ManifestMigrationResult { - var legacy = try StateStore.decode(Data(bytes), as: Declaration.self) - try legacy.validate(environment: environment) - // The strict decoder checks duplicates, UTF-8 and discarded values. Check field names - // independently as well, including unknown fields whose value is JSON null. - let input = try JSONSerialization.jsonObject(with: Data(bytes)) as! [String: Any] - try validateKeys(input) - var diagnostics: [MigrationDiagnostic] = [] - removeDuplicateRecipients(from: &legacy, diagnostics: &diagnostics) - for alias in (legacy.skills ?? [:]).keys.sorted(by: utf8Less) { - guard let selection = legacy.skills?[alias], case .names(let names) = selection.select else { - continue - } - let selected = Set(names) - for name in (selection.overrides ?? [:]).keys.sorted(by: utf8Less) - where !selected.contains(name) { - let pointer = "/skills/" + pointerEscape(alias) + "/overrides/" + pointerEscape(name) - let full = - ((input["skills"] as! [String: Any])[alias] as! [String: Any])["overrides"] - as! [String: Any] - diagnostics.append( - MigrationDiagnostic( - pointer: pointer, code: "migration.inertOverride", - message: - "override is outside the explicit skill selection and cannot affect installation", - value: try ManifestJSONValue.json(full[name]!))) - legacy.skills?[alias]?.overrides?.removeValue(forKey: name) - } - } - if let dot = legacy.sources.removeValue(forKey: ".") { - var alias = "source" - var suffix = 2 - while legacy.sources[alias] != nil { - alias = "source-\(suffix)" - suffix += 1 - } - legacy.sources[alias] = dot - if let selection = legacy.skills?.removeValue(forKey: ".") { - legacy.skills?[alias] = selection - } - legacy.watch = legacy.watch?.map { $0 == "." ? alias : $0 } - func rewrite(_ references: [String]) -> [String] { - references.map { $0.hasPrefix(".:") ? alias + $0.dropFirst() : $0 } - } - if let instructions = legacy.instructions { - legacy.instructions?.sections = rewrite(instructions.sections) - for name in (instructions.chatgpt ?? [:]).keys { - legacy.instructions?.chatgpt?[name]?.sections = rewrite( - instructions.chatgpt![name]!.sections) - } - } - diagnostics.append( - MigrationDiagnostic( - pointer: "/sources/.", code: "migration.sourceAliasRenamed", - message: "reserved source alias renamed", oldAlias: ".", newAlias: alias)) - } - diagnostics.sort { - $0.pointer == $1.pointer ? utf8Less($0.code, $1.code) : utf8Less($0.pointer, $1.pointer) - } - let projection = try legacy.compatibilityProjection() - let construction = MigrationConstruction.root(projection) - try preflight(construction) - let output = try CanonicalPrinter().manifest(construction) - let document: DeclarationDocument - do { - document = try DeclarationDocument(bytes: output, identity: DocumentIdentity("manifest")) - } catch let failure as ManifestFailure { - if let limit = failure.diagnostics.first(where: { $0.code == "manifest.limit" }) { - throw MigrationFailure.limit(limit.message) - } - throw failure - } - guard document.declaration == expected(projection) else { - throw MigrationFailure(diagnostics: [ - MigrationDiagnostic( - pointer: "", code: "migration.mismatch", - message: "generated declaration differs from compatibility projection") - ]) - } - return ManifestMigrationResult(bytes: output, declaration: projection, diagnostics: diagnostics) - } - - private static func removeDuplicateRecipients( - from legacy: inout Declaration, diagnostics: inout [MigrationDiagnostic] - ) { - func recipients(_ agents: [AgentID]?, at pointer: String) -> [AgentID]? { - guard let agents else { return nil } - var seen = Set() - var unique: [AgentID] = [] - for (index, agent) in agents.enumerated() { - if seen.insert(agent).inserted { - unique.append(agent) - } else { - diagnostics.append( - MigrationDiagnostic( - pointer: pointer + "/\(index)", code: "migration.duplicateRecipient", - message: "recipient repeats an earlier entry in the same agents array", - value: .string(agent.rawValue))) - } - } - return unique - } - // Preserve original element indices and aliases before any other transformation removes - // overrides or renames sources. Optional arrays retain their inheritance boundary. - legacy.agents = recipients(legacy.agents, at: "/agents") - if var instructions = legacy.instructions { - instructions.agents = recipients(instructions.agents, at: "/instructions/agents") - legacy.instructions = instructions - } - for alias in (legacy.skills ?? [:]).keys.sorted(by: utf8Less) { - var selection = legacy.skills![alias]! - let pointer = "/skills/" + pointerEscape(alias) - selection.agents = recipients(selection.agents, at: pointer + "/agents") - for name in (selection.overrides ?? [:]).keys.sorted(by: utf8Less) { - var override = selection.overrides![name]! - override.agents = recipients( - override.agents, at: pointer + "/overrides/" + pointerEscape(name) + "/agents") - selection.overrides?[name] = override - } - legacy.skills?[alias] = selection - } - } - - static func preflight(_ value: ConstructionValue) throws { - var pending = [(value, 1)] - var nodes = 0 - var strings = 0 - while let (value, depth) = pending.popLast() { - nodes += 1 - guard nodes <= ManifestLimits.Values.nodes else { - throw MigrationFailure.limit("expanded nodes") - } - guard depth <= ManifestLimits.Values.depth else { - throw MigrationFailure.limit("expanded depth") - } - let children: [ConstructionValue] - switch value { - case .array(let values): children = values - case .object(let fields), .node(_, _, let fields): - strings = fields.keys.reduce(strings) { ValueCost.add($0, $1.utf8.count) } - children = fields.keys.sorted(by: utf8Less).map { fields[$0]! } - case .text(let text): - strings = ValueCost.add(strings, text.utf8.count) - children = [] - case .version(let version): - strings = ValueCost.add(strings, version.normalized.utf8.count) - children = [] - case .range(let range): children = [.version(range.lowerBound), .version(range.upperBound)] - default: children = [] - } - guard children.count <= ManifestLimits.Values.entries else { - throw MigrationFailure.limit("collection entries") - } - guard strings <= ManifestLimits.Values.stringBytes else { - throw MigrationFailure.limit("decoded string bytes") - } - guard children.count <= ManifestLimits.Values.nodes - nodes - pending.count else { - throw MigrationFailure.limit("expanded nodes") - } - pending += children.map { ($0, depth + 1) } - } - let cost = constructionCost(value) - guard cost.encoded <= ManifestLimits.Output.encodedBytes else { - throw MigrationFailure.limit("encoded output bytes") - } - } - - private static func validateKeys(_ root: [String: Any]) throws { - func keys(_ value: [String: Any], _ allowed: Set) throws { - if let unknown = value.keys.sorted(by: utf8Less).first(where: { !allowed.contains($0) }) { - throw CoreError.invalidState("unknown state field: \(unknown)") - } - } - try keys(root, ["agents", "sources", "skills", "instructions", "watch"]) - for source in (root["sources"] as? [String: [String: Any]] ?? [:]).values { - try keys( - source, - [ - "git", "local", "well-known", "path", "branch", "revision", "exact", "from", "to", - "upToNextMinor", - ]) - } - for selection in (root["skills"] as? [String: [String: Any]] ?? [:]).values { - try keys(selection, ["select", "exclude", "agents", "mode", "overrides"]) - for override in (selection["overrides"] as? [String: [String: Any]] ?? [:]).values { - try keys(override, ["agents", "mode"]) - } - } - if let instructions = root["instructions"] as? [String: Any] { - try keys(instructions, ["agents", "sections", "chatgpt"]) - for prompt in (instructions["chatgpt"] as? [String: [String: Any]] ?? [:]).values { - try keys(prompt, ["sections", "append"]) - } - } - } -} - -private enum MigrationConstruction { - static func root(_ ir: DeclarationIR) -> ConstructionValue { - record( - DeclarationRecord( - kind: "Agents", - fields: [ - "defaultAgents": ir.defaultAgents.map { .array($0.map { .string($0) }) } ?? .null, - "exports": .array(ir.exports.map { .string($0) }), - "sources": .array(ir.sources.map { .record($0) }), - "components": .array(ir.components.map { .record($0) }), - "groups": .array(ir.groups.map { .record($0) }), - "uses": .array(ir.uses.map { .record($0) }), - "watch": .array(ir.watch.map { .string($0) }), - ]), as: "Agents") - } - - private static func record(_ record: DeclarationRecord, as type: String) -> ConstructionValue { - if type == "Source" { - return .node( - type: type, member: "source", - fields: record.fields.mapValues { value($0, as: .named("String")) }) - } - let signature = Vocabulary.signatures.first { $0.type == type && $0.member == record.kind }! - return .node( - type: type, member: record.kind, - fields: record.fields.reduce(into: [:]) { result, field in - let parameter = signature.parameters.first { $0.name == field.key }! - result[field.key] = value(field.value, as: parameter.type) - }) - } - - private static func value(_ input: DeclarationValue, as type: ConstructionType) - -> ConstructionValue - { - switch input { - case .null: return .none - case .string(let text): - if case .named(let name) = type.unwrapped { - if let member = Vocabulary.scalarValues[name]?.first(where: { $0.value == text })?.key { - return .node(type: name, member: member, fields: [:]) - } - if name == "SkillSelection" { return .node(type: name, member: "all", fields: [:]) } - } - return .text(text) - case .integer(let number): return .integer(number) - case .boolean(let flag): return .boolean(flag) - case .array(let values): - if case .named("SkillSelection") = type.unwrapped { - return .node( - type: "SkillSelection", member: "names", - fields: ["names": .array(values.map { value($0, as: .named("String")) })]) - } - guard case .array(let element) = type.unwrapped else { - preconditionFailure("projection array type") - } - return .array(values.map { value($0, as: element) }) - case .dictionary(let fields): - guard case .dictionary(let element) = type.unwrapped else { - preconditionFailure("projection dictionary type") - } - return .object(fields.mapValues { value($0, as: element) }) - case .record(let node): - guard case .named(let name) = type.unwrapped else { - preconditionFailure("projection record type") - } - return record(node, as: name) - case .requirement(let requirement): - func version(_ text: String) -> Version { Version(stringLiteral: text) } - switch requirement { - case .upToNextMajor(let lower): return .range(.upToNextMajor(from: version(lower))) - case .upToNextMinor(let lower): return .range(.upToNextMinor(from: version(lower))) - case .range(let lower, let upper): return .range(version(lower).. Declaration { + let ir = document.declaration + func unsupported(_ pointer: String, _ message: String) -> ManifestFailure { + let span = + document.sourceMap.locations(at: pointer).first?.span + ?? document.source.span(0..<0) + return ManifestFailure( + ManifestDiagnostic(code: "manifest.unsupported", message: message, span: span)) + } + func recipients(_ value: DeclarationValue?, at pointer: String) throws -> [AgentID]? { + guard let values = value?.elements else { return nil } + return try values.map { + guard let agent = $0.string.flatMap(AgentID.init(rawValue:)) else { + throw unsupported(pointer, "unknown recipient") + } + return agent + } + } + func section(_ value: DeclarationValue, at pointer: String) throws -> String { + guard let record = value.record, let name = record["name"]?.string else { + throw unsupported(pointer, "unknown section reference") + } + guard record["condition"] == .null else { + throw unsupported(pointer + "/condition", "conditional sections are not deployable") + } + // `.` names the declaring project, whose own sections are bare names. + guard let alias = record["source"]?.string, alias != "." else { return name } + return alias + ":" + name + } + func applicable(_ record: DeclarationRecord, at pointer: String) throws { + guard record["condition"] == .null else { + throw unsupported(pointer + "/condition", "conditional components are not deployable") + } + guard record["native"] == .dictionary([:]) else { + throw unsupported(pointer + "/native", "native configuration is not deployable") + } + } + + if !ir.uses.isEmpty { throw unsupported("/uses/0", "group uses are not deployable") } + var sources: [String: SourceDeclaration] = [:] + for (index, record) in ir.sources.enumerated() { + let kind: SourceKind + let location: DeclarationValue? + switch record.kind { + case "git": (kind, location) = (.git, record["url"]) + case "local": (kind, location) = (.local, record["path"]) + default: (kind, location) = (.wellKnown, record["index"]) + } + guard let alias = record["name"]?.string, let location = location?.string else { + throw unsupported("/sources/\(index)", "unknown source form") + } + var requirement: SourceRequirement? + if case .requirement(let value) = record["requirement"] { requirement = value } + sources[alias] = SourceDeclaration( + kind: kind, location: location, requirement: requirement, + path: record["subpath"]?.string) + } + var skills: [String: SkillDeclaration] = [:] + var instructions: InstructionsDeclaration? + for (index, record) in ir.components.enumerated() { + let pointer = "/components/\(index)" + switch record.kind { + case "skills": + try applicable(record, at: pointer) + guard let alias = record["source"]?.string, alias != "." else { + throw unsupported( + pointer + "/source", "skills of the declaring package are not deployable") + } + guard skills[alias] == nil else { + throw unsupported(pointer, "a source alias has more than one skills component") + } + let select: SkillSelection + if let names = record["select"]?.elements { + select = .names(names.compactMap(\.string)) + } else { + select = .all + } + let exclude = record["exclude"]?.elements?.compactMap(\.string) ?? [] + var overrides: [String: SkillOverride] = [:] + for (position, value) in (record["overrides"]?.elements ?? []).enumerated() { + let path = pointer + "/overrides/\(position)" + guard let override = value.record, let name = override["name"]?.string else { + throw unsupported(path, "unknown skill override") + } + overrides[name] = SkillOverride( + agents: try recipients(override["agents"], at: path + "/agents"), + mode: override["mode"]?.string.flatMap(InstallMode.init(rawValue:))) + } + skills[alias] = SkillDeclaration( + select: select, exclude: exclude.isEmpty ? nil : exclude, + agents: try recipients(record["agents"], at: pointer + "/agents"), + mode: record["mode"]?.string.flatMap(InstallMode.init(rawValue:)), + overrides: overrides.isEmpty ? nil : overrides) + case "instructions": + try applicable(record, at: pointer) + guard instructions == nil else { + throw unsupported(pointer, "the declaration has more than one instructions component") + } + let sections = try (record["sections"]?.elements ?? []).enumerated().map { + try section($1, at: pointer + "/sections/\($0)") + } + var prompts: [String: PromptDeclaration] = [:] + for (position, value) in (record["chatGPT"]?.elements ?? []).enumerated() { + let path = pointer + "/chatGPT/\(position)" + guard let prompt = value.record, let name = prompt["name"]?.string else { + throw unsupported(path, "unknown ChatGPT prompt") + } + guard prompt["condition"] == .null else { + throw unsupported(path + "/condition", "conditional prompts are not deployable") + } + prompts[name] = PromptDeclaration( + sections: try (prompt["sections"]?.elements ?? []).enumerated().map { + try section($1, at: path + "/sections/\($0)") + }, append: prompt["append"]?.string) + } + instructions = InstructionsDeclaration( + agents: try recipients(record["agents"], at: pointer + "/agents"), sections: sections, + chatgpt: prompts.isEmpty ? nil : prompts) + default: + throw unsupported(pointer, "\(record.kind) components are not deployable") + } + } + let declaration = Declaration( + agents: try recipients( + ir.defaultAgents.map { .array($0.map(DeclarationValue.string)) }, at: "/defaultAgents"), + sources: sources, skills: skills.isEmpty ? nil : skills, instructions: instructions, + watch: ir.watch.isEmpty ? nil : ir.watch) + try declaration.validate(environment: environment) + return declaration + } + + /// Semantic declaration equality. Sources compare identity, requirement meaning and normalized + /// subpath, so equivalent spellings stay unchanged. Recipients compare as sets and keep `nil` + /// distinct from `[]`; absent and empty exclusions, overrides, prompts, watch subscriptions and + /// skills are equal. Sections compare in order. + package static func equivalent( + _ lhs: Declaration, _ rhs: Declaration, environment: RuntimeEnvironment + ) -> Bool { + guard sameRecipients(lhs.agents, rhs.agents), Set(lhs.watch ?? []) == Set(rhs.watch ?? []), + lhs.sources.keys == rhs.sources.keys, + lhs.sources.allSatisfy({ equivalent($1, rhs.sources[$0]!, environment: environment) }) + else { return false } + let left = lhs.skills ?? [:] + let right = rhs.skills ?? [:] + guard left.keys == right.keys, left.allSatisfy({ equivalent($1, right[$0]!) }) else { + return false + } + switch (lhs.instructions, rhs.instructions) { + case (nil, nil): return true + case (let left?, let right?): return equivalent(left, right) + default: return false + } + } + + static func equivalent( + _ lhs: SourceDeclaration, _ rhs: SourceDeclaration, environment: RuntimeEnvironment + ) -> Bool { + func identity(_ source: SourceDeclaration) -> String { + (try? source.identity(environment: environment)) ?? source.location + } + func subpath(_ source: SourceDeclaration) -> String { + source.path.map { (try? PathSafety.sanitizeSubpath($0)) ?? $0 } ?? "." + } + let requirements: Bool + switch (lhs.requirement, rhs.requirement) { + case (nil, nil): requirements = true + case (let left?, let right?): requirements = left.declarationEquivalent(to: right) + default: requirements = false + } + return lhs.kind == rhs.kind && requirements && identity(lhs) == identity(rhs) + && subpath(lhs) == subpath(rhs) + } + + static func equivalent(_ lhs: SkillDeclaration, _ rhs: SkillDeclaration) -> Bool { + let selections: Bool + switch (lhs.select, rhs.select) { + case (.all, .all): selections = true + case (.names(let left), .names(let right)): selections = Set(left) == Set(right) + default: selections = false + } + let left = lhs.overrides ?? [:] + let right = rhs.overrides ?? [:] + return selections && Set(lhs.exclude ?? []) == Set(rhs.exclude ?? []) + && lhs.mode == rhs.mode && sameRecipients(lhs.agents, rhs.agents) && left.keys == right.keys + && left.allSatisfy { equivalent($1, right[$0]!) } + } + + static func equivalent(_ lhs: SkillOverride, _ rhs: SkillOverride) -> Bool { + lhs.mode == rhs.mode && sameRecipients(lhs.agents, rhs.agents) + } + + static func equivalent(_ lhs: InstructionsDeclaration, _ rhs: InstructionsDeclaration) -> Bool { + sameRecipients(lhs.agents, rhs.agents) && lhs.sections == rhs.sections + && lhs.chatgpt ?? [:] == rhs.chatgpt ?? [:] + } + + static func sameRecipients(_ lhs: [AgentID]?, _ rhs: [AgentID]?) -> Bool { + lhs.map(Set.init) == rhs.map(Set.init) + } +} diff --git a/Tests/AgentsManifestTests/CompiledFixtures.swift b/Tests/AgentsManifestTests/CompiledFixtures.swift index 639e7f8..a03807d 100644 --- a/Tests/AgentsManifestTests/CompiledFixtures.swift +++ b/Tests/AgentsManifestTests/CompiledFixtures.swift @@ -21,16 +21,12 @@ func compiledFixtures() -> [CompiledManifestFixture] { compiledExportedGroup(), compiledInstructionRecipients(), compiledLiteralCoverage(), - compiledMigrationAliasGap(), - compiledMigrationAliases(), - compiledMigrationDuplicateRecipients(), - compiledMigrationEdgeExample(), - compiledMigrationEmpty(), - compiledMigrationEscapes(), - compiledMigrationExplicitEmpty(), - compiledMigrationFields(), - compiledMigrationRanges(), - compiledMigrationWidth(), + compiledPrintedEmpty(), + compiledPrintedEscapes(), + compiledPrintedExplicitEmpty(), + compiledPrintedFields(), + compiledPrintedRanges(), + compiledPrintedWidth(), compiledProducerExample(), compiledRecipientConditions(), compiledRequirementValues(), @@ -352,200 +348,18 @@ private func compiledLiteralCoverage() -> CompiledManifestFixture { ]) } -private func compiledMigrationAliasGap() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - sources: [ - .source(name: "source", path: "live"), - .source(name: "source-2", path: "other"), - ], - components: [ - .skills( - source: "source", - overrides: [ - .skill(name: "future") - ] - ) - ] - ) - return CompiledManifestFixture( - name: "MigrationAliasGap.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledMigrationAliases() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - sources: [ - .source(name: "source", path: "./s"), - .source(name: "source-2", path: "./s2"), - .source(name: "source-3", url: "git@Intranet:team/rules.git"), - ], - components: [ - .skills( - source: "source-3", - select: ["a"], - exclude: ["a"], - overrides: [ - .skill(name: "a", mode: .copy) - ] - ), - .instructions( - sections: [ - "guide", - .section(name: "rule", source: "source-3"), - .section(name: "rule", source: "source-3"), - ], - chatGPT: [ - .prompt( - name: "", - sections: [ - .section(name: "rule", source: "source-3"), - "guide", - ] - ) - ] - ), - ], - watch: ["source", "source-3"] - ) - return CompiledManifestFixture( - name: "MigrationAliases.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledMigrationDuplicateRecipients() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - defaultAgents: [.claudeCode, .codex], - sources: [ - .source(name: "a~/b", path: "./other"), - .source(name: "source", path: "./inherited"), - .source(name: "source-2", path: "./rules"), - ], - components: [ - .skills( - source: "a~/b", - overrides: [ - .skill( - name: "future", - agents: [.openCode] - ) - ], - agents: [] - ), - .skills(source: "source"), - .skills( - source: "source-2", - select: ["empty", "inherited", "review"], - exclude: ["review"], - overrides: [ - .skill( - name: "empty", - agents: [] - ), - .skill(name: "inherited", mode: .copy), - .skill( - name: "review", - agents: [.codex, .cursor] - ), - ], - agents: [.claudeCode, .openCode] - ), - .instructions( - sections: [ - "guide", - .section(name: "rule", source: "source-2"), - ], - agents: [.codex, .geminiCLI] - ), - ], - watch: ["source-2"] - ) - return CompiledManifestFixture( - name: "MigrationDuplicateRecipients.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledMigrationEdgeExample() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - sources: [ - .source(name: "source", path: "./drafts", from: "1.2.0"), - .source( - name: "source-2", - path: "./more", - .upToNextMinor(from: "1.2.0") - ), - .source(name: "source-3", url: "https://example.org/rules.git"), - ], - components: [ - .skills( - source: "source", - overrides: [ - .skill( - name: "future", - agents: [.openCode] - ) - ] - ), - .skills( - source: "source-3", - select: ["a"], - overrides: [ - .skill( - name: "a", - mode: .copy, - agents: [.codex] - ) - ] - ), - .instructions( - sections: [ - "guide", - .section(name: "rule", source: "source-3"), - ], - chatGPT: [ - .prompt( - name: "", - sections: [ - .section(name: "rule", source: "source-3") - ] - ) - ] - ), - ], - watch: ["source-3"] - ) - return CompiledManifestFixture( - name: "MigrationEdgeExample.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledMigrationEmpty() -> CompiledManifestFixture { +private func compiledPrintedEmpty() -> CompiledManifestFixture { // agents-tools-version: 1.0 let agents = Agents() return CompiledManifestFixture( - name: "MigrationEmpty.swift.txt", agents: agents, + name: "PrintedEmpty.swift.txt", agents: agents, constants: [ "agents": agents.constructionValue ]) } -private func compiledMigrationEscapes() -> CompiledManifestFixture { +private func compiledPrintedEscapes() -> CompiledManifestFixture { // agents-tools-version: 1.0 let agents = Agents( @@ -573,13 +387,13 @@ private func compiledMigrationEscapes() -> CompiledManifestFixture { ] ) return CompiledManifestFixture( - name: "MigrationEscapes.swift.txt", agents: agents, + name: "PrintedEscapes.swift.txt", agents: agents, constants: [ "agents": agents.constructionValue ]) } -private func compiledMigrationExplicitEmpty() -> CompiledManifestFixture { +private func compiledPrintedExplicitEmpty() -> CompiledManifestFixture { // agents-tools-version: 1.0 let agents = Agents( @@ -591,13 +405,13 @@ private func compiledMigrationExplicitEmpty() -> CompiledManifestFixture { ] ) return CompiledManifestFixture( - name: "MigrationExplicitEmpty.swift.txt", agents: agents, + name: "PrintedExplicitEmpty.swift.txt", agents: agents, constants: [ "agents": agents.constructionValue ]) } -private func compiledMigrationFields() -> CompiledManifestFixture { +private func compiledPrintedFields() -> CompiledManifestFixture { // agents-tools-version: 1.0 let agents = Agents( @@ -674,13 +488,13 @@ private func compiledMigrationFields() -> CompiledManifestFixture { watch: ["git", "index", "local"] ) return CompiledManifestFixture( - name: "MigrationFields.swift.txt", agents: agents, + name: "PrintedFields.swift.txt", agents: agents, constants: [ "agents": agents.constructionValue ]) } -private func compiledMigrationRanges() -> CompiledManifestFixture { +private func compiledPrintedRanges() -> CompiledManifestFixture { // agents-tools-version: 1.0 let agents = Agents( @@ -725,13 +539,13 @@ private func compiledMigrationRanges() -> CompiledManifestFixture { ] ) return CompiledManifestFixture( - name: "MigrationRanges.swift.txt", agents: agents, + name: "PrintedRanges.swift.txt", agents: agents, constants: [ "agents": agents.constructionValue ]) } -private func compiledMigrationWidth() -> CompiledManifestFixture { +private func compiledPrintedWidth() -> CompiledManifestFixture { // agents-tools-version: 1.0 let agents = Agents( @@ -756,7 +570,7 @@ private func compiledMigrationWidth() -> CompiledManifestFixture { ] ) return CompiledManifestFixture( - name: "MigrationWidth.swift.txt", agents: agents, + name: "PrintedWidth.swift.txt", agents: agents, constants: [ "agents": agents.constructionValue ]) diff --git a/Tests/AgentsManifestTests/DeclarationPropertyTests.swift b/Tests/AgentsManifestTests/DeclarationPropertyTests.swift new file mode 100644 index 0000000..73e0f37 --- /dev/null +++ b/Tests/AgentsManifestTests/DeclarationPropertyTests.swift @@ -0,0 +1,207 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsManifest + +/// Deterministic declarations over a small alias, name and section vocabulary. +private struct DeclarationGenerator { + var random = ManifestRandom(state: 0x5eed_2026_1030) + + mutating func flip() -> Bool { random.next(2) == 0 } + + mutating func subset(_ values: [T]) -> [T] { values.filter { _ in flip() } } + + mutating func recipients() -> [AgentID]? { + switch random.next(3) { + case 0: return nil + case 1: return [] + default: return subset(AgentID.allCases) + } + } + + mutating func source(_ alias: String) -> SourceDeclaration { + let requirements: [SourceRequirement?] = [ + nil, .branch("main"), .revision("abc123"), .exact("1.2.3"), .upToNextMajor(from: "1.2.0"), + .upToNextMinor(from: "1.2.0"), .range(from: "1.2.0", to: "1.5.0"), + ] + let subpath = flip() ? nil : "skills" + switch random.next(3) { + case 0: + return SourceDeclaration( + kind: .git, location: "example.org/team/\(alias).git", + requirement: requirements[random.next(requirements.count)], path: subpath) + case 1: + return SourceDeclaration( + kind: .local, location: "./\(alias)", + requirement: requirements[random.next(requirements.count)], path: subpath) + default: + return SourceDeclaration( + kind: .wellKnown, location: "https://example.org/\(alias)/index.json", path: subpath) + } + } + + mutating func skills() -> SkillDeclaration { + let names = ["x", "y", "z"] + let select: SkillSelection = flip() ? .all : .names(subset(names)) + var overrides: [String: SkillOverride] = [:] + let candidates: [String] + if case .names(let selected) = select { candidates = selected } else { candidates = names } + for name in subset(candidates) { + overrides[name] = SkillOverride( + agents: recipients(), mode: [nil, .copy, .link][random.next(3)]) + } + return SkillDeclaration( + select: select, exclude: flip() ? nil : subset(names), agents: recipients(), + mode: [nil, .copy, .link][random.next(3)], overrides: flip() ? nil : overrides) + } + + mutating func sections(_ aliases: [String]) -> [String] { + let pool = ["guide", "rules"] + aliases.map { $0 + ":guide" } + return (0.. InstructionsDeclaration? { + guard flip() else { return nil } + var prompts: [String: PromptDeclaration] = [:] + for name in subset(["daily", "weekly"]) { + prompts[name] = PromptDeclaration( + sections: sections(aliases), append: flip() ? nil : "notes/\(name).md") + } + return InstructionsDeclaration( + agents: recipients(), sections: sections(aliases), chatgpt: flip() ? nil : prompts) + } + + mutating func declaration() -> Declaration { + var declaration = Declaration(agents: recipients()) + for alias in subset(["a", "b", "c", "d"]) { + declaration.sources[alias] = source(alias) + } + let aliases = declaration.sources.keys.sorted() + var skills: [String: SkillDeclaration] = [:] + for alias in subset(aliases) { skills[alias] = self.skills() } + declaration.skills = skills.isEmpty && flip() ? nil : skills + declaration.instructions = instructions(aliases) + declaration.watch = flip() ? nil : subset(aliases) + return declaration + } + + /// A neighbor of `base`: each part is kept, changed or removed, and references follow sources. + mutating func change(_ base: Declaration) -> Declaration { + var result = base + if random.next(3) == 0 { result.agents = recipients() } + for alias in base.sources.keys.sorted() { + switch random.next(4) { + case 0: result.sources[alias] = nil + case 1: result.sources[alias] = source(alias) + default: break + } + } + for alias in ["e", "f"] where random.next(3) == 0 { result.sources[alias] = source(alias) } + let aliases = result.sources.keys.sorted() + var skills = (result.skills ?? [:]).filter { result.sources[$0.key] != nil } + for alias in aliases where random.next(3) == 0 { + skills[alias] = flip() ? nil : self.skills() + } + result.skills = skills + let referenced = result.instructions.map { + ($0.sections + ($0.chatgpt ?? [:]).values.flatMap(\.sections)).allSatisfy { + !$0.contains(":") || result.sources[String($0.split(separator: ":")[0])] != nil + } + } + if referenced == false || random.next(3) == 0 { result.instructions = instructions(aliases) } + result.watch = random.next(3) == 0 ? subset(aliases) : result.watch?.filter(aliases.contains) + return result + } +} + +private func equivalent(_ lhs: Declaration, _ rhs: Declaration) -> Bool { + ManifestProjection.equivalent(lhs, rhs, environment: projectionEnvironment) +} + +private func projection(of bytes: [UInt8]) throws -> Declaration { + try ManifestProjection.declaration( + of: DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")), + environment: projectionEnvironment) +} + +/// Comments above every source, skills and instructions entry that `next` keeps unchanged. +private func commented(_ text: String, keeping kept: [String]) -> String { + var lines = text.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) + for marker in kept { + let (call, name) = (marker.split(separator: " ")[0], marker.split(separator: " ")[1]) + guard + let index = lines.indices.first(where: { index in + let line = lines[index].trimmingCharacters(in: .whitespaces) + let next = index + 1 < lines.count ? lines[index + 1] : "" + return line.hasPrefix(String(call) + "(") + && (line.contains("\"\(name)\"") + || !line.hasSuffix(")") && !line.hasSuffix("),") + && next.contains("\"\(name)\"")) + }) + else { continue } + let indentation = lines[index].prefix { $0 == " " } + lines.insert(indentation + "// keep " + marker, at: index) + } + lines.insert("// file comment", at: 3) + return lines.joined(separator: "\n") + "// end of file\n" +} + +@Suite("Declaration properties") +struct DeclarationPropertyTests { + @Test func printedDeclarationsProjectToThemselves() throws { + var generator = DeclarationGenerator() + for _ in 0..<96 { + let declaration = generator.declaration() + try declaration.validate(environment: projectionEnvironment) + guard let bytes = try planned(Declaration(), declaration, in: nil) else { + #expect(equivalent(declaration, Declaration())) + continue + } + #expect(try planned(Declaration(), declaration, in: nil) == bytes) + #expect(equivalent(try projection(of: bytes), declaration), "\(declaration)") + } + } + + @Test func plansReachTheirTargetAndKeepCommentsOfUnchangedEntries() throws { + var generator = DeclarationGenerator() + var (edited, markers) = (0, 0) + for _ in 0..<96 { + let previous = generator.declaration() + let next = generator.change(previous) + try next.validate(environment: projectionEnvironment) + let printed = String( + decoding: try planned(Declaration(), previous, in: nil) ?? [], as: UTF8.self) + guard !printed.isEmpty else { continue } + var kept: [String] = [] + for alias in previous.sources.keys.sorted() { + if let source = next.sources[alias], source == previous.sources[alias] { + kept.append(".source \(alias)") + } + } + for alias in (previous.skills ?? [:]).keys.sorted() + where next.skills?[alias] == previous.skills?[alias] { + kept.append(".skills \(alias)") + } + let text = commented(printed, keeping: kept) + let bytes = try planned(previous, next, in: text) + guard let bytes else { + #expect(equivalent(previous, next)) + continue + } + #expect(equivalent(try projection(of: bytes), next), "\(previous) -> \(next)") + let result = String(decoding: bytes, as: UTF8.self) + #expect( + result.contains( + "// agents-tools-version: 1.0\nimport AgentsDescription\n\n// file comment\n")) + #expect(result.hasSuffix(")\n// end of file\n")) + for marker in kept { + #expect(result.components(separatedBy: "// keep " + marker + "\n").count == 2, "\(marker)") + } + edited += 1 + markers += kept.count + } + // The seed must exercise edits and retained comments, not only no-op or empty plans. + #expect(edited >= 64 && markers >= 64) + } +} diff --git a/Tests/AgentsManifestTests/DumpTests.swift b/Tests/AgentsManifestTests/DumpTests.swift index ac12fa9..bc8dd26 100644 --- a/Tests/AgentsManifestTests/DumpTests.swift +++ b/Tests/AgentsManifestTests/DumpTests.swift @@ -7,7 +7,7 @@ import Testing @Suite("Evaluated manifest dump") struct DumpTests { @Test(arguments: [ - "MigrationEmpty", "MigrationFields", "DumpSymbolic", "ConsumerExample", "LiteralCoverage", + "PrintedEmpty", "PrintedFields", "DumpSymbolic", "ConsumerExample", "LiteralCoverage", ]) func completeGoldenObjectsAndLocationsAreByteExact(_ name: String) throws { let bytes = try manifestFixture(name + ".swift.txt") diff --git a/Tests/AgentsManifestTests/EditPlanTests.swift b/Tests/AgentsManifestTests/EditPlanTests.swift new file mode 100644 index 0000000..3420315 --- /dev/null +++ b/Tests/AgentsManifestTests/EditPlanTests.swift @@ -0,0 +1,619 @@ +import AgentsCore +import AgentsDescription +import Foundation +import Testing + +@testable import AgentsManifest + +func planned(_ previous: Declaration, _ next: Declaration, in text: String?) throws -> [UInt8]? { + try DeclarationEditPlan.bytes( + replacing: previous, with: next, in: text.map { Array($0.utf8) }, + identity: DocumentIdentity("manifest"), environment: projectionEnvironment) +} + +private func expectChange( + _ body: String, to expected: String, sourceLocation: SourceLocation = #_sourceLocation, + _ update: (inout Declaration) -> Void +) throws { + let result = try changed(body, update) + #expect(result == expected, sourceLocation: sourceLocation) +} + +/// Plans a change to a manifest body and returns the edited body, checked against the intent. +private func changed(_ body: String, _ update: (inout Declaration) -> Void) throws -> String { + let previous = try projected(body) + var next = previous + update(&next) + let bytes = try #require(try planned(previous, next, in: manifestHeader + body)) + let text = String(decoding: bytes, as: UTF8.self) + #expect(text.hasPrefix(manifestHeader)) + let result = String(text.dropFirst(manifestHeader.count)) + let reparsed = try projected(result) + #expect(ManifestProjection.equivalent(reparsed, next, environment: projectionEnvironment)) + return result +} + +private let local = SourceDeclaration(kind: .local, location: "s") + +@Suite("Declaration edit planning") +struct EditPlanTests { + @Test func equivalentSpellingsAndLayoutPlanNoEdit() throws { + let body = """ + let agents = Agents(defaultAgents:[.codex,.claudeCode], + sources: [.source(name: "g", url: "github.com/team/skills", "1.2.0" ..< "2.0.0"), + .source(name: "l", path: "./rules/", subpath: "./skills"),], + components: [.skills(source: "g", select: ["b", "a"], exclude: [])], + watch: ["l", "g"]) + """ + let previous = try projected(body) + var next = previous + next.agents = [.claudeCode, .codex] + next.sources["g"] = SourceDeclaration( + kind: .git, location: "https://GitHub.com/team/skills.git", + requirement: .upToNextMajor(from: "1.2.0")) + next.sources["l"] = SourceDeclaration( + kind: .local, location: "/work/project/rules", path: "skills") + next.skills?["g"] = SkillDeclaration(select: .names(["a", "b"])) + next.watch = ["g", "l"] + #expect(try planned(previous, next, in: manifestHeader + body) == nil) + #expect(try planned(Declaration(), Declaration(), in: nil) == nil) + } + + @Test func defaultAgentsChangeByElementOrWholeArgument() throws { + let body = """ + let agents = Agents( + // recipients + defaultAgents: [.codex /* keep */, .openCode], + watch: [] + ) + """ + try expectChange( + body, + to: """ + let agents = Agents( + // recipients + defaultAgents: [.claudeCode, .codex /* keep */], + watch: [] + ) + """ + ) { $0.agents = [.codex, .claudeCode] } + expectManifestFailure("manifest.edit.readOnly") { try changed(body) { $0.agents = nil } } + try expectChange( + "let agents = Agents(defaultAgents: [.codex], watch: [])", + to: "let agents = Agents(defaultAgents: nil, watch: [])" + ) { $0.agents = nil } + try expectChange( + "let agents = Agents(watch: [])", + to: "let agents = Agents(defaultAgents: [.codex, .cursor], watch: [])" + ) { $0.agents = [.cursor, .codex] } + } + + @Test func sourcesAppendReplaceInPlaceAndLeaveWithTheirReferences() throws { + let body = """ + let agents = Agents( + sources: [ + // team + .source(name: "team", url: "https://e.org/t", branch: "main"), // pin + .source(name: "s", path: "s"), + ], + components: [ + .skills(source: "s"), + ], + watch: ["s"] + ) + """ + try expectChange( + body, + to: """ + let agents = Agents( + sources: [ + // team + .source(name: "team", url: "https://e.org/t", revision: "abc123"), // pin + .source(name: "s", path: "s"), + .source(name: "new", url: "https://github.com/a/new"), + ], + components: [ + .skills(source: "s"), + ], + watch: ["s"] + ) + """ + ) { + $0.sources["team"]?.requirement = .revision("abc123") + $0.sources["new"] = SourceDeclaration(kind: .git, location: "github.com/a/new") + } + try expectChange( + body, + to: """ + let agents = Agents( + sources: [ + // team + .source(name: "team", url: "https://e.org/t", branch: "main"), // pin + ], + components: [ + ], + watch: [] + ) + """ + ) { + $0.sources["s"] = nil + $0.skills = nil + $0.watch = nil + } + } + + @Test func newSkillsComponentsPrecedeInstructionsOrAppend() throws { + let body = """ + let agents = Agents( + sources: [.source(name: "a", path: "a"), .source(name: "b", path: "b")], + components: [ + // rules + .instructions(sections: ["guide"]), + ] + ) + """ + try expectChange( + body, + to: """ + let agents = Agents( + sources: [.source(name: "a", path: "a"), .source(name: "b", path: "b")], + components: [ + .skills( + source: "a", + select: ["x"] + ), + .skills(source: "b"), + // rules + .instructions(sections: ["guide"]), + ] + ) + """ + ) { + $0.skills = [ + "b": SkillDeclaration(select: .all), "a": SkillDeclaration(select: .names(["x"])), + ] + } + try expectChange( + "let agents = Agents(sources: [.source(name: \"a\", path: \"a\")])", + to: """ + let agents = Agents(sources: [.source(name: "a", path: "a")], components: [ + .skills(source: "a"), + ]) + """ + ) { $0.skills = ["a": SkillDeclaration(select: .all)] } + } + + @Test func selectionSwitchesAndNameEditsKeepOrder() throws { + let body = """ + let agents = Agents( + sources: [.source(name: "s", path: "s")], + components: [ + .skills(source: "s", select: ["a", "c" /* c */, "e"]), + ] + ) + """ + try expectChange( + body, + to: """ + let agents = Agents( + sources: [.source(name: "s", path: "s")], + components: [ + .skills(source: "s", select: ["b", "c" /* c */, "d", "e"]), + ] + ) + """ + ) { $0.skills?["s"]?.select = .names(["b", "c", "d", "e"]) } + expectManifestFailure("manifest.edit.readOnly") { + try changed(body) { $0.skills?["s"]?.select = .all } + } + let plain = """ + let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ + .skills(source: "s", select: .all), + ]) + """ + try expectChange( + plain, + to: """ + let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ + .skills(source: "s", select: ["y", "z"]), + ]) + """ + ) { $0.skills?["s"]?.select = .names(["z", "y"]) } + try expectChange( + plain.replacingOccurrences(of: ".all", with: "[\"a\"]"), + to: plain + ) { $0.skills?["s"]?.select = .all } + } + + @Test func excludeAgentsAndModeAreArgumentEdits() throws { + let body = """ + let agents = Agents( + sources: [.source(name: "s", path: "s")], + components: [ + .skills( + // all team skills + source: "s", + mode: .copy + ), + ] + ) + """ + try expectChange( + body, + to: """ + let agents = Agents( + sources: [.source(name: "s", path: "s")], + components: [ + .skills( + // all team skills + source: "s", + exclude: ["x"], + mode: nil, + agents: [] + ), + ] + ) + """ + ) { + $0.skills?["s"]?.exclude = ["x"] + $0.skills?["s"]?.mode = nil + $0.skills?["s"]?.agents = [] + } + try expectChange( + """ + let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ + .skills(source: "s", exclude: ["a", "c"], agents: [.codex]), + ]) + """, + to: """ + let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ + .skills(source: "s", exclude: ["b", "c"], mode: .link, agents: [.claudeCode, .codex]), + ]) + """ + ) { + $0.skills?["s"]?.exclude = ["b", "c"] + $0.skills?["s"]?.agents = [.codex, .claudeCode] + $0.skills?["s"]?.mode = .link + } + } + + @Test func overridesAreUpsertedAndRemovedByName() throws { + let body = """ + let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ + .skills(source: "s", select: ["a", "b"], overrides: [ + .skill(name: "a", mode: .copy), // copy a + .skill(name: "b"), + ]), + ]) + """ + try expectChange( + body, + to: """ + let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ + .skills(source: "s", select: ["a", "c"], overrides: [ + .skill(name: "a", mode: .copy), // copy a + .skill( + name: "c", + agents: [.codex] + ), + ]), + ]) + """ + ) { + $0.skills?["s"]?.overrides = [ + "a": SkillOverride(mode: .copy), "c": SkillOverride(agents: [.codex]), + ] + $0.skills?["s"]?.select = .names(["a", "c"]) + } + } + + @Test func instructionsComponentsAreAddedRemovedAndRetargeted() throws { + try expectChange( + """ + let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ + // skills + .skills(source: "s"), + ]) + """, + to: """ + let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ + // skills + .skills(source: "s"), + .instructions( + sections: ["guide"] + ), + ]) + """ + ) { $0.instructions = InstructionsDeclaration(sections: ["guide"]) } + let body = """ + let agents = Agents(components: [ + // rules + .instructions(sections: ["guide"], agents: [.codex]), + ]) + """ + try expectChange(body, to: "let agents = Agents(components: [\n])") { + $0.instructions = nil + } + try expectChange( + body, + to: """ + let agents = Agents(components: [ + // rules + .instructions(sections: ["guide"], agents: [.cursor]), + ]) + """ + ) { $0.instructions?.agents = [.cursor] } + } + + @Test func sectionsFollowTheLongestCommonSubsequenceAndKeepDuplicates() throws { + let body = """ + let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ + .instructions(sections: [ + "a", // first a + "b", + "a", + .section(name: "c", source: "s"), + ]), + ]) + """ + try expectChange( + body, + to: """ + let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ + .instructions(sections: [ + "a", // first a + "x", + "a", + .section(name: "c", source: "s"), + "a", + "y", + ]), + ]) + """ + ) { $0.instructions?.sections = ["a", "x", "a", "s:c", "a", "y"] } + try expectChange( + body, + to: """ + let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ + .instructions(sections: [ + "b", + ]), + ]) + """ + ) { $0.instructions?.sections = ["b"] } + } + + @Test func promptsAreUpsertedAndRemovedByName() throws { + let body = """ + let agents = Agents(components: [ + .instructions(chatGPT: [ + .prompt(name: "daily", sections: ["guide"]), // daily + .prompt(name: "weekly", sections: ["guide"]), + ]), + ]) + """ + try expectChange( + body, + to: """ + let agents = Agents(components: [ + .instructions(chatGPT: [ + .prompt( + name: "daily", + sections: ["guide", "notes"] + ), // daily + .prompt( + name: "monthly", + sections: [], + append: "notes/monthly.md" + ), + ]), + ]) + """ + ) { + $0.instructions?.chatgpt = [ + "daily": PromptDeclaration(sections: ["guide", "notes"]), + "monthly": PromptDeclaration(sections: [], append: "notes/monthly.md"), + ] + } + } + + @Test func watchChangesByElementOrWholeArgument() throws { + let sources = + "sources: [.source(name: \"a\", path: \"a\"), .source(name: \"b\", path: \"b\"), .source(name: \"c\", path: \"c\")]" + try expectChange( + "let agents = Agents(\n \(sources),\n watch: [\"a\", \"c\"] // watched\n)", + to: "let agents = Agents(\n \(sources),\n watch: [\"b\", \"c\"] // watched\n)" + ) { $0.watch = ["b", "c"] } + try expectChange( + "let agents = Agents(sources: [.source(name: \"a\", path: \"a\")])", + to: "let agents = Agents(sources: [.source(name: \"a\", path: \"a\")], watch: [\"a\"])" + ) { $0.watch = ["a"] } + } + + @Test func sharedConstantsAndCommentedReplacementsAreReadOnly() throws { + let constant = """ + let picked: SkillSelection = ["a"] + let agents = Agents(sources: [.source(name: "s", path: "s")], components: [.skills(source: "s", select: picked)]) + """ + let previous = try projected(constant) + var next = previous + next.skills?["s"]?.select = .names(["a", "b"]) + expectManifestFailure("manifest.edit.readOnly") { + try planned(previous, next, in: manifestHeader + constant) + } + let commented = """ + let agents = Agents(sources: [.source(name: "s", /* pinned */ url: "https://e.org/s.git", branch: "main")]) + """ + let source = try projected(commented) + var moved = source + moved.sources["s"]?.requirement = .branch("next") + expectManifestFailure("manifest.edit.readOnly") { + try planned(source, moved, in: manifestHeader + commented) + } + } + + @Test func largeChangesAreSplitIntoReplannedBatches() throws { + var next = Declaration() + for index in 0..<150 { + next.sources["s\(index)"] = SourceDeclaration(kind: .local, location: "s\(index)") + } + var batches: [Int] = [] + let bytes = try #require( + try DeclarationEditPlan.bytes( + replacing: Declaration(), with: next, + in: Array((manifestHeader + "let agents = Agents()").utf8), + identity: DocumentIdentity("manifest"), environment: projectionEnvironment, + planning: { + batches.append($0.count) + return $0 + })) + #expect(batches == [150, 50, 0]) + let result = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) + #expect(result.declaration.sources.count == 150) + } + + @Test func previousMustDescribeTheDocument() throws { + let body = "let agents = Agents(sources: [.source(name: \"s\", path: \"s\")])" + let stale = Declaration(sources: ["s": local, "t": local]) + expectManifestFailure("manifest.edit.baseline") { + try planned(stale, stale, in: manifestHeader + body) + } + expectManifestFailure("manifest.edit.baseline") { + try planned(Declaration(sources: ["s": local]), Declaration(), in: nil) + } + } + + @Test func plannerOmissionsFailTheFinalComparison() throws { + var next = Declaration(sources: ["s": local]) + next.watch = ["s"] + expectManifestFailure("manifest.edit.mismatch") { + try DeclarationEditPlan.bytes( + replacing: Declaration(), with: next, + in: Array((manifestHeader + "let agents = Agents()").utf8), + identity: DocumentIdentity("manifest"), environment: projectionEnvironment, + planning: { Array($0.dropLast()) }) + } + } + + @Test func repeatedEditsOfACommentedManifestKeepUnrelatedBytes() throws { + var body = """ + // Team manifest: keep this header. + let agents = Agents( + // Recipients for everything below. + defaultAgents: [.claudeCode, .codex], + sources: [ + // Shared team skills. + .source(name: "team", url: "https://github.com/team/skills", from: "1.0.0"), + // Local drafts stay editable. + .source(name: "drafts", path: "./drafts"), + ], + components: [ + // Everything from the team. + .skills( + // pinned upstream + source: "team" + ), + // Drafts linked for editing. + .skills(source: "drafts", mode: .edit), + // House rules. + .instructions( + sections: [ + "guide", // first + .section(name: "rules", source: "team"), + ] + ), + ], + // Watched for upstream changes. + watch: ["team"] + ) + // trailing note + + """ + let kept = [ + "// Team manifest: keep this header.\nlet agents = Agents(\n", + " // Recipients for everything below.\n defaultAgents: [.claudeCode, .codex],\n", + " // Shared team skills.\n .source(name: \"team\", url: \"https://github.com/team/skills\", from: \"1.0.0\"),\n", + " // Everything from the team.\n .skills(\n // pinned upstream\n source: \"team\"", + " // House rules.\n .instructions(\n sections: [\n \"guide\", // first\n", + " .section(name: \"rules\", source: \"team\"),\n", + " // Watched for upstream changes.\n watch: [", + ")\n// trailing note\n", + ] + func expectKept(_ text: String, sourceLocation: SourceLocation = #_sourceLocation) { + var remainder = text[...] + for segment in kept { + guard let range = remainder.range(of: segment) else { + Issue.record("missing unchanged bytes: \(segment)", sourceLocation: sourceLocation) + return + } + remainder = remainder[range.upperBound...] + } + } + let steps: [(inout Declaration) -> Void] = [ + { $0.skills?["team"]?.exclude = ["deprecated"] }, + { + $0.sources["extra"] = SourceDeclaration(kind: .git, location: "github.com/team/extra") + $0.skills?["extra"] = SkillDeclaration(select: .names(["one"])) + }, + { + $0.instructions?.sections.append("extra:style") + $0.instructions?.agents = [.codex] + }, + { $0.watch?.append("extra") }, + { + $0.sources["drafts"] = nil + $0.skills?["drafts"] = nil + }, + { $0.instructions?.chatgpt = ["weekly": PromptDeclaration(sections: ["guide"])] }, + ] + for step in steps { + body = try changed(body, step) + expectKept(body) + } + #expect(!body.contains("drafts")) + #expect( + body == """ + // Team manifest: keep this header. + let agents = Agents( + // Recipients for everything below. + defaultAgents: [.claudeCode, .codex], + sources: [ + // Shared team skills. + .source(name: "team", url: "https://github.com/team/skills", from: "1.0.0"), + .source(name: "extra", url: "https://github.com/team/extra"), + ], + components: [ + // Everything from the team. + .skills( + // pinned upstream + source: "team", + exclude: ["deprecated"] + ), + .skills( + source: "extra", + select: ["one"] + ), + // House rules. + .instructions( + sections: [ + "guide", // first + .section(name: "rules", source: "team"), + .section(name: "style", source: "extra"), + ], + chatGPT: [ + .prompt( + name: "weekly", + sections: ["guide"] + ), + ], + agents: [.codex] + ), + ], + // Watched for upstream changes. + watch: ["extra", "team"] + ) + // trailing note + + """) + } +} diff --git a/Tests/AgentsManifestTests/EditingTests.swift b/Tests/AgentsManifestTests/EditingTests.swift index 8e2bacf..cf3a125 100644 --- a/Tests/AgentsManifestTests/EditingTests.swift +++ b/Tests/AgentsManifestTests/EditingTests.swift @@ -167,6 +167,28 @@ struct EditingTests { #expect(source.contains("// file\r\n")) } + @Test func equivalentRangeSourceUpsertKeepsOriginalBytes() throws { + let doc = try document( + "let agents = Agents(sources: [.source(name: \"b\", path: \"./b\", from: \"1.2.0\")])") + let change = try doc.preparing([ + .upsertSource(.source(name: "b", path: "./b", "1.2.0"..<"2.0.0")) + ]) + #expect(change.bytes == doc.bytes && change.patches.isEmpty) + } + + @Test func printedWidthCountsLabelsCommasAndUTF8Bytes() { + let printer = CanonicalPrinter() + let atBoundary = Source.source(name: String(repeating: "a", count: 47), path: "p") + .constructionValue + let overBoundary = Source.source(name: String(repeating: "a", count: 48), path: "p") + .constructionValue + #expect(!printer.render(atBoundary, indentation: " ").contains("\n")) + #expect(printer.render(overBoundary, indentation: " ").contains("\n")) + let unicode = Source.source(name: String(repeating: "é", count: 24), path: "p") + .constructionValue + #expect(printer.render(unicode, indentation: " ").contains("\n")) + } + @Test func noOpsKeepOriginalBytesAndUnsafeEditsPublishNothing() throws { let doc = try document( "let agents = Agents(defaultAgents: nil, sources: [.source(name: \"s\", url: \"https://example.org/s.git\", \"1.2.0\" ..< \"2.0.0\")], components: [/*container*/])" diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationAliasGap.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationAliasGap.migration.json deleted file mode 100644 index cbec071..0000000 --- a/Tests/AgentsManifestTests/Fixtures/MigrationAliasGap.migration.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "sources": { - ".": { - "local": "live" - }, - "source-2": { - "local": "other" - } - }, - "skills": { - ".": { - "select": "all", - "overrides": { - "future": {} - } - } - } -} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationAliasGap.swift.txt b/Tests/AgentsManifestTests/Fixtures/MigrationAliasGap.swift.txt deleted file mode 100644 index 914c704..0000000 --- a/Tests/AgentsManifestTests/Fixtures/MigrationAliasGap.swift.txt +++ /dev/null @@ -1,17 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - sources: [ - .source(name: "source", path: "live"), - .source(name: "source-2", path: "other"), - ], - components: [ - .skills( - source: "source", - overrides: [ - .skill(name: "future"), - ] - ), - ] -) diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationAliases.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationAliases.migration.json deleted file mode 100644 index 691d375..0000000 --- a/Tests/AgentsManifestTests/Fixtures/MigrationAliases.migration.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "sources": { - ".": { - "git": "git@Intranet:team/rules.git" - }, - "source": { - "local": "./s" - }, - "source-2": { - "local": "./s2" - } - }, - "skills": { - ".": { - "select": [ - "a" - ], - "exclude": [ - "a" - ], - "overrides": { - "a": { - "mode": "copy" - }, - "b": {} - } - } - }, - "instructions": { - "sections": [ - "guide", - ".:rule", - ".:rule" - ], - "chatgpt": { - "": { - "sections": [ - ".:rule", - "guide" - ] - } - } - }, - "watch": [ - ".", - "source" - ] -} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationAliases.swift.txt b/Tests/AgentsManifestTests/Fixtures/MigrationAliases.swift.txt deleted file mode 100644 index ccaf17a..0000000 --- a/Tests/AgentsManifestTests/Fixtures/MigrationAliases.swift.txt +++ /dev/null @@ -1,37 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - sources: [ - .source(name: "source", path: "./s"), - .source(name: "source-2", path: "./s2"), - .source(name: "source-3", url: "git@Intranet:team/rules.git"), - ], - components: [ - .skills( - source: "source-3", - select: ["a"], - exclude: ["a"], - overrides: [ - .skill(name: "a", mode: .copy), - ] - ), - .instructions( - sections: [ - "guide", - .section(name: "rule", source: "source-3"), - .section(name: "rule", source: "source-3"), - ], - chatGPT: [ - .prompt( - name: "", - sections: [ - .section(name: "rule", source: "source-3"), - "guide", - ] - ), - ] - ), - ], - watch: ["source", "source-3"] -) diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationDuplicateRecipients.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationDuplicateRecipients.migration.json deleted file mode 100644 index c60e2a0..0000000 --- a/Tests/AgentsManifestTests/Fixtures/MigrationDuplicateRecipients.migration.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "agents": ["codex", "claude-code", "codex", "codex", "claude-code"], - "sources": { - ".": {"local": "./rules"}, - "a~/b": {"local": "./other"}, - "source": {"local": "./inherited"} - }, - "skills": { - ".": { - "select": ["review", "empty", "inherited"], - "exclude": ["review"], - "agents": ["opencode", "claude-code", "opencode", "claude-code"], - "overrides": { - "review": {"agents": ["cursor", "codex", "cursor", "codex"]}, - "empty": {"agents": []}, - "inherited": {"mode": "copy"}, - "unused": {"agents": ["gemini-cli", "gemini-cli"], "mode": "copy"} - } - }, - "a~/b": { - "select": "all", - "agents": [], - "overrides": { - "future": {"agents": ["opencode", "opencode"]} - } - }, - "source": {"select": "all"} - }, - "instructions": { - "agents": ["gemini-cli", "codex", "gemini-cli", "codex"], - "sections": ["guide", ".:rule"] - }, - "watch": ["."] -} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationDuplicateRecipients.swift.txt b/Tests/AgentsManifestTests/Fixtures/MigrationDuplicateRecipients.swift.txt deleted file mode 100644 index 8b919e6..0000000 --- a/Tests/AgentsManifestTests/Fixtures/MigrationDuplicateRecipients.swift.txt +++ /dev/null @@ -1,49 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - defaultAgents: [.claudeCode, .codex], - sources: [ - .source(name: "a~/b", path: "./other"), - .source(name: "source", path: "./inherited"), - .source(name: "source-2", path: "./rules"), - ], - components: [ - .skills( - source: "a~/b", - overrides: [ - .skill( - name: "future", - agents: [.openCode] - ), - ], - agents: [] - ), - .skills(source: "source"), - .skills( - source: "source-2", - select: ["empty", "inherited", "review"], - exclude: ["review"], - overrides: [ - .skill( - name: "empty", - agents: [] - ), - .skill(name: "inherited", mode: .copy), - .skill( - name: "review", - agents: [.codex, .cursor] - ), - ], - agents: [.claudeCode, .openCode] - ), - .instructions( - sections: [ - "guide", - .section(name: "rule", source: "source-2"), - ], - agents: [.codex, .geminiCLI] - ), - ], - watch: ["source-2"] -) diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationEdgeExample.swift.txt b/Tests/AgentsManifestTests/Fixtures/MigrationEdgeExample.swift.txt deleted file mode 100644 index b153fea..0000000 --- a/Tests/AgentsManifestTests/Fixtures/MigrationEdgeExample.swift.txt +++ /dev/null @@ -1,51 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - sources: [ - .source(name: "source", path: "./drafts", from: "1.2.0"), - .source( - name: "source-2", - path: "./more", - .upToNextMinor(from: "1.2.0") - ), - .source(name: "source-3", url: "https://example.org/rules.git"), - ], - components: [ - .skills( - source: "source", - overrides: [ - .skill( - name: "future", - agents: [.openCode] - ), - ] - ), - .skills( - source: "source-3", - select: ["a"], - overrides: [ - .skill( - name: "a", - mode: .copy, - agents: [.codex] - ), - ] - ), - .instructions( - sections: [ - "guide", - .section(name: "rule", source: "source-3"), - ], - chatGPT: [ - .prompt( - name: "", - sections: [ - .section(name: "rule", source: "source-3"), - ] - ), - ] - ), - ], - watch: ["source-3"] -) diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationEmpty.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationEmpty.migration.json deleted file mode 100644 index 0967ef4..0000000 --- a/Tests/AgentsManifestTests/Fixtures/MigrationEmpty.migration.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationEscapes.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationEscapes.migration.json deleted file mode 100644 index 352a9a1..0000000 --- a/Tests/AgentsManifestTests/Fixtures/MigrationEscapes.migration.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "agents": [], - "sources": { - "é/别名~\"\\\n\r\t\u0001…": { - "git": "https://example.org/escape.git" - } - }, - "skills": { - "é/别名~\"\\\n\r\t\u0001…": { - "select": [ - "selected" - ], - "overrides": { - "unused": { - "agents": [] - } - } - } - }, - "instructions": { - "chatgpt": { - "\"\\\n\r\t\u0001… é 😀": { - "sections": [ - "own" - ], - "append": "notes/内容.md" - } - }, - "sections": [] - } -} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationExplicitEmpty.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationExplicitEmpty.migration.json deleted file mode 100644 index 4e9f762..0000000 --- a/Tests/AgentsManifestTests/Fixtures/MigrationExplicitEmpty.migration.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "agents": [], - "sources": {}, - "skills": {}, - "instructions": { - "agents": [], - "sections": [], - "chatgpt": {} - }, - "watch": [] -} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationFields.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationFields.migration.json deleted file mode 100644 index 357f558..0000000 --- a/Tests/AgentsManifestTests/Fixtures/MigrationFields.migration.json +++ /dev/null @@ -1,100 +0,0 @@ -{ - "agents": [ - "opencode", - "claude-code", - "codex" - ], - "sources": { - "git": { - "git": "intranet/team.git", - "branch": "main", - "path": "skills" - }, - "local": { - "local": "./drafts", - "revision": "abc123" - }, - "index": { - "well-known": "https://example.org/.well-known/skills/index.json", - "path": "bundle" - }, - "empty": { - "local": "./live" - } - }, - "skills": { - "git": { - "select": [ - "b", - "a" - ], - "exclude": [ - "b" - ], - "agents": [], - "mode": "copy", - "overrides": { - "a": { - "mode": "link", - "agents": [ - "codex" - ] - }, - "b": { - "agents": [] - }, - "unused": { - "mode": "copy", - "agents": [ - "opencode", - "codex" - ] - } - } - }, - "local": { - "select": "all", - "overrides": { - "future": { - "mode": "copy" - } - } - }, - "index": { - "select": [] - }, - "empty": { - "select": "all", - "mode": "edit" - } - }, - "instructions": { - "agents": [ - "gemini-cli", - "codex" - ], - "sections": [ - "own", - "git:rule", - "own", - "local:nested/rule" - ], - "chatgpt": { - "周报": { - "sections": [ - "git:rule", - "own" - ], - "append": "notes/周报.md" - }, - "": { - "sections": [] - } - } - }, - "watch": [ - "local", - "git", - "index" - ] -} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationRanges.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationRanges.migration.json deleted file mode 100644 index 6b23d8d..0000000 --- a/Tests/AgentsManifestTests/Fixtures/MigrationRanges.migration.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "sources": { - "a": { - "git": "https://Example.org/a.git", - "exact": " V1.2.3+build " - }, - "b": { - "local": "./b", - "from": "v1.2.0" - }, - "c": { - "local": "./c", - "upToNextMinor": "1.2.0-beta+build" - }, - "d": { - "local": "./d", - "from": "1.2.0", - "to": "2.0.0+meta" - }, - "e": { - "local": "./e", - "from": "1.2.0+lower", - "to": "1.3.0+upper" - }, - "f": { - "local": "./f", - "from": "1.2.0", - "to": "1.8.0-beta+bound" - }, - "g": { - "local": "./g", - "from": "9223372036854775807.1.0", - "to": "9223372036854775807.2.0" - }, - "h": { - "git": "ssh://User@INTRANET:2222/team/h.git", - "revision": "abc123" - }, - "i": { - "local": "./i", - "upToNextMinor": "1.2.0-alphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalpha" - }, - "j": { - "git": "intranet/team@variant" - } - } -} diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationWidth.migration.json b/Tests/AgentsManifestTests/Fixtures/MigrationWidth.migration.json deleted file mode 100644 index 9100533..0000000 --- a/Tests/AgentsManifestTests/Fixtures/MigrationWidth.migration.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "sources": { - "s": { - "local": "./s" - }, - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": { - "local": "p" - }, - "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy": { - "local": "p2" - } - }, - "skills": { - "s": { - "select": [ - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bbbbbbbbbbbbbbbbbbbbbbbb" - ], - "exclude": [ - "ccccccccccccccccccccccccccccccccc", - "dddddddddddddddddddddddd" - ], - "mode": "link" - } - } -} diff --git a/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json b/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json index bc4540b..d68b7e4 100644 --- a/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json +++ b/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json @@ -36,61 +36,37 @@ "syntaxReservation": 2932, "tokens": 729 }, - "MigrationAliasGap.swift.txt": { - "syntaxDepth": 26, - "syntaxNodes": 152, - "syntaxReservation": 264, - "tokens": 62 - }, - "MigrationAliases.swift.txt": { - "syntaxDepth": 32, - "syntaxNodes": 403, - "syntaxReservation": 680, - "tokens": 166 - }, - "MigrationDuplicateRecipients.swift.txt": { - "syntaxDepth": 28, - "syntaxNodes": 520, - "syntaxReservation": 920, - "tokens": 226 - }, - "MigrationEdgeExample.swift.txt": { - "syntaxDepth": 32, - "syntaxNodes": 446, - "syntaxReservation": 780, - "tokens": 191 - }, - "MigrationEmpty.swift.txt": { + "PrintedEmpty.swift.txt": { "syntaxDepth": 10, "syntaxNodes": 29, "syntaxReservation": 48, "tokens": 8 }, - "MigrationEscapes.swift.txt": { + "PrintedEscapes.swift.txt": { "syntaxDepth": 29, "syntaxNodes": 192, "syntaxReservation": 424, "tokens": 75 }, - "MigrationExplicitEmpty.swift.txt": { + "PrintedExplicitEmpty.swift.txt": { "syntaxDepth": 18, "syntaxNodes": 62, "syntaxReservation": 120, "tokens": 26 }, - "MigrationFields.swift.txt": { + "PrintedFields.swift.txt": { "syntaxDepth": 32, "syntaxNodes": 748, "syntaxReservation": 1304, "tokens": 322 }, - "MigrationRanges.swift.txt": { + "PrintedRanges.swift.txt": { "syntaxDepth": 23, "syntaxNodes": 474, "syntaxReservation": 752, "tokens": 184 }, - "MigrationWidth.swift.txt": { + "PrintedWidth.swift.txt": { "syntaxDepth": 23, "syntaxNodes": 209, "syntaxReservation": 348, diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationEmpty.dump.json b/Tests/AgentsManifestTests/Fixtures/PrintedEmpty.dump.json similarity index 100% rename from Tests/AgentsManifestTests/Fixtures/MigrationEmpty.dump.json rename to Tests/AgentsManifestTests/Fixtures/PrintedEmpty.dump.json diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationEmpty.swift.txt b/Tests/AgentsManifestTests/Fixtures/PrintedEmpty.swift.txt similarity index 100% rename from Tests/AgentsManifestTests/Fixtures/MigrationEmpty.swift.txt rename to Tests/AgentsManifestTests/Fixtures/PrintedEmpty.swift.txt diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationEscapes.swift.txt b/Tests/AgentsManifestTests/Fixtures/PrintedEscapes.swift.txt similarity index 100% rename from Tests/AgentsManifestTests/Fixtures/MigrationEscapes.swift.txt rename to Tests/AgentsManifestTests/Fixtures/PrintedEscapes.swift.txt diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationExplicitEmpty.swift.txt b/Tests/AgentsManifestTests/Fixtures/PrintedExplicitEmpty.swift.txt similarity index 100% rename from Tests/AgentsManifestTests/Fixtures/MigrationExplicitEmpty.swift.txt rename to Tests/AgentsManifestTests/Fixtures/PrintedExplicitEmpty.swift.txt diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationFields.dump.json b/Tests/AgentsManifestTests/Fixtures/PrintedFields.dump.json similarity index 100% rename from Tests/AgentsManifestTests/Fixtures/MigrationFields.dump.json rename to Tests/AgentsManifestTests/Fixtures/PrintedFields.dump.json diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationFields.swift.txt b/Tests/AgentsManifestTests/Fixtures/PrintedFields.swift.txt similarity index 100% rename from Tests/AgentsManifestTests/Fixtures/MigrationFields.swift.txt rename to Tests/AgentsManifestTests/Fixtures/PrintedFields.swift.txt diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationRanges.swift.txt b/Tests/AgentsManifestTests/Fixtures/PrintedRanges.swift.txt similarity index 100% rename from Tests/AgentsManifestTests/Fixtures/MigrationRanges.swift.txt rename to Tests/AgentsManifestTests/Fixtures/PrintedRanges.swift.txt diff --git a/Tests/AgentsManifestTests/Fixtures/MigrationWidth.swift.txt b/Tests/AgentsManifestTests/Fixtures/PrintedWidth.swift.txt similarity index 100% rename from Tests/AgentsManifestTests/Fixtures/MigrationWidth.swift.txt rename to Tests/AgentsManifestTests/Fixtures/PrintedWidth.swift.txt diff --git a/Tests/AgentsManifestTests/FrontEndTests.swift b/Tests/AgentsManifestTests/FrontEndTests.swift index 8988350..b4f0c07 100644 --- a/Tests/AgentsManifestTests/FrontEndTests.swift +++ b/Tests/AgentsManifestTests/FrontEndTests.swift @@ -12,6 +12,10 @@ func document(_ body: String) throws -> DeclarationDocument { bytes: Array((manifestHeader + body).utf8), identity: DocumentIdentity("manifest")) } +func manifestFixture(_ name: String) throws -> [UInt8] { + Array(try Data(contentsOf: Bundle.module.resourceURL!.appendingPathComponent("Fixtures/" + name))) +} + @Suite("Manifest front end") struct FrontEndTests { @Test func completeExamplesCompileAndAgreeUnderValueEquality() throws { diff --git a/Tests/AgentsManifestTests/MigrationTests.swift b/Tests/AgentsManifestTests/MigrationTests.swift deleted file mode 100644 index f66acd4..0000000 --- a/Tests/AgentsManifestTests/MigrationTests.swift +++ /dev/null @@ -1,255 +0,0 @@ -import AgentsCore -import AgentsDescription -import Foundation -import Testing - -@testable import AgentsManifest - -private let migrationCases = [ - "MigrationEmpty", "MigrationExplicitEmpty", "MigrationFields", "MigrationAliases", - "MigrationRanges", "MigrationEscapes", "MigrationWidth", "MigrationAliasGap", - "MigrationDuplicateRecipients", -] - -func manifestFixture(_ name: String) throws -> [UInt8] { - Array(try Data(contentsOf: Bundle.module.resourceURL!.appendingPathComponent("Fixtures/" + name))) -} - -@Suite("Manifest migration") -struct MigrationTests { - @Test(arguments: migrationCases) - func canonicalFixturesAreByteExactDeterministicAndStableUnderEqualEdits(_ name: String) throws { - let input = try manifestFixture(name + ".migration.json") - let first = try ManifestMigration.generate(json: input) - let second = try ManifestMigration.generate(json: input) - #expect(try first.bytes == manifestFixture(name + ".swift.txt")) - #expect(first.bytes == second.bytes) - #expect(first.diagnostics == second.diagnostics) - #expect(first.bytes.last == 10 && !first.bytes.dropLast().suffix(1).contains(10)) - #expect(!first.bytes.starts(with: [0xEF, 0xBB, 0xBF]) && !first.bytes.contains(13)) - let doc = try DeclarationDocument(bytes: first.bytes, identity: DocumentIdentity("manifest")) - #expect(doc.declaration == first.declaration) - let edited = try doc.preparing([.setWatch(first.declaration.watch)]) - #expect(edited.bytes == first.bytes && edited.patches.isEmpty) - } - - @Test func transformationsReportOriginalPointersFullValuesAndPreserveExcludedOverrides() throws { - let result = try ManifestMigration.generate( - json: manifestFixture("MigrationAliases.migration.json")) - #expect( - result.diagnostics.map(\.code) == ["migration.inertOverride", "migration.sourceAliasRenamed"]) - #expect(result.diagnostics.map(\.pointer) == ["/skills/./overrides/b", "/sources/."]) - #expect(result.diagnostics[0].value == .object([:])) - #expect(result.diagnostics[1].oldAlias == "." && result.diagnostics[1].newAlias == "source-3") - #expect( - result.declaration.sources.map { $0["name"]?.string } == ["source", "source-2", "source-3"]) - #expect(result.declaration.components[0]["overrides"]?.elements?.count == 1) - let instructions = result.declaration.components[1] - let sections = try #require(instructions["sections"]?.elements) - #expect( - sections.map { $0.record?["source"] } == [.null, .string("source-3"), .string("source-3")]) - let prompts = try #require(instructions["chatGPT"]?.elements) - #expect(prompts[0].record?["sections"]?.elements?[0].record?["source"] == .string("source-3")) - #expect(result.declaration.watch == ["source", "source-3"]) - let fields = try ManifestMigration.generate( - json: manifestFixture("MigrationFields.migration.json")) - #expect(fields.diagnostics.count == 1) - #expect( - fields.diagnostics[0].value - == .object([ - "agents": .array([.string("opencode"), .string("codex")]), "mode": .string("copy"), - ])) - #expect(fields.declaration.components[3]["overrides"]?.elements?.count == 1) - let escaped = try ManifestMigration.generate( - json: manifestFixture("MigrationEscapes.migration.json")) - #expect( - escaped.diagnostics[0].pointer.contains("~1") && escaped.diagnostics[0].pointer.contains("~0") - ) - } - - @Test func firstUnusedAliasAndInertRulesDoNotDependOnDiscovery() throws { - let result = try ManifestMigration.generate( - json: manifestFixture("MigrationAliasGap.migration.json")) - #expect(result.diagnostics.count == 1 && result.diagnostics[0].newAlias == "source") - #expect(result.declaration.components[0]["overrides"]?.elements?.count == 1) - } - - @Test func duplicateRecipientsReportOriginalElementsAndRoundtripTheTransformedProjection() throws - { - let input = try manifestFixture("MigrationDuplicateRecipients.migration.json") - let legacy = try StateStore.decode(Data(input), as: Declaration.self) - try legacy.validate(environment: RuntimeEnvironment()) - #expect(legacy.agents == [.codex, .claudeCode, .codex, .codex, .claudeCode]) - let result = try ManifestMigration.generate(json: input) - #expect( - result.diagnostics.map(\.pointer) == [ - "/agents/2", "/agents/3", "/agents/4", - "/instructions/agents/2", "/instructions/agents/3", - "/skills/./agents/2", "/skills/./agents/3", - "/skills/./overrides/review/agents/2", "/skills/./overrides/review/agents/3", - "/skills/./overrides/unused", "/skills/./overrides/unused/agents/1", - "/skills/a~0~1b/overrides/future/agents/1", "/sources/.", - ]) - #expect( - result.diagnostics.map(\.code) - == Array(repeating: "migration.duplicateRecipient", count: 9) - + [ - "migration.inertOverride", "migration.duplicateRecipient", - "migration.duplicateRecipient", "migration.sourceAliasRenamed", - ]) - #expect( - result.diagnostics.filter { $0.code == "migration.duplicateRecipient" }.map(\.value) - == [ - .string("codex"), .string("codex"), .string("claude-code"), - .string("gemini-cli"), .string("codex"), - .string("opencode"), .string("claude-code"), - .string("cursor"), .string("codex"), .string("gemini-cli"), .string("opencode"), - ]) - #expect( - result.diagnostics[9].value - == .object([ - "agents": .array([.string("gemini-cli"), .string("gemini-cli")]), - "mode": .string("copy"), - ])) - #expect(result.diagnostics[12].oldAlias == "." && result.diagnostics[12].newAlias == "source-2") - - var transformed = legacy - transformed.agents = [.codex, .claudeCode] - transformed.instructions?.agents = [.geminiCLI, .codex] - transformed.instructions?.sections = ["guide", "source-2:rule"] - let originalSelection = transformed.skills?.removeValue(forKey: ".") - var selection = try #require(originalSelection) - selection.agents = [.opencode, .claudeCode] - selection.overrides?["review"]?.agents = [.cursor, .codex] - selection.overrides?.removeValue(forKey: "unused") - transformed.skills?["source-2"] = selection - transformed.skills?["a~/b"]?.overrides?["future"]?.agents = [.opencode] - let source = transformed.sources.removeValue(forKey: ".") - transformed.sources["source-2"] = source - transformed.watch = ["source-2"] - let projection = try transformed.compatibilityProjection() - let doc = try DeclarationDocument(bytes: result.bytes, identity: DocumentIdentity("manifest")) - #expect(doc.declaration == projection) - #expect(result.declaration == projection) - #expect(projection.defaultAgents == ["claude-code", "codex"]) - #expect(projection.components[0]["agents"] == .array([])) - #expect(projection.components[1]["agents"] == .null) - let overrides = try #require(projection.components[2]["overrides"]?.elements) - #expect(overrides[0].record?["agents"] == .array([])) - #expect(overrides[1].record?["agents"] == .null) - } - - @Test func compatibilityProjectionRetainsInheritanceAndCanonicalizesCoreRequirements() throws { - let legacy = Declaration( - agents: [], - sources: [ - "a": SourceDeclaration( - kind: .git, location: "intranet/team.git", - requirement: .range(from: "v1.2.0", to: "2.0.0+meta")) - ], - skills: [ - "a": SkillDeclaration( - select: .names([]), agents: [], mode: .link, - overrides: ["future": SkillOverride(agents: [])]) - ], - instructions: InstructionsDeclaration()) - let projection = try legacy.compatibilityProjection() - #expect(projection.defaultAgents == []) - #expect(projection.sources[0]["url"] == .string("https://intranet/team.git")) - #expect(projection.sources[0]["requirement"] == .requirement(.upToNextMajor(from: "1.2.0"))) - #expect(projection.components[0]["agents"] == .array([])) - #expect(projection.components[0]["mode"] == .string("link")) - #expect(projection.components[0]["overrides"]?.elements?.count == 1) - #expect(projection.components[1]["agents"] == .null) - #expect(try Declaration().compatibilityProjection() == DeclarationIR()) - let migration = try ManifestMigration.generate( - json: manifestFixture("MigrationRanges.migration.json")) - let doc = try DeclarationDocument( - bytes: migration.bytes, identity: DocumentIdentity("manifest")) - let change = try doc.preparing([ - .upsertSource(.source(name: "b", path: "./b", "1.2.0"..<"2.0.0")) - ]) - #expect(change.bytes == doc.bytes && change.patches.isEmpty) - } - - @Test(arguments: [ - #"{"unknown":null}"#, #"{"sources":{"x":{"git":"intranet/team","unknown":null}}}"#, - #"{"sources":{},"sources":{}}"#, #"{"agents":["unknown"]}"#, - #"{"sources":{"x":{"local":"a"}},"skills":{"x":{"select":"all","overrides":{"a":{"unknown":null}}}}}"#, - ]) - func strictJSONFailuresNeverProduceSource(_ input: String) { - #expect(throws: (any Error).self) { try ManifestMigration.generate(json: Array(input.utf8)) } - } - - @Test func invalidUTF8AndSelfCheckFailuresHaveNoPartialResult() throws { - #expect(throws: (any Error).self) { try ManifestMigration.generate(json: [0xFF]) } - var result: ManifestMigrationResult? - do { - result = try ManifestMigration.generate( - json: Array("{}".utf8), environment: RuntimeEnvironment(), - checking: { _ in DeclarationIR(watch: ["wrong"]) }) - Issue.record("self-check did not reject mismatching projection") - } catch let failure as MigrationFailure { - #expect(failure.diagnostics.map(\.code) == ["migration.mismatch"]) - } - #expect(result == nil) - } - - @Test func byteWidthIncludesLabelsCommasAndUTF8() throws { - let printer = CanonicalPrinter() - let atBoundary = Source.source(name: String(repeating: "a", count: 47), path: "p") - .constructionValue - let overBoundary = Source.source(name: String(repeating: "a", count: 48), path: "p") - .constructionValue - #expect(!printer.render(atBoundary, indentation: " ").contains("\n")) - #expect(printer.render(overBoundary, indentation: " ").contains("\n")) - let unicode = Source.source(name: String(repeating: "é", count: 24), path: "p") - .constructionValue - #expect(printer.render(unicode, indentation: " ").contains("\n")) - let doc = try ManifestMigration.generate(json: manifestFixture("MigrationWidth.migration.json")) - let text = String(decoding: doc.bytes, as: UTF8.self) - #expect(text.contains("select: [")) - #expect(text.split(separator: "\n").allSatisfy { $0.utf8.count <= 80 }) - } - - @Test func migrationLimitsAreNamedAndNeverReturnTruncatedResults() throws { - func limit(_ budget: String, _ operation: () throws -> Void) { - do { - try operation() - Issue.record("expected migration.limit: \(budget)") - } catch let failure as MigrationFailure { - #expect(failure.diagnostics.map(\.code) == ["migration.limit"]) - #expect(failure.diagnostics[0].budget?.contains(budget) == true) - } catch { Issue.record(error) } - } - limit("collection entries") { - try ManifestMigration.preflight(.array(Array(repeating: .none, count: 10_001))) - } - var deep: ConstructionValue = .none - for _ in 0..<64 { deep = .array([deep]) } - limit("expanded depth") { try ManifestMigration.preflight(deep) } - let nodes = ConstructionValue.array( - Array(repeating: .array(Array(repeating: .none, count: 100)), count: 1_000)) - limit("expanded nodes") { try ManifestMigration.preflight(nodes) } - limit("decoded string bytes") { - try ManifestMigration.preflight( - .text(String(repeating: "x", count: ManifestLimits.Values.stringBytes + 1))) - } - limit("encoded output bytes") { - try ManifestMigration.preflight(.text(String(repeating: "\0", count: 6_000_000))) - } - let oversized = Declaration(sources: [ - "s": SourceDeclaration( - kind: .local, location: String(repeating: "x", count: ManifestLimits.Input.bytes)) - ]) - limit("source bytes") { - _ = try ManifestMigration.generate(json: Array(JSONEncoder().encode(oversized))) - } - let many = Declaration( - sources: ["s": SourceDeclaration(kind: .local, location: "s")], - instructions: InstructionsDeclaration(sections: Array(repeating: "s:guide", count: 3_600))) - limit("reservation") { - _ = try ManifestMigration.generate(json: Array(JSONEncoder().encode(many))) - } - } -} diff --git a/Tests/AgentsManifestTests/PrintingTests.swift b/Tests/AgentsManifestTests/PrintingTests.swift new file mode 100644 index 0000000..fc4dc85 --- /dev/null +++ b/Tests/AgentsManifestTests/PrintingTests.swift @@ -0,0 +1,166 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsManifest + +private func local(_ location: String, _ requirement: SourceRequirement? = nil) -> SourceDeclaration +{ + SourceDeclaration(kind: .local, location: location, requirement: requirement) +} + +private let escapedAlias = "é/别名~\"\\\n\r\t\u{1}\u{7f}\u{85}" + +/// Declarations whose canonical documents are the `Printed*` goldens. +let printedDeclarations: [(String, Declaration)] = [ + ("PrintedEmpty", Declaration()), + ( + "PrintedExplicitEmpty", + Declaration(agents: [], instructions: InstructionsDeclaration(agents: [])) + ), + ( + "PrintedEscapes", + Declaration( + agents: [], + sources: [escapedAlias: SourceDeclaration(kind: .git, location: "example.org/escape.git")], + skills: [escapedAlias: SkillDeclaration(select: .names(["selected"]))], + instructions: InstructionsDeclaration(chatgpt: [ + "\"\\\n\r\t\u{1}\u{7f}\u{85} e\u{301} 😀": PromptDeclaration( + sections: ["own"], append: "notes/内容.md") + ])) + ), + ( + "PrintedRanges", + Declaration(sources: [ + "a": SourceDeclaration( + kind: .git, location: "https://Example.org/a.git", requirement: .exact("1.2.3+build")), + "b": local("./b", .upToNextMajor(from: "1.2.0")), + "c": local("./c", .upToNextMinor(from: "1.2.0-beta+build")), + "d": local("./d", .range(from: "1.2.0", to: "2.0.0")), + "e": local("./e", .upToNextMinor(from: "1.2.0+lower")), + "f": local("./f", .range(from: "1.2.0", to: "1.8.0-beta+bound")), + "g": local("./g", .upToNextMinor(from: "9223372036854775807.1.0")), + "h": SourceDeclaration( + kind: .git, location: "ssh://User@INTRANET:2222/team/h.git", + requirement: .revision("abc123")), + "i": local("./i", .upToNextMinor(from: "1.2.0-" + String(repeating: "alpha", count: 20))), + "j": SourceDeclaration(kind: .git, location: "intranet/team@variant"), + ]) + ), + ( + "PrintedWidth", + Declaration( + sources: [ + "s": local("./s"), String(repeating: "x", count: 47): local("p"), + String(repeating: "y", count: 48): local("p2"), + ], + skills: [ + "s": SkillDeclaration( + select: .names([String(repeating: "b", count: 24), String(repeating: "a", count: 33)]), + exclude: [String(repeating: "d", count: 24), String(repeating: "c", count: 33)], + mode: .link) + ]) + ), + ( + "PrintedFields", + Declaration( + agents: [.opencode, .codex, .claudeCode], + sources: [ + "empty": local("./live"), + "git": SourceDeclaration( + kind: .git, location: "intranet/team.git", requirement: .branch("main"), path: "skills"), + "index": SourceDeclaration( + kind: .wellKnown, location: "https://example.org/.well-known/skills/index.json", + path: "bundle"), + "local": local("./drafts", .revision("abc123")), + ], + skills: [ + "empty": SkillDeclaration(select: .all, mode: .edit), + "git": SkillDeclaration( + select: .names(["b", "a"]), exclude: ["b"], agents: [], mode: .copy, + overrides: [ + "a": SkillOverride(agents: [.codex], mode: .link), "b": SkillOverride(agents: []), + ]), + "index": SkillDeclaration(select: .names([])), + "local": SkillDeclaration(select: .all, overrides: ["future": SkillOverride(mode: .copy)]), + ], + instructions: InstructionsDeclaration( + agents: [.geminiCLI, .codex], sections: ["own", "git:rule", "own", "local:nested/rule"], + chatgpt: [ + "": PromptDeclaration(sections: []), + "周报": PromptDeclaration(sections: ["git:rule", "own"], append: "notes/周报.md"), + ]), + watch: ["local", "git", "index"]) + ), +] + +@Suite("Canonical manifest printing") +struct PrintingTests { + @Test(arguments: printedDeclarations) + func newDocumentsMatchTheirGoldensDeterministically(_ name: String, _ declaration: Declaration) + throws + { + let golden = try manifestFixture(name + ".swift.txt") + let printed = try CanonicalPrinter().manifest( + DeclarationConstruction.root(declaration).constructionValue) + #expect(printed == golden) + #expect( + try CanonicalPrinter().manifest(DeclarationConstruction.root(declaration).constructionValue) + == printed) + let created = try planned(Declaration(), declaration, in: nil) + let empty = ManifestProjection.equivalent( + declaration, Declaration(), environment: projectionEnvironment) + #expect(created == (empty ? nil : golden)) + #expect(try planned(Declaration(), declaration, in: nil) == created) + #expect(golden.last == 10 && !golden.contains(13)) + #expect(!golden.starts(with: [0xEF, 0xBB, 0xBF])) + let text = String(decoding: golden, as: UTF8.self) + for line in text.split(separator: "\n") where !line.contains("alphaalpha") { + #expect(line.utf8.count <= 80, "\(name): \(line)") + } + let document = try DeclarationDocument(bytes: golden, identity: DocumentIdentity("manifest")) + let projection = try ManifestProjection.declaration( + of: document, environment: projectionEnvironment) + #expect( + ManifestProjection.equivalent(projection, declaration, environment: projectionEnvironment)) + } + + @Test func firstEditsOfAnEmptyManifestUseTheCanonicalLayout() throws { + let empty = manifestHeader + "let agents = Agents()\n" + var added = Declaration() + added.sources["skills"] = SourceDeclaration(kind: .git, location: "github.com/team/skills") + added.skills = ["skills": SkillDeclaration(select: .all)] + let bytes = try #require(try planned(Declaration(), added, in: empty)) + #expect( + String(decoding: bytes, as: UTF8.self) == manifestHeader + """ + let agents = Agents( + sources: [ + .source(name: "skills", url: "https://github.com/team/skills"), + ], + components: [ + .skills(source: "skills"), + ] + ) + + """) + #expect( + bytes + == (try CanonicalPrinter().manifest(DeclarationConstruction.root(added).constructionValue))) + for (name, declaration) in printedDeclarations where name != "PrintedEmpty" { + let edited = try #require(try planned(Declaration(), declaration, in: empty)) + #expect(edited == (try manifestFixture(name + ".swift.txt")), "\(name)") + } + } + + @Test func emptyArgumentListsSkipDefaultsAndRejectCommentOnlyInteriors() throws { + let doc = try document("let agents = Agents()") + let source = try doc.preparing(operations: [ + .setArgument(doc.node(at: "")!, field: "watch", value: .array([])) + ]) + #expect(source.bytes == doc.bytes) + let commented = try document("let agents = Agents(/* empty */)") + expectManifestFailure("manifest.edit.readOnly") { + try commented.preparing([.setWatch(["s"])]) + } + } +} diff --git a/Tests/AgentsManifestTests/ProjectionTests.swift b/Tests/AgentsManifestTests/ProjectionTests.swift new file mode 100644 index 0000000..414bdb0 --- /dev/null +++ b/Tests/AgentsManifestTests/ProjectionTests.swift @@ -0,0 +1,226 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsManifest + +let projectionEnvironment = RuntimeEnvironment( + projectDirectory: URL(fileURLWithPath: "/work/project", isDirectory: true), + homeDirectory: URL(fileURLWithPath: "/work/home", isDirectory: true), environment: [:]) + +func projected(_ body: String) throws -> Declaration { + try ManifestProjection.declaration(of: document(body), environment: projectionEnvironment) +} + +@Suite("Manifest projection") +struct ProjectionTests { + @Test func everyDeployableShapeMapsToTheDeclaration() throws { + let declaration = try projected( + """ + let agents = Agents( + defaultAgents: [.openCode, .claudeCode], + sources: [ + .source(name: "git", url: "github.com/team/skills", branch: "main", subpath: "skills"), + .source(name: "local", path: "./drafts", "1.2.0"..<"2.0.0"), + .source(name: "index", index: "https://example.org/.well-known/skills/index.json"), + .source(name: "pinned", url: "https://example.org/p.git", exact: "1.2.3+build"), + ], + components: [ + .skills(source: "git"), + .skills( + source: "local", select: ["a", "b"], exclude: ["b"], mode: .copy, + overrides: [.skill(name: "a", mode: .link, agents: []), .skill(name: "b")], + agents: [.codex]), + .skills(source: "index", select: [], exclude: []), + .instructions( + sections: ["guide", .section(name: "rule", source: "git"), .section(name: "own", source: "."), "guide"], + chatGPT: [.prompt(name: "weekly", sections: [], append: "notes/weekly.md")], + agents: []), + ], + watch: ["git"] + ) + """) + #expect( + declaration + == Declaration( + agents: [.opencode, .claudeCode], + sources: [ + "git": SourceDeclaration( + kind: .git, location: "https://github.com/team/skills", requirement: .branch("main"), + path: "skills"), + "local": SourceDeclaration( + kind: .local, location: "./drafts", requirement: .upToNextMajor(from: "1.2.0")), + "index": SourceDeclaration( + kind: .wellKnown, location: "https://example.org/.well-known/skills/index.json"), + "pinned": SourceDeclaration( + kind: .git, location: "https://example.org/p.git", requirement: .exact("1.2.3+build")), + ], + skills: [ + "git": SkillDeclaration(select: .all), + "local": SkillDeclaration( + select: .names(["a", "b"]), exclude: ["b"], agents: [.codex], mode: .copy, + overrides: [ + "a": SkillOverride(agents: [], mode: .link), "b": SkillOverride(), + ]), + "index": SkillDeclaration(select: .names([])), + ], + instructions: InstructionsDeclaration( + agents: [], sections: ["guide", "git:rule", "own", "guide"], + chatgpt: ["weekly": PromptDeclaration(sections: [], append: "notes/weekly.md")]), + watch: ["git"])) + } + + @Test func absentValuesStayDistinctFromExplicitEmptyValues() throws { + #expect(try projected("let agents = Agents()") == Declaration()) + let explicit = try projected( + "let agents = Agents(defaultAgents: [], components: [.instructions(agents: [])], watch: [])") + #expect(explicit.agents == []) + #expect(explicit.instructions == InstructionsDeclaration(agents: [])) + #expect(explicit.watch == nil) + let inherited = try projected("let agents = Agents(components: [.instructions()])") + #expect(inherited.agents == nil) + #expect(inherited.instructions == InstructionsDeclaration()) + #expect(inherited.instructions?.agents == nil) + } + + @Test(arguments: [ + ("groups: [.group(name: \"g\")], uses: [\"g\"]", "\"g\""), + ( + "components: [.skills(source: \"s\", condition: .when(agents: [.codex]))]", + ".when(agents: [.codex])" + ), + ( + "components: [.skills(source: \"s\", native: [\"claude-code/skill@1\": [\"x\": 1]])]", + "[\"claude-code/skill@1\": [\"x\": 1]]" + ), + ("components: [.instructions(condition: .when(scopes: [.user]))]", ".when(scopes: [.user])"), + ( + "components: [.instructions(sections: [.section(name: \"g\", condition: .when())])]", + ".when()" + ), + ( + "components: [.instructions(chatGPT: [.prompt(name: \"p\", sections: [], condition: .when(platforms: [.linux]))])]", + ".when(platforms: [.linux])" + ), + ( + "components: [.instructions(chatGPT: [.prompt(name: \"p\", sections: [.section(name: \"g\", condition: .when())])])]", + ".when()" + ), + ("components: [.ignore(name: \"i\", patterns: [])]", ".ignore(name: \"i\", patterns: [])"), + ( + "components: [.skills(source: \"s\"), .skills(source: \"s\", select: [\"a\"])]", + ".skills(source: \"s\", select: [\"a\"])" + ), + ( + "components: [.instructions(), .instructions(sections: [\"g\"])]", + ".instructions(sections: [\"g\"])" + ), + ("components: [.skills(source: \".\")]", "\".\""), + ]) + func unsupportedStructuresAreReportedAtTheirLocation(_ fields: String, _ located: String) throws { + let body = + "let agents = Agents(sources: [.source(name: \"s\", path: \"s\")], " + fields + ")" + let doc = try document(body) + do { + _ = try ManifestProjection.declaration(of: doc, environment: projectionEnvironment) + Issue.record("projection accepted unsupported structure: \(fields)") + } catch let failure as ManifestFailure { + #expect(failure.diagnostics.map(\.code) == ["manifest.unsupported"]) + let span = try #require(failure.diagnostics.first?.span) + #expect(span.document == DocumentIdentity("manifest")) + #expect( + String(decoding: doc.bytes[span.start.. 1) + } + } + + @Test func inertGroupsAndExportsAreAccepted() throws { + let declaration = try projected( + """ + let agents = Agents( + exports: ["review"], + sources: [.source(name: "s", path: "s")], + groups: [ + .group( + name: "review", + components: [ + .skills(source: "s", condition: .when(agents: [.codex])), + .ignore(name: "i", patterns: ["x"]), + ], + uses: ["nested"] + ), + .group(name: "nested", components: [.instructions(sections: ["g"])]), + ] + ) + """) + #expect( + declaration == Declaration(sources: ["s": SourceDeclaration(kind: .local, location: "s")])) + } + + @Test func environmentDependentValidationFollowsProjection() throws { + let doc = try document( + "let agents = Agents(sources: [.source(name: \"a\", path: \"~/rules\"), .source(name: \"b\", path: \"/work/home/rules\")])" + ) + #expect(throws: CoreError.self) { + try ManifestProjection.declaration(of: doc, environment: projectionEnvironment) + } + let other = RuntimeEnvironment( + projectDirectory: URL(fileURLWithPath: "/work/project", isDirectory: true), + homeDirectory: URL(fileURLWithPath: "/elsewhere", isDirectory: true), environment: [:]) + #expect(try ManifestProjection.declaration(of: doc, environment: other).sources.count == 2) + } + + @Test func semanticEqualityIgnoresSpellingButKeepsInheritanceAndSectionOrder() { + func equal(_ lhs: Declaration, _ rhs: Declaration) -> Bool { + ManifestProjection.equivalent(lhs, rhs, environment: projectionEnvironment) + } + func sources(_ source: SourceDeclaration) -> Declaration { Declaration(sources: ["s": source]) } + #expect( + equal( + sources(SourceDeclaration(kind: .git, location: "github.com/a/b")), + sources(SourceDeclaration(kind: .git, location: "https://GitHub.com/a/b.git/")))) + #expect( + equal( + sources(SourceDeclaration(kind: .local, location: "./rules", path: "./skills/")), + sources(SourceDeclaration(kind: .local, location: "/work/project/rules", path: "skills")))) + #expect( + equal( + sources( + SourceDeclaration( + kind: .git, location: "https://e.org/r", requirement: .range(from: "1.2.0", to: "2.0.0") + )), + sources( + SourceDeclaration( + kind: .git, location: "https://e.org/r", requirement: .upToNextMajor(from: "v1.2.0"))))) + #expect( + !equal( + sources( + SourceDeclaration(kind: .git, location: "https://e.org/r", requirement: .exact("1.0.0"))), + sources( + SourceDeclaration(kind: .git, location: "https://e.org/r", requirement: .exact("1.0.0+b")) + ))) + #expect( + !equal( + sources(SourceDeclaration(kind: .local, location: "a")), + sources(SourceDeclaration(kind: .local, location: "a", path: "x")))) + #expect(equal(Declaration(agents: [.codex, .cursor]), Declaration(agents: [.cursor, .codex]))) + #expect(!equal(Declaration(agents: []), Declaration())) + #expect(equal(Declaration(skills: [:], watch: []), Declaration())) + let base = Declaration(sources: ["s": SourceDeclaration(kind: .local, location: "s")]) + var left = base + var right = base + left.skills = ["s": SkillDeclaration(select: .names(["a", "b"]), exclude: [], overrides: [:])] + right.skills = ["s": SkillDeclaration(select: .names(["b", "a"]))] + #expect(equal(left, right)) + right.skills?["s"]?.agents = [] + #expect(!equal(left, right)) + left.instructions = InstructionsDeclaration(sections: ["a", "b"], chatgpt: [:]) + right = left + right.instructions?.chatgpt = nil + #expect(equal(left, right)) + right.instructions?.sections = ["b", "a"] + #expect(!equal(left, right)) + right.instructions = nil + #expect(!equal(left, right)) + } +} From d47bc9b89954ff6bad01bf610891f4dd939dbb63 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:34:24 +0800 Subject: [PATCH 018/171] fix(manifest): report editability the editor accepts Member values and omitted signature arguments are direct edits; only references, concatenations and normalized fields remain read-only. A test pins the report to the editor's own acceptance for every value node of a representative manifest, and the dump goldens follow. --- .../AgentsManifest/DeclarationDocument.swift | 47 ++- Tests/AgentsManifestTests/EditingTests.swift | 88 ++++ .../Fixtures/ConsumerExample.dump.json | 377 +++++++----------- .../Fixtures/DumpSymbolic.dump.json | 123 +++--- .../Fixtures/LiteralCoverage.dump.json | 366 +++++++---------- .../Fixtures/PrintedEmpty.dump.json | 21 +- .../Fixtures/PrintedFields.dump.json | 187 ++++----- 7 files changed, 555 insertions(+), 654 deletions(-) diff --git a/Sources/AgentsManifest/DeclarationDocument.swift b/Sources/AgentsManifest/DeclarationDocument.swift index 3eccb37..b2398d0 100644 --- a/Sources/AgentsManifest/DeclarationDocument.swift +++ b/Sources/AgentsManifest/DeclarationDocument.swift @@ -72,6 +72,10 @@ public struct DeclarationDocument: Sendable { } } + /// Agrees with the editor: elements and entries of a direct collection literal and signature + /// arguments of a direct construction, including omitted ones, are direct, as are member values + /// such as `.copy`. References, concatenations, normalized fields such as source requirements + /// and component kinds, and everything inside a read-only value are read-only. public func editability(of node: NodeID) -> Editability { guard node.digest == digest, values[node.pointer]?.syntax == node.syntax else { return .readOnly(reason: "stale snapshot handle") @@ -80,18 +84,47 @@ public struct DeclarationDocument: Sendable { let name = pointerUnescape(String(node.pointer.dropFirst("/constants/".count))) return .sharedConstant(uses: uses(ofConstant: name)) } - guard let value = values[node.pointer], !value.defaulted, value.type != .untyped else { - return .readOnly(reason: "default field has no source range") + return editability(at: node.pointer) + } + + private func editability(at pointer: String) -> Editability { + guard let value = values[pointer] else { + return .readOnly(reason: "stale snapshot handle") } - if value.referent != nil || hasAssembledAncestor(node.pointer) { + // Containing values are checked by the recursion below, so each entry costs its depth. + if value.referent != nil { return .readOnly( reason: "shared constant or assembled value; replace its definition explicitly") } - let kind = admission.nodes[node.syntax].kind - if kind == .sequence || kind == .name { - return .readOnly(reason: "expanded value has no independent source range") + if admission.nodes[value.syntax].kind == .sequence { + return .readOnly(reason: "concatenated value has no independent source range") + } + guard let slash = pointer.lastIndex(of: "/") else { return .direct } + let parent = String(pointer[.. Bool { diff --git a/Tests/AgentsManifestTests/EditingTests.swift b/Tests/AgentsManifestTests/EditingTests.swift index cf3a125..b8e3f70 100644 --- a/Tests/AgentsManifestTests/EditingTests.swift +++ b/Tests/AgentsManifestTests/EditingTests.swift @@ -189,6 +189,94 @@ struct EditingTests { #expect(printer.render(unicode, indentation: " ").contains("\n")) } + @Test func editabilityReportsExactlyTheValuesTheEditorChangesDirectly() throws { + let doc = try document( + """ + let shared: [String] = ["x"] + let base = "guide" + let agents = Agents( + defaultAgents: [.codex, .claudeCode], + exports: ["review"], + sources: [ + .source(name: "team", url: "https://e.org/team.git", branch: "main", subpath: "skills"), + .source(name: "local", path: "./drafts", "1.2.0"..<"1.5.0"), + .source(name: "pinned", url: "https://e.org/p.git", from: "1.0.0"), + ], + components: [ + .skills( + source: "team", select: ["a", "b"], exclude: shared, mode: .copy, + overrides: [.skill(name: "a", mode: .link, agents: [.cursor])], agents: [.codex]), + .skills(source: "local"), + .instructions( + sections: ["guide", .section(name: base, source: "team")], + chatGPT: [.prompt(name: "weekly", sections: ["guide"], append: "notes/w.md")], + agents: []), + ], + groups: [ + .group( + name: "review", + components: [ + .ignore(name: "i", patterns: ["a"] + shared), + .lspServer( + name: "l", run: .executable("tool", arguments: ["-v"]), + languages: [".swift": "swift"], + initializationOptions: [ + "k": 1, "o": ["n": true], "c": .object(["m": nil]), "a": [1, "s"], + ]), + ]) + ], + watch: ["team"] + ) + """) + var checked = (direct: 0, readOnly: 0) + for pointer in doc.values.keys.sorted() + where !pointer.isEmpty && !pointer.hasPrefix("/constants/") { + let node = try #require(doc.node(at: pointer)) + let slash = pointer.lastIndex(of: "/")! + let parent = String(pointer[.. 80 && checked.readOnly > 30) + for pointer in ["/components/0/mode", "/defaultAgents/0", "/components/1/agents"] { + #expect(doc.editability(of: doc.node(at: pointer)!) == .direct, "\(pointer)") + } + for pointer in ["/components/0/exclude", "/groups/0/components/0/patterns"] { + #expect(doc.editability(of: doc.node(at: pointer)!) != .direct, "\(pointer)") + } + } + @Test func noOpsKeepOriginalBytesAndUnsafeEditsPublishNothing() throws { let doc = try document( "let agents = Agents(defaultAgents: nil, sources: [.source(name: \"s\", url: \"https://example.org/s.git\", \"1.2.0\" ..< \"2.0.0\")], components: [/*container*/])" diff --git a/Tests/AgentsManifestTests/Fixtures/ConsumerExample.dump.json b/Tests/AgentsManifestTests/Fixtures/ConsumerExample.dump.json index d9689e7..362af07 100644 --- a/Tests/AgentsManifestTests/Fixtures/ConsumerExample.dump.json +++ b/Tests/AgentsManifestTests/Fixtures/ConsumerExample.dump.json @@ -454,8 +454,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/agents", @@ -470,8 +469,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/condition", @@ -517,7 +515,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/0/kind", @@ -532,8 +530,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/mode", @@ -548,8 +545,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/native", @@ -609,8 +605,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/overrides/0/agents/0", @@ -625,8 +620,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/overrides/0/mode", @@ -656,8 +650,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/select", @@ -702,8 +695,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/agents", @@ -748,8 +740,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/condition/agents/0", @@ -764,8 +755,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/condition/platforms", @@ -795,8 +785,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/condition/scopes/0", @@ -811,8 +800,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/exclude", @@ -828,7 +816,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/1/kind", @@ -843,8 +831,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/mode", @@ -859,8 +846,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/native", @@ -875,8 +861,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/overrides", @@ -966,8 +951,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/10/agents/0", @@ -997,8 +981,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/10/condition/agents", @@ -1013,8 +996,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/10/condition/platforms", @@ -1044,8 +1026,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/10/condition/scopes/0", @@ -1060,8 +1041,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/10/exclude", @@ -1077,7 +1057,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/10/kind", @@ -1092,8 +1072,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/10/mode", @@ -1123,8 +1102,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/10/native", @@ -1154,8 +1132,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/10/select", @@ -1200,8 +1177,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/11/agents", @@ -1231,8 +1207,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/11/condition/agents", @@ -1247,8 +1222,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/11/condition/platforms", @@ -1278,8 +1252,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/11/condition/scopes/0", @@ -1325,7 +1298,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/11/exclude/0/kind", @@ -1356,7 +1329,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/11/kind", @@ -1371,8 +1344,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/11/mode", @@ -1402,8 +1374,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/11/native", @@ -1433,8 +1404,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/11/select", @@ -1479,8 +1449,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/agents", @@ -1540,8 +1509,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/chatGPT/0/condition", @@ -1627,7 +1595,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1658,7 +1626,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1689,7 +1657,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1719,8 +1687,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/condition", @@ -1736,7 +1703,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/2/kind", @@ -1751,8 +1718,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/native", @@ -1823,7 +1789,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1854,7 +1820,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1885,7 +1851,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1947,7 +1913,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -2083,8 +2049,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/3/agents/0", @@ -2099,8 +2064,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/3/condition", @@ -2116,7 +2080,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/3/kind", @@ -2146,8 +2110,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/3/native", @@ -2238,7 +2201,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/3/transport/environment/LOG_LEVEL/kind", @@ -2254,7 +2217,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/3/transport/environment/LOG_LEVEL/value", @@ -2285,7 +2248,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/3/transport/environment/TOKEN/kind", @@ -2331,7 +2294,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/3/transport/kind", @@ -2346,8 +2309,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/3/transport/workingDirectory", @@ -2392,8 +2354,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/agents/0", @@ -2408,8 +2369,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/condition", @@ -2425,7 +2385,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/4/kind", @@ -2455,8 +2415,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/native", @@ -2517,7 +2476,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/4/transport/headers/Authorization/kind", @@ -2548,7 +2507,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/4/transport/kind", @@ -2608,8 +2567,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/5/agents/0", @@ -2639,8 +2597,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/5/condition/agents", @@ -2655,8 +2612,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/5/condition/platforms", @@ -2686,8 +2642,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/5/condition/scopes/0", @@ -2702,8 +2657,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/5/event", @@ -2719,7 +2673,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/5/event/kind", @@ -2735,7 +2689,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/5/kind", @@ -2750,8 +2704,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/5/matcher", @@ -2781,8 +2734,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/5/native", @@ -2872,8 +2824,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/5/run/environment", @@ -2904,7 +2855,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/5/run/kind", @@ -3009,8 +2960,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/6/agents/0", @@ -3025,8 +2975,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/6/condition", @@ -3057,7 +3006,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/6/kind", @@ -3087,8 +3036,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/6/native", @@ -3133,8 +3081,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/6/parameters/0/defaultValue", @@ -3195,7 +3142,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/6/prompt/kind", @@ -3211,7 +3158,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/6/prompt/value", @@ -3256,8 +3203,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/agents/0", @@ -3287,8 +3233,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/condition/agents", @@ -3318,8 +3263,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/condition/platforms/0", @@ -3334,8 +3278,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/condition/scopes", @@ -3381,7 +3324,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/7/initializationOptions/backgroundIndexing/kind", @@ -3396,7 +3339,8 @@ { "defaulted": false, "editability": { - "kind": "direct" + "kind": "readOnly", + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/7/initializationOptions/backgroundIndexing/value", @@ -3412,7 +3356,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/7/kind", @@ -3472,8 +3416,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/native", @@ -3503,8 +3446,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/run/arguments", @@ -3519,8 +3461,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/run/environment", @@ -3551,7 +3492,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/7/run/kind", @@ -3566,8 +3507,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/run/workingDirectory", @@ -3612,8 +3552,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/8/agents/0", @@ -3643,8 +3582,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/8/condition/agents", @@ -3659,8 +3597,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/8/condition/platforms", @@ -3690,8 +3627,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/8/condition/scopes/0", @@ -3707,7 +3643,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/8/kind", @@ -3737,8 +3673,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/8/native", @@ -3784,7 +3719,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/8/rules/0/kind", @@ -3799,8 +3734,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/8/rules/0/operation", @@ -3816,7 +3750,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/8/rules/0/operation/kind", @@ -3876,8 +3810,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/9/agents/0", @@ -3907,8 +3840,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/9/condition/agents", @@ -3923,8 +3855,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/9/condition/platforms", @@ -3954,8 +3885,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/9/condition/scopes/0", @@ -3971,7 +3901,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/9/kind", @@ -4001,8 +3931,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/9/native", @@ -4062,8 +3991,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/9/purpose", @@ -4078,8 +4006,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/defaultAgents", @@ -4094,8 +4021,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/exports", @@ -4280,7 +4206,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -4394,7 +4320,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -4456,7 +4382,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -4480,7 +4406,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -4649,7 +4575,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -4770,7 +4696,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -4801,7 +4727,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -4832,7 +4758,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -4855,8 +4781,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/groups/0/condition", @@ -4946,8 +4871,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/groups/0/uses/0/condition/agents/0", @@ -4962,8 +4886,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/groups/0/uses/0/condition/platforms", @@ -4978,8 +4901,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/groups/0/uses/0/condition/scopes", @@ -4995,7 +4917,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/groups/0/uses/0/kind", @@ -5086,7 +5008,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/0/kind", @@ -5117,7 +5039,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/0/requirement", @@ -5132,8 +5054,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/sources/0/subpath", @@ -5164,7 +5085,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/1/kind", @@ -5210,7 +5131,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/1/requirement", @@ -5225,8 +5146,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/sources/1/subpath", @@ -5257,7 +5177,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/2/kind", @@ -5287,7 +5207,8 @@ { "defaulted": false, "editability": { - "kind": "direct" + "kind": "readOnly", + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/2/requirement", @@ -5302,7 +5223,8 @@ { "defaulted": false, "editability": { - "kind": "direct" + "kind": "readOnly", + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/2/requirement/from", @@ -5317,8 +5239,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/sources/2/subpath", @@ -5364,7 +5285,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/3/kind", @@ -5410,7 +5331,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/3/requirement", @@ -5425,8 +5346,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/sources/3/subpath", @@ -5457,7 +5377,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/4/kind", @@ -5487,7 +5407,8 @@ { "defaulted": false, "editability": { - "kind": "direct" + "kind": "readOnly", + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/4/requirement", @@ -5502,7 +5423,8 @@ { "defaulted": false, "editability": { - "kind": "direct" + "kind": "readOnly", + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/4/requirement/exact", @@ -5517,8 +5439,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/sources/4/subpath", @@ -5579,7 +5500,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/uses/0/condition", @@ -5595,7 +5516,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/uses/0/kind", @@ -5611,7 +5532,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/uses/0/name", @@ -5627,7 +5548,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/uses/0/source", diff --git a/Tests/AgentsManifestTests/Fixtures/DumpSymbolic.dump.json b/Tests/AgentsManifestTests/Fixtures/DumpSymbolic.dump.json index 8aa7f49..c0acf14 100644 --- a/Tests/AgentsManifestTests/Fixtures/DumpSymbolic.dump.json +++ b/Tests/AgentsManifestTests/Fixtures/DumpSymbolic.dump.json @@ -303,8 +303,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/chatGPT/0/append", @@ -319,8 +318,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/chatGPT/0/condition", @@ -381,7 +379,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/0/chatGPT/0/sections/0/condition", @@ -397,7 +395,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/0/chatGPT/0/sections/0/name", @@ -413,7 +411,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/0/chatGPT/0/sections/0/source", @@ -443,8 +441,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/chatGPT/1/append", @@ -459,8 +456,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/chatGPT/1/condition", @@ -505,8 +501,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/condition", @@ -522,7 +517,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/0/kind", @@ -537,8 +532,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/native", @@ -584,7 +578,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/0/sections/0/condition", @@ -600,7 +594,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/0/sections/0/name", @@ -616,7 +610,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/0/sections/0/source", @@ -1036,8 +1030,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/agents", @@ -1052,8 +1045,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/condition", @@ -1114,7 +1106,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/1/kind", @@ -1129,8 +1121,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/mode", @@ -1145,8 +1136,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/native", @@ -1191,8 +1181,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/overrides/0/agents", @@ -1207,8 +1196,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/overrides/0/mode", @@ -1268,8 +1256,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/overrides/1/mode", @@ -1374,8 +1361,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/agents", @@ -1390,8 +1376,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/condition", @@ -1437,7 +1422,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/2/exclude/0/kind", @@ -1483,7 +1468,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/2/exclude/1/kind", @@ -1529,7 +1514,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/2/exclude/2/kind", @@ -1575,7 +1560,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/2/exclude/3/kind", @@ -1606,7 +1591,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/2/kind", @@ -1621,8 +1606,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/mode", @@ -1652,8 +1636,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/native", @@ -1683,8 +1666,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/select", @@ -1804,8 +1786,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/groups/0/components", @@ -1820,8 +1801,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/groups/0/condition", @@ -1851,8 +1831,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/groups/0/uses", @@ -1882,8 +1861,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/groups/1/components", @@ -2258,8 +2236,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/groups/1/uses", @@ -2305,7 +2282,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/0/kind", @@ -2351,7 +2328,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/0/requirement", @@ -2366,8 +2343,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/sources/0/subpath", @@ -2398,7 +2374,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/1/kind", @@ -2428,7 +2404,8 @@ { "defaulted": false, "editability": { - "kind": "direct" + "kind": "readOnly", + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/1/requirement", @@ -2443,7 +2420,8 @@ { "defaulted": false, "editability": { - "kind": "direct" + "kind": "readOnly", + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/1/requirement/upToNextMinor", @@ -2458,8 +2436,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/sources/1/subpath", @@ -2865,7 +2842,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/uses/0/kind", @@ -2926,7 +2903,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/uses/1/condition", @@ -2942,7 +2919,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/uses/1/kind", @@ -2958,7 +2935,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/uses/1/name", @@ -2974,7 +2951,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/uses/1/source", diff --git a/Tests/AgentsManifestTests/Fixtures/LiteralCoverage.dump.json b/Tests/AgentsManifestTests/Fixtures/LiteralCoverage.dump.json index b0ccd53..b29b3e9 100644 --- a/Tests/AgentsManifestTests/Fixtures/LiteralCoverage.dump.json +++ b/Tests/AgentsManifestTests/Fixtures/LiteralCoverage.dump.json @@ -441,8 +441,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/agents", @@ -457,8 +456,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/condition", @@ -474,7 +472,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/0/kind", @@ -504,8 +502,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/native", @@ -535,8 +532,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/transport/arguments", @@ -607,7 +603,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -638,7 +634,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -700,7 +696,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -784,7 +780,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/0/transport/kind", @@ -799,8 +795,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/transport/workingDirectory", @@ -830,8 +825,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/agents", @@ -846,8 +840,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/condition", @@ -863,7 +856,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/1/kind", @@ -893,8 +886,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/native", @@ -924,8 +916,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/transport/headers", @@ -941,7 +932,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/1/transport/kind", @@ -996,7 +987,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1020,7 +1011,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1075,7 +1066,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1099,7 +1090,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1154,7 +1145,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1209,7 +1200,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1240,7 +1231,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1316,8 +1307,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/agents", @@ -1332,8 +1322,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/condition", @@ -1364,7 +1353,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/2/kind", @@ -1394,8 +1383,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/native", @@ -1410,8 +1398,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/parameters", @@ -1451,7 +1438,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1475,7 +1462,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1513,8 +1500,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/3/agents", @@ -1529,8 +1515,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/3/chatGPT", @@ -1545,8 +1530,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/3/condition", @@ -1562,7 +1546,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/3/kind", @@ -1577,8 +1561,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/3/native", @@ -1633,7 +1616,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1657,7 +1640,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1681,7 +1664,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -1719,8 +1702,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/agents", @@ -1735,8 +1717,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/condition", @@ -1751,8 +1732,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/exclude", @@ -1768,7 +1748,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/4/kind", @@ -1783,8 +1763,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/mode", @@ -1799,8 +1778,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/native", @@ -1860,8 +1838,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/overrides/0/agents/0", @@ -1876,8 +1853,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/overrides/0/mode", @@ -2023,8 +1999,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/5/agents", @@ -2039,8 +2014,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/5/condition", @@ -2095,7 +2069,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -2174,7 +2148,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -2274,7 +2248,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -2388,7 +2362,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -2502,7 +2476,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -2616,7 +2590,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -2685,7 +2659,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -2778,7 +2752,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -2878,7 +2852,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -2971,7 +2945,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -3033,7 +3007,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -3133,7 +3107,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -3240,7 +3214,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -3302,7 +3276,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/5/kind", @@ -3362,8 +3336,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/5/native", @@ -3403,7 +3376,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -3510,7 +3483,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -3555,7 +3528,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -3645,7 +3618,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -3773,7 +3746,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -3918,8 +3891,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/6/agents", @@ -3934,8 +3906,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/6/condition", @@ -3951,7 +3922,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/6/kind", @@ -3981,8 +3952,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/6/native", @@ -4028,7 +3998,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/6/rules/0/kind", @@ -4043,8 +4013,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/6/rules/0/operation", @@ -4060,7 +4029,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/6/rules/0/operation/kind", @@ -4106,7 +4075,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/6/rules/1/kind", @@ -4121,8 +4090,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/6/rules/1/operation", @@ -4138,7 +4106,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/6/rules/1/operation/kind", @@ -4184,7 +4152,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/6/rules/2/kind", @@ -4199,8 +4167,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/6/rules/2/operation", @@ -4216,7 +4183,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/6/rules/2/operation/kind", @@ -4262,7 +4229,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/6/rules/3/kind", @@ -4293,7 +4260,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/6/rules/3/operation/kind", @@ -4353,8 +4320,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/agents", @@ -4369,8 +4335,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/condition", @@ -4416,7 +4381,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/7/exclude/0/kind", @@ -4462,7 +4427,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/7/exclude/1/kind", @@ -4508,7 +4473,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/7/exclude/2/kind", @@ -4554,7 +4519,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/7/exclude/3/kind", @@ -4600,7 +4565,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/7/exclude/4/kind", @@ -4646,7 +4611,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/7/exclude/5/kind", @@ -4692,7 +4657,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/7/exclude/6/kind", @@ -4738,7 +4703,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/7/exclude/7/kind", @@ -4784,7 +4749,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/7/exclude/8/kind", @@ -4830,7 +4795,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/7/exclude/9/kind", @@ -4861,7 +4826,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/7/kind", @@ -4876,8 +4841,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/mode", @@ -4907,8 +4871,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/native", @@ -4953,8 +4916,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/select/0", @@ -4969,8 +4931,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/select/1", @@ -4985,8 +4946,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/select/2", @@ -5001,8 +4961,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/select/3", @@ -5017,8 +4976,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/select/4", @@ -5033,8 +4991,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/select/5", @@ -5049,8 +5006,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/select/6", @@ -5065,8 +5021,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/select/7", @@ -5081,8 +5036,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/select/8", @@ -5097,8 +5051,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/7/select/9", @@ -5158,8 +5111,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/8/agents/0", @@ -5174,8 +5126,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/8/condition", @@ -5206,7 +5157,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/8/event/kind", @@ -5237,7 +5188,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/8/kind", @@ -5252,8 +5203,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/8/matcher", @@ -5283,8 +5233,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/8/native", @@ -5324,7 +5273,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -5431,7 +5380,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -5476,7 +5425,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -5566,7 +5515,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -5694,7 +5643,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -5824,8 +5773,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/8/timeoutSeconds", @@ -5885,8 +5833,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/9/condition/agents", @@ -5916,8 +5863,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/9/condition/platforms/0", @@ -5932,8 +5878,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/9/condition/platforms/1", @@ -5963,8 +5908,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/9/condition/scopes/0", @@ -5979,8 +5923,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/9/condition/scopes/1", @@ -5996,7 +5939,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/9/kind", @@ -6026,8 +5969,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/9/native", @@ -6057,8 +5999,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/9/purpose", @@ -6073,8 +6014,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/defaultAgents", @@ -6149,8 +6089,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/groups/0/components", @@ -6165,8 +6104,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/groups/0/condition", @@ -6196,8 +6134,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/groups/0/uses", @@ -6243,7 +6180,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/0/kind", @@ -6289,7 +6226,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/0/requirement", @@ -6304,8 +6241,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/sources/0/subpath", @@ -6336,7 +6272,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/1/kind", @@ -6382,7 +6318,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/1/requirement", @@ -6397,8 +6333,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/sources/1/subpath", @@ -6453,7 +6388,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -6477,7 +6412,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -6501,7 +6436,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -6525,7 +6460,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "shared constant or assembled value; replace its definition explicitly" }, "origins": [ { @@ -6593,8 +6528,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/uses/1/condition/agents/0", @@ -6609,8 +6543,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/uses/1/condition/platforms", @@ -6625,8 +6558,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/uses/1/condition/scopes", @@ -6642,7 +6574,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/uses/1/kind", @@ -6672,8 +6604,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/uses/1/source", @@ -6688,8 +6619,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/watch", diff --git a/Tests/AgentsManifestTests/Fixtures/PrintedEmpty.dump.json b/Tests/AgentsManifestTests/Fixtures/PrintedEmpty.dump.json index 24fcf74..b55ad0e 100644 --- a/Tests/AgentsManifestTests/Fixtures/PrintedEmpty.dump.json +++ b/Tests/AgentsManifestTests/Fixtures/PrintedEmpty.dump.json @@ -30,8 +30,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components", @@ -46,8 +45,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/defaultAgents", @@ -62,8 +60,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/exports", @@ -78,8 +75,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/groups", @@ -94,8 +90,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/sources", @@ -110,8 +105,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/uses", @@ -126,8 +120,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/watch", diff --git a/Tests/AgentsManifestTests/Fixtures/PrintedFields.dump.json b/Tests/AgentsManifestTests/Fixtures/PrintedFields.dump.json index 7fe46c1..96281c0 100644 --- a/Tests/AgentsManifestTests/Fixtures/PrintedFields.dump.json +++ b/Tests/AgentsManifestTests/Fixtures/PrintedFields.dump.json @@ -226,8 +226,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/agents", @@ -242,8 +241,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/condition", @@ -258,8 +256,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/exclude", @@ -275,7 +272,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/0/kind", @@ -290,8 +287,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/mode", @@ -306,8 +302,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/native", @@ -322,8 +317,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/overrides", @@ -338,8 +332,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/0/select", @@ -399,8 +392,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/condition", @@ -446,7 +438,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/1/kind", @@ -461,8 +453,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/mode", @@ -477,8 +468,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/native", @@ -538,8 +528,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/overrides/0/agents/0", @@ -554,8 +543,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/overrides/0/mode", @@ -615,8 +603,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/1/overrides/1/mode", @@ -721,8 +708,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/agents", @@ -737,8 +723,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/condition", @@ -753,8 +738,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/exclude", @@ -770,7 +754,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/2/kind", @@ -785,8 +769,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/mode", @@ -801,8 +784,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/native", @@ -817,8 +799,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/2/overrides", @@ -878,8 +859,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/3/agents", @@ -894,8 +874,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/3/condition", @@ -910,8 +889,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/3/exclude", @@ -927,7 +905,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/3/kind", @@ -942,8 +920,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/3/mode", @@ -958,8 +935,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/3/native", @@ -1004,8 +980,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/3/overrides/0/agents", @@ -1020,8 +995,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/3/overrides/0/mode", @@ -1051,8 +1025,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/3/select", @@ -1112,8 +1085,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/agents/0", @@ -1128,8 +1100,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/agents/1", @@ -1174,8 +1145,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/chatGPT/0/append", @@ -1190,8 +1160,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/chatGPT/0/condition", @@ -1266,8 +1235,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/chatGPT/1/condition", @@ -1327,8 +1295,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/chatGPT/1/sections/0/condition", @@ -1389,7 +1356,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/4/chatGPT/1/sections/1/condition", @@ -1405,7 +1372,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/4/chatGPT/1/sections/1/name", @@ -1421,7 +1388,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/4/chatGPT/1/sections/1/source", @@ -1436,8 +1403,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/condition", @@ -1453,7 +1419,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/4/kind", @@ -1468,8 +1434,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/native", @@ -1515,7 +1480,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/4/sections/0/condition", @@ -1531,7 +1496,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/4/sections/0/name", @@ -1547,7 +1512,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/4/sections/0/source", @@ -1577,8 +1542,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/sections/1/condition", @@ -1639,7 +1603,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/4/sections/2/condition", @@ -1655,7 +1619,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/4/sections/2/name", @@ -1671,7 +1635,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/components/4/sections/2/source", @@ -1701,8 +1665,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/components/4/sections/3/condition", @@ -1762,8 +1725,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/defaultAgents/0", @@ -1778,8 +1740,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/defaultAgents/1", @@ -1794,8 +1755,7 @@ { "defaulted": false, "editability": { - "kind": "readOnly", - "reason": "expanded value has no independent source range" + "kind": "direct" }, "origins": [], "pointer": "/defaultAgents/2", @@ -1810,8 +1770,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/exports", @@ -1826,8 +1785,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/groups", @@ -1873,7 +1831,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/0/kind", @@ -1919,7 +1877,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/0/requirement", @@ -1934,8 +1892,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/sources/0/subpath", @@ -1966,7 +1923,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/1/kind", @@ -1996,7 +1953,8 @@ { "defaulted": false, "editability": { - "kind": "direct" + "kind": "readOnly", + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/1/requirement", @@ -2011,7 +1969,8 @@ { "defaulted": false, "editability": { - "kind": "direct" + "kind": "readOnly", + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/1/requirement/branch", @@ -2087,7 +2046,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/2/kind", @@ -2118,7 +2077,7 @@ "defaulted": true, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/2/requirement", @@ -2164,7 +2123,7 @@ "defaulted": false, "editability": { "kind": "readOnly", - "reason": "default field has no source range" + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/3/kind", @@ -2209,7 +2168,8 @@ { "defaulted": false, "editability": { - "kind": "direct" + "kind": "readOnly", + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/3/requirement", @@ -2224,7 +2184,8 @@ { "defaulted": false, "editability": { - "kind": "direct" + "kind": "readOnly", + "reason": "normalized field; replace its containing construction" }, "origins": [], "pointer": "/sources/3/requirement/revision", @@ -2239,8 +2200,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/sources/3/subpath", @@ -2255,8 +2215,7 @@ { "defaulted": true, "editability": { - "kind": "readOnly", - "reason": "default field has no source range" + "kind": "direct" }, "origins": [], "pointer": "/uses", From f8a8aaed7e73c8b4bd310acdf8f19df121c8a90f Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:43:12 +0800 Subject: [PATCH 019/171] fix(state): persist observed journals before recovery and prepare watch writes Recovery syncs the observed journal's directory before it acts in any phase. Watch add, seen and remove capture preparation evidence before contacting Git and validate it before publication. Check preimages before entering publication, record disposal conflicts on the failing container, and scope rename capability to one transaction. Name recovery slots by their contents, move checkpoints, disposal and the session into their own files, model content as a source and expectation, and keep CPlatform within DirectoryHandle. Tests confirm a stopped child before signalling it and bound its termination. The full kill-point matrix runs under the publicationMatrix tag with AGENTS_PUBLICATION_MATRIX=full. --- Documentation/Architecture/Package.md | 22 +- Documentation/Architecture/State.md | 95 +++-- README.md | 10 + Sources/AgentsCore/DirectoryHandle.swift | 146 ++++--- Sources/AgentsCore/FileLock.swift | 5 +- Sources/AgentsCore/FileTransaction.swift | 351 ++++++++------- Sources/AgentsCore/SourceCache.swift | 3 +- .../AgentsCore/TransactionCheckpoint.swift | 84 ++++ Sources/AgentsCore/TransactionDisposal.swift | 147 +++++++ Sources/AgentsCore/TransactionEvidence.swift | 56 +-- Sources/AgentsCore/TransactionJournal.swift | 168 +++----- Sources/AgentsCore/TransactionPaths.swift | 18 +- .../AgentsCore/TransactionPermissions.swift | 84 ++-- Sources/AgentsCore/TransactionRecovery.swift | 398 ++---------------- Sources/AgentsCore/TransactionSession.swift | 243 +++++++++++ Sources/AgentsCore/UpdatePreconditions.swift | 1 - Sources/AgentsCore/WatchOperations.swift | 43 +- .../CachePublicationTests.swift | 51 ++- .../DirectoryHandleTests.swift | 8 +- .../InstructionTransactionTests.swift | 2 +- .../PreparationEvidenceTests.swift | 20 +- .../ProcessTerminationTests.swift | 74 ++++ .../AgentsCoreTests/ProcessTestSupport.swift | 6 +- Tests/AgentsCoreTests/PublicationTests.swift | 309 +++++++++++--- .../StateInspectionTests.swift | 8 +- .../StateTransactionTests.swift | 194 ++++----- .../TransactionCostTests.swift | 74 ++-- .../TransactionMetadataTests.swift | 34 +- .../WatchDurabilityTests.swift | 24 +- Tests/AgentsCoreTests/WatchGitLockTests.swift | 15 +- .../WatchInspectionTests.swift | 13 +- .../WatchPreparationTests.swift | 93 ++++ .../AgentsCoreTests/WatchReferenceTests.swift | 8 +- Tests/AgentsCoreTests/WatchStateTests.swift | 21 +- .../AutomaticSelectionTests.swift | 5 +- Tests/AgentsSkillsTests/CoreTestSupport.swift | 6 + .../LockedArtifactLifecycleTests.swift | 17 +- .../ReadOnlyInspectionTests.swift | 16 +- .../TransactionDoctorTests.swift | 4 +- .../UpdateReportingTests.swift | 8 +- .../CombinedUpdateTests.swift | 10 +- .../UpdateTransactionTests.swift | 46 +- Tests/StateTestProcess/main.swift | 27 +- Tests/StateTestSupport/ProcessWait.swift | 37 ++ 44 files changed, 1797 insertions(+), 1207 deletions(-) create mode 100644 Sources/AgentsCore/TransactionCheckpoint.swift create mode 100644 Sources/AgentsCore/TransactionDisposal.swift create mode 100644 Sources/AgentsCore/TransactionSession.swift create mode 100644 Tests/AgentsCoreTests/ProcessTerminationTests.swift create mode 100644 Tests/AgentsCoreTests/WatchPreparationTests.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index acf9c0c..2346b4c 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -148,20 +148,20 @@ baselines and seeds belong to the test corpus, not the runtime language. including the complete instruction section, prompt and physical-target models. - `StateStore` owns scope paths, validation, deterministic encoding and state persistence. `FileLock` serializes state access; `FileTransaction` durably - journals replacements across installations, state and cache. `FileSnapshot` and - `FileObjectIdentity` own content and physical-object evidence, including directory - descendants and permission bits. `DirectoryHandle` owns verified deletion, + journals replacements across installations, state and cache. `FileSnapshot`, + `FileObjectIdentity` and `DirectoryWriteLease` own content, physical-object + and temporary directory-write evidence, including directory descendants and + permission bits. Within the transaction protocol only `DirectoryHandle` calls + `CPlatform`; it owns verified deletion, durable synchronization, inode-checked directory permission updates and typed cross-directory rename results. Mutating state access recovers interrupted transactions before - proceeding, as described in - [State and cache](State.md). + proceeding, as described in [State and cache](State.md). - `SourceCache` owns bare Git mirrors, requirement resolution, exact snapshots, - digest-addressed downloads and pruning across skill, instruction and watch pins. - `SourceResolutionSession` shares disposable exact snapshots between domain - planners during one update. `StatePrecondition`, `TargetPrecondition` and - `PathIdentity` validate - the rendered generation before application. `TransactionOutcome` follows - its owning journal through commit and recovery. + digest-addressed downloads and pruning across skill, instruction and watch + pins. `SourceResolutionSession` shares disposable exact snapshots between + domain planners during one update. `StatePrecondition`, `TargetPrecondition` + and `PathIdentity` validate the rendered generation before application. + `TransactionOutcome` follows its owning journal through commit and recovery. `ProcessRunner` executes subprocesses. - `WatchOperations` owns source subscriptions, seen baselines, branch tracking and file comparisons. `WatchState` defines version 1 of `agents.watch`. diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index bb0e399..4947806 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -131,9 +131,11 @@ remains live. Domain plans also validate source content and executable flags. The scope writer lock covers recovery, preparation, retention and publication. Recovery runs first. Apply checks the prepared evidence before retention, after -retention at commit entry, and after staging before publication. The journal -receives the plan's captured preimages rather than taking a later state -baseline. Transactions without a state plan, such as cache publication, do not +retention at commit entry, and after staging before publication. The journal's +expected preimages are the evidence the plan captured. Watch subscription, +acknowledgment and removal capture declaration, lock and watch state before +contacting Git; that evidence is also the baseline for the lock that pruning +follows. Transactions without a state plan, such as cache publication, do not implicitly add declaration, lock or watch preconditions. Domain hooks check related inputs that the journal does not replace. State parsing consumes the captured raw bytes, so decoded inputs and journal evidence describe the same @@ -179,8 +181,9 @@ Each operation records its path, install/delete action, expected preimage or absence, parent identity, private container, sealed staged object, progress and any conflict reason and retained locations. Object evidence contains device, inode, type, SHA-256 digest, permission bits and executable status. Directory -evidence includes child identities and digests. Data replacements inherit the existing regular -file's metadata. Undo restores the original object and its metadata. +evidence includes child identities and digests. Data replacements inherit the +existing regular file's metadata. Undo restores the original object and its +metadata. Each used target parent has one private container with a UUID-derived name and mode 0700 on the same filesystem as its targets. The journal records the name @@ -192,16 +195,20 @@ no ownership claim on content inserted into this private transaction storage. An unidentified container may only be removed with `rmdir` when empty; a nonempty one is an unresolved conflict. -Construction is sealed once. Snapshot and content verification consume the same -read bytes, and check the expected content hash and executable flags. `ready` -and that snapshot become durable together. Changes after sealing are conflicts; -recovery never refreshes a sealed snapshot to adopt changed content. -Construction checkpoints do not rewrite the journal or rescan a growing copy. +Construction is sealed once, and sealing is its only journal write. Snapshot and +content verification consume the same read bytes, and check the expected content +hash and executable flags. `ready` and that snapshot become durable together. +Changes after sealing are conflicts; recovery never refreshes a sealed snapshot +to adopt changed content. Preimages displaced by exchange, deletion quarantines and published objects are user data. Their identity and digest remain mandatory evidence even inside a -private container. A container holding such recovery objects receives complete -terminal disposal evidence after their expected distribution has been verified. +private container. Container entries are named by operation index and what they +hold: `staged` is a creation's private staging, `exchanged` holds an exchange's +staging until publication and then the displaced preimage, `deleted` holds a +deleted object and `withdrawn` holds a creation that undo moved aside. A +container holding such recovery objects receives complete terminal disposal +evidence after their expected distribution has been verified. | Progress | Durable evidence and possible distribution | | --- | --- | @@ -229,10 +236,12 @@ also uses `F_FULLFSYNC` to request a storage flush. Atomic exchange and no-replace rename are checked before modifying any target, preimage or state file. Before this check the transaction can only create missing ancestry, its journal and its private containers. Probes run on -container objects on the actual publication device. Successful capability -results are cached by `st_dev` within the process. Unsupported primitives remove -the journal and containers; empty missing ancestry may remain. There is no -replacing-rename fallback, including for declaration, lock and watch creation. +container objects on the actual publication device. A successful result is +cached by `st_dev` only for the rest of that commit; every commit probes its +devices again, because a device number can be reused after an unmount. +Unsupported primitives remove the journal and containers; empty missing ancestry +may remain. There is no replacing-rename fallback, including for declaration, +lock and watch creation. Only `EINVAL`, `ENOSYS`, `ENOTSUP` and `EOPNOTSUPP` mean unsupported. `EEXIST` and `ENOTEMPTY` mean an existence conflict. Other failures retain their errno @@ -244,16 +253,20 @@ and system reason. Probes and publication use the same classification. | Existing | Recheck the preimage, then exchange it with staging using Darwin `RENAME_SWAP` or Linux `RENAME_EXCHANGE`. The displaced object stays inside the container and is compared before confirmation. A mismatched preimage is retained as a conflict. | | Deletion | Move the entry without replacement into the container's quarantine, then verify its physical identity and digest. Destructive cleanup verifies that evidence again. | -Publication intent is durable before rename. Both container and target parent -are synced before `applied` becomes durable. Replacement always retains a -directory entry at the installation path. The operation's complete target and -recovery-object distribution must match before confirmation and again before the -commit marker. The scope lock excludes cooperating writers; the atomic protocol -also preserves objects changed by editors that ignore it. - -Read-only directory roots retain their final modes. Darwin requires write access -to relocate a directory between parents. Before granting owner-write on a recorded -inode, `publishing` or `restoring` intent and the original permission bits are +Each operation checks its preimage before and again after its publication intent +becomes durable; a preparation already stale before the intent cancels from +`ready` without leasing or moving any object. Publication intent is durable +before rename. Both container and target parent are synced before `applied` +becomes durable. Replacement always retains a directory entry at the +installation path. The operation's complete target and recovery-object +distribution must match before confirmation and again before the commit marker. +The scope lock excludes cooperating writers; the atomic protocol also preserves +objects changed by editors that ignore it. + +Read-only directory targets retain their final modes. Darwin and Linux require +write access to a directory to move it between parents, because the rename +updates its `..` entry. Before granting owner-write on a recorded inode, +`publishing` or `restoring` intent and the original permission bits are durable. The transaction syncs the temporary mode, performs the atomic rename, then restores and syncs the original mode before recording `applied`, `restored` or `cancelled`. Only the recorded mode or that mode plus owner-write is admitted @@ -269,8 +282,11 @@ watch reconciliation can release any ref. Pending watch-reference recovery also reports `CoreError.transactionRecovered` when no journal remains. Retained refs remain available while a journal conflict is unresolved. -An applying journal reverses verified publications in reverse order. A committed -journal completes terminal cleanup. Physical identity and digest distinguish a +Recovery treats any observed journal as possibly renamed without its directory +barrier: before granting permissions, renaming objects or deleting any resource +it syncs `transaction.json` and its parent, including on retry. An applying +journal reverses verified publications in reverse order. A committed journal +completes terminal cleanup. Physical identity and digest distinguish a transaction's publication even after rename but before `applied`. Another inode with identical bytes remains external. Missing or changed evidence causes an unresolved conflict; names and equal bytes never establish ownership. Other @@ -287,19 +303,20 @@ barriers before recording restoration. Interrupted permission changes are restored by recorded inode, independently of payload rollback. Changed payload bytes remain available. Restoration repeats the mode barrier even when the original mode is already visible. A recorded directory -inode missing from all known locations, or a mode outside the original/temporary -pair, leaves an unresolved conflict with the original mode and intent retained. +inode missing from every location the operation/progress table allows, or a mode +outside the original/temporary pair, leaves an unresolved conflict with the +original mode and intent retained. Before disposal the journal persists terminal `committed` or `rolledBack` state -and the complete recovery-object evidence. A terminal marker observed on entry -may have been renamed without its directory barrier: recovery syncs the marker -and its parent before deleting any resource. A separate global discard intent -then becomes durable. Only after that intent may missing objects or descendants -mean interrupted cleanup. Changed identities, digests or unexpected descendants -in sealed disposal evidence remain conflicts. Unpublished private construction -is discarded by verified container identity. Links are never followed during -deletion. Owner access may be granted to discarded directories without changing -installed or restored metadata. Absent entries still receive a parent barrier. +and the complete recovery-object evidence. A commit disposes immediately after +sealing that evidence; recovery first revalidates every target and container +against it. A separate global discard intent then becomes durable. Only after +that intent may missing objects or descendants mean interrupted cleanup. Changed +identities, digests or unexpected descendants in sealed disposal evidence remain +conflicts. Unpublished private construction is discarded by verified container +identity. Links are never followed during deletion. Owner access may be granted +to discarded directories without changing installed or restored metadata. Absent +entries still receive a parent barrier. Conflicts retain `transaction.json`, the available target objects and private containers holding displaced preimages or rollback quarantines. Each conflicting diff --git a/README.md b/README.md index 1df85fb..62c7a08 100644 --- a/README.md +++ b/README.md @@ -306,6 +306,16 @@ swift format lint --strict --configuration .swift-format \ --recursive Package.swift Sources Tests ``` +Publication kill-point tests, tagged `publicationMatrix`, kill each operation at +representative points and recovery from every seed at its durable steps. When +changing the transaction protocol, also run every recorded point: + +```bash +env -u CODEX_HOME -u CLAUDE_CONFIG_DIR -u XDG_CONFIG_HOME \ + -u XDG_STATE_HOME -u XDG_CACHE_HOME AGENTS_PUBLICATION_MATRIX=full \ + swift test --filter PublicationTests +``` + The required checks are `policy / policy` and `validate / result`, provided by full-SHA-pinned reusable workflows from `agents-tools/github-workflows`. Source policy validates PR titles, new commit messages and added lines. diff --git a/Sources/AgentsCore/DirectoryHandle.swift b/Sources/AgentsCore/DirectoryHandle.swift index 8b6a7a8..0f205cc 100644 --- a/Sources/AgentsCore/DirectoryHandle.swift +++ b/Sources/AgentsCore/DirectoryHandle.swift @@ -1,6 +1,5 @@ import CPlatform import Foundation -import Synchronization /// Pins directory ancestry. Child operations never traverse symbolic links. final class DirectoryHandle { @@ -8,19 +7,38 @@ final class DirectoryHandle { let descriptor: Int32 let url: URL + /// Depth counts levels above the opened directory; 0 is the directory itself. + enum AncestryStep { + case created(depth: Int) + /// The parent barrier that makes a created component durable. + case synced(depth: Int) + + var name: String { + switch self { + case .created(let depth): "created.\(depth)" + case .synced(let depth): "synced.\(depth)" + } + } + } + + /// With `create`, every component's parent is synced. Checkpoints mark only components + /// this call creates, so their names and number do not depend on the host path. init( - at url: URL, create: Bool = false, checkpoint: (String) throws -> Void = { _ in } + at url: URL, create: Bool = false, checkpoint: (AncestryStep) throws -> Void = { _ in } ) throws { self.url = url.standardizedFileURL var current = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC) guard current >= 0 else { throw CoreError.unsafePath("cannot open filesystem root") } defer { if current >= 0 { close(current) } } - for (index, component) in self.url.pathComponents.dropFirst().enumerated() { + let components = self.url.pathComponents.dropFirst() + for (index, component) in components.enumerated() { // macOS exposes these root-owned system directories through immutable aliases. // All task-controlled components, including every cache ancestor, use O_NOFOLLOW. let systemAlias = index == 0 && platform_system_alias(component) if create { + let depth = components.count - 1 - index var info = stat() + var created = false if fstatat(current, component, &info, AT_SYMLINK_NOFOLLOW) != 0 { guard errno == ENOENT, mkdirat(current, component, 0o700) == 0 else { throw FileSystem.posixError( @@ -28,11 +46,12 @@ final class DirectoryHandle { } try FileSystem.requireAccess( R_OK | W_OK | X_OK, at: self.url, parent: current, name: component) - try checkpoint("directory.created.\(component)") + created = true + try checkpoint(.created(depth: depth)) } // An existing entry may have been published by an interrupted creator. try Self.synchronize(current) - try checkpoint("directory.synced.\(component)") + if created { try checkpoint(.synced(depth: depth)) } } let next = openat( current, component, O_RDONLY | O_DIRECTORY | (systemAlias ? 0 : O_NOFOLLOW) | O_CLOEXEC) @@ -65,6 +84,22 @@ final class DirectoryHandle { try DirectoryHandle(parent: self, name: name) } + /// Opens a child directory only if it is still the generation `expected` described. + func child(_ name: String, matching expected: stat) throws -> DirectoryHandle { + let directory = try child(name) + var opened = stat() + guard fstat(directory.descriptor, &opened) == 0, Self.sameGeneration(expected, opened) else { + throw CoreError.invalidState("directory changed before reading: \(name)") + } + return directory + } + + static func sameGeneration(_ first: stat, _ second: stat) -> Bool { + var first = first + var second = second + return platform_same_generation(&first, &second) + } + func info(_ name: String) throws -> stat? { var value = stat() if fstatat(descriptor, name, &value, AT_SYMLINK_NOFOLLOW) == 0 { return value } @@ -92,6 +127,7 @@ final class DirectoryHandle { enum RemovalStep: String { case unlinked, synced } struct RemovalPoint { + /// Relative to the removed entry; empty for the entry itself. let path: String let step: RemovalStep } @@ -104,11 +140,11 @@ final class DirectoryHandle { checkpoint: (RemovalPoint) throws -> Void = { _ in } ) throws { try removeContents( - name, expected: expected, identity: expectedIdentity, prefix: name, + name, expected: expected, identity: expectedIdentity, prefix: "", checkpoint: checkpoint) // An absent entry may be an interrupted unlink whose parent was not synced. try sync() - try checkpoint(RemovalPoint(path: name, step: .synced)) + try checkpoint(RemovalPoint(path: "", step: .synced)) } private func removeContents( @@ -136,7 +172,7 @@ final class DirectoryHandle { } try directory.removeContents( child, expected: expected?.children?[child], identity: nil, - prefix: prefix + "/" + child, checkpoint: checkpoint) + prefix: prefix.isEmpty ? child : prefix + "/" + child, checkpoint: checkpoint) } try directory.sync() } else if let expected, try FileSnapshot.read(name, from: self) != expected { @@ -196,9 +232,8 @@ final class DirectoryHandle { } } - // A nil override delegates to the platform primitive; injected errno takes the same classifier. + /// A non-nil injected errno replaces the platform result and takes the same classifier. @TaskLocal static var atomicRenameFailure: (@Sendable (RenameMode) -> Int32?)? - private static let capableDevices = Mutex>([]) var device: UInt64 { get throws { try objectIdentity.device } } var objectIdentity: FileObjectIdentity { @@ -213,12 +248,12 @@ final class DirectoryHandle { enum PermissionStep: String { case changed, synced } - /// Only a recorded directory inode may receive the journal's temporary owner-write bit. + /// Only the lease's recorded directory inode may receive its temporary owner-write bit. func setPermissions( - _ mode: mode_t, expecting identity: FileObjectIdentity, - from original: mode_t, checkpoint: (PermissionStep) throws -> Void + _ lease: DirectoryWriteLease, granting: Bool, checkpoint: (PermissionStep) throws -> Void ) throws { - let current = try checkedPermissions(expecting: identity, from: original) + let mode = granting ? lease.grantedMode : lease.original + let current = try checkedPermissions(lease) if current != mode { guard fchmod(descriptor, mode) == 0 else { let code = errno @@ -236,15 +271,13 @@ final class DirectoryHandle { try checkpoint(.synced) } - func checkedPermissions(expecting identity: FileObjectIdentity, from original: mode_t) throws - -> mode_t - { + func checkedPermissions(_ lease: DirectoryWriteLease) throws -> mode_t { var value = stat() - guard fstat(descriptor, &value) == 0, FileObjectIdentity(value) == identity else { + guard fstat(descriptor, &value) == 0, FileObjectIdentity(value) == lease.identity else { throw CoreError.invalidState("recorded directory identity changed") } let current = value.st_mode & 0o7777 - guard current == original || current == original | 0o200 else { + guard lease.admits(current) else { throw CoreError.invalidState( "directory permissions changed beyond transaction intent: \(url.path)") } @@ -274,51 +307,15 @@ final class DirectoryHandle { if self !== parent { try sync() } } - func rename( - _ name: String, to destination: String, swap: Bool = false, - afterRename: () throws -> Void = {} - ) throws { - if swap { - try move(name, to: self, named: destination, mode: .exchange, afterRename: afterRename) - } else { - guard renameat(descriptor, name, descriptor, destination) == 0 else { - throw CoreError.invalidState("cannot replace \(destination): \(errno)") - } - try afterRename() - try sync() - } - } - - func renameExclusive( - _ name: String, to destination: String, - afterRename: () throws -> Void = {} - ) throws { - try move(name, to: self, named: destination, mode: .exclusive, afterRename: afterRename) - } - enum ProbeStep: String { case firstCreated, secondCreated, exchanged, collisionChecked, moved, verified } - /// The descriptor is a journal-owned private container on the publication device. - func requireAtomicRenames(checkpoint: (ProbeStep) throws -> Void) throws { - if Self.atomicRenameFailure != nil { - try probeAtomicRenames(checkpoint: checkpoint) - return - } - let device = try device - // The lock spans probing so concurrent scopes check a device only once. - try Self.capableDevices.withLock { devices in - if devices.contains(device) { return } - try probeAtomicRenames(checkpoint: checkpoint) - devices.insert(device) - } - } - - private func probeAtomicRenames(checkpoint: (ProbeStep) throws -> Void) throws { - let a = TransactionScratch.probeA.name - let b = TransactionScratch.probeB.name - let c = TransactionScratch.probeC.name + /// The descriptor is a private container on the publication device; the caller names + /// three absent probe entries inside it. + func requireAtomicRenames( + first a: String, second b: String, moved c: String, checkpoint: (ProbeStep) throws -> Void + ) throws { try write( a, data: Data("a".utf8), syncParent: false, afterCreate: { try checkpoint(.firstCreated) }) try write( @@ -447,7 +444,12 @@ final class DirectoryHandle { } try write("transaction.new", data: data, syncParent: false) try afterWrite() - try rename("transaction.new", to: "transaction.json", afterRename: afterRename) + // A replacing rename is reserved for the journal; publication exchanges or never replaces. + guard renameat(descriptor, "transaction.new", descriptor, "transaction.json") == 0 else { + throw CoreError.invalidState("cannot replace transaction.json: \(errno)") + } + try afterRename() + try sync() } func removeJournal(afterUnlink: () throws -> Void = {}) throws { @@ -516,6 +518,28 @@ final class DirectoryHandle { if includingParent { try sync() } } + /// Syncs a verified object's file contents, then each directory level after its children, + /// then this parent. + func synchronize(_ name: String, as snapshot: FileSnapshot) throws { + guard try FileSnapshot.read(name, from: self) == snapshot else { + throw CoreError.invalidState("transaction preimage changed before synchronization: \(name)") + } + try synchronizeContents(name, as: snapshot) + try sync() + } + + private func synchronizeContents(_ name: String, as snapshot: FileSnapshot) throws { + if let children = snapshot.children { + let directory = try child(name) + for (child, value) in children.sorted(by: { $0.key < $1.key }) { + try directory.synchronizeContents(child, as: value) + } + try directory.sync() + } else if snapshot.isRegular { + try syncFile(name, includingParent: false) + } + } + var identity: String { get throws { var info = stat() diff --git a/Sources/AgentsCore/FileLock.swift b/Sources/AgentsCore/FileLock.swift index 45d3db7..9e99a00 100644 --- a/Sources/AgentsCore/FileLock.swift +++ b/Sources/AgentsCore/FileLock.swift @@ -13,8 +13,9 @@ package enum FileLock { package static func withDescriptor( at url: URL, checkpoint: (String) throws -> Void = { _ in }, _ body: (Int32) throws -> T ) throws -> T { - let parent = try DirectoryHandle( - at: url.deletingLastPathComponent(), create: true, checkpoint: checkpoint) + let parent = try DirectoryHandle(at: url.deletingLastPathComponent(), create: true) { + try checkpoint("lock.ancestry." + $0.name) + } let descriptor = openat( parent.descriptor, url.lastPathComponent, O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC, S_IRUSR | S_IWUSR) diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index a152c17..3637170 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -4,22 +4,27 @@ import Foundation /// sealed publication evidence and terminal disposal. The scope writer lock spans /// preparation, commit and recovery; external writers are identified by inode and digest. package final class FileTransaction { - struct Content { - var url: URL? - var link: Bool - var linkDestination: String? - var data: Data? - var expectedHash: String? + enum Source { + case data(Data) + case copy(URL) + /// The destination is interpreted after publication, relative to the target parent. + case link(URL, destination: String) + /// A producer may construct arbitrary intermediate objects only inside its private container. + case prepared((URL) throws -> URL) + } + /// Checks for the sealed staging; nil fields are not compared. + struct Expectation { + var hash: String? var executableFlags: [String: Bool]? - var expectedKind: mode_t? - var expectedMode: mode_t? - var prepare: ((URL) throws -> URL)? + var kind: mode_t? + var mode: mode_t? } private struct Request { - var action: TransactionJournal.Action let path: String let evidence: TargetPrecondition - var content: Content + /// Absent for a deletion. + let source: Source? + let expectation: Expectation } private let store: StateStore private let checkpoint: (String) throws -> Void @@ -48,6 +53,40 @@ package final class FileTransaction { throw CoreError.invalidState("verification requires content") } } + let source: Source? + if let data { + source = .data(data) + } else if let content { + source = + link + ? .link( + content, + destination: Self.linkDestination( + content, parent: destination.deletingLastPathComponent(), store: store)) + : .copy(content) + } else { + source = nil + } + try append(destination, source: source, expecting: expecting) { + guard case .copy(let url) = source else { + return Expectation(hash: expectedHash, executableFlags: executableFlags) + } + return try Self.copyExpectation(url, hash: expectedHash, flags: executableFlags) + } + } + + func prepare(_ destination: URL, content: @escaping (URL) throws -> URL) throws { + try append(destination, source: .prepared(content), expecting: nil) { Expectation() } + } + + func remove(_ name: String, from parent: DirectoryHandle) throws { + try replace(parent.url.appendingPathComponent(name), content: nil) + } + + private func append( + _ destination: URL, source: Source?, expecting: TargetPrecondition?, + expectation: () throws -> Expectation + ) throws { let path = try TransactionPaths(store: store).path(for: destination) guard !requests.contains(where: { $0.path == path }) else { throw CoreError.invalidState("duplicate transaction destination") @@ -56,57 +95,27 @@ package final class FileTransaction { guard evidence.url.path == destination.standardizedFileURL.path else { throw CoreError.invalidState("precondition belongs to another target") } - var hash = expectedHash - var flags = executableFlags - var kind: mode_t? - var mode: mode_t? - if let content, data == nil, !link { - let expected = try Self.copyExpectation(content, hash: hash, flags: flags) - (hash, flags, kind, mode) = expected - } requests.append( - Request( - action: content != nil || data != nil ? .install : .delete, - path: path, evidence: evidence, - content: Content( - url: content, link: link, - linkDestination: link - ? content.map { - Self.linkDestination( - $0, parent: destination.deletingLastPathComponent(), store: store) - } : nil, - data: data, expectedHash: hash, executableFlags: flags, expectedKind: kind, - expectedMode: mode))) + Request(path: path, evidence: evidence, source: source, expectation: try expectation())) } fileprivate static func copyExpectation( _ source: URL, hash: String?, flags: [String: Bool]? - ) throws -> (String?, [String: Bool]?, mode_t?, mode_t?) { + ) throws -> Expectation { let physical = source.resolvingSymlinksInPath() let parent = try DirectoryHandle(at: physical.deletingLastPathComponent()) if let hash, let flags { let info = try parent.info(physical.lastPathComponent) - return ( - hash, flags, info.map(FileObjectIdentity.init)?.kind, info.map { $0.st_mode & 0o7777 } - ) + return Expectation( + hash: hash, executableFlags: flags, kind: info.map(FileObjectIdentity.init)?.kind, + mode: info.map { $0.st_mode & 0o7777 }) } let capture = try FileSnapshot.capture(physical.lastPathComponent, from: parent) guard let snapshot = capture.snapshot else { throw CoreError.notFound(source.path) } - return ( - hash ?? "sha256:" + capture.contentHash, flags ?? capture.executableFlags, - snapshot.identity.kind, snapshot.mode - ) - } - - /// A producer may construct arbitrary intermediate objects only inside its private container. - func prepare(_ destination: URL, content: @escaping (URL) throws -> URL) throws { - try replace(destination, content: nil) - requests[requests.count - 1].action = .install - requests[requests.count - 1].content.prepare = content - } - - func remove(_ name: String, from parent: DirectoryHandle) throws { - try replace(parent.url.appendingPathComponent(name), content: nil) + return Expectation( + hash: hash ?? "sha256:" + capture.contentHash, + executableFlags: flags ?? capture.executableFlags, + kind: snapshot.identity.kind, mode: snapshot.mode) } package func commit() throws { @@ -132,8 +141,8 @@ package final class FileTransaction { }) { try SourceCache(store: store, checkpoint: checkpoint).beginWatchReferenceUpdate() } - for index in session.journal.entries.indices { - try session.stage(index, content: requests[index].content) + for (index, request) in requests.enumerated() { + try session.stage(index, source: request.source, expectation: request.expectation) } try session.emit(.preconditions) try validateBeforePublication() @@ -143,11 +152,10 @@ package final class FileTransaction { try validateBeforePublication() try session.prepareCleanup() try session.emit(.commitValidated) - session.journal.phase = .committed - try session.persist(.terminal) + try session.finish(.committed) outcome.disposition = .committed try session.emit(.phase(.committed)) - try session.cleanup() + try session.dispose() } catch { do { _ = try Self.recover(store: store, outcome: outcome) } catch { outcome.disposition = .recoveryRequired @@ -177,11 +185,15 @@ package final class FileTransaction { for request in requests { let key = try paths.components(request.path).root if roots[key] == nil { - roots[key] = try paths.root(key, create: true, checkpoint: checkpoint) + roots[key] = try paths.root(key, create: true) { step in + try checkpoint(TransactionCheckpoint.rootAncestry(key, step).name) + } } } - let parents = try requests.map { - try paths.parent(for: $0.path, roots: roots, create: true, checkpoint: checkpoint) + let parents = try requests.enumerated().map { index, request in + try paths.parent(for: request.path, roots: roots, create: true) { level in + try checkpoint(TransactionCheckpoint.parentCreated(entry: index, level: level).name) + } } for request in requests { try request.evidence.validateIdentity() } let id = UUID() @@ -196,12 +208,13 @@ package final class FileTransaction { } else { container = containers.count identities[identity] = container - containers.append(.init(entry: index, name: ".agents-\(id.uuidString)-\(container)")) + containers.append( + .init(entry: index, name: TransactionJournal.containerName(id: id, index: container))) } entries.append( .init( - path: request.path, action: request.action, preimage: request.evidence.snapshot, - parentIdentity: identity, container: container)) + path: request.path, action: request.source == nil ? .delete : .install, + preimage: request.evidence.snapshot, parentIdentity: identity, container: container)) } let journal = TransactionJournal( id: id, scope: try directory.identity, @@ -228,35 +241,7 @@ package final class FileTransaction { } } -final class TransactionSession { - var journal: TransactionJournal - let directory: DirectoryHandle - let parents: [DirectoryHandle] - let checkpoint: (String) throws -> Void - - init( - journal: TransactionJournal, directory: DirectoryHandle, parents: [DirectoryHandle], - checkpoint: @escaping (String) throws -> Void - ) { - self.journal = journal - self.directory = directory - self.parents = parents - self.checkpoint = checkpoint - } - - func emit(_ point: TransactionCheckpoint) throws { try checkpoint(point.name) } - func persist(_ change: TransactionCheckpoint.Change) throws { - try requireScope() - try directory.writeJournal( - StateStore.encode(journal), - afterWrite: { - try emit(.persisted(journal.phase, change, .written)) - }, - afterRename: { - try emit(.persisted(journal.phase, change, .renamed)) - }) - } - +extension TransactionSession { func createContainers() throws { for index in journal.containers.indices { let parent = parents[journal.containers[index].entry] @@ -276,134 +261,134 @@ final class TransactionSession { try emit(.containersIdentified) } - func container(_ index: Int) throws -> DirectoryHandle { - let record = journal.containers[index] - let parent = parents[record.entry] - guard let expected = record.identity, - try parent.info(record.name).map(FileObjectIdentity.init) == expected - else { - throw conflict(record.entry, "private container identity changed or is missing") - } - let handle = try parent.child(record.name) - guard try handle.objectIdentity == expected else { - throw conflict(record.entry, "private container changed while opening") - } - return handle - } - func checkCapabilities() throws { for index in journal.containers.indices { - try container(index).requireAtomicRenames { try emit(.probe(index, $0)) } + let container = try container(index) + let device = try container.device + guard !capableDevices.contains(device) else { continue } + let names = TransactionScratch.probes + try container.requireAtomicRenames( + first: names.first, second: names.second, moved: names.moved + ) { try emit(.probe(index, $0)) } + capableDevices.insert(device) } } - func stage(_ index: Int, content input: FileTransaction.Content) throws { + func stage( + _ index: Int, source: FileTransaction.Source?, expectation: FileTransaction.Expectation + ) throws { let entry = journal.entries[index] let parent = parents[index] let scratch = try container(entry.container) - try entry.preimage?.synchronize(entry.name, from: parent) + if let preimage = entry.preimage { try parent.synchronize(entry.name, as: preimage) } try emit(.stage(index, .preimageSynced)) - var content = try prepareContent(input, index: index, scratch: scratch) - if content.data != nil { - content.expectedMode = entry.preimage?.isRegular == true ? entry.preimage!.mode : 0o600 - } - let name = TransactionScratch.staged.name(index) - try construct(content, index: index, scratch: scratch, parent: parent) - try emit(.stage(index, .constructed)) - let capture = try FileSnapshot.capture(name, from: scratch) - try verify(content, capture: capture) - if entry.action == .install, capture.snapshot == nil { - throw conflict(index, "missing constructed object") + let staging = TransactionScratch.staging(for: entry) + var staged: FileSnapshot? + if let source { + let sealed = try construct( + source, expectation: expectation, named: staging.name(index), index: index, + scratch: scratch, parent: parent) + try emit(.stage(index, .constructed)) + let capture = try FileSnapshot.capture(staging.name(index), from: scratch) + try verify(source, sealed, capture: capture) + guard let snapshot = capture.snapshot else { + throw conflict(index, "missing constructed object") + } + staged = snapshot + } else { + try emit(.stage(index, .constructed)) } - for slot in TransactionScratch.objectSlots - where entry.action == .delete || slot != .staged { + for slot in TransactionScratch.objectSlots where source == nil || slot != staging { guard try scratch.info(slot.name(index)) == nil else { throw CoreError.invalidState("unexpected private recovery slot before sealing") } } try scratch.sync() - journal.entries[index].staged = capture.snapshot + journal.entries[index].staged = staged try advance(index, to: .ready) } - private func prepareContent( - _ input: FileTransaction.Content, index: Int, - scratch: DirectoryHandle - ) throws -> FileTransaction.Content { - guard let prepare = input.prepare else { return input } - var content = input - let name = TransactionScratch.work.name(index) - try scratch.makeDirectory(name, syncParent: false) - try emit(.stage(index, .workCreated)) - let root = scratch.url.appendingPathComponent(name) - let source = try prepare(root) - guard PathSafety.isContained(source.resolvingSymlinksInPath(), in: root) else { - throw CoreError.unsafePath("prepared content escapes transaction staging") - } - content.url = source - (content.expectedHash, content.executableFlags, content.expectedKind, content.expectedMode) = - try FileTransaction.copyExpectation( - source, hash: nil, flags: nil) - try emit(.stage(index, .workPrepared)) - return content - } - + /// Returns the expectation the sealed staging must meet. private func construct( - _ content: FileTransaction.Content, index: Int, - scratch: DirectoryHandle, parent: DirectoryHandle - ) throws { + _ source: FileTransaction.Source, expectation: FileTransaction.Expectation, + named name: String, index: Int, scratch: DirectoryHandle, parent: DirectoryHandle + ) throws -> FileTransaction.Expectation { let entry = journal.entries[index] - let name = TransactionScratch.staged.name(index) - if let data = content.data { + var expectation = expectation + switch source { + case .data(let data): + let original = entry.preimage?.isRegular == true ? entry.preimage : nil + expectation.mode = original?.mode ?? 0o600 try scratch.write( - name, data: data, - preservingMetadataOf: entry.preimage?.isRegular == true ? entry.name : nil, + name, data: data, preservingMetadataOf: original == nil ? nil : entry.name, originalParent: parent, syncParent: false, afterCreate: { try emit(.stage(index, .writeCreated)) }) - } else if let source = content.url { - if content.link { - // The link is interpreted after publication, relative to the target parent. - let destination = content.linkDestination ?? source.path - try scratch.link(name, destination: destination, syncParent: false) - } else { - try Self.validateCopy(source) - let origin = source.resolvingSymlinksInPath() - try scratch.copy( - name, from: DirectoryHandle(at: origin.deletingLastPathComponent()), - named: origin.lastPathComponent, syncParent: false - ) { try emit(.copy(index, $0)) } + case .link(_, let destination): + try scratch.link(name, destination: destination, syncParent: false) + case .copy(let url): + try copy(url, named: name, index: index, scratch: scratch) + case .prepared(let produce): + let work = TransactionScratch.work.name(index) + try scratch.makeDirectory(work, syncParent: false) + try emit(.stage(index, .workCreated)) + let root = scratch.url.appendingPathComponent(work) + let url = try produce(root) + guard PathSafety.isContained(url.resolvingSymlinksInPath(), in: root) else { + throw CoreError.unsafePath("prepared content escapes transaction staging") } + expectation = try FileTransaction.copyExpectation(url, hash: nil, flags: nil) + try emit(.stage(index, .workPrepared)) + try copy(url, named: name, index: index, scratch: scratch) } + return expectation } - private func verify(_ content: FileTransaction.Content, capture: FileSnapshot.Capture) throws { - if let kind = content.expectedKind, capture.snapshot?.identity.kind != kind { + private func copy(_ source: URL, named name: String, index: Int, scratch: DirectoryHandle) + throws + { + try Self.validateCopy(source) + let origin = source.resolvingSymlinksInPath() + try scratch.copy( + name, from: DirectoryHandle(at: origin.deletingLastPathComponent()), + named: origin.lastPathComponent, syncParent: false + ) { try emit(.copy(index, $0)) } + } + + private func verify( + _ source: FileTransaction.Source, _ expectation: FileTransaction.Expectation, + capture: FileSnapshot.Capture + ) throws { + let snapshot = capture.snapshot + if let kind = expectation.kind, snapshot?.identity.kind != kind { throw CoreError.invalidState("staged content type mismatch") } - if content.data != nil, capture.snapshot?.isRegular != true { + if case .data = source, snapshot?.isRegular != true { throw CoreError.invalidState("staged content type mismatch") } - if let mode = content.expectedMode, capture.snapshot?.mode != mode { + if let mode = expectation.mode, snapshot?.mode != mode { throw CoreError.invalidState("staged content permissions mismatch") } - if content.link { - let destination = content.linkDestination ?? content.url!.path - guard capture.snapshot?.isSymbolicLink == true, - capture.snapshot?.digest == FileHash.sha256Hex(data: Data(destination.utf8)) + var linked: URL? + switch source { + case .data(let data): + guard snapshot?.digest == FileHash.sha256Hex(data: data) else { + throw CoreError.invalidState("staged content bytes mismatch") + } + case .link(let url, let destination): + guard snapshot?.isSymbolicLink == true, + snapshot?.digest == FileHash.sha256Hex(data: Data(destination.utf8)) else { throw CoreError.invalidState("staged symbolic link destination mismatch") } + linked = url + case .copy, .prepared: break } - if let data = content.data, capture.snapshot?.digest != FileHash.sha256Hex(data: data) { - throw CoreError.invalidState("staged content bytes mismatch") - } - if let expected = content.expectedHash { - let actual = try content.link ? FileHash.folderHash(content.url!) : capture.contentHash + if let expected = expectation.hash { + let actual = try linked.map(FileHash.folderHash) ?? capture.contentHash guard "sha256:" + actual == expected else { throw CoreError.invalidState("staged content digest mismatch") } } - if let flags = content.executableFlags { - let actual = - try content.link ? FileHash.executableFlags(content.url!) : capture.executableFlags + if let flags = expectation.executableFlags { + let actual = try linked.map(FileHash.executableFlags) ?? capture.executableFlags guard actual == flags else { throw CoreError.invalidState("staged content executable mode mismatch") } @@ -422,6 +407,8 @@ final class TransactionSession { guard layout.kind == .prepared else { throw conflict(index, "operation is not prepared") } + // A stale preparation cancels from ready; rechecking after the intent narrows the race. + try requirePreimage(index) try advance(index, to: .publishing) try requirePreimage(index) try emit(.publication(index, .validated)) @@ -429,21 +416,21 @@ final class TransactionSession { if entry.action == .install { let exchange = entry.preimage != nil try scratch.move( - TransactionScratch.staged.name(index), to: parent, named: entry.name, + TransactionScratch.staging(for: entry).name(index), to: parent, named: entry.name, mode: exchange ? .exchange : .exclusive ) { try emit(.publication(index, exchange ? .exchanged : .created)) } } else if entry.preimage != nil { try parent.move( - entry.name, to: scratch, named: TransactionScratch.preimage.name(index), mode: .exclusive + entry.name, to: scratch, named: TransactionScratch.deleted.name(index), mode: .exclusive ) { try emit(.publication(index, .quarantined)) } } try emit(.publication(index, .synced)) try restoreDirectoryPermissions(index, purpose: .publicationRestore) - guard try distribution(index, permittingDirectoryWrite: false).kind == .installed else { + guard try distribution(index).kind == .installed else { throw conflict(index, "publication did not retain its preimage") } try advance(index, to: .applied) diff --git a/Sources/AgentsCore/SourceCache.swift b/Sources/AgentsCore/SourceCache.swift index 1d6571c..b93b60a 100644 --- a/Sources/AgentsCore/SourceCache.swift +++ b/Sources/AgentsCore/SourceCache.swift @@ -134,6 +134,7 @@ package struct SourceCache { } /// The marker precedes ref preparation or a state change that can release an existing pin. + /// An existing marker is synced again; only its creation is a checkpoint. func beginWatchReferenceUpdate() throws { guard let directory = try store.openDirectoryIfPresent(), try directory.info("cache") != nil, @@ -141,13 +142,13 @@ package struct SourceCache { else { return } if try directory.info("watch-refs.pending") == nil { try directory.write("watch-refs.pending", data: Data()) + try checkpoint("watch.references.pending") } else { guard try directory.read("watch-refs.pending").isEmpty else { throw CoreError.invalidState("invalid watch ref cleanup marker") } try directory.syncFile("watch-refs.pending") } - try checkpoint("watch.references.pending") } /// Run only after journal recovery or successful commit, while holding the scope lock. diff --git a/Sources/AgentsCore/TransactionCheckpoint.swift b/Sources/AgentsCore/TransactionCheckpoint.swift new file mode 100644 index 0000000..79e91be --- /dev/null +++ b/Sources/AgentsCore/TransactionCheckpoint.swift @@ -0,0 +1,84 @@ +import Foundation + +/// Names are unique within one transaction and never contain host path components. +enum TransactionCheckpoint { + enum Change { + case created, containers + case entry(Int, TransactionJournal.Progress) + case terminal, discard + case conflict(Int, TransactionJournal.Progress) + var name: String { + switch self { + case .created: "created" + case .containers: "containers" + case .entry(let index, let progress): "entry.\(index).\(progress.rawValue)" + case .terminal: "terminal" + case .discard: "discard" + case .conflict(let index, let progress): "entry.\(index).\(progress.rawValue).conflict" + } + } + } + enum Stage: String { case preimageSynced, workCreated, workPrepared, writeCreated, constructed } + enum Publication: String { case validated, exchanged, created, quarantined, synced } + enum Restoration: String { case validated, exchanged, returned, creationQuarantined, synced } + enum PersistenceStep: String { case written, renamed } + enum Permission: String { + case publicationGrant = "publish.grant" + case publicationRestore = "publish.restore" + case undoGrant = "undo.grant" + case undoRestore = "undo.restore" + case cancelRestore = "cancel.restore" + case conflictRestore = "conflict.restore" + } + case persisted(TransactionJournal.Phase, Change, PersistenceStep) + case phase(TransactionJournal.Phase) + case progress(Int, TransactionJournal.Progress) + /// Creation of a missing registered root or one of its ancestors. + case rootAncestry(String, DirectoryHandle.AncestryStep) + /// Creation of a missing destination parent at a level below its root. + case parentCreated(entry: Int, level: Int) + case containerCreated(Int) + case containersIdentified + case probe(Int, DirectoryHandle.ProbeStep) + case stage(Int, Stage) + case copy(Int, DirectoryHandle.CopyPoint) + case publication(Int, Publication) + case restoration(Int, Restoration) + case permissions(Int, Permission, TransactionObjectLocation, DirectoryHandle.PermissionStep) + case preconditions, commitValidated, journalSynced, discardIntent + /// The path is relative to the container; empty names the container itself. + case unlinked(container: Int, path: String) + /// The container's removal and its parent barrier are complete. + case containerRemoved(Int) + case journalUnlinked + case journalRemoved + + var name: String { + switch self { + case .persisted(let phase, let change, let step): + "journal.\(phase.rawValue).\(change.name).\(step.rawValue)" + case .phase(let phase): "journal.\(phase.rawValue)" + case .progress(let index, let progress): "entry.\(index).\(progress.rawValue)" + case .rootAncestry(let root, let step): "ancestry.\(root).\(step.name)" + case .parentCreated(let index, let level): "ancestry.entry.\(index).\(level).created" + case .containerCreated(let index): "container.\(index).created" + case .containersIdentified: "containers.identified" + case .probe(let index, let point): "atomic.\(index).\(point.rawValue)" + case .stage(let index, let point): "stage.\(index).\(point.rawValue)" + case .copy(let index, let point): "stage.\(index).copy.\(point.path).\(point.step.rawValue)" + case .publication(let index, let point): "publish.\(index).\(point.rawValue)" + case .restoration(let index, let point): "restore.\(index).\(point.rawValue)" + case .permissions(let index, let purpose, let location, let point): + "permissions.\(index).\(purpose.rawValue).\(location.name).\(point.rawValue)" + case .preconditions: "publication.preconditions" + case .commitValidated: "publication.commitValidated" + case .journalSynced: "journal.synced" + case .discardIntent: "cleanup.intent" + case .unlinked(let index, let path): + "cleanup.\(index).unlinked" + (path.isEmpty ? "" : "." + path) + case .containerRemoved(let index): "cleanup.\(index).removed" + case .journalUnlinked: "journal.unlinked" + case .journalRemoved: "journal.removed" + } + } +} diff --git a/Sources/AgentsCore/TransactionDisposal.swift b/Sources/AgentsCore/TransactionDisposal.swift new file mode 100644 index 0000000..3d7880d --- /dev/null +++ b/Sources/AgentsCore/TransactionDisposal.swift @@ -0,0 +1,147 @@ +import Foundation + +extension TransactionSession { + /// Verifies every expected distribution and seals disposal evidence for containers that + /// hold user data. A failure is recorded on the entry or container that caused it. + func prepareCleanup() throws { + let layouts = try journal.entries.indices.map { index in + do { return try distribution(index) } catch { + try recordConflict(index, error) + throw error + } + } + var userContainers: Set = [] + for (index, layout) in layouts.enumerated() + where [.installed, .reverted].contains(layout.kind) && !layout.objects.isEmpty { + userContainers.insert(journal.entries[index].container) + } + for index in journal.containers.indices { + do { + try sealDisposal(index, userData: userContainers.contains(index), layouts: layouts) + } catch { + try recordConflict(journal.containers[index].entry, error) + throw error + } + } + for index in journal.entries.indices { journal.entries[index].conflict = nil } + } + + private func sealDisposal(_ index: Int, userData: Bool, layouts: [TransactionLayout]) throws { + let record = journal.containers[index] + guard record.identity != nil else { return try validateContainerForDisposal(index) } + let handle = try container(index) + guard userData else { + journal.containers[index].cleanup = nil + return + } + let snapshot = try FileSnapshot.read(record.name, from: parents[record.entry]) + guard try handle.objectIdentity == snapshot?.identity else { + throw conflict(record.entry, "container changed while sealing disposal") + } + for entryIndex in journal.entries.indices where journal.entries[entryIndex].container == index { + for (slot, expected) in layouts[entryIndex].objects { + guard snapshot?.children?[slot.name(entryIndex)] == expected else { + throw conflict(entryIndex, "expected user object changed while sealing disposal") + } + } + } + journal.containers[index].cleanup = snapshot + } + + /// Recovery revalidates terminal evidence before disposal. + func cleanup() throws { + try requireScope() + for index in journal.entries.indices { + do { + if journal.discarding { + try verifyTarget(index) + } else { + _ = try distribution(index) + } + } catch { + try recordConflict(index, error) + throw error + } + } + for index in journal.containers.indices { + do { try validateContainerForDisposal(index) } catch { + try recordConflict(journal.containers[index].entry, error) + throw error + } + } + try dispose() + } + + /// Commit disposes directly: `prepareCleanup` verified the distribution and sealed this + /// evidence immediately before the terminal marker. Deletion still verifies every object. + func dispose() throws { + try requireScope() + if !journal.discarding { + journal.discarding = true + try persist(.discard) + try emit(.discardIntent) + } + for index in journal.containers.indices { try discardContainer(index) } + try requireScope() + try directory.removeJournal { try emit(.journalUnlinked) } + try emit(.journalRemoved) + } + + func verifyTarget(_ index: Int) throws { + let entry = journal.entries[index] + try requireParent(index) + // Terminal phases have a single distribution; disposal may have removed its scratch slots. + guard try TransactionLayout.expected(entry)[0].target.matches(entry.name, from: parents[index]) + else { + throw conflict( + index, + journal.phase == .committed + ? "committed destination changed" : "restored destination changed") + } + } + + /// The only disposal check of a container: its identity and sealed evidence, or, without + /// a durable identity, that it is absent or empty. + func validateContainerForDisposal(_ index: Int) throws { + let record = journal.containers[index] + let parent = parents[record.entry] + try requireParent(record.entry) + guard let actual = try parent.info(record.name) else { + if journal.discarding || record.identity == nil { return } + throw conflict(record.entry, "private container disappeared before discard intent") + } + guard let identity = record.identity else { + guard try parent.child(record.name).names().isEmpty else { + throw conflict(record.entry, "unidentified private container is not empty") + } + return + } + guard FileObjectIdentity(actual) == identity else { + throw conflict(record.entry, "private container identity changed") + } + if let expected = record.cleanup { + let current = try FileSnapshot.read(record.name, from: parent) + let matches = + journal.discarding + ? current.map(expected.containsRemaining) == true : current == expected + guard matches else { throw conflict(record.entry, "terminal disposal evidence changed") } + } + } + + private func discardContainer(_ index: Int) throws { + let record = journal.containers[index] + let parent = parents[record.entry] + try requireScope() + try requireParent(record.entry) + if let identity = record.identity { + try parent.remove(record.name, expecting: record.cleanup, identity: identity) { point in + try emit( + point.step == .synced + ? .containerRemoved(index) : .unlinked(container: index, path: point.path)) + } + } else { + try parent.removeEmptyDirectory(record.name) + try emit(.containerRemoved(index)) + } + } +} diff --git a/Sources/AgentsCore/TransactionEvidence.swift b/Sources/AgentsCore/TransactionEvidence.swift index 417f0c9..de24c6b 100644 --- a/Sources/AgentsCore/TransactionEvidence.swift +++ b/Sources/AgentsCore/TransactionEvidence.swift @@ -1,4 +1,3 @@ -import CPlatform import Foundation struct FileObjectIdentity: Codable, Equatable, Sendable { @@ -15,6 +14,23 @@ struct FileObjectIdentity: Codable, Equatable, Sendable { } } +/// A recorded directory inode whose final mode lacks owner-write. While `publishing` or +/// `restoring` intent is durable it admits the original mode or that mode plus owner-write. +struct DirectoryWriteLease: Equatable { + let identity: FileObjectIdentity + let original: mode_t + + init?(_ snapshot: FileSnapshot) { + guard snapshot.identity.isDirectory, snapshot.mode & 0o200 == 0 else { return nil } + identity = snapshot.identity + original = snapshot.mode + } + + var grantedMode: mode_t { original | 0o200 } + + func admits(_ mode: mode_t) -> Bool { mode == original || mode == grantedMode } +} + /// Content and physical ownership are separate evidence. Descendant identities let /// terminal cleanup resume after partial deletion without adopting new entries. struct FileSnapshot: Codable, Equatable, Sendable { @@ -94,17 +110,12 @@ struct FileSnapshot: Codable, Equatable, Sendable { _ name: String, from parent: DirectoryHandle, relative: String, collect: ((String, mode_t, Data, Bool) -> Void)? ) throws -> FileSnapshot? { - guard var before = try parent.info(name) else { return nil } + guard let before = try parent.info(name) else { return nil } let children: [String: FileSnapshot]? let payload: Data switch before.st_mode & S_IFMT { case S_IFDIR: - let directory = try parent.child(name) - var opened = stat() - guard fstat(directory.descriptor, &opened) == 0, platform_same_generation(&before, &opened) - else { - throw CoreError.invalidState("directory changed before reading: \(name)") - } + let directory = try parent.child(name, matching: before) var entries: [String: FileSnapshot] = [:] for child in try directory.names() { guard @@ -128,7 +139,7 @@ struct FileSnapshot: Codable, Equatable, Sendable { payload = try parent.readLinkData(name) default: throw CoreError.unsafePath("unsupported transaction entry: \(name)") } - guard var after = try parent.info(name), platform_same_generation(&before, &after) else { + guard let after = try parent.info(name), DirectoryHandle.sameGeneration(before, after) else { throw CoreError.invalidState("entry changed while reading: \(name)") } collect?(relative, before.st_mode & S_IFMT, payload, before.st_mode & 0o111 != 0) @@ -139,15 +150,15 @@ struct FileSnapshot: Codable, Equatable, Sendable { children: children) } - var needsDirectoryWriteLease: Bool { identity.isDirectory && mode & 0o200 == 0 } + var writeLease: DirectoryWriteLease? { DirectoryWriteLease(self) } func matches(_ current: Self, permittingDirectoryWrite: Bool) -> Bool { if self == current { return true } - guard permittingDirectoryWrite, needsDirectoryWriteLease, current.mode == mode | 0o200 else { + guard permittingDirectoryWrite, let lease = writeLease, lease.admits(current.mode) else { return false } return Self( - identity: identity, digest: digest, executable: executable, mode: mode | 0o200, + identity: identity, digest: digest, executable: executable, mode: current.mode, children: children) == current } @@ -173,25 +184,4 @@ struct FileSnapshot: Codable, Equatable, Sendable { guard let children, let remaining = current.children else { return self == current } return remaining.allSatisfy { name, value in children[name]?.containsRemaining(value) == true } } - - func synchronize(_ name: String, from parent: DirectoryHandle) throws { - guard try Self.read(name, from: parent) == self else { - throw CoreError.invalidState("transaction preimage changed before synchronization: \(name)") - } - try syncContents(name, from: parent) - try parent.sync() - } - - private func syncContents(_ name: String, from parent: DirectoryHandle) throws { - if let children { - let directory = try parent.child(name) - for child in children.keys.sorted() { - try children[child]!.syncContents(child, from: directory) - } - try directory.sync() - } else if identity.kind == S_IFREG { - try parent.syncFile(name, includingParent: false) - } - } - } diff --git a/Sources/AgentsCore/TransactionJournal.swift b/Sources/AgentsCore/TransactionJournal.swift index 6b1f1cb..04294f1 100644 --- a/Sources/AgentsCore/TransactionJournal.swift +++ b/Sources/AgentsCore/TransactionJournal.swift @@ -18,7 +18,7 @@ struct TransactionJournal: Codable { enum Progress: String, Codable { /// Preimage and container name are durable; construction has no per-object ownership claims. case queued - /// Construction is verified; staged is sealed and other recovery slots are absent. + /// Construction is verified; staging is sealed and other recovery slots are absent. case ready /// Publication and temporary directory-write intent are durable, with original modes. case publishing @@ -65,17 +65,39 @@ struct TransactionJournal: Codable { var cleanup: FileSnapshot? } + static func containerName(id: UUID, index: Int) -> String { ".agents-\(id.uuidString)-\(index)" } + func containerName(_ index: Int) -> String { containers[index].name } + + /// Without an identified container or sealed operation, the journal owns no object. + var isUnstarted: Bool { + phase == .preparing && containers.allSatisfy { $0.identity == nil } + && entries.allSatisfy { $0.progress == .queued } + } } -enum TransactionScratch: String, CaseIterable { - case staged, preimage, removed, work - case probeA = "probe-a" - case probeB = "probe-b" - case probeC = "probe-c" - var name: String { rawValue } +/// Container entry names. Each recovery slot holds either private staging or user data. +enum TransactionScratch: String { + /// Private sealed staging for a creation; publication moves it out of the container. + case staged + /// Private sealed staging for an exchange until publication; afterwards the displaced user + /// preimage, and after undo the withdrawn published object. + case exchanged + /// The user object moved aside by a deletion. + case deleted + /// The published creation moved aside by undo; it is user data. + case withdrawn + /// Private extraction work for prepared content. + case work + func name(_ index: Int) -> String { "entry.\(index).\(rawValue)" } - static let objectSlots: [Self] = [.staged, .preimage, .removed] + static let objectSlots: [Self] = [.staged, .exchanged, .deleted, .withdrawn] + static let probes = (first: "probe-a", second: "probe-b", moved: "probe-c") + + /// The slot that holds an install's sealed staging. + static func staging(for entry: TransactionJournal.Entry) -> Self { + entry.preimage == nil ? .staged : .exchanged + } } /// The operation/progress table is the single authority for physical object distribution. @@ -110,26 +132,26 @@ struct TransactionLayout { let objects: [TransactionScratch: FileSnapshot] static func expected(_ entry: TransactionJournal.Entry) -> [Self] { - if entry.progress == .queued { return [Self(kind: .construction, target: .any, objects: [:])] } - let prepared = Self( - kind: .prepared, target: .any, - objects: entry.staged.map { [.staged: $0] } ?? [:]) + let prepared: Self let installed: Self let reverted: Self - switch (entry.action, entry.preimage) { - case (.install, .some(let original)): - installed = Self( - kind: .installed, target: .object(entry.staged!), objects: [.staged: original]) - reverted = Self(kind: .reverted, target: .object(original), objects: [.staged: entry.staged!]) - case (.install, .none): - installed = Self(kind: .installed, target: .object(entry.staged!), objects: [:]) + // Validated records carry staged evidence exactly for installs past construction. + switch (entry.preimage, entry.staged) { + case (let original?, let staged?): + prepared = Self(kind: .prepared, target: .any, objects: [.exchanged: staged]) + installed = Self(kind: .installed, target: .object(staged), objects: [.exchanged: original]) + reverted = Self(kind: .reverted, target: .object(original), objects: [.exchanged: staged]) + case (nil, let staged?): + prepared = Self(kind: .prepared, target: .any, objects: [.staged: staged]) + installed = Self(kind: .installed, target: .object(staged), objects: [:]) reverted = Self( - kind: .reverted, target: .externalTo(entry.staged!.identity), - objects: [.removed: entry.staged!]) - case (.delete, .some(let original)): - installed = Self(kind: .installed, target: .absent, objects: [.preimage: original]) + kind: .reverted, target: .externalTo(staged.identity), objects: [.withdrawn: staged]) + case (let original?, nil): + prepared = Self(kind: .prepared, target: .any, objects: [:]) + installed = Self(kind: .installed, target: .absent, objects: [.deleted: original]) reverted = Self(kind: .reverted, target: .object(original), objects: [:]) - case (.delete, .none): + case (nil, nil): + prepared = Self(kind: .prepared, target: .any, objects: [:]) installed = Self(kind: .installed, target: .absent, objects: [:]) reverted = Self(kind: .reverted, target: .any, objects: [:]) } @@ -146,93 +168,21 @@ struct TransactionLayout { case .restored: return [reverted] } } -} -enum TransactionCheckpoint { - enum Change { - case created, containers - case entry(Int, TransactionJournal.Progress) - case terminal, discard - case conflict(Int, TransactionJournal.Progress) - var name: String { - switch self { - case .created: "created" - case .containers: "containers" - case .entry(let index, let progress): "entry.\(index).\(progress.rawValue)" - case .terminal: "terminal" - case .discard: "discard" - case .conflict(let index, let progress): "entry.\(index).\(progress.rawValue).conflict" - } - } - } - enum Stage: String { case preimageSynced, workCreated, workPrepared, writeCreated, constructed } - enum Publication: String { case validated, exchanged, created, quarantined, synced } - enum Restoration: String { case validated, exchanged, returned, creationQuarantined, synced } - enum PersistenceStep: String { case written, renamed } - case persisted(TransactionJournal.Phase, Change, PersistenceStep) - case phase(TransactionJournal.Phase) - case progress(Int, TransactionJournal.Progress) - case containerCreated(Int) - case containersIdentified - case probe(Int, DirectoryHandle.ProbeStep) - case stage(Int, Stage) - case copy(Int, DirectoryHandle.CopyPoint) - case publication(Int, Publication) - case restoration(Int, Restoration) - case permissions( - Int, TransactionPermissionPurpose, TransactionObjectLocation, DirectoryHandle.PermissionStep) - case preconditions, commitValidated, terminalSynced, discardIntent - case disposal(Int, DirectoryHandle.RemovalPoint) - case containerRemoved(Int) - case journalUnlinked - case journalRemoved - - var name: String { - switch self { - case .persisted(let phase, let change, let step): - "journal.\(phase.rawValue).\(change.name).\(step.rawValue)" - case .phase(let phase): "journal.\(phase.rawValue)" - case .progress(let index, let progress): "entry.\(index).\(progress.rawValue)" - case .containerCreated(let index): "container.\(index).created" - case .containersIdentified: "containers.identified" - case .probe(let index, let point): "atomic.\(index).\(point.rawValue)" - case .stage(let index, let point): "stage.\(index).\(point.rawValue)" - case .copy(let index, let point): "stage.\(index).copy.\(point.path).\(point.step.rawValue)" - case .publication(let index, let point): "publish.\(index).\(point.rawValue)" - case .restoration(let index, let point): "restore.\(index).\(point.rawValue)" - case .permissions(let index, let purpose, let location, let point): - "permissions.\(index).\(purpose.rawValue).\(location.name).\(point.rawValue)" - case .preconditions: "publication.preconditions" - case .commitValidated: "publication.commitValidated" - case .terminalSynced: "journal.terminalSynced" - case .discardIntent: "cleanup.intent" - case .disposal(let index, let point): - "cleanup.\(index)." - + (["container"] + point.path.split(separator: "/").dropFirst().map(String.init)).joined( - separator: "/") + ".\(point.step.rawValue)" - case .containerRemoved(let index): "cleanup.\(index).removed" - case .journalUnlinked: "journal.unlinked" - case .journalRemoved: "journal.removed" + /// Recorded objects and their locations in this distribution. A prepared operation still + /// has its preimage at the target, which the table does not constrain before publication. + func objectLocations( + _ entry: TransactionJournal.Entry + ) -> [(location: TransactionObjectLocation, object: FileSnapshot)] { + var locations: [(location: TransactionObjectLocation, object: FileSnapshot)] = [] + if case .object(let expected) = target { + locations.append((.target, expected)) + } else if kind == .prepared, let original = entry.preimage { + locations.append((.target, original)) } - } -} - -extension TransactionSession { - /// Transitions and their durable evidence promises are changed together. - func advance(_ index: Int, to next: TransactionJournal.Progress) throws { - let previous = journal.entries[index].progress - let legal: [TransactionJournal.Progress: Set] = [ - .queued: [.ready], .ready: [.publishing, .cancelled], - .publishing: [.applied, .restoring, .cancelled], .applied: [.restoring], - .restoring: [.restored], .restored: [], .cancelled: [], - ] - guard legal[previous]?.contains(next) == true else { - throw conflict(index, "illegal progress transition: \(previous) -> \(next)") + for slot in TransactionScratch.objectSlots { + if let expected = objects[slot] { locations.append((.scratch(slot), expected)) } } - if next == .publishing { journal.phase = .applying } - journal.entries[index].progress = next - journal.entries[index].conflict = nil - try persist(.entry(index, next)) - try emit(.progress(index, next)) + return locations } } diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index 03b5522..f398640 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -50,9 +50,10 @@ struct TransactionPaths { throw CoreError.unsafePath("transaction destination is outside managed paths") } - func root(_ key: String, create: Bool = false, checkpoint: (String) throws -> Void = { _ in }) - throws -> DirectoryHandle - { + func root( + _ key: String, create: Bool = false, + checkpoint: (DirectoryHandle.AncestryStep) throws -> Void = { _ in } + ) throws -> DirectoryHandle { try DirectoryHandle(at: rootURL(key), create: create, checkpoint: checkpoint) } @@ -135,19 +136,22 @@ struct TransactionPaths { return (key, descendants) } + /// With `create`, each descendant's parent is synced; the checkpoint reports the level + /// below the root of each descendant this call creates. func parent( for path: String, roots: [String: DirectoryHandle], create: Bool = false, - checkpoint: (String) throws -> Void = { _ in } + checkpoint: (Int) throws -> Void = { _ in } ) throws -> DirectoryHandle { let components = try components(path) guard var directory = roots[components.root] else { throw CoreError.invalidState("missing transaction root") } - for name in components.descendants.dropLast() { + for (index, name) in components.descendants.dropLast().enumerated() { if create { - if try directory.info(name) == nil { try directory.makeDirectory(name) } + let created = try directory.info(name) == nil + if created { try directory.makeDirectory(name) } try directory.sync() - try checkpoint("directory.synced.\(name)") + if created { try checkpoint(index + 1) } } directory = try directory.child(name) } diff --git a/Sources/AgentsCore/TransactionPermissions.swift b/Sources/AgentsCore/TransactionPermissions.swift index 26c4e61..4bff3ec 100644 --- a/Sources/AgentsCore/TransactionPermissions.swift +++ b/Sources/AgentsCore/TransactionPermissions.swift @@ -1,6 +1,6 @@ import Foundation -enum TransactionObjectLocation { +enum TransactionObjectLocation: Equatable { case target case scratch(TransactionScratch) @@ -12,80 +12,67 @@ enum TransactionObjectLocation { } } -enum TransactionPermissionPurpose: String { - case publicationGrant = "publish.grant" - case publicationRestore = "publish.restore" - case undoGrant = "undo.grant" - case undoRestore = "undo.restore" - case cancelRestore = "cancel.restore" - case conflictRestore = "conflict.restore" -} - extension TransactionSession { /// Publishing/restoring intent binds a temporary owner-write bit to the recorded /// directory inode. It never grants access through an external replacement. func grantDirectoryPermissions( - _ index: Int, layout: TransactionLayout, purpose: TransactionPermissionPurpose + _ index: Int, layout: TransactionLayout, purpose: TransactionCheckpoint.Permission ) throws { - let entry = journal.entries[index] - var objects: [(TransactionObjectLocation, FileSnapshot)] = [] - if case .object(let expected) = layout.target { - objects.append((.target, expected)) - } else if layout.kind == .prepared, let original = entry.preimage { - objects.append((.target, original)) - } - for slot in TransactionScratch.objectSlots { - if let expected = layout.objects[slot] { objects.append((.scratch(slot), expected)) } - } - for (location, expected) in objects where expected.needsDirectoryWriteLease { + for (location, object) in layout.objectLocations(journal.entries[index]) { + guard let lease = object.writeLease else { continue } try setDirectoryPermissions( - index, location: location, expected: expected, mode: expected.mode | 0o200, purpose: purpose - ) + index, location: location, lease: lease, granting: true, purpose: purpose) } } /// Mode restoration uses physical identity independently of byte rollback. A /// changed payload is retained, while a known temporary permission can be undone. /// Missing inodes or modes outside the recorded pair require owner action. - func restoreDirectoryPermissions(_ index: Int, purpose: TransactionPermissionPurpose) throws { - try forEachDirectoryPermission(index) { location, expected in + func restoreDirectoryPermissions(_ index: Int, purpose: TransactionCheckpoint.Permission) + throws + { + try forEachDirectoryLease(index) { location, lease in try setDirectoryPermissions( - index, location: location, expected: expected, mode: expected.mode, purpose: purpose) + index, location: location, lease: lease, granting: false, purpose: purpose) } } func inspectDirectoryPermissions(_ index: Int) throws { guard journal.entries[index].progress.permitsDirectoryWrite else { return } - try forEachDirectoryPermission(index) { location, expected in + try forEachDirectoryLease(index) { location, lease in let (parent, name) = try permissionLocation(index, location) - _ = try parent.child(name).checkedPermissions( - expecting: expected.identity, from: expected.mode) + _ = try parent.child(name).checkedPermissions(lease) } } - private func forEachDirectoryPermission( - _ index: Int, body: (TransactionObjectLocation, FileSnapshot) throws -> Void + /// Candidate locations are those of the progress's expected distributions. Each leased + /// inode is acted on where it is found; one found in no candidate location is a conflict. + private func forEachDirectoryLease( + _ index: Int, body: (TransactionObjectLocation, DirectoryWriteLease) throws -> Void ) throws { let entry = journal.entries[index] - let expected = [entry.preimage, entry.staged].compactMap { $0 } - .filter(\.needsDirectoryWriteLease) - guard !expected.isEmpty else { return } + var candidates: [(location: TransactionObjectLocation, lease: DirectoryWriteLease)] = [] + for layout in TransactionLayout.expected(entry) { + for (location, object) in layout.objectLocations(entry) { + guard let lease = object.writeLease, + !candidates.contains(where: { $0.location == location && $0.lease == lease }) + else { continue } + candidates.append((location, lease)) + } + } var found: [FileObjectIdentity] = [] var errors: [String] = [] - let locations: [TransactionObjectLocation] = - [.target] - + TransactionScratch.objectSlots.map { .scratch($0) } - for location in locations { + for (location, lease) in candidates { do { let (parent, name) = try permissionLocation(index, location) - guard let identity = try parent.info(name).map(FileObjectIdentity.init), - let object = expected.first(where: { $0.identity == identity }) - else { continue } - found.append(identity) - try body(location, object) + guard try parent.info(name).map(FileObjectIdentity.init) == lease.identity else { + continue + } + found.append(lease.identity) + try body(location, lease) } catch { errors.append(String(describing: error)) } } - if expected.contains(where: { !found.contains($0.identity) }) { + if candidates.contains(where: { !found.contains($0.lease.identity) }) { errors.append("directory mode restoration is missing its recorded inode") } guard errors.isEmpty else { throw conflict(index, errors.joined(separator: "; ")) } @@ -103,15 +90,14 @@ extension TransactionSession { } private func setDirectoryPermissions( - _ index: Int, location: TransactionObjectLocation, expected: FileSnapshot, mode: mode_t, - purpose: TransactionPermissionPurpose + _ index: Int, location: TransactionObjectLocation, lease: DirectoryWriteLease, + granting: Bool, purpose: TransactionCheckpoint.Permission ) throws { guard journal.entries[index].progress.permitsDirectoryWrite else { throw conflict(index, "directory permission change requires durable intent") } let (parent, name) = try permissionLocation(index, location) - let directory = try parent.child(name) - try directory.setPermissions(mode, expecting: expected.identity, from: expected.mode) { + try parent.child(name).setPermissions(lease, granting: granting) { try emit(.permissions(index, purpose, location, $0)) } } diff --git a/Sources/AgentsCore/TransactionRecovery.swift b/Sources/AgentsCore/TransactionRecovery.swift index 1a6a7ae..3a03060 100644 --- a/Sources/AgentsCore/TransactionRecovery.swift +++ b/Sources/AgentsCore/TransactionRecovery.swift @@ -3,6 +3,9 @@ import Foundation package struct TransactionRecoveryDiagnostic { package let requiresOwner: Bool package let message: String + + static let pendingMessage = + "Transaction recovery is pending; the next command that changes this scope will recover it." } extension FileTransaction { @@ -13,16 +16,7 @@ extension FileTransaction { guard let directory = try store.openDirectoryIfPresent() else { return false } guard try directory.info("transaction.json") != nil else { guard try directory.info("transaction.new") != nil else { return false } - let bytes = try directory.read("transaction.new") - if (try? JSONSerialization.jsonObject(with: bytes)) != nil { - let journal = try readJournal(bytes) - guard journal.phase == .preparing, journal.containers.allSatisfy({ $0.identity == nil }), - journal.entries.allSatisfy({ $0.progress == .queued }) - else { - throw CoreError.invalidState( - "missing primary journal; retained transaction.new needs owner action") - } - } + try requireUnstartedIncompleteJournal(in: directory) try directory.remove("transaction.new") return true } @@ -34,15 +28,17 @@ extension FileTransaction { journal, store: store, directory: directory, checkpoint: checkpoint) // Validate the journal's scratch file before any recovery mutation. if try directory.info("transaction.new") != nil { _ = try directory.read("transaction.new") } - let observedTerminal = journal.phase == .committed || journal.phase == .rolledBack + // Any observed journal may have been renamed without its directory barrier. Persist it + // before granting permissions, renaming objects or deleting any resource, including on retry. + try directory.syncFile("transaction.json") + try session.emit(.journalSynced) if journal.phase == .applying { try session.rollback() } if session.journal.phase == .applying || session.journal.phase == .preparing { try session.prepareCleanup() - session.journal.phase = .rolledBack - try session.persist(.terminal) + try session.finish(.rolledBack) try session.emit(.phase(.rolledBack)) } - try session.cleanup(observedTerminal: observedTerminal) + try session.cleanup() if outcome?.journalID == journal.id { outcome?.disposition = session.journal.phase == .committed ? .committed : .unchanged } @@ -60,39 +56,21 @@ extension FileTransaction { var retained = [store.directory.appendingPathComponent("transaction.json").path] do { guard let directory = try store.openDirectoryIfPresent() else { - return .init( - requiresOwner: false, - message: - "Transaction recovery is pending; the next command that changes this scope will recover it." - ) + return .init(requiresOwner: false, message: TransactionRecoveryDiagnostic.pendingMessage) } if try directory.info("transaction.json") == nil { if try directory.info("transaction.new") != nil { - let bytes = try directory.read("transaction.new") - if (try? JSONSerialization.jsonObject(with: bytes)) != nil { - let incomplete = try readJournal(bytes) - guard incomplete.phase == .preparing, - incomplete.containers.allSatisfy({ $0.identity == nil }), - incomplete.entries.allSatisfy({ $0.progress == .queued }) - else { - throw CoreError.invalidState( - "missing primary journal; retained transaction.new needs owner action") - } - } + try requireUnstartedIncompleteJournal(in: directory) } - return .init( - requiresOwner: false, - message: - "Transaction recovery is pending; the next command that changes this scope will recover it." - ) + return .init(requiresOwner: false, message: TransactionRecoveryDiagnostic.pendingMessage) } let journal = try readJournal(directory.read("transaction.json")) retained += journal.entries.compactMap { entry in guard journal.containers.indices.contains(entry.container) else { return nil } let container = journal.containers[entry.container] - guard container.name == ".agents-\(journal.id.uuidString)-\(entry.container)" else { - return nil - } + guard + container.name == TransactionJournal.containerName(id: journal.id, index: entry.container) + else { return nil } return entry.path.split(separator: "/").dropLast().joined(separator: "/") + "/" + container.name } @@ -110,11 +88,7 @@ extension FileTransaction { + "; journal: " + directory.url.appendingPathComponent("transaction.json").path) } try session.inspectRecoveryObjects() - return .init( - requiresOwner: false, - message: - "Transaction recovery is pending; the next command that changes this scope will recover it." - ) + return .init(requiresOwner: false, message: TransactionRecoveryDiagnostic.pendingMessage) } catch { return .init( requiresOwner: true, @@ -124,6 +98,16 @@ extension FileTransaction { } } + /// A lone `transaction.new` may be discarded only while it is unparseable or unstarted. + private static func requireUnstartedIncompleteJournal(in directory: DirectoryHandle) throws { + let bytes = try directory.read("transaction.new") + guard (try? JSONSerialization.jsonObject(with: bytes)) != nil else { return } + guard try readJournal(bytes).isUnstarted else { + throw CoreError.invalidState( + "missing primary journal; retained transaction.new needs owner action") + } + } + private static func readJournal(_ bytes: Data) throws -> TransactionJournal { try JSONKeys.validate(bytes) let value = try JSONSerialization.jsonObject(with: bytes) as? [String: Any] @@ -159,155 +143,17 @@ extension FileTransaction { } extension TransactionSession { - func requireScope() throws { - guard try DirectoryHandle(at: directory.url).identity == journal.scope else { - throw CoreError.invalidState("transaction scope identity changed") - } - } - - func requireParent(_ index: Int) throws { - guard - try DirectoryHandle(at: parents[index].url).identity == journal.entries[index].parentIdentity - else { - throw conflict(index, "destination parent changed") - } - } - - func conflict(_ index: Int, _ reason: String) -> CoreError { - .invalidState( - "transaction conflict at \(journal.entries[index].path): \(reason); retained container: \(containerLocation(index))" - ) - } - - func containerLocation(_ index: Int) -> String { - let entry = journal.entries[index] - guard journal.containers.indices.contains(entry.container) else { - return "" - } - return entry.path.split(separator: "/").dropLast().joined(separator: "/") + "/" - + journal.containerName(entry.container) - } - - func recordConflict(_ index: Int, _ error: Error) throws { - journal.entries[index].conflict = .init( - reason: String(describing: error), - locations: [journal.entries[index].path, containerLocation(index)]) - try persist(.conflict(index, journal.entries[index].progress)) - } - - func validateRecords(store: StateStore) throws { - try requireScope() - let paths = TransactionPaths(store: store) - let keys = try Set(journal.entries.map { try paths.components($0.path).root }) - guard keys == Set(journal.roots.keys), !journal.entries.isEmpty else { - throw CoreError.invalidState("invalid transaction roots") - } - var targets: [URL] = [] - for (index, entry) in journal.entries.enumerated() { - try requireParent(index) - let target = parents[index].url.appendingPathComponent(entry.name) - guard - !targets.contains(where: { - PathSafety.isContained(target, in: $0) || PathSafety.isContained($0, in: target) - }), - journal.containers.indices.contains(entry.container) - else { - throw conflict(index, "overlapping destinations or invalid container") - } - targets.append(target) - try validateProgress(index) - try entry.preimage?.validate() - try entry.staged?.validate() - } - for index in journal.containers.indices { try validateContainerRecord(index) } - for (index, entry) in journal.entries.enumerated() { - if let conflict = entry.conflict, - conflict.locations != [entry.path, containerLocation(index)] - { - throw CoreError.invalidState("invalid transaction conflict locations") - } - } - } - - private func validateContainerRecord(_ index: Int) throws { - let record = journal.containers[index] - guard journal.entries.indices.contains(record.entry), - journal.entries[record.entry].container == index, - record.name == ".agents-\(journal.id.uuidString)-\(index)", - record.identity?.isDirectory != false - else { - throw CoreError.invalidState("invalid private transaction container evidence") - } - for entry in journal.entries where entry.container == index { - guard entry.parentIdentity == journal.entries[record.entry].parentIdentity else { - throw CoreError.invalidState("private container belongs to another parent") - } - guard entry.progress == .queued || record.identity != nil else { - throw CoreError.invalidState("sealed operation is missing private container identity") - } - } - try record.cleanup?.validate() - if let cleanup = record.cleanup { - guard cleanup.identity == record.identity else { - throw CoreError.invalidState("terminal container evidence has another identity") - } - } - if journal.phase == .committed || journal.phase == .rolledBack { - let containsUserData = journal.entries.filter { $0.container == index }.contains { entry in - [.applied, .restored].contains(entry.progress) - && TransactionLayout.expected(entry).contains { !$0.objects.isEmpty } - } - guard !containsUserData || record.cleanup != nil else { - throw CoreError.invalidState("terminal container is missing user-object disposal evidence") - } - } - } - - private func validateProgress(_ index: Int) throws { - let entry = journal.entries[index] - let allowed: Set - switch journal.phase { - case .preparing: allowed = [.queued, .ready] - case .applying: allowed = [.ready, .publishing, .applied, .restoring, .restored, .cancelled] - case .committed: allowed = [.applied] - case .rolledBack: allowed = [.queued, .ready, .restored, .cancelled] - } - let requiresStaging = entry.action == .install && entry.progress != .queued - guard allowed.contains(entry.progress), - (entry.staged != nil) == requiresStaging, - !journal.discarding || journal.phase == .committed || journal.phase == .rolledBack - else { - throw conflict(index, "operation progress contradicts its evidence or journal phase") - } - } - - func distribution(_ index: Int, permittingDirectoryWrite: Bool = true) throws -> TransactionLayout - { - let entry = journal.entries[index] - try requireParent(index) - if entry.progress == .queued { return TransactionLayout.expected(entry)[0] } - let scratch = try container(entry.container) - let layouts = TransactionLayout.expected(entry) - var objects: [TransactionScratch: FileSnapshot] = [:] - for slot in TransactionScratch.objectSlots { - if let value = try FileSnapshot.read(slot.name(index), from: scratch) { - objects[slot] = value - } - } - let permitsWrite = permittingDirectoryWrite && entry.progress.permitsDirectoryWrite - for layout in layouts where Set(layout.objects.keys) == Set(objects.keys) { - guard - layout.objects.allSatisfy({ slot, expected in - expected.matches(objects[slot]!, permittingDirectoryWrite: permitsWrite) - }) - else { continue } - if try layout.target.matches( - entry.name, from: parents[index], permittingDirectoryWrite: permitsWrite) - { - return layout + /// Read-only diagnosis of the distribution recovery would act on. + func inspectRecoveryObjects() throws { + for index in journal.entries.indices { + if journal.discarding { + try verifyTarget(index) + } else { + _ = try distribution(index, permittingDirectoryWrite: true) + try inspectDirectoryPermissions(index) } } - throw conflict(index, "missing or changed expected target, preimage or rollback quarantine") + for index in journal.containers.indices { try validateContainerForDisposal(index) } } func rollback() throws { @@ -332,7 +178,7 @@ extension TransactionSession { } private func rollbackEntry(_ index: Int) throws { - let layout = try distribution(index) + let layout = try distribution(index, permittingDirectoryWrite: true) let progress = journal.entries[index].progress if progress == .ready { try advance(index, to: .cancelled) @@ -341,7 +187,7 @@ extension TransactionSession { if progress == .cancelled || progress == .restored { return } if layout.kind == .prepared { try restoreDirectoryPermissions(index, purpose: .cancelRestore) - _ = try distribution(index, permittingDirectoryWrite: false) + _ = try distribution(index) try advance(index, to: .cancelled) return } @@ -356,7 +202,7 @@ extension TransactionSession { } try restoreDirectoryPermissions(index, purpose: .undoRestore) try emit(.restoration(index, .synced)) - guard try distribution(index, permittingDirectoryWrite: false).kind == .reverted else { + guard try distribution(index).kind == .reverted else { throw conflict(index, "undo did not restore the expected objects") } try advance(index, to: .restored) @@ -370,182 +216,24 @@ extension TransactionSession { if entry.preimage != nil { if entry.action == .install { try scratch.move( - TransactionScratch.staged.name(index), to: parent, named: entry.name, mode: .exchange + TransactionScratch.exchanged.name(index), to: parent, named: entry.name, + mode: .exchange ) { try emit(.restoration(index, .exchanged)) } } else { try scratch.move( - TransactionScratch.preimage.name(index), to: parent, named: entry.name, mode: .exclusive + TransactionScratch.deleted.name(index), to: parent, named: entry.name, mode: .exclusive ) { try emit(.restoration(index, .returned)) } } } else if entry.action == .install { try parent.move( - entry.name, to: scratch, named: TransactionScratch.removed.name(index), mode: .exclusive + entry.name, to: scratch, named: TransactionScratch.withdrawn.name(index), mode: .exclusive ) { try emit(.restoration(index, .creationQuarantined)) } } } - - func prepareCleanup() throws { - var userContainers: Set = [] - var layouts: [Int: TransactionLayout] = [:] - for index in journal.entries.indices { - do { - let layout = try distribution(index) - layouts[index] = layout - if [.installed, .reverted].contains(layout.kind), !layout.objects.isEmpty { - userContainers.insert(journal.entries[index].container) - } - } catch { - try recordConflict(index, error) - throw error - } - } - for index in journal.containers.indices { - do { - try prepareContainerCleanup( - index, userData: userContainers.contains(index), layouts: layouts) - } catch { - try recordConflict(journal.containers[index].entry, error) - throw error - } - } - for index in journal.entries.indices { journal.entries[index].conflict = nil } - } - - private func prepareContainerCleanup( - _ index: Int, userData: Bool, layouts: [Int: TransactionLayout] - ) throws { - let record = journal.containers[index] - let parent = parents[record.entry] - if record.identity == nil { - if try parent.info(record.name) != nil, try !parent.child(record.name).names().isEmpty { - throw conflict(record.entry, "unidentified private container is not empty") - } - return - } - let handle = try container(index) - guard userData else { return } - let snapshot = try FileSnapshot.read(record.name, from: parent) - guard try handle.objectIdentity == snapshot?.identity else { - throw conflict(record.entry, "container changed while sealing disposal") - } - for entryIndex in journal.entries.indices where journal.entries[entryIndex].container == index { - for (slot, expected) in layouts[entryIndex]!.objects { - guard snapshot?.children?[slot.name(entryIndex)] == expected else { - throw conflict(entryIndex, "expected user object changed while sealing disposal") - } - } - } - journal.containers[index].cleanup = snapshot - } - - func inspectRecoveryObjects() throws { - if journal.discarding { - for index in journal.entries.indices { try verifyTarget(index) } - } else { - for index in journal.entries.indices { - _ = try distribution(index) - try inspectDirectoryPermissions(index) - } - } - try validateContainersForDisposal() - } - - func cleanup(observedTerminal: Bool = false) throws { - try requireScope() - if observedTerminal { - // An observed terminal rename may not have reached its parent barrier. - // Persist it before deleting any preimage or quarantine, including on retry. - try directory.syncFile("transaction.json") - try emit(.terminalSynced) - } - try validateCleanupOperations() - do { try validateContainersForDisposal() } catch { - if let index = journal.entries.indices.first { try recordConflict(index, error) } - throw error - } - if !journal.discarding { - journal.discarding = true - try persist(.discard) - try emit(.discardIntent) - } - for index in journal.containers.indices { try discardContainer(index) } - try requireScope() - try directory.removeJournal { try emit(.journalUnlinked) } - try emit(.journalRemoved) - } - - private func validateCleanupOperations() throws { - for index in journal.entries.indices { - do { - if journal.discarding { - try verifyTarget(index) - } else { - _ = try distribution(index) - } - } catch { - try recordConflict(index, error) - throw error - } - } - } - - private func verifyTarget(_ index: Int) throws { - let entry = journal.entries[index] - try requireParent(index) - // Terminal phases have a single distribution; disposal may have removed its scratch slots. - guard try TransactionLayout.expected(entry)[0].target.matches(entry.name, from: parents[index]) - else { - throw conflict( - index, - journal.phase == .committed - ? "committed destination changed" : "restored destination changed") - } - } - - private func validateContainersForDisposal() throws { - for index in journal.containers.indices { - let record = journal.containers[index] - let parent = parents[record.entry] - try requireParent(record.entry) - guard let actual = try parent.info(record.name) else { - if journal.discarding || record.identity == nil { continue } - throw conflict(record.entry, "private container disappeared before discard intent") - } - if let identity = record.identity { - guard FileObjectIdentity(actual) == identity else { - throw conflict(record.entry, "private container identity changed") - } - if let expected = record.cleanup { - let current = try FileSnapshot.read(record.name, from: parent) - let matches = - journal.discarding - ? current.map(expected.containsRemaining) == true : current == expected - guard matches else { throw conflict(record.entry, "terminal disposal evidence changed") } - } - } else if try !parent.child(record.name).names().isEmpty { - throw conflict(record.entry, "unidentified private container is not empty") - } - } - } - - private func discardContainer(_ index: Int) throws { - let record = journal.containers[index] - let parent = parents[record.entry] - try requireScope() - try requireParent(record.entry) - if let identity = record.identity { - try parent.remove(record.name, expecting: record.cleanup, identity: identity) { - try emit(.disposal(index, $0)) - } - } else { - try parent.removeEmptyDirectory(record.name) - } - try emit(.containerRemoved(index)) - } } diff --git a/Sources/AgentsCore/TransactionSession.swift b/Sources/AgentsCore/TransactionSession.swift new file mode 100644 index 0000000..cddbe34 --- /dev/null +++ b/Sources/AgentsCore/TransactionSession.swift @@ -0,0 +1,243 @@ +import Foundation + +/// One commit or recovery pass over the scope journal under the writer lock. +final class TransactionSession { + var journal: TransactionJournal + let directory: DirectoryHandle + let parents: [DirectoryHandle] + let checkpoint: (String) throws -> Void + /// Devices whose atomic renames passed a probe during this session only; `st_dev` values + /// can be reused by another filesystem after an unmount. + var capableDevices: Set = [] + + init( + journal: TransactionJournal, directory: DirectoryHandle, parents: [DirectoryHandle], + checkpoint: @escaping (String) throws -> Void + ) { + self.journal = journal + self.directory = directory + self.parents = parents + self.checkpoint = checkpoint + } + + func emit(_ point: TransactionCheckpoint) throws { try checkpoint(point.name) } + + func persist(_ change: TransactionCheckpoint.Change) throws { + try requireScope() + try directory.writeJournal( + StateStore.encode(journal), + afterWrite: { + try emit(.persisted(journal.phase, change, .written)) + }, + afterRename: { + try emit(.persisted(journal.phase, change, .renamed)) + }) + } + + /// Transitions and their durable evidence promises are changed together. The first + /// publishing entry also moves a preparing journal to applying in the same write. + func advance(_ index: Int, to next: TransactionJournal.Progress) throws { + let previous = journal.entries[index].progress + let legal: [TransactionJournal.Progress: Set] = [ + .queued: [.ready], .ready: [.publishing, .cancelled], + .publishing: [.applied, .restoring, .cancelled], .applied: [.restoring], + .restoring: [.restored], .restored: [], .cancelled: [], + ] + guard legal[previous]?.contains(next) == true else { + throw conflict(index, "illegal progress transition: \(previous) -> \(next)") + } + if next == .publishing, journal.phase == .preparing { try changePhase(to: .applying) } + journal.entries[index].progress = next + journal.entries[index].conflict = nil + try persist(.entry(index, next)) + try emit(.progress(index, next)) + } + + /// The terminal marker is durable before any disposal. + func finish(_ phase: TransactionJournal.Phase) throws { + try changePhase(to: phase) + try persist(.terminal) + } + + private func changePhase(to next: TransactionJournal.Phase) throws { + let legal: [TransactionJournal.Phase: Set] = [ + .preparing: [.applying, .rolledBack], .applying: [.committed, .rolledBack], + .committed: [], .rolledBack: [], + ] + guard legal[journal.phase]?.contains(next) == true else { + throw CoreError.invalidState( + "illegal transaction phase transition: \(journal.phase) -> \(next)") + } + journal.phase = next + } + + func requireScope() throws { + guard try DirectoryHandle(at: directory.url).identity == journal.scope else { + throw CoreError.invalidState("transaction scope identity changed") + } + } + + func requireParent(_ index: Int) throws { + guard + try DirectoryHandle(at: parents[index].url).identity == journal.entries[index].parentIdentity + else { + throw conflict(index, "destination parent changed") + } + } + + func conflict(_ index: Int, _ reason: String) -> CoreError { + .invalidState( + "transaction conflict at \(journal.entries[index].path): \(reason); retained container: \(containerLocation(index))" + ) + } + + func containerLocation(_ index: Int) -> String { + let entry = journal.entries[index] + guard journal.containers.indices.contains(entry.container) else { + return "" + } + return entry.path.split(separator: "/").dropLast().joined(separator: "/") + "/" + + journal.containerName(entry.container) + } + + func recordConflict(_ index: Int, _ error: Error) throws { + journal.entries[index].conflict = .init( + reason: String(describing: error), + locations: [journal.entries[index].path, containerLocation(index)]) + try persist(.conflict(index, journal.entries[index].progress)) + } + + func container(_ index: Int) throws -> DirectoryHandle { + let record = journal.containers[index] + let parent = parents[record.entry] + guard let expected = record.identity, + try parent.info(record.name).map(FileObjectIdentity.init) == expected + else { + throw conflict(record.entry, "private container identity changed or is missing") + } + let handle = try parent.child(record.name) + guard try handle.objectIdentity == expected else { + throw conflict(record.entry, "private container changed while opening") + } + return handle + } + + func validateRecords(store: StateStore) throws { + try requireScope() + let paths = TransactionPaths(store: store) + let keys = try Set(journal.entries.map { try paths.components($0.path).root }) + guard keys == Set(journal.roots.keys), !journal.entries.isEmpty else { + throw CoreError.invalidState("invalid transaction roots") + } + var targets: [URL] = [] + for (index, entry) in journal.entries.enumerated() { + try requireParent(index) + let target = parents[index].url.appendingPathComponent(entry.name) + guard + !targets.contains(where: { + PathSafety.isContained(target, in: $0) || PathSafety.isContained($0, in: target) + }), + journal.containers.indices.contains(entry.container) + else { + throw conflict(index, "overlapping destinations or invalid container") + } + targets.append(target) + try validateProgress(index) + try entry.preimage?.validate() + try entry.staged?.validate() + } + for index in journal.containers.indices { try validateContainerRecord(index) } + for (index, entry) in journal.entries.enumerated() { + if let conflict = entry.conflict, + conflict.locations != [entry.path, containerLocation(index)] + { + throw CoreError.invalidState("invalid transaction conflict locations") + } + } + } + + private func validateContainerRecord(_ index: Int) throws { + let record = journal.containers[index] + guard journal.entries.indices.contains(record.entry), + journal.entries[record.entry].container == index, + record.name == TransactionJournal.containerName(id: journal.id, index: index), + record.identity?.isDirectory != false + else { + throw CoreError.invalidState("invalid private transaction container evidence") + } + for entry in journal.entries where entry.container == index { + guard entry.parentIdentity == journal.entries[record.entry].parentIdentity else { + throw CoreError.invalidState("private container belongs to another parent") + } + guard entry.progress == .queued || record.identity != nil else { + throw CoreError.invalidState("sealed operation is missing private container identity") + } + } + try record.cleanup?.validate() + if let cleanup = record.cleanup { + guard cleanup.identity == record.identity else { + throw CoreError.invalidState("terminal container evidence has another identity") + } + } + if journal.phase == .committed || journal.phase == .rolledBack { + let containsUserData = journal.entries.filter { $0.container == index }.contains { entry in + [.applied, .restored].contains(entry.progress) + && TransactionLayout.expected(entry).contains { !$0.objects.isEmpty } + } + guard !containsUserData || record.cleanup != nil else { + throw CoreError.invalidState("terminal container is missing user-object disposal evidence") + } + } + } + + private func validateProgress(_ index: Int) throws { + let entry = journal.entries[index] + let allowed: Set + switch journal.phase { + case .preparing: allowed = [.queued, .ready] + case .applying: allowed = [.ready, .publishing, .applied, .restoring, .restored, .cancelled] + case .committed: allowed = [.applied] + case .rolledBack: allowed = [.queued, .ready, .restored, .cancelled] + } + let requiresStaging = entry.action == .install && entry.progress != .queued + guard allowed.contains(entry.progress), + (entry.staged != nil) == requiresStaging, + !journal.discarding || journal.phase == .committed || journal.phase == .rolledBack + else { + throw conflict(index, "operation progress contradicts its evidence or journal phase") + } + } + + /// Matches the target and every recovery slot against the operation/progress table. + /// Only interrupted publishing or restoring may observe a leased owner-write bit. + func distribution(_ index: Int, permittingDirectoryWrite: Bool = false) throws + -> TransactionLayout + { + let entry = journal.entries[index] + try requireParent(index) + let layouts = TransactionLayout.expected(entry) + if entry.progress == .queued { return layouts[0] } + let scratch = try container(entry.container) + var objects: [TransactionScratch: FileSnapshot] = [:] + for slot in TransactionScratch.objectSlots { + if let value = try FileSnapshot.read(slot.name(index), from: scratch) { + objects[slot] = value + } + } + let permitsWrite = permittingDirectoryWrite && entry.progress.permitsDirectoryWrite + for layout in layouts where Set(layout.objects.keys) == Set(objects.keys) { + guard + layout.objects.allSatisfy({ slot, expected in + guard let actual = objects[slot] else { return false } + return expected.matches(actual, permittingDirectoryWrite: permitsWrite) + }) + else { continue } + if try layout.target.matches( + entry.name, from: parents[index], permittingDirectoryWrite: permitsWrite) + { + return layout + } + } + throw conflict(index, "missing or changed expected target, preimage or rollback quarantine") + } +} diff --git a/Sources/AgentsCore/UpdatePreconditions.swift b/Sources/AgentsCore/UpdatePreconditions.swift index b986050..689508b 100644 --- a/Sources/AgentsCore/UpdatePreconditions.swift +++ b/Sources/AgentsCore/UpdatePreconditions.swift @@ -1,4 +1,3 @@ -import CPlatform import Foundation /// Captures existing ancestry and the final entry without following that entry's link. diff --git a/Sources/AgentsCore/WatchOperations.swift b/Sources/AgentsCore/WatchOperations.swift index 00b536c..a06d90c 100644 --- a/Sources/AgentsCore/WatchOperations.swift +++ b/Sources/AgentsCore/WatchOperations.swift @@ -32,9 +32,10 @@ public struct WatchOperations: Sendable { ) throws -> WatchSeen { let store = StateStore(scope: scope, environment: environment) return try store.withLock(checkpoint: checkpoint) { - var declaration = try store.readDeclaration() - let lock = try store.readResolved() - var watch = try store.readWatch() + let baseline = try StatePrecondition(store: store) + var declaration = try store.readDeclaration(prepared: baseline) + let lock = try store.readResolved(prepared: baseline) + var watch = try store.readWatch(prepared: baseline) let argument = try SourceArgument(source) guard argument.name == nil else { throw CoreError.invalidSource("@skill: selects skills; watch subscribes to whole sources") @@ -58,7 +59,8 @@ public struct WatchOperations: Sendable { try declaration.validate(environment: environment) let current = try acknowledge(declared, revision: nil, store: store) watch.sources[id] = WatchSourceState(seen: current) - try commit(declaration: declaration, watch: watch, lock: lock, store: store) + try commit( + declaration: declaration, watch: watch, lock: lock, store: store, baseline: baseline) return current } } @@ -104,15 +106,16 @@ public struct WatchOperations: Sendable { ) throws -> WatchSeen { let store = StateStore(scope: scope, environment: environment) return try store.withLock(checkpoint: checkpoint) { - let declaration = try store.readDeclaration() - let lock = try store.readResolved() - var watch = try store.readWatch() + let baseline = try StatePrecondition(store: store) + let declaration = try store.readDeclaration(prepared: baseline) + let lock = try store.readResolved(prepared: baseline) + var watch = try store.readWatch(prepared: baseline) let alias = try subscription(source, declaration: declaration, environment: environment) let declared = declaration.sources[alias]! let id = try declared.identity(environment: environment) let current = try acknowledge(declared, revision: revision, store: store) watch.sources[id] = WatchSourceState(seen: current) - try commit(declaration: nil, watch: watch, lock: lock, store: store) + try commit(declaration: nil, watch: watch, lock: lock, store: store, baseline: baseline) return current } } @@ -124,14 +127,16 @@ public struct WatchOperations: Sendable { ) throws { let store = StateStore(scope: scope, environment: environment) try store.withLock(checkpoint: checkpoint) { - var declaration = try store.readDeclaration() - let lock = try store.readResolved() - var watch = try store.readWatch() + let baseline = try StatePrecondition(store: store) + var declaration = try store.readDeclaration(prepared: baseline) + let lock = try store.readResolved(prepared: baseline) + var watch = try store.readWatch(prepared: baseline) let alias = try subscription(source, declaration: declaration, environment: environment) let id = try declaration.sources[alias]!.identity(environment: environment) declaration.watch?.removeAll { $0 == alias } watch.sources.removeValue(forKey: id) - try commit(declaration: declaration, watch: watch, lock: lock, store: store) + try commit( + declaration: declaration, watch: watch, lock: lock, store: store, baseline: baseline) } } @@ -164,15 +169,23 @@ public struct WatchOperations: Sendable { throw CoreError.notFound("source is not subscribed: \(input)") } + /// The prepared generation, captured before any network acknowledgment, is the journal's + /// preimage evidence and also guards the lock that pruning follows. private func commit( - declaration: Declaration?, watch: WatchState, lock: ResolvedState, store: StateStore + declaration: Declaration?, watch: WatchState, lock: ResolvedState, store: StateStore, + baseline: StatePrecondition ) throws { try watch.validate() let transaction = FileTransaction(store: store, checkpoint: checkpoint) + transaction.validateBeforePublication = { [unowned transaction] in + try baseline.validate(excludingTargets: transaction.targetPaths) + } if let declaration { - try store.stageDeclaration(declaration, in: transaction) + try store.stageDeclaration(declaration, in: transaction, prepared: baseline) } - try transaction.replace(store.watchURL, content: nil, data: StateStore.encode(watch)) + try transaction.replace( + store.watchURL, content: nil, data: StateStore.encode(watch), + expecting: baseline.evidence(for: store.watchURL)) try SourceCache(store: store).prune(referencedBy: lock, watch: watch, transaction: transaction) try transaction.commit() } diff --git a/Tests/AgentsCoreTests/CachePublicationTests.swift b/Tests/AgentsCoreTests/CachePublicationTests.swift index 9b75ecf..5ac19e4 100644 --- a/Tests/AgentsCoreTests/CachePublicationTests.swift +++ b/Tests/AgentsCoreTests/CachePublicationTests.swift @@ -10,22 +10,27 @@ struct CachePublicationTests { @Test( arguments: ["cache-content", "cache-git"], [ - "stage.0.copy.entry.0.staged.directoryCreated", - "stage.0.copy.entry.0.staged/SKILL.md.entryCopied", "entry.0.ready", "publish.0.created", - "journal.committed.terminal.renamed", + TransactionCheckpoint.copy( + 0, .init(path: TransactionScratch.staged.name(0), step: .directoryCreated) + ).name, + TransactionCheckpoint.copy( + 0, .init(path: TransactionScratch.staged.name(0) + "/SKILL.md", step: .entryCopied) + ).name, TransactionCheckpoint.progress(0, .ready).name, + TransactionCheckpoint.publication(0, .created).name, + TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, ]) func interruptedTreePublicationRecoversAndRetries(_ kind: String, _ point: String) throws { let fixture = try CacheFixture(git: kind == "cache-git") try interrupt(fixture, kind: kind, point: point) - if point.hasPrefix("stage.") || point.hasPrefix("entry.") { - #expect(try FileSnapshot.read(at: fixture.destination) == nil) - } else { + let committed = point == TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name + if committed || point == TransactionCheckpoint.publication(0, .created).name { #expect(try FileHash.folderHash(fixture.destination) == fixture.hash) + } else { + #expect(try FileSnapshot.read(at: fixture.destination) == nil) } #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { try fixture.store.loadResolved() } - let committed = point.hasPrefix("journal.committed") #expect(FileManager.default.fileExists(atPath: fixture.destination.path) == committed) #expect(try Data(contentsOf: fixture.store.resolvedURL) == fixture.lockBytes) try fixture.publish() @@ -39,8 +44,10 @@ struct CachePublicationTests { } @Test(arguments: [ - "stage.0.constructed", "entry.0.ready", "publish.0.created", - "journal.committed.terminal.renamed", + TransactionCheckpoint.stage(0, .constructed).name, + TransactionCheckpoint.progress(0, .ready).name, + TransactionCheckpoint.publication(0, .created).name, + TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, ]) func interruptedArtifactBytesAreNeverPublishedPartially(_ point: String) throws { let fixture = try CacheFixture() @@ -57,7 +64,10 @@ struct CachePublicationTests { #expect(try Data(contentsOf: fixture.store.resolvedURL) == fixture.lockBytes) } - @Test(arguments: ["stage.0.workCreated", "stage.0.workPrepared"]) + @Test(arguments: [ + TransactionCheckpoint.stage(0, .workCreated).name, + TransactionCheckpoint.stage(0, .workPrepared).name, + ]) func interruptedExtractionCleansJournalOwnedScratch(_ point: String) throws { let fixture = try CacheFixture(git: true) try interrupt(fixture, kind: "cache-git", point: point) @@ -78,13 +88,13 @@ struct CachePublicationTests { let fixture = try CacheFixture() let beforeState = try FileSnapshot.read(at: fixture.store.resolvedURL) let cache = SourceCache(store: fixture.store) { step in - if step == "stage.0.constructed" { + if step == TransactionCheckpoint.stage(0, .constructed).name { let parent = fixture.destination.deletingLastPathComponent() for name in try FileManager.default.contentsOfDirectory(atPath: parent.path) where name.hasPrefix(".agents-") { try Data("tampered".utf8).write( to: parent.appendingPathComponent(name).appendingPathComponent( - "entry.0.staged/injected")) + TransactionScratch.staged.name(0) + "/injected")) } } } @@ -108,12 +118,13 @@ struct CachePublicationTests { let fixture = try CacheFixture() let beforeState = try FileSnapshot.read(at: fixture.store.resolvedURL) let cache = SourceCache(store: fixture.store) { step in - if step == "stage.0.constructed" { + if step == TransactionCheckpoint.stage(0, .constructed).name { let parent = fixture.store.cacheDirectory.appendingPathComponent("artifacts") for name in try FileManager.default.contentsOfDirectory(atPath: parent.path) where name.hasPrefix(".agents-") { try Data("tampered".utf8).write( - to: parent.appendingPathComponent(name).appendingPathComponent("entry.0.staged")) + to: parent.appendingPathComponent(name).appendingPathComponent( + TransactionScratch.staged.name(0))) } } } @@ -139,7 +150,7 @@ struct CachePublicationTests { let final = try SourceCache(store: fixture.store).artifactURL(digest: fixture.digest) var external: FileSnapshot? let cache = SourceCache(store: fixture.store) { step in - if step == "publish.0.validated" { + if step == TransactionCheckpoint.publication(0, .validated).name { try (equalBytes ? payload : Data("external cache bytes".utf8)).write(to: final) external = try FileSnapshot.read(at: final) } @@ -160,16 +171,10 @@ struct CachePublicationTests { private func interrupt(_ fixture: CacheFixture, kind: String, point: String) throws { let child = try stateTestProcess(root: fixture.root, arguments: [kind, point]) - defer { - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } - } + defer { terminateProcess(child) } let marker = fixture.root.appendingPathComponent("ready") try ProcessWait.marker(marker, child: child, root: fixture.root) - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + terminateProcess(child) } } diff --git a/Tests/AgentsCoreTests/DirectoryHandleTests.swift b/Tests/AgentsCoreTests/DirectoryHandleTests.swift index c0ca90e..08964a9 100644 --- a/Tests/AgentsCoreTests/DirectoryHandleTests.swift +++ b/Tests/AgentsCoreTests/DirectoryHandleTests.swift @@ -73,7 +73,7 @@ struct DirectoryHandleTests { try Data(name.utf8).write(to: child.appendingPathComponent("content")) } let directory = try DirectoryHandle(at: root) - try directory.rename("first", to: "second", swap: true) + try directory.move("first", to: directory, named: "second", mode: .exchange) #expect(try directory.child("first").read("content") == Data("second".utf8)) #expect(try directory.child("second").read("content") == Data("first".utf8)) } @@ -95,10 +95,12 @@ struct DirectoryHandleTests { } let staged = try FileSnapshot.read("staged", from: directory) let external = try FileSnapshot.read("external", from: directory) - #expect(throws: CoreError.self) { try directory.renameExclusive("staged", to: "external") } + #expect(throws: CoreError.self) { + try directory.move("staged", to: directory, named: "external", mode: .exclusive) + } #expect(try FileSnapshot.read("staged", from: directory) == staged) #expect(try FileSnapshot.read("external", from: directory) == external) - try directory.renameExclusive("staged", to: "published") + try directory.move("staged", to: directory, named: "published", mode: .exclusive) #expect(try FileSnapshot.read("published", from: directory) == staged) #expect(try directory.info("staged") == nil) } diff --git a/Tests/AgentsCoreTests/InstructionTransactionTests.swift b/Tests/AgentsCoreTests/InstructionTransactionTests.swift index f7b56ae..7727d4f 100644 --- a/Tests/AgentsCoreTests/InstructionTransactionTests.swift +++ b/Tests/AgentsCoreTests/InstructionTransactionTests.swift @@ -30,7 +30,7 @@ struct InstructionTransactionTests { struct Interrupted: Error {} try store.withLock { let transaction = FileTransaction(store: store) { checkpoint in - if checkpoint == "entry.1.applied" { throw Interrupted() } + if checkpoint == TransactionCheckpoint.progress(1, .applied).name { throw Interrupted() } } for file in files { try transaction.replace( diff --git a/Tests/AgentsCoreTests/PreparationEvidenceTests.swift b/Tests/AgentsCoreTests/PreparationEvidenceTests.swift index 842391a..eed1532 100644 --- a/Tests/AgentsCoreTests/PreparationEvidenceTests.swift +++ b/Tests/AgentsCoreTests/PreparationEvidenceTests.swift @@ -8,12 +8,12 @@ struct PreparationEvidenceTests { @Test func dataSealingRejectsAnUnexpectedExecutableMode() throws { let fixture = try PublicationFixture(.fileCreate) let transaction = FileTransaction(store: fixture.store) { point in - if point == "stage.0.constructed" { + if point == TransactionCheckpoint.stage(0, .constructed).name { let name = try #require( try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) .first(where: { $0.hasPrefix(".agents-") })) let staged = fixture.root.appendingPathComponent(name).appendingPathComponent( - "entry.0.staged") + TransactionScratch.staged.name(0)) try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: staged.path) } } @@ -32,7 +32,7 @@ struct PreparationEvidenceTests { var original: FileSnapshot? var location: URL? let transaction = FileTransaction(store: fixture.store) { point in - if point == "container.0.created" { + if point == TransactionCheckpoint.containerCreated(0).name { let name = try #require( try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) .first(where: { $0.hasPrefix(".agents-") })) @@ -61,13 +61,13 @@ struct PreparationEvidenceTests { { let fixture = try PublicationFixture(operation) let transaction = FileTransaction(store: fixture.store) { point in - if point == "stage.0.constructed" { + if point == TransactionCheckpoint.stage(0, .constructed).name { let name = try #require( try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) .first(where: { $0.hasPrefix(".agents-") })) - let slot = operation == .directoryDelete ? "staged" : "preimage" + let slot: TransactionScratch = operation == .directoryDelete ? .staged : .deleted try Data("private injection".utf8).write( - to: fixture.root.appendingPathComponent(name).appendingPathComponent("entry.0." + slot)) + to: fixture.root.appendingPathComponent(name).appendingPathComponent(slot.name(0))) } } try transaction.replace( @@ -82,12 +82,12 @@ struct PreparationEvidenceTests { @Test func equalDigestDoesNotTurnDataIntoASymbolicLink() throws { let fixture = try PublicationFixture(.fileCreate) let transaction = FileTransaction(store: fixture.store) { point in - if point == "stage.0.constructed" { + if point == TransactionCheckpoint.stage(0, .constructed).name { let name = try #require( try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) .first(where: { $0.hasPrefix(".agents-") })) let staged = fixture.root.appendingPathComponent(name).appendingPathComponent( - "entry.0.staged") + TransactionScratch.staged.name(0)) try FileManager.default.removeItem(at: staged) try FileManager.default.createSymbolicLink( atPath: staged.path, withDestinationPath: "postimage") @@ -105,12 +105,12 @@ struct PreparationEvidenceTests { func constructionMustMatchTheRequestedCopyOrLink(_ link: Bool) throws { let fixture = try PublicationFixture(.fileCreate) let transaction = FileTransaction(store: fixture.store) { point in - if point == "stage.0.constructed" { + if point == TransactionCheckpoint.stage(0, .constructed).name { let name = try #require( try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) .first(where: { $0.hasPrefix(".agents-") })) let staged = fixture.root.appendingPathComponent(name).appendingPathComponent( - "entry.0.staged") + TransactionScratch.staged.name(0)) if link { try FileManager.default.removeItem(at: staged) try FileManager.default.createSymbolicLink( diff --git a/Tests/AgentsCoreTests/ProcessTerminationTests.swift b/Tests/AgentsCoreTests/ProcessTerminationTests.swift new file mode 100644 index 0000000..2b974b0 --- /dev/null +++ b/Tests/AgentsCoreTests/ProcessTerminationTests.swift @@ -0,0 +1,74 @@ +import CPlatform +import Foundation +import StateTestSupport +import Testing + +/// A SIGKILL racing a child's own SIGSTOP was observed to be lost on Darwin, leaving the child +/// running or stopped. That interleaving cannot be produced on demand, so these tests pin its +/// handling: a stop is observed before signals that depend on it, and lost SIGKILLs are resent +/// within a bounded deadline. +@Suite("Test process termination") +struct ProcessTerminationTests { + @Test func pausedChildIsObservedStoppedBeforeResuming() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let child = try stateTestProcess(root: root, arguments: ["pause", "paused"]) + defer { terminateProcess(child) } + try ProcessWait.marker(root.appendingPathComponent("ready"), child: child, root: root) + try ProcessWait.stopped(child, root: root) + kill(child.processIdentifier, SIGCONT) + try ProcessWait.exit(child, root: root) + #expect(child.terminationStatus == 0) + } + + @Test func stoppedChildIsTerminatedWhenTheFirstKillIsLost() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let child = try stateTestProcess(root: root, arguments: ["pause", "paused"]) + defer { terminateProcess(child) } + try ProcessWait.marker(root.appendingPathComponent("ready"), child: child, root: root) + try ProcessWait.stopped(child, root: root) + var sends = 0 + try ProcessWait.terminate(child, timeout: 10) { processIdentifier in + sends += 1 + if sends > 1 { kill(processIdentifier, SIGKILL) } + } + #expect(sends >= 2) + #expect(child.terminationReason == .uncaughtSignal) + } + + @Test func markedChildThatNeverStopsIsTerminatedWithinTheDeadline() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let child = try stateTestProcess(root: root, arguments: ["unstopped-marker"]) + defer { terminateProcess(child) } + try ProcessWait.marker(root.appendingPathComponent("ready"), child: child, root: root) + #expect(throws: (any Error).self) { try ProcessWait.stopped(child, root: root, timeout: 0.5) } + let start = Date() + try ProcessWait.terminate(child, timeout: 10) + #expect(Date().timeIntervalSince(start) < 10) + #expect(child.terminationReason == .uncaughtSignal) + } + + @Test func lostSignalsAreResentAndTheLoopIsBounded() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let child = try stateTestProcess(root: root, arguments: ["unstopped-marker"]) + defer { terminateProcess(child) } + try ProcessWait.marker(root.appendingPathComponent("ready"), child: child, root: root) + let start = Date() + #expect(throws: (any Error).self) { + try ProcessWait.terminate(child, timeout: 0.5, send: { _ in }) + } + let elapsed = Date().timeIntervalSince(start) + #expect(elapsed >= 0.5 && elapsed < 5) + #expect(child.isRunning) + var sends = 0 + try ProcessWait.terminate(child, timeout: 10) { processIdentifier in + sends += 1 + if sends > 1 { kill(processIdentifier, SIGKILL) } + } + #expect(sends >= 2) + #expect(child.terminationReason == .uncaughtSignal) + } +} diff --git a/Tests/AgentsCoreTests/ProcessTestSupport.swift b/Tests/AgentsCoreTests/ProcessTestSupport.swift index 456f2df..574a835 100644 --- a/Tests/AgentsCoreTests/ProcessTestSupport.swift +++ b/Tests/AgentsCoreTests/ProcessTestSupport.swift @@ -14,11 +14,9 @@ func finishProcesses( pause?.completed() } +/// A child that survives the termination deadline fails the test instead of blocking the run. func terminateProcess(_ process: Process) { - if process.isRunning { - CPlatform.kill(process.processIdentifier, SIGKILL) - process.waitUntilExit() - } + do { try ProcessWait.terminate(process) } catch { Issue.record(error) } } /// FIFO messages establish ordering; the timeout only bounds a failed handshake. diff --git a/Tests/AgentsCoreTests/PublicationTests.swift b/Tests/AgentsCoreTests/PublicationTests.swift index c9eff71..2586a38 100644 --- a/Tests/AgentsCoreTests/PublicationTests.swift +++ b/Tests/AgentsCoreTests/PublicationTests.swift @@ -7,7 +7,7 @@ import Testing @Suite("Journal publication and ownership") struct PublicationTests { - @Test(arguments: PublicationMatrix.publications) + @Test(.tags(.publicationMatrix), arguments: PublicationMatrix.publications) func killedPublicationAtEachStageRecoversPhysicalGeneration(_ fault: PublicationFault) throws { try fault.checkSetup() let fixture = try PublicationFixture(fault.operation) @@ -20,22 +20,105 @@ struct PublicationTests { try fixture.expectClean() } - @Test(arguments: PublicationMatrix.recoveries) + @Test(.tags(.publicationMatrix), arguments: PublicationMatrix.recoveries) func recoveryCanBeKilledAtEachStageAndRepeated(_ fault: PublicationFault) throws { try fault.checkSetup() let fixture = try PublicationFixture(fault.operation) terminateProcess(try fixture.pause("publication", at: fault.seed!)) + let journal = try fixture.lastJournal() terminateProcess(try fixture.pause("publication-recover", at: fault.point)) - try fixture.recover(expected: .unchanged) - try fixture.check(committed: false, journal: nil) + try fixture.recover(expected: fault.committed ? .committed : .unchanged, afterRecovery: true) + try fixture.check(committed: fault.committed, journal: journal) #expect(try !FileTransaction.recover(store: fixture.store)) try fixture.expectClean() } + /// An observed `restoring` journal may still lack its directory barrier. Resumed undo syncs + /// it before it grants directory write access or reverses any rename. + @Test func resumedUndoSyncsTheObservedJournalFirst() throws { + let fixture = try PublicationFixture(.directoryReplace) + terminateProcess( + try fixture.pause("publication", at: TransactionCheckpoint.progress(1, .applied).name)) + terminateProcess( + try fixture.pause( + "publication-recover", + at: TransactionCheckpoint.persisted(.applying, .entry(1, .restoring), .renamed).name)) + #expect(try fixture.lastJournal()?.entries[1].progress == .restoring) + let recovery = try fixture.launch("publication-recover", at: "never") + defer { terminateProcess(recovery) } + try ProcessWait.exit(recovery, root: fixture.root) + let trace = try fixture.trace(recovery) + #expect(trace.first == TransactionCheckpoint.journalSynced.name) + let grant = try #require( + trace.firstIndex( + of: TransactionCheckpoint.permissions(1, .undoGrant, .target, .changed).name)) + let undo = try #require( + trace.firstIndex(of: TransactionCheckpoint.restoration(1, .exchanged).name)) + #expect(grant < undo) + #expect(try fixture.result("recovery-result") == "recovered") + try fixture.check(committed: false, journal: nil) + try fixture.expectClean() + } + + /// A preparation that becomes stale before its entry publishes cancels from `ready`: + /// nothing is leased or moved, the journal is removed and the scope stays writable. + @Test(arguments: [PublicationOperation.directoryDelete, .directoryReplace]) + func stalePreparationBeforePublicationCancelsWithoutConflict(_ operation: PublicationOperation) + throws + { + let fixture = try PublicationFixture(operation) + let child = try fixture.pause( + "publication", at: TransactionCheckpoint.progress(0, .applied).name) + defer { terminateProcess(child) } + let original = fixture.root.appendingPathComponent("moved-original") + if operation == .directoryDelete { + try Data("external edit".utf8).write(to: fixture.target.appendingPathComponent("file")) + } else { + try FileManager.default.moveItem(at: fixture.target, to: original) + try FileManager.default.createDirectory( + at: fixture.target, withIntermediateDirectories: false) + try Data("external replacement".utf8).write( + to: fixture.target.appendingPathComponent("file")) + try FileManager.default.setAttributes( + [.posixPermissions: 0o555], ofItemAtPath: fixture.target.path) + } + let external = try FileSnapshot.read(at: fixture.target) + try fixture.resume(child) + let result = try fixture.result("publication-result") + #expect(result.hasPrefix("unchanged\n")) + #expect(result.contains("preparation is stale; prepare again")) + #expect(try FileSnapshot.read(at: fixture.target) == external) + if operation == .directoryReplace { + #expect(try FileSnapshot.read(at: original) == fixture.beforeTarget) + } + #expect(try FileSnapshot.read(at: fixture.auxiliary) == fixture.beforeAuxiliary) + try fixture.expectClean() + try fixture.store.withLock {} + } + + @Test func disposalConflictNamesTheChangedContainer() throws { + let fixture = try PublicationFixture(.crossParentReplace) + let child = try fixture.pause("publication", at: TransactionCheckpoint.phase(.committed).name) + defer { terminateProcess(child) } + let journal = try #require(try fixture.lastJournal()) + #expect(journal.containers.map(\.entry) == [0, 1]) + let foreign = fixture.container(1, journal: journal).appendingPathComponent("foreign") + try Data("external".utf8).write(to: foreign) + terminateProcess(child) + try fixture.expectUnresolved(containing: "terminal disposal evidence changed") + let recorded = try #require(try fixture.lastJournal()) + #expect(recorded.entries[0].conflict == nil) + let entry = recorded.entries[1] + let root = try #require(entry.path.split(separator: "/").first) + #expect(entry.conflict?.locations == [entry.path, root + "/" + recorded.containerName(1)]) + #expect(try Data(contentsOf: foreign) == Data("external".utf8)) + } + @Test(arguments: ["external", "postimage"]) func concurrentCreatorKeepsItsBytesAndInode(_ bytes: String) throws { let fixture = try PublicationFixture(.fileCreate) - let child = try fixture.pause("publication", at: "publish.1.validated") + let child = try fixture.pause( + "publication", at: TransactionCheckpoint.publication(1, .validated).name) defer { terminateProcess(child) } try Data(bytes.utf8).write(to: fixture.target) let external = try FileSnapshot.read(at: fixture.target) @@ -49,7 +132,8 @@ struct PublicationTests { @Test(arguments: [false, true]) func exchangedUnexpectedPreimageIsNeverDiscarded(_ inPlace: Bool) throws { let fixture = try PublicationFixture(.fileReplace) - let child = try fixture.pause("publication", at: "publish.1.validated") + let child = try fixture.pause( + "publication", at: TransactionCheckpoint.publication(1, .validated).name) defer { terminateProcess(child) } if !inPlace { try FileManager.default.moveItem( @@ -57,17 +141,19 @@ struct PublicationTests { } try Data("external preimage".utf8).write(to: fixture.target) let external = try FileSnapshot.read(at: fixture.target) - try fixture.restop(child, at: "publish.1.exchanged") + try fixture.restop(child, at: TransactionCheckpoint.publication(1, .exchanged).name) terminateProcess(child) let journal = try #require(try fixture.lastJournal()) let postimage = try #require(journal.entries[1].staged) #expect(try FileSnapshot.read(at: fixture.target) == postimage) #expect( - try FileSnapshot.read(at: fixture.scratch(.staged, entry: 1, journal: journal)) == external) + try FileSnapshot.read(at: fixture.scratch(.exchanged, entry: 1, journal: journal)) == external + ) try fixture.expectUnresolved() #expect(try FileSnapshot.read(at: fixture.target) == postimage) #expect( - try FileSnapshot.read(at: fixture.scratch(.staged, entry: 1, journal: journal)) == external) + try FileSnapshot.read(at: fixture.scratch(.exchanged, entry: 1, journal: journal)) == external + ) if !inPlace { #expect( try FileSnapshot.read(at: fixture.root.appendingPathComponent("original")) @@ -80,21 +166,22 @@ struct PublicationTests { throws { let fixture = try PublicationFixture(operation) - let child = try fixture.pause("publication", at: "entry.1.applied") + let child = try fixture.pause( + "publication", at: TransactionCheckpoint.progress(1, .applied).name) defer { terminateProcess(child) } let journal = try #require(try fixture.lastJournal()) - let slot: TransactionScratch = operation == .directoryDelete ? .preimage : .staged + let slot: TransactionScratch = operation == .directoryDelete ? .deleted : .exchanged let original = fixture.scratch(slot, entry: 1, journal: journal) let saved = fixture.root.appendingPathComponent("saved-preimage") - let before = try #require(fixture.beforeTarget) - if before.needsDirectoryWriteLease { + let lease = try #require(fixture.beforeTarget).writeLease + if let lease { try FileManager.default.setAttributes( - [.posixPermissions: before.mode | 0o200], ofItemAtPath: original.path) + [.posixPermissions: lease.grantedMode], ofItemAtPath: original.path) } try FileManager.default.moveItem(at: original, to: saved) - if before.needsDirectoryWriteLease { + if let lease { try FileManager.default.setAttributes( - [.posixPermissions: before.mode], ofItemAtPath: saved.path) + [.posixPermissions: lease.original], ofItemAtPath: saved.path) } let published = try FileSnapshot.read(at: fixture.target) terminateProcess(child) @@ -106,11 +193,13 @@ struct PublicationTests { @Test func missingRollbackQuarantineIsUnresolvedBeforeTerminalIntent() throws { let fixture = try PublicationFixture(.fileCreate) - terminateProcess(try fixture.pause("publication", at: "publish.1.created")) - let recovery = try fixture.pause("publication-recover", at: "entry.1.restored") + terminateProcess( + try fixture.pause("publication", at: TransactionCheckpoint.publication(1, .created).name)) + let recovery = try fixture.pause( + "publication-recover", at: TransactionCheckpoint.progress(1, .restored).name) defer { terminateProcess(recovery) } let journal = try #require(try fixture.lastJournal()) - let quarantined = fixture.scratch(.removed, entry: 1, journal: journal) + let quarantined = fixture.scratch(.withdrawn, entry: 1, journal: journal) let saved = fixture.root.appendingPathComponent("saved-postimage") try FileManager.default.moveItem(at: quarantined, to: saved) terminateProcess(recovery) @@ -122,8 +211,10 @@ struct PublicationTests { @Test(arguments: [PublicationOperation.fileCreate, .fileReplace, .directoryDelete]) func externalRecoveryDestinationPreservesBothVersions(_ operation: PublicationOperation) throws { let fixture = try PublicationFixture(operation) - terminateProcess(try fixture.pause("publication", at: "entry.1.applied")) - let recovery = try fixture.pause("publication-recover", at: "restore.1.validated") + terminateProcess( + try fixture.pause("publication", at: TransactionCheckpoint.progress(1, .applied).name)) + let recovery = try fixture.pause( + "publication-recover", at: TransactionCheckpoint.restoration(1, .validated).name) defer { terminateProcess(recovery) } let journal = try #require(try fixture.lastJournal()) if try FileSnapshot.read(at: fixture.target) != nil { @@ -136,8 +227,8 @@ struct PublicationTests { #expect(try fixture.result("recovery-result").hasPrefix("unresolved:")) let location: URL switch operation { - case .fileCreate: location = fixture.scratch(.removed, entry: 1, journal: journal) - case .fileReplace: location = fixture.scratch(.staged, entry: 1, journal: journal) + case .fileCreate: location = fixture.scratch(.withdrawn, entry: 1, journal: journal) + case .fileReplace: location = fixture.scratch(.exchanged, entry: 1, journal: journal) default: location = fixture.target } #expect(try FileSnapshot.read(at: location) == external) @@ -148,7 +239,7 @@ struct PublicationTests { #expect(try FileSnapshot.read(at: location) == external) if operation == .directoryDelete { #expect( - try FileSnapshot.read(at: fixture.scratch(.preimage, entry: 1, journal: journal)) + try FileSnapshot.read(at: fixture.scratch(.deleted, entry: 1, journal: journal)) == fixture.beforeTarget) } else { #expect( @@ -159,7 +250,7 @@ struct PublicationTests { @Test func committedFailureRetainsUserDataAndRecordsConflict() throws { let fixture = try PublicationFixture(.fileReplace) - let child = try fixture.pause("publication", at: "journal.committed") + let child = try fixture.pause("publication", at: TransactionCheckpoint.phase(.committed).name) defer { terminateProcess(child) } let journal = try #require(try fixture.lastJournal()) let saved = fixture.root.appendingPathComponent("saved-published") @@ -171,17 +262,18 @@ struct PublicationTests { #expect(try FileSnapshot.read(at: fixture.target) == external) #expect(try FileSnapshot.read(at: saved) == journal.entries[1].staged) #expect( - try FileSnapshot.read(at: fixture.scratch(.staged, entry: 1, journal: journal)) + try FileSnapshot.read(at: fixture.scratch(.exchanged, entry: 1, journal: journal)) == fixture.beforeTarget) } @Test(arguments: [false, true]) func plannedUnidentifiedContainerOnlyAdmitsEmptyRmdir(_ populate: Bool) throws { let fixture = try PublicationFixture(.fileCreate) - terminateProcess(try fixture.pause("publication", at: "container.0.created")) + terminateProcess( + try fixture.pause("publication", at: TransactionCheckpoint.containerCreated(0).name)) let journal = try #require(try fixture.lastJournal()) #expect(journal.containers[0].identity == nil) - let container = fixture.root.appendingPathComponent(journal.containerName(0)) + let container = fixture.container(0, journal: journal) if populate { let file = container.appendingPathComponent("keep") try Data("unidentified bytes".utf8).write(to: file) @@ -197,9 +289,10 @@ struct PublicationTests { @Test func sealedPrivateObjectChangesAreUnresolved() throws { let fixture = try PublicationFixture(.fileReplace) - terminateProcess(try fixture.pause("publication", at: "entry.1.ready")) + terminateProcess( + try fixture.pause("publication", at: TransactionCheckpoint.progress(1, .ready).name)) let journal = try #require(try fixture.lastJournal()) - let file = fixture.scratch(.staged, entry: 1, journal: journal) + let file = fixture.scratch(.exchanged, entry: 1, journal: journal) try Data("changed after sealing".utf8).write(to: file) let changed = try FileSnapshot.read(at: file) try fixture.expectUnresolved() @@ -209,7 +302,9 @@ struct PublicationTests { @Test func directoryPermissionChangesOutsideIntentRemainExternal() throws { let fixture = try PublicationFixture(.directoryReplace) - let child = try fixture.pause("publication", at: "permissions.1.publish.grant.target.synced") + let child = try fixture.pause( + "publication", + at: TransactionCheckpoint.permissions(1, .publicationGrant, .target, .synced).name) defer { terminateProcess(child) } try FileManager.default.setAttributes( [.posixPermissions: 0o770], ofItemAtPath: fixture.target.path) @@ -253,7 +348,8 @@ struct PublicationTests { @Test(arguments: ["staged", "parent", "container"]) func missingJournalEvidenceReachesSemanticValidation(_ field: String) throws { let fixture = try PublicationFixture(.fileReplace) - terminateProcess(try fixture.pause("publication", at: "entry.1.ready")) + terminateProcess( + try fixture.pause("publication", at: TransactionCheckpoint.progress(1, .ready).name)) var journal = try #require(try fixture.lastJournal()) switch field { case "staged": journal.entries[1].staged = nil @@ -321,7 +417,8 @@ struct PublicationTests { @Test(arguments: ["identity", "disposal"]) func missingContainerEvidenceCannotAuthorizeTerminalDeletion(_ field: String) throws { let fixture = try PublicationFixture(.fileReplace) - terminateProcess(try fixture.pause("publication", at: "journal.committed")) + terminateProcess( + try fixture.pause("publication", at: TransactionCheckpoint.phase(.committed).name)) var journal = try #require(try fixture.lastJournal()) if field == "identity" { journal.containers[0].identity = nil @@ -358,12 +455,34 @@ struct PublicationTests { enum PublicationOperation: String, CaseIterable, Sendable { case fileReplace, directoryReplace, directoryDelete, symlinkCreate, fileCreate + /// The target is in another parent than the auxiliary file, so two containers are used. + case crossParentReplace + var renamePoint: String { switch self { - case .directoryDelete: "publish.1.quarantined" - case .fileReplace, .directoryReplace: "publish.1.exchanged" - default: "publish.1.created" + case .directoryDelete: TransactionCheckpoint.publication(1, .quarantined).name + case .fileReplace, .directoryReplace, .crossParentReplace: + TransactionCheckpoint.publication(1, .exchanged).name + case .symlinkCreate, .fileCreate: TransactionCheckpoint.publication(1, .created).name + } + } + + /// Recovery starts from construction, sealed staging, an interrupted rename or directory + /// grant, an applied entry, the committed marker and terminal cleanup. + var recoverySeeds: [(point: String, committed: Bool)] { + var seeds = [ + (TransactionCheckpoint.stage(1, .constructed).name, false), + (TransactionCheckpoint.progress(1, .ready).name, false), + (renamePoint, false), + (TransactionCheckpoint.progress(1, .applied).name, false), + (TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, true), + (TransactionCheckpoint.discardIntent.name, true), + ] + if self == .directoryReplace || self == .directoryDelete { + seeds.append( + (TransactionCheckpoint.permissions(1, .publicationGrant, .target, .changed).name, false)) } + return seeds } } @@ -383,21 +502,61 @@ struct PublicationFault: Sendable, CustomTestStringConvertible { } } +extension Tag { + /// Kill-point matrices recorded from real traces. + @Tag static var publicationMatrix: Self +} + +/// By default each operation is killed at its representative points and recovery from every +/// seed at its durable recovery steps. `AGENTS_PUBLICATION_MATRIX=full` kills at every +/// recorded point. private enum PublicationMatrix { + static let complete = ProcessInfo.processInfo.environment["AGENTS_PUBLICATION_MATRIX"] == "full" static let publications = record(recovery: false) static let recoveries = record(recovery: true) + /// Every recovery seed, durable intent and the removal of the first container. + private static func representativePublication(_ operation: PublicationOperation) -> Set { + Set( + operation.recoverySeeds.map(\.point) + [ + TransactionCheckpoint.progress(1, .publishing).name, + TransactionCheckpoint.containerRemoved(0).name, + ]) + } + + /// The observed-journal barrier, each durable recovery write, each reverse rename or undo + /// grant, and disposal. + private static let representativeRecovery: Set = { + var points: [TransactionCheckpoint] = [.journalSynced, .containerRemoved(0), .journalRemoved] + for phase in [TransactionJournal.Phase.applying, .committed, .rolledBack] { + points += [.persisted(phase, .terminal, .renamed), .persisted(phase, .discard, .renamed)] + for index in 0...1 { + for progress in [TransactionJournal.Progress.restoring, .restored, .cancelled] { + points.append(.persisted(phase, .entry(index, progress), .renamed)) + } + } + } + for index in 0...1 { + points += [ + .restoration(index, .exchanged), .restoration(index, .returned), + .restoration(index, .creationQuarantined), + .permissions(index, .undoGrant, .target, .changed), + ] + } + return Set(points.map(\.name)) + }() + private static func record(recovery: Bool) -> [PublicationFault] { var cases: [PublicationFault] = [] + let commitMarker = TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name for operation in PublicationOperation.allCases { - var seeds: [String?] = recovery ? [operation.renamePoint, "entry.1.applied"] : [nil] - if recovery, operation == .directoryReplace || operation == .directoryDelete { - seeds.append("permissions.1.publish.grant.target.changed") - } + let selected = recovery ? representativeRecovery : representativePublication(operation) + let seeds: [(point: String, committed: Bool)?] = + recovery ? operation.recoverySeeds.map { $0 } : [nil] for seed in seeds { do { let fixture = try PublicationFixture(operation) - if let seed { terminateProcess(try fixture.pause("publication", at: seed)) } + if let seed { terminateProcess(try fixture.pause("publication", at: seed.point)) } let command = recovery ? "publication-recover" : "publication" let child = try fixture.launch(command, at: "never") defer { terminateProcess(child) } @@ -405,25 +564,26 @@ private enum PublicationMatrix { guard child.terminationStatus == 0 else { throw CoreError.invalidState("checkpoint recorder exited \(child.terminationStatus)") } - let trace = try String( - contentsOf: fixture.root.appendingPathComponent( - "checkpoint-\(child.processIdentifier).log"), encoding: .utf8 - ) - .split(separator: "\n").map(String.init) + let trace = try fixture.trace(child) guard !trace.isEmpty, Set(trace).count == trace.count else { throw CoreError.invalidState("checkpoint names are empty or repeated") } - var committed = false + if !recovery, !selected.isSubset(of: trace) { + throw CoreError.invalidState( + "representative points were not recorded: \(selected.subtracting(trace).sorted())") + } + var committed = seed?.committed ?? false for point in trace { - if point == "journal.committed.terminal.renamed" { committed = true } + if point == commitMarker { committed = true } + guard complete || selected.contains(point) else { continue } cases.append( - PublicationFault(operation: operation, point: point, committed: committed, seed: seed) - ) + PublicationFault( + operation: operation, point: point, committed: committed, seed: seed?.point)) } } catch { cases.append( PublicationFault( - operation: operation, point: "recording", seed: seed, + operation: operation, point: "recording", seed: seed?.point, setupFailure: String(describing: error))) } } @@ -450,7 +610,10 @@ final class PublicationFixture { environment: RuntimeEnvironment( projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: [:] )) - target = root.appendingPathComponent("AGENTS.md") + target = + operation == .crossParentReplace + ? root.appendingPathComponent(".agents/skills/target") + : root.appendingPathComponent("AGENTS.md") auxiliary = root.appendingPathComponent("GEMINI.md") do { try store.save(declaration: Declaration(), resolved: ResolvedState()) @@ -461,7 +624,13 @@ final class PublicationFixture { try Data("tree postimage".utf8).write(to: source.appendingPathComponent("nested/file")) try FileManager.default.createSymbolicLink( atPath: source.appendingPathComponent("link").path, withDestinationPath: "nested/file") - if operation == .fileReplace { try Data("preimage".utf8).write(to: target) } + if operation == .crossParentReplace { + try FileManager.default.createDirectory( + at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + } + if operation == .fileReplace || operation == .crossParentReplace { + try Data("preimage".utf8).write(to: target) + } if operation == .directoryReplace || operation == .directoryDelete { try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true) try Data("tree preimage".utf8).write(to: target.appendingPathComponent("file")) @@ -497,6 +666,7 @@ final class PublicationFixture { let child = try launch(command, at: point) do { try ProcessWait.marker(marker, child: child, root: root) + try ProcessWait.stopped(child, root: root) return child } catch { terminateProcess(child) @@ -504,6 +674,7 @@ final class PublicationFixture { } } + /// The child was confirmed stopped by `pause` or `restop`, so SIGCONT cannot be lost. func resume(_ child: Process, marker: String = "ready") throws { try? FileManager.default.removeItem(at: root.appendingPathComponent(marker)) kill(child.processIdentifier, SIGCONT) @@ -517,6 +688,14 @@ final class PublicationFixture { try Data(point.utf8).write(to: root.appendingPathComponent("stop-at")) kill(child.processIdentifier, SIGCONT) try ProcessWait.marker(marker, child: child, root: root) + try ProcessWait.stopped(child, root: root) + } + + func trace(_ child: Process) throws -> [String] { + try String( + contentsOf: root.appendingPathComponent("checkpoint-\(child.processIdentifier).log"), + encoding: .utf8 + ).split(separator: "\n").map(String.init) } func result(_ name: String) throws -> String { @@ -536,12 +715,18 @@ final class PublicationFixture { return nil } + func container(_ index: Int, journal: TransactionJournal) -> URL { + (journal.containers[index].entry == 0 ? auxiliary : target).deletingLastPathComponent() + .appendingPathComponent(journal.containerName(index)) + } + func scratch(_ slot: TransactionScratch, entry index: Int, journal: TransactionJournal) -> URL { - root.appendingPathComponent(journal.containerName(journal.entries[index].container)) + container(journal.entries[index].container, journal: journal) .appendingPathComponent(slot.name(index)) } - func recover(expected: TransactionOutcome.Disposition) throws { + /// After an interrupted recovery, a journal already removed has no outcome left to report. + func recover(expected: TransactionOutcome.Disposition, afterRecovery: Bool = false) throws { let outcome = TransactionOutcome() outcome.journalID = try lastJournal()?.id let directory = try #require(try store.openDirectoryIfPresent()) @@ -554,7 +739,9 @@ final class PublicationFixture { #expect(outcome.disposition == expected) } else { try store.withLock(outcome: outcome, {}) - if expected == .committed { #expect(try result("stopped-outcome") == "committed") } + if expected == .committed, !afterRecovery { + #expect(try result("stopped-outcome") == "committed") + } } } @@ -594,10 +781,12 @@ final class PublicationFixture { func expectClean() throws { #expect(try store.openDirectoryIfPresent()?.info("transaction.json") == nil) #expect(try store.openDirectoryIfPresent()?.info("transaction.new") == nil) - #expect( - try !FileManager.default.contentsOfDirectory(atPath: root.path).contains { - $0.hasPrefix(".agents-") - }) + for parent in Set([auxiliary, target].map { $0.deletingLastPathComponent().path }) { + #expect( + try !FileManager.default.contentsOfDirectory(atPath: parent).contains { + $0.hasPrefix(".agents-") + }) + } } } diff --git a/Tests/AgentsCoreTests/StateInspectionTests.swift b/Tests/AgentsCoreTests/StateInspectionTests.swift index 170ef43..d6767ae 100644 --- a/Tests/AgentsCoreTests/StateInspectionTests.swift +++ b/Tests/AgentsCoreTests/StateInspectionTests.swift @@ -1,7 +1,8 @@ -import AgentsCore import Foundation import Testing +@testable import AgentsCore + @Suite("State inspection concurrency") struct StateInspectionTests { @Test(arguments: [false, true]) @@ -87,8 +88,9 @@ struct StateInspectionTests { try fixture.store.withReadLock { reads += 1 let child = try stateTestProcess( - root: fixture.root, arguments: ["watch-add", "publish.1.created"]) - try fixture.kill(child, at: "publish.1.created") + root: fixture.root, + arguments: ["watch-add", TransactionCheckpoint.publication(1, .created).name]) + try fixture.kill(child, at: TransactionCheckpoint.publication(1, .created).name) let declaration = try fixture.store.readDeclaration() let watch = try fixture.store.readWatch() try #require(declaration.watch == ["source"]) diff --git a/Tests/AgentsCoreTests/StateTransactionTests.swift b/Tests/AgentsCoreTests/StateTransactionTests.swift index 456afbf..1ffb5e4 100644 --- a/Tests/AgentsCoreTests/StateTransactionTests.swift +++ b/Tests/AgentsCoreTests/StateTransactionTests.swift @@ -14,7 +14,7 @@ struct StateTransactionTests { let moved = fixture.root.appendingPathComponent("displaced-cache") try fixture.store.withLock { let transaction = FileTransaction(store: fixture.store) { step in - if step == "journal.committed.terminal.renamed" { + if step == TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name { try FileManager.default.moveItem(at: parent, to: moved) throw CoreError.invalidState("cache cleanup interrupted") } @@ -42,17 +42,17 @@ struct StateTransactionTests { var checkpoints: [String] = [] do { let fixture = try TransactionFixture() - try fixture.commit { - if !$0.contains(fixture.root.lastPathComponent) { checkpoints.append($0) } - } + try fixture.commit { checkpoints.append($0) } } - #expect(checkpoints.contains("journal.committed")) + #expect(checkpoints.contains(TransactionCheckpoint.phase(.committed).name)) for failure in Set(checkpoints).sorted() { let fixture = try TransactionFixture() var committed = false #expect(throws: CoreError.invalidState("injected failure")) { try fixture.commit { step in - if step == "journal.committed.terminal.renamed" { committed = true } + if step == TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name { + committed = true + } if step == failure { throw CoreError.invalidState("injected failure") } } } @@ -64,37 +64,42 @@ struct StateTransactionTests { } @Test(arguments: [ - "journal.preparing", "journal.preparing.created.renamed", "entry.0.ready", "entry.4.ready", - "entry.0.publishing", - "entry.0.applied", - "entry.1.applied", "entry.2.applied", - "entry.3.applied", "entry.4.applied", "entry.5.applied", "publish.5.exchanged", - "publish.0.exchanged", - "journal.applying.entry.0.publishing.renamed", - "journal.committed.terminal.renamed", "journal.committed", "cleanup.0.removed", + TransactionCheckpoint.phase(.preparing).name, + TransactionCheckpoint.persisted(.preparing, .created, .renamed).name, + TransactionCheckpoint.progress(0, .ready).name, TransactionCheckpoint.progress(4, .ready).name, + TransactionCheckpoint.progress(0, .publishing).name, + TransactionCheckpoint.progress(0, .applied).name, + TransactionCheckpoint.progress(1, .applied).name, + TransactionCheckpoint.progress(2, .applied).name, + TransactionCheckpoint.progress(3, .applied).name, + TransactionCheckpoint.progress(4, .applied).name, + TransactionCheckpoint.progress(5, .applied).name, + TransactionCheckpoint.publication(5, .exchanged).name, + TransactionCheckpoint.publication(0, .exchanged).name, + TransactionCheckpoint.persisted(.applying, .entry(0, .publishing), .renamed).name, + TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, + TransactionCheckpoint.phase(.committed).name, TransactionCheckpoint.containerRemoved(0).name, ]) func killedWriterRecoversOnNextStateRead(_ step: String) throws { let fixture = try TransactionFixture() let child = try stateTestProcess(root: fixture.root, arguments: ["crash", step]) - defer { - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } - } + defer { terminateProcess(child) } try ProcessWait.marker( fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) // At every interruption point the replaced installation still has a directory entry. #expect( FileManager.default.fileExists( atPath: fixture.root.appendingPathComponent(".agents/skills/target/SKILL.md").path)) - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + terminateProcess(child) #expect(child.terminationReason == .uncaughtSignal) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { _ = try fixture.store.loadResolved() } - try fixture.check(committed: step.hasPrefix("journal.committed") || step == "cleanup.0.removed") + let committed = [ + TransactionCheckpoint.persisted(.committed, .terminal, .renamed), + .phase(.committed), .containerRemoved(0), + ].map(\.name) + try fixture.check(committed: committed.contains(step)) } @Test func serializesSeparateWriterProcesses() throws { @@ -103,7 +108,7 @@ struct StateTransactionTests { try stateTestProcess(root: fixture.root, arguments: ["writer", "writer-\($0)"]) } for child in children { - child.waitUntilExit() + try ProcessWait.exit(child, root: fixture.root) #expect(child.terminationStatus == 0) } #expect(try fixture.store.loadDeclaration().sources.count == 20) @@ -228,20 +233,15 @@ extension StateTransactionTests { } private func abandon( - _ fixture: TransactionFixture, at step: String = "entry.2.applied", + _ fixture: TransactionFixture, + at step: String = TransactionCheckpoint.progress(2, .applied).name, scope: InstallScope = .project ) throws { let child = try stateTestProcess( root: fixture.root, arguments: ["crash", step, "--scope", scope.rawValue]) - defer { - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } - } + defer { terminateProcess(child) } try waitFor("ready", root: fixture.root, child: child) - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + terminateProcess(child) } @Test(arguments: [InstallScope.project, .user]) @@ -258,22 +258,19 @@ extension StateTransactionTests { let target = AgentRegistry.installSkillsDirectory( for: .claudeCode, scope: scope, environment: environment ).appendingPathComponent("created") - try abandon(fixture, at: "entry.4.applied", scope: scope) + try abandon(fixture, at: TransactionCheckpoint.progress(4, .applied).name, scope: scope) try #require(FileManager.default.fileExists(atPath: target.path)) let recovery = try stateTestProcess( root: fixture.root, - arguments: ["recover", "restore.4.creationQuarantined", "--scope", scope.rawValue]) - defer { - if recovery.isRunning { - kill(recovery.processIdentifier, SIGKILL) - recovery.waitUntilExit() - } - } + arguments: [ + "recover", TransactionCheckpoint.restoration(4, .creationQuarantined).name, "--scope", + scope.rawValue, + ]) + defer { terminateProcess(recovery) } try waitFor("recovery-ready", root: fixture.root, child: recovery) #expect(try DirectoryHandle(at: target.deletingLastPathComponent()).info("created") == nil) - kill(recovery.processIdentifier, SIGKILL) - recovery.waitUntilExit() + terminateProcess(recovery) #expect(recovery.terminationReason == .uncaughtSignal) var steps: [String] = [] @@ -281,10 +278,12 @@ extension StateTransactionTests { let recovered = try FileTransaction.recover(store: store) { steps.append($0) } #expect(recovered) } - #expect(!steps.contains("restore.4.creationQuarantined")) - let synced = try #require(steps.firstIndex(of: "restore.4.synced")) - let terminal = try #require(steps.firstIndex(of: "journal.rolledBack.terminal.renamed")) - let cleanup = try #require(steps.firstIndex(of: "cleanup.intent")) + #expect(!steps.contains(TransactionCheckpoint.restoration(4, .creationQuarantined).name)) + let synced = try #require( + steps.firstIndex(of: TransactionCheckpoint.restoration(4, .synced).name)) + let terminal = try #require( + steps.firstIndex(of: TransactionCheckpoint.persisted(.rolledBack, .terminal, .renamed).name)) + let cleanup = try #require(steps.firstIndex(of: TransactionCheckpoint.discardIntent.name)) #expect(synced < terminal && terminal < cleanup) #expect(try Data(contentsOf: store.declarationURL) == declaration) #expect(try Data(contentsOf: store.resolvedURL) == resolved) @@ -300,60 +299,47 @@ extension StateTransactionTests { } @Test(arguments: [ - "restore.2.exchanged", "entry.0.restored", "journal.rolledBack.terminal.renamed", - "journal.rolledBack", - "cleanup.0.removed", + TransactionCheckpoint.restoration(2, .exchanged).name, + TransactionCheckpoint.progress(0, .restored).name, + TransactionCheckpoint.persisted(.rolledBack, .terminal, .renamed).name, + TransactionCheckpoint.phase(.rolledBack).name, + TransactionCheckpoint.containerRemoved(0).name, ]) func interruptedRecoverySerializesCompetingReader(_ point: String) throws { let fixture = try TransactionFixture() try abandon(fixture) let recovery = try stateTestProcess(root: fixture.root, arguments: ["recover", point]) - defer { - if recovery.isRunning { - kill(recovery.processIdentifier, SIGKILL) - recovery.waitUntilExit() - } - } + defer { terminateProcess(recovery) } try waitFor("recovery-ready", root: fixture.root, child: recovery) let reader = try stateTestProcess(root: fixture.root, arguments: ["read", ""]) - defer { - if reader.isRunning { - kill(reader.processIdentifier, SIGKILL) - reader.waitUntilExit() - } - } + defer { terminateProcess(reader) } try waitFor("reader-started", root: fixture.root, child: reader) Thread.sleep(forTimeInterval: 0.05) #expect( !FileManager.default.fileExists( atPath: fixture.root.appendingPathComponent("reader-finished").path)) - kill(recovery.processIdentifier, SIGKILL) - recovery.waitUntilExit() + terminateProcess(recovery) try waitFor("reader-finished", root: fixture.root, child: reader) - reader.waitUntilExit() + try ProcessWait.exit(reader, root: fixture.root) #expect(reader.terminationStatus == 0) try fixture.check(committed: false) } - @Test(arguments: ["journal.terminalSynced", "cleanup.0.removed"]) + @Test(arguments: [ + TransactionCheckpoint.journalSynced.name, TransactionCheckpoint.containerRemoved(0).name, + ]) func committedRecoverySyncsObservedMarkerBeforeCleanup(_ point: String) throws { let fixture = try TransactionFixture() - try abandon(fixture, at: "journal.committed.terminal.renamed") + try abandon(fixture, at: TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name) let recovery = try stateTestProcess(root: fixture.root, arguments: ["recover", point]) - defer { - if recovery.isRunning { - kill(recovery.processIdentifier, SIGKILL) - recovery.waitUntilExit() - } - } + defer { terminateProcess(recovery) } try waitFor("recovery-ready", root: fixture.root, child: recovery) - if point == "journal.terminalSynced" { + if point == TransactionCheckpoint.journalSynced.name { let names = try FileManager.default.contentsOfDirectory( atPath: fixture.root.appendingPathComponent(".agents/skills").path) #expect(names.contains { $0.hasPrefix(".agents-") }) } - kill(recovery.processIdentifier, SIGKILL) - recovery.waitUntilExit() + terminateProcess(recovery) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { try fixture.store.loadResolved() } @@ -538,39 +524,59 @@ extension StateTransactionTests { defer { removeTemporaryDirectory(root) } try FileManager.default.createDirectory( at: root.appendingPathComponent(".claude/skills"), withIntermediateDirectories: true) - let child = try stateTestProcess( - root: root, arguments: ["create-scope", "directory.created..agent"]) - defer { - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } + func lockPoint(_ step: DirectoryHandle.AncestryStep) -> String { + "lock.ancestry." + step.name } + let child = try stateTestProcess( + root: root, arguments: ["create-scope", lockPoint(.created(depth: 0))]) + defer { terminateProcess(child) } try waitFor("ready", root: root, child: child) #expect( !FileManager.default.fileExists(atPath: root.appendingPathComponent("lock-acquired").path)) - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + terminateProcess(child) + // The interrupted creator's entry receives a parent barrier like every existing component. + let scope = root.appendingPathComponent(".agent") + let barriers = SynchronizationCount() var steps: [String] = [] - try FileLock.withLock( - at: root.appendingPathComponent(".agent/.agents.lock"), checkpoint: { steps.append($0) }, - { - #expect(steps.contains("directory.synced..agent")) + try DirectoryHandle.$synchronizationObserver.withValue( + { barriers.add() }, + operation: { + try FileLock.withLock( + at: scope.appendingPathComponent(".agents.lock"), checkpoint: { steps.append($0) }, + { + #expect(barriers.value == scope.resolvingSymlinksInPath().pathComponents.count - 1) + }) }) + #expect(steps.isEmpty) let new = root.appendingPathComponent("new/ancestry/.agents") - steps = [] try FileLock.withLock( at: new.appendingPathComponent(".agents.lock"), checkpoint: { steps.append($0) }, { - for name in ["new", "ancestry", ".agents"] { - let created = try #require(steps.firstIndex(of: "directory.created.\(name)")) - let synced = try #require(steps.firstIndex(of: "directory.synced.\(name)")) + for depth in 0...2 { + let created = try #require(steps.firstIndex(of: lockPoint(.created(depth: depth)))) + let synced = try #require(steps.firstIndex(of: lockPoint(.synced(depth: depth)))) #expect(created < synced) } + #expect(steps.count == 6) }) } } +private final class SynchronizationCount: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + var value: Int { + lock.lock() + defer { lock.unlock() } + return count + } + func add() { + lock.lock() + defer { lock.unlock() } + count += 1 + } +} + extension StateTransactionTests { @Test func userRecoveryBindsConfiguredTargetsAndPreservesProjectState() throws { let fixture = try TransactionFixture() @@ -592,7 +598,7 @@ extension StateTransactionTests { #expect(throws: CoreError.invalidState("interrupted user write")) { try store.withLock { let transaction = FileTransaction(store: store) { step in - if step == "publish.3.exchanged" { + if step == TransactionCheckpoint.publication(3, .exchanged).name { let journal = try String( contentsOf: store.directory.appendingPathComponent("transaction.json"), encoding: .utf8) diff --git a/Tests/AgentsCoreTests/TransactionCostTests.swift b/Tests/AgentsCoreTests/TransactionCostTests.swift index 6bfd23d..24d7200 100644 --- a/Tests/AgentsCoreTests/TransactionCostTests.swift +++ b/Tests/AgentsCoreTests/TransactionCostTests.swift @@ -5,8 +5,8 @@ import Testing @Suite("Transaction I/O cost") struct TransactionCostTests { - @Test(arguments: [false, true]) - func twoSmallFiles(_ coldDevice: Bool) throws { + /// Every commit probes its device once; existing ancestry costs one barrier per component. + @Test func twoSmallFiles() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } let store = StateStore( @@ -16,31 +16,51 @@ struct TransactionCostTests { try store.save(declaration: Declaration(), resolved: ResolvedState()) let targets = ["AGENTS.md", "GEMINI.md"].map { root.appendingPathComponent($0) } for target in targets { try Data("before".utf8).write(to: target) } - let count = TransactionIOCount() - try store.withLock { - let transaction = FileTransaction(store: store) { step in - if step.hasPrefix("journal."), step.hasSuffix(".renamed") { count.persist() } - if step.hasPrefix("directory.synced.") { count.ancestor() } - } - for target in targets { - try transaction.replace(target, content: nil, data: Data("after".utf8)) - } - try DirectoryHandle.$synchronizationObserver.withValue({ count.sync() }) { - if coldDevice { - try DirectoryHandle.$atomicRenameFailure.withValue({ _ in nil }) { - try transaction.commit() - } - } else { + let ancestry = root.resolvingSymlinksInPath().pathComponents.count - 1 + for _ in 0..<2 { + let count = TransactionIOCount() + try store.withLock { + let transaction = FileTransaction(store: store) { step in + if step.hasPrefix("journal."), step.hasSuffix(".renamed") { count.persist() } + if step == TransactionCheckpoint.probe(0, .verified).name { count.probe() } + } + for target in targets { + try transaction.replace(target, content: nil, data: Data("after".utf8)) + } + try DirectoryHandle.$synchronizationObserver.withValue({ count.sync() }) { try transaction.commit() } } + print( + "TWO_SMALL_FILES persists=\(count.persists) barriers=\(count.barriers) ancestry=\(ancestry)" + ) + #expect(count.persists == 10) + #expect(count.probes == 1) + #expect(count.barriers - ancestry == 38) + for target in targets { #expect(try Data(contentsOf: target) == Data("after".utf8)) } } - print( - "TWO_SMALL_FILES cold=\(coldDevice) persists=\(count.persists) barriers=\(count.barriers) ancestry=\(count.ancestors)" + } + + @Test func containersOnOneDeviceShareOneProbe() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment(projectDirectory: root, homeDirectory: root, environment: [:]) ) - #expect(count.persists == 10) - #expect(count.barriers - count.ancestors == (coldDevice ? 38 : 36)) - for target in targets { #expect(try Data(contentsOf: target) == Data("after".utf8)) } + try store.save(declaration: Declaration(), resolved: ResolvedState()) + var steps: [String] = [] + try store.withLock { + let transaction = FileTransaction(store: store) { steps.append($0) } + try transaction.replace( + root.appendingPathComponent("AGENTS.md"), content: nil, data: Data("after".utf8)) + try transaction.replace( + store.declarationURL, content: nil, data: StateStore.encode(Declaration(agents: [.codex]))) + try transaction.commit() + } + #expect(steps.contains(TransactionCheckpoint.containerCreated(1).name)) + #expect(steps.contains(TransactionCheckpoint.probe(0, .verified).name)) + #expect(!steps.contains(TransactionCheckpoint.probe(1, .firstCreated).name)) } } @@ -48,16 +68,16 @@ private final class TransactionIOCount: @unchecked Sendable { private let lock = NSLock() private(set) var persists = 0 private(set) var barriers = 0 - private(set) var ancestors = 0 - func ancestor() { + private(set) var probes = 0 + func persist() { lock.lock() defer { lock.unlock() } - ancestors += 1 + persists += 1 } - func persist() { + func probe() { lock.lock() defer { lock.unlock() } - persists += 1 + probes += 1 } func sync() { lock.lock() diff --git a/Tests/AgentsCoreTests/TransactionMetadataTests.swift b/Tests/AgentsCoreTests/TransactionMetadataTests.swift index 4e89ab4..cff6b3b 100644 --- a/Tests/AgentsCoreTests/TransactionMetadataTests.swift +++ b/Tests/AgentsCoreTests/TransactionMetadataTests.swift @@ -7,7 +7,10 @@ import Testing @Suite("Transaction metadata") struct TransactionMetadataTests { - @Test(arguments: ["complete", "entry.0.publishing", "entry.1.applied", "journal.committed"]) + @Test(arguments: [ + "complete", TransactionCheckpoint.progress(0, .publishing).name, + TransactionCheckpoint.progress(1, .applied).name, TransactionCheckpoint.phase(.committed).name, + ]) func dataReplacementPreservesPermissionsACLsAndExtendedAttributes(_ point: String) throws { let fixture = try TransactionFixture() let target = fixture.root.appendingPathComponent("AGENTS.md") @@ -33,7 +36,7 @@ struct TransactionMetadataTests { #expect(throws: CoreError.invalidState("injected failure")) { try transaction.commit() } } } - let committed = point == "complete" || point == "journal.committed" + let committed = point == "complete" || point == TransactionCheckpoint.phase(.committed).name #expect(try files.map(metadata) == before) #expect( try files.map { try Data(contentsOf: $0) } @@ -48,7 +51,10 @@ struct TransactionMetadataTests { try expectRecoveryMaterialRemoved(fixture) } - @Test(arguments: ["complete", "journal.committed", "cleanup.0.removed"]) + @Test(arguments: [ + "complete", TransactionCheckpoint.phase(.committed).name, + TransactionCheckpoint.containerRemoved(0).name, + ]) func committedCleanupDiscardsReadOnlyDirectories(_ point: String) throws { let fixture = try TransactionFixture() defer { makeDirectoriesWritable(fixture.root) } @@ -78,7 +84,9 @@ struct TransactionMetadataTests { } @Test(arguments: [ - "restore.3.returned", "restore.0.exchanged", "journal.rolledBack.terminal.renamed", + TransactionCheckpoint.restoration(3, .returned).name, + TransactionCheckpoint.restoration(0, .exchanged).name, + TransactionCheckpoint.persisted(.rolledBack, .terminal, .renamed).name, ]) func interruptedRollbackPreservesReadOnlyMetadata(_ point: String) throws { let fixture = try TransactionFixture() @@ -92,7 +100,7 @@ struct TransactionMetadataTests { let declaration = try Data(contentsOf: fixture.store.declarationURL) let resolved = try Data(contentsOf: fixture.store.resolvedURL) - try interrupt(fixture, command: "crash", at: "entry.4.applied") + try interrupt(fixture, command: "crash", at: TransactionCheckpoint.progress(4, .applied).name) try interrupt(fixture, command: "recover", at: point) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { try fixture.store.loadResolved() @@ -106,7 +114,11 @@ struct TransactionMetadataTests { try expectRecoveryMaterialRemoved(fixture) } - @Test(arguments: ["entry.0.publishing", "entry.0.applied", "entry.2.applied"]) + @Test(arguments: [ + TransactionCheckpoint.progress(0, .publishing).name, + TransactionCheckpoint.progress(0, .applied).name, + TransactionCheckpoint.progress(2, .applied).name, + ]) func rollbackPreservesPermissionsACLsAndExtendedAttributes(_ point: String) throws { let fixture = try TransactionFixture() let target = fixture.root.appendingPathComponent(".agents/skills/target") @@ -148,17 +160,11 @@ struct TransactionMetadataTests { private func interrupt(_ fixture: TransactionFixture, command: String, at point: String) throws { let child = try stateTestProcess(root: fixture.root, arguments: [command, point]) - defer { - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } - } + defer { terminateProcess(child) } let marker = fixture.root.appendingPathComponent( command == "recover" ? "recovery-ready" : "ready") try ProcessWait.marker(marker, child: child, root: fixture.root) - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + terminateProcess(child) #expect(child.terminationReason == .uncaughtSignal) } diff --git a/Tests/AgentsCoreTests/WatchDurabilityTests.swift b/Tests/AgentsCoreTests/WatchDurabilityTests.swift index a9d6271..8a1e126 100644 --- a/Tests/AgentsCoreTests/WatchDurabilityTests.swift +++ b/Tests/AgentsCoreTests/WatchDurabilityTests.swift @@ -1,9 +1,10 @@ -import AgentsCore import CPlatform import Foundation import StateTestSupport import Testing +@testable import AgentsCore + @Suite("Watch Git durability") struct WatchDurabilityTests { @Test( @@ -11,8 +12,10 @@ struct WatchDurabilityTests { [ "watch.mirror.fetched", "watch.references.pending", "watch.objects.synced", "watch.ref.updated", "watch.ref.synced", - "watch.mirror.synced", "entry.0.publishing", "publish.0.exchanged", - "journal.committed.terminal.renamed", "journal.committed", "journal.removed", + "watch.mirror.synced", TransactionCheckpoint.progress(0, .publishing).name, + TransactionCheckpoint.publication(0, .exchanged).name, + TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, + TransactionCheckpoint.phase(.committed).name, TransactionCheckpoint.journalRemoved.name, ]) func interruptedAcknowledgmentRetainsTheRecoveredBaseline(_ advancing: Bool, _ step: String) throws @@ -28,7 +31,10 @@ struct WatchDurabilityTests { let child = try stateTestProcess( root: fixture.root, arguments: [advancing ? "watch-seen" : "watch-add", step]) try fixture.kill(child, at: step) - let committed = step.hasPrefix("journal.committed") || step == "journal.removed" + let committed = [ + TransactionCheckpoint.persisted(.committed, .terminal, .renamed), .phase(.committed), + .journalRemoved, + ].map(\.name).contains(step) let state = try fixture.recoveredWatch() let expected = committed ? current : advancing ? first : nil #expect(state.sources[fixture.id]?.seen == expected.map(WatchSeen.revision)) @@ -230,17 +236,11 @@ final class WatchGitFixture { } func kill(_ child: Process, at step: String) throws { - defer { - if child.isRunning { - CPlatform.kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } - } + defer { terminateProcess(child) } let marker = root.appendingPathComponent("ready") try ProcessWait.marker(marker, child: child, root: root) #expect(try String(contentsOf: marker, encoding: .utf8) == step) - CPlatform.kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + terminateProcess(child) try FileManager.default.removeItem(at: marker) } } diff --git a/Tests/AgentsCoreTests/WatchGitLockTests.swift b/Tests/AgentsCoreTests/WatchGitLockTests.swift index 9dac569..fb9a4c6 100644 --- a/Tests/AgentsCoreTests/WatchGitLockTests.swift +++ b/Tests/AgentsCoreTests/WatchGitLockTests.swift @@ -46,7 +46,7 @@ struct WatchGitLockTests { CPlatform.kill(pid, SIGKILL) } } - terminate(writer) + terminateProcess(writer) } try waitFor(ready, process: writer) var locks = [ @@ -56,20 +56,20 @@ struct WatchGitLockTests { if packed { locks.append(fixture.mirror.appendingPathComponent("packed-refs.new")) } for lock in locks { try #require(FileManager.default.fileExists(atPath: lock.path)) } let reader = try stateTestProcess(root: fixture.root, arguments: ["read", ""]) - defer { terminate(reader) } + defer { terminateProcess(reader) } try waitFor(fixture.root.appendingPathComponent("reader-started"), process: reader) Thread.sleep(forTimeInterval: 0.05) #expect( !FileManager.default.fileExists( atPath: fixture.root.appendingPathComponent("reader-finished").path)) for lock in locks { #expect(FileManager.default.fileExists(atPath: lock.path)) } - terminate(reader) + terminateProcess(reader) CPlatform.kill(writer.processIdentifier, SIGSTOP) let pids = try String(contentsOf: ready, encoding: .utf8) .split(whereSeparator: \.isWhitespace).compactMap { Int32($0) } try #require(pids.count == 2) for pid in pids { CPlatform.kill(pid, SIGKILL) } - terminate(writer) + terminateProcess(writer) try FileManager.default.removeItem(at: ready) try FileManager.default.removeItem(at: hook) for lock in locks { #expect(FileManager.default.fileExists(atPath: lock.path)) } @@ -154,11 +154,4 @@ struct WatchGitLockTests { private func waitFor(_ marker: URL, process: Process) throws { try ProcessWait.marker(marker, child: process, root: marker.deletingLastPathComponent()) } - - private func terminate(_ process: Process) { - if process.isRunning { - CPlatform.kill(process.processIdentifier, SIGKILL) - process.waitUntilExit() - } - } } diff --git a/Tests/AgentsCoreTests/WatchInspectionTests.swift b/Tests/AgentsCoreTests/WatchInspectionTests.swift index 74cf813..6329af1 100644 --- a/Tests/AgentsCoreTests/WatchInspectionTests.swift +++ b/Tests/AgentsCoreTests/WatchInspectionTests.swift @@ -1,10 +1,14 @@ -import AgentsCore import Foundation import Testing +@testable import AgentsCore + @Suite("Read-only watch inspection") struct WatchInspectionTests { - @Test(arguments: ["publish.0.exchanged", "journal.committed"]) + @Test(arguments: [ + TransactionCheckpoint.publication(0, .exchanged).name, + TransactionCheckpoint.phase(.committed).name, + ]) func pendingTransactionLeavesStateUnchanged(_ step: String) throws { let fixture = try WatchGitFixture() try fixture.watch.add("source", environment: fixture.environment) @@ -24,7 +28,7 @@ struct WatchInspectionTests { #expect(try FileHash.folderHash(fixture.store.directory) == before) } - @Test(arguments: ["journal.removed", "watch.references.deleted"]) + @Test(arguments: [TransactionCheckpoint.journalRemoved.name, "watch.references.deleted"]) func pendingRefCleanupLeavesStateUnchanged(_ step: String) throws { let fixture = try WatchGitFixture() let first = try fixture.head() @@ -40,7 +44,8 @@ struct WatchInspectionTests { try #require( FileManager.default.fileExists( atPath: fixture.store.directory.appendingPathComponent("watch-refs.pending").path)) - let refs: Set = step == "journal.removed" ? [first, committed] : [committed] + let refs: Set = + step == TransactionCheckpoint.journalRemoved.name ? [first, committed] : [committed] try #require(try fixture.watchRefs() == refs) try fixture.rewrite("later") let before = try FileHash.folderHash(fixture.store.directory) diff --git a/Tests/AgentsCoreTests/WatchPreparationTests.swift b/Tests/AgentsCoreTests/WatchPreparationTests.swift new file mode 100644 index 0000000..45a969a --- /dev/null +++ b/Tests/AgentsCoreTests/WatchPreparationTests.swift @@ -0,0 +1,93 @@ +import Foundation +import Testing + +@testable import AgentsCore + +/// Watch writes take their journal preimages and lock baseline before the Git acknowledgment, +/// which can be slow; editors that ignore the scope lock may change state meanwhile. +@Suite("Watch preparation evidence") +struct WatchPreparationTests { + @Test func declarationEditedDuringAcknowledgmentIsPreserved() throws { + let fixture = try WatchGitFixture() + let watchBefore = try FileSnapshot.read(at: fixture.store.watchURL) + let edited = try StateStore.encodeState( + Declaration( + agents: [.codex], + sources: ["source": SourceDeclaration(kind: .local, location: fixture.repo.path)])) + let external = ExternalEdit() + let watch = fixture.operations { [store = fixture.store] in + try edited.write(to: store.declarationURL) + external.snapshot = try FileSnapshot.read(at: store.declarationURL) + } + #expect { + try watch.add("source", environment: fixture.environment) + } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("changed during preparation") + && reason.contains(fixture.store.declarationURL.lastPathComponent) + } + #expect(external.snapshot != nil) + #expect(try FileSnapshot.read(at: fixture.store.declarationURL) == external.snapshot) + #expect(try FileSnapshot.read(at: fixture.store.watchURL) == watchBefore) + } + + @Test func lockEditedDuringAcknowledgmentPreventsPruning() throws { + let fixture = try WatchGitFixture() + try fixture.watch.add("source", environment: fixture.environment) + let unreferenced = fixture.store.cacheDirectory.appendingPathComponent( + "artifact-content/" + String(repeating: "a", count: 64)) + try FileManager.default.createDirectory(at: unreferenced, withIntermediateDirectories: true) + try Data("unreferenced".utf8).write(to: unreferenced.appendingPathComponent("SKILL.md")) + let cached = try FileSnapshot.read(at: unreferenced) + let declaration = try FileSnapshot.read(at: fixture.store.declarationURL) + let watchBefore = try FileSnapshot.read(at: fixture.store.watchURL) + let edited = try StateStore.encodeState( + ResolvedState(sources: ["local:/edited": LockedSource(kind: .local)])) + let external = ExternalEdit() + let watch = fixture.operations { [store = fixture.store] in + try edited.write(to: store.resolvedURL) + external.snapshot = try FileSnapshot.read(at: store.resolvedURL) + } + #expect { + try watch.seen("source", environment: fixture.environment) + } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("changed during preparation") + && reason.contains(fixture.store.resolvedURL.lastPathComponent) + } + #expect(external.snapshot != nil) + #expect(try FileSnapshot.read(at: fixture.store.resolvedURL) == external.snapshot) + #expect(try FileSnapshot.read(at: unreferenced) == cached) + #expect(try FileSnapshot.read(at: fixture.store.declarationURL) == declaration) + #expect(try FileSnapshot.read(at: fixture.store.watchURL) == watchBefore) + } +} + +private final class ExternalEdit: @unchecked Sendable { + private let lock = NSLock() + private var value: FileSnapshot? + var snapshot: FileSnapshot? { + get { + lock.lock() + defer { lock.unlock() } + return value + } + set { + lock.lock() + defer { lock.unlock() } + value = newValue + } + } +} + +extension WatchGitFixture { + /// Runs `edit` once, after the Git fetch and before the scope journal is written. + fileprivate func operations(edit: @escaping @Sendable () throws -> Void) -> WatchOperations { + WatchOperations( + discoverSkills: { _ in [] }, + fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, + checkpoint: { step in + if step == "watch.mirror.fetched" { try edit() } + }) + } +} diff --git a/Tests/AgentsCoreTests/WatchReferenceTests.swift b/Tests/AgentsCoreTests/WatchReferenceTests.swift index 4d6838c..aad4deb 100644 --- a/Tests/AgentsCoreTests/WatchReferenceTests.swift +++ b/Tests/AgentsCoreTests/WatchReferenceTests.swift @@ -1,7 +1,8 @@ -import AgentsCore import Foundation import Testing +@testable import AgentsCore + @Suite("Watch Git ref retention") struct WatchReferenceTests { @Test( @@ -48,8 +49,9 @@ struct WatchReferenceTests { try fixture.rewrite("replacement") let replacement = try fixture.head() let writer = try stateTestProcess( - root: fixture.root, arguments: ["watch-seen", "publish.0.exchanged"]) - try fixture.kill(writer, at: "publish.0.exchanged") + root: fixture.root, + arguments: ["watch-seen", TransactionCheckpoint.publication(0, .exchanged).name]) + try fixture.kill(writer, at: TransactionCheckpoint.publication(0, .exchanged).name) #expect(try fixture.watchRefs() == [first, replacement]) let recovery = try stateTestProcess( root: fixture.root, arguments: ["watch-recover", "watch.references.deleted"]) diff --git a/Tests/AgentsCoreTests/WatchStateTests.swift b/Tests/AgentsCoreTests/WatchStateTests.swift index 0319960..35c8679 100644 --- a/Tests/AgentsCoreTests/WatchStateTests.swift +++ b/Tests/AgentsCoreTests/WatchStateTests.swift @@ -1,9 +1,10 @@ -import AgentsCore import CPlatform import Foundation import StateTestSupport import Testing +@testable import AgentsCore + @Suite("Watch state") struct WatchStateTests { @Test(arguments: [InstallScope.project, .user]) @@ -111,7 +112,9 @@ struct WatchStateTests { } @Test(arguments: [ - "publish.0.exchanged", "publish.1.exchanged", "journal.committed", "cleanup.0.removed", + TransactionCheckpoint.publication(0, .exchanged).name, + TransactionCheckpoint.publication(1, .exchanged).name, + TransactionCheckpoint.phase(.committed).name, TransactionCheckpoint.containerRemoved(0).name, ]) func interruptedWatchAndDeclarationRecoverTogether(_ checkpoint: String) throws { let root = try temporaryDirectory() @@ -127,18 +130,14 @@ struct WatchStateTests { try store.save(declaration: declaration, resolved: ResolvedState(), watch: WatchState()) let lockBytes = try Data(contentsOf: store.resolvedURL) let child = try stateTestProcess(root: root, arguments: ["watch-crash", checkpoint]) - defer { - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } - } + defer { terminateProcess(child) } let marker = root.appendingPathComponent("ready") try ProcessWait.marker(marker, child: child, root: root) - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + terminateProcess(child) #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.loadWatch() } - let committed = checkpoint == "journal.committed" || checkpoint == "cleanup.0.removed" + let committed = + checkpoint == TransactionCheckpoint.phase(.committed).name + || checkpoint == TransactionCheckpoint.containerRemoved(0).name #expect(try store.loadDeclaration().watch == (committed ? ["source"] : nil)) #expect(try store.loadWatch().sources.isEmpty == !committed) #expect(try Data(contentsOf: store.resolvedURL) == lockBytes) diff --git a/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift b/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift index d5a16b2..1103570 100644 --- a/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift +++ b/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift @@ -32,10 +32,7 @@ struct AutomaticSelectionTests { defer { // Release the Git wrapper even if fixture preparation fails. _ = "\n".withCString { write(descriptor, $0, 1) } - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } + terminateProcess(child) } try wait(for: child) { FileManager.default.fileExists(atPath: root.appendingPathComponent("discovery-ready").path) diff --git a/Tests/AgentsSkillsTests/CoreTestSupport.swift b/Tests/AgentsSkillsTests/CoreTestSupport.swift index 2195c9c..0210c56 100644 --- a/Tests/AgentsSkillsTests/CoreTestSupport.swift +++ b/Tests/AgentsSkillsTests/CoreTestSupport.swift @@ -1,4 +1,5 @@ import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -20,6 +21,11 @@ func removeTemporaryDirectory(_ directory: URL) { } } +/// A child that survives the termination deadline fails the test instead of blocking the run. +func terminateProcess(_ process: Process) { + do { try ProcessWait.terminate(process) } catch { Issue.record(error) } +} + func initGitRepo(_ repo: URL) throws { try ProcessRunner.run( "/usr/bin/env", arguments: ["git", "init", "--initial-branch=master", repo.path]) diff --git a/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift b/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift index 7180a42..e24e0b7 100644 --- a/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift @@ -1,9 +1,9 @@ -import AgentsCore import CPlatform import Foundation import StateTestSupport import Testing +@testable import AgentsCore @testable import AgentsSkills @Suite("Locked artifacts") @@ -176,19 +176,13 @@ extension LockedArtifactLifecycleTests { try FileManager.default.removeItem(at: store.cacheDirectory) try FileManager.default.removeItem(at: fixture.target("demo")) let child = try artifactTestProcess(root: project) - defer { - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } - } + defer { terminateProcess(child) } let marker = project.appendingPathComponent("ready") try ProcessWait.marker(marker, child: child, root: fixture.root) let final = store.cacheDirectory.appendingPathComponent( "artifact-content/" + digest.dropFirst(7)) #expect(!FileManager.default.fileExists(atPath: final.path)) - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + terminateProcess(child) let restore = WellKnownProvider { guard $0.absoluteString == url else { throw CoreError.invalidState("restore consulted index") @@ -218,7 +212,10 @@ extension LockedArtifactLifecycleTests { let process = Process() process.executableURL = directory.appendingPathComponent("StateTestProcess") process.arguments = [ - root.path, "cache-content", "stage.0.copy.entry.0.staged/SKILL.md.entryCopied", + root.path, "cache-content", + TransactionCheckpoint.copy( + 0, .init(path: TransactionScratch.staged.name(0) + "/SKILL.md", step: .entryCopied) + ).name, ] try process.run() return process diff --git a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift index 0dde41b..21a566d 100644 --- a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift +++ b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift @@ -1,4 +1,3 @@ -import AgentsCore import AgentsInstructions import AgentsSkills import CPlatform @@ -6,6 +5,8 @@ import Foundation import StateTestSupport import Testing +@testable import AgentsCore + @Suite("Read-only skill inspection") struct ReadOnlyInspectionTests { @Test(arguments: [false, true], [false, true]) @@ -97,16 +98,10 @@ struct ReadOnlyInspectionTests { at: instructions.deletingLastPathComponent(), withIntermediateDirectories: true) try Data("Original instructions\n".utf8).write(to: instructions) let child = try interruptedTransaction(root: root, scope: scope) - defer { - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } - } + defer { terminateProcess(child) } let marker = root.appendingPathComponent("ready") try ProcessWait.marker(marker, child: child, root: root) - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + terminateProcess(child) #expect(!FileManager.default.fileExists(atPath: instructions.path)) #expect(try Data(contentsOf: created) == Data("New instructions\n".utf8)) #expect(try Data(contentsOf: target.appendingPathComponent("SKILL.md")) == Data("new".utf8)) @@ -422,7 +417,8 @@ struct ReadOnlyInspectionTests { let process = Process() process.executableURL = directory.appendingPathComponent("StateTestProcess") process.arguments = [ - root.path, "inspection-transaction", "entry.4.applied", "--scope", scope.rawValue, + root.path, "inspection-transaction", TransactionCheckpoint.progress(4, .applied).name, + "--scope", scope.rawValue, ] try process.run() return process diff --git a/Tests/AgentsSkillsTests/TransactionDoctorTests.swift b/Tests/AgentsSkillsTests/TransactionDoctorTests.swift index c78bc20..3371d58 100644 --- a/Tests/AgentsSkillsTests/TransactionDoctorTests.swift +++ b/Tests/AgentsSkillsTests/TransactionDoctorTests.swift @@ -17,13 +17,13 @@ struct TransactionDoctorTests { #expect(throws: CoreError.invalidState("interrupt after removing preimage")) { try store.withLock { let transaction = FileTransaction(store: store) { point in - if point == "entry.0.applied" { + if point == TransactionCheckpoint.progress(0, .applied).name { let journal = try StateStore.decode( Data(contentsOf: store.directory.appendingPathComponent("transaction.json")), as: TransactionJournal.self) let backup = target.deletingLastPathComponent().appendingPathComponent( journal.containerName(0) - ).appendingPathComponent("entry.0.staged") + ).appendingPathComponent(TransactionScratch.exchanged.name(0)) try FileManager.default.moveItem(at: backup, to: saved) throw CoreError.invalidState("interrupt after removing preimage") } diff --git a/Tests/AgentsSkillsTests/UpdateReportingTests.swift b/Tests/AgentsSkillsTests/UpdateReportingTests.swift index 98d8b35..10138a2 100644 --- a/Tests/AgentsSkillsTests/UpdateReportingTests.swift +++ b/Tests/AgentsSkillsTests/UpdateReportingTests.swift @@ -126,7 +126,7 @@ struct UpdateReportingTests { } else { let retained = try plan.retain() let transaction = FileTransaction(store: store) { step in - if step == "stage.0.constructed" { + if step == TransactionCheckpoint.stage(0, .constructed).name { let parent = fixture.target("demo").deletingLastPathComponent() let staged = try #require( FileManager.default.contentsOfDirectory( @@ -134,14 +134,16 @@ struct UpdateReportingTests { includingPropertiesForKeys: nil ).first { $0.lastPathComponent.hasPrefix(".agents-") } ) - .appendingPathComponent("entry.0.staged") + .appendingPathComponent(TransactionScratch.exchanged.name(0)) try FileManager.default.setAttributes( [.posixPermissions: 0o755], ofItemAtPath: staged.appendingPathComponent("SKILL.md").path) } } try plan.stage(retained: retained, transaction: transaction) - #expect(throws: CoreError.self) { try transaction.commit() } + #expect(throws: CoreError.invalidState("staged content executable mode mismatch")) { + try transaction.commit() + } } } #expect(try fixture.stateAndTargetBytes() == before) diff --git a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift index cc43566..c88f485 100644 --- a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift +++ b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift @@ -1,9 +1,9 @@ -import AgentsCore import AgentsInstructions import AgentsSkills import Foundation import Testing +@testable import AgentsCore @testable import AgentsUpdates @Suite("Combined updates") @@ -180,7 +180,9 @@ struct CombinedUpdateTests { environment: fixture.environment, checkpoint: { step in // Pruning is queued after both kinds and the merged state; rollback restores it too. - if step == "journal.committed.terminal.renamed" { return } + if step == TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name { + return + } if step.hasPrefix("entry."), step.hasSuffix(".applied"), !FileManager.default.fileExists(atPath: unused.path) { @@ -335,7 +337,7 @@ struct CombinedUpdateTests { try UpdateOperations.withPreparedUpdate( environment: fixture.environment, checkpoint: { step in - if step == "stage.0.constructed" { + if step == TransactionCheckpoint.stage(0, .constructed).name { let file = cache.appendingPathComponent("skills/demo/run.sh") if dimension == "bytes" { try fixture.write("corrupt", to: file) @@ -363,7 +365,7 @@ struct CombinedUpdateTests { var journals = 0 let receipt = try UpdateOperations.withPreparedUpdate( scope: scope, environment: fixture.environment, - checkpoint: { if $0 == "journal.preparing" { journals += 1 } }, + checkpoint: { if $0 == TransactionCheckpoint.phase(.preparing).name { journals += 1 } }, { update in #expect(update.report == preview) #expect(try fixture.snapshot() == before) diff --git a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift index 3d8f61f..3eca652 100644 --- a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift +++ b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift @@ -1,10 +1,10 @@ -import AgentsCore import AgentsSkills import CPlatform import Foundation import StateTestSupport import Testing +@testable import AgentsCore @testable import AgentsUpdates @Suite("Combined update transactions") @@ -20,7 +20,7 @@ struct UpdateTransactionTests { _ = try UpdateOperations.withPreparedUpdate( environment: fixture.environment, checkpoint: { step in - if step == "entry.0.applied" { + if step == TransactionCheckpoint.progress(0, .applied).name { // Exchange a journal-bound root so every automatic recovery attempt must stop. try FileManager.default.moveItem(at: root, to: moved) try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) @@ -51,9 +51,11 @@ struct UpdateTransactionTests { } @Test(arguments: [ - "between-kinds", "journal.preparing", "journal.applying.entry.0.publishing.renamed", - "journal.committed.terminal.renamed", "journal.committed", "cleanup.0.removed", - "journal.removed", + "between-kinds", TransactionCheckpoint.phase(.preparing).name, + TransactionCheckpoint.persisted(.applying, .entry(0, .publishing), .renamed).name, + TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, + TransactionCheckpoint.phase(.committed).name, TransactionCheckpoint.containerRemoved(0).name, + TransactionCheckpoint.journalRemoved.name, ]) func failuresReportTheRecoveredGeneration(_ failure: String) throws { let fixture = try UpdateFixture() @@ -70,11 +72,12 @@ struct UpdateTransactionTests { _ = try UpdateOperations.withPreparedUpdate( environment: fixture.environment, checkpoint: { step in - if step == "journal.preparing" { + if step == TransactionCheckpoint.phase(.preparing).name { lastSkill = try lastSkillIndex(fixture.store) } if step == failure - || (failure == "between-kinds" && step == lastSkill.map { "entry.\($0).applied" }) + || (failure == "between-kinds" + && step == lastSkill.map { TransactionCheckpoint.progress($0, .applied).name }) { failed = true throw CoreError.invalidState("injected update failure") @@ -83,9 +86,7 @@ struct UpdateTransactionTests { { try $0.apply() }) Issue.record("failure checkpoint was not reached") } catch let error as UpdateApplyError { - let committed = - failure.hasPrefix("journal.committed") || failure == "cleanup.0.removed" - || failure == "journal.removed" + let committed = committedPoints.contains(failure) #expect(error.disposition == (committed ? .committed : .unchanged)) #expect(error.underlyingError as? CoreError == .invalidState("injected update failure")) if committed { @@ -102,8 +103,10 @@ struct UpdateTransactionTests { } @Test(arguments: [ - "between-kinds", "journal.preparing", "journal.applying.entry.0.publishing.renamed", - "journal.committed.terminal.renamed", "cleanup.0.removed", + "between-kinds", TransactionCheckpoint.phase(.preparing).name, + TransactionCheckpoint.persisted(.applying, .entry(0, .publishing), .renamed).name, + TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, + TransactionCheckpoint.containerRemoved(0).name, ]) func killedCombinedWriterRecoversThenPreparesTheWholeUpdate(_ checkpoint: String) throws { let fixture = try UpdateFixture() @@ -120,7 +123,7 @@ struct UpdateTransactionTests { #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { try fixture.apply() } - let committed = checkpoint.hasPrefix("journal.committed") || checkpoint == "cleanup.0.removed" + let committed = committedPoints.contains(checkpoint) if !committed { #expect(try fixture.snapshot() == before) } var displayed = 0 _ = try UpdateOperations.withPreparedUpdate(environment: fixture.environment) { update in @@ -150,11 +153,12 @@ struct UpdateTransactionTests { #expect( !FileManager.default.fileExists( atPath: fixture.root.appendingPathComponent("contender-finished").path)) + try ProcessWait.stopped(prepared, root: fixture.root) kill(prepared.processIdentifier, SIGCONT) - prepared.waitUntilExit() + try ProcessWait.exit(prepared, root: fixture.root) #expect(prepared.terminationStatus == 0) try waitFor("contender-finished", fixture: fixture, child: contender) - contender.waitUntilExit() + try ProcessWait.exit(contender, root: fixture.root) #expect(contender.terminationStatus == 0) } @@ -198,6 +202,12 @@ private func lastSkillIndex(_ store: StateStore) throws -> Int { private final class UpdateTestBundle: NSObject {} +/// Interruptions at or after the terminal commit marker. +private let committedPoints = [ + TransactionCheckpoint.persisted(.committed, .terminal, .renamed), .phase(.committed), + .containerRemoved(0), .journalRemoved, +].map(\.name) + private func launch(_ fixture: UpdateFixture, command: String, argument: String) throws -> Process { var directory = Bundle(for: UpdateTestBundle.self).bundleURL while !FileManager.default.isExecutableFile( @@ -218,9 +228,7 @@ private func waitFor(_ name: String, fixture: UpdateFixture, child: Process) thr try ProcessWait.marker(file, child: child, root: fixture.root) } +/// A child that survives the termination deadline fails the test instead of blocking the run. private func terminate(_ process: Process) { - if process.isRunning { - kill(process.processIdentifier, SIGKILL) - process.waitUntilExit() - } + do { try ProcessWait.terminate(process) } catch { Issue.record(error) } } diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 8bd3881..f28133d 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -18,21 +18,19 @@ let store = StateStore( homeDirectory: root.appendingPathComponent("home"), environment: ["CLAUDE_CONFIG_DIR": root.appendingPathComponent("configured-claude").path])) let checkpointState = Mutex( - (requested: arguments.count > 3 ? arguments[3] : "", counts: [String: Int]())) + (requested: arguments.count > 3 ? arguments[3] : "", seen: Set())) let traceURL = root.appendingPathComponent( "checkpoint-\(ProcessInfo.processInfo.processIdentifier).log") FileManager.default.createFile(atPath: traceURL.path, contents: nil) let trace = try FileHandle(forWritingTo: traceURL) -func stop(_ step: String, marker: String = "ready") throws { - let normalized = step.replacingOccurrences(of: root.lastPathComponent, with: "$ROOT") - let (point, shouldStop) = checkpointState.withLock { state in - state.counts[normalized, default: 0] += 1 - let count = state.counts[normalized]! - let point = count == 1 ? normalized : normalized + "#\(count)" - return (point, point == state.requested) +/// A repeated name would make a kill point ambiguous, so the recorder fails the run. +func stop(_ point: String, marker: String = "ready") throws { + let (repeated, shouldStop) = checkpointState.withLock { state in + (!state.seen.insert(point).inserted, point == state.requested) } try trace.write(contentsOf: Data((point + "\n").utf8)) - if step.hasPrefix("journal."), step.hasSuffix(".renamed"), + if repeated { fatalError("repeated checkpoint: \(point)") } + if point.hasPrefix("journal."), point.hasSuffix(".renamed"), let bytes = try? Data(contentsOf: store.directory.appendingPathComponent("transaction.json")) { try bytes.write(to: root.appendingPathComponent("last-journal")) @@ -195,7 +193,10 @@ if arguments[2] == "git-environment" { try transaction.replace( root.appendingPathComponent("GEMINI.md"), content: nil, data: Data("auxiliary postimage".utf8)) - let target = root.appendingPathComponent("AGENTS.md") + let target = + arguments[4] == "crossParentReplace" + ? root.appendingPathComponent(".agents/skills/target") + : root.appendingPathComponent("AGENTS.md") switch arguments[4] { case "directoryReplace": let source = root.appendingPathComponent("new") @@ -259,6 +260,12 @@ if arguments[2] == "git-environment" { default: _ = try store.loadResolved() } try Data().write(to: root.appendingPathComponent("contender-finished")) +} else if arguments[2] == "pause" { + try stop("paused") +} else if arguments[2] == "unstopped-marker" { + // The marker exists but the process never stops, as when it is killed before its self-stop. + try Data().write(to: root.appendingPathComponent("ready"), options: .atomic) + while true { sleep(1) } } else if arguments[2] == "create-scope" { try FileLock.withLock( at: store.directory.appendingPathComponent(".agents.lock"), checkpoint: { try stop($0) }, diff --git a/Tests/StateTestSupport/ProcessWait.swift b/Tests/StateTestSupport/ProcessWait.swift index 0b5e745..690a659 100644 --- a/Tests/StateTestSupport/ProcessWait.swift +++ b/Tests/StateTestSupport/ProcessWait.swift @@ -15,6 +15,43 @@ package enum ProcessWait { child.waitUntilExit() } + /// A checkpoint writes its marker before raising SIGSTOP. Signals sent before the stop takes + /// effect can be lost, so a paused child is resumed or killed only after this returns. + package static func stopped(_ child: Process, root: URL, timeout: TimeInterval = 120) throws { + try until(child, root: root, timeout: timeout, description: "process stop") { + isStopped(child.processIdentifier) + } + } + + /// `WNOWAIT` leaves the stop reportable; Foundation reaps only exits. + private static func isStopped(_ processIdentifier: Int32) -> Bool { + var info = siginfo_t() + guard waitid(P_PID, id_t(processIdentifier), &info, WSTOPPED | WNOHANG | WNOWAIT) == 0 else { + return false + } + return info.si_signo == SIGCHLD && info.si_code == Int32(CLD_STOPPED) + } + + /// SIGKILL can be lost while a child is stopping itself, so it is resent until the exit is + /// observed. The deadline bounds the whole termination. + package static func terminate( + _ child: Process, timeout: TimeInterval = 30, retry: TimeInterval = 0.2, + send: (Int32) -> Void = { _ = kill($0, SIGKILL) } + ) throws { + let deadline = Date().addingTimeInterval(timeout) + while child.isRunning { + guard Date() < deadline else { + throw WaitFailure( + message: + "Process \(child.processIdentifier) survived SIGKILL for \(timeout) seconds") + } + send(child.processIdentifier) + let resend = min(deadline, Date().addingTimeInterval(retry)) + while child.isRunning, Date() < resend { Thread.sleep(forTimeInterval: 0.005) } + } + child.waitUntilExit() + } + package static func condition(_ child: Process, root: URL, description: String, ready: () -> Bool) throws { From 48148bfb71ee8936fc83809696103d8ea8ba6e93 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 30 Oct 2026 22:11:06 +0800 Subject: [PATCH 020/171] refactor(state): name transaction slots and disposal consistently Rename recovery slots and the disposal phase consistently across the journal, checkpoints and documentation, and give each recovery rule one home. Transactions now take a single content source and one requireUnchanged(since:) precondition hook. Make every checkpoint unique within a recorded process. Cover directory-mode restoration in the default kill-point matrix, and require each recovery seed to reach its representative points. --- Documentation/Architecture/Package.md | 3 +- Documentation/Architecture/State.md | 74 ++-- README.md | 18 +- Sources/AgentsCore/DirectoryHandle.swift | 73 ++-- Sources/AgentsCore/FileLock.swift | 24 +- Sources/AgentsCore/FileTransaction.swift | 326 +++--------------- Sources/AgentsCore/SourceCache.swift | 53 +-- Sources/AgentsCore/StateInspection.swift | 5 +- Sources/AgentsCore/StateStore.swift | 13 +- .../AgentsCore/TransactionCheckpoint.swift | 32 +- Sources/AgentsCore/TransactionDisposal.swift | 55 +-- Sources/AgentsCore/TransactionEvidence.swift | 10 +- Sources/AgentsCore/TransactionJournal.swift | 63 +++- Sources/AgentsCore/TransactionPaths.swift | 16 +- .../AgentsCore/TransactionPermissions.swift | 36 +- .../AgentsCore/TransactionPublication.swift | 228 ++++++++++++ Sources/AgentsCore/TransactionRecovery.swift | 68 ++-- Sources/AgentsCore/TransactionSession.swift | 36 +- Sources/AgentsCore/UpdatePreconditions.swift | 8 +- Sources/AgentsCore/WatchOperations.swift | 21 +- .../InstructionOperations.swift | 16 +- .../InstructionUpdatePlan.swift | 8 +- Sources/AgentsSkills/SkillLifecycle.swift | 17 +- Sources/AgentsSkills/SkillOperations.swift | 7 +- Sources/AgentsSkills/SkillUpdatePlan.swift | 2 +- Sources/AgentsUpdates/UpdatePlan.swift | 8 +- .../CachePublicationTests.swift | 10 +- .../CheckpointUniquenessTests.swift | 132 +++++++ .../InstructionTransactionTests.swift | 7 +- .../PreparationEvidenceTests.swift | 33 +- .../ProcessTerminationTests.swift | 13 +- Tests/AgentsCoreTests/PublicationTests.swift | 149 +++++--- .../StateTransactionTests.swift | 58 ++-- .../TransactionCostTests.swift | 11 +- .../TransactionMetadataTests.swift | 2 +- Tests/AgentsCoreTests/WatchGitLockTests.swift | 4 +- .../WatchInspectionTests.swift | 2 +- .../WatchPreparationTests.swift | 25 +- .../AgentsCoreTests/WatchReferenceTests.swift | 6 +- .../LockedArtifactLifecycleTests.swift | 2 +- .../TransactionDoctorTests.swift | 6 +- .../UpdateReportingTests.swift | 2 +- Tests/StateTestProcess/main.swift | 79 +++-- Tests/StateTestSupport/ProcessWait.swift | 3 +- 44 files changed, 1020 insertions(+), 744 deletions(-) create mode 100644 Sources/AgentsCore/TransactionPublication.swift create mode 100644 Tests/AgentsCoreTests/CheckpointUniquenessTests.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 2346b4c..ee2a62d 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -66,7 +66,8 @@ CryptoKit on Apple platforms and supplies its own implementation on Linux. `StateTestSupport` supplies the shared process-handshake deadline and diagnostics for transaction, watch and update tests. `StateTestProcess` records actual checkpoints and supports interruption and resumed recovery through the production -journal protocol. +journal protocol. Its recorder fails on a repeated name, so repeated work numbers +its checkpoints and nested transactions prefix theirs. ## AgentsDescription and AgentsManifest diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index 4947806..2826a48 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -164,7 +164,7 @@ the denial. Existing user content and metadata are preserved. Journal format version 1 is independent of declaration, lock and watch versions. The root records its version, transaction UUID, scope identity, registered root -identities, transaction phase, operations, private containers and discard +identities, transaction phase, operations, private containers and disposal intent. A journal without this version, or with another version, is retained unchanged. Recovery reports that it was written by another version and must be recovered with the version that wrote it; it does not guess a compatible replay. @@ -190,7 +190,7 @@ mode 0700 on the same filesystem as its targets. The journal records the name before `mkdir`, then records the container's physical identity before inserting anything. Probes, extraction work and staging stay inside it. An identified container owns all construction before publication: incomplete objects can be -discarded as a whole without individual ownership evidence. Another writer has +disposed of as a whole without individual ownership evidence. Another writer has no ownership claim on content inserted into this private transaction storage. An unidentified container may only be removed with `rmdir` when empty; a nonempty one is an unresolved conflict. @@ -201,14 +201,15 @@ hash and executable flags. `ready` and that snapshot become durable together. Changes after sealing are conflicts; recovery never refreshes a sealed snapshot to adopt changed content. -Preimages displaced by exchange, deletion quarantines and published objects are +Container entries are named by operation index and slot. `staged` holds a +creation's private staging. `exchanged` holds an exchange's private staging +until publication, then the displaced preimage, and after undo the published +object exchanged back out. `deleted` holds the object a deletion moved aside, +and `withdrawn` holds a published creation that undo moved aside. Displaced +preimages, the contents of `deleted` and `withdrawn`, and published objects are user data. Their identity and digest remain mandatory evidence even inside a -private container. Container entries are named by operation index and what they -hold: `staged` is a creation's private staging, `exchanged` holds an exchange's -staging until publication and then the displaced preimage, `deleted` holds a -deleted object and `withdrawn` holds a creation that undo moved aside. A -container holding such recovery objects receives complete terminal disposal -evidence after their expected distribution has been verified. +private container. A container holding such slot objects receives complete +terminal disposal evidence after their expected distribution has been verified. | Progress | Durable evidence and possible distribution | | --- | --- | @@ -217,13 +218,13 @@ evidence after their expected distribution has been verified. | `publishing` | Publication and temporary directory-write intent; objects can be prepared or installed. | | `applied` | Rename parents and original directory modes synced; postimage and preimage verified. | | `restoring` | Undo and temporary directory-write intent; installed or reverted objects can be present. | -| `restored` | Undo parents and original modes synced; restored target and rollback quarantine verified. | +| `restored` | Undo parents and original modes synced; restored target and remaining slot objects verified. | | `cancelled` | Original modes restored; publication did not consume private staging. | One operation-type/progress table defines every expected target and recovery slot. Publication validation, rollback classification and disposal preparation -use that table. Before durable discard intent, an expected preimage or rollback -quarantine must exist and match; absence cannot be treated as completed cleanup. +use that table. Before durable disposal intent, every expected slot object must +exist and match; absence cannot be treated as completed disposal. Journal publication orders the new journal file barrier before rename, then the parent directory barrier. Ordinary preimage files are synced once with their @@ -251,7 +252,7 @@ and system reason. Probes and publication use the same classification. | --- | --- | | Absent | Persist the sealed inode and digest, then move it from the container with Darwin `renameatx_np(RENAME_EXCL)` or Linux `renameat2(RENAME_NOREPLACE)`. A concurrent creator keeps its bytes and inode. | | Existing | Recheck the preimage, then exchange it with staging using Darwin `RENAME_SWAP` or Linux `RENAME_EXCHANGE`. The displaced object stays inside the container and is compared before confirmation. A mismatched preimage is retained as a conflict. | -| Deletion | Move the entry without replacement into the container's quarantine, then verify its physical identity and digest. Destructive cleanup verifies that evidence again. | +| Deletion | Move the entry without replacement into the container's `deleted` slot, then verify its physical identity and digest. Disposal verifies that evidence again. | Each operation checks its preimage before and again after its publication intent becomes durable; a preparation already stale before the intent cancels from @@ -282,21 +283,22 @@ watch reconciliation can release any ref. Pending watch-reference recovery also reports `CoreError.transactionRecovered` when no journal remains. Retained refs remain available while a journal conflict is unresolved. -Recovery treats any observed journal as possibly renamed without its directory -barrier: before granting permissions, renaming objects or deleting any resource -it syncs `transaction.json` and its parent, including on retry. An applying -journal reverses verified publications in reverse order. A committed journal -completes terminal cleanup. Physical identity and digest distinguish a -transaction's publication even after rename but before `applied`. Another inode -with identical bytes remains external. Missing or changed evidence causes an -unresolved conflict; names and equal bytes never establish ownership. Other -verified operations can roll back while conflicted objects remain available. +Recovery treats any observed `transaction.json` as possibly renamed without its +directory barrier: before granting permissions, renaming objects or deleting any +resource it syncs that file and its parent, including on retry. A lone unstarted +`transaction.new` owns no object and is discarded directly. An applying journal +reverses verified publications in reverse order. A committed journal completes +terminal disposal. Physical identity and digest distinguish a transaction's +publication even after rename but before `applied`. Another inode with identical +bytes remains external. Missing or changed evidence causes an unresolved +conflict; names and equal bytes never establish ownership. Other verified +operations can roll back while conflicted objects remain available. Replacement undo exchanges a retained preimage only with the verified published object and verifies the displaced object. An external replacement before or during undo leaves both available versions and stops recovery. Deleted entries return with no-replace rename, preserving an occupied original name. Creation -undo moves only a verified published object into rollback quarantine and checks +undo moves only a verified published object into its `withdrawn` slot and checks it there. A retry recognizing an interrupted reverse rename repeats both parent barriers before recording restoration. @@ -310,19 +312,19 @@ original mode and intent retained. Before disposal the journal persists terminal `committed` or `rolledBack` state and the complete recovery-object evidence. A commit disposes immediately after sealing that evidence; recovery first revalidates every target and container -against it. A separate global discard intent then becomes durable. Only after -that intent may missing objects or descendants mean interrupted cleanup. Changed -identities, digests or unexpected descendants in sealed disposal evidence remain -conflicts. Unpublished private construction is discarded by verified container -identity. Links are never followed during deletion. Owner access may be granted -to discarded directories without changing installed or restored metadata. Absent -entries still receive a parent barrier. +against it. A separate global disposal intent then becomes durable. Only after +that intent may missing objects or descendants mean interrupted disposal. +Changed identities, digests or unexpected descendants in sealed disposal +evidence remain conflicts. Unpublished private construction is disposed of by +verified container identity. Links are never followed during deletion. Owner +access may be granted to directories being disposed of without changing +installed or restored metadata. Absent entries still receive a parent barrier. Conflicts retain `transaction.json`, the available target objects and private -containers holding displaced preimages or rollback quarantines. Each conflicting -entry records the reason and scope-relative recovery locations. Doctor lists -those reasons and locations and asks for owner action; it does not promise that -another write will resolve them or provide a conflict-resolution command. +containers holding user data in their slots. Each conflicting entry records the +reason and scope-relative recovery locations. Doctor lists those reasons and +locations and asks for owner action; it does not promise that another write will +resolve them or provide a conflict-resolution command. Recovery can itself be interrupted and repeated. Successful recovery reports `CoreError.transactionRecovered` and callers retry the whole preparation. @@ -418,7 +420,7 @@ private journal-owned staging. Exact Git commits are extracted there; expanded artifacts are checked against their locked tree hash. Copied trees are hashed through pinned directory descriptors and verified before publication. Files, metadata and directory entries are synced before atomic publication of the final -cache name. Git extraction scratch also belongs to the journal, so recovery +cache name. Git extraction work also belongs to the journal, so recovery cleans an incomplete copy or extraction without retaining a partial final directory just because the lock references its pin. Cache publication completes before the installation transaction references that content. @@ -495,7 +497,7 @@ sections or prompt sections remain cached, as do artifact contents referenced by watch state and trees containing live edit sources. Pruning opens directory ancestry without following symlinks and uses directory-relative enumeration, rename and deletion. It rejects symlinked cache containers and never recursively -follows a link during cleanup. Mirrors remain available for source history and +follows a link during deletion. Mirrors remain available for source history and future resolution. Watch-owned Git refs retain only revisions still referenced by watch state or installed pins; obsolete histories can be collected by Git after those refs are released. diff --git a/README.md b/README.md index 62c7a08..94de54e 100644 --- a/README.md +++ b/README.md @@ -306,9 +306,9 @@ swift format lint --strict --configuration .swift-format \ --recursive Package.swift Sources Tests ``` -Publication kill-point tests, tagged `publicationMatrix`, kill each operation at -representative points and recovery from every seed at its durable steps. When -changing the transaction protocol, also run every recorded point: +By default, publication tests kill each operation at representative points, and +kill recovery at durable steps from each seeded interruption. When changing the +transaction protocol, also kill at every recorded point: ```bash env -u CODEX_HOME -u CLAUDE_CONFIG_DIR -u XDG_CONFIG_HOME \ @@ -321,11 +321,13 @@ full-SHA-pinned reusable workflows from `agents-tools/github-workflows`. Source policy validates PR titles, new commit messages and added lines. [Package validation configuration](.github/swift-package.json) selects Xcode 26.6 on `macos-26` and a digest-pinned official Swift Linux container. macOS and -Linux validation run the full Debug and Release test suites. macOS also runs a -release build and strict formatting with `.swift-format` over `Package.swift`, -`Sources` and `Tests`. The test suites include subprocess recovery tests. The -configuration owns the Linux compiler version and image digest. Tests also -require Perl, which is included by the Linux image's Git dependencies. +Linux validation run the Debug and Release test suites with the default +publication matrix; the full publication matrix is not part of CI. macOS also +runs a release build and strict formatting with `.swift-format` over +`Package.swift`, `Sources` and `Tests`. The test suites include subprocess +recovery tests. The configuration owns the Linux compiler version and image +digest. Tests also require Perl, which is included by the Linux image's Git +dependencies. Render and check the committed [social preview](.github/assets/social-preview/social-preview.png) locally with diff --git a/Sources/AgentsCore/DirectoryHandle.swift b/Sources/AgentsCore/DirectoryHandle.swift index 0f205cc..6cd9964 100644 --- a/Sources/AgentsCore/DirectoryHandle.swift +++ b/Sources/AgentsCore/DirectoryHandle.swift @@ -132,7 +132,7 @@ final class DirectoryHandle { let step: RemovalStep } - /// Missing descendants are accepted only by callers with a durable discard intent. + /// Missing descendants are accepted only by callers with a durable disposal intent. /// Private trees and verified user objects share the same descriptor-relative deleter. func remove( _ name: String, expecting expected: FileSnapshot? = nil, @@ -154,21 +154,21 @@ final class DirectoryHandle { guard let info = try info(name) else { return } let observed = FileObjectIdentity(info) if let identity, observed != identity { - throw CoreError.invalidState("transaction cleanup identity changed: \(name)") + throw CoreError.invalidState("removal identity changed: \(name)") } if let expected, observed != expected.identity { - throw CoreError.invalidState("transaction cleanup ownership changed: \(name)") + throw CoreError.invalidState("removal ownership changed: \(name)") } if info.st_mode & S_IFMT == S_IFDIR { let directory = try child(name) if info.st_mode & S_IRWXU != S_IRWXU { guard fchmod(directory.descriptor, (info.st_mode & 0o7777) | S_IRWXU) == 0 else { - throw CoreError.unsafePath("cannot make discarded directory writable: \(name)") + throw CoreError.unsafePath("cannot make removed directory writable: \(name)") } } for child in try directory.names() { if let expected, expected.children?[child] == nil { - throw CoreError.invalidState("unexpected transaction descendant: \(child)") + throw CoreError.invalidState("unexpected descendant during removal: \(child)") } try directory.removeContents( child, expected: expected?.children?[child], identity: nil, @@ -176,22 +176,24 @@ final class DirectoryHandle { } try directory.sync() } else if let expected, try FileSnapshot.read(name, from: self) != expected { - throw CoreError.invalidState("transaction cleanup content changed: \(name)") + throw CoreError.invalidState("removal content changed: \(name)") } guard try self.info(name).map(FileObjectIdentity.init) == observed else { - throw CoreError.invalidState("transaction cleanup identity changed: \(name)") + throw CoreError.invalidState("removal identity changed: \(name)") } guard unlinkat(descriptor, name, info.st_mode & S_IFMT == S_IFDIR ? AT_REMOVEDIR : 0) == 0 else { - throw CoreError.invalidState("cannot discard filesystem entry: \(name): \(errno)") + throw CoreError.invalidState("cannot remove filesystem entry: \(name): \(errno)") } try checkpoint(RemovalPoint(path: prefix, step: .unlinked)) } - /// Only an empty unidentified container may be removed; rmdir never erases contents. + /// rmdir never erases contents; an absent entry still receives the parent barrier. func removeEmptyDirectory(_ name: String) throws { guard unlinkat(descriptor, name, AT_REMOVEDIR) == 0 || errno == ENOENT else { - throw CoreError.invalidState("unidentified transaction container is not empty: \(name)") + let code = errno + throw CoreError.invalidState( + "cannot remove directory: \(name): \(code) (\(String(cString: strerror(code))))") } try sync() } @@ -249,10 +251,17 @@ final class DirectoryHandle { enum PermissionStep: String { case changed, synced } /// Only the lease's recorded directory inode may receive its temporary owner-write bit. - func setPermissions( - _ lease: DirectoryWriteLease, granting: Bool, checkpoint: (PermissionStep) throws -> Void + func grant(_ lease: DirectoryWriteLease, checkpoint: (PermissionStep) throws -> Void) throws { + try setPermissions(lease.grantedMode, lease: lease, checkpoint: checkpoint) + } + + func restore(_ lease: DirectoryWriteLease, checkpoint: (PermissionStep) throws -> Void) throws { + try setPermissions(lease.originalMode, lease: lease, checkpoint: checkpoint) + } + + private func setPermissions( + _ mode: mode_t, lease: DirectoryWriteLease, checkpoint: (PermissionStep) throws -> Void ) throws { - let mode = granting ? lease.grantedMode : lease.original let current = try checkedPermissions(lease) if current != mode { guard fchmod(descriptor, mode) == 0 else { @@ -356,7 +365,9 @@ final class DirectoryHandle { } @discardableResult - func makeDirectory(_ name: String, syncParent: Bool = true) throws -> DirectoryHandle { + func makeDirectory( + _ name: String, syncParent: Bool = true, afterCreate: () throws -> Void = {} + ) throws -> DirectoryHandle { if try info(name) != nil { try FileSystem.requireAccess( R_OK | W_OK | X_OK, at: url.appendingPathComponent(name), parent: descriptor) @@ -368,6 +379,7 @@ final class DirectoryHandle { } try FileSystem.requireAccess( R_OK | W_OK | X_OK, at: url.appendingPathComponent(name), parent: descriptor) + try afterCreate() let directory = try child(name) guard fchmod(directory.descriptor, 0o700) == 0 else { throw CoreError.invalidState("cannot set directory permissions") @@ -433,33 +445,36 @@ final class DirectoryHandle { if syncParent { try sync() } } - func writeJournal(_ data: Data, afterWrite: () throws -> Void, afterRename: () throws -> Void) - throws - { - if try info("transaction.new") != nil { - _ = try read("transaction.new") - guard unlinkat(descriptor, "transaction.new", 0) == 0 else { - throw CoreError.invalidState("cannot remove incomplete journal: \(errno)") + /// Writes and syncs `staging`, then replaces `name` with an ordinary rename and syncs this + /// directory. Only the journal is replaced this way; publication exchanges or never replaces. + func replaceFile( + _ name: String, through staging: String, with data: Data, afterWrite: () throws -> Void, + afterRename: () throws -> Void + ) throws { + if try info(staging) != nil { + _ = try read(staging) + guard unlinkat(descriptor, staging, 0) == 0 else { + throw CoreError.invalidState("cannot remove \(staging): \(errno)") } } - try write("transaction.new", data: data, syncParent: false) + try write(staging, data: data, syncParent: false) try afterWrite() - // A replacing rename is reserved for the journal; publication exchanges or never replaces. - guard renameat(descriptor, "transaction.new", descriptor, "transaction.json") == 0 else { - throw CoreError.invalidState("cannot replace transaction.json: \(errno)") + guard renameat(descriptor, staging, descriptor, name) == 0 else { + throw CoreError.invalidState("cannot replace \(name): \(errno)") } try afterRename() try sync() } - func removeJournal(afterUnlink: () throws -> Void = {}) throws { - for name in ["transaction.new", "transaction.json"] { + /// Unlinks each present regular file in order, then syncs this directory once. + func removeFiles(_ names: [String], afterUnlink: (String) throws -> Void = { _ in }) throws { + for name in names { if try info(name) != nil { _ = try read(name) guard unlinkat(descriptor, name, 0) == 0 else { - throw CoreError.invalidState("cannot remove journal: \(errno)") + throw CoreError.invalidState("cannot remove \(name): \(errno)") } - if name == "transaction.json" { try afterUnlink() } + try afterUnlink(name) } } try sync() diff --git a/Sources/AgentsCore/FileLock.swift b/Sources/AgentsCore/FileLock.swift index 9e99a00..35af712 100644 --- a/Sources/AgentsCore/FileLock.swift +++ b/Sources/AgentsCore/FileLock.swift @@ -1,7 +1,26 @@ import CPlatform import Foundation +import Synchronization package enum FileLock { + /// Contended acquisitions are numbered within the process, so every wait has its own + /// checkpoint name. The ordinal only names checkpoints; it never changes locking. + private static let contentions = Atomic(0) + + static func ancestryCheckpoint(_ step: DirectoryHandle.AncestryStep) -> String { + "lock.ancestry." + step.name + } + + private static func contentionCheckpoint(_ ordinal: Int) -> String { + "lock.\(ordinal).contended" + } + + package static func isContentionCheckpoint(_ name: String) -> Bool { + let parts = name.split(separator: ".", omittingEmptySubsequences: false) + return parts.count >= 3 && parts[parts.count - 3] == "lock" && parts.last == "contended" + && Int(parts[parts.count - 2]) != nil + } + package static func withLock( at url: URL, checkpoint: (String) throws -> Void = { _ in }, _ body: () throws -> T ) throws -> T { @@ -14,7 +33,7 @@ package enum FileLock { at url: URL, checkpoint: (String) throws -> Void = { _ in }, _ body: (Int32) throws -> T ) throws -> T { let parent = try DirectoryHandle(at: url.deletingLastPathComponent(), create: true) { - try checkpoint("lock.ancestry." + $0.name) + try checkpoint(ancestryCheckpoint($0)) } let descriptor = openat( parent.descriptor, url.lastPathComponent, O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC, @@ -63,7 +82,8 @@ package enum FileLock { guard errno == EWOULDBLOCK else { throw CoreError.invalidState("cannot acquire writer lock: \(url.path)") } - try checkpoint("lock.contended") + try checkpoint( + contentionCheckpoint(contentions.wrappingAdd(1, ordering: .relaxed).oldValue)) while platform_flock(descriptor, LOCK_EX) != 0 { if errno != EINTR { throw CoreError.invalidState("cannot acquire writer lock: \(url.path)") diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 3637170..ab45cb8 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -4,11 +4,11 @@ import Foundation /// sealed publication evidence and terminal disposal. The scope writer lock spans /// preparation, commit and recovery; external writers are identified by inode and digest. package final class FileTransaction { - enum Source { + package enum Source { case data(Data) case copy(URL) - /// The destination is interpreted after publication, relative to the target parent. - case link(URL, destination: String) + /// A symbolic link to the URL, relative to the target parent when the URL is in the scope. + case link(URL) /// A producer may construct arbitrary intermediate objects only inside its private container. case prepared((URL) throws -> URL) } @@ -18,6 +18,8 @@ package final class FileTransaction { var executableFlags: [String: Bool]? var kind: mode_t? var mode: mode_t? + /// The destination a staged symbolic link must contain. + var linkDestination: String? } private struct Request { let path: String @@ -30,8 +32,8 @@ package final class FileTransaction { private let checkpoint: (String) throws -> Void private let outcome: TransactionOutcome private var requests: [Request] = [] - package var validateBeforePublication: () throws -> Void = {} - package var targetPaths: Set { Set(requests.map { $0.evidence.url.path }) } + private var unchanged: [any PreparedEvidence] = [] + private var targetPaths: Set { Set(requests.map { $0.evidence.url.path }) } package init( store: StateStore, outcome: TransactionOutcome = TransactionOutcome(), @@ -42,51 +44,44 @@ package final class FileTransaction { self.checkpoint = checkpoint } + /// `expectedHash` and `executableFlags` describe the content's tree hash and execute bits. package func replace( - _ destination: URL, content: URL?, link: Bool = false, data: Data? = nil, - expectedHash: String? = nil, executableFlags: [String: Bool]? = nil, - expecting: TargetPrecondition? = nil + _ destination: URL, with source: Source, expectedHash: String? = nil, + executableFlags: [String: Bool]? = nil, expecting: TargetPrecondition? = nil ) throws { - if let expectedHash { - try StateValidation.digest(expectedHash) - guard content != nil || data != nil else { - throw CoreError.invalidState("verification requires content") - } - } - let source: Source? - if let data { - source = .data(data) - } else if let content { - source = - link - ? .link( - content, - destination: Self.linkDestination( - content, parent: destination.deletingLastPathComponent(), store: store)) - : .copy(content) - } else { - source = nil - } - try append(destination, source: source, expecting: expecting) { - guard case .copy(let url) = source else { - return Expectation(hash: expectedHash, executableFlags: executableFlags) - } - return try Self.copyExpectation(url, hash: expectedHash, flags: executableFlags) + if let expectedHash { try StateValidation.digest(expectedHash) } + let (path, evidence) = try request(destination, expecting: expecting) + var expectation = Expectation(hash: expectedHash, executableFlags: executableFlags) + switch source { + case .copy(let url): + expectation = try Self.copyExpectation(url, hash: expectedHash, flags: executableFlags) + case .link(let url): + expectation.linkDestination = Self.linkDestination( + url, parent: destination.deletingLastPathComponent(), store: store) + case .data, .prepared: break } + requests.append( + Request(path: path, evidence: evidence, source: source, expectation: expectation)) } - func prepare(_ destination: URL, content: @escaping (URL) throws -> URL) throws { - try append(destination, source: .prepared(content), expecting: nil) { Expectation() } + package func delete(_ destination: URL, expecting: TargetPrecondition? = nil) throws { + let (path, evidence) = try request(destination, expecting: expecting) + requests.append(Request(path: path, evidence: evidence, source: nil, expectation: .init())) } - func remove(_ name: String, from parent: DirectoryHandle) throws { - try replace(parent.url.appendingPathComponent(name), content: nil) + /// Prepared inputs that this journal does not replace must still match at commit entry, + /// after staging and after publication; the journal verifies its own targets itself. + package func requireUnchanged(since evidence: any PreparedEvidence...) { + unchanged += evidence } - private func append( - _ destination: URL, source: Source?, expecting: TargetPrecondition?, - expectation: () throws -> Expectation - ) throws { + private func validateUnchanged() throws { + for evidence in unchanged { try evidence.validate(excludingTargets: targetPaths) } + } + + private func request(_ destination: URL, expecting: TargetPrecondition?) throws -> ( + path: String, evidence: TargetPrecondition + ) { let path = try TransactionPaths(store: store).path(for: destination) guard !requests.contains(where: { $0.path == path }) else { throw CoreError.invalidState("duplicate transaction destination") @@ -95,11 +90,10 @@ package final class FileTransaction { guard evidence.url.path == destination.standardizedFileURL.path else { throw CoreError.invalidState("precondition belongs to another target") } - requests.append( - Request(path: path, evidence: evidence, source: source, expectation: try expectation())) + return (path, evidence) } - fileprivate static func copyExpectation( + static func copyExpectation( _ source: URL, hash: String?, flags: [String: Bool]? ) throws -> Expectation { let physical = source.resolvingSymlinksInPath() @@ -121,11 +115,11 @@ package final class FileTransaction { package func commit() throws { guard !requests.isEmpty else { return } guard let directory = try store.openDirectoryIfPresent(), - try directory.info("transaction.json") == nil, try directory.info("transaction.new") == nil + try !TransactionJournal.isPresent(in: directory) else { throw CoreError.invalidState("transaction recovery is required") } - try validateBeforePublication() + try validateUnchanged() for request in requests { try request.evidence.validate() } try validateOverlap() let session = try makeSession(directory) @@ -145,19 +139,24 @@ package final class FileTransaction { try session.stage(index, source: request.source, expectation: request.expectation) } try session.emit(.preconditions) - try validateBeforePublication() + try validateUnchanged() try session.validatePreimages() outcome.disposition = .recoveryRequired for index in session.journal.entries.indices { try session.publish(index) } - try validateBeforePublication() - try session.prepareCleanup() + try validateUnchanged() + try session.sealDisposal() try session.emit(.commitValidated) try session.finish(.committed) outcome.disposition = .committed try session.emit(.phase(.committed)) try session.dispose() } catch { - do { _ = try Self.recover(store: store, outcome: outcome) } catch { + // Recovery names its checkpoints under `recovery.`, apart from the failed commit's. + do { + _ = try Self.recover(store: store, outcome: outcome) { + try self.checkpoint("recovery." + $0) + } + } catch { outcome.disposition = .recoveryRequired } throw error @@ -191,8 +190,8 @@ package final class FileTransaction { } } let parents = try requests.enumerated().map { index, request in - try paths.parent(for: request.path, roots: roots, create: true) { level in - try checkpoint(TransactionCheckpoint.parentCreated(entry: index, level: level).name) + try paths.parent(for: request.path, roots: roots, create: true) { step in + try checkpoint(TransactionCheckpoint.parentAncestry(entry: index, step).name) } } for request in requests { try request.evidence.validateIdentity() } @@ -240,226 +239,3 @@ package final class FileTransaction { return source.path } } - -extension TransactionSession { - func createContainers() throws { - for index in journal.containers.indices { - let parent = parents[journal.containers[index].entry] - let created = try parent.makeDirectory(journal.containerName(index)) - let identity = try created.objectIdentity - try emit(.containerCreated(index)) - guard try parent.info(journal.containerName(index)).map(FileObjectIdentity.init) == identity - else { - throw conflict( - journal.containers[index].entry, - "private container changed before its identity was durable") - } - journal.containers[index].identity = identity - } - // No object enters any container until all newly created identities are durable. - try persist(.containers) - try emit(.containersIdentified) - } - - func checkCapabilities() throws { - for index in journal.containers.indices { - let container = try container(index) - let device = try container.device - guard !capableDevices.contains(device) else { continue } - let names = TransactionScratch.probes - try container.requireAtomicRenames( - first: names.first, second: names.second, moved: names.moved - ) { try emit(.probe(index, $0)) } - capableDevices.insert(device) - } - } - - func stage( - _ index: Int, source: FileTransaction.Source?, expectation: FileTransaction.Expectation - ) throws { - let entry = journal.entries[index] - let parent = parents[index] - let scratch = try container(entry.container) - if let preimage = entry.preimage { try parent.synchronize(entry.name, as: preimage) } - try emit(.stage(index, .preimageSynced)) - let staging = TransactionScratch.staging(for: entry) - var staged: FileSnapshot? - if let source { - let sealed = try construct( - source, expectation: expectation, named: staging.name(index), index: index, - scratch: scratch, parent: parent) - try emit(.stage(index, .constructed)) - let capture = try FileSnapshot.capture(staging.name(index), from: scratch) - try verify(source, sealed, capture: capture) - guard let snapshot = capture.snapshot else { - throw conflict(index, "missing constructed object") - } - staged = snapshot - } else { - try emit(.stage(index, .constructed)) - } - for slot in TransactionScratch.objectSlots where source == nil || slot != staging { - guard try scratch.info(slot.name(index)) == nil else { - throw CoreError.invalidState("unexpected private recovery slot before sealing") - } - } - try scratch.sync() - journal.entries[index].staged = staged - try advance(index, to: .ready) - } - - /// Returns the expectation the sealed staging must meet. - private func construct( - _ source: FileTransaction.Source, expectation: FileTransaction.Expectation, - named name: String, index: Int, scratch: DirectoryHandle, parent: DirectoryHandle - ) throws -> FileTransaction.Expectation { - let entry = journal.entries[index] - var expectation = expectation - switch source { - case .data(let data): - let original = entry.preimage?.isRegular == true ? entry.preimage : nil - expectation.mode = original?.mode ?? 0o600 - try scratch.write( - name, data: data, preservingMetadataOf: original == nil ? nil : entry.name, - originalParent: parent, syncParent: false, - afterCreate: { try emit(.stage(index, .writeCreated)) }) - case .link(_, let destination): - try scratch.link(name, destination: destination, syncParent: false) - case .copy(let url): - try copy(url, named: name, index: index, scratch: scratch) - case .prepared(let produce): - let work = TransactionScratch.work.name(index) - try scratch.makeDirectory(work, syncParent: false) - try emit(.stage(index, .workCreated)) - let root = scratch.url.appendingPathComponent(work) - let url = try produce(root) - guard PathSafety.isContained(url.resolvingSymlinksInPath(), in: root) else { - throw CoreError.unsafePath("prepared content escapes transaction staging") - } - expectation = try FileTransaction.copyExpectation(url, hash: nil, flags: nil) - try emit(.stage(index, .workPrepared)) - try copy(url, named: name, index: index, scratch: scratch) - } - return expectation - } - - private func copy(_ source: URL, named name: String, index: Int, scratch: DirectoryHandle) - throws - { - try Self.validateCopy(source) - let origin = source.resolvingSymlinksInPath() - try scratch.copy( - name, from: DirectoryHandle(at: origin.deletingLastPathComponent()), - named: origin.lastPathComponent, syncParent: false - ) { try emit(.copy(index, $0)) } - } - - private func verify( - _ source: FileTransaction.Source, _ expectation: FileTransaction.Expectation, - capture: FileSnapshot.Capture - ) throws { - let snapshot = capture.snapshot - if let kind = expectation.kind, snapshot?.identity.kind != kind { - throw CoreError.invalidState("staged content type mismatch") - } - if case .data = source, snapshot?.isRegular != true { - throw CoreError.invalidState("staged content type mismatch") - } - if let mode = expectation.mode, snapshot?.mode != mode { - throw CoreError.invalidState("staged content permissions mismatch") - } - var linked: URL? - switch source { - case .data(let data): - guard snapshot?.digest == FileHash.sha256Hex(data: data) else { - throw CoreError.invalidState("staged content bytes mismatch") - } - case .link(let url, let destination): - guard snapshot?.isSymbolicLink == true, - snapshot?.digest == FileHash.sha256Hex(data: Data(destination.utf8)) - else { throw CoreError.invalidState("staged symbolic link destination mismatch") } - linked = url - case .copy, .prepared: break - } - if let expected = expectation.hash { - let actual = try linked.map(FileHash.folderHash) ?? capture.contentHash - guard "sha256:" + actual == expected else { - throw CoreError.invalidState("staged content digest mismatch") - } - } - if let flags = expectation.executableFlags { - let actual = try linked.map(FileHash.executableFlags) ?? capture.executableFlags - guard actual == flags else { - throw CoreError.invalidState("staged content executable mode mismatch") - } - } - } - - func validatePreimages() throws { - for index in journal.entries.indices { try requirePreimage(index) } - } - - func publish(_ index: Int) throws { - let entry = journal.entries[index] - let parent = parents[index] - let scratch = try container(entry.container) - let layout = try distribution(index) - guard layout.kind == .prepared else { - throw conflict(index, "operation is not prepared") - } - // A stale preparation cancels from ready; rechecking after the intent narrows the race. - try requirePreimage(index) - try advance(index, to: .publishing) - try requirePreimage(index) - try emit(.publication(index, .validated)) - try grantDirectoryPermissions(index, layout: layout, purpose: .publicationGrant) - if entry.action == .install { - let exchange = entry.preimage != nil - try scratch.move( - TransactionScratch.staging(for: entry).name(index), to: parent, named: entry.name, - mode: exchange ? .exchange : .exclusive - ) { - try emit(.publication(index, exchange ? .exchanged : .created)) - } - } else if entry.preimage != nil { - try parent.move( - entry.name, to: scratch, named: TransactionScratch.deleted.name(index), mode: .exclusive - ) { - try emit(.publication(index, .quarantined)) - } - } - try emit(.publication(index, .synced)) - try restoreDirectoryPermissions(index, purpose: .publicationRestore) - guard try distribution(index).kind == .installed else { - throw conflict(index, "publication did not retain its preimage") - } - try advance(index, to: .applied) - } - - func requirePreimage(_ index: Int) throws { - try requireParent(index) - guard - try FileSnapshot.read(journal.entries[index].name, from: parents[index]) - == journal.entries[index].preimage - else { - throw conflict(index, "preparation is stale; prepare again") - } - } - - /// A copied subtree keeps relative links that stay inside it, dangling ones included. - private static func validateCopy(_ source: URL) throws { - guard let root = PathSafety.realPath(source.path), - let entries = FileManager.default.enumerator( - 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("/"), try PathSafety.linkStaysInside(entry, root: root) else { - throw CoreError.unsafePath("copy symlink escapes installed subtree: \(entry.path)") - } - } - } - } -} diff --git a/Sources/AgentsCore/SourceCache.swift b/Sources/AgentsCore/SourceCache.swift index b93b60a..44de06c 100644 --- a/Sources/AgentsCore/SourceCache.swift +++ b/Sources/AgentsCore/SourceCache.swift @@ -155,9 +155,9 @@ package struct SourceCache { /// The marker survives interruptions until every deletion and its parent are durable. func recoverWatchReferences() throws -> Bool { guard let directory = try store.openDirectoryIfPresent() else { return false } - guard try directory.info("transaction.json") == nil, - try directory.info("transaction.new") == nil - else { throw CoreError.invalidState("transaction recovery must precede watch ref cleanup") } + guard try !TransactionJournal.isPresent(in: directory) else { + throw CoreError.invalidState("transaction recovery must precede watch ref cleanup") + } if try directory.info("watch-refs.pending") != nil, try !directory.read("watch-refs.pending").isEmpty { @@ -201,7 +201,8 @@ package struct SourceCache { let cache = try directory.child("cache") if try cache.info("mirrors") != nil { let mirrors = try cache.child("mirrors") - for name in try mirrors.names() where name.hasSuffix(".git") { + // Checkpoints are numbered by mirror and by deletion within this reconciliation. + for (ordinal, name) in try mirrors.names().filter({ $0.hasSuffix(".git") }).enumerated() { try withMirrorLock(at: mirrors.url.appendingPathComponent(name)) { descriptor in let mirror = try mirrors.child(name) let source = try sourceLocations[name] ?? mirrorSource(mirror.url, lock: descriptor) @@ -212,6 +213,7 @@ package struct SourceCache { mirror.url, ["for-each-ref", "--format=%(refname) %(objectname)", "refs/agents-watch/"], operation: .listReferences, source: source, lock: descriptor) + var deleted = 0 for line in references.split(separator: "\n") { let parts = line.split(separator: " ").map(String.init) guard parts.count == 2, parts[0] == "refs/agents-watch/" + parts[1], @@ -224,7 +226,8 @@ package struct SourceCache { mirror.url, ["update-ref", "--no-deref", "-d", parts[0], parts[1]], operation: .deleteReference, source: source, lock: descriptor ) - try checkpoint("watch.references.deleted") + try checkpoint("watch.references.\(ordinal).\(deleted).deleted") + deleted += 1 } // A previous attempt may have unlinked the final loose ref or rewritten packed-refs. // Flush their parents even when enumeration now finds no obsolete refs. @@ -232,7 +235,7 @@ package struct SourceCache { if try refs.info("agents-watch") != nil { try refs.child("agents-watch").sync() } try refs.sync() try mirror.sync() - try checkpoint("watch.references.synced") + try checkpoint("watch.references.\(ordinal).synced") } } } @@ -249,15 +252,17 @@ package struct SourceCache { let cache = try directory.child("cache") guard try cache.info("mirrors") != nil else { return } let mirrors = try cache.child("mirrors") - for name in try mirrors.names() where name.hasSuffix(".git") { + for (ordinal, name) in try mirrors.names().filter({ $0.hasSuffix(".git") }).enumerated() { try withMirrorLock(at: mirrors.url.appendingPathComponent(name)) { _ in - try recoverGitLocks(in: mirrors.child(name), scope: directory) + try recoverGitLocks(in: mirrors.child(name), ordinal: ordinal, scope: directory) } } } - private func recoverGitLocks(in mirror: DirectoryHandle, scope directory: DirectoryHandle) throws - { + /// Checkpoints are numbered by the mirror's ordinal and the lock's position in traversal. + private func recoverGitLocks( + in mirror: DirectoryHandle, ordinal: Int, scope directory: DirectoryHandle + ) throws { var locks: [(DirectoryHandle, String)] = [] func inspect(_ parent: DirectoryHandle, isMirrorRoot: Bool = false) throws { for name in try parent.names() { @@ -276,8 +281,10 @@ package struct SourceCache { try inspect(mirror, isMirrorRoot: true) if !locks.isEmpty { try beginWatchReferenceUpdate() } guard try directory.info("watch-refs.pending") != nil else { return } - for (parent, name) in locks { - try parent.remove(name) { try checkpoint("watch.git-lock.\($0.step.rawValue)") } + for (index, (parent, name)) in locks.enumerated() { + try parent.remove(name) { + try checkpoint("watch.git-lock.\(ordinal).\(index).\($0.step.rawValue)") + } } // A killed cleanup may have unlinked the last lock before syncing its parent. // The pending marker requires these barriers even if no lock remains visible. @@ -306,11 +313,13 @@ package struct SourceCache { if FileManager.default.fileExists(atPath: destination.path) { return destination } let mirror = try pinnedMirror(sourceID: sourceID, source: source, revision: revision) let transaction = FileTransaction(store: store, checkpoint: checkpoint) - try transaction.prepare(destination) { work in - try extract( - revision: revision, mirror: mirror, - source: declaration(sourceID: sourceID, source: source).location, root: work) - } + try transaction.replace( + destination, + with: .prepared { work in + try extract( + revision: revision, mirror: mirror, + source: declaration(sourceID: sourceID, source: source).location, root: work) + }) try transaction.commit() return destination } @@ -441,7 +450,7 @@ package struct SourceCache { } } else { let transaction = FileTransaction(store: store, checkpoint: checkpoint) - try transaction.replace(url, content: nil, data: data, expectedHash: digest) + try transaction.replace(url, with: .data(data), expectedHash: digest) try transaction.commit() } return url @@ -460,7 +469,7 @@ package struct SourceCache { } } else { let transaction = FileTransaction(store: store, checkpoint: checkpoint) - try transaction.replace(destination, content: directory, expectedHash: hash) + try transaction.replace(destination, with: .copy(directory), expectedHash: hash) try transaction.commit() } return destination @@ -523,9 +532,9 @@ package struct SourceCache { if !paths.contains(tree.url.path) && !edited(tree.url) { unused.append(pin) } } if unused.count == pins.count { - try transactionToUse.remove(name, from: materialized) + try transactionToUse.delete(materialized.url.appendingPathComponent(name)) } else { - for pin in unused { try transactionToUse.remove(pin, from: source) } + for pin in unused { try transactionToUse.delete(source.url.appendingPathComponent(pin)) } } } } @@ -539,7 +548,7 @@ package struct SourceCache { throw CoreError.unsafePath("unexpected artifact cache entry") } if !digests.contains(name) && !edited(url) { - try transactionToUse.remove(name, from: directory) + try transactionToUse.delete(url) } } } diff --git a/Sources/AgentsCore/StateInspection.swift b/Sources/AgentsCore/StateInspection.swift index 2b8eb5e..704ffa3 100644 --- a/Sources/AgentsCore/StateInspection.swift +++ b/Sources/AgentsCore/StateInspection.swift @@ -43,7 +43,8 @@ extension StateStore { } private func hasPendingRecovery(in directory: DirectoryHandle?) throws -> Bool { - try directory?.info("transaction.json") != nil || directory?.info("transaction.new") != nil - || directory?.info("watch-refs.pending") != nil + guard let directory else { return false } + return try TransactionJournal.isPresent(in: directory) + || directory.info("watch-refs.pending") != nil } } diff --git a/Sources/AgentsCore/StateStore.swift b/Sources/AgentsCore/StateStore.swift index c535093..5c5a94e 100644 --- a/Sources/AgentsCore/StateStore.swift +++ b/Sources/AgentsCore/StateStore.swift @@ -62,17 +62,14 @@ public struct StateStore: Sendable { _ = try readDeclaration(prepared: baseline) _ = try readResolved(prepared: baseline) let transaction = FileTransaction(store: self) - transaction.validateBeforePublication = { [unowned transaction] in - try baseline.validate(excludingTargets: transaction.targetPaths) - } + transaction.requireUnchanged(since: baseline) try stageDeclaration(declaration, in: transaction, prepared: baseline) try transaction.replace( - resolvedURL, content: nil, data: Self.encodeState(resolved.normalized), + resolvedURL, with: .data(Self.encodeState(resolved.normalized)), expecting: baseline.evidence(for: resolvedURL)) if let watch { try transaction.replace( - watchURL, content: nil, data: Self.encode(watch), - expecting: baseline.evidence(for: watchURL)) + watchURL, with: .data(Self.encode(watch)), expecting: baseline.evidence(for: watchURL)) } try transaction.commit() } @@ -92,7 +89,7 @@ public struct StateStore: Sendable { input = try TargetPrecondition.readingFile(declarationURL) } guard input.bytes != data else { return } - try transaction.replace(declarationURL, content: nil, data: data, expecting: input.evidence) + try transaction.replace(declarationURL, with: .data(data), expecting: input.evidence) } package func withLock( @@ -106,7 +103,7 @@ public struct StateStore: Sendable { if !FileManager.default.fileExists( atPath: directory.appendingPathComponent(".agents.lock").path), !FileManager.default.fileExists( - atPath: directory.appendingPathComponent("transaction.json").path) + atPath: directory.appendingPathComponent(TransactionJournal.fileName).path) { _ = try readDeclaration() _ = try readResolved() diff --git a/Sources/AgentsCore/TransactionCheckpoint.swift b/Sources/AgentsCore/TransactionCheckpoint.swift index 79e91be..72b23e3 100644 --- a/Sources/AgentsCore/TransactionCheckpoint.swift +++ b/Sources/AgentsCore/TransactionCheckpoint.swift @@ -1,11 +1,12 @@ import Foundation -/// Names are unique within one transaction and never contain host path components. +/// Names are unique within one transaction and never contain host path components. A caller +/// that nests transactions under one checkpoint stream prefixes each nested transaction's names. enum TransactionCheckpoint { enum Change { case created, containers case entry(Int, TransactionJournal.Progress) - case terminal, discard + case terminal, disposing case conflict(Int, TransactionJournal.Progress) var name: String { switch self { @@ -13,14 +14,14 @@ enum TransactionCheckpoint { case .containers: "containers" case .entry(let index, let progress): "entry.\(index).\(progress.rawValue)" case .terminal: "terminal" - case .discard: "discard" + case .disposing: "disposing" case .conflict(let index, let progress): "entry.\(index).\(progress.rawValue).conflict" } } } enum Stage: String { case preimageSynced, workCreated, workPrepared, writeCreated, constructed } - enum Publication: String { case validated, exchanged, created, quarantined, synced } - enum Restoration: String { case validated, exchanged, returned, creationQuarantined, synced } + enum Publication: String { case validated, exchanged, created, deleted, synced } + enum Restoration: String { case validated, exchanged, returned, withdrawn, synced } enum PersistenceStep: String { case written, renamed } enum Permission: String { case publicationGrant = "publish.grant" @@ -33,10 +34,10 @@ enum TransactionCheckpoint { case persisted(TransactionJournal.Phase, Change, PersistenceStep) case phase(TransactionJournal.Phase) case progress(Int, TransactionJournal.Progress) - /// Creation of a missing registered root or one of its ancestors. + /// Creation of a missing registered root or of its ancestors. case rootAncestry(String, DirectoryHandle.AncestryStep) - /// Creation of a missing destination parent at a level below its root. - case parentCreated(entry: Int, level: Int) + /// Creation of an entry's missing destination parent or of its ancestors below the root. + case parentAncestry(entry: Int, DirectoryHandle.AncestryStep) case containerCreated(Int) case containersIdentified case probe(Int, DirectoryHandle.ProbeStep) @@ -45,7 +46,7 @@ enum TransactionCheckpoint { case publication(Int, Publication) case restoration(Int, Restoration) case permissions(Int, Permission, TransactionObjectLocation, DirectoryHandle.PermissionStep) - case preconditions, commitValidated, journalSynced, discardIntent + case preconditions, commitValidated, journalSynced, disposalIntent /// The path is relative to the container; empty names the container itself. case unlinked(container: Int, path: String) /// The container's removal and its parent barrier are complete. @@ -60,7 +61,7 @@ enum TransactionCheckpoint { case .phase(let phase): "journal.\(phase.rawValue)" case .progress(let index, let progress): "entry.\(index).\(progress.rawValue)" case .rootAncestry(let root, let step): "ancestry.\(root).\(step.name)" - case .parentCreated(let index, let level): "ancestry.entry.\(index).\(level).created" + case .parentAncestry(let index, let step): "ancestry.entry.\(index).\(step.name)" case .containerCreated(let index): "container.\(index).created" case .containersIdentified: "containers.identified" case .probe(let index, let point): "atomic.\(index).\(point.rawValue)" @@ -73,12 +74,17 @@ enum TransactionCheckpoint { case .preconditions: "publication.preconditions" case .commitValidated: "publication.commitValidated" case .journalSynced: "journal.synced" - case .discardIntent: "cleanup.intent" + case .disposalIntent: "disposal.intent" case .unlinked(let index, let path): - "cleanup.\(index).unlinked" + (path.isEmpty ? "" : "." + path) - case .containerRemoved(let index): "cleanup.\(index).removed" + "disposal.\(index).unlinked" + (path.isEmpty ? "" : "." + path) + case .containerRemoved(let index): "disposal.\(index).removed" case .journalUnlinked: "journal.unlinked" case .journalRemoved: "journal.removed" } } + + /// Whether `name` follows the rename that makes a journal generation visible. + static func isJournalPublished(_ name: String) -> Bool { + name.hasPrefix("journal.") && name.hasSuffix("." + PersistenceStep.renamed.rawValue) + } } diff --git a/Sources/AgentsCore/TransactionDisposal.swift b/Sources/AgentsCore/TransactionDisposal.swift index 3d7880d..81cce55 100644 --- a/Sources/AgentsCore/TransactionDisposal.swift +++ b/Sources/AgentsCore/TransactionDisposal.swift @@ -3,7 +3,7 @@ import Foundation extension TransactionSession { /// Verifies every expected distribution and seals disposal evidence for containers that /// hold user data. A failure is recorded on the entry or container that caused it. - func prepareCleanup() throws { + func sealDisposal() throws { let layouts = try journal.entries.indices.map { index in do { return try distribution(index) } catch { try recordConflict(index, error) @@ -17,7 +17,8 @@ extension TransactionSession { } for index in journal.containers.indices { do { - try sealDisposal(index, userData: userContainers.contains(index), layouts: layouts) + try sealContainerDisposal( + index, userData: userContainers.contains(index), layouts: layouts) } catch { try recordConflict(journal.containers[index].entry, error) throw error @@ -26,12 +27,15 @@ extension TransactionSession { for index in journal.entries.indices { journal.entries[index].conflict = nil } } - private func sealDisposal(_ index: Int, userData: Bool, layouts: [TransactionLayout]) throws { + /// Conflicts name the container's representative entry, where they are recorded. + private func sealContainerDisposal(_ index: Int, userData: Bool, layouts: [TransactionLayout]) + throws + { let record = journal.containers[index] guard record.identity != nil else { return try validateContainerForDisposal(index) } let handle = try container(index) guard userData else { - journal.containers[index].cleanup = nil + journal.containers[index].disposal = nil return } let snapshot = try FileSnapshot.read(record.name, from: parents[record.entry]) @@ -40,20 +44,21 @@ extension TransactionSession { } for entryIndex in journal.entries.indices where journal.entries[entryIndex].container == index { for (slot, expected) in layouts[entryIndex].objects { - guard snapshot?.children?[slot.name(entryIndex)] == expected else { - throw conflict(entryIndex, "expected user object changed while sealing disposal") + let name = slot.name(entryIndex) + guard snapshot?.children?[name] == expected else { + throw conflict(record.entry, "user object \(name) changed while sealing disposal") } } } - journal.containers[index].cleanup = snapshot + journal.containers[index].disposal = snapshot } /// Recovery revalidates terminal evidence before disposal. - func cleanup() throws { + func revalidateDisposal() throws { try requireScope() for index in journal.entries.indices { do { - if journal.discarding { + if journal.disposing { try verifyTarget(index) } else { _ = try distribution(index) @@ -72,25 +77,29 @@ extension TransactionSession { try dispose() } - /// Commit disposes directly: `prepareCleanup` verified the distribution and sealed this + /// Commit disposes directly: `sealDisposal` verified the distribution and sealed this /// evidence immediately before the terminal marker. Deletion still verifies every object. func dispose() throws { try requireScope() - if !journal.discarding { - journal.discarding = true - try persist(.discard) - try emit(.discardIntent) + if !journal.disposing { + journal.disposing = true + try persist(.disposing) + try emit(.disposalIntent) } - for index in journal.containers.indices { try discardContainer(index) } + for index in journal.containers.indices { try disposeContainer(index) } try requireScope() - try directory.removeJournal { try emit(.journalUnlinked) } + try directory.removeFiles( + [TransactionJournal.incompleteFileName, TransactionJournal.fileName] + ) { name in + if name == TransactionJournal.fileName { try emit(.journalUnlinked) } + } try emit(.journalRemoved) } func verifyTarget(_ index: Int) throws { let entry = journal.entries[index] try requireParent(index) - // Terminal phases have a single distribution; disposal may have removed its scratch slots. + // Terminal phases have a single distribution; disposal may have removed its slots. guard try TransactionLayout.expected(entry)[0].target.matches(entry.name, from: parents[index]) else { throw conflict( @@ -107,8 +116,8 @@ extension TransactionSession { let parent = parents[record.entry] try requireParent(record.entry) guard let actual = try parent.info(record.name) else { - if journal.discarding || record.identity == nil { return } - throw conflict(record.entry, "private container disappeared before discard intent") + if journal.disposing || record.identity == nil { return } + throw conflict(record.entry, "private container disappeared before disposal intent") } guard let identity = record.identity else { guard try parent.child(record.name).names().isEmpty else { @@ -119,22 +128,22 @@ extension TransactionSession { guard FileObjectIdentity(actual) == identity else { throw conflict(record.entry, "private container identity changed") } - if let expected = record.cleanup { + if let expected = record.disposal { let current = try FileSnapshot.read(record.name, from: parent) let matches = - journal.discarding + journal.disposing ? current.map(expected.containsRemaining) == true : current == expected guard matches else { throw conflict(record.entry, "terminal disposal evidence changed") } } } - private func discardContainer(_ index: Int) throws { + private func disposeContainer(_ index: Int) throws { let record = journal.containers[index] let parent = parents[record.entry] try requireScope() try requireParent(record.entry) if let identity = record.identity { - try parent.remove(record.name, expecting: record.cleanup, identity: identity) { point in + try parent.remove(record.name, expecting: record.disposal, identity: identity) { point in try emit( point.step == .synced ? .containerRemoved(index) : .unlinked(container: index, path: point.path)) diff --git a/Sources/AgentsCore/TransactionEvidence.swift b/Sources/AgentsCore/TransactionEvidence.swift index de24c6b..d1653cb 100644 --- a/Sources/AgentsCore/TransactionEvidence.swift +++ b/Sources/AgentsCore/TransactionEvidence.swift @@ -18,21 +18,21 @@ struct FileObjectIdentity: Codable, Equatable, Sendable { /// `restoring` intent is durable it admits the original mode or that mode plus owner-write. struct DirectoryWriteLease: Equatable { let identity: FileObjectIdentity - let original: mode_t + let originalMode: mode_t init?(_ snapshot: FileSnapshot) { guard snapshot.identity.isDirectory, snapshot.mode & 0o200 == 0 else { return nil } identity = snapshot.identity - original = snapshot.mode + originalMode = snapshot.mode } - var grantedMode: mode_t { original | 0o200 } + var grantedMode: mode_t { originalMode | 0o200 } - func admits(_ mode: mode_t) -> Bool { mode == original || mode == grantedMode } + func admits(_ mode: mode_t) -> Bool { mode == originalMode || mode == grantedMode } } /// Content and physical ownership are separate evidence. Descendant identities let -/// terminal cleanup resume after partial deletion without adopting new entries. +/// terminal disposal resume after partial deletion without adopting new entries. struct FileSnapshot: Codable, Equatable, Sendable { let identity: FileObjectIdentity let digest: String diff --git a/Sources/AgentsCore/TransactionJournal.swift b/Sources/AgentsCore/TransactionJournal.swift index 04294f1..dec9c4f 100644 --- a/Sources/AgentsCore/TransactionJournal.swift +++ b/Sources/AgentsCore/TransactionJournal.swift @@ -3,6 +3,9 @@ import Foundation /// The version is independent of declaration, resolved and watch formats. struct TransactionJournal: Codable { static let currentVersion = 1 + static let fileName = "transaction.json" + /// The next journal generation before it replaces `fileName`. + static let incompleteFileName = "transaction.new" var version = currentVersion var id: UUID var scope: String @@ -11,7 +14,7 @@ struct TransactionJournal: Codable { var entries: [Entry] var containers: [Container] /// Only this durable intent permits absent or partially removed disposal objects. - var discarding = false + var disposing = false enum Phase: String, Codable { case preparing, applying, committed, rolledBack } enum Action: String, Codable { case install, delete } @@ -26,7 +29,7 @@ struct TransactionJournal: Codable { case applied /// Undo and directory-write intent are durable; installed or reverted objects may be present. case restoring - /// Undo parents and original modes are synced; reverted objects remain until discard intent. + /// Undo parents and original modes are synced; reverted objects remain until disposal intent. case restored /// Original modes are restored; publication did not consume private staging. case cancelled @@ -60,15 +63,30 @@ struct TransactionJournal: Codable { var name: String /// Persisted before inserting any object. Without it only an empty rmdir is allowed. var identity: FileObjectIdentity? - /// Present only for terminal disposal containing user data. Missing entries are admitted - /// only after discarding is durable; private unfinished construction needs no tree evidence. - var cleanup: FileSnapshot? + /// Terminal disposal evidence, present only for a container holding user data. Missing + /// entries are admitted only after `disposing` is durable; private unfinished construction + /// needs no tree evidence. + var disposal: FileSnapshot? } static func containerName(id: UUID, index: Int) -> String { ".agents-\(id.uuidString)-\(index)" } func containerName(_ index: Int) -> String { containers[index].name } + /// The scope-relative location of an entry's container, or nil when the record does not name + /// this journal's container for that index. + func containerLocation(of entry: Entry) -> String? { + guard containers.indices.contains(entry.container), + containers[entry.container].name == Self.containerName(id: id, index: entry.container) + else { return nil } + return entry.path.split(separator: "/").dropLast().joined(separator: "/") + "/" + + containers[entry.container].name + } + + static func isPresent(in directory: DirectoryHandle) throws -> Bool { + try directory.info(fileName) != nil || directory.info(incompleteFileName) != nil + } + /// Without an identified container or sealed operation, the journal owns no object. var isUnstarted: Bool { phase == .preparing && containers.allSatisfy { $0.identity == nil } @@ -76,16 +94,17 @@ struct TransactionJournal: Codable { } } -/// Container entry names. Each recovery slot holds either private staging or user data. -enum TransactionScratch: String { - /// Private sealed staging for a creation; publication moves it out of the container. +/// Entry names inside a private container. At each progress a recovery slot holds either +/// private staging or user data, as each case states. +enum TransactionSlot: String { + /// Private staging for a creation through `ready`; publication moves it out of the container. case staged - /// Private sealed staging for an exchange until publication; afterwards the displaced user - /// preimage, and after undo the withdrawn published object. + /// Private staging for an exchange through `ready`; user data from publication on: the + /// displaced preimage, and after undo the published object exchanged back out. case exchanged - /// The user object moved aside by a deletion. + /// User data: the object a deletion moved aside, from publication until undo or disposal. case deleted - /// The published creation moved aside by undo; it is user data. + /// User data: the published creation that undo moved aside. case withdrawn /// Private extraction work for prepared content. case work @@ -100,6 +119,18 @@ enum TransactionScratch: String { } } +enum TransactionObjectLocation: Equatable { + case target + case slot(TransactionSlot) + + var name: String { + switch self { + case .target: "target" + case .slot(let slot): slot.rawValue + } + } +} + /// The operation/progress table is the single authority for physical object distribution. /// A nil expected object means the slot must be absent, not that ownership is unknown. struct TransactionLayout { @@ -129,7 +160,7 @@ struct TransactionLayout { } let kind: Kind let target: Target - let objects: [TransactionScratch: FileSnapshot] + let objects: [TransactionSlot: FileSnapshot] static func expected(_ entry: TransactionJournal.Entry) -> [Self] { let prepared: Self @@ -159,6 +190,8 @@ struct TransactionLayout { case .queued: return [Self(kind: .construction, target: .any, objects: [:])] case .ready, .cancelled: return [prepared] case .publishing: + // A deletion has no slot object before its rename, so only the target can tell a + // prepared deletion from an installed one. if entry.action == .delete, let original = entry.preimage { return [Self(kind: .prepared, target: .object(original), objects: [:]), installed] } @@ -180,8 +213,8 @@ struct TransactionLayout { } else if kind == .prepared, let original = entry.preimage { locations.append((.target, original)) } - for slot in TransactionScratch.objectSlots { - if let expected = objects[slot] { locations.append((.scratch(slot), expected)) } + for slot in TransactionSlot.objectSlots { + if let expected = objects[slot] { locations.append((.slot(slot), expected)) } } return locations } diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index f398640..36f0bed 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -136,22 +136,26 @@ struct TransactionPaths { return (key, descendants) } - /// With `create`, each descendant's parent is synced; the checkpoint reports the level - /// below the root of each descendant this call creates. + /// With `create`, each descendant's parent is synced. Checkpoints mark only descendants + /// this call creates; depth counts levels above the returned parent, as for roots. func parent( for path: String, roots: [String: DirectoryHandle], create: Bool = false, - checkpoint: (Int) throws -> Void = { _ in } + checkpoint: (DirectoryHandle.AncestryStep) throws -> Void = { _ in } ) throws -> DirectoryHandle { let components = try components(path) guard var directory = roots[components.root] else { throw CoreError.invalidState("missing transaction root") } - for (index, name) in components.descendants.dropLast().enumerated() { + let ancestry = components.descendants.dropLast() + for (index, name) in ancestry.enumerated() { if create { + let depth = ancestry.count - 1 - index let created = try directory.info(name) == nil - if created { try directory.makeDirectory(name) } + if created { + try directory.makeDirectory(name) { try checkpoint(.created(depth: depth)) } + } try directory.sync() - if created { try checkpoint(index + 1) } + if created { try checkpoint(.synced(depth: depth)) } } directory = try directory.child(name) } diff --git a/Sources/AgentsCore/TransactionPermissions.swift b/Sources/AgentsCore/TransactionPermissions.swift index 4bff3ec..2aa3509 100644 --- a/Sources/AgentsCore/TransactionPermissions.swift +++ b/Sources/AgentsCore/TransactionPermissions.swift @@ -1,17 +1,5 @@ import Foundation -enum TransactionObjectLocation: Equatable { - case target - case scratch(TransactionScratch) - - var name: String { - switch self { - case .target: "target" - case .scratch(let slot): slot.rawValue - } - } -} - extension TransactionSession { /// Publishing/restoring intent binds a temporary owner-write bit to the recorded /// directory inode. It never grants access through an external replacement. @@ -20,8 +8,9 @@ extension TransactionSession { ) throws { for (location, object) in layout.objectLocations(journal.entries[index]) { guard let lease = object.writeLease else { continue } - try setDirectoryPermissions( - index, location: location, lease: lease, granting: true, purpose: purpose) + try leasedDirectory(index, location).grant(lease) { + try emit(.permissions(index, purpose, location, $0)) + } } } @@ -32,8 +21,9 @@ extension TransactionSession { throws { try forEachDirectoryLease(index) { location, lease in - try setDirectoryPermissions( - index, location: location, lease: lease, granting: false, purpose: purpose) + try leasedDirectory(index, location).restore(lease) { + try emit(.permissions(index, purpose, location, $0)) + } } } @@ -84,21 +74,19 @@ extension TransactionSession { try requireParent(index) switch location { case .target: return (parents[index], journal.entries[index].name) - case .scratch(let slot): + case .slot(let slot): return (try container(journal.entries[index].container), slot.name(index)) } } - private func setDirectoryPermissions( - _ index: Int, location: TransactionObjectLocation, lease: DirectoryWriteLease, - granting: Bool, purpose: TransactionCheckpoint.Permission - ) throws { + /// Mode changes require durable publishing or restoring intent. + private func leasedDirectory(_ index: Int, _ location: TransactionObjectLocation) throws + -> DirectoryHandle + { guard journal.entries[index].progress.permitsDirectoryWrite else { throw conflict(index, "directory permission change requires durable intent") } let (parent, name) = try permissionLocation(index, location) - try parent.child(name).setPermissions(lease, granting: granting) { - try emit(.permissions(index, purpose, location, $0)) - } + return try parent.child(name) } } diff --git a/Sources/AgentsCore/TransactionPublication.swift b/Sources/AgentsCore/TransactionPublication.swift new file mode 100644 index 0000000..d951c59 --- /dev/null +++ b/Sources/AgentsCore/TransactionPublication.swift @@ -0,0 +1,228 @@ +import Foundation + +/// Construction, sealing and publication of a commit's operations. +extension TransactionSession { + func createContainers() throws { + for index in journal.containers.indices { + let parent = parents[journal.containers[index].entry] + let created = try parent.makeDirectory(journal.containerName(index)) + let identity = try created.objectIdentity + try emit(.containerCreated(index)) + guard try parent.info(journal.containerName(index)).map(FileObjectIdentity.init) == identity + else { + throw conflict( + journal.containers[index].entry, + "private container changed before its identity was durable") + } + journal.containers[index].identity = identity + } + // No object enters any container until all newly created identities are durable. + try persist(.containers) + try emit(.containersIdentified) + } + + func checkCapabilities() throws { + for index in journal.containers.indices { + let container = try self.container(index) + let device = try container.device + guard !capableDevices.contains(device) else { continue } + let names = TransactionSlot.probes + try container.requireAtomicRenames( + first: names.first, second: names.second, moved: names.moved + ) { try emit(.probe(index, $0)) } + capableDevices.insert(device) + } + } + + func stage( + _ index: Int, source: FileTransaction.Source?, expectation: FileTransaction.Expectation + ) throws { + let entry = journal.entries[index] + let parent = parents[index] + let container = try self.container(entry.container) + if let preimage = entry.preimage { try parent.synchronize(entry.name, as: preimage) } + try emit(.stage(index, .preimageSynced)) + let staging = TransactionSlot.staging(for: entry) + var staged: FileSnapshot? + if let source { + let sealed = try construct( + source, expectation: expectation, named: staging.name(index), index: index, + container: container, parent: parent) + try emit(.stage(index, .constructed)) + let capture = try FileSnapshot.capture(staging.name(index), from: container) + try verify(source, sealed, capture: capture) + guard let snapshot = capture.snapshot else { + throw conflict(index, "missing constructed object") + } + staged = snapshot + } else { + try emit(.stage(index, .constructed)) + } + for slot in TransactionSlot.objectSlots where source == nil || slot != staging { + guard try container.info(slot.name(index)) == nil else { + throw CoreError.invalidState("unexpected private recovery slot before sealing") + } + } + try container.sync() + journal.entries[index].staged = staged + try advance(index, to: .ready) + } + + /// Returns the expectation the sealed staging must meet. + private func construct( + _ source: FileTransaction.Source, expectation: FileTransaction.Expectation, + named name: String, index: Int, container: DirectoryHandle, parent: DirectoryHandle + ) throws -> FileTransaction.Expectation { + let entry = journal.entries[index] + var expectation = expectation + switch source { + case .data(let data): + let original = entry.preimage?.isRegular == true ? entry.preimage : nil + expectation.mode = original?.mode ?? 0o600 + try container.write( + name, data: data, preservingMetadataOf: original == nil ? nil : entry.name, + originalParent: parent, syncParent: false, + afterCreate: { try emit(.stage(index, .writeCreated)) }) + case .link(let url): + let destination = expectation.linkDestination ?? url.path + expectation.linkDestination = destination + try container.link(name, destination: destination, syncParent: false) + case .copy(let url): + try copy(url, named: name, index: index, container: container) + case .prepared(let produce): + let work = TransactionSlot.work.name(index) + try container.makeDirectory(work, syncParent: false) + try emit(.stage(index, .workCreated)) + let root = container.url.appendingPathComponent(work) + let url = try produce(root) + guard PathSafety.isContained(url.resolvingSymlinksInPath(), in: root) else { + throw CoreError.unsafePath("prepared content escapes transaction staging") + } + expectation = try FileTransaction.copyExpectation( + url, hash: expectation.hash, flags: expectation.executableFlags) + try emit(.stage(index, .workPrepared)) + try copy(url, named: name, index: index, container: container) + } + return expectation + } + + private func copy(_ source: URL, named name: String, index: Int, container: DirectoryHandle) + throws + { + try Self.validateCopy(source) + let origin = source.resolvingSymlinksInPath() + try container.copy( + name, from: DirectoryHandle(at: origin.deletingLastPathComponent()), + named: origin.lastPathComponent, syncParent: false + ) { try emit(.copy(index, $0)) } + } + + private func verify( + _ source: FileTransaction.Source, _ expectation: FileTransaction.Expectation, + capture: FileSnapshot.Capture + ) throws { + let snapshot = capture.snapshot + if let kind = expectation.kind, snapshot?.identity.kind != kind { + throw CoreError.invalidState("staged content type mismatch") + } + if case .data = source, snapshot?.isRegular != true { + throw CoreError.invalidState("staged content type mismatch") + } + if let mode = expectation.mode, snapshot?.mode != mode { + throw CoreError.invalidState("staged content permissions mismatch") + } + var linked: URL? + switch source { + case .data(let data): + guard snapshot?.digest == FileHash.sha256Hex(data: data) else { + throw CoreError.invalidState("staged content bytes mismatch") + } + case .link(let url): + guard snapshot?.isSymbolicLink == true, let destination = expectation.linkDestination, + snapshot?.digest == FileHash.sha256Hex(data: Data(destination.utf8)) + else { throw CoreError.invalidState("staged symbolic link destination mismatch") } + linked = url + case .copy, .prepared: break + } + if let expected = expectation.hash { + let actual = try linked.map(FileHash.folderHash) ?? capture.contentHash + guard "sha256:" + actual == expected else { + throw CoreError.invalidState("staged content digest mismatch") + } + } + if let flags = expectation.executableFlags { + let actual = try linked.map(FileHash.executableFlags) ?? capture.executableFlags + guard actual == flags else { + throw CoreError.invalidState("staged content executable mode mismatch") + } + } + } + + func validatePreimages() throws { + for index in journal.entries.indices { try requirePreimage(index) } + } + + func publish(_ index: Int) throws { + let entry = journal.entries[index] + let parent = parents[index] + let container = try self.container(entry.container) + let layout = try distribution(index) + guard layout.kind == .prepared else { + throw conflict(index, "operation is not prepared") + } + // A stale preparation cancels from ready; rechecking after the intent narrows the race. + try requirePreimage(index) + try advance(index, to: .publishing) + try requirePreimage(index) + try emit(.publication(index, .validated)) + try grantDirectoryPermissions(index, layout: layout, purpose: .publicationGrant) + if entry.action == .install { + let exchange = entry.preimage != nil + try container.move( + TransactionSlot.staging(for: entry).name(index), to: parent, named: entry.name, + mode: exchange ? .exchange : .exclusive + ) { + try emit(.publication(index, exchange ? .exchanged : .created)) + } + } else if entry.preimage != nil { + try parent.move( + entry.name, to: container, named: TransactionSlot.deleted.name(index), mode: .exclusive + ) { + try emit(.publication(index, .deleted)) + } + } + try emit(.publication(index, .synced)) + try restoreDirectoryPermissions(index, purpose: .publicationRestore) + guard try distribution(index).kind == .installed else { + throw conflict(index, "publication did not retain its preimage") + } + try advance(index, to: .applied) + } + + func requirePreimage(_ index: Int) throws { + try requireParent(index) + guard + try FileSnapshot.read(journal.entries[index].name, from: parents[index]) + == journal.entries[index].preimage + else { + throw conflict(index, "preparation is stale; prepare again") + } + } + + /// A copied subtree keeps relative links that stay inside it, dangling ones included. + private static func validateCopy(_ source: URL) throws { + guard let root = PathSafety.realPath(source.path), + let entries = FileManager.default.enumerator( + 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("/"), try PathSafety.linkStaysInside(entry, root: root) else { + throw CoreError.unsafePath("copy symlink escapes installed subtree: \(entry.path)") + } + } + } + } +} diff --git a/Sources/AgentsCore/TransactionRecovery.swift b/Sources/AgentsCore/TransactionRecovery.swift index 3a03060..048015b 100644 --- a/Sources/AgentsCore/TransactionRecovery.swift +++ b/Sources/AgentsCore/TransactionRecovery.swift @@ -6,6 +6,7 @@ package struct TransactionRecoveryDiagnostic { static let pendingMessage = "Transaction recovery is pending; the next command that changes this scope will recover it." + static let conflictMessage = "Unresolved transaction conflict; owner action is required" } extension FileTransaction { @@ -14,31 +15,34 @@ extension FileTransaction { checkpoint: @escaping (String) throws -> Void = { _ in } ) throws -> Bool { guard let directory = try store.openDirectoryIfPresent() else { return false } - guard try directory.info("transaction.json") != nil else { - guard try directory.info("transaction.new") != nil else { return false } + let primary = TransactionJournal.fileName + let incomplete = TransactionJournal.incompleteFileName + guard try directory.info(primary) != nil else { + guard try directory.info(incomplete) != nil else { return false } + // An unstarted journal owns no object, so it is discarded without a journal barrier. try requireUnstartedIncompleteJournal(in: directory) - try directory.remove("transaction.new") + try directory.remove(incomplete) return true } var recoveredID: UUID? do { - let journal = try readJournal(directory.read("transaction.json")) + let journal = try readJournal(directory.read(primary)) recoveredID = journal.id let session = try recoverySession( journal, store: store, directory: directory, checkpoint: checkpoint) - // Validate the journal's scratch file before any recovery mutation. - if try directory.info("transaction.new") != nil { _ = try directory.read("transaction.new") } + // Validate the incomplete next generation before any recovery mutation. + if try directory.info(incomplete) != nil { _ = try directory.read(incomplete) } // Any observed journal may have been renamed without its directory barrier. Persist it // before granting permissions, renaming objects or deleting any resource, including on retry. - try directory.syncFile("transaction.json") + try directory.syncFile(primary) try session.emit(.journalSynced) if journal.phase == .applying { try session.rollback() } if session.journal.phase == .applying || session.journal.phase == .preparing { - try session.prepareCleanup() + try session.sealDisposal() try session.finish(.rolledBack) try session.emit(.phase(.rolledBack)) } - try session.cleanup() + try session.revalidateDisposal() if outcome?.journalID == journal.id { outcome?.disposition = session.journal.phase == .committed ? .committed : .unchanged } @@ -53,27 +57,20 @@ extension FileTransaction { } package static func recoveryDiagnostic(store: StateStore) -> TransactionRecoveryDiagnostic { - var retained = [store.directory.appendingPathComponent("transaction.json").path] + let journalURL = store.directory.appendingPathComponent(TransactionJournal.fileName) + var retained = [journalURL.path] do { guard let directory = try store.openDirectoryIfPresent() else { return .init(requiresOwner: false, message: TransactionRecoveryDiagnostic.pendingMessage) } - if try directory.info("transaction.json") == nil { - if try directory.info("transaction.new") != nil { + if try directory.info(TransactionJournal.fileName) == nil { + if try directory.info(TransactionJournal.incompleteFileName) != nil { try requireUnstartedIncompleteJournal(in: directory) } return .init(requiresOwner: false, message: TransactionRecoveryDiagnostic.pendingMessage) } - let journal = try readJournal(directory.read("transaction.json")) - retained += journal.entries.compactMap { entry in - guard journal.containers.indices.contains(entry.container) else { return nil } - let container = journal.containers[entry.container] - guard - container.name == TransactionJournal.containerName(id: journal.id, index: entry.container) - else { return nil } - return entry.path.split(separator: "/").dropLast().joined(separator: "/") - + "/" + container.name - } + let journal = try readJournal(directory.read(TransactionJournal.fileName)) + retained += journal.entries.compactMap(journal.containerLocation(of:)) let session = try recoverySession( journal, store: store, directory: directory, checkpoint: { _ in }) let conflicts = journal.entries.compactMap(\.conflict) @@ -83,9 +80,8 @@ extension FileTransaction { } return .init( requiresOwner: true, - message: "Unresolved transaction conflict; owner action is required. " - + details.joined(separator: "; ") - + "; journal: " + directory.url.appendingPathComponent("transaction.json").path) + message: TransactionRecoveryDiagnostic.conflictMessage + ". " + + details.joined(separator: "; ") + "; journal: " + journalURL.path) } try session.inspectRecoveryObjects() return .init(requiresOwner: false, message: TransactionRecoveryDiagnostic.pendingMessage) @@ -93,14 +89,14 @@ extension FileTransaction { return .init( requiresOwner: true, message: - "Unresolved transaction conflict; owner action is required: \(error). Retained locations: \(Set(retained).sorted().joined(separator: ", "))." + "\(TransactionRecoveryDiagnostic.conflictMessage): \(error). Retained locations: \(Set(retained).sorted().joined(separator: ", "))." ) } } - /// A lone `transaction.new` may be discarded only while it is unparseable or unstarted. + /// A lone incomplete journal may be discarded only while it is unparseable or unstarted. private static func requireUnstartedIncompleteJournal(in directory: DirectoryHandle) throws { - let bytes = try directory.read("transaction.new") + let bytes = try directory.read(TransactionJournal.incompleteFileName) guard (try? JSONSerialization.jsonObject(with: bytes)) != nil else { return } guard try readJournal(bytes).isUnstarted else { throw CoreError.invalidState( @@ -146,7 +142,7 @@ extension TransactionSession { /// Read-only diagnosis of the distribution recovery would act on. func inspectRecoveryObjects() throws { for index in journal.entries.indices { - if journal.discarding { + if journal.disposing { try verifyTarget(index) } else { _ = try distribution(index, permittingDirectoryWrite: true) @@ -211,28 +207,28 @@ extension TransactionSession { private func undo(_ index: Int) throws { let entry = journal.entries[index] let parent = parents[index] - let scratch = try container(entry.container) + let container = try self.container(entry.container) try emit(.restoration(index, .validated)) if entry.preimage != nil { if entry.action == .install { - try scratch.move( - TransactionScratch.exchanged.name(index), to: parent, named: entry.name, + try container.move( + TransactionSlot.exchanged.name(index), to: parent, named: entry.name, mode: .exchange ) { try emit(.restoration(index, .exchanged)) } } else { - try scratch.move( - TransactionScratch.deleted.name(index), to: parent, named: entry.name, mode: .exclusive + try container.move( + TransactionSlot.deleted.name(index), to: parent, named: entry.name, mode: .exclusive ) { try emit(.restoration(index, .returned)) } } } else if entry.action == .install { try parent.move( - entry.name, to: scratch, named: TransactionScratch.withdrawn.name(index), mode: .exclusive + entry.name, to: container, named: TransactionSlot.withdrawn.name(index), mode: .exclusive ) { - try emit(.restoration(index, .creationQuarantined)) + try emit(.restoration(index, .withdrawn)) } } } diff --git a/Sources/AgentsCore/TransactionSession.swift b/Sources/AgentsCore/TransactionSession.swift index cddbe34..67278a2 100644 --- a/Sources/AgentsCore/TransactionSession.swift +++ b/Sources/AgentsCore/TransactionSession.swift @@ -24,8 +24,9 @@ final class TransactionSession { func persist(_ change: TransactionCheckpoint.Change) throws { try requireScope() - try directory.writeJournal( - StateStore.encode(journal), + try directory.replaceFile( + TransactionJournal.fileName, through: TransactionJournal.incompleteFileName, + with: StateStore.encode(journal), afterWrite: { try emit(.persisted(journal.phase, change, .written)) }, @@ -93,11 +94,8 @@ final class TransactionSession { func containerLocation(_ index: Int) -> String { let entry = journal.entries[index] - guard journal.containers.indices.contains(entry.container) else { - return "" - } - return entry.path.split(separator: "/").dropLast().joined(separator: "/") + "/" - + journal.containerName(entry.container) + return journal.containerLocation(of: entry) + ?? "" } func recordConflict(_ index: Int, _ error: Error) throws { @@ -173,9 +171,9 @@ final class TransactionSession { throw CoreError.invalidState("sealed operation is missing private container identity") } } - try record.cleanup?.validate() - if let cleanup = record.cleanup { - guard cleanup.identity == record.identity else { + try record.disposal?.validate() + if let disposal = record.disposal { + guard disposal.identity == record.identity else { throw CoreError.invalidState("terminal container evidence has another identity") } } @@ -184,7 +182,7 @@ final class TransactionSession { [.applied, .restored].contains(entry.progress) && TransactionLayout.expected(entry).contains { !$0.objects.isEmpty } } - guard !containsUserData || record.cleanup != nil else { + guard !containsUserData || record.disposal != nil else { throw CoreError.invalidState("terminal container is missing user-object disposal evidence") } } @@ -202,7 +200,7 @@ final class TransactionSession { let requiresStaging = entry.action == .install && entry.progress != .queued guard allowed.contains(entry.progress), (entry.staged != nil) == requiresStaging, - !journal.discarding || journal.phase == .committed || journal.phase == .rolledBack + !journal.disposing || journal.phase == .committed || journal.phase == .rolledBack else { throw conflict(index, "operation progress contradicts its evidence or journal phase") } @@ -217,10 +215,10 @@ final class TransactionSession { try requireParent(index) let layouts = TransactionLayout.expected(entry) if entry.progress == .queued { return layouts[0] } - let scratch = try container(entry.container) - var objects: [TransactionScratch: FileSnapshot] = [:] - for slot in TransactionScratch.objectSlots { - if let value = try FileSnapshot.read(slot.name(index), from: scratch) { + let container = try self.container(entry.container) + var objects: [TransactionSlot: FileSnapshot] = [:] + for slot in TransactionSlot.objectSlots { + if let value = try FileSnapshot.read(slot.name(index), from: container) { objects[slot] = value } } @@ -238,6 +236,10 @@ final class TransactionSession { return layout } } - throw conflict(index, "missing or changed expected target, preimage or rollback quarantine") + let expected = Set(layouts.flatMap(\.objects.keys)).map { $0.name(index) }.sorted() + throw conflict( + index, + "missing or changed expected target or recovery slot object; expected slots: " + + (expected.isEmpty ? "none" : expected.joined(separator: ", "))) } } diff --git a/Sources/AgentsCore/UpdatePreconditions.swift b/Sources/AgentsCore/UpdatePreconditions.swift index 689508b..2388318 100644 --- a/Sources/AgentsCore/UpdatePreconditions.swift +++ b/Sources/AgentsCore/UpdatePreconditions.swift @@ -44,8 +44,14 @@ package struct PathIdentity { } } +/// Prepared evidence checked again before publication, except for targets that the +/// transaction journal verifies itself. +package protocol PreparedEvidence { + func validate(excludingTargets targets: Set) throws +} + /// State bytes and presence belong to the same generation as the rendered targets. -package struct StatePrecondition { +package struct StatePrecondition: PreparedEvidence { private let files: [(url: URL, evidence: TargetPrecondition, bytes: Data?)] package init(store: StateStore) throws { diff --git a/Sources/AgentsCore/WatchOperations.swift b/Sources/AgentsCore/WatchOperations.swift index a06d90c..6cff9e8 100644 --- a/Sources/AgentsCore/WatchOperations.swift +++ b/Sources/AgentsCore/WatchOperations.swift @@ -177,14 +177,12 @@ public struct WatchOperations: Sendable { ) throws { try watch.validate() let transaction = FileTransaction(store: store, checkpoint: checkpoint) - transaction.validateBeforePublication = { [unowned transaction] in - try baseline.validate(excludingTargets: transaction.targetPaths) - } + transaction.requireUnchanged(since: baseline) if let declaration { try store.stageDeclaration(declaration, in: transaction, prepared: baseline) } try transaction.replace( - store.watchURL, content: nil, data: StateStore.encode(watch), + store.watchURL, with: .data(StateStore.encode(watch)), expecting: baseline.evidence(for: store.watchURL)) try SourceCache(store: store).prune(referencedBy: lock, watch: watch, transaction: transaction) try transaction.commit() @@ -209,7 +207,12 @@ public struct WatchOperations: Sendable { "agents-watch-" + UUID().uuidString) try FileSystem.createDirectory(at: root) defer { try? FileManager.default.removeItem(at: root) } - for artifact in artifacts { + // Each nested cache transaction names its checkpoints within its artifact and role, so + // they stay distinct from one another and from the watch commit. + func artifactCache(_ scope: String) -> SourceCache { + SourceCache(store: store) { try checkpoint("watch.artifact." + scope + "." + $0) } + } + for (index, artifact) in artifacts.enumerated() { let directory = root.appendingPathComponent(artifact.name) try FileSystem.createDirectory(at: directory) for (path, data) in artifact.files { @@ -217,8 +220,12 @@ public struct WatchOperations: Sendable { try FileSystem.createDirectory(at: destination.deletingLastPathComponent()) try FileSystem.write(data, to: destination) } - for (digest, data) in artifact.payloads { _ = try cache.storeArtifact(data, digest: digest) } - _ = try cache.materializeArtifact( + for (payload, (digest, data)) in artifact.payloads.sorted(by: { $0.key < $1.key }) + .enumerated() + { + _ = try artifactCache("\(index).payload.\(payload)").storeArtifact(data, digest: digest) + } + _ = try artifactCache("\(index).content").materializeArtifact( directory, digest: artifact.artifact.digest, hash: "sha256:" + FileHash.folderHash(directory)) } diff --git a/Sources/AgentsInstructions/InstructionOperations.swift b/Sources/AgentsInstructions/InstructionOperations.swift index 327d044..2d6774d 100644 --- a/Sources/AgentsInstructions/InstructionOperations.swift +++ b/Sources/AgentsInstructions/InstructionOperations.swift @@ -165,10 +165,7 @@ public enum InstructionOperations { try plan.validate() try plan.retain() let transaction = FileTransaction(store: store) - transaction.validateBeforePublication = { [unowned transaction] in - try baseline.validate(excludingTargets: transaction.targetPaths) - try plan.validate(excludingTargets: transaction.targetPaths) - } + transaction.requireUnchanged(since: baseline, plan) try plan.stage(transaction: transaction) try store.stageDeclaration( declaration, in: transaction, prepared: baseline) @@ -176,7 +173,7 @@ public enum InstructionOperations { comparedTo: baseline.bytes(for: store.resolvedURL)) { try transaction.replace( - store.resolvedURL, content: nil, data: data, + store.resolvedURL, with: .data(data), expecting: baseline.evidence(for: store.resolvedURL)) } try SourceCache(store: store).prune( @@ -330,7 +327,7 @@ public enum InstructionOperations { .utf8) _ = try Instructions.validateSource(bytes, id: name) let transaction = FileTransaction(store: store) - try transaction.replace(file, content: nil, data: bytes) + try transaction.replace(file, with: .data(bytes)) try transaction.commit() return file } @@ -438,16 +435,13 @@ public enum InstructionOperations { do { try plan.retain() let transaction = FileTransaction(store: store) - transaction.validateBeforePublication = { [unowned transaction] in - try baseline.validate(excludingTargets: transaction.targetPaths) - try plan.validate(excludingTargets: transaction.targetPaths) - } + transaction.requireUnchanged(since: baseline, plan) try plan.stage(transaction: transaction) if writeState { try store.stageDeclaration(declaration, in: transaction, prepared: baseline) if let data = try next.replacementData(comparedTo: baseline.bytes(for: store.resolvedURL)) { try transaction.replace( - store.resolvedURL, content: nil, data: data, + store.resolvedURL, with: .data(data), expecting: baseline.evidence(for: store.resolvedURL)) } } diff --git a/Sources/AgentsInstructions/InstructionUpdatePlan.swift b/Sources/AgentsInstructions/InstructionUpdatePlan.swift index 457ff77..613ed4e 100644 --- a/Sources/AgentsInstructions/InstructionUpdatePlan.swift +++ b/Sources/AgentsInstructions/InstructionUpdatePlan.swift @@ -2,7 +2,7 @@ import AgentsCore import Foundation /// Assembly and retention inputs for one scope generation; the caller owns commit and pruning. -package final class InstructionUpdatePlan { +package final class InstructionUpdatePlan: PreparedEvidence { package let next: ResolvedState package let report: InstructionUpdateReport private let sources: InstructionSources @@ -61,7 +61,11 @@ package final class InstructionUpdatePlan { else { throw CoreError.invalidState("instruction target has no prepared preimage") } - try transaction.replace(change.url, content: nil, data: change.after, expecting: evidence) + if let after = change.after { + try transaction.replace(change.url, with: .data(after), expecting: evidence) + } else { + try transaction.delete(change.url, expecting: evidence) + } } } } diff --git a/Sources/AgentsSkills/SkillLifecycle.swift b/Sources/AgentsSkills/SkillLifecycle.swift index fe0a166..f8f9832 100644 --- a/Sources/AgentsSkills/SkillLifecycle.swift +++ b/Sources/AgentsSkills/SkillLifecycle.swift @@ -227,10 +227,7 @@ final class SkillLifecycle { try plan.validate() let retained = try plan.retain() let transaction = FileTransaction(store: store) - transaction.validateBeforePublication = { [unowned transaction] in - try baseline.validate(excludingTargets: transaction.targetPaths) - try plan.validate(excludingTargets: transaction.targetPaths) - } + transaction.requireUnchanged(since: baseline, plan) try plan.stage(retained: retained, transaction: transaction) if writeState { try store.stageDeclaration(declaration, in: transaction, prepared: baseline) @@ -238,8 +235,8 @@ final class SkillLifecycle { comparedTo: baseline.bytes(for: store.resolvedURL)) { try transaction.replace( - store.resolvedURL, content: nil, data: data, - expecting: baseline.evidence(for: store.resolvedURL)) + store.resolvedURL, with: .data(data), expecting: baseline.evidence(for: store.resolvedURL) + ) } } try cache.prune( @@ -326,16 +323,14 @@ final class SkillLifecycle { content.resolvingSymlinksInPath(), in: URL(fileURLWithPath: path).standardizedFileURL) else { throw CoreError.unsafePath("installation would replace its own source") } try transaction.replace( - URL(fileURLWithPath: path), content: content, link: target.mode != .copy, - expectedHash: item.lock.hash, - executableFlags: item.executableFlags, expecting: evidence) + URL(fileURLWithPath: path), with: target.mode == .copy ? .copy(content) : .link(content), + expectedHash: item.lock.hash, executableFlags: item.executableFlags, expecting: evidence) } else if let target = oldTargets[path], names.contains(target.name), newTargets[path] == nil { guard let evidence = expectations[path] else { throw CoreError.invalidState("skill target has no prepared preimage") } - try transaction.replace( - URL(fileURLWithPath: path), content: nil, expecting: evidence) + try transaction.delete(URL(fileURLWithPath: path), expecting: evidence) } } } diff --git a/Sources/AgentsSkills/SkillOperations.swift b/Sources/AgentsSkills/SkillOperations.swift index 2cf5d36..7e9a7a6 100644 --- a/Sources/AgentsSkills/SkillOperations.swift +++ b/Sources/AgentsSkills/SkillOperations.swift @@ -157,10 +157,7 @@ public enum SkillOperations { try plan.validate() let retained = try plan.retain() let transaction = FileTransaction(store: store) - transaction.validateBeforePublication = { [unowned transaction] in - try baseline.validate(excludingTargets: transaction.targetPaths) - try plan.validate(excludingTargets: transaction.targetPaths) - } + transaction.requireUnchanged(since: baseline, plan) try plan.stage(retained: retained, transaction: transaction) try store.stageDeclaration( declaration, in: transaction, prepared: baseline) @@ -168,7 +165,7 @@ public enum SkillOperations { comparedTo: baseline.bytes(for: store.resolvedURL)) { try transaction.replace( - store.resolvedURL, content: nil, data: data, + store.resolvedURL, with: .data(data), expecting: baseline.evidence(for: store.resolvedURL)) } try SourceCache(store: store).prune( diff --git a/Sources/AgentsSkills/SkillUpdatePlan.swift b/Sources/AgentsSkills/SkillUpdatePlan.swift index 2b11c28..ecbf3e0 100644 --- a/Sources/AgentsSkills/SkillUpdatePlan.swift +++ b/Sources/AgentsSkills/SkillUpdatePlan.swift @@ -2,7 +2,7 @@ import AgentsCore import Foundation /// A domain plan borrows the scope lock and never commits or prunes independently. -package final class SkillUpdatePlan { +package final class SkillUpdatePlan: PreparedEvidence { package let next: ResolvedState package let results: [UpdateResult] package let targetPaths: [URL] diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 5c5bcc9..dc092c4 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -88,11 +88,7 @@ final class UpdatePlan { try instructions.retain() try checkpoint("apply.retained") let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) - transaction.validateBeforePublication = { [unowned transaction] in - try self.baseline.validate(excludingTargets: transaction.targetPaths) - try self.skills.validate(excludingTargets: transaction.targetPaths) - try self.instructions.validate(excludingTargets: transaction.targetPaths) - } + transaction.requireUnchanged(since: baseline, skills, instructions) try skills.stage(retained: retained, transaction: transaction) try instructions.stage(transaction: transaction) try store.stageDeclaration( @@ -101,7 +97,7 @@ final class UpdatePlan { comparedTo: baseline.bytes(for: store.resolvedURL)) { try transaction.replace( - store.resolvedURL, content: nil, data: resolvedBytes, + store.resolvedURL, with: .data(resolvedBytes), expecting: baseline.evidence(for: store.resolvedURL)) } try SourceCache(store: store).prune( diff --git a/Tests/AgentsCoreTests/CachePublicationTests.swift b/Tests/AgentsCoreTests/CachePublicationTests.swift index 5ac19e4..78e36fe 100644 --- a/Tests/AgentsCoreTests/CachePublicationTests.swift +++ b/Tests/AgentsCoreTests/CachePublicationTests.swift @@ -11,10 +11,10 @@ struct CachePublicationTests { arguments: ["cache-content", "cache-git"], [ TransactionCheckpoint.copy( - 0, .init(path: TransactionScratch.staged.name(0), step: .directoryCreated) + 0, .init(path: TransactionSlot.staged.name(0), step: .directoryCreated) ).name, TransactionCheckpoint.copy( - 0, .init(path: TransactionScratch.staged.name(0) + "/SKILL.md", step: .entryCopied) + 0, .init(path: TransactionSlot.staged.name(0) + "/SKILL.md", step: .entryCopied) ).name, TransactionCheckpoint.progress(0, .ready).name, TransactionCheckpoint.publication(0, .created).name, TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, @@ -68,7 +68,7 @@ struct CachePublicationTests { TransactionCheckpoint.stage(0, .workCreated).name, TransactionCheckpoint.stage(0, .workPrepared).name, ]) - func interruptedExtractionCleansJournalOwnedScratch(_ point: String) throws { + func interruptedExtractionCleansJournalOwnedWork(_ point: String) throws { let fixture = try CacheFixture(git: true) try interrupt(fixture, kind: "cache-git", point: point) #expect(try FileSnapshot.read(at: fixture.destination) == nil) @@ -94,7 +94,7 @@ struct CachePublicationTests { where name.hasPrefix(".agents-") { try Data("tampered".utf8).write( to: parent.appendingPathComponent(name).appendingPathComponent( - TransactionScratch.staged.name(0) + "/injected")) + TransactionSlot.staged.name(0) + "/injected")) } } } @@ -124,7 +124,7 @@ struct CachePublicationTests { where name.hasPrefix(".agents-") { try Data("tampered".utf8).write( to: parent.appendingPathComponent(name).appendingPathComponent( - TransactionScratch.staged.name(0))) + TransactionSlot.staged.name(0))) } } } diff --git a/Tests/AgentsCoreTests/CheckpointUniquenessTests.swift b/Tests/AgentsCoreTests/CheckpointUniquenessTests.swift new file mode 100644 index 0000000..89eb7af --- /dev/null +++ b/Tests/AgentsCoreTests/CheckpointUniquenessTests.swift @@ -0,0 +1,132 @@ +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +/// The recorder fails on a repeated name, so repeated work in one process must name each +/// repetition. Every scenario completes under the recorder and can stop at a second repetition. +@Suite("Recorded checkpoint uniqueness") +struct CheckpointUniquenessTests { + @Test func eachStaleWatchReferenceHasItsOwnPoint() throws { + let fixture = try WatchGitFixture() + try fixture.watch.add("source", environment: fixture.environment) + var stale = [try fixture.head()] + try fixture.rewrite("second") + try fixture.watch.seen("source", environment: fixture.environment) + stale.append(try fixture.head()) + try fixture.rewrite("third") + try fixture.watch.seen("source", environment: fixture.environment) + let current = try fixture.head() + func restoreStaleReferences() throws { + for revision in stale { + try fixture.mirrorGit(["update-ref", "refs/agents-watch/" + revision, revision]) + } + try Data().write(to: fixture.store.directory.appendingPathComponent("watch-refs.pending")) + } + try restoreStaleReferences() + try fixture.recordCompletely("watch-recover") + #expect(try fixture.watchRefs() == [current]) + try restoreStaleReferences() + let second = "watch.references.0.1.deleted" + try fixture.kill( + try stateTestProcess(root: fixture.root, arguments: ["watch-recover", second]), at: second) + #expect(try fixture.recoveredWatch().sources[fixture.id]?.seen == .revision(current)) + #expect(try fixture.watchRefs() == [current]) + } + + @Test func eachAbandonedGitLockHasItsOwnPoint() throws { + let fixture = try WatchGitFixture() + try fixture.watch.add("source", environment: fixture.environment) + let locks = ["config.lock", "objects/pack/abandoned.lock"].map { + fixture.mirror.appendingPathComponent($0) + } + func abandonLocks() throws { + for lock in locks { try Data("abandoned".utf8).write(to: lock) } + } + try abandonLocks() + try fixture.recordCompletely("watch-recover") + try abandonLocks() + let second = "watch.git-lock.0.1.unlinked" + try fixture.kill( + try stateTestProcess(root: fixture.root, arguments: ["watch-recover", second]), at: second) + for lock in locks { #expect(!FileManager.default.fileExists(atPath: lock.path)) } + _ = try fixture.recoveredWatch() + #expect( + !FileManager.default.fileExists( + atPath: fixture.store.directory.appendingPathComponent("watch-refs.pending").path)) + } + + /// Payload, content and watch transactions write the same transaction names; the two nested + /// cache transactions are scoped by artifact and role. + @Test func nestedArtifactTransactionsHaveScopedPoints() throws { + let ready = TransactionCheckpoint.progress(0, .ready).name + let complete = try ArtifactWatchFixture() + let trace = try complete.record("never") + for point in [ + "watch.artifact.0.payload.0." + ready, "watch.artifact.0.content." + ready, ready, + ] { + #expect(trace.contains(point)) + } + #expect(try complete.store.loadWatch().sources.count == 1) + + let interrupted = try ArtifactWatchFixture() + let content = "watch.artifact.0.content." + ready + let child = try stateTestProcess( + root: interrupted.root, arguments: ["watch-add-artifact", content]) + defer { terminateProcess(child) } + try ProcessWait.marker( + interrupted.root.appendingPathComponent("ready"), child: child, root: interrupted.root) + try ProcessWait.stopped(child, root: interrupted.root) + terminateProcess(child) + #expect(throws: CoreError.transactionRecovered(interrupted.store.directory.path)) { + try interrupted.store.loadWatch() + } + #expect(try interrupted.store.loadWatch().sources.isEmpty) + let contents = interrupted.store.cacheDirectory.appendingPathComponent("artifact-content") + #expect((try? FileManager.default.contentsOfDirectory(atPath: contents.path)) ?? [] == []) + } +} + +private final class ArtifactWatchFixture { + let root: URL + let store: StateStore + + init() throws { + root = try temporaryDirectory() + store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: [:])) + do { + try store.save(declaration: Declaration(), resolved: ResolvedState()) + } catch { + removeTemporaryDirectory(root) + throw error + } + } + + deinit { removeTemporaryDirectory(root) } + + func record(_ point: String) throws -> [String] { + let child = try stateTestProcess(root: root, arguments: ["watch-add-artifact", point]) + defer { terminateProcess(child) } + try ProcessWait.exit(child, root: root) + #expect(child.terminationStatus == 0) + return try String( + contentsOf: root.appendingPathComponent("checkpoint-\(child.processIdentifier).log"), + encoding: .utf8 + ).split(separator: "\n").map(String.init) + } +} + +extension WatchGitFixture { + /// Runs `command` to completion under the recorder, which fails on any repeated name. + fileprivate func recordCompletely(_ command: String) throws { + let child = try stateTestProcess(root: root, arguments: [command, "never"]) + defer { terminateProcess(child) } + try ProcessWait.exit(child, root: root) + #expect(child.terminationStatus == 0) + } +} diff --git a/Tests/AgentsCoreTests/InstructionTransactionTests.swift b/Tests/AgentsCoreTests/InstructionTransactionTests.swift index 7727d4f..7e120d7 100644 --- a/Tests/AgentsCoreTests/InstructionTransactionTests.swift +++ b/Tests/AgentsCoreTests/InstructionTransactionTests.swift @@ -33,11 +33,10 @@ struct InstructionTransactionTests { if checkpoint == TransactionCheckpoint.progress(1, .applied).name { throw Interrupted() } } for file in files { - try transaction.replace( - file.resolvingSymlinksInPath(), content: nil, data: Data("new".utf8)) + try transaction.replace(file.resolvingSymlinksInPath(), with: .data(Data("new".utf8))) } try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(Declaration(agents: [.codex]))) + store.declarationURL, with: .data(StateStore.encode(Declaration(agents: [.codex])))) #expect(throws: Interrupted.self) { try transaction.commit() } } for file in files { #expect(try Data(contentsOf: file) == Data("original".utf8)) } @@ -97,7 +96,7 @@ struct InstructionTransactionTests { try store.withLock { let transaction = FileTransaction(store: store) try transaction.replace( - root.appendingPathComponent(".claude/CLAUDE.md"), content: nil, data: Data("new".utf8)) + root.appendingPathComponent(".claude/CLAUDE.md"), with: .data(Data("new".utf8))) #expect { try transaction.commit() } throws: { error in diff --git a/Tests/AgentsCoreTests/PreparationEvidenceTests.swift b/Tests/AgentsCoreTests/PreparationEvidenceTests.swift index eed1532..c080be9 100644 --- a/Tests/AgentsCoreTests/PreparationEvidenceTests.swift +++ b/Tests/AgentsCoreTests/PreparationEvidenceTests.swift @@ -13,11 +13,11 @@ struct PreparationEvidenceTests { try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) .first(where: { $0.hasPrefix(".agents-") })) let staged = fixture.root.appendingPathComponent(name).appendingPathComponent( - TransactionScratch.staged.name(0)) + TransactionSlot.staged.name(0)) try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: staged.path) } } - try transaction.replace(fixture.target, content: nil, data: Data("postimage".utf8)) + try transaction.replace(fixture.target, with: .data(Data("postimage".utf8))) #expect(throws: CoreError.invalidState("staged content permissions mismatch")) { try transaction.commit() } @@ -45,7 +45,7 @@ struct PreparationEvidenceTests { location = container } } - try transaction.replace(fixture.target, content: nil, data: Data("postimage".utf8)) + try transaction.replace(fixture.target, with: .data(Data("postimage".utf8))) #expect { try transaction.commit() } throws: { error in guard case CoreError.invalidState(let reason) = error else { return false } return reason.contains("private container changed before its identity was durable") @@ -57,21 +57,23 @@ struct PreparationEvidenceTests { } @Test(arguments: [PublicationOperation.fileCreate, .directoryDelete]) - func reservedScratchIsRejectedBeforeSealingAndDiscarded(_ operation: PublicationOperation) throws - { + func reservedSlotIsRejectedBeforeSealingAndDiscarded(_ operation: PublicationOperation) throws { let fixture = try PublicationFixture(operation) let transaction = FileTransaction(store: fixture.store) { point in if point == TransactionCheckpoint.stage(0, .constructed).name { let name = try #require( try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) .first(where: { $0.hasPrefix(".agents-") })) - let slot: TransactionScratch = operation == .directoryDelete ? .staged : .deleted + let slot: TransactionSlot = operation == .directoryDelete ? .staged : .deleted try Data("private injection".utf8).write( to: fixture.root.appendingPathComponent(name).appendingPathComponent(slot.name(0))) } } - try transaction.replace( - fixture.target, content: nil, data: operation == .fileCreate ? Data("postimage".utf8) : nil) + if operation == .fileCreate { + try transaction.replace(fixture.target, with: .data(Data("postimage".utf8))) + } else { + try transaction.delete(fixture.target) + } #expect(throws: CoreError.invalidState("unexpected private recovery slot before sealing")) { try transaction.commit() } @@ -87,13 +89,13 @@ struct PreparationEvidenceTests { try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) .first(where: { $0.hasPrefix(".agents-") })) let staged = fixture.root.appendingPathComponent(name).appendingPathComponent( - TransactionScratch.staged.name(0)) + TransactionSlot.staged.name(0)) try FileManager.default.removeItem(at: staged) try FileManager.default.createSymbolicLink( atPath: staged.path, withDestinationPath: "postimage") } } - try transaction.replace(fixture.target, content: nil, data: Data("postimage".utf8)) + try transaction.replace(fixture.target, with: .data(Data("postimage".utf8))) #expect(throws: CoreError.invalidState("staged content type mismatch")) { try transaction.commit() } @@ -110,7 +112,7 @@ struct PreparationEvidenceTests { try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) .first(where: { $0.hasPrefix(".agents-") })) let staged = fixture.root.appendingPathComponent(name).appendingPathComponent( - TransactionScratch.staged.name(0)) + TransactionSlot.staged.name(0)) if link { try FileManager.default.removeItem(at: staged) try FileManager.default.createSymbolicLink( @@ -121,7 +123,10 @@ struct PreparationEvidenceTests { } } try transaction.replace( - fixture.target, content: fixture.root.appendingPathComponent("new"), link: link) + fixture.target, + with: link + ? .link(fixture.root.appendingPathComponent("new")) + : .copy(fixture.root.appendingPathComponent("new"))) #expect( throws: CoreError.invalidState( link ? "staged symbolic link destination mismatch" : "staged content digest mismatch") @@ -134,7 +139,7 @@ struct PreparationEvidenceTests { let fixture = try PublicationFixture(.fileCreate) let source = fixture.root.appendingPathComponent("new/nested/file") let transaction = FileTransaction(store: fixture.store) - try transaction.replace(fixture.target, content: source) + try transaction.replace(fixture.target, with: .copy(source)) try transaction.commit() #expect(try Data(contentsOf: fixture.target) == Data(contentsOf: source)) #expect( @@ -161,7 +166,7 @@ struct PreparationEvidenceTests { #expect(try prepared.bytes(for: store.declarationURL) == original) let transaction = FileTransaction(store: store) try transaction.replace( - store.declarationURL, content: nil, data: original, + store.declarationURL, with: .data(original), expecting: prepared.evidence(for: store.declarationURL)) #expect { try transaction.commit() diff --git a/Tests/AgentsCoreTests/ProcessTerminationTests.swift b/Tests/AgentsCoreTests/ProcessTerminationTests.swift index 2b974b0..30c0b41 100644 --- a/Tests/AgentsCoreTests/ProcessTerminationTests.swift +++ b/Tests/AgentsCoreTests/ProcessTerminationTests.swift @@ -46,11 +46,11 @@ struct ProcessTerminationTests { #expect(throws: (any Error).self) { try ProcessWait.stopped(child, root: root, timeout: 0.5) } let start = Date() try ProcessWait.terminate(child, timeout: 10) - #expect(Date().timeIntervalSince(start) < 10) + #expect(Date().timeIntervalSince(start) < 2) #expect(child.terminationReason == .uncaughtSignal) } - @Test func lostSignalsAreResentAndTheLoopIsBounded() throws { + @Test func terminationLoopIsBoundedWhenSignalsNeverArrive() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } let child = try stateTestProcess(root: root, arguments: ["unstopped-marker"]) @@ -61,14 +61,7 @@ struct ProcessTerminationTests { try ProcessWait.terminate(child, timeout: 0.5, send: { _ in }) } let elapsed = Date().timeIntervalSince(start) - #expect(elapsed >= 0.5 && elapsed < 5) + #expect(elapsed >= 0.5 && elapsed < 2) #expect(child.isRunning) - var sends = 0 - try ProcessWait.terminate(child, timeout: 10) { processIdentifier in - sends += 1 - if sends > 1 { kill(processIdentifier, SIGKILL) } - } - #expect(sends >= 2) - #expect(child.terminationReason == .uncaughtSignal) } } diff --git a/Tests/AgentsCoreTests/PublicationTests.swift b/Tests/AgentsCoreTests/PublicationTests.swift index 2586a38..db5aec7 100644 --- a/Tests/AgentsCoreTests/PublicationTests.swift +++ b/Tests/AgentsCoreTests/PublicationTests.swift @@ -7,20 +7,18 @@ import Testing @Suite("Journal publication and ownership") struct PublicationTests { - @Test(.tags(.publicationMatrix), arguments: PublicationMatrix.publications) + @Test(arguments: PublicationMatrix.publications) func killedPublicationAtEachStageRecoversPhysicalGeneration(_ fault: PublicationFault) throws { try fault.checkSetup() let fixture = try PublicationFixture(fault.operation) - let child = try fixture.pause("publication", at: fault.point) - defer { terminateProcess(child) } - terminateProcess(child) + terminateProcess(try fixture.pause("publication", at: fault.point)) let journal = try fixture.lastJournal() try fixture.recover(expected: fault.committed ? .committed : .unchanged) try fixture.check(committed: fault.committed, journal: journal) try fixture.expectClean() } - @Test(.tags(.publicationMatrix), arguments: PublicationMatrix.recoveries) + @Test(arguments: PublicationMatrix.recoveries) func recoveryCanBeKilledAtEachStageAndRepeated(_ fault: PublicationFault) throws { try fault.checkSetup() let fixture = try PublicationFixture(fault.operation) @@ -84,6 +82,9 @@ struct PublicationTests { } let external = try FileSnapshot.read(at: fixture.target) try fixture.resume(child) + let trace = try fixture.trace(child) + #expect(!trace.contains(TransactionCheckpoint.progress(1, .publishing).name)) + #expect(trace.contains("recovery." + TransactionCheckpoint.progress(1, .cancelled).name)) let result = try fixture.result("publication-result") #expect(result.hasPrefix("unchanged\n")) #expect(result.contains("preparation is stale; prepare again")) @@ -147,12 +148,12 @@ struct PublicationTests { let postimage = try #require(journal.entries[1].staged) #expect(try FileSnapshot.read(at: fixture.target) == postimage) #expect( - try FileSnapshot.read(at: fixture.scratch(.exchanged, entry: 1, journal: journal)) == external + try FileSnapshot.read(at: fixture.slot(.exchanged, entry: 1, journal: journal)) == external ) try fixture.expectUnresolved() #expect(try FileSnapshot.read(at: fixture.target) == postimage) #expect( - try FileSnapshot.read(at: fixture.scratch(.exchanged, entry: 1, journal: journal)) == external + try FileSnapshot.read(at: fixture.slot(.exchanged, entry: 1, journal: journal)) == external ) if !inPlace { #expect( @@ -170,8 +171,8 @@ struct PublicationTests { "publication", at: TransactionCheckpoint.progress(1, .applied).name) defer { terminateProcess(child) } let journal = try #require(try fixture.lastJournal()) - let slot: TransactionScratch = operation == .directoryDelete ? .deleted : .exchanged - let original = fixture.scratch(slot, entry: 1, journal: journal) + let slot: TransactionSlot = operation == .directoryDelete ? .deleted : .exchanged + let original = fixture.slot(slot, entry: 1, journal: journal) let saved = fixture.root.appendingPathComponent("saved-preimage") let lease = try #require(fixture.beforeTarget).writeLease if let lease { @@ -181,7 +182,7 @@ struct PublicationTests { try FileManager.default.moveItem(at: original, to: saved) if let lease { try FileManager.default.setAttributes( - [.posixPermissions: lease.original], ofItemAtPath: saved.path) + [.posixPermissions: lease.originalMode], ofItemAtPath: saved.path) } let published = try FileSnapshot.read(at: fixture.target) terminateProcess(child) @@ -191,7 +192,7 @@ struct PublicationTests { #expect(try fixture.lastJournal()?.phase == .applying) } - @Test func missingRollbackQuarantineIsUnresolvedBeforeTerminalIntent() throws { + @Test func missingWithdrawnObjectIsUnresolvedBeforeDisposalIntent() throws { let fixture = try PublicationFixture(.fileCreate) terminateProcess( try fixture.pause("publication", at: TransactionCheckpoint.publication(1, .created).name)) @@ -199,9 +200,9 @@ struct PublicationTests { "publication-recover", at: TransactionCheckpoint.progress(1, .restored).name) defer { terminateProcess(recovery) } let journal = try #require(try fixture.lastJournal()) - let quarantined = fixture.scratch(.withdrawn, entry: 1, journal: journal) + let withdrawn = fixture.slot(.withdrawn, entry: 1, journal: journal) let saved = fixture.root.appendingPathComponent("saved-postimage") - try FileManager.default.moveItem(at: quarantined, to: saved) + try FileManager.default.moveItem(at: withdrawn, to: saved) terminateProcess(recovery) try fixture.expectUnresolved() #expect(try FileSnapshot.read(at: fixture.target) == nil) @@ -227,8 +228,8 @@ struct PublicationTests { #expect(try fixture.result("recovery-result").hasPrefix("unresolved:")) let location: URL switch operation { - case .fileCreate: location = fixture.scratch(.withdrawn, entry: 1, journal: journal) - case .fileReplace: location = fixture.scratch(.exchanged, entry: 1, journal: journal) + case .fileCreate: location = fixture.slot(.withdrawn, entry: 1, journal: journal) + case .fileReplace: location = fixture.slot(.exchanged, entry: 1, journal: journal) default: location = fixture.target } #expect(try FileSnapshot.read(at: location) == external) @@ -239,7 +240,7 @@ struct PublicationTests { #expect(try FileSnapshot.read(at: location) == external) if operation == .directoryDelete { #expect( - try FileSnapshot.read(at: fixture.scratch(.deleted, entry: 1, journal: journal)) + try FileSnapshot.read(at: fixture.slot(.deleted, entry: 1, journal: journal)) == fixture.beforeTarget) } else { #expect( @@ -262,7 +263,7 @@ struct PublicationTests { #expect(try FileSnapshot.read(at: fixture.target) == external) #expect(try FileSnapshot.read(at: saved) == journal.entries[1].staged) #expect( - try FileSnapshot.read(at: fixture.scratch(.exchanged, entry: 1, journal: journal)) + try FileSnapshot.read(at: fixture.slot(.exchanged, entry: 1, journal: journal)) == fixture.beforeTarget) } @@ -292,7 +293,7 @@ struct PublicationTests { terminateProcess( try fixture.pause("publication", at: TransactionCheckpoint.progress(1, .ready).name)) let journal = try #require(try fixture.lastJournal()) - let file = fixture.scratch(.exchanged, entry: 1, journal: journal) + let file = fixture.slot(.exchanged, entry: 1, journal: journal) try Data("changed after sealing".utf8).write(to: file) let changed = try FileSnapshot.read(at: file) try fixture.expectUnresolved() @@ -329,7 +330,7 @@ struct PublicationTests { let fixture = try PublicationFixture(.fileReplace) let outcome = TransactionOutcome() let transaction = FileTransaction(store: fixture.store, outcome: outcome) - try transaction.replace(fixture.target, content: nil, data: Data("postimage".utf8)) + try transaction.replace(fixture.target, with: .data(Data("postimage".utf8))) let operation = mode == .exchange ? "exchange atomic probe" : "check exclusive atomic probe collision" let expected: CoreError = @@ -423,7 +424,7 @@ struct PublicationTests { if field == "identity" { journal.containers[0].identity = nil } else { - journal.containers[0].cleanup = nil + journal.containers[0].disposal = nil } try StateStore.encode(journal).write( to: fixture.store.directory.appendingPathComponent("transaction.json")) @@ -444,7 +445,7 @@ struct PublicationTests { let digest = "sha256:" + FileHash.sha256Hex(data: Data("artifact".utf8)) let transaction = FileTransaction(store: fixture.store) let target = try cache.artifactURL(digest: digest) - try transaction.replace(target, content: nil, data: bytes, expectedHash: digest) + try transaction.replace(target, with: .data(bytes), expectedHash: digest) try Data("{\"agents\":[]}".utf8).write(to: fixture.store.declarationURL) let state = try FileSnapshot.read(at: fixture.store.declarationURL) try transaction.commit() @@ -460,30 +461,65 @@ enum PublicationOperation: String, CaseIterable, Sendable { var renamePoint: String { switch self { - case .directoryDelete: TransactionCheckpoint.publication(1, .quarantined).name + case .directoryDelete: TransactionCheckpoint.publication(1, .deleted).name case .fileReplace, .directoryReplace, .crossParentReplace: TransactionCheckpoint.publication(1, .exchanged).name case .symlinkCreate, .fileCreate: TransactionCheckpoint.publication(1, .created).name } } + /// Undo of the target's publication rename. + var reverseRenamePoint: String { + switch self { + case .directoryDelete: TransactionCheckpoint.restoration(1, .returned).name + case .fileReplace, .directoryReplace, .crossParentReplace: + TransactionCheckpoint.restoration(1, .exchanged).name + case .symlinkCreate, .fileCreate: TransactionCheckpoint.restoration(1, .withdrawn).name + } + } + + var leasesDirectories: Bool { self == .directoryReplace || self == .directoryDelete } + /// Recovery starts from construction, sealed staging, an interrupted rename or directory - /// grant, an applied entry, the committed marker and terminal cleanup. - var recoverySeeds: [(point: String, committed: Bool)] { + /// grant, an applied entry, the committed marker and terminal disposal. + var recoverySeeds: [RecoverySeed] { var seeds = [ - (TransactionCheckpoint.stage(1, .constructed).name, false), - (TransactionCheckpoint.progress(1, .ready).name, false), - (renamePoint, false), - (TransactionCheckpoint.progress(1, .applied).name, false), - (TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, true), - (TransactionCheckpoint.discardIntent.name, true), + RecoverySeed(point: TransactionCheckpoint.stage(1, .constructed).name), + RecoverySeed(point: TransactionCheckpoint.progress(1, .ready).name), + RecoverySeed(point: renamePoint, renamed: true), + RecoverySeed(point: TransactionCheckpoint.progress(1, .applied).name, renamed: true), + RecoverySeed( + point: TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, + committed: true), + RecoverySeed(point: TransactionCheckpoint.disposalIntent.name, committed: true), ] - if self == .directoryReplace || self == .directoryDelete { + if leasesDirectories { seeds.append( - (TransactionCheckpoint.permissions(1, .publicationGrant, .target, .changed).name, false)) + RecoverySeed( + point: TransactionCheckpoint.permissions(1, .publicationGrant, .target, .changed).name)) } return seeds } + + /// Points every recovery from `seed` must reach. + func requiredRecoveryPoints(from seed: RecoverySeed) -> Set { + var points = [ + TransactionCheckpoint.journalSynced.name, TransactionCheckpoint.journalRemoved.name, + ] + if !seed.committed { + points.append(TransactionCheckpoint.persisted(.rolledBack, .terminal, .renamed).name) + } + if seed.renamed { points.append(reverseRenamePoint) } + return Set(points) + } +} + +/// A publication interruption that recovery starts from. +struct RecoverySeed: Sendable { + let point: String + var committed = false + /// The target's publication rename has happened, so rollback must reverse it. + var renamed = false } struct PublicationFault: Sendable, CustomTestStringConvertible { @@ -502,34 +538,39 @@ struct PublicationFault: Sendable, CustomTestStringConvertible { } } -extension Tag { - /// Kill-point matrices recorded from real traces. - @Tag static var publicationMatrix: Self -} - -/// By default each operation is killed at its representative points and recovery from every -/// seed at its durable recovery steps. `AGENTS_PUBLICATION_MATRIX=full` kills at every -/// recorded point. +/// Kill-point matrices recorded from real traces. By default publication tests kill each +/// operation at representative points, and kill recovery at durable steps from each seeded +/// interruption; `AGENTS_PUBLICATION_MATRIX=full` kills at every recorded point. private enum PublicationMatrix { static let complete = ProcessInfo.processInfo.environment["AGENTS_PUBLICATION_MATRIX"] == "full" static let publications = record(recovery: false) static let recoveries = record(recovery: true) - /// Every recovery seed, durable intent and the removal of the first container. + /// Every recovery seed, durable intent, the synced rename, the mode restoration and the + /// removal of the first container. private static func representativePublication(_ operation: PublicationOperation) -> Set { - Set( + var points = operation.recoverySeeds.map(\.point) + [ TransactionCheckpoint.progress(1, .publishing).name, + TransactionCheckpoint.publication(1, .synced).name, TransactionCheckpoint.containerRemoved(0).name, - ]) + ] + if operation.leasesDirectories { + // A deleted directory's mode is restored in its slot; a replacement's at the target. + let location: TransactionObjectLocation = + operation == .directoryDelete ? .slot(.deleted) : .target + points.append( + TransactionCheckpoint.permissions(1, .publicationRestore, location, .changed).name) + } + return Set(points) } - /// The observed-journal barrier, each durable recovery write, each reverse rename or undo - /// grant, and disposal. + /// The observed-journal barrier, each durable recovery write, each reverse rename, undo + /// grant and mode restoration, and disposal. private static let representativeRecovery: Set = { var points: [TransactionCheckpoint] = [.journalSynced, .containerRemoved(0), .journalRemoved] for phase in [TransactionJournal.Phase.applying, .committed, .rolledBack] { - points += [.persisted(phase, .terminal, .renamed), .persisted(phase, .discard, .renamed)] + points += [.persisted(phase, .terminal, .renamed), .persisted(phase, .disposing, .renamed)] for index in 0...1 { for progress in [TransactionJournal.Progress.restoring, .restored, .cancelled] { points.append(.persisted(phase, .entry(index, progress), .renamed)) @@ -539,8 +580,10 @@ private enum PublicationMatrix { for index in 0...1 { points += [ .restoration(index, .exchanged), .restoration(index, .returned), - .restoration(index, .creationQuarantined), + .restoration(index, .withdrawn), .restoration(index, .synced), .permissions(index, .undoGrant, .target, .changed), + .permissions(index, .undoRestore, .target, .changed), + .permissions(index, .cancelRestore, .target, .changed), ] } return Set(points.map(\.name)) @@ -551,8 +594,7 @@ private enum PublicationMatrix { let commitMarker = TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name for operation in PublicationOperation.allCases { let selected = recovery ? representativeRecovery : representativePublication(operation) - let seeds: [(point: String, committed: Bool)?] = - recovery ? operation.recoverySeeds.map { $0 } : [nil] + let seeds: [RecoverySeed?] = recovery ? operation.recoverySeeds.map { $0 } : [nil] for seed in seeds { do { let fixture = try PublicationFixture(operation) @@ -568,9 +610,10 @@ private enum PublicationMatrix { guard !trace.isEmpty, Set(trace).count == trace.count else { throw CoreError.invalidState("checkpoint names are empty or repeated") } - if !recovery, !selected.isSubset(of: trace) { + let required = seed.map(operation.requiredRecoveryPoints(from:)) ?? selected + if !required.isSubset(of: trace) { throw CoreError.invalidState( - "representative points were not recorded: \(selected.subtracting(trace).sorted())") + "representative points were not recorded: \(required.subtracting(trace).sorted())") } var committed = seed?.committed ?? false for point in trace { @@ -720,7 +763,7 @@ final class PublicationFixture { .appendingPathComponent(journal.containerName(index)) } - func scratch(_ slot: TransactionScratch, entry index: Int, journal: TransactionJournal) -> URL { + func slot(_ slot: TransactionSlot, entry index: Int, journal: TransactionJournal) -> URL { container(journal.entries[index].container, journal: journal) .appendingPathComponent(slot.name(index)) } @@ -747,7 +790,7 @@ final class PublicationFixture { func expectUnresolved( containing expected: String = - "missing or changed expected target, preimage or rollback quarantine" + "missing or changed expected target or recovery slot object" ) throws { let outcome = TransactionOutcome() outcome.journalID = try lastJournal()?.id diff --git a/Tests/AgentsCoreTests/StateTransactionTests.swift b/Tests/AgentsCoreTests/StateTransactionTests.swift index 1ffb5e4..3e80ffa 100644 --- a/Tests/AgentsCoreTests/StateTransactionTests.swift +++ b/Tests/AgentsCoreTests/StateTransactionTests.swift @@ -21,7 +21,7 @@ struct StateTransactionTests { } try transaction.replace( parent.appendingPathComponent("pruned"), - content: fixture.root.appendingPathComponent("new")) + with: .copy(fixture.root.appendingPathComponent("new"))) #expect(throws: CoreError.invalidState("cache cleanup interrupted")) { try transaction.commit() } @@ -146,21 +146,19 @@ final class TransactionFixture { let transaction = FileTransaction(store: store, checkpoint: checkpoint) try transaction.replace( root.appendingPathComponent(".agents/skills/target"), - content: root.appendingPathComponent("new")) + with: .copy(root.appendingPathComponent("new"))) try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(Declaration(agents: [.codex]))) + store.declarationURL, with: .data(StateStore.encode(Declaration(agents: [.codex])))) try transaction.replace( - store.resolvedURL, content: nil, - data: StateStore.encode(ResolvedState(sources: ["local:/new": LockedSource(kind: .local)]))) - try transaction.replace( - root.appendingPathComponent(".agent/cache/artifact-content/pruned"), content: nil) + store.resolvedURL, + with: .data( + StateStore.encode(ResolvedState(sources: ["local:/new": LockedSource(kind: .local)])))) + try transaction.delete(root.appendingPathComponent(".agent/cache/artifact-content/pruned")) try transaction.replace( root.appendingPathComponent(".claude/skills/created"), - content: root.appendingPathComponent("new"), - link: true) + with: .link(root.appendingPathComponent("new"))) try transaction.replace( - root.appendingPathComponent("AGENTS.md"), content: nil, - data: Data("new instructions".utf8)) + root.appendingPathComponent("AGENTS.md"), with: .data(Data("new instructions".utf8))) try transaction.commit() } } @@ -264,7 +262,7 @@ extension StateTransactionTests { let recovery = try stateTestProcess( root: fixture.root, arguments: [ - "recover", TransactionCheckpoint.restoration(4, .creationQuarantined).name, "--scope", + "recover", TransactionCheckpoint.restoration(4, .withdrawn).name, "--scope", scope.rawValue, ]) defer { terminateProcess(recovery) } @@ -278,13 +276,13 @@ extension StateTransactionTests { let recovered = try FileTransaction.recover(store: store) { steps.append($0) } #expect(recovered) } - #expect(!steps.contains(TransactionCheckpoint.restoration(4, .creationQuarantined).name)) + #expect(!steps.contains(TransactionCheckpoint.restoration(4, .withdrawn).name)) let synced = try #require( steps.firstIndex(of: TransactionCheckpoint.restoration(4, .synced).name)) let terminal = try #require( steps.firstIndex(of: TransactionCheckpoint.persisted(.rolledBack, .terminal, .renamed).name)) - let cleanup = try #require(steps.firstIndex(of: TransactionCheckpoint.discardIntent.name)) - #expect(synced < terminal && terminal < cleanup) + let disposal = try #require(steps.firstIndex(of: TransactionCheckpoint.disposalIntent.name)) + #expect(synced < terminal && terminal < disposal) #expect(try Data(contentsOf: store.declarationURL) == declaration) #expect(try Data(contentsOf: store.resolvedURL) == resolved) #expect(try Data(contentsOf: fixture.store.resolvedURL) == projectState) @@ -451,14 +449,14 @@ extension StateTransactionTests { #expect(try FileSnapshot.read(at: copy) == copyHash) } - @Test(arguments: ["journal", "scratch", "cache", "agent"]) + @Test(arguments: ["journal", "incompleteJournal", "cache", "agent"]) func rejectsSymlinkedRecoveryPaths(_ component: String) throws { let fixture = try TransactionFixture() try abandon(fixture) let original: URL switch component { case "journal": original = fixture.store.directory.appendingPathComponent("transaction.json") - case "scratch": + case "incompleteJournal": original = fixture.store.directory.appendingPathComponent("transaction.new") try Data("incomplete".utf8).write(to: original) case "cache": original = fixture.store.cacheDirectory.appendingPathComponent("artifact-content") @@ -474,7 +472,8 @@ extension StateTransactionTests { } guard case CoreError.unsafePath(let reason) = error else { return false } return reason.contains( - component == "journal" || component == "scratch" ? "cannot open file" : "unsafe directory") + component == "journal" || component == "incompleteJournal" + ? "cannot open file" : "unsafe directory") } #expect(try FileSnapshot.read(at: fixture.root) == snapshot) } @@ -524,11 +523,8 @@ extension StateTransactionTests { defer { removeTemporaryDirectory(root) } try FileManager.default.createDirectory( at: root.appendingPathComponent(".claude/skills"), withIntermediateDirectories: true) - func lockPoint(_ step: DirectoryHandle.AncestryStep) -> String { - "lock.ancestry." + step.name - } let child = try stateTestProcess( - root: root, arguments: ["create-scope", lockPoint(.created(depth: 0))]) + root: root, arguments: ["create-scope", FileLock.ancestryCheckpoint(.created(depth: 0))]) defer { terminateProcess(child) } try waitFor("ready", root: root, child: child) #expect( @@ -553,8 +549,10 @@ extension StateTransactionTests { at: new.appendingPathComponent(".agents.lock"), checkpoint: { steps.append($0) }, { for depth in 0...2 { - let created = try #require(steps.firstIndex(of: lockPoint(.created(depth: depth)))) - let synced = try #require(steps.firstIndex(of: lockPoint(.synced(depth: depth)))) + let created = try #require( + steps.firstIndex(of: FileLock.ancestryCheckpoint(.created(depth: depth)))) + let synced = try #require( + steps.firstIndex(of: FileLock.ancestryCheckpoint(.synced(depth: depth)))) #expect(created < synced) } #expect(steps.count == 6) @@ -607,15 +605,15 @@ extension StateTransactionTests { } } for target in targets { - try transaction.replace(target, content: fixture.root.appendingPathComponent("new")) + try transaction.replace(target, with: .copy(fixture.root.appendingPathComponent("new"))) } try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(Declaration(agents: [.codex])) - ) + store.declarationURL, with: .data(StateStore.encode(Declaration(agents: [.codex])))) try transaction.replace( - store.resolvedURL, content: nil, - data: StateStore.encode( - ResolvedState(sources: ["local:/new": LockedSource(kind: .local)]))) + store.resolvedURL, + with: .data( + StateStore.encode( + ResolvedState(sources: ["local:/new": LockedSource(kind: .local)])))) try transaction.commit() } } diff --git a/Tests/AgentsCoreTests/TransactionCostTests.swift b/Tests/AgentsCoreTests/TransactionCostTests.swift index 24d7200..12e93d2 100644 --- a/Tests/AgentsCoreTests/TransactionCostTests.swift +++ b/Tests/AgentsCoreTests/TransactionCostTests.swift @@ -21,19 +21,16 @@ struct TransactionCostTests { let count = TransactionIOCount() try store.withLock { let transaction = FileTransaction(store: store) { step in - if step.hasPrefix("journal."), step.hasSuffix(".renamed") { count.persist() } + if TransactionCheckpoint.isJournalPublished(step) { count.persist() } if step == TransactionCheckpoint.probe(0, .verified).name { count.probe() } } for target in targets { - try transaction.replace(target, content: nil, data: Data("after".utf8)) + try transaction.replace(target, with: .data(Data("after".utf8))) } try DirectoryHandle.$synchronizationObserver.withValue({ count.sync() }) { try transaction.commit() } } - print( - "TWO_SMALL_FILES persists=\(count.persists) barriers=\(count.barriers) ancestry=\(ancestry)" - ) #expect(count.persists == 10) #expect(count.probes == 1) #expect(count.barriers - ancestry == 38) @@ -53,9 +50,9 @@ struct TransactionCostTests { try store.withLock { let transaction = FileTransaction(store: store) { steps.append($0) } try transaction.replace( - root.appendingPathComponent("AGENTS.md"), content: nil, data: Data("after".utf8)) + root.appendingPathComponent("AGENTS.md"), with: .data(Data("after".utf8))) try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(Declaration(agents: [.codex]))) + store.declarationURL, with: .data(StateStore.encode(Declaration(agents: [.codex])))) try transaction.commit() } #expect(steps.contains(TransactionCheckpoint.containerCreated(1).name)) diff --git a/Tests/AgentsCoreTests/TransactionMetadataTests.swift b/Tests/AgentsCoreTests/TransactionMetadataTests.swift index cff6b3b..aed6310 100644 --- a/Tests/AgentsCoreTests/TransactionMetadataTests.swift +++ b/Tests/AgentsCoreTests/TransactionMetadataTests.swift @@ -28,7 +28,7 @@ struct TransactionMetadataTests { if step == point { throw CoreError.invalidState("injected failure") } } for file in files + [created] { - try transaction.replace(file, content: nil, data: replacement) + try transaction.replace(file, with: .data(replacement)) } if point == "complete" { try transaction.commit() diff --git a/Tests/AgentsCoreTests/WatchGitLockTests.swift b/Tests/AgentsCoreTests/WatchGitLockTests.swift index fb9a4c6..92f21fc 100644 --- a/Tests/AgentsCoreTests/WatchGitLockTests.swift +++ b/Tests/AgentsCoreTests/WatchGitLockTests.swift @@ -88,8 +88,8 @@ struct WatchGitLockTests { } for lock in additional { try Data("abandoned".utf8).write(to: lock) } let recovery = try stateTestProcess( - root: fixture.root, arguments: ["watch-recover", "watch.git-lock.unlinked"]) - try fixture.kill(recovery, at: "watch.git-lock.unlinked") + root: fixture.root, arguments: ["watch-recover", "watch.git-lock.0.0.unlinked"]) + try fixture.kill(recovery, at: "watch.git-lock.0.0.unlinked") #expect( try fixture.recoveredWatch().sources[fixture.id]?.seen == (removing ? nil : .revision(replacement))) diff --git a/Tests/AgentsCoreTests/WatchInspectionTests.swift b/Tests/AgentsCoreTests/WatchInspectionTests.swift index 6329af1..5dad158 100644 --- a/Tests/AgentsCoreTests/WatchInspectionTests.swift +++ b/Tests/AgentsCoreTests/WatchInspectionTests.swift @@ -28,7 +28,7 @@ struct WatchInspectionTests { #expect(try FileHash.folderHash(fixture.store.directory) == before) } - @Test(arguments: [TransactionCheckpoint.journalRemoved.name, "watch.references.deleted"]) + @Test(arguments: [TransactionCheckpoint.journalRemoved.name, "watch.references.0.0.deleted"]) func pendingRefCleanupLeavesStateUnchanged(_ step: String) throws { let fixture = try WatchGitFixture() let first = try fixture.head() diff --git a/Tests/AgentsCoreTests/WatchPreparationTests.swift b/Tests/AgentsCoreTests/WatchPreparationTests.swift index 45a969a..79b9a14 100644 --- a/Tests/AgentsCoreTests/WatchPreparationTests.swift +++ b/Tests/AgentsCoreTests/WatchPreparationTests.swift @@ -31,13 +31,19 @@ struct WatchPreparationTests { #expect(try FileSnapshot.read(at: fixture.store.watchURL) == watchBefore) } + /// Control for the lock edit below: the unchanged lock lets the same seen prune the entry. + @Test func unchangedLockPrunesUnreferencedCache() throws { + let fixture = try WatchGitFixture() + try fixture.watch.add("source", environment: fixture.environment) + let unreferenced = try fixture.unreferencedCacheEntry() + try fixture.watch.seen("source", environment: fixture.environment) + #expect(try FileSnapshot.read(at: unreferenced) == nil) + } + @Test func lockEditedDuringAcknowledgmentPreventsPruning() throws { let fixture = try WatchGitFixture() try fixture.watch.add("source", environment: fixture.environment) - let unreferenced = fixture.store.cacheDirectory.appendingPathComponent( - "artifact-content/" + String(repeating: "a", count: 64)) - try FileManager.default.createDirectory(at: unreferenced, withIntermediateDirectories: true) - try Data("unreferenced".utf8).write(to: unreferenced.appendingPathComponent("SKILL.md")) + let unreferenced = try fixture.unreferencedCacheEntry() let cached = try FileSnapshot.read(at: unreferenced) let declaration = try FileSnapshot.read(at: fixture.store.declarationURL) let watchBefore = try FileSnapshot.read(at: fixture.store.watchURL) @@ -81,7 +87,7 @@ private final class ExternalEdit: @unchecked Sendable { } extension WatchGitFixture { - /// Runs `edit` once, after the Git fetch and before the scope journal is written. + /// Runs `edit` after each Git fetch of an acknowledgment, before the scope journal is written. fileprivate func operations(edit: @escaping @Sendable () throws -> Void) -> WatchOperations { WatchOperations( discoverSkills: { _ in [] }, @@ -90,4 +96,13 @@ extension WatchGitFixture { if step == "watch.mirror.fetched" { try edit() } }) } + + /// An artifact tree that neither the lock nor watch state references. + fileprivate func unreferencedCacheEntry() throws -> URL { + let entry = store.cacheDirectory.appendingPathComponent( + "artifact-content/" + String(repeating: "a", count: 64)) + try FileManager.default.createDirectory(at: entry, withIntermediateDirectories: true) + try Data("unreferenced".utf8).write(to: entry.appendingPathComponent("SKILL.md")) + return entry + } } diff --git a/Tests/AgentsCoreTests/WatchReferenceTests.swift b/Tests/AgentsCoreTests/WatchReferenceTests.swift index aad4deb..e492e95 100644 --- a/Tests/AgentsCoreTests/WatchReferenceTests.swift +++ b/Tests/AgentsCoreTests/WatchReferenceTests.swift @@ -7,7 +7,7 @@ import Testing struct WatchReferenceTests { @Test( arguments: [false, true], - ["watch.references.deleted", "watch.references.synced", "watch.references.cleared"]) + ["watch.references.0.0.deleted", "watch.references.0.synced", "watch.references.cleared"]) func interruptedCleanupUsesCommittedBaselines(_ removing: Bool, _ step: String) throws { let fixture = try WatchGitFixture() let first = try fixture.head() @@ -54,8 +54,8 @@ struct WatchReferenceTests { try fixture.kill(writer, at: TransactionCheckpoint.publication(0, .exchanged).name) #expect(try fixture.watchRefs() == [first, replacement]) let recovery = try stateTestProcess( - root: fixture.root, arguments: ["watch-recover", "watch.references.deleted"]) - try fixture.kill(recovery, at: "watch.references.deleted") + root: fixture.root, arguments: ["watch-recover", "watch.references.0.0.deleted"]) + try fixture.kill(recovery, at: "watch.references.0.0.deleted") #expect(try fixture.recoveredWatch().sources[fixture.id]?.seen == .revision(first)) #expect(try fixture.stateBytes() == before) #expect(try fixture.watchRefs() == [first]) diff --git a/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift b/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift index e24e0b7..1445744 100644 --- a/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift @@ -214,7 +214,7 @@ extension LockedArtifactLifecycleTests { process.arguments = [ root.path, "cache-content", TransactionCheckpoint.copy( - 0, .init(path: TransactionScratch.staged.name(0) + "/SKILL.md", step: .entryCopied) + 0, .init(path: TransactionSlot.staged.name(0) + "/SKILL.md", step: .entryCopied) ).name, ] try process.run() diff --git a/Tests/AgentsSkillsTests/TransactionDoctorTests.swift b/Tests/AgentsSkillsTests/TransactionDoctorTests.swift index 3371d58..4dffdd6 100644 --- a/Tests/AgentsSkillsTests/TransactionDoctorTests.swift +++ b/Tests/AgentsSkillsTests/TransactionDoctorTests.swift @@ -23,12 +23,12 @@ struct TransactionDoctorTests { as: TransactionJournal.self) let backup = target.deletingLastPathComponent().appendingPathComponent( journal.containerName(0) - ).appendingPathComponent(TransactionScratch.exchanged.name(0)) + ).appendingPathComponent(TransactionSlot.exchanged.name(0)) try FileManager.default.moveItem(at: backup, to: saved) throw CoreError.invalidState("interrupt after removing preimage") } } - try transaction.replace(target, content: nil, data: Data("published".utf8)) + try transaction.replace(target, with: .data(Data("published".utf8))) try transaction.commit() } } @@ -39,7 +39,7 @@ struct TransactionDoctorTests { #expect(instructions.diagnostics.map(\.kind) == [.unresolvedTransaction]) for message in skills.checks.map(\.message) + instructions.diagnostics.map(\.message) { #expect(message.contains("owner action is required")) - #expect(message.contains("preimage")) + #expect(message.contains("expected slots: " + TransactionSlot.exchanged.name(0))) #expect(message.contains("instructions-project/AGENTS.md")) #expect(message.contains(".agents-")) } diff --git a/Tests/AgentsSkillsTests/UpdateReportingTests.swift b/Tests/AgentsSkillsTests/UpdateReportingTests.swift index 10138a2..d489c3a 100644 --- a/Tests/AgentsSkillsTests/UpdateReportingTests.swift +++ b/Tests/AgentsSkillsTests/UpdateReportingTests.swift @@ -134,7 +134,7 @@ struct UpdateReportingTests { includingPropertiesForKeys: nil ).first { $0.lastPathComponent.hasPrefix(".agents-") } ) - .appendingPathComponent(TransactionScratch.exchanged.name(0)) + .appendingPathComponent(TransactionSlot.exchanged.name(0)) try FileManager.default.setAttributes( [.posixPermissions: 0o755], ofItemAtPath: staged.appendingPathComponent("SKILL.md").path) diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index f28133d..599b214 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -23,16 +23,16 @@ let traceURL = root.appendingPathComponent( "checkpoint-\(ProcessInfo.processInfo.processIdentifier).log") FileManager.default.createFile(atPath: traceURL.path, contents: nil) let trace = try FileHandle(forWritingTo: traceURL) -/// A repeated name would make a kill point ambiguous, so the recorder fails the run. +/// Names must be unique across the whole recorded process: a repeated name would make a kill +/// point ambiguous, so the recorder fails the run. Each command runs one recorded operation. func stop(_ point: String, marker: String = "ready") throws { let (repeated, shouldStop) = checkpointState.withLock { state in (!state.seen.insert(point).inserted, point == state.requested) } try trace.write(contentsOf: Data((point + "\n").utf8)) if repeated { fatalError("repeated checkpoint: \(point)") } - if point.hasPrefix("journal."), point.hasSuffix(".renamed"), - let bytes = try? Data(contentsOf: store.directory.appendingPathComponent("transaction.json")) - { + // The last visible journal survives its own removal for the parent's assertions. + if let bytes = try? Data(contentsOf: store.directory.appendingPathComponent("transaction.json")) { try bytes.write(to: root.appendingPathComponent("last-journal")) } if shouldStop { @@ -95,7 +95,7 @@ if arguments[2] == "git-environment" { } else if arguments[2] == "lock-contender" { try FileLock.withLock( at: root.appendingPathComponent(arguments[3]), - checkpoint: { if $0 == "lock.contended" { try signalContention() } }, + checkpoint: { if FileLock.isContentionCheckpoint($0) { try signalContention() } }, { try Data().write(to: root.appendingPathComponent("lock-acquired")) }) } else if arguments[2] == "closed-streams" { let mask = Int(arguments[3])! @@ -141,7 +141,7 @@ if arguments[2] == "git-environment" { discoverSkills: { _ in [] }, fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, checkpoint: { step in - if step == "mirror.lock.contended" { + if step.hasPrefix("mirror."), FileLock.isContentionCheckpoint(step) { try signalContention() } }) @@ -168,8 +168,21 @@ if arguments[2] == "git-environment" { } else { try watch.remove("source", environment: store.environment) } +} else if arguments[2] == "watch-add-artifact" { + let bytes = Data("---\nname: demo\ndescription: Fixture skill.\n---\nBody\n".utf8) + let digest = "sha256:" + FileHash.sha256Hex(data: bytes) + let artifact = WatchArtifact( + name: "demo", + artifact: LockedArtifact( + type: .skillMD, url: "https://watch.example.test/demo/SKILL.md", digest: digest), + files: ["SKILL.md": bytes], payloads: [digest: bytes]) + let watch = WatchOperations( + discoverSkills: { _ in [] }, fetchArtifacts: { _ in [artifact] }, + checkpoint: { try stop($0) }) + try watch.add("https://watch.example.test", alias: "site", environment: store.environment) } else if arguments[2] == "watch-recover" { - try store.withLock(checkpoint: { try stop($0) }, {}) + do { try store.withLock(checkpoint: { try stop($0) }, {}) } catch CoreError.transactionRecovered { + } } else if arguments[2] == "publication-recover" { let outcome = TransactionOutcome() let result: String @@ -191,8 +204,7 @@ if arguments[2] == "git-environment" { try stop($0) } try transaction.replace( - root.appendingPathComponent("GEMINI.md"), content: nil, - data: Data("auxiliary postimage".utf8)) + root.appendingPathComponent("GEMINI.md"), with: .data(Data("auxiliary postimage".utf8))) let target = arguments[4] == "crossParentReplace" ? root.appendingPathComponent(".agents/skills/target") @@ -201,11 +213,11 @@ if arguments[2] == "git-environment" { case "directoryReplace": let source = root.appendingPathComponent("new") try transaction.replace( - target, content: source, expectedHash: "sha256:" + FileHash.folderHash(source)) - case "directoryDelete": try transaction.replace(target, content: nil) + target, with: .copy(source), expectedHash: "sha256:" + FileHash.folderHash(source)) + case "directoryDelete": try transaction.delete(target) case "symlinkCreate": - try transaction.replace(target, content: root.appendingPathComponent("new"), link: true) - default: try transaction.replace(target, content: nil, data: Data("postimage".utf8)) + try transaction.replace(target, with: .link(root.appendingPathComponent("new"))) + default: try transaction.replace(target, with: .data(Data("postimage".utf8))) } try transaction.commit() } @@ -298,17 +310,15 @@ if arguments[2] == "git-environment" { try transaction.replace( AgentRegistry.installSkillsDirectory( for: .codex, scope: scope, environment: store.environment - ).appendingPathComponent("target"), content: root.appendingPathComponent("new")) - try transaction.replace( - InstructionLocations.file(for: .codex, scope: scope, environment: store.environment)!, - content: nil) + ).appendingPathComponent("target"), with: .copy(root.appendingPathComponent("new"))) + try transaction.delete( + InstructionLocations.file(for: .codex, scope: scope, environment: store.environment)!) try transaction.replace( InstructionLocations.file(for: .geminiCLI, scope: scope, environment: store.environment)!, - content: nil, data: Data("New instructions\n".utf8)) + with: .data(Data("New instructions\n".utf8))) try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(Declaration(agents: [.cursor]))) - try transaction.replace( - store.resolvedURL, content: nil, data: StateStore.encode(ResolvedState())) + store.declarationURL, with: .data(StateStore.encode(Declaration(agents: [.cursor])))) + try transaction.replace(store.resolvedURL, with: .data(StateStore.encode(ResolvedState()))) try transaction.commit() } else if arguments[2] == "watch-crash" { var declaration = try store.readDeclaration() @@ -317,9 +327,8 @@ if arguments[2] == "git-environment" { "local:/source": WatchSourceState(seen: .revision(String(repeating: "b", count: 40))) ]) let transaction = FileTransaction(store: store) { try stop($0) } - try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(declaration)) - try transaction.replace(store.watchURL, content: nil, data: StateStore.encode(watch)) + try transaction.replace(store.declarationURL, with: .data(StateStore.encode(declaration))) + try transaction.replace(store.watchURL, with: .data(StateStore.encode(watch))) try transaction.commit() } else if arguments[2] == "writer" { for index in 0..<5 { @@ -328,8 +337,7 @@ if arguments[2] == "git-environment" { kind: .local, location: root.appendingPathComponent("\(arguments[3])-\(index)").path) usleep(10_000) let transaction = FileTransaction(store: store) - try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(declaration)) + try transaction.replace(store.declarationURL, with: .data(StateStore.encode(declaration))) try transaction.commit() } } else { @@ -340,24 +348,21 @@ if arguments[2] == "git-environment" { AgentRegistry.installSkillsDirectory( for: .codex, scope: scope, environment: store.environment ) - .appendingPathComponent("target"), - content: root.appendingPathComponent("new")) - try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(Declaration(agents: [.codex]))) + .appendingPathComponent("target"), with: .copy(root.appendingPathComponent("new"))) try transaction.replace( - store.resolvedURL, content: nil, - data: StateStore.encode(ResolvedState(sources: ["local:/new": LockedSource(kind: .local)]))) + store.declarationURL, with: .data(StateStore.encode(Declaration(agents: [.codex])))) try transaction.replace( - store.cacheDirectory.appendingPathComponent("artifact-content/pruned"), content: nil) + store.resolvedURL, + with: .data( + StateStore.encode(ResolvedState(sources: ["local:/new": LockedSource(kind: .local)])))) + try transaction.delete(store.cacheDirectory.appendingPathComponent("artifact-content/pruned")) try transaction.replace( AgentRegistry.installSkillsDirectory( for: .claudeCode, scope: scope, environment: store.environment - ).appendingPathComponent("created"), - content: root.appendingPathComponent("new"), - link: true) + ).appendingPathComponent("created"), with: .link(root.appendingPathComponent("new"))) try transaction.replace( InstructionLocations.file(for: .codex, scope: scope, environment: store.environment)!, - content: nil, data: Data("new instructions".utf8)) + with: .data(Data("new instructions".utf8))) try transaction.commit() } } diff --git a/Tests/StateTestSupport/ProcessWait.swift b/Tests/StateTestSupport/ProcessWait.swift index 690a659..78172c8 100644 --- a/Tests/StateTestSupport/ProcessWait.swift +++ b/Tests/StateTestSupport/ProcessWait.swift @@ -1,6 +1,7 @@ import Foundation -/// One deadline and one diagnostic format for filesystem handshakes and process completion. +/// Every wait on a test child is bounded. Marker, stop and exit waits share one deadline and a +/// diagnostic naming the child's last checkpoint; termination has its own shorter deadline. package enum ProcessWait { package static func marker(_ file: URL, child: Process, root: URL, timeout: TimeInterval = 120) throws From 0564db914d23d97d01e8b29871b38b4d4f26cb60 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 30 Oct 2026 22:38:58 +0800 Subject: [PATCH 021/171] docs: specify the Agents.swift language and its state integration Publish the manifest language 1.0 reference, retire the implemented proposal sections to it and to the state architecture, and describe declaration writes, the absent-declaration rule and read-only loads. The vocabulary inventory test reads the reference. --- Documentation/Architecture/Instructions.md | 10 +- Documentation/Architecture/Package.md | 58 +- Documentation/Architecture/README.md | 21 +- Documentation/Architecture/State.md | 267 +++- Documentation/Architecture/Watch.md | 58 +- Documentation/Decisions/AgentComponents.md | 2 +- Documentation/Decisions/SwiftManifest.md | 17 +- Documentation/Proposals/AgentInstructions.md | 143 +- Documentation/Proposals/AgentsManifest.md | 1334 ++--------------- Documentation/Proposals/README.md | 5 +- Documentation/Reference/Manifest.md | 1207 +++++++++++++++ Documentation/Reference/Presentation.md | 2 +- Documentation/Reference/README.md | 2 + README.md | 36 +- .../AgentsManifestTests/InventoryTests.swift | 16 +- 15 files changed, 1753 insertions(+), 1425 deletions(-) create mode 100644 Documentation/Reference/Manifest.md diff --git a/Documentation/Architecture/Instructions.md b/Documentation/Architecture/Instructions.md index 202f106..7d86be4 100644 --- a/Documentation/Architecture/Instructions.md +++ b/Documentation/Architecture/Instructions.md @@ -40,7 +40,8 @@ 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 +name; `.section(name:source:)` in `Agents.swift`, or `alias:name` in operation +arguments, 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`, and so does adding named files, so other @@ -199,9 +200,10 @@ generated files, takes over others only with `replace`, and records targets as ## ChatGPT Prompts -`instructions.chatgpt.` has ordered `sections` and an optional scope-relative -`append` file. Update locks prompt sections with file targets. Reports list -prompts whose section content, order, membership or append path changed. A +`.instructions(chatGPT: [.prompt(name:sections:append:)])` declares a named +prompt with ordered `sections` and an optional scope-relative `append` file. +Update locks prompt sections with file targets. Reports list prompts whose +section content, order, membership or append path changed. A 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. diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index ee2a62d..ce210ca 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -15,15 +15,15 @@ with glibc 2.34 or newer. AgentsDescription (standard library only) AgentsManifest ──> AgentsDescription, AgentsCore, SwiftSyntax, SwiftParser (swift-syntax) -AgentsUpdates ──> AgentsCore, AgentsSkills, AgentsInstructions, CPlatform +AgentsUpdates ──> AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, CPlatform AgentsCore ──> Crypto (swift-crypto), CPlatform -AgentsSkills ──> AgentsCore +AgentsSkills ──> AgentsCore, AgentsManifest │ └───────> Yams -AgentsInstructions ──> AgentsCore +AgentsInstructions ──> AgentsCore, AgentsManifest │ └───────> Markdown (swift-markdown) ──> cmark-gfm @@ -32,11 +32,11 @@ ManifestTestProcess ──> AgentsManifest, AgentsCore, AgentsDescription, Manif AgentsManifestTests ──> AgentsManifest, AgentsDescription, AgentsCore, ManifestTestProcess, ManifestTestSupport, SwiftParser, SwiftSyntax StateTestSupport (Foundation only) -StateTestProcess ──> AgentsCore, AgentsSkills, AgentsInstructions, AgentsUpdates, CPlatform -AgentsCoreTests ──> AgentsCore, StateTestProcess, StateTestSupport, CPlatform -AgentsSkillsTests ──> AgentsSkills, AgentsCore, AgentsInstructions, Yams, StateTestProcess, StateTestSupport, CPlatform -AgentsInstructionsTests ──> AgentsInstructions -AgentsUpdatesTests ──> AgentsUpdates, StateTestProcess, StateTestSupport, CPlatform +StateTestProcess ──> AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, AgentsUpdates, CPlatform +AgentsCoreTests ──> AgentsCore, AgentsManifest, StateTestProcess, StateTestSupport, CPlatform +AgentsSkillsTests ──> AgentsSkills, AgentsCore, AgentsManifest, AgentsInstructions, Yams, StateTestProcess, StateTestSupport, CPlatform +AgentsInstructionsTests ──> AgentsInstructions, AgentsManifest +AgentsUpdatesTests ──> AgentsUpdates, AgentsManifest, StateTestProcess, StateTestSupport, CPlatform ``` `AgentsDescription`, `AgentsManifest`, `AgentsCore`, `AgentsSkills`, @@ -78,7 +78,8 @@ literal inventory; `Scripts/generate-manifest-vocabulary.py` generates the publi factories, literal conversions, package-only registrations and `StaticValue` factories together. CI commands in `.github/swift-package.json` compare generated bytes on the last compiler entry's runner. SwiftPM tests compare registered signatures, -defaults and literal protocols with the contract, and the complete fixture +defaults and literal protocols with the +[language reference](../Reference/Manifest.md), and the complete fixture inventory with compiler-backed values and the parser baseline. See [Development](../../README.md#development) for local validation commands. @@ -116,6 +117,20 @@ front end and compares the resulting declaration. `DocumentChange` carries both byte digests, resulting bytes, diagnostics, impacted references and semantic delta for later orchestration. Source edits do not publish files. Shared constants require explicit impact acceptance; ambiguous comments or separators are refused. +The [manifest language reference](../Reference/Manifest.md) specifies the +language, editing rules and dump schema. + +`AgentsManifest` also connects `Agents.swift` to scope state through +`extension StateStore`. The public `loadDeclaration()` returns the deployable +projection and `loadManifest()` the complete document; both are read-only. +Package-level declaration reading and planning, the projection onto +`AgentsCore.Declaration` and the declaration edit planner serve the domain +modules, and `DeclarationAccess.manifest` supplies the same access to +`WatchOperations`, whose public `init(discoverSkills:fetchArtifacts:)` this +module provides. All file I/O, evidence and publication stay in `AgentsCore`: +the extension parses prepared bytes and returns planned bytes. See +[Declaration](State.md#declaration) for the deployable subset and write +semantics. `ManifestTestProcess` is a test-only executable and calls the same instrumented front-end pipeline as document construction. `ManifestTestSupport` owns the @@ -145,10 +160,14 @@ baselines and seeds belong to the test corpus, not the runtime language. - `DeclarationIR`, `DeclarationRecord` and `DeclarationValue` hold syntax-independent manifest intent; `SourceSpan`, `SourceProvenance` and `DeclarationSourceMap` carry document coordinates and origins without syntax or source access. -- `Declaration` and `ResolvedState` define the current stored intent and resolved version 1 state, - including the complete instruction section, prompt and physical-target models. -- `StateStore` owns scope paths, validation, deterministic encoding and state - persistence. `FileLock` serializes state access; `FileTransaction` durably +- `Declaration` is the typed in-memory projection of the deployable declaration + subset and has no serialized form; `ResolvedState` defines resolved version 1 + state. Together they hold the complete instruction section, prompt and + physical-target models. +- `StateStore` owns scope paths, validation, deterministic lock and watch + encoding and state persistence. It holds declaration bytes, their evidence, + the absent-declaration rule and publication without knowing the declaration + format. `FileLock` serializes state access; `FileTransaction` durably journals replacements across installations, state and cache. `FileSnapshot`, `FileObjectIdentity` and `DirectoryWriteLease` own content, physical-object and temporary directory-write evidence, including directory descendants and @@ -167,14 +186,16 @@ baselines and seeds belong to the test corpus, not the runtime language. - `WatchOperations` owns source subscriptions, seen baselines, branch tracking and file comparisons. `WatchState` defines version 1 of `agents.watch`. Skill discovery and artifact loading are injected by `AgentsSkills` through - `SkillOperations.watchOperations()`. See [Watch](Watch.md) for the public API. + `SkillOperations.watchOperations()`, and declaration access by + `AgentsManifest`. See [Watch](Watch.md) for the public API. - `AgentRegistry` owns agent skill locations. `RuntimeEnvironment` supplies the project root, home directory and environment. Universal agent skill locations can be shared, so recipients sharing one directory must agree on install mode. - `FileHash` hashes tree entries, hidden files and symlink destinations; `PathSafety` checks paths and creates filesystem skill identities. -Core has no dependency on skill discovery, frontmatter, Yams or Markdown. +Core has no dependency on manifest syntax, skill discovery, frontmatter, Yams or +Markdown. `AgentsInstructions` owns instruction text transformations and lifecycle. `InstructionLocations` supplies fixed target locations to lifecycle and journal validation. @@ -371,8 +392,11 @@ changes, cancellation, failure dispositions and recovery. Core tests cover source identities, declarations, lock validation, deterministic 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. +agent paths. Transaction fault tests interrupt every publication and recovery +stage, including concurrent creation of an absent destination and external +replacement of existing targets and recovery 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 the instructions file format, generation, link checks, Claude forwarding and ChatGPT rendering through public diff --git a/Documentation/Architecture/README.md b/Documentation/Architecture/README.md index 90f30ec..8c000c1 100644 --- a/Documentation/Architecture/README.md +++ b/Documentation/Architecture/README.md @@ -1,14 +1,19 @@ # Architecture This directory holds the current truth for `core`, a SwiftPM library package. -`AgentsDescription` supplies the types-only construction vocabulary, and -`AgentsManifest` statically evaluates and edits supplied manifest snapshots without I/O. -`AgentsCore` owns syntax-independent declaration IR, spans, provenance, shared sources, declaration and lock storage, cache, watch subscriptions, and agent locations; -`AgentsSkills` owns skill discovery and lifecycle operations and depends on -`AgentsCore` and Yams. `AgentsInstructions` owns instruction lifecycle and text -transformations. It depends on `AgentsCore` for sources and state, and on -`swift-markdown` for CommonMark structure. `AgentsUpdates` composes both domains -above those modules. Tests follow those module boundaries. +`AgentsDescription` supplies the types-only construction vocabulary. +`AgentsManifest` statically evaluates and edits manifest snapshots, projects +`Agents.swift` onto the deployable declaration and plans declaration writes +through `StateStore`, whose file I/O stays in core. `AgentsCore` owns +syntax-independent declaration IR, spans, provenance, shared sources, +declaration bytes and lock storage, cache, watch subscriptions, and agent +locations, without knowing the declaration format. `AgentsSkills` owns skill +discovery and lifecycle operations and depends on `AgentsCore`, +`AgentsManifest` and Yams. `AgentsInstructions` owns instruction lifecycle and +text transformations. It depends on `AgentsCore` for sources and state, +`AgentsManifest` for the declaration, and `swift-markdown` for CommonMark +structure. `AgentsUpdates` composes both domains above those modules. Tests +follow those module boundaries. ## Belongs Here diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index 2826a48..cf04be8 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -4,8 +4,8 @@ | Scope | Declaration | Lock | Watch state | Cache | | --- | --- | --- | --- | --- | -| Project | `.agent/agents.json` | `.agent/agents.resolved` | `.agent/agents.watch` | `.agent/cache/` | -| User | `~/.agents/agents.json` | `~/.agents/agents.resolved` | `~/.agents/agents.watch` | `~/.agents/cache/` | +| Project | `.agent/Agents.swift` | `.agent/agents.resolved` | `.agent/agents.watch` | `.agent/cache/` | +| User | `~/.agents/Agents.swift` | `~/.agents/agents.resolved` | `~/.agents/agents.watch` | `~/.agents/cache/` | User paths are relative to `RuntimeEnvironment.homeDirectory`. State files belong to their scope. A project may commit its declaration and lock; the cache, @@ -15,68 +15,196 @@ operations. ## Declaration -`agents.json` records user intent. `agents` defaults to `codex` and -`claude-code`. Source aliases name exactly one `git`, `local` or `well-known` -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. - -`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 -{ - "agents": ["codex", "claude-code"], - "sources": { - "team": { "git": "github.com/example/skills", "from": "1.0.0" }, - "drafts": { "local": "~/Developer/skills" } - }, - "skills": { - "team": { "select": "all", "exclude": ["retired"] }, - "drafts": { - "select": ["release-notes"], - "mode": "edit", - "overrides": { "release-notes": { "agents": ["codex"] } } - } - } -} +`Agents.swift` records user intent in the [manifest +language](../Reference/Manifest.md). The document is the declaration's only +truth. `AgentsManifest` parses and evaluates its bytes and projects them onto +`AgentsCore.Declaration`, a typed in-memory view of the deployable subset with +no serialized form. `AgentsCore` holds the declaration's bytes and evidence, the +absent-declaration rule and publication, and knows no syntax; `AgentsManifest` +extends `StateStore` with declaration reading, planning and loading. Parse, edit +and subset failures are `ManifestFailure` diagnostics located in the declaration +file. + +```swift +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + sources: [ + .source(name: "drafts", path: "~/Developer/skills"), + .source( + name: "team", url: "https://github.com/example/skills", from: "1.0.0" + ), + ], + components: [ + .skills( + source: "drafts", select: ["release-notes"], mode: .edit, + overrides: [.skill(name: "release-notes", agents: [.codex])] + ), + .skills(source: "team", exclude: ["retired"]), + ] +) ``` -A skill selection is `"all"` or a name array, with optional exclusions, -recipients, mode and per-skill overrides. `all` follows discovery membership on -an unnamed update. Removing a member adds an exclusion. Explicitly named updates -resolve only those members and fail if a requested member is missing. Skill -filesystem identities are unique within a scope across sources. - -Requirements encode as `branch`, `revision`, `exact`, `from`, `upToNextMinor`, -or `from` plus `to`. Ranges include their lower bound and exclude their upper -bound. A prerelease requires a prerelease bound with the same major, minor and -patch. With no requirement, resolution chooses the latest semantic-version tag, -then the source's default branch when no version tag exists. +### Deployable subset + +The state layer deploys root `defaultAgents`, `sources` and `watch`, and root +`components` of kinds `.skills` and `.instructions`: at most one skills component +per source alias and one instructions component, with no `condition` on a +component, section or prompt and an empty `native`. Groups and exports may be +declared; unused groups are inert. Every other active structure fails with +`manifest.unsupported` at its location, and nothing is dropped: root `uses`, a +condition, native configuration, another component kind, a second skills +component for one alias, a second instructions component, or +`.skills(source: ".")`. After projection, `Declaration.validate(environment:)` +performs the checks that depend on the runtime environment, such as duplicate +identities after local-path expansion. + +`defaultAgents` defaults to `codex` and `claude-code`. Explicit recipients, +including an empty array, replace the default; the projection keeps omitted and +empty recipients distinct. 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. + +A skill selection is all members, when `select` is omitted or `.all`, or an +explicit name array, with optional exclusions, recipients, mode and per-skill +overrides. An all-member selection follows discovery membership on an unnamed +update. Removing a member adds an exclusion. Explicitly named updates resolve +only those members and fail if a requested member is missing. Skill filesystem +identities are unique within a scope across sources. + +Requirements are `branch:`, `revision:`, `exact:`, `from:` (up to the next +major version), `.upToNextMinor(from:)` or a half-open range. Ranges include +their lower bound and exclude their upper bound. A prerelease requires a +prerelease bound with the same major, minor and patch. With no requirement, +resolution chooses the latest semantic-version tag, then the source's default +branch when no version tag exists. 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 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. +The `.instructions` component holds recipients, ordered section references (a +bare string for the project's own instructions, `.section(name:source:)` for a +declared source), and named `chatGPT` prompts with ordered sections and optional +relative `append` paths. `watch` is a unique alias array. Skill operations +preserve both and existing watch-state bytes. + +### Absent declaration + +| Declaration | Lock or watch state | Behavior | +| --- | --- | --- | +| Absent | Absent | An empty declaration. Reads return empty results; the first write creates `Agents.swift` with no-replace publication. | +| Present | Any | Normal. An absent lock is an empty resolved state: `update` creates it and `install` has nothing to restore. | +| Absent | Present | Every read and write path, including the `load*` accessors, listings, previews, doctor, install, initialization and export, throws `CoreError.missingDeclaration` with the declaration path. Nothing is written, and no `.agents.lock` is created. | + +Read paths apply the rule after their pending-recovery check, and writers after +transaction recovery; the check before taking the writer lock runs only when no +journal or pending marker exists. An interrupted first write of the declaration +and lock therefore recovers on the next write instead of reporting a missing +declaration. Watch state counts because its baselines derive from the +declaration; treating a missing declaration as empty would let the next update +remove what was deployed. + +### Declaration writes + +Every declaration write passes through two entries. +`planDeclaration(_:replacing:prepared:)` in `AgentsManifest` compares the next +declaration with the previous one the operation read from the same prepared +baseline. It returns no change when they are semantically equal, and otherwise +bytes that passed the complete front end and the projection check. +`stageDeclaration(_:in:prepared:)` in `AgentsCore` publishes those bytes in the +operation's transaction, expecting the baseline's evidence for the declaration. +Skill, instruction, watch and update writes use only these entries; adding or +changing a source is a difference in the declaration's sources. A combined +update leaves the declaration unchanged, and `validateBeforePublication` still +checks its evidence. + +Planning completes before `beforeApply`, cache retention, a watch's Git fetch +and any staging, so an edit that cannot be addressed exactly fails without side +effects. When the previous declaration differs from the projection of the +baseline bytes, planning fails with `manifest.edit.baseline` rather than +overwriting an external change. Under the scope writer lock, a later writer reads +its own baseline and plans again, so concurrent writers lose no update. + +Semantic equality decides whether anything changes: + +- sources are equal when identity, requirement and normalized subpath are + equal, so URL spelling, relative or absolute local paths and range spelling + never cause a rewrite; +- recipient arrays compare as sets, with omitted and empty distinct; +- omitted and empty exclusions, overrides, prompts, watch lists and skills + components are equal; +- sections compare in order. + +Planning makes minimal document edits and never reorders existing text. A new +source is appended, a changed source is replaced in place, and a removed source +goes after the components that reference it in the same batch. A new skills +component is inserted before the instructions component, or last; a new +instructions component is last. Selections, exclusions, recipients, mode, +overrides, sections, prompts, watch aliases and default recipients change at +argument or element granularity: existing arrays gain and lose elements in +place, an ordered array gains them in order, and sections use a +longest-common-subsequence edit that keeps repetitions. Edits replace only their +target ranges; bytes outside them, comments included, stay unchanged. Constructs +the editor cannot address exactly, such as shared constants, concatenations and +ambiguous comments, fail with `manifest.edit.readOnly`. A batch holds at most +100 requests, and the document is rebuilt from the new bytes before the +remaining difference is planned. The projection of the final document must equal +the intended declaration, or planning fails with `manifest.edit.mismatch`. + +Without declaration bytes, planning prints the complete declaration with the +[canonical printer](../Reference/Manifest.md#canonical-printing): sources, skills +components, overrides, prompts, selected names and watch aliases sorted by UTF-8 +bytes, recipients deduplicated in agent-ID order, and skills before instructions. +The printed bytes pass the same front end and projection check and are published +with no-replace. A semantically empty declaration creates no file. + +One transaction covers the declaration, lock, affected watch state, installation +targets, cache retention and pruning; a declaration-only change uses the same +journal and evidence. The declaration is published only as planned source bytes, +while the lock and watch state keep their own encoders. Preparation records +presence, physical identity and byte digest for the declaration, lock, watch +state and related targets. A changed comment, or another inode with equal bytes, +therefore invalidates a prepared preview, and a declaration created externally +after preparation is an existence conflict that keeps the external file. + +### Requirement comparison + +Semantic comparison expands range requirements to their bounds; raw case or +encoded-field equality is insufficient. Branch and revision compare their +strings, exact versions compare normalized full versions, and absence keeps its +distinct latest-tag/default-branch policy. Canonical spelling applies to new IR +and newly serialized requirement fields. + +| Site | Rule | +| --- | --- | +| Declaration IR and dump | Canonical requirement kinds and normalized version strings; a factory and a literal range with equal bounds compare equal. | +| Declaration writes and `upsertSource` | Semantic values are compared; an equal edit keeps the original source bytes. New or changed nodes print canonically; untouched spelling is retained. | +| `LockedSource.requirement` in the lock | Newly written records use canonical requirements. Existing records keep their bytes and are compared through a semantic view. A requirement-spelling difference alone never changes pins, reports an update or stages a write. | +| Skill and instruction lock producers, combined update conflicts and change detection | Source identity, discovery root and semantic requirement values are compared; equal ranges merge without a conflict. A semantically unchanged lock keeps its original bytes even when another state file changes; a necessary rewrite emits canonical requirements. | +| Resolution-session reuse and cache descriptors | Requirements are keyed by semantic value. Cache identity and materialization keys use source identity and exact revision or artifact digest; restoration uses the stored pins without re-resolving requirements. | +| `agents.watch` | Stores source identities and seen baselines, with no requirement. Re-evaluating an equivalent declaration preserves the subscription and baseline; watch-created lock descriptors follow the lock rule. | + +State transactions compare semantic state before choosing any serialization and +never rewrite records on read. ## Lock `agents.resolved` version 1 has identity-keyed `sources` and `skills`, and an `instructions` object containing `sections`, `chatgpt` and `targets`. +The lock is 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. A semantically +unchanged lock keeps its original bytes; a changed lock is written in that +layout. Empty lock sections such as `"skills": {}` remain, because earlier +readers require them. Journals, `agents.watch` and content hashes keep the +encoder's fixed layout. + A locked source records its kind, Git URL where applicable, requirement and search path. A skill records its source ID, its own revision and optional version, relative directory path, content hash and `installs` mapping agent IDs @@ -110,15 +238,16 @@ payloads, including empty directories and symbolic link destinations. Tree hashes intentionally exclude permissions. Skill update snapshots compare the any-execute-bit Boolean separately for regular files. Preparation, retention and transaction staging verify that dimension without changing stored hashes, -pins or the version 1 declaration, lock and watch schemas. +pins, the declaration or the version 1 lock and watch schemas. ## State Transaction and Recovery The scope's `transaction.json` is the sole persistent transaction owner for installation targets, declaration, lock, watch state, cache publication and pruning. Its protocol accepts regular files, directories and symbolic links -independently of the declaration format. Declaration and lock keep their state -encoders; watch state keeps its fixed encoder. +independently of the declaration format. The declaration is published as the +source bytes its plan produced; the lock keeps its state encoder and watch state +its fixed encoder. ### Preparation and preconditions @@ -141,10 +270,10 @@ related inputs that the journal does not replace. State parsing consumes the captured raw bytes, so decoded inputs and journal evidence describe the same generation. -Changed bytes, including declaration whitespace or target comments, invalidate -preparation. Another inode with equal bytes also invalidates a captured target -entry or directory descendant. Apply requires a newly prepared plan and never -rebases an old edit onto changed inputs. +Changed bytes, including declaration comments or whitespace and target comments, +invalidate preparation. Another inode with equal bytes also invalidates a +captured target entry or directory descendant. Apply requires a newly prepared +plan and never rebases an old edit onto changed inputs. Readers and writers serialize through `.agents.lock`. Missing scope and target ancestry is created with descriptor-relative operations. Parent directories are @@ -162,7 +291,8 @@ the denial. Existing user content and metadata are preserved. ### Journal records -Journal format version 1 is independent of declaration, lock and watch versions. +Journal format version 1 is independent of the manifest language, lock and watch +versions. The root records its version, transaction UUID, scope identity, registered root identities, transaction phase, operations, private containers and disposal intent. A journal without this version, or with another version, is retained @@ -278,8 +408,11 @@ ownership denials are reported rather than bypassed. Every mutating state operation first checks for an abandoned journal under the scope lock, validates watch state and finishes pending reference cleanup before -proceeding. Journal recovery selects and syncs a consistent generation before -watch reconciliation can release any ref. Pending watch-reference recovery also +proceeding. Recovery never reads the declaration: journal and watch-reference +recovery complete even when `Agents.swift` does not parse, and orphaned mirror +locations come from watch state and the lock, then from the mirror's origin. +Journal recovery selects and syncs a consistent generation before watch +reconciliation can release any ref. Pending watch-reference recovery also reports `CoreError.transactionRecovered` when no journal remains. Retained refs remain available while a journal conflict is unresolved. @@ -333,8 +466,11 @@ their journal UUID: recovering a cache publication cannot mark a later combined update committed. Failure after a commit marker can still be unresolved if recovery material changed. A committed failure is never described as rollback. -The public `StateStore.loadDeclaration`, `loadResolved` and `loadWatch` -accessors retain their writer-lock and recovering-loader semantics. +The public `StateStore.loadResolved()` and `loadWatch()` in `AgentsCore` and +`loadDeclaration()` and `loadManifest()` in `AgentsManifest` are read-only, as +described below. `loadDeclaration()` returns the deployable projection; +`loadManifest()` returns the complete `DeclarationDocument` without subset +projection, or `nil` when no declaration exists. ### Read-only access @@ -345,8 +481,11 @@ lock or recovery marker before returning either its result or its error. A writer causes that attempt to be discarded and retried under the shared lock. Writers create the scope lock before mutation and never remove it. +The `load*` accessors follow the same rules and never create `.agents.lock`. Pending journals and watch-reference markers stop inspection with -`CoreError.invalidState`. Doctor distinguishes pending automatic recovery from +`CoreError.recoveryPending`, which carries the recovery diagnostic; a mutating +operation on the scope performs the recovery. The absent-declaration rule +applies after this check. Doctor distinguishes pending automatic recovery from an unresolved conflict requiring owner action, and skips checks needing a consistent generation. Skill doctor uses `pending-recovery` or `unresolved-transaction`; instruction doctor uses `pendingRecovery` or diff --git a/Documentation/Architecture/Watch.md b/Documentation/Architecture/Watch.md index 8514dd4..dc9b868 100644 --- a/Documentation/Architecture/Watch.md +++ b/Documentation/Architecture/Watch.md @@ -1,8 +1,9 @@ # Watch Subscriptions `AgentsCore.WatchOperations` manages subscriptions independently of installation -intent and pins. `agents.json` lists subscribed source aliases in `watch`; -`agents.watch` records a seen baseline per normalized source ID. Subscribing +intent and pins. `Agents.swift` lists subscribed source aliases in the `watch:` +argument of `Agents(...)`; `agents.watch` records a seen baseline per normalized +source ID. Subscribing installs nothing, and removing a subscription preserves source declarations, skill selections, locked records and installed content. @@ -11,21 +12,25 @@ skill selections, locked records and installed content. Both CLI consumers can construct `SkillOperations.watchOperations()` from `AgentsSkills`. It supplies the existing skill discovery rules and well-known loader to `AgentsCore`. Callers implementing another content provider can use -`WatchOperations.init(discoverSkills:fetchArtifacts:)` directly. This keeps -frontmatter, skill discovery and artifact format parsing in their owning module; -core has no dependency on `AgentsSkills`, Yams or instruction rendering. +`WatchOperations.init(discoverSkills:fetchArtifacts:)`, which `AgentsManifest` +provides because it also supplies the declaration access that core receives by +injection. This keeps frontmatter, skill discovery, artifact format parsing and +manifest syntax in their owning modules; core has no dependency on +`AgentsManifest`, `AgentsSkills`, Yams or instruction rendering. Every operation accepts `scope` and `RuntimeEnvironment`: | Operation | Behavior | | --- | --- | -| `add(_:alias:requirement:path:scope:environment:)` | Resolve an alias or source location, declare it if needed, subscribe and record current content as seen. Returns `WatchSeen`. | +| `add(_:alias:requirement:path:scope:environment:)` | Resolve an alias or source location, declare it if needed, subscribe and record current content as seen. Returns `WatchChange`. | | `status(scope:environment:)` | Return sorted `WatchStatus` values for all subscribed sources. | | `diff(_:name:kind:scope:environment:)` | Inspect one subscribed source, optionally filtering item name and kind. Returns file bytes and entry metadata for presentation by the caller. | -| `seen(_:revision:scope:environment:)` | Acknowledge the current head or resolve a supplied Git revision to a full commit ID. Well-known sources accept no revision argument. | -| `remove(_:scope:environment:)` | Remove the alias from `watch` and delete its baseline without changing installations. | +| `seen(_:revision:scope:environment:)` | Acknowledge the current head or resolve a supplied Git revision to a full commit ID. Well-known sources accept no revision argument. Returns `WatchChange`. | +| `remove(_:scope:environment:)` | Remove the alias from `watch` and delete its baseline without changing installations. Returns `WatchChange` without a baseline. | -Existing subscriptions can be addressed by alias, normalized source ID or source +`WatchChange` contains the alias, normalized source ID and the recorded +`WatchSeen` baseline, so callers need no separate declaration read. Existing +subscriptions can be addressed by alias, normalized source ID or source location. Repeating `add` records current content as seen. Missing subscriptions, invalid revisions and missing baseline content produce errors. A local directory must be a Git repository to be subscribed. @@ -103,31 +108,32 @@ is reported even when expanded file contents are identical. Expanded baseline contents remain in the digest-addressed cache while referenced by watch state; skill lifecycle pruning respects those references. -`StateStore.loadWatch()` reads and validates the baseline. `save` accepts an -optional `watch` value; omitting it preserves existing watch bytes. JSON is +`StateStore.loadWatch()` reads and validates the baseline without recovery or +writes. Writes that do not replace watch state preserve its bytes. JSON is sorted, timestamp-free, UTF-8 without a BOM and newline-terminated. Duplicate keys, malformed input, unknown non-null fields, unsupported versions and invalid revisions or digests are errors. Subscriptions cannot repeat an alias. Add, seen and remove hold the scope writer lock and recover interrupted -transactions and pending ref cleanup before proceeding. Add and seen prepare -cached content before publishing its baseline. Declaration and watch replacements -and cache pruning commit through the existing scope transaction journal; recovery -follows the same retry contract as other mutating state operations. Every scope +transactions and pending ref cleanup before proceeding. They capture declaration, +lock and watch evidence and plan the `Agents.swift` change before contacting Git, +so a declaration the editor cannot change fails before any fetch. Add and seen +prepare cached content before publishing its baseline. Declaration and watch +replacements and cache pruning commit through the existing scope transaction +journal, expecting the captured evidence; recovery follows the same retry +contract as other mutating state operations. Every scope mutation checks watch state after transaction recovery, and corrupt watch state blocks mutations before fetching, cache publication, installation or state replacement. Status and diff take an existing shared scope lock without creating state files or replaying recovery. When a first writer creates the scope lock during an -unlocked read, inspection discards that attempt, including any error, and retries -under the shared lock. A pending transaction journal or watch-ref cleanup marker -fails inspection with -`CoreError.invalidState` ("transaction recovery is required before inspection"). -Inspection leaves pending cleanup and retained refs untouched for the next -mutating operation to recover. -Status and diff may fetch into mirrors under each mirror's lock and download -current index artifacts for inspection. They use disposable snapshots and memory, -leave retained artifact content unchanged, and do not write declaration, lock, -watch state, installations or source working trees. Scheduling and diff rendering -belong to consumers. +unlocked read, inspection discards that attempt, including any error, and +retries under the shared lock. A pending transaction journal or watch-ref +cleanup marker fails inspection with `CoreError.recoveryPending`. Inspection +leaves pending cleanup and retained refs untouched for the next mutating +operation to recover. Status and diff may fetch into mirrors under each mirror's +lock and download current index artifacts for inspection. They use disposable +snapshots and memory, leave retained artifact content unchanged, and do not +write declaration, lock, watch state, installations or source working trees. +Scheduling and diff rendering belong to consumers. diff --git a/Documentation/Decisions/AgentComponents.md b/Documentation/Decisions/AgentComponents.md index 5c317f0..3c53628 100644 --- a/Documentation/Decisions/AgentComponents.md +++ b/Documentation/Decisions/AgentComponents.md @@ -64,7 +64,7 @@ physical locations; Codex, Cursor, Gemini CLI and OpenCode read the same adapters for every component; adding an agent or component means adding registry entries, adapters and client probes. - The lock grows from pins and hashes into a deployment ledger, a lock format - change that `agents migrate` covers. + change with its own lock conversion. - Input adapters are versioned against the upstream formats they read and need fixtures from those formats. - Shared settings files require structured, format-preserving edits for JSON, diff --git a/Documentation/Decisions/SwiftManifest.md b/Documentation/Decisions/SwiftManifest.md index 8f09081..66ffa18 100644 --- a/Documentation/Decisions/SwiftManifest.md +++ b/Documentation/Decisions/SwiftManifest.md @@ -6,9 +6,8 @@ Accepted ## Context -A scope's declaration is `agents.json`, standard JSON that the state store -rewrites in full on every save. People cannot annotate it, and every write -normalizes it. +A scope's declaration is standard JSON that the state store rewrites in full on +every save. People cannot annotate it, and every write normalizes it. The declaration is about to describe every agent configuration component, not only skills and instructions, and two front ends will edit it: the `agents` @@ -51,9 +50,10 @@ uneditable for tools once it contains logic. lock, not in the manifest. - `agents manifest dump --json` prints the evaluated declaration for tools in other languages. -- `agents migrate` converts `agents.json` to `Agents.swift` once and gives the - same result when repeated. Commands report an unmigrated `agents.json` - instead of converting it implicitly. +- The product reads and writes only `Agents.swift`. Existing repository and user + scopes are converted once outside the product at release; the product does not + read the earlier JSON declaration. A scope with a lock or watch state but no + `Agents.swift` is an error. ## Consequences @@ -67,8 +67,8 @@ uneditable for tools once it contains logic. - Parsing untrusted manifests needs explicit limits on file size, nesting and evaluation work, and fuzzing before release. - Editors offer completion only where `AgentsDescription` is available to them. -- Every repository that commits `agents.json`, and every user scope, migrates - once. +- Every repository that commits a JSON declaration, and every user scope, is + converted once at release, outside the product. ## Alternatives Considered @@ -85,6 +85,7 @@ uneditable for tools once it contains logic. - Accepted by the repository owner (showxu) on 2026-10-28. - Current declaration, lock and state layout: [State](../Architecture/State.md) +- Language specification: [Agents Manifest Language](../Reference/Manifest.md) - Component model the manifest describes: [Agent Components and Adapters](AgentComponents.md) - Approval of executable components: [Executable Component Approval](ExecutableApproval.md) - Product scope and front ends: [agents-tools/cli decisions](https://github.com/agents-tools/cli/tree/master/Documentation/Decisions) diff --git a/Documentation/Proposals/AgentInstructions.md b/Documentation/Proposals/AgentInstructions.md index 3588242..823bf4e 100644 --- a/Documentation/Proposals/AgentInstructions.md +++ b/Documentation/Proposals/AgentInstructions.md @@ -160,8 +160,8 @@ 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` 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 | +| Project | `.agent/Agents.swift` | `.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.swift` | `~/.agents/agents.resolved` | `~/.agents/agents.watch` | User skills; each agent's user instructions file; ChatGPT prompts | 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, @@ -173,64 +173,83 @@ always lives under `~/.agents`. ### Declaration -Commands edit the declaration; editing it by hand is possible. - -```json -{ - "agents": ["codex", "claude-code"], - "sources": { - "rules": { "local": "~/Developer/rules", "branch": "main" }, - "swift-skills": { "git": "github.com/swift-library/skills", "from": "1.0.0" }, - "my-skills": { "local": "~/Developer/my-skills", "path": "skills" }, - "anthropic": { "git": "github.com/anthropics/skills" } - }, - "skills": { - "swift-skills": { "select": "all", "exclude": ["legacy-docx"] }, - "my-skills": { - "select": ["pdf-forms", "release-notes"], - "mode": "edit", - "overrides": { "release-notes": { "agents": ["codex"] } } - } - }, - "instructions": { - "agents": ["codex", "claude-code", "cursor", "opencode"], - "sections": ["guide", "rules:canonical-artifacts", "code-review-rules"], - "chatgpt": { - "training": { - "sections": ["rules:canonical-artifacts", "rules:training-logging"], - "append": ".agent/chatgpt-training.md" - }, - "weekly-export": { "sections": ["rules:weekly-nutrition-export"] } - } - }, - "watch": ["anthropic"] -} +Commands edit the declaration in place and keep its comments; editing it by hand +is possible. + +```swift +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + sources: [ + .source(name: "anthropic", url: "https://github.com/anthropics/skills"), + .source(name: "my-skills", path: "~/Developer/my-skills", subpath: "skills"), + .source(name: "rules", path: "~/Developer/rules", branch: "main"), + .source( + name: "swift-skills", url: "https://github.com/swift-library/skills", + from: "1.0.0" + ), + ], + components: [ + .skills( + source: "my-skills", select: ["pdf-forms", "release-notes"], mode: .edit, + overrides: [.skill(name: "release-notes", agents: [.codex])] + ), + .skills(source: "swift-skills", exclude: ["legacy-docx"]), + .instructions( + sections: [ + "guide", + .section(name: "canonical-artifacts", source: "rules"), + "code-review-rules", + ], + chatGPT: [ + .prompt( + name: "training", + sections: [ + .section(name: "canonical-artifacts", source: "rules"), + .section(name: "training-logging", source: "rules"), + ], + append: ".agent/chatgpt-training.md" + ), + .prompt( + name: "weekly-export", + sections: [.section(name: "weekly-nutrition-export", source: "rules")] + ), + ], + agents: [.codex, .claudeCode, .cursor, .openCode] + ), + ], + watch: ["anthropic"] +) ``` -- A source names its kind by key (`git`, `local`, `well-known`), plus an - optional requirement and search `path`. Requirements are `branch`, - `revision`, `exact` (one version), `from` (up to the next major version), - `upToNextMinor`, or `from` with `to` (a half-open range). Without one, the - latest version tag is used, or the default branch when there are no version - tags. -- `agents` is the default agent list. Without it the default is `codex` and - `claude-code`. -- `select` is `"all"` or a list of names. `"all"` follows the source's current - membership on `update`; `exclude` names skills it skips. Removing one skill - of an `"all"` selection adds it to `exclude`. -- `agents` and `mode` on a selection apply to its skills; `overrides` sets - them for single skills. `mode` is `link` (default), `copy` or `edit`. - `edit` links the live directory of a local source, takes no requirement and - is never pinned. -- `instructions` holds one ordered section list per scope, written to the - 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. +- A source is `.source(name:url:)` for Git, `.source(name:path:)` for a local + directory or `.source(name:index:)` for a well-known index, with an optional + requirement and `subpath`. Requirements are `branch:`, `revision:`, `exact:` + (one version), `from:` (up to the next major version), + `.upToNextMinor(from:)`, or a half-open range such as `"1.0.0"..<"1.4.0"`. + Without one, the latest version tag is used, or the default branch when there + are no version tags. +- `defaultAgents` is the default agent list. Without it the default is `codex` + and `claude-code`. +- A `.skills` component without `select` selects all members; `select:` lists + names. An all-member selection follows the source's current membership on + `update`; `exclude` names skills it skips. Removing one skill of an + all-member selection adds it to `exclude`. +- `agents` and `mode` on a selection apply to its skills; + `overrides: [.skill(name:mode:agents:)]` sets them for single skills. `mode` + is `.link` (default), `.copy` or `.edit`. `.edit` links the live directory of + a local source, takes no requirement and is never pinned. +- The `.instructions` component holds one ordered section list per scope, + written to the 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 a bare string for the project's own instructions, or + `.section(name:source:)` for a declared source. +- `chatGPT: [.prompt(name:sections:append:)]` 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. - `watch` lists the aliases of subscribed sources. A source can be subscribed without selecting anything from it. @@ -355,9 +374,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. The declaration - and lock use Prettier's default JSON layout. Writes take a file lock and - replace the file atomically. +- Output is sorted, except section order, and has no timestamps. The lock uses + Prettier's default JSON layout; the declaration keeps its own source layout. + Writes take a file lock and replace the file atomically. ### Watch State @@ -425,7 +444,7 @@ For skills, omitting `--agent` makes `remove` act on all recipients and `list` s | 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 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 | +| `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-member 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 | diff --git a/Documentation/Proposals/AgentsManifest.md b/Documentation/Proposals/AgentsManifest.md index 3b71913..87f238b 100644 --- a/Documentation/Proposals/AgentsManifest.md +++ b/Documentation/Proposals/AgentsManifest.md @@ -2,7 +2,9 @@ ## Status -Accepted — language version 1.0. +Accepted — partially implemented. Language version 1.0, its document editor and +dump, and the `Agents.swift` state integration are implemented; targeting, +source linking, component deployment, approvals and lock version 2 are pending. ## Authors / Owners @@ -77,6 +79,14 @@ source patches, reparses and validates the entire candidate, and passes it to core's prepare/apply transaction. The manifest owns intent; the ledger owns resolved deployment facts. Comments and untouched source bytes remain intact. +## Implementation Status + +| Part | Status and owner | +| --- | --- | +| Construction vocabulary, files and versions, grammar, typing, resource limits, document editing, evaluated dump, diagnostics and conformance | Implemented; specified in the [manifest language reference](../Reference/Manifest.md). | +| `Agents.swift` as scope declaration, deployable subset, declaration writes, absent-declaration rule and requirement comparison | Implemented; specified in [State](../Architecture/State.md#declaration). | +| [Component deployment](#component-deployment), [Targeting](#targeting), [Groups and source linking](#groups-and-source-linking), the `Components` target in [Target Architecture](#target-architecture), [Approvals](#approvals) and [Lock version 2](#lock-version-2-and-ownership-conversion) | Pending; specified below. | + ## Motivation A typed Swift vocabulary provides reusable composition and editor completion @@ -90,344 +100,64 @@ The accepted [Swift manifest](../Decisions/SwiftManifest.md), ## Proposed Change -Adopt the vocabulary, static grammar, source editing, migration and JSON contract -below. Add the types-only `AgentsDescription` and document/compiler-front-end -`AgentsManifest` library products, with linking and native adapters in an internal -`Components` target. Keep shared IR, source storage, capabilities and transactions -in `AgentsCore`, and orchestration in `AgentsUpdates`. +Adopt the vocabulary, static grammar, source editing and JSON contract of the +[manifest language reference](../Reference/Manifest.md), and complete deployment +of the whole vocabulary: targeting, group and source linking, native adapters +and executable approval. The types-only `AgentsDescription` and +document/compiler-front-end `AgentsManifest` library products exist; linking and +native adapters belong in an internal `Components` target. Shared IR, source +storage, capabilities and transactions stay in `AgentsCore`, and orchestration in +`AgentsUpdates`. ## Detailed Design -### Construction vocabulary - -`AgentsDescription` is a compilable, types-only Swift module. Every manifest -accepted by the static evaluator must type-check against the matching module -with the real Swift compiler, including contextual factories, dictionaries and -literal conversions. Compiler type-checkability is a language 1.0 requirement; -editor integration, including making the module available to SourceKit-LSP, is -outside this contract. +### Language -The interface below lists the entire public construction surface. Types conform -to `Sendable` and `Equatable`; factory results are immutable data. Opaque structs -have no public memberwise initializer. Literal-protocol initializers are compiler -entry points, invoked through literals in the manifest grammar. The module uses -the standard library and performs no I/O, registration, resolution or evaluation. -Public names are distinct from top-level standard-library, Foundation and SwiftUI -types so front ends can import those modules together. +The [manifest language reference](../Reference/Manifest.md) specifies: -Factories and labels follow SwiftPM's authoring shape and the -[Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/). -Each component occupies one construction level. Its family-specific fields end -with the same `agents:`, `condition:`, `native:` tail. Payload storage is private. +- [construction vocabulary](../Reference/Manifest.md#construction-vocabulary) + and [domain rules](../Reference/Manifest.md#domain-rules); +- [source files and versions](../Reference/Manifest.md#source-files-and-versions), + [static grammar](../Reference/Manifest.md#static-grammar), + [type inference](../Reference/Manifest.md#type-inference-and-literal-conversions) + and the [admission grammar](../Reference/Manifest.md#normative-admission-grammar); +- [resource limits](../Reference/Manifest.md#resource-limits) and + [group references](../Reference/Manifest.md#group-references); +- [document editing](../Reference/Manifest.md#document-editing), + the [evaluated JSON dump](../Reference/Manifest.md#evaluated-json-dump) and + [diagnostics](../Reference/Manifest.md#diagnostics). -A **watch subscription** observes changes in a named source independently of -installation. **Install mode** chooses a link to verified cached content (`.link`), -a verified installed copy (`.copy`), or a live local skill link (`.edit`). Edit -mode has no immutable pin or content hash and requires a local source without a -requirement. +[State](../Architecture/State.md#deployable-subset) specifies the subset that +the state layer deploys; every other active structure is reported as +`manifest.unsupported`. The sections below specify the remaining deployment. -#### Root, sources and composition - -```swift -public enum Agent: Sendable, Equatable { - case claudeCode, codex, cursor, geminiCLI, openCode -} -public enum Scope: Sendable, Equatable { case project, user } -public enum Platform: Sendable, Equatable { case macOS, linux } -public enum InstallMode: Sendable, Equatable { case link, copy, edit } - -public struct Condition: Sendable, Equatable { - public static func when( - agents: [Agent]? = nil, scopes: [Scope]? = nil, - platforms: [Platform]? = nil - ) -> Condition -} - -public struct Agents: Sendable, Equatable { - public init( - defaultAgents: [Agent]? = nil, exports: [String] = [], sources: [Source] = [], - components: [Component] = [], groups: [ComponentGroup] = [], - uses: [GroupReference] = [], watch: [String] = [] - ) -} - -public struct Version: Sendable, Comparable, ExpressibleByStringLiteral { - public init(stringLiteral value: String) - public static func == (lhs: Version, rhs: Version) -> Bool - public static func < (lhs: Version, rhs: Version) -> Bool -} - -extension Range where Bound == Version { - public static func upToNextMajor(from version: Version) -> Range - public static func upToNextMinor(from version: Version) -> Range -} - -public struct Source: Sendable, Equatable { - public static func source( - name: String, url: String, subpath: String? = nil - ) -> Source - public static func source( - name: String, url: String, from: Version, subpath: String? = nil - ) -> Source - public static func source( - name: String, url: String, exact: Version, subpath: String? = nil - ) -> Source - public static func source( - name: String, url: String, branch: String, subpath: String? = nil - ) -> Source - public static func source( - name: String, url: String, revision: String, subpath: String? = nil - ) -> Source - public static func source( - name: String, url: String, _ range: Range, subpath: String? = nil - ) -> Source - public static func source( - name: String, path: String, subpath: String? = nil - ) -> Source - public static func source( - name: String, path: String, from: Version, subpath: String? = nil - ) -> Source - public static func source( - name: String, path: String, exact: Version, subpath: String? = nil - ) -> Source - public static func source( - name: String, path: String, branch: String, subpath: String? = nil - ) -> Source - public static func source( - name: String, path: String, revision: String, subpath: String? = nil - ) -> Source - public static func source( - name: String, path: String, _ range: Range, subpath: String? = nil - ) -> Source - public static func source(name: String, index: String, subpath: String? = nil) -> Source -} - -public struct ComponentGroup: Sendable, Equatable { - public static func group( - name: String, components: [Component] = [], uses: [GroupReference] = [], - condition: Condition? = nil - ) -> ComponentGroup -} -public struct GroupReference: Sendable, Equatable, ExpressibleByStringLiteral { - public init(stringLiteral value: String) - public static func group(name: String, condition: Condition? = nil) -> GroupReference - public static func group( - name: String, source: String, condition: Condition? = nil - ) -> GroupReference -} -``` +### Component deployment -There is one `let agents = Agents(...)`, optionally annotated `: Agents`. -Other constants contain reusable values. Source names are lexical aliases, not -output paths. A **discovery root** is the source root with its optional safe -`subpath` applied; component and export discovery start there. Core owns source -identity normalization and requirement resolution. - -`Version` uses core's semantic-version validation and precedence. A requirement -is a value: `from: x` and `.upToNextMajor(from: x)` denote -`x ..< (major + 1).0.0`; `.upToNextMinor(from: x)` denotes -`x ..< major.(minor + 1).0`. The upper bounds have no prerelease or build metadata, -even when the lower bound has either. The lower bound retains its prerelease and -metadata. All range forms use the resolver's `isInRange(from:to:)`: build metadata -does not affect precedence, and a prerelease tag additionally needs a bound with -a prerelease and the same major/minor/patch triple. Exact requirements retain -core's full normalized-version matching, including build metadata. - -Lowering canonicalizes the `Range` value. An upper bound equal by SemVer -precedence to `(major + 1).0.0` becomes `SourceRequirement.upToNextMajor`; one -equal to `major.(minor + 1).0` becomes `upToNextMinor`; any other upper bound -becomes `SourceRequirement.range(from:to:)`. The two canonical upper bounds -never coincide. Version strings use core's -normalized description; range equality compares bounds by SemVer precedence, -while exact-version equality includes metadata. Invalid versions, non-increasing -ranges and successor overflow are located `manifest.domain` errors. Candidate -successor bounds are computed with checked arithmetic; a literal range does not -fail merely because a nonmatching candidate successor would overflow. - -The canonical printer uses `from:` for a major range, -`.upToNextMinor(from:)` for a minor range and adjacent `"lower"..<"upper"` for -other half-open ranges. `exact:`, `branch:` and `revision:` retain their meanings. -Default latest-tag/default-branch selection remains core's rule. Requirements -apply to Git URL sources and Git-backed local paths only. `.source(name:index:)` -represents the existing well-known index kind and has no Git requirement. -`path:` locates a resource inside a named source or supplies a local source -location; `subpath:` narrows the source's own discovery root. - -Source aliases follow the existing nonempty, colon-free string rule, with `.` -reserved for the declaring package. Escapes preserve otherwise valid string -contents. Two aliases for one normalized source identity in a document are errors. -Group and newly introduced named component identifiers are relative slash-separated -names with no empty, `.` or `..` segment, colon, backslash or control character. -Skill and instruction names retain their domain validators. ChatGPT prompt names -retain the existing arbitrary string-key namespace; they are not filesystem paths. -Names must be unique in their respective namespace. - -Git URLs are complete transport URLs, as in SwiftPM. A hand-written shorthand is -admitted with `SourceDeclaration` normalization and a `manifest.domain` warning -whose fix-it is the complete URL: `intranet/team` means `https://intranet/team`, -preserving the host; it is not the CLI's owner/repository shorthand. The editor -and migration emit complete URLs using `SourceDeclaration.gitURL`: add `https://` -to host/repository shorthand, preserve existing schemes and preserve complete -SCP-style URLs such as `user@host:path`. Preserving SCP transport syntax also -preserves its remote path interpretation. Identity normalization lowercases the -host, retains an explicit port, trims path slashes and removes a terminal `.git`; -printing preserves the repository suffix. - -`exports: ["review"]` exports the group named `review`; export name and group name -are identical. A differently named wrapper group provides a renamed export. -`watch` is a unique array of declared source aliases, with no recipient or condition. Observed -baselines remain in `agents.watch`, not the manifest. Neither exports nor unused -groups cause deployment or subscriptions in a consumer. - -#### Literal values and supporting types +Deployment gives every vocabulary family its native meaning. The front end +already checks the +[domain rules](../Reference/Manifest.md#domain-rules); the rules below apply when +resolved components are lowered to native configuration. -```swift -public struct SkillSelection: Sendable, Equatable, ExpressibleByArrayLiteral { - public static var all: SkillSelection { get } - public init(arrayLiteral elements: String...) -} -public struct SkillOverride: Sendable, Equatable { - public static func skill(name: String, mode: InstallMode? = nil, agents: [Agent]? = nil) -> SkillOverride -} -public struct SectionReference: Sendable, Equatable, ExpressibleByStringLiteral { - public init(stringLiteral value: String) - public static func section( - name: String, source: String? = nil, condition: Condition? = nil - ) -> SectionReference -} -public struct ChatGPTPrompt: Sendable, Equatable { - public static func prompt( - name: String, sections: [SectionReference], append: String? = nil, - condition: Condition? = nil - ) -> ChatGPTPrompt -} -public struct Resource: Sendable, Equatable { - public static func path(_ path: String, source: String? = nil) -> Resource -} -public struct PromptContent: Sendable, Equatable, ExpressibleByStringLiteral { - public init(stringLiteral value: String) - public static func file(_ path: String, source: String? = nil) -> PromptContent -} -public enum RuntimeValue: Sendable, Equatable, ExpressibleByStringLiteral { - case literal(String) - case environment(String) - case secret(String) - public init(stringLiteral value: String) -} -public struct ExecutableInvocation: Sendable, Equatable { - public static func executable( - _ executable: String, arguments: [String] = [], - environment: [String: RuntimeValue] = [:], workingDirectory: Resource? = nil - ) -> ExecutableInvocation -} -public indirect enum ConfigurationValue: Sendable, Equatable, - ExpressibleByStringLiteral, ExpressibleByIntegerLiteral, - ExpressibleByBooleanLiteral, ExpressibleByNilLiteral, - ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral -{ - case string(String) - case integer(Int) - case decimal(String) - case boolean(Bool) - case null - case array([ConfigurationValue]) - case object([String: ConfigurationValue]) - public init(stringLiteral value: String) - public init(integerLiteral value: Int) - public init(booleanLiteral value: Bool) - public init(nilLiteral: ()) - public init(arrayLiteral elements: ConfigurationValue...) - public init(dictionaryLiteral elements: (String, ConfigurationValue)...) -} -public typealias NativeConfiguration = [String: [String: ConfigurationValue]] - -public struct MCPTransport: Sendable, Equatable { - public static func stdio( - _ executable: String, arguments: [String] = [], - environment: [String: RuntimeValue] = [:], workingDirectory: Resource? = nil - ) -> MCPTransport - public static func streamableHTTP( - url: String, headers: [String: RuntimeValue] = [:] - ) -> MCPTransport - public static func sse(url: String, headers: [String: RuntimeValue] = [:]) -> MCPTransport -} -public enum HookEvent: Sendable, Equatable { - case beforeTool, afterTool, sessionStart, sessionEnd - case native(String) -} -public struct PromptParameter: Sendable, Equatable { - public static func parameter(name: String, description: String, defaultValue: String? = nil) -> PromptParameter -} -public enum PermissionOperation: Sendable, Equatable { - case read, write, execute - case tool(String) -} -public struct PermissionRule: Sendable, Equatable { - public static func allow(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule - public static func ask(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule - public static func deny(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule -} -public enum IgnorePurpose: Sendable, Equatable { case context, indexing } -public enum PluginMode: Sendable, Equatable { case native, components } -public enum ComponentKind: Sendable, Equatable { - case skills, instructions, mcpServer, hook, subagent, command - case lspServer, permissions, ignore, plugin -} -public enum ComponentReference: Sendable, Equatable { - case skill(name: String) - case instruction(name: String) - case mcpServer(name: String) - case hook(name: String) - case subagent(name: String) - case command(name: String) - case lspServer(name: String) - case permissions(name: String) - case ignore(name: String) - case plugin(name: String) -} -``` +| Family | Payload semantics | +| --- | --- | +| Skills | Selection, exclusions, installation mode and member overrides preserve membership tracking and item pins. Duplicate names and conflicting members are diagnosed. | +| Instructions | Contributions append sections in traversal order. Prompt names are unique; each prompt has its own ordered sections. | +| MCP server | Stdio, Streamable HTTP and SSE are distinct transports. Transport conversion must be exact; all registrations require approval. | +| Hook | Portable events mean before/after a tool invocation and session start/end. Adapters preserve event and command-result behavior. `.native("event")` uses its single recipient's event grammar. Matchers use its verified grammar. Omitted timeouts retain the native default. Hooks preserve declaration order. | +| Subagent | Description and prompt are portable text. Model/tool names are identifiers validated by the recipient adapter. Omitted tools inherit its default; `[]` requires no tools. | +| Command | A named user-invoked prompt. Parameter tokens appear as literal `${input:name}`; missing required inputs are errors. Substitution is text, not shell evaluation. | +| LSP server | A stdio executable invocation, an extension-keyed `languages` dictionary and initialization options. One extension has one language by construction. Plugin-only recipients get an adapter-generated native plugin recorded in the ledger. | +| Permissions | Ordered last-match rules, with no match inheriting native policy. Read/write patterns are scope-relative globs (`*`, `**`, `?`). Execute/tool patterns use the adapter's verified request representation. Translation must preserve the full policy, including unmanaged rules; otherwise deployment fails. | +| Ignore | Ordered gitignore-style patterns with `!` negation, rooted at scope. Context and indexing are separate purposes, neither an access-denial guarantee. | +| Plugin/extension | Components mode decomposes a pinned container and selects all kinds when `select` is omitted; `[]` selects none. Typed references exclude individual children. Native mode keeps the container unchanged. Native configuration may configure only its registration, not rewrite container content. | -Literal conversions are closed and contextual. `PromptContent`, -`SectionReference`, `GroupReference`, `Version` and `RuntimeValue` accept string literals; `SkillSelection` -accepts string array literals. `ConfigurationValue` accepts strings, signed -64-bit integer literals, booleans, `nil`, arrays and string-keyed dictionaries. -Decimals use `.decimal("1.25")`, with finite JSON-number text; floating-point -literals are outside the grammar. Native configuration is a dictionary keyed -by registry schema ID, with a string-keyed configuration object as each value. -Duplicate decoded keys, compared using Swift String equality including canonical -Unicode equivalence, are domain errors at every dictionary level, even if their -values are equal. There is no user-defined literal conformance or conversion -from an already-typed `String`, `[String]` or dictionary to a wrapper type. - -A bare section string names the declaring project's own instruction section; -`.section(name: "engineering", source: "rules")` names a source section. A root user-scope -declaration uses named instruction sources. Exported own sections belong to the -producer package and may be consumed in either supported scope. Ordered sections, -Markdown rendering and **front matter** (the structured metadata preceding a -content file's body) retain their domain semantics. ChatGPT is a named prompt -rendering destination, not an `Agent`. Prompt `append` paths remain relative to -the project root in project scope and runtime home in user scope; exported -prompt append paths are attached to the producer snapshot. - -Omitted mode inherits the selection mode, then `.link`. Link and copy modes -preserve independent item pins. Omitted skill selection means all discovered -members; `[]` selects none. Exclusions win; overrides do not re-add excluded items. -An override outside an explicit selection is a `manifest.domain` error; -compatibility conversion of inert JSON overrides is defined under migration. -An all-member selection can retain overrides for members not yet discovered. - -`path` locates a resource inside the declaring package or a named source -discovery root; `subpath` narrows the source's own root before discovery. Resource -paths are safe relative paths. Project package roots are project directories; a user package root is its -user-state directory. Exported resources remain pinned to their producer. -Absolute resource paths, traversal and escaping symlinks are errors. Source -locations retain their existing absolute/home-relative path support. -Executables are fixed program names or package-relative executable paths, with -separate argument arrays. Shell interpretation requires an explicitly declared -shell command. Symbolic environment and secret bindings are resolved by core's -machine binding provider at apply, or emitted as native references where supported. -Reading and dumping do not fetch values. Previews redact secrets; locks retain -binding identity, not values. Secret rotation does not change command identity. +Shell interpretation requires an explicitly declared shell command. Symbolic +environment and secret bindings are resolved by core's machine binding provider +at apply, or emitted as native references where supported. Previews redact +secrets; locks retain binding identity, not values. Secret rotation does not +change command identity. Exported resources, own sections and prompt `append` +paths remain attached to their producer snapshot; exported own sections may be +consumed in either supported scope. A native schema ID, for example `claude-code/subagent@1`, identifies its agent, component kind and adapter schema version. Agent identity is not repeated in the @@ -439,83 +169,6 @@ errors for active deployment. A native permission policy can use empty portable rules when no exact portable translation exists. Native configuration remains subject to ordinary preview, ownership and approval checks. -#### Component factories - -```swift -public struct Component: Sendable, Equatable { - public static func skills( - source: String, select: SkillSelection = .all, exclude: [String] = [], - mode: InstallMode? = nil, overrides: [SkillOverride] = [], - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func instructions( - sections: [SectionReference] = [], chatGPT: [ChatGPTPrompt] = [], - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func mcpServer( - name: String, transport: MCPTransport, - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func hook( - name: String, event: HookEvent, run: ExecutableInvocation, - matcher: String? = nil, timeoutSeconds: Int? = nil, - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func subagent( - name: String, description: String, prompt: PromptContent, - model: String? = nil, tools: [String]? = nil, - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func command( - name: String, description: String, prompt: PromptContent, - parameters: [PromptParameter] = [], - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func lspServer( - name: String, run: ExecutableInvocation, languages: [String: String], - initializationOptions: [String: ConfigurationValue] = [:], - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func permissions( - name: String, rules: [PermissionRule], - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func ignore( - name: String, patterns: [String], purpose: IgnorePurpose = .context, - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func plugin( - name: String, path: String, source: String, - mode: PluginMode = .components, select: [ComponentKind]? = nil, - exclude: [ComponentReference] = [], - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component -} -``` - -| Family | Payload semantics | -| --- | --- | -| Skills | Selection, exclusions, installation mode and member overrides preserve membership tracking and item pins. Duplicate names and conflicting members are diagnosed. | -| Instructions | Contributions append sections in traversal order. Prompt names are unique; each prompt has its own ordered sections. | -| MCP server | Stdio, Streamable HTTP and SSE are distinct transports. HTTP(S) URLs have no embedded credentials or fragments. Transport conversion must be exact; all registrations require approval. | -| Hook | Portable events mean before/after a tool invocation and session start/end. Adapters preserve event and command-result behavior. `.native("event")` requires exactly one explicit agent recipient and uses that agent's event grammar. Matchers use its verified grammar. Timeouts are positive seconds; omission retains the native default. Hooks preserve declaration order. | -| Subagent | Description and prompt are portable text. Model/tool names are identifiers validated by the recipient adapter. Omitted tools inherit its default; `[]` requires no tools. | -| Command | A named user-invoked prompt. Unique parameter names appear as literal `${input:name}` tokens; `$${input:name}` escapes a token. Missing required inputs and undeclared tokens are errors. Substitution is text, not shell evaluation. | -| LSP server | A stdio executable invocation, an extension-keyed `languages` dictionary and initialization options. Each dot-prefixed extension key maps to one language ID; duplicate keys are domain errors, so one extension has one language by construction. Plugin-only recipients get an adapter-generated native plugin recorded in the ledger. | -| Permissions | `.allow(.read, "pattern")`, `.ask(.write, "pattern")` and `.deny(.execute, "pattern")` put the operation before its pattern. Ordered last-match rules, with no match inheriting native policy. Read/write patterns are scope-relative globs (`*`, `**`, `?`). Execute/tool patterns use the adapter's verified request representation. Translation must preserve the full policy, including unmanaged rules; otherwise deployment fails. | -| Ignore | Ordered gitignore-style patterns with `!` negation, rooted at scope. Context and indexing are separate purposes, neither an access-denial guarantee. | -| Plugin/extension | Components mode decomposes a pinned container and selects all kinds when `select` is omitted; `[]` selects none. Typed references exclude individual children. Native mode keeps the container unchanged, requires one explicit recipient in `agents`, and accepts neither selection nor exclusions. Native configuration may configure only its registration, not rewrite container content. | - Capability validation checks every active agent/component/scope/feature against the registry; unsupported requests are reported rather than dropped. Inactive branches still undergo syntax, type and domain checks. Pending executable @@ -534,7 +187,8 @@ an intersection with consumer defaults. When the component omits `agents`, its declaring document supplies the default, which is captured when exporting it, including its language-version fallback. A producer omitting `defaultAgents` publishes to Claude Code and Codex in language 1.0. Consumer defaults never -retarget imported content. +retarget imported content. The state layer applies this fallback to the +unconditional root components it deploys. A skill member's explicit override recipients replace its selection's recipients; otherwise those selection recipients are its default. This is the same fallback @@ -597,8 +251,9 @@ The producer's defaults are captured as described under targeting. new name, declare a wrapper `.group(name: "quality", uses: ["review"])` and export `"quality"`. References do not import Swift symbols. There are no wildcard exports, implicit exports or executable package -initializers. Duplicate group/export names and unknown local group names are -errors, including in unused declarations. +initializers. The front end checks +[local group references](../Reference/Manifest.md#group-references), including +in unused declarations. A source manifest is `/.agent/Agents.swift`; when the discovery root itself is `.agent`, it is `/Agents.swift`. Exactly one lookup @@ -634,10 +289,11 @@ explicit edit-mode skill children remain live. `install` restores the recorded closure without consulting a mutable index or branch. `update` re-resolves the affected closure and previews changes. Pins are never copied into the manifest. -Cycle detection follows the active local/cross-source reference stack before -memoization and reports the cycle with source spans. A diamond is not a cycle. -Repeated references retain occurrence provenance. Conflicting active payloads -for the same named identity and overlapping recipients are errors. Equal named +Cross-source cycle detection follows the active reference stack before +memoization and reports `manifest.group.cycle` with source spans. A diamond is +not a cycle. Repeated references retain occurrence provenance. Conflicting active +payloads for the same named identity and overlapping recipients are +`manifest.group.conflict` errors. Equal named hooks/policies coalesce at their first position to avoid duplicate execution; ordered instruction sections retain intentional repetition. Disjoint targeting may reuse a name. @@ -650,11 +306,24 @@ must preserve the entire ordered policy including unmanaged rules. There is no last-writer-wins merge or implicit deployment rename. Resolve conflicts through producer naming, selection/exclusions or conditions. +Linking is bounded by 256 distinct source snapshots, 16,777,216 aggregate +manifest input bytes, 64 active group references, 10,000 component contributions +and 1,000,000 total resolution/evaluation steps, including backtracking. Linked +expanded values also obey the +[expanded-value limits](../Reference/Manifest.md#resource-limits). Source +download and extraction limits remain in core's loader before the linker +receives bytes. + +An exported declaration is read-only in a consumer: an edit changes its +`GroupReference.condition` or the producer's own document, never cached source. +After a document edit, prepare re-links affected sources and revalidates +capabilities and targets. + ### Examples #### showxu/skills -The skills repository's existing declaration converts to: +The skills repository declares: ```swift // agents-tools-version: 1.0 @@ -802,565 +471,6 @@ let agents = Agents( ) ``` -### Files, versions and static grammar - -Project source is `.agent/Agents.swift` relative to the explicit project root; -user source is `~/.agents/Agents.swift` relative to core's runtime home. Their -locks remain adjacent `agents.resolved` files. There is no ancestor search or -automatic user/project merge. An absent manifest means an absent declaration. -Existing `agents.json` requires migration; both filenames present is a conflict. - -The first line is exactly `// agents-tools-version: 1.0`, at byte zero after an -optional UTF-8 BOM, terminated by LF, CRLF or EOF. General version syntax is -`// agents-tools-version: MAJOR.MINOR`, with the shown spaces, decimal components -without leading zeroes except `0`, and no patch, suffix or trailing whitespace. -A missing, malformed, duplicate or unsupported directive has its own diagnostic. -Directive recognition is lexical: a directive-shaped line comment outside a -string is a duplicate; text inside a string literal is ordinary content. -A 1.0 reader accepts exactly `1.0`. A future reader explicitly declares its support -set. Newer unsupported versions request an upgrade; older unsupported versions -request a supported converter. Language, package, adapter, lock and dump versions -are independent. Editing preserves BOM/newlines; migration emits UTF-8 without BOM. - -Exactly one unqualified `import AgentsDescription` precedes top-level initialized, -single-binding `let` declarations. Names use the identifier grammar below, are -unique and cannot shadow vocabulary types. Constants bind in textual order; references to later constants -or themselves fail. There are no modifiers, attributes, wrappers or semicolons. -Every declaration, including unused constants and inactive branches, is checked. -Group-name references are resolved separately and may refer forward. - -| Accepted syntax | Rule | -| --- | --- | -| `SourceFileSyntax`, `ImportDeclSyntax`, `VariableDeclSyntax` | The file structure above, with one identifier-pattern binding and initializer per declaration. | -| `StringLiteralExprSyntax` | Single-line and multiline literals from the closed lexical grammar below, with Swift decoding and no interpolation. Contextual `GroupReference` literals denote local groups; this is a type conversion, not an extra grammar production. | -| Integer, Boolean and nil literals | Decimal signed-64 integers with underscore separators, Bool and contextual nil. One unary minus is accepted only immediately adjacent to a decimal integer literal, with no intervening trivia. Other bases, floating literals and other numeric operators fail admission. | -| `ArrayExprSyntax` | Homogeneous arrays or a contextual, whitelisted array-literal conversion. Trailing commas are allowed. Empty literals require contextual type. | -| `DictionaryExprSyntax` | String-literal keys, homogeneous contextual values, or a contextual configuration object. `[:]` is an empty dictionary. Keys are decoded before duplicate detection; key references/interpolation are rejected. | -| `DeclReferenceExprSyntax` | A preceding constant, a vocabulary type as a member/call base, or the permitted operator. | -| Sequence/folded infix expressions | Only left-associative array `+` with exact `[T]` operands, at most 32 terms per additive chain. No concatenation of selections or configuration values, dictionary merging or string concatenation. A single half-open version range is admitted only in the source requirement position defined below; other operators are rejected. | -| `TupleExprSyntax` | One unlabeled expression in parentheses, not tuple values. | -| `MemberAccessExprSyntax` | Listed static factories, static `.all`, and enum cases, qualified or contextual. No instance-property access, subscripts or optional chaining. | -| `FunctionCallExprSyntax` | `Agents(...)`, listed static factories and associated cases, with exact labels and order. Literal-protocol entry points are reached only through literals. No arbitrary functions or trailing closures. | -| Type annotations | `String`, `Int`, `Bool`, named vocabulary types/aliases, `[T]` and `[String: T]`. No explicit Optional annotations, user aliases, qualified/generic/existential/function/metatype syntax. | - -Grammar admission precedes SwiftParser and the iterative tree check precedes all -recursive SwiftSyntax processing. The normative productions below and the syntax -node table describe the same constructs, subject to the byte, token, chain and -depth limits below. These limits apply even to unused or inactive -expressions. Parser recovery, missing tokens and unexpected syntax are errors. -Tokens inside accepted nodes are admitted only in the roles above. Constructors create data; -they never invoke Swift compiler code while evaluating a manifest. - -#### Type inference and literal conversions - -An annotation or parameter type supplies context inward. Otherwise literals, -qualified calls and references synthesize types outward. Without context, a -string is `String`, an integer is `Int`, and a boolean is `Bool`. Arrays infer -from the first element; dictionaries infer from the first value and require all -other values to agree. Empty collections, nil and a leading shorthand member -cannot infer a type alone. Dictionary keys are always strings. - -Optional parameter types remain part of the construction API: their context -admits `nil` or injection of a value of the wrapped type. Source annotations use -the non-Optional forms in the grammar; `T?` and `Optional` fail grammar admission. -This does not change the module's public Optional signatures or compiler typing. - -In contextual vocabulary types, only the literal conformances declared above -apply. Nested configuration literals propagate `ConfigurationValue` context to -every child. For an Optional parameter with wrapped type `T`, nil means absence; -non-nil values may receive `T` context and Optional injection. For non-Optional `ConfigurationValue`, nil means -configuration null. Signed integer literal conversion follows Swift's literal -semantics and must fit the declared literal type. `.decimal(...)` remains explicit. -No arbitrary user protocol dispatch or conversion of pre-existing typed values -is allowed. In particular, a `String` constant is not implicitly a `PromptContent` -or a `SectionReference`, `GroupReference` or `Version`, and a `[String]` constant is not a `SkillSelection`. - -For array `+`, context propagates to both operands when present; otherwise infer -the left array and use its element type for the right array. An expression of -`SkillSelection` or `ConfigurationValue` type is not a Swift array. Constants -must be typed where declared, not inferred backward from later uses. A standalone -component is `let reviewer: Component = .subagent(...)` or a fully qualified -factory call. The evaluator's accepted language is a subset of real Swift typing, -not an alternative type system. - -| Diagnostic | Meaning | -| --- | --- | -| `manifest.version.missing`, `.invalid`, `.duplicate`, `.unsupported` | Version selection failed. | -| `manifest.syntax` | Recognizer: a lexical or production violation, including missing/extra imports, juxtaposed identifiers, unsupported prefixes, raw strings, interpolation and malformed literals. SwiftParser syntax/recovery diagnostics can occur only after recognizer acceptance and the tree guard; such a disagreement is also an implementation regression. | -| `manifest.call`, `manifest.type`, `manifest.operator` | After the tree guard: unlisted call/member, incorrect labels/order/type, missing context, integer overflow or non-array use of the admitted `+` operator. The `..<` operator is typed as `Range` only in its admitted requirement position. Other operators, including closed ranges (`...`), fail admission with a located `manifest.syntax` diagnostic; `ClosedRange` also has no matching compiler overload. | -| `manifest.reference` | Unknown, forward, self, duplicate or shadowing constant name. | -| `manifest.domain`, `manifest.dictionary.duplicateKey` | Invalid domain value or duplicate decoded dictionary key. | -| `manifest.group.cycle`, `.missing`, `.conflict` | Invalid group/source graph, with the relevant reference chain. | -| `manifest.limit` | Recognizer: byte, token, syntax-storage reservation, comment, delimiter or chain limit. Iterative tree guard: node/depth limit. Later stages: evaluation, expansion, output or other named budget. | - -Diagnostics include stable code, severity, message, primary span, related spans -and optional suggested edit. Spans use half-open UTF-8 byte offsets and 1-based -line/UTF-8-byte-column positions. At most 100 diagnostics plus one truncation -notice are produced. Any structural/type/domain error rejects the candidate; -no partial declaration is published. - -#### Normative admission grammar - -`AgentsManifest` owns a strict lexer and a deterministic recognizer for these -productions. No byte reaches SwiftParser until the complete input snapshot passes -recognition. SwiftParser supplies the lossless tree for editing and diagnostics; -it does not decide which source grammar is admitted. The recognizer does not -resolve constants or evaluate constructors. The subsequent type/domain checks -restrict identifiers and calls to the vocabulary and rules above. - -The grammar uses `?` for optional, `*` for repetition and `|` for alternatives; -quoted punctuation denotes source tokens. Trivia may separate tokens except at -explicitly contiguous spellings. `newline` means at least one LF, CRLF or CR in -the separating trivia. The version directive is checked as specified above using -the same lexer's comment/string boundaries, before syntax is handed to SwiftParser. - -```ebnf -document = "import" "AgentsDescription" newline declaration - (newline declaration)* EOF ; -declaration = "let" bareName (":" type)? "=" expression ; -type = typeName | "[" type "]" | "[" "String" ":" type "]" ; -expression = primary ("+" primary)* ; -primary = string | integer | "-" integer | "true" | "false" | "nil" - | namedValue | array | dictionary | "(" expression ")" ; -namedValue = sourceCall | callee ("(" arguments? ")")? ; -callee = bareName | bareName "." name | "." name ; -arguments = argument ("," argument)* ; -argument = (name ":")? expression ; -sourceCall = (".source" | "Source.source") "(" "name" ":" expression "," - (("url" | "path") ":" expression - ("," requirement)? | "index" ":" expression) - ("," "subpath" ":" expression)? ")" ; -requirement = ("from" | "exact" | "branch" | "revision") ":" expression - | versionRange | rangeFactory ; -versionRange = string "..<" string ; -rangeFactory = (".upToNextMajor" | ".upToNextMinor") - "(" "from" ":" expression ")" ; -array = "[" (expression ("," expression)* ","?)? "]" ; -dictionary = "[" ":" "]" - | "[" string ":" expression - ("," string ":" expression)* ","? "]" ; -``` - -`typeName` is exactly `String`, `Int`, `Bool`, or a public vocabulary type/alias -listed under Construction vocabulary. Type existence is checked during recognition. `sourceCall` takes -precedence over the general call production for `.source` and `Source.source`; those spellings cannot bypass it through `callee`. The -`.upToNextMajor` and `.upToNextMinor` callees are reserved to `rangeFactory`, -including its required argument list; other positions fail recognition. -`versionRange` is not a general expression: no grouping, constants, chaining or -other operands are admitted at its position. A range factory is contextual to -this same unlabeled requirement slot. Its argument receives `Version` context; -`from:` and `exact:` on the source also receive `Version` context. The subsequent -checker enforces version typing and domain validation. `callee` is a -syntactic spelling; subsequent vocabulary checking rejects unlisted functions, -instance members, literal-protocol entry points and invalid factory labels. -There is no postfix loop: a callee has at most one member operation and one call, -for a maximum grammatical chain of **2**. The independent postfix-operation -counter has a ceiling of **4** per primary; budget headroom admits no additional -production. No operation attaches to a call result, grouped -expression or subscript. The leading shorthand dot counts as one operation. -These are exactly the construction forms needed by the vocabulary. Parentheses -contain one expression; calls have no trailing comma; collections may have one. -The additive production has at most **32 terms**, with later type checking -requiring array operands. A version range has exactly two literal operands. -No assignment expression or prefix-keyword production exists. An identifier after a completed expression is a syntax error, not an -implicit prefix, argument or declaration. - -The lexical grammar is closed: - -- An identifier has ASCII head `[A-Za-z_]` and continuation `[A-Za-z_0-9]*`. - Backticks, `$` names and non-ASCII identifiers are excluded; Unicode remains - available in string values, including all domain names and paths. `name` excludes - the reserved spellings listed below. `bareName` additionally excludes `await`, - `copy`, `consume`, `each` and `unsafe`; those contextual spellings may occur as - argument labels or member names, including `.copy`. They cannot introduce a - prefix production or a bare binding/reference/callee in language 1.0. -- `integer` is `[0-9][0-9_]*`. The optional minus is a separate token immediately - adjacent to its digits and only in the shown primary production. Its preceding - source character must be ASCII whitespace (space, tab, CR or LF), `(`, `[`, `,` - or `:`; an adjacent operator or comment terminator cannot precede the sign. - Range checking follows during typing. There are no floating-point, exponent or - radix literals; - decimal configuration values use `.decimal("1.25")`. -- `string` is an ordinary double-quoted single-line literal or a triple-quoted - multiline literal. Both allow exactly `\0`, `\\`, `\t`, `\n`, `\r`, `\"`, `\'` - and `\u{H}` escapes, where `H` is one to eight ASCII hex digits naming a Unicode - scalar (not a surrogate and at most `10FFFF`). Interpolation and escaped newline - continuation are excluded. A single-line literal contains no unescaped CR/LF. - A multiline opener is followed immediately by LF, CRLF or CR; its closing - delimiter is preceded on its line only by spaces. A content line is either - empty (zero characters before its newline) or starts with the closing delimiter's - exact space indentation prefix, which Swift decoding removes. Additional leading - spaces remain content. Whitespace-only lines are nonempty and must carry the - full prefix. A tab anywhere in a content line's leading whitespace or in the - closing delimiter's indentation is a syntax error; tabs after the first - non-whitespace content character remain literal content. These rules apply - identically to LF, CRLF and CR lines. Unescaped single/double quote runs are - multiline content; the first - unescaped triple quote closes it. Unescaped control scalars below U+0020 other - than tab and multiline CR/LF are rejected. Raw strings do not exist: `#` outside - string/comment content always fails recognition. -- Trivia is ASCII space, tab, LF, CRLF or CR, an optional BOM at byte zero, `//` - comments through the next CR/LF or EOF, and `/* ... */` comments with at most - **20** nested levels. The lexer validates UTF-8 throughout the snapshot. Strings - and comments are opaque to expression counters. No other whitespace or comment - form is admitted. -- Source punctuation is `( ) [ ] , : . = + ..<` and the adjacent numeric sign `-`, - only in the roles in the productions. Callee member spellings contain no trivia - around their dot; the call opener immediately follows its callee. Both `=` and - binary `+` require at least one ASCII whitespace character (space, tab, CR or LF) - immediately on each side. Comments do not substitute for whitespace: every - comment in an operator-to-operand gap must itself have whitespace immediately - before and after it. Thus `value /* note */ = -1` is admitted, but `value=0`, - `value= 0`, `value=-1`, `a+b` and `a/* note */ + b` fail recognition. A located - `manifest.syntax` diagnostic names the canonical spelling, such as - `let value = -1` or `left + right`. These adjacency rules make - Swift operator/member tokenization unambiguous. The single `..<` token is - admitted only by `versionRange`, with either no whitespace on both sides or - at least one ASCII whitespace character immediately on both sides. Comments - in either operand gap must themselves be surrounded by whitespace, as for `+`. - The canonical operator spelling is `"1.2.0"..<"1.8.0"`; an asymmetric boundary - reports that spelling in a located `manifest.syntax` diagnostic. A lone `<` - or `>` is never admitted. Other operators, generic angle - brackets, braces, attributes, directives, macros and regex literals fail at - recognition. There is no fallback to SwiftParser recovery. - -The exact reserved identifier spellings are: - -```text -_ Any Self as associatedtype break case catch class continue default defer deinit -do else enum extension fallthrough false fileprivate for func guard if import in -init inout internal is let nil open operator precedencegroup private protocol public -repeat rethrows return self static struct subscript super switch throw throws true -try typealias var where while -``` - -The lexer consumes each byte a bounded number of times, without backtracking or -unbounded lookahead. The parser uses at most two tokens of lookahead to distinguish -argument labels and dictionary entries, bounded delimiter frames for nested -productions, and loops for siblings and additive terms. It never speculatively -parses a whole expression and rewinds. Its work, storage, literal validation and -located-diagnostic construction are linear in bounded input size. A failure ends -recognition with a located `manifest.syntax` or `manifest.limit`; SwiftParser is -not called. Accepted grammar structure and spans are retained for differential -validation, independently of the later semantic IR. - -#### Expanded-size accounting and resource limits - -Admission reads at most 2,097,153 bytes, rejecting the extra byte before decoding, -lexing or parsing; it never allocates an unbounded file buffer. The exact admitted -snapshot is subsequently parsed. The recognizer permits at most 100,000 non-trivia -tokens; the minus and integer count separately, and `..<` counts as one token -plus its two string-literal operands. Range factories count as ordinary calls. -Version values charge their decoded bytes and nodes; range costs include both -endpoints before canonical lowering or serialization. It additionally reserves syntax -storage conservatively as **16 + 4 × (tokens + literal breaks + literal escapes)**, -capped at 100,000 nodes before SwiftParser is invoked. A literal break is each -CR or LF byte inside a string (CRLF counts twice); a literal escape is each -backslash byte inside a string, including escaped backslashes. These extra units -cover the parser's segmentation of multiline/escaped literals. The grammar-derived -reservation covers file and wrapper nodes as well as tokens; the independent -post-parse guard verifies actual counts. -A parser dependency change must revalidate the reservation against every grammar -production. The reservation is a language budget even when an individual input's -actual tree would be smaller; migration preflight applies it too. - -Every open `[` or `(` increments a grammar counter before entering the enclosed -production, including type annotations. Square depth above **8** or combined -depth above **20** is `manifest.limit` at the first excess opener. Block-comment -depth above 20, a thirty-third additive term or an excess token/storage reservation -likewise fails before parsing. All other missing, misplaced or unsupported tokens -are `manifest.syntax` at the expected production's location (EOF for missing -input). Unbalanced openers remain counted until rejection; neither trivia nor -parenthesized subexpressions can bypass the counters. No production permits more -than two postfix operations or more than one numeric sign. These grammar bounds -apply equally to unused constants and inactive components. - -Immediately after parsing, an **iterative, non-recursive** walk checks all syntax -nodes, including collections, tokens, missing nodes and unexpected nodes, in the -all-nodes view. The root has depth 1; depth above **128** or more than **100,000** -nodes is `manifest.limit`. Reserve stack/node budget before enqueueing children; -compute failure offsets from cached byte lengths during the walk. Do not call -recursive visitors, `hasError`, diagnostic generation, tree descriptions, source -mapping, equality or evaluation before this guard succeeds. The same rule applies -to transformed/folded trees: build/check them iteratively before recursive use. -The tree ceiling is independent of source delimiter depth and leaves room for -SwiftSyntax's wrapper nodes. Evaluation retains its separate frame/work limits. - -No manifest input within the byte limit may crash or hang the hosting process, -including the GUI. Invalid and over-budget input must end in a bounded diagnostic -without writes or partial IR publication. This is a required implementation and -release invariant, not a conclusion inferred from `maximumNestingLevel` or a -finite set of passing examples. Parser construction, error inspection, tree -lifetime/teardown and every consumer of syntax are included in the invariant. - -The square-bracket ceiling is **8**, independently of the general delimiter -ceiling of **20**. The complete manifest examples in this contract reach depth -3. Fixed family fields, excluding recursive configuration values and arbitrary -nested array constants, reach depth 5: root groups, components, ChatGPT prompts, -sections, then a section condition's recipient array. -Eight leaves three levels of syntax-depth margin over that fixed structure. -`ConfigurationValue` is recursive, so its vocabulary has no intrinsic finite -nesting maximum; its expanded values remain limited to depth 64. Named constants -allow deeper configuration values to be assembled without deep source nesting, -subject to all expansion budgets. This separates authoring depth from value depth -and caps square-bracket ambiguity before parser recovery. The parser's own -nesting option remains defense in depth, not a parse-time bound. - -The evaluator may store immutable values as a DAG, but all limits are measured -as if each reference were expanded by value. Each value carries a checked cost -summary: expanded node count, decoded string/key bytes, canonical encoded byte -count, maximum depth and source-origin count. For a container, costs are its own -cost plus the sum of each child's costs **for every occurrence**. Reusing a -constant twice adds its full cost twice, including all descendants. An alias -inherits the referenced cost; memoization does not discount expansion. - -Compute costs bottom-up with checked, saturating arithmetic capped at the limit -plus one. Before concatenation, reference insertion, group expansion or any output -allocation, combine the summaries and reject an oversized result. No descendant -walk, copying, formatting, map expansion or equality comparison occurs first. -This rejects exponential reuse such as repeated `array([previous, previous])` -while that value is constructed, even when its underlying storage is small. -Every constant must fit individually; totals count every top-level definition -and every root occurrence, including inactive and unused values. - -Encoded-size summaries include repeated dictionary keys, string escaping, -punctuation, indentation and trailing newline. Before writing a dump or generated -source, reserve its complete bounded size from those summaries. When formatting -context changes indentation, use a checked worst-case bound or recompute the -summary over the bounded structure before emitting bytes. Locations and provenance -are separately budgeted and included in the final dump's size reservation. - -| Resource | Language 1.0 bound | -| --- | --- | -| Input | 2,097,152 UTF-8 bytes per manifest, enforced by bounded reading before grammar admission, decoding or parsing; invalid UTF-8 fails. | -| Admission | Linear lexer and grammar recognizer; 100,000 tokens; syntax reservation `16 + 4 × (tokens + literal breaks + literal escapes) ≤ 100,000`; square depth 8; combined square/parenthesis depth 20; comment depth 20; postfix-operation budget 4 (the grammar uses at most 2); one adjacent numeric sign; additive chain 32 terms. Failures reject before SwiftParser. | -| Parser/tree | `maximumNestingLevel: 20` in every build configuration. Iterative guard: depth 128 (root 1), 100,000 syntax nodes including tokens and excluding trivia, before any recursive processing. | -| Evaluator | 64 active expression/reference frames; 100,000 work steps per document. Every visited expression, lookup, produced node and concatenation element costs a step. | -| Expanded values | 100,000 nodes and 16,777,216 decoded string/key bytes across the document's values, charged by occurrence, with 10,000 entries per array/dictionary and maximum expanded value depth 64, including referenced descendants. | -| Linking | 256 distinct source snapshots, 16,777,216 aggregate manifest input bytes, 64 active group references, 10,000 component contributions and 1,000,000 total resolution/evaluation steps, including backtracking. Linked expanded values also obey the node/string limits above. | -| Source maps | 100,000 location records, 1,000,000 total origin spans and 16,777,216 encoded bytes; repeated origins count repeatedly. Reserve before expanding a reference's map. | -| Output | 33,554,432 bytes for the entire dump including locations/diagnostics; generated manifest source still obeys the 2,097,152-byte input limit. | -| Comparison/edit batch | 200,000 expanded node-pair visits per full comparison; 1,000,000 aggregate steps and 100 requests per edit batch. Operand cost summaries are checked before comparison starts. | - -A work budget is charged before executing a step; exhaustion is a diagnostic, -not an invitation to return a truncated model. Comparisons can use identity or -memoization only after verifying expanded operand bounds. Diagnostics and JSON -escaping are bounded operations. Source download/extraction limits remain in -core's loader before the linker receives bytes. Cancellation is separate from -language semantics. Fuzzing and adversarial reuse tests cover every bounded -consumer of values, not just the parser. - -### Document editing - -`AgentsManifest.DeclarationDocument` owns original bytes, syntax, declaration IR, -source maps, diagnostics, editability and the original byte digest. Domain edits -use the same vocabulary names as authored values; lowering converts them to core -IR. Snapshot node handles are separate from persistent component identities. - -```swift -public struct DeclarationDocument: Sendable { - public init(bytes: [UInt8], identity: DocumentIdentity) throws - public var declaration: DeclarationIR { get } - public var diagnostics: [ManifestDiagnostic] { get } - public func editability(of node: NodeID) -> Editability - public func preparing(_ edits: [ManifestEdit]) throws -> DocumentChange -} -public enum ManifestEdit: Sendable { - case setDefaultAgents([Agent]?) - case upsertSource(Source) - case removeSource(alias: String) - case insertComponent(Component, into: ContainerID, at: InsertionPosition) - case replaceComponent(NodeID, with: Component) - case removeComponent(NodeID) - case moveComponent(NodeID, into: ContainerID, at: InsertionPosition) - case setSkillSelection(NodeID, SkillSelection) - case upsertSkillOverride(NodeID, SkillOverride) - case removeSkillOverride(NodeID, name: String) - case insertSection(SectionReference, into: NodeID, at: InsertionPosition) - case removeSection(NodeID) - case moveSection(NodeID, at: InsertionPosition) - case upsertPrompt(NodeID, ChatGPTPrompt) - case removePrompt(NodeID, name: String) - case upsertGroup(ComponentGroup) - case removeGroup(name: String) - case insertGroupReference(GroupReference, into: ContainerID, at: InsertionPosition) - case removeGroupReference(NodeID) - case setExports([String]) - case setWatch([String]) - case setDictionaryEntry(NodeID, key: String, value: StaticValue) - case removeDictionaryEntry(NodeID, key: String) - case replaceConstant(NodeID, with: StaticValue, acceptingUses: [NodeID]) -} -``` - -`NodeID` is an opaque handle bound to the document digest. `ContainerID` addresses -the root or a group. `InsertionPosition` is `.first`, `.last`, `.before(NodeID)` -or `.after(NodeID)`. `StaticValue` is the bounded checked algebra of literals, -collections and vocabulary values, not raw Swift text. Dictionary value edits -must match the target's inferred value type. Whole-component replacement covers -recipients, conditions and all family-specific fields. - -The document applies requests in order to construct the expected complete IR, -checks their complete impact and budgets, and produces disjoint byte patches. -`DocumentChange` contains the original digest, patches, resulting bytes/digest, -expected declaration, impacted references, diagnostics and semantic delta. -Only the document layer constructs it. `AgentsUpdates` incorporates it in prepare; -front ends never save source independently. - -| Construct | Editability | -| --- | --- | -| Direct literal/factory argument | Replace the exact value range; retain outer trivia. | -| Direct array literal | Insert, remove and move identifiable elements, preserving order. | -| Direct dictionary literal | Set/remove a decoded key's value or entry; preserve unrelated entries and their order/comments. | -| Direct root/group/component construction | Insert missing arguments in signature order and remove/replace unambiguous arguments. | -| Constant reference | Readable with all references identified. Only explicit `replaceConstant` changes its definition, accepting the complete impacted reference set. | -| Concatenation/assembled value | Readable; expanded element edits are read-only. An independently addressed literal leaf or explicitly replaced constant can be edited with its full impact accepted. | -| Exported declaration | Read-only in a consumer. Edit its `GroupReference.condition` or the producer's own document, never cached source. | -| Ambiguous trivia or separators | `manifest.edit.readOnly` with a span and reason; no regeneration fallback. | - -Removing referenced sources/groups requires a complete batch that repairs the -references. Stale handles, overlaps, incomplete impact and mismatched results have -separate `manifest.edit.stale`, `.overlap`, `.impact`, `.mismatch` diagnostics. - -Comments follow SwiftSyntax trivia ownership: - -1. Standalone comments immediately above a node with no separating blank line - belong to that node; a dictionary key and value form one entry node. -2. Comments beginning on a node's or its comma's line belong to that preceding - node, including multiline block comments. -3. Comments inside an expression or between it and its comma belong to it. -4. Comments separated from the next node by a blank line belong to the container. - The preamble and version directive belong to the file. -5. Delete/move operations carry owned comments. Value replacement preserves outer - comments; whole-node replacement refuses if internal comments cannot be mapped - to retained fields. Unowned comments remain in place. -6. Empty containers become `[]` or `[:]` only when their interiors are whitespace. - Container comments survive; ambiguous mixed layouts or comment-only insertion - sites are read-only. - -New nodes use the shortest canonical type-correct spelling. `Agents(...)` is the -only ordinary initializer in manifest expressions; nested values use leading-dot -factories. Sources use `.source(name:url:)`, `.source(name:path:)` or -`.source(name:index:)`, and references use `source:`. -Requirement values use the canonical printer defined under Construction vocabulary. Literal conformances provide strings -for prompts, own sections, local group references and versions, array literals for explicit skill -selections, and JSON-style configuration literals. Dictionary literals and -direct factories construct the remaining values. Existing unmodified expressions keep their spelling. New text uses -the container's consistent indentation, newline and comma style; absent evidence, -use two spaces, LF and trailing commas in multiline collections. Argument order -follows signatures; root insertion order is `defaultAgents`, `exports`, `sources`, -`components`, `groups`, `uses`, `watch`. `upsertSource(Source)` preserves the -complete requirement value. Fresh node layout follows the deterministic migration printer; -existing surrounding style takes precedence. Conflicting local style is an -editability diagnostic, not permission to reformat the file. - -The editor and migration printer emit one ASCII space on each side of `=` and -`+`, with adjacent sign/digits for negative integers: `let value = -1`. A value -replacement re-checks both joins with the unchanged source, including neighboring -comments, against the lexical rules before it becomes a patch. For example, -replacing `0` in `[/* note */0]` emits ` -1` inside that value's replacement range, -producing `[/* note */ -1]` while preserving all bytes outside the range. The -editor never joins a sign to `=` or to a comment terminator. A source that already -fails recognition, such as `let value=0`, cannot receive a domain edit. If a safe -boundary cannot be represented in the authorized patch range, preparation fails -with an editability diagnostic. The complete candidate passes recognition again -before SwiftParser is invoked; a failed check publishes no patch or source bytes. - -The invariants are byte-exact no-op return, byte preservation outside disjoint -patch ranges, and full reparse/type-check/evaluation/domain validation before -commit. The resulting complete IR must equal the expected IR, including inactive -groups and exports; only source positions and trivia are excluded. Prepare then -re-links affected sources and revalidates capabilities/targets. All stages use the -expanded-size budgets. BOM, final-newline presence and unrelated bytes survive. - -Range replacement re-checks both operator/operand boundaries and the containing -source requirement slot. A complete replacement uses the canonical requirement -printer, including changing the argument label when its range category changes. A leaf endpoint edit preserves surrounding trivia only if the -result still meets balanced spacing and comment rules; otherwise include the -necessary whitespace in the explicit patch or report `manifest.edit.readOnly` -when comment ownership is ambiguous. Re-run admission, typing and expected-IR -comparison before publishing any edit. - -### Evaluated JSON dump - -`agents manifest dump --json` reads and evaluates only the local declaration. -It does not resolve external groups, fetch sources/secrets, inspect native files -or compile/run the manifest. Conditional branches and group references remain -symbolic. Successful stdout is one UTF-8 JSON object with sorted keys, two-space -indentation and a trailing LF. Invalid input exits 1 with stderr diagnostics and -no partial success object. - -The root has `schemaVersion: 1`, `kind: "manifest"`, `languageVersion: "1.0"`, -`sourceDigest`, `declaration`, `locations` and `diagnostics`. The digest is -`sha256:` plus 64 lowercase hexadecimal digits over the original bytes. -`declaration` has `defaultAgents`, `exports`, `sources`, `components`, `groups`, -`uses` and `watch`. Default arrays are empty, Optional absence is null, and -explicit empty recipients remain distinct from inheritance. - -A component encodes directly as `{ "kind": "mcpServer", "name": "workspace", -"transport": { ... }, "agents": ["claude-code"], "condition": null, -"native": {} }`. There is no payload wrapper. The remaining schema is determined -by the vocabulary as follows: - -- Tagged families encode `{kind, ...fields}`. Component/transport kinds are - their factory names. `ExecutableInvocation` is `kind: "executable"` with executable, - arguments, environment and workingDirectory. `.group(name:)` references encode - kind `local`; `.group(name:source:)` references encode kind `exported`, with - name and condition. An exported reference always has a non-null source; a local - reference has none (encoded as null). Conditions encode their - three dimensions without a kind. Permission rules encode - `{kind: "allow" | "ask" | "deny", operation, pattern}`; their two unlabeled - factory arguments use the keys `operation` and `pattern`. LSP `languages` - encodes an object mapping extension keys to language-ID strings. -- A source has `kind: "git" | "local" | "index"`, name, location (`url`, `path` or - `index`, matching its factory field), subpath and requirement. A `path:` source - with a requirement remains kind `local`. Requirement is null or an - object with exactly one of `branch`, `revision`, `exact`, `from`, `upToNextMinor`, - or `from` plus `to`, matching core's `SourceRequirement` encoding. Version values encode - as normalized version strings. Every range value encodes its canonical - requirement kind: `from`, - `upToNextMinor`, or `from`/`to`, regardless of its construction spelling. -- Groups, skill overrides, ChatGPT prompts, prompt parameters and resources encode - their factory fields without a factory-name tag; the resource's unlabeled - subject uses key `path`. Arrays/dictionaries encode as JSON collections, - with defaults supplied. - Exports and watch are string arrays. An instruction section is always an object - with name, source and condition, even when authored as a string. -- Skill selection encodes `"all"` or an array of names. Prompt content is - `{kind: "literal", value: }` or `{kind: "file", path, source}`. - Runtime values similarly use literal/environment/secret and value. Literal - spelling and explicit equivalent cases have identical evaluated output. -- Payload-free enum cases are strings, except mixed enums always use tagged - objects. Associated values retain labels; a single unlabeled payload uses - `value`. Typed component references use kind and name. Configuration values - retain kind and value tags, including nested arrays/objects; null has only kind, - and decimal values remain strings to prevent numeric rounding. -- Agent IDs are `claude-code`, `codex`, `cursor`, `gemini-cli`, `opencode`; - platforms are `macos`, `linux`; other enum spellings are unchanged. - -Components, group references, sections, hooks, permission rules, ignore patterns, -arguments and prompt parameters preserve order. Definitions of sources/groups, -exports, watch, named prompts and overrides sort by name; recipients, exclusions -and explicit skill selections sort by canonical identity. Dictionary keys sort -by decoded UTF-8 bytes. Typed plugin exclusions sort by kind then name. -Constants are substituted by value within the checked expansion budget. - -A location has `pointer` (JSON Pointer into the normalized declaration), `span`, -`origins`, `defaulted` and `editability`. Spans have document `"manifest"`, start/end -byte offsets and starting line/column. A use's span identifies the use site; -origins include definitions. Missing fields anchor to their containing construction -with defaulted true. Editability has kind `direct`, `sharedConstant` or `readOnly`, -plus relevant stable reason and impacted-reference spans. Locations sort by -pointer then start offset; runtime node handles are not serialized. - -Diagnostics have code, severity, message, span and related spans, sorted by -position then code. No timestamps, cache paths or resolved secrets are emitted. -Readers ignore unknown object keys but reject unsupported schema versions and -unknown semantic discriminants. Changed meanings or new discriminants require -a new schema version; optional metadata additions do not. Source digest/locations -may change with comments while declaration stays equal. Entire output and map -size are reserved before serialization under the expanded-size budgets. - ## Target Architecture ```text @@ -1374,13 +484,12 @@ CLI/GUI/skill CLI -> domain edits -> source patches -> front end again -> expected-IR comparison -> prepare -> transaction ``` +[Package Architecture](../Architecture/Package.md) owns the current targets. +Deployment adds or extends: + | Target | Ownership and dependencies | | --- | --- | -| `AgentsDescription` | Public immutable construction vocabulary and literal conformances; standard library only. | -| `AgentsCore` | Agent-independent declaration/resolved IR, source identity, requirements, provenance/span values, capability protocols/descriptors, approval identity, cache, locks and transactions. No syntax or adapter-implementation dependency. | -| `AgentsManifest` | Version selection, strict lexer and grammar recognizer, iterative tree guard, static symbol/type checking and evaluation, diagnostics, source maps, lowering to IR and source editing. Depends on `AgentsDescription`, `AgentsCore`, SwiftSyntax and SwiftParser. No deployment/resolution I/O. | -| `AgentsSkills` | Existing skill discovery, metadata and materialization; depends on `AgentsCore` and Yams. | -| `AgentsInstructions` | Existing instruction discovery, lifecycle and Markdown transformations; depends on `AgentsCore` and swift-markdown. | +| `AgentsCore` | Adds capability protocols/descriptors, resolved component IR and approval identity. No syntax or adapter-implementation dependency. | | `Components` | Internal group linker, input-container adapters and native output adapters. Depends on `AgentsCore`, `AgentsManifest`, `AgentsSkills`, `AgentsInstructions`. Uses core source-resolution sessions and registers capability implementations during composition. Agent adapters are types/files, not one target per agent. | | `AgentsUpdates` | Public prepare/apply orchestration across document edits, domains, components, approvals and one state transaction. Depends on the targets above; front ends consume its workflows. | @@ -1412,15 +521,10 @@ owns the current publication, precondition and recovery guarantees. ### Manifest integration -Manifest orchestration must publish validated source bytes in place of declaration -re-encoding. The deployment ledger and watch state retain their own encoders. -One transaction includes the source, ledger, affected watch state, native outputs, -cache retention and cleanup. Source-only changes use the same protocol. - -Preparation records presence, physical identity and byte digest for the manifest, -ledger, watch state and related targets. A changed comment also invalidates the -prepared preview. These obligations belong to the integration that connects -`Agents.swift` to the state engine. +[Declaration writes](../Architecture/State.md#declaration-writes) own the +publication of validated source bytes, the shared transaction with the ledger, +watch state, native outputs and cache, and the preparation evidence for the +manifest. ### Approvals @@ -1432,139 +536,18 @@ of source validity. ## Compatibility / Migration Impact -### Field mapping - -`agents migrate` validates the existing strict JSON declaration and converts its -intent without fetching, re-resolving pins or inferring installed recipients. - -| JSON | Swift construction | -| --- | --- | -| `agents` | `Agents(defaultAgents: [...])`; omitted remains inheritance, explicit empty remains empty. | -| `sources..git` | `.source(name: , url: , ...)`. | -| `sources..local` | `.source(name: , path: , ...)`. | -| `sources..well-known` | `.source(name: , index: , ...)`. | -| `sources..path` | `subpath:` unchanged. | -| `branch`, `revision`, `exact` | Corresponding source factory label. | -| `from`, `to` | Decode the lower bound and optional upper bound, canonicalize the range value, then print `from:`, the minor-range factory or the unlabeled literal range as appropriate. | -| `upToNextMinor` | The unlabeled `.upToNextMinor(from: "version")` requirement. | -| `skills.` | `.skills(source: , ...)` in components. | -| `select: "all"` | Omit `select`; explicit names become a string array literal, including `[]`. | -| `exclude` | String array, omitted when empty. | -| Skill `agents`, `mode` | Corresponding fields; omission preserves inheritance. | -| `overrides.` | `.skill(name: ..., mode: ..., agents: ...)`, subject to the explicit inert-override rule below. | -| `instructions` | One `.instructions(...)` after skill selections; missing object means no contribution. | -| `instructions.agents` | `agents:` on that component, preserving explicit recipient intent. | -| `instructions.sections[]` | Bare name becomes a string literal; `alias:name` becomes `.section(name: "name", source: "alias")`. Preserve order and repetitions. | -| `instructions.chatgpt.` | `.prompt(name: ..., sections: ..., append: ...)` in `chatGPT`. Names and per-prompt section order remain exact. | -| Prompt `append` | Unchanged string, with existing project-root/user-home interpretation. | -| `watch[]` | Source alias strings in `watch`, with no condition. | -| Missing sources/skills/prompts/watch | Empty collections, with default-valued arguments omitted. | - -Unknown JSON fields, duplicate object keys, invalid UTF-8 and declarations invalid -under the existing validators remain errors. Every currently valid declaration -whose converted manifest fits the language budgets has a deterministic conversion. -Migration preflights all applicable language budgets, including parsing, evaluation, -expansion and output, before starting a state transaction. If any limit is exceeded, it reports `migration.limit` -with the limiting budget and leaves the original declaration, ledger, watch state -and native files untouched. The compatibility transformations below handle valid -JSON that differs from the manifest's domain rules; exceeding a resource budget -never triggers truncation or partial migration. - -### Compatibility transformations - -Three explicit transformations precede printing and are included in the migration -result's ordered diagnostics: - -1. For an explicit skill selection, an override whose name is not in `select` is - provably inert under existing lifecycle behavior. Remove it from the converted - declaration and report `migration.inertOverride` with its original JSON Pointer, - full value and reason. Preserve overrides for selected names, including excluded - selected names, and all overrides of an all-member selection. No override is - removed merely because discovery does not currently find its member. -2. Rename a source alias `.` to the first unused name in `source`, `source-2`, - `source-3`, and so on, considering all original aliases. Report - `migration.sourceAliasRenamed` with old/new aliases. Rewrite its source entry, - skill-selection key, watch references and explicit `.:name` section references - in both native instructions and ChatGPT prompts. Bare section names still mean - own sections and are not rewritten. Normalized source identities and pins do - not change. -3. In each `agents` array at the root, in instructions, in a skill selection or - in a skill override, retain the first occurrence of each recipient ID and remove - subsequent occurrences. Report `migration.duplicateRecipient` for every removed - element with its original JSON Pointer and recipient ID. A nonempty array stays - nonempty, and explicit versus inherited recipients remain distinct. - -Diagnostics sort by original JSON Pointer and code. They are returned in preview -and apply reports; conversion never silently discards a removed override or -recipient, or hides a rename. The compatibility projection compares effective selections, -recipients, modes, ordered content, subscriptions and source identities after -applying precisely those reported transformations. Apart from them, explicit -versus inherited intent and every field above are preserved. No groups, native -settings or additional approvals are synthesized. - -### Deterministic source and migration transaction - -Git locations use the legacy `SourceDeclaration` identity normalization described -under Construction vocabulary, including single-label hosts and SCP-style SSH -locations. Local paths remain paths. Migration and the JSON-to-IR compatibility -path canonicalize requirement values identically to Swift lowering. A legacy -`from`/`to` pair may therefore print as `from:` or a minor-range factory. This -preserves the selected tag set and every exact ledger pin. - -The same validated JSON, language version and compatibility transformations -produce identical source bytes and diagnostic records. Emit the version line, -import, one blank line, then `let agents = Agents(...)`; two-space indentation, -LF, no BOM and one final newline. Assignment and array concatenation use one -ASCII space on each side of `=` and `+`; negative literals use an adjacent sign -and digits, as in `let value = -1`. Strings use ordinary quotes; escape quotes, -backslashes, LF, CR and tab, and encode other controls as lowercase Swift -`\u{...}`. Preserve other Unicode scalars without normalization. - -Use literal prompts/sections/selections/dictionaries and direct factories. -Omit default-valued arguments, retaining explicit Optional values that distinguish -inheritance. Signature order determines labels. Sort aliases, selection/override -names, prompt names, watch names and recipient IDs by canonical UTF-8 identity; -keep instruction and per-prompt section order. A collection of scalar literals or -payload-free enum members fits inline when the complete line, including indentation -and comma, is at most 80 UTF-8 bytes; otherwise expand it. Collections containing -factory/initializer calls are multiline. A call with only scalar arguments fits -inline under the same limit; calls with collections/nested calls are multiline. -Multiline collections have trailing commas; call arguments have none after the -last argument. Empty collections are `[]` or `[:]`. No formatting pass touches -an already migrated manifest. - -One transaction creates `Agents.swift`, upgrades an existing ledger as needed and -removes `agents.json`. Creation uses the -[no-replace protocol](../Architecture/State.md#publication-and-concurrent-writers). -Existing native files, cache content and watch-state bytes do not change. A missing ledger stays -missing. Repeating migration after success is unchanged. Both declaration files -present is a conflict; Swift source with a version-1 lock permits a lock-only -migration. Normal commands report required migration rather than converting -implicitly. A failed migration retains a recoverable original declaration and -never treats a concurrent file as generated output. +The product reads and writes only `Agents.swift`. It does not read, recognize +or convert the earlier JSON declaration; existing repository and user scopes are +converted once outside the product at release. A scope with a lock or watch state +and no `Agents.swift` reports the missing declaration +([absent declaration](../Architecture/State.md#absent-declaration)). ### Requirement persistence and comparison -Canonicalization applies to new IR and new serialized requirement fields. -Semantic comparison of existing range requirements expands them to bounds; -raw enum-case equality or raw requirement JSON equality is insufficient. Branch -and revision compare their strings; exact versions compare normalized full -versions; absence retains its distinct latest-tag/default-branch policy. - -| Site | Contract | -| --- | --- | -| Declaration IR, JSON compatibility projection and dump | Canonical requirement kinds and normalized version strings; comparisons use range-value equality. A factory, literal range and legacy JSON denoting equal bounds compare equal. | -| Document edits and `upsertSource` | Compare semantic values; an equal edit returns original source bytes. New or changed nodes print canonically; untouched spelling is retained. | -| `LockedSource.requirement` in the deployment ledger and requirements in `groupResolutions` | Newly written records use canonical requirements. Reading existing records preserves their bytes and builds a semantic comparison view. A requirement-spelling difference alone never changes pins, reports an update or stages a write. | -| Lock version 1 to version 2 conversion | Canonicalize requirements while preserving exact source/item pins and ownership. An existing version-2 ledger is not upgraded merely to canonicalize requirements. | -| Skill/instruction lock producers, combined update-plan conflict and change detection | Compare source identity, discovery root and semantic requirement values; merge equal ranges without a conflict. If the complete resulting ledger is semantically unchanged, keep its original bytes even when another state file changes. A necessary ledger rewrite emits canonical requirements. | -| Resolution-session reuse and cache descriptors | Key requirement comparisons by semantic value, not case spelling. Cache identity/materialization keys continue to use source identity and exact revision/artifact digest; restore uses the stored pins without requirement re-resolution. | -| `agents.watch` | Stores source identities and `seen` revision/artifact digests, no requirement kind. Migration retains its bytes. Re-evaluating an equivalent declaration preserves the subscription and baseline; watch-created lock descriptors follow the ledger rule. | - -These rules extend the existing requirement comparisons in source argument -selection, source resolution sessions and combined update planning. They do not -rewrite historical records on read. State transactions compare semantic state -before choosing any serialization and retain the original ledger bytes on a no-op. +[Requirement comparison](../Architecture/State.md#requirement-comparison) +specifies semantic requirement comparison across declarations, edits, the +ledger, update planning, resolution sessions and watch state. Lock version 2 +extends it to group resolutions below. ### Lock version 2 and ownership conversion @@ -1582,8 +565,8 @@ files, hash the owned values and retain formatting-sensitive patch preconditions unmanaged keys are not claimed. Local approval dispositions are observations, not transferable authorization. -Migration derives ownership only from existing install/target records. Shared -skill destinations coalesce only when mode, content and ownership agree. +Lock conversion derives ownership only from existing install/target records. +Shared skill destinations coalesce only when mode, content and ownership agree. Instruction records preserve these separate removal rules exactly: | Existing instruction record | Version-2 ownership and removal | @@ -1591,12 +574,12 @@ Instruction records preserve these separate removal rules exactly: | Generated unit target (`import == nil`) | Whole generated rendering, governed by `blockHash`. When obsolete, delete the file if its current bytes hash to `blockHash`; preserve drifted bytes. Its existing `created: false` does not prevent deletion. | | Forwarding/import target (`import != nil`) | Managed import block with its marker/hash and the existing `created` flag. Remove the managed block; delete the whole file only when `created` is true and no custom content remains. Otherwise preserve the remaining file. | -Heading offsets, import markers, block hashes and creation provenance retain their -meanings. Missing targets remain missing; drifted targets retain expected hashes, -not hashes of adopted bytes. Migration does not scan and claim unmanaged native -files. Source-alias renaming changes no normalized ledger identity. No generated -unit is reclassified as a non-deletable custom file, and no forwarding file gains -whole-file ownership from a unit-target rule. +Heading offsets, import markers, block hashes and creation provenance retain +their meanings. Missing targets remain missing; drifted targets retain expected +hashes, not hashes of adopted bytes. Lock conversion does not scan and claim +unmanaged native files. No generated unit is reclassified as a non-deletable +custom file, and no forwarding file gains whole-file ownership from a +unit-target rule. Lock conversion is deterministic for the same old lock and explicit registered layout. An already-version-2 ledger remains byte-identical when unchanged. @@ -1604,94 +587,22 @@ Restoration must address the same original pins and physical targets after conversion, and removing the last instruction must produce the same deletion or preservation result as before conversion. +Lock conversion canonicalizes requirements while preserving exact source and +item pins and ownership; an existing version-2 ledger is not upgraded merely to +canonicalize requirements. Requirements in `groupResolutions` follow the +[ledger rule](../Architecture/State.md#requirement-comparison): newly written +records are canonical, existing records keep their bytes, and comparison is +semantic. + ## Validation Contract -Every Swift code block, including interface and editor-API blocks, must pass -`swiftc -parse`; signature-only interface blocks use `swiftc -frontend -parse` -with `.swiftinterface` inputs so getter declarations are parsed in interface mode. -Positive fixtures compile against `AgentsDescription` and their -compiled values match static evaluation under plain value equality, including -equal range forms and string-literal group references. Compiler-required literal conformances and evaluator -registrations are checked against the same signature inventory. Negative fixtures -cover unsupported syntax, contextual typing, duplicate dictionary keys, budgets -and spans. No accepted static value may fail real Swift type checking. - -Adversarial tests run every input in a subprocess with a parent watchdog and -assert normal completion without signals, crashes or unbounded memory growth. -Fixed regressions include balanced/unbalanced square nests, mixed square/call -nests, dictionaries, nested shorthand calls and parentheses, brace nests, generic -types `A>`, ambiguous `a Condition +} + +public struct Agents: Sendable, Equatable { + public init( + defaultAgents: [Agent]? = nil, exports: [String] = [], sources: [Source] = [], + components: [Component] = [], groups: [ComponentGroup] = [], + uses: [GroupReference] = [], watch: [String] = [] + ) +} + +public struct Version: Sendable, Comparable, ExpressibleByStringLiteral { + public init(stringLiteral value: String) + public static func == (lhs: Version, rhs: Version) -> Bool + public static func < (lhs: Version, rhs: Version) -> Bool +} + +extension Range where Bound == Version { + public static func upToNextMajor(from version: Version) -> Range + public static func upToNextMinor(from version: Version) -> Range +} + +public struct Source: Sendable, Equatable { + public static func source( + name: String, url: String, subpath: String? = nil + ) -> Source + public static func source( + name: String, url: String, from: Version, subpath: String? = nil + ) -> Source + public static func source( + name: String, url: String, exact: Version, subpath: String? = nil + ) -> Source + public static func source( + name: String, url: String, branch: String, subpath: String? = nil + ) -> Source + public static func source( + name: String, url: String, revision: String, subpath: String? = nil + ) -> Source + public static func source( + name: String, url: String, _ range: Range, subpath: String? = nil + ) -> Source + public static func source( + name: String, path: String, subpath: String? = nil + ) -> Source + public static func source( + name: String, path: String, from: Version, subpath: String? = nil + ) -> Source + public static func source( + name: String, path: String, exact: Version, subpath: String? = nil + ) -> Source + public static func source( + name: String, path: String, branch: String, subpath: String? = nil + ) -> Source + public static func source( + name: String, path: String, revision: String, subpath: String? = nil + ) -> Source + public static func source( + name: String, path: String, _ range: Range, subpath: String? = nil + ) -> Source + public static func source(name: String, index: String, subpath: String? = nil) -> Source +} + +public struct ComponentGroup: Sendable, Equatable { + public static func group( + name: String, components: [Component] = [], uses: [GroupReference] = [], + condition: Condition? = nil + ) -> ComponentGroup +} +public struct GroupReference: Sendable, Equatable, ExpressibleByStringLiteral { + public init(stringLiteral value: String) + public static func group(name: String, condition: Condition? = nil) -> GroupReference + public static func group( + name: String, source: String, condition: Condition? = nil + ) -> GroupReference +} +``` + +There is one `let agents = Agents(...)`, optionally annotated `: Agents`. +Other constants contain reusable values. Source names are lexical aliases, not +output paths. A **discovery root** is the source root with its optional safe +`subpath` applied; component and export discovery start there. Core owns source +identity normalization and requirement resolution. + +`Version` uses core's semantic-version validation and precedence. A requirement +is a value: `from: x` and `.upToNextMajor(from: x)` denote +`x ..< (major + 1).0.0`; `.upToNextMinor(from: x)` denotes +`x ..< major.(minor + 1).0`. The upper bounds have no prerelease or build metadata, +even when the lower bound has either. The lower bound retains its prerelease and +metadata. All range forms use the resolver's `isInRange(from:to:)`: build metadata +does not affect precedence, and a prerelease tag additionally needs a bound with +a prerelease and the same major/minor/patch triple. Exact requirements retain +core's full normalized-version matching, including build metadata. + +Lowering canonicalizes the `Range` value. An upper bound equal by SemVer +precedence to `(major + 1).0.0` becomes `SourceRequirement.upToNextMajor`; one +equal to `major.(minor + 1).0` becomes `upToNextMinor`; any other upper bound +becomes `SourceRequirement.range(from:to:)`. The two canonical upper bounds +never coincide. Version strings use core's +normalized description; range equality compares bounds by SemVer precedence, +while exact-version equality includes metadata. Invalid versions, non-increasing +ranges and successor overflow are located `manifest.domain` errors. Candidate +successor bounds are computed with checked arithmetic; a literal range does not +fail merely because a nonmatching candidate successor would overflow. + +The canonical printer uses `from:` for a major range, +`.upToNextMinor(from:)` for a minor range and adjacent `"lower"..<"upper"` for +other half-open ranges. `exact:`, `branch:` and `revision:` retain their meanings. +Default latest-tag/default-branch selection remains core's rule. Requirements +apply to Git URL sources and Git-backed local paths only. `.source(name:index:)` +represents the well-known index kind and has no Git requirement. +`path:` locates a resource inside a named source or supplies a local source +location; `subpath:` narrows the source's own discovery root. + +Source aliases are nonempty, colon-free strings, with `.` reserved for the +declaring package. Escapes preserve otherwise valid string +contents. Two aliases for one normalized source identity in a document are errors. +Group and newly introduced named component identifiers are relative slash-separated +names with no empty, `.` or `..` segment, colon, backslash or control character. +Skill and instruction names retain their domain validators. ChatGPT prompt names +use an arbitrary string-key namespace; they are not filesystem paths. +Names must be unique in their respective namespace. + +Git URLs are complete transport URLs, as in SwiftPM. A hand-written shorthand is +admitted with `SourceDeclaration` normalization and a `manifest.domain` warning +whose fix-it is the complete URL: `intranet/team` means `https://intranet/team`, +preserving the host; it is not the CLI's owner/repository shorthand. The editor +and canonical printer emit complete URLs using `SourceDeclaration.gitURL`: add `https://` +to host/repository shorthand, preserve existing schemes and preserve complete +SCP-style URLs such as `user@host:path`. Preserving SCP transport syntax also +preserves its remote path interpretation. Identity normalization lowercases the +host, retains an explicit port, trims path slashes and removes a terminal `.git`; +printing preserves the repository suffix. + +`exports: ["review"]` exports the group named `review`; export name and group name +are identical. A differently named wrapper group provides a renamed export. +`watch` is a unique array of declared source aliases, with no recipient or condition. Observed +baselines remain in `agents.watch`, not the manifest. Neither exports nor unused +groups cause deployment or subscriptions in a consumer. + +### Literal values and supporting types + +```swift +public struct SkillSelection: Sendable, Equatable, ExpressibleByArrayLiteral { + public static var all: SkillSelection { get } + public init(arrayLiteral elements: String...) +} +public struct SkillOverride: Sendable, Equatable { + public static func skill(name: String, mode: InstallMode? = nil, agents: [Agent]? = nil) -> SkillOverride +} +public struct SectionReference: Sendable, Equatable, ExpressibleByStringLiteral { + public init(stringLiteral value: String) + public static func section( + name: String, source: String? = nil, condition: Condition? = nil + ) -> SectionReference +} +public struct ChatGPTPrompt: Sendable, Equatable { + public static func prompt( + name: String, sections: [SectionReference], append: String? = nil, + condition: Condition? = nil + ) -> ChatGPTPrompt +} +public struct Resource: Sendable, Equatable { + public static func path(_ path: String, source: String? = nil) -> Resource +} +public struct PromptContent: Sendable, Equatable, ExpressibleByStringLiteral { + public init(stringLiteral value: String) + public static func file(_ path: String, source: String? = nil) -> PromptContent +} +public enum RuntimeValue: Sendable, Equatable, ExpressibleByStringLiteral { + case literal(String) + case environment(String) + case secret(String) + public init(stringLiteral value: String) +} +public struct ExecutableInvocation: Sendable, Equatable { + public static func executable( + _ executable: String, arguments: [String] = [], + environment: [String: RuntimeValue] = [:], workingDirectory: Resource? = nil + ) -> ExecutableInvocation +} +public indirect enum ConfigurationValue: Sendable, Equatable, + ExpressibleByStringLiteral, ExpressibleByIntegerLiteral, + ExpressibleByBooleanLiteral, ExpressibleByNilLiteral, + ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral +{ + case string(String) + case integer(Int) + case decimal(String) + case boolean(Bool) + case null + case array([ConfigurationValue]) + case object([String: ConfigurationValue]) + public init(stringLiteral value: String) + public init(integerLiteral value: Int) + public init(booleanLiteral value: Bool) + public init(nilLiteral: ()) + public init(arrayLiteral elements: ConfigurationValue...) + public init(dictionaryLiteral elements: (String, ConfigurationValue)...) +} +public typealias NativeConfiguration = [String: [String: ConfigurationValue]] + +public struct MCPTransport: Sendable, Equatable { + public static func stdio( + _ executable: String, arguments: [String] = [], + environment: [String: RuntimeValue] = [:], workingDirectory: Resource? = nil + ) -> MCPTransport + public static func streamableHTTP( + url: String, headers: [String: RuntimeValue] = [:] + ) -> MCPTransport + public static func sse(url: String, headers: [String: RuntimeValue] = [:]) -> MCPTransport +} +public enum HookEvent: Sendable, Equatable { + case beforeTool, afterTool, sessionStart, sessionEnd + case native(String) +} +public struct PromptParameter: Sendable, Equatable { + public static func parameter(name: String, description: String, defaultValue: String? = nil) -> PromptParameter +} +public enum PermissionOperation: Sendable, Equatable { + case read, write, execute + case tool(String) +} +public struct PermissionRule: Sendable, Equatable { + public static func allow(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule + public static func ask(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule + public static func deny(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule +} +public enum IgnorePurpose: Sendable, Equatable { case context, indexing } +public enum PluginMode: Sendable, Equatable { case native, components } +public enum ComponentKind: Sendable, Equatable { + case skills, instructions, mcpServer, hook, subagent, command + case lspServer, permissions, ignore, plugin +} +public enum ComponentReference: Sendable, Equatable { + case skill(name: String) + case instruction(name: String) + case mcpServer(name: String) + case hook(name: String) + case subagent(name: String) + case command(name: String) + case lspServer(name: String) + case permissions(name: String) + case ignore(name: String) + case plugin(name: String) +} +``` + +Literal conversions are closed and contextual. `PromptContent`, +`SectionReference`, `GroupReference`, `Version` and `RuntimeValue` accept string literals; `SkillSelection` +accepts string array literals. `ConfigurationValue` accepts strings, signed +64-bit integer literals, booleans, `nil`, arrays and string-keyed dictionaries. +Decimals use `.decimal("1.25")`, with finite JSON-number text; floating-point +literals are outside the grammar. Native configuration is a dictionary keyed +by registry schema ID, with a string-keyed configuration object as each value. +Duplicate decoded keys, compared using Swift String equality including canonical +Unicode equivalence, are domain errors at every dictionary level, even if their +values are equal. There is no user-defined literal conformance or conversion +from an already-typed `String`, `[String]` or dictionary to a wrapper type. + +A bare section string names the declaring package's own instruction section; +`.section(name: "engineering", source: "rules")` names a source section, and +source `"."` names an own section. A root user-scope declaration uses named +instruction sources. Ordered sections, Markdown rendering and **front matter** +(the structured metadata preceding a content file's body) retain their +instruction-domain semantics. ChatGPT is a named prompt rendering destination, +not an `Agent`. Prompt `append` paths are relative to the project root in project +scope and to the runtime home in user scope. + +Omitted mode inherits the selection mode, then `.link`. Link and copy modes +preserve independent item pins. Omitted skill selection means all discovered +members; `[]` selects none. Exclusions win; overrides do not re-add excluded items. +An override outside an explicit selection is a `manifest.domain` error. +An all-member selection can retain overrides for members not yet discovered. + +`path` locates a resource inside the declaring package or a named source +discovery root; `subpath` narrows the source's own root before discovery. Resource +paths are safe relative paths. Project package roots are project directories; a +user package root is its user-state directory. Absolute and home-relative +resource paths, traversal and escaping symlinks are errors. Source locations keep +their absolute and home-relative path support. Executables are fixed program +names or package-relative executable paths, with separate argument arrays. +Environment and secret bindings are symbolic: reading and dumping never resolve +their values. + +### Component factories + +```swift +public struct Component: Sendable, Equatable { + public static func skills( + source: String, select: SkillSelection = .all, exclude: [String] = [], + mode: InstallMode? = nil, overrides: [SkillOverride] = [], + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func instructions( + sections: [SectionReference] = [], chatGPT: [ChatGPTPrompt] = [], + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func mcpServer( + name: String, transport: MCPTransport, + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func hook( + name: String, event: HookEvent, run: ExecutableInvocation, + matcher: String? = nil, timeoutSeconds: Int? = nil, + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func subagent( + name: String, description: String, prompt: PromptContent, + model: String? = nil, tools: [String]? = nil, + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func command( + name: String, description: String, prompt: PromptContent, + parameters: [PromptParameter] = [], + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func lspServer( + name: String, run: ExecutableInvocation, languages: [String: String], + initializationOptions: [String: ConfigurationValue] = [:], + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func permissions( + name: String, rules: [PermissionRule], + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func ignore( + name: String, patterns: [String], purpose: IgnorePurpose = .context, + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component + public static func plugin( + name: String, path: String, source: String, + mode: PluginMode = .components, select: [ComponentKind]? = nil, + exclude: [ComponentReference] = [], + agents: [Agent]? = nil, condition: Condition? = nil, + native: NativeConfiguration = [:] + ) -> Component +} +``` + +### Domain rules + +Domain validation runs offline over every evaluated value, including unused +constants, inactive values and unused groups. A failure is a located +`manifest.domain` error unless the table names another code. + +| Value | Checks | +| --- | --- | +| Sources | Aliases are unique, nonempty, colon-free and not `.`. Git URLs and index URLs must yield a transport identity; a local path is nonempty and has no NUL. `branch:` and `revision:` values are nonempty, have no NUL and do not start with `-`. `subpath` is a safe relative path. Two aliases with one normalized identity are an error; a Git shorthand is a warning with the complete-URL fix-it. | +| Root fields | `defaultAgents` and each condition dimension have no duplicate members. Group names, `exports` and `watch` are unique. An export names a local group (`manifest.group.missing`); a watch entry names a declared alias. | +| Names | Group, named-component and typed component-reference names are relative names as defined above. Skill and instruction section names use their domain validators. Prompt names are unique within a component; prompt parameter names are nonempty and contain no `}`, `:` or NUL. | +| Skills | The source is a declared alias or `.`. Explicit selections and exclusions are valid, unique skill names; override names are unique and lie inside an explicit selection. Edit mode, on the selection or an override, requires a local source without a requirement. | +| Resources | Resource, prompt file, `append` and `subpath` paths are safe relative paths. An executable containing `/` or starting with `~` is also a resource path. | +| Transports | Streamable HTTP and SSE URLs are HTTP(S) URLs with a host and no credentials or fragment. | +| Hooks | `timeoutSeconds` is positive. A `.native` event has exactly one explicit recipient. | +| Commands | Every `${input:name}` token in a literal prompt names a declared parameter; `$${input:` escapes a token. | +| LSP servers | Each `languages` key is a dot-prefixed file extension without `/`; each language ID is nonempty. | +| Permissions | Read and write patterns are safe relative paths. | +| Plugins | The source is declared and `path` is a safe relative path. Native mode has exactly one explicit recipient and no selection or exclusions. Selections and exclusions have no duplicates. | +| Configuration values | `.decimal` text is a finite JSON number. Duplicate decoded keys at any dictionary level are `manifest.dictionary.duplicateKey`. | + +Recipient capabilities, native schema registration, executable approval and +adapter rules are deployment checks; the +[manifest proposal](../Proposals/AgentsManifest.md#component-deployment) specifies +them. + +## Source Files and Versions + +Project source is `.agent/Agents.swift` relative to the explicit project root; +user source is `~/.agents/Agents.swift` relative to core's runtime home. Each +scope's lock is the adjacent `agents.resolved`. There is no ancestor search or +automatic user/project merge. An absent file is an absent declaration; +[State](../Architecture/State.md#absent-declaration) defines how that combines +with existing lock or watch state. + +The first line is exactly `// agents-tools-version: 1.0`, at byte zero after an +optional UTF-8 BOM, terminated by LF, CRLF or EOF. General version syntax is +`// agents-tools-version: MAJOR.MINOR`, with the shown spaces, decimal components +without leading zeroes except `0`, and no patch, suffix or trailing whitespace. +A missing, malformed, duplicate or unsupported directive has its own diagnostic. +Directive recognition is lexical: a directive-shaped line comment outside a +string is a duplicate; text inside a string literal is ordinary content. +A 1.0 reader accepts exactly `1.0`. A future reader explicitly declares its support +set. Newer unsupported versions request an upgrade; older unsupported versions +request a supported converter. Language, package, adapter, lock and dump versions +are independent. Editing preserves the BOM and newline style; the canonical +printer emits UTF-8 without a BOM. + +## Static Grammar + +Exactly one unqualified `import AgentsDescription` precedes top-level initialized, +single-binding `let` declarations. Names use the identifier grammar below, are +unique and cannot shadow vocabulary types. Constants bind in textual order; references to later constants +or themselves fail. There are no modifiers, attributes, wrappers or semicolons. +Every declaration, including unused constants and inactive branches, is checked. +Group-name references are resolved separately and may refer forward. + +| Accepted syntax | Rule | +| --- | --- | +| `SourceFileSyntax`, `ImportDeclSyntax`, `VariableDeclSyntax` | The file structure above, with one identifier-pattern binding and initializer per declaration. | +| `StringLiteralExprSyntax` | Single-line and multiline literals from the closed lexical grammar below, with Swift decoding and no interpolation. Contextual `GroupReference` literals denote local groups; this is a type conversion, not an extra grammar production. | +| Integer, Boolean and nil literals | Decimal signed-64 integers with underscore separators, Bool and contextual nil. One unary minus is accepted only immediately adjacent to a decimal integer literal, with no intervening trivia. Other bases, floating literals and other numeric operators fail admission. | +| `ArrayExprSyntax` | Homogeneous arrays or a contextual, whitelisted array-literal conversion. Trailing commas are allowed. Empty literals require contextual type. | +| `DictionaryExprSyntax` | String-literal keys, homogeneous contextual values, or a contextual configuration object. `[:]` is an empty dictionary. Keys are decoded before duplicate detection; key references/interpolation are rejected. | +| `DeclReferenceExprSyntax` | A preceding constant, a vocabulary type as a member/call base, or the permitted operator. | +| Sequence/folded infix expressions | Only left-associative array `+` with exact `[T]` operands, at most 32 terms per additive chain. No concatenation of selections or configuration values, dictionary merging or string concatenation. A single half-open version range is admitted only in the source requirement position defined below; other operators are rejected. | +| `TupleExprSyntax` | One unlabeled expression in parentheses, not tuple values. | +| `MemberAccessExprSyntax` | Listed static factories, static `.all`, and enum cases, qualified or contextual. No instance-property access, subscripts or optional chaining. | +| `FunctionCallExprSyntax` | `Agents(...)`, listed static factories and associated cases, with exact labels and order. Literal-protocol entry points are reached only through literals. No arbitrary functions or trailing closures. | +| Type annotations | `String`, `Int`, `Bool`, named vocabulary types/aliases, `[T]` and `[String: T]`. No explicit Optional annotations, user aliases, qualified/generic/existential/function/metatype syntax. | + +Grammar admission precedes SwiftParser and the iterative tree check precedes all +recursive SwiftSyntax processing. The normative productions below and the syntax +node table describe the same constructs, subject to the byte, token, chain and +depth limits below. These limits apply even to unused or inactive +expressions. Parser recovery, missing tokens and unexpected syntax are errors. +Tokens inside accepted nodes are admitted only in the roles above. Constructors create data; +they never invoke Swift compiler code while evaluating a manifest. + +### Type inference and literal conversions + +An annotation or parameter type supplies context inward. Otherwise literals, +qualified calls and references synthesize types outward. Without context, a +string is `String`, an integer is `Int`, and a boolean is `Bool`. Arrays infer +from the first element; dictionaries infer from the first value and require all +other values to agree. Empty collections, nil and a leading shorthand member +cannot infer a type alone. Dictionary keys are always strings. + +Optional parameter types remain part of the construction API: their context +admits `nil` or injection of a value of the wrapped type. Source annotations use +the non-Optional forms in the grammar; `T?` and `Optional` fail grammar admission. +This does not change the module's public Optional signatures or compiler typing. + +In contextual vocabulary types, only the literal conformances declared above +apply. Nested configuration literals propagate `ConfigurationValue` context to +every child. For an Optional parameter with wrapped type `T`, nil means absence; +non-nil values may receive `T` context and Optional injection. For non-Optional `ConfigurationValue`, nil means +configuration null. Signed integer literal conversion follows Swift's literal +semantics and must fit the declared literal type. `.decimal(...)` remains explicit. +No arbitrary user protocol dispatch or conversion of pre-existing typed values +is allowed. In particular, a `String` constant is not implicitly a `PromptContent` +or a `SectionReference`, `GroupReference` or `Version`, and a `[String]` constant is not a `SkillSelection`. + +For array `+`, context propagates to both operands when present; otherwise infer +the left array and use its element type for the right array. An expression of +`SkillSelection` or `ConfigurationValue` type is not a Swift array. Constants +must be typed where declared, not inferred backward from later uses. A standalone +component is `let reviewer: Component = .subagent(...)` or a fully qualified +factory call. The evaluator's accepted language is a subset of real Swift typing, +not an alternative type system. + +### Normative admission grammar + +`AgentsManifest` owns a strict lexer and a deterministic recognizer for these +productions. No byte reaches SwiftParser until the complete input snapshot passes +recognition. SwiftParser supplies the lossless tree for editing and diagnostics; +it does not decide which source grammar is admitted. The recognizer does not +resolve constants or evaluate constructors. The subsequent type/domain checks +restrict identifiers and calls to the vocabulary and rules above. + +The grammar uses `?` for optional, `*` for repetition and `|` for alternatives; +quoted punctuation denotes source tokens. Trivia may separate tokens except at +explicitly contiguous spellings. `newline` means at least one LF, CRLF or CR in +the separating trivia. The version directive is checked as specified above using +the same lexer's comment/string boundaries, before syntax is handed to SwiftParser. + +```ebnf +document = "import" "AgentsDescription" newline declaration + (newline declaration)* EOF ; +declaration = "let" bareName (":" type)? "=" expression ; +type = typeName | "[" type "]" | "[" "String" ":" type "]" ; +expression = primary ("+" primary)* ; +primary = string | integer | "-" integer | "true" | "false" | "nil" + | namedValue | array | dictionary | "(" expression ")" ; +namedValue = sourceCall | callee ("(" arguments? ")")? ; +callee = bareName | bareName "." name | "." name ; +arguments = argument ("," argument)* ; +argument = (name ":")? expression ; +sourceCall = (".source" | "Source.source") "(" "name" ":" expression "," + (("url" | "path") ":" expression + ("," requirement)? | "index" ":" expression) + ("," "subpath" ":" expression)? ")" ; +requirement = ("from" | "exact" | "branch" | "revision") ":" expression + | versionRange | rangeFactory ; +versionRange = string "..<" string ; +rangeFactory = (".upToNextMajor" | ".upToNextMinor") + "(" "from" ":" expression ")" ; +array = "[" (expression ("," expression)* ","?)? "]" ; +dictionary = "[" ":" "]" + | "[" string ":" expression + ("," string ":" expression)* ","? "]" ; +``` + +`typeName` is exactly `String`, `Int`, `Bool`, or a public vocabulary type/alias +listed under Construction vocabulary. Type existence is checked during recognition. `sourceCall` takes +precedence over the general call production for `.source` and `Source.source`; those spellings cannot bypass it through `callee`. The +`.upToNextMajor` and `.upToNextMinor` callees are reserved to `rangeFactory`, +including its required argument list; other positions fail recognition. +`versionRange` is not a general expression: no grouping, constants, chaining or +other operands are admitted at its position. A range factory is contextual to +this same unlabeled requirement slot. Its argument receives `Version` context; +`from:` and `exact:` on the source also receive `Version` context. The subsequent +checker enforces version typing and domain validation. `callee` is a +syntactic spelling; subsequent vocabulary checking rejects unlisted functions, +instance members, literal-protocol entry points and invalid factory labels. +There is no postfix loop: a callee has at most one member operation and one call, +for a maximum grammatical chain of **2**. The independent postfix-operation +counter has a ceiling of **4** per primary; budget headroom admits no additional +production. No operation attaches to a call result, grouped +expression or subscript. The leading shorthand dot counts as one operation. +These are exactly the construction forms needed by the vocabulary. Parentheses +contain one expression; calls have no trailing comma; collections may have one. +The additive production has at most **32 terms**, with later type checking +requiring array operands. A version range has exactly two literal operands. +No assignment expression or prefix-keyword production exists. An identifier after a completed expression is a syntax error, not an +implicit prefix, argument or declaration. + +The lexical grammar is closed: + +- An identifier has ASCII head `[A-Za-z_]` and continuation `[A-Za-z_0-9]*`. + Backticks, `$` names and non-ASCII identifiers are excluded; Unicode remains + available in string values, including all domain names and paths. `name` excludes + the reserved spellings listed below. `bareName` additionally excludes `await`, + `copy`, `consume`, `each` and `unsafe`; those contextual spellings may occur as + argument labels or member names, including `.copy`. They cannot introduce a + prefix production or a bare binding/reference/callee in language 1.0. +- `integer` is `[0-9][0-9_]*`. The optional minus is a separate token immediately + adjacent to its digits and only in the shown primary production. Its preceding + source character must be ASCII whitespace (space, tab, CR or LF), `(`, `[`, `,` + or `:`; an adjacent operator or comment terminator cannot precede the sign. + Range checking follows during typing. There are no floating-point, exponent or + radix literals; + decimal configuration values use `.decimal("1.25")`. +- `string` is an ordinary double-quoted single-line literal or a triple-quoted + multiline literal. Both allow exactly `\0`, `\\`, `\t`, `\n`, `\r`, `\"`, `\'` + and `\u{H}` escapes, where `H` is one to eight ASCII hex digits naming a Unicode + scalar (not a surrogate and at most `10FFFF`). Interpolation and escaped newline + continuation are excluded. A single-line literal contains no unescaped CR/LF. + A multiline opener is followed immediately by LF, CRLF or CR; its closing + delimiter is preceded on its line only by spaces. A content line is either + empty (zero characters before its newline) or starts with the closing delimiter's + exact space indentation prefix, which Swift decoding removes. Additional leading + spaces remain content. Whitespace-only lines are nonempty and must carry the + full prefix. A tab anywhere in a content line's leading whitespace or in the + closing delimiter's indentation is a syntax error; tabs after the first + non-whitespace content character remain literal content. These rules apply + identically to LF, CRLF and CR lines. Unescaped single/double quote runs are + multiline content; the first + unescaped triple quote closes it. Unescaped control scalars below U+0020 other + than tab and multiline CR/LF are rejected. Raw strings do not exist: `#` outside + string/comment content always fails recognition. +- Trivia is ASCII space, tab, LF, CRLF or CR, an optional BOM at byte zero, `//` + comments through the next CR/LF or EOF, and `/* ... */` comments with at most + **20** nested levels. The lexer validates UTF-8 throughout the snapshot. Strings + and comments are opaque to expression counters. No other whitespace or comment + form is admitted. +- Source punctuation is `( ) [ ] , : . = + ..<` and the adjacent numeric sign `-`, + only in the roles in the productions. Callee member spellings contain no trivia + around their dot; the call opener immediately follows its callee. Both `=` and + binary `+` require at least one ASCII whitespace character (space, tab, CR or LF) + immediately on each side. Comments do not substitute for whitespace: every + comment in an operator-to-operand gap must itself have whitespace immediately + before and after it. Thus `value /* note */ = -1` is admitted, but `value=0`, + `value= 0`, `value=-1`, `a+b` and `a/* note */ + b` fail recognition. A located + `manifest.syntax` diagnostic names the canonical spelling, such as + `let value = -1` or `left + right`. These adjacency rules make + Swift operator/member tokenization unambiguous. The single `..<` token is + admitted only by `versionRange`, with either no whitespace on both sides or + at least one ASCII whitespace character immediately on both sides. Comments + in either operand gap must themselves be surrounded by whitespace, as for `+`. + The canonical operator spelling is `"1.2.0"..<"1.8.0"`; an asymmetric boundary + reports that spelling in a located `manifest.syntax` diagnostic. A lone `<` + or `>` is never admitted. Other operators, generic angle + brackets, braces, attributes, directives, macros and regex literals fail at + recognition. There is no fallback to SwiftParser recovery. + +The exact reserved identifier spellings are: + +```text +_ Any Self as associatedtype break case catch class continue default defer deinit +do else enum extension fallthrough false fileprivate for func guard if import in +init inout internal is let nil open operator precedencegroup private protocol public +repeat rethrows return self static struct subscript super switch throw throws true +try typealias var where while +``` + +The lexer consumes each byte a bounded number of times, without backtracking or +unbounded lookahead. The parser uses at most two tokens of lookahead to distinguish +argument labels and dictionary entries, bounded delimiter frames for nested +productions, and loops for siblings and additive terms. It never speculatively +parses a whole expression and rewinds. Its work, storage, literal validation and +located-diagnostic construction are linear in bounded input size. A failure ends +recognition with a located `manifest.syntax` or `manifest.limit`; SwiftParser is +not called. Accepted grammar structure and spans are retained for differential +validation, independently of the later semantic IR. + +## Resource Limits + +Admission reads at most 2,097,153 bytes, rejecting the extra byte before decoding, +lexing or parsing; it never allocates an unbounded file buffer. The exact admitted +snapshot is subsequently parsed. The recognizer permits at most 100,000 non-trivia +tokens; the minus and integer count separately, and `..<` counts as one token +plus its two string-literal operands. Range factories count as ordinary calls. +Version values charge their decoded bytes and nodes; range costs include both +endpoints before canonical lowering or serialization. It additionally reserves syntax +storage conservatively as **16 + 4 × (tokens + literal breaks + literal escapes)**, +capped at 100,000 nodes before SwiftParser is invoked. A literal break is each +CR or LF byte inside a string (CRLF counts twice); a literal escape is each +backslash byte inside a string, including escaped backslashes. These extra units +cover the parser's segmentation of multiline/escaped literals. The grammar-derived +reservation covers file and wrapper nodes as well as tokens; the independent +post-parse guard verifies actual counts. +A parser dependency change must revalidate the reservation against every grammar +production. The reservation is a language budget even when an individual input's +actual tree would be smaller; generated source passes the same admission. + +Every open `[` or `(` increments a grammar counter before entering the enclosed +production, including type annotations. Square depth above **8** or combined +depth above **20** is `manifest.limit` at the first excess opener. Block-comment +depth above 20, a thirty-third additive term or an excess token/storage reservation +likewise fails before parsing. All other missing, misplaced or unsupported tokens +are `manifest.syntax` at the expected production's location (EOF for missing +input). Unbalanced openers remain counted until rejection; neither trivia nor +parenthesized subexpressions can bypass the counters. No production permits more +than two postfix operations or more than one numeric sign. These grammar bounds +apply equally to unused constants and inactive components. + +Immediately after parsing, an **iterative, non-recursive** walk checks all syntax +nodes, including collections, tokens, missing nodes and unexpected nodes, in the +all-nodes view. The root has depth 1; depth above **128** or more than **100,000** +nodes is `manifest.limit`. Reserve stack/node budget before enqueueing children; +compute failure offsets from cached byte lengths during the walk. Do not call +recursive visitors, `hasError`, diagnostic generation, tree descriptions, source +mapping, equality or evaluation before this guard succeeds. The same rule applies +to transformed/folded trees: build/check them iteratively before recursive use. +The tree ceiling is independent of source delimiter depth and leaves room for +SwiftSyntax's wrapper nodes. Evaluation retains its separate frame/work limits. + +No manifest input within the byte limit may crash or hang the hosting process, +including the GUI. Invalid and over-budget input must end in a bounded diagnostic +without writes or partial IR publication. This is a required implementation and +release invariant, not a conclusion inferred from `maximumNestingLevel` or a +finite set of passing examples. Parser construction, error inspection, tree +lifetime/teardown and every consumer of syntax are included in the invariant. + +The square-bracket ceiling is **8**, independently of the general delimiter +ceiling of **20**. The complete manifest examples in this reference and in the +manifest proposal reach depth 3. Fixed family fields, excluding recursive +configuration values and arbitrary nested array constants, reach depth 5: root +groups, components, ChatGPT prompts, sections, then a section condition's +recipient array. +Eight leaves three levels of syntax-depth margin over that fixed structure. +`ConfigurationValue` is recursive, so its vocabulary has no intrinsic finite +nesting maximum; its expanded values remain limited to depth 64. Named constants +allow deeper configuration values to be assembled without deep source nesting, +subject to all expansion budgets. This separates authoring depth from value depth +and caps square-bracket ambiguity before parser recovery. The parser's own +nesting option remains defense in depth, not a parse-time bound. + +The evaluator may store immutable values as a DAG, but all limits are measured +as if each reference were expanded by value. Each value carries a checked cost +summary: expanded node count, decoded string/key bytes, canonical encoded byte +count, maximum depth and source-origin count. For a container, costs are its own +cost plus the sum of each child's costs **for every occurrence**. Reusing a +constant twice adds its full cost twice, including all descendants. An alias +inherits the referenced cost; memoization does not discount expansion. + +Compute costs bottom-up with checked, saturating arithmetic capped at the limit +plus one. Before concatenation, reference insertion, group expansion or any output +allocation, combine the summaries and reject an oversized result. No descendant +walk, copying, formatting, map expansion or equality comparison occurs first. +This rejects exponential reuse such as repeated `array([previous, previous])` +while that value is constructed, even when its underlying storage is small. +Every constant must fit individually; totals count every top-level definition +and every root occurrence, including inactive and unused values. + +Encoded-size summaries include repeated dictionary keys, string escaping, +punctuation, indentation and trailing newline. Before writing a dump or generated +source, reserve its complete bounded size from those summaries. When formatting +context changes indentation, use a checked worst-case bound or recompute the +summary over the bounded structure before emitting bytes. Locations and provenance +are separately budgeted and included in the final dump's size reservation. + +| Resource | Language 1.0 bound | +| --- | --- | +| Input | 2,097,152 UTF-8 bytes per manifest, enforced by bounded reading before grammar admission, decoding or parsing; invalid UTF-8 fails. | +| Admission | Linear lexer and grammar recognizer; 100,000 tokens; syntax reservation `16 + 4 × (tokens + literal breaks + literal escapes) ≤ 100,000`; square depth 8; combined square/parenthesis depth 20; comment depth 20; postfix-operation budget 4 (the grammar uses at most 2); one adjacent numeric sign; additive chain 32 terms. Failures reject before SwiftParser. | +| Parser/tree | `maximumNestingLevel: 20` in every build configuration. Iterative guard: depth 128 (root 1), 100,000 syntax nodes including tokens and excluding trivia, before any recursive processing. | +| Evaluator | 64 active expression/reference frames; 100,000 work steps per document. Every visited expression, lookup, produced node and concatenation element costs a step. | +| Expanded values | 100,000 nodes and 16,777,216 decoded string/key bytes across the document's values, charged by occurrence, with 10,000 entries per array/dictionary and maximum expanded value depth 64, including referenced descendants. | +| Domain validation | 100,000 traversal steps per document. | +| Local groups | 64 active local group references while checking for reference cycles. | +| Source maps | 100,000 location records, 1,000,000 total origin spans and 16,777,216 encoded bytes; repeated origins count repeatedly. Reserve before expanding a reference's map. | +| Output | 33,554,432 bytes for the entire dump including locations/diagnostics; generated manifest source still obeys the 2,097,152-byte input limit. | +| Comparison/edit batch | 200,000 expanded node-pair visits per full comparison; 1,000,000 aggregate steps and 100 requests per edit batch. Operand cost summaries are checked before comparison starts. | + +A work budget is charged before executing a step; exhaustion is a diagnostic, +not an invitation to return a truncated model. Comparisons can use identity or +memoization only after verifying expanded operand bounds. Diagnostics and JSON +escaping are bounded operations. Source download and extraction limits belong to +core's loader. Cancellation is separate from language semantics. Fuzzing and adversarial reuse tests cover every bounded +consumer of values, not just the parser. + +## Group References + +Group references are symbolic in the front end: no group is expanded and no +source manifest is read. The front end checks the local graph only: + +- group names are unique, including unused groups; +- every export and every unqualified `GroupReference` names a local group, or + fails with `manifest.group.missing`; +- following unqualified references from every group, a reference back into the + active chain fails with `manifest.group.cycle`, whose related spans list the + chain; a diamond is not a cycle; +- an active chain longer than the local group budget is `manifest.limit`. + +A qualified `.group(name:source:)` reference names a declared source alias; its +group is resolved only by source linking. Group references may refer forward to +groups declared later in the same document. + +## Document Editing + +`AgentsManifest.DeclarationDocument` owns the original bytes, syntax, declaration +IR, source map, diagnostics, editability and the original byte digest. Domain +edits use the same vocabulary names as authored values; lowering converts them to +core IR. Snapshot node handles are separate from persistent component identities. + +```swift +public struct DeclarationDocument: Sendable { + public init(bytes: [UInt8], identity: DocumentIdentity) throws + public let declaration: DeclarationIR + public let diagnostics: [ManifestDiagnostic] + public let sourceMap: DeclarationSourceMap + public let digest: String + public var bytes: [UInt8] { get } + public func node(at pointer: String) -> NodeID? + public func constant(named name: String) -> NodeID? + public func uses(ofConstant name: String) -> [NodeID] + public func editability(of node: NodeID) -> Editability + public func preparing(_ edits: [ManifestEdit]) throws -> DocumentChange +} +public enum Editability: Sendable, Equatable { + case direct + case sharedConstant(uses: [NodeID]) + case readOnly(reason: String) +} +public enum ManifestEdit: Sendable { + case setDefaultAgents([Agent]?) + case upsertSource(Source) + case removeSource(alias: String) + case insertComponent(Component, into: ContainerID, at: InsertionPosition) + case replaceComponent(NodeID, with: Component) + case removeComponent(NodeID) + case moveComponent(NodeID, into: ContainerID, at: InsertionPosition) + case setSkillSelection(NodeID, SkillSelection) + case upsertSkillOverride(NodeID, SkillOverride) + case removeSkillOverride(NodeID, name: String) + case insertSection(SectionReference, into: NodeID, at: InsertionPosition) + case removeSection(NodeID) + case moveSection(NodeID, at: InsertionPosition) + case upsertPrompt(NodeID, ChatGPTPrompt) + case removePrompt(NodeID, name: String) + case upsertGroup(ComponentGroup) + case removeGroup(name: String) + case insertGroupReference(GroupReference, into: ContainerID, at: InsertionPosition) + case removeGroupReference(NodeID) + case setExports([String]) + case setWatch([String]) + case setDictionaryEntry(NodeID, key: String, value: StaticValue) + case removeDictionaryEntry(NodeID, key: String) + case replaceConstant(NodeID, with: StaticValue, acceptingUses: [NodeID]) +} +``` + +`NodeID` is an opaque handle bound to the document digest; `node(at:)` takes a +JSON Pointer into the lowered declaration, and `constant(named:)` and +`uses(ofConstant:)` take Swift identifiers. `ContainerID` addresses the root or a +group. `InsertionPosition` is `.first`, `.last`, `.before(NodeID)` or +`.after(NodeID)`. `StaticValue` is the bounded checked algebra of literals, +collections and vocabulary values, not raw Swift text. Dictionary value edits +must match the target's inferred value type. Whole-component replacement covers +recipients, conditions and all family-specific fields. + +The document applies requests in order to construct the expected complete IR, +checks their complete impact and budgets, and produces disjoint byte patches. +`DocumentChange` contains the original digest, patches, resulting bytes and +digest, expected declaration, impacted references, diagnostics and semantic +delta. Only the document layer constructs it, and it publishes nothing. Scope +declarations are written only through the state layer's +[declaration writes](../Architecture/State.md#declaration-writes); front ends +never save source independently. + +### Editability + +`editability(of:)` reports exactly what the editor accepts: + +| Construct | Editability | +| --- | --- | +| Element of a direct array literal | `direct`. Insert, remove and move identifiable elements, preserving order. Removing an element of a single-line array also removes its separating space. | +| Entry of a direct dictionary literal, including a literal configuration value | `direct`. Set or remove a decoded key's value or entry; unrelated entries keep their order and comments. | +| Signature argument of a direct root, group or component construction, present or omitted | `direct`. Replace the exact value range and retain outer trivia, insert a missing argument in signature order, or remove an unambiguous argument. | +| Member value, such as `.copy` or `.codex` | `direct`. Replaced in place. | +| Constant definition | `sharedConstant`, listing every direct and transitive use. Only `replaceConstant` changes it, accepting the complete impacted reference set. | +| Constant reference or assembled value | `readOnly`; replace the definition explicitly. | +| Concatenation | `readOnly`; it has no independent source range. | +| Normalized field, such as a source requirement or a component kind | `readOnly`; replace the containing construction. | +| Any value inside a read-only value | `readOnly`. | +| Stale handle | `readOnly`; preparing an edit with it fails with `manifest.edit.stale`. | + +Ambiguous trivia or separators make an edit fail with `manifest.edit.readOnly`, +with a span and reason; there is no regeneration fallback. Removing referenced +sources or groups requires a complete batch that repairs the references. Stale +handles, overlaps, incomplete impact and mismatched results have separate +`manifest.edit.stale`, `.overlap`, `.impact` and `.mismatch` diagnostics. + +### Comment ownership + +Comments follow SwiftSyntax trivia ownership: + +1. Standalone comments immediately above a node with no separating blank line + belong to that node; a dictionary key and value form one entry node. +2. Comments beginning on a node's or its comma's line belong to that preceding + node, including multiline block comments. +3. Comments inside an expression or between it and its comma belong to it. +4. Comments separated from the next node by a blank line belong to the container. + The preamble and version directive belong to the file. +5. Delete/move operations carry owned comments. Value replacement preserves outer + comments; whole-node replacement refuses if internal comments cannot be mapped + to retained fields. Unowned comments remain in place. +6. Empty containers become `[]` or `[:]` only when their interiors are whitespace. + Container comments survive; ambiguous mixed layouts or comment-only insertion + sites are read-only. An argument list holding only comments is read-only. + +### New text + +New nodes use the shortest canonical type-correct spelling. `Agents(...)` is the +only ordinary initializer in manifest expressions; nested values use leading-dot +factories. Sources use `.source(name:url:)`, `.source(name:path:)` or +`.source(name:index:)`, and references use `source:`. Requirement values use the +canonical requirement spelling defined under Construction vocabulary. Literal +conformances provide strings for prompts, own sections, local group references +and versions, array literals for explicit skill selections, and JSON-style +configuration literals. Dictionary literals and direct factories construct the +remaining values. Existing unmodified expressions keep their spelling. + +New text uses the container's consistent indentation, newline and comma style; +absent evidence, it uses two spaces, LF and trailing commas in multiline +collections. Argument order follows signatures; root insertion order is +`defaultAgents`, `exports`, `sources`, `components`, `groups`, `uses`, `watch`. +`upsertSource(Source)` preserves the complete requirement value. Fresh node +layout follows the canonical printer; existing surrounding style takes +precedence. Inserting the first argument into an empty argument list, such as +`Agents()`, uses the canonical call layout, so a collection or nested call +argument starts a multiline list. Conflicting local style is an editability +diagnostic, not permission to reformat the file. + +The editor and canonical printer emit one ASCII space on each side of `=` and +`+`, with adjacent sign/digits for negative integers: `let value = -1`. A value +replacement re-checks both joins with the unchanged source, including neighboring +comments, against the lexical rules before it becomes a patch. For example, +replacing `0` in `[/* note */0]` emits ` -1` inside that value's replacement range, +producing `[/* note */ -1]` while preserving all bytes outside the range. The +editor never joins a sign to `=` or to a comment terminator. A source that already +fails recognition, such as `let value=0`, cannot receive a domain edit. If a safe +boundary cannot be represented in the authorized patch range, preparation fails +with an editability diagnostic. The complete candidate passes recognition again +before SwiftParser is invoked; a failed check publishes no patch or source bytes. + +Range replacement re-checks both operator/operand boundaries and the containing +source requirement slot. A complete replacement uses the canonical requirement +spelling, including changing the argument label when its range category changes. +A leaf endpoint edit preserves surrounding trivia only if the result still meets +balanced spacing and comment rules; otherwise the necessary whitespace is part of +the explicit patch, or the edit fails with `manifest.edit.readOnly` when comment +ownership is ambiguous. + +### Edit invariants + +The invariants are byte-exact no-op return, byte preservation outside disjoint +patch ranges, and full reparse, type check, evaluation and domain validation of +the complete candidate before it is returned. The resulting complete IR must equal +the expected IR, including inactive groups and exports; only source positions and +trivia are excluded. All stages use the expanded-size budgets. BOM, final-newline +presence and unrelated bytes survive. + +### Canonical printing + +The canonical printer lays out new nodes and prints a complete document for a +new declaration file. Equal values print identical bytes. A document is the +version line, `import AgentsDescription`, one blank line, then +`let agents = Agents(...)`, with two-space indentation, LF, no BOM and one final +newline. Assignment and array concatenation use one ASCII space on each side of +`=` and `+`; negative literals use an adjacent sign and digits. Strings use +ordinary quotes; quotes, backslashes, LF, CR and tab are escaped, other control +scalars are lowercase Swift `\u{...}` escapes, and other Unicode scalars are +preserved without normalization. + +Values use literal prompts, sections, selections and dictionaries and direct +factories. Default-valued arguments are omitted; explicit Optional values that +distinguish inheritance are retained. Signature order determines labels. +Dictionary keys sort by UTF-8 bytes; arrays keep their order. A collection of +scalar literals or payload-free enum members fits inline when the complete line, +including indentation and comma, is at most 80 UTF-8 bytes; otherwise it expands. +Collections containing collections or factory/initializer calls are multiline. +A call with only scalar arguments fits inline under the same limit; calls with +collections, ranges or nested calls are multiline. Multiline collections have +trailing commas; call arguments have none after the last argument. Empty +collections are `[]` or `[:]`. Printing never reformats an existing document. + +## Evaluated JSON Dump + +`ManifestDump(bytes:)` and `ManifestDump(document:)` evaluate only one local +declaration. The dump does not resolve external groups, fetch sources or +secrets, inspect native files or compile or run the manifest. Conditional +branches and group references remain symbolic. `encodedJSON()` returns one UTF-8 +JSON object with sorted keys, two-space indentation and a trailing LF. Invalid +input throws `ManifestFailure` with its diagnostics, and no partial object +exists. `agents manifest dump --json` prints these bytes; its exit status and +diagnostic presentation belong to the CLI. + +The root has `schemaVersion: 1`, `kind: "manifest"`, `languageVersion: "1.0"`, +`sourceDigest`, `declaration`, `locations` and `diagnostics`. The digest is +`sha256:` plus 64 lowercase hexadecimal digits over the original bytes. +`declaration` has `defaultAgents`, `exports`, `sources`, `components`, `groups`, +`uses` and `watch`. Default arrays are empty, Optional absence is null, and +explicit empty recipients remain distinct from inheritance. + +A component encodes directly as `{ "kind": "mcpServer", "name": "workspace", +"transport": { ... }, "agents": ["claude-code"], "condition": null, +"native": {} }`. There is no payload wrapper. The remaining schema is determined +by the vocabulary as follows: + +- Tagged families encode `{kind, ...fields}`. Component/transport kinds are + their factory names. `ExecutableInvocation` is `kind: "executable"` with executable, + arguments, environment and workingDirectory. `.group(name:)` references encode + kind `local`; `.group(name:source:)` references encode kind `exported`, with + name and condition. An exported reference always has a non-null source; a local + reference has none (encoded as null). Conditions encode their + three dimensions without a kind. Permission rules encode + `{kind: "allow" | "ask" | "deny", operation, pattern}`; their two unlabeled + factory arguments use the keys `operation` and `pattern`. LSP `languages` + encodes an object mapping extension keys to language-ID strings. +- A source has `kind: "git" | "local" | "index"`, name, location (`url`, `path` or + `index`, matching its factory field), subpath and requirement. A `path:` source + with a requirement remains kind `local`. Requirement is null or an + object with exactly one of `branch`, `revision`, `exact`, `from`, `upToNextMinor`, + or `from` plus `to`, matching core's `SourceRequirement` encoding. Version values encode + as normalized version strings. Every range value encodes its canonical + requirement kind: `from`, + `upToNextMinor`, or `from`/`to`, regardless of its construction spelling. +- Groups, skill overrides, ChatGPT prompts, prompt parameters and resources encode + their factory fields without a factory-name tag; the resource's unlabeled + subject uses key `path`. Arrays/dictionaries encode as JSON collections, + with defaults supplied. + Exports and watch are string arrays. An instruction section is always an object + with name, source and condition, even when authored as a string. +- Skill selection encodes `"all"` or an array of names. Prompt content is + `{kind: "literal", value: }` or `{kind: "file", path, source}`. + Runtime values similarly use literal/environment/secret and value. Literal + spelling and explicit equivalent cases have identical evaluated output. +- Payload-free enum cases are strings, except mixed enums always use tagged + objects. Associated values retain labels; a single unlabeled payload uses + `value`. Typed component references use kind and name. Configuration values + retain kind and value tags, including nested arrays/objects; null has only kind, + and decimal values remain strings to prevent numeric rounding. +- Agent IDs are `claude-code`, `codex`, `cursor`, `gemini-cli`, `opencode`; + platforms are `macos`, `linux`; other enum spellings are unchanged. + +Components, group references, sections, hooks, permission rules, ignore patterns, +arguments and prompt parameters preserve order. Definitions of sources/groups, +exports, watch, named prompts and overrides sort by name; recipients, exclusions +and explicit skill selections sort by canonical identity. Dictionary keys sort +by decoded UTF-8 bytes. Typed plugin exclusions sort by kind then name. +Constants are substituted by value within the checked expansion budget. + +A location has `pointer` (JSON Pointer into the normalized declaration), `span`, +`origins`, `defaulted` and `editability`. Spans have document `"manifest"`, start/end +byte offsets and starting line/column. A use's span identifies the use site; +origins include definitions. Missing fields anchor to their containing construction +with defaulted true. Editability is `editability(of:)` for that location: kind +`direct`; kind `sharedConstant` with the `uses` spans of every impacted reference; +or kind `readOnly` with its `reason`. Locations sort by pointer then start +offset; runtime node handles are not serialized. + +Diagnostics have code, severity, message, span and related spans, sorted by +position then code. No timestamps, cache paths or resolved secrets are emitted. +Readers ignore unknown object keys but reject unsupported schema versions and +unknown semantic discriminants. Changed meanings or new discriminants require +a new schema version; optional metadata additions do not. Source digest/locations +may change with comments while declaration stays equal. Entire output and map +size are reserved before serialization under the expanded-size budgets. + +## Diagnostics + +Diagnostics include stable code, severity, message, primary span, related spans +and optional suggested edit. Spans use half-open UTF-8 byte offsets and 1-based +line/UTF-8-byte-column positions. At most 100 diagnostics plus one truncation +notice are produced. Any structural/type/domain error rejects the candidate; +no partial declaration is published. + +| Diagnostic | Meaning | +| --- | --- | +| `manifest.version.missing`, `.invalid`, `.duplicate`, `.unsupported` | Version selection failed. | +| `manifest.syntax` | Recognizer: a lexical or production violation, including missing/extra imports, juxtaposed identifiers, unsupported prefixes, raw strings, interpolation and malformed literals. SwiftParser syntax/recovery diagnostics can occur only after recognizer acceptance and the tree guard; such a disagreement is also an implementation regression. | +| `manifest.call`, `manifest.type`, `manifest.operator` | After the tree guard: unlisted call/member, incorrect labels/order/type, missing context, integer overflow or non-array use of the admitted `+` operator. The `..<` operator is typed as `Range` only in its admitted requirement position. Other operators, including closed ranges (`...`), fail admission with a located `manifest.syntax` diagnostic; `ClosedRange` also has no matching compiler overload. | +| `manifest.reference` | Unknown, forward, self, duplicate or shadowing constant name. | +| `manifest.domain`, `manifest.dictionary.duplicateKey` | Invalid domain value or duplicate decoded dictionary key. A `manifest.domain` warning reports a Git shorthand with its fix-it. | +| `manifest.group.cycle`, `.missing` | Invalid local group graph, with the relevant reference chain. | +| `manifest.limit` | Recognizer: byte, token, syntax-storage reservation, comment, delimiter or chain limit. Iterative tree guard: node/depth limit. Later stages: evaluation, expansion, domain traversal, local group depth, output, generated source or edit budget. | +| `manifest.diagnostics.truncated` | The warning that replaces diagnostics beyond the limit. | +| `manifest.edit.readOnly`, `.stale`, `.overlap`, `.impact`, `.mismatch` | Document editing, as described under Document Editing. Declaration edit planning also reports `.mismatch` when a batch makes no progress or the final projection differs from the intended declaration. | +| `manifest.edit.baseline` | Declaration edit planning: the declaration an operation read differs from the projection of the bytes it prepared. | +| `manifest.unsupported` | The state layer's deployable-subset projection meets an active structure outside that subset; the span locates it. See [State](../Architecture/State.md#deployable-subset). | +| `manifest.dump.mismatch` | A source-map pointer is absent from the evaluated declaration while building a dump; this is an implementation regression. | + +## Conformance and Validation + +Every Swift code block in this reference and in the manifest proposal, +including interface and editor-API blocks, must pass `swiftc -parse`; +signature-only interface blocks use `swiftc -frontend -parse` with +`.swiftinterface` inputs so getter declarations are parsed in interface mode. +Positive fixtures compile against `AgentsDescription` and their +compiled values match static evaluation under plain value equality, including +equal range forms and string-literal group references. Compiler-required literal conformances and evaluator +registrations are checked against the same signature inventory. Negative fixtures +cover unsupported syntax, contextual typing, duplicate dictionary keys, budgets +and spans. No accepted static value may fail real Swift type checking. + +Adversarial tests run every input in a subprocess with a parent watchdog and +assert normal completion without signals, crashes or unbounded memory growth. +Fixed regressions include balanced/unbalanced square nests, mixed square/call +nests, dictionaries, nested shorthand calls and parentheses, brace nests, generic +types `A>`, ambiguous `a Date: Sat, 31 Oct 2026 00:05:52 +0800 Subject: [PATCH 022/171] feat(state): read and write declarations through Agents.swift State stores read the declaration by parsing Agents.swift and project it onto the deployable subset. Every declaration write is planned into comment-preserving edits before any side effect, then published with its preparation evidence in the same transaction as the lock and watch state. A scope with a lock or watch state but no declaration is an error, not an empty declaration. Public loads are read-only and report pending recovery, recovery no longer reads the declaration, and watch changes return the affected source. Declaration types have no serialized form. --- Package.swift | 28 +- Sources/AgentsCore/CoreError.swift | 10 + Sources/AgentsCore/Declaration.swift | 80 +---- Sources/AgentsCore/DeclarationAccess.swift | 30 ++ .../AgentsCore/ResolvedStateEncoding.swift | 13 + Sources/AgentsCore/SourceCache.swift | 7 +- Sources/AgentsCore/StateInspection.swift | 16 +- Sources/AgentsCore/StateJSON.swift | 10 +- Sources/AgentsCore/StateStore.swift | 105 +++--- Sources/AgentsCore/TransactionPaths.swift | 4 +- Sources/AgentsCore/WatchModels.swift | 7 + Sources/AgentsCore/WatchOperations.swift | 58 ++-- .../InstructionDoctor.swift | 1 + .../InstructionExport.swift | 1 + .../InstructionOperations.swift | 34 +- Sources/AgentsManifest/ManifestState.swift | 106 ++++++ Sources/AgentsSkills/SkillLifecycle.swift | 28 +- Sources/AgentsSkills/SkillOperations.swift | 63 ++-- Sources/AgentsSkills/WatchSupport.swift | 4 +- Sources/AgentsUpdates/UpdatePlan.swift | 7 +- .../CachePublicationTests.swift | 7 +- .../CheckpointUniquenessTests.swift | 3 +- Tests/AgentsCoreTests/CoreTestSupport.swift | 3 + .../DeclarationStateTests.swift | 189 ++++++++++ Tests/AgentsCoreTests/GitErrorTests.swift | 9 +- .../InstructionTransactionTests.swift | 4 +- .../PreparationEvidenceTests.swift | 1 + Tests/AgentsCoreTests/PublicationTests.swift | 15 +- Tests/AgentsCoreTests/SourceCacheTests.swift | 1 + .../AgentsCoreTests/StateEncodingTests.swift | 17 +- .../StateInspectionTests.swift | 4 +- Tests/AgentsCoreTests/StateModelTests.swift | 41 +-- .../StatePublicationTests.swift | 322 ++++++++++++++++++ .../StateTransactionTests.swift | 42 ++- .../TransactionCostTests.swift | 4 +- .../TransactionMetadataTests.swift | 4 +- .../WatchDurabilityTests.swift | 9 +- Tests/AgentsCoreTests/WatchGitLockTests.swift | 9 +- .../WatchInspectionTests.swift | 15 +- .../WatchPreparationTests.swift | 9 +- .../AgentsCoreTests/WatchReferenceTests.swift | 2 +- Tests/AgentsCoreTests/WatchStateTests.swift | 3 +- .../DeclarationDocumentTests.swift | 119 +++++++ .../LifecycleSafetyTests.swift | 1 + .../LifecycleTests.swift | 1 + .../OwnershipAndPlacementTests.swift | 12 +- .../SourceDiagnosticTests.swift | 1 + .../SourceShorthandTests.swift | 1 + .../TargetLifecycleTests.swift | 36 +- .../AutomaticSelectionTests.swift | 4 +- Tests/AgentsSkillsTests/CoreTestSupport.swift | 12 + .../DefaultResolutionTests.swift | 1 + .../DiscoveryBehaviorTests.swift | 1 + .../InstalledInventoryTests.swift | 33 +- .../LifecycleRegressionTests.swift | 1 + .../ManifestLifecycleTests.swift | 296 ++++++++++++++++ .../PublicLifecycleTests.swift | 1 + .../ReadOnlyInspectionTests.swift | 12 +- .../RetainedLifecycleTests.swift | 1 + .../SkillLifecycleTests.swift | 5 +- .../AgentsSkillsTests/SourceAliasTests.swift | 1 + .../SourceShorthandTests.swift | 1 + .../TransactionDoctorTests.swift | 1 + .../UpdateReportingTests.swift | 1 + .../WatchSubscriptionTests.swift | 25 +- .../CombinedUpdateTests.swift | 8 +- .../RequirementUpdateTests.swift | 1 + Tests/AgentsUpdatesTests/UpdateFixture.swift | 1 + .../UpdateTransactionTests.swift | 4 +- Tests/StateTestProcess/main.swift | 39 ++- Tests/StateTestSupport/ManifestText.swift | 9 + 71 files changed, 1559 insertions(+), 395 deletions(-) create mode 100644 Sources/AgentsCore/DeclarationAccess.swift create mode 100644 Sources/AgentsManifest/ManifestState.swift create mode 100644 Tests/AgentsCoreTests/DeclarationStateTests.swift create mode 100644 Tests/AgentsCoreTests/StatePublicationTests.swift create mode 100644 Tests/AgentsInstructionsTests/DeclarationDocumentTests.swift create mode 100644 Tests/AgentsSkillsTests/ManifestLifecycleTests.swift create mode 100644 Tests/StateTestSupport/ManifestText.swift diff --git a/Package.swift b/Package.swift index c823cba..eec9b6a 100644 --- a/Package.swift +++ b/Package.swift @@ -38,23 +38,31 @@ let package = Package( ), .target( name: "AgentsInstructions", - dependencies: ["AgentsCore", .product(name: "Markdown", package: "swift-markdown")] + dependencies: [ + "AgentsCore", "AgentsManifest", .product(name: "Markdown", package: "swift-markdown"), + ] ), - .target(name: "AgentsSkills", dependencies: ["AgentsCore", "Yams"]), + .target(name: "AgentsSkills", dependencies: ["AgentsCore", "AgentsManifest", "Yams"]), .target( name: "AgentsUpdates", - dependencies: ["AgentsCore", "AgentsSkills", "AgentsInstructions", "CPlatform"]), + dependencies: [ + "AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions", "CPlatform", + ]), .target(name: "StateTestSupport", path: "Tests/StateTestSupport"), .executableTarget( name: "StateTestProcess", dependencies: [ - "AgentsCore", "AgentsInstructions", "AgentsSkills", "AgentsUpdates", "CPlatform", + "AgentsCore", "AgentsManifest", "AgentsInstructions", "AgentsSkills", "AgentsUpdates", + "CPlatform", "StateTestSupport", ], path: "Tests/StateTestProcess"), .testTarget( name: "AgentsCoreTests", - dependencies: ["AgentsCore", "StateTestProcess", "StateTestSupport", "CPlatform"]), - .testTarget(name: "AgentsInstructionsTests", dependencies: ["AgentsInstructions"]), + dependencies: [ + "AgentsCore", "AgentsManifest", "StateTestProcess", "StateTestSupport", "CPlatform", + ]), + .testTarget( + name: "AgentsInstructionsTests", dependencies: ["AgentsInstructions", "AgentsManifest"]), .target( name: "ManifestTestSupport", dependencies: ["AgentsManifest"], path: "Tests/ManifestTestSupport"), @@ -73,12 +81,14 @@ let package = Package( resources: [.copy("Fixtures")]), .testTarget( name: "AgentsUpdatesTests", - dependencies: ["AgentsUpdates", "StateTestProcess", "StateTestSupport", "CPlatform"]), + dependencies: [ + "AgentsUpdates", "AgentsManifest", "StateTestProcess", "StateTestSupport", "CPlatform", + ]), .testTarget( name: "AgentsSkillsTests", dependencies: [ - "AgentsSkills", "AgentsCore", "AgentsInstructions", "Yams", "StateTestProcess", - "StateTestSupport", "CPlatform", + "AgentsSkills", "AgentsCore", "AgentsManifest", "AgentsInstructions", "Yams", + "StateTestProcess", "StateTestSupport", "CPlatform", ]), ], swiftLanguageModes: [.v6] diff --git a/Sources/AgentsCore/CoreError.swift b/Sources/AgentsCore/CoreError.swift index ad53c5a..fbe3c09 100644 --- a/Sources/AgentsCore/CoreError.swift +++ b/Sources/AgentsCore/CoreError.swift @@ -10,6 +10,10 @@ public enum CoreError: Error, CustomStringConvertible, Equatable { case commandFailed(String) /// Recovery completed; retry the operation against the recovered state. case transactionRecovered(String) + /// Inspection found an interrupted transaction; a command that changes the scope recovers it. + case recoveryPending(String) + /// The scope has lock or watch state but no declaration at the given path. + case missingDeclaration(String) public var description: String { switch self { @@ -27,6 +31,12 @@ public enum CoreError: Error, CustomStringConvertible, Equatable { return "Invalid state: \(message)" case .transactionRecovered(let path): return "Recovered interrupted transaction at \(path); retry the command" + case .recoveryPending(let message): + return message + case .missingDeclaration(let path): + return + "Missing declaration at \(path): the scope has lock or watch state; restore the file " + + "from version control, or remove the scope's state files to start again" case .commandFailed(let message): return "Command failed: \(message)" } diff --git a/Sources/AgentsCore/Declaration.swift b/Sources/AgentsCore/Declaration.swift index 7bf232f..0038666 100644 --- a/Sources/AgentsCore/Declaration.swift +++ b/Sources/AgentsCore/Declaration.swift @@ -6,8 +6,8 @@ public enum SourceKind: String, Codable, Sendable { case wellKnown = "well-known" } -/// A source alias's location, requirement and discovery root in agents.json. -public struct SourceDeclaration: Codable, Equatable, Sendable { +/// A source alias's location, requirement and discovery root. +public struct SourceDeclaration: Equatable, Sendable { public var kind: SourceKind public var location: String public var requirement: SourceRequirement? @@ -22,35 +22,6 @@ public struct SourceDeclaration: Codable, Equatable, Sendable { self.path = path } - private enum CodingKeys: String, CodingKey { - case git, local - case wellKnown = "well-known" - case path - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - let kinds: [(CodingKeys, SourceKind)] = [ - (.git, .git), (.local, .local), (.wellKnown, .wellKnown), - ] - let present = kinds.filter { container.contains($0.0) } - guard present.count == 1, let (key, kind) = present.first else { - throw CoreError.invalidState("a source must specify exactly one of git, local or well-known") - } - self.kind = kind - location = try container.decode(String.self, forKey: key) - path = try container.decodeIfPresent(String.self, forKey: .path) - requirement = try SourceRequirement.decodeIfPresent(from: decoder) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - let key: CodingKeys = kind == .git ? .git : (kind == .local ? .local : .wellKnown) - try container.encode(location, forKey: key) - try container.encodeIfPresent(path, forKey: .path) - try requirement?.encode(to: encoder) - } - public func identity(environment: RuntimeEnvironment) throws -> String { guard !location.isEmpty else { throw CoreError.invalidSource("empty source location") } switch kind { @@ -116,29 +87,12 @@ public struct SourceDeclaration: Codable, Equatable, Sendable { } } -public enum SkillSelection: Codable, Equatable, Sendable { +public enum SkillSelection: Equatable, Sendable { case all case names([String]) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - if let value = try? container.decode(String.self), value == "all" { - self = .all - } else { - self = .names(try container.decode([String].self)) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - switch self { - case .all: try container.encode("all") - case .names(let names): try container.encode(names.sorted()) - } - } } -public struct SkillOverride: Codable, Equatable, Sendable { +public struct SkillOverride: Equatable, Sendable { public var agents: [AgentID]? public var mode: InstallMode? @@ -148,7 +102,7 @@ public struct SkillOverride: Codable, Equatable, Sendable { } } -public struct SkillDeclaration: Codable, Equatable, Sendable { +public struct SkillDeclaration: Equatable, Sendable { public var select: SkillSelection public var exclude: [String]? public var agents: [AgentID]? @@ -167,7 +121,7 @@ public struct SkillDeclaration: Codable, Equatable, Sendable { } } -public struct PromptDeclaration: Codable, Equatable, Sendable { +public struct PromptDeclaration: Equatable, Sendable { /// Source alias and section name pairs, in rendering order. public var sections: [String] public var append: String? @@ -178,7 +132,7 @@ public struct PromptDeclaration: Codable, Equatable, Sendable { } } -public struct InstructionsDeclaration: Codable, Equatable, Sendable { +public struct InstructionsDeclaration: Equatable, Sendable { public var agents: [AgentID]? public var sections: [String] public var chatgpt: [String: PromptDeclaration]? @@ -192,8 +146,9 @@ public struct InstructionsDeclaration: Codable, Equatable, Sendable { } } -/// User intent. Section order is significant; other collections are emitted in identity order. -public struct Declaration: Codable, Equatable, Sendable { +/// User intent from the scope's declaration document. Section order is significant; other +/// collections are unordered. +public struct Declaration: Equatable, Sendable { public var agents: [AgentID]? public var sources: [String: SourceDeclaration] public var skills: [String: SkillDeclaration]? @@ -212,25 +167,12 @@ 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 { var identities = Set() for (alias, source) in sources { - guard !alias.isEmpty, !alias.contains(":") else { + guard !alias.isEmpty, alias != ".", !alias.contains(":") else { throw CoreError.invalidState("invalid source alias: \(alias)") } guard try identities.insert(source.identity(environment: environment)).inserted else { diff --git a/Sources/AgentsCore/DeclarationAccess.swift b/Sources/AgentsCore/DeclarationAccess.swift new file mode 100644 index 0000000..3acaa7e --- /dev/null +++ b/Sources/AgentsCore/DeclarationAccess.swift @@ -0,0 +1,30 @@ +import Foundation + +/// Declaration source bytes that the declaration format planned and verified for one prepared +/// generation. Core publishes them without reading the format. +package struct DeclarationChange: Sendable { + package let bytes: Data + + package init(bytes: Data) { + self.bytes = bytes + } +} + +/// Reads and plans declarations through the module that owns the declaration format. +package struct DeclarationAccess: Sendable { + /// Reads the declaration, from the prepared generation when one is supplied. + package typealias Read = @Sendable (StateStore, StatePrecondition?) throws -> Declaration + /// Plans `next` against the prepared document that `previous` was read from; nil leaves the + /// declaration unchanged. + package typealias Plan = + @Sendable (StateStore, _ previous: Declaration, _ next: Declaration, StatePrecondition) + throws -> DeclarationChange? + + package let read: Read + package let plan: Plan + + package init(read: @escaping Read, plan: @escaping Plan) { + self.read = read + self.plan = plan + } +} diff --git a/Sources/AgentsCore/ResolvedStateEncoding.swift b/Sources/AgentsCore/ResolvedStateEncoding.swift index 55b5633..1f00b97 100644 --- a/Sources/AgentsCore/ResolvedStateEncoding.swift +++ b/Sources/AgentsCore/ResolvedStateEncoding.swift @@ -10,4 +10,17 @@ extension ResolvedState { } return try StateStore.encodeState(normalized) } + + /// The replacement for the prepared generation's lock. A scope whose prepared generation has + /// neither a lock nor a declaration receives no empty ledger, because lock state without a + /// declaration stops every later access to the scope. + package func replacementData(in store: StateStore, prepared: StatePrecondition) throws -> Data? { + let existing = try prepared.bytes(for: store.resolvedURL) + if existing == nil, try prepared.bytes(for: store.declarationURL) == nil, + normalized == ResolvedState().normalized + { + return nil + } + return try replacementData(comparedTo: existing) + } } diff --git a/Sources/AgentsCore/SourceCache.swift b/Sources/AgentsCore/SourceCache.swift index 44de06c..2495c67 100644 --- a/Sources/AgentsCore/SourceCache.swift +++ b/Sources/AgentsCore/SourceCache.swift @@ -175,10 +175,6 @@ package struct SourceCache { for (id, source) in resolved.sources where source.kind != .wellKnown { sourceLocations[key(id) + ".git"] = try declaration(sourceID: id, source: source).location } - for source in try store.readDeclaration().sources.values where source.kind != .wellKnown { - let id = try source.identity(environment: store.environment) - sourceLocations[key(id) + ".git"] = source.location - } var retained: [String: Set] = [:] func retain(_ source: String, _ revision: String?) { if let revision { retained[key(source) + ".git", default: []].insert(revision) } @@ -693,7 +689,8 @@ package struct SourceCache { } private func mirrorSource(_ mirror: URL, lock: Int32) throws -> String { - // Orphaned mirrors outlive their declarations; the clone's origin retains the source location. + // Recovery never reads the declaration. A mirror that neither watch state nor the lock + // names, including an orphan, is identified by its clone's origin. let source: String do { source = try git( diff --git a/Sources/AgentsCore/StateInspection.swift b/Sources/AgentsCore/StateInspection.swift index 704ffa3..3d07a9f 100644 --- a/Sources/AgentsCore/StateInspection.swift +++ b/Sources/AgentsCore/StateInspection.swift @@ -3,12 +3,11 @@ import Foundation extension StateStore { /// Takes an existing scope lock without creating files or replaying recovery. - /// Pending recovery runs the diagnostic callback instead of inspecting inconsistent state. + /// Pending recovery runs the diagnostic callback instead of inspecting inconsistent state; + /// by default it throws `CoreError.recoveryPending`. /// The body may be retried when a first writer creates the scope lock. package func withReadLock( - onPendingRecovery: () throws -> T = { - throw CoreError.invalidState("transaction recovery is required before inspection") - }, + onPendingRecovery: (() throws -> T)? = nil, _ body: () throws -> T ) throws -> T { while true { @@ -30,7 +29,14 @@ extension StateStore { } defer { if descriptor >= 0 { platform_flock(descriptor, LOCK_UN) } } let pending = try hasPendingRecovery(in: directory) - let result = Result { try pending ? onPendingRecovery() : body() } + let result = Result { + guard pending else { return try body() } + guard let onPendingRecovery else { + throw CoreError.recoveryPending( + FileTransaction.recoveryDiagnostic(store: self).message) + } + return try onPendingRecovery() + } // Writers create the lock before mutation and never remove it. A failed // unlocked read also needs revalidation before its error can be trusted. if descriptor < 0, let current = try openDirectoryIfPresent(), diff --git a/Sources/AgentsCore/StateJSON.swift b/Sources/AgentsCore/StateJSON.swift index 4ecd595..abc73ba 100644 --- a/Sources/AgentsCore/StateJSON.swift +++ b/Sources/AgentsCore/StateJSON.swift @@ -1,10 +1,10 @@ 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. +/// The layout of `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 diff --git a/Sources/AgentsCore/StateStore.swift b/Sources/AgentsCore/StateStore.swift index 5c5a94e..752cd78 100644 --- a/Sources/AgentsCore/StateStore.swift +++ b/Sources/AgentsCore/StateStore.swift @@ -15,23 +15,39 @@ public struct StateStore: Sendable { ? environment.projectDirectory.appendingPathComponent(".agent") : environment.homeDirectory.appendingPathComponent(".agents") } - public var declarationURL: URL { directory.appendingPathComponent("agents.json") } - public var resolvedURL: URL { directory.appendingPathComponent("agents.resolved") } - public var watchURL: URL { directory.appendingPathComponent("agents.watch") } + public var declarationURL: URL { directory.appendingPathComponent(Self.declarationFileName) } + public var resolvedURL: URL { directory.appendingPathComponent(Self.resolvedFileName) } + public var watchURL: URL { directory.appendingPathComponent(Self.watchFileName) } public var cacheDirectory: URL { directory.appendingPathComponent("cache") } - public func loadDeclaration() throws -> Declaration { - try withLock(createIfMissing: false) { try readDeclaration() } - } - - package func readDeclaration(prepared: StatePrecondition? = nil) throws -> Declaration { - let declaration: Declaration = try load(declarationURL, prepared: prepared) ?? Declaration() - try declaration.validate(environment: environment) - return declaration + package static let declarationFileName = "Agents.swift" + package static let resolvedFileName = "agents.resolved" + package static let watchFileName = "agents.watch" + /// The scope files a state transaction may replace. + package static let stateFileNames: Set = [ + declarationFileName, resolvedFileName, watchFileName, + ] + + /// The declaration's bytes, or nil when the scope has no declaration and no lock or watch + /// state. Lock or watch state without a declaration is `CoreError.missingDeclaration`; a + /// prepared generation answers from its captured bytes. + package func declarationBytes(prepared: StatePrecondition? = nil) throws -> Data? { + func bytes(_ url: URL) throws -> Data? { + try prepared.map { try $0.bytes(for: url) } ?? existingData(url) + } + if let declaration = try bytes(declarationURL) { return declaration } + guard try bytes(resolvedURL) == nil, try bytes(watchURL) == nil else { + throw CoreError.missingDeclaration(declarationURL.path) + } + return nil } + /// Reads the lock under a shared lock, without recovery or creating files. public func loadResolved() throws -> ResolvedState { - try withLock(createIfMissing: false) { try readResolved() } + try withReadLock { + _ = try declarationBytes() + return try readResolved() + } } package func readResolved(prepared: StatePrecondition? = nil) throws -> ResolvedState { @@ -40,8 +56,12 @@ public struct StateStore: Sendable { return lock } + /// Reads watch state under a shared lock, without recovery or creating files. public func loadWatch() throws -> WatchState { - try withLock(createIfMissing: false) { try readWatch() } + try withReadLock { + _ = try declarationBytes() + return try readWatch() + } } package func readWatch(prepared: StatePrecondition? = nil) throws -> WatchState { @@ -50,46 +70,15 @@ public struct StateStore: Sendable { return watch } - /// Commits state through the scope journal. Omitting watch preserves its existing bytes. - public func save( - declaration: Declaration, resolved: ResolvedState, watch: WatchState? = nil - ) throws { - try withLock { - try declaration.validate(environment: environment) - try resolved.validate() - try watch?.validate() - let baseline = try StatePrecondition(store: self) - _ = try readDeclaration(prepared: baseline) - _ = try readResolved(prepared: baseline) - let transaction = FileTransaction(store: self) - transaction.requireUnchanged(since: baseline) - try stageDeclaration(declaration, in: transaction, prepared: baseline) - try transaction.replace( - resolvedURL, with: .data(Self.encodeState(resolved.normalized)), - expecting: baseline.evidence(for: resolvedURL)) - if let watch { - try transaction.replace( - watchURL, with: .data(Self.encode(watch)), expecting: baseline.evidence(for: watchURL)) - } - try transaction.commit() - } - } - - /// 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. + /// Publishes a planned declaration change in the transaction, expecting the prepared + /// generation. Without a change the declaration stays unchanged. package func stageDeclaration( - _ declaration: Declaration, in transaction: FileTransaction, - prepared: StatePrecondition? = nil + _ change: DeclarationChange?, in transaction: FileTransaction, prepared: StatePrecondition ) throws { - let data = try Self.encodeState(declaration.normalized) - let input: (bytes: Data?, evidence: TargetPrecondition) - if let prepared { - input = try (prepared.bytes(for: declarationURL), prepared.evidence(for: declarationURL)) - } else { - input = try TargetPrecondition.readingFile(declarationURL) - } - guard input.bytes != data else { return } - try transaction.replace(declarationURL, with: .data(data), expecting: input.evidence) + guard let change else { return } + try transaction.replace( + declarationURL, with: .data(change.bytes), + expecting: prepared.evidence(for: declarationURL)) } package func withLock( @@ -100,14 +89,14 @@ public struct StateStore: Sendable { if try openDirectoryIfPresent() == nil, !createIfMissing { return try body() } - if !FileManager.default.fileExists( - atPath: directory.appendingPathComponent(".agents.lock").path), - !FileManager.default.fileExists( - atPath: directory.appendingPathComponent(TransactionJournal.fileName).path) - { - _ = try readDeclaration() + // Without a scope lock, journal or ref-cleanup marker, invalid or orphaned state stops the + // operation before the scope lock exists. Otherwise recovery precedes these checks. + if ![".agents.lock", TransactionJournal.fileName, "watch-refs.pending"].contains(where: { + FileManager.default.fileExists(atPath: directory.appendingPathComponent($0).path) + }) { _ = try readResolved() _ = try readWatch() + _ = try declarationBytes() } let base = scope == .project ? environment.projectDirectory : environment.homeDirectory let physicalDirectory = base.resolvingSymlinksInPath().appendingPathComponent( @@ -150,7 +139,7 @@ public struct StateStore: Sendable { return try parent.child(name) } - /// Encodes `agents.json` or `agents.resolved` in the layout `StateJSON` describes. + /// Encodes `agents.resolved` in the layout `StateJSON` describes. package static func encodeState(_ value: T) throws -> Data { let encoder = JSONEncoder() encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index 36f0bed..ebff758 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -103,9 +103,7 @@ struct TransactionPaths { else { throw CoreError.invalidState("invalid scope-relative transaction path") } let descendants = Array(parts.dropFirst()) if key == "state" { - let stateFile = - descendants.count == 1 - && ["agents.json", "agents.resolved", "agents.watch"].contains(descendants[0]) + let stateFile = descendants.count == 1 && StateStore.stateFileNames.contains(descendants[0]) let cache = descendants.first == "cache" && descendants.count >= 3 && ((descendants[1] == "materialized" && (3...4).contains(descendants.count)) diff --git a/Sources/AgentsCore/WatchModels.swift b/Sources/AgentsCore/WatchModels.swift index de322ea..8afed57 100644 --- a/Sources/AgentsCore/WatchModels.swift +++ b/Sources/AgentsCore/WatchModels.swift @@ -71,3 +71,10 @@ public struct WatchStatus: Equatable, Sendable { public let commitCount: Int? public var changes: [WatchItemChange] } + +/// A subscription after a watch change. `seen` is the acknowledged baseline, or nil after removal. +public struct WatchChange: Equatable, Sendable { + public let alias: String + public let sourceID: String + public let seen: WatchSeen? +} diff --git a/Sources/AgentsCore/WatchOperations.swift b/Sources/AgentsCore/WatchOperations.swift index 6cff9e8..1288e48 100644 --- a/Sources/AgentsCore/WatchOperations.swift +++ b/Sources/AgentsCore/WatchOperations.swift @@ -1,39 +1,38 @@ import Foundation -/// Scope-bound subscriptions. Discovery and artifact loading are supplied by the owning module. +/// Scope-bound subscriptions. Discovery and artifact loading are supplied by the owning module, +/// and declaration reading and planning by the declaration format's module. public struct WatchOperations: Sendable { private let discoverSkills: @Sendable (URL) throws -> [WatchSkill] private let fetchArtifacts: @Sendable (String) throws -> [WatchArtifact] + private let declarations: DeclarationAccess private let checkpoint: @Sendable (String) throws -> Void - public init( - discoverSkills: @escaping @Sendable (URL) throws -> [WatchSkill], - fetchArtifacts: @escaping @Sendable (String) throws -> [WatchArtifact] - ) { - self.init(discoverSkills: discoverSkills, fetchArtifacts: fetchArtifacts, checkpoint: { _ in }) - } - package init( discoverSkills: @escaping @Sendable (URL) throws -> [WatchSkill], fetchArtifacts: @escaping @Sendable (String) throws -> [WatchArtifact], - checkpoint: @escaping @Sendable (String) throws -> Void + declarations: DeclarationAccess, + checkpoint: @escaping @Sendable (String) throws -> Void = { _ in } ) { self.discoverSkills = discoverSkills self.fetchArtifacts = fetchArtifacts + self.declarations = declarations self.checkpoint = checkpoint } /// Declares a source when needed and acknowledges its current content without installing it. + /// The declaration change is planned before Git or an index is contacted. @discardableResult public func add( _ source: String, alias: String? = nil, requirement: SourceRequirement? = nil, path: String? = nil, scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() - ) throws -> WatchSeen { + ) throws -> WatchChange { let store = StateStore(scope: scope, environment: environment) return try store.withLock(checkpoint: checkpoint) { let baseline = try StatePrecondition(store: store) - var declaration = try store.readDeclaration(prepared: baseline) + let previous = try declarations.read(store, baseline) + var declaration = previous let lock = try store.readResolved(prepared: baseline) var watch = try store.readWatch(prepared: baseline) let argument = try SourceArgument(source) @@ -57,11 +56,11 @@ public struct WatchOperations: Sendable { declaration.sources[name] = declared declaration.watch = Array(Set((declaration.watch ?? []) + [name])).sorted() try declaration.validate(environment: environment) + let change = try declarations.plan(store, previous, declaration, baseline) let current = try acknowledge(declared, revision: nil, store: store) watch.sources[id] = WatchSourceState(seen: current) - try commit( - declaration: declaration, watch: watch, lock: lock, store: store, baseline: baseline) - return current + try commit(change, watch: watch, lock: lock, store: store, baseline: baseline) + return WatchChange(alias: name, sourceID: id, seen: current) } } @@ -71,7 +70,7 @@ public struct WatchOperations: Sendable { ) throws -> [WatchStatus] { let store = StateStore(scope: scope, environment: environment) return try store.withReadLock { - let declaration = try store.readDeclaration() + let declaration = try declarations.read(store, nil) _ = try store.readResolved() let watch = try store.readWatch() return try (declaration.watch ?? []).sorted().map { alias in @@ -87,7 +86,7 @@ public struct WatchOperations: Sendable { ) throws -> WatchStatus { let store = StateStore(scope: scope, environment: environment) return try store.withReadLock { - let declaration = try store.readDeclaration() + let declaration = try declarations.read(store, nil) _ = try store.readResolved() let watch = try store.readWatch() let alias = try subscription(source, declaration: declaration, environment: environment) @@ -103,11 +102,11 @@ public struct WatchOperations: Sendable { public func seen( _ source: String, revision: String? = nil, scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() - ) throws -> WatchSeen { + ) throws -> WatchChange { let store = StateStore(scope: scope, environment: environment) return try store.withLock(checkpoint: checkpoint) { let baseline = try StatePrecondition(store: store) - let declaration = try store.readDeclaration(prepared: baseline) + let declaration = try declarations.read(store, baseline) let lock = try store.readResolved(prepared: baseline) var watch = try store.readWatch(prepared: baseline) let alias = try subscription(source, declaration: declaration, environment: environment) @@ -115,28 +114,31 @@ public struct WatchOperations: Sendable { let id = try declared.identity(environment: environment) let current = try acknowledge(declared, revision: revision, store: store) watch.sources[id] = WatchSourceState(seen: current) - try commit(declaration: nil, watch: watch, lock: lock, store: store, baseline: baseline) - return current + try commit(nil, watch: watch, lock: lock, store: store, baseline: baseline) + return WatchChange(alias: alias, sourceID: id, seen: current) } } /// Removes only the subscription and baseline. Source declarations and installations remain. + @discardableResult public func remove( _ source: String, scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() - ) throws { + ) throws -> WatchChange { let store = StateStore(scope: scope, environment: environment) - try store.withLock(checkpoint: checkpoint) { + return try store.withLock(checkpoint: checkpoint) { let baseline = try StatePrecondition(store: store) - var declaration = try store.readDeclaration(prepared: baseline) + let previous = try declarations.read(store, baseline) + var declaration = previous let lock = try store.readResolved(prepared: baseline) var watch = try store.readWatch(prepared: baseline) let alias = try subscription(source, declaration: declaration, environment: environment) let id = try declaration.sources[alias]!.identity(environment: environment) declaration.watch?.removeAll { $0 == alias } watch.sources.removeValue(forKey: id) - try commit( - declaration: declaration, watch: watch, lock: lock, store: store, baseline: baseline) + let change = try declarations.plan(store, previous, declaration, baseline) + try commit(change, watch: watch, lock: lock, store: store, baseline: baseline) + return WatchChange(alias: alias, sourceID: id, seen: nil) } } @@ -172,15 +174,13 @@ public struct WatchOperations: Sendable { /// The prepared generation, captured before any network acknowledgment, is the journal's /// preimage evidence and also guards the lock that pruning follows. private func commit( - declaration: Declaration?, watch: WatchState, lock: ResolvedState, store: StateStore, + _ change: DeclarationChange?, watch: WatchState, lock: ResolvedState, store: StateStore, baseline: StatePrecondition ) throws { try watch.validate() let transaction = FileTransaction(store: store, checkpoint: checkpoint) transaction.requireUnchanged(since: baseline) - if let declaration { - try store.stageDeclaration(declaration, in: transaction, prepared: baseline) - } + try store.stageDeclaration(change, in: transaction, prepared: baseline) try transaction.replace( store.watchURL, with: .data(StateStore.encode(watch)), expecting: baseline.evidence(for: store.watchURL)) diff --git a/Sources/AgentsInstructions/InstructionDoctor.swift b/Sources/AgentsInstructions/InstructionDoctor.swift index f4efdc7..c7a5e21 100644 --- a/Sources/AgentsInstructions/InstructionDoctor.swift +++ b/Sources/AgentsInstructions/InstructionDoctor.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import Foundation extension InstructionOperations { diff --git a/Sources/AgentsInstructions/InstructionExport.swift b/Sources/AgentsInstructions/InstructionExport.swift index 1d52361..50d53a5 100644 --- a/Sources/AgentsInstructions/InstructionExport.swift +++ b/Sources/AgentsInstructions/InstructionExport.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import Foundation /// One scope's locked instruction mapping. It describes the lock, not the files on disk. diff --git a/Sources/AgentsInstructions/InstructionOperations.swift b/Sources/AgentsInstructions/InstructionOperations.swift index 2d6774d..e97cf3a 100644 --- a/Sources/AgentsInstructions/InstructionOperations.swift +++ b/Sources/AgentsInstructions/InstructionOperations.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import Foundation /// Scope-bound instruction workflows. Consumers own argument parsing and difference presentation. @@ -98,11 +99,13 @@ public enum InstructionOperations { declaration: declaration, previousDeclaration: previousDeclaration, previous: previous, prepared: prepared, store: store) try plan.lock.validate() + let change = try store.planDeclaration( + declaration, replacing: previousDeclaration, prepared: baseline) if !options.replace { try requireOwnership(plan.report) } try beforeApply?(plan.report) try Self.apply( - declaration: declaration, next: plan.lock, report: plan.report, sources: sources, - baseline: baseline, expectations: plan.expectations) + declaration: declaration, change: change, next: plan.lock, report: plan.report, + sources: sources, baseline: baseline, expectations: plan.expectations) return InstructionAddOutcome(sourceID: id, available: available, result: plan.report) } } @@ -159,6 +162,8 @@ public enum InstructionOperations { try plan.next.validate() try baseline.validate() if apply { + let change = try store.planDeclaration( + declaration, replacing: previousDeclaration, prepared: baseline) if !replace { try requireOwnership(plan.report) } try beforeApply?(plan.report) try baseline.validate() @@ -167,11 +172,8 @@ public enum InstructionOperations { let transaction = FileTransaction(store: store) transaction.requireUnchanged(since: baseline, plan) try plan.stage(transaction: transaction) - try store.stageDeclaration( - declaration, in: transaction, prepared: baseline) - if let data = try plan.next.replacementData( - comparedTo: baseline.bytes(for: store.resolvedURL)) - { + try store.stageDeclaration(change, in: transaction, prepared: baseline) + if let data = try plan.next.replacementData(in: store, prepared: baseline) { try transaction.replace( store.resolvedURL, with: .data(data), expecting: baseline.evidence(for: store.resolvedURL)) @@ -222,7 +224,7 @@ public enum InstructionOperations { hasChanges: targets.changes.contains(where: \.changed)) try requireOwnership(report) try apply( - declaration: declaration, next: lock, report: report, sources: sources, + declaration: declaration, change: nil, next: lock, report: report, sources: sources, baseline: baseline, expectations: targets.expectations, writeState: false) return report } @@ -271,11 +273,13 @@ public enum InstructionOperations { declaration: declaration, previousDeclaration: previousDeclaration, previous: previous, prepared: prepared, store: store) try plan.lock.validate() + let change = try store.planDeclaration( + declaration, replacing: previousDeclaration, prepared: baseline) try requireOwnership(plan.report) try beforeApply?(plan.report) try apply( - declaration: declaration, next: plan.lock, report: plan.report, sources: sources, - baseline: baseline, expectations: plan.expectations) + declaration: declaration, change: change, next: plan.lock, report: plan.report, + sources: sources, baseline: baseline, expectations: plan.expectations) return plan.report } } @@ -316,6 +320,7 @@ public enum InstructionOperations { } let store = StateStore(scope: .project, environment: environment) return try store.withLock { + _ = try store.declarationBytes() let file = environment.projectDirectory.resolvingSymlinksInPath() .appendingPathComponent(InstructionSources.ownContainer) .appendingPathComponent(name + ".md") @@ -420,9 +425,10 @@ public enum InstructionOperations { guard foreign.isEmpty else { throw InstructionError.unownedTargets(foreign) } } + /// `change` is the declaration edit planned before any callback, retention or staging. private static func apply( - declaration: Declaration, next: ResolvedState, report: InstructionUpdateReport, - sources: InstructionSources, baseline: StatePrecondition, + declaration: Declaration, change: DeclarationChange?, next: ResolvedState, + report: InstructionUpdateReport, sources: InstructionSources, baseline: StatePrecondition, expectations: [String: TargetPrecondition], writeState: Bool = true ) throws { let store = sources.store @@ -438,8 +444,8 @@ public enum InstructionOperations { transaction.requireUnchanged(since: baseline, plan) try plan.stage(transaction: transaction) if writeState { - try store.stageDeclaration(declaration, in: transaction, prepared: baseline) - if let data = try next.replacementData(comparedTo: baseline.bytes(for: store.resolvedURL)) { + try store.stageDeclaration(change, in: transaction, prepared: baseline) + if let data = try next.replacementData(in: store, prepared: baseline) { try transaction.replace( store.resolvedURL, with: .data(data), expecting: baseline.evidence(for: store.resolvedURL)) diff --git a/Sources/AgentsManifest/ManifestState.swift b/Sources/AgentsManifest/ManifestState.swift new file mode 100644 index 0000000..98ee488 --- /dev/null +++ b/Sources/AgentsManifest/ManifestState.swift @@ -0,0 +1,106 @@ +import AgentsCore +import AgentsDescription +import Foundation + +/// Declaration access for scope state. Core owns the file, its captured bytes, the missing +/// declaration rule and publication; this module parses, projects and plans edits. Parse, edit +/// and subset failures are `ManifestFailure` diagnostics identified by the declaration path. +extension StateStore { + /// The deployable declaration, or an empty one when the scope has no state. + package func readDeclaration(prepared: StatePrecondition? = nil) throws -> Declaration { + guard let document = try declarationDocument(prepared: prepared) else { return Declaration() } + return try ManifestProjection.declaration(of: document, environment: environment) + } + + /// Plans `next` as an edit of the prepared document that `previous` was read from. Nil means + /// no semantic change. A document that no longer projects to `previous` is a stale + /// preparation. + package func planDeclaration( + _ next: Declaration, replacing previous: Declaration, prepared: StatePrecondition + ) throws -> DeclarationChange? { + let bytes = try declarationBytes(prepared: prepared) + let output: [UInt8]? + do { + output = try DeclarationEditPlan.bytes( + replacing: previous, with: next, in: bytes.map(Array.init), identity: declarationIdentity, + environment: environment) + } catch let failure as ManifestFailure + where failure.diagnostics.contains(where: { $0.code == "manifest.edit.baseline" }) + { + throw CoreError.invalidState("declaration changed during preparation: \(declarationURL.path)") + } + return output.map { DeclarationChange(bytes: Data($0)) } + } + + /// Commits state through the scope journal. Omitting watch preserves its existing bytes. A + /// scope without a declaration document receives one, so the saved lock is never orphaned. + package func save( + declaration: Declaration, resolved: ResolvedState, watch: WatchState? = nil + ) throws { + try withLock { + try declaration.validate(environment: environment) + try resolved.validate() + try watch?.validate() + let baseline = try StatePrecondition(store: self) + let previous = try readDeclaration(prepared: baseline) + _ = try readResolved(prepared: baseline) + var change = try planDeclaration(declaration, replacing: previous, prepared: baseline) + if change == nil, try declarationBytes(prepared: baseline) == nil { + change = DeclarationChange( + bytes: Data( + try CanonicalPrinter().manifest( + DeclarationConstruction.root(declaration).constructionValue))) + } + let transaction = FileTransaction(store: self) + transaction.requireUnchanged(since: baseline) + try stageDeclaration(change, in: transaction, prepared: baseline) + try transaction.replace( + resolvedURL, with: .data(Self.encodeState(resolved.normalized)), + expecting: baseline.evidence(for: resolvedURL)) + if let watch { + try transaction.replace( + watchURL, with: .data(Self.encode(watch)), expecting: baseline.evidence(for: watchURL)) + } + try transaction.commit() + } + } + + /// Reads the deployable declaration under a shared lock, without recovery or creating files. + public func loadDeclaration() throws -> Declaration { + try withReadLock { try readDeclaration() } + } + + /// Reads the complete declaration document under a shared lock, without recovery, creating + /// files or restricting it to the deployable subset. Nil means the scope has no state. + public func loadManifest() throws -> DeclarationDocument? { + try withReadLock { try declarationDocument(prepared: nil) } + } + + private var declarationIdentity: DocumentIdentity { DocumentIdentity(declarationURL.path) } + + private func declarationDocument(prepared: StatePrecondition?) throws -> DeclarationDocument? { + try declarationBytes(prepared: prepared).map { + try DeclarationDocument(bytes: Array($0), identity: declarationIdentity) + } + } +} + +extension DeclarationAccess { + package static var manifest: Self { + Self( + read: { store, prepared in try store.readDeclaration(prepared: prepared) }, + plan: { store, previous, next, prepared in + try store.planDeclaration(next, replacing: previous, prepared: prepared) + }) + } +} + +extension WatchOperations { + public init( + discoverSkills: @escaping @Sendable (URL) throws -> [WatchSkill], + fetchArtifacts: @escaping @Sendable (String) throws -> [WatchArtifact] + ) { + self.init( + discoverSkills: discoverSkills, fetchArtifacts: fetchArtifacts, declarations: .manifest) + } +} diff --git a/Sources/AgentsSkills/SkillLifecycle.swift b/Sources/AgentsSkills/SkillLifecycle.swift index f8f9832..20f69c3 100644 --- a/Sources/AgentsSkills/SkillLifecycle.swift +++ b/Sources/AgentsSkills/SkillLifecycle.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import Foundation struct DiscoveredSource { @@ -34,11 +35,15 @@ final class SkillLifecycle { let provider: WellKnownProvider let workspace: URL let resolutions: SourceResolutionSession? + /// Receives the applying transaction's checkpoints. + let checkpoint: (String) throws -> Void init( - store: StateStore, provider: WellKnownProvider, resolutions: SourceResolutionSession? = nil + store: StateStore, provider: WellKnownProvider, resolutions: SourceResolutionSession? = nil, + checkpoint: @escaping (String) throws -> Void = { _ in } ) throws { self.resolutions = resolutions + self.checkpoint = checkpoint self.store = store self.cache = SourceCache(store: store) self.provider = provider @@ -212,13 +217,20 @@ final class SkillLifecycle { return try PreparedSkill(lock: skill, directory: directory, payloads: payloads) } + /// `declaration` replaces `previousDeclaration`, which was read from `baseline`. Its edit is + /// planned before content retention, so a declaration that cannot be edited fails without + /// side effects. Without `writeState` the declaration and lock stay unchanged. func apply( - declaration: Declaration, previous: ResolvedState, next: ResolvedState, - prepared: [String: PreparedSkill], names: Set, baseline: StatePrecondition, - writeState: Bool = true + declaration: Declaration, replacing previousDeclaration: Declaration, + previous: ResolvedState, next: ResolvedState, prepared: [String: PreparedSkill], + names: Set, baseline: StatePrecondition, writeState: Bool = true ) throws -> [InstallResult] { try declaration.validate(environment: store.environment) try next.validate() + let change = + writeState + ? try store.planDeclaration(declaration, replacing: previousDeclaration, prepared: baseline) + : nil let plan = try SkillUpdatePlan( lifecycle: self, previous: previous, next: next, prepared: prepared, names: names, results: [] ) @@ -226,14 +238,12 @@ final class SkillLifecycle { try baseline.validate() try plan.validate() let retained = try plan.retain() - let transaction = FileTransaction(store: store) + let transaction = FileTransaction(store: store, checkpoint: checkpoint) transaction.requireUnchanged(since: baseline, plan) try plan.stage(retained: retained, transaction: transaction) if writeState { - try store.stageDeclaration(declaration, in: transaction, prepared: baseline) - if let data = try next.replacementData( - comparedTo: baseline.bytes(for: store.resolvedURL)) - { + try store.stageDeclaration(change, in: transaction, prepared: baseline) + if let data = try next.replacementData(in: store, prepared: baseline) { try transaction.replace( store.resolvedURL, with: .data(data), expecting: baseline.evidence(for: store.resolvedURL) ) diff --git a/Sources/AgentsSkills/SkillOperations.swift b/Sources/AgentsSkills/SkillOperations.swift index 7e9a7a6..783bb5c 100644 --- a/Sources/AgentsSkills/SkillOperations.swift +++ b/Sources/AgentsSkills/SkillOperations.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import Foundation public enum SkillOperations { @@ -6,7 +7,17 @@ public enum SkillOperations { try add(options, provider: WellKnownProvider()) } - static func add(_ options: AddOptions, provider: WellKnownProvider) throws -> AddOutcome { + /// Reports the scope lock's and the applying transaction's named checkpoints. + package static func add( + _ options: AddOptions, checkpoint: @escaping (String) throws -> Void + ) throws -> AddOutcome { + try add(options, provider: WellKnownProvider(), checkpoint: checkpoint) + } + + static func add( + _ options: AddOptions, provider: WellKnownProvider, + checkpoint: @escaping (String) throws -> Void = { _ in } + ) throws -> AddOutcome { var options = options if let name = try SourceArgument(options.source).name { guard !options.all else { @@ -20,17 +31,21 @@ public enum SkillOperations { if options.listOnly || outcome.availableSkills.count > 1 { return outcome } automaticSelection = outcome.availableSkills.first.map { (outcome.sourceID, $0.name) } } - return try add(options, provider: provider, apply: true, automaticSelection: automaticSelection) + return try add( + options, provider: provider, apply: true, automaticSelection: automaticSelection, + checkpoint: checkpoint) } private static func add( _ options: AddOptions, provider: WellKnownProvider, apply: Bool, - automaticSelection: (sourceID: String, name: String)? = nil + automaticSelection: (sourceID: String, name: String)? = nil, + checkpoint: @escaping (String) throws -> Void = { _ in } ) throws -> AddOutcome { let store = StateStore(scope: options.scope, environment: options.environment) - return try operate(store, apply: apply) { declaration, lock, baseline in - let lifecycle = try SkillLifecycle(store: store, provider: provider) - var declaration = declaration + return try operate(store, apply: apply, checkpoint: checkpoint) { + previousDeclaration, lock, baseline in + let lifecycle = try SkillLifecycle(store: store, provider: provider, checkpoint: checkpoint) + var declaration = previousDeclaration let selectionChanged = CoreError.invalidState( "automatic skill selection changed during discovery; retry the command") let source: SourceDeclaration @@ -119,8 +134,8 @@ public enum SkillOperations { } try next.validate() let installed = try lifecycle.apply( - declaration: declaration, previous: lock, next: next, prepared: prepared, names: Set(names), - baseline: baseline) + declaration: declaration, replacing: previousDeclaration, previous: lock, next: next, + prepared: prepared, names: Set(names), baseline: baseline) return AddOutcome( source: source, sourceID: id, availableSkills: selected, installed: installed) } @@ -159,11 +174,7 @@ public enum SkillOperations { let transaction = FileTransaction(store: store) transaction.requireUnchanged(since: baseline, plan) try plan.stage(retained: retained, transaction: transaction) - try store.stageDeclaration( - declaration, in: transaction, prepared: baseline) - if let data = try plan.next.replacementData( - comparedTo: baseline.bytes(for: store.resolvedURL)) - { + if let data = try plan.next.replacementData(in: store, prepared: baseline) { try transaction.replace( store.resolvedURL, with: .data(data), expecting: baseline.evidence(for: store.resolvedURL)) @@ -312,8 +323,9 @@ public enum SkillOperations { } return ResolvedInstallReport( installed: try lifecycle.apply( - declaration: declaration, previous: lock, next: lock, prepared: prepared, - names: Set(lock.skills.keys), baseline: baseline, writeState: false)) + declaration: declaration, replacing: declaration, previous: lock, next: lock, + prepared: prepared, names: Set(lock.skills.keys), baseline: baseline, + writeState: false)) } } @@ -323,8 +335,8 @@ public enum SkillOperations { environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> [String] { let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: true) { declaration, lock, baseline in - var declaration = declaration + return try operate(store, apply: true) { previousDeclaration, lock, baseline in + var declaration = previousDeclaration var next = lock let names = Set(skillNames.map(PathSafety.sanitizeName)) guard names.isSubset(of: Set(lock.skills.keys)) else { @@ -361,8 +373,8 @@ public enum SkillOperations { } let lifecycle = try SkillLifecycle(store: store, provider: WellKnownProvider()) _ = try lifecycle.apply( - declaration: declaration, previous: lock, next: next, prepared: [:], names: names, - baseline: baseline) + declaration: declaration, replacing: previousDeclaration, previous: lock, next: next, + prepared: [:], names: names, baseline: baseline) return names.sorted() } } @@ -560,10 +572,11 @@ public enum SkillOperations { } } - private static func operate(_ store: StateStore, apply: Bool, _ body: () throws -> T) throws - -> T - { - if apply { return try store.withLock(body) } + private static func operate( + _ store: StateStore, apply: Bool, checkpoint: @escaping (String) throws -> Void = { _ in }, + _ body: () throws -> T + ) throws -> T { + if apply { return try store.withLock(checkpoint: checkpoint, body) } return try store.withReadLock(body) } @@ -577,10 +590,10 @@ public enum SkillOperations { } private static func operate( - _ store: StateStore, apply: Bool, + _ store: StateStore, apply: Bool, checkpoint: @escaping (String) throws -> Void = { _ in }, _ body: (Declaration, ResolvedState, StatePrecondition) throws -> T ) throws -> T { - try operate(store, apply: apply) { + try operate(store, apply: apply, checkpoint: checkpoint) { let baseline = try StatePrecondition(store: store) return try body( store.readDeclaration(prepared: baseline), store.readResolved(prepared: baseline), baseline) diff --git a/Sources/AgentsSkills/WatchSupport.swift b/Sources/AgentsSkills/WatchSupport.swift index 2dadf7f..68bd79f 100644 --- a/Sources/AgentsSkills/WatchSupport.swift +++ b/Sources/AgentsSkills/WatchSupport.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import Foundation extension SkillOperations { @@ -23,6 +24,7 @@ extension SkillOperations { WatchArtifact( name: $0.installName, artifact: $0.artifact, files: $0.files, payloads: $0.payloads) } - }) + }, + declarations: .manifest) } } diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index dc092c4..6026e00 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsInstructions +import AgentsManifest import AgentsSkills import Foundation @@ -91,11 +92,7 @@ final class UpdatePlan { transaction.requireUnchanged(since: baseline, skills, instructions) try skills.stage(retained: retained, transaction: transaction) try instructions.stage(transaction: transaction) - try store.stageDeclaration( - declaration, in: transaction, prepared: baseline) - if let resolvedBytes = try next.replacementData( - comparedTo: baseline.bytes(for: store.resolvedURL)) - { + if let resolvedBytes = try next.replacementData(in: store, prepared: baseline) { try transaction.replace( store.resolvedURL, with: .data(resolvedBytes), expecting: baseline.evidence(for: store.resolvedURL)) diff --git a/Tests/AgentsCoreTests/CachePublicationTests.swift b/Tests/AgentsCoreTests/CachePublicationTests.swift index 78e36fe..8310f5c 100644 --- a/Tests/AgentsCoreTests/CachePublicationTests.swift +++ b/Tests/AgentsCoreTests/CachePublicationTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import CPlatform import Foundation import StateTestSupport @@ -29,7 +30,7 @@ struct CachePublicationTests { #expect(try FileSnapshot.read(at: fixture.destination) == nil) } #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } #expect(FileManager.default.fileExists(atPath: fixture.destination.path) == committed) #expect(try Data(contentsOf: fixture.store.resolvedURL) == fixture.lockBytes) @@ -53,7 +54,7 @@ struct CachePublicationTests { let fixture = try CacheFixture() try interrupt(fixture, kind: "cache-bytes", point: point) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } let cache = SourceCache(store: fixture.store) let payload = try Data(contentsOf: fixture.root.appendingPathComponent("payload")) @@ -73,7 +74,7 @@ struct CachePublicationTests { try interrupt(fixture, kind: "cache-git", point: point) #expect(try FileSnapshot.read(at: fixture.destination) == nil) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } #expect( try FileManager.default.contentsOfDirectory( diff --git a/Tests/AgentsCoreTests/CheckpointUniquenessTests.swift b/Tests/AgentsCoreTests/CheckpointUniquenessTests.swift index 89eb7af..7c0c3ae 100644 --- a/Tests/AgentsCoreTests/CheckpointUniquenessTests.swift +++ b/Tests/AgentsCoreTests/CheckpointUniquenessTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import Foundation import StateTestSupport import Testing @@ -80,7 +81,7 @@ struct CheckpointUniquenessTests { try ProcessWait.stopped(child, root: interrupted.root) terminateProcess(child) #expect(throws: CoreError.transactionRecovered(interrupted.store.directory.path)) { - try interrupted.store.loadWatch() + try interrupted.store.withLock {} } #expect(try interrupted.store.loadWatch().sources.isEmpty) let contents = interrupted.store.cacheDirectory.appendingPathComponent("artifact-content") diff --git a/Tests/AgentsCoreTests/CoreTestSupport.swift b/Tests/AgentsCoreTests/CoreTestSupport.swift index 9ff8c59..128d5e5 100644 --- a/Tests/AgentsCoreTests/CoreTestSupport.swift +++ b/Tests/AgentsCoreTests/CoreTestSupport.swift @@ -32,6 +32,9 @@ func makeDirectoriesWritable(_ root: URL) { } } +/// The inspection error while automatic recovery is pending. +let pendingRecovery = CoreError.recoveryPending(TransactionRecoveryDiagnostic.pendingMessage) + func initGitRepo(_ repo: URL) throws { try ProcessRunner.run( "/usr/bin/env", arguments: ["git", "init", "--initial-branch=master", repo.path]) diff --git a/Tests/AgentsCoreTests/DeclarationStateTests.swift b/Tests/AgentsCoreTests/DeclarationStateTests.swift new file mode 100644 index 0000000..e588581 --- /dev/null +++ b/Tests/AgentsCoreTests/DeclarationStateTests.swift @@ -0,0 +1,189 @@ +import AgentsManifest +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite("Declaration state") +struct DeclarationStateTests { + @Test(arguments: ["lock", "watch"]) + func stateWithoutADeclarationStopsEveryAccessWithoutWriting(_ kind: String) throws { + let fixture = try ScopeFixture() + let store = fixture.store + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + if kind == "lock" { + try StateStore.encodeState(ResolvedState()).write(to: store.resolvedURL) + } else { + try StateStore.encode(WatchState()).write(to: store.watchURL) + } + let missing = CoreError.missingDeclaration(store.declarationURL.path) + let before = try FileHash.folderHash(fixture.root) + #expect(throws: missing) { try store.loadDeclaration() } + #expect(throws: missing) { try store.loadManifest() } + #expect(throws: missing) { try store.loadResolved() } + #expect(throws: missing) { try store.loadWatch() } + #expect(throws: missing) { try store.readDeclaration() } + #expect(throws: missing) { try store.withLock {} } + #expect(throws: missing) { + try store.save(declaration: Declaration(agents: [.codex]), resolved: ResolvedState()) + } + #expect(try FileHash.folderHash(fixture.root) == before) + + // A writer that already owns the scope lock recovers first, then reaches the same rule. + FileManager.default.createFile(atPath: fixture.scopeLock.path, contents: nil) + let locked = try FileHash.folderHash(fixture.root) + #expect(throws: missing) { try store.withLock { _ = try store.readDeclaration() } } + #expect(throws: missing) { + try store.save(declaration: Declaration(agents: [.codex]), resolved: ResolvedState()) + } + #expect(try FileHash.folderHash(fixture.root) == locked) + } + + @Test func scopeWithoutStateIsEmptyAndADeclarationAloneIsComplete() throws { + let fixture = try ScopeFixture() + let store = fixture.store + let before = try FileHash.folderHash(fixture.root) + #expect(try store.loadDeclaration() == Declaration()) + #expect(try store.loadManifest() == nil) + #expect(try store.loadResolved() == ResolvedState()) + #expect(try store.loadWatch() == WatchState()) + #expect(try FileHash.folderHash(fixture.root) == before) + + let bytes = manifestText("defaultAgents: [.cursor]") + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + try bytes.write(to: store.declarationURL) + let declared = try FileHash.folderHash(fixture.root) + #expect(try store.loadDeclaration() == Declaration(agents: [.cursor])) + #expect(try store.loadManifest()?.bytes == Array(bytes)) + #expect(try store.loadResolved() == ResolvedState()) + #expect(try FileHash.folderHash(fixture.root) == declared) + #expect(try store.withLock { try store.readDeclaration() } == Declaration(agents: [.cursor])) + } + + /// A writer interrupted after moving the declaration aside leaves lock state without a + /// declaration. Readers report the pending recovery without touching any file, and the next + /// writer recovers before the missing-declaration rule applies. + @Test func pendingRecoveryPrecedesTheMissingDeclarationRule() throws { + let fixture = try ScopeFixture() + let store = fixture.store + try store.save(declaration: Declaration(agents: [.cursor]), resolved: ResolvedState()) + struct Interrupted: Error {} + try FileLock.withLock(at: fixture.scopeLock) { + let transaction = FileTransaction(store: store) { point in + if point == TransactionCheckpoint.progress(0, .applied).name || point.hasPrefix("recovery.") + { + throw Interrupted() + } + } + try transaction.delete(store.declarationURL) + #expect(throws: Interrupted.self) { try transaction.commit() } + } + try FileManager.default.removeItem(at: fixture.scopeLock) + let journal = store.directory.appendingPathComponent(TransactionJournal.fileName) + let recorded = try #require(try FileSnapshot.read(at: journal)) + #expect(!FileManager.default.fileExists(atPath: store.declarationURL.path)) + #expect(FileManager.default.fileExists(atPath: store.resolvedURL.path)) + let before = try FileHash.folderHash(fixture.root) + + #expect(throws: pendingRecovery) { try store.loadDeclaration() } + #expect(throws: pendingRecovery) { try store.loadManifest() } + #expect(throws: pendingRecovery) { try store.loadResolved() } + #expect(throws: pendingRecovery) { try store.loadWatch() } + #expect(try FileSnapshot.read(at: journal) == recorded) + #expect(try FileHash.folderHash(fixture.root) == before) + + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + #expect(try store.loadDeclaration() == Declaration(agents: [.cursor])) + #expect(!FileManager.default.fileExists(atPath: journal.path)) + } + + /// Planning from a declaration that the prepared document no longer projects to is a stale + /// preparation, and nothing is planned over the other writer's intent. + @Test func planningFromAnotherGenerationIsAStalePreparation() throws { + let fixture = try ScopeFixture() + let store = fixture.store + try store.save(declaration: Declaration(agents: [.cursor]), resolved: ResolvedState()) + let baseline = try StatePrecondition(store: store) + #expect( + throws: CoreError.invalidState( + "declaration changed during preparation: \(store.declarationURL.path)") + ) { + try store.planDeclaration( + Declaration(agents: [.codex]), replacing: Declaration(), prepared: baseline) + } + #expect( + try store.planDeclaration( + Declaration(agents: [.cursor]), replacing: Declaration(agents: [.cursor]), + prepared: baseline) == nil) + } + + /// A first add killed after publishing the lock but before its commit is recovered by the + /// next writer; neither readers nor writers report a missing declaration. + @Test func interruptedFirstCreationIsPendingRecoveryNotAMissingDeclaration() throws { + let fixture = try StateOperationFixture(.freshSkillAdd) + let store = fixture.store + terminateProcess( + try fixture.pause("skill-add", at: TransactionCheckpoint.publication(2, .created).name)) + #expect(FileManager.default.fileExists(atPath: store.resolvedURL.path)) + #expect(throws: pendingRecovery) { try store.loadDeclaration() } + #expect(throws: pendingRecovery) { try store.loadResolved() } + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + try fixture.check(committed: false) + } + + /// Ref reconciliation reads watch state and the lock only, so an unreadable declaration + /// cannot hold it back. + @Test func watchReferenceRecoveryDoesNotReadTheDeclaration() throws { + let fixture = try WatchGitFixture() + try fixture.watch.add("source", environment: fixture.environment) + let stale = try fixture.head() + try fixture.rewrite("second") + try fixture.watch.seen("source", environment: fixture.environment) + let current = try fixture.head() + try fixture.mirrorGit(["update-ref", "refs/agents-watch/" + stale, stale]) + let marker = fixture.store.directory.appendingPathComponent("watch-refs.pending") + try Data().write(to: marker) + let unreadable = Data("let agents = \n".utf8) + try unreadable.write(to: fixture.store.declarationURL) + + #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { + try fixture.store.withLock {} + } + #expect(try fixture.watchRefs() == [current]) + #expect(!FileManager.default.fileExists(atPath: marker.path)) + #expect(try Data(contentsOf: fixture.store.declarationURL) == unreadable) + #expect(throws: ManifestFailure.self) { try fixture.store.loadDeclaration() } + } + + @Test func stateTransactionsAcceptOnlyTheCurrentStateFiles() throws { + let fixture = try ScopeFixture() + let paths = TransactionPaths(store: fixture.store) + #expect(try paths.path(for: fixture.store.declarationURL) == "state/Agents.swift") + for name in ["Agents.swift", "agents.resolved", "agents.watch"] { + #expect(try paths.components("state/" + name).descendants == [name]) + } + for name in ["other.json", "agents.swift", "Agents.swift.new"] { + #expect(throws: CoreError.unsafePath("unmanaged state transaction path")) { + try paths.components("state/" + name) + } + } + } +} + +private final class ScopeFixture { + let root: URL + let store: StateStore + var scopeLock: URL { store.directory.appendingPathComponent(".agents.lock") } + + init() throws { + root = try temporaryDirectory() + store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: [:])) + } + + deinit { removeTemporaryDirectory(root) } +} diff --git a/Tests/AgentsCoreTests/GitErrorTests.swift b/Tests/AgentsCoreTests/GitErrorTests.swift index c4c736f..3a378aa 100644 --- a/Tests/AgentsCoreTests/GitErrorTests.swift +++ b/Tests/AgentsCoreTests/GitErrorTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import Foundation import Testing @@ -144,11 +145,15 @@ struct GitErrorTests { try initGitRepo(upstream) let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) let source = SourceDeclaration(kind: .local, location: upstream.path) - try store.save(declaration: Declaration(sources: ["source": source]), resolved: ResolvedState()) + let id = try source.identity(environment: store.environment) + // Recovery knows a source location from the lock or watch state, never the declaration. + try store.save( + declaration: Declaration(sources: ["source": source]), + resolved: ResolvedState(sources: [id: LockedSource(kind: .local)])) let cache = SourceCache(store: store) _ = try cache.resolve(source) try cache.beginWatchReferenceUpdate() - let mirror = cache.mirrorURL(sourceID: try source.identity(environment: store.environment)) + let mirror = cache.mirrorURL(sourceID: id) try Data("[invalid\n".utf8).write(to: mirror.appendingPathComponent("config")) let error = try #require(throws: GitError.self) { try cache.recoverWatchReferences() } diff --git a/Tests/AgentsCoreTests/InstructionTransactionTests.swift b/Tests/AgentsCoreTests/InstructionTransactionTests.swift index 7e120d7..e901cb4 100644 --- a/Tests/AgentsCoreTests/InstructionTransactionTests.swift +++ b/Tests/AgentsCoreTests/InstructionTransactionTests.swift @@ -1,4 +1,6 @@ +import AgentsManifest import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -36,7 +38,7 @@ struct InstructionTransactionTests { try transaction.replace(file.resolvingSymlinksInPath(), with: .data(Data("new".utf8))) } try transaction.replace( - store.declarationURL, with: .data(StateStore.encode(Declaration(agents: [.codex])))) + store.declarationURL, with: .data(manifestText("defaultAgents: [.codex]"))) #expect(throws: Interrupted.self) { try transaction.commit() } } for file in files { #expect(try Data(contentsOf: file) == Data("original".utf8)) } diff --git a/Tests/AgentsCoreTests/PreparationEvidenceTests.swift b/Tests/AgentsCoreTests/PreparationEvidenceTests.swift index c080be9..5a01bc9 100644 --- a/Tests/AgentsCoreTests/PreparationEvidenceTests.swift +++ b/Tests/AgentsCoreTests/PreparationEvidenceTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import Foundation import Testing diff --git a/Tests/AgentsCoreTests/PublicationTests.swift b/Tests/AgentsCoreTests/PublicationTests.swift index db5aec7..9593d5a 100644 --- a/Tests/AgentsCoreTests/PublicationTests.swift +++ b/Tests/AgentsCoreTests/PublicationTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import CPlatform import Foundation import StateTestSupport @@ -376,7 +377,7 @@ struct PublicationTests { "transaction conflict at instructions-project/AGENTS.md: \(reason); retained container: \(location)" ) ) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } #expect(try FileSnapshot.read(at: fixture.root) == before) } @@ -389,12 +390,14 @@ struct PublicationTests { let directory = try #require(try fixture.store.openDirectoryIfPresent()) let backup = directory.url.appendingPathComponent(".agents-\(id.uuidString)-0.old") try FileManager.default.moveItem(at: fixture.store.declarationURL, to: backup) - try Data("{\"agents\":[\"codex\"]}".utf8).write(to: fixture.store.declarationURL) + try manifestText("defaultAgents: [.codex]").write(to: fixture.store.declarationURL) var old = try StateStore.encode( LegacyJournal( id: id, scope: directory.identity, roots: ["state": directory.identity], phase: "applying", - entries: [.init(path: "state/agents.json", existed: true, replacement: true)])) + entries: [ + .init(path: "state/" + StateStore.declarationFileName, existed: true, replacement: true) + ])) if let version { var encoded = try #require(JSONSerialization.jsonObject(with: old) as? [String: Any]) encoded["version"] = version @@ -407,7 +410,7 @@ struct PublicationTests { "transaction journal was written by another version; recover it with the version that wrote it (journal version: \(version.map(String.init) ?? "missing"))" ) ) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } #expect(try FileSnapshot.read(at: fixture.root) == before) let diagnostic = FileTransaction.recoveryDiagnostic(store: fixture.store) @@ -434,7 +437,7 @@ struct PublicationTests { field == "identity" ? "sealed operation is missing private container identity" : "terminal container is missing user-object disposal evidence") - ) { try fixture.store.loadResolved() } + ) { try fixture.store.withLock {} } #expect(try FileSnapshot.read(at: fixture.root) == before) } @@ -446,7 +449,7 @@ struct PublicationTests { let transaction = FileTransaction(store: fixture.store) let target = try cache.artifactURL(digest: digest) try transaction.replace(target, with: .data(bytes), expectedHash: digest) - try Data("{\"agents\":[]}".utf8).write(to: fixture.store.declarationURL) + try manifestText("defaultAgents: []").write(to: fixture.store.declarationURL) let state = try FileSnapshot.read(at: fixture.store.declarationURL) try transaction.commit() #expect(try Data(contentsOf: target) == bytes) diff --git a/Tests/AgentsCoreTests/SourceCacheTests.swift b/Tests/AgentsCoreTests/SourceCacheTests.swift index f0122e9..e18be18 100644 --- a/Tests/AgentsCoreTests/SourceCacheTests.swift +++ b/Tests/AgentsCoreTests/SourceCacheTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import Foundation import Testing diff --git a/Tests/AgentsCoreTests/StateEncodingTests.swift b/Tests/AgentsCoreTests/StateEncodingTests.swift index caf5e23..4c0ef85 100644 --- a/Tests/AgentsCoreTests/StateEncodingTests.swift +++ b/Tests/AgentsCoreTests/StateEncodingTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import Foundation import Testing @@ -5,7 +6,7 @@ import Testing @Suite("State JSON encoding") struct StateEncodingTests { - @Test(arguments: ["agents.json", "agents.resolved", "transaction.json"]) + @Test(arguments: ["agents.resolved", "transaction.json"]) func rejectsEncodedDocumentsWithoutChangingFiles(_ name: String) throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } @@ -15,8 +16,6 @@ struct StateEncodingTests { let resolved = try Data(contentsOf: store.resolvedURL) let json: String switch name { - case "agents.json": - json = #"{"sources":{"same":{"local":"/a"},"same":{"local":"/b"}}}"# case "agents.resolved": json = String(decoding: resolved, as: UTF8.self) default: let directory = try #require(try store.openDirectoryIfPresent()) @@ -36,20 +35,12 @@ struct StateEncodingTests { for data in encodings { let url = store.directory.appendingPathComponent(name) try data.write(to: url) - #expect(throws: (any Error).self) { - if name == "agents.json" { - _ = try store.loadDeclaration() - } else { - _ = try store.loadResolved() - } - } + #expect(throws: (any Error).self) { _ = try store.loadResolved() } #expect(throws: (any Error).self) { try store.save(declaration: Declaration(), resolved: ResolvedState()) } #expect(try Data(contentsOf: url) == data) - if name != "agents.json" { - #expect(try Data(contentsOf: store.declarationURL) == declaration) - } + #expect(try Data(contentsOf: store.declarationURL) == declaration) if name != "agents.resolved" { #expect(try Data(contentsOf: store.resolvedURL) == resolved) } } } diff --git a/Tests/AgentsCoreTests/StateInspectionTests.swift b/Tests/AgentsCoreTests/StateInspectionTests.swift index d6767ae..fef4417 100644 --- a/Tests/AgentsCoreTests/StateInspectionTests.swift +++ b/Tests/AgentsCoreTests/StateInspectionTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import Foundation import Testing @@ -82,9 +83,8 @@ struct StateInspectionTests { atPath: fixture.store.directory.appendingPathComponent(".agents.lock").path)) var reads = 0 var interruptedState: String? - let pending = CoreError.invalidState("transaction recovery is required before inspection") - #expect(throws: pending) { + #expect(throws: pendingRecovery) { try fixture.store.withReadLock { reads += 1 let child = try stateTestProcess( diff --git a/Tests/AgentsCoreTests/StateModelTests.swift b/Tests/AgentsCoreTests/StateModelTests.swift index 5dc05c5..1f7c02b 100644 --- a/Tests/AgentsCoreTests/StateModelTests.swift +++ b/Tests/AgentsCoreTests/StateModelTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import Foundation import Testing @@ -97,7 +98,10 @@ struct StateModelTests { try store.save(declaration: declaration, resolved: lock) #expect(try Data(contentsOf: store.resolvedURL) == first) #expect(try Data(contentsOf: store.declarationURL) == firstDeclaration) - #expect(try store.loadDeclaration() == declaration) + // The document spells the Git location as a URL; the projection keeps its meaning. + #expect( + ManifestProjection.equivalent( + try store.loadDeclaration(), declaration, environment: environment)) #expect(try store.loadResolved() == lock) #expect(String(decoding: first, as: UTF8.self).contains("\"from\": \"1.0.0\"")) } @@ -141,23 +145,10 @@ struct StateModelTests { StateStore(scope: .user, environment: environment).resolvedURL.path == "/home/test/.agents/agents.resolved") } - - @Test(arguments: [ - #"{"git":"github.com/a/b","local":"/a"}"#, - #"{"git":"github.com/a/b","from":"1.0.0","exact":"2.0.0"}"#, #"{"local":"/a","to":"2.0.0"}"#, - ]) - func rejectsAmbiguousSources(_ json: String) { - #expect(throws: (any Error).self) { - try JSONDecoder().decode(SourceDeclaration.self, from: Data(json.utf8)) - } - } } extension StateModelTests { @Test(arguments: [ - #"{"sources":{"same":{"local":"/a"},"same":{"local":"/b"}}}"#, - #"{"sources":{"same":{"local":"/a"},"sa\u006de":{"local":"/b"}}}"#, - #"{"sources":{},"skills":{"demo":{"select":"all"},"demo":{"select":[]}}}"#, #"{"version":1,"sources":{},"skills":{"demo":{},"demo":{}},"instructions":{"sections":[],"chatgpt":{},"targets":{}}}"#, #"{"version":1,"sources":{},"skills":{"demo":{"source":"local:/a","installs":{"codex":"link","codex":"copy"}}},"instructions":{"sections":[],"chatgpt":{},"targets":{}}}"#, ]) @@ -166,32 +157,14 @@ extension StateModelTests { defer { removeTemporaryDirectory(root) } let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) try store.save(declaration: Declaration(), resolved: ResolvedState()) - let url = json.contains("version") ? store.resolvedURL : store.declarationURL - try Data(json.utf8).write(to: url) + try Data(json.utf8).write(to: store.resolvedURL) let beforeDeclaration = try Data(contentsOf: store.declarationURL) let beforeLock = try Data(contentsOf: store.resolvedURL) - #expect(throws: CoreError.self) { - if url == store.resolvedURL { - _ = try store.loadResolved() - } else { - _ = try store.loadDeclaration() - } - } + #expect(throws: CoreError.self) { _ = try store.loadResolved() } #expect(throws: CoreError.self) { try store.save(declaration: Declaration(), resolved: ResolvedState()) } #expect(try Data(contentsOf: store.declarationURL) == beforeDeclaration) #expect(try Data(contentsOf: store.resolvedURL) == beforeLock) } - - @Test func rejectsUnknownFieldsInsteadOfDiscardingIntent() throws { - let root = try temporaryDirectory() - defer { removeTemporaryDirectory(root) } - let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) - try store.save(declaration: Declaration(), resolved: ResolvedState()) - let bytes = Data(#"{"sources":{},"unexpected":{"intent":true}}"#.utf8) - try bytes.write(to: store.declarationURL) - #expect(throws: CoreError.self) { try store.loadDeclaration() } - #expect(try Data(contentsOf: store.declarationURL) == bytes) - } } diff --git a/Tests/AgentsCoreTests/StatePublicationTests.swift b/Tests/AgentsCoreTests/StatePublicationTests.swift new file mode 100644 index 0000000..a5c3f73 --- /dev/null +++ b/Tests/AgentsCoreTests/StatePublicationTests.swift @@ -0,0 +1,322 @@ +import AgentsManifest +import CPlatform +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +/// Domain operations whose single journal creates the declaration with the state beside it. +/// Killing them or their recovery at any recorded point leaves either no scope state or the +/// complete new generation, with declaration, lock, watch state and targets in agreement. +@Suite("State operation publication") +struct StatePublicationTests { + @Test(arguments: StateOperationMatrix.publications) + func killedOperationRecoversOneGeneration(_ fault: StateOperationFault) throws { + try fault.checkSetup() + let fixture = try StateOperationFixture(fault.operation) + terminateProcess(try fixture.pause(fault.operation.command, at: fault.point)) + try fixture.recover() + try fixture.check(committed: fault.committed) + } + + @Test(arguments: StateOperationMatrix.recoveries) + func recoveryCanBeKilledAtEachStageAndRepeated(_ fault: StateOperationFault) throws { + try fault.checkSetup() + let fixture = try StateOperationFixture(fault.operation) + terminateProcess(try fixture.pause(fault.operation.command, at: fault.seed!)) + terminateProcess(try fixture.pause("publication-recover", at: fault.point)) + try fixture.recover() + try fixture.check(committed: fault.committed) + } + + /// A writer waiting for the scope lock prepares from the generation the holder committed, so + /// neither declaration change is lost. + @Test func serializedWritersKeepBothDeclarationChanges() throws { + let fixture = try StateOperationFixture(.watchAdd) + let watch = try fixture.pause("watch-add", at: "watch.mirror.fetched") + defer { terminateProcess(watch) } + let skill = try fixture.launch("skill-add", at: "never") + defer { terminateProcess(skill) } + Thread.sleep(forTimeInterval: 0.2) + #expect(skill.isRunning) + try FileManager.default.removeItem(at: fixture.root.appendingPathComponent("ready")) + kill(watch.processIdentifier, SIGCONT) + for child in [watch, skill] { + try ProcessWait.exit(child, root: fixture.root) + #expect(child.terminationStatus == 0) + } + let declaration = try fixture.store.loadDeclaration() + #expect(declaration.sources.keys.sorted() == ["source"]) + #expect(declaration.watch == ["source"]) + #expect(declaration.skills?["source"]?.select == .names(["demo"])) + #expect(try fixture.store.loadResolved().skills.keys.sorted() == ["demo"]) + #expect(try fixture.store.loadWatch().sources.count == 1) + } +} + +enum StateOperation: String, CaseIterable, Sendable { + /// A first skill add creates the declaration, the lock and an installation target. + case freshSkillAdd + /// A first watch subscription creates the declaration and watch state. + case watchAdd + + var command: String { self == .freshSkillAdd ? "skill-add" : "watch-add" } + + /// Journal entries in request order; the declaration is created by entry `declaration`. + var entries: Int { self == .freshSkillAdd ? 3 : 2 } + var declaration: Int { self == .freshSkillAdd ? 1 : 0 } + + /// Recovery starts from sealed staging, a published declaration, every applied entry, the + /// committed marker and terminal disposal. + var recoverySeeds: [RecoverySeed] { + [ + RecoverySeed(point: TransactionCheckpoint.progress(entries - 1, .ready).name), + RecoverySeed( + point: TransactionCheckpoint.publication(declaration, .created).name, renamed: true), + RecoverySeed( + point: TransactionCheckpoint.progress(entries - 1, .applied).name, renamed: true), + RecoverySeed( + point: TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, + committed: true), + RecoverySeed(point: TransactionCheckpoint.disposalIntent.name, committed: true), + ] + } + + func requiredRecoveryPoints(from seed: RecoverySeed) -> Set { + var points = [ + TransactionCheckpoint.journalSynced.name, TransactionCheckpoint.journalRemoved.name, + ] + if !seed.committed { + points.append(TransactionCheckpoint.persisted(.rolledBack, .terminal, .renamed).name) + } + if seed.renamed { + points.append(TransactionCheckpoint.restoration(declaration, .withdrawn).name) + } + return Set(points) + } +} + +struct StateOperationFault: Sendable, CustomTestStringConvertible { + let operation: StateOperation + let point: String + var committed = false + var seed: String? + var setupFailure: String? + var testDescription: String { + "\(operation.rawValue), \(seed.map { "from \($0), " } ?? "")\(point)" + } + func checkSetup() throws { + if let setupFailure { + throw CoreError.invalidState("checkpoint recording failed: " + setupFailure) + } + } +} + +/// Kill points recorded from real traces. By default each operation is killed at +/// representative points, and its recovery at durable steps from each seeded interruption; +/// `AGENTS_PUBLICATION_MATRIX=full` kills at every recorded point. +enum StateOperationMatrix { + static let complete = ProcessInfo.processInfo.environment["AGENTS_PUBLICATION_MATRIX"] == "full" + static let publications = record(recovery: false) + static let recoveries = record(recovery: true) + + /// Every recovery seed, the first durable intent, the last synced publication, container + /// removal, and for watch subscriptions the acknowledged fetch and the ref reconciliation + /// that follows the commit. + private static func representativePublication(_ operation: StateOperation) -> Set { + var points = + operation.recoverySeeds.map(\.point) + [ + TransactionCheckpoint.progress(0, .publishing).name, + TransactionCheckpoint.publication(operation.entries - 1, .synced).name, + TransactionCheckpoint.phase(.committed).name, + TransactionCheckpoint.containerRemoved(0).name, + ] + if operation == .watchAdd { + points += ["watch.mirror.fetched", "watch.references.pending", "watch.references.0.synced"] + } + return Set(points) + } + + /// The observed-journal barrier, each durable recovery write, each creation's withdrawal and + /// its barrier, disposal and the ref reconciliation that follows recovery. + private static func representativeRecovery(_ operation: StateOperation) -> Set { + var points: [TransactionCheckpoint] = [.journalSynced, .containerRemoved(0), .journalRemoved] + for phase in [TransactionJournal.Phase.applying, .committed, .rolledBack] { + points += [.persisted(phase, .terminal, .renamed), .persisted(phase, .disposing, .renamed)] + for index in 0.. [StateOperationFault] { + var cases: [StateOperationFault] = [] + let commitMarker = TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name + for operation in StateOperation.allCases { + let selected = + recovery ? representativeRecovery(operation) : representativePublication(operation) + let seeds: [RecoverySeed?] = recovery ? operation.recoverySeeds.map { $0 } : [nil] + for seed in seeds { + do { + let fixture = try StateOperationFixture(operation) + if let seed { terminateProcess(try fixture.pause(operation.command, at: seed.point)) } + let command = recovery ? "publication-recover" : operation.command + let child = try fixture.launch(command, at: "never") + defer { terminateProcess(child) } + try ProcessWait.exit(child, root: fixture.root) + guard child.terminationStatus == 0 else { + throw CoreError.invalidState("checkpoint recorder exited \(child.terminationStatus)") + } + let trace = try fixture.trace(child) + guard !trace.isEmpty, Set(trace).count == trace.count else { + throw CoreError.invalidState("checkpoint names are empty or repeated") + } + let required = + seed.map(operation.requiredRecoveryPoints(from:)) + ?? representativePublication(operation) + if !required.isSubset(of: trace) { + throw CoreError.invalidState( + "representative points were not recorded: \(required.subtracting(trace).sorted())") + } + var committed = seed?.committed ?? false + for point in trace { + if point == commitMarker { committed = true } + guard complete || selected.contains(point) else { continue } + cases.append( + StateOperationFault( + operation: operation, point: point, committed: committed, seed: seed?.point)) + } + } catch { + cases.append( + StateOperationFault( + operation: operation, point: "recording", seed: seed?.point, + setupFailure: String(describing: error))) + } + } + } + return cases + } +} + +final class StateOperationFixture { + let operation: StateOperation + let root: URL + let source: URL + let store: StateStore + let target: URL + + init(_ operation: StateOperation) throws { + self.operation = operation + root = try temporaryDirectory() + source = root.appendingPathComponent("source") + store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: ["CLAUDE_CONFIG_DIR": root.appendingPathComponent("configured-claude").path] + )) + target = AgentRegistry.installSkillsDirectory( + for: .codex, scope: .project, environment: store.environment + ).appendingPathComponent("demo") + do { + let skill = source.appendingPathComponent("skills/demo") + try FileManager.default.createDirectory(at: skill, withIntermediateDirectories: true) + try Data("---\nname: demo\ndescription: Fixture skill.\n---\nBody\n".utf8).write( + to: skill.appendingPathComponent("SKILL.md")) + try initGitRepo(source) + } catch { + removeTemporaryDirectory(root) + throw error + } + } + + deinit { removeTemporaryDirectory(root) } + + func launch(_ command: String, at point: String) throws -> Process { + try stateTestProcess(root: root, arguments: [command, point]) + } + + func pause(_ command: String, at point: String) throws -> Process { + let marker = root.appendingPathComponent( + command == "publication-recover" ? "recovery-ready" : "ready") + try? FileManager.default.removeItem(at: marker) + let child = try launch(command, at: point) + do { + try ProcessWait.marker(marker, child: child, root: root) + try ProcessWait.stopped(child, root: root) + return child + } catch { + terminateProcess(child) + throw error + } + } + + func trace(_ child: Process) throws -> [String] { + try String( + contentsOf: root.appendingPathComponent("checkpoint-\(child.processIdentifier).log"), + encoding: .utf8 + ).split(separator: "\n").map(String.init) + } + + /// Recovers as the next writer would; repeating it finds nothing left to recover. + func recover() throws { + do { try store.withLock {} } catch CoreError.transactionRecovered {} + try store.withLock {} + } + + func check(committed: Bool) throws { + #expect(try store.openDirectoryIfPresent()?.info(TransactionJournal.fileName) == nil) + #expect(try store.openDirectoryIfPresent()?.info("watch-refs.pending") == nil) + let declaration = try store.loadDeclaration() + let lock = try store.loadResolved() + let watch = try store.loadWatch() + let present = { (url: URL) in FileManager.default.fileExists(atPath: url.path) } + guard committed else { + for url in [store.declarationURL, store.resolvedURL, store.watchURL] { + #expect(!present(url)) + } + #expect((try? FileManager.default.destinationOfSymbolicLink(atPath: target.path)) == nil) + #expect(declaration == Declaration()) + return + } + let id = try SourceDeclaration(kind: .local, location: source.path).identity( + environment: store.environment) + #expect(declaration.sources.keys.sorted() == ["source"]) + #expect(try declaration.sources["source"]?.identity(environment: store.environment) == id) + switch operation { + case .freshSkillAdd: + #expect( + declaration.skills == [ + "source": SkillDeclaration(select: .names(["demo"]), agents: [.codex], mode: .edit) + ]) + #expect(declaration.watch == nil) + #expect(lock.skills["demo"]?.source == id) + #expect(lock.skills["demo"]?.installs == ["codex": .edit]) + #expect(lock.sources[id] == LockedSource(kind: .local)) + #expect( + target.resolvingSymlinksInPath() + == source.appendingPathComponent("skills/demo").resolvingSymlinksInPath()) + #expect(!present(store.watchURL)) + case .watchAdd: + #expect(declaration.skills == nil) + #expect(declaration.watch == ["source"]) + #expect(watch.sources[id]?.seen == .revision(try gitHead(source))) + #expect(lock == ResolvedState()) + #expect(!present(store.resolvedURL)) + } + let parents = [store.directory, target.deletingLastPathComponent()] + for parent in parents where present(parent) { + #expect( + try !FileManager.default.contentsOfDirectory(atPath: parent.path).contains { + $0.hasPrefix(".agents-") + }) + } + } +} diff --git a/Tests/AgentsCoreTests/StateTransactionTests.swift b/Tests/AgentsCoreTests/StateTransactionTests.swift index 3e80ffa..c3c855f 100644 --- a/Tests/AgentsCoreTests/StateTransactionTests.swift +++ b/Tests/AgentsCoreTests/StateTransactionTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import CPlatform import Foundation import StateTestSupport @@ -80,7 +81,7 @@ struct StateTransactionTests { TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, TransactionCheckpoint.phase(.committed).name, TransactionCheckpoint.containerRemoved(0).name, ]) - func killedWriterRecoversOnNextStateRead(_ step: String) throws { + func killedWriterIsReportedToReadersAndRecoveredByTheNextWriter(_ step: String) throws { let fixture = try TransactionFixture() let child = try stateTestProcess(root: fixture.root, arguments: ["crash", step]) defer { terminateProcess(child) } @@ -92,8 +93,9 @@ struct StateTransactionTests { atPath: fixture.root.appendingPathComponent(".agents/skills/target/SKILL.md").path)) terminateProcess(child) #expect(child.terminationReason == .uncaughtSignal) + #expect(throws: pendingRecovery) { try fixture.store.loadResolved() } #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - _ = try fixture.store.loadResolved() + try fixture.store.withLock {} } let committed = [ TransactionCheckpoint.persisted(.committed, .terminal, .renamed), @@ -148,7 +150,7 @@ final class TransactionFixture { root.appendingPathComponent(".agents/skills/target"), with: .copy(root.appendingPathComponent("new"))) try transaction.replace( - store.declarationURL, with: .data(StateStore.encode(Declaration(agents: [.codex])))) + store.declarationURL, with: .data(manifestText("defaultAgents: [.codex]"))) try transaction.replace( store.resolvedURL, with: .data( @@ -162,7 +164,9 @@ final class TransactionFixture { try transaction.commit() } } + /// Recovers as the next writer would, then compares the selected generation. func check(committed: Bool) throws { + do { try store.withLock {} } catch CoreError.transactionRecovered {} #expect( try Data(contentsOf: root.appendingPathComponent("AGENTS.md")) == Data((committed ? "new instructions" : "old instructions").utf8)) @@ -192,7 +196,7 @@ extension StateTransactionTests { let staging = store.directory.appendingPathComponent("transaction.new") try Data("partial journal".utf8).write(to: staging) #expect(throws: CoreError.transactionRecovered(store.directory.path)) { - try store.loadDeclaration() + try store.withLock {} } #expect(try Data(contentsOf: store.resolvedURL) == before) #expect(!FileManager.default.fileExists(atPath: staging.path)) @@ -211,6 +215,10 @@ extension StateTransactionTests { let journal = store.directory.appendingPathComponent("transaction.json") try Data(json.utf8).write(to: journal) #expect { try store.loadResolved() } throws: { error in + guard case CoreError.recoveryPending(let message) = error else { return false } + return message.hasPrefix(TransactionRecoveryDiagnostic.conflictMessage) + } + #expect { try store.withLock {} } throws: { error in if json == "{broken" { let error = error as NSError return error.domain == NSCocoaErrorDomain && error.code == 3840 @@ -339,7 +347,7 @@ extension StateTransactionTests { } terminateProcess(recovery) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } try fixture.check(committed: true) } @@ -355,7 +363,7 @@ extension StateTransactionTests { try Data("keep".utf8).write(to: victim.appendingPathComponent("sentinel")) let maliciousPaths = [ victim.path, "file://" + victim.path, "state/../../Documents/victim", "state/cache/../victim", - "state/agents.json/child", "codex/../victim", "codex/other/child", "unknown/victim", + "state/Agents.swift/child", "codex/../victim", "codex/other/child", "unknown/victim", "state/cache/artifact-content/../../victim", ] for path in maliciousPaths { @@ -374,14 +382,14 @@ extension StateTransactionTests { } else { expected = .unsafePath("unmanaged installation transaction path") } - #expect(throws: expected) { try fixture.store.loadResolved() } + #expect(throws: expected) { try fixture.store.withLock {} } #expect(try FileSnapshot.read(at: fixture.root) == snapshot) } var directories = try #require(JSONSerialization.jsonObject(with: original) as? [String: Any]) directories["directories"] = [victim.absoluteString] try JSONSerialization.data(withJSONObject: directories).write(to: journalURL) let directorySnapshot = try FileSnapshot.read(at: fixture.root) - #expect { try fixture.store.loadResolved() } throws: { error in + #expect { try fixture.store.withLock {} } throws: { error in guard case CoreError.invalidState(let reason) = error else { return false } return reason.contains("unknown state field: directories") } @@ -396,14 +404,14 @@ extension StateTransactionTests { throws: CoreError.invalidState( "transaction journal was written by another version; recover it with the version that wrote it (journal version: missing)" ) - ) { try fixture.store.loadResolved() } + ) { try fixture.store.withLock {} } #expect( try String(contentsOf: victim.appendingPathComponent("sentinel"), encoding: .utf8) == "keep") try FileManager.default.removeItem(at: victim.deletingLastPathComponent()) try original.write(to: journalURL) #expect(try FileSnapshot.read(at: fixture.root) == before) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } } @@ -425,7 +433,7 @@ extension StateTransactionTests { } try StateStore.encode(journal).write(to: url) let before = try FileSnapshot.read(at: fixture.root) - #expect { try fixture.store.loadResolved() } throws: { error in + #expect { try fixture.store.withLock {} } throws: { error in guard case CoreError.invalidState(let reason) = error else { return false } return reason.contains("state/cache/materialized/source/pin: overlapping destinations") } @@ -443,7 +451,7 @@ extension StateTransactionTests { let copyHash = try FileSnapshot.read(at: copy) let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: copy)) #expect(throws: CoreError.invalidState("transaction root identity changed")) { - try store.loadDeclaration() + try store.withLock {} } #expect(try FileSnapshot.read(at: fixture.root) == originalHash) #expect(try FileSnapshot.read(at: copy) == copyHash) @@ -466,7 +474,7 @@ extension StateTransactionTests { try FileManager.default.moveItem(at: original, to: external) try FileManager.default.createSymbolicLink(at: original, withDestinationURL: external) let snapshot = try FileSnapshot.read(at: fixture.root) - #expect { try fixture.store.loadResolved() } throws: { error in + #expect { try fixture.store.withLock {} } throws: { error in if component == "agent" { return error as? CoreError == .invalidState("transaction root identity changed") } @@ -496,7 +504,7 @@ extension StateTransactionTests { for (index, bytes) in encodings.enumerated() { try bytes.write(to: url) let snapshot = try FileSnapshot.read(at: fixture.root) - #expect { try fixture.store.loadResolved() } throws: { error in + #expect { try fixture.store.withLock {} } throws: { error in if index < 4 { return error as? CoreError == .invalidState("JSON must be UTF-8 without a byte order mark") @@ -509,11 +517,11 @@ extension StateTransactionTests { } try Data(duplicate.utf8).write(to: url) #expect(throws: CoreError.invalidState("duplicate JSON key: phase")) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } try original.write(to: url) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } try fixture.check(committed: false) } @@ -608,7 +616,7 @@ extension StateTransactionTests { try transaction.replace(target, with: .copy(fixture.root.appendingPathComponent("new"))) } try transaction.replace( - store.declarationURL, with: .data(StateStore.encode(Declaration(agents: [.codex])))) + store.declarationURL, with: .data(manifestText("defaultAgents: [.codex]"))) try transaction.replace( store.resolvedURL, with: .data( diff --git a/Tests/AgentsCoreTests/TransactionCostTests.swift b/Tests/AgentsCoreTests/TransactionCostTests.swift index 12e93d2..5fab812 100644 --- a/Tests/AgentsCoreTests/TransactionCostTests.swift +++ b/Tests/AgentsCoreTests/TransactionCostTests.swift @@ -1,4 +1,6 @@ +import AgentsManifest import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -52,7 +54,7 @@ struct TransactionCostTests { try transaction.replace( root.appendingPathComponent("AGENTS.md"), with: .data(Data("after".utf8))) try transaction.replace( - store.declarationURL, with: .data(StateStore.encode(Declaration(agents: [.codex])))) + store.declarationURL, with: .data(manifestText("defaultAgents: [.codex]"))) try transaction.commit() } #expect(steps.contains(TransactionCheckpoint.containerCreated(1).name)) diff --git a/Tests/AgentsCoreTests/TransactionMetadataTests.swift b/Tests/AgentsCoreTests/TransactionMetadataTests.swift index aed6310..caa2f5d 100644 --- a/Tests/AgentsCoreTests/TransactionMetadataTests.swift +++ b/Tests/AgentsCoreTests/TransactionMetadataTests.swift @@ -72,7 +72,7 @@ struct TransactionMetadataTests { } else { try interrupt(fixture, command: "crash", at: point) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } } @@ -103,7 +103,7 @@ struct TransactionMetadataTests { try interrupt(fixture, command: "crash", at: TransactionCheckpoint.progress(4, .applied).name) try interrupt(fixture, command: "recover", at: point) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } try fixture.check(committed: false) diff --git a/Tests/AgentsCoreTests/WatchDurabilityTests.swift b/Tests/AgentsCoreTests/WatchDurabilityTests.swift index 8a1e126..7eff557 100644 --- a/Tests/AgentsCoreTests/WatchDurabilityTests.swift +++ b/Tests/AgentsCoreTests/WatchDurabilityTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import CPlatform import Foundation import StateTestSupport @@ -113,7 +114,7 @@ struct WatchDurabilityTests { let before = try fixture.stateBytes() let watch = WatchOperations( discoverSkills: { _ in [] }, - fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, + fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, declarations: .manifest, checkpoint: { step in if step == "watch.ref.updated" { throw CoreError.invalidState("injected durability failure") @@ -215,10 +216,10 @@ final class WatchGitFixture { } } + /// Recovers as the next mutating command would, then reads the watch state. func recoveredWatch() throws -> WatchState { - do { return try store.loadWatch() } catch CoreError.transactionRecovered { - return try store.loadWatch() - } + do { try store.withLock {} } catch CoreError.transactionRecovered {} + return try store.loadWatch() } func cachedInstruction(_ revision: String) throws -> String { diff --git a/Tests/AgentsCoreTests/WatchGitLockTests.swift b/Tests/AgentsCoreTests/WatchGitLockTests.swift index 92f21fc..d12875d 100644 --- a/Tests/AgentsCoreTests/WatchGitLockTests.swift +++ b/Tests/AgentsCoreTests/WatchGitLockTests.swift @@ -76,10 +76,11 @@ struct WatchGitLockTests { // Pruning the disappeared upstream branch would need the abandoned packed-refs lock. try fixture.rewrite("later") let before = try FileHash.folderHash(fixture.store.directory) - let pending = CoreError.invalidState("transaction recovery is required before inspection") - #expect(throws: pending) { try fixture.watch.status(environment: fixture.environment) } + #expect(throws: pendingRecovery) { try fixture.watch.status(environment: fixture.environment) } #expect(try FileHash.folderHash(fixture.store.directory) == before) - #expect(throws: pending) { try fixture.watch.diff("source", environment: fixture.environment) } + #expect(throws: pendingRecovery) { + try fixture.watch.diff("source", environment: fixture.environment) + } #expect(try FileHash.folderHash(fixture.store.directory) == before) let committed = try fixture.stateBytes() @@ -125,7 +126,7 @@ struct WatchGitLockTests { try #require(mkfifo(unsafe.path, 0o600) == 0) } let before = try fixture.stateBytes() - #expect(throws: CoreError.self) { try fixture.store.loadWatch() } + #expect(throws: CoreError.self) { try fixture.store.withLock {} } #expect(try fixture.stateBytes() == before) #expect(try Data(contentsOf: safe) == original) #expect(try Data(contentsOf: external) == original) diff --git a/Tests/AgentsCoreTests/WatchInspectionTests.swift b/Tests/AgentsCoreTests/WatchInspectionTests.swift index 5dad158..44207d8 100644 --- a/Tests/AgentsCoreTests/WatchInspectionTests.swift +++ b/Tests/AgentsCoreTests/WatchInspectionTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import Foundation import Testing @@ -20,11 +21,12 @@ struct WatchInspectionTests { FileManager.default.fileExists( atPath: fixture.store.directory.appendingPathComponent("transaction.json").path)) let before = try FileHash.folderHash(fixture.store.directory) - let pending = CoreError.invalidState("transaction recovery is required before inspection") - #expect(throws: pending) { try fixture.watch.status(environment: fixture.environment) } + #expect(throws: pendingRecovery) { try fixture.watch.status(environment: fixture.environment) } #expect(try FileHash.folderHash(fixture.store.directory) == before) - #expect(throws: pending) { try fixture.watch.diff("source", environment: fixture.environment) } + #expect(throws: pendingRecovery) { + try fixture.watch.diff("source", environment: fixture.environment) + } #expect(try FileHash.folderHash(fixture.store.directory) == before) } @@ -49,11 +51,12 @@ struct WatchInspectionTests { try #require(try fixture.watchRefs() == refs) try fixture.rewrite("later") let before = try FileHash.folderHash(fixture.store.directory) - let pending = CoreError.invalidState("transaction recovery is required before inspection") - #expect(throws: pending) { try fixture.watch.status(environment: fixture.environment) } + #expect(throws: pendingRecovery) { try fixture.watch.status(environment: fixture.environment) } #expect(try FileHash.folderHash(fixture.store.directory) == before) - #expect(throws: pending) { try fixture.watch.diff("source", environment: fixture.environment) } + #expect(throws: pendingRecovery) { + try fixture.watch.diff("source", environment: fixture.environment) + } #expect(try FileHash.folderHash(fixture.store.directory) == before) #expect(try fixture.watchRefs() == refs) } diff --git a/Tests/AgentsCoreTests/WatchPreparationTests.swift b/Tests/AgentsCoreTests/WatchPreparationTests.swift index 79b9a14..5308988 100644 --- a/Tests/AgentsCoreTests/WatchPreparationTests.swift +++ b/Tests/AgentsCoreTests/WatchPreparationTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import Foundation import Testing @@ -7,15 +8,13 @@ import Testing /// which can be slow; editors that ignore the scope lock may change state meanwhile. @Suite("Watch preparation evidence") struct WatchPreparationTests { + /// A comment-only edit changes no declared intent but still invalidates the preparation. @Test func declarationEditedDuringAcknowledgmentIsPreserved() throws { let fixture = try WatchGitFixture() let watchBefore = try FileSnapshot.read(at: fixture.store.watchURL) - let edited = try StateStore.encodeState( - Declaration( - agents: [.codex], - sources: ["source": SourceDeclaration(kind: .local, location: fixture.repo.path)])) let external = ExternalEdit() let watch = fixture.operations { [store = fixture.store] in + let edited = try Data(contentsOf: store.declarationURL) + Data("// Edited.\n".utf8) try edited.write(to: store.declarationURL) external.snapshot = try FileSnapshot.read(at: store.declarationURL) } @@ -91,7 +90,7 @@ extension WatchGitFixture { fileprivate func operations(edit: @escaping @Sendable () throws -> Void) -> WatchOperations { WatchOperations( discoverSkills: { _ in [] }, - fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, + fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, declarations: .manifest, checkpoint: { step in if step == "watch.mirror.fetched" { try edit() } }) diff --git a/Tests/AgentsCoreTests/WatchReferenceTests.swift b/Tests/AgentsCoreTests/WatchReferenceTests.swift index e492e95..f1bba43 100644 --- a/Tests/AgentsCoreTests/WatchReferenceTests.swift +++ b/Tests/AgentsCoreTests/WatchReferenceTests.swift @@ -76,7 +76,7 @@ struct WatchReferenceTests { try fixture.kill(child, at: "watch.mirror.synced") let corrupt = Data("invalid watch state".utf8) try corrupt.write(to: fixture.store.watchURL) - #expect(throws: CoreError.self) { try fixture.store.loadWatch() } + #expect(throws: CoreError.self) { try fixture.store.withLock {} } #expect(try Data(contentsOf: fixture.store.watchURL) == corrupt) #expect(try fixture.watchRefs() == [first, replacement]) #expect( diff --git a/Tests/AgentsCoreTests/WatchStateTests.swift b/Tests/AgentsCoreTests/WatchStateTests.swift index 35c8679..8efd92b 100644 --- a/Tests/AgentsCoreTests/WatchStateTests.swift +++ b/Tests/AgentsCoreTests/WatchStateTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import CPlatform import Foundation import StateTestSupport @@ -134,7 +135,7 @@ struct WatchStateTests { let marker = root.appendingPathComponent("ready") try ProcessWait.marker(marker, child: child, root: root) terminateProcess(child) - #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.loadWatch() } + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } let committed = checkpoint == TransactionCheckpoint.phase(.committed).name || checkpoint == TransactionCheckpoint.containerRemoved(0).name diff --git a/Tests/AgentsInstructionsTests/DeclarationDocumentTests.swift b/Tests/AgentsInstructionsTests/DeclarationDocumentTests.swift new file mode 100644 index 0000000..802b97a --- /dev/null +++ b/Tests/AgentsInstructionsTests/DeclarationDocumentTests.swift @@ -0,0 +1,119 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import Foundation +import Testing + +/// Instruction writes through the scope's `Agents.swift` declaration document. +@Suite("Instruction declaration documents") +struct DeclarationDocumentTests { + @Test func instructionEditsKeepCommentsAndUntouchedBytes() throws { + let fixture = try InstructionFixture() + try fixture.own("guide") + try fixture.own("style") + let declaration = fixture.store().declarationURL + let header = """ + // agents-tools-version: 1.0 + import AgentsDescription + + // Project instructions. + let agents = Agents( + components: [ + // Shared guidance first. + + """ + let closing = " ]\n)\n" + try fixture.write( + header + " .instructions(sections: [\"guide\"], agents: [.codex]),\n" + closing, + to: declaration) + _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + func text() throws -> String { + String(decoding: try Data(contentsOf: declaration), as: UTF8.self) + } + + try fixture.addOwn(names: ["style"]) + #expect(try text().hasPrefix(header)) + #expect(try fixture.store().loadDeclaration().instructions?.sections == ["guide", "style"]) + try InstructionOperations.remove(names: ["guide"], environment: fixture.environment) + #expect(try text().hasPrefix(header)) + _ = try InstructionOperations.updateInstalled( + agents: [.claudeCode, .codex], environment: fixture.environment, apply: true) + #expect( + try text() + == header + " .instructions(sections: [\"style\"], agents: [.claudeCode, .codex]),\n" + + closing) + #expect(try fixture.store().loadResolved().instructions.sections.map(\.name) == ["style"]) + } + + /// A declaration another writer creates after preparation is kept, and no lock or target is + /// published beside it. + @Test func externallyCreatedDeclarationIsKept() throws { + let fixture = try InstructionFixture() + try fixture.own("guide") + let store = fixture.store() + let external = Data( + "// agents-tools-version: 1.0\nimport AgentsDescription\n\nlet agents = Agents()\n".utf8) + #expect(throws: CoreError.self) { + try InstructionOperations.add( + InstructionAddOptions(source: ".", names: ["guide"], environment: fixture.environment), + beforeApply: { _ in try external.write(to: store.declarationURL) }) + } + #expect(try Data(contentsOf: store.declarationURL) == external) + #expect(!FileManager.default.fileExists(atPath: store.resolvedURL.path)) + #expect( + !FileManager.default.fileExists( + atPath: fixture.project.appendingPathComponent("AGENTS.md").path)) + } + + /// Sections held in a constant have no direct source range, so the add stops before the + /// callback and any write. + @Test func readOnlySectionsStopBeforeTheCallback() throws { + let fixture = try InstructionFixture() + try fixture.own("guide") + try fixture.own("style") + try fixture.write( + """ + // agents-tools-version: 1.0 + import AgentsDescription + + let shared: [SectionReference] = ["guide"] + let agents = Agents(components: [.instructions(sections: shared, agents: [.codex])]) + + """, to: fixture.store().declarationURL) + _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + let before = try fixture.snapshot() + var called = false + #expect { + try InstructionOperations.add( + InstructionAddOptions(source: ".", names: ["style"], environment: fixture.environment), + beforeApply: { _ in called = true }) + } throws: { error in + (error as? ManifestFailure)?.diagnostics.first?.code == "manifest.edit.readOnly" + } + #expect(!called) + #expect(try fixture.snapshot() == before) + } + + /// A lock without its declaration stops instruction writes, including authoring a new file + /// while the scope lock already exists. + @Test func missingDeclarationStopsInstructionWrites() throws { + let fixture = try InstructionFixture() + try fixture.own("guide") + try fixture.addOwn(names: ["guide"]) + let store = fixture.store() + try FileManager.default.removeItem(at: store.declarationURL) + let before = try fixture.snapshot() + let missing = CoreError.missingDeclaration(store.declarationURL.path) + #expect(throws: missing) { + try InstructionOperations.initializeInstructions( + named: "style", environment: fixture.environment) + } + #expect(throws: missing) { + try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + } + #expect(throws: missing) { + try InstructionOperations.listManaged(environment: fixture.environment) + } + #expect(try fixture.snapshot() == before) + } +} diff --git a/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift b/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift index 2b8cba6..0366a77 100644 --- a/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift +++ b/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsInstructions +import AgentsManifest import Foundation import Testing diff --git a/Tests/AgentsInstructionsTests/LifecycleTests.swift b/Tests/AgentsInstructionsTests/LifecycleTests.swift index b901843..bc0ca4f 100644 --- a/Tests/AgentsInstructionsTests/LifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/LifecycleTests.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsInstructions +import AgentsManifest import Foundation import Testing diff --git a/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift b/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift index f13f9f8..5df67c7 100644 --- a/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift +++ b/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsInstructions +import AgentsManifest import Foundation import Testing @@ -156,8 +157,15 @@ struct OwnershipAndPlacementTests { let fixture = try InstructionFixture() try fixture.own("guide") try fixture.write( - "{\"instructions\": {\"sections\": [], \"chatgpt\": {\"weekly\": {\"sections\": [\"guide\"]}}}}\n", - to: fixture.store().declarationURL) + """ + // agents-tools-version: 1.0 + import AgentsDescription + + let agents = Agents( + components: [.instructions(chatGPT: [.prompt(name: "weekly", sections: ["guide"])])] + ) + + """, to: fixture.store().declarationURL) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) #expect( try fixture.store().loadResolved().instructions.chatgpt["weekly"]?.sections.map(\.name) diff --git a/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift b/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift index dc496b0..914148a 100644 --- a/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift +++ b/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsInstructions +import AgentsManifest import Foundation import Testing diff --git a/Tests/AgentsInstructionsTests/SourceShorthandTests.swift b/Tests/AgentsInstructionsTests/SourceShorthandTests.swift index 38d4532..5fb4d04 100644 --- a/Tests/AgentsInstructionsTests/SourceShorthandTests.swift +++ b/Tests/AgentsInstructionsTests/SourceShorthandTests.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsInstructions +import AgentsManifest import Foundation import Testing diff --git a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift index 4dd8a4c..a31ca24 100644 --- a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsInstructions +import AgentsManifest import Foundation import Testing @@ -58,22 +59,41 @@ struct TargetLifecycleTests { }) } - @Test func updateApplyFormatsDeclarationAndPreservesUnchangedLedger() throws { + @Test func updateApplyKeepsAnUnchangedDeclarationAndLedgerAsWritten() throws { let fixture = try InstructionFixture() try fixture.own("guide") 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( - 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) + String(decoding: try Data(contentsOf: declarationFile), as: UTF8.self) == """ + // agents-tools-version: 1.0 + import AgentsDescription + + let agents = Agents( + components: [ + .instructions( + sections: ["guide"], + agents: [.codex] + ), + ] + ) + + """) + let lockText = String(decoding: try Data(contentsOf: lockFile), as: UTF8.self) #expect(lockText.contains("\"chatgpt\": {}") && lockText.contains("\"skills\": {}")) #expect(!lockText.contains(" : ")) - try StateStore.encode(fixture.store().loadDeclaration()).write(to: declarationFile) + // The same intent in another layout, with a comment, is not rewritten. + let declaration = Data( + """ + // agents-tools-version: 1.0 + import AgentsDescription + + // Project instructions. + let agents = Agents(components: [.instructions(sections: ["guide"], agents: [.codex])]) + + """.utf8) + try declaration.write(to: declarationFile) let existingLockBytes = try StateStore.encode(fixture.store().loadResolved()) try existingLockBytes.write(to: lockFile) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) diff --git a/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift b/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift index 1103570..ff8b694 100644 --- a/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift +++ b/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import CPlatform import Foundation import StateTestSupport @@ -16,11 +17,10 @@ struct AutomaticSelectionTests { to: instructions.appendingPathComponent("demo.md")) try fixture.commit() let store = fixture.store() - try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) var declaration = Declaration(sources: [ "source": SourceDeclaration(kind: .local, location: fixture.repo.path) ]) - try StateStore.encode(declaration).write(to: store.declarationURL) + try store.writeDeclaration(declaration) let root = fixture.environment.projectDirectory let resume = root.appendingPathComponent("resume-discovery") diff --git a/Tests/AgentsSkillsTests/CoreTestSupport.swift b/Tests/AgentsSkillsTests/CoreTestSupport.swift index 0210c56..de0d2c1 100644 --- a/Tests/AgentsSkillsTests/CoreTestSupport.swift +++ b/Tests/AgentsSkillsTests/CoreTestSupport.swift @@ -1,3 +1,4 @@ +import AgentsManifest import Foundation import StateTestSupport import Testing @@ -48,3 +49,14 @@ func gitHead(_ repo: URL) throws -> String { .stdout .trimmingCharacters(in: .whitespacesAndNewlines) } + +extension StateStore { + /// Writes the document that a first write of `declaration` creates, without a lock, watch + /// state or scope lock. + func writeDeclaration(_ declaration: Declaration) throws { + let change = try planDeclaration( + declaration, replacing: Declaration(), prepared: StatePrecondition(store: self)) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try (change?.bytes ?? manifestText()).write(to: declarationURL) + } +} diff --git a/Tests/AgentsSkillsTests/DefaultResolutionTests.swift b/Tests/AgentsSkillsTests/DefaultResolutionTests.swift index 9748a50..1462a50 100644 --- a/Tests/AgentsSkillsTests/DefaultResolutionTests.swift +++ b/Tests/AgentsSkillsTests/DefaultResolutionTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import Foundation import Testing diff --git a/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift b/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift index 8d1e5a0..9532fdd 100644 --- a/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift +++ b/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import Foundation import Testing diff --git a/Tests/AgentsSkillsTests/InstalledInventoryTests.swift b/Tests/AgentsSkillsTests/InstalledInventoryTests.swift index 03d4122..717e71c 100644 --- a/Tests/AgentsSkillsTests/InstalledInventoryTests.swift +++ b/Tests/AgentsSkillsTests/InstalledInventoryTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import Foundation import Testing @@ -98,24 +99,32 @@ struct InstalledInventoryTests { let file = corruptDeclaration ? store.declarationURL : store.resolvedURL let bytes = Data("{corrupt".utf8) try bytes.write(to: file) - #expect(throws: CoreError.self) { try fixture.add(mode: mode, scope: scope) } - #expect(throws: CoreError.self) { - try SkillOperations.listManaged(scope: scope, environment: fixture.environment) + // Declaration diagnostics come from the manifest front end; a corrupt lock is a state error. + func expectFailure(_ body: () throws -> Void) { + if corruptDeclaration { + #expect(throws: ManifestFailure.self, performing: body) + } else { + #expect(throws: CoreError.self, performing: body) + } } - #expect(throws: CoreError.self) { - try SkillOperations.listInstalled(scope: scope, environment: fixture.environment) + expectFailure { _ = try fixture.add(mode: mode, scope: scope) } + expectFailure { + _ = try SkillOperations.listManaged(scope: scope, environment: fixture.environment) } - #expect(throws: CoreError.self) { - try SkillOperations.removableSkillNames(scope: scope, environment: fixture.environment) + expectFailure { + _ = try SkillOperations.listInstalled(scope: scope, environment: fixture.environment) } - #expect(throws: CoreError.self) { - try SkillOperations.doctor(scope: scope, environment: fixture.environment) + expectFailure { + _ = try SkillOperations.removableSkillNames(scope: scope, environment: fixture.environment) + } + expectFailure { + _ = try SkillOperations.doctor(scope: scope, environment: fixture.environment) } #expect(try Data(contentsOf: file) == bytes) + // The declaration is parsed under the scope lock, which a first writer creates. #expect( - try FileManager.default.contentsOfDirectory(atPath: store.directory.path) == [ - file.lastPathComponent - ]) + try Set(FileManager.default.contentsOfDirectory(atPath: store.directory.path)) + == Set([file.lastPathComponent] + (corruptDeclaration ? [".agents.lock"] : []))) #expect(!FileManager.default.fileExists(atPath: store.cacheDirectory.path)) #expect( !FileManager.default.fileExists( diff --git a/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift b/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift index 5d38385..7fe0e34 100644 --- a/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift +++ b/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import Foundation import Testing diff --git a/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift b/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift new file mode 100644 index 0000000..a90c723 --- /dev/null +++ b/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift @@ -0,0 +1,296 @@ +import AgentsManifest +import AgentsSkills +import CPlatform +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +/// Skill and watch writes through the scope's `Agents.swift` declaration document. +@Suite("Skill declaration documents") +struct ManifestLifecycleTests { + @Test func freshAddCreatesTheCanonicalDeclarationInTheLockJournal() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "A") + try fixture.commit() + let store = fixture.store() + let entries = JournalEntries() + _ = try SkillOperations.add( + AddOptions( + source: fixture.repo.path, alias: "fixture", agents: [.codex], mode: .copy, all: true, + environment: fixture.environment), + checkpoint: { point in + guard point == TransactionCheckpoint.progress(0, .ready).name else { return } + let journal = try StateStore.decode( + Data(contentsOf: store.directory.appendingPathComponent(TransactionJournal.fileName)), + as: TransactionJournal.self) + entries.value = journal.entries + }) + #expect( + entries.value.map(\.path) == ["codex/demo", "state/Agents.swift", "state/agents.resolved"]) + #expect(entries.value.allSatisfy { $0.preimage == nil }) + #expect( + String(decoding: try Data(contentsOf: store.declarationURL), as: UTF8.self) == """ + // agents-tools-version: 1.0 + import AgentsDescription + + let agents = Agents( + sources: [ + .source( + name: "fixture", + path: "\(fixture.repo.path)" + ), + ], + components: [ + .skills( + source: "fixture", + mode: .copy, + agents: [.codex] + ), + ] + ) + + """) + #expect(try store.loadResolved().skills["demo"]?.installs == ["codex": .copy]) + } + + @Test func skillAndWatchEditsKeepCommentsAndUntouchedBytes() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "A") + try fixture.skill("other", body: "B") + try fixture.commit() + let store = fixture.store() + let header = """ + // agents-tools-version: 1.0 + import AgentsDescription + + // Team skills, reviewed weekly. + let agents = Agents( + sources: [ + // The fixture repository. + .source(name: "fixture", path: "\(fixture.repo.path)"), + ], + """ + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + try Data( + (header + """ + + components: [ + // Everything the fixture publishes. + .skills(source: "fixture", agents: [.codex]), + ] + ) + + """).utf8 + ).write(to: store.declarationURL) + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(try store.loadResolved().skills.keys.sorted() == ["demo", "other"]) + func text() throws -> String { + String(decoding: try Data(contentsOf: store.declarationURL), as: UTF8.self) + } + func expectUntouched() throws { + let current = try text() + #expect(current.hasPrefix(header)) + #expect(current.contains(" // Everything the fixture publishes.\n")) + } + + try SkillOperations.remove(skillNames: ["demo"], environment: fixture.environment) + try expectUntouched() + #expect(try store.loadDeclaration().skills?["fixture"]?.exclude == ["demo"]) + #expect(try store.loadResolved().skills.keys.sorted() == ["other"]) + + _ = try SkillOperations.add( + AddOptions( + source: "fixture", agents: [.codex], skillNames: ["demo"], environment: fixture.environment) + ) + try expectUntouched() + #expect(try store.loadDeclaration().skills?["fixture"]?.exclude == nil) + + let watch = SkillOperations.watchOperations() + try watch.add("fixture", environment: fixture.environment) + try expectUntouched() + #expect(try store.loadDeclaration().watch == ["fixture"]) + try watch.remove("fixture", environment: fixture.environment) + try expectUntouched() + // Only the component's arguments and the root's watch argument were edited. + let final = try text() + #expect( + final.hasPrefix( + header + "\n components: [\n // Everything the fixture publishes.\n .skills(source: " + )) + #expect(final.hasSuffix("),\n ],\n watch: []\n)\n")) + let declaration = try store.loadDeclaration() + #expect(declaration.watch == nil) + #expect(declaration.skills?["fixture"]?.select == .all) + #expect(declaration.skills?["fixture"]?.exclude == nil) + #expect(try store.loadResolved().skills.keys.sorted() == ["demo", "other"]) + } + + @Test func unchangedUpdateKeepsTheDeclarationFile() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "A") + try fixture.commit() + _ = try fixture.add(mode: .copy) + let declaration = fixture.store().declarationURL + let before = try FileStatus(declaration) + let results = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(results.allSatisfy { !$0.changed }) + let after = try FileStatus(declaration) + #expect(after == before) + } + + /// A comment-only edit during the callback changes no declared intent but still invalidates + /// the preparation. + @Test func commentEditBeforeApplyRejectsTheUpdate() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "A") + try fixture.commit() + _ = try fixture.add(mode: .copy) + try fixture.skill("demo", body: "B") + try fixture.commit() + let store = fixture.store() + let lock = try Data(contentsOf: store.resolvedURL) + let target = try fixture.body(fixture.target("demo")) + var edited = Data() + #expect { + try SkillOperations.updateInstalled( + environment: fixture.environment, apply: true, + beforeApply: { _ in + edited = try Data(contentsOf: store.declarationURL) + Data("// Reviewed.\n".utf8) + try edited.write(to: store.declarationURL) + }) + } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("changed during preparation") + } + #expect(try Data(contentsOf: store.declarationURL) == edited) + #expect(try Data(contentsOf: store.resolvedURL) == lock) + #expect(try fixture.body(fixture.target("demo")) == target) + } + + /// A selection held in a constant has no direct source range, so the add stops before + /// retaining content or touching targets. + @Test func readOnlySelectionStopsAnAddBeforeRetention() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "A") + try fixture.skill("other", body: "B") + try fixture.commit() + _ = try fixture.add(mode: .copy) + let store = fixture.store() + let declaration = Data( + """ + // agents-tools-version: 1.0 + import AgentsDescription + + let picked: SkillSelection = ["demo"] + let agents = Agents( + sources: [.source(name: "fixture", path: "\(fixture.repo.path)")], + components: [.skills(source: "fixture", select: picked, mode: .copy, agents: [.codex])] + ) + + """.utf8) + try declaration.write(to: store.declarationURL) + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + let before = try snapshot(fixture.environment.projectDirectory) + #expect { + try SkillOperations.add( + AddOptions( + source: "fixture", agents: [.codex], skillNames: ["other"], mode: .copy, + environment: fixture.environment)) + } throws: { error in + (error as? ManifestFailure)?.diagnostics.first?.code == "manifest.edit.readOnly" + } + #expect(try snapshot(fixture.environment.projectDirectory) == before) + #expect(try Data(contentsOf: store.declarationURL) == declaration) + } + + /// Components outside the deployable subset are reported, never dropped; the complete + /// document stays readable. + @Test func undeployableComponentsAreReportedAndStillReadable() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "A") + try fixture.commit() + let store = fixture.store() + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + let declaration = Data( + """ + // agents-tools-version: 1.0 + import AgentsDescription + + let agents = Agents( + sources: [.source(name: "fixture", path: "\(fixture.repo.path)")], + components: [ + .skills(source: "fixture"), + .mcpServer(name: "tools", transport: .stdio("server")), + ] + ) + + """.utf8) + try declaration.write(to: store.declarationURL) + let before = try snapshot(fixture.root) + for operation in ["update", "add", "list"] { + #expect { + switch operation { + case "update": + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + case "add": + _ = try SkillOperations.add( + AddOptions(source: "fixture", all: true, environment: fixture.environment)) + default: _ = try SkillOperations.listManaged(environment: fixture.environment) + } + } throws: { error in + guard let failure = error as? ManifestFailure, + let diagnostic = failure.diagnostics.first + else { return false } + return diagnostic.code == "manifest.unsupported" + && diagnostic.span.document.rawValue == store.declarationURL.path + } + } + let document = try #require(try store.loadManifest()) + #expect(document.bytes == Array(declaration)) + #expect(document.declaration.components.contains { $0.kind == "mcpServer" }) + #expect(try snapshot(fixture.root).filter { !$0.key.hasSuffix(".agents.lock") } == before) + } +} + +/// Checkpoint callbacks run synchronously in the calling test. +private final class JournalEntries: @unchecked Sendable { + var value: [TransactionJournal.Entry] = [] +} + +/// The inode and modification time a rewrite would change. +private struct FileStatus: Equatable { + let inode: UInt64 + let seconds: Int + let nanoseconds: Int + + init(_ url: URL) throws { + var info = stat() + guard lstat(url.path, &info) == 0 else { throw CoreError.notFound(url.path) } + inode = UInt64(info.st_ino) + #if canImport(Darwin) + seconds = info.st_mtimespec.tv_sec + nanoseconds = info.st_mtimespec.tv_nsec + #else + seconds = info.st_mtim.tv_sec + nanoseconds = info.st_mtim.tv_nsec + #endif + } +} + +private func snapshot(_ directory: URL) throws -> [String: Data] { + var result: [String: Data] = [:] + let entries = try #require(FileManager.default.enumerator(atPath: directory.path)) + for case let path as String in entries { + let url = directory.appendingPathComponent(path) + if let destination = try? FileManager.default.destinationOfSymbolicLink(atPath: url.path) { + result[path] = Data(("link:" + destination).utf8) + } else if (try? url.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile == true { + result[path] = try Data(contentsOf: url) + } else { + result[path] = Data() + } + } + return result +} diff --git a/Tests/AgentsSkillsTests/PublicLifecycleTests.swift b/Tests/AgentsSkillsTests/PublicLifecycleTests.swift index e2f48bf..5094556 100644 --- a/Tests/AgentsSkillsTests/PublicLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/PublicLifecycleTests.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import AgentsSkills import Foundation import Testing diff --git a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift index 21a566d..bd1f17e 100644 --- a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift +++ b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift @@ -1,4 +1,5 @@ import AgentsInstructions +import AgentsManifest import AgentsSkills import CPlatform import Foundation @@ -142,14 +143,11 @@ struct ReadOnlyInspectionTests { } let store = fixture.store(scope) if existingDirectory { - try FileManager.default.createDirectory( - at: store.directory, withIntermediateDirectories: true) - try StateStore.encode( + try store.writeDeclaration( Declaration(sources: [ "relative": SourceDeclaration(kind: .local, location: "../source"), "remote": SourceDeclaration(kind: .git, location: "file://localhost" + fixture.repo.path), - ]) - ).write(to: store.declarationURL) + ])) } let before = try snapshot(fixture.root) let sources = @@ -267,7 +265,7 @@ struct ReadOnlyInspectionTests { if existingDirectory { try FileManager.default.createDirectory( at: store.directory, withIntermediateDirectories: true) - try StateStore.encode(Declaration()).write(to: store.declarationURL) + try manifestText().write(to: store.declarationURL) } let before = try snapshot(fixture.root) #expect( @@ -337,7 +335,7 @@ struct ReadOnlyInspectionTests { report.diagnostics.first?.message.contains("next command that changes this scope") == true) #expect(try snapshot(root) == before) - let pending = CoreError.invalidState("transaction recovery is required before inspection") + let pending = CoreError.recoveryPending(TransactionRecoveryDiagnostic.pendingMessage) #expect(throws: pending) { try SkillOperations.listManaged(scope: scope, environment: environment) } diff --git a/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift b/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift index 3da70f2..4ba46cd 100644 --- a/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import Foundation import Testing diff --git a/Tests/AgentsSkillsTests/SkillLifecycleTests.swift b/Tests/AgentsSkillsTests/SkillLifecycleTests.swift index be8445f..1bc27ef 100644 --- a/Tests/AgentsSkillsTests/SkillLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/SkillLifecycleTests.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import Foundation import Testing @@ -154,7 +155,9 @@ struct SkillLifecycleTests { #expect(!FileManager.default.fileExists(atPath: fixture.store().resolvedURL.path)) } - @Test(arguments: ["agents.json", "agents.resolved"], ["add", "update", "install", "remove"]) + @Test( + arguments: [StateStore.declarationFileName, StateStore.resolvedFileName], + ["add", "update", "install", "remove"]) func corruptStateStopsEveryMutation(_ filename: String, _ operation: String) throws { let fixture = try SkillFixture() try fixture.skill("demo", body: "A") diff --git a/Tests/AgentsSkillsTests/SourceAliasTests.swift b/Tests/AgentsSkillsTests/SourceAliasTests.swift index ff9fdd4..7400aec 100644 --- a/Tests/AgentsSkillsTests/SourceAliasTests.swift +++ b/Tests/AgentsSkillsTests/SourceAliasTests.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import AgentsSkills import Foundation import Testing diff --git a/Tests/AgentsSkillsTests/SourceShorthandTests.swift b/Tests/AgentsSkillsTests/SourceShorthandTests.swift index b99b1b4..e4cccef 100644 --- a/Tests/AgentsSkillsTests/SourceShorthandTests.swift +++ b/Tests/AgentsSkillsTests/SourceShorthandTests.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import AgentsSkills import Foundation import Testing diff --git a/Tests/AgentsSkillsTests/TransactionDoctorTests.swift b/Tests/AgentsSkillsTests/TransactionDoctorTests.swift index 4dffdd6..4747e54 100644 --- a/Tests/AgentsSkillsTests/TransactionDoctorTests.swift +++ b/Tests/AgentsSkillsTests/TransactionDoctorTests.swift @@ -1,4 +1,5 @@ import AgentsInstructions +import AgentsManifest import AgentsSkills import Foundation import Testing diff --git a/Tests/AgentsSkillsTests/UpdateReportingTests.swift b/Tests/AgentsSkillsTests/UpdateReportingTests.swift index d489c3a..307c3fa 100644 --- a/Tests/AgentsSkillsTests/UpdateReportingTests.swift +++ b/Tests/AgentsSkillsTests/UpdateReportingTests.swift @@ -1,3 +1,4 @@ +import AgentsManifest import Foundation import Testing diff --git a/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift b/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift index de156ee..58913a9 100644 --- a/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift +++ b/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import AgentsSkills import Foundation import Testing @@ -15,9 +16,11 @@ struct WatchSubscriptionTests { let initial = try fixture.head() try fixture.store().save(declaration: Declaration(), resolved: ResolvedState()) let watch = SkillOperations.watchOperations() - #expect( - try watch.add(fixture.repo.path, alias: "upstream", environment: fixture.environment) - == .revision(initial)) + let id = try SourceDeclaration(kind: .local, location: fixture.repo.path).identity( + environment: fixture.environment) + let added = try watch.add( + fixture.repo.path, alias: "upstream", environment: fixture.environment) + #expect(added.alias == "upstream" && added.sourceID == id && added.seen == .revision(initial)) #expect(try fixture.store().loadDeclaration().skills == nil) #expect(try fixture.store().loadResolved().skills.isEmpty) #expect(!FileManager.default.fileExists(atPath: fixture.target("changed").path)) @@ -57,7 +60,10 @@ struct WatchSubscriptionTests { #expect(try stateBytes(fixture) == bytes) #expect(try fixture.head() == current) - try watch.seen("upstream", environment: fixture.environment) + let acknowledged = try watch.seen("upstream", environment: fixture.environment) + #expect( + acknowledged.alias == "upstream" && acknowledged.sourceID == id + && acknowledged.seen == .revision(current)) #expect(try watch.status(environment: fixture.environment).first?.changes.isEmpty == true) try fixture.skill("later", body: "later") try fixture.commit() @@ -85,10 +91,12 @@ struct WatchSubscriptionTests { let store = fixture.store(scope) let lock = try Data(contentsOf: store.resolvedURL) let installed = try fixture.body(fixture.target("demo", scope: scope)) - try watch.add("fixture", scope: scope, environment: fixture.environment) - try watch.remove(fixture.repo.path, scope: scope, environment: fixture.environment) + let added = try watch.add("fixture", scope: scope, environment: fixture.environment) + let removed = try watch.remove( + fixture.repo.path, scope: scope, environment: fixture.environment) + #expect(removed.alias == "fixture" && removed.sourceID == added.sourceID && removed.seen == nil) #expect(try store.loadWatch().sources.isEmpty) - #expect(try store.loadDeclaration().watch == []) + #expect(try store.loadDeclaration().watch == nil) #expect(try store.loadDeclaration().skills?["fixture"] != nil) #expect(try Data(contentsOf: store.resolvedURL) == lock) #expect(try fixture.body(fixture.target("demo", scope: scope)) == installed) @@ -109,7 +117,8 @@ struct WatchSubscriptionTests { try fixture.skill("demo", body: "head") try fixture.commit() let watch = SkillOperations.watchOperations() - #expect(try watch.add("source", environment: fixture.environment) == .revision(fixture.head())) + #expect( + try watch.add("source", environment: fixture.environment).seen == .revision(fixture.head())) try fixture.skill("demo", body: "uncommitted") #expect(try watch.status(environment: fixture.environment).first?.changes.isEmpty == true) try git(fixture, ["checkout", "-b", "next-default"]) diff --git a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift index c88f485..8687b6c 100644 --- a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift +++ b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift @@ -1,4 +1,5 @@ import AgentsInstructions +import AgentsManifest import AgentsSkills import Foundation import Testing @@ -490,7 +491,12 @@ struct CombinedUpdateTests { try FileManager.default.createSymbolicLink( at: fixture.target(), withDestinationURL: fixture.repo.appendingPathComponent("skills/demo")) - case "declaration": try fixture.write("{}\n", to: fixture.store.declarationURL) + case "declaration": + // A comment changes no declared intent but still invalidates the preparation. + let declaration = try fixture.bytes(fixture.store.declarationURL) + try fixture.write( + String(decoding: declaration, as: UTF8.self) + "// Edited.\n", + to: fixture.store.declarationURL) case "resolved": try fixture.write("{}\n", to: fixture.store.resolvedURL) default: try fixture.write("{}\n", to: fixture.store.watchURL) } diff --git a/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift b/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift index 9e2bd8e..98cc1f4 100644 --- a/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift +++ b/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsInstructions +import AgentsManifest import AgentsSkills import Foundation import Testing diff --git a/Tests/AgentsUpdatesTests/UpdateFixture.swift b/Tests/AgentsUpdatesTests/UpdateFixture.swift index 7d0b8fe..7ae5177 100644 --- a/Tests/AgentsUpdatesTests/UpdateFixture.swift +++ b/Tests/AgentsUpdatesTests/UpdateFixture.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsInstructions +import AgentsManifest import AgentsSkills import AgentsUpdates import Foundation diff --git a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift index 3eca652..b938f7d 100644 --- a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift +++ b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift @@ -37,7 +37,7 @@ struct UpdateTransactionTests { let retained = try FileManager.default.contentsOfDirectory(atPath: moved.path) #expect(retained.contains { $0.hasPrefix(".agents-") }) #expect(throws: CoreError.invalidState("transaction root identity changed")) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } #expect(try FileManager.default.contentsOfDirectory(atPath: moved.path) == retained) try FileManager.default.removeItem(at: root) @@ -117,7 +117,7 @@ struct UpdateTransactionTests { defer { terminate(child) } try waitFor("ready", fixture: fixture, child: child) terminate(child) - #expect(throws: CoreError.invalidState("transaction recovery is required before inspection")) { + #expect(throws: CoreError.recoveryPending(TransactionRecoveryDiagnostic.pendingMessage)) { try fixture.preview() } #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 599b214..ecb8b59 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -1,9 +1,11 @@ import AgentsCore import AgentsInstructions +import AgentsManifest import AgentsSkills import AgentsUpdates import CPlatform import Foundation +import StateTestSupport import Synchronization let arguments = CommandLine.arguments @@ -139,7 +141,7 @@ if arguments[2] == "git-environment" { } else if ["watch-subscribe", "watch-acknowledge"].contains(arguments[2]) { let watch = WatchOperations( discoverSkills: { _ in [] }, - fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, + fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, declarations: .manifest, checkpoint: { step in if step.hasPrefix("mirror."), FileLock.isContentionCheckpoint(step) { try signalContention() @@ -158,7 +160,7 @@ if arguments[2] == "git-environment" { } else if ["watch-add", "watch-seen", "watch-remove"].contains(arguments[2]) { let watch = WatchOperations( discoverSkills: { _ in [] }, - fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, + fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, declarations: .manifest, checkpoint: { try stop($0) }) if arguments[2] == "watch-add" { try watch.add( @@ -168,6 +170,12 @@ if arguments[2] == "git-environment" { } else { try watch.remove("source", environment: store.environment) } +} else if arguments[2] == "skill-add" { + _ = try SkillOperations.add( + AddOptions( + source: root.appendingPathComponent("source").path, agents: [.codex], + skillNames: ["demo"], mode: .edit, environment: store.environment), + checkpoint: { try stop($0) }) } else if arguments[2] == "watch-add-artifact" { let bytes = Data("---\nname: demo\ndescription: Fixture skill.\n---\nBody\n".utf8) let digest = "sha256:" + FileHash.sha256Hex(data: bytes) @@ -177,7 +185,7 @@ if arguments[2] == "git-environment" { type: .skillMD, url: "https://watch.example.test/demo/SKILL.md", digest: digest), files: ["SKILL.md": bytes], payloads: [digest: bytes]) let watch = WatchOperations( - discoverSkills: { _ in [] }, fetchArtifacts: { _ in [artifact] }, + discoverSkills: { _ in [] }, fetchArtifacts: { _ in [artifact] }, declarations: .manifest, checkpoint: { try stop($0) }) try watch.add("https://watch.example.test", alias: "site", environment: store.environment) } else if arguments[2] == "watch-recover" { @@ -230,9 +238,8 @@ if arguments[2] == "git-environment" { } } else if arguments[2] == "read" { try Data().write(to: root.appendingPathComponent("reader-started")) - do { _ = try store.loadResolved() } catch CoreError.transactionRecovered { - _ = try store.loadResolved() - } + // The reader waits for the writer lock and reports, rather than replays, pending recovery. + do { _ = try store.loadResolved() } catch CoreError.recoveryPending {} try Data().write(to: root.appendingPathComponent("reader-finished")) } else if arguments[2] == "combined-crash" { _ = try UpdateOperations.withPreparedUpdate( @@ -317,27 +324,35 @@ if arguments[2] == "git-environment" { InstructionLocations.file(for: .geminiCLI, scope: scope, environment: store.environment)!, with: .data(Data("New instructions\n".utf8))) try transaction.replace( - store.declarationURL, with: .data(StateStore.encode(Declaration(agents: [.cursor])))) + store.declarationURL, with: .data(manifestText("defaultAgents: [.cursor]"))) try transaction.replace(store.resolvedURL, with: .data(StateStore.encode(ResolvedState()))) try transaction.commit() } else if arguments[2] == "watch-crash" { - var declaration = try store.readDeclaration() + let baseline = try StatePrecondition(store: store) + let previous = try store.readDeclaration(prepared: baseline) + var declaration = previous declaration.watch = ["source"] let watch = WatchState(sources: [ "local:/source": WatchSourceState(seen: .revision(String(repeating: "b", count: 40))) ]) let transaction = FileTransaction(store: store) { try stop($0) } - try transaction.replace(store.declarationURL, with: .data(StateStore.encode(declaration))) + try store.stageDeclaration( + store.planDeclaration(declaration, replacing: previous, prepared: baseline), + in: transaction, prepared: baseline) try transaction.replace(store.watchURL, with: .data(StateStore.encode(watch))) try transaction.commit() } else if arguments[2] == "writer" { for index in 0..<5 { - var declaration = try store.readDeclaration() + let baseline = try StatePrecondition(store: store) + let previous = try store.readDeclaration(prepared: baseline) + var declaration = previous declaration.sources["\(arguments[3])-\(index)"] = SourceDeclaration( kind: .local, location: root.appendingPathComponent("\(arguments[3])-\(index)").path) usleep(10_000) let transaction = FileTransaction(store: store) - try transaction.replace(store.declarationURL, with: .data(StateStore.encode(declaration))) + try store.stageDeclaration( + store.planDeclaration(declaration, replacing: previous, prepared: baseline), + in: transaction, prepared: baseline) try transaction.commit() } } else { @@ -350,7 +365,7 @@ if arguments[2] == "git-environment" { ) .appendingPathComponent("target"), with: .copy(root.appendingPathComponent("new"))) try transaction.replace( - store.declarationURL, with: .data(StateStore.encode(Declaration(agents: [.codex])))) + store.declarationURL, with: .data(manifestText("defaultAgents: [.codex]"))) try transaction.replace( store.resolvedURL, with: .data( diff --git a/Tests/StateTestSupport/ManifestText.swift b/Tests/StateTestSupport/ManifestText.swift new file mode 100644 index 0000000..bd9eae3 --- /dev/null +++ b/Tests/StateTestSupport/ManifestText.swift @@ -0,0 +1,9 @@ +import Foundation + +/// A language 1.0 declaration document whose root `Agents(...)` call receives `arguments` +/// verbatim, for fixtures that need declaration bytes without the declaration model. +package func manifestText(_ arguments: String = "") -> Data { + let call = arguments.isEmpty ? "Agents()" : "Agents(\n \(arguments)\n)" + let header = "// agents-tools-version: 1.0\nimport AgentsDescription\n\n" + return Data((header + "let agents = \(call)\n").utf8) +} From cebfcd02ab1a80f7d6ceb069b94440c3ee4af45e Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 31 Oct 2026 00:11:35 +0800 Subject: [PATCH 023/171] docs: align the state documentation with the declaration wiring --- Documentation/Architecture/Package.md | 8 ++-- Documentation/Architecture/State.md | 62 ++++++++++++++++----------- Documentation/Architecture/Watch.md | 21 +++++---- Documentation/Reference/Manifest.md | 2 +- README.md | 9 ++-- 5 files changed, 60 insertions(+), 42 deletions(-) diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index ce210ca..d0c4c25 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -17,7 +17,7 @@ AgentsManifest ──> AgentsDescription, AgentsCore, SwiftSyntax, SwiftParser ( AgentsUpdates ──> AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, CPlatform -AgentsCore ──> Crypto (swift-crypto), CPlatform +AgentsCore ──> CPlatform, Crypto (swift-crypto) AgentsSkills ──> AgentsCore, AgentsManifest │ @@ -32,7 +32,7 @@ ManifestTestProcess ──> AgentsManifest, AgentsCore, AgentsDescription, Manif AgentsManifestTests ──> AgentsManifest, AgentsDescription, AgentsCore, ManifestTestProcess, ManifestTestSupport, SwiftParser, SwiftSyntax StateTestSupport (Foundation only) -StateTestProcess ──> AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, AgentsUpdates, CPlatform +StateTestProcess ──> AgentsCore, AgentsManifest, AgentsInstructions, AgentsSkills, AgentsUpdates, CPlatform, StateTestSupport AgentsCoreTests ──> AgentsCore, AgentsManifest, StateTestProcess, StateTestSupport, CPlatform AgentsSkillsTests ──> AgentsSkills, AgentsCore, AgentsManifest, AgentsInstructions, Yams, StateTestProcess, StateTestSupport, CPlatform AgentsInstructionsTests ──> AgentsInstructions, AgentsManifest @@ -122,7 +122,9 @@ language, editing rules and dump schema. `AgentsManifest` also connects `Agents.swift` to scope state through `extension StateStore`. The public `loadDeclaration()` returns the deployable -projection and `loadManifest()` the complete document; both are read-only. +projection and `loadManifest()` the complete document; both are read-only and, +like the public `WatchOperations.init(discoverSkills:fetchArtifacts:)`, require +`import AgentsManifest`. Package-level declaration reading and planning, the projection onto `AgentsCore.Declaration` and the declaration edit planner serve the domain modules, and `DeclarationAccess.manifest` supplies the same access to diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index cf04be8..9302e27 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -95,17 +95,18 @@ preserve both and existing watch-state bytes. | Declaration | Lock or watch state | Behavior | | --- | --- | --- | -| Absent | Absent | An empty declaration. Reads return empty results; the first write creates `Agents.swift` with no-replace publication. | +| Absent | Absent | An empty declaration. Reads return empty results; the first write that declares something creates `Agents.swift` with no-replace publication. A write whose declaration and resulting lock are both empty creates neither file. | | Present | Any | Normal. An absent lock is an empty resolved state: `update` creates it and `install` has nothing to restore. | | Absent | Present | Every read and write path, including the `load*` accessors, listings, previews, doctor, install, initialization and export, throws `CoreError.missingDeclaration` with the declaration path. Nothing is written, and no `.agents.lock` is created. | Read paths apply the rule after their pending-recovery check, and writers after -transaction recovery; the check before taking the writer lock runs only when no -journal or pending marker exists. An interrupted first write of the declaration -and lock therefore recovers on the next write instead of reporting a missing -declaration. Watch state counts because its baselines derive from the -declaration; treating a missing declaration as empty would let the next update -remove what was deployed. +transaction recovery. Before taking the writer lock, a writer in a scope without +`.agents.lock`, journal or pending watch-reference marker validates the lock and +watch state and checks only the declaration's presence. An interrupted first +write of the declaration and lock therefore recovers on the next write instead +of reporting a missing declaration. Watch state counts because its baselines +derive from the declaration; treating a missing declaration as empty would let +the next update remove what was deployed. ### Declaration writes @@ -117,16 +118,19 @@ bytes that passed the complete front end and the projection check. `stageDeclaration(_:in:prepared:)` in `AgentsCore` publishes those bytes in the operation's transaction, expecting the baseline's evidence for the declaration. Skill, instruction, watch and update writes use only these entries; adding or -changing a source is a difference in the declaration's sources. A combined -update leaves the declaration unchanged, and `validateBeforePublication` still -checks its evidence. +changing a source is a difference in the declaration's sources. Combined and +skill updates leave the declaration unchanged; the transaction still checks its +prepared evidence through `FileTransaction.requireUnchanged(since:)` before +publication. Planning completes before `beforeApply`, cache retention, a watch's Git fetch and any staging, so an edit that cannot be addressed exactly fails without side effects. When the previous declaration differs from the projection of the -baseline bytes, planning fails with `manifest.edit.baseline` rather than -overwriting an external change. Under the scope writer lock, a later writer reads -its own baseline and plans again, so concurrent writers lose no update. +baseline bytes, planning reports a stale preparation, +`CoreError.invalidState("declaration changed during preparation: ")`, +rather than overwriting an external change. Under the scope writer lock, a +later writer reads its own baseline and plans again, so concurrent writers lose +no update. Semantic equality decides whether anything changes: @@ -201,9 +205,12 @@ 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. A semantically unchanged lock keeps its original bytes; a changed lock is written in that -layout. Empty lock sections such as `"skills": {}` remain, because earlier -readers require them. Journals, `agents.watch` and content hashes keep the -encoder's fixed layout. +layout. When the prepared generation has neither a lock nor a declaration and +the resulting lock is empty, no lock is created, because lock state without a +declaration would stop every later access to the scope. A scope with a +declaration receives a lock even when it is empty. Empty lock sections such as +`"skills": {}` remain, because earlier readers require them. Journals, +`agents.watch` and content hashes keep the encoder's fixed layout. A locked source records its kind, Git URL where applicable, requirement and search path. A skill records its source ID, its own revision and optional @@ -468,9 +475,10 @@ recovery material changed. A committed failure is never described as rollback. The public `StateStore.loadResolved()` and `loadWatch()` in `AgentsCore` and `loadDeclaration()` and `loadManifest()` in `AgentsManifest` are read-only, as -described below. `loadDeclaration()` returns the deployable projection; -`loadManifest()` returns the complete `DeclarationDocument` without subset -projection, or `nil` when no declaration exists. +described below; the latter two require `import AgentsManifest`. +`loadDeclaration()` returns the deployable projection; `loadManifest()` returns +the complete `DeclarationDocument` without subset projection, or `nil` for a +scope without state. Both can also throw the declaration's `ManifestFailure`. ### Read-only access @@ -479,15 +487,19 @@ and watch diff take an existing shared lock, report pending recovery and never replay it or create state files. With no lock, inspection rechecks for a new lock or recovery marker before returning either its result or its error. A writer causes that attempt to be discarded and retried under the shared lock. -Writers create the scope lock before mutation and never remove it. +Writers create the scope lock before mutation and never remove it. The scope +lock exists before the declaration is parsed, so a first writer that meets an +invalid `Agents.swift` reports its `ManifestFailure` after creating +`.agents.lock`; invalid lock or watch state stops the writer before the lock +exists. The `load*` accessors follow the same rules and never create `.agents.lock`. Pending journals and watch-reference markers stop inspection with -`CoreError.recoveryPending`, which carries the recovery diagnostic; a mutating -operation on the scope performs the recovery. The absent-declaration rule -applies after this check. Doctor distinguishes pending automatic recovery from -an unresolved conflict requiring owner action, and skips checks needing a -consistent generation. Skill doctor uses `pending-recovery` or +`CoreError.recoveryPending`, whose description is the recovery diagnostic text +itself; a mutating operation on the scope performs the recovery. The +absent-declaration rule applies after this check. Doctor distinguishes pending +automatic recovery from an unresolved conflict requiring owner action, and skips +checks needing a consistent generation. Skill doctor uses `pending-recovery` or `unresolved-transaction`; instruction doctor uses `pendingRecovery` or `unresolvedTransaction`. Explicit multi-root instruction audits never write. Corrupt or foreign-version journals remain available rather than being replayed. diff --git a/Documentation/Architecture/Watch.md b/Documentation/Architecture/Watch.md index dc9b868..c54583f 100644 --- a/Documentation/Architecture/Watch.md +++ b/Documentation/Architecture/Watch.md @@ -12,11 +12,12 @@ skill selections, locked records and installed content. Both CLI consumers can construct `SkillOperations.watchOperations()` from `AgentsSkills`. It supplies the existing skill discovery rules and well-known loader to `AgentsCore`. Callers implementing another content provider can use -`WatchOperations.init(discoverSkills:fetchArtifacts:)`, which `AgentsManifest` -provides because it also supplies the declaration access that core receives by -injection. This keeps frontmatter, skill discovery, artifact format parsing and -manifest syntax in their owning modules; core has no dependency on -`AgentsManifest`, `AgentsSkills`, Yams or instruction rendering. +`WatchOperations.init(discoverSkills:fetchArtifacts:)` after `import +AgentsManifest`; that module provides the initializer because it also supplies +the declaration access that core receives by injection. This keeps frontmatter, +skill discovery, artifact format parsing and manifest syntax in their owning +modules; core has no dependency on `AgentsManifest`, `AgentsSkills`, Yams or +instruction rendering. Every operation accepts `scope` and `RuntimeEnvironment`: @@ -28,8 +29,9 @@ Every operation accepts `scope` and `RuntimeEnvironment`: | `seen(_:revision:scope:environment:)` | Acknowledge the current head or resolve a supplied Git revision to a full commit ID. Well-known sources accept no revision argument. Returns `WatchChange`. | | `remove(_:scope:environment:)` | Remove the alias from `watch` and delete its baseline without changing installations. Returns `WatchChange` without a baseline. | -`WatchChange` contains the alias, normalized source ID and the recorded -`WatchSeen` baseline, so callers need no separate declaration read. Existing +`WatchChange` has `alias`, the normalized `sourceID` and `seen`, the +acknowledged `WatchSeen` baseline or `nil` after removal, so callers need no +separate declaration read. Existing subscriptions can be addressed by alias, normalized source ID or source location. Repeating `add` records current content as seen. Missing subscriptions, invalid revisions and missing baseline content produce errors. A local directory @@ -116,8 +118,9 @@ revisions or digests are errors. Subscriptions cannot repeat an alias. Add, seen and remove hold the scope writer lock and recover interrupted transactions and pending ref cleanup before proceeding. They capture declaration, -lock and watch evidence and plan the `Agents.swift` change before contacting Git, -so a declaration the editor cannot change fails before any fetch. Add and seen +lock and watch evidence before contacting Git. Add and remove plan the +`Agents.swift` change at that point, so a declaration the editor cannot change +fails before any fetch; seen leaves the declaration unchanged. Add and seen prepare cached content before publishing its baseline. Declaration and watch replacements and cache pruning commit through the existing scope transaction journal, expecting the captured evidence; recovery follows the same retry diff --git a/Documentation/Reference/Manifest.md b/Documentation/Reference/Manifest.md index 22f646e..8b42eda 100644 --- a/Documentation/Reference/Manifest.md +++ b/Documentation/Reference/Manifest.md @@ -1101,7 +1101,7 @@ no partial declaration is published. | `manifest.limit` | Recognizer: byte, token, syntax-storage reservation, comment, delimiter or chain limit. Iterative tree guard: node/depth limit. Later stages: evaluation, expansion, domain traversal, local group depth, output, generated source or edit budget. | | `manifest.diagnostics.truncated` | The warning that replaces diagnostics beyond the limit. | | `manifest.edit.readOnly`, `.stale`, `.overlap`, `.impact`, `.mismatch` | Document editing, as described under Document Editing. Declaration edit planning also reports `.mismatch` when a batch makes no progress or the final projection differs from the intended declaration. | -| `manifest.edit.baseline` | Declaration edit planning: the declaration an operation read differs from the projection of the bytes it prepared. | +| `manifest.edit.baseline` | Declaration edit planning: the declaration an operation read differs from the projection of the bytes it prepared. The state layer reports it as a stale preparation; see [Declaration writes](../Architecture/State.md#declaration-writes). | | `manifest.unsupported` | The state layer's deployable-subset projection meets an active structure outside that subset; the span locates it. See [State](../Architecture/State.md#deployable-subset). | | `manifest.dump.mismatch` | A source-map pointer is absent from the evaluated declaration while building a dump; this is an implementation regression. | diff --git a/README.md b/README.md index 2eb5861..9bd2156 100644 --- a/README.md +++ b/README.md @@ -147,10 +147,11 @@ Mutating state operations recover interrupted transactions before proceeding and report `CoreError.transactionRecovered` when the command should be retried. The durable scope journal covers installations, declaration, lock, watch state and cache pruning. Corrupt watch state stops scope mutations before any replacement. -Read-only access, including `loadDeclaration()`, `loadManifest()`, -`loadResolved()` and `loadWatch()`, never recovers and reports a pending -transaction with `CoreError.recoveryPending`. A scope with a lock or watch state -but no `Agents.swift` reports `CoreError.missingDeclaration`. +Read-only access, including `loadResolved()`, `loadWatch()` and, with `import +AgentsManifest`, `loadDeclaration()` and `loadManifest()`, never recovers and +reports a pending transaction with `CoreError.recoveryPending`. A scope with a +lock or watch state but no `Agents.swift` reports +`CoreError.missingDeclaration`. ### Skills From 6d70fe30e85e7fe6c97637785e946c660083beef Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 31 Oct 2026 01:19:38 +0800 Subject: [PATCH 024/171] test(state): compare resolved skill targets by path --- Tests/AgentsCoreTests/StatePublicationTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/AgentsCoreTests/StatePublicationTests.swift b/Tests/AgentsCoreTests/StatePublicationTests.swift index a5c3f73..aef2942 100644 --- a/Tests/AgentsCoreTests/StatePublicationTests.swift +++ b/Tests/AgentsCoreTests/StatePublicationTests.swift @@ -301,8 +301,8 @@ final class StateOperationFixture { #expect(lock.skills["demo"]?.installs == ["codex": .edit]) #expect(lock.sources[id] == LockedSource(kind: .local)) #expect( - target.resolvingSymlinksInPath() - == source.appendingPathComponent("skills/demo").resolvingSymlinksInPath()) + target.resolvingSymlinksInPath().path + == source.appendingPathComponent("skills/demo").resolvingSymlinksInPath().path) #expect(!present(store.watchURL)) case .watchAdd: #expect(declaration.skills == nil) From f52f1d3d348610e19aa34856480b103a49b82cc1 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:30:54 +0800 Subject: [PATCH 025/171] docs: clarify missing declaration results --- Documentation/Architecture/State.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index 9302e27..a2a21a9 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -97,7 +97,7 @@ preserve both and existing watch-state bytes. | --- | --- | --- | | Absent | Absent | An empty declaration. Reads return empty results; the first write that declares something creates `Agents.swift` with no-replace publication. A write whose declaration and resulting lock are both empty creates neither file. | | Present | Any | Normal. An absent lock is an empty resolved state: `update` creates it and `install` has nothing to restore. | -| Absent | Present | Every read and write path, including the `load*` accessors, listings, previews, doctor, install, initialization and export, throws `CoreError.missingDeclaration` with the declaration path. Nothing is written, and no `.agents.lock` is created. | +| Absent | Present | The state cannot be used. Throwing APIs report `CoreError.missingDeclaration` with the declaration path; export returns `.unavailable`, and batch doctor reports a `.stateUnavailable` diagnostic for the affected scope. Nothing is written, and no `.agents.lock` is created. | Read paths apply the rule after their pending-recovery check, and writers after transaction recovery. Before taking the writer lock, a writer in a scope without From 88a6039da12c8bc996c2f8b33e70f3be6e9dec64 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:05:06 +0800 Subject: [PATCH 026/171] fix: resolve declared watch source identities --- Sources/AgentsCore/WatchOperations.swift | 9 +- Tests/AgentsCoreTests/WatchSourceTests.swift | 99 ++++++++++++++++++++ 2 files changed, 107 insertions(+), 1 deletion(-) create mode 100644 Tests/AgentsCoreTests/WatchSourceTests.swift diff --git a/Sources/AgentsCore/WatchOperations.swift b/Sources/AgentsCore/WatchOperations.swift index 1288e48..b265056 100644 --- a/Sources/AgentsCore/WatchOperations.swift +++ b/Sources/AgentsCore/WatchOperations.swift @@ -35,10 +35,17 @@ public struct WatchOperations: Sendable { var declaration = previous let lock = try store.readResolved(prepared: baseline) var watch = try store.readWatch(prepared: baseline) - let argument = try SourceArgument(source) + var argument = try SourceArgument(source) guard argument.name == nil else { throw CoreError.invalidSource("@skill: selects skills; watch subscribes to whole sources") } + if declaration.sources[argument.location] == nil, + let alias = try declaration.sources.keys.sorted().first(where: { + try declaration.sources[$0]?.identity(environment: environment) == argument.location + }) + { + argument.location = alias + } let selection = try argument.selection( in: declaration, requirement: requirement, path: path, environment: environment) let parsed = selection.source diff --git a/Tests/AgentsCoreTests/WatchSourceTests.swift b/Tests/AgentsCoreTests/WatchSourceTests.swift new file mode 100644 index 0000000..3d3c780 --- /dev/null +++ b/Tests/AgentsCoreTests/WatchSourceTests.swift @@ -0,0 +1,99 @@ +import AgentsManifest +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Watch source selection") +struct WatchSourceTests { + @Test(arguments: [InstallScope.project, .user]) + func addAcceptsDeclaredLocalIdentityAndPreservesSource(_ scope: InstallScope) throws { + let fixture = try WatchGitFixture() + let store = StateStore(scope: scope, environment: fixture.environment) + let source = SourceDeclaration( + kind: .local, location: "./source", requirement: .exact("1.0.0"), path: "instructions") + try store.save(declaration: Declaration(sources: ["source": source]), resolved: ResolvedState()) + let lock = try FileSnapshot.read(at: store.resolvedURL) + + let added = try fixture.watch.add( + fixture.id, scope: scope, environment: fixture.environment) + + #expect(added.alias == "source" && added.sourceID == fixture.id) + #expect(added.seen == .revision(try fixture.head())) + let declaration = try store.loadDeclaration() + #expect(declaration.sources == ["source": source]) + #expect(declaration.watch == ["source"]) + #expect(try store.loadWatch().sources[fixture.id]?.seen == added.seen) + #expect(try FileSnapshot.read(at: store.resolvedURL) == lock) + } + + @Test(arguments: ["alias", "identity", "location"]) + func selectorsReplaceDeclaredRequirementAndPath(_ input: String) throws { + let fixture = try WatchGitFixture() + let source = SourceDeclaration( + kind: .local, location: "./source", requirement: .exact("1.0.0"), path: "instructions") + try fixture.store.save( + declaration: Declaration(sources: ["source": source]), resolved: ResolvedState()) + let topic = try fixture.head() + try fixture.git(["branch", "topic"]) + try fixture.git(["commit", "--allow-empty", "-m", "advance default branch"]) + let location = + input == "alias" ? "source" : input == "identity" ? fixture.id : fixture.repo.path + + let added = try fixture.watch.add( + location + "@branch:topic@path:rules", requirement: .branch("topic"), path: "rules", + environment: fixture.environment) + + #expect(added.alias == "source" && added.sourceID == fixture.id) + #expect(added.seen == .revision(topic)) + #expect( + try fixture.store.loadDeclaration().sources == [ + "source": SourceDeclaration( + kind: .local, location: "./source", requirement: .branch("topic"), path: "rules") + ]) + } + + @Test(arguments: ["requirement", "path", "skill"]) + func invalidSelectorsForDeclaredIdentityStopBeforeGit(_ kind: String) throws { + let fixture = try WatchGitFixture() + let before = try fixture.stateBytes() + let selector = + kind == "requirement" ? "@branch:master" : kind == "path" ? "@path:rules" : "@skill:demo" + let reason = + kind == "requirement" + ? "the source selector and option give different requirements" + : kind == "path" + ? "the source selector and option give different paths" + : "@skill: selects skills; watch subscribes to whole sources" + + #expect(throws: CoreError.invalidSource(reason)) { + try fixture.watch.add( + fixture.id + selector, requirement: kind == "requirement" ? .branch("topic") : nil, + path: kind == "path" ? "other" : nil, environment: fixture.environment) + } + + #expect(try fixture.stateBytes() == before) + #expect(!FileManager.default.fileExists(atPath: fixture.mirror.path)) + } + + @Test func declaredIdentityIsPlannedBeforeGit() throws { + let fixture = try WatchGitFixture() + let before = try fixture.stateBytes() + struct PlanningFailed: Error {} + let watch = WatchOperations( + discoverSkills: { _ in [] }, + fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, + declarations: DeclarationAccess( + read: DeclarationAccess.manifest.read, + plan: { _, _, next, _ in + #expect(next.sources.count == 1 && next.watch == ["source"]) + throw PlanningFailed() + })) + + #expect(throws: PlanningFailed.self) { + try watch.add(fixture.id, environment: fixture.environment) + } + #expect(try fixture.stateBytes() == before) + #expect(!FileManager.default.fileExists(atPath: fixture.mirror.path)) + } +} From a2d734fb14cf2d93e7ddd8a6087d7c90453abea4 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:43:05 +0800 Subject: [PATCH 027/171] fix(manifest): expand calls for multiline argument insertions --- Documentation/Reference/Manifest.md | 6 + Sources/AgentsManifest/DocumentEdits.swift | 39 +++++- Tests/AgentsManifestTests/EditPlanTests.swift | 7 +- Tests/AgentsManifestTests/EditingTests.swift | 117 ++++++++++++++++++ .../ManifestLifecycleTests.swift | 3 +- 5 files changed, 168 insertions(+), 4 deletions(-) diff --git a/Documentation/Reference/Manifest.md b/Documentation/Reference/Manifest.md index 8b42eda..7f02115 100644 --- a/Documentation/Reference/Manifest.md +++ b/Documentation/Reference/Manifest.md @@ -946,6 +946,12 @@ precedence. Inserting the first argument into an empty argument list, such as argument starts a multiline list. Conflicting local style is an editability diagnostic, not permission to reformat the file. +Inserting a multiline argument into a nonempty single-line call expands that +call's argument boundaries using the document's indentation and newline style. +Existing argument expressions, order and owned comments keep their spelling; +bytes outside the call remain unchanged. Scalar additions keep the existing +single-line layout. + The editor and canonical printer emit one ASCII space on each side of `=` and `+`, with adjacent sign/digits for negative integers: `let value = -1`. A value replacement re-checks both joins with the unchanged source, including neighboring diff --git a/Sources/AgentsManifest/DocumentEdits.swift b/Sources/AgentsManifest/DocumentEdits.swift index 1c525ef..0e5500e 100644 --- a/Sources/AgentsManifest/DocumentEdits.swift +++ b/Sources/AgentsManifest/DocumentEdits.swift @@ -129,7 +129,10 @@ extension DocumentEditor { value, indentation: indentation + style.indent, column: (indentation + style.indent + label).utf8.count, trailing: multiline && next == nil ? 0 : 1)) - if let next { + if !multiline, !node.arguments.isEmpty, content.utf8.contains(10) || content.utf8.contains(13) { + try multilineArgument( + content, before: next, call: node, style: style, indentation: indentation) + } else if let next { let start = next.labelRange?.lowerBound ?? current.admission.nodes[next.value].range.lowerBound if multiline { @@ -162,6 +165,40 @@ extension DocumentEditor { try mutate(pointer + "/" + pointerEscape(field), value) } + /// Expand only argument boundaries; existing expressions and same-line comments retain + /// their spelling and ownership, and their occurrence handles remain addressable. + func multilineArgument( + _ content: String, before next: GrammarArgument?, call: GrammarNode, + style: PrintStyle, indentation: String + ) throws { + let argumentIndent = indentation + style.indent + func boundary(before offset: Int) -> Range { + var start = offset + while start > call.range.lowerBound && blank(start - 1) { start -= 1 } + return start.. Decla @Suite("Manifest document editing") struct EditingTests { + @Test(arguments: [(" ", "\n"), (" ", "\r\n"), ("\t", "\n"), ("\t", "\r\n")]) + func multilineArgumentInsertionExpandsOnlyItsCall(_ indent: String, _ newline: String) throws { + let prefix = + manifestHeader + """ + let alias = "fixture" + let recipients: [Agent] = [.codex] + let agents = Agents( + sources: [.source(name: "fixture", path: "./fixture")], + components: [ + // Keep this component. + + """ + let suffix = ", // Keep its neighbor.\n .instructions(sections: []),\n ]\n)" + let old = + ".skills(source : alias /* source */, /* source note */ exclude: [] /* exclude */, agents: recipients)" + let text = (prefix + " " + old + suffix).replacingOccurrences(of: " ", with: indent) + .replacingOccurrences(of: "\n", with: newline) + let doc = try DeclarationDocument( + bytes: Array(text.utf8), identity: DocumentIdentity("manifest")) + let override = SkillOverride.skill(name: "review", mode: .copy, agents: [.cursor]) + let handle = try #require(doc.node(at: "/components/0")) + let change = try doc.preparing([.upsertSkillOverride(handle, override)]) + let expanded = """ + .skills( + source : alias /* source */, /* source note */ + exclude: [] /* exclude */, + overrides: [ + .skill( + name: "review", + mode: .copy, + agents: [.cursor] + ), + ], + agents: recipients + ) + """ + .replacingOccurrences(of: " ", with: indent) + .replacingOccurrences(of: "\n", with: newline) + #expect( + String(decoding: change.bytes, as: UTF8.self) + == text.replacingOccurrences(of: old, with: expanded)) + let call = doc.admission.nodes[handle.syntax].range + #expect( + change.patches.allSatisfy { + $0.range.lowerBound >= call.lowerBound && $0.range.upperBound <= call.upperBound + }) + let result = try DeclarationDocument( + bytes: change.bytes, identity: DocumentIdentity("manifest")) + #expect(result.declaration == change.expectedDeclaration) + let noOp = try result.preparing([ + .upsertSkillOverride(result.node(at: "/components/0")!, override) + ]) + #expect(noOp.bytes == result.bytes && noOp.patches.isEmpty) + let batched = try doc.preparing(operations: [ + .edit(.upsertSkillOverride(handle, override)), + .insertElement(.text("unused"), into: doc.node(at: "/components/0/exclude")!, at: .last), + ]) + #expect( + String(decoding: batched.bytes, as: UTF8.self).contains("exclude: [\"unused\"] /* exclude */") + ) + } + + @Test func multilineArgumentCanPrecedeTheFirstExistingArgument() throws { + let doc = try document("let agents = Agents(watch: [])") + let result = try edited(doc, [.upsertSource(.source(name: "s", path: "./s"))]) + #expect( + String(decoding: result.bytes, as: UTF8.self) == manifestHeader + """ + let agents = Agents( + sources: [ + .source(name: "s", path: "./s"), + ], + watch: [] + ) + """) + } + + @Test func multilineArgumentAppendsToSingleLineCallsAndScalarEditsStayInline() throws { + let old = ".skills(source: \"fixture\", exclude: [])" + let doc = try document( + "let agents = Agents(sources: [.source(name: \"fixture\", path: \"./fixture\")], components: [\(old)])" + ) + let handle = try #require(doc.node(at: "/components/0")) + let result = try edited( + doc, [.upsertSkillOverride(handle, .skill(name: "review", mode: .copy))]) + let expanded = """ + .skills( + source: "fixture", + exclude: [], + overrides: [ + .skill(name: "review", mode: .copy) + ] + ) + """ + #expect( + result.bytes + == Array( + String(decoding: doc.bytes, as: UTF8.self).replacingOccurrences(of: old, with: expanded) + .utf8)) + let scalar = try doc.preparing(operations: [ + .setArgument(handle, field: "mode", value: InstallMode.copy.constructionValue) + ]) + #expect( + String(decoding: scalar.bytes, as: UTF8.self) + == String(decoding: doc.bytes, as: UTF8.self).replacingOccurrences( + of: old, with: ".skills(source: \"fixture\", exclude: [], mode: .copy)")) + let commented = try document( + "let agents = Agents(sources: [.source(name: \"fixture\", path: \"./fixture\")], components: [.skills(source: \"fixture\" /* trailing */)])" + ) + expectManifestFailure("manifest.edit.readOnly") { + try commented.preparing([ + .upsertSkillOverride( + commented.node(at: "/components/0")!, .skill(name: "review", mode: .copy)) + ]) + } + #expect(try doc.preparing([.setSkillSelection(handle, .all)]).bytes == doc.bytes) + } + @Test func rootArgumentsUseSignatureOrderAndCanonicalSourceRequirements() throws { let initial = try document("let agents = Agents()") let result = try edited( diff --git a/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift b/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift index a90c723..eaf8ad7 100644 --- a/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift @@ -117,7 +117,8 @@ struct ManifestLifecycleTests { let final = try text() #expect( final.hasPrefix( - header + "\n components: [\n // Everything the fixture publishes.\n .skills(source: " + header + + "\n components: [\n // Everything the fixture publishes.\n .skills(\n source: " )) #expect(final.hasSuffix("),\n ],\n watch: []\n)\n")) let declaration = try store.loadDeclaration() From 2124c44f76444a7e3cb81a9a0e35d85371b5a80a Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:44:45 +0800 Subject: [PATCH 028/171] ci: capture release test host crash diagnostics --- .github/swift-package.json | 4 ++ Scripts/diagnose-release-tests.py | 89 +++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 Scripts/diagnose-release-tests.py diff --git a/.github/swift-package.json b/.github/swift-package.json index 22e5cd5..49912fe 100644 --- a/.github/swift-package.json +++ b/.github/swift-package.json @@ -7,6 +7,10 @@ { "name": "manifest-fixture-generation", "run": "python3 Scripts/generate-manifest-fixtures.py --check" + }, + { + "name": "release-crash-diagnostics", + "run": "python3 Scripts/diagnose-release-tests.py" } ], "test_configurations": ["debug", "release"], diff --git a/Scripts/diagnose-release-tests.py b/Scripts/diagnose-release-tests.py new file mode 100644 index 0000000..b4ddcfb --- /dev/null +++ b/Scripts/diagnose-release-tests.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Capture the Release test host under LLDB on the selected macOS toolchain.""" + +import argparse +import json +import os +from pathlib import Path +import re +import shlex +import subprocess +import sys +import tempfile + + +ROOT = Path(__file__).resolve().parents[1] +OUTPUT = ROOT / ".build/release-crash-diagnostics" +FLAGS = ["-c", "release", "--disable-index-store", "--build-system", "native"] +FILTER = "PublicationTests.primitiveFailuresCleanPrivateResourcesBeforeChangingUserData" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--filter-only", action="store_true") + args = parser.parse_args() + OUTPUT.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="home-", dir=OUTPUT) as home: + environment = {key: value for key, value in os.environ.items() + if key in ("PATH", "DEVELOPER_DIR", "SDKROOT", "TMPDIR")} + environment.update(HOME=home, GIT_CONFIG_NOSYSTEM="1", + GIT_CONFIG_GLOBAL="/dev/null", GIT_TERMINAL_PROMPT="0", + TERM="dumb", LC_ALL="C") + + def output(command): + return subprocess.check_output(command, cwd=ROOT, env=environment, + text=True).strip() + + def record(name, command): + print(shlex.join(command), flush=True) + result = subprocess.run(command, cwd=ROOT, env=environment, + text=True, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, timeout=1800) + (OUTPUT / (name + ".log")).write_text(result.stdout) + print(result.stdout, flush=True) + return result + + print(output(["xcodebuild", "-version"]), flush=True) + print(output(["swift", "--version"]), flush=True) + print(output(["git", "rev-parse", "HEAD"]), flush=True) + build = record("build", ["swift", "test", *FLAGS, "list"]) + if build.returncode: + return build.returncode + swift = Path(output(["xcrun", "--find", "swift"])) + helper = swift.parent.parent / "libexec/swift/pm/swiftpm-testing-helper" + platform = Path(output(["xcrun", "--sdk", "macosx", "--show-sdk-platform-path"])) + binary_directory = Path(output(["swift", "build", *FLAGS, "--show-bin-path"])) + bundle = binary_directory / "corePackageTests.xctest/Contents/MacOS/corePackageTests" + framework_directory = platform / "Developer/Library/Frameworks" + for path in (helper, bundle, framework_directory / "Testing.framework"): + if not path.exists(): + raise RuntimeError(f"Missing selected-toolchain artifact: {path}") + settings = "settings set target.env-vars " + " ".join(map(shlex.quote, [ + "DYLD_FRAMEWORK_PATH=" + str(framework_directory), + "DYLD_LIBRARY_PATH=" + str(platform / "Developer/usr/lib"), + ])) + command = ["xcrun", "lldb", "--batch", "--no-lldbinit", "-o", settings, + "-o", "run", "-k", "thread backtrace all", "-k", "register read", + "-k", "image list", "--", str(helper), "--test-bundle-path", + str(bundle), "-c", "release", "--disable-index-store", str(bundle), + "--testing-library", "swift-testing"] + results = [] + probes = [("filtered", ["--filter", FILTER])] + if not args.filter_only: + probes.append(("full", [])) + for name, extra in probes: + result = record(name, command + extra) + passed = (result.returncode == 0 + and "stop reason =" not in result.stdout + and re.search(r"Test run with [1-9]\d* tests? in .* passed", result.stdout) + and re.search(r"Process \d+ exited with status = 0", result.stdout)) + results.append({"probe": name, "lldb_exit": result.returncode, + "passed": bool(passed), "command": command + extra}) + (OUTPUT / "results.json").write_text(json.dumps(results, indent=2) + "\n") + if not passed: + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 19be46f3c38efbd32bb95ae33649d1b141b7efe6 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:07:22 +0800 Subject: [PATCH 029/171] docs: define configuration application and connection checks --- Documentation/Decisions/AgentComponents.md | 2 +- .../Decisions/ConfigurationApplication.md | 53 ++++++++++++++++ Documentation/Decisions/ExecutableApproval.md | 4 +- Documentation/Decisions/README.md | 4 +- Documentation/Decisions/SwiftManifest.md | 2 +- Documentation/Proposals/AgentsManifest.md | 62 +++++++++++-------- Documentation/Proposals/README.md | 4 +- Documentation/Reference/Manifest.md | 6 +- 8 files changed, 102 insertions(+), 35 deletions(-) create mode 100644 Documentation/Decisions/ConfigurationApplication.md diff --git a/Documentation/Decisions/AgentComponents.md b/Documentation/Decisions/AgentComponents.md index 3c53628..0af6f00 100644 --- a/Documentation/Decisions/AgentComponents.md +++ b/Documentation/Decisions/AgentComponents.md @@ -89,4 +89,4 @@ physical locations; Codex, Cursor, Gemini CLI and OpenCode read the same - Current agent locations and state: [Package](../Architecture/Package.md), [State](../Architecture/State.md) - Manifest that declares components: [Swift Manifest](SwiftManifest.md) -- Approval before executable components deploy: [Executable Component Approval](ExecutableApproval.md) +- Configuration application and connection tests: [Configuration Application](ConfigurationApplication.md) diff --git a/Documentation/Decisions/ConfigurationApplication.md b/Documentation/Decisions/ConfigurationApplication.md new file mode 100644 index 0000000..58502a5 --- /dev/null +++ b/Documentation/Decisions/ConfigurationApplication.md @@ -0,0 +1,53 @@ +# Configuration Application + +## Status + +Accepted by the repository owner (showxu) on 2026-11-06. +Supersedes [Executable Component Approval](ExecutableApproval.md). + +## Context + +`agents` manages declarations, installed resources and native configuration. +The agent that consumes a configuration owns its runtime: starting servers, +authenticating, trusting a workspace and deciding whether to call a tool. +Configuration changes and runtime operations have different owners. + +## Decision + +- **One application action.** The GUI shows the concrete configuration changes + and targets, then applies them when the user confirms. An explicit modifying + CLI command expresses the same intent. External automation invokes those + commands within its supplied scope. The GUI checks, notifies and applies on + request. +- **Preview freshness.** Core validates that the candidate and relevant target + state still match the presented changes. If they changed, the front end + refreshes the preview before applying. +- **Configuration lifecycle.** Installation and updates write configuration, + resources and registration files. Parsing, inspection and configuration + application do not start the declared component programs. The manifest is + statically evaluated. +- **Optional MCP connection test.** A separate explicit action tests the chosen + configuration through protocol initialization and tool discovery. A stdio + test starts its displayed command; a remote test connects through the + declared transport. The test has bounded time and output, supports + cancellation and cleans up the connections and processes it owns. It does + not invoke business tools. Testing is independent of configuration apply. +- **Client-owned runtime decisions.** Server trust, tool-call authorization and + authentication remain with the consuming client. An adapter does not modify + those records merely to make a configured component appear active. Explicit + permission configuration remains a managed component with its own declared + intent. + +## Consequences + +The declaration records intent and the ledger records committed configuration +and ownership. CLI and GUI use the same prepare/apply transaction. Connection +tests return observations about the selected configuration in the current +environment; their result does not establish that a native client has loaded +or enabled the component. + +## Related Documentation + +- [Agent Components and Adapters](AgentComponents.md) +- [Swift Manifest](SwiftManifest.md) +- [Agents Manifest Contract](../Proposals/AgentsManifest.md) diff --git a/Documentation/Decisions/ExecutableApproval.md b/Documentation/Decisions/ExecutableApproval.md index 6fc9ef9..34a57d1 100644 --- a/Documentation/Decisions/ExecutableApproval.md +++ b/Documentation/Decisions/ExecutableApproval.md @@ -2,7 +2,9 @@ ## Status -Accepted +Superseded on 2026-11-06 by +[Configuration Application](ConfigurationApplication.md). The original decision +and its acceptance record below are retained as history. ## Context diff --git a/Documentation/Decisions/README.md b/Documentation/Decisions/README.md index 31615bf..e3d085f 100644 --- a/Documentation/Decisions/README.md +++ b/Documentation/Decisions/README.md @@ -14,7 +14,9 @@ This directory holds durable decision records for `skill-cli`. declaration with lossless edits - `AgentComponents.md`: component model, capability registry, input adapters and native deployment -- `ExecutableApproval.md`: per-machine approval of components that run code +- `ConfigurationApplication.md`: shared configuration preview/application and + explicitly invoked MCP connection tests +- `ExecutableApproval.md`: superseded decision, retained as history ## Placement diff --git a/Documentation/Decisions/SwiftManifest.md b/Documentation/Decisions/SwiftManifest.md index 66ffa18..e444998 100644 --- a/Documentation/Decisions/SwiftManifest.md +++ b/Documentation/Decisions/SwiftManifest.md @@ -87,5 +87,5 @@ uneditable for tools once it contains logic. - Current declaration, lock and state layout: [State](../Architecture/State.md) - Language specification: [Agents Manifest Language](../Reference/Manifest.md) - Component model the manifest describes: [Agent Components and Adapters](AgentComponents.md) -- Approval of executable components: [Executable Component Approval](ExecutableApproval.md) +- Configuration application: [Configuration Application](ConfigurationApplication.md) - Product scope and front ends: [agents-tools/cli decisions](https://github.com/agents-tools/cli/tree/master/Documentation/Decisions) diff --git a/Documentation/Proposals/AgentsManifest.md b/Documentation/Proposals/AgentsManifest.md index 87f238b..aa870f3 100644 --- a/Documentation/Proposals/AgentsManifest.md +++ b/Documentation/Proposals/AgentsManifest.md @@ -4,7 +4,8 @@ Accepted — partially implemented. Language version 1.0, its document editor and dump, and the `Agents.swift` state integration are implemented; targeting, -source linking, component deployment, approvals and lock version 2 are pending. +source linking, component deployment, configuration application and lock version 2 +are pending. ## Authors / Owners @@ -19,8 +20,8 @@ grammar recognition, SwiftSyntax parsing and static type checking produce an agent-independent intermediate representation (IR); source linking and capability-driven adapters produce native configuration files. The **deployment ledger**, `agents.resolved`, records exact -source pins, physical artifacts, owned keys/sections and their hashes. Machine -user state separately owns approvals for executable content. +source pins, physical artifacts, owned keys/sections and their hashes. CLI and +GUI apply concrete configuration changes through one shared transaction. The core repository's complete declaration is: @@ -85,7 +86,7 @@ resolved deployment facts. Comments and untouched source bytes remain intact. | --- | --- | | Construction vocabulary, files and versions, grammar, typing, resource limits, document editing, evaluated dump, diagnostics and conformance | Implemented; specified in the [manifest language reference](../Reference/Manifest.md). | | `Agents.swift` as scope declaration, deployable subset, declaration writes, absent-declaration rule and requirement comparison | Implemented; specified in [State](../Architecture/State.md#declaration). | -| [Component deployment](#component-deployment), [Targeting](#targeting), [Groups and source linking](#groups-and-source-linking), the `Components` target in [Target Architecture](#target-architecture), [Approvals](#approvals) and [Lock version 2](#lock-version-2-and-ownership-conversion) | Pending; specified below. | +| [Component deployment](#component-deployment), [Targeting](#targeting), [Groups and source linking](#groups-and-source-linking), the `Components` target in [Target Architecture](#target-architecture), [Configuration application](#configuration-application) and [Lock version 2](#lock-version-2-and-ownership-conversion) | Pending; specified below. | ## Motivation @@ -96,14 +97,15 @@ conditions and source provenance make deployment and conflicts explainable. The accepted [Swift manifest](../Decisions/SwiftManifest.md), [component](../Decisions/AgentComponents.md) and -[approval](../Decisions/ExecutableApproval.md) decisions constrain this contract. +[configuration application](../Decisions/ConfigurationApplication.md) decisions +constrain this contract. ## Proposed Change Adopt the vocabulary, static grammar, source editing and JSON contract of the [manifest language reference](../Reference/Manifest.md), and complete deployment of the whole vocabulary: targeting, group and source linking, native adapters -and executable approval. The types-only `AgentsDescription` and +and shared configuration application. The types-only `AgentsDescription` and document/compiler-front-end `AgentsManifest` library products exist; linking and native adapters belong in an internal `Components` target. Shared IR, source storage, capabilities and transactions stay in `AgentsCore`, and orchestration in @@ -142,7 +144,7 @@ resolved components are lowered to native configuration. | --- | --- | | Skills | Selection, exclusions, installation mode and member overrides preserve membership tracking and item pins. Duplicate names and conflicting members are diagnosed. | | Instructions | Contributions append sections in traversal order. Prompt names are unique; each prompt has its own ordered sections. | -| MCP server | Stdio, Streamable HTTP and SSE are distinct transports. Transport conversion must be exact; all registrations require approval. | +| MCP server | Stdio, Streamable HTTP and SSE are distinct transports. Transport conversion must be exact. Registration is a configuration change; an optional connection test is a separate explicit action. | | Hook | Portable events mean before/after a tool invocation and session start/end. Adapters preserve event and command-result behavior. `.native("event")` uses its single recipient's event grammar. Matchers use its verified grammar. Omitted timeouts retain the native default. Hooks preserve declaration order. | | Subagent | Description and prompt are portable text. Model/tool names are identifiers validated by the recipient adapter. Omitted tools inherit its default; `[]` requires no tools. | | Command | A named user-invoked prompt. Parameter tokens appear as literal `${input:name}`; missing required inputs are errors. Substitution is text, not shell evaluation. | @@ -164,18 +166,17 @@ component kind and adapter schema version. Agent identity is not repeated in the value. Registry validation checks fields, client-version compatibility and the component's recipients. A schema contributes only to its own agent and cannot replace portable fields, conditions, resource identities, target paths, owned-key -boundaries or approval metadata. Collisions and unknown schemas/fields/types are -errors for active deployment. A native permission policy can use empty portable +boundaries. Collisions and unknown schemas/fields/types are errors for active +deployment. A native permission policy can use empty portable rules when no exact portable translation exists. Native configuration remains -subject to ordinary preview, ownership and approval checks. +subject to ordinary preview, ownership and freshness checks. Capability validation checks every active agent/component/scope/feature against the registry; unsupported requests are reported rather than dropped. Inactive -branches still undergo syntax, type and domain checks. Pending executable -approval is separate: apply deploys approved components and reports pending or -refused components as undeployed. Local additions approve their reviewed content -identity through core's mutation API. Imports and group declarations do not -approve transitive or future content. +branches still undergo syntax, type and domain checks. Applying a valid candidate +commits its selected configuration changes. Imports and group selections use the +same preview and application boundary. Client runtime trust and tool-call +permissions remain with the client. ### Targeting @@ -489,9 +490,9 @@ Deployment adds or extends: | Target | Ownership and dependencies | | --- | --- | -| `AgentsCore` | Adds capability protocols/descriptors, resolved component IR and approval identity. No syntax or adapter-implementation dependency. | +| `AgentsCore` | Adds capability protocols/descriptors, resolved component IR and content identity. No syntax or adapter-implementation dependency. | | `Components` | Internal group linker, input-container adapters and native output adapters. Depends on `AgentsCore`, `AgentsManifest`, `AgentsSkills`, `AgentsInstructions`. Uses core source-resolution sessions and registers capability implementations during composition. Agent adapters are types/files, not one target per agent. | -| `AgentsUpdates` | Public prepare/apply orchestration across document edits, domains, components, approvals and one state transaction. Depends on the targets above; front ends consume its workflows. | +| `AgentsUpdates` | Public prepare/apply orchestration across document edits, domains, components and one state transaction. Depends on the targets above; front ends consume its workflows. | Core does not depend on `Components`; descriptions and document editing do not own a second state store. Public import names retain family identity; the @@ -526,13 +527,23 @@ publication of validated source bytes, the shared transaction with the ledger, watch state, native outputs and cache, and the preparation evidence for the manifest. -### Approvals +### Configuration application -Approval identity covers declarations, commands and shipped content, excluding -comments and formatting. Approval is machine-local; a copied ledger disposition -is not authorization on another machine. Apply checks the local approval for the -resolved content identity and reports pending/refused components independently -of source validity. +The GUI presents concrete configuration changes and targets. Confirming applies +that candidate through core. An explicit modifying CLI command expresses the +same application intent. Before publication, core checks the candidate and +relevant target state against the preparation evidence; changed evidence +requires preparation and preview to be refreshed. + +Configuration reads and application do not start declared component programs. +An optional MCP connection test is explicitly invoked against a selected +configuration snapshot. It initializes the protocol and discovers tools, with +bounded time/output, cancellation and cleanup of its own connections and +processes. A local stdio test starts the displayed command. The test does not +invoke business tools or determine whether configuration can be applied. +Client runtime trust, authentication and tool-call authorization remain with +the client. [Configuration Application](../Decisions/ConfigurationApplication.md) +owns this boundary. ## Compatibility / Migration Impact @@ -562,8 +573,7 @@ A deployment records registered-root-relative target, artifact kind, owners, recipients, owned keys/sections, expected content hash, source pins and adapter format. Whole-file versus managed-section ownership is explicit. For structured files, hash the owned values and retain formatting-sensitive patch preconditions; -unmanaged keys are not claimed. Local approval dispositions are observations, -not transferable authorization. +unmanaged keys are not claimed. Lock conversion derives ownership only from existing install/target records. Shared skill destinations coalesce only when mode, content and ownership agree. @@ -624,7 +634,7 @@ require current client probes. - [Agents Manifest Language](../Reference/Manifest.md) - [Swift Manifest](../Decisions/SwiftManifest.md) - [Agent Components and Adapters](../Decisions/AgentComponents.md) -- [Executable Component Approval](../Decisions/ExecutableApproval.md) +- [Configuration Application](../Decisions/ConfigurationApplication.md) - [Package Architecture](../Architecture/Package.md) - [State and Source Cache](../Architecture/State.md) - [Updates](../Architecture/Updates.md) diff --git a/Documentation/Proposals/README.md b/Documentation/Proposals/README.md index 94e6175..4432c5d 100644 --- a/Documentation/Proposals/README.md +++ b/Documentation/Proposals/README.md @@ -6,8 +6,8 @@ This directory holds design-in-progress documents and unresolved alternatives. - [Agents Manifest Contract](AgentsManifest.md) — owner: showxu; review status: Accepted — partially implemented. Pending targeting, group and source linking, - component deployment, approvals and lock version 2; the implemented language - is in [the manifest reference](../Reference/Manifest.md). + component deployment, configuration application and lock version 2; the + implemented language is in [the manifest reference](../Reference/Manifest.md). - `AgentInstructions.md`: skills and instructions as two kinds of one model, the declaration and lock formats, the command tree, the rules for writing diff --git a/Documentation/Reference/Manifest.md b/Documentation/Reference/Manifest.md index 7f02115..1e106c2 100644 --- a/Documentation/Reference/Manifest.md +++ b/Documentation/Reference/Manifest.md @@ -10,7 +10,7 @@ and conformance requirements. `AgentsDescription` supplies the vocabulary and [State](../Architecture/State.md#declaration) specifies the subset the state layer deploys and how declaration writes are published. The [manifest proposal](../Proposals/AgentsManifest.md) holds the pending targeting, -source linking, component deployment, approval and lock design. +source linking, component deployment, configuration application and lock design. The core repository declares: @@ -451,8 +451,8 @@ constants, inactive values and unused groups. A failure is a located | Plugins | The source is declared and `path` is a safe relative path. Native mode has exactly one explicit recipient and no selection or exclusions. Selections and exclusions have no duplicates. | | Configuration values | `.decimal` text is a finite JSON number. Duplicate decoded keys at any dictionary level are `manifest.dictionary.duplicateKey`. | -Recipient capabilities, native schema registration, executable approval and -adapter rules are deployment checks; the +Recipient capabilities, native schema registration and adapter rules are +deployment checks; the [manifest proposal](../Proposals/AgentsManifest.md#component-deployment) specifies them. From bf3e45522c72702891861336908150772c3ac9cd Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:19:17 +0800 Subject: [PATCH 030/171] fix: represent publication faults as task-local values --- Sources/AgentsCore/DirectoryHandle.swift | 13 ++++++++++--- Tests/AgentsCoreTests/PublicationTests.swift | 2 +- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/Sources/AgentsCore/DirectoryHandle.swift b/Sources/AgentsCore/DirectoryHandle.swift index 6cd9964..33e74ad 100644 --- a/Sources/AgentsCore/DirectoryHandle.swift +++ b/Sources/AgentsCore/DirectoryHandle.swift @@ -234,8 +234,13 @@ final class DirectoryHandle { } } - /// A non-nil injected errno replaces the platform result and takes the same classifier. - @TaskLocal static var atomicRenameFailure: (@Sendable (RenameMode) -> Int32?)? + struct AtomicRenameFailure: Sendable { + let mode: RenameMode + let code: Int32 + } + + /// A matching injected errno replaces the platform result and takes the same classifier. + @TaskLocal static var atomicRenameFailure: AtomicRenameFailure? var device: UInt64 { get throws { try objectIdentity.device } } var objectIdentity: FileObjectIdentity { @@ -297,7 +302,9 @@ final class DirectoryHandle { _ name: String, to parent: DirectoryHandle, named destination: String, mode: RenameMode ) -> RenameResult { - if let code = Self.atomicRenameFailure?(mode) { return RenameResult(code: code) } + if let failure = Self.atomicRenameFailure, failure.mode == mode { + return RenameResult(code: failure.code) + } let result = mode == .exchange ? platform_exchange(descriptor, name, parent.descriptor, destination) diff --git a/Tests/AgentsCoreTests/PublicationTests.swift b/Tests/AgentsCoreTests/PublicationTests.swift index 9593d5a..d732144 100644 --- a/Tests/AgentsCoreTests/PublicationTests.swift +++ b/Tests/AgentsCoreTests/PublicationTests.swift @@ -340,7 +340,7 @@ struct PublicationTests { : .unsupported( "atomic rename is required: \(operation): \(code) (\(String(cString: strerror(code))))") DirectoryHandle.$atomicRenameFailure.withValue( - { $0 == mode ? code : nil }, + DirectoryHandle.AtomicRenameFailure(mode: mode, code: code), operation: { #expect(throws: expected) { try transaction.commit() } }) #expect(outcome.disposition == .unchanged) try fixture.check(committed: false, journal: nil) From 7dfa15d175e50a5929ebbec3df80fc06ae35cacd Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 6 Nov 2026 21:55:56 +0800 Subject: [PATCH 031/171] feat: preserve complete symbolic component declarations --- Documentation/Architecture/Package.md | 17 +- Documentation/Architecture/README.md | 2 +- Documentation/Architecture/State.md | 73 +-- Documentation/Reference/Manifest.md | 7 +- README.md | 5 +- Sources/AgentsCore/ComponentDeclaration.swift | 301 +++++++++++++ Sources/AgentsCore/Declaration.swift | 319 +++++++++++--- .../InstructionDoctor.swift | 10 +- .../InstructionExport.swift | 2 +- .../InstructionOperations.swift | 32 +- .../CompleteDeclarationPlanner.swift | 195 ++++++++ .../ComponentConstruction.swift | 174 ++++++++ .../DeclarationConstruction.swift | 48 +- .../AgentsManifest/DeclarationEditPlan.swift | 78 +++- Sources/AgentsManifest/DeploymentSubset.swift | 71 +++ Sources/AgentsManifest/DocumentEditor.swift | 6 + Sources/AgentsManifest/DocumentEdits.swift | 11 +- Sources/AgentsManifest/DocumentModels.swift | 3 + .../AgentsManifest/ManifestProjection.swift | 416 +++++++++++------- Sources/AgentsManifest/ManifestState.swift | 18 +- Sources/AgentsSkills/SkillOperations.swift | 51 ++- Sources/AgentsUpdates/UpdatePlan.swift | 2 +- .../DeclarationStateTests.swift | 29 ++ .../StatePublicationTests.swift | 6 +- Tests/AgentsCoreTests/WatchSourceTests.swift | 15 +- .../LifecycleSafetyTests.swift | 12 +- .../LifecycleTests.swift | 13 +- .../DeclarationPropertyTests.swift | 28 +- Tests/AgentsManifestTests/EditPlanTests.swift | 91 ++-- .../FullDeclarationTests.swift | 351 +++++++++++++++ Tests/AgentsManifestTests/PrintingTests.swift | 14 +- .../AgentsManifestTests/ProjectionTests.swift | 164 +++---- .../LifecycleRegressionTests.swift | 6 +- .../ManifestLifecycleTests.swift | 4 +- .../SkillLifecycleTests.swift | 9 +- .../AgentsSkillsTests/SourceAliasTests.swift | 2 +- .../SourceShorthandTests.swift | 7 +- .../UpdateReportingTests.swift | 8 +- .../WatchSubscriptionTests.swift | 2 +- .../CombinedUpdateTests.swift | 40 +- .../RequirementUpdateTests.swift | 2 +- 41 files changed, 2097 insertions(+), 547 deletions(-) create mode 100644 Sources/AgentsCore/ComponentDeclaration.swift create mode 100644 Sources/AgentsManifest/CompleteDeclarationPlanner.swift create mode 100644 Sources/AgentsManifest/ComponentConstruction.swift create mode 100644 Sources/AgentsManifest/DeploymentSubset.swift create mode 100644 Tests/AgentsManifestTests/FullDeclarationTests.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index d0c4c25..44efcc4 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -121,8 +121,8 @@ The [manifest language reference](../Reference/Manifest.md) specifies the language, editing rules and dump schema. `AgentsManifest` also connects `Agents.swift` to scope state through -`extension StateStore`. The public `loadDeclaration()` returns the deployable -projection and `loadManifest()` the complete document; both are read-only and, +`extension StateStore`. The public `loadDeclaration()` returns the complete +typed symbolic declaration and `loadManifest()` the complete document; both are read-only and, like the public `WatchOperations.init(discoverSkills:fetchArtifacts:)`, require `import AgentsManifest`. Package-level declaration reading and planning, the projection onto @@ -131,8 +131,8 @@ modules, and `DeclarationAccess.manifest` supplies the same access to `WatchOperations`, whose public `init(discoverSkills:fetchArtifacts:)` this module provides. All file I/O, evidence and publication stay in `AgentsCore`: the extension parses prepared bytes and returns planned bytes. See -[Declaration](State.md#declaration) for the deployable subset and write -semantics. +[Declaration](State.md#declaration) for the current deployment boundary and full +declaration write semantics. `ManifestTestProcess` is a test-only executable and calls the same instrumented front-end pipeline as document construction. `ManifestTestSupport` owns the @@ -162,10 +162,11 @@ baselines and seeds belong to the test corpus, not the runtime language. - `DeclarationIR`, `DeclarationRecord` and `DeclarationValue` hold syntax-independent manifest intent; `SourceSpan`, `SourceProvenance` and `DeclarationSourceMap` carry document coordinates and origins without syntax or source access. -- `Declaration` is the typed in-memory projection of the deployable declaration - subset and has no serialized form; `ResolvedState` defines resolved version 1 - state. Together they hold the complete instruction section, prompt and - physical-target models. +- `Declaration` holds complete typed symbolic manifest intent: ordered component + and group occurrences, conditions, native values, symbolic group references and + source declaration directories. It has no serialized form. `ResolvedState` + defines version 1 skill/instruction state, including instruction sections, + prompts and physical targets. - `StateStore` owns scope paths, validation, deterministic lock and watch encoding and state persistence. It holds declaration bytes, their evidence, the absent-declaration rule and publication without knowing the declaration diff --git a/Documentation/Architecture/README.md b/Documentation/Architecture/README.md index 8c000c1..2893672 100644 --- a/Documentation/Architecture/README.md +++ b/Documentation/Architecture/README.md @@ -3,7 +3,7 @@ This directory holds the current truth for `core`, a SwiftPM library package. `AgentsDescription` supplies the types-only construction vocabulary. `AgentsManifest` statically evaluates and edits manifest snapshots, projects -`Agents.swift` onto the deployable declaration and plans declaration writes +`Agents.swift` onto the complete typed symbolic declaration and plans declaration writes through `StateStore`, whose file I/O stays in core. `AgentsCore` owns syntax-independent declaration IR, spans, provenance, shared sources, declaration bytes and lock storage, cache, watch subscriptions, and agent diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index a2a21a9..b168253 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -18,11 +18,13 @@ operations. `Agents.swift` records user intent in the [manifest language](../Reference/Manifest.md). The document is the declaration's only truth. `AgentsManifest` parses and evaluates its bytes and projects them onto -`AgentsCore.Declaration`, a typed in-memory view of the deployable subset with -no serialized form. `AgentsCore` holds the declaration's bytes and evidence, the +`AgentsCore.Declaration`, the complete typed symbolic intent with no serialized +form. Ordered sources, components, groups, uses, exports, prompt sections and +parameters retain their occurrences. Conditions, native values, runtime bindings +and source declaration directories remain data for later linking. `AgentsCore` holds the declaration's bytes and evidence, the absent-declaration rule and publication, and knows no syntax; `AgentsManifest` extends `StateStore` with declaration reading, planning and loading. Parse, edit -and subset failures are `ManifestFailure` diagnostics located in the declaration +and deployment-boundary failures are `ManifestFailure` diagnostics located in the declaration file. ```swift @@ -48,17 +50,32 @@ let agents = Agents( ### Deployable subset -The state layer deploys root `defaultAgents`, `sources` and `watch`, and root -`components` of kinds `.skills` and `.instructions`: at most one skills component -per source alias and one instructions component, with no `condition` on a -component, section or prompt and an empty `native`. Groups and exports may be -declared; unused groups are inert. Every other active structure fails with -`manifest.unsupported` at its location, and nothing is dropped: root `uses`, a -condition, native configuration, another component kind, a second skills -component for one alias, a second instructions component, or -`.skills(source: ".")`. After projection, `Declaration.validate(environment:)` -performs the checks that depend on the runtime environment, such as duplicate -identities after local-path expansion. +`loadDeclaration()` projects every language 1.0 component family, including MCP, +hooks, subagents, commands, LSP, permissions, ignores and plugins. It preserves +unused groups and inactive structures and never resolves sources, reads resources +or runs component programs. `Declaration.sourceDeclarations` and `components` +are the ordered owners; alias dictionaries and the flat skill/instruction accessors +are derived views. Source aliases retain their declaring project and home +directories so importing code cannot reinterpret their relative paths. + +The current skill/instruction deployment paths use +`readDeploymentDeclaration(prepared:)`. This explicit boundary accepts root +`defaultAgents`, `sources` and `watch`, and root `.skills` and `.instructions` +components: at most one skills occurrence per alias and one instructions +occurrence, with no condition on a component, section or prompt and empty native +configuration. Unused groups and exports remain preserved. Active group uses, +own-package skill discovery and other component families require linking or +native lowering and fail with a located `manifest.unsupported` before source work +or deployment. Repeated matching root selections fail with `manifest.ambiguous` +and related occurrence locations. Full declaration reads do not use this gate. + +`Declaration.skills` and `instructions` are throwing root-selection views: they +reject multiple matching occurrences. `setSkills`, `setInstructions`, +`updateSkills` and `updateInstructions` serve the current domain operations and +preserve unrelated components. Full occurrence edits use `components`, group +payloads and typed section references directly. `Declaration.validate(environment:)` +checks source identities using the aliases' declaring directories and validates +skill and instruction references. `defaultAgents` defaults to `codex` and `claude-code`. Explicit recipients, including an empty array, replace the default; the projection keeps omitted and @@ -140,11 +157,17 @@ Semantic equality decides whether anything changes: - recipient arrays compare as sets, with omitted and empty distinct; - omitted and empty exclusions, overrides, prompts, watch lists and skills components are equal; -- sections compare in order. - -Planning makes minimal document edits and never reorders existing text. A new -source is appended, a changed source is replaced in place, and a removed source -goes after the components that reference it in the same batch. A new skills +- components, source aliases, groups, uses, exports, sections and prompts compare + in order; conditions, symbolic references, runtime bindings and native values + all participate. + +Planning edits direct fields, dictionary members and ordered occurrences. Existing +skill/instruction workflows keep their established insertion order. Explicit +changes to full ordered collections retain matching occurrences where possible; +a length change with repeated matching names is ambiguous and requires an +occurrence-addressed `ManifestEdit`. The skill/instruction plan appends new +sources, replaces changed sources in place and removes sources after their +references. A new skills component is inserted before the instructions component, or last; a new instructions component is last. Selections, exclusions, recipients, mode, overrides, sections, prompts, watch aliases and default recipients change at @@ -158,10 +181,10 @@ ambiguous comments, fail with `manifest.edit.readOnly`. A batch holds at most remaining difference is planned. The projection of the final document must equal the intended declaration, or planning fails with `manifest.edit.mismatch`. -Without declaration bytes, planning prints the complete declaration with the -[canonical printer](../Reference/Manifest.md#canonical-printing): sources, skills -components, overrides, prompts, selected names and watch aliases sorted by UTF-8 -bytes, recipients deduplicated in agent-ID order, and skills before instructions. +Without declaration bytes, planning prints the complete typed declaration with the +[canonical printer](../Reference/Manifest.md#canonical-printing), retaining its +ordered collections and symbolic group uses. Dictionary-based convenience +initializers and domain mutations choose deterministic order for new entries. The printed bytes pass the same front end and projection check and are published with no-replace. A semantically empty declaration creates no file. @@ -476,8 +499,8 @@ recovery material changed. A committed failure is never described as rollback. The public `StateStore.loadResolved()` and `loadWatch()` in `AgentsCore` and `loadDeclaration()` and `loadManifest()` in `AgentsManifest` are read-only, as described below; the latter two require `import AgentsManifest`. -`loadDeclaration()` returns the deployable projection; `loadManifest()` returns -the complete `DeclarationDocument` without subset projection, or `nil` for a +`loadDeclaration()` returns the complete typed symbolic declaration; `loadManifest()` +returns the complete `DeclarationDocument`, or `nil` for a scope without state. Both can also throw the declaration's `ManifestFailure`. ### Read-only access diff --git a/Documentation/Reference/Manifest.md b/Documentation/Reference/Manifest.md index 1e106c2..7fd4a85 100644 --- a/Documentation/Reference/Manifest.md +++ b/Documentation/Reference/Manifest.md @@ -7,8 +7,8 @@ typing, resource limits, document editing, the evaluated JSON dump, diagnostics and conformance requirements. `AgentsDescription` supplies the vocabulary and `AgentsManifest` implements the front end, editor and dump. -[State](../Architecture/State.md#declaration) specifies the subset the state -layer deploys and how declaration writes are published. The +[State](../Architecture/State.md#declaration) specifies the complete typed +declaration, the current deployment boundary and how declaration writes are published. The [manifest proposal](../Proposals/AgentsManifest.md) holds the pending targeting, source linking, component deployment, configuration application and lock design. @@ -1108,7 +1108,8 @@ no partial declaration is published. | `manifest.diagnostics.truncated` | The warning that replaces diagnostics beyond the limit. | | `manifest.edit.readOnly`, `.stale`, `.overlap`, `.impact`, `.mismatch` | Document editing, as described under Document Editing. Declaration edit planning also reports `.mismatch` when a batch makes no progress or the final projection differs from the intended declaration. | | `manifest.edit.baseline` | Declaration edit planning: the declaration an operation read differs from the projection of the bytes it prepared. The state layer reports it as a stale preparation; see [Declaration writes](../Architecture/State.md#declaration-writes). | -| `manifest.unsupported` | The state layer's deployable-subset projection meets an active structure outside that subset; the span locates it. See [State](../Architecture/State.md#deployable-subset). | +| `manifest.unsupported` | A deployment reader meets an active structure requiring linking or native lowering; full declaration projection still preserves it. See [State](../Architecture/State.md#deployable-subset). | +| `manifest.ambiguous` | A named deployment selection or ordered edit matches multiple occurrences; related spans identify the candidates. Address a document occurrence explicitly. | | `manifest.dump.mismatch` | A source-map pointer is absent from the evaluated declaration while building a dump; this is an implementation regression. | ## Conformance and Validation diff --git a/README.md b/README.md index 9bd2156..4a6ed4e 100644 --- a/README.md +++ b/README.md @@ -139,7 +139,10 @@ and agent-to-mode mapping. `link` uses shared cached content, `copy` writes a directory, and `edit` links a live local source with no requirement or pin. Local Git installs in `link` and `copy` use committed content. -`AgentsCore` defines the instruction declaration and lock models. Skill +`AgentsCore` defines the complete typed declaration and the skill and instruction +lock models. +`loadDeclaration()` preserves all component families, conditions and symbolic +groups; deployment support is checked by the owning operation. Skill operations preserve the instruction and watch declarations and the locked instruction records. diff --git a/Sources/AgentsCore/ComponentDeclaration.swift b/Sources/AgentsCore/ComponentDeclaration.swift new file mode 100644 index 0000000..a8cfb91 --- /dev/null +++ b/Sources/AgentsCore/ComponentDeclaration.swift @@ -0,0 +1,301 @@ +import Foundation + +/// Directories in which a source alias was declared. Linking must not reinterpret relative +/// paths using the importing document's directories. Process environment values are not captured. +public struct SourceEnvironment: Equatable, Sendable { + public var projectDirectory: URL + public var homeDirectory: URL + + public init(projectDirectory: URL, homeDirectory: URL) { + self.projectDirectory = projectDirectory.standardizedFileURL + self.homeDirectory = homeDirectory.standardizedFileURL + } + + /// URL directory hints do not change the declaring directory's identity. + public static func == (lhs: SourceEnvironment, rhs: SourceEnvironment) -> Bool { + lhs.projectDirectory.standardizedFileURL.path == rhs.projectDirectory.standardizedFileURL.path + && lhs.homeDirectory.standardizedFileURL.path == rhs.homeDirectory.standardizedFileURL.path + } + + package var runtime: RuntimeEnvironment { + RuntimeEnvironment( + projectDirectory: projectDirectory, homeDirectory: homeDirectory, environment: [:]) + } +} + +public struct NamedSourceDeclaration: Equatable, Sendable { + public var name: String + public var source: SourceDeclaration + + public init(name: String, source: SourceDeclaration) { + self.name = name + self.source = source + } +} + +public enum DeclarationPlatform: String, Equatable, Sendable { + case macOS = "macos" + case linux +} + +/// Omitted dimensions impose no restriction; an explicit empty dimension matches nothing. +public struct DeclarationCondition: Equatable, Sendable { + public var agents: [AgentID]? + public var scopes: [InstallScope]? + public var platforms: [DeclarationPlatform]? + + public init( + agents: [AgentID]? = nil, scopes: [InstallScope]? = nil, platforms: [DeclarationPlatform]? = nil + ) { + self.agents = agents + self.scopes = scopes + self.platforms = platforms + } +} + +/// Values remain symbolic until binding at the consuming operation. +public enum RuntimeBinding: Equatable, Sendable { + case literal(String) + case environment(String) + case secret(String) +} + +public indirect enum NativeValue: Equatable, Sendable { + case string(String) + case integer(Int) + case decimal(String) + case boolean(Bool) + case null + case array([NativeValue]) + case object([String: NativeValue]) +} + +public typealias NativeConfiguration = [String: [String: NativeValue]] + +public struct ResourceDeclaration: Equatable, Sendable { + public var path: String + public var source: String? + + public init(path: String, source: String? = nil) { + self.path = path + self.source = source + } +} + +public enum PromptBody: Equatable, Sendable { + case literal(String) + case file(ResourceDeclaration) +} + +public struct ExecutableDeclaration: Equatable, Sendable { + public var executable: String + public var arguments: [String] + public var environment: [String: RuntimeBinding] + public var workingDirectory: ResourceDeclaration? + + public init( + executable: String, arguments: [String] = [], environment: [String: RuntimeBinding] = [:], + workingDirectory: ResourceDeclaration? = nil + ) { + self.executable = executable + self.arguments = arguments + self.environment = environment + self.workingDirectory = workingDirectory + } +} + +public enum MCPTransportDeclaration: Equatable, Sendable { + case stdio(ExecutableDeclaration) + case streamableHTTP(url: String, headers: [String: RuntimeBinding] = [:]) + case sse(url: String, headers: [String: RuntimeBinding] = [:]) +} + +public enum HookEventDeclaration: Equatable, Sendable { + case beforeTool + case afterTool + case sessionStart + case sessionEnd + case native(String) +} + +public struct PromptParameterDeclaration: Equatable, Sendable { + public var name: String + public var description: String + public var defaultValue: String? + + public init(name: String, description: String, defaultValue: String? = nil) { + self.name = name + self.description = description + self.defaultValue = defaultValue + } +} + +public enum PermissionOperationDeclaration: Equatable, Sendable { + case read + case write + case execute + case tool(String) +} + +public enum PermissionRuleDeclaration: Equatable, Sendable { + case allow(PermissionOperationDeclaration, String) + case ask(PermissionOperationDeclaration, String) + case deny(PermissionOperationDeclaration, String) +} + +public enum IgnorePurposeDeclaration: String, Equatable, Sendable { + case context + case indexing +} + +public enum PluginModeDeclaration: String, Equatable, Sendable { + case native + case components +} + +public enum DeclaredComponentKind: String, CaseIterable, Equatable, Sendable { + case skills, instructions, mcpServer, hook, subagent, command, lspServer, permissions, ignore, + plugin +} + +public enum ComponentReferenceDeclaration: Equatable, Sendable { + case skill(name: String) + case instruction(name: String) + case mcpServer(name: String) + case hook(name: String) + case subagent(name: String) + case command(name: String) + case lspServer(name: String) + case permissions(name: String) + case ignore(name: String) + case plugin(name: String) +} + +public struct SectionDeclaration: Equatable, Sendable { + public var name: String + public var source: String? + public var condition: DeclarationCondition? + + public init(name: String, source: String? = nil, condition: DeclarationCondition? = nil) { + self.name = name + self.source = source + self.condition = condition + } + + public init(reference: String) { + if let colon = reference.firstIndex(of: ":") { + self.init( + name: String(reference[reference.index(after: colon)...]), + source: String(reference[.. String { @@ -65,6 +68,7 @@ public struct SourceDeclaration: Equatable, Sendable { } package func localURL(environment: RuntimeEnvironment) -> URL { + let environment = self.environment.map { $0.runtime } ?? environment let expanded = location == "~" ? environment.homeDirectory.path @@ -107,73 +111,256 @@ public struct SkillDeclaration: Equatable, Sendable { public var exclude: [String]? public var agents: [AgentID]? public var mode: InstallMode? - public var overrides: [String: SkillOverride]? + public var overrideDeclarations: [NamedSkillOverrideDeclaration] + + public var overrides: [String: SkillOverride]? { + get { + overrideDeclarations.isEmpty + ? nil + : Dictionary(uniqueKeysWithValues: overrideDeclarations.map { ($0.name, $0.override) }) + } + set { + let retained = Set(overrideDeclarations.map(\.name)) + overrideDeclarations = + overrideDeclarations.compactMap { entry in + newValue?[entry.name].map { + NamedSkillOverrideDeclaration(name: entry.name, override: $0) + } + } + + (newValue ?? [:]).keys.filter { !retained.contains($0) }.sorted(by: declarationNameLess) + .map { + NamedSkillOverrideDeclaration(name: $0, override: newValue![$0]!) + } + } + } + public var condition: DeclarationCondition? + public var native: NativeConfiguration public init( select: SkillSelection, exclude: [String]? = nil, agents: [AgentID]? = nil, - mode: InstallMode? = nil, overrides: [String: SkillOverride]? = nil + mode: InstallMode? = nil, overrides: [String: SkillOverride]? = nil, + condition: DeclarationCondition? = nil, native: NativeConfiguration = [:] ) { self.select = select self.exclude = exclude self.agents = agents self.mode = mode - self.overrides = overrides + overrideDeclarations = (overrides ?? [:]).keys.sorted(by: declarationNameLess).map { + NamedSkillOverrideDeclaration(name: $0, override: overrides![$0]!) + } + self.condition = condition + self.native = native } } public struct PromptDeclaration: Equatable, Sendable { - /// Source alias and section name pairs, in rendering order. - public var sections: [String] + public var sectionReferences: [SectionDeclaration] public var append: String? + public var condition: DeclarationCondition? - public init(sections: [String], append: String? = nil) { - self.sections = sections + public init(sections: [String], append: String? = nil, condition: DeclarationCondition? = nil) { + sectionReferences = sections.map(SectionDeclaration.init(reference:)) self.append = append + self.condition = condition + } + + public var sections: [String] { + get { sectionReferences.map(\.reference) } + set { sectionReferences = newValue.map(SectionDeclaration.init(reference:)) } } } public struct InstructionsDeclaration: Equatable, Sendable { public var agents: [AgentID]? - public var sections: [String] - public var chatgpt: [String: PromptDeclaration]? + public var sectionReferences: [SectionDeclaration] + public var prompts: [NamedPromptDeclaration] + public var condition: DeclarationCondition? + public var native: NativeConfiguration public init( - agents: [AgentID]? = nil, sections: [String] = [], chatgpt: [String: PromptDeclaration]? = nil + agents: [AgentID]? = nil, sections: [String] = [], chatgpt: [String: PromptDeclaration]? = nil, + condition: DeclarationCondition? = nil, native: NativeConfiguration = [:] ) { self.agents = agents - self.sections = sections - self.chatgpt = chatgpt + sectionReferences = sections.map(SectionDeclaration.init(reference:)) + prompts = (chatgpt ?? [:]).keys.sorted(by: declarationNameLess).map { + NamedPromptDeclaration(name: $0, prompt: chatgpt![$0]!) + } + self.condition = condition + self.native = native + } + + public var sections: [String] { + get { sectionReferences.map(\.reference) } + set { sectionReferences = newValue.map(SectionDeclaration.init(reference:)) } + } + + public var chatgpt: [String: PromptDeclaration]? { + get { + prompts.isEmpty ? nil : Dictionary(uniqueKeysWithValues: prompts.map { ($0.name, $0.prompt) }) + } + set { + let retained = Set(prompts.map(\.name)) + prompts = + prompts.compactMap { entry in + newValue?[entry.name].map { NamedPromptDeclaration(name: entry.name, prompt: $0) } + } + + (newValue ?? [:]).keys.filter { !retained.contains($0) }.sorted(by: declarationNameLess) + .map { + NamedPromptDeclaration(name: $0, prompt: newValue![$0]!) + } + } } } -/// User intent from the scope's declaration document. Section order is significant; other -/// collections are unordered. +/// Complete symbolic intent. Components, sources, groups, uses and exports retain their order. +/// Source discovery and condition evaluation belong to linking, after this declaration is read. public struct Declaration: Equatable, Sendable { public var agents: [AgentID]? - public var sources: [String: SourceDeclaration] - public var skills: [String: SkillDeclaration]? - public var instructions: InstructionsDeclaration? + public var sourceDeclarations: [NamedSourceDeclaration] + public var components: [ComponentDeclaration] + public var groups: [ComponentGroupDeclaration] + public var uses: [GroupUseDeclaration] + public var exports: [String] public var watch: [String]? public init( agents: [AgentID]? = nil, sources: [String: SourceDeclaration] = [:], skills: [String: SkillDeclaration]? = nil, instructions: InstructionsDeclaration? = nil, - watch: [String]? = nil + watch: [String]? = nil, components: [ComponentDeclaration] = [], + groups: [ComponentGroupDeclaration] = [], uses: [GroupUseDeclaration] = [], + exports: [String] = [] ) { self.agents = agents - self.sources = sources - self.skills = skills - self.instructions = instructions + sourceDeclarations = sources.keys.sorted(by: declarationNameLess).map { + NamedSourceDeclaration(name: $0, source: sources[$0]!) + } + self.components = + (skills ?? [:]).keys.sorted(by: declarationNameLess).map { .skills(source: $0, skills![$0]!) } + + (instructions.map { [.instructions($0)] } ?? []) + components + self.groups = groups + self.uses = uses + self.exports = exports self.watch = watch } + public init( + agents: [AgentID]? = nil, sourceDeclarations: [NamedSourceDeclaration], + components: [ComponentDeclaration] = [], groups: [ComponentGroupDeclaration] = [], + uses: [GroupUseDeclaration] = [], exports: [String] = [], watch: [String]? = nil + ) { + self.agents = agents + self.sourceDeclarations = sourceDeclarations + self.components = components + self.groups = groups + self.uses = uses + self.exports = exports + self.watch = watch + } + + /// Alias access preserves the positions and declaration environments of retained sources. + public var sources: [String: SourceDeclaration] { + get { Dictionary(uniqueKeysWithValues: sourceDeclarations.map { ($0.name, $0.source) }) } + set { + let retained = Set(sourceDeclarations.map(\.name)) + sourceDeclarations = + sourceDeclarations.compactMap { entry in + newValue[entry.name].map { NamedSourceDeclaration(name: entry.name, source: $0) } + } + + newValue.keys.filter { !retained.contains($0) }.sorted(by: declarationNameLess).map { + NamedSourceDeclaration(name: $0, source: newValue[$0]!) + } + } + } + public var defaultAgents: [AgentID] { agents ?? [.codex, .claudeCode] } + /// The flat root selection used by existing skill operations. Multiple occurrences require + /// an occurrence-addressed edit; no occurrence is selected by precedence or condition. + public var skills: [String: SkillDeclaration]? { + get throws { + var result: [String: SkillDeclaration] = [:] + for case .skills(let source, let selection) in components { + guard result[source] == nil else { + throw CoreError.invalidState("ambiguous skills occurrence: \(source)") + } + result[source] = selection + } + return result.isEmpty ? nil : result + } + } + + public mutating func setSkills(_ selections: [String: SkillDeclaration]?) throws { + _ = try skills + var pending = selections ?? [:] + components = components.compactMap { component in + guard case .skills(let source, _) = component else { return component } + return pending.removeValue(forKey: source).map { .skills(source: source, $0) } + } + let additions = pending.keys.sorted(by: declarationNameLess).map { + ComponentDeclaration.skills(source: $0, pending[$0]!) + } + let insertion = + components.firstIndex { + if case .instructions = $0 { return true } + return false + } ?? components.endIndex + components.insert(contentsOf: additions, at: insertion) + } + + public mutating func updateSkills(_ change: (inout [String: SkillDeclaration]?) throws -> Void) + throws + { + var selections = try skills + try change(&selections) + try setSkills(selections) + } + + public var instructions: InstructionsDeclaration? { + get throws { + let values = components.compactMap { component -> InstructionsDeclaration? in + if case .instructions(let value) = component { return value } + return nil + } + guard values.count <= 1 else { + throw CoreError.invalidState("ambiguous instructions occurrence") + } + return values.first + } + } + + public mutating func setInstructions(_ value: InstructionsDeclaration?) throws { + _ = try instructions + if let index = components.firstIndex(where: { + if case .instructions = $0 { return true } + return false + }) { + if let value { + components[index] = .instructions(value) + } else { + components.remove(at: index) + } + } else if let value { + components.append(.instructions(value)) + } + } + + public mutating func updateInstructions(_ change: (inout InstructionsDeclaration?) throws -> Void) + throws + { + var value = try instructions + try change(&value) + try setInstructions(value) + } + public func validate(environment: RuntimeEnvironment) throws { + var aliases = Set() var identities = Set() - for (alias, source) in sources { - guard !alias.isEmpty, alias != ".", !alias.contains(":") else { - throw CoreError.invalidState("invalid source alias: \(alias)") + for entry in sourceDeclarations { + let (alias, source) = (entry.name, entry.source) + guard !alias.isEmpty, alias != ".", !alias.contains(":"), aliases.insert(alias).inserted + else { + throw CoreError.invalidState("invalid or duplicate source alias: \(alias)") } guard try identities.insert(source.identity(environment: environment)).inserted else { throw CoreError.invalidState("two source aliases normalize to the same source ID") @@ -184,39 +371,44 @@ public struct Declaration: Equatable, Sendable { throw CoreError.invalidState("well-known sources take no Git requirement") } } - for (alias, selection) in skills ?? [:] { - guard let source = sources[alias] else { - throw CoreError.invalidState("unknown source alias: \(alias)") + for component in components + groups.flatMap(\.components) { + switch component { + case .skills(let alias, let selection): + guard alias == "." || sources[alias] != nil else { + throw CoreError.invalidState("unknown source alias: \(alias)") + } + let source = sources[alias] + let modes = + [selection.mode ?? .link] + selection.overrideDeclarations.compactMap { $0.override.mode } + if modes.contains(.edit), alias != ".", source?.kind != .local || source?.requirement != nil + { + throw CoreError.invalidState("edit requires a local source with no requirement") + } + if case .names(let names) = selection.select { try Self.validateNames(names) } + try Self.validateNames(selection.exclude ?? []) + try Self.validateNames(selection.overrideDeclarations.map(\.name)) + case .instructions(let instructions): + for section in instructions.sectionReferences + + instructions.prompts.flatMap({ $0.prompt.sectionReferences }) + { + guard Self.isInstructionName(section.name), + section.source == nil || section.source == "." || sources[section.source!] != nil + else { + throw CoreError.invalidState("invalid section reference: \(section.reference)") + } + } + for entry in instructions.prompts { + if let append = entry.prompt.append { _ = try PathSafety.sanitizeSubpath(append) } + } + default: break } - var modes = [selection.mode ?? .link] - modes += (selection.overrides ?? [:]).values.compactMap(\.mode) - if modes.contains(.edit), source.kind != .local || source.requirement != nil { - throw CoreError.invalidState("edit requires a local source with no requirement") - } - if case .names(let names) = selection.select { try Self.validateNames(names) } - try Self.validateNames(selection.exclude ?? []) - try Self.validateNames(Array((selection.overrides ?? [:]).keys)) } guard Set(watch ?? []).count == (watch ?? []).count else { throw CoreError.invalidState("duplicate watch subscription") } - for alias in watch ?? [] where sources[alias] == nil { + for alias in watch ?? [] where !aliases.contains(alias) { throw CoreError.invalidState("unknown watch source: \(alias)") } - for reference in (instructions?.sections ?? []) - + (instructions?.chatgpt ?? [:]).values.flatMap(\.sections) - { - let parts = reference.split(separator: ":", omittingEmptySubsequences: false) - 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 @@ -240,16 +432,24 @@ public struct Declaration: Equatable, Sendable { var result = self result.agents?.sort { $0.rawValue < $1.rawValue } result.watch?.sort() - result.instructions?.agents?.sort { $0.rawValue < $1.rawValue } - for alias in (result.skills ?? [:]).keys { - result.skills?[alias]?.exclude?.sort() - result.skills?[alias]?.agents?.sort { $0.rawValue < $1.rawValue } - for name in (result.skills?[alias]?.overrides ?? [:]).keys { - result.skills?[alias]?.overrides?[name]?.agents?.sort { $0.rawValue < $1.rawValue } + result.components = components.map { component in + switch component { + case .skills(let source, var selection): + selection.exclude?.sort() + selection.agents?.sort { $0.rawValue < $1.rawValue } + for index in selection.overrideDeclarations.indices { + selection.overrideDeclarations[index].override.agents?.sort { $0.rawValue < $1.rawValue } + } + return .skills(source: source, selection) + case .instructions(var instructions): + instructions.agents?.sort { $0.rawValue < $1.rawValue } + return .instructions(instructions) + default: return component } } return result } + } extension Declaration { @@ -274,3 +474,8 @@ extension Declaration { return candidate } } + +/// Canonical order for new entries supplied through alias/name dictionaries. +private func declarationNameLess(_ lhs: String, _ rhs: String) -> Bool { + lhs.utf8.lexicographicallyPrecedes(rhs.utf8) +} diff --git a/Sources/AgentsInstructions/InstructionDoctor.swift b/Sources/AgentsInstructions/InstructionDoctor.swift index c7a5e21..b08dfd7 100644 --- a/Sources/AgentsInstructions/InstructionDoctor.swift +++ b/Sources/AgentsInstructions/InstructionDoctor.swift @@ -22,7 +22,7 @@ extension InstructionOperations { let otherSections: [LockedSection]? = try other.withReadLock( onPendingRecovery: { nil }, { - _ = try other.readDeclaration() + _ = try other.readDeploymentDeclaration() return try other.readResolved().instructions.sections }) let otherDiagnostics = otherSections == nil ? [pendingRecovery(other)] : [] @@ -33,15 +33,15 @@ extension InstructionOperations { root: root, diagnostics: otherDiagnostics + [pendingRecovery(store)]) }, { - let declaration = try store.readDeclaration() + let declaration = try store.readDeploymentDeclaration() let lock = try store.readResolved() var diagnostics = otherDiagnostics func report(_ kind: InstructionDiagnostic.Kind, _ message: String, _ path: URL? = nil) { diagnostics.append(InstructionDiagnostic(kind: kind, message: message, path: path)) } if !FileManager.default.fileExists(atPath: store.resolvedURL.path), - !(declaration.instructions?.sections.isEmpty ?? true) - || !(declaration.instructions?.chatgpt?.isEmpty ?? true) + try !((declaration.instructions)?.sections.isEmpty ?? true) + || !((declaration.instructions)?.chatgpt?.isEmpty ?? true) { report( .missingLock, "Instruction declaration has no lock; update can reconstruct it.", @@ -127,7 +127,7 @@ extension InstructionOperations { } } let agents = Set(lock.instructions.targets.values.flatMap(\.agents)) - .union(declaration.instructions?.agents ?? declaration.defaultAgents) + .union((try declaration.instructions)?.agents ?? declaration.defaultAgents) let claudeTargets = lock.instructions.targets.filter { $0.value.import == nil && $0.value.agents.contains(.claudeCode) }.keys.sorted() diff --git a/Sources/AgentsInstructions/InstructionExport.swift b/Sources/AgentsInstructions/InstructionExport.swift index 50d53a5..a94143e 100644 --- a/Sources/AgentsInstructions/InstructionExport.swift +++ b/Sources/AgentsInstructions/InstructionExport.swift @@ -60,7 +60,7 @@ extension InstructionOperations { return try store.withReadLock( onPendingRecovery: { empty(.pendingRecovery) }, { - _ = try store.readDeclaration() + _ = try store.readDeploymentDeclaration() guard try store.existingData(store.resolvedURL) != nil else { return empty(.missingLock) } diff --git a/Sources/AgentsInstructions/InstructionOperations.swift b/Sources/AgentsInstructions/InstructionOperations.swift index e97cf3a..1929a7c 100644 --- a/Sources/AgentsInstructions/InstructionOperations.swift +++ b/Sources/AgentsInstructions/InstructionOperations.swift @@ -86,13 +86,13 @@ public enum InstructionOperations { } } guard !selected.isEmpty else { throw CoreError.notFound("source provides no instructions") } - var instructions = declaration.instructions ?? InstructionsDeclaration() + var instructions = (try declaration.instructions) ?? InstructionsDeclaration() if let agents = options.agents { instructions.agents = agents } let references = selected.map { (alias.map { $0 + ":" } ?? "") + $0.record.name } for reference in references where !instructions.sections.contains(reference) { instructions.sections.append(reference) } - declaration.instructions = instructions + try declaration.setInstructions(instructions) let prepared = try prepare( declaration: declaration, previous: previous, sources: sources, resolving: Set(references)) let plan = try plan( @@ -151,9 +151,9 @@ public enum InstructionOperations { return try operate(store, apply: apply) { previousDeclaration, previous, baseline in var declaration = previousDeclaration if let agents { - var instructions = declaration.instructions ?? InstructionsDeclaration() + var instructions = (try declaration.instructions) ?? InstructionsDeclaration() instructions.agents = agents - declaration.instructions = instructions + try declaration.setInstructions(instructions) } let resolutions = try SourceResolutionSession(store: store) let plan = try prepareUpdate( @@ -241,7 +241,7 @@ public enum InstructionOperations { let store = StateStore(scope: scope, environment: environment) return try operate(store, apply: true) { previousDeclaration, previous, baseline in var declaration = previousDeclaration - var instructions = declaration.instructions ?? InstructionsDeclaration() + var instructions = (try declaration.instructions) ?? InstructionsDeclaration() let references = Set( instructions.sections + (instructions.chatgpt ?? [:]).values.flatMap(\.sections)) var removed = Set() @@ -265,7 +265,7 @@ public enum InstructionOperations { } } if let agents { instructions.agents = agents } - declaration.instructions = instructions + try declaration.setInstructions(instructions) let sources = InstructionSources(store: store) let prepared = try prepare( declaration: declaration, previous: previous, sources: sources, resolving: []) @@ -363,10 +363,11 @@ public enum InstructionOperations { } } let sections = try units( - declaration.instructions?.sections ?? [], locked: previous.instructions.sections) + (try declaration.instructions)?.sections ?? [], locked: previous.instructions.sections) next.instructions.sections = sections.map(\.record) - for (name, prompt) in (declaration.instructions?.chatgpt ?? [:]).sorted(by: { $0.key < $1.key }) - { + for (name, prompt) in ((try declaration.instructions)?.chatgpt ?? [:]).sorted(by: { + $0.key < $1.key + }) { let selected = try units( prompt.sections, locked: previous.instructions.chatgpt[name]?.sections ?? []) _ = try Instructions.renderChatGPT(sections: selected.map(\.section)) @@ -385,7 +386,7 @@ public enum InstructionOperations { var next = prepared.lock let targets = try InstructionTargets(store: store).plan( sections: prepared.sections, - agents: declaration.instructions?.agents ?? declaration.defaultAgents, + agents: (try declaration.instructions)?.agents ?? declaration.defaultAgents, previous: previous.instructions) next.instructions.targets = targets.targets try InstructionTargets.validateSourceDirectories(targets.changes, sources: next.sources) @@ -473,9 +474,13 @@ public enum InstructionOperations { _ store: StateStore, apply: Bool, _ body: (Declaration, ResolvedState) throws -> T ) throws -> T { if apply { - return try store.withLock { try body(store.readDeclaration(), store.readResolved()) } + return try store.withLock { + try body(store.readDeploymentDeclaration(), store.readResolved()) + } + } + return try store.withReadLock { + try body(store.readDeploymentDeclaration(), store.readResolved()) } - return try store.withReadLock { try body(store.readDeclaration(), store.readResolved()) } } private static func operate( @@ -485,7 +490,8 @@ public enum InstructionOperations { try operate(store, apply: apply) { let baseline = try StatePrecondition(store: store) return try body( - store.readDeclaration(prepared: baseline), store.readResolved(prepared: baseline), baseline) + store.readDeploymentDeclaration(prepared: baseline), store.readResolved(prepared: baseline), + baseline) } } diff --git a/Sources/AgentsManifest/CompleteDeclarationPlanner.swift b/Sources/AgentsManifest/CompleteDeclarationPlanner.swift new file mode 100644 index 0000000..e7525e0 --- /dev/null +++ b/Sources/AgentsManifest/CompleteDeclarationPlanner.swift @@ -0,0 +1,195 @@ +import AgentsCore +import AgentsDescription + +/// Diffs full symbolic values against their source locations. Direct constructions are edited +/// by field, ordered arrays by occurrence, and assembled expressions remain read-only. +struct CompleteDeclarationPlanner { + let document: DeclarationDocument + let next: Declaration + + func plan() throws -> [DocumentOperation] { + var operations: [DocumentOperation] = [] + let desired = try DeclarationConstruction.root(next).constructionValue + try difference(document.evaluation.root.value, desired, at: "", into: &operations) + return operations + } + + private func handle(_ pointer: String) throws -> NodeID { + guard let handle = document.node(at: pointer) else { + throw DeclarationEditPlan.failure( + "manifest.edit.readOnly", "value has no independent source location", + span: document.source.span(0..<0)) + } + return handle + } + + private func difference( + _ old: ConstructionValue, _ new: ConstructionValue, at pointer: String, + into operations: inout [DocumentOperation] + ) throws { + if Lowering.lower(old) == Lowering.lower(new) { return } + switch (old, new) { + case (.node("SkillSelection", "names", let left), .node("SkillSelection", "names", let right)): + try array(left["names"]!.array!, right["names"]!.array!, at: pointer, into: &operations) + case (.node(let type, let member, let fields), .node(let newType, let newMember, let desired)) + where type == newType && member == newMember && type != "Source" && type != "SkillSelection": + if let value = document.values[pointer], document.admission.nodes[value.syntax].kind != .call, + type != "ConfigurationValue" || !["array", "object"].contains(member) + { + operations.append(.replaceValue(try handle(pointer), new)) + return + } + // Vocabulary order keeps the batch deterministic and respects constructor argument order. + let signature = Vocabulary.signatures.filter { $0.type == type && $0.member == member }.max { + $0.parameters.count < $1.parameters.count + } + let names = signature?.parameters.map(\.name) ?? [] + if names.isEmpty { + operations.append(.replaceValue(try handle(pointer), new)) + return + } + for name in names { + guard let left = fields[name], let right = desired[name], + Lowering.lower(left) != Lowering.lower(right) + else { continue } + let child = pointer + "/" + pointerEscape(name) + let explicit = document.values[child].map { !$0.defaulted } ?? false + if explicit, canDescend(left, right) { + try difference(left, right, at: child, into: &operations) + } else { + operations.append(.setArgument(try handle(pointer), field: name, value: right)) + } + } + case (.array(let left), .array(let right)): + try array(left, right, at: pointer, into: &operations) + case (.object(let left), .object(let right)): + for key in right.keys.sorted(by: utf8Less) { + if let old = left[key] { + try difference( + old, right[key]!, at: pointer + "/" + pointerEscape(key), into: &operations) + } else { + operations.append(.dictionaryEntry(try handle(pointer), key: key, value: right[key]!)) + } + } + for key in left.keys.sorted(by: utf8Less) where right[key] == nil { + operations.append(.dictionaryEntry(try handle(pointer), key: key, value: nil)) + } + default: + operations.append(.replaceValue(try handle(pointer), new)) + } + } + + private func canDescend(_ old: ConstructionValue, _ new: ConstructionValue) -> Bool { + switch (old, new) { + case (.array, .array), (.object, .object): return true + case (.node(let a, let b, _), .node(let x, let y, _)): + return a == x && b == y && a != "Source" && (a != "SkillSelection" || b == "names") + default: return false + } + } + + private func identity(_ value: ConstructionValue) -> String? { + guard case .node(let type, let member, let fields) = value else { return nil } + if let name = fields["name"]?.text { + if type == "GroupReference" || type == "SectionReference" { + let kind = Lowering.recordKind(type: type, member: member, fields: fields) + return type + ":" + kind + ":" + (fields["source"]?.text ?? ".") + ":" + name + } + return type + ":" + member + ":" + name + } + if type == "Component", let source = fields["source"]?.text { + return type + ":" + member + ":" + source + } + if type == "Component", member == "instructions" { return type + ":" + member } + return nil + } + + private func array( + _ old: [ConstructionValue], _ new: [ConstructionValue], at pointer: String, + into operations: inout [DocumentOperation] + ) throws { + // Equal-length occurrence-addressed changes retain each position, including repeated names. + if old.count == new.count, zip(old, new).allSatisfy({ identity($0) == identity($1) }) { + for index in old.indices { + try difference(old[index], new[index], at: pointer + "/\(index)", into: &operations) + } + return + } + let (count, overflow) = (old.count + 1).multipliedReportingOverflow(by: new.count + 1) + guard !overflow, count <= ManifestLimits.Editing.comparisonPairs else { + throw DeclarationEditPlan.failure( + "manifest.limit", "declaration comparison pairs", span: document.source.span(0..<0)) + } + func matches(_ a: ConstructionValue, _ b: ConstructionValue) -> Bool { + if let identity = identity(a), identity == self.identity(b) { return true } + return Lowering.lower(a) == Lowering.lower(b) + } + // A named edit across a length change cannot infer which conditional occurrence survives. + let keys = old.compactMap(identity) + for key in Set(keys) where keys.filter({ $0 == key }).count > 1 { + if old != new, new.contains(where: { identity($0) == key }) { + let candidates = old.indices.filter { identity(old[$0]) == key }.map { pointer + "/\($0)" } + let spans = candidates.compactMap { document.sourceMap.locations(at: $0).first?.span } + throw ManifestFailure( + ManifestDiagnostic( + code: "manifest.ambiguous", + message: "multiple matching occurrences require an occurrence-addressed edit", + span: spans.first ?? document.source.span(0..<0), related: Array(spans.dropFirst()))) + } + } + let width = new.count + 1 + var lengths = [Int](repeating: 0, count: count) + for i in old.indices.reversed() { + for j in new.indices.reversed() { + lengths[i * width + j] = + matches(old[i], new[j]) + ? lengths[(i + 1) * width + j + 1] + 1 + : max(lengths[(i + 1) * width + j], lengths[i * width + j + 1]) + } + } + var pairs: [(Int, Int)] = [] + var (i, j) = (0, 0) + while i < old.count && j < new.count { + if matches(old[i], new[j]) { + pairs.append((i, j)) + i += 1 + j += 1 + } else if lengths[(i + 1) * width + j] >= lengths[i * width + j + 1] { + i += 1 + } else { + j += 1 + } + } + let anchors = pairs + var keptOld = Set(pairs.map(\.0)) + let anchoredNew = Set(pairs.map(\.1)) + var moved: [Int: Int] = [:] + for j in new.indices where !anchoredNew.contains(j) { + let candidates = old.indices.filter { !keptOld.contains($0) && matches(old[$0], new[j]) } + if candidates.count == 1, let i = candidates.first { + moved[j] = i + keptOld.insert(i) + pairs.append((i, j)) + } + } + // Field edits precede moves so original occurrence handles still address their owners. + for (i, j) in pairs { + try difference(old[i], new[j], at: pointer + "/\(i)", into: &operations) + } + for j in new.indices where !anchoredNew.contains(j) { + let anchor = try anchors.first { $0.1 > j }.map { + InsertionPosition.before(try handle(pointer + "/\($0.0)")) + } + if let i = moved[j] { + operations.append( + .moveElement( + try handle(pointer + "/\(i)"), into: try handle(pointer), at: anchor ?? .last)) + } else { + operations.append(.insertElement(new[j], into: try handle(pointer), at: anchor ?? .last)) + } + } + for i in old.indices where !keptOld.contains(i) { + operations.append(.removeElement(try handle(pointer + "/\(i)"))) + } + } +} diff --git a/Sources/AgentsManifest/ComponentConstruction.swift b/Sources/AgentsManifest/ComponentConstruction.swift new file mode 100644 index 0000000..de5a900 --- /dev/null +++ b/Sources/AgentsManifest/ComponentConstruction.swift @@ -0,0 +1,174 @@ +import AgentsCore +import AgentsDescription + +extension DeclarationConstruction { + static func condition(_ condition: DeclarationCondition?) -> Condition? { + condition.map { + .when( + agents: $0.agents.map { $0.map(agent) }, + scopes: $0.scopes.map { $0.map { $0 == .project ? .project : .user } }, + platforms: $0.platforms.map { $0.map { $0 == .macOS ? .macOS : .linux } }) + } + } + + static func nativeValue(_ value: NativeValue) -> ConfigurationValue { + switch value { + case .string(let v): .string(v) + case .integer(let v): .integer(v) + case .decimal(let v): .decimal(v) + case .boolean(let v): .boolean(v) + case .null: .null + case .array(let v): .array(v.map(nativeValue)) + case .object(let v): .object(v.mapValues(nativeValue)) + } + } + + static func native(_ native: AgentsCore.NativeConfiguration) + -> AgentsDescription.NativeConfiguration + { native.mapValues { $0.mapValues(nativeValue) } } + + static func binding(_ value: RuntimeBinding) -> RuntimeValue { + switch value { + case .literal(let v): .literal(v) + case .environment(let v): .environment(v) + case .secret(let v): .secret(v) + } + } + static func resource(_ value: ResourceDeclaration) -> Resource { + .path(value.path, source: value.source) + } + static func promptBody(_ value: PromptBody) -> PromptContent { + switch value { + case .literal(let v): PromptContent(stringLiteral: v) + case .file(let v): .file(v.path, source: v.source) + } + } + static func executable(_ value: ExecutableDeclaration) -> ExecutableInvocation { + .executable( + value.executable, arguments: value.arguments, + environment: value.environment.mapValues(binding), + workingDirectory: value.workingDirectory.map(resource)) + } + static func transport(_ value: MCPTransportDeclaration) -> MCPTransport { + switch value { + case .stdio(let v): + .stdio( + v.executable, arguments: v.arguments, environment: v.environment.mapValues(binding), + workingDirectory: v.workingDirectory.map(resource)) + case .streamableHTTP(let url, let headers): + .streamableHTTP(url: url, headers: headers.mapValues(binding)) + case .sse(let url, let headers): .sse(url: url, headers: headers.mapValues(binding)) + } + } + static func event(_ value: HookEventDeclaration) -> HookEvent { + switch value { + case .beforeTool: .beforeTool + case .afterTool: .afterTool + case .sessionStart: .sessionStart + case .sessionEnd: .sessionEnd + case .native(let v): .native(v) + } + } + static func operation(_ value: PermissionOperationDeclaration) -> PermissionOperation { + switch value { + case .read: .read + case .write: .write + case .execute: .execute + case .tool(let v): .tool(v) + } + } + static func rule(_ value: PermissionRuleDeclaration) -> PermissionRule { + switch value { + case .allow(let op, let pattern): .allow(operation(op), pattern) + case .ask(let op, let pattern): .ask(operation(op), pattern) + case .deny(let op, let pattern): .deny(operation(op), pattern) + } + } + static func reference(_ value: ComponentReferenceDeclaration) -> ComponentReference { + switch value { + case .skill(let n): .skill(name: n) + case .instruction(let n): .instruction(name: n) + case .mcpServer(let n): .mcpServer(name: n) + case .hook(let n): .hook(name: n) + case .subagent(let n): .subagent(name: n) + case .command(let n): .command(name: n) + case .lspServer(let n): .lspServer(name: n) + case .permissions(let n): .permissions(name: n) + case .ignore(let n): .ignore(name: n) + case .plugin(let n): .plugin(name: n) + } + } + static func kind(_ value: DeclaredComponentKind) -> AgentsDescription.ComponentKind { + switch value { + case .skills: .skills + case .instructions: .instructions + case .mcpServer: .mcpServer + case .hook: .hook + case .subagent: .subagent + case .command: .command + case .lspServer: .lspServer + case .permissions: .permissions + case .ignore: .ignore + case .plugin: .plugin + } + } + static func use(_ value: GroupUseDeclaration) -> GroupReference { + if let source = value.source { + return .group(name: value.name, source: source, condition: condition(value.condition)) + } + return .group(name: value.name, condition: condition(value.condition)) + } + static func group(_ value: ComponentGroupDeclaration) -> ComponentGroup { + .group( + name: value.name, components: value.components.map(component), uses: value.uses.map(use), + condition: condition(value.condition)) + } + static func component(_ value: ComponentDeclaration) -> Component { + switch value { + case .skills(let source, let v): return skills(alias: source, v) + case .instructions(let v): return instructions(v) + case .mcpServer(let name, let v, let agents, let when, let config): + return .mcpServer( + name: name, transport: transport(v), agents: agents.map { $0.map(agent) }, + condition: condition(when), native: native(config)) + case .hook(let name, let e, let run, let matcher, let timeout, let agents, let when, let config): + return .hook( + name: name, event: event(e), run: executable(run), matcher: matcher, + timeoutSeconds: timeout, agents: agents.map { $0.map(agent) }, condition: condition(when), + native: native(config)) + case .subagent( + let name, let description, let prompt, let model, let tools, let agents, let when, let config): + return .subagent( + name: name, description: description, prompt: promptBody(prompt), model: model, + tools: tools, agents: agents.map { $0.map(agent) }, condition: condition(when), + native: native(config)) + case .command( + let name, let description, let prompt, let parameters, let agents, let when, let config): + return .command( + name: name, description: description, prompt: promptBody(prompt), + parameters: parameters.map { + .parameter(name: $0.name, description: $0.description, defaultValue: $0.defaultValue) + }, agents: agents.map { $0.map(agent) }, condition: condition(when), native: native(config)) + case .lspServer(let name, let run, let languages, let options, let agents, let when, let config): + return .lspServer( + name: name, run: executable(run), languages: languages, + initializationOptions: options.mapValues(nativeValue), agents: agents.map { $0.map(agent) }, + condition: condition(when), native: native(config)) + case .permissions(let name, let rules, let agents, let when, let config): + return .permissions( + name: name, rules: rules.map(rule), agents: agents.map { $0.map(agent) }, + condition: condition(when), native: native(config)) + case .ignore(let name, let patterns, let purpose, let agents, let when, let config): + return .ignore( + name: name, patterns: patterns, purpose: purpose == .context ? .context : .indexing, + agents: agents.map { $0.map(agent) }, condition: condition(when), native: native(config)) + case .plugin( + let name, let path, let source, let mode, let select, let exclude, let agents, let when, + let config): + return .plugin( + name: name, path: path, source: source, mode: mode == .native ? .native : .components, + select: select.map { $0.map(kind) }, exclude: exclude.map(reference), + agents: agents.map { $0.map(agent) }, condition: condition(when), native: native(config)) + } + } +} diff --git a/Sources/AgentsManifest/DeclarationConstruction.swift b/Sources/AgentsManifest/DeclarationConstruction.swift index b943a19..ab95f3d 100644 --- a/Sources/AgentsManifest/DeclarationConstruction.swift +++ b/Sources/AgentsManifest/DeclarationConstruction.swift @@ -1,20 +1,14 @@ import AgentsCore import AgentsDescription -/// Maps declaration values to construction vocabulary in canonical order: sources, skills -/// components, overrides, prompts, names and watch subscriptions by UTF-8 name, recipients by -/// agent ID without duplicates, and skills components before the instructions component. +/// Constructs the complete symbolic declaration without linking or evaluating conditions. package enum DeclarationConstruction { package static func root(_ declaration: Declaration) throws -> Agents { - let skills = declaration.skills ?? [:] - return Agents( - defaultAgents: recipients(declaration.agents), - sources: try declaration.sources.keys.sorted(by: utf8Less).map { - try source(alias: $0, declaration.sources[$0]!) - }, - components: skills.keys.sorted(by: utf8Less).map { self.skills(alias: $0, skills[$0]!) } - + (declaration.instructions.map { [instructions($0)] } ?? []), - watch: (declaration.watch ?? []).sorted(by: utf8Less)) + Agents( + defaultAgents: declaration.agents.map { $0.map(agent) }, exports: declaration.exports, + sources: try declaration.sourceDeclarations.map { try source(alias: $0.name, $0.source) }, + components: declaration.components.map(component), groups: declaration.groups.map(group), + uses: declaration.uses.map(use), watch: declaration.watch ?? []) } /// Git sources use complete transport URLs. Version ranges are checked before construction. @@ -68,12 +62,12 @@ package enum DeclarationConstruction { } package static func skills(alias: String, _ skills: SkillDeclaration) -> Component { - let overrides = skills.overrides ?? [:] return .skills( source: alias, select: selection(skills.select), - exclude: (skills.exclude ?? []).sorted(by: utf8Less), mode: skills.mode.map(mode), - overrides: overrides.keys.sorted(by: utf8Less).map { override(name: $0, overrides[$0]!) }, - agents: recipients(skills.agents)) + exclude: skills.exclude ?? [], mode: skills.mode.map(mode), + overrides: skills.overrideDeclarations.map { override(name: $0.name, $0.override) }, + agents: skills.agents.map { $0.map(agent) }, condition: condition(skills.condition), + native: native(skills.native)) } package static func selection( @@ -85,26 +79,32 @@ package enum DeclarationConstruction { return AgentsDescription.SkillSelection( value: .construct( type: "SkillSelection", member: "names", - fields: ["names": names.sorted(by: utf8Less).constructionValue])) + fields: ["names": names.constructionValue])) } } package static func override( name: String, _ override: AgentsCore.SkillOverride ) -> AgentsDescription.SkillOverride { - .skill(name: name, mode: override.mode.map(mode), agents: recipients(override.agents)) + .skill(name: name, mode: override.mode.map(mode), agents: override.agents.map { $0.map(agent) }) } package static func instructions(_ instructions: InstructionsDeclaration) -> Component { - let prompts = instructions.chatgpt ?? [:] - return .instructions( - sections: instructions.sections.map(section), - chatGPT: prompts.keys.sorted(by: utf8Less).map { prompt(name: $0, prompts[$0]!) }, - agents: recipients(instructions.agents)) + .instructions( + sections: instructions.sectionReferences.map(section), + chatGPT: instructions.prompts.map { prompt(name: $0.name, $0.prompt) }, + agents: instructions.agents.map { $0.map(agent) }, + condition: condition(instructions.condition), native: native(instructions.native)) } package static func prompt(name: String, _ prompt: PromptDeclaration) -> ChatGPTPrompt { - .prompt(name: name, sections: prompt.sections.map(section), append: prompt.append) + .prompt( + name: name, sections: prompt.sectionReferences.map(section), append: prompt.append, + condition: condition(prompt.condition)) + } + + package static func section(_ section: SectionDeclaration) -> SectionReference { + .section(name: section.name, source: section.source, condition: condition(section.condition)) } /// `alias:name` names a source section; a bare name is the declaring project's own section. diff --git a/Sources/AgentsManifest/DeclarationEditPlan.swift b/Sources/AgentsManifest/DeclarationEditPlan.swift index 067d2f7..a9f46e4 100644 --- a/Sources/AgentsManifest/DeclarationEditPlan.swift +++ b/Sources/AgentsManifest/DeclarationEditPlan.swift @@ -98,6 +98,11 @@ private struct Planner { var operations: [DocumentOperation] = [] mutating func plan() throws -> [DocumentOperation] { + if !flat(current) || !flat(next) || !flatOrder() || current.groups != next.groups + || current.uses != next.uses || current.exports != next.exports + { + return try CompleteDeclarationPlanner(document: document, next: next).plan() + } var skillComponents: [String: Int] = [:] var instructionsComponent: Int? for (index, component) in document.declaration.components.enumerated() { @@ -119,10 +124,10 @@ private struct Planner { } try recipients(owner: "", field: "defaultAgents", current.agents, next.agents) - let currentSkills = current.skills ?? [:] - let nextSkills = next.skills ?? [:] + let currentSkills = (try current.skills) ?? [:] + let nextSkills = (try next.skills) ?? [:] let retainedInstructions = - next.instructions == nil + (try next.instructions) == nil ? nil : try instructionsComponent.map { try handle("/components/\($0)") } for alias in nextSkills.keys.sorted(by: utf8Less) { if let existing = currentSkills[alias] { @@ -135,9 +140,9 @@ private struct Planner { at: retainedInstructions.map { .before($0) } ?? .last))) } } - switch (instructionsComponent, next.instructions) { + switch (instructionsComponent, (try next.instructions)) { case (let index?, let instructions?): - try self.instructions(at: "/components/\(index)", current.instructions!, instructions) + try self.instructions(at: "/components/\(index)", (try current.instructions)!, instructions) case (nil, let instructions?): operations.append( .edit( @@ -167,6 +172,63 @@ private struct Planner { return operations } + func flatOrder() -> Bool { + func keys(_ declaration: Declaration) -> [String] { + declaration.components.map { component in + switch component { + case .skills(let source, _): "skills:" + source + default: "instructions" + } + } + } + let old = keys(current) + let desired = keys(next) + let desiredSet = Set(desired) + var planned = old.filter(desiredSet.contains) + let added = desired.filter { !Set(old).contains($0) && $0 != "instructions" }.sorted( + by: utf8Less) + planned.insert( + contentsOf: added, at: planned.firstIndex(of: "instructions") ?? planned.endIndex) + if desiredSet.contains("instructions"), !old.contains("instructions") { + planned.append("instructions") + } + let oldSources = current.sourceDeclarations.map(\.name) + let newSources = next.sourceDeclarations.map(\.name) + let newSet = Set(newSources) + let sourceOrder = + oldSources.filter(newSet.contains) + + newSources.filter { !Set(oldSources).contains($0) }.sorted(by: utf8Less) + return planned == desired && sourceOrder == newSources + } + + func flat(_ value: Declaration) -> Bool { + var aliases = Set() + var instructions = false + for component in value.components { + switch component { + case .skills(let source, let selection): + if !aliases.insert(source).inserted || selection.condition != nil + || !selection.native.isEmpty + { + return false + } + case .instructions(let selection): + if instructions || selection.condition != nil || !selection.native.isEmpty + || selection.sectionReferences.contains(where: { $0.condition != nil }) + || selection.prompts.contains(where: { + $0.prompt.condition != nil + || $0.prompt.sectionReferences.contains(where: { $0.condition != nil }) + }) + { + return false + } + instructions = true + default: return false + } + } + return true + } + mutating func skills( at pointer: String, _ current: SkillDeclaration, _ next: SkillDeclaration ) throws { @@ -182,9 +244,11 @@ private struct Planner { reductions = changes.removals case (.names, .all): operations.append(.edit(.setSkillSelection(owner, .all))) - case (.all, .names): + case (.all, .names(let names)): reductions = [ - .edit(.setSkillSelection(owner, DeclarationConstruction.selection(next.select))) + .edit( + .setSkillSelection( + owner, DeclarationConstruction.selection(.names(names.sorted(by: utf8Less))))) ] } let currentOverrides = current.overrides ?? [:] diff --git a/Sources/AgentsManifest/DeploymentSubset.swift b/Sources/AgentsManifest/DeploymentSubset.swift new file mode 100644 index 0000000..3866ec6 --- /dev/null +++ b/Sources/AgentsManifest/DeploymentSubset.swift @@ -0,0 +1,71 @@ +import AgentsCore + +extension DeclarationDocument { + /// Validates the concrete input expected by the current skill/instruction deployment paths. + /// Full declaration readers and source-only watch operations do not use this gate. + func requireDeploymentSubset() throws { + func fail( + _ pointer: String, _ message: String, code: String = "manifest.unsupported", + related: [String] = [] + ) -> ManifestFailure { + func span(_ pointer: String) -> SourceSpan { + sourceMap.locations(at: pointer).first?.span ?? source.span(0..<0) + } + return ManifestFailure( + ManifestDiagnostic( + code: code, message: message, span: span(pointer), related: related.map(span))) + } + if !declaration.uses.isEmpty { throw fail("/uses/0", "group uses require component linking") } + var matches: [String: [String]] = [:] + var order: [String] = [] + for (index, component) in declaration.components.enumerated() { + let key: String + switch component.kind { + case "skills": key = "skills occurrence: " + component["source"]!.string! + case "instructions": key = "instructions occurrence" + default: continue + } + if matches[key] == nil { order.append(key) } + matches[key, default: []].append("/components/\(index)") + } + for key in order { + let locations = matches[key]! + if locations.count > 1 { + throw fail( + locations[0], "ambiguous " + key, code: "manifest.ambiguous", + related: Array(locations.dropFirst())) + } + } + for (index, component) in declaration.components.enumerated() { + let path = "/components/\(index)" + guard ["skills", "instructions"].contains(component.kind) else { + throw fail(path, "\(component.kind) components require native lowering") + } + guard component["condition"] == .null else { + throw fail(path + "/condition", "conditional components require component linking") + } + guard component["native"] == .dictionary([:]) else { + throw fail(path + "/native", "native configuration requires native lowering") + } + if component.kind == "skills", component["source"]?.string == "." { + throw fail(path + "/source", "own-package skills require component linking") + } + func sections(_ record: DeclarationRecord, _ path: String) throws { + for (index, value) in (record["sections"]?.elements ?? []).enumerated() + where value.record?["condition"] != .null { + throw fail( + path + "/sections/\(index)/condition", "conditional sections require component linking") + } + } + try sections(component, path) + for (index, value) in (component["chatGPT"]?.elements ?? []).enumerated() { + let prompt = value.record! + let path = path + "/chatGPT/\(index)" + guard prompt["condition"] == .null else { + throw fail(path + "/condition", "conditional prompts require component linking") + } + try sections(prompt, path) + } + } + } +} diff --git a/Sources/AgentsManifest/DocumentEditor.swift b/Sources/AgentsManifest/DocumentEditor.swift index ebc882e..5ba09ea 100644 --- a/Sources/AgentsManifest/DocumentEditor.swift +++ b/Sources/AgentsManifest/DocumentEditor.swift @@ -250,6 +250,12 @@ final class DocumentEditor { if depth == parts.count { return replacement } let part = parts[depth] switch value { + case .node("SkillSelection", "names", var fields) where Int(part) != nil: + guard let names = fields["names"] else { + throw fail("manifest.edit.mismatch", "expected skill selection is missing") + } + fields["names"] = try update(names, depth) + return .node(type: "SkillSelection", member: "names", fields: fields) case .node(let type, let member, var fields): guard let child = fields[part] else { throw fail("manifest.edit.mismatch", "expected field is missing") diff --git a/Sources/AgentsManifest/DocumentEdits.swift b/Sources/AgentsManifest/DocumentEdits.swift index 0e5500e..02aad62 100644 --- a/Sources/AgentsManifest/DocumentEdits.swift +++ b/Sources/AgentsManifest/DocumentEdits.swift @@ -10,6 +10,15 @@ extension DocumentEditor { case .insertElement(let value, let handle, let position): try insert(value, into: resolve(handle), at: position) case .removeElement(let handle): try remove(resolve(handle)) + case .moveElement(let handle, let container, let position): + try move(resolve(handle), into: resolve(container), at: position) + case .replaceValue(let handle, let value): try replace(resolve(handle), with: value) + case .dictionaryEntry(let handle, let key, let value): + let pointer = try resolve(handle) + guard case .dictionary(let type) = current.values[pointer]?.type.unwrapped else { + throw fail("manifest.edit.readOnly", "target is not a typed dictionary") + } + try dictionary(pointer, key: key, value: value.map { StaticValue.checked($0, type: type) }) } } @@ -447,7 +456,7 @@ extension DocumentEditor { let value = try direct(pointer) let from = parent(pointer) guard let old = current.values[from], let index = Int(key(pointer)), - let target = current.values[collection], case .array = target.value + let target = current.values[collection], arrayElements(target.value) != nil else { throw fail("manifest.edit.readOnly", "move requires array containers") } let destination = try self.position( position, collection: collection, count: target.elementsForUse.count) diff --git a/Sources/AgentsManifest/DocumentModels.swift b/Sources/AgentsManifest/DocumentModels.swift index 4d42813..e971c97 100644 --- a/Sources/AgentsManifest/DocumentModels.swift +++ b/Sources/AgentsManifest/DocumentModels.swift @@ -99,6 +99,9 @@ package enum DocumentOperation: Sendable { case setArgument(NodeID, field: String, value: ConstructionValue) case insertElement(ConstructionValue, into: NodeID, at: InsertionPosition) case removeElement(NodeID) + case moveElement(NodeID, into: NodeID, at: InsertionPosition) + case replaceValue(NodeID, ConstructionValue) + case dictionaryEntry(NodeID, key: String, value: ConstructionValue?) } public struct SemanticDelta: Sendable, Equatable { diff --git a/Sources/AgentsManifest/ManifestProjection.swift b/Sources/AgentsManifest/ManifestProjection.swift index e45c2aa..2b95c37 100644 --- a/Sources/AgentsManifest/ManifestProjection.swift +++ b/Sources/AgentsManifest/ManifestProjection.swift @@ -1,164 +1,62 @@ import AgentsCore -/// Projects a document onto the declaration model this release deploys: root recipients, -/// sources and watch subscriptions, plus at most one skills component per source alias and one -/// instructions component, none with a condition or native configuration. Unused groups and -/// exports are inert and accepted. Every other active structure fails with -/// `manifest.unsupported` at its location; nothing is dropped. +/// Static projection of the complete declaration. References and runtime bindings remain data; +/// this layer does not resolve sources, read resources or execute declared programs. package enum ManifestProjection { - package static func declaration( - of document: DeclarationDocument, environment: RuntimeEnvironment - ) throws -> Declaration { + package static func declaration(of document: DeclarationDocument, environment: RuntimeEnvironment) + throws -> Declaration + { + let projection = Projection(document: document) let ir = document.declaration - func unsupported(_ pointer: String, _ message: String) -> ManifestFailure { - let span = - document.sourceMap.locations(at: pointer).first?.span - ?? document.source.span(0..<0) - return ManifestFailure( - ManifestDiagnostic(code: "manifest.unsupported", message: message, span: span)) - } - func recipients(_ value: DeclarationValue?, at pointer: String) throws -> [AgentID]? { - guard let values = value?.elements else { return nil } - return try values.map { - guard let agent = $0.string.flatMap(AgentID.init(rawValue:)) else { - throw unsupported(pointer, "unknown recipient") - } - return agent - } - } - func section(_ value: DeclarationValue, at pointer: String) throws -> String { - guard let record = value.record, let name = record["name"]?.string else { - throw unsupported(pointer, "unknown section reference") - } - guard record["condition"] == .null else { - throw unsupported(pointer + "/condition", "conditional sections are not deployable") - } - // `.` names the declaring project, whose own sections are bare names. - guard let alias = record["source"]?.string, alias != "." else { return name } - return alias + ":" + name - } - func applicable(_ record: DeclarationRecord, at pointer: String) throws { - guard record["condition"] == .null else { - throw unsupported(pointer + "/condition", "conditional components are not deployable") - } - guard record["native"] == .dictionary([:]) else { - throw unsupported(pointer + "/native", "native configuration is not deployable") - } - } - - if !ir.uses.isEmpty { throw unsupported("/uses/0", "group uses are not deployable") } - var sources: [String: SourceDeclaration] = [:] - for (index, record) in ir.sources.enumerated() { - let kind: SourceKind - let location: DeclarationValue? - switch record.kind { - case "git": (kind, location) = (.git, record["url"]) - case "local": (kind, location) = (.local, record["path"]) - default: (kind, location) = (.wellKnown, record["index"]) - } - guard let alias = record["name"]?.string, let location = location?.string else { - throw unsupported("/sources/\(index)", "unknown source form") - } + let sources = ir.sources.map { record in + let kind: SourceKind = + record.kind == "git" ? .git : record.kind == "local" ? .local : .wellKnown + let location = record[kind == .git ? "url" : kind == .local ? "path" : "index"]!.string! var requirement: SourceRequirement? if case .requirement(let value) = record["requirement"] { requirement = value } - sources[alias] = SourceDeclaration( - kind: kind, location: location, requirement: requirement, - path: record["subpath"]?.string) + return NamedSourceDeclaration( + name: record["name"]!.string!, + source: SourceDeclaration( + kind: kind, location: location, requirement: requirement, path: record["subpath"]?.string, + environment: SourceEnvironment( + projectDirectory: environment.projectDirectory, homeDirectory: environment.homeDirectory + ))) } - var skills: [String: SkillDeclaration] = [:] - var instructions: InstructionsDeclaration? - for (index, record) in ir.components.enumerated() { - let pointer = "/components/\(index)" - switch record.kind { - case "skills": - try applicable(record, at: pointer) - guard let alias = record["source"]?.string, alias != "." else { - throw unsupported( - pointer + "/source", "skills of the declaring package are not deployable") - } - guard skills[alias] == nil else { - throw unsupported(pointer, "a source alias has more than one skills component") - } - let select: SkillSelection - if let names = record["select"]?.elements { - select = .names(names.compactMap(\.string)) - } else { - select = .all - } - let exclude = record["exclude"]?.elements?.compactMap(\.string) ?? [] - var overrides: [String: SkillOverride] = [:] - for (position, value) in (record["overrides"]?.elements ?? []).enumerated() { - let path = pointer + "/overrides/\(position)" - guard let override = value.record, let name = override["name"]?.string else { - throw unsupported(path, "unknown skill override") - } - overrides[name] = SkillOverride( - agents: try recipients(override["agents"], at: path + "/agents"), - mode: override["mode"]?.string.flatMap(InstallMode.init(rawValue:))) - } - skills[alias] = SkillDeclaration( - select: select, exclude: exclude.isEmpty ? nil : exclude, - agents: try recipients(record["agents"], at: pointer + "/agents"), - mode: record["mode"]?.string.flatMap(InstallMode.init(rawValue:)), - overrides: overrides.isEmpty ? nil : overrides) - case "instructions": - try applicable(record, at: pointer) - guard instructions == nil else { - throw unsupported(pointer, "the declaration has more than one instructions component") - } - let sections = try (record["sections"]?.elements ?? []).enumerated().map { - try section($1, at: pointer + "/sections/\($0)") - } - var prompts: [String: PromptDeclaration] = [:] - for (position, value) in (record["chatGPT"]?.elements ?? []).enumerated() { - let path = pointer + "/chatGPT/\(position)" - guard let prompt = value.record, let name = prompt["name"]?.string else { - throw unsupported(path, "unknown ChatGPT prompt") - } - guard prompt["condition"] == .null else { - throw unsupported(path + "/condition", "conditional prompts are not deployable") - } - prompts[name] = PromptDeclaration( - sections: try (prompt["sections"]?.elements ?? []).enumerated().map { - try section($1, at: path + "/sections/\($0)") - }, append: prompt["append"]?.string) - } - instructions = InstructionsDeclaration( - agents: try recipients(record["agents"], at: pointer + "/agents"), sections: sections, - chatgpt: prompts.isEmpty ? nil : prompts) - default: - throw unsupported(pointer, "\(record.kind) components are not deployable") - } - } - let declaration = Declaration( - agents: try recipients( - ir.defaultAgents.map { .array($0.map(DeclarationValue.string)) }, at: "/defaultAgents"), - sources: sources, skills: skills.isEmpty ? nil : skills, instructions: instructions, + let result = Declaration( + agents: ir.defaultAgents?.map { AgentID(rawValue: $0)! }, + sourceDeclarations: sources, + components: try ir.components.map(projection.component), + groups: try ir.groups.map { record in + ComponentGroupDeclaration( + name: record["name"]!.string!, + components: try projection.records(record["components"]).map(projection.component), + uses: try projection.records(record["uses"]).map(projection.use), + condition: projection.condition(record["condition"])) + }, uses: ir.uses.map(projection.use), exports: ir.exports, watch: ir.watch.isEmpty ? nil : ir.watch) - try declaration.validate(environment: environment) - return declaration + try result.validate(environment: environment) + return result } - /// Semantic declaration equality. Sources compare identity, requirement meaning and normalized - /// subpath, so equivalent spellings stay unchanged. Recipients compare as sets and keep `nil` - /// distinct from `[]`; absent and empty exclusions, overrides, prompts, watch subscriptions and - /// skills are equal. Sections compare in order. + /// Source spelling is compared using its declaring directories. All ordered structures and + /// every component field participate; absent recipients remain distinct from explicit empty. package static func equivalent( _ lhs: Declaration, _ rhs: Declaration, environment: RuntimeEnvironment ) -> Bool { - guard sameRecipients(lhs.agents, rhs.agents), Set(lhs.watch ?? []) == Set(rhs.watch ?? []), - lhs.sources.keys == rhs.sources.keys, - lhs.sources.allSatisfy({ equivalent($1, rhs.sources[$0]!, environment: environment) }) + guard sameRecipients(lhs.agents, rhs.agents), lhs.exports == rhs.exports, + lhs.groups == rhs.groups, lhs.uses == rhs.uses, Set(lhs.watch ?? []) == Set(rhs.watch ?? []), + lhs.sourceDeclarations.map(\.name) == rhs.sourceDeclarations.map(\.name), + zip(lhs.sourceDeclarations, rhs.sourceDeclarations).allSatisfy({ + equivalent($0.source, $1.source, environment: environment) + }), + lhs.components.count == rhs.components.count else { return false } - let left = lhs.skills ?? [:] - let right = rhs.skills ?? [:] - guard left.keys == right.keys, left.allSatisfy({ equivalent($1, right[$0]!) }) else { - return false - } - switch (lhs.instructions, rhs.instructions) { - case (nil, nil): return true - case (let left?, let right?): return equivalent(left, right) - default: return false + return zip(lhs.components, rhs.components).allSatisfy { left, right in + switch (left, right) { + case (.skills(let a, let x), .skills(let b, let y)): return a == b && equivalent(x, y) + case (.instructions(let x), .instructions(let y)): return equivalent(x, y) + default: return left == right + } } } @@ -190,9 +88,10 @@ package enum ManifestProjection { } let left = lhs.overrides ?? [:] let right = rhs.overrides ?? [:] - return selections && Set(lhs.exclude ?? []) == Set(rhs.exclude ?? []) - && lhs.mode == rhs.mode && sameRecipients(lhs.agents, rhs.agents) && left.keys == right.keys + return selections && Set(lhs.exclude ?? []) == Set(rhs.exclude ?? []) && lhs.mode == rhs.mode + && sameRecipients(lhs.agents, rhs.agents) && left.keys == right.keys && left.allSatisfy { equivalent($1, right[$0]!) } + && lhs.condition == rhs.condition && lhs.native == rhs.native } static func equivalent(_ lhs: SkillOverride, _ rhs: SkillOverride) -> Bool { @@ -200,11 +99,226 @@ package enum ManifestProjection { } static func equivalent(_ lhs: InstructionsDeclaration, _ rhs: InstructionsDeclaration) -> Bool { - sameRecipients(lhs.agents, rhs.agents) && lhs.sections == rhs.sections - && lhs.chatgpt ?? [:] == rhs.chatgpt ?? [:] + sameRecipients(lhs.agents, rhs.agents) && lhs.sectionReferences == rhs.sectionReferences + && lhs.prompts == rhs.prompts && lhs.condition == rhs.condition && lhs.native == rhs.native } static func sameRecipients(_ lhs: [AgentID]?, _ rhs: [AgentID]?) -> Bool { lhs.map(Set.init) == rhs.map(Set.init) } } + +/// The front end has already checked the vocabulary and field types before projection. +private struct Projection { + let document: DeclarationDocument + + func records(_ value: DeclarationValue?) -> [DeclarationRecord] { + (value?.elements ?? []).map { $0.record! } + } + func strings(_ value: DeclarationValue?) -> [String] { + (value?.elements ?? []).map { $0.string! } + } + func recipients(_ value: DeclarationValue?) -> [AgentID]? { + value?.elements.map { $0.map { AgentID(rawValue: $0.string!)! } } + } + func dictionary(_ value: DeclarationValue?) -> [String: DeclarationValue] { + if case .dictionary(let values) = value { return values } + return [:] + } + func condition(_ value: DeclarationValue?) -> DeclarationCondition? { + guard let r = value?.record else { return nil } + return DeclarationCondition( + agents: recipients(r["agents"]), + scopes: r["scopes"]?.elements.map { $0.map { InstallScope(rawValue: $0.string!)! } }, + platforms: r["platforms"]?.elements.map { + $0.map { DeclarationPlatform(rawValue: $0.string!)! } + }) + } + func use(_ r: DeclarationRecord) -> GroupUseDeclaration { + GroupUseDeclaration( + name: r["name"]!.string!, source: r["source"]?.string, condition: condition(r["condition"])) + } + func section(_ r: DeclarationRecord) -> SectionDeclaration { + SectionDeclaration( + name: r["name"]!.string!, source: r["source"]?.string, condition: condition(r["condition"])) + } + func resource(_ r: DeclarationRecord) -> ResourceDeclaration { + ResourceDeclaration(path: r["path"]!.string!, source: r["source"]?.string) + } + func binding(_ value: DeclarationValue) -> RuntimeBinding { + let r = value.record! + let text = r["value"]!.string! + switch r.kind { + case "environment": return .environment(text) + case "secret": return .secret(text) + default: return .literal(text) + } + } + func executable(_ r: DeclarationRecord) -> ExecutableDeclaration { + ExecutableDeclaration( + executable: r["executable"]!.string!, arguments: strings(r["arguments"]), + environment: dictionary(r["environment"]).mapValues(binding), + workingDirectory: r["workingDirectory"]?.record.map(resource)) + } + func prompt(_ r: DeclarationRecord) -> PromptBody { + r.kind == "literal" ? .literal(r["value"]!.string!) : .file(resource(r)) + } + func nativeValue(_ value: DeclarationValue) -> NativeValue { + let r = value.record! + switch r.kind { + case "string": return .string(r["value"]!.string!) + case "integer": if case .integer(let v) = r["value"] { return .integer(v) } + case "decimal": return .decimal(r["value"]!.string!) + case "boolean": if case .boolean(let v) = r["value"] { return .boolean(v) } + case "null": return .null + case "array": return .array((r["value"]?.elements ?? []).map(nativeValue)) + case "object": return .object(dictionary(r["value"]).mapValues(nativeValue)) + default: break + } + preconditionFailure("validated configuration value") + } + func native(_ value: DeclarationValue?) -> AgentsCore.NativeConfiguration { + dictionary(value).mapValues { dictionary($0).mapValues(nativeValue) } + } + func event(_ r: DeclarationRecord) -> HookEventDeclaration { + switch r.kind { + case "beforeTool": return .beforeTool + case "afterTool": return .afterTool + case "sessionStart": return .sessionStart + case "sessionEnd": return .sessionEnd + default: return .native(r["value"]!.string!) + } + } + func operation(_ r: DeclarationRecord) -> PermissionOperationDeclaration { + switch r.kind { + case "read": return .read + case "write": return .write + case "execute": return .execute + default: return .tool(r["value"]!.string!) + } + } + func rule(_ r: DeclarationRecord) -> PermissionRuleDeclaration { + let op = operation(r["operation"]!.record!) + let pattern = r["pattern"]!.string! + switch r.kind { + case "allow": return .allow(op, pattern) + case "ask": return .ask(op, pattern) + default: return .deny(op, pattern) + } + } + func reference(_ r: DeclarationRecord) -> ComponentReferenceDeclaration { + let name = r["name"]!.string! + switch r.kind { + case "skill": return .skill(name: name) + case "instruction": return .instruction(name: name) + case "mcpServer": return .mcpServer(name: name) + case "hook": return .hook(name: name) + case "subagent": return .subagent(name: name) + case "command": return .command(name: name) + case "lspServer": return .lspServer(name: name) + case "permissions": return .permissions(name: name) + case "ignore": return .ignore(name: name) + default: return .plugin(name: name) + } + } + func component(_ r: DeclarationRecord) throws -> ComponentDeclaration { + let agents = recipients(r["agents"]) + let condition = condition(r["condition"]) + let native = native(r["native"]) + let name = r["name"]?.string ?? "" + switch r.kind { + case "skills": + let overrides = records(r["overrides"]).map { record in + ( + record["name"]!.string!, + SkillOverride( + agents: recipients(record["agents"]), + mode: record["mode"]?.string.flatMap(InstallMode.init(rawValue:))) + ) + } + var result = SkillDeclaration( + select: r["select"]?.elements.map { .names($0.map { $0.string! }) } ?? .all, + exclude: strings(r["exclude"]).isEmpty ? nil : strings(r["exclude"]), agents: agents, + mode: r["mode"]?.string.flatMap(InstallMode.init(rawValue:)), + overrides: nil, condition: condition, native: native) + result.overrideDeclarations = overrides.map { + NamedSkillOverrideDeclaration(name: $0.0, override: $0.1) + } + return .skills(source: r["source"]!.string!, result) + case "instructions": + var result = InstructionsDeclaration(agents: agents, condition: condition, native: native) + result.sectionReferences = records(r["sections"]).map(section) + result.prompts = records(r["chatGPT"]).map { record in + var prompt = PromptDeclaration( + sections: [], append: record["append"]?.string, + condition: self.condition(record["condition"])) + prompt.sectionReferences = records(record["sections"]).map(section) + return NamedPromptDeclaration(name: record["name"]!.string!, prompt: prompt) + } + return .instructions(result) + case "mcpServer": + let record = r["transport"]!.record! + let transport: MCPTransportDeclaration + switch record.kind { + case "stdio": transport = .stdio(executable(record)) + case "streamableHTTP": + transport = .streamableHTTP( + url: record["url"]!.string!, headers: dictionary(record["headers"]).mapValues(binding)) + default: + transport = .sse( + url: record["url"]!.string!, headers: dictionary(record["headers"]).mapValues(binding)) + } + return .mcpServer( + name: name, transport: transport, agents: agents, condition: condition, native: native) + case "hook": + var timeout: Int? + if case .integer(let v) = r["timeoutSeconds"] { timeout = v } + return .hook( + name: name, event: event(r["event"]!.record!), run: executable(r["run"]!.record!), + matcher: r["matcher"]?.string, timeoutSeconds: timeout, agents: agents, + condition: condition, native: native) + case "subagent": + return .subagent( + name: name, description: r["description"]!.string!, prompt: prompt(r["prompt"]!.record!), + model: r["model"]?.string, + tools: r["tools"]?.elements.map { $0.map { $0.string! } }, agents: agents, + condition: condition, native: native) + case "command": + return .command( + name: name, description: r["description"]!.string!, prompt: prompt(r["prompt"]!.record!), + parameters: records(r["parameters"]).map { + PromptParameterDeclaration( + name: $0["name"]!.string!, description: $0["description"]!.string!, + defaultValue: $0["defaultValue"]?.string) + }, agents: agents, condition: condition, native: native) + case "lspServer": + return .lspServer( + name: name, run: executable(r["run"]!.record!), + languages: dictionary(r["languages"]).mapValues { $0.string! }, + initializationOptions: dictionary(r["initializationOptions"]).mapValues(nativeValue), + agents: agents, condition: condition, native: native) + case "permissions": + return .permissions( + name: name, rules: records(r["rules"]).map(rule), agents: agents, condition: condition, + native: native) + case "ignore": + return .ignore( + name: name, patterns: strings(r["patterns"]), + purpose: IgnorePurposeDeclaration(rawValue: r["purpose"]!.string!)!, agents: agents, + condition: condition, native: native) + case "plugin": + return .plugin( + name: name, path: r["path"]!.string!, source: r["source"]!.string!, + mode: PluginModeDeclaration(rawValue: r["mode"]!.string!)!, + select: r["select"]?.elements.map { + $0.map { DeclaredComponentKind(rawValue: $0.string!)! } + }, exclude: records(r["exclude"]).map(reference), agents: agents, condition: condition, + native: native) + default: + throw ManifestFailure( + ManifestDiagnostic( + code: "manifest.unsupported", message: "unknown component family: \(r.kind)", + span: document.source.span(0..<0))) + } + } +} diff --git a/Sources/AgentsManifest/ManifestState.swift b/Sources/AgentsManifest/ManifestState.swift index 98ee488..f2f4427 100644 --- a/Sources/AgentsManifest/ManifestState.swift +++ b/Sources/AgentsManifest/ManifestState.swift @@ -3,15 +3,23 @@ import AgentsDescription import Foundation /// Declaration access for scope state. Core owns the file, its captured bytes, the missing -/// declaration rule and publication; this module parses, projects and plans edits. Parse, edit -/// and subset failures are `ManifestFailure` diagnostics identified by the declaration path. +/// declaration rule and publication; this module parses, projects and plans edits. Parse, projection +/// and edit failures are `ManifestFailure` diagnostics identified by the declaration path. extension StateStore { - /// The deployable declaration, or an empty one when the scope has no state. + /// The complete declaration, or an empty one when the scope has no state. package func readDeclaration(prepared: StatePrecondition? = nil) throws -> Declaration { guard let document = try declarationDocument(prepared: prepared) else { return Declaration() } return try ManifestProjection.declaration(of: document, environment: environment) } + /// Existing skill/instruction deployment paths require a flat selection until linking and + /// native lowering are supplied by their owning lifecycle layer. + package func readDeploymentDeclaration(prepared: StatePrecondition? = nil) throws -> Declaration { + guard let document = try declarationDocument(prepared: prepared) else { return Declaration() } + try document.requireDeploymentSubset() + return try ManifestProjection.declaration(of: document, environment: environment) + } + /// Plans `next` as an edit of the prepared document that `previous` was read from. Nil means /// no semantic change. A document that no longer projects to `previous` is a stale /// preparation. @@ -65,13 +73,13 @@ extension StateStore { } } - /// Reads the deployable declaration under a shared lock, without recovery or creating files. + /// Reads the complete declaration under a shared lock, without recovery or creating files. public func loadDeclaration() throws -> Declaration { try withReadLock { try readDeclaration() } } /// Reads the complete declaration document under a shared lock, without recovery, creating - /// files or restricting it to the deployable subset. Nil means the scope has no state. + /// files or resolving its sources. Nil means the scope has no state. public func loadManifest() throws -> DeclarationDocument? { try withReadLock { try declarationDocument(prepared: nil) } } diff --git a/Sources/AgentsSkills/SkillOperations.swift b/Sources/AgentsSkills/SkillOperations.swift index 783bb5c..ff00783 100644 --- a/Sources/AgentsSkills/SkillOperations.swift +++ b/Sources/AgentsSkills/SkillOperations.swift @@ -88,7 +88,7 @@ public enum SkillOperations { if !apply { return AddOutcome(source: source, sourceID: id, availableSkills: selected, installed: []) } - var selection = declaration.skills?[alias] ?? SkillDeclaration(select: .names([])) + var selection = (try declaration.skills)?[alias] ?? SkillDeclaration(select: .names([])) let names = selected.map { PathSafety.sanitizeName($0.name) } if options.all { selection.select = .all @@ -96,18 +96,22 @@ public enum SkillOperations { selection.select = .names(Array(Set(previous + names)).sorted()) } selection.exclude = selection.exclude?.filter { !names.contains($0) } - if declaration.skills?[alias] == nil || options.all { + if (try declaration.skills)?[alias] == nil || options.all { selection.agents = options.agents selection.mode = options.mode } else { + var overrides = selection.overrides ?? [:] for name in names { - selection.overrides = selection.overrides ?? [:] - let recipients = options.agents ?? selection.overrides?[name]?.agents ?? selection.agents - selection.overrides?[name] = SkillOverride(agents: recipients, mode: options.mode) + let recipients = options.agents ?? overrides[name]?.agents ?? selection.agents + overrides[name] = SkillOverride(agents: recipients, mode: options.mode) } + selection.overrides = overrides + } + try declaration.updateSkills { + var selections = $0 ?? [:] + selections[alias] = selection + $0 = selections } - declaration.skills = declaration.skills ?? [:] - declaration.skills?[alias] = selection try declaration.validate(environment: options.environment) var next = lock next.sources[id] = lifecycle.lockedSource(source) @@ -211,8 +215,9 @@ public enum SkillOperations { let requested = Set(skillNames.map(PathSafety.sanitizeName)) var next = previous var prepared: [String: PreparedSkill] = [:] - for alias in (declaration.skills ?? [:]).keys.sorted() { - guard let selection = declaration.skills?[alias], let source = declaration.sources[alias] + for alias in ((try declaration.skills) ?? [:]).keys.sorted() { + guard let selection = (try declaration.skills)?[alias], + let source = declaration.sources[alias] else { continue } let id = try source.identity(environment: environment) let requestedHere = requested.filter { name in @@ -350,10 +355,10 @@ public enum SkillOperations { skill.installs = [:] } next.skills[name] = skill.installs.isEmpty ? nil : skill - for alias in (declaration.skills ?? [:]).keys { + for alias in ((try declaration.skills) ?? [:]).keys { guard let source = declaration.sources[alias], try source.identity(environment: environment) == skill.source, - var selection = declaration.skills?[alias] + var selection = (try declaration.skills)?[alias] else { continue } if skill.installs.isEmpty { if case .all = selection.select { @@ -363,12 +368,13 @@ public enum SkillOperations { } selection.overrides?.removeValue(forKey: name) } else { - selection.overrides = selection.overrides ?? [:] - let mode = selection.overrides?[name]?.mode - selection.overrides?[name] = SkillOverride( + var overrides = selection.overrides ?? [:] + let mode = overrides[name]?.mode + overrides[name] = SkillOverride( agents: skill.installs.keys.compactMap(AgentID.init(rawValue:)), mode: mode) + selection.overrides = overrides } - declaration.skills?[alias] = selection + try declaration.updateSkills { $0?[alias] = selection } } } let lifecycle = try SkillLifecycle(store: store, provider: WellKnownProvider()) @@ -492,7 +498,7 @@ public enum SkillOperations { ]) }, { - let declaration = try store.readDeclaration() + let declaration = try store.readDeploymentDeclaration() let lock = try store.readResolved() var checks = try managedInventory(store: store, lock: lock, agents: agents).filter { $0.status != .installed && $0.status != .editLinked @@ -551,7 +557,7 @@ public enum SkillOperations { let store = StateStore( scope: .project, environment: RuntimeEnvironment(projectDirectory: directory)) return try store.withLock(createIfMissing: false) { - _ = try store.readDeclaration() + _ = try store.readDeploymentDeclaration() _ = try store.readResolved() let name = name.map(PathSafety.sanitizeName) let root = name.map { directory.appendingPathComponent($0) } ?? directory @@ -584,9 +590,13 @@ public enum SkillOperations { _ store: StateStore, apply: Bool, _ body: (Declaration, ResolvedState) throws -> T ) throws -> T { if apply { - return try store.withLock { try body(store.readDeclaration(), store.readResolved()) } + return try store.withLock { + try body(store.readDeploymentDeclaration(), store.readResolved()) + } + } + return try store.withReadLock { + try body(store.readDeploymentDeclaration(), store.readResolved()) } - return try store.withReadLock { try body(store.readDeclaration(), store.readResolved()) } } private static func operate( @@ -596,7 +606,8 @@ public enum SkillOperations { try operate(store, apply: apply, checkpoint: checkpoint) { let baseline = try StatePrecondition(store: store) return try body( - store.readDeclaration(prepared: baseline), store.readResolved(prepared: baseline), baseline) + store.readDeploymentDeclaration(prepared: baseline), store.readResolved(prepared: baseline), + baseline) } } diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 6026e00..72b4656 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -22,7 +22,7 @@ final class UpdatePlan { self.store = store self.checkpoint = checkpoint baseline = try StatePrecondition(store: store) - declaration = try store.readDeclaration(prepared: baseline) + declaration = try store.readDeploymentDeclaration(prepared: baseline) previous = try store.readResolved(prepared: baseline) watch = try store.readWatch(prepared: baseline) resolutions = try SourceResolutionSession(store: store) diff --git a/Tests/AgentsCoreTests/DeclarationStateTests.swift b/Tests/AgentsCoreTests/DeclarationStateTests.swift index e588581..6d22220 100644 --- a/Tests/AgentsCoreTests/DeclarationStateTests.swift +++ b/Tests/AgentsCoreTests/DeclarationStateTests.swift @@ -61,6 +61,35 @@ struct DeclarationStateTests { #expect(try store.withLock { try store.readDeclaration() } == Declaration(agents: [.cursor])) } + @Test func completeDeclarationReadsKeepSymbolicIntentWithoutDeploymentSideEffects() throws { + let fixture = try ScopeFixture() + let store = fixture.store + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + let bytes = manifestText( + """ + sources: [.source(name: "remote", url: "https://does-not-exist.invalid/repo.git")], + components: [ + .mcpServer(name: "tools", transport: .stdio("program-does-not-exist")), + .hook(name: "hook", event: .sessionStart, run: .executable("program-does-not-exist")), + .subagent(name: "agent", description: "d", prompt: .file("missing.md", source: "remote")), + ], + groups: [.group(name: "unused", components: [.ignore(name: "i", patterns: [], condition: .when(agents: []))])] + """) + try bytes.write(to: store.declarationURL) + let before = try FileHash.folderHash(fixture.root) + let declaration = try store.loadDeclaration() + #expect(declaration.components.map(\.kind) == [.mcpServer, .hook, .subagent]) + #expect(declaration.groups.map(\.name) == ["unused"]) + #expect( + declaration.sources["remote"]?.environment + == SourceEnvironment( + projectDirectory: store.environment.projectDirectory, + homeDirectory: store.environment.homeDirectory)) + #expect(try store.loadManifest()?.bytes == Array(bytes)) + #expect(throws: ManifestFailure.self) { try store.readDeploymentDeclaration() } + #expect(try FileHash.folderHash(fixture.root) == before) + } + /// A writer interrupted after moving the declaration aside leaves lock state without a /// declaration. Readers report the pending recovery without touching any file, and the next /// writer recovers before the missing-declaration rule applies. diff --git a/Tests/AgentsCoreTests/StatePublicationTests.swift b/Tests/AgentsCoreTests/StatePublicationTests.swift index aef2942..a40ab61 100644 --- a/Tests/AgentsCoreTests/StatePublicationTests.swift +++ b/Tests/AgentsCoreTests/StatePublicationTests.swift @@ -49,7 +49,7 @@ struct StatePublicationTests { let declaration = try fixture.store.loadDeclaration() #expect(declaration.sources.keys.sorted() == ["source"]) #expect(declaration.watch == ["source"]) - #expect(declaration.skills?["source"]?.select == .names(["demo"])) + #expect((try declaration.skills)?["source"]?.select == .names(["demo"])) #expect(try fixture.store.loadResolved().skills.keys.sorted() == ["demo"]) #expect(try fixture.store.loadWatch().sources.count == 1) } @@ -293,7 +293,7 @@ final class StateOperationFixture { switch operation { case .freshSkillAdd: #expect( - declaration.skills == [ + (try declaration.skills) == [ "source": SkillDeclaration(select: .names(["demo"]), agents: [.codex], mode: .edit) ]) #expect(declaration.watch == nil) @@ -305,7 +305,7 @@ final class StateOperationFixture { == source.appendingPathComponent("skills/demo").resolvingSymlinksInPath().path) #expect(!present(store.watchURL)) case .watchAdd: - #expect(declaration.skills == nil) + #expect((try declaration.skills) == nil) #expect(declaration.watch == ["source"]) #expect(watch.sources[id]?.seen == .revision(try gitHead(source))) #expect(lock == ResolvedState()) diff --git a/Tests/AgentsCoreTests/WatchSourceTests.swift b/Tests/AgentsCoreTests/WatchSourceTests.swift index 3d3c780..0a40ebf 100644 --- a/Tests/AgentsCoreTests/WatchSourceTests.swift +++ b/Tests/AgentsCoreTests/WatchSourceTests.swift @@ -11,7 +11,10 @@ struct WatchSourceTests { let fixture = try WatchGitFixture() let store = StateStore(scope: scope, environment: fixture.environment) let source = SourceDeclaration( - kind: .local, location: "./source", requirement: .exact("1.0.0"), path: "instructions") + kind: .local, location: "./source", requirement: .exact("1.0.0"), path: "instructions", + environment: SourceEnvironment( + projectDirectory: fixture.environment.projectDirectory, + homeDirectory: fixture.environment.homeDirectory)) try store.save(declaration: Declaration(sources: ["source": source]), resolved: ResolvedState()) let lock = try FileSnapshot.read(at: store.resolvedURL) @@ -31,7 +34,10 @@ struct WatchSourceTests { func selectorsReplaceDeclaredRequirementAndPath(_ input: String) throws { let fixture = try WatchGitFixture() let source = SourceDeclaration( - kind: .local, location: "./source", requirement: .exact("1.0.0"), path: "instructions") + kind: .local, location: "./source", requirement: .exact("1.0.0"), path: "instructions", + environment: SourceEnvironment( + projectDirectory: fixture.environment.projectDirectory, + homeDirectory: fixture.environment.homeDirectory)) try fixture.store.save( declaration: Declaration(sources: ["source": source]), resolved: ResolvedState()) let topic = try fixture.head() @@ -49,7 +55,10 @@ struct WatchSourceTests { #expect( try fixture.store.loadDeclaration().sources == [ "source": SourceDeclaration( - kind: .local, location: "./source", requirement: .branch("topic"), path: "rules") + kind: .local, location: "./source", requirement: .branch("topic"), path: "rules", + environment: SourceEnvironment( + projectDirectory: fixture.environment.projectDirectory, + homeDirectory: fixture.environment.homeDirectory)) ]) } diff --git a/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift b/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift index 0366a77..4074063 100644 --- a/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift +++ b/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift @@ -73,7 +73,7 @@ struct InstructionLifecycleSafetyTests { var declaration = try fixture.store().loadDeclaration() var lock = try fixture.store().loadResolved() let previous = lock.instructions.sections[0] - declaration.skills = ["rules": SkillDeclaration(select: .names([]))] + try declaration.setSkills(["rules": SkillDeclaration(select: .names([]))]) lock.skills["example"] = LockedSkill( source: previous.source, revision: previous.revision, path: "skills/example", hash: previous.hash, installs: ["codex": .copy]) @@ -83,7 +83,7 @@ struct InstructionLifecycleSafetyTests { try fixture.add(names: ["two"]) #expect(try fixture.store().loadResolved().instructions.sections[0] == previous) #expect(try fixture.store().loadResolved().skills == lock.skills) - #expect(try fixture.store().loadDeclaration().skills == declaration.skills) + #expect(try fixture.store().loadDeclaration().skills == (try declaration.skills)) #expect(try !fixture.text().contains("Changed")) } @@ -165,9 +165,11 @@ struct InstructionLifecycleSafetyTests { try fixture.commit() try fixture.add() var declaration = try fixture.store().loadDeclaration() - declaration.instructions?.chatgpt = [ - "prompt": PromptDeclaration(sections: ["rules:rules"], append: "custom.md") - ] + try declaration.updateInstructions { + $0?.chatgpt = [ + "prompt": PromptDeclaration(sections: ["rules:rules"], append: "custom.md") + ] + } try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) let outside = fixture.root.appendingPathComponent("outside.md") diff --git a/Tests/AgentsInstructionsTests/LifecycleTests.swift b/Tests/AgentsInstructionsTests/LifecycleTests.swift index bc0ca4f..f748200 100644 --- a/Tests/AgentsInstructionsTests/LifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/LifecycleTests.swift @@ -63,7 +63,7 @@ struct InstructionLifecycleTests { try fixture.add(names: ["one", "two"], scope: .user, agents: [.cursor]) let store = fixture.store(.user) var declaration = try store.loadDeclaration() - declaration.instructions?.sections.reverse() + try declaration.updateInstructions { $0?.sections.reverse() } try store.save(declaration: declaration, resolved: store.loadResolved()) let report = try InstructionOperations.updateInstalled( scope: .user, environment: fixture.environment) @@ -214,10 +214,13 @@ struct InstructionLifecycleTests { try fixture.commit() try fixture.add(agents: [.codex, .geminiCLI]) var declaration = try fixture.store().loadDeclaration() - declaration.instructions?.chatgpt = [ - "daily": PromptDeclaration(sections: ["rules:one", "rules:two"], append: ".agent/custom.md"), - "stable": PromptDeclaration(sections: ["rules:two"]), - ] + try declaration.updateInstructions { + $0?.chatgpt = [ + "daily": PromptDeclaration( + sections: ["rules:one", "rules:two"], append: ".agent/custom.md"), + "stable": PromptDeclaration(sections: ["rules:two"]), + ] + } try fixture.write( "Custom prompt.\r\n", to: fixture.project.appendingPathComponent(".agent/custom.md")) try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) diff --git a/Tests/AgentsManifestTests/DeclarationPropertyTests.swift b/Tests/AgentsManifestTests/DeclarationPropertyTests.swift index 73e0f37..909c224 100644 --- a/Tests/AgentsManifestTests/DeclarationPropertyTests.swift +++ b/Tests/AgentsManifestTests/DeclarationPropertyTests.swift @@ -72,7 +72,7 @@ private struct DeclarationGenerator { agents: recipients(), sections: sections(aliases), chatgpt: flip() ? nil : prompts) } - mutating func declaration() -> Declaration { + mutating func declaration() throws -> Declaration { var declaration = Declaration(agents: recipients()) for alias in subset(["a", "b", "c", "d"]) { declaration.sources[alias] = source(alias) @@ -80,14 +80,14 @@ private struct DeclarationGenerator { let aliases = declaration.sources.keys.sorted() var skills: [String: SkillDeclaration] = [:] for alias in subset(aliases) { skills[alias] = self.skills() } - declaration.skills = skills.isEmpty && flip() ? nil : skills - declaration.instructions = instructions(aliases) + try declaration.setSkills(skills.isEmpty && flip() ? nil : skills) + try declaration.setInstructions(instructions(aliases)) declaration.watch = flip() ? nil : subset(aliases) return declaration } /// A neighbor of `base`: each part is kept, changed or removed, and references follow sources. - mutating func change(_ base: Declaration) -> Declaration { + mutating func change(_ base: Declaration) throws -> Declaration { var result = base if random.next(3) == 0 { result.agents = recipients() } for alias in base.sources.keys.sorted() { @@ -99,17 +99,19 @@ private struct DeclarationGenerator { } for alias in ["e", "f"] where random.next(3) == 0 { result.sources[alias] = source(alias) } let aliases = result.sources.keys.sorted() - var skills = (result.skills ?? [:]).filter { result.sources[$0.key] != nil } + var skills = ((try result.skills) ?? [:]).filter { result.sources[$0.key] != nil } for alias in aliases where random.next(3) == 0 { skills[alias] = flip() ? nil : self.skills() } - result.skills = skills - let referenced = result.instructions.map { + try result.setSkills(skills) + let referenced = (try result.instructions).map { ($0.sections + ($0.chatgpt ?? [:]).values.flatMap(\.sections)).allSatisfy { !$0.contains(":") || result.sources[String($0.split(separator: ":")[0])] != nil } } - if referenced == false || random.next(3) == 0 { result.instructions = instructions(aliases) } + if referenced == false || random.next(3) == 0 { + try result.setInstructions(instructions(aliases)) + } result.watch = random.next(3) == 0 ? subset(aliases) : result.watch?.filter(aliases.contains) return result } @@ -152,7 +154,7 @@ struct DeclarationPropertyTests { @Test func printedDeclarationsProjectToThemselves() throws { var generator = DeclarationGenerator() for _ in 0..<96 { - let declaration = generator.declaration() + let declaration = try generator.declaration() try declaration.validate(environment: projectionEnvironment) guard let bytes = try planned(Declaration(), declaration, in: nil) else { #expect(equivalent(declaration, Declaration())) @@ -167,8 +169,8 @@ struct DeclarationPropertyTests { var generator = DeclarationGenerator() var (edited, markers) = (0, 0) for _ in 0..<96 { - let previous = generator.declaration() - let next = generator.change(previous) + let previous = try generator.declaration() + let next = try generator.change(previous) try next.validate(environment: projectionEnvironment) let printed = String( decoding: try planned(Declaration(), previous, in: nil) ?? [], as: UTF8.self) @@ -179,8 +181,8 @@ struct DeclarationPropertyTests { kept.append(".source \(alias)") } } - for alias in (previous.skills ?? [:]).keys.sorted() - where next.skills?[alias] == previous.skills?[alias] { + for alias in ((try previous.skills) ?? [:]).keys.sorted() + where (try next.skills)?[alias] == (try previous.skills)?[alias] { kept.append(".skills \(alias)") } let text = commented(printed, keeping: kept) diff --git a/Tests/AgentsManifestTests/EditPlanTests.swift b/Tests/AgentsManifestTests/EditPlanTests.swift index 312359f..a17d58f 100644 --- a/Tests/AgentsManifestTests/EditPlanTests.swift +++ b/Tests/AgentsManifestTests/EditPlanTests.swift @@ -13,17 +13,18 @@ func planned(_ previous: Declaration, _ next: Declaration, in text: String?) thr private func expectChange( _ body: String, to expected: String, sourceLocation: SourceLocation = #_sourceLocation, - _ update: (inout Declaration) -> Void + _ update: (inout Declaration) throws -> Void ) throws { let result = try changed(body, update) #expect(result == expected, sourceLocation: sourceLocation) } /// Plans a change to a manifest body and returns the edited body, checked against the intent. -private func changed(_ body: String, _ update: (inout Declaration) -> Void) throws -> String { +private func changed(_ body: String, _ update: (inout Declaration) throws -> Void) throws -> String +{ let previous = try projected(body) var next = previous - update(&next) + try update(&next) let bytes = try #require(try planned(previous, next, in: manifestHeader + body)) let text = String(decoding: bytes, as: UTF8.self) #expect(text.hasPrefix(manifestHeader)) @@ -53,7 +54,7 @@ struct EditPlanTests { requirement: .upToNextMajor(from: "1.2.0")) next.sources["l"] = SourceDeclaration( kind: .local, location: "/work/project/rules", path: "skills") - next.skills?["g"] = SkillDeclaration(select: .names(["a", "b"])) + try next.updateSkills { $0?["g"] = SkillDeclaration(select: .names(["a", "b"])) } next.watch = ["g", "l"] #expect(try planned(previous, next, in: manifestHeader + body) == nil) #expect(try planned(Declaration(), Declaration(), in: nil) == nil) @@ -137,7 +138,7 @@ struct EditPlanTests { """ ) { $0.sources["s"] = nil - $0.skills = nil + try $0.setSkills(nil) $0.watch = nil } } @@ -169,9 +170,9 @@ struct EditPlanTests { ) """ ) { - $0.skills = [ + try $0.setSkills([ "b": SkillDeclaration(select: .all), "a": SkillDeclaration(select: .names(["x"])), - ] + ]) } try expectChange( "let agents = Agents(sources: [.source(name: \"a\", path: \"a\")])", @@ -183,7 +184,7 @@ struct EditPlanTests { ] ) """ - ) { $0.skills = ["a": SkillDeclaration(select: .all)] } + ) { try $0.setSkills(["a": SkillDeclaration(select: .all)]) } } @Test func selectionSwitchesAndNameEditsKeepOrder() throws { @@ -205,9 +206,9 @@ struct EditPlanTests { ] ) """ - ) { $0.skills?["s"]?.select = .names(["b", "c", "d", "e"]) } + ) { try $0.updateSkills { $0?["s"]?.select = .names(["b", "c", "d", "e"]) } } expectManifestFailure("manifest.edit.readOnly") { - try changed(body) { $0.skills?["s"]?.select = .all } + try changed(body) { try $0.updateSkills { $0?["s"]?.select = .all } } } let plain = """ let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ @@ -221,11 +222,11 @@ struct EditPlanTests { .skills(source: "s", select: ["y", "z"]), ]) """ - ) { $0.skills?["s"]?.select = .names(["z", "y"]) } + ) { try $0.updateSkills { $0?["s"]?.select = .names(["z", "y"]) } } try expectChange( plain.replacingOccurrences(of: ".all", with: "[\"a\"]"), to: plain - ) { $0.skills?["s"]?.select = .all } + ) { try $0.updateSkills { $0?["s"]?.select = .all } } } @Test func excludeAgentsAndModeAreArgumentEdits() throws { @@ -258,9 +259,9 @@ struct EditPlanTests { ) """ ) { - $0.skills?["s"]?.exclude = ["x"] - $0.skills?["s"]?.mode = nil - $0.skills?["s"]?.agents = [] + try $0.updateSkills { $0?["s"]?.exclude = ["x"] } + try $0.updateSkills { $0?["s"]?.mode = nil } + try $0.updateSkills { $0?["s"]?.agents = [] } } try expectChange( """ @@ -274,9 +275,9 @@ struct EditPlanTests { ]) """ ) { - $0.skills?["s"]?.exclude = ["b", "c"] - $0.skills?["s"]?.agents = [.codex, .claudeCode] - $0.skills?["s"]?.mode = .link + try $0.updateSkills { $0?["s"]?.exclude = ["b", "c"] } + try $0.updateSkills { $0?["s"]?.agents = [.codex, .claudeCode] } + try $0.updateSkills { $0?["s"]?.mode = .link } } } @@ -303,10 +304,12 @@ struct EditPlanTests { ]) """ ) { - $0.skills?["s"]?.overrides = [ - "a": SkillOverride(mode: .copy), "c": SkillOverride(agents: [.codex]), - ] - $0.skills?["s"]?.select = .names(["a", "c"]) + try $0.updateSkills { + $0?["s"]?.overrides = [ + "a": SkillOverride(mode: .copy), "c": SkillOverride(agents: [.codex]), + ] + } + try $0.updateSkills { $0?["s"]?.select = .names(["a", "c"]) } } } @@ -327,7 +330,7 @@ struct EditPlanTests { ), ]) """ - ) { $0.instructions = InstructionsDeclaration(sections: ["guide"]) } + ) { try $0.setInstructions(InstructionsDeclaration(sections: ["guide"])) } let body = """ let agents = Agents(components: [ // rules @@ -335,7 +338,7 @@ struct EditPlanTests { ]) """ try expectChange(body, to: "let agents = Agents(components: [\n])") { - $0.instructions = nil + try $0.setInstructions(nil) } try expectChange( body, @@ -345,7 +348,7 @@ struct EditPlanTests { .instructions(sections: ["guide"], agents: [.cursor]), ]) """ - ) { $0.instructions?.agents = [.cursor] } + ) { try $0.updateInstructions { $0?.agents = [.cursor] } } } @Test func sectionsFollowTheLongestCommonSubsequenceAndKeepDuplicates() throws { @@ -373,7 +376,7 @@ struct EditPlanTests { ]), ]) """ - ) { $0.instructions?.sections = ["a", "x", "a", "s:c", "a", "y"] } + ) { try $0.updateInstructions { $0?.sections = ["a", "x", "a", "s:c", "a", "y"] } } try expectChange( body, to: """ @@ -383,7 +386,7 @@ struct EditPlanTests { ]), ]) """ - ) { $0.instructions?.sections = ["b"] } + ) { try $0.updateInstructions { $0?.sections = ["b"] } } } @Test func promptsAreUpsertedAndRemovedByName() throws { @@ -413,10 +416,12 @@ struct EditPlanTests { ]) """ ) { - $0.instructions?.chatgpt = [ - "daily": PromptDeclaration(sections: ["guide", "notes"]), - "monthly": PromptDeclaration(sections: [], append: "notes/monthly.md"), - ] + try $0.updateInstructions { + $0?.chatgpt = [ + "daily": PromptDeclaration(sections: ["guide", "notes"]), + "monthly": PromptDeclaration(sections: [], append: "notes/monthly.md"), + ] + } } } @@ -440,7 +445,7 @@ struct EditPlanTests { """ let previous = try projected(constant) var next = previous - next.skills?["s"]?.select = .names(["a", "b"]) + try next.updateSkills { $0?["s"]?.select = .names(["a", "b"]) } expectManifestFailure("manifest.edit.readOnly") { try planned(previous, next, in: manifestHeader + constant) } @@ -457,8 +462,8 @@ struct EditPlanTests { @Test func largeChangesAreSplitIntoReplannedBatches() throws { var next = Declaration() - for index in 0..<150 { - next.sources["s\(index)"] = SourceDeclaration(kind: .local, location: "s\(index)") + for alias in (0..<150).map({ "s\($0)" }).sorted(by: utf8Less) { + next.sources[alias] = SourceDeclaration(kind: .local, location: alias) } var batches: [Int] = [] let bytes = try #require( @@ -552,22 +557,26 @@ struct EditPlanTests { remainder = remainder[range.upperBound...] } } - let steps: [(inout Declaration) -> Void] = [ - { $0.skills?["team"]?.exclude = ["deprecated"] }, + let steps: [(inout Declaration) throws -> Void] = [ + { try $0.updateSkills { $0?["team"]?.exclude = ["deprecated"] } }, { $0.sources["extra"] = SourceDeclaration(kind: .git, location: "github.com/team/extra") - $0.skills?["extra"] = SkillDeclaration(select: .names(["one"])) + try $0.updateSkills { $0?["extra"] = SkillDeclaration(select: .names(["one"])) } }, { - $0.instructions?.sections.append("extra:style") - $0.instructions?.agents = [.codex] + try $0.updateInstructions { $0?.sections.append("extra:style") } + try $0.updateInstructions { $0?.agents = [.codex] } }, { $0.watch?.append("extra") }, { $0.sources["drafts"] = nil - $0.skills?["drafts"] = nil + try $0.updateSkills { $0?["drafts"] = nil } + }, + { + try $0.updateInstructions { + $0?.chatgpt = ["weekly": PromptDeclaration(sections: ["guide"])] + } }, - { $0.instructions?.chatgpt = ["weekly": PromptDeclaration(sections: ["guide"])] }, ] for step in steps { body = try changed(body, step) diff --git a/Tests/AgentsManifestTests/FullDeclarationTests.swift b/Tests/AgentsManifestTests/FullDeclarationTests.swift new file mode 100644 index 0000000..4692859 --- /dev/null +++ b/Tests/AgentsManifestTests/FullDeclarationTests.swift @@ -0,0 +1,351 @@ +import AgentsCore +import AgentsDescription +import Foundation +import Testing + +@testable import AgentsManifest + +@Suite("Complete symbolic declarations") +struct FullDeclarationTests { + @Test func conditionsRecipientsAndPluginSelectionsKeepInheritanceAndExplicitEmpty() throws { + let declaration = try projected( + """ + let agents = Agents(defaultAgents: [], sources: [.source(name: "s", path: "missing")], components: [ + .subagent(name: "inherited", description: "d", prompt: "p"), + .subagent(name: "empty", description: "d", prompt: "p", tools: [], agents: [], condition: .when(agents: [], scopes: [], platforms: [])), + .plugin(name: "all", path: "plugins/p", source: "s"), + .plugin(name: "none", path: "plugins/p", source: "s", select: []), + ]) + """) + #expect(declaration.agents == []) + guard + case .subagent( + _, _, _, _, let inheritedTools, let inheritedAgents, let inheritedCondition, _) = + declaration.components[0], + case .subagent(_, _, _, _, let emptyTools, let emptyAgents, let emptyCondition, _) = + declaration.components[1], + case .plugin(_, _, _, _, let all, _, _, _, _) = declaration.components[2], + case .plugin(_, _, _, _, let none, _, _, _, _) = declaration.components[3] + else { + Issue.record("unexpected component payload") + return + } + #expect(inheritedTools == nil && inheritedAgents == nil && inheritedCondition == nil) + #expect(emptyTools == [] && emptyAgents == []) + #expect(emptyCondition == DeclarationCondition(agents: [], scopes: [], platforms: [])) + #expect(all == nil && none == []) + } + + @Test func everyComponentFamilyCanBeEditedAsTypedIntent() throws { + var instructions = InstructionsDeclaration() + instructions.sectionReferences = [ + SectionDeclaration(name: "a", condition: DeclarationCondition(agents: [])), + SectionDeclaration(name: "b"), + ] + let cases: [(String, ComponentDeclaration)] = [ + ( + #".skills(source: "s", select: ["a" /* keep member */, "c"], condition: .when(scopes: []))"#, + .skills( + source: "s", + SkillDeclaration(select: .names(["a", "b"]), condition: DeclarationCondition(scopes: []))) + ), + ( + #""" + .skills(source: "s", select: [ + "a", + "b", + /* keep member */ + "c", + ], condition: .when(scopes: [])) + """#, + .skills( + source: "s", + SkillDeclaration(select: .names(["c", "a"]), condition: DeclarationCondition(scopes: []))) + ), + ( + #".instructions(sections: [.section(name: "a", condition: .when(agents: []))])"#, + .instructions(instructions) + ), + ( + #".mcpServer(name: "m", transport: .stdio("unused"))"#, + .mcpServer( + name: "m", + transport: .streamableHTTP( + url: "https://does-not-exist.invalid/mcp", + headers: ["Authorization": .environment("TOKEN")])) + ), + ( + #".hook(name: "h", event: .afterTool, run: .executable("unused"))"#, + .hook( + name: "h", event: .afterTool, run: ExecutableDeclaration(executable: "unused"), + timeoutSeconds: 5) + ), + ( + #".subagent(name: "a", description: "d", prompt: "p")"#, + .subagent(name: "a", description: "d", prompt: .literal("p"), tools: []) + ), + ( + #".command(name: "c", description: "d", prompt: "p", parameters: [.parameter(name: "x", description: "d", defaultValue: "old")])"#, + .command( + name: "c", description: "d", prompt: .literal("p"), + parameters: [PromptParameterDeclaration(name: "x", description: "d", defaultValue: "new")] + ) + ), + ( + #".lspServer(name: "l", run: .executable("unused"), languages: [".swift": "swift"], initializationOptions: ["enabled": true])"#, + .lspServer( + name: "l", run: ExecutableDeclaration(executable: "unused"), + languages: [".swift": "swift"], + initializationOptions: ["enabled": .boolean(false), "number": .decimal("1.25")]) + ), + ( + #".permissions(name: "p", rules: [.allow(.read, "a/**")])"#, + .permissions(name: "p", rules: [.ask(.tool("lookup"), "*"), .deny(.write, "private/**")]) + ), + ( + #".ignore(name: "i", patterns: ["a"])"#, + .ignore(name: "i", patterns: ["a"], purpose: .indexing) + ), + ( + #".plugin(name: "p", path: "plugins/p", source: "s")"#, + .plugin( + name: "p", path: "plugins/p", source: "s", select: [], + exclude: [.command(name: "obsolete")]) + ), + ] + for (component, intended) in cases { + let body = + #"let agents = Agents(sources: [.source(name: "s", path: "missing")], components: ["# + + component + "] )" + let previous = try projected(body) + var next = previous + next.components[0] = intended + let bytes = try #require(try planned(previous, next, in: manifestHeader + body)) + let actual = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) + #expect( + actual.declaration + == Lowering.declaration(try DeclarationConstruction.root(next).constructionValue), + "\(intended.kind)") + if intended.kind == .skills { + #expect(String(decoding: bytes, as: UTF8.self).contains("/* keep member */")) + } + } + } + + @Test func sourceAliasesRetainTheirDeclaringDirectories() throws { + let declaration = try projected( + "let agents = Agents(sources: [.source(name: \"s\", path: \"~/rules\")])") + let source = try #require(declaration.sources["s"]) + let importing = RuntimeEnvironment( + projectDirectory: URL(fileURLWithPath: "/importer"), + homeDirectory: URL(fileURLWithPath: "/other-home"), environment: [:]) + #expect( + source.environment + == SourceEnvironment( + projectDirectory: projectionEnvironment.projectDirectory, + homeDirectory: projectionEnvironment.homeDirectory)) + #expect(try source.identity(environment: importing) == "local:/work/home/rules") + } + + @Test func repeatedOccurrencesRequireAnExplicitOccurrence() throws { + let body = """ + let agents = Agents(sources: [.source(name: "s", path: "missing")], components: [ + .skills(source: "s", condition: .when(scopes: [.project])), + .skills(source: "s", condition: .when(scopes: [.user])), + .skills(source: "s", condition: .when(platforms: [])), + ]) + """ + let doc = try document(body) + var declaration = try ManifestProjection.declaration( + of: doc, environment: projectionEnvironment) + #expect(declaration.components.count == 3) + #expect(throws: CoreError.self) { try declaration.skills } + #expect(throws: CoreError.self) { try declaration.setSkills(nil) } + do { + try doc.requireDeploymentSubset() + Issue.record("ambiguous deployment selection accepted") + } catch let failure as ManifestFailure { + #expect(failure.diagnostics.map(\.code) == ["manifest.ambiguous"]) + #expect(failure.diagnostics.first?.related.count == 2) + } + guard case .skills(let source, var selection) = declaration.components[1] else { return } + selection.agents = [] + declaration.components[1] = .skills(source: source, selection) + let bytes = try #require( + try planned(try projected(body), declaration, in: manifestHeader + body)) + let result = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) + #expect(result.declaration.components[0] == doc.declaration.components[0]) + #expect(result.declaration.components[1]["agents"] == .array([])) + #expect(result.declaration.components[2] == doc.declaration.components[2]) + } + + @Test func fullEditsPreserveUnusedGroupsConditionsAndUnchangedBytes() throws { + let body = """ + // Header stays verbatim. + let agents = Agents( + components: [ + .mcpServer(name: "tools", transport: .stdio("never-start-this", arguments: ["serve"])), // server + ], + groups: [ + // This group is unused and must survive. + .group(name: "unused", components: [.ignore(name: "i", patterns: ["keep"], condition: .when(platforms: []))]), + ] + ) + // Tail stays verbatim. + """ + let previous = try projected(body) + var next = previous + next.components[0] = .mcpServer( + name: "tools", + transport: .stdio( + ExecutableDeclaration(executable: "never-start-this", arguments: ["inspect"]))) + let bytes = try #require(try planned(previous, next, in: manifestHeader + body)) + let output = String(decoding: bytes, as: UTF8.self) + #expect( + output == manifestHeader + body.replacingOccurrences(of: "[\"serve\"]", with: "[\"inspect\"]") + ) + #expect(try projected(String(output.dropFirst(manifestHeader.count))).groups == previous.groups) + } + + @Test func groupUsesStaySymbolicAndOrderedDuringEdits() throws { + let body = """ + let agents = Agents(sources: [.source(name: "s", path: "unavailable")], groups: [ + .group(name: "local", components: [.ignore(name: "i", patterns: [])]), + ], uses: ["local", .group(name: "remote", source: "s", condition: .when(agents: [])), "local"]) + """ + let previous = try projected(body) + var next = previous + next.uses[1].condition = DeclarationCondition(scopes: []) + next.exports = ["local"] + let bytes = try #require(try planned(previous, next, in: manifestHeader + body)) + let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) + let result = try ManifestProjection.declaration( + of: document, environment: projectionEnvironment) + #expect(result.uses == next.uses) + #expect(result.components.isEmpty) + #expect(result.groups == previous.groups) + #expect(result.exports == ["local"]) + } + + @Test func groupReferencesWithDifferentSourceAliasesRemainDistinct() throws { + let body = """ + let agents = Agents(sources: [.source(name: "a", path: "missing-a"), .source(name: "b", path: "missing-b")], + groups: [.group(name: "local")], uses: [ + .group(name: "review", source: "a", condition: .when(agents: [])), + .group(name: "review", source: "b", condition: .when(platforms: [])), + ]) + """ + let previous = try projected(body) + var next = previous + next.uses.insert(GroupUseDeclaration(name: "local"), at: 1) + let bytes = try #require(try planned(previous, next, in: manifestHeader + body)) + let actual = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) + #expect( + actual.declaration + == Lowering.declaration(try DeclarationConstruction.root(next).constructionValue)) + } + + @Test func reorderingFullCollectionsCarriesOwnedComments() throws { + let body = """ + let agents = Agents( + sources: [ + // Source a. + .source(name: "a", path: "missing-a"), + // Source b. + .source(name: "b", path: "missing-b"), + ], + components: [ + // Server a. + .mcpServer(name: "a", transport: .stdio("unused-a")), + // Server b. + .mcpServer(name: "b", transport: .stdio("unused-b")), + ], + groups: [.group(name: "a"), .group(name: "b")], + uses: ["a", "b"] + ) + """ + let previous = try projected(body) + var next = previous + next.sourceDeclarations.reverse() + next.components.reverse() + next.groups.reverse() + next.uses.reverse() + let bytes = try #require(try planned(previous, next, in: manifestHeader + body)) + let output = String(decoding: bytes, as: UTF8.self) + #expect(output.contains("// Source a.\n .source(name: \"a\", path: \"missing-a\")")) + #expect(output.contains("// Source b.\n .source(name: \"b\", path: \"missing-b\")")) + #expect( + output.contains("// Server a.\n .mcpServer(name: \"a\", transport: .stdio(\"unused-a\"))")) + #expect( + output.contains("// Server b.\n .mcpServer(name: \"b\", transport: .stdio(\"unused-b\"))")) + let actual = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) + #expect( + actual.declaration + == Lowering.declaration(try DeclarationConstruction.root(next).constructionValue)) + } + + @Test func fullBaselineAndFinalGuardsIncludeUnusedStructures() throws { + let body = + "let agents = Agents(groups: [.group(name: \"g\", components: [.ignore(name: \"i\", patterns: [\"old\"])])])" + let previous = try projected(body) + var stale = previous + stale.groups = [] + expectManifestFailure("manifest.edit.baseline") { + try planned(stale, stale, in: manifestHeader + body) + } + var next = previous + next.groups[0].components[0] = .ignore(name: "i", patterns: ["new"]) + expectManifestFailure("manifest.edit.mismatch") { + try DeclarationEditPlan.bytes( + replacing: previous, with: next, in: Array((manifestHeader + body).utf8), + identity: DocumentIdentity("manifest"), environment: projectionEnvironment, + planning: { _ in [] }) + } + } + + @Test func sharedConstantChangesAccountForUnusedGroupImpact() throws { + let doc = try document( + """ + let recipients: [Agent] = [.codex] + let agents = Agents(components: [.instructions(agents: recipients)], groups: [ + .group(name: "unused", components: [.ignore(name: "i", patterns: [], agents: recipients)]), + ]) + """) + let constant = try #require(doc.constant(named: "recipients")) + let uses = doc.uses(ofConstant: "recipients") + #expect(uses.count == 2) + expectManifestFailure("manifest.edit.impact") { + try doc.preparing([ + .replaceConstant(constant, with: .array([]), acceptingUses: Array(uses.prefix(1))) + ]) + } + let change = try doc.preparing([ + .replaceConstant(constant, with: .array([]), acceptingUses: uses) + ]) + let typed = try ManifestProjection.declaration( + of: DeclarationDocument(bytes: change.bytes, identity: DocumentIdentity("manifest")), + environment: projectionEnvironment) + #expect((try typed.instructions)?.agents == []) + #expect( + change.expectedDeclaration.groups[0]["components"]?.elements?[0].record?["agents"] + == .array([])) + #expect(typed.groups.count == 1 && typed.components.count == 1) + } + + @Test func readingAndConstructingNeverReadsSourcesResourcesOrRunsPrograms() throws { + let declaration = try projected( + """ + let agents = Agents(sources: [.source(name: "remote", url: "https://does-not-exist.invalid/repo.git")], components: [ + .mcpServer(name: "tools", transport: .stdio("program-does-not-exist", environment: ["KEY": .secret("unbound")])), + .hook(name: "run", event: .sessionStart, run: .executable("program-does-not-exist")), + .subagent(name: "agent", description: "d", prompt: .file("missing.md", source: "remote")), + ]) + """) + let bytes = try #require(try planned(Declaration(), declaration, in: nil)) + #expect( + try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")).declaration + .components.count == 3) + #expect( + try planned(declaration, declaration, in: String(decoding: bytes, as: UTF8.self)) == nil) + } +} diff --git a/Tests/AgentsManifestTests/PrintingTests.swift b/Tests/AgentsManifestTests/PrintingTests.swift index fc4dc85..5921700 100644 --- a/Tests/AgentsManifestTests/PrintingTests.swift +++ b/Tests/AgentsManifestTests/PrintingTests.swift @@ -56,15 +56,15 @@ let printedDeclarations: [(String, Declaration)] = [ ], skills: [ "s": SkillDeclaration( - select: .names([String(repeating: "b", count: 24), String(repeating: "a", count: 33)]), - exclude: [String(repeating: "d", count: 24), String(repeating: "c", count: 33)], + select: .names([String(repeating: "a", count: 33), String(repeating: "b", count: 24)]), + exclude: [String(repeating: "c", count: 33), String(repeating: "d", count: 24)], mode: .link) ]) ), ( "PrintedFields", Declaration( - agents: [.opencode, .codex, .claudeCode], + agents: [.claudeCode, .codex, .opencode], sources: [ "empty": local("./live"), "git": SourceDeclaration( @@ -77,7 +77,7 @@ let printedDeclarations: [(String, Declaration)] = [ skills: [ "empty": SkillDeclaration(select: .all, mode: .edit), "git": SkillDeclaration( - select: .names(["b", "a"]), exclude: ["b"], agents: [], mode: .copy, + select: .names(["a", "b"]), exclude: ["b"], agents: [], mode: .copy, overrides: [ "a": SkillOverride(agents: [.codex], mode: .link), "b": SkillOverride(agents: []), ]), @@ -85,12 +85,12 @@ let printedDeclarations: [(String, Declaration)] = [ "local": SkillDeclaration(select: .all, overrides: ["future": SkillOverride(mode: .copy)]), ], instructions: InstructionsDeclaration( - agents: [.geminiCLI, .codex], sections: ["own", "git:rule", "own", "local:nested/rule"], + agents: [.codex, .geminiCLI], sections: ["own", "git:rule", "own", "local:nested/rule"], chatgpt: [ "": PromptDeclaration(sections: []), "周报": PromptDeclaration(sections: ["git:rule", "own"], append: "notes/周报.md"), ]), - watch: ["local", "git", "index"]) + watch: ["git", "index", "local"]) ), ] @@ -129,7 +129,7 @@ struct PrintingTests { let empty = manifestHeader + "let agents = Agents()\n" var added = Declaration() added.sources["skills"] = SourceDeclaration(kind: .git, location: "github.com/team/skills") - added.skills = ["skills": SkillDeclaration(select: .all)] + try added.setSkills(["skills": SkillDeclaration(select: .all)]) let bytes = try #require(try planned(Declaration(), added, in: empty)) #expect( String(decoding: bytes, as: UTF8.self) == manifestHeader + """ diff --git a/Tests/AgentsManifestTests/ProjectionTests.swift b/Tests/AgentsManifestTests/ProjectionTests.swift index 414bdb0..fa0806e 100644 --- a/Tests/AgentsManifestTests/ProjectionTests.swift +++ b/Tests/AgentsManifestTests/ProjectionTests.swift @@ -14,60 +14,22 @@ func projected(_ body: String) throws -> Declaration { @Suite("Manifest projection") struct ProjectionTests { - @Test func everyDeployableShapeMapsToTheDeclaration() throws { - let declaration = try projected( - """ - let agents = Agents( - defaultAgents: [.openCode, .claudeCode], - sources: [ - .source(name: "git", url: "github.com/team/skills", branch: "main", subpath: "skills"), - .source(name: "local", path: "./drafts", "1.2.0"..<"2.0.0"), - .source(name: "index", index: "https://example.org/.well-known/skills/index.json"), - .source(name: "pinned", url: "https://example.org/p.git", exact: "1.2.3+build"), - ], - components: [ - .skills(source: "git"), - .skills( - source: "local", select: ["a", "b"], exclude: ["b"], mode: .copy, - overrides: [.skill(name: "a", mode: .link, agents: []), .skill(name: "b")], - agents: [.codex]), - .skills(source: "index", select: [], exclude: []), - .instructions( - sections: ["guide", .section(name: "rule", source: "git"), .section(name: "own", source: "."), "guide"], - chatGPT: [.prompt(name: "weekly", sections: [], append: "notes/weekly.md")], - agents: []), - ], - watch: ["git"] + @Test func compilerBackedFixturesProjectAndConstructWithoutLoss() throws { + for fixture in compiledFixtures() { + let doc = try DeclarationDocument( + bytes: manifestFixture(fixture.name), identity: DocumentIdentity(fixture.name)) + let declaration = try ManifestProjection.declaration( + of: doc, environment: projectionEnvironment) + let construction = try DeclarationConstruction.root(declaration).constructionValue + #expect(Lowering.declaration(construction) == doc.declaration, "\(fixture.name)") + #expect( + Lowering.declaration(fixture.agents.constructionValue) == doc.declaration, "\(fixture.name)" ) - """) - #expect( - declaration - == Declaration( - agents: [.opencode, .claudeCode], - sources: [ - "git": SourceDeclaration( - kind: .git, location: "https://github.com/team/skills", requirement: .branch("main"), - path: "skills"), - "local": SourceDeclaration( - kind: .local, location: "./drafts", requirement: .upToNextMajor(from: "1.2.0")), - "index": SourceDeclaration( - kind: .wellKnown, location: "https://example.org/.well-known/skills/index.json"), - "pinned": SourceDeclaration( - kind: .git, location: "https://example.org/p.git", requirement: .exact("1.2.3+build")), - ], - skills: [ - "git": SkillDeclaration(select: .all), - "local": SkillDeclaration( - select: .names(["a", "b"]), exclude: ["b"], agents: [.codex], mode: .copy, - overrides: [ - "a": SkillOverride(agents: [], mode: .link), "b": SkillOverride(), - ]), - "index": SkillDeclaration(select: .names([])), - ], - instructions: InstructionsDeclaration( - agents: [], sections: ["guide", "git:rule", "own", "guide"], - chatgpt: ["weekly": PromptDeclaration(sections: [], append: "notes/weekly.md")]), - watch: ["git"])) + let printed = try CanonicalPrinter().manifest(construction) + let roundtrip = try DeclarationDocument( + bytes: printed, identity: DocumentIdentity(fixture.name)) + #expect(roundtrip.declaration == doc.declaration, "\(fixture.name)") + } } @Test func absentValuesStayDistinctFromExplicitEmptyValues() throws { @@ -75,66 +37,38 @@ struct ProjectionTests { let explicit = try projected( "let agents = Agents(defaultAgents: [], components: [.instructions(agents: [])], watch: [])") #expect(explicit.agents == []) - #expect(explicit.instructions == InstructionsDeclaration(agents: [])) + #expect((try explicit.instructions) == InstructionsDeclaration(agents: [])) #expect(explicit.watch == nil) let inherited = try projected("let agents = Agents(components: [.instructions()])") #expect(inherited.agents == nil) - #expect(inherited.instructions == InstructionsDeclaration()) - #expect(inherited.instructions?.agents == nil) + #expect((try inherited.instructions) == InstructionsDeclaration()) + #expect((try inherited.instructions)?.agents == nil) } @Test(arguments: [ - ("groups: [.group(name: \"g\")], uses: [\"g\"]", "\"g\""), - ( - "components: [.skills(source: \"s\", condition: .when(agents: [.codex]))]", - ".when(agents: [.codex])" - ), - ( - "components: [.skills(source: \"s\", native: [\"claude-code/skill@1\": [\"x\": 1]])]", - "[\"claude-code/skill@1\": [\"x\": 1]]" - ), - ("components: [.instructions(condition: .when(scopes: [.user]))]", ".when(scopes: [.user])"), - ( - "components: [.instructions(sections: [.section(name: \"g\", condition: .when())])]", - ".when()" - ), - ( - "components: [.instructions(chatGPT: [.prompt(name: \"p\", sections: [], condition: .when(platforms: [.linux]))])]", - ".when(platforms: [.linux])" - ), - ( - "components: [.instructions(chatGPT: [.prompt(name: \"p\", sections: [.section(name: \"g\", condition: .when())])])]", - ".when()" - ), - ("components: [.ignore(name: \"i\", patterns: [])]", ".ignore(name: \"i\", patterns: [])"), - ( - "components: [.skills(source: \"s\"), .skills(source: \"s\", select: [\"a\"])]", - ".skills(source: \"s\", select: [\"a\"])" - ), - ( - "components: [.instructions(), .instructions(sections: [\"g\"])]", - ".instructions(sections: [\"g\"])" - ), - ("components: [.skills(source: \".\")]", "\".\""), + "groups: [.group(name: \"g\")], uses: [\"g\"]", + "components: [.skills(source: \"s\", condition: .when(agents: [.codex]))]", + "components: [.skills(source: \"s\", native: [\"claude-code/skill@1\": [\"x\": 1]])]", + "components: [.instructions(condition: .when(scopes: [.user]))]", + "components: [.instructions(sections: [.section(name: \"g\", condition: .when())])]", + "components: [.instructions(chatGPT: [.prompt(name: \"p\", sections: [], condition: .when(platforms: [.linux]))])]", + "components: [.instructions(chatGPT: [.prompt(name: \"p\", sections: [.section(name: \"g\", condition: .when())])])]", + "components: [.ignore(name: \"i\", patterns: [])]", + "components: [.skills(source: \"s\"), .skills(source: \"s\", select: [\"a\"])]", + "components: [.instructions(), .instructions(sections: [\"g\"])]", + "components: [.skills(source: \".\")]", ]) - func unsupportedStructuresAreReportedAtTheirLocation(_ fields: String, _ located: String) throws { - let body = - "let agents = Agents(sources: [.source(name: \"s\", path: \"s\")], " + fields + ")" + func completeStructuresRemainSymbolic(_ fields: String) throws { + let body = #"let agents = Agents(sources: [.source(name: "s", path: "s")], "# + fields + ")" let doc = try document(body) - do { - _ = try ManifestProjection.declaration(of: doc, environment: projectionEnvironment) - Issue.record("projection accepted unsupported structure: \(fields)") - } catch let failure as ManifestFailure { - #expect(failure.diagnostics.map(\.code) == ["manifest.unsupported"]) - let span = try #require(failure.diagnostics.first?.span) - #expect(span.document == DocumentIdentity("manifest")) - #expect( - String(decoding: doc.bytes[span.start.. 1) - } + let declaration = try ManifestProjection.declaration( + of: doc, environment: projectionEnvironment) + #expect( + Lowering.declaration(try DeclarationConstruction.root(declaration).constructionValue) + == doc.declaration) } - @Test func inertGroupsAndExportsAreAccepted() throws { + @Test func unusedGroupsAndExportsArePreserved() throws { let declaration = try projected( """ let agents = Agents( @@ -153,8 +87,10 @@ struct ProjectionTests { ] ) """) - #expect( - declaration == Declaration(sources: ["s": SourceDeclaration(kind: .local, location: "s")])) + #expect(declaration.exports == ["review"]) + #expect(declaration.groups.map(\.name) == ["review", "nested"]) + #expect(declaration.groups[0].components.count == 2) + #expect(declaration.groups[0].uses == [GroupUseDeclaration(name: "nested")]) } @Test func environmentDependentValidationFollowsProjection() throws { @@ -170,7 +106,7 @@ struct ProjectionTests { #expect(try ManifestProjection.declaration(of: doc, environment: other).sources.count == 2) } - @Test func semanticEqualityIgnoresSpellingButKeepsInheritanceAndSectionOrder() { + @Test func semanticEqualityIgnoresSpellingButKeepsInheritanceAndSectionOrder() throws { func equal(_ lhs: Declaration, _ rhs: Declaration) -> Bool { ManifestProjection.equivalent(lhs, rhs, environment: projectionEnvironment) } @@ -209,18 +145,20 @@ struct ProjectionTests { let base = Declaration(sources: ["s": SourceDeclaration(kind: .local, location: "s")]) var left = base var right = base - left.skills = ["s": SkillDeclaration(select: .names(["a", "b"]), exclude: [], overrides: [:])] - right.skills = ["s": SkillDeclaration(select: .names(["b", "a"]))] + try left.setSkills([ + "s": SkillDeclaration(select: .names(["a", "b"]), exclude: [], overrides: [:]) + ]) + try right.setSkills(["s": SkillDeclaration(select: .names(["b", "a"]))]) #expect(equal(left, right)) - right.skills?["s"]?.agents = [] + try right.updateSkills { $0?["s"]?.agents = [] } #expect(!equal(left, right)) - left.instructions = InstructionsDeclaration(sections: ["a", "b"], chatgpt: [:]) + try left.setInstructions(InstructionsDeclaration(sections: ["a", "b"], chatgpt: [:])) right = left - right.instructions?.chatgpt = nil + try right.updateInstructions { $0?.chatgpt = nil } #expect(equal(left, right)) - right.instructions?.sections = ["b", "a"] + try right.updateInstructions { $0?.sections = ["b", "a"] } #expect(!equal(left, right)) - right.instructions = nil + try right.setInstructions(nil) #expect(!equal(left, right)) } } diff --git a/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift b/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift index 7fe0e34..e452104 100644 --- a/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift +++ b/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift @@ -45,7 +45,7 @@ struct LifecycleRegressionTests { source: fixture.repo.path, alias: "fixture", agents: [.codex, .claudeCode], mode: .copy, environment: fixture.environment)) var declaration = try fixture.store().loadDeclaration() - declaration.skills?["fixture"]?.agents = [.codex] + try declaration.updateSkills { $0?["fixture"]?.agents = [.codex] } try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) let target = fixture.target("demo") try FileManager.default.createDirectory( @@ -102,7 +102,9 @@ struct LifecycleRegressionTests { try fixture.commit() _ = try fixture.add(mode: .copy) var declaration = try fixture.store().loadDeclaration() - declaration.skills?["fixture"]?.overrides = ["demo": SkillOverride(mode: .edit)] + try declaration.updateSkills { + $0?["fixture"]?.overrides = ["demo": SkillOverride(mode: .edit)] + } try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) try FileManager.default.removeItem(at: fixture.repo.appendingPathComponent("skills/demo")) diff --git a/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift b/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift index eaf8ad7..85337ff 100644 --- a/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift @@ -123,8 +123,8 @@ struct ManifestLifecycleTests { #expect(final.hasSuffix("),\n ],\n watch: []\n)\n")) let declaration = try store.loadDeclaration() #expect(declaration.watch == nil) - #expect(declaration.skills?["fixture"]?.select == .all) - #expect(declaration.skills?["fixture"]?.exclude == nil) + #expect((try declaration.skills)?["fixture"]?.select == .all) + #expect((try declaration.skills)?["fixture"]?.exclude == nil) #expect(try store.loadResolved().skills.keys.sorted() == ["demo", "other"]) } diff --git a/Tests/AgentsSkillsTests/SkillLifecycleTests.swift b/Tests/AgentsSkillsTests/SkillLifecycleTests.swift index 1bc27ef..5e3b91d 100644 --- a/Tests/AgentsSkillsTests/SkillLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/SkillLifecycleTests.swift @@ -200,9 +200,10 @@ struct SkillLifecycleTests { try fixture.commit() _ = try fixture.add() var declaration = try fixture.store().loadDeclaration() - declaration.instructions = InstructionsDeclaration( - sections: ["fixture:rules"], - chatgpt: ["prompt": PromptDeclaration(sections: ["fixture:rules"])]) + try declaration.setInstructions( + InstructionsDeclaration( + sections: ["fixture:rules"], + chatgpt: ["prompt": PromptDeclaration(sections: ["fixture:rules"])])) declaration.watch = ["fixture"] var lock = try fixture.store().loadResolved() let skill = try #require(lock.skills["demo"]) @@ -214,7 +215,7 @@ struct SkillLifecycleTests { try fixture.store().save(declaration: declaration, resolved: lock) try SkillOperations.remove(skillNames: ["demo"], environment: fixture.environment) #expect(try fixture.store().loadResolved().instructions == lock.instructions) - #expect(try fixture.store().loadDeclaration().instructions == declaration.instructions) + #expect(try fixture.store().loadDeclaration().instructions == (try declaration.instructions)) #expect(try fixture.store().loadDeclaration().watch == ["fixture"]) } diff --git a/Tests/AgentsSkillsTests/SourceAliasTests.swift b/Tests/AgentsSkillsTests/SourceAliasTests.swift index 7400aec..bd49f72 100644 --- a/Tests/AgentsSkillsTests/SourceAliasTests.swift +++ b/Tests/AgentsSkillsTests/SourceAliasTests.swift @@ -23,6 +23,6 @@ struct SkillSourceAliasTests { let declaration = try fixture.store().loadDeclaration() #expect(declaration.sources["source"]?.location == fixture.repo.path) #expect(declaration.sources["mirror-source"]?.location == mirror.path) - #expect(declaration.skills?["mirror-source"]?.select == .names(["other"])) + #expect((try declaration.skills)?["mirror-source"]?.select == .names(["other"])) } } diff --git a/Tests/AgentsSkillsTests/SourceShorthandTests.swift b/Tests/AgentsSkillsTests/SourceShorthandTests.swift index e4cccef..adf8f0e 100644 --- a/Tests/AgentsSkillsTests/SourceShorthandTests.swift +++ b/Tests/AgentsSkillsTests/SourceShorthandTests.swift @@ -20,9 +20,12 @@ struct SourceShorthandTests { #expect( declaration.sources == [ "source": SourceDeclaration( - kind: .local, location: fixture.repo.path, requirement: .branch("master")) + kind: .local, location: fixture.repo.path, requirement: .branch("master"), + environment: SourceEnvironment( + projectDirectory: fixture.environment.projectDirectory, + homeDirectory: fixture.environment.homeDirectory)) ]) - #expect(declaration.skills?["source"]?.select == .names(["demo"])) + #expect((try declaration.skills)?["source"]?.select == .names(["demo"])) } @Test func sourceListingFiltersToTheSelectedSkill() throws { diff --git a/Tests/AgentsSkillsTests/UpdateReportingTests.swift b/Tests/AgentsSkillsTests/UpdateReportingTests.swift index 307c3fa..7f3e189 100644 --- a/Tests/AgentsSkillsTests/UpdateReportingTests.swift +++ b/Tests/AgentsSkillsTests/UpdateReportingTests.swift @@ -193,7 +193,7 @@ struct UpdateReportingTests { SkillOperations.updateInstalled(environment: fixture.environment).first) #expect(repair.membership.allSatisfy { $0.before == $0.after } && !repair.changes.isEmpty) var declaration = try store.loadDeclaration() - declaration.skills = nil + try declaration.setSkills(nil) try store.save(declaration: declaration, resolved: store.loadResolved()) let removed = try #require( SkillOperations.updateInstalled(environment: fixture.environment).first) @@ -213,15 +213,15 @@ struct UpdateReportingTests { _ = try fixture.add(mode: .edit) let store = fixture.store() var declaration = try store.loadDeclaration() - declaration.skills?["fixture"]?.agents = [.codex, .cursor, .claudeCode] + try declaration.updateSkills { $0?["fixture"]?.agents = [.codex, .cursor, .claudeCode] } try store.save(declaration: declaration, resolved: store.loadResolved()) let added = try #require( SkillOperations.updateInstalled(environment: fixture.environment).first) #expect(added.membership.first { $0.agent == .codex }?.before == .installed(mode: .edit)) #expect(added.membership.first { $0.agent == .cursor }?.before == .absent) _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) - declaration.skills?["fixture"]?.agents = [.codex, .cursor] - declaration.skills?["fixture"]?.mode = .copy + try declaration.updateSkills { $0?["fixture"]?.agents = [.codex, .cursor] } + try declaration.updateSkills { $0?["fixture"]?.mode = .copy } try store.save(declaration: declaration, resolved: store.loadResolved()) let changed = try #require( SkillOperations.updateInstalled(environment: fixture.environment).first) diff --git a/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift b/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift index 58913a9..3dc6430 100644 --- a/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift +++ b/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift @@ -363,7 +363,7 @@ struct WatchSubscriptionTests { try watch.add("rules", environment: fixture.environment) try watch.seen("rules", environment: fixture.environment) try watch.remove("rules", environment: fixture.environment) - #expect(try fixture.store().loadDeclaration().instructions == declaration.instructions) + #expect(try fixture.store().loadDeclaration().instructions == (try declaration.instructions)) #expect(try Data(contentsOf: fixture.store().resolvedURL) == lockBytes) } } diff --git a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift index 8687b6c..c1217d8 100644 --- a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift +++ b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift @@ -14,7 +14,7 @@ struct CombinedUpdateTests { try fixture.install(mode: .edit, agents: [.codex]) try fixture.advance() var declaration = try fixture.store.loadDeclaration() - declaration.skills?["fixture"]?.mode = .copy + try declaration.updateSkills { $0?["fixture"]?.mode = .copy } declaration.sources["fixture"]?.requirement = .branch("main") try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) let before = try fixture.snapshot() @@ -55,7 +55,7 @@ struct CombinedUpdateTests { 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 declaration.updateInstructions { $0?.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 }) @@ -70,7 +70,7 @@ struct CombinedUpdateTests { let fixture = try UpdateFixture() try fixture.install(mode: .edit, agents: [.codex]) var declaration = try fixture.store.loadDeclaration() - declaration.skills?["fixture"]?.mode = .copy + try declaration.updateSkills { $0?["fixture"]?.mode = .copy } declaration.sources["fixture"]?.requirement = .branch("main") try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) let before = try fixture.snapshot() @@ -92,7 +92,7 @@ struct CombinedUpdateTests { try fixture.commit() try fixture.install(mode: .edit, agents: [.codex]) var declaration = try fixture.store.loadDeclaration() - declaration.skills?["fixture"]?.mode = .copy + try declaration.updateSkills { $0?["fixture"]?.mode = .copy } declaration.sources["fixture"]?.requirement = .branch("main") try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) let before = try fixture.snapshot() @@ -161,10 +161,12 @@ struct CombinedUpdateTests { } var declaration = try fixture.store.loadDeclaration() declaration.sources["live"] = SourceDeclaration(kind: .local, location: live.path) - declaration.skills?["live"] = SkillDeclaration(select: .all, agents: [.codex], mode: .edit) + try declaration.updateSkills { + $0?["live"] = SkillDeclaration(select: .all, agents: [.codex], mode: .edit) + } declaration.sources["rules"] = SourceDeclaration(kind: .local, location: rules.repo.path) - declaration.instructions?.sections = ["rules:rules"] - declaration.instructions?.chatgpt?["weekly"]?.sections = ["rules:rules"] + try declaration.updateInstructions { $0?.sections = ["rules:rules"] } + try declaration.updateInstructions { $0?.chatgpt?["weekly"]?.sections = ["rules:rules"] } declaration.sources["watched"] = SourceDeclaration( kind: .wellKnown, location: "https://example.test") declaration.watch = ["watched"] @@ -235,8 +237,8 @@ struct CombinedUpdateTests { try fixture.declare() var declaration = try fixture.store.loadDeclaration() declaration.sources["rules"] = SourceDeclaration(kind: .local, location: other.repo.path) - declaration.instructions?.sections = ["rules:rules"] - declaration.instructions?.chatgpt?["weekly"]?.sections = ["rules:rules"] + try declaration.updateInstructions { $0?.sections = ["rules:rules"] } + try declaration.updateInstructions { $0?.chatgpt?["weekly"]?.sections = ["rules:rules"] } try fixture.store.save(declaration: declaration, resolved: ResolvedState()) _ = try fixture.apply() try fixture.advance() @@ -418,7 +420,7 @@ struct CombinedUpdateTests { if kind == "skills" { try fixture.write("invalid", to: fixture.repo.appendingPathComponent("skills/demo/SKILL.md")) var declaration = try fixture.store.loadDeclaration() - declaration.skills?["fixture"]?.select = .names(["demo"]) + try declaration.updateSkills { $0?["fixture"]?.select = .names(["demo"]) } try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) try fixture.commit() } else if kind == "instructions" { @@ -546,11 +548,13 @@ struct CombinedUpdateTests { #expect(!FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) try fixture.declare() var declaration = try fixture.store.loadDeclaration() - declaration.skills = nil + try declaration.setSkills(nil) try fixture.store.save(declaration: declaration, resolved: ResolvedState()) #expect(try fixture.apply().report.skills.isEmpty) - declaration.instructions = nil - declaration.skills = ["fixture": SkillDeclaration(select: .all, agents: [.codex], mode: .copy)] + try declaration.setInstructions(nil) + try declaration.setSkills([ + "fixture": SkillDeclaration(select: .all, agents: [.codex], mode: .copy) + ]) try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) _ = try fixture.apply() #expect(try fixture.store.loadResolved().instructions == LockedInstructions()) @@ -561,8 +565,8 @@ struct CombinedUpdateTests { let fixture = try UpdateFixture() try fixture.install() var declaration = try fixture.store.loadDeclaration() - declaration.skills = nil - declaration.instructions?.sections = [] + try declaration.setSkills(nil) + try declaration.updateInstructions { $0?.sections = [] } try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) _ = try fixture.apply() try fixture.git(["commit", "--allow-empty", "-m", "repin"]) @@ -575,10 +579,12 @@ struct CombinedUpdateTests { to: fixture.repo.appendingPathComponent("instructions/second.md") ) try fixture.commit() - declaration.instructions?.chatgpt?["weekly"]?.sections = ["fixture:rules", "fixture:second"] + try declaration.updateInstructions { + $0?.chatgpt?["weekly"]?.sections = ["fixture:rules", "fixture:second"] + } try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) _ = try fixture.apply() - declaration.instructions?.chatgpt?["weekly"]?.sections.reverse() + try declaration.updateInstructions { $0?.chatgpt?["weekly"]?.sections.reverse() } try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) #expect(try fixture.preview().hasChanges) _ = try fixture.apply() diff --git a/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift b/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift index 98cc1f4..f0d5aaf 100644 --- a/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift +++ b/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift @@ -42,7 +42,7 @@ struct RequirementUpdateTests { try fixture.declare(agents: [.codex]) var declaration = try fixture.store.loadDeclaration() declaration.agents = [.codex] - declaration.instructions?.agents = nil + try declaration.updateInstructions { $0?.agents = nil } declaration.sources["fixture"]?.requirement = .upToNextMajor(from: "1.2.0") try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) _ = try fixture.apply() From 79013a48e151d331b554bbf20872792152cce908 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 6 Nov 2026 21:55:56 +0800 Subject: [PATCH 032/171] fix: bind synchronization observers as task-local values --- Scripts/diagnose-release-tests.py | 8 ++++++-- Sources/AgentsCore/DirectoryHandle.swift | 10 +++++++--- Tests/AgentsCoreTests/StateTransactionTests.swift | 2 +- Tests/AgentsCoreTests/TransactionCostTests.swift | 4 +++- 4 files changed, 17 insertions(+), 7 deletions(-) diff --git a/Scripts/diagnose-release-tests.py b/Scripts/diagnose-release-tests.py index b4ddcfb..f36dbf4 100644 --- a/Scripts/diagnose-release-tests.py +++ b/Scripts/diagnose-release-tests.py @@ -15,7 +15,11 @@ ROOT = Path(__file__).resolve().parents[1] OUTPUT = ROOT / ".build/release-crash-diagnostics" FLAGS = ["-c", "release", "--disable-index-store", "--build-system", "native"] -FILTER = "PublicationTests.primitiveFailuresCleanPrivateResourcesBeforeChangingUserData" +FILTERED_PROBES = [ + ("primitive-failures", "PublicationTests.primitiveFailuresCleanPrivateResourcesBeforeChangingUserData"), + ("scope-creation", "StateTransactionTests.scopeCreationSyncsParentBeforeAllowingTargets"), + ("transaction-cost", "TransactionCostTests.twoSmallFiles"), +] def main(): @@ -68,7 +72,7 @@ def record(name, command): str(bundle), "-c", "release", "--disable-index-store", str(bundle), "--testing-library", "swift-testing"] results = [] - probes = [("filtered", ["--filter", FILTER])] + probes = [(name, ["--filter", pattern]) for name, pattern in FILTERED_PROBES] if not args.filter_only: probes.append(("full", [])) for name, extra in probes: diff --git a/Sources/AgentsCore/DirectoryHandle.swift b/Sources/AgentsCore/DirectoryHandle.swift index 33e74ad..7ad0f5c 100644 --- a/Sources/AgentsCore/DirectoryHandle.swift +++ b/Sources/AgentsCore/DirectoryHandle.swift @@ -3,7 +3,11 @@ import Foundation /// Pins directory ancestry. Child operations never traverse symbolic links. final class DirectoryHandle { - @TaskLocal static var synchronizationObserver: (@Sendable () -> Void)? + struct SynchronizationObserver: Sendable { + let didSynchronize: @Sendable () -> Void + } + + @TaskLocal static var synchronizationObserver: SynchronizationObserver? let descriptor: Int32 let url: URL @@ -591,7 +595,7 @@ final class DirectoryHandle { guard platform_sync(file) == 0 else { throw CoreError.invalidState("cannot sync filesystem entry: \(errno)") } - synchronizationObserver?() + synchronizationObserver?.didSynchronize() } enum CopyStep: String { case directoryCreated, fileCreated, linkCreated, entryCopied } @@ -667,6 +671,6 @@ final class DirectoryHandle { guard platform_copy_metadata(origin, destination, mode) == 0 else { throw CoreError.invalidState("cannot preserve filesystem metadata: \(errno)") } - synchronizationObserver?() + synchronizationObserver?.didSynchronize() } } diff --git a/Tests/AgentsCoreTests/StateTransactionTests.swift b/Tests/AgentsCoreTests/StateTransactionTests.swift index c3c855f..826f9b4 100644 --- a/Tests/AgentsCoreTests/StateTransactionTests.swift +++ b/Tests/AgentsCoreTests/StateTransactionTests.swift @@ -543,7 +543,7 @@ extension StateTransactionTests { let barriers = SynchronizationCount() var steps: [String] = [] try DirectoryHandle.$synchronizationObserver.withValue( - { barriers.add() }, + DirectoryHandle.SynchronizationObserver(didSynchronize: { barriers.add() }), operation: { try FileLock.withLock( at: scope.appendingPathComponent(".agents.lock"), checkpoint: { steps.append($0) }, diff --git a/Tests/AgentsCoreTests/TransactionCostTests.swift b/Tests/AgentsCoreTests/TransactionCostTests.swift index 5fab812..93b3768 100644 --- a/Tests/AgentsCoreTests/TransactionCostTests.swift +++ b/Tests/AgentsCoreTests/TransactionCostTests.swift @@ -29,7 +29,9 @@ struct TransactionCostTests { for target in targets { try transaction.replace(target, with: .data(Data("after".utf8))) } - try DirectoryHandle.$synchronizationObserver.withValue({ count.sync() }) { + try DirectoryHandle.$synchronizationObserver.withValue( + DirectoryHandle.SynchronizationObserver(didSynchronize: { count.sync() }) + ) { try transaction.commit() } } From 14b20fb7e6f589cbf4649f5a156c3af702bcf9b7 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 6 Nov 2026 22:44:22 +0800 Subject: [PATCH 033/171] fix: preserve complete declaration edit semantics --- Documentation/Architecture/State.md | 9 +- .../CompleteDeclarationPlanner.swift | 67 ++++++++++- .../AgentsManifest/DeclarationEditPlan.swift | 23 ++-- Sources/AgentsManifest/ManifestState.swift | 2 + Tests/AgentsCoreTests/WatchStateTests.swift | 35 ++++++ .../FullDeclarationDependencyTests.swift | 54 +++++++++ .../FullDeclarationTests.swift | 113 ++++++++++++++++++ 7 files changed, 294 insertions(+), 9 deletions(-) create mode 100644 Tests/AgentsManifestTests/FullDeclarationDependencyTests.swift diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index b168253..4f83c8e 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -180,11 +180,18 @@ ambiguous comments, fail with `manifest.edit.readOnly`. A batch holds at most 100 requests, and the document is rebuilt from the new bytes before the remaining difference is planned. The projection of the final document must equal the intended declaration, or planning fails with `manifest.edit.mismatch`. +Full plans introduce source and group definitions before references, remove +obsolete group edges before adding their replacements, and retain definitions +until all removed references are gone. Each batch therefore remains valid even +when declaration order differs from dependency order. Without declaration bytes, planning prints the complete typed declaration with the [canonical printer](../Reference/Manifest.md#canonical-printing), retaining its ordered collections and symbolic group uses. Dictionary-based convenience initializers and domain mutations choose deterministic order for new entries. +First state-declaration creation sorts only the set-like watch aliases; pure +construction retains input order, and equivalent watch reorders in existing +documents preserve their bytes. The printed bytes pass the same front end and projection check and are published with no-replace. A semantically empty declaration creates no file. @@ -684,4 +691,4 @@ transaction uses `unresolved-transaction` and lists retained recovery locations. It also reports missing installs, changed content and broken links, newer matching Git resolutions and uncommitted changes in selected local source paths. `install` restores all recorded recipients and modes without changing lock -bytes. The consuming CLI controls presentation and user interaction. \ No newline at end of file +bytes. The consuming CLI controls presentation and user interaction. diff --git a/Sources/AgentsManifest/CompleteDeclarationPlanner.swift b/Sources/AgentsManifest/CompleteDeclarationPlanner.swift index e7525e0..ed35e53 100644 --- a/Sources/AgentsManifest/CompleteDeclarationPlanner.swift +++ b/Sources/AgentsManifest/CompleteDeclarationPlanner.swift @@ -5,11 +5,76 @@ import AgentsDescription /// by field, ordered arrays by occurrence, and assembled expressions remain read-only. struct CompleteDeclarationPlanner { let document: DeclarationDocument + let current: Declaration let next: Declaration + let environment: RuntimeEnvironment func plan() throws -> [DocumentOperation] { + // Keep definitions until their references leave. New groups start without references, so + // declaration order need not be dependency order and every split batch remains valid. + var stage = current + let sourceNames = Set(next.sourceDeclarations.map(\.name)) + stage.sourceDeclarations = + next.sourceDeclarations + + current.sourceDeclarations.filter { !sourceNames.contains($0.name) } + var operations = try plan(stage) + if !operations.isEmpty { return operations } + + let groupNames = Set(current.groups.map(\.name)) + stage.groups += next.groups.filter { !groupNames.contains($0.name) }.map { + ComponentGroupDeclaration(name: $0.name, condition: $0.condition) + } + operations = try plan(stage) + if !operations.isEmpty { return operations } + + // Remove obsolete edges before adding final edges; their union can contain a cycle even + // when both declarations are acyclic. Definitions remain available throughout this phase. + for index in stage.groups.indices { + let desired = next.groups.first { $0.name == stage.groups[index].name } + stage.groups[index].uses.removeAll { use in + use.source == nil + && !(desired?.uses.contains { $0.source == nil && $0.name == use.name } ?? false) + } + } + operations = try plan(stage) + if !operations.isEmpty { return operations } + + let desiredGroups = Set(next.groups.map(\.name)) + let obsoleteGroups = stage.groups.filter { !desiredGroups.contains($0.name) } + stage.groups = next.groups + obsoleteGroups + operations = try plan(stage) + if !operations.isEmpty { return operations } + + var referenced = next + referenced.sourceDeclarations = stage.sourceDeclarations + referenced.groups = stage.groups + operations = try plan(referenced) + if !operations.isEmpty { return operations } + + referenced.groups = next.groups + operations = try plan(referenced) + if !operations.isEmpty { return operations } + return try plan(next) + } + + private func plan(_ target: Declaration) throws -> [DocumentOperation] { var operations: [DocumentOperation] = [] - let desired = try DeclarationConstruction.root(next).constructionValue + var desired = try DeclarationConstruction.root(target).constructionValue + if case .node(let type, let member, var fields) = desired { + let originals = document.evaluation.root.value.fields["sources"]!.array! + fields["sources"] = .array( + try target.sourceDeclarations.map { entry in + if let index = current.sourceDeclarations.firstIndex(where: { $0.name == entry.name }), + ManifestProjection.equivalent( + current.sourceDeclarations[index].source, entry.source, environment: environment) + { + return originals[index] + } + return try DeclarationConstruction.source(alias: entry.name, entry.source) + .constructionValue + }) + desired = .node(type: type, member: member, fields: fields) + } try difference(document.evaluation.root.value, desired, at: "", into: &operations) return operations } diff --git a/Sources/AgentsManifest/DeclarationEditPlan.swift b/Sources/AgentsManifest/DeclarationEditPlan.swift index a9f46e4..5aa35fc 100644 --- a/Sources/AgentsManifest/DeclarationEditPlan.swift +++ b/Sources/AgentsManifest/DeclarationEditPlan.swift @@ -2,8 +2,8 @@ import AgentsCore import AgentsDescription /// Turns a declaration change into source bytes. Existing documents receive the smallest edits -/// that express the semantic difference, without reordering; bytes outside the edited ranges, -/// including comments, are unchanged. Batches hold at most 100 requests and are replanned +/// that express the semantic difference, including ordered occurrence changes. Bytes outside +/// the edited ranges, including comments, are unchanged. Batches hold at most 100 requests and are replanned /// against the bytes each batch produces. The final document must project to `next`. package enum DeclarationEditPlan { /// Returns `nil` when `next` is semantically equal to `previous`. Without existing bytes, the @@ -49,7 +49,9 @@ package enum DeclarationEditPlan { span: document.source.span(0..<0)) } if equivalent(previous, next) { return nil } - var remaining = Int.max + // Definition/reference phases can expose more operations after a batch. Detect stalled + // or cyclic plans by snapshot instead of requiring the operation count to decrease. + var snapshots: Set = [document.digest] while true { var planner = Planner( document: document, current: current, next: next, environment: environment) @@ -57,12 +59,11 @@ package enum DeclarationEditPlan { if operations.isEmpty { break } let change = try document.preparing( operations: Array(operations.prefix(ManifestLimits.Editing.requests))) - guard change.bytes != document.bytes, operations.count < remaining else { + guard change.bytes != document.bytes, snapshots.insert(change.digest).inserted else { throw failure( "manifest.edit.mismatch", "an edit batch made no progress", span: document.source.span(0..<0)) } - remaining = operations.count document = try DeclarationDocument(bytes: change.bytes, identity: identity) current = try ManifestProjection.declaration(of: document, environment: environment) } @@ -101,7 +102,9 @@ private struct Planner { if !flat(current) || !flat(next) || !flatOrder() || current.groups != next.groups || current.uses != next.uses || current.exports != next.exports { - return try CompleteDeclarationPlanner(document: document, next: next).plan() + return try CompleteDeclarationPlanner( + document: document, current: current, next: next, environment: environment + ).plan() } var skillComponents: [String: Int] = [:] var instructionsComponent: Int? @@ -198,7 +201,13 @@ private struct Planner { let sourceOrder = oldSources.filter(newSet.contains) + newSources.filter { !Set(oldSources).contains($0) }.sorted(by: utf8Less) - return planned == desired && sourceOrder == newSources + let oldPrompts = (try? current.instructions)?.prompts.map(\.name) ?? [] + let newPrompts = (try? next.instructions)?.prompts.map(\.name) ?? [] + let promptSet = Set(newPrompts) + let promptOrder = + oldPrompts.filter(promptSet.contains) + + newPrompts.filter { !Set(oldPrompts).contains($0) }.sorted(by: utf8Less) + return planned == desired && sourceOrder == newSources && promptOrder == newPrompts } func flat(_ value: Declaration) -> Bool { diff --git a/Sources/AgentsManifest/ManifestState.swift b/Sources/AgentsManifest/ManifestState.swift index f2f4427..dd3c90b 100644 --- a/Sources/AgentsManifest/ManifestState.swift +++ b/Sources/AgentsManifest/ManifestState.swift @@ -27,6 +27,8 @@ extension StateStore { _ next: Declaration, replacing previous: Declaration, prepared: StatePrecondition ) throws -> DeclarationChange? { let bytes = try declarationBytes(prepared: prepared) + var next = next + if bytes == nil { next.watch = next.watch?.sorted(by: utf8Less) } let output: [UInt8]? do { output = try DeclarationEditPlan.bytes( diff --git a/Tests/AgentsCoreTests/WatchStateTests.swift b/Tests/AgentsCoreTests/WatchStateTests.swift index 8efd92b..d8ff0b1 100644 --- a/Tests/AgentsCoreTests/WatchStateTests.swift +++ b/Tests/AgentsCoreTests/WatchStateTests.swift @@ -8,6 +8,41 @@ import Testing @Suite("Watch state") struct WatchStateTests { + @Test func existingDeclarationWatchReorderingPreservesBytesAndInode() throws { + let root = try temporaryDirectory() + defer { try? FileManager.default.removeItem(at: root) } + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: [:] + )) + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + let text = """ + // agents-tools-version: 1.0 + import AgentsDescription + + // Preserve this layout. + let agents = Agents(sources: [ + .source(name: "web", url: "https://example.test/repo.git"), + .source(name: "git", path: "missing"), + ], watch: ["web", "git"]) + + """ + let bytes = Data(text.utf8) + try bytes.write(to: store.declarationURL) + let inode = try #require( + FileManager.default.attributesOfItem(atPath: store.declarationURL.path)[.systemFileNumber] + as? NSNumber) + var declaration = try store.loadDeclaration() + #expect(declaration.watch == ["web", "git"]) + declaration.watch = ["git", "web"] + try store.save(declaration: declaration, resolved: ResolvedState()) + #expect(try Data(contentsOf: store.declarationURL) == bytes) + #expect( + try FileManager.default.attributesOfItem(atPath: store.declarationURL.path)[.systemFileNumber] + as? NSNumber == inode) + } + @Test(arguments: [InstallScope.project, .user]) func storesSortedBaselinesAndPreservesWatchWhenSavingOtherState(_ scope: InstallScope) throws { let root = try temporaryDirectory() diff --git a/Tests/AgentsManifestTests/FullDeclarationDependencyTests.swift b/Tests/AgentsManifestTests/FullDeclarationDependencyTests.swift new file mode 100644 index 0000000..a525b0a --- /dev/null +++ b/Tests/AgentsManifestTests/FullDeclarationDependencyTests.swift @@ -0,0 +1,54 @@ +import AgentsCore +import Testing + +@testable import AgentsManifest + +extension FullDeclarationTests { + @Test(arguments: [false, true]) + func addingAndRemovingGroupDependenciesAcrossBatches(_ removing: Bool) throws { + let groups = + (0..<102).map { index in + ComponentGroupDeclaration(name: "g\(index)", uses: [GroupUseDeclaration(name: "hub")]) + } + [ComponentGroupDeclaration(name: "hub")] + let populated = Declaration( + sourceDeclarations: [], groups: groups, uses: [GroupUseDeclaration(name: "g0")], + exports: ["g0"]) + let empty = try projected("let agents = Agents()") + let previous = removing ? populated : empty + let next = removing ? empty : populated + let initial = + try planned(Declaration(), previous, in: nil) + ?? Array((manifestHeader + "let agents = Agents()").utf8) + let bytes = try #require( + try planned(previous, next, in: String(decoding: initial, as: UTF8.self))) + let result = try ManifestProjection.declaration( + of: DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")), + environment: projectionEnvironment) + #expect(result == next) + #expect(try planned(result, next, in: String(decoding: bytes, as: UTF8.self)) == nil) + } + + @Test func reversingGroupDependenciesAcrossBatchesKeepsAcyclicIntermediateDeclarations() throws { + var previous = Declaration( + sourceDeclarations: [], + groups: (0..<102).map { index in + ComponentGroupDeclaration(name: "g\(index)", uses: [GroupUseDeclaration(name: "hub")]) + } + [ComponentGroupDeclaration(name: "hub")]) + let initial = try #require(try planned(Declaration(), previous, in: nil)) + previous = try ManifestProjection.declaration( + of: DeclarationDocument(bytes: initial, identity: DocumentIdentity("manifest")), + environment: projectionEnvironment) + var next = previous + for index in next.groups.indices { + next.groups[index].uses = + next.groups[index].name == "hub" + ? (0..<102).map { GroupUseDeclaration(name: "g\($0)") } : [] + } + let bytes = try #require( + try planned(previous, next, in: String(decoding: initial, as: UTF8.self))) + let result = try ManifestProjection.declaration( + of: DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")), + environment: projectionEnvironment) + #expect(result == next) + } +} diff --git a/Tests/AgentsManifestTests/FullDeclarationTests.swift b/Tests/AgentsManifestTests/FullDeclarationTests.swift index 4692859..0a55e7e 100644 --- a/Tests/AgentsManifestTests/FullDeclarationTests.swift +++ b/Tests/AgentsManifestTests/FullDeclarationTests.swift @@ -7,6 +7,119 @@ import Testing @Suite("Complete symbolic declarations") struct FullDeclarationTests { + @Test func removingReferencedSourceAcrossBatchesProducesEmptyDeclaration() throws { + let components = (0..<100).map { + #" .subagent(name: "agent\#($0)", description: "d", prompt: .file("x.md", source: "s")),"# + }.joined(separator: "\n") + let body = """ + let agents = Agents(sources: [.source(name: "s", path: "missing")], components: [ + \(components) + ]) + """ + let previous = try projected(body) + #expect(previous.components.count == 100) + var next = previous + next.components = [] + next.sourceDeclarations = [] + let bytes = try #require(try planned(previous, next, in: manifestHeader + body)) + let result = try ManifestProjection.declaration( + of: DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")), + environment: projectionEnvironment) + #expect(result == next) + } + + @Test func reorderingPromptsMovesTheirCommentsAndRepeatsAsNoOp() throws { + let body = """ + // Keep this header. + let agents = Agents(components: [ + .instructions(chatGPT: [ + // Prompt a. + .prompt(name: "a", sections: ["first"]), + // Prompt b. + .prompt(name: "b", sections: ["second"]), + ]), + ]) + // Keep this tail. + """ + let previous = try projected(body) + var next = previous + guard case .instructions(var instructions) = next.components[0] else { + Issue.record("expected instructions") + return + } + instructions.prompts.reverse() + next.components[0] = .instructions(instructions) + let bytes = try #require(try planned(previous, next, in: manifestHeader + body)) + let output = String(decoding: bytes, as: UTF8.self) + let expected = body.replacingOccurrences( + of: """ + // Prompt a. + .prompt(name: "a", sections: ["first"]), + // Prompt b. + .prompt(name: "b", sections: ["second"]), + """, + with: """ + // Prompt b. + .prompt(name: "b", sections: ["second"]), + // Prompt a. + .prompt(name: "a", sections: ["first"]), + """) + #expect(output == manifestHeader + expected) + let result = try ManifestProjection.declaration( + of: DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")), + environment: projectionEnvironment) + #expect(result.components == next.components) + #expect(try planned(result, next, in: output) == nil) + } + + @Test func equivalentSourceSpellingSurvivesFullComponentEdit() throws { + let body = """ + let agents = Agents( + sources: [.source(name: "s", /* keep source comment */ path: "./s")], + components: [.ignore(name: "i", patterns: ["old"]) ] + ) + """ + let previous = try projected(body) + var next = previous + next.sources["s"]?.location = + projectionEnvironment.projectDirectory.appendingPathComponent("s").path + next.components[0] = .ignore(name: "i", patterns: ["new"]) + let bytes = try #require(try planned(previous, next, in: manifestHeader + body)) + let output = String(decoding: bytes, as: UTF8.self) + #expect(output.contains(#".source(name: "s", /* keep source comment */ path: "./s")"#)) + let result = try ManifestProjection.declaration( + of: DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")), + environment: projectionEnvironment) + #expect(result.components == next.components) + #expect(ManifestProjection.equivalent(result, next, environment: projectionEnvironment)) + } + + @Test func projectionAndConstructionKeepDeclarationOrder() throws { + let body = """ + let agents = Agents( + exports: ["b", "a"], + sources: [.source(name: "web", url: "https://example.test/repo.git"), .source(name: "git", path: "missing")], + components: [.ignore(name: "b", patterns: []), .ignore(name: "a", patterns: [])], + groups: [.group(name: "b"), .group(name: "a")], + uses: ["b", "a"], watch: ["web", "git"] + ) + """ + let doc = try document(body) + let declaration = try ManifestProjection.declaration( + of: doc, environment: projectionEnvironment) + #expect(declaration.watch == ["web", "git"]) + #expect( + declaration.components == [ + .ignore(name: "b", patterns: []), .ignore(name: "a", patterns: []), + ]) + #expect(declaration.groups.map(\.name) == ["b", "a"]) + #expect(declaration.uses.map(\.name) == ["b", "a"]) + #expect(declaration.exports == ["b", "a"]) + #expect( + Lowering.declaration(try DeclarationConstruction.root(declaration).constructionValue) + == doc.declaration) + } + @Test func conditionsRecipientsAndPluginSelectionsKeepInheritanceAndExplicitEmpty() throws { let declaration = try projected( """ From 2bc807d8e8ffbfb21fd923e4b8c7a507607d7e39 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 6 Nov 2026 22:46:28 +0800 Subject: [PATCH 034/171] ci: remove completed release crash diagnostics --- .github/swift-package.json | 4 -- Scripts/diagnose-release-tests.py | 93 ------------------------------- 2 files changed, 97 deletions(-) delete mode 100644 Scripts/diagnose-release-tests.py diff --git a/.github/swift-package.json b/.github/swift-package.json index 49912fe..22e5cd5 100644 --- a/.github/swift-package.json +++ b/.github/swift-package.json @@ -7,10 +7,6 @@ { "name": "manifest-fixture-generation", "run": "python3 Scripts/generate-manifest-fixtures.py --check" - }, - { - "name": "release-crash-diagnostics", - "run": "python3 Scripts/diagnose-release-tests.py" } ], "test_configurations": ["debug", "release"], diff --git a/Scripts/diagnose-release-tests.py b/Scripts/diagnose-release-tests.py deleted file mode 100644 index f36dbf4..0000000 --- a/Scripts/diagnose-release-tests.py +++ /dev/null @@ -1,93 +0,0 @@ -#!/usr/bin/env python3 -"""Capture the Release test host under LLDB on the selected macOS toolchain.""" - -import argparse -import json -import os -from pathlib import Path -import re -import shlex -import subprocess -import sys -import tempfile - - -ROOT = Path(__file__).resolve().parents[1] -OUTPUT = ROOT / ".build/release-crash-diagnostics" -FLAGS = ["-c", "release", "--disable-index-store", "--build-system", "native"] -FILTERED_PROBES = [ - ("primitive-failures", "PublicationTests.primitiveFailuresCleanPrivateResourcesBeforeChangingUserData"), - ("scope-creation", "StateTransactionTests.scopeCreationSyncsParentBeforeAllowingTargets"), - ("transaction-cost", "TransactionCostTests.twoSmallFiles"), -] - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--filter-only", action="store_true") - args = parser.parse_args() - OUTPUT.mkdir(parents=True, exist_ok=True) - with tempfile.TemporaryDirectory(prefix="home-", dir=OUTPUT) as home: - environment = {key: value for key, value in os.environ.items() - if key in ("PATH", "DEVELOPER_DIR", "SDKROOT", "TMPDIR")} - environment.update(HOME=home, GIT_CONFIG_NOSYSTEM="1", - GIT_CONFIG_GLOBAL="/dev/null", GIT_TERMINAL_PROMPT="0", - TERM="dumb", LC_ALL="C") - - def output(command): - return subprocess.check_output(command, cwd=ROOT, env=environment, - text=True).strip() - - def record(name, command): - print(shlex.join(command), flush=True) - result = subprocess.run(command, cwd=ROOT, env=environment, - text=True, stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, timeout=1800) - (OUTPUT / (name + ".log")).write_text(result.stdout) - print(result.stdout, flush=True) - return result - - print(output(["xcodebuild", "-version"]), flush=True) - print(output(["swift", "--version"]), flush=True) - print(output(["git", "rev-parse", "HEAD"]), flush=True) - build = record("build", ["swift", "test", *FLAGS, "list"]) - if build.returncode: - return build.returncode - swift = Path(output(["xcrun", "--find", "swift"])) - helper = swift.parent.parent / "libexec/swift/pm/swiftpm-testing-helper" - platform = Path(output(["xcrun", "--sdk", "macosx", "--show-sdk-platform-path"])) - binary_directory = Path(output(["swift", "build", *FLAGS, "--show-bin-path"])) - bundle = binary_directory / "corePackageTests.xctest/Contents/MacOS/corePackageTests" - framework_directory = platform / "Developer/Library/Frameworks" - for path in (helper, bundle, framework_directory / "Testing.framework"): - if not path.exists(): - raise RuntimeError(f"Missing selected-toolchain artifact: {path}") - settings = "settings set target.env-vars " + " ".join(map(shlex.quote, [ - "DYLD_FRAMEWORK_PATH=" + str(framework_directory), - "DYLD_LIBRARY_PATH=" + str(platform / "Developer/usr/lib"), - ])) - command = ["xcrun", "lldb", "--batch", "--no-lldbinit", "-o", settings, - "-o", "run", "-k", "thread backtrace all", "-k", "register read", - "-k", "image list", "--", str(helper), "--test-bundle-path", - str(bundle), "-c", "release", "--disable-index-store", str(bundle), - "--testing-library", "swift-testing"] - results = [] - probes = [(name, ["--filter", pattern]) for name, pattern in FILTERED_PROBES] - if not args.filter_only: - probes.append(("full", [])) - for name, extra in probes: - result = record(name, command + extra) - passed = (result.returncode == 0 - and "stop reason =" not in result.stdout - and re.search(r"Test run with [1-9]\d* tests? in .* passed", result.stdout) - and re.search(r"Process \d+ exited with status = 0", result.stdout)) - results.append({"probe": name, "lldb_exit": result.returncode, - "passed": bool(passed), "command": command + extra}) - (OUTPUT / "results.json").write_text(json.dumps(results, indent=2) + "\n") - if not passed: - return 1 - return 0 - - -if __name__ == "__main__": - sys.exit(main()) From 2cfac3f61ac3714219e04c63a4ff0a267a164707 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:51:15 +0800 Subject: [PATCH 035/171] fix: compose complete source transitions before validation --- Documentation/Architecture/State.md | 13 +- .../CompleteDeclarationPlanner.swift | 67 ++------ .../AgentsManifest/DeclarationEditPlan.swift | 59 +++++-- Sources/AgentsManifest/DocumentEditor.swift | 45 +++-- Sources/AgentsManifest/DocumentEdits.swift | 16 +- .../AgentsManifest/ManifestProjection.swift | 25 ++- .../DeclarationStateTests.swift | 27 +++ .../FullDeclarationDependencyTests.swift | 2 +- .../FullDeclarationDraftTests.swift | 156 ++++++++++++++++++ .../FullDeclarationTests.swift | 96 +++++++++++ 10 files changed, 412 insertions(+), 94 deletions(-) create mode 100644 Tests/AgentsManifestTests/FullDeclarationDraftTests.swift diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index 4f83c8e..a9f22df 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -180,10 +180,15 @@ ambiguous comments, fail with `manifest.edit.readOnly`. A batch holds at most 100 requests, and the document is rebuilt from the new bytes before the remaining difference is planned. The projection of the final document must equal the intended declaration, or planning fails with `manifest.edit.mismatch`. -Full plans introduce source and group definitions before references, remove -obsolete group edges before adding their replacements, and retain definitions -until all removed references are gone. Each batch therefore remains valid even -when declaration order differs from dependency order. +Complete edits compose private static drafts across batches. Each batch retains +the front end's static limits and compares its complete IR with the expected +batch result. Domain validation waits until composition finishes, so related +source and reference changes can cross a batch boundary. The final bytes must +pass normal domain validation, environment-aware typed validation and the full +intended-declaration comparison before they can leave planning. Public prepared +changes always validate their final domain, including no-ops. +Composition has an operation budget of twice the combined current and target +value-node counts, and each replan must reduce the remaining direct difference. Without declaration bytes, planning prints the complete typed declaration with the [canonical printer](../Reference/Manifest.md#canonical-printing), retaining its diff --git a/Sources/AgentsManifest/CompleteDeclarationPlanner.swift b/Sources/AgentsManifest/CompleteDeclarationPlanner.swift index ed35e53..94c0b61 100644 --- a/Sources/AgentsManifest/CompleteDeclarationPlanner.swift +++ b/Sources/AgentsManifest/CompleteDeclarationPlanner.swift @@ -10,61 +10,26 @@ struct CompleteDeclarationPlanner { let environment: RuntimeEnvironment func plan() throws -> [DocumentOperation] { - // Keep definitions until their references leave. New groups start without references, so - // declaration order need not be dependency order and every split batch remains valid. - var stage = current - let sourceNames = Set(next.sourceDeclarations.map(\.name)) - stage.sourceDeclarations = - next.sourceDeclarations - + current.sourceDeclarations.filter { !sourceNames.contains($0.name) } - var operations = try plan(stage) - if !operations.isEmpty { return operations } - - let groupNames = Set(current.groups.map(\.name)) - stage.groups += next.groups.filter { !groupNames.contains($0.name) }.map { - ComponentGroupDeclaration(name: $0.name, condition: $0.condition) - } - operations = try plan(stage) - if !operations.isEmpty { return operations } - - // Remove obsolete edges before adding final edges; their union can contain a cycle even - // when both declarations are acyclic. Definitions remain available throughout this phase. - for index in stage.groups.indices { - let desired = next.groups.first { $0.name == stage.groups[index].name } - stage.groups[index].uses.removeAll { use in - use.source == nil - && !(desired?.uses.contains { $0.source == nil && $0.name == use.name } ?? false) - } - } - operations = try plan(stage) - if !operations.isEmpty { return operations } - - let desiredGroups = Set(next.groups.map(\.name)) - let obsoleteGroups = stage.groups.filter { !desiredGroups.contains($0.name) } - stage.groups = next.groups + obsoleteGroups - operations = try plan(stage) - if !operations.isEmpty { return operations } - - var referenced = next - referenced.sourceDeclarations = stage.sourceDeclarations - referenced.groups = stage.groups - operations = try plan(referenced) - if !operations.isEmpty { return operations } - - referenced.groups = next.groups - operations = try plan(referenced) - if !operations.isEmpty { return operations } - return try plan(next) - } - - private func plan(_ target: Declaration) throws -> [DocumentOperation] { var operations: [DocumentOperation] = [] - var desired = try DeclarationConstruction.root(target).constructionValue + var desired = try DeclarationConstruction.root(next).constructionValue if case .node(let type, let member, var fields) = desired { let originals = document.evaluation.root.value.fields["sources"]!.array! fields["sources"] = .array( - try target.sourceDeclarations.map { entry in - if let index = current.sourceDeclarations.firstIndex(where: { $0.name == entry.name }), + try next.sourceDeclarations.map { entry in + let matches = current.sourceDeclarations.indices.filter { + current.sourceDeclarations[$0].name == entry.name + } + if matches.count > 1 { + let spans = matches.compactMap { + document.sourceMap.locations(at: "/sources/\($0)").first?.span + } + throw ManifestFailure( + ManifestDiagnostic( + code: "manifest.ambiguous", message: "multiple matching source declarations", + span: spans.first ?? document.source.span(0..<0), related: Array(spans.dropFirst())) + ) + } + if let index = matches.first, ManifestProjection.equivalent( current.sourceDeclarations[index].source, entry.source, environment: environment) { diff --git a/Sources/AgentsManifest/DeclarationEditPlan.swift b/Sources/AgentsManifest/DeclarationEditPlan.swift index 5aa35fc..d825586 100644 --- a/Sources/AgentsManifest/DeclarationEditPlan.swift +++ b/Sources/AgentsManifest/DeclarationEditPlan.swift @@ -49,26 +49,51 @@ package enum DeclarationEditPlan { span: document.source.span(0..<0)) } if equivalent(previous, next) { return nil } - // Definition/reference phases can expose more operations after a batch. Detect stalled - // or cyclic plans by snapshot instead of requiring the operation count to decrease. - var snapshots: Set = [document.digest] + let target = try DeclarationConstruction.root(next).constructionValue + let targetCost = try DocumentEditor(document: document).valueCost(target) + // Direct differences finalize fields, insert/delete occurrences, or move them toward + // retained subsequence anchors. Each original/target node needs at most a field edit and + // an occurrence edit. Replanning must also strictly reduce the remaining operation count. + var operationBudget = 2 * (document.evaluation.root.cost.nodes + targetCost.nodes) + var remaining = Int.max while true { var planner = Planner( document: document, current: current, next: next, environment: environment) let operations = adjust(try planner.plan()) if operations.isEmpty { break } - let change = try document.preparing( - operations: Array(operations.prefix(ManifestLimits.Editing.requests))) - guard change.bytes != document.bytes, snapshots.insert(change.digest).inserted else { + guard operations.count < remaining else { throw failure( "manifest.edit.mismatch", "an edit batch made no progress", span: document.source.span(0..<0)) } - document = try DeclarationDocument(bytes: change.bytes, identity: identity) - current = try ManifestProjection.declaration(of: document, environment: environment) + // Each operation re-evaluates the snapshot, scans syntax for local style and checks + // expected values. Size the prefix from that snapshot work, leaving room for growth + // and the final IR comparison. Actual charges still enforce the batch budget; failures + // are never retried with a fresh counter. + let snapshotWork = + document.metrics.evaluationSteps + document.metrics.syntaxNodes + + document.admission.nodes.count + 4 * document.evaluation.root.cost.nodes + let workRequests = max(1, ManifestLimits.Editing.steps / (2 * snapshotWork)) + let batch = Array(operations.prefix(min(ManifestLimits.Editing.requests, workRequests))) + guard batch.count <= operationBudget else { + throw failure( + "manifest.limit", "declaration composition operation budget", + span: document.source.span(0..<0)) + } + operationBudget -= batch.count + let draft = try DocumentEditor(document: document).prepareDraft(operations: batch) + guard draft.document.bytes != document.bytes else { + throw failure( + "manifest.edit.mismatch", "an edit batch made no progress", + span: document.source.span(0..<0)) + } + remaining = operations.count + document = draft.document + current = try ManifestProjection.draftDeclaration(of: document, environment: environment) } - try verify(document, next, environment: environment) - return document.bytes + let validated = try DeclarationDocument(bytes: document.bytes, identity: identity) + try verify(validated, next, environment: environment) + return validated.bytes } private static func verify( @@ -87,10 +112,9 @@ package enum DeclarationEditPlan { } } -/// Plans one batch over one snapshot. Sources are added before references to them and removed -/// after every reference. Each collection receives insertions before removals, so a retained -/// element stays the insertion anchor. Selections grow before overrides arrive and shrink after -/// overrides leave, so every prefix of a split plan keeps overrides inside the selection. +/// Plans skill/instruction edits or delegates complete occurrence changes over one snapshot. +/// Collections receive insertions before removals, so retained elements stay insertion anchors. +/// Internal drafts defer domain validation until the complete edit is ready. private struct Planner { let document: DeclarationDocument let current: Declaration @@ -211,18 +235,23 @@ private struct Planner { } func flat(_ value: Declaration) -> Bool { + let sources = value.sourceDeclarations.map(\.name) + guard Set(sources).count == sources.count else { return false } var aliases = Set() var instructions = false for component in value.components { switch component { case .skills(let source, let selection): + let overrides = selection.overrideDeclarations.map(\.name) if !aliases.insert(source).inserted || selection.condition != nil - || !selection.native.isEmpty + || !selection.native.isEmpty || Set(overrides).count != overrides.count { return false } case .instructions(let selection): + let prompts = selection.prompts.map(\.name) if instructions || selection.condition != nil || !selection.native.isEmpty + || Set(prompts).count != prompts.count || selection.sectionReferences.contains(where: { $0.condition != nil }) || selection.prompts.contains(where: { $0.prompt.condition != nil diff --git a/Sources/AgentsManifest/DocumentEditor.swift b/Sources/AgentsManifest/DocumentEditor.swift index 5ba09ea..097e8e3 100644 --- a/Sources/AgentsManifest/DocumentEditor.swift +++ b/Sources/AgentsManifest/DocumentEditor.swift @@ -78,6 +78,32 @@ final class DocumentEditor { } func prepare(operations: [DocumentOperation]) throws -> DocumentChange { + let draft = try prepareDraft(operations: operations) + // Public prepared changes always have valid final domain semantics, including no-ops + // prepared from a module-internal draft snapshot. + let candidate = try DeclarationDocument( + bytes: draft.document.bytes, identity: original.source.identity) + if candidate.bytes == original.bytes { + return DocumentChange( + originalDigest: original.digest, patches: [], bytes: candidate.bytes, + digest: candidate.digest, expectedDeclaration: candidate.declaration, + impactedReferences: [], diagnostics: candidate.diagnostics, + delta: SemanticDelta(changedPointers: [])) + } + return DocumentChange( + originalDigest: original.digest, patches: table.patches(), bytes: candidate.bytes, + digest: candidate.digest, expectedDeclaration: candidate.declaration, + impactedReferences: Array(Set(impacted)).sorted { $0.syntax < $1.syntax }, + diagnostics: candidate.diagnostics, delta: try semanticDelta()) + } + + /// A checked static snapshot for composing a complete declaration edit. It is not a + /// publishable change; only the composition owner may validate and return its final bytes. + struct DraftBatch { + let document: DeclarationDocument + } + + func prepareDraft(operations: [DocumentOperation]) throws -> DraftBatch { if operations.count > ManifestLimits.Editing.requests { throw fail("manifest.limit", "edit batch has more than 100 requests") } @@ -93,16 +119,8 @@ final class DocumentEditor { let expectedCost = try valueCost(expected) try charge(expectedCost.nodes) let bytes = table.bytes - if bytes == original.bytes { - guard Lowering.declaration(expected) == original.declaration else { - throw fail("manifest.edit.mismatch", "no-op bytes disagree with expected declaration") - } - return DocumentChange( - originalDigest: original.digest, patches: [], bytes: bytes, digest: original.digest, - expectedDeclaration: original.declaration, impactedReferences: [], - diagnostics: original.diagnostics, delta: SemanticDelta(changedPointers: [])) - } - let candidate = try DeclarationDocument(bytes: bytes, identity: original.source.identity) + let candidate = try DeclarationDocument( + bytes: bytes, identity: original.source.identity, validateDomain: false) let actualCost = candidate.evaluation.root.cost if expectedCost.nodes + actualCost.nodes > ManifestLimits.Editing.comparisonPairs { throw fail("manifest.limit", "comparison node-pair budget") @@ -113,12 +131,7 @@ final class DocumentEditor { throw fail( "manifest.edit.mismatch", "complete candidate differs from the expected declaration") } - return DocumentChange( - originalDigest: original.digest, patches: table.patches(), bytes: bytes, - digest: candidate.digest, expectedDeclaration: expectedIR, - impactedReferences: Array(Set(impacted)).sorted { $0.syntax < $1.syntax }, - diagnostics: candidate.diagnostics, - delta: try semanticDelta()) + return DraftBatch(document: candidate) } func semanticDelta() throws -> SemanticDelta { diff --git a/Sources/AgentsManifest/DocumentEdits.swift b/Sources/AgentsManifest/DocumentEdits.swift index 02aad62..eb30e8d 100644 --- a/Sources/AgentsManifest/DocumentEdits.swift +++ b/Sources/AgentsManifest/DocumentEdits.swift @@ -248,7 +248,13 @@ extension DocumentEditor { throw fail("manifest.edit.readOnly", "collection has no source map") } let name = value.fields[key]?.text - if let index = old.elementsForUse.firstIndex(where: { $0.value.fields[key]?.text == name }) { + let matches = old.elementsForUse.indices.filter { + old.elementsForUse[$0].value.fields[key]?.text == name + } + guard matches.count <= 1 else { + throw fail("manifest.ambiguous", "multiple matching declarations") + } + if let index = matches.first { try replace(collection + "/\(index)", with: value) } else { try insert(value, into: collection, at: .last) @@ -259,7 +265,13 @@ extension DocumentEditor { guard let old = current.values[collection] else { throw fail("manifest.edit.readOnly", "collection has no source map") } - if let index = old.elementsForUse.firstIndex(where: { $0.value.fields[key]?.text == name }) { + let matches = old.elementsForUse.indices.filter { + old.elementsForUse[$0].value.fields[key]?.text == name + } + guard matches.count <= 1 else { + throw fail("manifest.ambiguous", "multiple matching declarations") + } + if let index = matches.first { try remove(collection + "/\(index)") } } diff --git a/Sources/AgentsManifest/ManifestProjection.swift b/Sources/AgentsManifest/ManifestProjection.swift index 2b95c37..6e3e365 100644 --- a/Sources/AgentsManifest/ManifestProjection.swift +++ b/Sources/AgentsManifest/ManifestProjection.swift @@ -5,6 +5,15 @@ import AgentsCore package enum ManifestProjection { package static func declaration(of document: DeclarationDocument, environment: RuntimeEnvironment) throws -> Declaration + { + let result = try draftDeclaration(of: document, environment: environment) + try result.validate(environment: environment) + return result + } + + /// Converts statically typed values without domain validation for private edit composition. + static func draftDeclaration(of document: DeclarationDocument, environment: RuntimeEnvironment) + throws -> Declaration { let projection = Projection(document: document) let ir = document.declaration @@ -34,7 +43,6 @@ package enum ManifestProjection { condition: projection.condition(record["condition"])) }, uses: ir.uses.map(projection.use), exports: ir.exports, watch: ir.watch.isEmpty ? nil : ir.watch) - try result.validate(environment: environment) return result } @@ -86,8 +94,15 @@ package enum ManifestProjection { case (.names(let left), .names(let right)): selections = Set(left) == Set(right) default: selections = false } - let left = lhs.overrides ?? [:] - let right = rhs.overrides ?? [:] + let leftNames = lhs.overrideDeclarations.map(\.name) + let rightNames = rhs.overrideDeclarations.map(\.name) + guard Set(leftNames).count == leftNames.count, Set(rightNames).count == rightNames.count else { + return false + } + let left = Dictionary( + uniqueKeysWithValues: lhs.overrideDeclarations.map { ($0.name, $0.override) }) + let right = Dictionary( + uniqueKeysWithValues: rhs.overrideDeclarations.map { ($0.name, $0.override) }) return selections && Set(lhs.exclude ?? []) == Set(rhs.exclude ?? []) && lhs.mode == rhs.mode && sameRecipients(lhs.agents, rhs.agents) && left.keys == right.keys && left.allSatisfy { equivalent($1, right[$0]!) } @@ -108,7 +123,7 @@ package enum ManifestProjection { } } -/// The front end has already checked the vocabulary and field types before projection. +/// Static evaluation checks vocabulary and field types before conversion, including in drafts. private struct Projection { let document: DeclarationDocument @@ -175,7 +190,7 @@ private struct Projection { case "object": return .object(dictionary(r["value"]).mapValues(nativeValue)) default: break } - preconditionFailure("validated configuration value") + preconditionFailure("statically typed configuration value") } func native(_ value: DeclarationValue?) -> AgentsCore.NativeConfiguration { dictionary(value).mapValues { dictionary($0).mapValues(nativeValue) } diff --git a/Tests/AgentsCoreTests/DeclarationStateTests.swift b/Tests/AgentsCoreTests/DeclarationStateTests.swift index 6d22220..7e31629 100644 --- a/Tests/AgentsCoreTests/DeclarationStateTests.swift +++ b/Tests/AgentsCoreTests/DeclarationStateTests.swift @@ -7,6 +7,33 @@ import Testing @Suite("Declaration state") struct DeclarationStateTests { + @Test func failedFinalValidationAfterDraftBatchesPreservesStateAndTargets() throws { + let fixture = try ScopeFixture() + let store = fixture.store + let declaration = Declaration( + sources: ["s": SourceDeclaration(kind: .local, location: "missing")], + components: (0..<101).map { + .subagent( + name: "a\($0)", description: "d", + prompt: .file(ResourceDeclaration(path: "x.md", source: "s"))) + }) + try store.save(declaration: declaration, resolved: ResolvedState()) + try Data("installed content".utf8).write( + to: fixture.root.appendingPathComponent("installed-target")) + let previous = try store.loadDeclaration() + var next = previous + next.sourceDeclarations = [] + next.components = Array(previous.components.suffix(1)) + let baseline = try StatePrecondition(store: store) + let before = try FileHash.folderHash(fixture.root) + #expect(throws: ManifestFailure.self) { + try store.planDeclaration(next, replacing: previous, prepared: baseline) + } + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(try store.loadDeclaration() == previous) + #expect(try store.loadResolved() == ResolvedState()) + } + @Test(arguments: ["lock", "watch"]) func stateWithoutADeclarationStopsEveryAccessWithoutWriting(_ kind: String) throws { let fixture = try ScopeFixture() diff --git a/Tests/AgentsManifestTests/FullDeclarationDependencyTests.swift b/Tests/AgentsManifestTests/FullDeclarationDependencyTests.swift index a525b0a..3f79818 100644 --- a/Tests/AgentsManifestTests/FullDeclarationDependencyTests.swift +++ b/Tests/AgentsManifestTests/FullDeclarationDependencyTests.swift @@ -28,7 +28,7 @@ extension FullDeclarationTests { #expect(try planned(result, next, in: String(decoding: bytes, as: UTF8.self)) == nil) } - @Test func reversingGroupDependenciesAcrossBatchesKeepsAcyclicIntermediateDeclarations() throws { + @Test func reversingGroupDependenciesAcrossBatchesProducesTheCompleteDeclaration() throws { var previous = Declaration( sourceDeclarations: [], groups: (0..<102).map { index in diff --git a/Tests/AgentsManifestTests/FullDeclarationDraftTests.swift b/Tests/AgentsManifestTests/FullDeclarationDraftTests.swift new file mode 100644 index 0000000..7e78367 --- /dev/null +++ b/Tests/AgentsManifestTests/FullDeclarationDraftTests.swift @@ -0,0 +1,156 @@ +import AgentsCore +import AgentsDescription +import Foundation +import Testing + +@testable import AgentsManifest + +extension FullDeclarationTests { + @Test(arguments: [false, true]) + func flatSourceTransitionsComposeWithoutOtherComponents(_ rename: Bool) throws { + let body = """ + let agents = Agents(sources: [.source(name: "s", path: "missing")], components: [ + .skills(source: "s", mode: .edit), + ]) + """ + let target = + rename + ? body.replacingOccurrences(of: #""s""#, with: #""t""#) + : body.replacingOccurrences( + of: #"path: "missing""#, with: #"url: "https://example.invalid/repo.git""# + ).replacingOccurrences(of: "mode: .edit", with: "mode: .copy") + let previous = try projected(body) + let next = try projected(target) + let bytes = try #require(try planned(previous, next, in: manifestHeader + body)) + let result = try ManifestProjection.declaration( + of: DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")), + environment: projectionEnvironment) + #expect(ManifestProjection.equivalent(result, next, environment: projectionEnvironment)) + #expect(try planned(result, next, in: String(decoding: bytes, as: UTF8.self)) == nil) + } + + @Test func aliasRenameComposesRootAndUnusedGroupResourceReferencesAcrossBatches() throws { + let components = (0..<101).map { + #" .subagent(name: "a\#($0)", description: "d", prompt: .file("x.md", source: "s"))"# + }.joined(separator: ",\n") + let body = """ + // Keep this header. + let agents = Agents( + sources: [.source(name: "s", path: "missing")], + components: [ + .instructions(sections: [.section(name: "guide", source: "s")]), + .plugin(name: "bundle", path: "plugins/bundle", source: "s"), + .hook(name: "run", event: .sessionStart, + run: .executable("tool", workingDirectory: .path("dir", source: "s"))), + ], + groups: [ + .group( + name: "unused", + components: [ + \(components) + ], + uses: [.group(name: "remote", source: "s")] + ), + ] + ) + // Keep this tail. + """ + let next = try projected(body.replacingOccurrences(of: #""s""#, with: #""t""#)) + let bytes = try #require(try planned(try projected(body), next, in: manifestHeader + body)) + let output = String(decoding: bytes, as: UTF8.self) + #expect(output.hasPrefix(manifestHeader + "// Keep this header.\n")) + #expect(output.hasSuffix("// Keep this tail.")) + let result = try ManifestProjection.declaration( + of: DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")), + environment: projectionEnvironment) + #expect(result == next) + } + + @Test func draftBatchesRejectExpectedIRMismatchAndRetainTheirLimits() throws { + let doc = try document("let agents = Agents()") + for operations: [DocumentOperation] in [ + [], [.edit(.insertComponent(.instructions(), into: .root, at: .last))], + ] { + let editor = DocumentEditor(document: doc) + editor.expected = Agents(defaultAgents: [.codex]).constructionValue + expectManifestFailure("manifest.edit.mismatch") { + try editor.prepareDraft(operations: operations) + } + } + expectManifestFailure("manifest.limit") { + try DocumentEditor(document: doc).prepareDraft( + operations: Array(repeating: .edit(.setWatch([])), count: 101)) + } + let exhausted = DocumentEditor(document: doc) + exhausted.steps = ManifestLimits.Editing.steps + expectManifestFailure("manifest.limit") { try exhausted.prepareDraft(operations: []) } + } + + @Test func publicPreparedChangesValidateDraftDomainEvenForNoOps() throws { + let doc = try document( + "let agents = Agents(sources: [.source(name: \"s\", path: \"missing\")], components: [.skills(source: \"s\", mode: .edit)])" + ) + let draft = try DocumentEditor(document: doc).prepareDraft(operations: [ + .edit(.upsertSource(.source(name: "s", url: "https://example.invalid/repo.git"))) + ]) + expectManifestFailure("manifest.domain") { + try DeclarationDocument(bytes: draft.document.bytes, identity: DocumentIdentity("manifest")) + } + expectManifestFailure("manifest.domain") { try draft.document.preparing([]) } + expectManifestFailure("manifest.domain") { try draft.document.preparing(operations: []) } + #expect(throws: CoreError.self) { + try ManifestProjection.declaration(of: draft.document, environment: projectionEnvironment) + } + } + + @Test func compositionRejectsNoProgressAndExcessOperationWork() throws { + let doc = try document("let agents = Agents()") + let next = Declaration(agents: [.codex]) + expectManifestFailure("manifest.edit.mismatch") { + try DeclarationEditPlan.bytes( + replacing: Declaration(), with: next, in: doc.bytes, + identity: DocumentIdentity("manifest"), environment: projectionEnvironment, + planning: { _ in [.edit(.setWatch([]))] }) + } + expectManifestFailure("manifest.limit") { + try DeclarationEditPlan.bytes( + replacing: Declaration(), with: next, in: doc.bytes, + identity: DocumentIdentity("manifest"), environment: projectionEnvironment, + planning: { _ in Array(repeating: .edit(.setDefaultAgents([.codex])), count: 100) }) + } + } + + @Test func draftReplanningDiagnosesDuplicateSourceAliases() throws { + let doc = try document("let agents = Agents()") + let root = try #require(doc.node(at: "")) + let next = Declaration(sources: ["s": SourceDeclaration(kind: .local, location: "s")]) + var injected = false + expectManifestFailure("manifest.ambiguous") { + try DeclarationEditPlan.bytes( + replacing: Declaration(), with: next, in: doc.bytes, + identity: DocumentIdentity("manifest"), environment: projectionEnvironment, + planning: { operations in + if injected { return operations } + injected = true + return [ + .setArgument( + root, field: "sources", + value: .array([ + Source.source(name: "s", path: "s").constructionValue, + Source.source(name: "s", path: "t").constructionValue, + ])) + ] + }) + } + } + + @Test func composedFinalProjectionPerformsEnvironmentValidation() throws { + let doc = try document( + "let agents = Agents(sources: [.source(name: \"a\", path: \"~/rules\"), .source(name: \"b\", path: \"/work/home/rules\")])" + ) + let next = try ManifestProjection.draftDeclaration(of: doc, environment: projectionEnvironment) + #expect(throws: CoreError.self) { + try planned(Declaration(), next, in: manifestHeader + "let agents = Agents()") + } + } +} diff --git a/Tests/AgentsManifestTests/FullDeclarationTests.swift b/Tests/AgentsManifestTests/FullDeclarationTests.swift index 0a55e7e..ecd6356 100644 --- a/Tests/AgentsManifestTests/FullDeclarationTests.swift +++ b/Tests/AgentsManifestTests/FullDeclarationTests.swift @@ -7,6 +7,102 @@ import Testing @Suite("Complete symbolic declarations") struct FullDeclarationTests { + @Test(arguments: [0, 101]) + func renamingSourceAtSameIdentityRetargetsAllReferences(_ referenceCount: Int) throws { + let references = (0.. Date: Sat, 7 Nov 2026 00:43:50 +0800 Subject: [PATCH 036/171] fix: keep declaration planning stable across batches --- .../AgentsManifest/DeclarationEditPlan.swift | 23 +++++- .../DeclarationProgressTests.swift | 80 +++++++++++++++++++ 2 files changed, 99 insertions(+), 4 deletions(-) create mode 100644 Tests/AgentsManifestTests/DeclarationProgressTests.swift diff --git a/Sources/AgentsManifest/DeclarationEditPlan.swift b/Sources/AgentsManifest/DeclarationEditPlan.swift index d825586..b9303ee 100644 --- a/Sources/AgentsManifest/DeclarationEditPlan.swift +++ b/Sources/AgentsManifest/DeclarationEditPlan.swift @@ -56,10 +56,15 @@ package enum DeclarationEditPlan { // an occurrence edit. Replanning must also strictly reduce the remaining operation count. var operationBudget = 2 * (document.evaluation.root.cost.nodes + targetCost.nodes) var remaining = Int.max + // Keep operation counts comparable across drafts: a source move can make a complete + // edit eligible for the flat path, whose insertion/deletion counts use different units. + let complete = Planner( + document: document, current: current, next: next, environment: environment + ).requiresCompletePlanning while true { var planner = Planner( document: document, current: current, next: next, environment: environment) - let operations = adjust(try planner.plan()) + let operations = adjust(try planner.plan(complete: complete)) if operations.isEmpty { break } guard operations.count < remaining else { throw failure( @@ -122,14 +127,24 @@ private struct Planner { let environment: RuntimeEnvironment var operations: [DocumentOperation] = [] - mutating func plan() throws -> [DocumentOperation] { - if !flat(current) || !flat(next) || !flatOrder() || current.groups != next.groups + var requiresCompletePlanning: Bool { + !flat(current) || !flat(next) || !flatOrder() || current.groups != next.groups || current.uses != next.uses || current.exports != next.exports - { + } + + mutating func plan(complete: Bool) throws -> [DocumentOperation] { + if complete { return try CompleteDeclarationPlanner( document: document, current: current, next: next, environment: environment ).plan() } + // Flat operations preserve this shape and uniqueness even while domain constraints are + // deferred. Reject a malformed draft rather than switching strategy or using lossy views. + guard flat(current) else { + throw DeclarationEditPlan.failure( + "manifest.ambiguous", "draft is no longer an unambiguous flat declaration", + span: document.source.span(0..<0)) + } var skillComponents: [String: Int] = [:] var instructionsComponent: Int? for (index, component) in document.declaration.components.enumerated() { diff --git a/Tests/AgentsManifestTests/DeclarationProgressTests.swift b/Tests/AgentsManifestTests/DeclarationProgressTests.swift new file mode 100644 index 0000000..36091f4 --- /dev/null +++ b/Tests/AgentsManifestTests/DeclarationProgressTests.swift @@ -0,0 +1,80 @@ +import AgentsCore +import AgentsDescription +import Foundation +import Testing + +@testable import AgentsManifest + +@Suite("Declaration edit progress") +struct DeclarationProgressTests { + @Test func flatSkillReplacementsKeepTheirInsertionAndRemovalProgressAcrossBatches() throws { + let old = (0..<100).map { "old\($0)" } + let replacement = (0..<100).map { "new\($0)" }.sorted(by: utf8Less) + let keep = (0..<2000).map { "keep\($0)" } + func literals(_ names: [String]) -> String { + names.map { "\"\($0)\"" }.joined(separator: ", ") + } + let body = """ + let agents = Agents( + sources: [.source(name: "a", path: "a"), .source(name: "b", path: "b")], + components: [ + .skills(source: "a", select: [\(literals(old))]), + .skills(source: "b", select: [\(literals(keep))]), + ] + ) + """ + let previous = try projected(body) + var next = previous + try next.updateSkills { $0?["a"]?.select = .names(replacement) } + let bytes = try #require(try planned(previous, next, in: manifestHeader + body)) + let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) + #expect( + document.declaration + == Lowering.declaration(try DeclarationConstruction.root(next).constructionValue)) + let result = try ManifestProjection.declaration( + of: document, environment: projectionEnvironment) + #expect(try result.skills?["b"]?.select == .names(keep)) + #expect(try planned(result, next, in: String(decoding: bytes, as: UTF8.self)) == nil) + } + + @Test func sourceReorderingAndSkillReplacementProgressAcrossBatches() throws { + let old = (0..<100).map { "old\($0)" } + let replacement = (0..<100).map { "new\($0)" } + let keep = (0..<2000).map { "keep\($0)" } + func literals(_ names: [String]) -> String { + names.map { "\"\($0)\"" }.joined(separator: ", ") + } + let body = """ + let agents = Agents( + sources: [ + .source(name: "b", path: "b"), + .source(name: "a", path: "a"), + ], + components: [ + .skills(source: "a", select: [\(literals(old))]), + .skills(source: "b", select: [\(literals(keep))]), + ] + ) + """ + let previous = try projected(body) + var next = previous + next.sourceDeclarations.reverse() + try next.updateSkills { $0?["a"]?.select = .names(replacement) } + try previous.validate(environment: projectionEnvironment) + try next.validate(environment: projectionEnvironment) + #expect(previous.sourceDeclarations.map(\.name) == ["b", "a"]) + #expect(next.sourceDeclarations.map(\.name) == ["a", "b"]) + #expect(try previous.skills?["a"]?.select == .names(old)) + #expect(try next.skills?["a"]?.select == .names(replacement)) + #expect(try next.skills?["b"]?.select == .names(keep)) + + let bytes = try #require(try planned(previous, next, in: manifestHeader + body)) + let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) + #expect( + document.declaration + == Lowering.declaration(try DeclarationConstruction.root(next).constructionValue)) + let result = try ManifestProjection.declaration( + of: document, environment: projectionEnvironment) + #expect(try planned(result, next, in: String(decoding: bytes, as: UTF8.self)) == nil) + } +} From bff048b8cc686f3eb30dfe543f9e7539982102f2 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 7 Nov 2026 03:43:52 +0800 Subject: [PATCH 037/171] feat: link component sources and exported groups --- Documentation/Architecture/Package.md | 52 ++ Documentation/Architecture/README.md | 3 +- Package.swift | 8 + Sources/AgentsCore/ComponentConditions.swift | 43 ++ Sources/AgentsCore/SourceCache.swift | 45 ++ Sources/AgentsCore/SourceCatalog.swift | 66 ++ Sources/AgentsCore/SourceReference.swift | 21 +- Sources/AgentsCore/SourceRequirement.swift | 2 +- .../AgentsCore/SourceResolutionSession.swift | 270 +++++++- Sources/AgentsCore/SourceSnapshot.swift | 84 +++ .../InstructionFrontMatter.swift | 41 +- .../InstructionModels.swift | 2 + .../InstructionSnapshotReader.swift | 42 ++ .../InstructionSources.swift | 2 +- Sources/AgentsInstructions/Instructions.swift | 12 +- .../ManifestExpansionBudget.swift | 78 +++ Sources/AgentsManifest/MapBuilder.swift | 17 +- Sources/AgentsManifest/ValueBudget.swift | 37 +- Sources/AgentsSkills/Discovery.swift | 37 +- .../AgentsSkills/SkillSnapshotReader.swift | 71 +++ Sources/Components/ComponentFields.swift | 112 ++++ Sources/Components/ComponentLinker.swift | 297 +++++++++ Sources/Components/Expansion.swift | 580 ++++++++++++++++++ Sources/Components/LinkBudget.swift | 39 ++ Sources/Components/LinkedComponents.swift | 179 ++++++ .../ExpansionBudgetTests.swift | 113 ++++ Tests/ComponentsTests/ImpactTests.swift | 135 ++++ Tests/ComponentsTests/LinkBudgetTests.swift | 153 +++++ Tests/ComponentsTests/LinkFixture.swift | 97 +++ .../LinkingAcceptanceTests.swift | 361 +++++++++++ Tests/ComponentsTests/LinkingTests.swift | 224 +++++++ Tests/ComponentsTests/SnapshotTests.swift | 309 ++++++++++ Tests/ComponentsTests/UserScopeTests.swift | 148 +++++ 33 files changed, 3624 insertions(+), 56 deletions(-) create mode 100644 Sources/AgentsCore/ComponentConditions.swift create mode 100644 Sources/AgentsCore/SourceCatalog.swift create mode 100644 Sources/AgentsCore/SourceSnapshot.swift create mode 100644 Sources/AgentsInstructions/InstructionSnapshotReader.swift create mode 100644 Sources/AgentsManifest/ManifestExpansionBudget.swift create mode 100644 Sources/AgentsSkills/SkillSnapshotReader.swift create mode 100644 Sources/Components/ComponentFields.swift create mode 100644 Sources/Components/ComponentLinker.swift create mode 100644 Sources/Components/Expansion.swift create mode 100644 Sources/Components/LinkBudget.swift create mode 100644 Sources/Components/LinkedComponents.swift create mode 100644 Tests/AgentsManifestTests/ExpansionBudgetTests.swift create mode 100644 Tests/ComponentsTests/ImpactTests.swift create mode 100644 Tests/ComponentsTests/LinkBudgetTests.swift create mode 100644 Tests/ComponentsTests/LinkFixture.swift create mode 100644 Tests/ComponentsTests/LinkingAcceptanceTests.swift create mode 100644 Tests/ComponentsTests/LinkingTests.swift create mode 100644 Tests/ComponentsTests/SnapshotTests.swift create mode 100644 Tests/ComponentsTests/UserScopeTests.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 44efcc4..fdb22e5 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -15,6 +15,7 @@ with glibc 2.34 or newer. AgentsDescription (standard library only) AgentsManifest ──> AgentsDescription, AgentsCore, SwiftSyntax, SwiftParser (swift-syntax) +Components ──> AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions AgentsUpdates ──> AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, CPlatform AgentsCore ──> CPlatform, Crypto (swift-crypto) @@ -37,6 +38,7 @@ AgentsCoreTests ──> AgentsCore, AgentsManifest, StateTestProcess, StateTestS AgentsSkillsTests ──> AgentsSkills, AgentsCore, AgentsManifest, AgentsInstructions, Yams, StateTestProcess, StateTestSupport, CPlatform AgentsInstructionsTests ──> AgentsInstructions, AgentsManifest AgentsUpdatesTests ──> AgentsUpdates, AgentsManifest, StateTestProcess, StateTestSupport, CPlatform +ComponentsTests ──> Components, AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions ``` `AgentsDescription`, `AgentsManifest`, `AgentsCore`, `AgentsSkills`, @@ -92,6 +94,11 @@ domain validation produce `AgentsCore.DeclarationIR` and `DeclarationSourceMap`. Constants, inactive values and unused groups receive the same checks. Group references and conditions remain symbolic. +The package-only `ManifestExpansionBudget` applies the same value, source-map +and output accounting to declarations repeated by source/group linking. +`Components` supplies each original IR record and its reference origins and +charges traversal work to the linker's retained work budget. + `DeclarationDocument` is the public consumer surface: | Operation | Consumer API | @@ -372,6 +379,51 @@ The probe is never emitted. Malformed managed markers still produce errors. declaration and lock updates, and deletion decisions using the lock's `created` flag. The `Instructions` and `ClaudeForwarding` text APIs perform no I/O. +## Components + +`Components` is an internal target. Its package-only `ComponentLinker` reads a +complete symbolic declaration and explicitly exported producer groups into an +ordered, exact source graph. Root components precede uses; groups follow the +same depth-first order. Producer defaults and frontmatter restrictions determine +recipients together with nested reference and component conditions. Instructions +retain repeated occurrences; identical named hooks and policies coalesce while +retaining their origins. Logical conflicts are checked before artifact lowering. + +Core owns frozen Git candidate evidence, exact snapshots, source containment and +the scoped temporary-read session. Export constraints share one version variable +per normalized source; discovery roots remain distinct namespaces. Direct skill +and section pins are independent. The session reuses existing exact cached +objects only under existing locks; other mirrors, refs, locks and content remain +temporary. The caller consumes borrowed resources within the linking closure; +cleanup runs on success, error and cooperative cancellation. The synchronous Git +runner completes owned in-flight work before cancellation returns. + +An exact view retains the original actual-local source environment independently +of its borrowed content and live-edit eligibility. Local producer aliases resolve +from that source's actual discovery root and home, even with a Git requirement. +Remote-contained local declarations inherit their immutable parent snapshot and +remain subject to lexical and real symlink containment. + +`SkillSnapshotReader` and `InstructionSnapshotReader` consume already selected +views without independently resolving or retaining sources. Actual local edit +skills preserve their live paths. Remote-contained local sources inherit the +producer snapshot. Existing skill-index formats supply skill artifacts, and do +not define an export-package format. + +The linked result records relative resource evidence, source requirements, +reference and contribution occurrences, provenance and exact dependency pins. +Its protected projection compares other domains' payloads, resource hashes, +recipients and pins; source sharing alone does not imply a changed projection. +Producer-owned children report `notEditableHere` with producer and reference +coordinates. These package seams do not publish state or lower native artifacts. +The existing public lifecycle operations still enforce their deployment subset. + +Root package resources use the project directory in project scope and the +user-state directory in user scope. Explicit sources retain their declaring +environment. Root user instructions require named sources, while imported +producer groups retain their own sections. User prompt append content is +read relative to the runtime home. + ## AgentsUpdates `UpdateOperations.preview` plans all declared skills, instruction targets and diff --git a/Documentation/Architecture/README.md b/Documentation/Architecture/README.md index 2893672..7dd59b6 100644 --- a/Documentation/Architecture/README.md +++ b/Documentation/Architecture/README.md @@ -12,7 +12,8 @@ discovery and lifecycle operations and depends on `AgentsCore`, `AgentsManifest` and Yams. `AgentsInstructions` owns instruction lifecycle and text transformations. It depends on `AgentsCore` for sources and state, `AgentsManifest` for the declaration, and `swift-markdown` for CommonMark -structure. `AgentsUpdates` composes both domains above those modules. Tests +structure. `Components` links exact source exports through package readers above those +modules. `AgentsUpdates` composes the existing skill and instruction lifecycle. Tests follow those module boundaries. ## Belongs Here diff --git a/Package.swift b/Package.swift index eec9b6a..41593e9 100644 --- a/Package.swift +++ b/Package.swift @@ -48,6 +48,14 @@ let package = Package( dependencies: [ "AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions", "CPlatform", ]), + .target( + name: "Components", + dependencies: ["AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions"]), + .testTarget( + name: "ComponentsTests", + dependencies: [ + "Components", "AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions", + ]), .target(name: "StateTestSupport", path: "Tests/StateTestSupport"), .executableTarget( name: "StateTestProcess", diff --git a/Sources/AgentsCore/ComponentConditions.swift b/Sources/AgentsCore/ComponentConditions.swift new file mode 100644 index 0000000..a2f2e88 --- /dev/null +++ b/Sources/AgentsCore/ComponentConditions.swift @@ -0,0 +1,43 @@ +import Foundation + +extension DeclarationCondition { + /// Format readers supply strings; Core owns their meaning. Unknown values are errors. + package static func restrictions(_ fields: [String: [String]]) throws -> Self { + func values(_ key: String, _ parse: (String) -> T?) throws -> [T]? { + guard let names = fields[key] else { return nil } + return try names.map { + guard let value = parse($0) else { + throw CoreError.invalidSource("invalid producer \(key) value: \($0)") + } + return value + } + } + return try Self( + agents: values("agents", AgentID.init(rawValue:)), + scopes: values("scopes", InstallScope.init(rawValue:)), + platforms: values("platforms", DeclarationPlatform.init(rawValue:))) + } + + package func matches(scope: InstallScope, platform: DeclarationPlatform) -> Bool { + (scopes?.contains(scope) ?? true) && (platforms?.contains(platform) ?? true) + } + + package func intersecting(_ other: Self) -> Self { + func intersection(_ lhs: [T]?, _ rhs: [T]?) -> [T]? { + guard let lhs else { return rhs } + guard let rhs else { return lhs } + return lhs.filter { rhs.contains($0) } + } + return Self( + agents: intersection(agents, other.agents), + scopes: intersection(scopes, other.scopes), + platforms: intersection(platforms, other.platforms)) + } + + package func recipients( + requested: [AgentID], scope: InstallScope, platform: DeclarationPlatform + ) -> Set { + guard matches(scope: scope, platform: platform) else { return [] } + return Set(requested.filter { agents?.contains($0) ?? true }) + } +} diff --git a/Sources/AgentsCore/SourceCache.swift b/Sources/AgentsCore/SourceCache.swift index 2495c67..fa1c1d9 100644 --- a/Sources/AgentsCore/SourceCache.swift +++ b/Sources/AgentsCore/SourceCache.swift @@ -54,6 +54,51 @@ package struct SourceCache { return SourceRevision(revision: revision, version: ref.version) } + /// Captures all advertised refs in an owned mirror. The caller uses a disposable cache. + func referenceCatalog( + _ source: SourceDeclaration, spending: (Int) throws -> Void = { _ in } + ) throws -> SourceCatalog { + let mirror = try fetch(source, id: source.identity(environment: store.environment)) + let output = try git( + mirror, ["show-ref", "--head", "--dereference"], operation: .listTags, + source: source.location) + var references: [String: String] = [:] + var tags: [String: String] = [:] + for line in output.split(separator: "\n") { + try spending(1) + let fields = line.split(separator: " ", maxSplits: 1).map(String.init) + guard fields.count == 2 else { continue } + references[fields[1]] = fields[0] + } + for name in references.keys.sorted() + where name.hasPrefix("refs/tags/") && !name.hasSuffix("^{}") { + let commit = references[name + "^{}"] ?? references[name] + references[name] = commit + tags[String(name.dropFirst(10))] = commit + } + return SourceCatalog(tags: tags, references: references) + } + + /// Resolves an expression against the already frozen mirror, without fetching new evidence. + func catalogRevision(_ expression: String, source: SourceDeclaration) throws -> String? { + try source.requirement?.validate() + return try withExistingMirror(sourceID: source.identity(environment: store.environment)) { + mirror, descriptor in + do { + return try git( + mirror, + [ + "--no-optional-locks", "rev-parse", "--quiet", "--verify", "--end-of-options", + expression + "^{commit}", + ], + operation: .resolveRevision(revision: expression), source: source.location, + lock: descriptor) + } catch let error as GitError where error.exitCode == 1 && error.stderr.isEmpty { + return nil + } + } ?? nil + } + /// Subscriptions follow branches even when installations select a tag or version range. func watchRevision(_ source: SourceDeclaration, revision: String? = nil) throws -> String { let id = try source.identity(environment: store.environment) diff --git a/Sources/AgentsCore/SourceCatalog.swift b/Sources/AgentsCore/SourceCatalog.swift new file mode 100644 index 0000000..c6588ed --- /dev/null +++ b/Sources/AgentsCore/SourceCatalog.swift @@ -0,0 +1,66 @@ +import Foundation + +/// Frozen Git reference evidence for a resolution session. Tags at the same version retain +/// the existing lexical tie break; branches and revision expressions must name one commit. +struct SourceCatalog { + var tags: [String: String] + var references: [String: String] + + func candidates( + requirements: [SourceRequirement?], spending: (Int) throws -> Void = { _ in } + ) throws -> [SourceRevision] { + for requirement in requirements { + try spending(1) + try requirement?.validate() + } + let constraints = requirements.compactMap { $0 } + let fixed = constraints.compactMap { requirement -> String? in + switch requirement { + case .branch(let name): return references["refs/heads/" + name] + case .revision(let name): return references[name] + default: return nil + } + } + let fixedCount = constraints.filter { !$0.isVersionRequirement }.count + guard fixed.count == fixedCount, Set(fixed).count <= 1 else { return [] } + let versions = constraints.filter(\.isVersionRequirement) + let ordered = try tags.compactMap { name, commit -> (String, SemanticVersion, String)? in + try spending(1) + return SemanticVersion(name).map { (name, $0, commit) } + }.sorted { + try spending(1) + return $0.1 == $1.1 ? $0.0 > $1.0 : $0.1 > $1.1 + } + if let commit = fixed.first, versions.isEmpty { + return [SourceRevision(revision: commit)] + } + var seen = Set() + let candidates = try ordered.filter { entry in + try spending(versions.count + 1) + return + (fixed.first == nil || fixed.first == entry.2) + && versions.allSatisfy { $0.matches(version: entry.1) } + && seen.insert(entry.2).inserted + }.map { SourceRevision(revision: $0.2, version: $0.1.description) } + if !candidates.isEmpty || !versions.isEmpty || !ordered.isEmpty { return candidates } + return references["HEAD"].map { [SourceRevision(revision: $0)] } ?? [] + } +} + +extension SourceRequirement { + func matches(version: SemanticVersion) -> Bool { + guard let lower = SemanticVersion(value) else { return false } + switch self { + case .exact: return version.description == lower.description + case .upToNextMajor: + return version.isInRange( + from: lower, to: SemanticVersion(major: lower.major + 1, minor: 0, patch: 0)) + case .upToNextMinor: + return version.isInRange( + from: lower, to: SemanticVersion(major: lower.major, minor: lower.minor + 1, patch: 0)) + case .range(_, let upper): + return SemanticVersion(upper).map { version.isInRange(from: lower, to: $0) } ?? false + case .branch, .revision: return false + } + } +} diff --git a/Sources/AgentsCore/SourceReference.swift b/Sources/AgentsCore/SourceReference.swift index 3207dc1..0b9c001 100644 --- a/Sources/AgentsCore/SourceReference.swift +++ b/Sources/AgentsCore/SourceReference.swift @@ -23,26 +23,7 @@ struct SourceReference { return default: break } - guard let lower = SemanticVersion(requirement.value) else { - throw CoreError.invalidSource("invalid semantic version") - } - let candidates: [(String, SemanticVersion)] - if requirement.kind == "exact" { - candidates = tags.filter { $0.1.description == lower.description } - } else { - let upper: SemanticVersion - switch requirement { - case .upToNextMajor: upper = SemanticVersion(major: lower.major + 1, minor: 0, patch: 0) - case .upToNextMinor: - upper = SemanticVersion(major: lower.major, minor: lower.minor + 1, patch: 0) - default: - guard let bound = requirement.upperBound, let parsed = SemanticVersion(bound) else { - throw CoreError.invalidSource("missing version upper bound") - } - upper = parsed - } - candidates = tags.filter { $0.1.isInRange(from: lower, to: upper) } - } + let candidates = tags.filter { requirement.matches(version: $0.1) } guard let selected = candidates.last else { throw CoreError.notFound("no tag matches source requirement") } diff --git a/Sources/AgentsCore/SourceRequirement.swift b/Sources/AgentsCore/SourceRequirement.swift index 9770925..87f86de 100644 --- a/Sources/AgentsCore/SourceRequirement.swift +++ b/Sources/AgentsCore/SourceRequirement.swift @@ -99,7 +99,7 @@ public enum SourceRequirement: Codable, Equatable, Sendable { } } - private var isVersionRequirement: Bool { + var isVersionRequirement: Bool { switch kind { case "exact", "from", "minor", "range": return true diff --git a/Sources/AgentsCore/SourceResolutionSession.swift b/Sources/AgentsCore/SourceResolutionSession.swift index a5ee4b1..82eda74 100644 --- a/Sources/AgentsCore/SourceResolutionSession.swift +++ b/Sources/AgentsCore/SourceResolutionSession.swift @@ -10,22 +10,287 @@ package final class SourceResolutionSession { } private let store: StateStore private let cache: SourceCache + package enum ReadMode { case persistentCache, temporary } + private let mode: ReadMode + private let temporaryCache: SourceCache + private var catalogs: [String: SourceCatalog] = [:] + private var exact: [SourceSnapshotID: SourceSnapshot] = [:] + private var localTrees: [String: SourceSnapshot] = [:] + private var closed = false + private var borrowed: [SourceSnapshotID: SourceSnapshot] = [:] + private var evidence: [SourceSnapshotID: SourceSnapshotEvidence] = [:] private let workspace: URL private var snapshots: [Snapshot] = [] - package init(store: StateStore) throws { + package init(store: StateStore, mode: ReadMode = .persistentCache) throws { + self.mode = mode self.store = store cache = SourceCache(store: store) workspace = FileManager.default.temporaryDirectory.appendingPathComponent( "agents-resolution-" + UUID().uuidString) try FileSystem.createDirectory(at: workspace) + var environment = store.environment + environment.projectDirectory = workspace.appendingPathComponent("sources") + temporaryCache = SourceCache(store: StateStore(scope: .project, environment: environment)) } deinit { try? FileManager.default.removeItem(at: workspace) } + /// All borrowed views must be consumed inside this closure. Cleanup errors are observable. + package static func withTemporaryRead( + store: StateStore, _ body: (SourceResolutionSession) throws -> T + ) throws -> T { + let session = try SourceResolutionSession(store: store, mode: .temporary) + do { + let result = try body(session) + try Task.checkCancellation() + try session.close() + return result + } catch { + try session.close() + throw error + } + } + + package func close() throws { + guard !closed else { return } + try FileManager.default.removeItem(at: workspace) + closed = true + snapshots.removeAll() + exact.removeAll() + localTrees.removeAll() + borrowed.removeAll() + evidence.removeAll() + } + + private func requireOpen() throws { + guard !closed else { throw CoreError.invalidState("source session is closed") } + if mode == .temporary { try Task.checkCancellation() } + } + + /// Candidate evidence is captured once per normalized source, including revision expressions + /// first encountered later during backtracking. No persistent mirror or ref is written. + package func candidates( + for source: SourceDeclaration, requirements: [SourceRequirement?], + spending: (Int) throws -> Void = { _ in } + ) throws -> [SourceRevision] { + try requireOpen() + for requirement in requirements { try requirement?.validate() } + let id = try source.identity(environment: store.environment) + let exactObjects = requirements.compactMap { requirement -> String? in + if case .revision(let object) = requirement, SourceCache.isObjectID(object) { return object } + return nil + } + if exactObjects.count == requirements.compactMap({ $0 }).count, !exactObjects.isEmpty { + return Set(exactObjects).count == 1 ? [SourceRevision(revision: exactObjects[0])] : [] + } + if catalogs[id] == nil { + catalogs[id] = try temporaryCache.referenceCatalog(source, spending: spending) + try Task.checkCancellation() + } + var catalog = catalogs[id]! + for requirement in requirements { + if case .revision(let expression) = requirement, catalog.references[expression] == nil { + catalog.references[expression] = try temporaryCache.catalogRevision( + expression, source: source) + } + } + catalogs[id] = catalog + return try catalog.candidates(requirements: requirements, spending: spending) + } + + package func snapshot(_ source: SourceDeclaration, at pin: SourceRevision) throws + -> SourceSnapshot + { + try requireOpen() + let id = try source.identity(environment: store.environment) + let key = SourceSnapshotID(source: id, revision: pin.revision) + let base: SourceSnapshot + if let existing = exact[key] { + base = existing + } else { + var selected = source + selected.requirement = .revision(pin.revision) + selected.path = nil + func copy(_ tree: URL) throws -> SourceSnapshot { + let root = workspace.appendingPathComponent(UUID().uuidString) + try FileManager.default.copyItem(at: tree, to: root) + return try SourceSnapshot( + snapshot: key, pin: pin, root: root, + localEnvironment: localEnvironment(for: source), + liveRoot: source.kind == .local && source.requirement == nil + ? source.localURL(environment: store.environment) : nil) + } + if catalogs[id] != nil, + try temporaryCache.catalogRevision(pin.revision, source: selected) == pin.revision + { + base = try temporaryCache.withSnapshot( + sourceID: id, + source: LockedSource( + kind: selected.kind, url: selected.kind == .git ? selected.gitURL : nil, + requirement: selected.requirement), revision: pin.revision, copy) + } else { + base = try cache.withResolvedSnapshot(selected, cacheSource: false) { _, tree in + try copy(tree) + } + } + exact[key] = base + register( + base, + source: LockedSource( + kind: source.kind, + url: source.kind == .git ? source.gitURL : nil, requirement: .revision(pin.revision))) + try Task.checkCancellation() + } + return try SourceSnapshot( + snapshot: key, pin: pin, root: base.root, + discoveryPath: source.path ?? ".", + localEnvironment: localEnvironment(for: source), + liveRoot: source.kind == .local && source.requirement == nil + ? source.localURL(environment: store.environment) : nil) + } + + /// Non-Git local producers are copied once, then identified by bytes and executable flags. + package func localSnapshot(_ source: SourceDeclaration) throws -> SourceSnapshot { + try requireOpen() + let id = try source.identity(environment: store.environment) + if let existing = localTrees[id] { + return try SourceSnapshot( + snapshot: existing.snapshot, pin: nil, root: existing.root, + discoveryPath: source.path ?? ".", localEnvironment: localEnvironment(for: source), + liveRoot: existing.liveRoot) + } + guard source.kind == .local, source.requirement == nil else { + throw CoreError.invalidSource("a non-Git source cannot have a Git requirement") + } + let live = source.localURL(environment: store.environment) + let root = workspace.appendingPathComponent(UUID().uuidString) + try FileManager.default.copyItem(at: live, to: root) + try Self.validateLinks(root) + let flags = try FileHash.executableFlags(root) + let content = try FileHash.folderHash(root) + let evidence = FileHash.hashRecords( + [("content", Data(content.utf8))] + + flags.keys.sorted().map { + ("execute\0" + $0, Data([flags[$0]! ? 1 : 0])) + }) + let result = try SourceSnapshot( + snapshot: SourceSnapshotID( + source: id, revision: "sha256:" + evidence), + pin: nil, root: root, discoveryPath: source.path ?? ".", + localEnvironment: localEnvironment(for: source), liveRoot: live) + localTrees[id] = result + register(result) + try Task.checkCancellation() + return result + } + + /// Registers only a borrowed view; closing the session invalidates all resource access. + package func register(_ view: SourceSnapshot, source: LockedSource? = nil) { + borrowed[view.snapshot] = view + if source == nil, evidence[view.snapshot] != nil { return } + let container = + view.packageIdentity == view.snapshot.source + ? nil + : SourceSnapshotID( + source: view.packageIdentity, revision: view.snapshot.revision) + let descriptor = + source + ?? (container == nil + ? LockedSource( + kind: view.snapshot.source.hasPrefix("local:") ? .local : .wellKnown) : nil) + evidence[view.snapshot] = SourceSnapshotEvidence( + snapshot: view.snapshot, pin: view.pin.map { SourceRevision(revision: $0.revision) }, + source: descriptor, container: container) + } + + package func sourceEvidence(for snapshots: Set) -> [SourceSnapshotEvidence] { + var required = snapshots + var pending = Array(snapshots) + while let snapshot = pending.popLast() { + if let container = evidence[snapshot]?.container, required.insert(container).inserted { + pending.append(container) + } + } + return required.compactMap { evidence[$0] }.sorted { + $0.snapshot.source == $1.snapshot.source + ? $0.snapshot.revision < $1.snapshot.revision : $0.snapshot.source < $1.snapshot.source + } + } + + package func resource(snapshot: SourceSnapshotID, path: String) throws -> URL { + try requireOpen() + guard let view = borrowed[snapshot] else { throw CoreError.notFound("source snapshot") } + return try view.resource(path) + } + + package func fileSnapshot(source: String, revision: String, files: [String: Data]) throws + -> SourceSnapshot + { + try requireOpen() + let id = SourceSnapshotID(source: source, revision: revision) + if let existing = borrowed[id] { return existing } + let root = workspace.appendingPathComponent(UUID().uuidString) + try FileSystem.createDirectory(at: root) + for path in files.keys.sorted() { + try Task.checkCancellation() + try FileSystem.write(files[path]!, to: PathSafety.resolvedChild(base: root, subpath: path)) + } + let result = try SourceSnapshot(snapshot: id, pin: nil, root: root) + register(result) + return result + } + + package func liveSnapshot(_ source: SourceDeclaration) throws -> SourceSnapshot { + try requireOpen() + guard source.kind == .local, source.requirement == nil else { + throw CoreError.invalidSource("edit requires an actual local source with no requirement") + } + let root = source.localURL(environment: store.environment) + let result = try SourceSnapshot( + snapshot: SourceSnapshotID( + source: source.identity(environment: store.environment), revision: "live"), + pin: nil, root: root, discoveryPath: source.path ?? ".", + localEnvironment: localEnvironment(for: source), liveRoot: root) + register(result) + return result + } + + package func isGitSource(_ source: SourceDeclaration) throws -> Bool { + guard source.kind == .local else { return source.kind == .git } + let local = source.localURL(environment: store.environment) + return + (try? ProcessRunner.git( + ["-C", local.path, "rev-parse", "--git-dir"], + operation: .findRepositoryRoot, source: source.location)) != nil + } + + private func localEnvironment(for source: SourceDeclaration) -> SourceEnvironment? { + guard source.kind == .local else { return nil } + return SourceEnvironment( + projectDirectory: source.localURL(environment: store.environment), + homeDirectory: source.environment?.homeDirectory ?? store.environment.homeDirectory) + } + + private static func validateLinks(_ root: URL) throws { + guard let real = PathSafety.realPath(root.path), + let entries = FileManager.default.enumerator( + at: root, includingPropertiesForKeys: [.isSymbolicLinkKey]) + else { return } + for case let entry as URL in entries { + try Task.checkCancellation() + if try entry.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true, + try !PathSafety.linkStaysInside(entry, root: real) + { + throw CoreError.unsafePath("local source symlink escapes snapshot") + } + } + } + package func withSnapshot( _ source: SourceDeclaration, _ body: (SourceRevision, URL) throws -> T ) throws -> T { + try requireOpen() let identity = try source.identity(environment: store.environment) let effective = LockedSource( kind: source.kind, url: source.kind == .git ? source.gitURL : nil, @@ -34,7 +299,8 @@ package final class SourceResolutionSession { { return try body(snapshot.pin, snapshot.root) } - let snapshot = try cache.withResolvedSnapshot(source) { pin, tree in + let snapshot = try cache.withResolvedSnapshot(source, cacheSource: mode == .persistentCache) { + pin, tree in let root = workspace.appendingPathComponent(UUID().uuidString) try FileSystem.withAccessErrors(at: root) { try FileManager.default.copyItem(at: tree, to: root) diff --git a/Sources/AgentsCore/SourceSnapshot.swift b/Sources/AgentsCore/SourceSnapshot.swift new file mode 100644 index 0000000..26a4526 --- /dev/null +++ b/Sources/AgentsCore/SourceSnapshot.swift @@ -0,0 +1,84 @@ +import Foundation + +/// Exact content identity. Discovery roots are namespaces within this content, not versions. +package struct SourceSnapshotID: Hashable, Sendable { + package let source: String + package let revision: String + + package init(source: String, revision: String) { + self.source = source + self.revision = revision + } +} + +/// A borrowed view, valid only while its source session is open. Stable output uses `snapshot` +/// and relative paths. `liveRoot` exists only for actual local authoring sources. +package struct SourceSnapshot { + package let snapshot: SourceSnapshotID + package let pin: SourceRevision? + package let root: URL + package let discoveryPath: String + /// Actual local source root before `discoveryPath`, with its declaring home. Pinned local + /// sources retain this origin; remote-contained syntax has none. It does not permit editing. + package let localEnvironment: SourceEnvironment? + package let liveRoot: URL? + package let packageIdentity: String + + package init( + snapshot: SourceSnapshotID, pin: SourceRevision?, root: URL, discoveryPath: String = ".", + localEnvironment: SourceEnvironment? = nil, liveRoot: URL? = nil, + packageIdentity: String? = nil + ) throws { + self.snapshot = snapshot + self.packageIdentity = packageIdentity ?? snapshot.source + self.pin = pin + self.root = root + self.discoveryPath = try PathSafety.sanitizeSubpath(discoveryPath) + self.localEnvironment = localEnvironment + self.liveRoot = liveRoot + _ = try directory() + } + + package func directory() throws -> URL { try resource(discoveryPath) } + + /// Both authored spelling and real symlink resolution must remain in the snapshot. + package func resource(_ path: String) throws -> URL { + guard !path.hasPrefix("~") else { throw CoreError.unsafePath("resource must be relative") } + let file = try PathSafety.resolvedChild(base: root, subpath: path) + guard PathSafety.isContained(file.resolvingSymlinksInPath(), in: root.resolvingSymlinksInPath()) + else { throw CoreError.unsafePath("resource escapes its source snapshot: \(path)") } + return file + } + + /// Directory resources may contain links below their top-level entry as well. + package func validateResourceTree(_ directory: URL) throws { + _ = try relativePath(directory) + guard let real = PathSafety.realPath(root.path), + let entries = FileManager.default.enumerator( + at: directory, includingPropertiesForKeys: [.isSymbolicLinkKey]) + else { return } + for case let entry as URL in entries { + try Task.checkCancellation() + if try entry.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true, + try !PathSafety.linkStaysInside(entry, root: real) + { + throw CoreError.unsafePath("resource symlink escapes source snapshot") + } + } + } + + package func relativePath(_ url: URL) throws -> String { + let path = PathSafety.relativePath(url.path, to: root.path) + _ = try resource(path) + return path + } +} + +/// Stable reconstruction coordinates. Contained sources borrow the enclosing package's exact +/// tree; resource paths remain relative to that tree. No borrowed URL is part of this evidence. +package struct SourceSnapshotEvidence: Equatable, Sendable { + package let snapshot: SourceSnapshotID + package let pin: SourceRevision? + package let source: LockedSource? + package let container: SourceSnapshotID? +} diff --git a/Sources/AgentsInstructions/InstructionFrontMatter.swift b/Sources/AgentsInstructions/InstructionFrontMatter.swift index 542cce9..56ce5a4 100644 --- a/Sources/AgentsInstructions/InstructionFrontMatter.swift +++ b/Sources/AgentsInstructions/InstructionFrontMatter.swift @@ -1,3 +1,4 @@ +import AgentsCore import Foundation /// The fixed front matter of an instructions file: a required `description` and optional `paths`. @@ -6,14 +7,16 @@ import Foundation struct InstructionFrontMatter: Equatable { let description: String let paths: [String] + let condition: DeclarationCondition struct Failure: Error { let reason: String } - static func parse(_ lines: [String]) throws -> Self { + static func parse(_ lines: [String], allowRestrictions: Bool = false) throws -> Self { var description: String? var paths: [String]? + var restrictions: [String: [String]] = [:] var index = 0 func fail(_ reason: String) -> Failure { Failure(reason: reason) } while index < lines.count { @@ -24,12 +27,17 @@ struct InstructionFrontMatter: Equatable { else { throw fail("front matter line \(index + 1) is not a 'key: value' entry.") } let key = String(line[.. String { diff --git a/Sources/AgentsInstructions/InstructionModels.swift b/Sources/AgentsInstructions/InstructionModels.swift index 7451983..6b7b462 100644 --- a/Sources/AgentsInstructions/InstructionModels.swift +++ b/Sources/AgentsInstructions/InstructionModels.swift @@ -1,3 +1,4 @@ +import AgentsCore import Foundation public struct InstructionSection: Sendable, Equatable { @@ -10,6 +11,7 @@ public struct InstructionSection: Sendable, Equatable { public let description: String /// Project-relative glob patterns that scope the section, in source order. public let paths: [String] + package let condition: DeclarationCondition /// 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 diff --git a/Sources/AgentsInstructions/InstructionSnapshotReader.swift b/Sources/AgentsInstructions/InstructionSnapshotReader.swift new file mode 100644 index 0000000..5aab1b6 --- /dev/null +++ b/Sources/AgentsInstructions/InstructionSnapshotReader.swift @@ -0,0 +1,42 @@ +import AgentsCore +import Foundation + +package struct SnapshotInstruction: Equatable, Sendable { + package let name: String + package let path: String + package let bytes: Data + package let section: InstructionSection +} + +/// Reads conventional containers in an exact source view. It does not resolve, cache or render. +package enum InstructionSnapshotReader { + package static func read(_ view: SourceSnapshot, own: Bool = false) throws + -> [SnapshotInstruction] + { + let root = try view.directory() + let containers = + own + ? [root.lastPathComponent == ".agent" ? "instructions" : InstructionSources.ownContainer] + : InstructionSources.containers + var names = Set() + var result: [SnapshotInstruction] = [] + for container in containers { + let directory = root.appendingPathComponent(container) + for (name, file) in try InstructionSources.files(in: directory, tree: view.root) { + try Task.checkCancellation() + guard names.insert(name).inserted else { + throw CoreError.invalidSource("duplicate instruction name: \(name)") + } + let path = try view.relativePath(file) + let bytes = try FileSystem.read(at: view.resource(path)) + let id = view.snapshot.source + ":" + name + let section = try Instructions.validateSource(bytes, id: id, allowRestrictions: true) + result.append( + SnapshotInstruction( + name: name, path: path, bytes: bytes, + section: section)) + } + } + return result.sorted { $0.name < $1.name } + } +} diff --git a/Sources/AgentsInstructions/InstructionSources.swift b/Sources/AgentsInstructions/InstructionSources.swift index eccffae..04ad541 100644 --- a/Sources/AgentsInstructions/InstructionSources.swift +++ b/Sources/AgentsInstructions/InstructionSources.swift @@ -216,7 +216,7 @@ final class InstructionSources { /// 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)] { + 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) diff --git a/Sources/AgentsInstructions/Instructions.swift b/Sources/AgentsInstructions/Instructions.swift index 4206959..88522f0 100644 --- a/Sources/AgentsInstructions/Instructions.swift +++ b/Sources/AgentsInstructions/Instructions.swift @@ -11,6 +11,12 @@ public enum Instructions { /// 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 { + try validateSource(bytes, id: id, allowRestrictions: false) + } + + static func validateSource(_ bytes: Data, id: String, allowRestrictions: Bool) throws + -> InstructionSection + { 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) @@ -21,7 +27,8 @@ public enum Instructions { } let front: InstructionFrontMatter do { - front = try InstructionFrontMatter.parse(Array(lines[1.. Void + ) throws { + var cost = try cost(.record(record), depth: 1, spending: spending) + guard origins.count <= ManifestLimits.SourceMap.origins else { throw Failure.limit } + // Reference origins are inherited by every descendant value location. + cost.origins = ValueCost.add(cost.origins, cost.nodes * origins.count) + total.append(cost) + guard total.fits, total.nodes <= ManifestLimits.SourceMap.locations else { + throw Failure.limit + } + for location in locations { + try spending(1 + location.origins.count + origins.count) + guard + sourceMap.consume( + pointer: location.pointer, span: location.span, + origins: location.origins + origins) + else { throw Failure.limit } + } + } + + private func cost( + _ value: DeclarationValue, depth: Int, spending: (Int) throws -> Void + ) throws -> ValueCost { + try spending(1) + guard depth < ManifestLimits.Values.depth else { throw Failure.limit } + let result: ValueCost + switch value { + case .string(let text): result = .scalar(text) + case .integer, .boolean, .null: result = ValueCost() + case .array(let values): + guard values.count <= ManifestLimits.Values.entries else { throw Failure.limit } + result = try .container(values.map { try cost($0, depth: depth + 1, spending: spending) }) + case .dictionary(let fields): + result = try fieldsCost(fields, depth: depth, spending: spending) + case .record(let record): + result = try fieldsCost( + record.fields, kind: record.kind, depth: depth, spending: spending) + case .requirement(let requirement): + var fields = [requirement.kind: DeclarationValue.string(requirement.value)] + if let upper = requirement.upperBound { fields["to"] = .string(upper) } + result = try fieldsCost(fields, depth: depth, spending: spending) + } + guard result.fits else { throw Failure.limit } + return result + } + + private func fieldsCost( + _ fields: [String: DeclarationValue], kind: String? = nil, depth: Int, + spending: (Int) throws -> Void + ) throws -> ValueCost { + guard fields.count <= ManifestLimits.Values.entries else { throw Failure.limit } + var children: [ValueCost] = [] + var keys = fields.keys.sorted() + if let kind { + try spending(1) + children.append(.scalar(kind)) + keys.append("kind") + } + for key in fields.keys.sorted() { + children.append(try cost(fields[key]!, depth: depth + 1, spending: spending)) + } + return .container(children, keys: keys) + } +} diff --git a/Sources/AgentsManifest/MapBuilder.swift b/Sources/AgentsManifest/MapBuilder.swift index b7ae713..dac54f4 100644 --- a/Sources/AgentsManifest/MapBuilder.swift +++ b/Sources/AgentsManifest/MapBuilder.swift @@ -12,8 +12,7 @@ final class MapBuilder { private let admission: Admission private let digest: String private var result = BuiltMap() - private var originCount = 0 - private var encodedBytes = 0 + private var budget = SourceMapBudget() init(source: SourceText, admission: Admission, digest: String) { self.source = source @@ -48,25 +47,17 @@ final class MapBuilder { resolved = next } if value.referent != nil { - guard resolved.cost.nodes <= ManifestLimits.SourceMap.locations - result.entries.count, - value.cost.origins <= ManifestLimits.SourceMap.origins - originCount + guard resolved.cost.nodes <= budget.remainingLocations, + value.cost.origins <= budget.remainingOrigins else { throw source.failure("manifest.limit", "reference source map expansion", range.lowerBound) } } let recordedOrigins = inherited + ownOrigins - let estimate = - pointer.utf8.count + (source.identity.rawValue.utf8.count + 160) * (recordedOrigins.count + 1) - + 80 - guard result.entries.count < ManifestLimits.SourceMap.locations, - recordedOrigins.count <= ManifestLimits.SourceMap.origins - originCount, - estimate <= ManifestLimits.SourceMap.encodedBytes - encodedBytes - else { + guard budget.consume(pointer: pointer, span: span, origins: recordedOrigins) else { throw source.failure( "manifest.limit", "source map locations, origins or encoded bytes", range.lowerBound) } - originCount += recordedOrigins.count - encodedBytes += estimate result.entries.append( SourceMapEntry( pointer: pointer, span: span, origins: recordedOrigins, defaulted: value.defaulted)) diff --git a/Sources/AgentsManifest/ValueBudget.swift b/Sources/AgentsManifest/ValueBudget.swift index 7f7569a..121da09 100644 --- a/Sources/AgentsManifest/ValueBudget.swift +++ b/Sources/AgentsManifest/ValueBudget.swift @@ -1,3 +1,4 @@ +import AgentsCore import AgentsDescription struct ValueCost: Sendable { @@ -20,11 +21,7 @@ struct ValueCost: Sendable { static func container(_ children: [ValueCost], keys: [String] = []) -> Self { var result = Self() for child in children { - result.nodes = add(result.nodes, child.nodes) - result.strings = add(result.strings, child.strings) - result.encoded = add(result.encoded, add(child.encoded, 4 + child.nodes * 2)) - result.origins = add(result.origins, child.origins) - result.depth = max(result.depth, child.depth + 1) + result.append(child) } for key in keys { let cost = scalar(key) @@ -34,6 +31,14 @@ struct ValueCost: Sendable { return result } + mutating func append(_ child: Self) { + nodes = Self.add(nodes, child.nodes) + strings = Self.add(strings, child.strings) + encoded = Self.add(encoded, Self.add(child.encoded, 4 + child.nodes * 2)) + origins = Self.add(origins, child.origins) + depth = max(depth, child.depth + 1) + } + var fits: Bool { nodes <= ManifestLimits.Values.nodes && strings <= ManifestLimits.Values.stringBytes && encoded <= ManifestLimits.Output.encodedBytes @@ -48,6 +53,28 @@ struct ValueCost: Sendable { } } +struct SourceMapBudget { + private var locations = 0 + private var origins = 0 + private var encoded = 0 + + var remainingLocations: Int { ManifestLimits.SourceMap.locations - locations } + var remainingOrigins: Int { ManifestLimits.SourceMap.origins - origins } + + mutating func consume(pointer: String, span: SourceSpan, origins: [SourceSpan]) -> Bool { + guard remainingLocations > 0, origins.count <= remainingOrigins else { return false } + let estimate = + origins.reduce(pointer.utf8.count + span.document.rawValue.utf8.count + 160 + 80) { + ValueCost.add($0, $1.document.rawValue.utf8.count + 160) + } + guard estimate <= ManifestLimits.SourceMap.encodedBytes - encoded else { return false } + locations += 1 + self.origins += origins.count + encoded += estimate + return true + } +} + func constructionCost(_ value: ConstructionValue) -> ValueCost { switch value { case .text(let text): return .scalar(text) diff --git a/Sources/AgentsSkills/Discovery.swift b/Sources/AgentsSkills/Discovery.swift index 282827c..4b18942 100644 --- a/Sources/AgentsSkills/Discovery.swift +++ b/Sources/AgentsSkills/Discovery.swift @@ -23,6 +23,7 @@ public struct Skill: Codable, Equatable, Sendable { struct DiscoveryOptions: Sendable { var includeInternal: Bool var fullDepth: Bool + var strict = false init(includeInternal: Bool = false, fullDepth: Bool = false) { self.includeInternal = includeInternal @@ -35,7 +36,9 @@ enum Discovery { "node_modules", ".git", "dist", "build", "__pycache__", "__pypackages__", ]) - static func parseSkill(at skillFile: URL, includeInternal: Bool = false) throws -> Skill? { + static func parseSkill(at skillFile: URL, includeInternal: Bool = false, strict: Bool = false) + throws -> Skill? + { let content = try FileSystem.withAccessErrors(at: skillFile) { try String(contentsOf: skillFile, encoding: .utf8) } @@ -43,13 +46,19 @@ enum Discovery { do { data = try parseFrontmatter(content) } catch { + if strict { + throw CoreError.invalidSource( + "\(skillFile.lastPathComponent): malformed front matter: \(error)") + } return nil } + if strict { _ = try producerCondition(data, file: skillFile, content: content) } guard let name = data["name"] as? String, let description = data["description"] as? String, !name.isEmpty, !description.isEmpty else { + if strict { throw CoreError.invalidSource("SKILL.md requires name and description") } return nil } @@ -83,7 +92,9 @@ enum Discovery { func addSkillDirectory(_ directory: URL) throws -> Bool { let skillFile = directory.appendingPathComponent("SKILL.md") guard FileManager.default.fileExists(atPath: skillFile.path) else { return false } - guard var skill = try parseSkill(at: skillFile, includeInternal: options.includeInternal) + guard + var skill = try parseSkill( + at: skillFile, includeInternal: options.includeInternal, strict: options.strict) else { return false } let key = skill.name.lowercased() guard !seen.contains(key) else { return true } @@ -145,7 +156,27 @@ enum Discovery { } } - private static func parseFrontmatter(_ raw: String) throws -> [String: Any] { + static func producerCondition(_ data: [String: Any], file: URL, content: String) throws + -> DeclarationCondition + { + var result = DeclarationCondition() + let lines = content.components(separatedBy: "\n") + for key in ["agents", "platforms", "scopes"] { + guard let raw = data[key] else { continue } + let line = (lines.firstIndex { $0.hasPrefix(key + ":") } ?? 0) + 1 + do { + guard let values = raw as? [String] else { + throw CoreError.invalidSource("producer '\(key)' must be a string list") + } + result = result.intersecting(try .restrictions([key: values])) + } catch { + throw CoreError.invalidSource("\(file.lastPathComponent):\(line): \(error)") + } + } + return result + } + + static func parseFrontmatter(_ raw: String) throws -> [String: Any] { guard raw.hasPrefix("---") else { return [:] } let pattern = #"^---\r?\n([\s\S]*?)\r?\n---\r?\n?"# guard let regex = try? NSRegularExpression(pattern: pattern), diff --git a/Sources/AgentsSkills/SkillSnapshotReader.swift b/Sources/AgentsSkills/SkillSnapshotReader.swift new file mode 100644 index 0000000..9c00905 --- /dev/null +++ b/Sources/AgentsSkills/SkillSnapshotReader.swift @@ -0,0 +1,71 @@ +import AgentsCore +import Foundation + +/// Relative skill evidence read from an already selected snapshot. This reader never resolves +/// a source or retains content. Live paths belong only to an actual local edit selection. +package struct SnapshotSkill: Equatable, Sendable { + package let name: String + package let description: String + package let path: String + package let condition: DeclarationCondition + package let hash: String + package let executableFlags: [String: Bool] + package let livePath: String? +} + +package enum SkillSnapshotReader { + package static func read(_ view: SourceSnapshot, live: Bool = false) throws -> [SnapshotSkill] { + let base: URL + if live { + guard let root = view.liveRoot else { + throw CoreError.invalidSource("skill source is immutable") + } + base = root + } else { + base = view.root + } + let selected = try SourceSnapshot( + snapshot: view.snapshot, pin: view.pin, root: base, + discoveryPath: view.discoveryPath, localEnvironment: view.localEnvironment, + liveRoot: view.liveRoot, + packageIdentity: view.packageIdentity) + var options = DiscoveryOptions(fullDepth: true) + options.strict = true + return try Discovery.discover(in: base, subpath: selected.discoveryPath, options: options).map { + skill in + try Task.checkCancellation() + let path = try selected.relativePath(URL(fileURLWithPath: skill.path)) + let directory = try selected.resource(path) + try selected.validateResourceTree(directory) + let file = try selected.resource(path + "/SKILL.md") + let bytes = try FileSystem.read(at: file) + let fields = try Discovery.parseFrontmatter(String(decoding: bytes, as: UTF8.self)) + return try SnapshotSkill( + name: skill.name, description: skill.description, path: path, + condition: Discovery.producerCondition( + fields, file: file, content: String(decoding: bytes, as: UTF8.self)), + hash: "sha256:" + FileHash.folderHash(directory), + executableFlags: FileHash.executableFlags(directory), + livePath: live ? directory.path : nil) + } + } +} + +/// Existing skill index formats remain skill-only. Artifact coordinates, not the mutable index, +/// identify the selected content for later retention and locked reconstruction. +package struct SnapshotIndexSkill: Sendable { + package let name: String + package let artifact: LockedArtifact + package let files: [String: Data] +} + +extension SkillSnapshotReader { + package static func index(_ source: SourceDeclaration) throws -> [SnapshotIndexSkill] { + try Task.checkCancellation() + let result = try WellKnownProvider().fetchAllSkills(from: source.location).map { + SnapshotIndexSkill(name: $0.installName, artifact: $0.artifact, files: $0.files) + } + try Task.checkCancellation() + return result + } +} diff --git a/Sources/Components/ComponentFields.swift b/Sources/Components/ComponentFields.swift new file mode 100644 index 0000000..0720e7f --- /dev/null +++ b/Sources/Components/ComponentFields.swift @@ -0,0 +1,112 @@ +import AgentsCore + +extension ComponentDeclaration { + var name: String? { + switch self { + case .skills, .instructions: nil + case .mcpServer(let name, _, _, _, _), .hook(let name, _, _, _, _, _, _, _), + .subagent(let name, _, _, _, _, _, _, _), .command(let name, _, _, _, _, _, _), + .lspServer(let name, _, _, _, _, _, _), .permissions(let name, _, _, _, _), + .ignore(let name, _, _, _, _, _), .plugin(let name, _, _, _, _, _, _, _, _): + name + } + } + + var agents: [AgentID]? { + switch self { + case .skills(_, let value): value.agents + case .instructions(let value): value.agents + case .mcpServer(_, _, let agents, _, _), .hook(_, _, _, _, _, let agents, _, _), + .subagent(_, _, _, _, _, let agents, _, _), .command(_, _, _, _, let agents, _, _), + .lspServer(_, _, _, _, let agents, _, _), .permissions(_, _, let agents, _, _), + .ignore(_, _, _, let agents, _, _), .plugin(_, _, _, _, _, _, let agents, _, _): + agents + } + } + + var condition: DeclarationCondition? { + switch self { + case .skills(_, let value): value.condition + case .instructions(let value): value.condition + case .mcpServer(_, _, _, let condition, _), .hook(_, _, _, _, _, _, let condition, _), + .subagent(_, _, _, _, _, _, let condition, _), .command(_, _, _, _, _, let condition, _), + .lspServer(_, _, _, _, _, let condition, _), .permissions(_, _, _, let condition, _), + .ignore(_, _, _, _, let condition, _), .plugin(_, _, _, _, _, _, _, let condition, _): + condition + } + } + + var resources: [ResourceDeclaration] { + func run(_ value: ExecutableDeclaration) -> [ResourceDeclaration] { + let executable = + value.executable.contains("/") ? [ResourceDeclaration(path: value.executable)] : [] + return executable + (value.workingDirectory.map { [$0] } ?? []) + } + func prompt(_ value: PromptBody) -> [ResourceDeclaration] { + if case .file(let resource) = value { return [resource] } + return [] + } + switch self { + case .mcpServer(_, .stdio(let value), _, _, _): return run(value) + case .hook(_, _, let value, _, _, _, _, _), .lspServer(_, let value, _, _, _, _, _): + return run(value) + case .subagent(_, _, let value, _, _, _, _, _), .command(_, _, let value, _, _, _, _): + return prompt(value) + case .plugin(_, let path, let source, _, _, _, _, _, _): + return [ResourceDeclaration(path: path, source: source)] + default: return [] + } + } + + /// Content comparison uses resolved resource evidence and effective targets separately. + var comparisonPayload: ComponentDeclaration { + func run(_ value: ExecutableDeclaration) -> ExecutableDeclaration { + var result = value + if let path = value.workingDirectory { + result.workingDirectory = ResourceDeclaration(path: path.path) + } + return result + } + func body(_ value: PromptBody) -> PromptBody { + if case .file(let path) = value { return .file(ResourceDeclaration(path: path.path)) } + return value + } + switch self { + case .mcpServer(let name, let transport, _, _, let native): + let resolved: MCPTransportDeclaration + if case .stdio(let value) = transport { + resolved = .stdio(run(value)) + } else { + resolved = transport + } + return .mcpServer(name: name, transport: resolved, native: native) + case .hook(let name, let event, let invocation, let matcher, let timeout, _, _, let native): + return .hook( + name: name, event: event, run: run(invocation), matcher: matcher, timeoutSeconds: timeout, + native: native) + case .subagent(let name, let description, let prompt, let model, let tools, _, _, let native): + return .subagent( + name: name, description: description, prompt: body(prompt), model: model, tools: tools, + native: native) + case .command(let name, let description, let prompt, let parameters, _, _, let native): + return .command( + name: name, description: description, prompt: body(prompt), parameters: parameters, + native: native + ) + case .lspServer(let name, let invocation, let languages, let options, _, _, let native): + return .lspServer( + name: name, run: run(invocation), languages: languages, initializationOptions: options, + native: native) + case .permissions(let name, let rules, _, _, let native): + return .permissions(name: name, rules: rules, native: native) + case .ignore(let name, let patterns, let purpose, _, _, let native): + return .ignore(name: name, patterns: patterns, purpose: purpose, native: native) + case .plugin( + let name, let path, _, let mode, let select, let exclude, _, _, let native): + return .plugin( + name: name, path: path, source: ".", mode: mode, select: select, exclude: exclude, + native: native) + case .skills, .instructions: return self + } + } +} diff --git a/Sources/Components/ComponentLinker.swift b/Sources/Components/ComponentLinker.swift new file mode 100644 index 0000000..d2a9826 --- /dev/null +++ b/Sources/Components/ComponentLinker.swift @@ -0,0 +1,297 @@ +import AgentsCore +import AgentsManifest +import Foundation + +/// Links symbolic declarations to exact, ordered contributions. The caller owns the read lock +/// and consumes borrowed resources inside `withLinkedComponents`; no state is published here. +package enum ComponentLinker { + package static func withLinkedComponents( + document: DeclarationDocument, store: StateStore, platform: DeclarationPlatform, + preserving pins: [String: SourceRevision] = [:], + directPins: [ComponentKey: SourceRevision] = [:], + _ body: (LinkedComponents, SourceResolutionSession) throws -> T + ) throws -> T { + try SourceResolutionSession.withTemporaryRead(store: store) { session in + let linker = Linking( + document: document, store: store, platform: platform, + session: session, directPins: directPins) + let graph = try linker.solve(preserving: pins) + return try body(graph, session) + } + } +} + +struct LinkingDocument { + let declaration: Declaration + let document: DeclarationDocument + let view: SourceSnapshot + let manifestPath: String + let producer: Bool + +} + +struct SourceAddress { + let id: String + let source: SourceDeclaration? + let contained: SourceSnapshot? + let root: String +} + +struct GroupIdentity: Hashable { + let snapshot: SourceSnapshotID + let root: String + let name: String +} + +struct RequirementSearch: Error { + let constraints: [SourceConstraint] +} + +final class Linking { + let document: DeclarationDocument + let store: StateStore + let platform: DeclarationPlatform + let session: SourceResolutionSession + let directPins: [ComponentKey: SourceRevision] + let budget = LinkBudget() + var documents: [GroupIdentity: LinkingDocument] = [:] + var nonGit = Set() + var git = Set() + var addresses: [String: SourceAddress] = [:] + private var componentMaps: [GroupIdentity: [String: [SourceMapEntry]]] = [:] + private var positions: [GroupIdentity: [String: SourceMapEntry]] = [:] + + init( + document: DeclarationDocument, store: StateStore, platform: DeclarationPlatform, + session: SourceResolutionSession, directPins: [ComponentKey: SourceRevision] + ) { + self.document = document + self.store = store + self.platform = platform + self.session = session + self.directPins = directPins + } + + func solve(preserving pins: [String: SourceRevision]) throws -> LinkedComponents { + try budget.step(document.metrics.evaluationSteps) + let declaration = try ManifestProjection.declaration( + of: document, environment: store.environment) + let packageRoot = + store.scope == .user ? store.directory : store.environment.projectDirectory + let root = try SourceSnapshot( + snapshot: SourceSnapshotID( + source: "local:" + packageRoot.path, + revision: "live"), pin: nil, + root: packageRoot, + localEnvironment: SourceEnvironment( + projectDirectory: packageRoot, homeDirectory: store.environment.homeDirectory), + liveRoot: packageRoot) + session.register(root) + let context = LinkingDocument( + declaration: declaration, document: document, view: root, + manifestPath: store.scope == .user ? "Agents.swift" : ".agent/Agents.swift", + producer: false) + try budget.manifest(root.snapshot, path: context.manifestPath, bytes: document.bytes.count) + guard let result = try search(root: context, choices: pins) else { + throw LinkError.incompatible(lastFailure) + } + return result + } + + var lastFailure: [SourceConstraint] = [] + + func componentLocations(at pointer: String, in context: LinkingDocument) throws + -> [SourceMapEntry] + { + let key = GroupIdentity( + snapshot: context.view.snapshot, root: context.view.discoveryPath, name: "") + if componentMaps[key] == nil { + var locations: [String: [SourceMapEntry]] = [:] + var firstPositions: [String: SourceMapEntry] = [:] + for entry in context.document.sourceMap.entries { + try budget.step() + if firstPositions[entry.pointer] == nil { firstPositions[entry.pointer] = entry } + let path = entry.pointer.split(separator: "/") + let prefix: Int + if path.first == "components", path.count >= 2 { + prefix = 2 + } else if path.first == "groups", path.count >= 4, path[2] == "components" { + prefix = 4 + } else { + continue + } + locations["/" + path.prefix(prefix).joined(separator: "/"), default: []].append(entry) + } + componentMaps[key] = locations + positions[key] = firstPositions + } + return componentMaps[key]?[pointer] ?? [] + } + + func position(at pointer: String, in context: LinkingDocument) throws -> SourceMapEntry? { + _ = try componentLocations(at: pointer, in: context) + return positions[ + GroupIdentity(snapshot: context.view.snapshot, root: context.view.discoveryPath, name: "") + ]?[pointer] + } + + private func search(root: LinkingDocument, choices initial: [String: SourceRevision]) throws + -> LinkedComponents? + { + struct Decision { + let source: String + let candidates: [SourceRevision] + var next: Int + } + var choices = initial + var decisions: [Decision] = [] + func backtrack() throws -> Bool { + while var decision = decisions.popLast() { + try budget.step() + choices.removeValue(forKey: decision.source) + if decision.next < decision.candidates.count { + choices[decision.source] = decision.candidates[decision.next] + decision.next += 1 + decisions.append(decision) + return true + } + } + return false + } + while true { + try budget.step() + let pass = Expansion(linking: self, choices: choices, emit: false) + do { try pass.expandRoot(root) } catch let error as RequirementSearch { + lastFailure = error.constraints + if try backtrack() { continue } + return nil + } + if let next = pass.constraints.keys.filter({ choices[$0] == nil }).sorted().first { + let requirements = pass.constraints[next]! + let candidates = try session.candidates( + for: addresses[next]!.source!, + requirements: requirements.map(\.requirement), spending: budget.step) + try budget.step(candidates.count) + guard let candidate = candidates.first else { + lastFailure = requirements + if try backtrack() { continue } + return nil + } + decisions.append(Decision(source: next, candidates: candidates, next: 1)) + choices[next] = candidate + continue + } + let final = Expansion(linking: self, choices: choices, emit: true) + do { try final.expandRoot(root) } catch let error as RequirementSearch { + lastFailure = error.constraints + if try backtrack() { continue } + return nil + } + return try final.result() + } + } + + func address(_ alias: String?, in context: LinkingDocument, chain: [SourceSpan]) throws + -> SourceAddress + { + try budget.step(chain.count + 1) + guard let alias, alias != "." else { + return SourceAddress( + id: context.view.snapshot.source, source: nil, + contained: context.view, root: context.view.discoveryPath) + } + guard let source = context.declaration.sources[alias] else { + throw LinkError.missing("source alias '\(alias)'", chain) + } + if context.producer, context.view.localEnvironment == nil, source.kind == .local { + let raw = source.location + guard !raw.hasPrefix("/"), !raw.hasPrefix("~"), !raw.contains("\\") else { + throw LinkError.invalid("producer-local source must stay inside its package", chain) + } + let relative = try PathSafety.sanitizeSubpath(raw) + let directory = try context.view.directory().appendingPathComponent(relative) + .standardizedFileURL + let path = try context.view.relativePath(directory) + let sourceID = + path == "." + ? context.view.packageIdentity + : context.view.packageIdentity + ":contained:" + String(path.utf8.count) + ":" + path + let discoveryPath = try PathSafety.sanitizeSubpath(path + "/" + (source.path ?? ".")) + let view = try SourceSnapshot( + snapshot: SourceSnapshotID(source: sourceID, revision: context.view.snapshot.revision), + pin: context.view.pin, root: context.view.root, discoveryPath: discoveryPath, + packageIdentity: context.view.packageIdentity) + guard source.requirement == nil else { + throw LinkError.invalid("contained sources inherit their producer snapshot", chain) + } + try budget.snapshot(view.snapshot) + session.register(view) + return SourceAddress(id: sourceID, source: nil, contained: view, root: view.discoveryPath) + } + let id = try source.identity(environment: store.environment) + let root = try PathSafety.sanitizeSubpath(source.path ?? ".") + let result = SourceAddress(id: id, source: source, contained: nil, root: root) + addresses[id] = result + return result + } + + func view(_ address: SourceAddress, pin: SourceRevision? = nil) throws -> SourceSnapshot? { + if let contained = address.contained { return contained } + let source = address.source! + guard source.kind != .wellKnown else { + throw LinkError.invalid("skill indexes cannot supply package resources", []) + } + if let pin { + let view = try session.snapshot(source, at: pin) + try budget.snapshot(view.snapshot) + return view + } + if source.requirement != nil { + git.insert(address.id) + return nil + } + if try nonGit.contains(address.id) + || (!git.contains(address.id) && !session.isGitSource(source)) + { + nonGit.insert(address.id) + let view = try session.localSnapshot(source) + try budget.snapshot(view.snapshot) + return view + } + git.insert(address.id) + return nil + } + + func producer(_ view: SourceSnapshot, chain: [SourceSpan]) throws -> LinkingDocument { + let key = GroupIdentity(snapshot: view.snapshot, root: view.discoveryPath, name: "") + if let existing = documents[key] { return existing } + let root = try view.directory() + let file = root.appendingPathComponent( + root.lastPathComponent == ".agent" ? "Agents.swift" : ".agent/Agents.swift") + let relative = try view.relativePath(file) + let handle = try FileHandle(forReadingFrom: view.resource(relative)) + defer { try? handle.close() } + let bytes = try handle.read(upToCount: ManifestLimits.Input.bytes + 1) ?? Data() + guard bytes.count <= ManifestLimits.Input.bytes else { + throw LinkError.budget("manifest input bytes") + } + try budget.manifest( + view.snapshot, path: relative, bytes: bytes.count) + let coordinates = try JSONEncoder().encode([view.snapshot.source, view.discoveryPath, relative]) + let identity = DocumentIdentity("source:" + String(decoding: coordinates, as: UTF8.self)) + let document = try DeclarationDocument(bytes: Array(bytes), identity: identity) + let environment = RuntimeEnvironment( + projectDirectory: view.localEnvironment.map { + $0.projectDirectory.appendingPathComponent(view.discoveryPath) + } ?? root, + homeDirectory: view.localEnvironment?.homeDirectory ?? store.environment.homeDirectory, + environment: [:]) + try budget.step(document.metrics.evaluationSteps) + let declaration = try ManifestProjection.declaration(of: document, environment: environment) + let result = LinkingDocument( + declaration: declaration, document: document, view: view, + manifestPath: relative, producer: true) + documents[key] = result + return result + } +} diff --git a/Sources/Components/Expansion.swift b/Sources/Components/Expansion.swift new file mode 100644 index 0000000..1710f05 --- /dev/null +++ b/Sources/Components/Expansion.swift @@ -0,0 +1,580 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import Foundation + +final class Expansion { + let linking: Linking + let choices: [String: SourceRevision] + let emit: Bool + var constraints: [String: [SourceConstraint]] = [:] + var components: [LinkedComponent] = [] + var references: [LinkedReference] = [] + var active: [GroupIdentity] = [] + var nextOccurrence = 0 + var referenceParent: Int? + var indexes: [String: [SnapshotIndexSkill]] = [:] + var values = ManifestExpansionBudget() + + init(linking: Linking, choices: [String: SourceRevision], emit: Bool) { + self.linking = linking + self.choices = choices + self.emit = emit + } + + func expandRoot(_ root: LinkingDocument) throws { + try expand( + root.declaration.components, records: root.document.declaration.components, + in: root, group: nil, pointer: "/components", + condition: DeclarationCondition(), chain: [], dependencies: [], parent: nil) + for (index, use) in root.declaration.uses.enumerated() { + try expand( + use, in: root, pointer: "/uses/\(index)", condition: DeclarationCondition(), + chain: [], dependencies: [], parent: nil) + } + for (id, requirements) in constraints { + if let selected = choices[id] { + let candidates = try linking.session.candidates( + for: linking.addresses[id]!.source!, + requirements: requirements.map(\.requirement), spending: linking.budget.step) + try linking.budget.step(candidates.count) + guard candidates.contains(where: { $0.revision == selected.revision }) else { + throw RequirementSearch(constraints: requirements) + } + } + } + } + + private struct Use { + let declaration: GroupUseDeclaration + let document: LinkingDocument + let pointer: String + let condition: DeclarationCondition + let chain: [SourceSpan] + let dependencies: [SourceSnapshotID] + let parent: Int? + } + + private enum Walk { + case enter(Use) + case leave + } + + private func expand( + _ use: GroupUseDeclaration, in context: LinkingDocument, pointer: String, + condition: DeclarationCondition, chain: [SourceSpan], dependencies: [SourceSnapshotID], + parent: Int? + ) throws { + var pending: [Walk] = [ + .enter( + Use( + declaration: use, document: context, pointer: pointer, + condition: condition, chain: chain, dependencies: dependencies, parent: parent)) + ] + while let step = pending.popLast() { + switch step { + case .leave: + try linking.budget.step() + active.removeLast() + case .enter(let use): try enter(use, pending: &pending) + } + } + } + + private func enter(_ reference: Use, pending: inout [Walk]) throws { + let use = reference.declaration + let context = reference.document + let pointer = reference.pointer + var condition = reference.condition + var chain = reference.chain + var dependencies = reference.dependencies + let parent = reference.parent + try linking.budget.step(chain.count + 1) + guard active.count < 64 else { throw LinkError.budget("active references") } + let location = try linking.position(at: pointer, in: context) + chain += (location.map { [$0.span] + $0.origins } ?? []) + let address = try linking.address(use.source, in: context, chain: chain) + var target = context + var constraint: SourceConstraint? + if use.source != nil, use.source != "." { + guard address.source?.kind != .wellKnown else { + throw LinkError.invalid("skill indexes do not define an immutable export package", chain) + } + let initial = try linking.view(address, pin: choices[address.id]) + if let source = address.source, !linking.nonGit.contains(address.id) { + let entry = SourceConstraint( + source: address.id, root: address.root, + requirement: source.requirement, referenceChain: chain) + constraints[address.id, default: []].append(entry) + constraint = entry + } + guard let view = initial else { return } + target = try linking.producer(view, chain: chain) + guard target.declaration.exports.contains(use.name) else { + throw LinkError.missing("explicit export '\(use.name)'", chain) + } + } + guard let index = target.declaration.groups.firstIndex(where: { $0.name == use.name }) else { + throw LinkError.missing("group '\(use.name)'", chain) + } + let group = target.declaration.groups[index] + let key = GroupIdentity( + snapshot: target.view.snapshot, root: target.view.discoveryPath, name: group.name) + guard !active.contains(key) else { + throw LinkError.cycle((active + [key]).map(\.name), chain) + } + active.append(key) + pending.append(.leave) + let occurrence = nextOccurrence + nextOccurrence += 1 + dependencies += [target.view.snapshot] + condition = condition.intersecting(use.condition ?? DeclarationCondition()) + .intersecting(group.condition ?? DeclarationCondition()) + if emit { + references.append( + LinkedReference( + occurrence: occurrence, parent: parent, + group: group.name, snapshot: target.view.snapshot, root: target.view.discoveryPath, + constraint: constraint, referenceChain: chain)) + } + try expand( + group.components, + records: target.document.declaration.groups[index]["components"]!.elements!.map { + $0.record! + }, + in: target, group: group.name, + pointer: "/groups/\(index)/components", condition: condition, chain: chain, + dependencies: dependencies, parent: occurrence) + for (useIndex, nested) in group.uses.enumerated().reversed() { + pending.append( + .enter( + Use( + declaration: nested, document: target, + pointer: "/groups/\(index)/uses/\(useIndex)", condition: condition, chain: chain, + dependencies: dependencies, parent: occurrence))) + } + } + + private func expand( + _ declarations: [ComponentDeclaration], records: [DeclarationRecord], + in context: LinkingDocument, group: String?, + pointer: String, condition: DeclarationCondition, chain: [SourceSpan], + dependencies: [SourceSnapshotID], parent: Int? + ) throws { + let previousParent = referenceParent + referenceParent = parent + defer { referenceParent = previousParent } + for (index, component) in declarations.enumerated() { + try linking.budget.step(chain.count + 1) + let pointer = pointer + "/\(index)" + let position = try linking.position(at: pointer, in: context) + do { + try values.consume( + records[index], origins: chain, + locations: linking.componentLocations(at: pointer, in: context), + spending: linking.budget.step) + } catch is ManifestExpansionBudget.Failure { + throw LinkError.budget("expanded manifest values") + } + for resource in component.resources { + try constrainResource( + resource, in: context, chain: chain + (position.map { [$0.span] + $0.origins } ?? [])) + } + guard emit else { continue } + let effective = condition.intersecting(component.condition ?? DeclarationCondition()) + do { + switch component { + case .skills(let alias, let selection): + try skills( + selection, alias: alias, context: context, group: group, + condition: effective, chain: chain, position: position, dependencies: dependencies) + case .instructions(let selection): + for (index, section) in selection.sectionReferences.enumerated() { + try instruction( + section, prompt: nil, selection: selection, context: context, group: group, + condition: effective, chain: chain, + position: linking.position(at: pointer + "/sections/\(index)", in: context) + ?? position, + dependencies: dependencies) + } + for prompt in selection.prompts { + let promptCondition = effective.intersecting( + prompt.prompt.condition ?? DeclarationCondition()) + for section in prompt.prompt.sectionReferences { + try instruction( + section, prompt: prompt.name, selection: selection, context: context, + group: group, condition: promptCondition, chain: chain, position: position, + dependencies: dependencies, append: prompt.prompt.append) + } + } + default: + let resources = try component.resources.map { + try resource($0, context: context, chain: chain) + } + try append( + key: key(component.name!, kind: component.kind, context: context, group: group), + snapshot: context.view.snapshot, pin: context.view.pin, + payload: .declaration(component), + context: context, + group: group, condition: effective, + recipients: effective.recipients( + requested: component.agents ?? context.declaration.defaultAgents, + scope: linking.store.scope, platform: linking.platform), chatGPT: false, + resources: resources, chain: chain, position: position, + dependencies: dependencies + resources.map(\.snapshot)) + } + } catch let error as LinkError { throw error } catch { + throw LinkError.invalid( + String(describing: error), chain + (position.map { [$0.span] + $0.origins } ?? [])) + } + } + } + + private func key( + _ name: String, kind: DeclaredComponentKind, context: LinkingDocument, group: String? + ) -> ComponentKey { + ComponentKey( + source: context.view.snapshot.source, root: context.view.discoveryPath, + group: group, kind: kind, name: name) + } + + private func selectedView(_ address: SourceAddress, key: ComponentKey?, live: Bool = false) throws + -> SourceSnapshot + { + if let contained = address.contained { + if live, let root = contained.liveRoot { + return try linking.session.liveSnapshot( + SourceDeclaration( + kind: .local, location: root.path, + path: contained.discoveryPath)) + } + return contained + } + let source = address.source! + if live { return try linking.session.liveSnapshot(source) } + if let key, let preserved = linking.directPins[key] { + return try linking.view(address, pin: preserved)! + } + if let view = try linking.view(address) { return view } + let pin: SourceRevision + do { + guard + let candidate = try linking.session.candidates( + for: source, requirements: [source.requirement], spending: linking.budget.step + ).first + else { + throw LinkError.incompatible([ + SourceConstraint( + source: address.id, root: address.root, + requirement: source.requirement, referenceChain: []) + ]) + } + pin = candidate + } + return try linking.view(address, pin: pin)! + } + + private func skills( + _ selection: SkillDeclaration, alias: String, + context: LinkingDocument, group: String?, condition: DeclarationCondition, + chain: [SourceSpan], position: SourceMapEntry?, dependencies: [SourceSnapshotID] + ) throws { + let location = chain + (position.map { [$0.span] + $0.origins } ?? []) + var address = try linking.address(alias, in: context, chain: location) + if alias == ".", !context.producer { + let source = SourceDeclaration(kind: .local, location: context.view.root.path) + address = SourceAddress( + id: context.view.snapshot.source, source: source, contained: nil, + root: context.view.discoveryPath) + } + if let source = address.source, source.kind == .wellKnown { + try indexSkills( + selection, address: address, source: source, context: context, group: group, + condition: condition, chain: chain, position: position, dependencies: dependencies) + return + } + let requestedNames: [String]? + switch selection.select { + case .all: requestedNames = nil + case .names(let names): requestedNames = names + } + // Each direct member may retain a different pin even when it shares an alias with exports. + let names: [String] + if let requestedNames { + names = requestedNames + } else { + let live = selection.mode == .edit + names = try SkillSnapshotReader.read(selectedView(address, key: nil, live: live), live: live) + .map(\.name) + } + for name in names where !(selection.exclude ?? []).contains(name) { + let componentKey = key(name, kind: .skills, context: context, group: group) + let override = selection.overrides?[name] + let mode = override?.mode ?? selection.mode ?? .link + let view = try selectedView(address, key: componentKey, live: mode == .edit) + if mode == .edit, view.liveRoot == nil { + throw LinkError.invalid("edit requires an actual local skill with no requirement", location) + } + let matches = try SkillSnapshotReader.read(view, live: mode == .edit).filter { + $0.name == name || PathSafety.sanitizeName($0.name) == name + || URL(fileURLWithPath: $0.path).lastPathComponent == name + } + guard matches.count == 1, let skill = matches.first else { + throw LinkError.missing("skill '\(name)'", location) + } + let effective = condition.intersecting(skill.condition) + let resource = LinkedResource( + snapshot: view.snapshot, path: skill.path, + hash: skill.hash, executableFlags: skill.executableFlags) + try append( + key: componentKey, snapshot: view.snapshot, pin: view.pin, + payload: .skill(skill, mode: mode, native: selection.native), context: context, + group: group, + condition: effective, + recipients: effective.recipients( + requested: override?.agents ?? selection.agents ?? context.declaration.defaultAgents, + scope: linking.store.scope, platform: linking.platform), chatGPT: false, + resources: [resource], chain: chain, position: position, + dependencies: dependencies + [view.snapshot]) + } + } + + private func indexSkills( + _ selection: SkillDeclaration, address: SourceAddress, source: SourceDeclaration, + context: LinkingDocument, group: String?, condition: DeclarationCondition, + chain: [SourceSpan], position: SourceMapEntry?, dependencies: [SourceSnapshotID] + ) throws { + if indexes[address.id] == nil { indexes[address.id] = try SkillSnapshotReader.index(source) } + let available = indexes[address.id]! + let names: [String] + switch selection.select { + case .all: names = available.map(\.name) + case .names(let requested): names = requested + } + for name in names where !(selection.exclude ?? []).contains(name) { + let location = chain + (position.map { [$0.span] + $0.origins } ?? []) + guard let artifact = available.first(where: { $0.name == name }) else { + throw LinkError.missing("skill '\(name)'", location) + } + let override = selection.overrides?[name] + let mode = override?.mode ?? selection.mode ?? .link + guard mode != .edit else { + throw LinkError.invalid("edit requires an actual local skill with no requirement", location) + } + let view = try linking.session.fileSnapshot( + source: address.id, revision: artifact.artifact.digest, + files: artifact.files) + try linking.budget.snapshot(view.snapshot) + guard let skill = try SkillSnapshotReader.read(view).first, + PathSafety.sanitizeName(skill.name) == name + else { + throw LinkError.missing("skill '\(name)'", location) + } + let effective = condition.intersecting(skill.condition) + try append( + key: key(name, kind: .skills, context: context, group: group), snapshot: view.snapshot, + pin: view.pin, + payload: .skill(skill, mode: mode, native: selection.native), context: context, + group: group, + condition: effective, + recipients: effective.recipients( + requested: override?.agents ?? selection.agents ?? context.declaration.defaultAgents, + scope: linking.store.scope, platform: linking.platform), chatGPT: false, + resources: [ + LinkedResource( + snapshot: view.snapshot, path: skill.path, hash: skill.hash, + executableFlags: skill.executableFlags, artifact: artifact.artifact) + ], + chain: chain, position: position, dependencies: dependencies + [view.snapshot]) + } + } + + private func instruction( + _ section: SectionDeclaration, prompt: String?, selection: InstructionsDeclaration, + context: LinkingDocument, group: String?, condition: DeclarationCondition, chain: [SourceSpan], + position: SourceMapEntry?, dependencies: [SourceSnapshotID], append appendPath: String? = nil + ) throws { + let location = chain + (position.map { [$0.span] + $0.origins } ?? []) + let own = section.source == nil || section.source == "." + guard context.producer || linking.store.scope != .user || !own else { + throw LinkError.invalid("root user instructions require a named source", location) + } + let address = try linking.address(section.source, in: context, chain: location) + let componentKey = key(section.name, kind: .instructions, context: context, group: group) + let view = try selectedView(address, key: componentKey) + guard + let unit = try InstructionSnapshotReader.read(view, own: own).first(where: { + $0.name == section.name + }) + else { + throw LinkError.missing("instruction '\(section.name)'", location) + } + let effective = condition.intersecting(section.condition ?? DeclarationCondition()) + .intersecting(unit.section.condition) + var resources = [ + LinkedResource( + snapshot: view.snapshot, path: unit.path, + hash: unit.section.hash, executableFlags: [:]) + ] + if let appendPath { + if linking.store.scope == .user { + let home = linking.store.environment.homeDirectory + let view = try SourceSnapshot( + snapshot: SourceSnapshotID(source: "local:" + home.path, revision: "live"), + pin: nil, root: home, + localEnvironment: SourceEnvironment(projectDirectory: home, homeDirectory: home), + liveRoot: home) + try linking.budget.snapshot(view.snapshot) + linking.session.register(view) + resources.append(try resource(appendPath, in: view, chain: location)) + } else { + resources.append( + try resource(ResourceDeclaration(path: appendPath), context: context, chain: location)) + } + } + let recipients = + prompt == nil + ? effective.recipients( + requested: selection.agents ?? context.declaration.defaultAgents, + scope: linking.store.scope, platform: linking.platform) : [] + try self.append( + key: componentKey, snapshot: view.snapshot, pin: view.pin, + payload: .instruction(unit, prompt: prompt, native: selection.native), context: context, + group: group, condition: effective, recipients: recipients, + chatGPT: prompt != nil + && effective.matches(scope: linking.store.scope, platform: linking.platform), + resources: resources, chain: chain, position: position, + dependencies: dependencies + resources.map(\.snapshot)) + } + + private func constrainResource( + _ resource: ResourceDeclaration, in context: LinkingDocument, + chain: [SourceSpan] + ) throws { + let address = try linking.address(resource.source, in: context, chain: chain) + guard let source = address.source else { return } + guard source.kind != .wellKnown else { + throw LinkError.invalid("skill indexes cannot supply package resources", chain) + } + _ = try linking.view(address, pin: choices[address.id]) + if !linking.nonGit.contains(address.id) { + constraints[address.id, default: []].append( + SourceConstraint( + source: address.id, + root: address.root, requirement: source.requirement, referenceChain: chain)) + } + } + + private func resource( + _ resource: ResourceDeclaration, context: LinkingDocument, chain: [SourceSpan] + ) throws -> LinkedResource { + let address = try linking.address(resource.source, in: context, chain: chain) + guard let view = try linking.view(address, pin: choices[address.id]) else { + throw LinkError.invalid("resource source has no exact selection", chain) + } + return try self.resource(resource.path, in: view, chain: chain) + } + + private func resource(_ resourcePath: String, in view: SourceSnapshot, chain: [SourceSpan]) throws + -> LinkedResource + { + let root = try view.directory() + let file = try PathSafety.resolvedChild(base: root, subpath: resourcePath) + let path = try view.relativePath(file) + let target = try view.resource(path) + var directory: ObjCBool = false + guard FileManager.default.fileExists(atPath: target.path, isDirectory: &directory) else { + throw LinkError.missing("resource '\(resourcePath)'", chain) + } + if directory.boolValue { + try view.validateResourceTree(target) + return try LinkedResource( + snapshot: view.snapshot, path: path, + hash: "sha256:" + FileHash.folderHash(target), + executableFlags: FileHash.executableFlags(target)) + } + let info = try FileManager.default.attributesOfItem(atPath: target.path) + return try LinkedResource( + snapshot: view.snapshot, path: path, + hash: "sha256:" + FileHash.sha256Hex(file: target), + executableFlags: [path: ((info[.posixPermissions] as? NSNumber)?.intValue ?? 0) & 0o111 != 0]) + } + + private func append( + key: ComponentKey, snapshot: SourceSnapshotID, pin: SourceRevision? = nil, + payload: LinkedPayload, context: LinkingDocument, + group: String?, condition: DeclarationCondition, recipients: Set, chatGPT: Bool, + resources: [LinkedResource], chain: [SourceSpan], position: SourceMapEntry?, + dependencies: [SourceSnapshotID] + ) throws { + try linking.budget.contribution(chain: chain.count + (position?.origins.count ?? 0)) + let occurrence = nextOccurrence + nextOccurrence += 1 + let provenance = SourceProvenance( + sourceIdentity: context.view.snapshot.source, + revision: context.view.pin?.revision, + artifactDigest: context.view.snapshot.revision.hasPrefix("sha256:") + ? context.view.snapshot.revision : nil, + relativePath: context.manifestPath, format: "Agents.swift", adapterVersion: "1.0", + group: group, referenceChain: chain) + let origin = ContributionOrigin( + occurrence: occurrence, provenance: provenance, + declaration: position?.span, sourceOrigins: position?.origins ?? [], + reference: referenceParent, condition: condition, + recipients: recipients, dependencies: dependencies, consumerEditable: !context.producer) + components.append( + LinkedComponent( + key: key, snapshot: snapshot, pin: pin, payload: payload, + conditions: [condition], recipients: recipients, chatGPT: chatGPT, resources: resources, + origins: [origin])) + } + + func result() throws -> LinkedComponents { + var result: [LinkedComponent] = [] + var byKey: [ComponentKey: [Int]] = [:] + for component in components { + try linking.budget.step() + if component.key.kind != .instructions { + var coalesced = false + for index in byKey[component.key] ?? [] { + try linking.budget.step() + let prior = result[index] + let same = + prior.payload.sameContent(as: component.payload) + && prior.resources == component.resources + && prior.snapshot == component.snapshot && prior.pin == component.pin + if same, [.hook, .permissions].contains(component.key.kind) { + result[index].origins += component.origins + result[index].recipients.formUnion(component.recipients) + for condition in component.conditions + where !result[index].conditions.contains(condition) { + result[index].conditions.append(condition) + } + coalesced = true + break + } + if !same, + !prior.recipients.isDisjoint(with: component.recipients) + || (prior.chatGPT && component.chatGPT) + { + throw LinkError.conflict(component.key, prior.origins + component.origins) + } + } + if coalesced { continue } + } + byKey[component.key, default: []].append(result.count) + result.append(component) + } + let snapshots = Set( + result.flatMap { component in + [component.snapshot] + component.resources.map(\.snapshot) + + component.origins.flatMap(\.dependencies) + } + references.map(\.snapshot)) + return LinkedComponents( + components: result, references: references, + constraints: constraints.keys.sorted().flatMap { constraints[$0]! }, + selections: choices.filter { constraints[$0.key] != nil }, + sourceSnapshots: linking.session.sourceEvidence(for: snapshots)) + } +} diff --git a/Sources/Components/LinkBudget.swift b/Sources/Components/LinkBudget.swift new file mode 100644 index 0000000..0a93a45 --- /dev/null +++ b/Sources/Components/LinkBudget.swift @@ -0,0 +1,39 @@ +import AgentsCore +import Foundation + +/// Spent work belongs to the whole search, including rejected candidates and repeated paths. +final class LinkBudget { + private var steps = 0 + private var snapshots = Set() + private struct Manifest: Hashable { + let snapshot: SourceSnapshotID + let path: String + } + private var manifests = Set() + private var bytes = 0 + private var contributions = 0 + + func step(_ count: Int = 1) throws { + try Task.checkCancellation() + steps += count + guard steps <= 1_000_000 else { throw LinkError.budget("resolution/evaluation steps") } + } + + func snapshot(_ value: SourceSnapshotID) throws { + try step() + snapshots.insert(value) + guard snapshots.count <= 256 else { throw LinkError.budget("distinct snapshots") } + } + + func manifest(_ snapshot: SourceSnapshotID, path: String, bytes count: Int) throws { + try step() + if manifests.insert(Manifest(snapshot: snapshot, path: path)).inserted { bytes += count } + guard bytes <= 16_777_216 else { throw LinkError.budget("aggregate manifest bytes") } + } + + func contribution(chain: Int) throws { + try step(1 + chain) + contributions += 1 + guard contributions <= 10_000 else { throw LinkError.budget("contribution occurrences") } + } +} diff --git a/Sources/Components/LinkedComponents.swift b/Sources/Components/LinkedComponents.swift new file mode 100644 index 0000000..bbe1932 --- /dev/null +++ b/Sources/Components/LinkedComponents.swift @@ -0,0 +1,179 @@ +import AgentsCore +import AgentsInstructions +import AgentsSkills +import Foundation + +/// Revision-independent, producer-qualified component identity. Roots remain separate namespaces. +package struct ComponentKey: Hashable, Sendable { + package let source: String + package let root: String + package let group: String? + package let kind: DeclaredComponentKind + package let name: String +} + +/// Exact, relative resource evidence. URLs used while reading never enter this value. +package struct LinkedResource: Equatable, Sendable { + package let snapshot: SourceSnapshotID + package let path: String + package let hash: String + package let executableFlags: [String: Bool] + package let artifact: LockedArtifact? + + package init( + snapshot: SourceSnapshotID, path: String, hash: String, + executableFlags: [String: Bool], artifact: LockedArtifact? = nil + ) { + self.snapshot = snapshot + self.path = path + self.hash = hash + self.executableFlags = executableFlags + self.artifact = artifact + } +} + +package enum LinkedPayload: Equatable, Sendable { + case declaration(ComponentDeclaration) + case skill(SnapshotSkill, mode: InstallMode, native: NativeConfiguration) + case instruction(SnapshotInstruction, prompt: String?, native: NativeConfiguration) + + func sameContent(as other: Self) -> Bool { + if case .declaration(let lhs) = self, case .declaration(let rhs) = other { + return lhs.comparisonPayload == rhs.comparisonPayload + } + return self == other + } +} + +package struct ContributionOrigin: Equatable, Sendable { + package let occurrence: Int + package let provenance: SourceProvenance + package let declaration: SourceSpan? + package let sourceOrigins: [SourceSpan] + package let reference: Int? + package let condition: DeclarationCondition + package let recipients: Set + /// Source variables traversed to reach this contribution, including resource dependencies. + package let dependencies: [SourceSnapshotID] + package let consumerEditable: Bool +} + +package struct LinkedComponent: Equatable, Sendable { + package let key: ComponentKey + package let snapshot: SourceSnapshotID + package let pin: SourceRevision? + package let payload: LinkedPayload + package var conditions: [DeclarationCondition] + package var recipients: Set + /// ChatGPT is a projection, not an AgentID. Scope/platform constraints still apply. + package let chatGPT: Bool + package let resources: [LinkedResource] + package var origins: [ContributionOrigin] +} + +package struct SourceConstraint: Equatable, Sendable { + package let source: String + package let root: String + package let requirement: SourceRequirement? + package let referenceChain: [SourceSpan] +} + +package struct LinkedReference: Equatable, Sendable { + package let occurrence: Int + package let parent: Int? + package let group: String + package let snapshot: SourceSnapshotID + package let root: String + package let constraint: SourceConstraint? + package let referenceChain: [SourceSpan] +} + +package struct LinkedComponents: Equatable, Sendable { + package let components: [LinkedComponent] + package let references: [LinkedReference] + package let constraints: [SourceConstraint] + package let selections: [String: SourceRevision] + package let sourceSnapshots: [SourceSnapshotEvidence] + + /// A semantic projection protects pins, payloads, resource evidence and effective targets. + /// Reference counts and occurrence numbering do not by themselves change protected content. + package func protectedChanges( + from previous: Self, allowing kinds: Set + ) -> [ComponentKey] { + func protected(_ graph: Self) -> [ComponentKey: [LinkedComponent]] { + Dictionary(grouping: graph.components.filter { !kinds.contains($0.key.kind) }, by: \.key) + } + let before = protected(previous) + let after = protected(self) + return Set(before.keys).union(after.keys).filter { key in + let lhs = before[key] ?? [] + let rhs = after[key] ?? [] + guard lhs.count == rhs.count else { return true } + return zip(lhs, rhs).contains { a, b in + a.snapshot != b.snapshot || a.pin != b.pin || !a.payload.sameContent(as: b.payload) + || a.conditions != b.conditions + || a.recipients != b.recipients || a.chatGPT != b.chatGPT || a.resources != b.resources + || Set(a.origins.flatMap(\.dependencies)) != Set(b.origins.flatMap(\.dependencies)) + } + }.sorted { lhs, rhs in + [lhs.source, lhs.root, lhs.group ?? "", lhs.kind.rawValue, lhs.name] + .lexicographicallyPrecedes( + [rhs.source, rhs.root, rhs.group ?? "", rhs.kind.rawValue, rhs.name]) + } + } + + package func requireEditable(_ key: ComponentKey) throws { + let matches = components.filter { $0.key == key } + guard !matches.isEmpty else { throw LinkError.missing("component: \(key.name)", []) } + for component in matches { + if let origin = component.origins.first(where: { !$0.consumerEditable }) { + throw LinkError.notEditableHere(key, origin.provenance) + } + } + } + + /// Keeps other domains' exact choices when removing constraints or updating direct items. + package func protectedPins(allowing kinds: Set) -> [String: SourceRevision] + { + let protected = Set( + components.filter { !kinds.contains($0.key.kind) } + .flatMap { $0.origins.flatMap(\.dependencies).map(\.source) }) + return selections.filter { protected.contains($0.key) } + } +} + +package enum LinkError: Error, Sendable, CustomStringConvertible { + case missing(String, [SourceSpan]) + case cycle([String], [SourceSpan]) + case incompatible([SourceConstraint]) + case budget(String) + case conflict(ComponentKey, [ContributionOrigin]) + case invalid(String, [SourceSpan]) + case notEditableHere(ComponentKey, SourceProvenance) + + package var description: String { + switch self { + case .missing(let value, let chain): return "Missing \(value)\(Self.locations(chain))" + case .cycle(let groups, let chain): + return "Group cycle: \(groups.joined(separator: " → "))\(Self.locations(chain))" + case .incompatible(let constraints): + return "Incompatible source requirements: " + + constraints.map { + $0.source + " " + String(describing: $0.requirement) + Self.locations($0.referenceChain) + }.joined(separator: "; ") + case .budget(let name): return "Component linking exceeded \(name) budget" + case .conflict(let key, let origins): + return "Conflicting \(key.kind.rawValue) '\(key.name)'" + + Self.locations(origins.flatMap { $0.provenance.referenceChain }) + case .invalid(let reason, let chain): return reason + Self.locations(chain) + case .notEditableHere(let key, let provenance): + return + "notEditableHere: '\(key.name)' is owned by \(provenance.sourceIdentity)/\(provenance.relativePath)" + + Self.locations(provenance.referenceChain) + } + } + + private static func locations(_ spans: [SourceSpan]) -> String { + spans.map { " at \($0.document.rawValue):\($0.line):\($0.column)" }.joined() + } +} diff --git a/Tests/AgentsManifestTests/ExpansionBudgetTests.swift b/Tests/AgentsManifestTests/ExpansionBudgetTests.swift new file mode 100644 index 0000000..879dc7a --- /dev/null +++ b/Tests/AgentsManifestTests/ExpansionBudgetTests.swift @@ -0,0 +1,113 @@ +import AgentsCore +import Testing + +@testable import AgentsManifest + +@Suite("Expanded manifest accounting") +struct ExpansionBudgetTests { + @Test func referenceOriginsChargeTheirOwnDocumentIdentities() throws { + let document = try DeclarationDocument( + bytes: Array( + """ + // agents-tools-version: 1.0 + import AgentsDescription + let agents = Agents(components: [.command(name: "review", description: "Review", prompt: "p")]) + """.utf8), identity: DocumentIdentity("producer")) + let record = try #require(document.declaration.components.first) + let locations = document.sourceMap.entries.filter { + $0.pointer == "/components/0" || $0.pointer.hasPrefix("/components/0/") + } + let origin = SourceSpan( + document: DocumentIdentity(String(repeating: "consumer", count: 5_000)), + start: 0, end: 1, line: 1, column: 1) + var budget = ManifestExpansionBudget() + try budget.consume(record, origins: [origin], locations: locations, spending: { _ in }) + #expect(throws: ManifestExpansionBudget.Failure.self) { + for _ in 0..<100 { + try budget.consume(record, origins: [origin], locations: locations, spending: { _ in }) + } + } + } + + @Test func repeatedLocationsShareTheSourceMapEncodedBudget() throws { + let document = try DeclarationDocument( + bytes: Array( + """ + // agents-tools-version: 1.0 + import AgentsDescription + let agents = Agents(components: [.command(name: "review", description: "Review", prompt: "p")]) + """.utf8), identity: DocumentIdentity(String(repeating: "source", count: 5_000))) + let record = try #require(document.declaration.components.first) + let locations = document.sourceMap.entries.filter { + $0.pointer == "/components/0" || $0.pointer.hasPrefix("/components/0/") + } + var budget = ManifestExpansionBudget() + try budget.consume(record, origins: [], locations: locations, spending: { _ in }) + #expect(throws: ManifestExpansionBudget.Failure.self) { + for _ in 0..<100 { + try budget.consume(record, origins: [], locations: locations, spending: { _ in }) + } + } + } + + @Test func repeatedRecordsAccumulateStringAndOutputCost() throws { + let record = DeclarationRecord( + kind: "command", fields: ["prompt": .string(String(repeating: "p", count: 100_000))]) + var budget = ManifestExpansionBudget() + for _ in 0..<100 { try budget.consume(record, origins: [], locations: [], spending: { _ in }) } + #expect(throws: ManifestExpansionBudget.Failure.self) { + for _ in 0..<100 { + try budget.consume(record, origins: [], locations: [], spending: { _ in }) + } + } + let escaped = DeclarationRecord( + kind: "command", fields: ["prompt": .string(String(repeating: "\0", count: 100_000))]) + var output = ManifestExpansionBudget() + #expect(throws: ManifestExpansionBudget.Failure.self) { + for _ in 0..<100 { + try output.consume(escaped, origins: [], locations: [], spending: { _ in }) + } + } + } + + @Test func collectionsAndInheritedOriginsUseManifestPolicy() throws { + let entries = DeclarationRecord( + kind: "configuration", fields: ["items": .array(Array(repeating: .null, count: 10_001))]) + var budget = ManifestExpansionBudget() + #expect(throws: ManifestExpansionBudget.Failure.self) { + try budget.consume(entries, origins: [], locations: [], spending: { _ in }) + } + let origins = DeclarationRecord(kind: "hook", fields: ["name": .string("h")]) + let span = SourceSpan( + document: DocumentIdentity("producer"), start: 0, end: 1, line: 1, column: 1) + let referenceOrigins = Array(repeating: span, count: 10_000) + var repeated = ManifestExpansionBudget() + #expect(throws: ManifestExpansionBudget.Failure.self) { + for _ in 0..<100 { + try repeated.consume(origins, origins: referenceOrigins, locations: [], spending: { _ in }) + } + } + } + + @Test func traversalWorkIsSpentBeforeFailureAndCancellationPropagates() throws { + let record = DeclarationRecord( + kind: "configuration", fields: ["items": .array(Array(repeating: .null, count: 1_000))]) + var budget = ManifestExpansionBudget() + var didSpend = false + #expect(throws: CancellationError.self) { + try budget.consume(record, origins: [], locations: []) { _ in + didSpend = true + throw CancellationError() + } + } + #expect(didSpend) + didSpend = false + #expect(throws: ManifestExpansionBudget.Failure.self) { + try budget.consume( + DeclarationRecord( + kind: "configuration", fields: ["items": .array(Array(repeating: .null, count: 10_001))]), + origins: [], locations: [], spending: { _ in didSpend = true }) + } + #expect(didSpend) + } +} diff --git a/Tests/ComponentsTests/ImpactTests.swift b/Tests/ComponentsTests/ImpactTests.swift new file mode 100644 index 0000000..a36c1aa --- /dev/null +++ b/Tests/ComponentsTests/ImpactTests.swift @@ -0,0 +1,135 @@ +import AgentsCore +import Components +import Foundation +import Testing + +@Suite("Component targeting and impact", .serialized) +struct ImpactTests { + @Test func conditionsNarrowAndNamedHooksCoalesce() throws { + let fixture = try LinkFixture() + let graph = try fixture.link( + """ + let agents = Agents(defaultAgents: [.claudeCode, .codex], components: [ + .hook(name: "format", event: .afterTool, run: .executable("never-run")), + .hook(name: "format", event: .afterTool, run: .executable("never-run")), + .hook(name: "format", event: .afterTool, run: .executable("different"), condition: .when(agents: [])), + .mcpServer(name: "empty", transport: .stdio("never-run"), agents: []), + .mcpServer(name: "linux", transport: .stdio("never-run"), condition: .when(platforms: [.linux]))]) + """) + #expect(graph.components.count == 4) + #expect(graph.components[0].origins.count == 2) + #expect(graph.components.dropFirst().allSatisfy { $0.recipients.isEmpty }) + #expect(throws: LinkError.self) { + try fixture.link( + """ + let agents = Agents(components: [ + .hook(name: "format", event: .afterTool, run: .executable("one")), + .hook(name: "format", event: .afterTool, run: .executable("two"))]) + """) + } + } + + @Test func directSkillAndInstructionPinsRemainIndependent() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("review", at: repository) + try fixture.instruction("rules", at: repository, own: false) + let firstPin = try fixture.commit(repository, tag: "1.0.0") + let expression = """ + let agents = Agents(sources: [.source(name: "s", path: "\(repository.path)")], components: [ + .skills(source: "s", select: ["review"]), + .instructions(sections: [.section(name: "rules", source: "s")])]) + """ + let before = try fixture.link(expression) + let sectionKey = try #require(before.components.last?.key) + try fixture.write( + "---\ndescription: Changed\n---\n# rules\nChanged\n", to: "instructions/rules.md", + base: repository) + try fixture.write( + "---\nname: review\ndescription: Changed\n---\nChanged\n", to: "skills/review/SKILL.md", + base: repository) + let secondPin = try fixture.commit(repository, tag: "1.1.0") + let after = try fixture.link( + expression, directPins: [sectionKey: try #require(before.components.last?.pin)]) + #expect(after.components[0].snapshot.revision == secondPin) + #expect(after.components[1].snapshot.revision == firstPin) + #expect(after.protectedChanges(from: before, allowing: [.skills]).isEmpty) + let combined = try fixture.link(expression) + #expect(combined.protectedChanges(from: before, allowing: [.skills]) == [sectionKey]) + } + + @Test func sharedTransitivePinChangesAreProtected() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("review", at: repository) + try fixture.manifest( + """ + let agents = Agents(exports: ["skills", "mcp"], groups: [ + .group(name: "skills", components: [.skills(source: ".", select: ["review"])]), + .group(name: "mcp", components: [.mcpServer(name: "server", transport: .stdio("never-run"))])]) + """, at: repository) + let firstPin = try fixture.commit(repository, tag: "1.0.0") + let expression = """ + let agents = Agents(sources: [.source(name: "s", path: "\(repository.path)")], uses: [ + .group(name: "skills", source: "s"), .group(name: "mcp", source: "s")]) + """ + let before = try fixture.link(expression) + try fixture.write("change", to: "unrelated.txt", base: repository) + try fixture.commit(repository, tag: "1.1.0") + let after = try fixture.link(expression) + #expect(after.protectedChanges(from: before, allowing: [.skills]).map(\.name) == ["server"]) + #expect( + before.protectedPins(allowing: [.skills])["local:" + repository.path]?.revision == firstPin) + let preserved = try fixture.link( + expression, preserving: before.protectedPins(allowing: [.skills])) + #expect(preserved.protectedChanges(from: before, allowing: [.skills]).isEmpty) + #expect(throws: LinkError.self) { try after.requireEditable(after.components[0].key) } + } + + @Test func chatGPTUsesScopeAndPlatformProjection() throws { + let fixture = try LinkFixture() + try fixture.instruction( + "rules", at: fixture.project, + restrictions: "agents: []\nscopes: [\"project\"]\nplatforms: [\"macos\"]\n") + let graph = try fixture.link( + """ + let agents = Agents(components: [.instructions(sections: ["rules"], chatGPT: [.prompt(name: "p", sections: ["rules"])])]) + """) + #expect(graph.components[0].recipients.isEmpty) + #expect(!graph.components[0].chatGPT) + #expect(graph.components[1].chatGPT) + } +} + +extension ImpactTests { + @Test func identicalNamedHooksUnionRecipientsAndKeepRestrictionOrigins() throws { + let fixture = try LinkFixture() + let graph = try fixture.link( + """ + let agents = Agents(components: [ + .hook(name: "format", event: .afterTool, run: .executable("never-run"), condition: .when(agents: [.codex])), + .hook(name: "format", event: .afterTool, run: .executable("never-run"), condition: .when(agents: [.claudeCode]))]) + """) + #expect(graph.components.count == 1) + #expect(graph.components[0].recipients == [.codex, .claudeCode]) + try #require(graph.components[0].origins.count == 2) + #expect(graph.components[0].origins[0].recipients == [.codex]) + #expect(graph.components[0].origins[1].recipients == [.claudeCode]) + } +} + +extension ImpactTests { + @Test func resourceAliasSpellingDoesNotChangeProtectedContent() throws { + let fixture = try LinkFixture() + let source = fixture.root.appendingPathComponent("source") + try fixture.write("Review", to: "review.md", base: source) + func expression(_ alias: String) -> String { + "let agents = Agents(sources: [.source(name: \"\(alias)\", path: \"\(source.path)\")], components: [.command(name: \"review\", description: \"Review\", prompt: .file(\"review.md\", source: \"\(alias)\"))])" + } + let before = try fixture.link(expression("old")) + let after = try fixture.link(expression("renamed")) + #expect(after.protectedChanges(from: before, allowing: [.skills]).isEmpty) + } +} diff --git a/Tests/ComponentsTests/LinkBudgetTests.swift b/Tests/ComponentsTests/LinkBudgetTests.swift new file mode 100644 index 0000000..ebb2c17 --- /dev/null +++ b/Tests/ComponentsTests/LinkBudgetTests.swift @@ -0,0 +1,153 @@ +import AgentsCore +import Components +import Foundation +import Testing + +@Suite("Observable component bounds", .serialized) +struct LinkBudgetTests { + @Test func repeatedExportsShareExpandedManifestValueLimits() throws { + let fixture = try LinkFixture() + let producer = fixture.root.appendingPathComponent("expanded-values") + try fixture.initialize(producer) + let prompt = String(repeating: "p", count: 100_000) + try fixture.manifest( + """ + let agents = Agents(exports: ["g"], groups: [.group(name: "g", components: [ + .command(name: "review", description: "Review", prompt: "\(prompt)")])]) + """, at: producer) + try fixture.commit(producer) + func expression(_ count: Int) -> String { + let uses = Array(repeating: ".group(name: \"g\", source: \"p\")", count: count) + .joined(separator: ",") + return + "let agents = Agents(sources: [.source(name: \"p\", path: \"\(producer.path)\")], uses: [\(uses)])" + } + #expect(try fixture.link(expression(100)).components.count == 100) + do { + _ = try fixture.link(expression(200)) + Issue.record("expected aggregate expanded-value limit") + } catch LinkError.budget(let name) { + #expect(name == "expanded manifest values") + } + } + + @Test func repeatedContributionsReachLimitAndRejectOverflow() throws { + let fixture = try LinkFixture() + try fixture.instruction("rules", at: fixture.project) + func expression(overflow: Bool) -> String { + let sections = Array(repeating: "\"rules\"", count: 10_000).joined(separator: ",") + let extra = overflow ? ", .instructions(sections: [\"rules\"])" : "" + return + "let agents = Agents(components: [.instructions(sections: [\(sections)])\(extra)])" + } + #expect(try fixture.link(expression(overflow: false)).components.count == 10_000) + do { + _ = try fixture.link(expression(overflow: true)) + Issue.record("expected occurrence limit") + } catch LinkError.budget(let name) { + #expect(name == "contribution occurrences") + } + } + + @Test func oversizedProducerManifestFailsBeforeParsing() throws { + let fixture = try LinkFixture() + let producer = fixture.root.appendingPathComponent("producer") + try fixture.write( + String(repeating: " ", count: 2_097_153), to: ".agent/Agents.swift", base: producer) + do { + _ = try fixture.link( + "let agents = Agents(sources: [.source(name: \"p\", path: \"\(producer.path)\")], uses: [.group(name: \"g\", source: \"p\")])" + ) + Issue.record("expected input limit") + } catch LinkError.budget(let name) { #expect(name == "manifest input bytes") } + } +} + +extension LinkBudgetTests { + @Test func distinctSnapshotLimitUsesSourceContent() throws { + let fixture = try LinkFixture() + var sources: [String] = [] + var uses: [String] = [] + for index in 0..<257 { + let producer = fixture.root.appendingPathComponent("p\(index)") + try fixture.manifest( + "let agents = Agents(exports: [\"g\"], groups: [.group(name: \"g\")])", at: producer) + sources.append(".source(name: \"p\(index)\", path: \"\(producer.path)\")") + uses.append(".group(name: \"g\", source: \"p\(index)\")") + } + func expression(_ count: Int) -> String { + "let agents = Agents(sources: [\(sources.prefix(count).joined(separator: ","))], uses: [\(uses.prefix(count).joined(separator: ","))])" + } + #expect(try fixture.link(expression(256)).references.count == 256) + do { + _ = try fixture.link(expression(257)) + Issue.record("expected snapshot limit") + } catch LinkError.budget(let name) { #expect(name == "distinct snapshots") } + } + + @Test func qualifiedReferenceDepthIsBounded() throws { + let fixture = try LinkFixture() + for count in [64, 65] { + let producer = fixture.root.appendingPathComponent("depth\(count)") + var directory = producer + for index in 0.. String { + "let agents = Agents(sources: [\(sources.prefix(count).joined(separator: ","))], uses: [\(uses.prefix(count).joined(separator: ","))])" + } + #expect(try fixture.link(expression(8)).references.count == 8) + do { + _ = try fixture.link(expression(9)) + Issue.record("expected aggregate manifest limit") + } catch LinkError.budget(let name) { #expect(name == "aggregate manifest bytes") } + } +} + +extension LinkBudgetTests { + @Test func repeatedReferenceProvenanceConsumesTotalWorkBudget() throws { + let fixture = try LinkFixture() + let groups = (0..<40).map { index in + index == 39 + ? ".group(name: \"g39\")" + : ".group(name: \"g\(index)\", uses: [\"g\(index + 1)\"])" + }.joined(separator: ",") + let uses = Array(repeating: "\"g0\"", count: 1500).joined(separator: ",") + do { + _ = try fixture.link("let agents = Agents(groups: [\(groups)], uses: [\(uses)])") + Issue.record("expected total-work bound for repeated provenance") + } catch LinkError.budget(let name) { #expect(name == "resolution/evaluation steps") } + } +} diff --git a/Tests/ComponentsTests/LinkFixture.swift b/Tests/ComponentsTests/LinkFixture.swift new file mode 100644 index 0000000..56895b6 --- /dev/null +++ b/Tests/ComponentsTests/LinkFixture.swift @@ -0,0 +1,97 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation +import Testing + +final class LinkFixture { + let root: URL + let project: URL + let home: URL + var environment: RuntimeEnvironment { + RuntimeEnvironment(projectDirectory: project, homeDirectory: home, environment: [:]) + } + var store: StateStore { StateStore(scope: .project, environment: environment) } + + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "component-tests-" + UUID().uuidString) + project = root.appendingPathComponent("project") + home = root.appendingPathComponent("home") + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + } + + deinit { + do { try FileManager.default.removeItem(at: root) } catch { Issue.record(error) } + } + + func write(_ text: String, to path: String, base: URL? = nil) throws { + let file = (base ?? root).appendingPathComponent(path) + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: file) + } + + func manifest(_ expression: String, at directory: URL) throws { + try write(Self.text(expression), to: ".agent/Agents.swift", base: directory) + } + + static func text(_ expression: String) -> String { + "// agents-tools-version: 1.0\nimport AgentsDescription\n" + expression + "\n" + } + + func document(_ expression: String) throws -> DeclarationDocument { + try DeclarationDocument( + bytes: Array(Self.text(expression).utf8), identity: DocumentIdentity("consumer/Agents.swift")) + } + + func link( + _ expression: String, preserving pins: [String: SourceRevision] = [:], + directPins: [ComponentKey: SourceRevision] = [:] + ) throws -> LinkedComponents { + try ComponentLinker.withLinkedComponents( + document: document(expression), store: store, + platform: .macOS, preserving: pins, directPins: directPins + ) { graph, _ in graph } + } + + @discardableResult + func git(_ directory: URL, _ arguments: [String]) throws -> String { + try ProcessRunner.run("/usr/bin/env", arguments: ["git", "-C", directory.path] + arguments) + .stdout.trimmingCharacters(in: .whitespacesAndNewlines) + } + + func initialize(_ directory: URL) throws { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try git(directory, ["init", "--initial-branch=main"]) + for (key, value) in [ + ("maintenance.auto", "false"), ("gc.auto", "0"), + ("user.name", "Fixture"), ("user.email", "fixture@example.test"), ("commit.gpgsign", "false"), + ] { + try git(directory, ["config", key, value]) + } + } + + @discardableResult + func commit(_ directory: URL, tag: String? = nil) throws -> String { + try git(directory, ["add", "."]) + try git(directory, ["commit", "-m", "fixture"]) + if let tag { try git(directory, ["tag", tag]) } + return try git(directory, ["rev-parse", "HEAD"]) + } + + func skill(_ name: String, at directory: URL, restrictions: String = "") throws { + try write( + "---\nname: \(name)\ndescription: Fixture skill\n\(restrictions)---\nBody\n", + to: "skills/\(name)/SKILL.md", base: directory) + } + + func instruction(_ name: String, at directory: URL, own: Bool = true, restrictions: String = "") + throws + { + try write( + "---\ndescription: Fixture section\n\(restrictions)---\n# \(name)\nBody\n", + to: (own ? ".agent/instructions/" : "instructions/") + name + ".md", base: directory) + } +} diff --git a/Tests/ComponentsTests/LinkingAcceptanceTests.swift b/Tests/ComponentsTests/LinkingAcceptanceTests.swift new file mode 100644 index 0000000..28a7842 --- /dev/null +++ b/Tests/ComponentsTests/LinkingAcceptanceTests.swift @@ -0,0 +1,361 @@ +import AgentsCore +import AgentsManifest +import AgentsSkills +import Components +import Foundation +import Testing + +@Suite("Component linking acceptance") +struct LinkingAcceptanceTests { + @Test("A later transitive constraint selects an older feasible Git version") + func laterTransitiveConstraintBacktracks() throws { + let fixture = try LinkingFixture() + defer { fixture.remove() } + + let repository = try fixture.gitRepository("a") + try fixture.write( + repository, ".agent/Agents.swift", + manifest( + """ + exports: ["server"], + groups: [ + .group(name: "server", components: [ + .mcpServer( + name: "server", transport: .stdio("server-v1"), agents: [.codex]) + ]) + ] + """)) + let older = try fixture.commit(repository, tag: "1.0.0") + try fixture.write( + repository, ".agent/Agents.swift", + manifest( + """ + exports: ["server"], + groups: [ + .group(name: "server", components: [ + .mcpServer( + name: "server", transport: .stdio("server-v2"), agents: [.codex]) + ]) + ] + """)) + _ = try fixture.commit(repository, tag: "2.0.0") + + let bridge = fixture.root.appendingPathComponent("bridge", isDirectory: true) + try fixture.write( + bridge, ".agent/Agents.swift", + manifest( + """ + exports: ["bridge"], + sources: [.source(name: "a", path: "../a", exact: "1.0.0")], + groups: [ + .group(name: "bridge", uses: [.group(name: "server", source: "a")]) + ] + """)) + let document = try fixture.document( + manifest( + """ + sources: [ + .source(name: "a", path: "../a", from: "1.0.0"), + .source(name: "bridge", path: "../bridge"), + ], + uses: [ + .group(name: "server", source: "a"), + .group(name: "bridge", source: "bridge"), + ] + """)) + + let graph = try fixture.link(document) + let selected = try #require(graph.selections.values.first { $0.revision == older }) + #expect(selected.version == "1.0.0") + #expect(graph.references.map(\.group) == ["server", "bridge", "server"]) + #expect(graph.references[2].parent == graph.references[1].occurrence) + #expect( + graph.constraints.filter { $0.source == graph.references[0].snapshot.source }.count == 2) + let server = try #require(graph.components.first { $0.key.name == "server" }) + let servers = graph.components.filter { $0.key == server.key } + let serverOrigins = servers.flatMap(\.origins) + #expect(servers.allSatisfy { $0.snapshot.revision == older }) + #expect(servers.allSatisfy { $0.recipients == [.codex] }) + #expect(serverOrigins.count == 2) + #expect(Set(serverOrigins.map(\.occurrence)).count == 2) + #expect(serverOrigins.map(\.provenance.referenceChain).allSatisfy { !$0.isEmpty }) + } + + @Test("Diamond references preserve occurrences, producer targeting and ownership") + func diamondOccurrencesAndTargeting() throws { + let fixture = try LinkingFixture() + defer { fixture.remove() } + + let producer = fixture.root.appendingPathComponent("producer", isDirectory: true) + try fixture.write( + producer, ".agent/Agents.swift", + manifest( + """ + defaultAgents: [.claudeCode, .codex], + exports: ["left", "right"], + components: [ + .mcpServer(name: "root-only", transport: .stdio("root-only")) + ], + groups: [ + .group( + name: "leaf", + components: [ + .mcpServer(name: "leaf-server", transport: .stdio("leaf")), + .mcpServer( + name: "empty-server", transport: .stdio("empty"), + condition: .when(agents: [])), + ], + condition: .when(agents: [.codex], scopes: [.project])), + .group(name: "left", uses: ["leaf"]), + .group(name: "right", uses: ["leaf"]), + ] + """)) + let document = try fixture.document( + manifest( + """ + defaultAgents: [.cursor], + sources: [.source(name: "producer", path: "../producer")], + uses: [ + .group(name: "left", source: "producer"), + .group(name: "right", source: "producer"), + .group(name: "left", source: "producer"), + ] + """)) + + let graph = try fixture.link(document) + #expect(graph.references.map(\.group) == ["left", "leaf", "right", "leaf", "left", "leaf"]) + #expect(graph.references[1].parent == graph.references[0].occurrence) + #expect(graph.references[3].parent == graph.references[2].occurrence) + #expect(graph.references[5].parent == graph.references[4].occurrence) + #expect(!graph.components.contains { $0.key.name == "root-only" }) + let leaf = try #require(graph.components.first { $0.key.name == "leaf-server" }) + let leaves = graph.components.filter { $0.key == leaf.key } + let leafOrigins = leaves.flatMap(\.origins) + #expect(leaves.allSatisfy { $0.recipients == [.codex] }) + #expect(leaves.allSatisfy { $0.snapshot == leaf.snapshot }) + #expect(leafOrigins.count == 3) + #expect(Set(leafOrigins.map(\.occurrence)).count == 3) + #expect(leafOrigins.allSatisfy { $0.provenance.referenceChain.count == 2 }) + let empty = try #require(graph.components.first { $0.key.name == "empty-server" }) + #expect(graph.components.filter { $0.key == empty.key }.allSatisfy { $0.recipients.isEmpty }) + do { + try graph.requireEditable(leaf.key) + Issue.record("An imported child must not be editable in the consumer declaration") + } catch let error as LinkError { + guard case .notEditableHere(let key, let provenance) = error else { + Issue.record("Expected notEditableHere, got \(error)") + return + } + #expect(key == leaf.key) + #expect(provenance.relativePath.hasSuffix(".agent/Agents.swift")) + #expect(!provenance.referenceChain.isEmpty) + } + } + + @Test("Protected impact follows actual pins and ignores unrelated root skills") + func protectedImpactAndStablePreparation() throws { + let fixture = try LinkingFixture() + defer { fixture.remove() } + + let repository = try fixture.gitRepository("shared") + let producer = manifest( + """ + exports: ["server", "empty"], + groups: [ + .group(name: "server", components: [ + .mcpServer(name: "shared-server", transport: .stdio("shared"), agents: [.codex]) + ]), + .group(name: "empty"), + ] + """) + try fixture.write(repository, ".agent/Agents.swift", producer) + let older = try fixture.commit(repository, tag: "1.0.0") + try fixture.write(repository, "revision-marker", "second snapshot\n") + let newer = try fixture.commit(repository, tag: "2.0.0") + let skills = fixture.root.appendingPathComponent("skills", isDirectory: true) + try fixture.write( + skills, "draft/SKILL.md", + "---\nname: draft\ndescription: A local draft.\n---\n\n# Draft\n") + + func root(version: String, includeSkill: Bool, includeEmpty: Bool) -> String { + let component = + includeSkill + ? #".skills(source: "drafts", select: ["draft"], mode: .edit, agents: [.codex])"# + : "" + let extra = includeEmpty ? #", .group(name: "empty", source: "shared")"# : "" + return manifest( + """ + sources: [ + .source(name: "shared", path: "../shared", exact: "\(version)"), + .source(name: "drafts", path: "../skills"), + ], + components: [\(component)], + uses: [.group(name: "server", source: "shared")\(extra)] + """) + } + + let initial = try fixture.document( + root(version: "1.0.0", includeSkill: false, includeEmpty: false)) + let withSkill = try fixture.document( + root(version: "1.0.0", includeSkill: true, includeEmpty: false)) + let bookkeeping = try fixture.document( + root(version: "1.0.0", includeSkill: true, includeEmpty: true)) + let changedPin = try fixture.document( + root(version: "2.0.0", includeSkill: true, includeEmpty: false)) + + let beforeFiles = try fixture.inventory() + let first = try fixture.link(initial) + let skillGraph = try fixture.link(withSkill) + let repeated = try fixture.link(withSkill) + let bookkeepingGraph = try fixture.link(bookkeeping) + let changed = try fixture.link(changedPin) + #expect(skillGraph == repeated) + #expect(try fixture.inventory() == beforeFiles) + #expect(skillGraph.protectedChanges(from: first, allowing: [.skills]).isEmpty) + #expect(bookkeepingGraph.protectedChanges(from: skillGraph, allowing: [.skills]).isEmpty) + + let server = try #require(skillGraph.components.first { $0.key.name == "shared-server" }) + #expect(server.snapshot.revision == older) + #expect(changed.components.first { $0.key == server.key }?.snapshot.revision == newer) + #expect(changed.protectedChanges(from: skillGraph, allowing: [.skills]).contains(server.key)) + #expect(skillGraph.protectedPins(allowing: [.skills]).values.contains { $0.revision == older }) + + let draft = try #require(skillGraph.components.first { $0.key.name == "draft" }) + guard case .skill(let skill, let mode, _) = draft.payload else { + Issue.record("Expected the live skill payload") + return + } + #expect(mode == .edit) + #expect(skill.livePath == skills.appendingPathComponent("draft").path) + try fixture.write( + skills, "draft/SKILL.md", + "---\nname: draft\ndescription: A changed local draft.\n---\n\n# Draft\n") + let edited = try fixture.link(withSkill) + let editedDraft = try #require(edited.components.first { $0.key.name == "draft" }) + guard case .skill(let editedSkill, _, _) = editedDraft.payload else { + Issue.record("Expected the edited live skill payload") + return + } + #expect(editedSkill.livePath == skill.livePath) + #expect(editedSkill.hash != skill.hash) + } +} + +private func manifest(_ arguments: String) -> String { + """ + // agents-tools-version: 1.0 + import AgentsDescription + + let agents = Agents( + \(arguments) + ) + """ +} + +private struct LinkingFixture { + let root: URL + let project: URL + let home: URL + + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "linking-acceptance-\(UUID().uuidString)", isDirectory: true) + project = root.appendingPathComponent("project", isDirectory: true) + home = root.appendingPathComponent("home", isDirectory: true) + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + } + + func remove() { + try? FileManager.default.removeItem(at: root) + } + + func write(_ directory: URL, _ path: String, _ contents: String) throws { + let file = directory.appendingPathComponent(path) + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(contents.utf8).write(to: file) + } + + func document(_ text: String) throws -> DeclarationDocument { + try DeclarationDocument( + bytes: Array(text.utf8), identity: DocumentIdentity("consumer/.agent/Agents.swift")) + } + + func link(_ document: DeclarationDocument) throws -> LinkedComponents { + let environment = RuntimeEnvironment( + projectDirectory: project, homeDirectory: home, environment: ["HOME": home.path]) + let store = StateStore(scope: .project, environment: environment) + return try ComponentLinker.withLinkedComponents( + document: document, store: store, platform: .macOS + ) { graph, _ in graph } + } + + func gitRepository(_ name: String) throws -> URL { + let directory = root.appendingPathComponent(name, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + _ = try git(directory, ["init", "--initial-branch=main"]) + _ = try git(directory, ["config", "--local", "user.name", "Fixture"]) + _ = try git(directory, ["config", "--local", "user.email", "fixture@example.invalid"]) + _ = try git(directory, ["config", "--local", "gc.auto", "0"]) + _ = try git(directory, ["config", "--local", "maintenance.auto", "false"]) + return directory + } + + func commit(_ repository: URL, tag: String) throws -> String { + _ = try git(repository, ["add", "."]) + _ = try git(repository, ["commit", "-m", "Fixture \(tag)"]) + _ = try git(repository, ["tag", tag]) + return try git(repository, ["rev-parse", "HEAD"]).trimmingCharacters( + in: .whitespacesAndNewlines) + } + + func git(_ directory: URL, _ arguments: [String]) throws -> String { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/env") + process.arguments = ["git"] + arguments + process.currentDirectoryURL = directory + process.environment = [ + "PATH": "/usr/bin:/bin:/usr/local/bin:/opt/homebrew/bin", + "HOME": home.path, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": "/dev/null", + "GIT_TERMINAL_PROMPT": "0", + "GIT_AUTHOR_DATE": "2001-01-01T00:00:00Z", + "GIT_COMMITTER_DATE": "2001-01-01T00:00:00Z", + ] + let output = Pipe() + process.standardOutput = output + process.standardError = output + try process.run() + let data = output.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw FixtureError.git(arguments, String(decoding: data, as: UTF8.self)) + } + return String(decoding: data, as: UTF8.self) + } + + func inventory() throws -> [String: Data] { + let manager = FileManager.default + guard + let enumerator = manager.enumerator( + at: project, includingPropertiesForKeys: [.isRegularFileKey], options: []) + else { throw FixtureError.inventory } + var files: [String: Data] = [:] + for case let url as URL in enumerator { + let values = try url.resourceValues(forKeys: [.isRegularFileKey]) + if values.isRegularFile == true { + files[String(url.path.dropFirst(project.path.count + 1))] = try Data(contentsOf: url) + } else { + files[String(url.path.dropFirst(project.path.count + 1)) + "/"] = Data() + } + } + return files + } +} + +private enum FixtureError: Error { + case git([String], String) + case inventory +} diff --git a/Tests/ComponentsTests/LinkingTests.swift b/Tests/ComponentsTests/LinkingTests.swift new file mode 100644 index 0000000..d45af28 --- /dev/null +++ b/Tests/ComponentsTests/LinkingTests.swift @@ -0,0 +1,224 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation +import Testing + +@Suite("Component source linking", .serialized) +struct LinkingTests { + @Test func pinnedLocalProducerAliasesUseTheirOriginalDiscoveryEnvironment() throws { + let fixture = try LinkFixture() + let dependency = fixture.root.appendingPathComponent("dependency") + let absoluteDependency = fixture.root.appendingPathComponent("absolute-dependency") + let homeDependency = fixture.home.appendingPathComponent("home-dependency") + for (repository, name) in [ + (dependency, "dependency"), (absoluteDependency, "absolute"), (homeDependency, "home"), + ] { + try fixture.initialize(repository) + try fixture.manifest( + """ + let agents = Agents(exports: ["g"], groups: [.group(name: "g", components: [ + .mcpServer(name: "\(name)", transport: .stdio("never-run"))])]) + """, at: repository) + try fixture.commit(repository, tag: "1.0.0") + } + let older = try fixture.git(dependency, ["rev-parse", "HEAD"]) + try fixture.write("new version", to: "version.txt", base: dependency) + try fixture.commit(dependency, tag: "2.0.0") + let producer = fixture.root.appendingPathComponent("producer") + let discovery = producer.appendingPathComponent("published") + try fixture.initialize(producer) + try fixture.write("pinned prompt", to: "prompt.md", base: discovery) + try fixture.manifest( + """ + let agents = Agents(exports: ["g"], sources: [ + .source(name: "relative", path: "../../dependency", exact: "1.0.0"), + .source(name: "absolute", path: "\(absoluteDependency.path)", exact: "1.0.0"), + .source(name: "home", path: "~/home-dependency", exact: "1.0.0")], + groups: [.group(name: "g", components: [ + .command(name: "review", description: "Review", prompt: .file("prompt.md"))], + uses: [.group(name: "g", source: "relative"), + .group(name: "g", source: "absolute"), .group(name: "g", source: "home")])]) + """, at: discovery) + let producerPin = try fixture.commit(producer, tag: "1.0.0") + try fixture.write("live prompt shadow", to: "prompt.md", base: discovery) + let document = try fixture.document( + """ + let agents = Agents(sources: [ + .source(name: "dependency", path: "\(dependency.path)", from: "1.0.0"), + .source(name: "p", path: "\(producer.path)", exact: "1.0.0", subpath: "published")], + uses: [.group(name: "g", source: "dependency"), .group(name: "g", source: "p")]) + """) + func link() throws -> LinkedComponents { + try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + let id = "local:" + dependency.path + #expect(graph.selections[id]?.revision == older) + #expect(graph.constraints.filter { $0.source == id }.count == 2) + #expect(graph.components.filter { $0.key.name == "dependency" }.count == 2) + #expect(graph.references[2].snapshot.source == id) + #expect(graph.references[3].snapshot.source == "local:" + absoluteDependency.path) + #expect(graph.references[4].snapshot.source == "local:" + homeDependency.path) + let command = try #require(graph.components.first { $0.key.name == "review" }) + #expect(command.snapshot.revision == producerPin) + #expect(command.origins[0].provenance.relativePath == "published/.agent/Agents.swift") + let resource = try #require(command.resources.first) + let file = try session.resource(snapshot: resource.snapshot, path: resource.path) + #expect(try String(contentsOf: file, encoding: .utf8) == "pinned prompt") + #expect(!graph.constraints.contains { $0.source.contains("agents-resolution-") }) + return graph + } + } + #expect(try link() == link()) + } + + @Test func orderDiamondsRepeatsAndProducerDefaults() throws { + let fixture = try LinkFixture() + let producer = fixture.root.appendingPathComponent("producer") + try fixture.instruction("section", at: producer) + try fixture.manifest( + """ + let agents = Agents(defaultAgents: [.claudeCode], exports: ["bundle"], + components: [.mcpServer(name: "not-imported", transport: .stdio("never-run"))], + groups: [ + .group(name: "leaf", components: [.instructions(sections: ["section"])]), + .group(name: "left", uses: ["leaf"]), + .group(name: "right", uses: ["leaf"]), + .group(name: "bundle", components: [.mcpServer(name: "first", transport: .stdio("never-run"))], uses: ["left", "right"]) + ]) + """, at: producer) + let expression = """ + let agents = Agents(defaultAgents: [.codex], + sources: [.source(name: "p", path: "\(producer.path)")], + components: [.mcpServer(name: "root", transport: .stdio("never-run"))], + uses: [.group(name: "bundle", source: "p"), .group(name: "bundle", source: "p")]) + """ + let graph = try fixture.link(expression) + #expect( + graph.components.map(\.key.name) == [ + "root", "first", "section", "section", "first", "section", "section", + ]) + #expect(graph.components.dropFirst().allSatisfy { $0.recipients == [.claudeCode] }) + #expect(Set(graph.components.flatMap(\.origins).map(\.occurrence)).count == 7) + #expect(graph.components[2].origins[0].provenance.referenceChain.count == 3) + #expect(graph.references.count == 10) + #expect(throws: LinkError.self) { try graph.requireEditable(graph.components[2].key) } + #expect(try fixture.link(expression) == graph) + #expect( + !FileManager.default.fileExists(atPath: fixture.project.appendingPathComponent(".agent").path) + ) + } + + @Test func crossSourceCycleAndExplicitExports() throws { + let fixture = try LinkFixture() + let producer = fixture.root.appendingPathComponent("producer") + try fixture.manifest( + """ + let agents = Agents(exports: ["loop"], sources: [.source(name: "self", path: ".")], + groups: [.group(name: "loop", uses: [.group(name: "loop", source: "self")])]) + """, at: producer) + #expect(throws: LinkError.self) { + try fixture.link( + "let agents = Agents(sources: [.source(name: \"p\", path: \"\(producer.path)\")], uses: [.group(name: \"loop\", source: \"p\")])" + ) + } + try fixture.manifest("let agents = Agents(groups: [.group(name: \"private\")])", at: producer) + #expect(throws: LinkError.self) { + try fixture.link( + "let agents = Agents(sources: [.source(name: \"p\", path: \"\(producer.path)\")], uses: [.group(name: \"private\", source: \"p\")])" + ) + } + } + + @Test func versionBacktrackingAndFixedBranchEvidence() throws { + let fixture = try LinkFixture() + let dependency = fixture.root.appendingPathComponent("dependency") + try fixture.initialize(dependency) + try fixture.manifest( + "let agents = Agents(exports: [\"d\"], groups: [.group(name: \"d\", components: [.mcpServer(name: \"dep-one\", transport: .stdio(\"never-run\"))])])", + at: dependency) + let depOne = try fixture.commit(dependency, tag: "1.0.0") + try fixture.manifest( + "let agents = Agents(exports: [\"d\"], groups: [.group(name: \"d\", components: [.mcpServer(name: \"dep-two\", transport: .stdio(\"never-run\"))])])", + at: dependency) + try fixture.commit(dependency, tag: "2.0.0") + let producer = fixture.root.appendingPathComponent("producer") + try fixture.initialize(producer) + let url = "file://localhost" + dependency.path + func writeProducer(_ version: String) throws { + try fixture.manifest( + """ + let agents = Agents(exports: ["p"], sources: [.source(name: "d", url: "\(url)", exact: "\(version)")], + groups: [.group(name: "p", uses: [.group(name: "d", source: "d")])]) + """, at: producer) + } + try writeProducer("1.0.0") + let lower = try fixture.commit(producer, tag: "1.0.0") + try writeProducer("2.0.0") + try fixture.commit(producer, tag: "1.1.0") + let graph = try fixture.link( + """ + let agents = Agents(sources: [ + .source(name: "p", path: "\(producer.path)", from: "1.0.0"), + .source(name: "d", url: "\(url)", exact: "1.0.0")], + uses: [.group(name: "p", source: "p"), .group(name: "d", source: "d")]) + """) + #expect(graph.components.map(\.key.name) == ["dep-one", "dep-one"]) + #expect(graph.selections["local:" + producer.path]?.revision == lower) + #expect(graph.selections.values.contains { $0.revision == depOne }) + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } + + @Test func targetingAndLiveEdit() throws { + let fixture = try LinkFixture() + let source = fixture.root.appendingPathComponent("skills") + try fixture.skill( + "review", at: source, + restrictions: "agents: [claude-code]\nscopes: [project]\nplatforms: [macos]\n") + let graph = try fixture.link( + """ + let agents = Agents(defaultAgents: [.codex], sources: [.source(name: "s", path: "\(source.path)")], + components: [.skills(source: "s", select: ["review"], mode: .edit, + overrides: [.skill(name: "review", agents: [.claudeCode, .codex])])]) + """) + let component = try #require(graph.components.first) + #expect(component.recipients == [.claudeCode]) + guard case .skill(let skill, .edit, _) = component.payload else { + Issue.record("expected live skill") + return + } + #expect(skill.livePath == source.appendingPathComponent("skills/review").path) + try fixture.skill("review", at: source, restrictions: "agents: wrong\n") + #expect(throws: (any Error).self) { + try fixture.link( + "let agents = Agents(sources: [.source(name: \"s\", path: \"\(source.path)\")], components: [.skills(source: \"s\")])" + ) + } + } +} + +extension LinkingTests { + @Test func packageResourcesShareTheExportSourceVariable() throws { + let fixture = try LinkFixture() + let dependency = fixture.root.appendingPathComponent("dependency") + try fixture.initialize(dependency) + try fixture.write("old", to: "prompt.md", base: dependency) + try fixture.manifest( + "let agents = Agents(exports: [\"d\"], groups: [.group(name: \"d\")])", at: dependency) + let first = try fixture.commit(dependency, tag: "1.0.0") + try fixture.write("new", to: "prompt.md", base: dependency) + try fixture.commit(dependency, tag: "1.1.0") + let producer = fixture.root.appendingPathComponent("producer") + try fixture.manifest( + """ + let agents = Agents(exports: ["tools"], sources: [.source(name: "r", url: "file://localhost\(dependency.path)", from: "1.0.0")], groups: [.group(name: "tools", components: [.command(name: "review", description: "Review", prompt: .file("prompt.md", source: "r"))])]) + """, at: producer) + let graph = try fixture.link( + """ + let agents = Agents(sources: [.source(name: "p", path: "\(producer.path)"), .source(name: "d", url: "file://localhost\(dependency.path)", exact: "1.0.0")], uses: [.group(name: "tools", source: "p"), .group(name: "d", source: "d")]) + """) + #expect(graph.components.first?.resources.first?.snapshot.revision == first) + #expect(graph.constraints.filter { $0.source.hasPrefix("localhost/") }.count == 2) + } +} diff --git a/Tests/ComponentsTests/SnapshotTests.swift b/Tests/ComponentsTests/SnapshotTests.swift new file mode 100644 index 0000000..3545574 --- /dev/null +++ b/Tests/ComponentsTests/SnapshotTests.swift @@ -0,0 +1,309 @@ +import AgentsCore +import AgentsManifest +import AgentsSkills +import Components +import Foundation +import Testing + +@Suite("Exact component snapshots", .serialized) +struct SnapshotTests { + @Test func frozenCatalogAndScopedLifetime() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("one", at: repository) + let first = try fixture.commit(repository, tag: "1.0.0") + let source = SourceDeclaration(kind: .local, location: repository.path) + var borrowed: URL? + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let candidates = try session.candidates(for: source, requirements: [nil]) + #expect(candidates.first?.revision == first) + try fixture.skill("two", at: repository) + try fixture.commit(repository, tag: "1.1.0") + #expect(try session.candidates(for: source, requirements: [nil]) == candidates) + let snapshot = try session.snapshot(source, at: candidates[0]) + var otherHome = source + otherHome.environment = SourceEnvironment( + projectDirectory: fixture.project, + homeDirectory: fixture.root.appendingPathComponent("other-home")) + let otherView = try session.snapshot(otherHome, at: candidates[0]) + #expect(otherView.localEnvironment?.homeDirectory == otherHome.environment?.homeDirectory) + #expect(otherView.localEnvironment?.projectDirectory.path == repository.path) + borrowed = snapshot.root + #expect(try SkillSnapshotReader.read(snapshot).map(\.name) == ["one"]) + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } + #expect(!FileManager.default.fileExists(atPath: try #require(borrowed).path)) + } + + @Test func cachedExactPinAndErrorCleanup() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("one", at: repository) + let pin = try fixture.commit(repository) + let source = SourceDeclaration( + kind: .local, location: repository.path, requirement: .revision(pin)) + let cache = SourceCache(store: fixture.store) + _ = try cache.resolve(source) + let before = try FileHash.folderHash(fixture.store.cacheDirectory) + try FileManager.default.removeItem(at: repository) + var borrowed: URL? + enum Stop: Error { case reading } + #expect(throws: Stop.self) { + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + #expect( + try session.candidates(for: source, requirements: [source.requirement]).first?.revision + == pin) + let snapshot = try session.snapshot(source, at: SourceRevision(revision: pin)) + #expect(snapshot.localEnvironment?.projectDirectory.path == repository.path) + #expect(snapshot.liveRoot == nil) + borrowed = snapshot.root + #expect(try SkillSnapshotReader.read(snapshot).first?.name == "one") + throw Stop.reading + } + } + #expect(!FileManager.default.fileExists(atPath: try #require(borrowed).path)) + #expect(try FileHash.folderHash(fixture.store.cacheDirectory) == before) + } + + @Test func remoteContainedSkillsRejectEditAndEscapingLinks() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("one", at: repository) + try fixture.manifest( + """ + let agents = Agents(exports: ["tools"], groups: [.group(name: "tools", components: [.skills(source: ".", mode: .edit)])]) + """, at: repository) + try fixture.commit(repository) + do { + _ = try fixture.link( + """ + let agents = Agents(sources: [.source(name: "p", url: "file://localhost\(repository.path)")], uses: [.group(name: "tools", source: "p")]) + """) + Issue.record("expected immutable edit rejection") + } catch LinkError.invalid(_, let positions) { + #expect(!positions.isEmpty) + } + let outside = fixture.root.appendingPathComponent("outside") + try fixture.write("outside", to: "outside") + try FileManager.default.createSymbolicLink( + at: repository.appendingPathComponent("escape"), withDestinationURL: outside) + try fixture.commit(repository) + #expect(throws: (any Error).self) { + try fixture.link( + """ + let agents = Agents(sources: [.source(name: "p", url: "file://localhost\(repository.path)")], uses: [.group(name: "tools", source: "p")]) + """) + } + } + + @Test func remoteProducerLocalAliasesRemainImmutableAndContained() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("remote") + try fixture.initialize(repository) + try fixture.manifest( + "let agents = Agents(exports: [\"leaf\"], groups: [.group(name: \"leaf\", components: [.mcpServer(name: \"leaf\", transport: .stdio(\"never-run\"))])])", + at: repository.appendingPathComponent("child")) + func producer(path: String, requirement: String = "") throws { + try fixture.manifest( + """ + let agents = Agents(exports: ["g"], sources: [ + .source(name: "child", path: "\(path)"\(requirement))], groups: [ + .group(name: "g", uses: [.group(name: "leaf", source: "child")])]) + """, at: repository) + try fixture.commit(repository) + } + let expression = + "let agents = Agents(sources: [.source(name: \"p\", url: \"file://localhost\(repository.path)\")], uses: [.group(name: \"g\", source: \"p\")])" + try producer(path: "child") + let graph = try fixture.link(expression) + #expect(graph.components.first?.key.name == "leaf") + #expect(graph.components.first?.snapshot.source.contains(":contained:") == true) + #expect(graph.references[0].snapshot.revision == graph.references[1].snapshot.revision) + for path in ["../outside", fixture.project.path, "~/outside"] { + try producer(path: path) + #expect(throws: (any Error).self) { try fixture.link(expression) } + } + try producer(path: "child", requirement: ", exact: \"1.0.0\"") + #expect(throws: LinkError.self) { try fixture.link(expression) } + try FileManager.default.createSymbolicLink( + at: repository.appendingPathComponent("escape"), withDestinationURL: fixture.project) + try producer(path: "escape") + #expect(throws: (any Error).self) { try fixture.link(expression) } + } +} + +extension SnapshotTests { + @Test func cancellationCleansOwnedSnapshots() async throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.skill("one", at: repository) + let store = fixture.store + let source = SourceDeclaration(kind: .local, location: repository.path) + let task = Task.detached { () throws -> URL in + var path: URL? + do { + try SourceResolutionSession.withTemporaryRead(store: store) { session in + path = try session.localSnapshot(source).root + withUnsafeCurrentTask { $0?.cancel() } + } + } catch is CancellationError { + return path! + } + throw CoreError.invalidState("expected cooperative cancellation") + } + let borrowed = try await task.value + #expect(!FileManager.default.fileExists(atPath: borrowed.path)) + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } + + @Test func namespacesShareVersionWithoutSharingMembers() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + for name in ["a", "b"] { + let directory = repository.appendingPathComponent(name) + try fixture.manifest( + "let agents = Agents(exports: [\"tools\"], groups: [.group(name: \"tools\", components: [.mcpServer(name: \"\(name)\", transport: .stdio(\"never-run\"))])])", + at: directory) + } + let commit = try fixture.commit(repository) + var sources: [String] = [] + for name in ["a", "b"] { + let producer = fixture.root.appendingPathComponent("producer-" + name) + try fixture.manifest( + """ + let agents = Agents(exports: ["tools"], sources: [.source(name: "s", url: "file://localhost\(repository.path)", subpath: "\(name)")], groups: [.group(name: "tools", uses: [.group(name: "tools", source: "s")])]) + """, at: producer) + sources.append(".source(name: \"\(name)\", path: \"\(producer.path)\")") + } + let graph = try fixture.link( + "let agents = Agents(sources: [\(sources.joined(separator: ","))], uses: [.group(name: \"tools\", source: \"a\"), .group(name: \"tools\", source: \"b\")])" + ) + #expect(graph.components.map(\.key.name) == ["a", "b"]) + #expect(graph.components.map(\.key.root) == ["a", "b"]) + #expect(graph.components.allSatisfy { $0.snapshot.revision == commit }) + #expect(graph.selections.count == 1) + } +} + +extension SnapshotTests { + @Test func branchRevisionAndVersionConstraintsUseOneAllowedTag() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.write("one", to: "file", base: repository) + let first = try fixture.commit(repository) + try fixture.git(repository, ["tag", "-a", "1.0.0+first", "-m", "tag"]) + try fixture.git(repository, ["tag", "1.0.0+second"]) + let source = SourceDeclaration(kind: .local, location: repository.path) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let mixed: [SourceRequirement?] = [ + .branch("main"), .revision("refs/tags/1.0.0+first"), .upToNextMajor(from: "1.0.0"), + ] + #expect(try session.candidates(for: source, requirements: mixed).first?.revision == first) + #expect( + try session.candidates(for: source, requirements: mixed).first?.version == "1.0.0+second") + #expect( + try session.candidates( + for: source, requirements: [.exact("1.0.0+first"), .exact("1.0.0+second")] + ).isEmpty) + try fixture.write("two", to: "file", base: repository) + try fixture.commit(repository) + // Branch evidence remains fixed after the source advances. + #expect(try session.candidates(for: source, requirements: mixed).first?.revision == first) + } + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session throws -> Void in + #expect( + try session.candidates( + for: source, + requirements: [.branch("main"), .revision(first), .upToNextMajor(from: "1.0.0")] + ).isEmpty) + } + } +} + +extension SnapshotTests { + @Test func missingPersistentMirrorLockIsNotRecreated() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("one", at: repository) + let pin = try fixture.commit(repository) + let source = SourceDeclaration( + kind: .local, location: repository.path, requirement: .revision(pin)) + let cache = SourceCache(store: fixture.store) + _ = try cache.resolve(source) + let locks = fixture.store.cacheDirectory.appendingPathComponent("locks") + for lock in try FileManager.default.contentsOfDirectory( + at: locks, includingPropertiesForKeys: nil) + { + try FileManager.default.removeItem(at: lock) + } + let before = try FileHash.folderHash(fixture.store.cacheDirectory) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let view = try session.snapshot(source, at: SourceRevision(revision: pin)) + #expect(try SkillSnapshotReader.read(view).map(\.name) == ["one"]) + } + #expect(try FileHash.folderHash(fixture.store.cacheDirectory) == before) + #expect(try FileManager.default.contentsOfDirectory(atPath: locks.path).isEmpty) + } + + @Test func resourceEvidenceRemainsReadableOnlyDuringSession() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.write("Prompt bytes", to: "prompts/review.md", base: repository) + try fixture.manifest( + """ + let agents = Agents(exports: ["tools"], groups: [.group(name: "tools", components: [.command(name: "review", description: "Review", prompt: .file("prompts/review.md"))])]) + """, at: repository) + let pin = try fixture.commit(repository, tag: "1.0.0") + let document = try fixture.document( + "let agents = Agents(sources: [.source(name: \"p\", path: \"\(repository.path)\")], uses: [.group(name: \"tools\", source: \"p\")])" + ) + var borrowed: URL? + let graph = try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + let resource = try #require(graph.components.first?.resources.first) + let path = try session.resource(snapshot: resource.snapshot, path: resource.path) + borrowed = path + #expect(try String(contentsOf: path, encoding: .utf8) == "Prompt bytes") + #expect(graph.components.first?.pin?.revision == pin) + #expect(graph.components.first?.pin?.version == "1.0.0") + #expect( + graph.sourceSnapshots.contains { + $0.snapshot == resource.snapshot && $0.source?.kind == .local + }) + return graph + } + #expect(!graph.sourceSnapshots.isEmpty) + #expect(!FileManager.default.fileExists(atPath: try #require(borrowed).path)) + } +} + +extension SnapshotTests { + @Test func ownPackageSkillsUseCommittedContentAndLiveEdit() throws { + let fixture = try LinkFixture() + try fixture.initialize(fixture.project) + try fixture.skill("one", at: fixture.project) + let pin = try fixture.commit(fixture.project) + try fixture.skill("two", at: fixture.project) + let linked = try fixture.link("let agents = Agents(components: [.skills(source: \".\")])") + #expect(linked.components.map(\.key.name) == ["one"]) + #expect(linked.components[0].pin?.revision == pin) + let edited = try fixture.link( + "let agents = Agents(components: [.skills(source: \".\", mode: .edit)])") + #expect(edited.components.map(\.key.name) == ["one", "two"]) + for component in edited.components { + guard case .skill(let skill, .edit, _) = component.payload else { + Issue.record("expected edit") + continue + } + #expect(skill.livePath?.hasPrefix(fixture.project.path) == true) + } + } +} diff --git a/Tests/ComponentsTests/UserScopeTests.swift b/Tests/ComponentsTests/UserScopeTests.swift new file mode 100644 index 0000000..5c20837 --- /dev/null +++ b/Tests/ComponentsTests/UserScopeTests.swift @@ -0,0 +1,148 @@ +import AgentsCore +import Components +import Foundation +import Testing + +@Suite("User package linking", .serialized) +struct UserScopeTests { + @Test func packageResourcesAndSelfSkillsUseStateRootWithStableProvenance() throws { + let fixture = try LinkFixture() + let store = StateStore(scope: .user, environment: fixture.environment) + for (directory, value) in [ + (fixture.project, "project shadow"), (fixture.home, "home shadow"), + (store.directory, "package content"), + ] { + try fixture.write(value, to: "prompt.md", base: directory) + try fixture.write(value, to: "tools/run", base: directory) + try fixture.skill(value.replacingOccurrences(of: " ", with: "-"), at: directory) + } + let document = try fixture.document( + """ + let agents = Agents(defaultAgents: [.codex], components: [ + .command(name: "review", description: "Review", prompt: .file("prompt.md")), + .hook(name: "run", event: .afterTool, run: .executable("tools/run")), + .skills(source: ".", mode: .edit)]) + """) + func link() throws -> LinkedComponents { + try ComponentLinker.withLinkedComponents(document: document, store: store, platform: .macOS) { + graph, session in + #expect(graph.components.map(\.key.name) == ["review", "run", "package-content"]) + for component in graph.components { + #expect(component.recipients == [.codex]) + let provenance = try #require(component.origins.first?.provenance) + #expect(provenance.sourceIdentity == "local:" + store.directory.path) + #expect(provenance.relativePath == "Agents.swift") + } + for component in graph.components.prefix(2) { + let resource = try #require(component.resources.first) + let file = try session.resource(snapshot: resource.snapshot, path: resource.path) + #expect(try String(contentsOf: file, encoding: .utf8) == "package content") + #expect(resource.snapshot.source == "local:" + store.directory.path) + } + guard case .skill(let skill, .edit, _) = graph.components[2].payload else { + Issue.record("expected live self-package skill") + return graph + } + #expect( + skill.livePath == store.directory.appendingPathComponent("skills/package-content").path) + return graph + } + } + #expect(try link() == link()) + } + + @Test func namedSourcesKeepDeclaringEnvironmentAndPromptAppendUsesHome() throws { + let fixture = try LinkFixture() + let store = StateStore(scope: .user, environment: fixture.environment) + let source = fixture.project.appendingPathComponent("rules") + try fixture.initialize(source) + try fixture.instruction("rules", at: source, own: false, restrictions: "scopes: [\"user\"]\n") + try fixture.commit(source) + for directory in [fixture.home, store.directory] { + try fixture.instruction("shadow", at: directory.appendingPathComponent("rules"), own: false) + } + for (directory, value) in [ + (fixture.project, "project append shadow"), (store.directory, "package append shadow"), + (fixture.home, "home append"), + ] { + try fixture.write(value, to: "append.md", base: directory) + } + let document = try fixture.document( + """ + let agents = Agents(sources: [.source(name: "rules", path: "rules")], components: [ + .instructions(sections: [.section(name: "rules", source: "rules")], + chatGPT: [.prompt(name: "p", sections: [.section(name: "rules", source: "rules")], append: "append.md")])]) + """) + try ComponentLinker.withLinkedComponents(document: document, store: store, platform: .macOS) { + graph, session in + #expect(graph.components.map(\.key.name) == ["rules", "rules"]) + #expect(graph.components[0].snapshot.source == "local:" + source.path) + #expect(graph.components[1].chatGPT) + let append = try #require(graph.components[1].resources.last) + let file = try session.resource(snapshot: append.snapshot, path: append.path) + #expect(try String(contentsOf: file, encoding: .utf8) == "home append") + #expect(append.snapshot.source == "local:" + fixture.home.path) + #expect(append.path == "append.md") + #expect(graph.components[1].origins[0].dependencies.contains(append.snapshot)) + #expect(graph.components[1].origins[0].provenance.relativePath == "Agents.swift") + } + } + + @Test func rootOwnSectionsRequireNamedSourcesAndProducerOwnSectionsRemainValid() throws { + let fixture = try LinkFixture() + let store = StateStore(scope: .user, environment: fixture.environment) + for directory in [fixture.project, fixture.home, store.directory] { + try fixture.instruction("rules", at: directory) + } + for section in ["\"rules\"", ".section(name: \"rules\", source: \".\")"] { + for selection in [ + ".instructions(sections: [\(section)])", + ".instructions(chatGPT: [.prompt(name: \"p\", sections: [\(section)])])", + ] { + do { + _ = try ComponentLinker.withLinkedComponents( + document: fixture.document("let agents = Agents(components: [\(selection)])"), + store: store, platform: .macOS + ) { _, _ in Issue.record("expected named-source requirement") } + } catch LinkError.invalid(let message, let spans) { + #expect(message == "root user instructions require a named source") + #expect(!spans.isEmpty) + } + } + } + let producer = fixture.project.appendingPathComponent("producer") + try fixture.initialize(producer) + try fixture.instruction("producer", at: producer) + try fixture.write("producer append shadow", to: "append.md", base: producer) + try fixture.write("package append shadow", to: "append.md", base: store.directory) + try fixture.write("home append", to: "append.md", base: fixture.home) + try fixture.manifest( + """ + let agents = Agents(defaultAgents: [.claudeCode], exports: ["g"], groups: [ + .group(name: "g", components: [.instructions(sections: ["producer"], + chatGPT: [.prompt(name: "p", sections: ["producer"], append: "append.md")])])]) + """, at: producer) + let pin = try fixture.commit(producer) + try ComponentLinker.withLinkedComponents( + document: fixture.document( + "let agents = Agents(sources: [.source(name: \"p\", path: \"producer\")], uses: [.group(name: \"g\", source: \"p\")])" + ), store: store, platform: .macOS + ) { graph, session in + let component = try #require(graph.components.first) + #expect(component.key.name == "producer") + #expect(component.snapshot.revision == pin) + #expect(component.recipients == [.claudeCode]) + #expect(component.origins[0].provenance.sourceIdentity == "local:" + producer.path) + #expect(component.origins[0].provenance.relativePath == ".agent/Agents.swift") + #expect(!component.origins[0].consumerEditable) + let prompt = try #require(graph.components.last) + #expect(prompt.chatGPT) + #expect(prompt.snapshot == component.snapshot) + #expect(prompt.origins[0].provenance == component.origins[0].provenance) + let append = try #require(prompt.resources.last) + let file = try session.resource(snapshot: append.snapshot, path: append.path) + #expect(try String(contentsOf: file, encoding: .utf8) == "home append") + #expect(append.snapshot.source == "local:" + fixture.home.path) + } + } +} From e0bc7c06e5c47bf59bb0b40070ee7a5653436b81 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 7 Nov 2026 04:11:43 +0800 Subject: [PATCH 038/171] fix: preserve component conflicts and protected ordering --- Sources/Components/Expansion.swift | 31 ++-- Sources/Components/LinkedComponents.swift | 64 ++++++-- Tests/ComponentsTests/ImpactTests.swift | 62 +++++++ Tests/ComponentsTests/LinkBudgetTests.swift | 51 ++++++ .../LinkingReviewRegressionTests.swift | 153 ++++++++++++++++++ 5 files changed, 338 insertions(+), 23 deletions(-) create mode 100644 Tests/ComponentsTests/LinkingReviewRegressionTests.swift diff --git a/Sources/Components/Expansion.swift b/Sources/Components/Expansion.swift index 1710f05..c862b4c 100644 --- a/Sources/Components/Expansion.swift +++ b/Sources/Components/Expansion.swift @@ -244,15 +244,21 @@ final class Expansion { { if let contained = address.contained { if live, let root = contained.liveRoot { - return try linking.session.liveSnapshot( + let view = try linking.session.liveSnapshot( SourceDeclaration( kind: .local, location: root.path, path: contained.discoveryPath)) + try linking.budget.snapshot(view.snapshot) + return view } return contained } let source = address.source! - if live { return try linking.session.liveSnapshot(source) } + if live { + let view = try linking.session.liveSnapshot(source) + try linking.budget.snapshot(view.snapshot) + return view + } if let key, let preserved = linking.directPins[key] { return try linking.view(address, pin: preserved)! } @@ -536,7 +542,7 @@ final class Expansion { for component in components { try linking.budget.step() if component.key.kind != .instructions { - var coalesced = false + var identical: Int? for index in byKey[component.key] ?? [] { try linking.budget.step() let prior = result[index] @@ -545,14 +551,7 @@ final class Expansion { && prior.resources == component.resources && prior.snapshot == component.snapshot && prior.pin == component.pin if same, [.hook, .permissions].contains(component.key.kind) { - result[index].origins += component.origins - result[index].recipients.formUnion(component.recipients) - for condition in component.conditions - where !result[index].conditions.contains(condition) { - result[index].conditions.append(condition) - } - coalesced = true - break + identical = index } if !same, !prior.recipients.isDisjoint(with: component.recipients) @@ -561,7 +560,15 @@ final class Expansion { throw LinkError.conflict(component.key, prior.origins + component.origins) } } - if coalesced { continue } + if let index = identical { + result[index].origins += component.origins + result[index].recipients.formUnion(component.recipients) + for condition in component.conditions + where !result[index].conditions.contains(condition) { + result[index].conditions.append(condition) + } + continue + } } byKey[component.key, default: []].append(result.count) result.append(component) diff --git a/Sources/Components/LinkedComponents.swift b/Sources/Components/LinkedComponents.swift index bbe1932..dec49c7 100644 --- a/Sources/Components/LinkedComponents.swift +++ b/Sources/Components/LinkedComponents.swift @@ -96,26 +96,68 @@ package struct LinkedComponents: Equatable, Sendable { package let sourceSnapshots: [SourceSnapshotEvidence] /// A semantic projection protects pins, payloads, resource evidence and effective targets. - /// Reference counts and occurrence numbering do not by themselves change protected content. + /// Instructions retain order within each recipient or named prompt. Reference counts and + /// occurrence numbering do not by themselves change protected content. package func protectedChanges( from previous: Self, allowing kinds: Set ) -> [ComponentKey] { func protected(_ graph: Self) -> [ComponentKey: [LinkedComponent]] { - Dictionary(grouping: graph.components.filter { !kinds.contains($0.key.kind) }, by: \.key) + Dictionary( + grouping: graph.components.filter { + $0.key.kind != .instructions && !kinds.contains($0.key.kind) + }, by: \.key) } - let before = protected(previous) - let after = protected(self) - return Set(before.keys).union(after.keys).filter { key in - let lhs = before[key] ?? [] - let rhs = after[key] ?? [] - guard lhs.count == rhs.count else { return true } - return zip(lhs, rhs).contains { a, b in - a.snapshot != b.snapshot || a.pin != b.pin || !a.payload.sameContent(as: b.payload) + var changes = Set() + func compare(_ lhs: [LinkedComponent], _ rhs: [LinkedComponent]) { + for (a, b) in zip(lhs, rhs) { + if a.key != b.key || a.snapshot != b.snapshot || a.pin != b.pin + || !a.payload.sameContent(as: b.payload) || a.conditions != b.conditions || a.recipients != b.recipients || a.chatGPT != b.chatGPT || a.resources != b.resources || Set(a.origins.flatMap(\.dependencies)) != Set(b.origins.flatMap(\.dependencies)) + { + changes.insert(a.key) + changes.insert(b.key) + } + } + for component in lhs.dropFirst(rhs.count) { changes.insert(component.key) } + for component in rhs.dropFirst(lhs.count) { changes.insert(component.key) } + } + let before = protected(previous) + let after = protected(self) + for key in Set(before.keys).union(after.keys) { + compare(before[key] ?? [], after[key] ?? []) + } + if !kinds.contains(.instructions) { + enum Destination: Hashable { + case agent(AgentID) + case prompt(String) + case inactive(ComponentKey) + } + func instructions(_ graph: Self) -> [Destination: [LinkedComponent]] { + var streams: [Destination: [LinkedComponent]] = [:] + for component in graph.components { + guard case .instruction(_, let prompt, _) = component.payload else { continue } + for agent in component.recipients { + streams[.agent(agent), default: []].append(component) + } + if component.chatGPT, let prompt { + streams[.prompt(prompt), default: []].append(component) + } else if component.recipients.isEmpty { + // Inactive declarations still protect their content, without imposing output order + // between unrelated keys. + streams[.inactive(component.key), default: []].append(component) + } + } + return streams } - }.sorted { lhs, rhs in + let before = instructions(previous) + let after = instructions(self) + for destination in Set(before.keys).union(after.keys) { + compare(before[destination] ?? [], after[destination] ?? []) + } + } + return changes.sorted { lhs, rhs in [lhs.source, lhs.root, lhs.group ?? "", lhs.kind.rawValue, lhs.name] .lexicographicallyPrecedes( [rhs.source, rhs.root, rhs.group ?? "", rhs.kind.rawValue, rhs.name]) diff --git a/Tests/ComponentsTests/ImpactTests.swift b/Tests/ComponentsTests/ImpactTests.swift index a36c1aa..3dc71be 100644 --- a/Tests/ComponentsTests/ImpactTests.swift +++ b/Tests/ComponentsTests/ImpactTests.swift @@ -104,6 +104,68 @@ struct ImpactTests { } extension ImpactTests { + @Test(arguments: [false, true]) + func coalescingChecksEveryDifferentPayload(permissions: Bool) throws { + let fixture = try LinkFixture() + func declaration(_ payload: String, _ agent: String) -> String { + let body = + permissions + ? ".permissions(name: \"shared\", rules: [.allow(.read, \"\(payload)/**\")]" + : ".hook(name: \"shared\", event: .afterTool, run: .executable(\"\(payload)\")" + return body + ", condition: .when(agents: [.\(agent)]))" + } + let a = declaration("a", "codex") + let b = declaration("b", "claudeCode") + let c = declaration("a", "claudeCode") + for declarations in [[a, b, c], [b, a, c], [a, c, b]] { + do { + _ = try fixture.link( + "let agents = Agents(components: [\(declarations.joined(separator: ","))])") + Issue.record("expected overlapping different payloads to conflict") + } catch LinkError.conflict(let key, let origins) { + #expect(key.kind == (permissions ? .permissions : .hook)) + #expect(origins.count >= 2) + } + } + } + + @Test(arguments: [false, true]) + func instructionOrderIsProtectedPerDestination(chatGPT: Bool) throws { + let fixture = try LinkFixture() + for name in ["a", "b"] { try fixture.instruction(name, at: fixture.project) } + func expression(_ sections: String) -> String { + let component = + chatGPT + ? ".instructions(chatGPT: [.prompt(name: \"review\", sections: [\(sections)])])" + : ".instructions(sections: [\(sections)], agents: [.codex])" + return "let agents = Agents(components: [\(component)])" + } + let before = try fixture.link(expression("\"a\", \"b\"")) + let after = try fixture.link(expression("\"b\", \"a\"")) + #expect(after.protectedChanges(from: before, allowing: [.skills]).map(\.name) == ["a", "b"]) + #expect(after.protectedChanges(from: before, allowing: [.instructions]).isEmpty) + } + + @Test func unrelatedOrderAndOccurrenceChangesAreNotProtected() throws { + let fixture = try LinkFixture() + try fixture.skill("review", at: fixture.project) + for name in ["a", "b"] { try fixture.instruction(name, at: fixture.project) } + let declarations = [ + ".instructions(sections: [\"a\"], agents: [.codex])", + ".instructions(sections: [\"b\"], agents: [.claudeCode])", + ".instructions(chatGPT: [.prompt(name: \"first\", sections: [\"a\"])])", + ".instructions(chatGPT: [.prompt(name: \"second\", sections: [\"b\"])])", + ".mcpServer(name: \"one\", transport: .stdio(\"never-run\"))", + ".mcpServer(name: \"two\", transport: .stdio(\"never-run\"))", + ] + let before = try fixture.link( + "let agents = Agents(components: [\(declarations.joined(separator: ","))])") + let after = try fixture.link( + "let agents = Agents(components: [.skills(source: \".\", select: [\"review\"], mode: .edit), \(declarations.reversed().joined(separator: ","))])" + ) + #expect(after.protectedChanges(from: before, allowing: [.skills]).isEmpty) + } + @Test func identicalNamedHooksUnionRecipientsAndKeepRestrictionOrigins() throws { let fixture = try LinkFixture() let graph = try fixture.link( diff --git a/Tests/ComponentsTests/LinkBudgetTests.swift b/Tests/ComponentsTests/LinkBudgetTests.swift index ebb2c17..3adaad2 100644 --- a/Tests/ComponentsTests/LinkBudgetTests.swift +++ b/Tests/ComponentsTests/LinkBudgetTests.swift @@ -64,6 +64,30 @@ struct LinkBudgetTests { } extension LinkBudgetTests { + @Test func distinctLiveSnapshotLimitCountsReusedViewsOnce() throws { + let fixture = try LinkFixture() + var sources: [String] = [] + var selections: [String] = [] + for index in 0..<257 { + let source = fixture.root.appendingPathComponent("live\(index)") + try fixture.skill("s\(index)", at: source) + sources.append(".source(name: \"s\(index)\", path: \"\(source.path)\")") + selections.append(".skills(source: \"s\(index)\", select: [\"s\(index)\"], mode: .edit)") + } + func expression(_ count: Int, repeated: Bool = false) -> String { + let selected = Array(selections.prefix(count)) + let components = repeated ? selected + selected : selected + return + "let agents = Agents(sources: [\(sources.prefix(count).joined(separator: ","))], components: [\(components.joined(separator: ","))])" + } + #expect(try fixture.link(expression(256)).sourceSnapshots.count == 256) + #expect(try fixture.link(expression(256, repeated: true)).components.count == 512) + do { + _ = try fixture.link(expression(257)) + Issue.record("expected live snapshot limit") + } catch LinkError.budget(let name) { #expect(name == "distinct snapshots") } + } + @Test func distinctSnapshotLimitUsesSourceContent() throws { let fixture = try LinkFixture() var sources: [String] = [] @@ -85,6 +109,33 @@ extension LinkBudgetTests { } catch LinkError.budget(let name) { #expect(name == "distinct snapshots") } } + @Test func containedLiveSnapshotsShareTheDistinctViewBudget() throws { + let fixture = try LinkFixture() + var sources: [String] = [] + var uses: [String] = [] + for index in 0..<129 { + let producer = fixture.root.appendingPathComponent("producer\(index)") + try fixture.skill("s\(index)", at: producer) + try fixture.manifest( + "let agents = Agents(exports: [\"g\"], groups: [.group(name: \"g\", components: [.skills(source: \".\", select: [\"s\(index)\"], mode: .edit)])])", + at: producer) + sources.append(".source(name: \"p\(index)\", path: \"\(producer.path)\")") + uses.append(".group(name: \"g\", source: \"p\(index)\")") + } + func expression(_ count: Int, repeated: Bool = false) -> String { + let selected = Array(uses.prefix(count)) + let references = repeated ? selected + selected : selected + return + "let agents = Agents(sources: [\(sources.prefix(count).joined(separator: ","))], uses: [\(references.joined(separator: ","))])" + } + #expect(try fixture.link(expression(128)).sourceSnapshots.count == 256) + #expect(try fixture.link(expression(128, repeated: true)).components.count == 256) + do { + _ = try fixture.link(expression(129)) + Issue.record("expected immutable and live views to share the snapshot limit") + } catch LinkError.budget(let name) { #expect(name == "distinct snapshots") } + } + @Test func qualifiedReferenceDepthIsBounded() throws { let fixture = try LinkFixture() for count in [64, 65] { diff --git a/Tests/ComponentsTests/LinkingReviewRegressionTests.swift b/Tests/ComponentsTests/LinkingReviewRegressionTests.swift new file mode 100644 index 0000000..89ca0e6 --- /dev/null +++ b/Tests/ComponentsTests/LinkingReviewRegressionTests.swift @@ -0,0 +1,153 @@ +import AgentsCore +import Components +import Foundation +import Testing + +@Suite("Component linking review regressions") +struct LinkingReviewRegressionTests { + @Test("Coalescing checks every overlapping hook and permission payload") + func coalescingRejectsOverlapInEitherOrder() throws { + let fixture = try LinkFixture() + + for kind in ["hook", "permissions"] { + func component(_ payload: String, _ agent: String) -> String { + if kind == "hook" { + return """ + .hook( + name: "shared", event: .afterTool, run: .executable("\(payload)"), + agents: [.\(agent)]) + """ + } + let rule = payload == "a" ? "allow" : "deny" + return """ + .permissions( + name: "shared", rules: [.\(rule)(.read, "files/**")], + agents: [.\(agent)]) + """ + } + + let aCodex = component("a", "codex") + let bClaude = component("b", "claudeCode") + let aClaude = component("a", "claudeCode") + let disjoint = try fixture.link( + "let agents = Agents(components: [\(aCodex), \(bClaude)])") + #expect(disjoint.components.count == 2) + let identical = try fixture.link( + "let agents = Agents(components: [\(aCodex), \(aClaude)])") + let merged = try #require(identical.components.first) + #expect(identical.components.count == 1) + #expect(merged.recipients == [.codex, .claudeCode]) + #expect(merged.origins.count == 2) + + for components in [ + [aCodex, bClaude, aClaude], + [aCodex, aClaude, bClaude], + ] { + do { + _ = try fixture.link( + "let agents = Agents(components: [\(components.joined(separator: ", "))])") + Issue.record("Expected conflicting \(kind) payloads to be rejected") + } catch let error as LinkError { + guard case .conflict(let key, _) = error else { + Issue.record("Expected a \(kind) conflict, got \(error)") + continue + } + #expect(key.name == "shared") + } + } + } + } + + @Test("Protected instruction order includes ordinary and named prompt sections") + func protectedInstructionOrder() throws { + let fixture = try LinkFixture() + try fixture.instruction("a", at: fixture.project) + try fixture.instruction("b", at: fixture.project) + let drafts = fixture.root.appendingPathComponent("drafts") + try fixture.skill("draft", at: drafts) + + for prompt in [false, true] { + func declaration(_ sections: String, extra: Bool = false) -> String { + let instruction = + prompt + ? #".instructions(chatGPT: [.prompt(name: "review", sections: ["# + sections + "])])" + : ".instructions(sections: [\(sections)], agents: [.codex])" + let skill = + extra + ? #".skills(source: "drafts", select: ["draft"], mode: .edit, agents: [.codex]),"# + : "" + let uses = extra ? #"uses: ["empty"],"# : "" + return """ + let agents = Agents( + sources: [.source(name: "drafts", path: "../drafts")], + components: [\(skill) \(instruction)], + groups: [.group(name: "empty")], + \(uses) + watch: [] + ) + """ + } + + let before = try fixture.link(declaration(#""a", "b""#)) + let after = try fixture.link(declaration(#""b", "a""#)) + let unrelated = try fixture.link(declaration(#""a", "b""#, extra: true)) + let beforeSections = before.components.filter { + $0.key.kind == .instructions && $0.chatGPT == prompt + } + let afterSections = after.components.filter { + $0.key.kind == .instructions && $0.chatGPT == prompt + } + #expect(beforeSections.map(\.key.name) == ["a", "b"]) + #expect(afterSections.map(\.key.name) == ["b", "a"]) + #expect(!after.protectedChanges(from: before, allowing: [.skills]).isEmpty) + #expect(unrelated.protectedChanges(from: before, allowing: [.skills]).isEmpty) + } + } + + @Test("Live edit sources consume the distinct snapshot budget") + func liveEditSnapshotBudget() throws { + let fixture = try LinkFixture() + for index in 0..<257 { + let directory = fixture.root.appendingPathComponent("source-\(index)") + try fixture.skill("skill-\(index)", at: directory) + } + + func declaration(distinct count: Int, repetitions: Int = 1) -> String { + let sources = (0.. Date: Sat, 7 Nov 2026 04:30:50 +0800 Subject: [PATCH 039/171] fix: compare coalesced restrictions by complete clause --- Sources/Components/LinkedComponents.swift | 8 +++- Tests/ComponentsTests/ImpactTests.swift | 46 +++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/Sources/Components/LinkedComponents.swift b/Sources/Components/LinkedComponents.swift index dec49c7..5803ffc 100644 --- a/Sources/Components/LinkedComponents.swift +++ b/Sources/Components/LinkedComponents.swift @@ -110,9 +110,15 @@ package struct LinkedComponents: Equatable, Sendable { var changes = Set() func compare(_ lhs: [LinkedComponent], _ rhs: [LinkedComponent]) { for (a, b) in zip(lhs, rhs) { + // Coalescing retains distinct complete clauses; collection order carries no restriction. + let sameConditions = + [.hook, .permissions].contains(a.key.kind) + ? a.conditions.count == b.conditions.count + && a.conditions.allSatisfy { b.conditions.contains($0) } + : a.conditions == b.conditions if a.key != b.key || a.snapshot != b.snapshot || a.pin != b.pin || !a.payload.sameContent(as: b.payload) - || a.conditions != b.conditions + || !sameConditions || a.recipients != b.recipients || a.chatGPT != b.chatGPT || a.resources != b.resources || Set(a.origins.flatMap(\.dependencies)) != Set(b.origins.flatMap(\.dependencies)) { diff --git a/Tests/ComponentsTests/ImpactTests.swift b/Tests/ComponentsTests/ImpactTests.swift index 3dc71be..8e1797a 100644 --- a/Tests/ComponentsTests/ImpactTests.swift +++ b/Tests/ComponentsTests/ImpactTests.swift @@ -104,6 +104,52 @@ struct ImpactTests { } extension ImpactTests { + @Test(arguments: [false, true]) + func coalescedRestrictionClausesIgnoreDeclarationOrder(permissions: Bool) throws { + let fixture = try LinkFixture() + let body = + permissions + ? ".permissions(name: \"shared\", rules: [.allow(.read, \"Sources/**\")]" + : ".hook(name: \"shared\", event: .afterTool, run: .executable(\"never-run\")" + func graph(_ conditions: [String]) throws -> LinkedComponents { + let components = conditions.map { body + ", condition: \($0))" }.joined(separator: ",") + return try fixture.link("let agents = Agents(components: [\(components)])") + } + let clauses = [ + ".when(agents: [.codex], scopes: [.project], platforms: [.macOS])", + ".when(agents: [.claudeCode], scopes: [.project], platforms: [.macOS, .linux])", + ] + let before = try graph(clauses) + let after = try graph(clauses.reversed()) + let component = try #require(after.components.first) + #expect(after.components.count == 1) + #expect(component.origins.count == 2) + #expect(component.conditions.count == 2) + #expect(component.conditions == before.components[0].conditions.reversed()) + #expect(after.protectedChanges(from: before, allowing: [.skills]).isEmpty) + #expect(before.protectedChanges(from: after, allowing: [.skills]).isEmpty) + + let changed = try graph([ + clauses[0], + ".when(agents: [.claudeCode], scopes: [.project], platforms: [.macOS])", + ]) + #expect(changed.components[0].recipients == component.recipients) + #expect(changed.protectedChanges(from: before, allowing: [.skills]) == [component.key]) + + let paired = try graph([ + ".when(agents: [.codex], scopes: [.project], platforms: [.macOS])", + ".when(agents: [.claudeCode], scopes: [.project], platforms: [.linux])", + ".when(agents: [.codex, .claudeCode], scopes: [.project], platforms: [.macOS])", + ]) + let swapped = try graph([ + ".when(agents: [.codex], scopes: [.project], platforms: [.linux])", + ".when(agents: [.claudeCode], scopes: [.project], platforms: [.macOS])", + ".when(agents: [.codex, .claudeCode], scopes: [.project], platforms: [.macOS])", + ]) + #expect(swapped.components[0].recipients == paired.components[0].recipients) + #expect(swapped.protectedChanges(from: paired, allowing: [.skills]) == [component.key]) + } + @Test(arguments: [false, true]) func coalescingChecksEveryDifferentPayload(permissions: Bool) throws { let fixture = try LinkFixture() From cb7dba90af286abae2a587de5478bed29be47d56 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 7 Nov 2026 05:34:36 +0800 Subject: [PATCH 040/171] feat: add versioned component state and replay --- Documentation/Architecture/Package.md | 10 +- Documentation/Architecture/State.md | 42 ++ Package.swift | 3 +- Sources/AgentsCore/DirectoryHandle.swift | 9 +- Sources/AgentsCore/LedgerAdmission.swift | 241 +++++++++++ Sources/AgentsCore/LedgerResources.swift | 166 ++++++++ Sources/AgentsCore/LedgerStateStore.swift | 53 +++ Sources/AgentsCore/LedgerValidation.swift | 256 ++++++++++++ Sources/AgentsCore/ResolvedLedger.swift | 378 ++++++++++++++++++ Sources/AgentsCore/ResolvedLedgerCodec.swift | 159 ++++++++ Sources/AgentsCore/RetentionReferences.swift | 89 +++++ Sources/AgentsCore/SourceCache.swift | 115 +++--- .../AgentsCore/SourceRevisionInspection.swift | 2 +- .../InstructionCompatibility.swift | 35 ++ Sources/Components/ComponentLinker.swift | 4 + Sources/Components/Expansion.swift | 10 +- Sources/Components/LedgerFreeze.swift | 157 ++++++++ Sources/Components/LedgerPayload.swift | 186 +++++++++ Sources/Components/LedgerReplay.swift | 277 +++++++++++++ Sources/Components/LinkedComponents.swift | 10 + .../IndependentLedgerAdmissionTests.swift | 219 ++++++++++ Tests/AgentsCoreTests/LedgerCodecTests.swift | 130 ++++++ .../LedgerRetentionTests.swift | 60 +++ .../LedgerWireSpellingTests.swift | 99 +++++ .../LedgerCompatibilityTests.swift | 49 +++ Tests/ComponentsTests/LedgerReplayTests.swift | 304 ++++++++++++++ Tests/StateTestProcess/LedgerProbe.swift | 106 +++++ Tests/StateTestProcess/main.swift | 4 +- 28 files changed, 3109 insertions(+), 64 deletions(-) create mode 100644 Sources/AgentsCore/LedgerAdmission.swift create mode 100644 Sources/AgentsCore/LedgerResources.swift create mode 100644 Sources/AgentsCore/LedgerStateStore.swift create mode 100644 Sources/AgentsCore/LedgerValidation.swift create mode 100644 Sources/AgentsCore/ResolvedLedger.swift create mode 100644 Sources/AgentsCore/ResolvedLedgerCodec.swift create mode 100644 Sources/AgentsCore/RetentionReferences.swift create mode 100644 Sources/AgentsInstructions/InstructionCompatibility.swift create mode 100644 Sources/Components/LedgerFreeze.swift create mode 100644 Sources/Components/LedgerPayload.swift create mode 100644 Sources/Components/LedgerReplay.swift create mode 100644 Tests/AgentsCoreTests/IndependentLedgerAdmissionTests.swift create mode 100644 Tests/AgentsCoreTests/LedgerCodecTests.swift create mode 100644 Tests/AgentsCoreTests/LedgerRetentionTests.swift create mode 100644 Tests/AgentsCoreTests/LedgerWireSpellingTests.swift create mode 100644 Tests/AgentsInstructionsTests/LedgerCompatibilityTests.swift create mode 100644 Tests/ComponentsTests/LedgerReplayTests.swift create mode 100644 Tests/StateTestProcess/LedgerProbe.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index fdb22e5..5b229e5 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -33,12 +33,12 @@ ManifestTestProcess ──> AgentsManifest, AgentsCore, AgentsDescription, Manif AgentsManifestTests ──> AgentsManifest, AgentsDescription, AgentsCore, ManifestTestProcess, ManifestTestSupport, SwiftParser, SwiftSyntax StateTestSupport (Foundation only) -StateTestProcess ──> AgentsCore, AgentsManifest, AgentsInstructions, AgentsSkills, AgentsUpdates, CPlatform, StateTestSupport +StateTestProcess ──> AgentsCore, AgentsManifest, AgentsInstructions, AgentsSkills, AgentsUpdates, Components, CPlatform, StateTestSupport AgentsCoreTests ──> AgentsCore, AgentsManifest, StateTestProcess, StateTestSupport, CPlatform AgentsSkillsTests ──> AgentsSkills, AgentsCore, AgentsManifest, AgentsInstructions, Yams, StateTestProcess, StateTestSupport, CPlatform AgentsInstructionsTests ──> AgentsInstructions, AgentsManifest AgentsUpdatesTests ──> AgentsUpdates, AgentsManifest, StateTestProcess, StateTestSupport, CPlatform -ComponentsTests ──> Components, AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions +ComponentsTests ──> Components, AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, StateTestProcess, StateTestSupport ``` `AgentsDescription`, `AgentsManifest`, `AgentsCore`, `AgentsSkills`, @@ -415,7 +415,11 @@ reference and contribution occurrences, provenance and exact dependency pins. Its protected projection compares other domains' payloads, resource hashes, recipients and pins; source sharing alone does not imply a changed projection. Producer-owned children report `notEditableHere` with producer and reference -coordinates. These package seams do not publish state or lower native artifacts. +coordinates. The ledger freeze seam captures complete durable inputs within the source session. +Versioned replay produces verified artifacts and owned-region intentions; its +compatibility renderer table contains only existing formats. Test process formats +are supplied explicitly and are absent from production registration. These +package seams do not publish state. The existing public lifecycle operations still enforce their deployment subset. Root package resources use the project directory in project scope and the diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index a9f22df..7ce1052 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -697,3 +697,45 @@ It also reports missing installs, changed content and broken links, newer matching Git resolutions and uncommitted changes in selected local source paths. `install` restores all recorded recipients and modes without changing lock bytes. The consuming CLI controls presentation and user interaction. + +## Version 2 ledger package interfaces + +`ResolvedLedger` is the package-internal version 2 representation of the same +`agents.resolved` file. `ResolvedLedgerCodec` accepts version 2 only. It preserves +unchanged bytes and rejects unknown fields, duplicate keys, invalid references, +corrupt embedded objects and unsupported versions. `LedgerAdmission` bounds +encoded bytes, structural depth and nodes, embedded decoded bytes and tree +entries before decoding. Scope reads also bound file bytes while reading. + +The ledger stores source uses and independent pins, complete symbolic component +payloads, ordered occurrences and group child closures, producer manifest +hashes, resource trees, deployment ownership and format-pinned lowerings. +Content objects embed deduplicated non-secret bytes for local and artifact +resources. Trees preserve directories, symlinks and executable files. Actual +local edit skills retain explicit live locations. Registered-root-relative +locations relocate with their registered root; explicit absolute locations keep +their authored meaning. Runtime secret values are not binding inputs to this +codec or the pure renderers. + +`Components.LedgerFreeze` consumes borrowed B graph resources inside the source +session. Its caller supplies explicit authoring coordinates and lowering/layout +choices. `LedgerReplay.prepareLowerings` seals symbolic output identities; +`withReplay` reconstructs exact resources, selects only the locked renderer +format and verifies outputs before returning borrowed artifacts and owned-value +intentions. Exact Git acquisition uses the recorded commit. Embedded resources +require no authoring tree or cache. Compatibility formats cover existing skill, +instruction, ChatGPT and Claude import rendering. Production native format +registration and document editing are owned by the native adapters. + +`RetentionReferences` validates and derives the complete source/resource closure, +including container ancestry and empty groups, then unions watch references. +Cache pruning stages deletions in the caller's `FileTransaction`. Ref cleanup +runs only after physical journal recovery or commit; unfinished journals prevent +independent pruning. Recovery interprets physical evidence and does not invoke +renderers or source providers. + +The existing public lifecycle methods continue to use their version 1 model and +reject version 2 input. Public lifecycle composition owns their eventual version +2 integration. Conversion tooling is external to the package and requires old +locks, original authoring inputs and explicit target layouts; it does not adopt +current deployed bytes. diff --git a/Package.swift b/Package.swift index 41593e9..708612c 100644 --- a/Package.swift +++ b/Package.swift @@ -55,13 +55,14 @@ let package = Package( name: "ComponentsTests", dependencies: [ "Components", "AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions", + "StateTestProcess", "StateTestSupport", ]), .target(name: "StateTestSupport", path: "Tests/StateTestSupport"), .executableTarget( name: "StateTestProcess", dependencies: [ "AgentsCore", "AgentsManifest", "AgentsInstructions", "AgentsSkills", "AgentsUpdates", - "CPlatform", "StateTestSupport", + "CPlatform", "StateTestSupport", "Components", ], path: "Tests/StateTestProcess"), .testTarget( diff --git a/Sources/AgentsCore/DirectoryHandle.swift b/Sources/AgentsCore/DirectoryHandle.swift index 7ad0f5c..bd4773e 100644 --- a/Sources/AgentsCore/DirectoryHandle.swift +++ b/Sources/AgentsCore/DirectoryHandle.swift @@ -491,7 +491,8 @@ final class DirectoryHandle { try sync() } - func read(_ name: String, matching expected: stat? = nil) throws -> Data { + func read(_ name: String, matching expected: stat? = nil, maximumBytes: Int? = nil) throws -> Data + { let file = try regularFile(name) defer { close(file) } var before = stat() @@ -501,6 +502,9 @@ final class DirectoryHandle { if var expected, !platform_same_generation(&expected, &before) { throw CoreError.invalidState("file changed before reading: \(name)") } + if let maximumBytes, before.st_size > maximumBytes { + throw CoreError.invalidState("file byte budget: \(name)") + } var data = Data() var buffer = [UInt8](repeating: 0, count: 65536) while true { @@ -518,6 +522,9 @@ final class DirectoryHandle { } return data } + if let maximumBytes, count > maximumBytes - data.count { + throw CoreError.invalidState("file byte budget: \(name)") + } data.append(contentsOf: buffer.prefix(count)) } } diff --git a/Sources/AgentsCore/LedgerAdmission.swift b/Sources/AgentsCore/LedgerAdmission.swift new file mode 100644 index 0000000..8af659c --- /dev/null +++ b/Sources/AgentsCore/LedgerAdmission.swift @@ -0,0 +1,241 @@ +import Foundation + +/// All counts are aggregate per ledger. The caller may reduce limits for a constrained operation. +package struct LedgerLimits: Sendable { + package var encodedBytes: Int + package var depth: Int + package var nodes: Int + package var objectBytes: Int + package var entries: Int + package var keyBytes: Int + package var resourceBytes: Int + package init( + encodedBytes: Int, depth: Int, nodes: Int, objectBytes: Int, entries: Int, keyBytes: Int, + resourceBytes: Int? = nil + ) { + self.encodedBytes = encodedBytes + self.depth = depth + self.nodes = nodes + self.objectBytes = objectBytes + self.entries = entries + self.keyBytes = keyBytes + self.resourceBytes = resourceBytes ?? objectBytes + } +} + +/// Grammar and aggregate bounds are checked before Foundation constructs a decoded object graph. +package enum LedgerAdmission { + package static func check(_ data: Data, limits: LedgerLimits) throws { + guard data.count <= limits.encodedBytes, limits.depth > 0, limits.nodes > 0, + limits.objectBytes >= 0, limits.entries >= 0, limits.keyBytes > 0, + String(data: data, encoding: .utf8) != nil, !data.starts(with: [239, 187, 191]) + else { + throw CoreError.invalidState("ledger encoding or byte budget") + } + var scanner = Scanner(data: data, limits: limits) + try scanner.value(depth: 0) + scanner.space() + guard scanner.index == data.count else { throw CoreError.invalidState("trailing ledger JSON") } + } + + private struct Scanner { + let data: Data + let limits: LedgerLimits + var index = 0 + var nodes = 0 + var objectBytes = 0 + var entries = 0 + + var byte: UInt8? { index < data.count ? data[index] : nil } + mutating func space() { while let byte, [9, 10, 13, 32].contains(byte) { index += 1 } } + mutating func take(_ expected: UInt8) throws { + guard byte == expected else { throw CoreError.invalidState("invalid ledger JSON") } + index += 1 + } + + mutating func value( + depth: Int, contentObjects: Bool = false, object: Bool = false, treeEntries: Bool = false + ) throws { + nodes += 1 + guard depth <= limits.depth, nodes <= limits.nodes else { + throw CoreError.invalidState("ledger structure budget") + } + space() + guard let current = byte else { throw CoreError.invalidState("truncated ledger JSON") } + switch current { + case 123: + index += 1 + space() + var keys = Set() + if byte == 125 { + index += 1 + return + } + while true { + let range = try string() + guard range.count <= limits.keyBytes else { + throw CoreError.invalidState("ledger key budget") + } + let key = try JSONDecoder().decode(String.self, from: data.subdata(in: range)) + guard keys.insert(key).inserted else { + throw CoreError.invalidState("duplicate ledger key") + } + space() + try take(58) + try value( + depth: depth + 1, contentObjects: depth == 0 && key == "contentObjects", + object: contentObjects, treeEntries: key == "entries" || key == "support") + space() + if byte == 125 { + index += 1 + break + } + try take(44) + space() + } + case 91: + index += 1 + space() + if byte == 93 { + index += 1 + return + } + while true { + if treeEntries { + entries += 1 + guard entries <= limits.entries else { + throw CoreError.invalidState("ledger entry budget") + } + } + try value(depth: depth + 1) + space() + if byte == 93 { + index += 1 + break + } + try take(44) + } + case 34: + let range = try string() + if object { + let count = try base64Bytes(in: range) + guard count <= limits.objectBytes - objectBytes else { + throw CoreError.invalidState("ledger content byte budget") + } + objectBytes += count + } + case 116: try literal("true") + case 102: try literal("false") + case 110: try literal("null") + case 45, 48...57: try number() + default: throw CoreError.invalidState("invalid ledger JSON value") + } + } + + /// Counts the decoded Base64 spelling without allocating either the unescaped string or bytes. + func base64Bytes(in range: Range) throws -> Int { + var cursor = range.lowerBound + 1 + let end = range.upperBound - 1 + var length = 0 + var padding = 0 + while cursor < end { + var scalar = Int(data[cursor]) + cursor += 1 + if scalar == 92 { + let escaped = data[cursor] + cursor += 1 + if escaped == 117 { + scalar = 0 + for _ in 0..<4 { + let hex = Int(data[cursor]) + scalar = scalar * 16 + (hex <= 57 ? hex - 48 : hex <= 70 ? hex - 55 : hex - 87) + cursor += 1 + } + } else if escaped == 47 { + scalar = 47 + } else { + throw CoreError.invalidState("invalid content encoding") + } + } + length += 1 + if scalar == 61 { + padding += 1 + guard padding <= 2 else { throw CoreError.invalidState("invalid content padding") } + } else { + guard padding == 0, + (65...90).contains(scalar) || (97...122).contains(scalar) + || (48...57).contains(scalar) || scalar == 43 || scalar == 47 + else { + throw CoreError.invalidState("invalid content encoding") + } + } + } + guard length % 4 == 0 else { throw CoreError.invalidState("invalid content encoding") } + return length / 4 * 3 - padding + } + + mutating func literal(_ text: String) throws { + for value in text.utf8 { try take(value) } + } + + mutating func string() throws -> Range { + let start = index + try take(34) + while let value = byte { + index += 1 + if value == 34 { return start..= 32 else { throw CoreError.invalidState("control byte in ledger string") } + if value == 92 { + guard let escaped = byte else { throw CoreError.invalidState("truncated ledger escape") } + index += 1 + if escaped == 117 { + for _ in 0..<4 { + guard let hex = byte, + (48...57).contains(hex) || (65...70).contains(hex) + || (97...102).contains(hex) + else { + throw CoreError.invalidState("invalid ledger Unicode escape") + } + index += 1 + } + } else if ![34, 92, 47, 98, 102, 110, 114, 116].contains(escaped) { + throw CoreError.invalidState("invalid ledger escape") + } + } + } + throw CoreError.invalidState("unterminated ledger string") + } + + mutating func number() throws { + if byte == 45 { index += 1 } + if byte == 48 { + index += 1 + } else { + guard let byte, (49...57).contains(byte) else { + throw CoreError.invalidState("invalid ledger number") + } + digits() + } + if byte == 46 { + index += 1 + let start = index + digits() + guard index > start else { throw CoreError.invalidState("invalid ledger fraction") } + } + if byte == 101 || byte == 69 { + index += 1 + if byte == 43 || byte == 45 { index += 1 } + let start = index + digits() + guard index > start else { throw CoreError.invalidState("invalid ledger exponent") } + } + } + mutating func digits() { while let byte, (48...57).contains(byte) { index += 1 } } + } +} + +extension LedgerLimits { + package static let standard = LedgerLimits( + encodedBytes: 256 * 1024 * 1024, depth: 128, nodes: 2_000_000, + objectBytes: 128 * 1024 * 1024, entries: 100_000, keyBytes: 256 * 1024 * 1024) +} diff --git a/Sources/AgentsCore/LedgerResources.swift b/Sources/AgentsCore/LedgerResources.swift new file mode 100644 index 0000000..e8c19d8 --- /dev/null +++ b/Sources/AgentsCore/LedgerResources.swift @@ -0,0 +1,166 @@ +import Foundation + +/// Resource trees retain empty directories, symlink spellings and executable files separately. +package enum LedgerResources { + package static func capture(_ url: URL, embed: Bool, limits: LedgerLimits, sourceRoot: URL? = nil) + throws -> ( + entries: [LedgerEntry], support: [LedgerEntry], objects: [String: Data], hash: String, + flags: [String: Bool] + ) + { + var entries: [LedgerEntry] = [] + var objects: [String: Data] = [:] + var support: [String: LedgerEntry] = [:] + var visiting = Set() + var bytes = 0 + var expandedBytes = 0 + var isDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory) else { + throw CoreError.notFound("locked resource") + } + func collect(_ file: URL, path: String, supporting: Bool = false) throws { + if supporting, !visiting.insert(path).inserted { return } + func append(_ entry: LedgerEntry) { + if supporting { support[entry.path] = entry } else { entries.append(entry) } + } + try Task.checkCancellation() + guard entries.count + support.count < limits.entries else { + throw CoreError.invalidState("resource entry budget") + } + let info = try FileManager.default.attributesOfItem(atPath: file.path) + let type = info[.type] as? FileAttributeType + if type == .typeDirectory { + append(.init(path: path, kind: .directory, executable: false)) + for name in try FileManager.default.contentsOfDirectory(atPath: file.path).sorted() { + try collect( + file.appendingPathComponent(name), path: path == "." ? name : path + "/" + name, + supporting: supporting) + } + } else if type == .typeSymbolicLink { + let link = try FileManager.default.destinationOfSymbolicLink(atPath: file.path) + append(.init(path: path, kind: .symlink, link: link, executable: false)) + if embed, let sourceRoot { + let target = file.deletingLastPathComponent().appendingPathComponent(link) + .standardizedFileURL + guard !link.hasPrefix("/"), PathSafety.isContained(target, in: sourceRoot), + PathSafety.isContained( + target.resolvingSymlinksInPath(), in: sourceRoot.resolvingSymlinksInPath()) + else { + throw CoreError.unsafePath("resource link escapes source snapshot") + } + if !PathSafety.isContained(target, in: url) { + let relative = PathSafety.relativePath(target.path, to: sourceRoot.path) + let parts = relative.split(separator: "/") + for count in 1..= 0, size <= limits.resourceBytes - expandedBytes else { + throw CoreError.invalidState("expanded resource byte budget") + } + expandedBytes += size + let object: String? + if embed { + guard size <= limits.objectBytes else { + throw CoreError.invalidState("resource byte budget") + } + let data = try FileSystem.read(at: file) + guard data.count == size else { + throw CoreError.invalidState("resource changed during freeze") + } + let digest = "sha256:" + FileHash.sha256Hex(data: data) + if objects[digest] == nil { + guard size <= limits.objectBytes - bytes else { + throw CoreError.invalidState("resource aggregate byte budget") + } + bytes += size + objects[digest] = data + } + object = digest + } else { + object = nil + } + append( + .init( + path: path, kind: .file, object: object, + executable: ((info[.posixPermissions] as? NSNumber)?.intValue ?? 0) & 0o111 != 0, + byteCount: size)) + } else { + throw CoreError.invalidState("unsupported locked resource entry") + } + } + try collect(url, path: ".") + let hash = + try "sha256:" + + (isDirectory.boolValue + ? FileHash.folderHash(url) : FileHash.sha256Hex(file: url)) + let flags = + try isDirectory.boolValue + ? FileHash.executableFlags(url) + : [ + ".": + ((FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions] as? NSNumber)? + .intValue ?? 0) & 0o111 != 0 + ] + return (entries, support.keys.sorted().map { support[$0]! }, objects, hash, flags) + } + + /// Writes only beneath a caller-owned disposable directory. This is not publication. + package static func materialize( + _ resource: LedgerResource, objects: [String: Data], at destination: URL + ) throws { + guard resource.kind == .embedded else { + throw CoreError.invalidState("resource is not embedded") + } + var all = resource.support + let hasSupport = !all.isEmpty + let selected = + hasSupport + ? try PathSafety.resolvedChild(base: destination, subpath: resource.path) : destination + if hasSupport { + try FileSystem.createDirectory(at: selected.deletingLastPathComponent()) + all += resource.entries.map { original in + var entry = original + entry.path = original.path == "." ? resource.path : resource.path + "/" + original.path + return entry + } + } else { + all = resource.entries + } + var unique: [String: LedgerEntry] = [:] + for entry in all { + guard unique[entry.path] == nil || unique[entry.path] == entry else { + throw CoreError.invalidState("conflicting resource support") + } + unique[entry.path] = entry + } + for entry in unique.values.sorted(by: { $0.path < $1.path }) { + try Task.checkCancellation() + let file = + entry.path == "." + ? destination + : try PathSafety.resolvedChild(base: destination, subpath: entry.path) + switch entry.kind { + case .directory: try FileSystem.createDirectory(at: file) + case .file: + guard let id = entry.object, let bytes = objects[id], + "sha256:" + FileHash.sha256Hex(data: bytes) == id + else { + throw CoreError.invalidState("missing or corrupt content object") + } + try FileSystem.createDirectory(at: file.deletingLastPathComponent()) + try FileSystem.write(bytes, to: file) + try FileManager.default.setAttributes( + [.posixPermissions: entry.executable ? 0o755 : 0o644], ofItemAtPath: file.path) + case .symlink: + guard let link = entry.link else { throw CoreError.invalidState("missing link") } + try FileManager.default.createSymbolicLink(atPath: file.path, withDestinationPath: link) + } + } + } +} diff --git a/Sources/AgentsCore/LedgerStateStore.swift b/Sources/AgentsCore/LedgerStateStore.swift new file mode 100644 index 0000000..c96d247 --- /dev/null +++ b/Sources/AgentsCore/LedgerStateStore.swift @@ -0,0 +1,53 @@ +import Foundation + +extension StateStore { + /// Internal v2 access preserves the existing read/recovery boundary; public v1 readers reject v2. + package func loadLedger(limits: LedgerLimits) throws -> ResolvedLedger { + try withReadLock { + _ = try declarationBytes() + guard let bytes = try ledgerBytes(limits: limits) else { + throw CoreError.notFound("resolved ledger") + } + return try ResolvedLedgerCodec.decode(bytes, limits: limits) + } + } + + package func stageLedger( + _ ledger: ResolvedLedger, limits: LedgerLimits, transaction: FileTransaction, + prepared: StatePrecondition + ) throws { + if let bytes = try ResolvedLedgerCodec.replacement( + ledger, existing: prepared.bytes(for: resolvedURL), limits: limits) + { + try transaction.replace( + resolvedURL, with: .data(bytes), expecting: prepared.evidence(for: resolvedURL)) + } + } + + private func ledgerBytes(limits: LedgerLimits) throws -> Data? { + guard let directory = try openDirectoryIfPresent(), + try directory.info(Self.resolvedFileName) != nil + else { return nil } + return try directory.read(Self.resolvedFileName, maximumBytes: limits.encodedBytes) + } + + /// Ref cleanup consumes the committed closure after physical journal recovery. + func retentionReferences() throws -> RetentionReferences { + guard let bytes = try ledgerBytes(limits: .standard) else { return RetentionReferences() } + struct Version: Decodable { let version: Int } + // This boundary is used only by recovery's cache reconciliation, never to reinterpret v2 + // as a v1 lifecycle model. Admission bounds decoding before examining the version. + try LedgerAdmission.check(bytes, limits: LedgerLimits.standard) + let version = try JSONDecoder().decode(Version.self, from: bytes).version + if version == 2 { + return try RetentionReferences( + ledger: ResolvedLedgerCodec.decode(bytes, limits: LedgerLimits.standard), + roots: [ + "project": environment.projectDirectory, "home": environment.homeDirectory, + "state": directory, + ]) + } + let resolved = try StateStore.decode(bytes, as: ResolvedState.self) + return try RetentionReferences(resolved: resolved, cache: SourceCache(store: self)) + } +} diff --git a/Sources/AgentsCore/LedgerValidation.swift b/Sources/AgentsCore/LedgerValidation.swift new file mode 100644 index 0000000..0f50542 --- /dev/null +++ b/Sources/AgentsCore/LedgerValidation.swift @@ -0,0 +1,256 @@ +import Foundation + +extension ResolvedLedger { + package func validate() throws { + guard version == 2 else { throw CoreError.invalidState("unsupported ledger version") } + for (id, source) in sources { + guard !id.isEmpty, !source.revision.isEmpty else { + throw CoreError.invalidState("invalid ledger source") + } + if let container = source.container { + guard sources[container] != nil, container != id else { + throw CoreError.invalidState("dangling source container") + } + } + try source.location?.validate() + if source.kind == .git { + guard let transport = source.transport, !transport.isEmpty, + SourceCache.isObjectID(source.revision) + else { + throw CoreError.invalidState("Git ledger source needs exact transport and commit") + } + } + var visited: Set = [id] + var current = source.container + while let next = current { + guard visited.insert(next).inserted else { throw CoreError.invalidState("source cycle") } + current = sources[next]?.container + } + } + for use in sourceUses { + try requireSource(use.source) + try ledgerPath(use.root) + try use.requirement?.validate() + } + for (digest, bytes) in contentObjects { + try StateValidation.digest(digest) + guard "sha256:" + FileHash.sha256Hex(data: bytes) == digest else { + throw CoreError.invalidState("content object digest mismatch") + } + } + for (id, resource) in resources { + guard !id.isEmpty else { throw CoreError.invalidState("empty resource ID") } + try requireSource(resource.source) + try ledgerPath(resource.path) + try StateValidation.digest(resource.hash) + try resource.location?.validate() + if resource.kind == .liveEdit { + guard resource.location != nil, resource.artifact == nil, resource.entries.isEmpty, + resource.support.isEmpty + else { + throw CoreError.invalidState("invalid live edit resource") + } + } else { + guard resource.location == nil, !resource.entries.isEmpty else { + throw CoreError.invalidState("incomplete locked resource") + } + } + if resource.kind == .git { + var source = sources[resource.source]! + while let parent = source.container { source = sources[parent]! } + guard SourceCache.isObjectID(source.revision) else { + throw CoreError.invalidState("resource requires exact Git commit") + } + } + if resource.kind == .artifact { + guard let artifact = resource.artifact else { + throw CoreError.invalidState("artifact resource needs immutable coordinates") + } + try artifact.validate() + } else if resource.artifact != nil { + throw CoreError.invalidState("unexpected resource artifact") + } + guard Set(resource.entries.map(\.path)).count == resource.entries.count, + Set(resource.support.map(\.path)).count == resource.support.count + else { + throw CoreError.invalidState("duplicate resource path") + } + var entries: [String: LedgerEntry] = [:] + var treeEntries = resource.support + treeEntries += resource.entries.map { original in + var entry = original + entry.path = + original.path == "." + ? resource.path + : resource.path == "." ? original.path : resource.path + "/" + original.path + return entry + } + for entry in treeEntries { + try ledgerPath(entry.path) + guard entries[entry.path] == nil || entries[entry.path] == entry else { + throw CoreError.invalidState("conflicting resource path") + } + entries[entry.path] = entry + switch entry.kind { + case .file: + guard let byteCount = entry.byteCount, byteCount >= 0 else { + throw CoreError.invalidState("file requires byte count") + } + guard entry.link == nil else { throw CoreError.invalidState("file has link target") } + if let object = entry.object { + guard contentObjects[object]?.count == byteCount else { + throw CoreError.invalidState("dangling content object") + } + } else if resource.kind == .embedded || resource.kind == .artifact { + throw CoreError.invalidState("embedded file lacks content") + } + case .directory: + guard entry.object == nil, entry.link == nil, entry.byteCount == nil, !entry.executable + else { + throw CoreError.invalidState("invalid directory entry") + } + case .symlink: + guard let link = entry.link, entry.object == nil, entry.byteCount == nil, + !entry.executable, + !link.hasPrefix("/"), !link.contains("\0"), !link.contains("\\") + else { + throw CoreError.invalidState("invalid resource link") + } + let base = URL(fileURLWithPath: "/ledger").appendingPathComponent(entry.path) + .deletingLastPathComponent() + let target = base.appendingPathComponent(link).standardizedFileURL + guard PathSafety.isContained(target, in: URL(fileURLWithPath: "/ledger")) else { + throw CoreError.invalidState("resource link escapes tree") + } + } + } + if resource.kind != .liveEdit, !resource.entries.contains(where: { $0.path == "." }) { + throw CoreError.invalidState("missing resource root entry") + } + let resourceParents = resource.path.split(separator: "/").dropLast() + for count in 1...max(1, resourceParents.count) where count <= resourceParents.count { + let parent = resourceParents.prefix(count).joined(separator: "/") + if entries[parent] == nil { + entries[parent] = .init(path: parent, kind: .directory, executable: false) + } + } + for path in entries.keys where path != "." { + let parts = path.split(separator: "/") + for count in 1..= 0, group.parent.map({ groupIDs.contains($0) && $0 < group.id }) ?? true, + Set(group.children).count == group.children.count, + group.children.allSatisfy({ groupIDs.contains($0) || occurrenceIDs.contains($0) }) + else { + throw CoreError.invalidState("invalid group closure") + } + let actual = + groups.filter { $0.parent == group.id }.map(\.id) + + occurrences.filter { $0.reference == group.id }.map(\.id) + guard group.children == actual.sorted() else { + throw CoreError.invalidState("incomplete group child closure") + } + } + for occurrence in occurrences { + try requireSource(occurrence.declaringSource) + try ledgerPath(occurrence.manifestPath) + guard occurrence.id >= 0, components[occurrence.component] != nil, + occurrence.reference.map({ groupIDs.contains($0) && $0 < occurrence.id }) ?? true + else { + throw CoreError.invalidState("dangling component occurrence") + } + for dependency in occurrence.dependencies { try requireSource(dependency) } + try validate(occurrence.condition) + } + let deploymentIDs = Set(deployments.map(\.id)) + guard deploymentIDs.count == deployments.count else { + throw CoreError.invalidState("duplicate deployment") + } + for deployment in deployments { + let producers = lowerings.filter { $0.deployments.contains(deployment.id) } + guard !producers.isEmpty, + producers.allSatisfy({ + Set(deployment.owners).isSubset(of: Set($0.inputs)) && $0.format == deployment.route + }) + else { throw CoreError.invalidState("deployment has incomplete lowering ownership") } + try deployment.target.validate() + guard deployment.target.kind != .authoringRelative else { + throw CoreError.invalidState("authoring coordinates cannot be deployment targets") + } + try StateValidation.digest(deployment.expectedHash) + guard !deployment.id.isEmpty, !deployment.route.isEmpty, !deployment.owners.isEmpty, + deployment.owners.allSatisfy({ components[$0] != nil }), + deployment.ownership != .importBlock || deployment.importReference != nil + else { + throw CoreError.invalidState("invalid deployment ownership") + } + } + guard Set(lowerings.map(\.id)).count == lowerings.count else { + throw CoreError.invalidState("duplicate lowering") + } + for lowering in lowerings { + guard !lowering.id.isEmpty, !lowering.format.isEmpty, + DeclarationPlatform(rawValue: lowering.platform) != nil, + lowering.inputs.allSatisfy({ components[$0] != nil }), + lowering.deployments.allSatisfy({ deploymentIDs.contains($0) }), + Set(lowering.artifacts.map(\.name)).count == lowering.artifacts.count + else { + throw CoreError.invalidState("invalid locked lowering references") + } + try lowering.layout.validate() + try requireResources(lowering.resources) + for artifact in lowering.artifacts { try StateValidation.digest(artifact.hash) } + } + } + + private func requireSource(_ id: String) throws { + guard sources[id] != nil else { throw CoreError.invalidState("dangling ledger source") } + } + + private func requireResources(_ ids: [String]) throws { + guard ids.allSatisfy({ resources[$0] != nil }) else { + throw CoreError.invalidState("dangling ledger resource") + } + } + + private func validate(_ condition: LedgerCondition) throws { + guard condition.platforms?.allSatisfy({ DeclarationPlatform(rawValue: $0) != nil }) ?? true + else { + throw CoreError.invalidState("unknown ledger platform") + } + } +} diff --git a/Sources/AgentsCore/ResolvedLedger.swift b/Sources/AgentsCore/ResolvedLedger.swift new file mode 100644 index 0000000..09c9150 --- /dev/null +++ b/Sources/AgentsCore/ResolvedLedger.swift @@ -0,0 +1,378 @@ +import Foundation + +/// Version 2 of the scope's single resolved file. Arrays preserve contribution and render order. +package struct ResolvedLedger: Codable, Equatable, Sendable { + package var version = 2 + package var sources: [String: LedgerSource] = [:] + package var sourceUses: [LedgerSourceUse] = [] + package var components: [String: LedgerComponent] = [:] + package var occurrences: [LedgerOccurrence] = [] + package var groups: [LedgerGroup] = [] + package var resources: [String: LedgerResource] = [:] + package var deployments: [LedgerDeployment] = [] + package var lowerings: [LockedLowering] = [] + /// Digest-keyed non-secret bytes. These are authoritative; materializations are disposable. + package var contentObjects: [String: Data] = [:] + package init() {} +} + +package struct LedgerSource: Codable, Equatable, Sendable { + package var kind: SourceKind + package var transport: String? + package var location: LedgerLocation? + package var revision: String + package var version: String? + package var container: String? + package var namespace: String? + + package init( + kind: SourceKind, transport: String? = nil, location: LedgerLocation? = nil, revision: String, + version: String? = nil, container: String? = nil, namespace: String? = nil + ) { + self.kind = kind + self.transport = transport + self.location = location + self.revision = revision + self.version = version + self.container = container + self.namespace = namespace + } +} + +package struct LedgerSourceUse: Codable, Equatable, Sendable { + package var source: String + package var root: String + package var requirement: SourceRequirement? + + package init(source: String, root: String, requirement: SourceRequirement? = nil) { + self.source = source + self.root = root + self.requirement = requirement + } +} + +/// Physical URLs are supplied by the caller. Absolute authored locations retain their meaning. +package struct LedgerLocation: Codable, Equatable, Hashable, Sendable { + package enum Kind: String, Codable, Sendable { case registered, authoringRelative, absolute } + package var kind: Kind + package var root: String? + package var path: String + + package func resolve(roots: [String: URL]) throws -> URL { + try validate() + if kind == .absolute { return URL(fileURLWithPath: path) } + guard let root, let directory = roots[root] else { + throw CoreError.invalidState("missing registered ledger root") + } + if kind == .authoringRelative { + return directory.appendingPathComponent(path).standardizedFileURL + } + return try PathSafety.resolvedChild(base: directory, subpath: path) + } + + package func validate() throws { + switch kind { + case .absolute: + guard root == nil, path.hasPrefix("/"), !path.contains("\0"), !path.contains("\\") else { + throw CoreError.invalidState("invalid absolute ledger location") + } + case .authoringRelative: + guard let root, !root.isEmpty, !path.isEmpty, !path.hasPrefix("/"), + !path.hasPrefix("~"), !path.contains("\0"), !path.contains("\\"), + path.split(separator: "/", omittingEmptySubsequences: false).allSatisfy({ !$0.isEmpty }) + else { + throw CoreError.invalidState("invalid authoring-relative location") + } + case .registered: + guard let root, !root.isEmpty else { throw CoreError.invalidState("missing ledger root") } + try ledgerPath(path) + } + } + + package init(kind: Kind, root: String? = nil, path: String) { + self.kind = kind + self.root = root + self.path = path + } +} + +/// A closed tagged value vocabulary, independent of Swift's synthesized enum representation. +package struct LedgerValue: Codable, Equatable, Sendable { + package enum Kind: String, Codable, Sendable { + case string, integer, decimal, boolean, null, array, object, literal, environment, secret + } + package var kind: Kind + package var text: String? + package var integer: Int? + package var boolean: Bool? + package var array: [LedgerValue]? + package var object: [String: LedgerValue]? + + package init(_ text: String, kind: Kind = .string) { + self.kind = kind + self.text = text + } + package init(integer: Int) { + kind = .integer + self.integer = integer + } + package init(boolean: Bool) { + kind = .boolean + self.boolean = boolean + } + package init(array: [LedgerValue]) { + kind = .array + self.array = array + } + package init(object: [String: LedgerValue]) { + kind = .object + self.object = object + } + package init() { kind = .null } + + package func validate() throws { + let fields = [text != nil, integer != nil, boolean != nil, array != nil, object != nil] + let expected: Int? + switch kind { + case .string, .decimal, .literal, .environment, .secret: expected = 0 + case .integer: expected = 1 + case .boolean: expected = 2 + case .array: expected = 3 + case .object: expected = 4 + case .null: expected = nil + } + guard fields.enumerated().allSatisfy({ $0.element == ($0.offset == expected) }) else { + throw CoreError.invalidState("invalid tagged ledger value") + } + for value in array ?? [] { try value.validate() } + for value in object?.values ?? [String: LedgerValue]().values { try value.validate() } + } +} + +package struct LedgerCondition: Codable, Equatable, Sendable { + package var agents: [AgentID]? + package var scopes: [InstallScope]? + package var platforms: [String]? + + package init(_ condition: DeclarationCondition) { + agents = condition.agents + scopes = condition.scopes + platforms = condition.platforms?.map(\.rawValue) + } +} + +package struct LedgerComponent: Codable, Equatable, Sendable { + package var declaringSource: String + package var source: String + package var root: String + package var group: String? + package var kind: String + package var name: String + package var revision: String? + package var version: String? + package var payload: LedgerValue + package var conditions: [LedgerCondition] + package var recipients: [AgentID] + package var chatGPT: Bool + package var resources: [String] + + package init( + declaringSource: String, source: String, root: String, group: String? = nil, kind: String, + name: String, revision: String? = nil, version: String? = nil, payload: LedgerValue, + conditions: [LedgerCondition], recipients: [AgentID], chatGPT: Bool, resources: [String] + ) { + self.source = source + self.root = root + self.declaringSource = declaringSource + self.group = group + self.kind = kind + self.name = name + self.revision = revision + self.version = version + self.payload = payload + self.conditions = conditions + self.recipients = recipients + self.chatGPT = chatGPT + self.resources = resources + } +} + +package struct LedgerOccurrence: Codable, Equatable, Sendable { + package var declaringSource: String + package var manifestPath: String + package var id: Int + package var component: String + package var reference: Int? + package var dependencies: [String] + package var condition: LedgerCondition + package var recipients: [AgentID] + package var consumerEditable: Bool + + package init( + declaringSource: String, manifestPath: String, id: Int, component: String, + reference: Int? = nil, dependencies: [String], condition: LedgerCondition, + recipients: [AgentID], consumerEditable: Bool + ) { + self.id = id + self.declaringSource = declaringSource + self.manifestPath = manifestPath + self.component = component + self.reference = reference + self.dependencies = dependencies + self.condition = condition + self.recipients = recipients + self.consumerEditable = consumerEditable + } +} + +package struct LedgerGroup: Codable, Equatable, Sendable { + package var id: Int + package var parent: Int? + package var source: String + package var root: String + package var name: String + package var requirement: SourceRequirement? + package var manifestHash: String + package var children: [Int] + + package init( + id: Int, parent: Int? = nil, source: String, root: String, name: String, + requirement: SourceRequirement? = nil, manifestHash: String, children: [Int] + ) { + self.id = id + self.parent = parent + self.source = source + self.root = root + self.name = name + self.requirement = requirement + self.manifestHash = manifestHash + self.children = children + } +} + +package struct LedgerEntry: Codable, Equatable, Sendable { + package enum Kind: String, Codable, Sendable { case file, directory, symlink } + package var path: String + package var kind: Kind + package var object: String? + package var link: String? + package var executable: Bool + package var byteCount: Int? + + package init( + path: String, kind: Kind, object: String? = nil, link: String? = nil, executable: Bool, + byteCount: Int? = nil + ) { + self.path = path + self.kind = kind + self.object = object + self.link = link + self.executable = executable + self.byteCount = byteCount + } +} + +package struct LedgerResource: Codable, Equatable, Sendable { + package enum Kind: String, Codable, Sendable { case git, artifact, embedded, liveEdit } + package var kind: Kind + package var source: String + package var path: String + package var hash: String + /// Single files use path "."; directory entries are relative to the selected resource. + package var entries: [LedgerEntry] + package var support: [LedgerEntry] + package var artifact: LockedArtifact? + package var location: LedgerLocation? + + package init( + kind: Kind, source: String, path: String, hash: String, entries: [LedgerEntry], + support: [LedgerEntry] = [], artifact: LockedArtifact? = nil, location: LedgerLocation? = nil + ) { + self.kind = kind + self.source = source + self.path = path + self.hash = hash + self.entries = entries + self.support = support + self.artifact = artifact + self.location = location + } +} + +package struct LedgerDeployment: Codable, Equatable, Sendable { + package enum Ownership: String, Codable, Sendable { case generated, importBlock, ownedValues } + package var id: String + package var target: LedgerLocation + package var route: String + package var owners: [String] + package var recipients: [AgentID] + package var ownership: Ownership + package var expectedHash: String + package var created: Bool + package var importReference: String? + package var headingOffset: Int? + + package init( + id: String, target: LedgerLocation, route: String, owners: [String], recipients: [AgentID], + ownership: Ownership, expectedHash: String, created: Bool, importReference: String? = nil, + headingOffset: Int? = nil + ) { + self.id = id + self.target = target + self.route = route + self.owners = owners + self.recipients = recipients + self.ownership = ownership + self.expectedHash = expectedHash + self.created = created + self.importReference = importReference + self.headingOffset = headingOffset + } +} + +/// Format identity fixes schema, ordering, paths, resource mappings and serialization semantics. +package struct LockedLowering: Codable, Equatable, Sendable { + package var id: String + package var format: String + package var inputs: [String] + package var resources: [String] + package var deployments: [String] + package var layout: LedgerValue + package var platform: String + package var artifacts: [LedgerArtifactDigest] + + package init( + id: String, format: String, inputs: [String], resources: [String], deployments: [String], + layout: LedgerValue, platform: String, artifacts: [LedgerArtifactDigest] + ) { + self.id = id + self.format = format + self.inputs = inputs + self.resources = resources + self.deployments = deployments + self.layout = layout + self.platform = platform + self.artifacts = artifacts + } +} + +package struct LedgerArtifactDigest: Codable, Equatable, Sendable { + package enum Kind: String, Codable, Sendable { case file, tree, ownedValues, registration, link } + package var name: String + package var kind: Kind + package var hash: String + + package init(name: String, kind: Kind, hash: String) { + self.name = name + self.kind = kind + self.hash = hash + } +} + +package func ledgerPath(_ path: String) throws { + guard !path.hasPrefix("/"), !path.hasPrefix("~"), + try PathSafety.sanitizeSubpath(path) == path + else { + throw CoreError.invalidState("noncanonical ledger path") + } +} diff --git a/Sources/AgentsCore/ResolvedLedgerCodec.swift b/Sources/AgentsCore/ResolvedLedgerCodec.swift new file mode 100644 index 0000000..657cbeb --- /dev/null +++ b/Sources/AgentsCore/ResolvedLedgerCodec.swift @@ -0,0 +1,159 @@ +import Foundation + +package enum ResolvedLedgerCodec { + package static func decode(_ data: Data, limits: LedgerLimits) throws -> ResolvedLedger { + try LedgerAdmission.check(data, limits: limits) + let ledger = try JSONDecoder().decode(ResolvedLedger.self, from: data) + try checkModel(ledger, limits: limits) + try ledger.validate() + guard ledger.resources.values.reduce(0, { $0 + $1.entries.count }) <= limits.entries else { + throw CoreError.invalidState("ledger entry budget") + } + // Admission bounds these allocations. Comparing against the wire shape also refuses fields + // a Codable decoder would discard, including unknown fields whose value is null. + let input = try JSONSerialization.jsonObject(with: data) + let encoded = try JSONSerialization.jsonObject(with: bytes(ledger)) + try fields(input, encoded, shape: .ledger) + return ledger + } + + package static func encode(_ ledger: ResolvedLedger, limits: LedgerLimits) throws -> Data { + try checkModel(ledger, limits: limits) + try ledger.validate() + let result = try bytes(ledger) + _ = try decode(result, limits: limits) + return result + } + + /// Nil means the caller must retain the original bytes, including their layout. + package static func replacement( + _ ledger: ResolvedLedger, existing: Data?, limits: LedgerLimits + ) throws -> Data? { + try checkModel(ledger, limits: limits) + try ledger.validate() + if let existing, try decode(existing, limits: limits) == ledger { return nil } + return try encode(ledger, limits: limits) + } + + package static func checkModel(_ ledger: ResolvedLedger, limits: LedgerLimits) throws { + var bytes = 0 + for object in ledger.contentObjects.values { + guard object.count <= limits.objectBytes - bytes else { + throw CoreError.invalidState("ledger content byte budget") + } + bytes += object.count + } + var entries = 0 + var expanded = 0 + for resource in ledger.resources.values { + guard resource.entries.count + resource.support.count <= limits.entries - entries else { + throw CoreError.invalidState("ledger entry budget") + } + entries += resource.entries.count + resource.support.count + for entry in resource.entries + resource.support where entry.kind == .file { + guard let count = entry.byteCount, count >= 0, count <= limits.resourceBytes - expanded + else { + throw CoreError.invalidState("ledger expanded resource budget") + } + expanded += count + } + } + var pending = + ledger.components.values.map { ($0.payload, 0) } + + ledger.lowerings.map { ($0.layout, 0) } + var nodes = 0 + while let (value, depth) = pending.popLast() { + nodes += 1 + guard depth < limits.depth / 2, nodes <= limits.nodes else { + throw CoreError.invalidState("ledger value budget") + } + pending += (value.array ?? []).map { ($0, depth + 1) } + pending += (value.object?.values ?? [String: LedgerValue]().values).map { ($0, depth + 1) } + } + } + + package static func digest(_ value: T) throws -> String { + "sha256:" + FileHash.sha256Hex(data: try bytes(value)) + } + + package static func bytes(_ value: T) throws -> Data { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + var bytes = try encoder.encode(value) + bytes.append(10) + return bytes + } + + /// Nullable members belong to their wire record, not to a spelling used elsewhere in JSON. + private indirect enum WireShape { + case ledger, source, location, sourceUse, component, condition, occurrence, group + case resource, entry, deployment, lowering, value, artifact, requirement, scalar + case map(WireShape) + case list(WireShape) + + var nullable: Set { + switch self { + case .source: ["transport", "location", "version", "container", "namespace"] + case .location: ["root"] + case .sourceUse: ["requirement"] + case .requirement: ["to"] + case .component: ["group", "revision", "version"] + case .condition: ["agents", "scopes", "platforms"] + case .occurrence: ["reference"] + case .group: ["parent", "requirement"] + case .resource: ["artifact", "location"] + case .entry: ["object", "link", "byteCount"] + case .deployment: ["importReference", "headingOffset"] + case .value: ["text", "integer", "boolean", "array", "object"] + case .artifact: ["files"] + default: [] + } + } + + func member(_ key: String) -> Self { + switch (self, key) { + case (.ledger, "sources"): .map(.source) + case (.ledger, "sourceUses"): .list(.sourceUse) + case (.ledger, "components"): .map(.component) + case (.ledger, "occurrences"): .list(.occurrence) + case (.ledger, "groups"): .list(.group) + case (.ledger, "resources"): .map(.resource) + case (.ledger, "deployments"): .list(.deployment) + case (.ledger, "lowerings"): .list(.lowering) + case (.source, "location"), (.resource, "location"), (.deployment, "target"): .location + case (.sourceUse, "requirement"), (.group, "requirement"): .requirement + case (.component, "payload"), (.lowering, "layout"): .value + case (.component, "conditions"): .list(.condition) + case (.occurrence, "condition"): .condition + case (.resource, "entries"), (.resource, "support"): .list(.entry) + case (.resource, "artifact"): .artifact + case (.value, "array"): .list(.value) + case (.value, "object"): .map(.value) + case (.map(let element), _): element + default: .scalar + } + } + + var element: Self { + if case .list(let element) = self { return element } + return .scalar + } + } + + private static func fields(_ input: Any, _ encoded: Any, shape: WireShape) throws { + if let input = input as? [String: Any], let encoded = encoded as? [String: Any] { + for (key, value) in input { + guard let counterpart = encoded[key] else { + if value is NSNull, shape.nullable.contains(key) { continue } + throw CoreError.invalidState("unknown ledger field") + } + try fields(value, counterpart, shape: shape.member(key)) + } + } else if let input = input as? [Any], let encoded = encoded as? [Any] { + guard input.count == encoded.count else { throw CoreError.invalidState("ledger array shape") } + for (value, counterpart) in zip(input, encoded) { + try fields(value, counterpart, shape: shape.element) + } + } + } +} diff --git a/Sources/AgentsCore/RetentionReferences.swift b/Sources/AgentsCore/RetentionReferences.swift new file mode 100644 index 0000000..0ac3d7c --- /dev/null +++ b/Sources/AgentsCore/RetentionReferences.swift @@ -0,0 +1,89 @@ +import Foundation + +/// Validated live cache references. Publication owns when a reduced set becomes authoritative. +package struct RetentionReferences: Sendable { + package struct Git: Hashable, Sendable { + package var source: String + package var revision: String + } + package var git: Set = [] + package var artifacts: Set = [] + package var live: [URL] = [] + package var sourceLocations: [String: String] = [:] + + package init() {} + + package init(ledger: ResolvedLedger, roots: [String: URL]) throws { + try ledger.validate() + // Every source is part of the accepted closure, including empty groups and container parents. + for source in ledger.sources.values { + guard source.container == nil, SourceCache.isObjectID(source.revision) else { continue } + let location: String + let identity: String + if let transport = source.transport { + location = transport + identity = try SourceDeclaration(kind: .git, location: transport).identity( + environment: RuntimeEnvironment()) + } else if let authored = source.location { + location = try authored.resolve(roots: roots).path + identity = "local:" + location + } else { + throw CoreError.invalidState("missing retained source coordinates") + } + git.insert(.init(source: identity, revision: source.revision)) + sourceLocations[identity] = location + } + for resource in ledger.resources.values { + if let artifact = resource.artifact { retain(artifact) } + if resource.kind == .liveEdit, let location = resource.location { + live.append(try location.resolve(roots: roots).resolvingSymlinksInPath()) + } + } + } + + init(resolved: ResolvedState, cache: SourceCache) throws { + try resolved.validate() + for (id, source) in resolved.sources where source.kind != .wellKnown { + sourceLocations[id] = source.kind == .local ? String(id.dropFirst(6)) : source.url + } + for skill in resolved.skills.values { + if let revision = skill.revision { + git.insert(.init(source: skill.source, revision: revision)) + } + if let artifact = skill.artifact { retain(artifact) } + if skill.installs.values.contains(.edit), let source = resolved.sources[skill.source] { + let root = + source.kind == .local + ? URL(fileURLWithPath: String(skill.source.dropFirst(6))) + : cache.store.directory + live.append( + try PathSafety.resolvedChild(base: root, subpath: skill.path ?? ".") + .resolvingSymlinksInPath()) + } + } + for section in resolved.instructions.sections + + resolved.instructions.chatgpt.values.flatMap(\.sections) + { + if let revision = section.revision { + git.insert(.init(source: section.source, revision: revision)) + } + if let artifact = section.artifact { retain(artifact) } + } + } + + package mutating func include(watch: WatchState) throws { + try watch.validate() + for (id, source) in watch.sources { + sourceLocations[id] = id.hasPrefix("local:") ? String(id.dropFirst(6)) : id + switch source.seen { + case .revision(let revision): git.insert(.init(source: id, revision: revision)) + case .artifacts(let objects): artifacts.formUnion(objects.values) + } + } + } + + private mutating func retain(_ artifact: LockedArtifact) { + artifacts.insert(artifact.digest) + artifacts.formUnion((artifact.files ?? []).map(\.digest)) + } +} diff --git a/Sources/AgentsCore/SourceCache.swift b/Sources/AgentsCore/SourceCache.swift index fa1c1d9..c93af3c 100644 --- a/Sources/AgentsCore/SourceCache.swift +++ b/Sources/AgentsCore/SourceCache.swift @@ -211,27 +211,15 @@ package struct SourceCache { try recoverMirrorLocks(in: directory) guard try directory.info("watch-refs.pending") != nil else { return false } let watch = try store.readWatch() - let resolved = try store.readResolved() - var sourceLocations: [String: String] = [:] - for id in watch.sources.keys { - sourceLocations[key(id) + ".git"] = - id.hasPrefix("local:") ? String(id.dropFirst("local:".count)) : id - } - for (id, source) in resolved.sources where source.kind != .wellKnown { - sourceLocations[key(id) + ".git"] = try declaration(sourceID: id, source: source).location - } + var references = try store.retentionReferences() + try references.include(watch: watch) + let sourceLocations = Dictionary( + uniqueKeysWithValues: references.sourceLocations.map { + (key($0.key) + ".git", $0.value) + }) var retained: [String: Set] = [:] - func retain(_ source: String, _ revision: String?) { - if let revision { retained[key(source) + ".git", default: []].insert(revision) } - } - for (source, state) in watch.sources { - if case .revision(let revision) = state.seen { retain(source, revision) } - } - for skill in resolved.skills.values { retain(skill.source, skill.revision) } - for section in resolved.instructions.sections - + resolved.instructions.chatgpt.values.flatMap(\.sections) - { - retain(section.source, section.revision) + for pin in references.git { + retained[key(pin.source) + ".git", default: []].insert(pin.revision) } // Even a manually supplied generation must reach storage before its obsolete pins go away. for file in ["agents.watch", "agents.resolved"] where try directory.info(file) != nil { @@ -407,6 +395,15 @@ package struct SourceCache { let cache = SourceCache(store: StateStore(scope: .project, environment: environment)) return try cache.withResolvedSnapshot(source, body) } + if case .revision(let object) = source.requirement, Self.isObjectID(object) { + let locked = LockedSource( + kind: source.kind, url: source.kind == .git ? source.gitURL : nil, + requirement: .revision(object), path: source.path) + return try withSnapshot( + sourceID: source.identity(environment: store.environment), source: locked, + revision: object + ) { try body(SourceRevision(revision: object), $0) } + } let pin = try resolve(source) let locked = LockedSource( kind: source.kind, url: source.kind == .git ? source.gitURL : nil, @@ -516,49 +513,60 @@ package struct SourceCache { return destination } + /// Makes exact Git objects durable before the caller's journal can reference the new ledger. + /// A failed preparation leaves a cleanup marker; reconciliation keeps the committed closure. + package func retain(references: RetentionReferences) throws { + for (ordinal, pin) in references.git.sorted(by: { + ($0.source, $0.revision) < ($1.source, $1.revision) + }).enumerated() { + guard let location = references.sourceLocations[pin.source], Self.isObjectID(pin.revision) + else { + throw CoreError.invalidState("missing exact retention coordinates") + } + let kind: SourceKind = pin.source.hasPrefix("local:") ? .local : .git + let source = LockedSource( + kind: kind, url: kind == .git ? location : nil, + requirement: .revision(pin.revision)) + _ = try pinnedMirror(sourceID: pin.source, source: source, revision: pin.revision) + let retained = SourceCache( + store: store, + checkpoint: { point in + try checkpoint("retention.\(ordinal)." + point) + }) + try retained.retainWatchRevision( + sourceID: pin.source, source: location, revision: pin.revision) + } + } + /// Retains pins and any cache tree containing a live edit source. /// The caller holds the scope lock, including during failure cleanup. package func prune( referencedBy lock: ResolvedState, watch: WatchState? = nil, transaction: FileTransaction? = nil ) throws { - let watch = try watch ?? store.readWatch() + var references = try RetentionReferences(resolved: lock, cache: self) + try references.include(watch: watch ?? store.readWatch()) + let transactionToUse = transaction ?? FileTransaction(store: store) + try prune(references: references, transaction: transactionToUse) + if transaction == nil { try transactionToUse.commit() } + } + + /// The caller stages pruning with its state generation and commits only after validation. + package func prune(references: RetentionReferences, transaction: FileTransaction) throws { guard let scope = try store.openDirectoryIfPresent(), try scope.info("cache") != nil else { return } - let cache = try scope.child("cache") - let transactionToUse = transaction ?? FileTransaction(store: store) - var paths = Set() - var digests = Set() - for state in watch.sources.values { - if case .artifacts(let artifacts) = state.seen { - digests.formUnion(artifacts.values.map { String($0.dropFirst(7)) }) - } - } - var edits: [URL] = [] - func retain(source: String, revision: String?, artifact: LockedArtifact?) { - if let revision { - paths.insert(materializedURL(sourceID: source, revision: revision).standardizedFileURL.path) - } - if let artifact { - digests.insert(String(artifact.digest.dropFirst(7))) - for file in artifact.files ?? [] { digests.insert(String(file.digest.dropFirst(7))) } - } - } - for skill in lock.skills.values { - retain(source: skill.source, revision: skill.revision, artifact: skill.artifact) - if skill.installs.values.contains(.edit), let source = lock.sources[skill.source] { - let local = try declaration(sourceID: skill.source, source: source).localURL( - environment: store.environment) - edits.append( - try PathSafety.resolvedChild(base: local, subpath: skill.path ?? ".") - .resolvingSymlinksInPath()) - } - } - for section in lock.instructions.sections + lock.instructions.chatgpt.values.flatMap(\.sections) - { - retain(source: section.source, revision: section.revision, artifact: section.artifact) + guard try !TransactionJournal.isPresent(in: scope) else { + throw CoreError.invalidState("transaction recovery must precede pruning") } + let cache = try scope.child("cache") + let transactionToUse = transaction + let paths = Set( + references.git.map { + materializedURL(sourceID: $0.source, revision: $0.revision).standardizedFileURL.path + }) + let digests = Set(references.artifacts.map { String($0.dropFirst(7)) }) + let edits = references.live func edited(_ url: URL) -> Bool { edits.contains { PathSafety.isContained($0, in: url) } } @@ -593,7 +601,6 @@ package struct SourceCache { } } } - if transaction == nil { try transactionToUse.commit() } } package func validatePath(_ url: URL, directory: Bool = true) throws { diff --git a/Sources/AgentsCore/SourceRevisionInspection.swift b/Sources/AgentsCore/SourceRevisionInspection.swift index 9822df9..7b330d6 100644 --- a/Sources/AgentsCore/SourceRevisionInspection.swift +++ b/Sources/AgentsCore/SourceRevisionInspection.swift @@ -71,7 +71,7 @@ extension SourceCache { throw CoreError.notFound("source reference cannot be resolved without fetching: \(ref.name)") } - static func isObjectID(_ value: String) -> Bool { + package static func isObjectID(_ value: String) -> Bool { value.range(of: #"^[0-9a-f]{40}([0-9a-f]{24})?$"#, options: .regularExpression) != nil } } diff --git a/Sources/AgentsInstructions/InstructionCompatibility.swift b/Sources/AgentsInstructions/InstructionCompatibility.swift new file mode 100644 index 0000000..bef452f --- /dev/null +++ b/Sources/AgentsInstructions/InstructionCompatibility.swift @@ -0,0 +1,35 @@ +import AgentsCore +import Foundation + +/// Existing instruction ownership semantics, usable by locked reconstruction and conversion +/// validation without discovery, target selection or filesystem mutation. +package enum InstructionCompatibility { + package static func obsolete(_ deployment: LedgerDeployment, before: Data?) throws -> Data? { + guard let before else { return nil } + switch deployment.ownership { + case .generated: + return Instructions.hash(before) == deployment.expectedHash ? nil : before + case .importBlock: + let edit = try Instructions.removeBlock(from: before) + return deployment.created && !edit.hasCustomContent ? nil : edit.bytes + case .ownedValues: + throw CoreError.invalidState("structured ownership requires its locked document format") + } + } + + package static func renderPrompt(_ bytes: [Data], ids: [String], append: Data?) throws -> Data { + guard bytes.count == ids.count else { throw CoreError.invalidState("prompt input count") } + let sections = try zip(bytes, ids).map { + try Instructions.validateSource($0.0, id: $0.1, allowRestrictions: true) + } + return try Instructions.renderChatGPT(sections: sections, customContent: append) + } + + package static func renderSections(_ bytes: [Data], ids: [String]) throws -> Data { + guard bytes.count == ids.count else { throw CoreError.invalidState("instruction input count") } + let sections = try zip(bytes, ids).map { + try Instructions.validateSource($0.0, id: $0.1, allowRestrictions: true) + } + return Data(try Instructions.render(sections).utf8) + } +} diff --git a/Sources/Components/ComponentLinker.swift b/Sources/Components/ComponentLinker.swift index d2a9826..cd82119 100644 --- a/Sources/Components/ComponentLinker.swift +++ b/Sources/Components/ComponentLinker.swift @@ -58,6 +58,7 @@ final class Linking { var nonGit = Set() var git = Set() var addresses: [String: SourceAddress] = [:] + var sourceUses: [LinkedSourceUse] = [] private var componentMaps: [GroupIdentity: [String: [SourceMapEntry]]] = [:] private var positions: [GroupIdentity: [String: SourceMapEntry]] = [:] @@ -181,6 +182,7 @@ final class Linking { choices[next] = candidate continue } + sourceUses.removeAll() let final = Expansion(linking: self, choices: choices, emit: true) do { try final.expandRoot(root) } catch let error as RequirementSearch { lastFailure = error.constraints @@ -232,6 +234,8 @@ final class Linking { let root = try PathSafety.sanitizeSubpath(source.path ?? ".") let result = SourceAddress(id: id, source: source, contained: nil, root: root) addresses[id] = result + let use = LinkedSourceUse(source: id, root: root, requirement: source.requirement) + if !sourceUses.contains(use) { sourceUses.append(use) } return result } diff --git a/Sources/Components/Expansion.swift b/Sources/Components/Expansion.swift index c862b4c..7b2f98a 100644 --- a/Sources/Components/Expansion.swift +++ b/Sources/Components/Expansion.swift @@ -136,7 +136,8 @@ final class Expansion { LinkedReference( occurrence: occurrence, parent: parent, group: group.name, snapshot: target.view.snapshot, root: target.view.discoveryPath, - constraint: constraint, referenceChain: chain)) + constraint: constraint, referenceChain: chain, + manifestHash: target.document.digest)) } try expand( group.components, @@ -531,7 +532,8 @@ final class Expansion { recipients: recipients, dependencies: dependencies, consumerEditable: !context.producer) components.append( LinkedComponent( - key: key, snapshot: snapshot, pin: pin, payload: payload, + key: key, declaringSnapshot: context.view.snapshot, snapshot: snapshot, pin: pin, + payload: payload, conditions: [condition], recipients: recipients, chatGPT: chatGPT, resources: resources, origins: [origin])) } @@ -582,6 +584,8 @@ final class Expansion { components: result, references: references, constraints: constraints.keys.sorted().flatMap { constraints[$0]! }, selections: choices.filter { constraints[$0.key] != nil }, - sourceSnapshots: linking.session.sourceEvidence(for: snapshots)) + sourceSnapshots: linking.session.sourceEvidence(for: snapshots), + sourceUses: linking.sourceUses, + declaringSnapshots: linking.session.sourceEvidence(for: Set(result.map(\.declaringSnapshot)))) } } diff --git a/Sources/Components/LedgerFreeze.swift b/Sources/Components/LedgerFreeze.swift new file mode 100644 index 0000000..f757013 --- /dev/null +++ b/Sources/Components/LedgerFreeze.swift @@ -0,0 +1,157 @@ +import AgentsCore +import Foundation + +/// Explicit authoring coordinates are keyed by B's source identity, before durable IDs are made. +/// The caller supplies their authored meaning; physical containment never infers relocation. +package struct LedgerFreezeLocations { + package var sources: [String: LedgerLocation] + package init(sources: [String: LedgerLocation]) { self.sources = sources } +} + +package enum LedgerFreeze { + package static func freeze( + _ linked: LinkedComponents, session: SourceResolutionSession, + locations: LedgerFreezeLocations, limits: LedgerLimits + ) throws -> ResolvedLedger { + var ledger = ResolvedLedger() + let allSnapshots = linked.sourceSnapshots + linked.declaringSnapshots + let evidence = Dictionary( + allSnapshots.map { ($0.snapshot, $0) }, uniquingKeysWith: { first, _ in first }) + var sources: [SourceSnapshotID: String] = [:] + func sourceID(_ snapshot: SourceSnapshotID) throws -> String { + if let id = sources[snapshot] { return id } + guard let item = evidence[snapshot] else { + throw CoreError.invalidState("missing snapshot evidence") + } + let container = try item.container.map(sourceID) + let descriptor = item.source + let location = locations.sources[snapshot.source] + if descriptor?.kind == .local, container == nil, location == nil { + throw CoreError.invalidState("local source needs explicit authoring coordinates") + } + let source = LedgerSource( + kind: descriptor?.kind ?? .local, + transport: descriptor?.url ?? (descriptor?.kind == .wellKnown ? snapshot.source : nil), + location: container == nil ? location : nil, + revision: snapshot.revision, version: item.pin?.version, container: container, + namespace: item.container.map { String(snapshot.source.dropFirst($0.source.count)) }) + let id = try ResolvedLedgerCodec.digest(source) + ledger.sources[id] = source + sources[snapshot] = id + return id + } + for item in allSnapshots { _ = try sourceID(item.snapshot) } + for use in linked.sourceUses { + for snapshot in allSnapshots where snapshot.snapshot.source == use.source { + ledger.sourceUses.append( + .init( + source: try sourceID(snapshot.snapshot), root: use.root, + requirement: use.requirement?.canonical)) + } + } + var objectBytes = 0 + for component in linked.components { + try Task.checkCancellation() + var resourceIDs: [String] = [] + for resource in component.resources { + let id = try sourceID(resource.snapshot) + let mode: InstallMode? + if case .skill(_, let selection, _) = component.payload { + mode = selection + } else { + mode = nil + } + let record: LedgerResource + if mode == .edit { + guard let base = locations.sources[resource.snapshot.source] else { + throw CoreError.invalidState("live skill needs explicit location") + } + var location = base + location.path = base.path == "." ? resource.path : base.path + "/" + resource.path + record = .init( + kind: .liveEdit, source: id, path: resource.path, hash: resource.hash, + entries: [], location: location) + } else { + let url = try session.resource(snapshot: resource.snapshot, path: resource.path) + var source = ledger.sources[id]! + while let container = source.container { source = ledger.sources[container]! } + let git = SourceCache.isObjectID(source.revision) + let kind: LedgerResource.Kind = + resource.artifact != nil ? .artifact : git ? .git : .embedded + let captured = try LedgerResources.capture( + url, embed: kind != .git, limits: limits, + sourceRoot: try session.resource(snapshot: resource.snapshot, path: ".")) + let flags = + captured.entries.count == 1 && captured.entries[0].kind == .file + ? [resource.path: captured.flags["."] ?? false] : captured.flags + guard captured.hash == resource.hash, + resource.executableFlags.isEmpty || flags == resource.executableFlags + else { + throw CoreError.invalidState("linked resource changed before freeze") + } + for (digest, bytes) in captured.objects where ledger.contentObjects[digest] == nil { + guard bytes.count <= limits.objectBytes - objectBytes else { + throw CoreError.invalidState("ledger aggregate content budget") + } + ledger.contentObjects[digest] = bytes + objectBytes += bytes.count + } + record = .init( + kind: kind, source: id, path: resource.path, hash: resource.hash, + entries: captured.entries, support: captured.support, artifact: resource.artifact) + } + let resourceID = try ResolvedLedgerCodec.digest(record) + ledger.resources[resourceID] = record + resourceIDs.append(resourceID) + } + let payload: LedgerValue + switch component.payload { + case .declaration(let declaration): payload = try LedgerPayload.component(declaration) + case .skill(let skill, let mode, let native): + payload = .init(object: [ + "name": .init(skill.name), "description": .init(skill.description), + "mode": .init(mode.rawValue), "native": LedgerPayload.native(native), + ]) + case .instruction(let instruction, let prompt, let native): + var fields: [String: LedgerValue] = [ + "name": .init(instruction.name), + "sourceHash": .init(instruction.section.hash), "native": LedgerPayload.native(native), + ] + fields["prompt"] = prompt.map { .init($0) } + payload = .init(object: fields) + } + let record = LedgerComponent( + declaringSource: try sourceID(component.declaringSnapshot), + source: try sourceID(component.snapshot), root: component.key.root, + group: component.key.group, kind: component.key.kind.rawValue, name: component.key.name, + revision: component.pin?.revision, version: component.pin?.version, + payload: payload, conditions: component.conditions.map(LedgerCondition.init), + recipients: component.recipients.sorted { $0.rawValue < $1.rawValue }, + chatGPT: component.chatGPT, resources: resourceIDs) + let id = try ResolvedLedgerCodec.digest(record) + ledger.components[id] = record + for origin in component.origins { + ledger.occurrences.append( + .init( + declaringSource: try sourceID(component.declaringSnapshot), + manifestPath: origin.provenance.relativePath, id: origin.occurrence, component: id, + reference: origin.reference, dependencies: try origin.dependencies.map(sourceID), + condition: LedgerCondition(origin.condition), + recipients: origin.recipients.sorted { $0.rawValue < $1.rawValue }, + consumerEditable: origin.consumerEditable)) + } + } + ledger.occurrences.sort { $0.id < $1.id } + ledger.groups = try linked.references.map { reference in + LedgerGroup( + id: reference.occurrence, parent: reference.parent, + source: try sourceID(reference.snapshot), root: reference.root, name: reference.group, + requirement: reference.constraint?.requirement?.canonical, + manifestHash: reference.manifestHash, + children: (linked.references.filter { $0.parent == reference.occurrence }.map(\.occurrence) + + ledger.occurrences.filter { $0.reference == reference.occurrence }.map(\.id)).sorted()) + } + try ledger.validate() + return ledger + } +} diff --git a/Sources/Components/LedgerPayload.swift b/Sources/Components/LedgerPayload.swift new file mode 100644 index 0000000..0e8fc6a --- /dev/null +++ b/Sources/Components/LedgerPayload.swift @@ -0,0 +1,186 @@ +import AgentsCore + +/// Converts typed symbolic payloads to the ledger's explicit tagged vocabulary. +enum LedgerPayload { + static func component(_ component: ComponentDeclaration) throws -> LedgerValue { + var fields: [String: LedgerValue] + let agents: [AgentID]? + let condition: DeclarationCondition? + let native: NativeConfiguration + switch component { + case .mcpServer(let name, let transport, let a, let c, let n): + fields = ["name": .init(name), "transport": self.transport(transport)] + (agents, condition, native) = (a, c, n) + case .hook(let name, let event, let run, let matcher, let timeout, let a, let c, let n): + let eventValue: LedgerValue + switch event { + case .beforeTool: eventValue = .init("beforeTool") + case .afterTool: eventValue = .init("afterTool") + case .sessionStart: eventValue = .init("sessionStart") + case .sessionEnd: eventValue = .init("sessionEnd") + case .native(let value): eventValue = .init(object: ["native": .init(value)]) + } + fields = ["name": .init(name), "event": eventValue, "run": executable(run)] + fields["matcher"] = matcher.map { .init($0) } + fields["timeoutSeconds"] = timeout.map { .init(integer: $0) } + (agents, condition, native) = (a, c, n) + case .subagent(let name, let description, let body, let model, let tools, let a, let c, let n): + fields = ["name": .init(name), "description": .init(description), "prompt": prompt(body)] + fields["model"] = model.map { .init($0) } + fields["tools"] = tools.map(strings) + (agents, condition, native) = (a, c, n) + case .command(let name, let description, let body, let parameters, let a, let c, let n): + fields = [ + "name": .init(name), "description": .init(description), "prompt": prompt(body), + "parameters": .init( + array: parameters.map { parameter in + var value = [ + "name": LedgerValue(parameter.name), "description": .init(parameter.description), + ] + value["defaultValue"] = parameter.defaultValue.map { .init($0) } + return .init(object: value) + }), + ] + (agents, condition, native) = (a, c, n) + case .lspServer(let name, let run, let languages, let options, let a, let c, let n): + fields = [ + "name": .init(name), "run": executable(run), + "languages": .init(object: languages.mapValues { .init($0) }), + "initializationOptions": .init(object: options.mapValues(value)), + ] + (agents, condition, native) = (a, c, n) + case .permissions(let name, let rules, let a, let c, let n): + fields = ["name": .init(name), "rules": .init(array: rules.map(rule))] + (agents, condition, native) = (a, c, n) + case .ignore(let name, let patterns, let purpose, let a, let c, let n): + fields = [ + "name": .init(name), "patterns": strings(patterns), "purpose": .init(purpose.rawValue), + ] + (agents, condition, native) = (a, c, n) + case .plugin( + let name, let path, let source, let mode, let select, let exclude, let a, let c, let n): + fields = [ + "name": .init(name), "path": .init(path), "source": .init(source), + "mode": .init(mode.rawValue), + "exclude": .init(array: exclude.map(reference)), + ] + fields["select"] = select.map { strings($0.map(\.rawValue)) } + (agents, condition, native) = (a, c, n) + case .skills, .instructions: + throw CoreError.invalidState("selected content requires its frozen payload") + } + fields["agents"] = agents.map { strings($0.map(\.rawValue)) } + fields["condition"] = condition.map(self.condition) + fields["native"] = self.native(native) + return .init(object: fields) + } + + static func native(_ native: NativeConfiguration) -> LedgerValue { + .init(object: native.mapValues { .init(object: $0.mapValues(value)) }) + } + + static func condition(_ condition: DeclarationCondition) -> LedgerValue { + var fields: [String: LedgerValue] = [:] + fields["agents"] = condition.agents.map { strings($0.map(\.rawValue)) } + fields["scopes"] = condition.scopes.map { strings($0.map(\.rawValue)) } + fields["platforms"] = condition.platforms.map { strings($0.map(\.rawValue)) } + return .init(object: fields) + } + + static func strings(_ values: [String]) -> LedgerValue { .init(array: values.map { .init($0) }) } + + private static func value(_ value: NativeValue) -> LedgerValue { + switch value { + case .string(let text): .init(text) + case .integer(let integer): .init(integer: integer) + case .decimal(let decimal): .init(decimal, kind: .decimal) + case .boolean(let boolean): .init(boolean: boolean) + case .null: .init() + case .array(let array): .init(array: array.map(self.value)) + case .object(let object): .init(object: object.mapValues(self.value)) + } + } + + private static func binding(_ binding: RuntimeBinding) -> LedgerValue { + switch binding { + case .literal(let value): .init(value, kind: .literal) + case .environment(let value): .init(value, kind: .environment) + case .secret(let value): .init(value, kind: .secret) + } + } + + private static func resource(_ resource: ResourceDeclaration) -> LedgerValue { + var fields = ["path": LedgerValue(resource.path)] + fields["source"] = resource.source.map { .init($0) } + return .init(object: fields) + } + + private static func executable(_ run: ExecutableDeclaration) -> LedgerValue { + var fields: [String: LedgerValue] = [ + "executable": .init(run.executable), "arguments": strings(run.arguments), + "environment": .init(object: run.environment.mapValues(binding)), + ] + fields["workingDirectory"] = run.workingDirectory.map(resource) + return .init(object: fields) + } + + private static func transport(_ transport: MCPTransportDeclaration) -> LedgerValue { + switch transport { + case .stdio(let run): return .init(object: ["kind": .init("stdio"), "run": executable(run)]) + case .streamableHTTP(let url, let headers): + return .init(object: [ + "kind": .init("streamableHTTP"), "url": .init(url), + "headers": .init(object: headers.mapValues(binding)), + ]) + case .sse(let url, let headers): + return .init(object: [ + "kind": .init("sse"), "url": .init(url), + "headers": .init(object: headers.mapValues(binding)), + ]) + } + } + + private static func prompt(_ prompt: PromptBody) -> LedgerValue { + switch prompt { + case .literal(let text): .init(text, kind: .literal) + case .file(let file): .init(object: ["file": resource(file)]) + } + } + + private static func rule(_ rule: PermissionRuleDeclaration) -> LedgerValue { + let action: String + let operation: PermissionOperationDeclaration + let pattern: String + switch rule { + case .allow(let op, let p): (action, operation, pattern) = ("allow", op, p) + case .ask(let op, let p): (action, operation, pattern) = ("ask", op, p) + case .deny(let op, let p): (action, operation, pattern) = ("deny", op, p) + } + let op: LedgerValue + switch operation { + case .read: op = .init("read") + case .write: op = .init("write") + case .execute: op = .init("execute") + case .tool(let name): op = .init(object: ["tool": .init(name)]) + } + return .init(object: ["action": .init(action), "operation": op, "pattern": .init(pattern)]) + } + + private static func reference(_ reference: ComponentReferenceDeclaration) -> LedgerValue { + let kind: String + let name: String + switch reference { + case .skill(let value): (kind, name) = ("skills", value) + case .instruction(let value): (kind, name) = ("instructions", value) + case .mcpServer(let value): (kind, name) = ("mcpServer", value) + case .hook(let value): (kind, name) = ("hook", value) + case .subagent(let value): (kind, name) = ("subagent", value) + case .command(let value): (kind, name) = ("command", value) + case .lspServer(let value): (kind, name) = ("lspServer", value) + case .permissions(let value): (kind, name) = ("permissions", value) + case .ignore(let value): (kind, name) = ("ignore", value) + case .plugin(let value): (kind, name) = ("plugin", value) + } + return .init(object: ["kind": .init(kind), "name": .init(name)]) + } +} diff --git a/Sources/Components/LedgerReplay.swift b/Sources/Components/LedgerReplay.swift new file mode 100644 index 0000000..da41968 --- /dev/null +++ b/Sources/Components/LedgerReplay.swift @@ -0,0 +1,277 @@ +import AgentsCore +import AgentsInstructions +import Foundation + +/// Borrowed trees are valid only inside the replay closure. Shared-file values are intentions; +/// physical ownership, secret binding and publication remain with the applying operation. +package struct ReplayedArtifact { + package var name: String + package var kind: LedgerArtifactDigest.Kind + package var bytes: Data? + package var tree: URL? + package var values: LedgerValue? + package var location: LedgerLocation? + + package init( + name: String, kind: LedgerArtifactDigest.Kind, bytes: Data? = nil, + tree: URL? = nil, values: LedgerValue? = nil, location: LedgerLocation? = nil + ) { + self.name = name + self.kind = kind + self.bytes = bytes + self.tree = tree + self.values = values + self.location = location + } + + package func digest(limits: LedgerLimits) throws -> LedgerArtifactDigest { + let hash: String + switch kind { + case .link: + guard let location, bytes == nil, tree == nil, values == nil else { + throw CoreError.invalidState("invalid live link") + } + hash = try ResolvedLedgerCodec.digest(location) + case .file, .registration: + guard let bytes, tree == nil, values == nil else { + throw CoreError.invalidState("invalid rendered file") + } + hash = "sha256:" + FileHash.sha256Hex(data: bytes) + case .tree: + guard let tree, bytes == nil, values == nil else { + throw CoreError.invalidState("invalid rendered tree") + } + let captured = try LedgerResources.capture(tree, embed: false, limits: limits) + hash = try ResolvedLedgerCodec.digest( + TreeDigest(content: captured.hash, entries: captured.entries)) + case .ownedValues: + guard let values, bytes == nil, tree == nil else { + throw CoreError.invalidState("invalid owned values") + } + hash = try ResolvedLedgerCodec.digest(values) + } + return .init(name: name, kind: kind, hash: hash) + } + + private struct TreeDigest: Encodable { + let content: String + let entries: [LedgerEntry] + } +} + +package typealias LedgerRenderer = ( + _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL] +) throws -> [ReplayedArtifact] + +package enum LedgerReplay { + /// Only formats with implemented production semantics are registered here. Tests explicitly + /// supply their own renderer table; a format is never selected by agent or current version. + package static var compatibilityRenderers: [String: LedgerRenderer] { + [ + "agents/skill@1": skill, "agents/instructions@1": instructions, + "agents/claude-import@1": forwarding, "agents/chatgpt@1": chatGPT, + ] + } + + package static func withReplay( + _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], limits: LedgerLimits, + renderers: [String: LedgerRenderer] = compatibilityRenderers, + _ body: ([ReplayedArtifact]) throws -> T + ) throws -> T { + try run( + ledger, store: store, roots: roots, limits: limits, renderers: renderers, + recording: false + ) { artifacts, _ in try body(artifacts) } + } + + /// Seals renderer output identities into a candidate before encoding or publication. + package static func prepareLowerings( + _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], limits: LedgerLimits, + renderers: [String: LedgerRenderer] = compatibilityRenderers + ) throws -> ResolvedLedger { + try run( + ledger, store: store, roots: roots, limits: limits, renderers: renderers, + recording: true + ) { _, lowerings in + var candidate = ledger + candidate.lowerings = lowerings + try candidate.validate() + return candidate + } + } + + private static func run( + _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], limits: LedgerLimits, + renderers: [String: LedgerRenderer], recording: Bool, + _ body: ([ReplayedArtifact], [LockedLowering]) throws -> T + ) throws -> T { + try ResolvedLedgerCodec.checkModel(ledger, limits: limits) + try ledger.validate() + try Task.checkCancellation() + let platform = ProcessInfo.processInfo.operatingSystemVersionString + #if os(macOS) + let current = "macos" + #else + let current = "linux" + #endif + for lowering in ledger.lowerings { + guard renderers[lowering.format] != nil else { + throw CoreError.invalidState("unknown renderer format") + } + guard lowering.platform == current else { + throw CoreError.invalidState("locked lowering is incompatible with platform: " + platform) + } + } + let workspace = FileManager.default.temporaryDirectory.appendingPathComponent( + "agents-ledger-" + UUID().uuidString) + try FileSystem.createDirectory(at: workspace) + defer { try? FileManager.default.removeItem(at: workspace) } + return try SourceResolutionSession.withTemporaryRead(store: store) { session in + var acquired: [String: URL] = [:] + for (id, resource) in ledger.resources.sorted(by: { $0.key < $1.key }) { + try Task.checkCancellation() + let file: URL + if resource.kind == .liveEdit { + guard let location = resource.location else { + throw CoreError.invalidState("missing live location") + } + file = try location.resolve(roots: roots) + var directory: ObjCBool = false + guard FileManager.default.fileExists(atPath: file.path, isDirectory: &directory), + directory.boolValue + else { + throw CoreError.notFound("live edit skill source") + } + } else if resource.kind == .embedded || resource.kind == .artifact { + let destination = workspace.appendingPathComponent(UUID().uuidString) + file = + resource.support.isEmpty + ? destination + : try PathSafety.resolvedChild(base: destination, subpath: resource.path) + var embedded = resource + embedded.kind = .embedded + try LedgerResources.materialize(embedded, objects: ledger.contentObjects, at: destination) + } else { + var source = ledger.sources[resource.source]! + while let container = source.container { source = ledger.sources[container]! } + let declaration: SourceDeclaration + if let transport = source.transport { + declaration = SourceDeclaration( + kind: .git, location: transport, requirement: .revision(source.revision)) + } else if let location = source.location { + declaration = SourceDeclaration( + kind: .local, location: try location.resolve(roots: roots).path, + requirement: .revision(source.revision)) + } else { + throw CoreError.invalidState("missing pinned source coordinates") + } + let view = try session.snapshot( + declaration, at: SourceRevision(revision: source.revision)) + file = try view.resource(resource.path) + } + if resource.kind != .liveEdit { + let captured = try LedgerResources.capture(file, embed: false, limits: limits) + let expected = resource.entries.map { entry -> LedgerEntry in + var entry = entry + entry.object = nil + return entry + } + guard captured.hash == resource.hash, captured.entries == expected else { + throw CoreError.invalidState("locked resource content or execute bits changed") + } + } + acquired[id] = file + } + var result: [ReplayedArtifact] = [] + var sealed: [LockedLowering] = [] + var names = Set() + for lowering in ledger.lowerings { + try Task.checkCancellation() + let rendered = try renderers[lowering.format]!(lowering, ledger, acquired) + let digests = try rendered.map { try $0.digest(limits: limits) } + guard recording || digests == lowering.artifacts else { + throw CoreError.invalidState("locked renderer output hash mismatch") + } + for artifact in rendered { + guard names.insert(artifact.name).inserted else { + throw CoreError.invalidState("overlapping rendered artifacts") + } + } + var locked = lowering + locked.artifacts = digests + sealed.append(locked) + result += rendered + } + return try body(result, sealed) + } + } + + private static func skill( + _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL] + ) throws -> [ReplayedArtifact] { + guard lowering.resources.count == 1, let resource = lowering.resources.first, + let tree = resources[resource], let name = lowering.layout.object?["name"]?.text + else { + throw CoreError.invalidState("invalid skill lowering") + } + if let record = ledger.resources[resource], record.kind == .liveEdit { + return [.init(name: name, kind: .link, location: record.location)] + } + return [.init(name: name, kind: .tree, tree: tree)] + } + + private static func instructions( + _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL] + ) throws -> [ReplayedArtifact] { + let bytes = try lowering.resources.map { id in + guard let resource = resources[id] else { + throw CoreError.invalidState("missing instruction input") + } + return try FileSystem.read(at: resource) + } + guard let name = lowering.layout.object?["name"]?.text, + lowering.layout.object?["headingOffset"]?.integer ?? 0 == 0 + else { + throw CoreError.invalidState("unsupported instruction layout") + } + return [ + .init( + name: name, kind: .file, + bytes: try InstructionCompatibility.renderSections(bytes, ids: lowering.resources)) + ] + } + + private static func chatGPT( + _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL] + ) throws -> [ReplayedArtifact] { + guard let count = lowering.layout.object?["sectionCount"]?.integer, count > 0, + count <= lowering.resources.count, lowering.resources.count <= count + 1, + let name = lowering.layout.object?["name"]?.text + else { throw CoreError.invalidState("invalid prompt layout") } + let sections = try lowering.resources.prefix(count).map { id in + guard let file = resources[id] else { throw CoreError.invalidState("missing prompt section") } + return try FileSystem.read(at: file) + } + let append = try lowering.resources.dropFirst(count).first.map { id in + guard let file = resources[id] else { throw CoreError.invalidState("missing prompt append") } + return try FileSystem.read(at: file) + } + return [ + .init( + name: name, kind: .file, + bytes: try InstructionCompatibility.renderPrompt( + sections, ids: Array(lowering.resources.prefix(count)), append: append)) + ] + } + + private static func forwarding( + _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL] + ) throws -> [ReplayedArtifact] { + guard let name = lowering.layout.object?["name"]?.text, + let path = ClaudeInstructionPath(rawValue: name) + else { throw CoreError.invalidState("invalid forwarding layout") } + return [ + .init(name: name, kind: .file, bytes: Data(ClaudeForwarding.renderBlock(for: path).utf8)) + ] + } +} diff --git a/Sources/Components/LinkedComponents.swift b/Sources/Components/LinkedComponents.swift index 5803ffc..6f35f39 100644 --- a/Sources/Components/LinkedComponents.swift +++ b/Sources/Components/LinkedComponents.swift @@ -60,6 +60,7 @@ package struct ContributionOrigin: Equatable, Sendable { package struct LinkedComponent: Equatable, Sendable { package let key: ComponentKey + package let declaringSnapshot: SourceSnapshotID package let snapshot: SourceSnapshotID package let pin: SourceRevision? package let payload: LinkedPayload @@ -86,6 +87,13 @@ package struct LinkedReference: Equatable, Sendable { package let root: String package let constraint: SourceConstraint? package let referenceChain: [SourceSpan] + package let manifestHash: String +} + +package struct LinkedSourceUse: Equatable, Sendable { + package let source: String + package let root: String + package let requirement: SourceRequirement? } package struct LinkedComponents: Equatable, Sendable { @@ -94,6 +102,8 @@ package struct LinkedComponents: Equatable, Sendable { package let constraints: [SourceConstraint] package let selections: [String: SourceRevision] package let sourceSnapshots: [SourceSnapshotEvidence] + package var sourceUses: [LinkedSourceUse] = [] + package var declaringSnapshots: [SourceSnapshotEvidence] = [] /// A semantic projection protects pins, payloads, resource evidence and effective targets. /// Instructions retain order within each recipient or named prompt. Reference counts and diff --git a/Tests/AgentsCoreTests/IndependentLedgerAdmissionTests.swift b/Tests/AgentsCoreTests/IndependentLedgerAdmissionTests.swift new file mode 100644 index 0000000..e8a2493 --- /dev/null +++ b/Tests/AgentsCoreTests/IndependentLedgerAdmissionTests.swift @@ -0,0 +1,219 @@ +import AgentsManifest +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Independent ledger admission") +struct IndependentLedgerAdmissionTests { + private var limits: LedgerLimits { + LedgerLimits( + encodedBytes: 32_768, depth: 32, nodes: 1_000, + objectBytes: 64, entries: 16, keyBytes: 256) + } + + private func fixture() -> ResolvedLedger { + var ledger = ResolvedLedger() + ledger.sources["source"] = LedgerSource( + kind: .local, revision: "revision", version: "braces { } and \"quoted\"") + let first = Data("a".utf8) + let second = Data("bc".utf8) + let firstID = "sha256:" + FileHash.sha256Hex(data: first) + let secondID = "sha256:" + FileHash.sha256Hex(data: second) + ledger.contentObjects = [firstID: first, secondID: second] + ledger.resources["first"] = LedgerResource( + kind: .embedded, source: "source", path: "first", hash: firstID, + entries: [ + LedgerEntry( + path: ".", kind: .file, object: firstID, executable: false, byteCount: first.count) + ]) + ledger.resources["second"] = LedgerResource( + kind: .embedded, source: "source", path: "second", hash: secondID, + entries: [ + LedgerEntry( + path: ".", kind: .file, object: secondID, executable: true, byteCount: second.count) + ]) + return ledger + } + + private func wire(_ ledger: ResolvedLedger) throws -> Data { + try ResolvedLedgerCodec.encode(ledger, limits: limits) + } + + private func object(_ data: Data) throws -> [String: Any] { + try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + + private func data(_ object: [String: Any]) throws -> Data { + try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) + } + + @Test func validControlsAndUnchangedReplacement() throws { + let ledger = fixture() + let canonical = try wire(ledger) + #expect(try ResolvedLedgerCodec.decode(canonical, limits: limits) == ledger) + + let pretty = try JSONSerialization.data( + withJSONObject: JSONSerialization.jsonObject(with: canonical), + options: [.prettyPrinted, .sortedKeys]) + #expect(pretty != canonical) + #expect(try ResolvedLedgerCodec.decode(pretty, limits: limits) == ledger) + #expect(try ResolvedLedgerCodec.replacement(ledger, existing: pretty, limits: limits) == nil) + var changed = ledger + changed.sources["source"]?.version = "another version" + let replacement = try #require( + try ResolvedLedgerCodec.replacement(changed, existing: pretty, limits: limits)) + #expect(try ResolvedLedgerCodec.decode(replacement, limits: limits) == changed) + } + + @Test func duplicateAndUnknownKeysAreRejected() throws { + let canonical = try wire(fixture()) + let text = try #require(String(data: canonical, encoding: .utf8)) + for prefix in [#""version":2,"#, #""ver\u0073ion":2,"#] { + let duplicate = Data(("{" + prefix + text.dropFirst()).utf8) + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(duplicate, limits: limits) + } + } + + var root = try object(canonical) + root["unexpected"] = NSNull() + let unknownRoot = try data(root) + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(unknownRoot, limits: limits) + } + root = try object(canonical) + var sources = try #require(root["sources"] as? [String: Any]) + var source = try #require(sources["source"] as? [String: Any]) + source["unexpected"] = NSNull() + sources["source"] = source + root["sources"] = sources + let unknownNested = try data(root) + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(unknownNested, limits: limits) + } + } + + @Test func knownOptionalNullIsAccepted() throws { + let ledger = fixture() + var root = try object(wire(ledger)) + var sources = try #require(root["sources"] as? [String: Any]) + var source = try #require(sources["source"] as? [String: Any]) + source["transport"] = NSNull() + sources["source"] = source + root["sources"] = sources + let bytes = try data(root) + #expect(try ResolvedLedgerCodec.decode(bytes, limits: limits) == ledger) + #expect(try ResolvedLedgerCodec.replacement(ledger, existing: bytes, limits: limits) == nil) + } + + @Test func versionsAndTagsAreStrict() throws { + let canonical = try wire(fixture()) + for version in [1, 3] { + var root = try object(canonical) + root["version"] = version + let bytes = try data(root) + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(bytes, limits: limits) + } + } + var root = try object(canonical) + var resources = try #require(root["resources"] as? [String: Any]) + var resource = try #require(resources["first"] as? [String: Any]) + resource["kind"] = "unknown" + resources["first"] = resource + root["resources"] = resources + let bytes = try data(root) + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(bytes, limits: limits) + } + } + + @Test func encodedAndAggregateObjectBudgets() throws { + let ledger = fixture() + let bytes = try wire(ledger) + var bound = limits + bound.encodedBytes = bytes.count + bound.objectBytes = 3 + #expect(try ResolvedLedgerCodec.decode(bytes, limits: bound) == ledger) + bound.encodedBytes = bytes.count - 1 + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(bytes, limits: bound) + } + bound.encodedBytes = bytes.count + bound.objectBytes = 2 + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(bytes, limits: bound) + } + + // JSON escapes do not change the decoded Base64 value or its byte budget. + let text = try #require(String(data: bytes, encoding: .utf8)) + let escaped = text.replacingOccurrences(of: #""YQ==""#, with: #""\u0059Q==""#) + #expect(escaped != text) + let escapedBytes = Data(escaped.utf8) + bound.encodedBytes = escapedBytes.count + bound.objectBytes = 3 + #expect(try ResolvedLedgerCodec.decode(escapedBytes, limits: bound) == ledger) + } + + @Test func structureAndEntryBudgets() throws { + let bytes = try wire(fixture()) + var bound = limits + bound.entries = 2 + #expect(try ResolvedLedgerCodec.decode(bytes, limits: bound) == fixture()) + bound.entries = 1 + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(bytes, limits: bound) + } + + let shallow = Data(#"{"a":[1,2]}"#.utf8) + bound = limits + bound.depth = 2 + bound.nodes = 4 + try LedgerAdmission.check(shallow, limits: bound) + bound.depth = 1 + #expect(throws: (any Error).self) { try LedgerAdmission.check(shallow, limits: bound) } + bound.depth = 2 + bound.nodes = 3 + #expect(throws: (any Error).self) { try LedgerAdmission.check(shallow, limits: bound) } + } + + @Test func corruptReferencesAndPathsFailAtCodecBoundary() throws { + let valid = fixture() + #expect(try ResolvedLedgerCodec.decode(wire(valid), limits: limits) == valid) + var broken = valid + let objectID = try #require(broken.resources["first"]?.entries.first?.object) + broken.contentObjects[objectID] = Data("different".utf8) + #expect(throws: (any Error).self) { _ = try wire(broken) } + + broken = valid + broken.contentObjects.removeValue(forKey: objectID) + #expect(throws: (any Error).self) { _ = try wire(broken) } + broken = valid + broken.resources["first"]?.source = "missing" + #expect(throws: (any Error).self) { _ = try wire(broken) } + for path in ["../escape", "/absolute", "a/../b"] { + broken = valid + broken.resources["first"]?.entries[0].path = path + #expect(throws: (any Error).self) { _ = try wire(broken) } + } + } + + @Test func publicV1OperationsPreserveV2Files() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let environment = RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: [:]) + let store = StateStore(scope: .project, environment: environment) + try store.save(declaration: Declaration(), resolved: ResolvedState()) + let declaration = try Data(contentsOf: store.declarationURL) + let bytes = try wire(fixture()) + try bytes.write(to: store.resolvedURL) + #expect(throws: (any Error).self) { _ = try store.loadResolved() } + #expect(throws: (any Error).self) { + try store.save(declaration: Declaration(), resolved: ResolvedState()) + } + #expect(try Data(contentsOf: store.resolvedURL) == bytes) + #expect(try Data(contentsOf: store.declarationURL) == declaration) + } +} diff --git a/Tests/AgentsCoreTests/LedgerCodecTests.swift b/Tests/AgentsCoreTests/LedgerCodecTests.swift new file mode 100644 index 0000000..29be10e --- /dev/null +++ b/Tests/AgentsCoreTests/LedgerCodecTests.swift @@ -0,0 +1,130 @@ +import CPlatform +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Ledger codec") +struct LedgerCodecTests { + @Test func emptyAndUnchangedBytes() throws { + let value = ResolvedLedger() + let bytes = try ResolvedLedgerCodec.encode(value, limits: .standard) + let spaced = Data(" \n".utf8) + bytes + #expect(try ResolvedLedgerCodec.decode(spaced, limits: .standard) == value) + #expect(try ResolvedLedgerCodec.replacement(value, existing: spaced, limits: .standard) == nil) + #expect(throws: (any Error).self) { _ = try StateStore.decode(bytes, as: ResolvedState.self) } + } + + @Test func strictAdmissionAndReferences() throws { + try LedgerAdmission.check( + Data(("{\"" + String(repeating: "k", count: 20_000) + "\":null}").utf8), limits: .standard) + let bytes = try ResolvedLedgerCodec.encode(ResolvedLedger(), limits: .standard) + var object = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + object["unknown"] = NSNull() + let unknown = try JSONSerialization.data(withJSONObject: object) + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(unknown, limits: .standard) + } + for malformed in [ + "{\"version\":2,\"version\":2}", "{\"a\":1,\"\\u0061\":2}", "[1,]", "[01]", "[true false]", + "\"\\uZZZZ\"", + ] { + #expect(throws: (any Error).self) { + try LedgerAdmission.check(Data(malformed.utf8), limits: .standard) + } + } + var limits = LedgerLimits.standard + limits.encodedBytes = bytes.count - 1 + #expect(throws: (any Error).self) { _ = try ResolvedLedgerCodec.decode(bytes, limits: limits) } + limits = .standard + limits.objectBytes = 2 + #expect(throws: (any Error).self) { + try LedgerAdmission.check(Data("{\"contentObjects\":{\"a\":\"YWJj\"}}".utf8), limits: limits) + } + limits = .standard + limits.depth = 2 + #expect(throws: (any Error).self) { + try LedgerAdmission.check(Data("[[[[]]]]".utf8), limits: limits) + } + var ledger = ResolvedLedger() + ledger.contentObjects["sha256:" + String(repeating: "0", count: 64)] = Data("bad".utf8) + #expect(throws: (any Error).self) { try ledger.validate() } + } + + @Test func locationsKeepAuthoredMeaning() throws { + let roots = ["home": URL(fileURLWithPath: "/new-home")] + #expect( + try LedgerLocation(kind: .registered, root: "home", path: "skills").resolve(roots: roots).path + == "/new-home/skills") + #expect( + try LedgerLocation(kind: .absolute, path: "/old-home/skills").resolve(roots: roots).path + == "/old-home/skills") + #expect( + try LedgerLocation(kind: .authoringRelative, root: "home", path: "../skills").resolve( + roots: roots + ).path == "/skills") + for path in ["../escape", "/absolute", "a/../b", "a//b", "~/x"] { + #expect(throws: (any Error).self) { + try LedgerLocation(kind: .registered, root: "home", path: path).validate() + } + } + } + + @Test func codecMeasurement() throws { + guard ProcessInfo.processInfo.environment["AGENTS_LEDGER_MEASURE"] == "1" else { return } + let count = + Int(ProcessInfo.processInfo.environment["AGENTS_LEDGER_MEASURE_BYTES"] ?? "") ?? 50 * 1024 + * 1024 + let entries = + Int(ProcessInfo.processInfo.environment["AGENTS_LEDGER_MEASURE_ENTRIES"] ?? "") ?? 1_000 + var ledger = ResolvedLedger() + let bytes = Data(repeating: 0x61, count: count) + let digest = "sha256:" + FileHash.sha256Hex(data: bytes) + ledger.contentObjects[digest] = bytes + let emptyDigest = "sha256:" + FileHash.sha256Hex(data: Data()) + ledger.contentObjects[emptyDigest] = Data() + ledger.sources["root"] = LedgerSource( + kind: .local, location: .init(kind: .registered, root: "project", path: "."), revision: "live" + ) + ledger.resources["resource"] = LedgerResource( + kind: .embedded, source: "root", path: ".", hash: digest, + entries: [LedgerEntry(path: ".", kind: .directory, executable: false)] + + (1.. (nodes: Int, depth: Int) { + let children: [Any] + if let object = value as? [String: Any] { + children = Array(object.values) + } else if let array = value as? [Any] { + children = array + } else { + children = [] + } + return children.reduce((1, depth)) { result, child in + let nested = shape(child, depth: depth + 1) + return (result.0 + nested.nodes, max(result.1, nested.depth)) + } + } + let structure = shape(try JSONSerialization.jsonObject(with: encoded)) + var usage = rusage() + #if os(Linux) + _ = getrusage(Int32(RUSAGE_SELF.rawValue), &usage) + #else + _ = getrusage(RUSAGE_SELF, &usage) + #endif + #if os(Linux) + let rss = usage.ru_maxrss * 1024 + #else + let rss = usage.ru_maxrss + #endif + print( + "LEDGER_MEASUREMENT nodes=\(structure.nodes) depth=\(structure.depth) entries=\(entries) peakRSSBytes=\(rss) decodedBytes=\(count) encodedBytes=\(encoded.count) seconds=\(Date().timeIntervalSince(start))" + ) + } +} diff --git a/Tests/AgentsCoreTests/LedgerRetentionTests.swift b/Tests/AgentsCoreTests/LedgerRetentionTests.swift new file mode 100644 index 0000000..8feff32 --- /dev/null +++ b/Tests/AgentsCoreTests/LedgerRetentionTests.swift @@ -0,0 +1,60 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Ledger retention") +struct LedgerRetentionTests { + @Test func completeClosureRetainsNonSkillPinsAndWatch() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) + try FileSystem.createDirectory(at: store.directory) + let cache = SourceCache(store: store) + let source = "github.com/example/components" + let pin = String(repeating: "a", count: 40) + let obsolete = String(repeating: "b", count: 40) + let kept = cache.materializedURL(sourceID: source, revision: pin) + let unused = cache.materializedURL(sourceID: source, revision: obsolete) + try FileSystem.createDirectory(at: kept) + try FileSystem.createDirectory(at: unused) + var ledger = ResolvedLedger() + ledger.sources["group-source"] = LedgerSource( + kind: .git, + transport: "https://github.com/example/components.git", revision: pin) + ledger.groups = [ + LedgerGroup( + id: 0, source: "group-source", root: ".", name: "empty-export", + manifestHash: "sha256:" + String(repeating: "c", count: 64), children: []) + ] + var references = try RetentionReferences(ledger: ledger, roots: [:]) + #expect(references.git.count == 1) + let tx = FileTransaction(store: store) + try cache.prune(references: references, transaction: tx) + #expect(FileManager.default.fileExists(atPath: unused.path)) + try tx.commit() + #expect(FileManager.default.fileExists(atPath: kept.path)) + #expect(!FileManager.default.fileExists(atPath: unused.path)) + ledger.groups = [] + ledger.sources = [:] + references = try RetentionReferences(ledger: ledger, roots: [:]) + try references.include( + watch: WatchState(sources: [source: WatchSourceState(seen: .revision(pin))])) + let watched = FileTransaction(store: store) + try cache.prune(references: references, transaction: watched) + try watched.commit() + #expect(FileManager.default.fileExists(atPath: kept.path)) + let released = FileTransaction(store: store) + try cache.prune(references: RetentionReferences(), transaction: released) + try released.commit() + #expect(!FileManager.default.fileExists(atPath: kept.path)) + } + + @Test func danglingAncestryAndReferencesReject() throws { + var ledger = ResolvedLedger() + ledger.sources["child"] = LedgerSource(kind: .local, revision: "x", container: "missing") + #expect(throws: (any Error).self) { _ = try RetentionReferences(ledger: ledger, roots: [:]) } + ledger.sources["missing"] = LedgerSource(kind: .local, revision: "x", container: "child") + #expect(throws: (any Error).self) { try ledger.validate() } + } +} diff --git a/Tests/AgentsCoreTests/LedgerWireSpellingTests.swift b/Tests/AgentsCoreTests/LedgerWireSpellingTests.swift new file mode 100644 index 0000000..e896ff6 --- /dev/null +++ b/Tests/AgentsCoreTests/LedgerWireSpellingTests.swift @@ -0,0 +1,99 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Ledger wire spelling") +struct LedgerWireSpellingTests { + @Test func nullableMembersFollowTheirOwningRecords() throws { + var ledger = ResolvedLedger() + ledger.sources["source"] = LedgerSource(kind: .local, revision: "live") + ledger.sourceUses = [ + LedgerSourceUse(source: "source", root: "."), + LedgerSourceUse(source: "source", root: ".", requirement: .upToNextMajor(from: "1.0.0")), + ] + ledger.lowerings = [ + LockedLowering( + id: "value", format: "test/value@1", inputs: [], resources: [], deployments: [], + layout: .init(), platform: "macos", artifacts: []) + ] + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + var root = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + var sources = try #require(root["sources"] as? [String: Any]) + var source = try #require(sources["source"] as? [String: Any]) + for key in ["transport", "location", "version", "container", "namespace"] { + source[key] = NSNull() + } + sources["source"] = source + root["sources"] = sources + root["sourceUses"] = [ + ["source": "source", "root": ".", "requirement": NSNull()], + ["source": "source", "root": ".", "requirement": ["from": "1.0.0", "to": NSNull()]], + ] + var lowerings = try #require(root["lowerings"] as? [[String: Any]]) + var layout: [String: Any] = ["kind": "null"] + for key in ["text", "integer", "boolean", "array", "object"] { layout[key] = NSNull() } + lowerings[0]["layout"] = layout + root["lowerings"] = lowerings + let bytes = try JSONSerialization.data(withJSONObject: root) + #expect(try ResolvedLedgerCodec.decode(bytes, limits: .standard) == ledger) + #expect(try ResolvedLedgerCodec.replacement(ledger, existing: bytes, limits: .standard) == nil) + + // A member nullable in a source is still unknown at the ledger root or in a tagged value. + root["transport"] = NSNull() + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode( + JSONSerialization.data(withJSONObject: root), limits: .standard) + } + root.removeValue(forKey: "transport") + layout["namespace"] = NSNull() + lowerings[0]["layout"] = layout + root["lowerings"] = lowerings + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode( + JSONSerialization.data(withJSONObject: root), limits: .standard) + } + layout.removeValue(forKey: "namespace") + layout["kind"] = "array" + lowerings[0]["layout"] = layout + root["lowerings"] = lowerings + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode( + JSONSerialization.data(withJSONObject: root), limits: .standard) + } + layout["array"] = [] as [Any] + lowerings[0]["layout"] = layout + root["lowerings"] = lowerings + let emptyArray = try ResolvedLedgerCodec.decode( + JSONSerialization.data(withJSONObject: root), limits: .standard) + #expect(emptyArray.lowerings[0].layout.array == []) + } + + @Test func escapedBase64UsesDecodedAggregateSize() throws { + var limits = LedgerLimits.standard + limits.objectBytes = 3 + for spelling in [#"YQ=="#, #"\u0059Q=="#, #"YQ\u003d\u003D"#] { + let bytes = Data((#"{"contentObjects":{"first":""# + spelling + #"","second":"YmM="}}"#).utf8) + limits.encodedBytes = bytes.count + try LedgerAdmission.check(bytes, limits: limits) + limits.objectBytes = 2 + #expect(throws: (any Error).self) { try LedgerAdmission.check(bytes, limits: limits) } + limits.objectBytes = 3 + } + limits = .standard + limits.objectBytes = 1 + for spelling in [#"/w=="#, #"\/w=="#, #"\u002fw\u003d="#] { + try LedgerAdmission.check( + Data((#"{"contentObjects":{"first":""# + spelling + #""}}"#).utf8), limits: limits) + } + } + + @Test func invalidEscapedContentCannotBypassAdmission() throws { + for spelling in [#"Y\nQ=="#, #"YQ\u003dA"#, #"\uD800Q=="#, #"YQ===\u003d"#] { + let bytes = Data((#"{"contentObjects":{"first":""# + spelling + #""}}"#).utf8) + #expect(throws: (any Error).self) { + try LedgerAdmission.check(bytes, limits: .standard) + } + } + } +} diff --git a/Tests/AgentsInstructionsTests/LedgerCompatibilityTests.swift b/Tests/AgentsInstructionsTests/LedgerCompatibilityTests.swift new file mode 100644 index 0000000..2626d7c --- /dev/null +++ b/Tests/AgentsInstructionsTests/LedgerCompatibilityTests.swift @@ -0,0 +1,49 @@ +import AgentsCore +import AgentsInstructions +import Foundation +import Testing + +@Suite("Ledger instruction compatibility") +struct LedgerCompatibilityTests { + @Test func generatedAndImportRemovalKeepExistingOwnership() throws { + let generated = Data((Instructions.notice + "\n\n# Section\nBody\n").utf8) + let digest = try ResolvedLedgerCodec.digest("unused") + var deployment = LedgerDeployment( + id: "target", target: .init(kind: .registered, root: "project", path: "AGENTS.md"), + route: "agents/instructions@1", owners: ["section"], recipients: [.codex], + ownership: .generated, + expectedHash: digest, created: false) + // Use the production source renderer to obtain the v1 whole-file expected hash. + let root = FileManager.default.temporaryDirectory.appendingPathComponent( + "ledger-compatibility-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let source = Data("---\ndescription: A section\n---\n# Section\nBody\n".utf8) + let rendered = try InstructionCompatibility.renderSections([source], ids: ["section"]) + #expect(rendered == generated) + // A tiny complete ledger gives the expected SHA-256 through the object identity. + let hash = try resourceHash(rendered, root: root) + deployment.expectedHash = hash + #expect(try InstructionCompatibility.obsolete(deployment, before: rendered) == nil) + #expect( + try InstructionCompatibility.obsolete(deployment, before: Data("drift".utf8)) + == Data("drift".utf8)) + #expect(try InstructionCompatibility.obsolete(deployment, before: nil) == nil) + deployment.ownership = .importBlock + deployment.importReference = "AGENTS.md" + deployment.created = true + let block = Data(ClaudeForwarding.renderBlock(for: .root).utf8) + #expect(try InstructionCompatibility.obsolete(deployment, before: block) == nil) + let custom = Data("# My instructions\n\n".utf8) + block + let after = try InstructionCompatibility.obsolete(deployment, before: custom) + #expect(after == Data("# My instructions\n".utf8)) + deployment.created = false + #expect(try InstructionCompatibility.obsolete(deployment, before: block) != nil) + } + + private func resourceHash(_ bytes: Data, root: URL) throws -> String { + let file = root.appendingPathComponent("rendered") + try bytes.write(to: file) + return try LedgerResources.capture(file, embed: false, limits: .standard).hash + } +} diff --git a/Tests/ComponentsTests/LedgerReplayTests.swift b/Tests/ComponentsTests/LedgerReplayTests.swift new file mode 100644 index 0000000..35991aa --- /dev/null +++ b/Tests/ComponentsTests/LedgerReplayTests.swift @@ -0,0 +1,304 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation +import StateTestSupport +import Testing + +@Suite("Ledger reconstruction") +struct LedgerReplayTests { + @Test func coldSubprocessReconstructsFrozenBResult() throws { + let fixture = try LinkFixture() + let project = fixture.project + try fixture.write("#!/bin/sh\nexit 0\n", to: "bin/server", base: project) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: project.appendingPathComponent("bin/server").path) + try fixture.write("# Frozen prompt\n", to: "prompts/task.md", base: project) + try fixture.write("vendor bytes\n", to: "vendor/data", base: project) + try FileManager.default.createDirectory( + at: project.appendingPathComponent("vendor/empty"), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: project.appendingPathComponent("vendor/alias").path, withDestinationPath: "data") + try fixture.manifest( + """ + let agents = Agents(components: [ + .mcpServer(name: "server", transport: .stdio("./bin/server")), + .command(name: "task", description: "Task", prompt: .file("prompts/task.md")), + .plugin(name: "vendor", path: "vendor", source: ".") + ]) + """, at: project) + try run("ledger-freeze", root: project) + let ledger = try fixture.store.loadLedger(limits: .standard) + #expect(!ledger.contentObjects.isEmpty) + let locked = try Data(contentsOf: fixture.store.resolvedURL) + let expected = try #require(ledger.lowerings.first).artifacts + let cold = fixture.root.appendingPathComponent("cold") + try FileManager.default.createDirectory( + at: cold.appendingPathComponent(".agent"), withIntermediateDirectories: true) + try FileManager.default.copyItem( + at: fixture.store.declarationURL, to: cold.appendingPathComponent(".agent/Agents.swift")) + try locked.write(to: cold.appendingPathComponent(".agent/agents.resolved")) + try FileManager.default.removeItem(at: project) + try run("ledger-replay", root: cold) + let actual = try JSONDecoder().decode( + [LedgerArtifactDigest].self, + from: Data(contentsOf: cold.appendingPathComponent("replay-summary.json"))) + #expect(actual == expected) + #expect(try Data(contentsOf: cold.appendingPathComponent(".agent/agents.resolved")) == locked) + #expect( + !FileManager.default.fileExists(atPath: cold.appendingPathComponent(".agent/cache").path)) + let tree = cold.appendingPathComponent("probe-bundle") + #expect( + FileManager.default.fileExists(atPath: tree.appendingPathComponent("resource-2/empty").path)) + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: tree.appendingPathComponent("resource-2/alias").path) == "data") + let flags = try FileManager.default.attributesOfItem( + atPath: tree.appendingPathComponent("resource-0").path) + #expect(((flags[.posixPermissions] as? NSNumber)?.intValue ?? 0) & 0o111 != 0) + } + + @Test func freezeRejectsMutationAndMissingLocations() throws { + let fixture = try LinkFixture() + try fixture.write("before", to: "prompt.md", base: fixture.project) + let document = try fixture.document( + "let agents = Agents(components: [.command(name: \"task\", description: \"Task\", prompt: .file(\"prompt.md\"))])" + ) + try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + #expect(throws: (any Error).self) { + _ = try LedgerFreeze.freeze( + graph, session: session, locations: .init(sources: [:]), limits: .standard) + } + try fixture.write("changed", to: "prompt.md", base: fixture.project) + #expect(throws: (any Error).self) { + _ = try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: [ + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: ".") + ]), limits: .standard) + } + } + } + + private func run(_ action: String, root: URL) throws { + var directory = Bundle(for: LedgerTestBundle.self).bundleURL + while directory.path != "/", + !FileManager.default.isExecutableFile( + atPath: directory.appendingPathComponent("StateTestProcess").path) + { + directory.deleteLastPathComponent() + } + let child = Process() + child.executableURL = directory.appendingPathComponent("StateTestProcess") + child.arguments = [root.path, action] + child.environment = ProcessInfo.processInfo.environment + try child.run() + defer { if child.isRunning { try? ProcessWait.terminate(child) } } + try ProcessWait.exit(child, root: root) + try #require(child.terminationStatus == 0) + } +} +private final class LedgerTestBundle: NSObject {} + +@Suite("Ledger replay failure boundaries") +struct LedgerReplayFailureTests { + @Test func formatAndHashRejectWithoutFallbackAndCleanup() throws { + let fixture = try LinkFixture() + var ledger = ResolvedLedger() + ledger.sources["root"] = LedgerSource( + kind: .local, location: .init(kind: .registered, root: "project", path: "."), revision: "live" + ) + try fixture.write("frozen", to: "file", base: fixture.project) + let input = try LedgerResources.capture( + fixture.project.appendingPathComponent("file"), embed: true, limits: .standard) + ledger.contentObjects = input.objects + ledger.resources["file"] = LedgerResource( + kind: .embedded, source: "root", path: "file", hash: input.hash, entries: input.entries) + #if os(macOS) + let platform = "macos" + #else + let platform = "linux" + #endif + ledger.lowerings = [ + LockedLowering( + id: "test", format: "test/frozen@1", inputs: [], resources: ["file"], deployments: [], + layout: .init(), platform: platform, artifacts: []) + ] + var borrowed: URL? + let renderer: LedgerRenderer = { _, _, resources in + borrowed = resources["file"] + return [ + ReplayedArtifact(name: "file", kind: .file, bytes: try Data(contentsOf: resources["file"]!)) + ] + } + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, + roots: ["project": fixture.project], limits: .standard, renderers: ["test/frozen@1": renderer] + ) + #expect(borrowed.map { !FileManager.default.fileExists(atPath: $0.path) } == true) + #expect(throws: (any Error).self) { + try LedgerReplay.withReplay(ledger, store: fixture.store, roots: [:], limits: .standard) { + _ in + } + } + let changed: LedgerRenderer = { _, _, _ in + [.init(name: "file", kind: .file, bytes: Data("new output".utf8))] + } + #expect(throws: (any Error).self) { + try LedgerReplay.withReplay( + ledger, store: fixture.store, roots: [:], limits: .standard, + renderers: ["test/frozen@1": changed] + ) { _ in } + } + let cancelled: LedgerRenderer = { _, _, resources in + borrowed = resources["file"] + throw CancellationError() + } + #expect(throws: CancellationError.self) { + try LedgerReplay.withReplay( + ledger, store: fixture.store, roots: [:], limits: .standard, + renderers: ["test/frozen@1": cancelled] + ) { _ in } + } + #expect(borrowed.map { !FileManager.default.fileExists(atPath: $0.path) } == true) + try LedgerReplay.withReplay( + ledger, store: fixture.store, roots: [:], limits: .standard, + renderers: ["test/frozen@1": renderer] + ) { #expect($0.count == 1) } + ledger.resources["file"]?.hash = "sha256:" + String(repeating: "0", count: 64) + #expect(throws: (any Error).self) { + try LedgerReplay.withReplay( + ledger, store: fixture.store, roots: [:], limits: .standard, + renderers: ["test/frozen@1": renderer] + ) { _ in } + } + } +} + +@Suite("Ledger resource closure") +struct LedgerResourceClosureTests { + @Test func freezesSourceContainedLinksOutsideSelectedSubtree() throws { + let fixture = try LinkFixture() + try fixture.write("outside selected subtree", to: "shared/text", base: fixture.project) + try FileManager.default.createDirectory( + at: fixture.project.appendingPathComponent("vendor"), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: fixture.project.appendingPathComponent("vendor/reference").path, + withDestinationPath: "../shared/text") + let document = try fixture.document( + "let agents = Agents(components: [.plugin(name: \"vendor\", path: \"vendor\", source: \".\")])" + ) + var ledger = try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { linked, session in + try LedgerFreeze.freeze( + linked, session: session, + locations: .init(sources: [ + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: ".") + ]), limits: .standard) + } + let resource = try #require(ledger.resources.keys.first) + #expect(!ledger.resources[resource]!.support.isEmpty) + #if os(macOS) + let platform = "macos" + #else + let platform = "linux" + #endif + ledger.lowerings = [ + .init( + id: "closure", format: "test/closure@1", inputs: [], resources: [resource], deployments: [], + layout: .init(), platform: platform, artifacts: []) + ] + let renderer: LedgerRenderer = { _, _, resources in + [ + .init( + name: "linked", kind: .file, + bytes: try Data(contentsOf: resources[resource]!.appendingPathComponent("reference"))) + ] + } + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: .standard, + renderers: ["test/closure@1": renderer]) + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + try FileManager.default.removeItem(at: fixture.project) + let cold = fixture.root.appendingPathComponent("cold") + try FileManager.default.createDirectory(at: cold, withIntermediateDirectories: true) + let coldStore = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: cold, homeDirectory: fixture.home, environment: [:])) + try LedgerReplay.withReplay( + ResolvedLedgerCodec.decode(bytes, limits: .standard), store: coldStore, + roots: [:], limits: .standard, renderers: ["test/closure@1": renderer] + ) { artifacts in + #expect(artifacts[0].bytes == Data("outside selected subtree".utf8)) + } + } +} + +@Suite("Ledger exact Git inputs") +struct LedgerExactGitTests { + @Test func changedProducerAndBranchDoNotReselectLockedInput() throws { + let fixture = try LinkFixture() + let producer = fixture.root.appendingPathComponent("producer") + try fixture.initialize(producer) + try fixture.write("original", to: "prompt.md", base: producer) + try fixture.manifest( + """ + let agents = Agents(exports: ["task"], groups: [ + .group(name: "task", components: [.command(name: "task", description: "Task", prompt: .file("prompt.md"))]) + ]) + """, at: producer) + let original = try fixture.commit(producer) + let document = try fixture.document( + """ + let agents = Agents(sources: [.source(name: "producer", path: "../producer", branch: "main")], + uses: [.group(name: "task", source: "producer")]) + """) + var ledger = try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { linked, session in + try LedgerFreeze.freeze( + linked, session: session, + locations: .init(sources: [ + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: "."), + "local:" + producer.path: .init( + kind: .authoringRelative, root: "project", path: "../producer"), + ]), limits: .standard) + } + #expect(ledger.groups.first?.manifestHash.hasPrefix("sha256:") == true) + #expect(ledger.sources.values.contains { $0.revision == original }) + try fixture.write("changed", to: "prompt.md", base: producer) + try fixture.write("invalid producer manifest", to: ".agent/Agents.swift", base: producer) + _ = try fixture.commit(producer) + let resource = try #require(ledger.resources.keys.first) + #if os(macOS) + let platform = "macos" + #else + let platform = "linux" + #endif + ledger.lowerings = [ + .init( + id: "exact", format: "test/exact@1", inputs: [], resources: [resource], deployments: [], + layout: .init(), platform: platform, artifacts: []) + ] + let renderer: LedgerRenderer = { _, _, resources in + let bytes = try Data(contentsOf: resources[resource]!) + guard bytes == Data("original".utf8) else { + throw CoreError.invalidState("mutable input selected") + } + return [.init(name: "original", kind: .file, bytes: bytes)] + } + let roots = ["project": fixture.project] + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: roots, limits: .standard, + renderers: ["test/exact@1": renderer]) + try LedgerReplay.withReplay( + ledger, store: fixture.store, roots: roots, limits: .standard, + renderers: ["test/exact@1": renderer] + ) { #expect($0[0].bytes == Data("original".utf8)) } + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } +} diff --git a/Tests/StateTestProcess/LedgerProbe.swift b/Tests/StateTestProcess/LedgerProbe.swift new file mode 100644 index 0000000..c92219c --- /dev/null +++ b/Tests/StateTestProcess/LedgerProbe.swift @@ -0,0 +1,106 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation + +/// An internal assembly probe, deliberately absent from the production renderer table. +private let probeFormat = "test/generated-bundle@1" + +func ledgerProbe(_ action: String, store: StateStore) throws { + let roots = [ + "project": store.environment.projectDirectory, "home": store.environment.homeDirectory, + "state": store.directory, + ] + let limits = LedgerLimits.standard + let renderers: [String: LedgerRenderer] = [ + probeFormat: { lowering, ledger, resources in + let destination = store.environment.projectDirectory.appendingPathComponent("probe-bundle") + if FileManager.default.fileExists(atPath: destination.path) { + try FileManager.default.removeItem(at: destination) + } + try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true) + let manifest = try ResolvedLedgerCodec.bytes(lowering.inputs.map { ledger.components[$0]! }) + try manifest.write(to: destination.appendingPathComponent("manifest.json")) + for (index, id) in lowering.resources.enumerated() { + try FileManager.default.copyItem( + at: resources[id]!, to: destination.appendingPathComponent("resource-\(index)")) + } + guard let registration = lowering.layout.object?["registration"], + let values = lowering.layout.object?["values"] + else { throw CoreError.invalidState("probe layout") } + return [ + ReplayedArtifact(name: "bundle", kind: .tree, tree: destination), + ReplayedArtifact( + name: "registration", kind: .registration, + bytes: try ResolvedLedgerCodec.bytes(registration)), + ReplayedArtifact(name: "owned", kind: .ownedValues, values: values), + ] + } + ] + if action == "ledger-freeze" { + let document = try DeclarationDocument( + bytes: Array(Data(contentsOf: store.declarationURL)), + identity: DocumentIdentity("probe/Agents.swift")) + let ledger = try ComponentLinker.withLinkedComponents( + document: document, store: store, + platform: { + #if os(macOS) + return .macOS + #else + return .linux + #endif + }() + ) { linked, session in + try LedgerFreeze.freeze( + linked, session: session, + locations: .init(sources: [ + "local:" + store.environment.projectDirectory.path: + LedgerLocation(kind: .registered, root: "project", path: ".") + ]), limits: limits) + } + var candidate = ledger + let inputs = ledger.occurrences.map(\.component) + let resourceIDs = inputs.flatMap { ledger.components[$0]!.resources } + candidate.lowerings = [ + LockedLowering( + id: "bundle", format: probeFormat, inputs: inputs, + resources: resourceIDs, deployments: [], + layout: .init(object: [ + "registration": .init(object: ["root": .init("project"), "path": .init("plugins/bundle")] + ), + "values": .init(object: ["server": ledger.components[inputs[0]]!.payload]), + ]), + platform: { + #if os(macOS) + return "macos" + #else + return "linux" + #endif + }(), artifacts: []) + ] + candidate = try LedgerReplay.prepareLowerings( + candidate, store: store, roots: roots, + limits: limits, renderers: renderers) + try ResolvedLedgerCodec.encode(candidate, limits: limits).write(to: store.resolvedURL) + } else if action == "ledger-compatibility" { + let ledger = try store.loadLedger(limits: limits) + try LedgerReplay.withReplay(ledger, store: store, roots: roots, limits: limits) { artifacts in + try ResolvedLedgerCodec.bytes(try artifacts.map { try $0.digest(limits: limits) }) + .write( + to: store.environment.projectDirectory.appendingPathComponent( + "compatibility-summary.json")) + } + } else if action == "ledger-replay" { + let ledger = try store.loadLedger(limits: limits) + try LedgerReplay.withReplay( + ledger, store: store, roots: roots, limits: limits, + renderers: renderers + ) { artifacts in + let summaries = try artifacts.map { try $0.digest(limits: limits) } + try ResolvedLedgerCodec.bytes(summaries).write( + to: store.environment.projectDirectory.appendingPathComponent("replay-summary.json")) + } + } else { + throw CoreError.invalidState("unknown ledger probe") + } +} diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index ecb8b59..7c7f984 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -51,7 +51,9 @@ func signalContention() throws { defer { try? signal.close() } try signal.write(contentsOf: Data("contended\n".utf8)) } -if arguments[2] == "git-environment" { +if arguments[2].hasPrefix("ledger-") { + try ledgerProbe(arguments[2], store: store) +} else if arguments[2] == "git-environment" { let before = ProcessInfo.processInfo.environment let cache = SourceCache(store: store) let source = SourceDeclaration(kind: .local, location: root.appendingPathComponent("source").path) From 69b68b0797015f659a5ec79da0e2955931d709a1 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 01:17:05 +0800 Subject: [PATCH 041/171] fix: bound ledger replay and resource resolution --- Sources/AgentsCore/LedgerResourceLinks.swift | 103 ++++++++++++++++ Sources/AgentsCore/LedgerResources.swift | 96 +++++++++------ Sources/AgentsCore/LedgerValidation.swift | 35 ++---- Sources/AgentsCore/SourceCache.swift | 20 ++- .../InstructionCompatibility.swift | 32 ++++- Sources/Components/LedgerFreeze.swift | 15 ++- Sources/Components/LedgerReplay.swift | 76 +++++++++--- .../LedgerGraphReviewTests.swift | 115 ++++++++++++++++++ .../LedgerReplayBudgetTests.swift | 102 ++++++++++++++++ 9 files changed, 509 insertions(+), 85 deletions(-) create mode 100644 Sources/AgentsCore/LedgerResourceLinks.swift create mode 100644 Tests/AgentsCoreTests/LedgerGraphReviewTests.swift create mode 100644 Tests/ComponentsTests/LedgerReplayBudgetTests.swift diff --git a/Sources/AgentsCore/LedgerResourceLinks.swift b/Sources/AgentsCore/LedgerResourceLinks.swift new file mode 100644 index 0000000..ae1f708 --- /dev/null +++ b/Sources/AgentsCore/LedgerResourceLinks.swift @@ -0,0 +1,103 @@ +import Foundation + +extension LedgerResources { + /// Validates the graph in the coordinates used by materialization, before any writes. + /// Supporting entries extend ownership to the source root; otherwise the selected tree is root. + static func validatedEntries(_ resource: LedgerResource) throws -> [String: LedgerEntry] { + var entries: [String: LedgerEntry] = [:] + for original in resource.support + + resource.entries.map({ original in + var entry = original + if !resource.support.isEmpty { + entry.path = + original.path == "." + ? resource.path + : resource.path == "." ? original.path : resource.path + "/" + original.path + } + return entry + }) + { + try ledgerPath(original.path) + guard entries[original.path] == nil || entries[original.path] == original else { + throw CoreError.invalidState("conflicting resource support") + } + entries[original.path] = original + } + if !resource.support.isEmpty { + let parents = resource.path.split(separator: "/").dropLast() + for count in 0...parents.count { + let path = count == 0 ? "." : parents.prefix(count).joined(separator: "/") + if entries[path] == nil { + entries[path] = .init(path: path, kind: .directory, executable: false) + } + } + } + for path in entries.keys where path != "." { + let parts = path.split(separator: "/") + guard entries["."]?.kind == .directory else { + throw CoreError.invalidState("resource ancestor is not a directory") + } + for count in 1.. = [entry.path] + var pending: [Step] = [.finish(entry.path)] + func parts(_ link: String?) throws -> [Step] { + guard let link, !link.isEmpty, !link.hasPrefix("/"), !link.contains("\0"), + !link.contains("\\") + else { throw CoreError.invalidState("invalid resource link") } + return link.split(separator: "/").reversed().map { .part(String($0)) } + } + pending += try parts(entry.link) + while let step = pending.popLast() { + switch step { + case .finish(let link): + resolved[link] = path + active.remove(link) + case .part(let part): + let current = path.isEmpty ? "." : path.joined(separator: "/") + guard entries[current]?.kind == .directory else { + throw CoreError.invalidState("resource link traverses non-directory") + } + if part == "." { continue } + if part == ".." { + guard !path.isEmpty else { throw CoreError.invalidState("resource link escapes tree") } + path.removeLast() + continue + } + let next = (path + [part]).joined(separator: "/") + guard let target = entries[next] else { + throw CoreError.invalidState("resource link has missing support") + } + if target.kind == .symlink { + if let cached = resolved[next] { + path = cached + } else { + guard active.insert(next).inserted else { + throw CoreError.invalidState("resource link cycle") + } + pending.append(.finish(next)) + pending += try parts(target.link) + } + } else { + path.append(part) + } + } + } + } + return entries + } +} diff --git a/Sources/AgentsCore/LedgerResources.swift b/Sources/AgentsCore/LedgerResources.swift index e8c19d8..9f6aa12 100644 --- a/Sources/AgentsCore/LedgerResources.swift +++ b/Sources/AgentsCore/LedgerResources.swift @@ -19,7 +19,16 @@ package enum LedgerResources { throw CoreError.notFound("locked resource") } func collect(_ file: URL, path: String, supporting: Bool = false) throws { - if supporting, !visiting.insert(path).inserted { return } + if supporting { + if !visiting.insert(path).inserted { return } + let parts = path.split(separator: "/") + for count in 1.. = [file.path] + guard !link.hasPrefix("/") else { throw CoreError.unsafePath("absolute resource link") } + while let step = pending.popLast() { + guard case .part(let part) = step else { + if case .finish(let path) = step { followed.remove(path) } + continue + } + if part == "." { continue } + if part == ".." { + resolved.deleteLastPathComponent() + } else { + resolved.appendPathComponent(part) + } + guard PathSafety.isContained(resolved, in: sourceRoot) else { + throw CoreError.unsafePath("resource link escapes source snapshot") + } + let info = try FileManager.default.attributesOfItem(atPath: resolved.path) + if info[.type] as? FileAttributeType == .typeSymbolicLink { + guard followed.insert(resolved.path).inserted else { + throw CoreError.unsafePath("resource link cycle") + } + if !PathSafety.isContained(resolved, in: url) { + try collect( + resolved, path: PathSafety.relativePath(resolved.path, to: sourceRoot.path), + supporting: true) + } + let next = try FileManager.default.destinationOfSymbolicLink(atPath: resolved.path) + guard !next.hasPrefix("/") else { + throw CoreError.unsafePath("absolute resource link") + } + pending.append(.finish(resolved.path)) + resolved.deleteLastPathComponent() + pending += next.split(separator: "/").reversed().map { .part(String($0)) } + } + } + if !PathSafety.isContained(resolved, in: url) { + let relative = PathSafety.relativePath(resolved.path, to: sourceRoot.path) let parts = relative.split(separator: "/") for count in 1.. Data { + package static func renderPrompt( + _ bytes: [Data], ids: [String], append: Data?, byteLimit: Int? = nil + ) throws -> Data { guard bytes.count == ids.count else { throw CoreError.invalidState("prompt input count") } let sections = try zip(bytes, ids).map { try Instructions.validateSource($0.0, id: $0.1, allowRestrictions: true) } + try checkOutput(sections, notice: false, append: append, byteLimit: byteLimit) return try Instructions.renderChatGPT(sections: sections, customContent: append) } - package static func renderSections(_ bytes: [Data], ids: [String]) throws -> Data { + package static func renderSections(_ bytes: [Data], ids: [String], byteLimit: Int? = nil) throws + -> Data + { guard bytes.count == ids.count else { throw CoreError.invalidState("instruction input count") } let sections = try zip(bytes, ids).map { try Instructions.validateSource($0.0, id: $0.1, allowRestrictions: true) } + try checkOutput(sections, notice: true, append: nil, byteLimit: byteLimit) return Data(try Instructions.render(sections).utf8) } + + private static func checkOutput( + _ sections: [InstructionSection], notice: Bool, append: Data?, byteLimit: Int? + ) throws { + guard var remaining = byteLimit else { return } + func charge(_ count: Int) throws { + guard count <= remaining else { + throw CoreError.invalidState("rendered instruction byte budget") + } + remaining -= count + } + if notice { try charge(Instructions.notice.utf8.count + 2) } + for (index, section) in sections.enumerated() { + if index > 0 { try charge(2) } + try charge(section.content.utf8.count) + } + try charge(1) + if let append, !append.isEmpty { + try charge(1) + try charge(append.count) + } + } } diff --git a/Sources/Components/LedgerFreeze.swift b/Sources/Components/LedgerFreeze.swift index f757013..4317a62 100644 --- a/Sources/Components/LedgerFreeze.swift +++ b/Sources/Components/LedgerFreeze.swift @@ -41,8 +41,9 @@ package enum LedgerFreeze { return id } for item in allSnapshots { _ = try sourceID(item.snapshot) } + let snapshotsBySource = Dictionary(grouping: allSnapshots, by: { $0.snapshot.source }) for use in linked.sourceUses { - for snapshot in allSnapshots where snapshot.snapshot.source == use.source { + for snapshot in snapshotsBySource[use.source] ?? [] { ledger.sourceUses.append( .init( source: try sourceID(snapshot.snapshot), root: use.root, @@ -142,14 +143,22 @@ package enum LedgerFreeze { } } ledger.occurrences.sort { $0.id < $1.id } + var children: [Int: [Int]] = [:] + for reference in linked.references { + if let parent = reference.parent { + children[parent, default: []].append(reference.occurrence) + } + } + for occurrence in ledger.occurrences { + if let parent = occurrence.reference { children[parent, default: []].append(occurrence.id) } + } ledger.groups = try linked.references.map { reference in LedgerGroup( id: reference.occurrence, parent: reference.parent, source: try sourceID(reference.snapshot), root: reference.root, name: reference.group, requirement: reference.constraint?.requirement?.canonical, manifestHash: reference.manifestHash, - children: (linked.references.filter { $0.parent == reference.occurrence }.map(\.occurrence) - + ledger.occurrences.filter { $0.reference == reference.occurrence }.map(\.id)).sorted()) + children: (children[reference.occurrence] ?? []).sorted()) } try ledger.validate() return ledger diff --git a/Sources/Components/LedgerReplay.swift b/Sources/Components/LedgerReplay.swift index da41968..f8f1a9d 100644 --- a/Sources/Components/LedgerReplay.swift +++ b/Sources/Components/LedgerReplay.swift @@ -67,15 +67,21 @@ package enum LedgerReplay { /// Only formats with implemented production semantics are registered here. Tests explicitly /// supply their own renderer table; a format is never selected by agent or current version. package static var compatibilityRenderers: [String: LedgerRenderer] { + compatibilityRenderers(outputBytes: LedgerLimits.standard.resourceBytes) + } + + private static func compatibilityRenderers(outputBytes: Int) -> [String: LedgerRenderer] { [ - "agents/skill@1": skill, "agents/instructions@1": instructions, - "agents/claude-import@1": forwarding, "agents/chatgpt@1": chatGPT, + "agents/skill@1": skill, + "agents/instructions@1": { try instructions($0, $1, $2, outputBytes: outputBytes) }, + "agents/claude-import@1": { try forwarding($0, $1, $2, outputBytes: outputBytes) }, + "agents/chatgpt@1": { try chatGPT($0, $1, $2, outputBytes: outputBytes) }, ] } package static func withReplay( _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], limits: LedgerLimits, - renderers: [String: LedgerRenderer] = compatibilityRenderers, + renderers: [String: LedgerRenderer]? = nil, _ body: ([ReplayedArtifact]) throws -> T ) throws -> T { try run( @@ -87,7 +93,7 @@ package enum LedgerReplay { /// Seals renderer output identities into a candidate before encoding or publication. package static func prepareLowerings( _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], limits: LedgerLimits, - renderers: [String: LedgerRenderer] = compatibilityRenderers + renderers: [String: LedgerRenderer]? = nil ) throws -> ResolvedLedger { try run( ledger, store: store, roots: roots, limits: limits, renderers: renderers, @@ -102,7 +108,7 @@ package enum LedgerReplay { private static func run( _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], limits: LedgerLimits, - renderers: [String: LedgerRenderer], recording: Bool, + renderers: [String: LedgerRenderer]?, recording: Bool, _ body: ([ReplayedArtifact], [LockedLowering]) throws -> T ) throws -> T { try ResolvedLedgerCodec.checkModel(ledger, limits: limits) @@ -115,13 +121,26 @@ package enum LedgerReplay { let current = "linux" #endif for lowering in ledger.lowerings { - guard renderers[lowering.format] != nil else { + guard (renderers ?? compatibilityRenderers)[lowering.format] != nil else { throw CoreError.invalidState("unknown renderer format") } guard lowering.platform == current else { throw CoreError.invalidState("locked lowering is incompatible with platform: " + platform) } } + // Charge every occurrence, not only unique stored resources. Reserve this before reads; + // the same Core expansion limit also bounds all outputs retained by this replay. + let sizes = ledger.resources.mapValues { resource in + (resource.entries + resource.support).reduce(0) { $0 + ($1.byteCount ?? 0) } + } + var remaining = limits.resourceBytes + for lowering in ledger.lowerings { + for id in lowering.resources { + let size = sizes[id]! + guard size <= remaining else { throw CoreError.invalidState("replay input byte budget") } + remaining -= size + } + } let workspace = FileManager.default.temporaryDirectory.appendingPathComponent( "agents-ledger-" + UUID().uuidString) try FileSystem.createDirectory(at: workspace) @@ -187,7 +206,27 @@ package enum LedgerReplay { var names = Set() for lowering in ledger.lowerings { try Task.checkCancellation() - let rendered = try renderers[lowering.format]!(lowering, ledger, acquired) + let table = renderers ?? compatibilityRenderers(outputBytes: remaining) + let rendered = try table[lowering.format]!(lowering, ledger, acquired) + for artifact in rendered { + let count: Int + if let bytes = artifact.bytes { + count = bytes.count + } else if let tree = artifact.tree { + let captured = try LedgerResources.capture(tree, embed: false, limits: limits) + count = (captured.entries + captured.support).reduce(0) { $0 + ($1.byteCount ?? 0) } + } else if let values = artifact.values { + count = try ResolvedLedgerCodec.bytes(values).count + } else if let location = artifact.location { + count = try ResolvedLedgerCodec.bytes(location).count + } else { + throw CoreError.invalidState("missing rendered output") + } + guard count <= remaining else { + throw CoreError.invalidState("replay output byte budget") + } + remaining -= count + } let digests = try rendered.map { try $0.digest(limits: limits) } guard recording || digests == lowering.artifacts else { throw CoreError.invalidState("locked renderer output hash mismatch") @@ -221,7 +260,8 @@ package enum LedgerReplay { } private static func instructions( - _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL] + _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL], + outputBytes: Int ) throws -> [ReplayedArtifact] { let bytes = try lowering.resources.map { id in guard let resource = resources[id] else { @@ -237,12 +277,14 @@ package enum LedgerReplay { return [ .init( name: name, kind: .file, - bytes: try InstructionCompatibility.renderSections(bytes, ids: lowering.resources)) + bytes: try InstructionCompatibility.renderSections( + bytes, ids: lowering.resources, byteLimit: outputBytes)) ] } private static func chatGPT( - _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL] + _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL], + outputBytes: Int ) throws -> [ReplayedArtifact] { guard let count = lowering.layout.object?["sectionCount"]?.integer, count > 0, count <= lowering.resources.count, lowering.resources.count <= count + 1, @@ -260,18 +302,22 @@ package enum LedgerReplay { .init( name: name, kind: .file, bytes: try InstructionCompatibility.renderPrompt( - sections, ids: Array(lowering.resources.prefix(count)), append: append)) + sections, ids: Array(lowering.resources.prefix(count)), append: append, + byteLimit: outputBytes)) ] } private static func forwarding( - _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL] + _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL], + outputBytes: Int ) throws -> [ReplayedArtifact] { guard let name = lowering.layout.object?["name"]?.text, let path = ClaudeInstructionPath(rawValue: name) else { throw CoreError.invalidState("invalid forwarding layout") } - return [ - .init(name: name, kind: .file, bytes: Data(ClaudeForwarding.renderBlock(for: path).utf8)) - ] + let block = ClaudeForwarding.renderBlock(for: path) + guard block.utf8.count <= outputBytes else { + throw CoreError.invalidState("replay output byte budget") + } + return [.init(name: name, kind: .file, bytes: Data(block.utf8))] } } diff --git a/Tests/AgentsCoreTests/LedgerGraphReviewTests.swift b/Tests/AgentsCoreTests/LedgerGraphReviewTests.swift new file mode 100644 index 0000000..afdd6f9 --- /dev/null +++ b/Tests/AgentsCoreTests/LedgerGraphReviewTests.swift @@ -0,0 +1,115 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Ledger graph integrity") +struct LedgerGraphReviewTests { + private let hash = "sha256:" + String(repeating: "0", count: 64) + + private func resource(_ entries: [LedgerEntry], support: [LedgerEntry] = []) -> LedgerResource { + .init( + kind: .embedded, source: "root", path: "vendor", hash: hash, + entries: entries, support: support) + } + + @Test func linksResolveBeforeParentTraversal() throws { + let root = LedgerEntry(path: ".", kind: .directory, executable: false) + let alias = LedgerEntry(path: "a", kind: .symlink, link: ".", executable: false) + let escape = LedgerEntry(path: "b", kind: .symlink, link: "a/../outside", executable: false) + #expect(throws: (any Error).self) { + _ = try LedgerResources.validatedEntries(resource([root, alias, escape])) + } + let valid = LedgerEntry(path: "b", kind: .symlink, link: "a/a", executable: false) + #expect(try LedgerResources.validatedEntries(resource([root, alias, valid])).count == 3) + let missing = LedgerEntry(path: "b", kind: .symlink, link: "absent", executable: false) + #expect(throws: (any Error).self) { + _ = try LedgerResources.validatedEntries(resource([root, missing])) + } + let cycle = LedgerEntry(path: "b", kind: .symlink, link: "b", executable: false) + #expect(throws: (any Error).self) { + _ = try LedgerResources.validatedEntries(resource([root, cycle])) + } + } + + @Test func supportingAndRootLinksUseOwnedRoot() throws { + let selected = LedgerEntry(path: ".", kind: .symlink, link: "shared/file", executable: false) + let directory = LedgerEntry(path: "shared", kind: .directory, executable: false) + let file = LedgerEntry(path: "shared/file", kind: .file, executable: false, byteCount: 0) + #expect( + try LedgerResources.validatedEntries(resource([selected], support: [directory, file])).count + == 4) + #expect(throws: (any Error).self) { + _ = try LedgerResources.validatedEntries(resource([selected], support: [directory])) + } + #expect(throws: (any Error).self) { + _ = try LedgerResources.validatedEntries(resource([selected])) + } + let escaping = LedgerEntry(path: "shared/a", kind: .symlink, link: ".", executable: false) + let outside = LedgerEntry( + path: "shared/b", kind: .symlink, link: "a/../../outside", executable: false) + #expect(throws: (any Error).self) { + _ = try LedgerResources.validatedEntries( + resource([selected], support: [directory, file, escaping, outside])) + } + } + + @Test func capturesIntermediateSupportingLinksAndMaterializesContainedChains() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let source = root.appendingPathComponent("source") + let selected = source.appendingPathComponent("vendor") + try FileManager.default.createDirectory(at: selected, withIntermediateDirectories: true) + try FileManager.default.createDirectory( + at: source.appendingPathComponent("shared"), withIntermediateDirectories: true) + try Data("content".utf8).write(to: source.appendingPathComponent("shared/file")) + try FileManager.default.createSymbolicLink( + atPath: source.appendingPathComponent("alias").path, withDestinationPath: "shared") + try FileManager.default.createSymbolicLink( + atPath: selected.appendingPathComponent("a").path, withDestinationPath: ".") + try FileManager.default.createSymbolicLink( + atPath: selected.appendingPathComponent("link").path, withDestinationPath: "a/a/../alias/file" + ) + let captured = try LedgerResources.capture( + selected, embed: true, limits: .standard, sourceRoot: source) + let record = LedgerResource( + kind: .embedded, source: "root", path: "vendor", hash: captured.hash, + entries: captured.entries, support: captured.support) + #expect(record.support.contains { $0.path == "alias" && $0.kind == .symlink }) + let destination = root.appendingPathComponent("materialized") + try LedgerResources.materialize(record, objects: captured.objects, at: destination) + #expect( + try Data(contentsOf: destination.appendingPathComponent("vendor/link")) + == Data("content".utf8)) + let gitCapture = try LedgerResources.capture( + selected, embed: false, limits: .standard, sourceRoot: source) + #expect(gitCapture.support.map(\.path) == captured.support.map(\.path)) + #expect(gitCapture.objects.isEmpty) + var escaped = record + escaped.entries.append( + .init(path: "bad", kind: .symlink, link: "a/../../outside", executable: false)) + let rejected = root.appendingPathComponent("rejected") + #expect(throws: (any Error).self) { + try LedgerResources.materialize(escaped, objects: captured.objects, at: rejected) + } + #expect(!FileManager.default.fileExists(atPath: rejected.path)) + } + + @Test func largeFlatGroupsAreAdmittedAndValidated() throws { + var ledger = ResolvedLedger() + ledger.sources["root"] = .init(kind: .local, revision: "live") + ledger.groups = (0..<100_000).map { + .init(id: $0, source: "root", root: ".", name: "group", manifestHash: hash, children: []) + } + let started = Date() + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + #expect(try ResolvedLedgerCodec.decode(encoded, limits: .standard) == ledger) + print( + "LEDGER_GROUP_CONTROL groups=\(ledger.groups.count) encodedBytes=\(encoded.count) seconds=\(Date().timeIntervalSince(started))" + ) + ledger.groups[0].children = [1] + #expect(throws: (any Error).self) { try ledger.validate() } + ledger.groups[1].parent = 0 + try ledger.validate() + } +} diff --git a/Tests/ComponentsTests/LedgerReplayBudgetTests.swift b/Tests/ComponentsTests/LedgerReplayBudgetTests.swift new file mode 100644 index 0000000..8a2d43b --- /dev/null +++ b/Tests/ComponentsTests/LedgerReplayBudgetTests.swift @@ -0,0 +1,102 @@ +import AgentsCore +import AgentsInstructions +import Components +import Foundation +import Testing + +@Suite("Ledger replay aggregate budget") +struct LedgerReplayBudgetTests { + private func fixture(bytes: Int, repeats: Int, format: String = "agents/instructions@1") throws + -> (LinkFixture, ResolvedLedger) + { + let fixture = try LinkFixture() + let content = Data(repeating: 97, count: bytes) + let hash = "sha256:" + FileHash.sha256Hex(data: content) + var ledger = ResolvedLedger() + ledger.sources["root"] = .init(kind: .local, revision: "live") + ledger.contentObjects[hash] = content + ledger.resources["file"] = .init( + kind: .embedded, source: "root", path: "file", hash: hash, + entries: [.init(path: ".", kind: .file, object: hash, executable: false, byteCount: bytes)]) + #if os(macOS) + let platform = "macos" + #else + let platform = "linux" + #endif + ledger.lowerings = [ + .init( + id: "test", format: format, inputs: [], resources: Array(repeating: "file", count: repeats), + deployments: [], + layout: .init(object: ["name": .init("output"), "sectionCount": .init(integer: repeats)]), + platform: platform, artifacts: []) + ] + return (fixture, ledger) + } + + @Test(arguments: ["agents/instructions@1", "agents/chatgpt@1"]) + func repeatedInputsRejectBeforeResourceAcquisition(_ format: String) throws { + let (fixture, ledger) = try fixture(bytes: 1024 * 1024, repeats: 50_000, format: format) + // Invalid content hashes would fail later; the aggregate bound must be the first failure. + do { + _ = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: .standard) + Issue.record("oversized replay accepted") + } catch { + #expect(String(describing: error).contains("replay input byte budget")) + } + } + + @Test func validRepeatsAndRetainedOutputsShareBudget() throws { + let (fixture, original) = try fixture(bytes: 3, repeats: 2, format: "test/budget@1") + var limits = LedgerLimits.standard + limits.resourceBytes = 12 + var calls = 0 + let renderer: LedgerRenderer = { lowering, _, _ in + calls += 1 + return [.init(name: lowering.id, kind: .file, bytes: Data(repeating: 98, count: 6))] + } + let table = ["test/budget@1": renderer] + _ = try LedgerReplay.prepareLowerings( + original, store: fixture.store, roots: [:], limits: limits, renderers: table) + #expect(calls == 1) + var ledger = original + var second = ledger.lowerings[0] + second.id = "second" + ledger.lowerings.append(second) + limits.resourceBytes = 18 + #expect(throws: (any Error).self) { + _ = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: limits, renderers: table) + } + #expect(calls == 3) + } + @Test(arguments: ["agents/instructions@1", "agents/chatgpt@1"]) + func compatibilityOutputsUseRemainingAggregateBudget(_ format: String) throws { + let content = Data("---\ndescription: Example\n---\n# Example\n\nBody\n".utf8) + let (fixture, original) = try fixture(bytes: content.count, repeats: 1, format: format) + var ledger = original + let hash = "sha256:" + FileHash.sha256Hex(data: content) + ledger.contentObjects = [hash: content] + ledger.resources["file"]?.hash = hash + ledger.resources["file"]?.entries[0].object = hash + let output = + try format == "agents/instructions@1" + ? InstructionCompatibility.renderSections([content], ids: ["file"]) + : InstructionCompatibility.renderPrompt([content], ids: ["file"], append: nil) + var limits = LedgerLimits.standard + limits.resourceBytes = content.count * 2 + output.count * 2 - 1 + _ = try LedgerReplay.prepareLowerings(ledger, store: fixture.store, roots: [:], limits: limits) + var second = ledger.lowerings[0] + second.id = "second" + second.layout.object?["name"] = .init("second-output") + ledger.lowerings.append(second) + do { + _ = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: limits) + Issue.record("aggregate output budget accepted") + } catch { + #expect(String(describing: error).contains("rendered instruction byte budget")) + } + } + +} From 35c8ab4db39b62b84553ce36d63a5c7da3656016 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:04:01 +0800 Subject: [PATCH 042/171] test: cover YAML declaration behavior --- .../IndependentYAMLAcceptanceTests.swift | 415 ++++++++++++++++++ 1 file changed, 415 insertions(+) create mode 100644 Tests/AgentsManifestTests/IndependentYAMLAcceptanceTests.swift diff --git a/Tests/AgentsManifestTests/IndependentYAMLAcceptanceTests.swift b/Tests/AgentsManifestTests/IndependentYAMLAcceptanceTests.swift new file mode 100644 index 0000000..bc2ab2f --- /dev/null +++ b/Tests/AgentsManifestTests/IndependentYAMLAcceptanceTests.swift @@ -0,0 +1,415 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsManifest + +private let yamlEnvironment = RuntimeEnvironment( + projectDirectory: URL(fileURLWithPath: "/work/project", isDirectory: true), + homeDirectory: URL(fileURLWithPath: "/work/home", isDirectory: true), environment: [:]) +private let yamlIdentity = DocumentIdentity("agents.yaml") + +private func yamlDocument(_ text: String) throws -> DeclarationDocument { + try DeclarationDocument(bytes: Array(text.utf8), identity: yamlIdentity) +} + +private func yamlProjection(_ text: String) throws -> Declaration { + try ManifestProjection.declaration(of: yamlDocument(text), environment: yamlEnvironment) +} + +private func yamlPlan(_ before: Declaration, _ after: Declaration, _ text: String?) throws + -> [UInt8]? +{ + try DeclarationEditPlan.bytes( + replacing: before, with: after, in: text.map { Array($0.utf8) }, + identity: yamlIdentity, environment: yamlEnvironment) +} + +private func assertYAMLEdit( + _ input: String, _ target: Declaration, preserving segments: [String], + sourceLocation: SourceLocation = #_sourceLocation +) throws -> String { + let before = try yamlProjection(input) + let bytes = try #require(try yamlPlan(before, target, input), sourceLocation: sourceLocation) + let output = String(decoding: bytes, as: UTF8.self) + let actual = try yamlProjection(output) + #expect(actual == target, sourceLocation: sourceLocation) + for segment in segments { + #expect( + output.contains(segment), "missing unchanged bytes: \(segment)", + sourceLocation: sourceLocation) + } + #expect(try yamlPlan(actual, target, output) == nil, sourceLocation: sourceLocation) + return output +} + +@Suite("Independent YAML acceptance") +struct IndependentYAMLAcceptanceTests { + @Test func nativeValuesRoundTripWithoutLosingNumericIdentity() throws { + let values: [NativeValue] = [ + .integer(1), .decimal("1"), .decimal("9223372036854775808"), .decimal("-0"), + .decimal("1.00"), .decimal("1E+003"), .decimal("1.2345678901234567890123456789"), + .string("1"), .string("true"), .boolean(true), .null, + ] + let desired = Declaration(components: [ + .lspServer( + name: "server", run: ExecutableDeclaration(executable: "missing-program"), + languages: [".swift": "swift"], + initializationOptions: ["nested": .array(values), "<<": .object(["text": .string("1")])], + native: ["example/lsp@1": ["values": .object(["nested": .array(values)])]]), + .ignore(name: "second", patterns: ["private/**"]), + ]) + let bytes = try #require(try yamlPlan(Declaration(), desired, nil)) + let text = String(decoding: bytes, as: UTF8.self) + let actual = try yamlProjection(text) + #expect(actual == desired) + guard case .lspServer(_, _, let languages, let options, _, _, let native) = actual.components[0] + else { + Issue.record("expected LSP component") + return + } + #expect(languages == [".swift": "swift"]) + #expect(options["nested"] == .array(values)) + #expect(options["<<"] == .object(["text": .string("1")])) + #expect(native["example/lsp@1"]?["values"] == .object(["nested": .array(values)])) + #expect(actual.components[1] == .ignore(name: "second", patterns: ["private/**"])) + #expect(try yamlPlan(actual, desired, text) == nil) + } + + @Test(arguments: ["\u{0085}", "\u{2028}", "\u{2029}"]) + func rawLineSeparatorsAreRejectedAtTheirOriginalBytes(_ character: String) throws { + let templates = [ + "version: 1\ncomponents:\n - {kind: subagent, name: a, description: \"left@right\", prompt: ok}\n", + "version: 1\ncomponents:\n - {kind: subagent, name: a, description: 'left@right', prompt: ok}\n", + "version: 1\ncomponents:\n - {kind: subagent, name: a, description: left@right, prompt: ok}\n", + "version: 1\ncomponents:\n - kind: subagent\n name: a\n description: |-\n left@right\n prompt: ok\n", + "version: 1\n# left@right\n", + ] + for template in templates { + let input = template.replacingOccurrences(of: "@", with: character) + let prefix = try #require(input.range(of: character)).lowerBound + let start = input[.. Date: Mon, 16 Nov 2026 03:31:41 +0800 Subject: [PATCH 043/171] feat: add YAML agent declarations --- .agent/agents.json | 17 - .agent/agents.yaml | 13 + .github/swift-package.json | 19 +- .gitignore | 2 +- Documentation/Architecture/Instructions.md | 2 +- Documentation/Architecture/Package.md | 185 +- Documentation/Architecture/README.md | 7 +- Documentation/Architecture/State.md | 100 +- Documentation/Architecture/Watch.md | 4 +- Documentation/Decisions/README.md | 4 +- Documentation/Decisions/SwiftManifest.md | 2 +- Documentation/Decisions/YAMLManifest.md | 24 + Documentation/Proposals/AgentInstructions.md | 4 +- Documentation/Proposals/AgentsManifest.md | 10 +- Documentation/Proposals/README.md | 7 +- Documentation/Reference/Manifest.md | 1302 +- Documentation/Reference/ManifestSchema.md | 266 + Documentation/Reference/Presentation.md | 2 +- Documentation/Reference/README.md | 3 +- Package.resolved | 10 +- Package.swift | 26 +- README.md | 26 +- Scripts/ManifestVocabulary.json | 1912 - Scripts/generate-manifest-fixtures.py | 57 - Scripts/generate-manifest-schema.py | 53 + Scripts/generate-manifest-vocabulary.py | 181 - Scripts/manifest_generation.py | 45 - Sources/AgentsCore/StateStore.swift | 2 +- .../AgentsDescription/ConstructionValue.swift | 118 - Sources/AgentsDescription/Version.swift | 103 - Sources/AgentsDescription/Vocabulary.swift | 862 - .../VocabularyInventory.swift | 866 - Sources/AgentsManifest/Admission.swift | 849 - Sources/AgentsManifest/CanonicalPrinter.swift | 338 - .../CompleteDeclarationPlanner.swift | 225 - .../ComponentConstruction.swift | 174 - .../ConstructionValueAccessors.swift | 21 - .../DeclarationConstruction.swift | 141 - .../AgentsManifest/DeclarationDocument.swift | 167 +- .../AgentsManifest/DeclarationEditPlan.swift | 522 +- Sources/AgentsManifest/DocumentEditor.swift | 600 +- Sources/AgentsManifest/DocumentEdits.swift | 700 - Sources/AgentsManifest/DocumentModels.swift | 102 +- Sources/AgentsManifest/DocumentStyle.swift | 82 - Sources/AgentsManifest/DocumentTrivia.swift | 138 - Sources/AgentsManifest/DomainValidation.swift | 422 - Sources/AgentsManifest/EvaluatedValue.swift | 44 - Sources/AgentsManifest/Evaluation.swift | 349 - Sources/AgentsManifest/IRTree.swift | 249 + .../AgentsManifest/LiteralConversion.swift | 118 - Sources/AgentsManifest/Lowering.swift | 64 - .../AgentsManifest/ManifestDiagnostic.swift | 3 +- Sources/AgentsManifest/ManifestDump.swift | 229 +- Sources/AgentsManifest/ManifestFrontEnd.swift | 124 +- Sources/AgentsManifest/ManifestLimits.swift | 13 +- .../AgentsManifest/ManifestProjection.swift | 4 +- Sources/AgentsManifest/ManifestSchema.swift | 174 + Sources/AgentsManifest/ManifestState.swift | 4 +- Sources/AgentsManifest/MapBuilder.swift | 204 - Sources/AgentsManifest/PieceTable.swift | 78 - .../Resources/agents.schema.json | 1217 + .../AgentsManifest/SourceRequirements.swift | 23 - Sources/AgentsManifest/SourceText.swift | 2 + .../StaticValueVocabulary.swift | 93 - Sources/AgentsManifest/SyntaxValidation.swift | 154 - Sources/AgentsManifest/ValueBudget.swift | 44 +- Sources/AgentsManifest/YAMLConstruction.swift | 353 + .../AgentsManifest/YAMLDomainValidation.swift | 303 + Sources/AgentsManifest/YAMLParser.swift | 322 + Sources/AgentsManifest/YAMLPatches.swift | 448 + Sources/AgentsManifest/YAMLProjection.swift | 357 + Sources/AgentsManifest/YAMLScalar.swift | 67 + Sources/AgentsManifest/YAMLValidation.swift | 177 + Sources/AgentsManifest/YAMLWriter.swift | 144 + Sources/Components/ComponentLinker.swift | 4 +- Sources/Components/Expansion.swift | 2 +- Sources/TreeSitterYAML/LICENSE | 20 + Sources/TreeSitterYAML/include/yaml.h | 16 + Sources/TreeSitterYAML/parser.c | 41384 ++++++++++++++++ Sources/TreeSitterYAML/provenance.json | 38 + Sources/TreeSitterYAML/scanner.c | 1415 + Sources/TreeSitterYAML/schema.core.c | 204 + Sources/TreeSitterYAML/tree_sitter/alloc.h | 54 + Sources/TreeSitterYAML/tree_sitter/array.h | 291 + Sources/TreeSitterYAML/tree_sitter/parser.h | 286 + .../DeclarationStateTests.swift | 20 +- .../InstructionTransactionTests.swift | 2 +- Tests/AgentsCoreTests/PublicationTests.swift | 2 +- .../StateTransactionTests.swift | 6 +- .../TransactionCostTests.swift | 2 +- Tests/AgentsCoreTests/WatchStateTests.swift | 12 +- .../DeclarationDocumentTests.swift | 39 +- .../OwnershipAndPlacementTests.swift | 9 +- .../TargetLifecycleTests.swift | 22 +- .../AdversarialTests.swift | 321 - .../CompiledFixtures.swift | 1053 - .../DeclarationProgressTests.swift | 32 +- .../DeclarationPropertyTests.swift | 209 - .../DifferentialFuzzTests.swift | 152 - Tests/AgentsManifestTests/DumpTests.swift | 150 - Tests/AgentsManifestTests/EditPlanTests.swift | 710 +- Tests/AgentsManifestTests/EditingTests.swift | 763 - .../ExpansionBudgetTests.swift | 10 +- .../Fixtures/ConsumerExample.dump.json | 5611 --- .../Fixtures/ConsumerExample.swift.txt | 97 - .../Fixtures/CoreExample.swift.txt | 23 - .../Fixtures/DumpSymbolic.dump.json | 3014 -- .../Fixtures/DumpSymbolic.swift.txt | 20 - .../Fixtures/ExportedGroup.swift.txt | 16 - .../Fixtures/InstructionRecipients.swift.txt | 11 - .../Fixtures/LiteralCoverage.dump.json | 6637 --- .../Fixtures/LiteralCoverage.swift.txt | 43 - .../Fixtures/ParserBaseline.json | 144 - .../Fixtures/PrintedEmpty.dump.json | 138 - .../Fixtures/PrintedEmpty.swift.txt | 4 - .../Fixtures/PrintedEscapes.swift.txt | 27 - .../Fixtures/PrintedExplicitEmpty.swift.txt | 11 - .../Fixtures/PrintedFields.dump.json | 2293 - .../Fixtures/PrintedFields.swift.txt | 76 - .../Fixtures/PrintedRanges.swift.txt | 43 - .../Fixtures/PrintedWidth.swift.txt | 24 - .../Fixtures/ProducerExample.swift.txt | 16 - .../Fixtures/RecipientConditions.swift.txt | 16 - .../Fixtures/RequirementValues.swift.txt | 24 - .../Fixtures/RequirementsExample.swift.txt | 46 - .../Fixtures/SectionConcatenation.swift.txt | 97 - .../Fixtures/SharedRules.swift.txt | 23 - .../Fixtures/SketchExample.swift.txt | 16 - .../Fixtures/SkillsExample.swift.txt | 11 - .../Fixtures/TeamConfiguration.swift.txt | 81 - .../Fixtures/VersionCollections.swift.txt | 8 - .../Fixtures/VocabularyDepthExample.swift.txt | 22 - Tests/AgentsManifestTests/FrontEndTests.swift | 246 +- .../FullDeclarationDependencyTests.swift | 4 +- .../FullDeclarationDraftTests.swift | 173 +- .../FullDeclarationTests.swift | 338 +- .../AgentsManifestTests/InventoryTests.swift | 206 - .../LanguageVersionTests.swift | 65 - .../LiteralConversionTests.swift | 42 - Tests/AgentsManifestTests/PrintingTests.swift | 166 - .../AgentsManifestTests/ProjectionTests.swift | 139 +- Tests/AgentsManifestTests/ResourceTests.swift | 170 +- .../SemanticVersionTests.swift | 94 - .../AgentsManifestTests/SourceMapTests.swift | 45 - Tests/AgentsManifestTests/Watchdog.swift | 9 +- .../ManifestLifecycleTests.swift | 96 +- Tests/ComponentsTests/ImpactTests.swift | 101 +- Tests/ComponentsTests/LedgerReplayTests.swift | 26 +- Tests/ComponentsTests/LinkBudgetTests.swift | 71 +- Tests/ComponentsTests/LinkFixture.swift | 6 +- .../LinkingAcceptanceTests.swift | 115 +- .../LinkingReviewRegressionTests.swift | 66 +- Tests/ComponentsTests/LinkingTests.swift | 97 +- Tests/ComponentsTests/SnapshotTests.swift | 47 +- Tests/ComponentsTests/UserScopeTests.swift | 36 +- Tests/ManifestTestProcess/main.swift | 3 +- Tests/StateTestProcess/LedgerProbe.swift | 2 +- Tests/StateTestProcess/main.swift | 4 +- Tests/StateTestSupport/ManifestText.swift | 9 +- 159 files changed, 49454 insertions(+), 34818 deletions(-) delete mode 100644 .agent/agents.json create mode 100644 .agent/agents.yaml create mode 100644 Documentation/Decisions/YAMLManifest.md create mode 100644 Documentation/Reference/ManifestSchema.md delete mode 100644 Scripts/ManifestVocabulary.json delete mode 100644 Scripts/generate-manifest-fixtures.py create mode 100644 Scripts/generate-manifest-schema.py delete mode 100644 Scripts/generate-manifest-vocabulary.py delete mode 100644 Scripts/manifest_generation.py delete mode 100644 Sources/AgentsDescription/ConstructionValue.swift delete mode 100644 Sources/AgentsDescription/Version.swift delete mode 100644 Sources/AgentsDescription/Vocabulary.swift delete mode 100644 Sources/AgentsDescription/VocabularyInventory.swift delete mode 100644 Sources/AgentsManifest/Admission.swift delete mode 100644 Sources/AgentsManifest/CanonicalPrinter.swift delete mode 100644 Sources/AgentsManifest/CompleteDeclarationPlanner.swift delete mode 100644 Sources/AgentsManifest/ComponentConstruction.swift delete mode 100644 Sources/AgentsManifest/ConstructionValueAccessors.swift delete mode 100644 Sources/AgentsManifest/DeclarationConstruction.swift delete mode 100644 Sources/AgentsManifest/DocumentEdits.swift delete mode 100644 Sources/AgentsManifest/DocumentStyle.swift delete mode 100644 Sources/AgentsManifest/DocumentTrivia.swift delete mode 100644 Sources/AgentsManifest/DomainValidation.swift delete mode 100644 Sources/AgentsManifest/EvaluatedValue.swift delete mode 100644 Sources/AgentsManifest/Evaluation.swift create mode 100644 Sources/AgentsManifest/IRTree.swift delete mode 100644 Sources/AgentsManifest/LiteralConversion.swift delete mode 100644 Sources/AgentsManifest/Lowering.swift create mode 100644 Sources/AgentsManifest/ManifestSchema.swift delete mode 100644 Sources/AgentsManifest/MapBuilder.swift delete mode 100644 Sources/AgentsManifest/PieceTable.swift create mode 100644 Sources/AgentsManifest/Resources/agents.schema.json delete mode 100644 Sources/AgentsManifest/SourceRequirements.swift delete mode 100644 Sources/AgentsManifest/StaticValueVocabulary.swift delete mode 100644 Sources/AgentsManifest/SyntaxValidation.swift create mode 100644 Sources/AgentsManifest/YAMLConstruction.swift create mode 100644 Sources/AgentsManifest/YAMLDomainValidation.swift create mode 100644 Sources/AgentsManifest/YAMLParser.swift create mode 100644 Sources/AgentsManifest/YAMLPatches.swift create mode 100644 Sources/AgentsManifest/YAMLProjection.swift create mode 100644 Sources/AgentsManifest/YAMLScalar.swift create mode 100644 Sources/AgentsManifest/YAMLValidation.swift create mode 100644 Sources/AgentsManifest/YAMLWriter.swift create mode 100644 Sources/TreeSitterYAML/LICENSE create mode 100644 Sources/TreeSitterYAML/include/yaml.h create mode 100644 Sources/TreeSitterYAML/parser.c create mode 100644 Sources/TreeSitterYAML/provenance.json create mode 100644 Sources/TreeSitterYAML/scanner.c create mode 100644 Sources/TreeSitterYAML/schema.core.c create mode 100644 Sources/TreeSitterYAML/tree_sitter/alloc.h create mode 100644 Sources/TreeSitterYAML/tree_sitter/array.h create mode 100644 Sources/TreeSitterYAML/tree_sitter/parser.h delete mode 100644 Tests/AgentsManifestTests/AdversarialTests.swift delete mode 100644 Tests/AgentsManifestTests/CompiledFixtures.swift delete mode 100644 Tests/AgentsManifestTests/DeclarationPropertyTests.swift delete mode 100644 Tests/AgentsManifestTests/DifferentialFuzzTests.swift delete mode 100644 Tests/AgentsManifestTests/DumpTests.swift delete mode 100644 Tests/AgentsManifestTests/EditingTests.swift delete mode 100644 Tests/AgentsManifestTests/Fixtures/ConsumerExample.dump.json delete mode 100644 Tests/AgentsManifestTests/Fixtures/ConsumerExample.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/CoreExample.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/DumpSymbolic.dump.json delete mode 100644 Tests/AgentsManifestTests/Fixtures/DumpSymbolic.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/ExportedGroup.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/InstructionRecipients.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/LiteralCoverage.dump.json delete mode 100644 Tests/AgentsManifestTests/Fixtures/LiteralCoverage.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/ParserBaseline.json delete mode 100644 Tests/AgentsManifestTests/Fixtures/PrintedEmpty.dump.json delete mode 100644 Tests/AgentsManifestTests/Fixtures/PrintedEmpty.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/PrintedEscapes.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/PrintedExplicitEmpty.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/PrintedFields.dump.json delete mode 100644 Tests/AgentsManifestTests/Fixtures/PrintedFields.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/PrintedRanges.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/PrintedWidth.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/ProducerExample.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/RecipientConditions.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/RequirementValues.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/RequirementsExample.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/SectionConcatenation.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/SharedRules.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/SketchExample.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/SkillsExample.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/TeamConfiguration.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/VersionCollections.swift.txt delete mode 100644 Tests/AgentsManifestTests/Fixtures/VocabularyDepthExample.swift.txt delete mode 100644 Tests/AgentsManifestTests/InventoryTests.swift delete mode 100644 Tests/AgentsManifestTests/LanguageVersionTests.swift delete mode 100644 Tests/AgentsManifestTests/LiteralConversionTests.swift delete mode 100644 Tests/AgentsManifestTests/PrintingTests.swift delete mode 100644 Tests/AgentsManifestTests/SemanticVersionTests.swift delete mode 100644 Tests/AgentsManifestTests/SourceMapTests.swift diff --git a/.agent/agents.json b/.agent/agents.json deleted file mode 100644 index 5c68742..0000000 --- a/.agent/agents.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "instructions": { - "agents": ["claude-code", "codex"], - "sections": [ - "guide", - "agents-tools:shared/swift-package-route", - "agents-tools:shared/swift-package-tests" - ] - }, - "sources": { - "agents-tools": { - "branch": "master", - "git": "github.com/agents-tools/.github", - "path": ".agent" - } - } -} diff --git a/.agent/agents.yaml b/.agent/agents.yaml new file mode 100644 index 0000000..2799bdd --- /dev/null +++ b/.agent/agents.yaml @@ -0,0 +1,13 @@ +version: 1 +sources: + agents-tools: + url: https://github.com/agents-tools/.github + requirement: {branch: master} + subpath: .agent +components: + - kind: instructions + agents: [claude-code, codex] + sections: + - {name: guide} + - {name: shared/swift-package-route, source: agents-tools} + - {name: shared/swift-package-tests, source: agents-tools} diff --git a/.github/swift-package.json b/.github/swift-package.json index 22e5cd5..83fa341 100644 --- a/.github/swift-package.json +++ b/.github/swift-package.json @@ -1,17 +1,20 @@ { "commands": [ { - "name": "manifest-vocabulary-generation", - "run": "python3 Scripts/generate-manifest-vocabulary.py --check" - }, - { - "name": "manifest-fixture-generation", - "run": "python3 Scripts/generate-manifest-fixtures.py --check" + "name": "manifest-schema-generation", + "run": "python3 Scripts/generate-manifest-schema.py --check" } ], - "test_configurations": ["debug", "release"], + "test_configurations": [ + "debug", + "release" + ], "compilers": [ - {"name": "macos-26-xcode-26.6", "runner": "macos-26", "xcode": "26.6"} + { + "name": "macos-26-xcode-26.6", + "runner": "macos-26", + "xcode": "26.6" + } ], "platforms": { "linux": [ diff --git a/.gitignore b/.gitignore index f27a062..00c45a6 100644 --- a/.gitignore +++ b/.gitignore @@ -10,5 +10,5 @@ DerivedData/ .netrc /.agent/* !/.agent/instructions/ -!/.agent/agents.json +!/.agent/agents.yaml !/.agent/agents.resolved diff --git a/Documentation/Architecture/Instructions.md b/Documentation/Architecture/Instructions.md index 7d86be4..0a9cda0 100644 --- a/Documentation/Architecture/Instructions.md +++ b/Documentation/Architecture/Instructions.md @@ -40,7 +40,7 @@ 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; `.section(name:source:)` in `Agents.swift`, or `alias:name` in operation +name; `.section(name:source:)` in `agents.yaml`, or `alias:name` in operation arguments, 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 diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 5b229e5..25e554d 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -2,152 +2,55 @@ ## Purpose and Consumers -`core` supplies skill and instruction management and instruction text -transformations. Both `agents` in `agents-tools/cli` and `skill` in -`skill-cli/cli` consume this package. Consumers own command trees, argument -parsing, terminal presentation, and executable distribution. The package uses -Swift 6.3 and Swift 6 language mode. It supports macOS 15 or newer and Linux -with glibc 2.34 or newer. +`core` supplies symbolic agent declarations, source linking, skill and instruction +management, resolved state and recoverable application. Both `agents-tools/cli` +and `skill-cli/cli` consume its public products. Consumers own command parsing, +terminal/UI presentation and executable distribution. -## Products and Dependencies +## Target Boundaries ```text -AgentsDescription (standard library only) -AgentsManifest ──> AgentsDescription, AgentsCore, SwiftSyntax, SwiftParser (swift-syntax) - -Components ──> AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions -AgentsUpdates ──> AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, CPlatform - -AgentsCore ──> CPlatform, Crypto (swift-crypto) - -AgentsSkills ──> AgentsCore, AgentsManifest - │ - └───────> Yams - -AgentsInstructions ──> AgentsCore, AgentsManifest - │ - └───────> Markdown (swift-markdown) ──> cmark-gfm - -ManifestTestSupport ──> AgentsManifest -ManifestTestProcess ──> AgentsManifest, AgentsCore, AgentsDescription, ManifestTestSupport -AgentsManifestTests ──> AgentsManifest, AgentsDescription, AgentsCore, ManifestTestProcess, ManifestTestSupport, SwiftParser, SwiftSyntax - -StateTestSupport (Foundation only) -StateTestProcess ──> AgentsCore, AgentsManifest, AgentsInstructions, AgentsSkills, AgentsUpdates, Components, CPlatform, StateTestSupport -AgentsCoreTests ──> AgentsCore, AgentsManifest, StateTestProcess, StateTestSupport, CPlatform -AgentsSkillsTests ──> AgentsSkills, AgentsCore, AgentsManifest, AgentsInstructions, Yams, StateTestProcess, StateTestSupport, CPlatform -AgentsInstructionsTests ──> AgentsInstructions, AgentsManifest -AgentsUpdatesTests ──> AgentsUpdates, AgentsManifest, StateTestProcess, StateTestSupport, CPlatform -ComponentsTests ──> Components, AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, StateTestProcess, StateTestSupport +AgentsManifest → AgentsCore, TreeSitterYAML, TreeSitter, Yams +AgentsSkills → AgentsCore, AgentsManifest, Yams +AgentsInstructions → AgentsCore, AgentsManifest, Markdown +Components → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions +AgentsUpdates → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions +AgentsCore → CPlatform, Crypto ``` -`AgentsDescription`, `AgentsManifest`, `AgentsCore`, `AgentsSkills`, -`AgentsInstructions` and `AgentsUpdates` are library products with -matching targets under `Sources/`. Tests under `Tests/` include construction -vocabulary and compiler-oracle coverage in `AgentsManifestTests`. Shared -implementation uses `package` access; consumers receive the -workflow APIs and the state and result models they need. `Package.swift` owns -this dependency graph. - -`CPlatform` is an internal C target for filesystem and process differences. It -wraps file locks, access checks, atomic exchange and no-replace rename, -filesystem-generation comparison, directory entry names, durable synchronization, -metadata copying and spawn actions. Linux uses -`renameat2(RENAME_EXCHANGE)` and `renameat2(RENAME_NOREPLACE)`, `fsync`, -descriptor-based mode/xattr copying (including POSIX ACLs) and glibc's -`posix_spawn_file_actions_addclosefrom_np`. Symlink metadata uses no-follow calls -through pinned parent paths in `/proc/self/fd`; Linux symlink modes remain 0777. -Darwin keeps `renameatx_np`, `F_FULLFSYNC`, `fcopyfile` and its spawn inheritance -policy. Business workflows share the same Swift implementation. -Foundation re-exports the platform libc used by the Swift code; `CPlatform` -bridges APIs missing from those overlays. - -`AgentsCore` hashes through swift-crypto's `Crypto` product, which delegates to -CryptoKit on Apple platforms and supplies its own implementation on Linux. - -`StateTestSupport` supplies the shared process-handshake deadline and diagnostics -for transaction, watch and update tests. `StateTestProcess` records actual -checkpoints and supports interruption and resumed recovery through the production -journal protocol. Its recorder fails on a repeated name, so repeated work numbers -its checkpoints and nested transactions prefix theirs. - -## AgentsDescription and AgentsManifest - -`AgentsDescription` owns the immutable language 1.0 authoring vocabulary. It uses -only the standard library, with private payload storage and closed literal -conformances. `Scripts/ManifestVocabulary.json` is the construction signature and -literal inventory; `Scripts/generate-manifest-vocabulary.py` generates the public -factories, literal conversions, package-only registrations and `StaticValue` factories -together. CI commands in `.github/swift-package.json` compare generated bytes on -the last compiler entry's runner. SwiftPM tests compare registered signatures, -defaults and literal protocols with the -[language reference](../Reference/Manifest.md), and the complete fixture -inventory with compiler-backed values and the parser baseline. See -[Development](../../README.md#development) for local validation commands. - -`AgentsManifest.DeclarationDocument` parses and statically evaluates supplied UTF-8 bytes without -executing code or reading sources. Version selection, strict lexing and bounded -grammar recognition complete before SwiftParser sees the exact snapshot. An -iterative all-nodes guard precedes syntax inspection and independent projection -comparison. Static typing, occurrence-based expanded-size accounting and offline -domain validation produce `AgentsCore.DeclarationIR` and `DeclarationSourceMap`. -Constants, inactive values and unused groups receive the same checks. Group -references and conditions remain symbolic. - -The package-only `ManifestExpansionBudget` applies the same value, source-map -and output accounting to declarations repeated by source/group linking. -`Components` supplies each original IR record and its reference origins and -charges traversal work to the linker's retained work budget. - -`DeclarationDocument` is the public consumer surface: - -| Operation | Consumer API | -| --- | --- | -| Parse and statically evaluate supplied bytes | `init(bytes:identity:)` | -| Read declaration and provenance | `declaration`, `sourceMap`, `diagnostics` | -| Read the immutable snapshot | `bytes`, `digest` | -| Address an occurrence | `node(at:)`, `constant(named:)`, `uses(ofConstant:)`, `NodeID` | -| Check an editing boundary | `editability(of:)`, `Editability` | -| Prepare checked source changes | `preparing(_:)`, `ManifestEdit`, `StaticValue`, `DocumentChange` | - -`node(at:)` accepts a JSON Pointer into lowered declaration fields. The empty -pointer addresses the root, decimal segments index arrays, and dictionary keys -escape `~` as `~0` and `/` as `~1`. Literal configuration payloads appear under -`value`; source requirements use normalized requirement fields. `constant(named:)` -and `uses(ofConstant:)` accept Swift identifiers directly. Handles belong to one -snapshot digest and cannot be reused after preparing a new document. - -The document retains original bytes, a lossless syntax tree, a byte digest and -snapshot-bound `NodeID` handles. `preparing(_:)` accepts `ManifestEdit` batches, -constructs expected intent, produces disjoint byte patches, reruns the complete -front end and compares the resulting declaration. `DocumentChange` carries both -byte digests, resulting bytes, diagnostics, impacted references and semantic delta -for later orchestration. Source edits do not publish files. Shared constants -require explicit impact acceptance; ambiguous comments or separators are refused. -The [manifest language reference](../Reference/Manifest.md) specifies the -language, editing rules and dump schema. - -`AgentsManifest` also connects `Agents.swift` to scope state through -`extension StateStore`. The public `loadDeclaration()` returns the complete -typed symbolic declaration and `loadManifest()` the complete document; both are read-only and, -like the public `WatchOperations.init(discoverSkills:fetchArtifacts:)`, require -`import AgentsManifest`. -Package-level declaration reading and planning, the projection onto -`AgentsCore.Declaration` and the declaration edit planner serve the domain -modules, and `DeclarationAccess.manifest` supplies the same access to -`WatchOperations`, whose public `init(discoverSkills:fetchArtifacts:)` this -module provides. All file I/O, evidence and publication stay in `AgentsCore`: -the extension parses prepared bytes and returns planned bytes. See -[Declaration](State.md#declaration) for the current deployment boundary and full -declaration write semantics. - -`ManifestTestProcess` is a test-only executable and calls the same instrumented -front-end pipeline as document construction. `ManifestTestSupport` owns the -shared process report and build-configuration watchdog limits. Parent watchdogs exercise -admission, parsing, checking and tree teardown, including fixed adversarial forms -and deterministic differential fuzzing. Positive corpus sources are also compiled -as ordinary Swift in the test target and compared using value equality. Parser -baselines and seeds belong to the test corpus, not the runtime language. +`TreeSitterYAML` is an internal C target containing the pinned, unmodified YAML +parser/scanner and headers, with upstream license and per-file provenance. +The runtime is a normal SwiftPM dependency. Consumers never receive parser types. + +## AgentsManifest + +The frontend reads `.agent/agents.yaml` or the user scope’s `agents.yaml` and +produces complete syntax-independent IR and typed declarations. Admission checks +UTF-8 and unsupported raw line separators before parsing. Tree-sitter supplies +concrete byte ranges under an enforced parser work policy; bounded CST admission +precedes public Yams ordered-node composition. The bundled schema owns field +shapes and generates finite runtime constraints and reference help. Core scalar +resolution preserves string values, integer kind and exact decimal payloads. + +`DeclarationDocument` is an immutable validated snapshot with digest-scoped +occurrence handles. `ManifestEdit` carries Core domain values. Its editor changes +owned ranges, preserves unrelated bytes/comments, refreshes source maps and checks +full expected IR. Public changes are domain-valid, including no-op preparations. +`DeclarationEditPlan` privately composes bounded drafts for complete domain changes +and validates final IR, domain and declaring environments before returning bytes. + +`ManifestDump` exposes schema version 2, format `yaml`, manifest version 1, typed +IR records and semantic indexed source locations. Parsing, projection, dump and +edit preparation do not resolve sources, read resources or execute programs. + +`StateStore` extensions supply declaration reads, loading and edit planning; +`DeclarationAccess.manifest` connects watch operations. All state I/O, evidence, +locks and publication remain in Core. See [state](State.md) and the +[manifest reference](../Reference/Manifest.md). + +`ManifestTestProcess` and `ManifestTestSupport` own isolated parser/editing probes +and their resource reports. Package tests cover the complete YAML/domain contract +and the existing state, linking, lifecycle and recovery guarantees. ## AgentsCore diff --git a/Documentation/Architecture/README.md b/Documentation/Architecture/README.md index 7dd59b6..5d66cda 100644 --- a/Documentation/Architecture/README.md +++ b/Documentation/Architecture/README.md @@ -1,10 +1,9 @@ # Architecture This directory holds the current truth for `core`, a SwiftPM library package. -`AgentsDescription` supplies the types-only construction vocabulary. -`AgentsManifest` statically evaluates and edits manifest snapshots, projects -`Agents.swift` onto the complete typed symbolic declaration and plans declaration writes -through `StateStore`, whose file I/O stays in core. `AgentsCore` owns +`AgentsManifest` owns YAML admission, scalar resolution, schema validation, +source maps and lossless edits for the complete typed declaration. It plans +writes through `StateStore`, whose file I/O stays in core. `AgentsCore` owns syntax-independent declaration IR, spans, provenance, shared sources, declaration bytes and lock storage, cache, watch subscriptions, and agent locations, without knowing the declaration format. `AgentsSkills` owns skill diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index 7ce1052..89083ab 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -4,8 +4,8 @@ | Scope | Declaration | Lock | Watch state | Cache | | --- | --- | --- | --- | --- | -| Project | `.agent/Agents.swift` | `.agent/agents.resolved` | `.agent/agents.watch` | `.agent/cache/` | -| User | `~/.agents/Agents.swift` | `~/.agents/agents.resolved` | `~/.agents/agents.watch` | `~/.agents/cache/` | +| Project | `.agent/agents.yaml` | `.agent/agents.resolved` | `.agent/agents.watch` | `.agent/cache/` | +| User | `~/.agents/agents.yaml` | `~/.agents/agents.resolved` | `~/.agents/agents.watch` | `~/.agents/cache/` | User paths are relative to `RuntimeEnvironment.homeDirectory`. State files belong to their scope. A project may commit its declaration and lock; the cache, @@ -15,9 +15,9 @@ operations. ## Declaration -`Agents.swift` records user intent in the [manifest +`agents.yaml` records user intent in the [manifest language](../Reference/Manifest.md). The document is the declaration's only -truth. `AgentsManifest` parses and evaluates its bytes and projects them onto +truth. `AgentsManifest` parses and validates its bytes and projects them onto `AgentsCore.Declaration`, the complete typed symbolic intent with no serialized form. Ordered sources, components, groups, uses, exports, prompt sections and parameters retain their occurrences. Conditions, native values, runtime bindings @@ -27,30 +27,25 @@ extends `StateStore` with declaration reading, planning and loading. Parse, edit and deployment-boundary failures are `ManifestFailure` diagnostics located in the declaration file. -```swift -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - sources: [ - .source(name: "drafts", path: "~/Developer/skills"), - .source( - name: "team", url: "https://github.com/example/skills", from: "1.0.0" - ), - ], - components: [ - .skills( - source: "drafts", select: ["release-notes"], mode: .edit, - overrides: [.skill(name: "release-notes", agents: [.codex])] - ), - .skills(source: "team", exclude: ["retired"]), - ] -) +```yaml +version: 1 +sources: + drafts: {path: ~/Developer/skills} + team: + url: https://github.com/example/skills + requirement: {from: "1.0.0"} +components: + - kind: skills + source: drafts + select: [release-notes] + mode: edit + overrides: {release-notes: {agents: [codex]}} + - {kind: skills, source: team, exclude: [retired]} ``` ### Deployable subset -`loadDeclaration()` projects every language 1.0 component family, including MCP, +`loadDeclaration()` projects every declared component family, including MCP, hooks, subagents, commands, LSP, permissions, ignores and plugins. It preserves unused groups and inactive structures and never resolves sources, reads resources or runs component programs. `Declaration.sourceDeclarations` and `components` @@ -60,7 +55,7 @@ directories so importing code cannot reinterpret their relative paths. The current skill/instruction deployment paths use `readDeploymentDeclaration(prepared:)`. This explicit boundary accepts root -`defaultAgents`, `sources` and `watch`, and root `.skills` and `.instructions` +`defaultAgents`, `sources` and `watch`, and root `skills` and `instructions` components: at most one skills occurrence per alias and one instructions occurrence, with no condition on a component, section or prompt and empty native configuration. Unused groups and exports remain preserved. Active group uses, @@ -84,7 +79,7 @@ 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. -A skill selection is all members, when `select` is omitted or `.all`, or an +A skill selection is all members, when `select` is omitted or `all`, or an explicit name array, with optional exclusions, recipients, mode and per-skill overrides. An all-member selection follows discovery membership on an unnamed update. Removing a member adds an exclusion. Explicitly named updates resolve @@ -92,7 +87,7 @@ only those members and fail if a requested member is missing. Skill filesystem identities are unique within a scope across sources. Requirements are `branch:`, `revision:`, `exact:`, `from:` (up to the next -major version), `.upToNextMinor(from:)` or a half-open range. Ranges include +major version), `upToNextMinor:` or `{from:, to:}`. Ranges include their lower bound and exclude their upper bound. A prerelease requires a prerelease bound with the same major, minor and patch. With no requirement, resolution chooses the latest semantic-version tag, then the source's default @@ -112,7 +107,7 @@ preserve both and existing watch-state bytes. | Declaration | Lock or watch state | Behavior | | --- | --- | --- | -| Absent | Absent | An empty declaration. Reads return empty results; the first write that declares something creates `Agents.swift` with no-replace publication. A write whose declaration and resulting lock are both empty creates neither file. | +| Absent | Absent | An empty declaration. Reads return empty results; the first write that declares something creates `agents.yaml` with no-replace publication. A write whose declaration and resulting lock are both empty creates neither file. | | Present | Any | Normal. An absent lock is an empty resolved state: `update` creates it and `install` has nothing to restore. | | Absent | Present | The state cannot be used. Throwing APIs report `CoreError.missingDeclaration` with the declaration path; export returns `.unavailable`, and batch doctor reports a `.stateUnavailable` diagnostic for the affected scope. Nothing is written, and no `.agents.lock` is created. | @@ -161,37 +156,24 @@ Semantic equality decides whether anything changes: in order; conditions, symbolic references, runtime bindings and native values all participate. -Planning edits direct fields, dictionary members and ordered occurrences. Existing -skill/instruction workflows keep their established insertion order. Explicit -changes to full ordered collections retain matching occurrences where possible; -a length change with repeated matching names is ambiguous and requires an -occurrence-addressed `ManifestEdit`. The skill/instruction plan appends new -sources, replaces changed sources in place and removes sources after their -references. A new skills -component is inserted before the instructions component, or last; a new -instructions component is last. Selections, exclusions, recipients, mode, -overrides, sections, prompts, watch aliases and default recipients change at -argument or element granularity: existing arrays gain and lose elements in -place, an ordered array gains them in order, and sections use a -longest-common-subsequence edit that keeps repetitions. Edits replace only their -target ranges; bytes outside them, comments included, stay unchanged. Constructs -the editor cannot address exactly, such as shared constants, concatenations and -ambiguous comments, fail with `manifest.edit.readOnly`. A batch holds at most -100 requests, and the document is rebuilt from the new bytes before the -remaining difference is planned. The projection of the final document must equal -the intended declaration, or planning fails with `manifest.edit.mismatch`. -Complete edits compose private static drafts across batches. Each batch retains -the front end's static limits and compares its complete IR with the expected -batch result. Domain validation waits until composition finishes, so related -source and reference changes can cross a batch boundary. The final bytes must -pass normal domain validation, environment-aware typed validation and the full -intended-declaration comparison before they can leave planning. Public prepared -changes always validate their final domain, including no-ops. -Composition has an operation budget of twice the combined current and target -value-node counts, and each replan must reduce the remaining direct difference. +Planning edits direct fields, dictionary members and ordered occurrences. Core's +skill/instruction convenience mutations retain their insertion order. Repeated +ambiguous selections require an occurrence-addressed `ManifestEdit`. The editor +changes owned ranges and retains comments, while unrelated bytes stay exact. + +Complete changes use one direct IR edit script throughout composition. Each array +step fixes the next target position or removes a surplus occurrence; each field is +visited once. Its finite operation bound is twice the combined current/target +value-node counts. Batches contain at most 100 operations and are sized against +actual editing work. Private drafts refresh the CST/source map and compare the +complete expected IR after every operation. Domain references can transition +across internal batches. Final normal domain validation, environment-aware typed +projection and full intended-IR comparison precede returning bytes. Public +prepared changes always validate final domain, including no-ops. No draft enters +state storage or a public change. Without declaration bytes, planning prints the complete typed declaration with the -[canonical printer](../Reference/Manifest.md#canonical-printing), retaining its +[YAML writer](../Reference/Manifest.md#edits-and-source-maps), retaining its ordered collections and symbolic group uses. Dictionary-based convenience initializers and domain mutations choose deterministic order for new entries. First state-declaration creation sorts only the set-like watch aliases; pure @@ -451,7 +433,7 @@ ownership denials are reported rather than bypassed. Every mutating state operation first checks for an abandoned journal under the scope lock, validates watch state and finishes pending reference cleanup before proceeding. Recovery never reads the declaration: journal and watch-reference -recovery complete even when `Agents.swift` does not parse, and orphaned mirror +recovery complete even when `agents.yaml` does not parse, and orphaned mirror locations come from watch state and the lock, then from the mirror's origin. Journal recovery selects and syncs a consistent generation before watch reconciliation can release any ref. Pending watch-reference recovery also @@ -524,7 +506,7 @@ lock or recovery marker before returning either its result or its error. A writer causes that attempt to be discarded and retried under the shared lock. Writers create the scope lock before mutation and never remove it. The scope lock exists before the declaration is parsed, so a first writer that meets an -invalid `Agents.swift` reports its `ManifestFailure` after creating +invalid `agents.yaml` reports its `ManifestFailure` after creating `.agents.lock`; invalid lock or watch state stops the writer before the lock exists. diff --git a/Documentation/Architecture/Watch.md b/Documentation/Architecture/Watch.md index c54583f..8f5c8f1 100644 --- a/Documentation/Architecture/Watch.md +++ b/Documentation/Architecture/Watch.md @@ -1,7 +1,7 @@ # Watch Subscriptions `AgentsCore.WatchOperations` manages subscriptions independently of installation -intent and pins. `Agents.swift` lists subscribed source aliases in the `watch:` +intent and pins. `agents.yaml` lists subscribed source aliases in the `watch:` argument of `Agents(...)`; `agents.watch` records a seen baseline per normalized source ID. Subscribing installs nothing, and removing a subscription preserves source declarations, @@ -119,7 +119,7 @@ revisions or digests are errors. Subscriptions cannot repeat an alias. Add, seen and remove hold the scope writer lock and recover interrupted transactions and pending ref cleanup before proceeding. They capture declaration, lock and watch evidence before contacting Git. Add and remove plan the -`Agents.swift` change at that point, so a declaration the editor cannot change +`agents.yaml` change at that point, so a declaration the editor cannot change fails before any fetch; seen leaves the declaration unchanged. Add and seen prepare cached content before publishing its baseline. Declaration and watch replacements and cache pruning commit through the existing scope transaction diff --git a/Documentation/Decisions/README.md b/Documentation/Decisions/README.md index e3d085f..ce05841 100644 --- a/Documentation/Decisions/README.md +++ b/Documentation/Decisions/README.md @@ -10,8 +10,8 @@ This directory holds durable decision records for `skill-cli`. - `SPMInspiredRegistry.md`: SPM-inspired first-party skill registry schema - `SwiftStyleFlagSurface.md`: Swift-style canonical flag spelling for install/list/remove/update -- `SwiftManifest.md`: `Agents.swift` as a statically evaluated Swift - declaration with lossless edits +- `YAMLManifest.md`: YAML authoring, bounded parsing and lossless source edits +- `SwiftManifest.md`: superseded frontend decision, retained as history - `AgentComponents.md`: component model, capability registry, input adapters and native deployment - `ConfigurationApplication.md`: shared configuration preview/application and diff --git a/Documentation/Decisions/SwiftManifest.md b/Documentation/Decisions/SwiftManifest.md index e444998..bcc5909 100644 --- a/Documentation/Decisions/SwiftManifest.md +++ b/Documentation/Decisions/SwiftManifest.md @@ -2,7 +2,7 @@ ## Status -Accepted +Superseded by [YAML Manifest](YAMLManifest.md). ## Context diff --git a/Documentation/Decisions/YAMLManifest.md b/Documentation/Decisions/YAMLManifest.md new file mode 100644 index 0000000..00f1757 --- /dev/null +++ b/Documentation/Decisions/YAMLManifest.md @@ -0,0 +1,24 @@ +# YAML Manifest + +## Status + +Accepted. + +## Decision + +The canonical authoring document is `agents.yaml`, using YAML version 1 field +shapes owned by AgentsManifest. Core domain and lifecycle semantics remain +independent of syntax. The lock remains JSON. No component program runs while +reading, inspecting or editing a declaration. + +A pinned Tree-sitter runtime and unmodified YAML grammar provide concrete ranges; +public Yams ordered-node composition decodes scalars after bounded admission. +Finite schema-generated constraints validate shapes. Explicit NativeValue-only +float tags retain decimal kind and exact text. Raw Unicode line separators that +parsers interpret differently are rejected before parsing; escaped values remain +exact strings. + +Edits preserve unrelated bytes and owned comments. Complete intent, source +references and ordering are checked before returning candidate bytes. The +existing transaction, source identity, security and client-owned trust boundaries +continue unchanged. See the [current reference](../Reference/Manifest.md). diff --git a/Documentation/Proposals/AgentInstructions.md b/Documentation/Proposals/AgentInstructions.md index 823bf4e..3c146c7 100644 --- a/Documentation/Proposals/AgentInstructions.md +++ b/Documentation/Proposals/AgentInstructions.md @@ -2,7 +2,9 @@ ## Status -Draft +Historical design draft. Frontend examples are superseded by the accepted +[YAML manifest decision](../Decisions/YAMLManifest.md); current lifecycle and +state contracts live in `../Architecture/`. ## Problem diff --git a/Documentation/Proposals/AgentsManifest.md b/Documentation/Proposals/AgentsManifest.md index aa870f3..d8c3ea8 100644 --- a/Documentation/Proposals/AgentsManifest.md +++ b/Documentation/Proposals/AgentsManifest.md @@ -2,10 +2,12 @@ ## Status -Accepted — partially implemented. Language version 1.0, its document editor and -dump, and the `Agents.swift` state integration are implemented; targeting, -source linking, component deployment, configuration application and lock version 2 -are pending. +The frontend/authoring portions are superseded by the accepted +[YAML manifest decision](../Decisions/YAMLManifest.md) and +[current manifest reference](../Reference/Manifest.md). This proposal retains +historical design context for the broader component-management requirement; +source, targeting, state, security and lifecycle ownership remain with their +current architecture documents. ## Authors / Owners diff --git a/Documentation/Proposals/README.md b/Documentation/Proposals/README.md index 4432c5d..f20bf14 100644 --- a/Documentation/Proposals/README.md +++ b/Documentation/Proposals/README.md @@ -4,10 +4,9 @@ This directory holds design-in-progress documents and unresolved alternatives. ## Active Proposals -- [Agents Manifest Contract](AgentsManifest.md) — owner: showxu; review status: - Accepted — partially implemented. Pending targeting, group and source linking, - component deployment, configuration application and lock version 2; the - implemented language is in [the manifest reference](../Reference/Manifest.md). +- [Agents Manifest Contract](AgentsManifest.md) — owner: showxu; historical + frontend design superseded by [YAML Manifest](../Decisions/YAMLManifest.md). + Remaining component-management work follows its current architecture owners. - `AgentInstructions.md`: skills and instructions as two kinds of one model, the declaration and lock formats, the command tree, the rules for writing diff --git a/Documentation/Reference/Manifest.md b/Documentation/Reference/Manifest.md index 7fd4a85..3dea96f 100644 --- a/Documentation/Reference/Manifest.md +++ b/Documentation/Reference/Manifest.md @@ -1,1214 +1,92 @@ -# Agents Manifest Language - -`Agents.swift` declares a scope's agent configuration in a statically evaluated -subset of Swift. This reference specifies language version 1.0: the construction -vocabulary, source files and the version directive, the admission grammar and -typing, resource limits, document editing, the evaluated JSON dump, diagnostics -and conformance requirements. `AgentsDescription` supplies the vocabulary and -`AgentsManifest` implements the front end, editor and dump. - -[State](../Architecture/State.md#declaration) specifies the complete typed -declaration, the current deployment boundary and how declaration writes are published. The -[manifest proposal](../Proposals/AgentsManifest.md) holds the pending targeting, -source linking, component deployment, configuration application and lock design. - -The core repository declares: - -```swift -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - sources: [ - .source( - name: "agents-tools", - url: "https://github.com/agents-tools/.github", - branch: "master", - subpath: ".agent" - ), - ], - components: [ - .instructions( - sections: [ - "guide", - .section(name: "shared/swift-package-route", source: "agents-tools"), - .section(name: "shared/swift-package-tests", source: "agents-tools"), - ], - agents: [.claudeCode, .codex] - ), - ] -) -``` - -## Construction Vocabulary - -`AgentsDescription` is a compilable, types-only Swift module. Every manifest -accepted by the static evaluator must type-check against the matching module -with the real Swift compiler, including contextual factories, dictionaries and -literal conversions. Compiler type-checkability is a language 1.0 requirement; -editor integration, including making the module available to SourceKit-LSP, is -outside this specification. - -The interface below lists the entire public construction surface. Types conform -to `Sendable` and `Equatable`; factory results are immutable data. Opaque structs -have no public memberwise initializer. Literal-protocol initializers are compiler -entry points, invoked through literals in the manifest grammar. The module uses -the standard library and performs no I/O, registration, resolution or evaluation. -Public names are distinct from top-level standard-library, Foundation and SwiftUI -types so front ends can import those modules together. - -Factories and labels follow SwiftPM's authoring shape and the -[Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/). -Each component occupies one construction level. Its family-specific fields end -with the same `agents:`, `condition:`, `native:` tail. Payload storage is private. - -A **watch subscription** observes changes in a named source independently of -installation. **Install mode** chooses a link to verified cached content (`.link`), -a verified installed copy (`.copy`), or a live local skill link (`.edit`). Edit -mode has no immutable pin or content hash and requires a local source without a -requirement. - -### Root, sources and composition - -```swift -public enum Agent: Sendable, Equatable { - case claudeCode, codex, cursor, geminiCLI, openCode -} -public enum Scope: Sendable, Equatable { case project, user } -public enum Platform: Sendable, Equatable { case macOS, linux } -public enum InstallMode: Sendable, Equatable { case link, copy, edit } - -public struct Condition: Sendable, Equatable { - public static func when( - agents: [Agent]? = nil, scopes: [Scope]? = nil, - platforms: [Platform]? = nil - ) -> Condition -} - -public struct Agents: Sendable, Equatable { - public init( - defaultAgents: [Agent]? = nil, exports: [String] = [], sources: [Source] = [], - components: [Component] = [], groups: [ComponentGroup] = [], - uses: [GroupReference] = [], watch: [String] = [] - ) -} - -public struct Version: Sendable, Comparable, ExpressibleByStringLiteral { - public init(stringLiteral value: String) - public static func == (lhs: Version, rhs: Version) -> Bool - public static func < (lhs: Version, rhs: Version) -> Bool -} - -extension Range where Bound == Version { - public static func upToNextMajor(from version: Version) -> Range - public static func upToNextMinor(from version: Version) -> Range -} - -public struct Source: Sendable, Equatable { - public static func source( - name: String, url: String, subpath: String? = nil - ) -> Source - public static func source( - name: String, url: String, from: Version, subpath: String? = nil - ) -> Source - public static func source( - name: String, url: String, exact: Version, subpath: String? = nil - ) -> Source - public static func source( - name: String, url: String, branch: String, subpath: String? = nil - ) -> Source - public static func source( - name: String, url: String, revision: String, subpath: String? = nil - ) -> Source - public static func source( - name: String, url: String, _ range: Range, subpath: String? = nil - ) -> Source - public static func source( - name: String, path: String, subpath: String? = nil - ) -> Source - public static func source( - name: String, path: String, from: Version, subpath: String? = nil - ) -> Source - public static func source( - name: String, path: String, exact: Version, subpath: String? = nil - ) -> Source - public static func source( - name: String, path: String, branch: String, subpath: String? = nil - ) -> Source - public static func source( - name: String, path: String, revision: String, subpath: String? = nil - ) -> Source - public static func source( - name: String, path: String, _ range: Range, subpath: String? = nil - ) -> Source - public static func source(name: String, index: String, subpath: String? = nil) -> Source -} - -public struct ComponentGroup: Sendable, Equatable { - public static func group( - name: String, components: [Component] = [], uses: [GroupReference] = [], - condition: Condition? = nil - ) -> ComponentGroup -} -public struct GroupReference: Sendable, Equatable, ExpressibleByStringLiteral { - public init(stringLiteral value: String) - public static func group(name: String, condition: Condition? = nil) -> GroupReference - public static func group( - name: String, source: String, condition: Condition? = nil - ) -> GroupReference -} -``` - -There is one `let agents = Agents(...)`, optionally annotated `: Agents`. -Other constants contain reusable values. Source names are lexical aliases, not -output paths. A **discovery root** is the source root with its optional safe -`subpath` applied; component and export discovery start there. Core owns source -identity normalization and requirement resolution. - -`Version` uses core's semantic-version validation and precedence. A requirement -is a value: `from: x` and `.upToNextMajor(from: x)` denote -`x ..< (major + 1).0.0`; `.upToNextMinor(from: x)` denotes -`x ..< major.(minor + 1).0`. The upper bounds have no prerelease or build metadata, -even when the lower bound has either. The lower bound retains its prerelease and -metadata. All range forms use the resolver's `isInRange(from:to:)`: build metadata -does not affect precedence, and a prerelease tag additionally needs a bound with -a prerelease and the same major/minor/patch triple. Exact requirements retain -core's full normalized-version matching, including build metadata. - -Lowering canonicalizes the `Range` value. An upper bound equal by SemVer -precedence to `(major + 1).0.0` becomes `SourceRequirement.upToNextMajor`; one -equal to `major.(minor + 1).0` becomes `upToNextMinor`; any other upper bound -becomes `SourceRequirement.range(from:to:)`. The two canonical upper bounds -never coincide. Version strings use core's -normalized description; range equality compares bounds by SemVer precedence, -while exact-version equality includes metadata. Invalid versions, non-increasing -ranges and successor overflow are located `manifest.domain` errors. Candidate -successor bounds are computed with checked arithmetic; a literal range does not -fail merely because a nonmatching candidate successor would overflow. - -The canonical printer uses `from:` for a major range, -`.upToNextMinor(from:)` for a minor range and adjacent `"lower"..<"upper"` for -other half-open ranges. `exact:`, `branch:` and `revision:` retain their meanings. -Default latest-tag/default-branch selection remains core's rule. Requirements -apply to Git URL sources and Git-backed local paths only. `.source(name:index:)` -represents the well-known index kind and has no Git requirement. -`path:` locates a resource inside a named source or supplies a local source -location; `subpath:` narrows the source's own discovery root. - -Source aliases are nonempty, colon-free strings, with `.` reserved for the -declaring package. Escapes preserve otherwise valid string -contents. Two aliases for one normalized source identity in a document are errors. -Group and newly introduced named component identifiers are relative slash-separated -names with no empty, `.` or `..` segment, colon, backslash or control character. -Skill and instruction names retain their domain validators. ChatGPT prompt names -use an arbitrary string-key namespace; they are not filesystem paths. -Names must be unique in their respective namespace. - -Git URLs are complete transport URLs, as in SwiftPM. A hand-written shorthand is -admitted with `SourceDeclaration` normalization and a `manifest.domain` warning -whose fix-it is the complete URL: `intranet/team` means `https://intranet/team`, -preserving the host; it is not the CLI's owner/repository shorthand. The editor -and canonical printer emit complete URLs using `SourceDeclaration.gitURL`: add `https://` -to host/repository shorthand, preserve existing schemes and preserve complete -SCP-style URLs such as `user@host:path`. Preserving SCP transport syntax also -preserves its remote path interpretation. Identity normalization lowercases the -host, retains an explicit port, trims path slashes and removes a terminal `.git`; -printing preserves the repository suffix. - -`exports: ["review"]` exports the group named `review`; export name and group name -are identical. A differently named wrapper group provides a renamed export. -`watch` is a unique array of declared source aliases, with no recipient or condition. Observed -baselines remain in `agents.watch`, not the manifest. Neither exports nor unused -groups cause deployment or subscriptions in a consumer. - -### Literal values and supporting types - -```swift -public struct SkillSelection: Sendable, Equatable, ExpressibleByArrayLiteral { - public static var all: SkillSelection { get } - public init(arrayLiteral elements: String...) -} -public struct SkillOverride: Sendable, Equatable { - public static func skill(name: String, mode: InstallMode? = nil, agents: [Agent]? = nil) -> SkillOverride -} -public struct SectionReference: Sendable, Equatable, ExpressibleByStringLiteral { - public init(stringLiteral value: String) - public static func section( - name: String, source: String? = nil, condition: Condition? = nil - ) -> SectionReference -} -public struct ChatGPTPrompt: Sendable, Equatable { - public static func prompt( - name: String, sections: [SectionReference], append: String? = nil, - condition: Condition? = nil - ) -> ChatGPTPrompt -} -public struct Resource: Sendable, Equatable { - public static func path(_ path: String, source: String? = nil) -> Resource -} -public struct PromptContent: Sendable, Equatable, ExpressibleByStringLiteral { - public init(stringLiteral value: String) - public static func file(_ path: String, source: String? = nil) -> PromptContent -} -public enum RuntimeValue: Sendable, Equatable, ExpressibleByStringLiteral { - case literal(String) - case environment(String) - case secret(String) - public init(stringLiteral value: String) -} -public struct ExecutableInvocation: Sendable, Equatable { - public static func executable( - _ executable: String, arguments: [String] = [], - environment: [String: RuntimeValue] = [:], workingDirectory: Resource? = nil - ) -> ExecutableInvocation -} -public indirect enum ConfigurationValue: Sendable, Equatable, - ExpressibleByStringLiteral, ExpressibleByIntegerLiteral, - ExpressibleByBooleanLiteral, ExpressibleByNilLiteral, - ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral -{ - case string(String) - case integer(Int) - case decimal(String) - case boolean(Bool) - case null - case array([ConfigurationValue]) - case object([String: ConfigurationValue]) - public init(stringLiteral value: String) - public init(integerLiteral value: Int) - public init(booleanLiteral value: Bool) - public init(nilLiteral: ()) - public init(arrayLiteral elements: ConfigurationValue...) - public init(dictionaryLiteral elements: (String, ConfigurationValue)...) -} -public typealias NativeConfiguration = [String: [String: ConfigurationValue]] - -public struct MCPTransport: Sendable, Equatable { - public static func stdio( - _ executable: String, arguments: [String] = [], - environment: [String: RuntimeValue] = [:], workingDirectory: Resource? = nil - ) -> MCPTransport - public static func streamableHTTP( - url: String, headers: [String: RuntimeValue] = [:] - ) -> MCPTransport - public static func sse(url: String, headers: [String: RuntimeValue] = [:]) -> MCPTransport -} -public enum HookEvent: Sendable, Equatable { - case beforeTool, afterTool, sessionStart, sessionEnd - case native(String) -} -public struct PromptParameter: Sendable, Equatable { - public static func parameter(name: String, description: String, defaultValue: String? = nil) -> PromptParameter -} -public enum PermissionOperation: Sendable, Equatable { - case read, write, execute - case tool(String) -} -public struct PermissionRule: Sendable, Equatable { - public static func allow(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule - public static func ask(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule - public static func deny(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule -} -public enum IgnorePurpose: Sendable, Equatable { case context, indexing } -public enum PluginMode: Sendable, Equatable { case native, components } -public enum ComponentKind: Sendable, Equatable { - case skills, instructions, mcpServer, hook, subagent, command - case lspServer, permissions, ignore, plugin -} -public enum ComponentReference: Sendable, Equatable { - case skill(name: String) - case instruction(name: String) - case mcpServer(name: String) - case hook(name: String) - case subagent(name: String) - case command(name: String) - case lspServer(name: String) - case permissions(name: String) - case ignore(name: String) - case plugin(name: String) -} +# YAML Manifest + +A project declares intent in `.agent/agents.yaml`; user intent lives in +`~/.agents/agents.yaml`. Producers publish the same canonical filename under +`.agent/`, or `agents.yaml` when the producer root is itself `.agent`. +`agents.resolved` remains tool-owned JSON. + +```yaml +version: 1 +sources: + team: {url: https://github.com/example/config, requirement: {from: "1.0.0"}} +components: + - {kind: skills, source: team, select: [review], agents: [codex]} + - kind: instructions + sections: [{name: common}] + chatgpt: + review: {sections: [{name: common}], append: prompts/review.md} +groups: + checks: + components: [{kind: ignore, name: private, patterns: [private/**]}] +uses: [{group: checks}] +exports: [checks] ``` -Literal conversions are closed and contextual. `PromptContent`, -`SectionReference`, `GroupReference`, `Version` and `RuntimeValue` accept string literals; `SkillSelection` -accepts string array literals. `ConfigurationValue` accepts strings, signed -64-bit integer literals, booleans, `nil`, arrays and string-keyed dictionaries. -Decimals use `.decimal("1.25")`, with finite JSON-number text; floating-point -literals are outside the grammar. Native configuration is a dictionary keyed -by registry schema ID, with a string-keyed configuration object as each value. -Duplicate decoded keys, compared using Swift String equality including canonical -Unicode equivalence, are domain errors at every dictionary level, even if their -values are equal. There is no user-defined literal conformance or conversion -from an already-typed `String`, `[String]` or dictionary to a wrapper type. - -A bare section string names the declaring package's own instruction section; -`.section(name: "engineering", source: "rules")` names a source section, and -source `"."` names an own section. A root user-scope declaration uses named -instruction sources. Ordered sections, Markdown rendering and **front matter** -(the structured metadata preceding a content file's body) retain their -instruction-domain semantics. ChatGPT is a named prompt rendering destination, -not an `Agent`. Prompt `append` paths are relative to the project root in project -scope and to the runtime home in user scope. - -Omitted mode inherits the selection mode, then `.link`. Link and copy modes -preserve independent item pins. Omitted skill selection means all discovered -members; `[]` selects none. Exclusions win; overrides do not re-add excluded items. -An override outside an explicit selection is a `manifest.domain` error. -An all-member selection can retain overrides for members not yet discovered. - -`path` locates a resource inside the declaring package or a named source -discovery root; `subpath` narrows the source's own root before discovery. Resource -paths are safe relative paths. Project package roots are project directories; a -user package root is its user-state directory. Absolute and home-relative -resource paths, traversal and escaping symlinks are errors. Source locations keep -their absolute and home-relative path support. Executables are fixed program -names or package-relative executable paths, with separate argument arrays. -Environment and secret bindings are symbolic: reading and dumping never resolve -their values. - -### Component factories - -```swift -public struct Component: Sendable, Equatable { - public static func skills( - source: String, select: SkillSelection = .all, exclude: [String] = [], - mode: InstallMode? = nil, overrides: [SkillOverride] = [], - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func instructions( - sections: [SectionReference] = [], chatGPT: [ChatGPTPrompt] = [], - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func mcpServer( - name: String, transport: MCPTransport, - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func hook( - name: String, event: HookEvent, run: ExecutableInvocation, - matcher: String? = nil, timeoutSeconds: Int? = nil, - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func subagent( - name: String, description: String, prompt: PromptContent, - model: String? = nil, tools: [String]? = nil, - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func command( - name: String, description: String, prompt: PromptContent, - parameters: [PromptParameter] = [], - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func lspServer( - name: String, run: ExecutableInvocation, languages: [String: String], - initializationOptions: [String: ConfigurationValue] = [:], - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func permissions( - name: String, rules: [PermissionRule], - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func ignore( - name: String, patterns: [String], purpose: IgnorePurpose = .context, - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component - public static func plugin( - name: String, path: String, source: String, - mode: PluginMode = .components, select: [ComponentKind]? = nil, - exclude: [ComponentReference] = [], - agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component -} -``` - -### Domain rules - -Domain validation runs offline over every evaluated value, including unused -constants, inactive values and unused groups. A failure is a located -`manifest.domain` error unless the table names another code. - -| Value | Checks | -| --- | --- | -| Sources | Aliases are unique, nonempty, colon-free and not `.`. Git URLs and index URLs must yield a transport identity; a local path is nonempty and has no NUL. `branch:` and `revision:` values are nonempty, have no NUL and do not start with `-`. `subpath` is a safe relative path. Two aliases with one normalized identity are an error; a Git shorthand is a warning with the complete-URL fix-it. | -| Root fields | `defaultAgents` and each condition dimension have no duplicate members. Group names, `exports` and `watch` are unique. An export names a local group (`manifest.group.missing`); a watch entry names a declared alias. | -| Names | Group, named-component and typed component-reference names are relative names as defined above. Skill and instruction section names use their domain validators. Prompt names are unique within a component; prompt parameter names are nonempty and contain no `}`, `:` or NUL. | -| Skills | The source is a declared alias or `.`. Explicit selections and exclusions are valid, unique skill names; override names are unique and lie inside an explicit selection. Edit mode, on the selection or an override, requires a local source without a requirement. | -| Resources | Resource, prompt file, `append` and `subpath` paths are safe relative paths. An executable containing `/` or starting with `~` is also a resource path. | -| Transports | Streamable HTTP and SSE URLs are HTTP(S) URLs with a host and no credentials or fragment. | -| Hooks | `timeoutSeconds` is positive. A `.native` event has exactly one explicit recipient. | -| Commands | Every `${input:name}` token in a literal prompt names a declared parameter; `$${input:` escapes a token. | -| LSP servers | Each `languages` key is a dot-prefixed file extension without `/`; each language ID is nonempty. | -| Permissions | Read and write patterns are safe relative paths. | -| Plugins | The source is declared and `path` is a safe relative path. Native mode has exactly one explicit recipient and no selection or exclusions. Selections and exclusions have no duplicates. | -| Configuration values | `.decimal` text is a finite JSON number. Duplicate decoded keys at any dictionary level are `manifest.dictionary.duplicateKey`. | - -Recipient capabilities, native schema registration and adapter rules are -deployment checks; the -[manifest proposal](../Proposals/AgentsManifest.md#component-deployment) specifies -them. - -## Source Files and Versions - -Project source is `.agent/Agents.swift` relative to the explicit project root; -user source is `~/.agents/Agents.swift` relative to core's runtime home. Each -scope's lock is the adjacent `agents.resolved`. There is no ancestor search or -automatic user/project merge. An absent file is an absent declaration; -[State](../Architecture/State.md#absent-declaration) defines how that combines -with existing lock or watch state. - -The first line is exactly `// agents-tools-version: 1.0`, at byte zero after an -optional UTF-8 BOM, terminated by LF, CRLF or EOF. General version syntax is -`// agents-tools-version: MAJOR.MINOR`, with the shown spaces, decimal components -without leading zeroes except `0`, and no patch, suffix or trailing whitespace. -A missing, malformed, duplicate or unsupported directive has its own diagnostic. -Directive recognition is lexical: a directive-shaped line comment outside a -string is a duplicate; text inside a string literal is ordinary content. -A 1.0 reader accepts exactly `1.0`. A future reader explicitly declares its support -set. Newer unsupported versions request an upgrade; older unsupported versions -request a supported converter. Language, package, adapter, lock and dump versions -are independent. Editing preserves the BOM and newline style; the canonical -printer emits UTF-8 without a BOM. - -## Static Grammar - -Exactly one unqualified `import AgentsDescription` precedes top-level initialized, -single-binding `let` declarations. Names use the identifier grammar below, are -unique and cannot shadow vocabulary types. Constants bind in textual order; references to later constants -or themselves fail. There are no modifiers, attributes, wrappers or semicolons. -Every declaration, including unused constants and inactive branches, is checked. -Group-name references are resolved separately and may refer forward. - -| Accepted syntax | Rule | -| --- | --- | -| `SourceFileSyntax`, `ImportDeclSyntax`, `VariableDeclSyntax` | The file structure above, with one identifier-pattern binding and initializer per declaration. | -| `StringLiteralExprSyntax` | Single-line and multiline literals from the closed lexical grammar below, with Swift decoding and no interpolation. Contextual `GroupReference` literals denote local groups; this is a type conversion, not an extra grammar production. | -| Integer, Boolean and nil literals | Decimal signed-64 integers with underscore separators, Bool and contextual nil. One unary minus is accepted only immediately adjacent to a decimal integer literal, with no intervening trivia. Other bases, floating literals and other numeric operators fail admission. | -| `ArrayExprSyntax` | Homogeneous arrays or a contextual, whitelisted array-literal conversion. Trailing commas are allowed. Empty literals require contextual type. | -| `DictionaryExprSyntax` | String-literal keys, homogeneous contextual values, or a contextual configuration object. `[:]` is an empty dictionary. Keys are decoded before duplicate detection; key references/interpolation are rejected. | -| `DeclReferenceExprSyntax` | A preceding constant, a vocabulary type as a member/call base, or the permitted operator. | -| Sequence/folded infix expressions | Only left-associative array `+` with exact `[T]` operands, at most 32 terms per additive chain. No concatenation of selections or configuration values, dictionary merging or string concatenation. A single half-open version range is admitted only in the source requirement position defined below; other operators are rejected. | -| `TupleExprSyntax` | One unlabeled expression in parentheses, not tuple values. | -| `MemberAccessExprSyntax` | Listed static factories, static `.all`, and enum cases, qualified or contextual. No instance-property access, subscripts or optional chaining. | -| `FunctionCallExprSyntax` | `Agents(...)`, listed static factories and associated cases, with exact labels and order. Literal-protocol entry points are reached only through literals. No arbitrary functions or trailing closures. | -| Type annotations | `String`, `Int`, `Bool`, named vocabulary types/aliases, `[T]` and `[String: T]`. No explicit Optional annotations, user aliases, qualified/generic/existential/function/metatype syntax. | - -Grammar admission precedes SwiftParser and the iterative tree check precedes all -recursive SwiftSyntax processing. The normative productions below and the syntax -node table describe the same constructs, subject to the byte, token, chain and -depth limits below. These limits apply even to unused or inactive -expressions. Parser recovery, missing tokens and unexpected syntax are errors. -Tokens inside accepted nodes are admitted only in the roles above. Constructors create data; -they never invoke Swift compiler code while evaluating a manifest. - -### Type inference and literal conversions - -An annotation or parameter type supplies context inward. Otherwise literals, -qualified calls and references synthesize types outward. Without context, a -string is `String`, an integer is `Int`, and a boolean is `Bool`. Arrays infer -from the first element; dictionaries infer from the first value and require all -other values to agree. Empty collections, nil and a leading shorthand member -cannot infer a type alone. Dictionary keys are always strings. - -Optional parameter types remain part of the construction API: their context -admits `nil` or injection of a value of the wrapped type. Source annotations use -the non-Optional forms in the grammar; `T?` and `Optional` fail grammar admission. -This does not change the module's public Optional signatures or compiler typing. - -In contextual vocabulary types, only the literal conformances declared above -apply. Nested configuration literals propagate `ConfigurationValue` context to -every child. For an Optional parameter with wrapped type `T`, nil means absence; -non-nil values may receive `T` context and Optional injection. For non-Optional `ConfigurationValue`, nil means -configuration null. Signed integer literal conversion follows Swift's literal -semantics and must fit the declared literal type. `.decimal(...)` remains explicit. -No arbitrary user protocol dispatch or conversion of pre-existing typed values -is allowed. In particular, a `String` constant is not implicitly a `PromptContent` -or a `SectionReference`, `GroupReference` or `Version`, and a `[String]` constant is not a `SkillSelection`. - -For array `+`, context propagates to both operands when present; otherwise infer -the left array and use its element type for the right array. An expression of -`SkillSelection` or `ConfigurationValue` type is not a Swift array. Constants -must be typed where declared, not inferred backward from later uses. A standalone -component is `let reviewer: Component = .subagent(...)` or a fully qualified -factory call. The evaluator's accepted language is a subset of real Swift typing, -not an alternative type system. - -### Normative admission grammar - -`AgentsManifest` owns a strict lexer and a deterministic recognizer for these -productions. No byte reaches SwiftParser until the complete input snapshot passes -recognition. SwiftParser supplies the lossless tree for editing and diagnostics; -it does not decide which source grammar is admitted. The recognizer does not -resolve constants or evaluate constructors. The subsequent type/domain checks -restrict identifiers and calls to the vocabulary and rules above. - -The grammar uses `?` for optional, `*` for repetition and `|` for alternatives; -quoted punctuation denotes source tokens. Trivia may separate tokens except at -explicitly contiguous spellings. `newline` means at least one LF, CRLF or CR in -the separating trivia. The version directive is checked as specified above using -the same lexer's comment/string boundaries, before syntax is handed to SwiftParser. - -```ebnf -document = "import" "AgentsDescription" newline declaration - (newline declaration)* EOF ; -declaration = "let" bareName (":" type)? "=" expression ; -type = typeName | "[" type "]" | "[" "String" ":" type "]" ; -expression = primary ("+" primary)* ; -primary = string | integer | "-" integer | "true" | "false" | "nil" - | namedValue | array | dictionary | "(" expression ")" ; -namedValue = sourceCall | callee ("(" arguments? ")")? ; -callee = bareName | bareName "." name | "." name ; -arguments = argument ("," argument)* ; -argument = (name ":")? expression ; -sourceCall = (".source" | "Source.source") "(" "name" ":" expression "," - (("url" | "path") ":" expression - ("," requirement)? | "index" ":" expression) - ("," "subpath" ":" expression)? ")" ; -requirement = ("from" | "exact" | "branch" | "revision") ":" expression - | versionRange | rangeFactory ; -versionRange = string "..<" string ; -rangeFactory = (".upToNextMajor" | ".upToNextMinor") - "(" "from" ":" expression ")" ; -array = "[" (expression ("," expression)* ","?)? "]" ; -dictionary = "[" ":" "]" - | "[" string ":" expression - ("," string ":" expression)* ","? "]" ; -``` - -`typeName` is exactly `String`, `Int`, `Bool`, or a public vocabulary type/alias -listed under Construction vocabulary. Type existence is checked during recognition. `sourceCall` takes -precedence over the general call production for `.source` and `Source.source`; those spellings cannot bypass it through `callee`. The -`.upToNextMajor` and `.upToNextMinor` callees are reserved to `rangeFactory`, -including its required argument list; other positions fail recognition. -`versionRange` is not a general expression: no grouping, constants, chaining or -other operands are admitted at its position. A range factory is contextual to -this same unlabeled requirement slot. Its argument receives `Version` context; -`from:` and `exact:` on the source also receive `Version` context. The subsequent -checker enforces version typing and domain validation. `callee` is a -syntactic spelling; subsequent vocabulary checking rejects unlisted functions, -instance members, literal-protocol entry points and invalid factory labels. -There is no postfix loop: a callee has at most one member operation and one call, -for a maximum grammatical chain of **2**. The independent postfix-operation -counter has a ceiling of **4** per primary; budget headroom admits no additional -production. No operation attaches to a call result, grouped -expression or subscript. The leading shorthand dot counts as one operation. -These are exactly the construction forms needed by the vocabulary. Parentheses -contain one expression; calls have no trailing comma; collections may have one. -The additive production has at most **32 terms**, with later type checking -requiring array operands. A version range has exactly two literal operands. -No assignment expression or prefix-keyword production exists. An identifier after a completed expression is a syntax error, not an -implicit prefix, argument or declaration. - -The lexical grammar is closed: - -- An identifier has ASCII head `[A-Za-z_]` and continuation `[A-Za-z_0-9]*`. - Backticks, `$` names and non-ASCII identifiers are excluded; Unicode remains - available in string values, including all domain names and paths. `name` excludes - the reserved spellings listed below. `bareName` additionally excludes `await`, - `copy`, `consume`, `each` and `unsafe`; those contextual spellings may occur as - argument labels or member names, including `.copy`. They cannot introduce a - prefix production or a bare binding/reference/callee in language 1.0. -- `integer` is `[0-9][0-9_]*`. The optional minus is a separate token immediately - adjacent to its digits and only in the shown primary production. Its preceding - source character must be ASCII whitespace (space, tab, CR or LF), `(`, `[`, `,` - or `:`; an adjacent operator or comment terminator cannot precede the sign. - Range checking follows during typing. There are no floating-point, exponent or - radix literals; - decimal configuration values use `.decimal("1.25")`. -- `string` is an ordinary double-quoted single-line literal or a triple-quoted - multiline literal. Both allow exactly `\0`, `\\`, `\t`, `\n`, `\r`, `\"`, `\'` - and `\u{H}` escapes, where `H` is one to eight ASCII hex digits naming a Unicode - scalar (not a surrogate and at most `10FFFF`). Interpolation and escaped newline - continuation are excluded. A single-line literal contains no unescaped CR/LF. - A multiline opener is followed immediately by LF, CRLF or CR; its closing - delimiter is preceded on its line only by spaces. A content line is either - empty (zero characters before its newline) or starts with the closing delimiter's - exact space indentation prefix, which Swift decoding removes. Additional leading - spaces remain content. Whitespace-only lines are nonempty and must carry the - full prefix. A tab anywhere in a content line's leading whitespace or in the - closing delimiter's indentation is a syntax error; tabs after the first - non-whitespace content character remain literal content. These rules apply - identically to LF, CRLF and CR lines. Unescaped single/double quote runs are - multiline content; the first - unescaped triple quote closes it. Unescaped control scalars below U+0020 other - than tab and multiline CR/LF are rejected. Raw strings do not exist: `#` outside - string/comment content always fails recognition. -- Trivia is ASCII space, tab, LF, CRLF or CR, an optional BOM at byte zero, `//` - comments through the next CR/LF or EOF, and `/* ... */` comments with at most - **20** nested levels. The lexer validates UTF-8 throughout the snapshot. Strings - and comments are opaque to expression counters. No other whitespace or comment - form is admitted. -- Source punctuation is `( ) [ ] , : . = + ..<` and the adjacent numeric sign `-`, - only in the roles in the productions. Callee member spellings contain no trivia - around their dot; the call opener immediately follows its callee. Both `=` and - binary `+` require at least one ASCII whitespace character (space, tab, CR or LF) - immediately on each side. Comments do not substitute for whitespace: every - comment in an operator-to-operand gap must itself have whitespace immediately - before and after it. Thus `value /* note */ = -1` is admitted, but `value=0`, - `value= 0`, `value=-1`, `a+b` and `a/* note */ + b` fail recognition. A located - `manifest.syntax` diagnostic names the canonical spelling, such as - `let value = -1` or `left + right`. These adjacency rules make - Swift operator/member tokenization unambiguous. The single `..<` token is - admitted only by `versionRange`, with either no whitespace on both sides or - at least one ASCII whitespace character immediately on both sides. Comments - in either operand gap must themselves be surrounded by whitespace, as for `+`. - The canonical operator spelling is `"1.2.0"..<"1.8.0"`; an asymmetric boundary - reports that spelling in a located `manifest.syntax` diagnostic. A lone `<` - or `>` is never admitted. Other operators, generic angle - brackets, braces, attributes, directives, macros and regex literals fail at - recognition. There is no fallback to SwiftParser recovery. - -The exact reserved identifier spellings are: - -```text -_ Any Self as associatedtype break case catch class continue default defer deinit -do else enum extension fallthrough false fileprivate for func guard if import in -init inout internal is let nil open operator precedencegroup private protocol public -repeat rethrows return self static struct subscript super switch throw throws true -try typealias var where while -``` - -The lexer consumes each byte a bounded number of times, without backtracking or -unbounded lookahead. The parser uses at most two tokens of lookahead to distinguish -argument labels and dictionary entries, bounded delimiter frames for nested -productions, and loops for siblings and additive terms. It never speculatively -parses a whole expression and rewinds. Its work, storage, literal validation and -located-diagnostic construction are linear in bounded input size. A failure ends -recognition with a located `manifest.syntax` or `manifest.limit`; SwiftParser is -not called. Accepted grammar structure and spans are retained for differential -validation, independently of the later semantic IR. - -## Resource Limits - -Admission reads at most 2,097,153 bytes, rejecting the extra byte before decoding, -lexing or parsing; it never allocates an unbounded file buffer. The exact admitted -snapshot is subsequently parsed. The recognizer permits at most 100,000 non-trivia -tokens; the minus and integer count separately, and `..<` counts as one token -plus its two string-literal operands. Range factories count as ordinary calls. -Version values charge their decoded bytes and nodes; range costs include both -endpoints before canonical lowering or serialization. It additionally reserves syntax -storage conservatively as **16 + 4 × (tokens + literal breaks + literal escapes)**, -capped at 100,000 nodes before SwiftParser is invoked. A literal break is each -CR or LF byte inside a string (CRLF counts twice); a literal escape is each -backslash byte inside a string, including escaped backslashes. These extra units -cover the parser's segmentation of multiline/escaped literals. The grammar-derived -reservation covers file and wrapper nodes as well as tokens; the independent -post-parse guard verifies actual counts. -A parser dependency change must revalidate the reservation against every grammar -production. The reservation is a language budget even when an individual input's -actual tree would be smaller; generated source passes the same admission. - -Every open `[` or `(` increments a grammar counter before entering the enclosed -production, including type annotations. Square depth above **8** or combined -depth above **20** is `manifest.limit` at the first excess opener. Block-comment -depth above 20, a thirty-third additive term or an excess token/storage reservation -likewise fails before parsing. All other missing, misplaced or unsupported tokens -are `manifest.syntax` at the expected production's location (EOF for missing -input). Unbalanced openers remain counted until rejection; neither trivia nor -parenthesized subexpressions can bypass the counters. No production permits more -than two postfix operations or more than one numeric sign. These grammar bounds -apply equally to unused constants and inactive components. - -Immediately after parsing, an **iterative, non-recursive** walk checks all syntax -nodes, including collections, tokens, missing nodes and unexpected nodes, in the -all-nodes view. The root has depth 1; depth above **128** or more than **100,000** -nodes is `manifest.limit`. Reserve stack/node budget before enqueueing children; -compute failure offsets from cached byte lengths during the walk. Do not call -recursive visitors, `hasError`, diagnostic generation, tree descriptions, source -mapping, equality or evaluation before this guard succeeds. The same rule applies -to transformed/folded trees: build/check them iteratively before recursive use. -The tree ceiling is independent of source delimiter depth and leaves room for -SwiftSyntax's wrapper nodes. Evaluation retains its separate frame/work limits. - -No manifest input within the byte limit may crash or hang the hosting process, -including the GUI. Invalid and over-budget input must end in a bounded diagnostic -without writes or partial IR publication. This is a required implementation and -release invariant, not a conclusion inferred from `maximumNestingLevel` or a -finite set of passing examples. Parser construction, error inspection, tree -lifetime/teardown and every consumer of syntax are included in the invariant. - -The square-bracket ceiling is **8**, independently of the general delimiter -ceiling of **20**. The complete manifest examples in this reference and in the -manifest proposal reach depth 3. Fixed family fields, excluding recursive -configuration values and arbitrary nested array constants, reach depth 5: root -groups, components, ChatGPT prompts, sections, then a section condition's -recipient array. -Eight leaves three levels of syntax-depth margin over that fixed structure. -`ConfigurationValue` is recursive, so its vocabulary has no intrinsic finite -nesting maximum; its expanded values remain limited to depth 64. Named constants -allow deeper configuration values to be assembled without deep source nesting, -subject to all expansion budgets. This separates authoring depth from value depth -and caps square-bracket ambiguity before parser recovery. The parser's own -nesting option remains defense in depth, not a parse-time bound. - -The evaluator may store immutable values as a DAG, but all limits are measured -as if each reference were expanded by value. Each value carries a checked cost -summary: expanded node count, decoded string/key bytes, canonical encoded byte -count, maximum depth and source-origin count. For a container, costs are its own -cost plus the sum of each child's costs **for every occurrence**. Reusing a -constant twice adds its full cost twice, including all descendants. An alias -inherits the referenced cost; memoization does not discount expansion. - -Compute costs bottom-up with checked, saturating arithmetic capped at the limit -plus one. Before concatenation, reference insertion, group expansion or any output -allocation, combine the summaries and reject an oversized result. No descendant -walk, copying, formatting, map expansion or equality comparison occurs first. -This rejects exponential reuse such as repeated `array([previous, previous])` -while that value is constructed, even when its underlying storage is small. -Every constant must fit individually; totals count every top-level definition -and every root occurrence, including inactive and unused values. - -Encoded-size summaries include repeated dictionary keys, string escaping, -punctuation, indentation and trailing newline. Before writing a dump or generated -source, reserve its complete bounded size from those summaries. When formatting -context changes indentation, use a checked worst-case bound or recompute the -summary over the bounded structure before emitting bytes. Locations and provenance -are separately budgeted and included in the final dump's size reservation. - -| Resource | Language 1.0 bound | -| --- | --- | -| Input | 2,097,152 UTF-8 bytes per manifest, enforced by bounded reading before grammar admission, decoding or parsing; invalid UTF-8 fails. | -| Admission | Linear lexer and grammar recognizer; 100,000 tokens; syntax reservation `16 + 4 × (tokens + literal breaks + literal escapes) ≤ 100,000`; square depth 8; combined square/parenthesis depth 20; comment depth 20; postfix-operation budget 4 (the grammar uses at most 2); one adjacent numeric sign; additive chain 32 terms. Failures reject before SwiftParser. | -| Parser/tree | `maximumNestingLevel: 20` in every build configuration. Iterative guard: depth 128 (root 1), 100,000 syntax nodes including tokens and excluding trivia, before any recursive processing. | -| Evaluator | 64 active expression/reference frames; 100,000 work steps per document. Every visited expression, lookup, produced node and concatenation element costs a step. | -| Expanded values | 100,000 nodes and 16,777,216 decoded string/key bytes across the document's values, charged by occurrence, with 10,000 entries per array/dictionary and maximum expanded value depth 64, including referenced descendants. | -| Domain validation | 100,000 traversal steps per document. | -| Local groups | 64 active local group references while checking for reference cycles. | -| Source maps | 100,000 location records, 1,000,000 total origin spans and 16,777,216 encoded bytes; repeated origins count repeatedly. Reserve before expanding a reference's map. | -| Output | 33,554,432 bytes for the entire dump including locations/diagnostics; generated manifest source still obeys the 2,097,152-byte input limit. | -| Comparison/edit batch | 200,000 expanded node-pair visits per full comparison; 1,000,000 aggregate steps and 100 requests per edit batch. Operand cost summaries are checked before comparison starts. | - -A work budget is charged before executing a step; exhaustion is a diagnostic, -not an invitation to return a truncated model. Comparisons can use identity or -memoization only after verifying expanded operand bounds. Diagnostics and JSON -escaping are bounded operations. Source download and extraction limits belong to -core's loader. Cancellation is separate from language semantics. Fuzzing and adversarial reuse tests cover every bounded -consumer of values, not just the parser. - -## Group References - -Group references are symbolic in the front end: no group is expanded and no -source manifest is read. The front end checks the local graph only: - -- group names are unique, including unused groups; -- every export and every unqualified `GroupReference` names a local group, or - fails with `manifest.group.missing`; -- following unqualified references from every group, a reference back into the - active chain fails with `manifest.group.cycle`, whose related spans list the - chain; a diamond is not a cycle; -- an active chain longer than the local group budget is `manifest.limit`. - -A qualified `.group(name:source:)` reference names a declared source alias; its -group is resolved only by source linking. Group references may refer forward to -groups declared later in the same document. - -## Document Editing - -`AgentsManifest.DeclarationDocument` owns the original bytes, syntax, declaration -IR, source map, diagnostics, editability and the original byte digest. Domain -edits use the same vocabulary names as authored values; lowering converts them to -core IR. Snapshot node handles are separate from persistent component identities. - -```swift -public struct DeclarationDocument: Sendable { - public init(bytes: [UInt8], identity: DocumentIdentity) throws - public let declaration: DeclarationIR - public let diagnostics: [ManifestDiagnostic] - public let sourceMap: DeclarationSourceMap - public let digest: String - public var bytes: [UInt8] { get } - public func node(at pointer: String) -> NodeID? - public func constant(named name: String) -> NodeID? - public func uses(ofConstant name: String) -> [NodeID] - public func editability(of node: NodeID) -> Editability - public func preparing(_ edits: [ManifestEdit]) throws -> DocumentChange -} -public enum Editability: Sendable, Equatable { - case direct - case sharedConstant(uses: [NodeID]) - case readOnly(reason: String) -} -public enum ManifestEdit: Sendable { - case setDefaultAgents([Agent]?) - case upsertSource(Source) - case removeSource(alias: String) - case insertComponent(Component, into: ContainerID, at: InsertionPosition) - case replaceComponent(NodeID, with: Component) - case removeComponent(NodeID) - case moveComponent(NodeID, into: ContainerID, at: InsertionPosition) - case setSkillSelection(NodeID, SkillSelection) - case upsertSkillOverride(NodeID, SkillOverride) - case removeSkillOverride(NodeID, name: String) - case insertSection(SectionReference, into: NodeID, at: InsertionPosition) - case removeSection(NodeID) - case moveSection(NodeID, at: InsertionPosition) - case upsertPrompt(NodeID, ChatGPTPrompt) - case removePrompt(NodeID, name: String) - case upsertGroup(ComponentGroup) - case removeGroup(name: String) - case insertGroupReference(GroupReference, into: ContainerID, at: InsertionPosition) - case removeGroupReference(NodeID) - case setExports([String]) - case setWatch([String]) - case setDictionaryEntry(NodeID, key: String, value: StaticValue) - case removeDictionaryEntry(NodeID, key: String) - case replaceConstant(NodeID, with: StaticValue, acceptingUses: [NodeID]) -} -``` - -`NodeID` is an opaque handle bound to the document digest; `node(at:)` takes a -JSON Pointer into the lowered declaration, and `constant(named:)` and -`uses(ofConstant:)` take Swift identifiers. `ContainerID` addresses the root or a -group. `InsertionPosition` is `.first`, `.last`, `.before(NodeID)` or -`.after(NodeID)`. `StaticValue` is the bounded checked algebra of literals, -collections and vocabulary values, not raw Swift text. Dictionary value edits -must match the target's inferred value type. Whole-component replacement covers -recipients, conditions and all family-specific fields. - -The document applies requests in order to construct the expected complete IR, -checks their complete impact and budgets, and produces disjoint byte patches. -`DocumentChange` contains the original digest, patches, resulting bytes and -digest, expected declaration, impacted references, diagnostics and semantic -delta. Only the document layer constructs it, and it publishes nothing. Scope -declarations are written only through the state layer's -[declaration writes](../Architecture/State.md#declaration-writes); front ends -never save source independently. - -### Editability - -`editability(of:)` reports exactly what the editor accepts: - -| Construct | Editability | -| --- | --- | -| Element of a direct array literal | `direct`. Insert, remove and move identifiable elements, preserving order. Removing an element of a single-line array also removes its separating space. | -| Entry of a direct dictionary literal, including a literal configuration value | `direct`. Set or remove a decoded key's value or entry; unrelated entries keep their order and comments. | -| Signature argument of a direct root, group or component construction, present or omitted | `direct`. Replace the exact value range and retain outer trivia, insert a missing argument in signature order, or remove an unambiguous argument. | -| Member value, such as `.copy` or `.codex` | `direct`. Replaced in place. | -| Constant definition | `sharedConstant`, listing every direct and transitive use. Only `replaceConstant` changes it, accepting the complete impacted reference set. | -| Constant reference or assembled value | `readOnly`; replace the definition explicitly. | -| Concatenation | `readOnly`; it has no independent source range. | -| Normalized field, such as a source requirement or a component kind | `readOnly`; replace the containing construction. | -| Any value inside a read-only value | `readOnly`. | -| Stale handle | `readOnly`; preparing an edit with it fails with `manifest.edit.stale`. | - -Ambiguous trivia or separators make an edit fail with `manifest.edit.readOnly`, -with a span and reason; there is no regeneration fallback. Removing referenced -sources or groups requires a complete batch that repairs the references. Stale -handles, overlaps, incomplete impact and mismatched results have separate -`manifest.edit.stale`, `.overlap`, `.impact` and `.mismatch` diagnostics. - -### Comment ownership - -Comments follow SwiftSyntax trivia ownership: - -1. Standalone comments immediately above a node with no separating blank line - belong to that node; a dictionary key and value form one entry node. -2. Comments beginning on a node's or its comma's line belong to that preceding - node, including multiline block comments. -3. Comments inside an expression or between it and its comma belong to it. -4. Comments separated from the next node by a blank line belong to the container. - The preamble and version directive belong to the file. -5. Delete/move operations carry owned comments. Value replacement preserves outer - comments; whole-node replacement refuses if internal comments cannot be mapped - to retained fields. Unowned comments remain in place. -6. Empty containers become `[]` or `[:]` only when their interiors are whitespace. - Container comments survive; ambiguous mixed layouts or comment-only insertion - sites are read-only. An argument list holding only comments is read-only. - -### New text - -New nodes use the shortest canonical type-correct spelling. `Agents(...)` is the -only ordinary initializer in manifest expressions; nested values use leading-dot -factories. Sources use `.source(name:url:)`, `.source(name:path:)` or -`.source(name:index:)`, and references use `source:`. Requirement values use the -canonical requirement spelling defined under Construction vocabulary. Literal -conformances provide strings for prompts, own sections, local group references -and versions, array literals for explicit skill selections, and JSON-style -configuration literals. Dictionary literals and direct factories construct the -remaining values. Existing unmodified expressions keep their spelling. - -New text uses the container's consistent indentation, newline and comma style; -absent evidence, it uses two spaces, LF and trailing commas in multiline -collections. Argument order follows signatures; root insertion order is -`defaultAgents`, `exports`, `sources`, `components`, `groups`, `uses`, `watch`. -`upsertSource(Source)` preserves the complete requirement value. Fresh node -layout follows the canonical printer; existing surrounding style takes -precedence. Inserting the first argument into an empty argument list, such as -`Agents()`, uses the canonical call layout, so a collection or nested call -argument starts a multiline list. Conflicting local style is an editability -diagnostic, not permission to reformat the file. - -Inserting a multiline argument into a nonempty single-line call expands that -call's argument boundaries using the document's indentation and newline style. -Existing argument expressions, order and owned comments keep their spelling; -bytes outside the call remain unchanged. Scalar additions keep the existing -single-line layout. - -The editor and canonical printer emit one ASCII space on each side of `=` and -`+`, with adjacent sign/digits for negative integers: `let value = -1`. A value -replacement re-checks both joins with the unchanged source, including neighboring -comments, against the lexical rules before it becomes a patch. For example, -replacing `0` in `[/* note */0]` emits ` -1` inside that value's replacement range, -producing `[/* note */ -1]` while preserving all bytes outside the range. The -editor never joins a sign to `=` or to a comment terminator. A source that already -fails recognition, such as `let value=0`, cannot receive a domain edit. If a safe -boundary cannot be represented in the authorized patch range, preparation fails -with an editability diagnostic. The complete candidate passes recognition again -before SwiftParser is invoked; a failed check publishes no patch or source bytes. - -Range replacement re-checks both operator/operand boundaries and the containing -source requirement slot. A complete replacement uses the canonical requirement -spelling, including changing the argument label when its range category changes. -A leaf endpoint edit preserves surrounding trivia only if the result still meets -balanced spacing and comment rules; otherwise the necessary whitespace is part of -the explicit patch, or the edit fails with `manifest.edit.readOnly` when comment -ownership is ambiguous. - -### Edit invariants - -The invariants are byte-exact no-op return, byte preservation outside disjoint -patch ranges, and full reparse, type check, evaluation and domain validation of -the complete candidate before it is returned. The resulting complete IR must equal -the expected IR, including inactive groups and exports; only source positions and -trivia are excluded. All stages use the expanded-size budgets. BOM, final-newline -presence and unrelated bytes survive. - -### Canonical printing - -The canonical printer lays out new nodes and prints a complete document for a -new declaration file. Equal values print identical bytes. A document is the -version line, `import AgentsDescription`, one blank line, then -`let agents = Agents(...)`, with two-space indentation, LF, no BOM and one final -newline. Assignment and array concatenation use one ASCII space on each side of -`=` and `+`; negative literals use an adjacent sign and digits. Strings use -ordinary quotes; quotes, backslashes, LF, CR and tab are escaped, other control -scalars are lowercase Swift `\u{...}` escapes, and other Unicode scalars are -preserved without normalization. - -Values use literal prompts, sections, selections and dictionaries and direct -factories. Default-valued arguments are omitted; explicit Optional values that -distinguish inheritance are retained. Signature order determines labels. -Dictionary keys sort by UTF-8 bytes; arrays keep their order. A collection of -scalar literals or payload-free enum members fits inline when the complete line, -including indentation and comma, is at most 80 UTF-8 bytes; otherwise it expands. -Collections containing collections or factory/initializer calls are multiline. -A call with only scalar arguments fits inline under the same limit; calls with -collections, ranges or nested calls are multiline. Multiline collections have -trailing commas; call arguments have none after the last argument. Empty -collections are `[]` or `[:]`. Printing never reformats an existing document. - -## Evaluated JSON Dump - -`ManifestDump(bytes:)` and `ManifestDump(document:)` evaluate only one local -declaration. The dump does not resolve external groups, fetch sources or -secrets, inspect native files or compile or run the manifest. Conditional -branches and group references remain symbolic. `encodedJSON()` returns one UTF-8 -JSON object with sorted keys, two-space indentation and a trailing LF. Invalid -input throws `ManifestFailure` with its diagnostics, and no partial object -exists. `agents manifest dump --json` prints these bytes; its exit status and -diagnostic presentation belong to the CLI. - -The root has `schemaVersion: 1`, `kind: "manifest"`, `languageVersion: "1.0"`, -`sourceDigest`, `declaration`, `locations` and `diagnostics`. The digest is -`sha256:` plus 64 lowercase hexadecimal digits over the original bytes. -`declaration` has `defaultAgents`, `exports`, `sources`, `components`, `groups`, -`uses` and `watch`. Default arrays are empty, Optional absence is null, and -explicit empty recipients remain distinct from inheritance. - -A component encodes directly as `{ "kind": "mcpServer", "name": "workspace", -"transport": { ... }, "agents": ["claude-code"], "condition": null, -"native": {} }`. There is no payload wrapper. The remaining schema is determined -by the vocabulary as follows: - -- Tagged families encode `{kind, ...fields}`. Component/transport kinds are - their factory names. `ExecutableInvocation` is `kind: "executable"` with executable, - arguments, environment and workingDirectory. `.group(name:)` references encode - kind `local`; `.group(name:source:)` references encode kind `exported`, with - name and condition. An exported reference always has a non-null source; a local - reference has none (encoded as null). Conditions encode their - three dimensions without a kind. Permission rules encode - `{kind: "allow" | "ask" | "deny", operation, pattern}`; their two unlabeled - factory arguments use the keys `operation` and `pattern`. LSP `languages` - encodes an object mapping extension keys to language-ID strings. -- A source has `kind: "git" | "local" | "index"`, name, location (`url`, `path` or - `index`, matching its factory field), subpath and requirement. A `path:` source - with a requirement remains kind `local`. Requirement is null or an - object with exactly one of `branch`, `revision`, `exact`, `from`, `upToNextMinor`, - or `from` plus `to`, matching core's `SourceRequirement` encoding. Version values encode - as normalized version strings. Every range value encodes its canonical - requirement kind: `from`, - `upToNextMinor`, or `from`/`to`, regardless of its construction spelling. -- Groups, skill overrides, ChatGPT prompts, prompt parameters and resources encode - their factory fields without a factory-name tag; the resource's unlabeled - subject uses key `path`. Arrays/dictionaries encode as JSON collections, - with defaults supplied. - Exports and watch are string arrays. An instruction section is always an object - with name, source and condition, even when authored as a string. -- Skill selection encodes `"all"` or an array of names. Prompt content is - `{kind: "literal", value: }` or `{kind: "file", path, source}`. - Runtime values similarly use literal/environment/secret and value. Literal - spelling and explicit equivalent cases have identical evaluated output. -- Payload-free enum cases are strings, except mixed enums always use tagged - objects. Associated values retain labels; a single unlabeled payload uses - `value`. Typed component references use kind and name. Configuration values - retain kind and value tags, including nested arrays/objects; null has only kind, - and decimal values remain strings to prevent numeric rounding. -- Agent IDs are `claude-code`, `codex`, `cursor`, `gemini-cli`, `opencode`; - platforms are `macos`, `linux`; other enum spellings are unchanged. - -Components, group references, sections, hooks, permission rules, ignore patterns, -arguments and prompt parameters preserve order. Definitions of sources/groups, -exports, watch, named prompts and overrides sort by name; recipients, exclusions -and explicit skill selections sort by canonical identity. Dictionary keys sort -by decoded UTF-8 bytes. Typed plugin exclusions sort by kind then name. -Constants are substituted by value within the checked expansion budget. - -A location has `pointer` (JSON Pointer into the normalized declaration), `span`, -`origins`, `defaulted` and `editability`. Spans have document `"manifest"`, start/end -byte offsets and starting line/column. A use's span identifies the use site; -origins include definitions. Missing fields anchor to their containing construction -with defaulted true. Editability is `editability(of:)` for that location: kind -`direct`; kind `sharedConstant` with the `uses` spans of every impacted reference; -or kind `readOnly` with its `reason`. Locations sort by pointer then start -offset; runtime node handles are not serialized. - -Diagnostics have code, severity, message, span and related spans, sorted by -position then code. No timestamps, cache paths or resolved secrets are emitted. -Readers ignore unknown object keys but reject unsupported schema versions and -unknown semantic discriminants. Changed meanings or new discriminants require -a new schema version; optional metadata additions do not. Source digest/locations -may change with comments while declaration stays equal. Entire output and map -size are reserved before serialization under the expanded-size budgets. - -## Diagnostics - -Diagnostics include stable code, severity, message, primary span, related spans -and optional suggested edit. Spans use half-open UTF-8 byte offsets and 1-based -line/UTF-8-byte-column positions. At most 100 diagnostics plus one truncation -notice are produced. Any structural/type/domain error rejects the candidate; -no partial declaration is published. - -| Diagnostic | Meaning | -| --- | --- | -| `manifest.version.missing`, `.invalid`, `.duplicate`, `.unsupported` | Version selection failed. | -| `manifest.syntax` | Recognizer: a lexical or production violation, including missing/extra imports, juxtaposed identifiers, unsupported prefixes, raw strings, interpolation and malformed literals. SwiftParser syntax/recovery diagnostics can occur only after recognizer acceptance and the tree guard; such a disagreement is also an implementation regression. | -| `manifest.call`, `manifest.type`, `manifest.operator` | After the tree guard: unlisted call/member, incorrect labels/order/type, missing context, integer overflow or non-array use of the admitted `+` operator. The `..<` operator is typed as `Range` only in its admitted requirement position. Other operators, including closed ranges (`...`), fail admission with a located `manifest.syntax` diagnostic; `ClosedRange` also has no matching compiler overload. | -| `manifest.reference` | Unknown, forward, self, duplicate or shadowing constant name. | -| `manifest.domain`, `manifest.dictionary.duplicateKey` | Invalid domain value or duplicate decoded dictionary key. A `manifest.domain` warning reports a Git shorthand with its fix-it. | -| `manifest.group.cycle`, `.missing` | Invalid local group graph, with the relevant reference chain. | -| `manifest.limit` | Recognizer: byte, token, syntax-storage reservation, comment, delimiter or chain limit. Iterative tree guard: node/depth limit. Later stages: evaluation, expansion, domain traversal, local group depth, output, generated source or edit budget. | -| `manifest.diagnostics.truncated` | The warning that replaces diagnostics beyond the limit. | -| `manifest.edit.readOnly`, `.stale`, `.overlap`, `.impact`, `.mismatch` | Document editing, as described under Document Editing. Declaration edit planning also reports `.mismatch` when a batch makes no progress or the final projection differs from the intended declaration. | -| `manifest.edit.baseline` | Declaration edit planning: the declaration an operation read differs from the projection of the bytes it prepared. The state layer reports it as a stale preparation; see [Declaration writes](../Architecture/State.md#declaration-writes). | -| `manifest.unsupported` | A deployment reader meets an active structure requiring linking or native lowering; full declaration projection still preserves it. See [State](../Architecture/State.md#deployable-subset). | -| `manifest.ambiguous` | A named deployment selection or ordered edit matches multiple occurrences; related spans identify the candidates. Address a document occurrence explicitly. | -| `manifest.dump.mismatch` | A source-map pointer is absent from the evaluated declaration while building a dump; this is an implementation regression. | - -## Conformance and Validation - -Every Swift code block in this reference and in the manifest proposal, -including interface and editor-API blocks, must pass `swiftc -parse`; -signature-only interface blocks use `swiftc -frontend -parse` with -`.swiftinterface` inputs so getter declarations are parsed in interface mode. -Positive fixtures compile against `AgentsDescription` and their -compiled values match static evaluation under plain value equality, including -equal range forms and string-literal group references. Compiler-required literal conformances and evaluator -registrations are checked against the same signature inventory. Negative fixtures -cover unsupported syntax, contextual typing, duplicate dictionary keys, budgets -and spans. No accepted static value may fail real Swift type checking. - -Adversarial tests run every input in a subprocess with a parent watchdog and -assert normal completion without signals, crashes or unbounded memory growth. -Fixed regressions include balanced/unbalanced square nests, mixed square/call -nests, dictionaries, nested shorthand calls and parentheses, brace nests, generic -types `A>`, ambiguous `a"`; integer-shaped +payloads, negative zero, exponent spelling and trailing zeroes retain identity. +This tag is permitted only on NativeValue scalars. `<<` is an ordinary data key. + +UTF-8, a leading BOM, LF/CRLF, block and flow collections and all ordinary scalar +styles are supported. Raw NEL, line separator and paragraph separator characters +are rejected before either parser; use double-quoted escapes `\u0085`, +`\u2028` and `\u2029` to retain those exact characters. Anchors, aliases, +directives, complex keys, multiple documents and other tags are rejected. + +## Edits and Source Maps + +`DeclarationDocument` exposes complete IR and semantic JSON Pointer locations: +`sources.team` maps to `/sources/0`, its key to `/sources/0/name`, and nested +group components to `/groups/0/components/...`. Handles belong to one digest. +`ManifestEdit` accepts Core domain values and prepares bytes without writing. + +No-op changes return exact bytes. Changed fields and collection entries preserve +unrelated bytes. Adjacent leading comments and same-line trailing comments belong +to their item; moves carry them. Deletion retains comments unless explicitly +owned by a replaced value. Blank-separated headers belong to their container. +Special layouts that cannot be changed precisely fail before publication. + +Complete declaration planning composes private parser/schema-checked drafts, +refreshes occurrence ranges and verifies full expected IR at every step. Final +domain and environment validation precede returning any candidate bytes. +Public documents and public prepared changes never expose unchecked drafts. + +## Bounds and Dump + +Input is bounded at 2,097,152 bytes; CSTs at 100,000 nodes/depth 128; decoded +values at 100,000 nodes/depth 64, 10,000 entries per container and 16,777,216 +string bytes. Parser-stage progress callbacks enforce an additional measured +work bound before CST traversal. Scalar scanning remains input-byte bounded; +these are work limits, not a claim of a fixed allocation bound. + +Source maps admit 100,000 locations, 1,000,000 origins and 16,777,216 encoded +bytes. Dump output is bounded at 33,554,432 bytes. Public edit batches admit 100 +requests, with 200,000 comparison pairs and 1,000,000 editing steps. Private +composition retains finite total work and bounded internal batches. + +`ManifestDump` uses schema version 2, `format: "yaml"`, manifest version 1, +source digest, complete typed IR and indexed locations. Decimal records retain +`{kind: "decimal", value: ""}`; arbitrary native object keys cannot +collide with this dump-only envelope. diff --git a/Documentation/Reference/ManifestSchema.md b/Documentation/Reference/ManifestSchema.md new file mode 100644 index 0000000..000451d --- /dev/null +++ b/Documentation/Reference/ManifestSchema.md @@ -0,0 +1,266 @@ +# Manifest Field Shapes + +Generated from `Sources/AgentsManifest/Resources/agents.schema.json`. + +## Declaration + +| Field | Required | Shape | +| --- | --- | --- | +| `version` | yes | `1` | +| `defaultAgents` | | sequence of agent | +| `sources` | | name → source | +| `components` | | sequence of component | +| `groups` | | name → group | +| `uses` | | sequence of use | +| `exports` | | sequence of string | +| `watch` | | sequence of string | + +## agent + +`codex` / `claude-code` / `cursor` / `gemini-cli` / `opencode` + +## condition + +| Field | Required | Shape | +| --- | --- | --- | +| `agents` | | sequence of agent | +| `scopes` | | sequence of `project` / `user` | +| `platforms` | | sequence of `macos` / `linux` | + +## resource + +| Field | Required | Shape | +| --- | --- | --- | +| `path` | yes | string | +| `source` | | string | + +## section + +| Field | Required | Shape | +| --- | --- | --- | +| `name` | yes | string | +| `source` | | string | +| `condition` | | condition | + +## binding + +one of: string, mapping, mapping + +## prompt + +one of: string, mapping + +## run + +| Field | Required | Shape | +| --- | --- | --- | +| `executable` | yes | string | +| `arguments` | | sequence of string | +| `environment` | | name → binding | +| `workingDirectory` | | resource | + +## transport + +one of: mapping, mapping + +## event + +one of: `beforeTool` / `afterTool` / `sessionStart` / `sessionEnd`, mapping + +## operation + +one of: `read` / `write` / `execute`, mapping + +## rule + +| Field | Required | Shape | +| --- | --- | --- | +| `effect` | yes | `allow` / `ask` / `deny` | +| `operation` | yes | operation | +| `pattern` | yes | string | + +## parameter + +| Field | Required | Shape | +| --- | --- | --- | +| `name` | yes | string | +| `description` | yes | string | +| `defaultValue` | | string | + +## promptDeclaration + +| Field | Required | Shape | +| --- | --- | --- | +| `sections` | | sequence of section | +| `append` | | string | +| `condition` | | condition | + +## override + +| Field | Required | Shape | +| --- | --- | --- | +| `agents` | | sequence of agent | +| `mode` | | `link` / `copy` / `edit` | + +## requirement + +one of: mapping, mapping, mapping, mapping, mapping, mapping + +## source + +one of: mapping, mapping, mapping + +## componentReference + +| Field | Required | Shape | +| --- | --- | --- | +| `kind` | yes | `skill` / `instruction` / `mcpServer` / `hook` / `subagent` / `command` / `lspServer` / `permissions` / `ignore` / `plugin` | +| `name` | yes | string | + +## component_skills + +| Field | Required | Shape | +| --- | --- | --- | +| `kind` | yes | `skills` | +| `agents` | | sequence of agent | +| `condition` | | condition | +| `native` | | name → name → NativeValue | +| `source` | yes | string | +| `select` | | one of: `all`, sequence of string | +| `exclude` | | sequence of string | +| `mode` | | `link` / `copy` / `edit` | +| `overrides` | | name → override | + +## component_instructions + +| Field | Required | Shape | +| --- | --- | --- | +| `kind` | yes | `instructions` | +| `agents` | | sequence of agent | +| `condition` | | condition | +| `native` | | name → name → NativeValue | +| `sections` | | sequence of section | +| `chatgpt` | | name → promptDeclaration | + +## component_mcpServer + +| Field | Required | Shape | +| --- | --- | --- | +| `kind` | yes | `mcpServer` | +| `agents` | | sequence of agent | +| `condition` | | condition | +| `native` | | name → name → NativeValue | +| `name` | yes | string | +| `transport` | yes | transport | + +## component_hook + +| Field | Required | Shape | +| --- | --- | --- | +| `kind` | yes | `hook` | +| `agents` | | sequence of agent | +| `condition` | | condition | +| `native` | | name → name → NativeValue | +| `name` | yes | string | +| `event` | yes | event | +| `run` | yes | run | +| `matcher` | | string | +| `timeoutSeconds` | | integer | + +## component_subagent + +| Field | Required | Shape | +| --- | --- | --- | +| `kind` | yes | `subagent` | +| `agents` | | sequence of agent | +| `condition` | | condition | +| `native` | | name → name → NativeValue | +| `name` | yes | string | +| `description` | yes | string | +| `prompt` | yes | prompt | +| `model` | | string | +| `tools` | | sequence of string | + +## component_command + +| Field | Required | Shape | +| --- | --- | --- | +| `kind` | yes | `command` | +| `agents` | | sequence of agent | +| `condition` | | condition | +| `native` | | name → name → NativeValue | +| `name` | yes | string | +| `description` | yes | string | +| `prompt` | yes | prompt | +| `parameters` | | sequence of parameter | + +## component_lspServer + +| Field | Required | Shape | +| --- | --- | --- | +| `kind` | yes | `lspServer` | +| `agents` | | sequence of agent | +| `condition` | | condition | +| `native` | | name → name → NativeValue | +| `name` | yes | string | +| `run` | yes | run | +| `languages` | yes | name → string | +| `initializationOptions` | | name → NativeValue | + +## component_permissions + +| Field | Required | Shape | +| --- | --- | --- | +| `kind` | yes | `permissions` | +| `agents` | | sequence of agent | +| `condition` | | condition | +| `native` | | name → name → NativeValue | +| `name` | yes | string | +| `rules` | yes | sequence of rule | + +## component_ignore + +| Field | Required | Shape | +| --- | --- | --- | +| `kind` | yes | `ignore` | +| `agents` | | sequence of agent | +| `condition` | | condition | +| `native` | | name → name → NativeValue | +| `name` | yes | string | +| `patterns` | yes | sequence of string | +| `purpose` | | `context` / `indexing` | + +## component_plugin + +| Field | Required | Shape | +| --- | --- | --- | +| `kind` | yes | `plugin` | +| `agents` | | sequence of agent | +| `condition` | | condition | +| `native` | | name → name → NativeValue | +| `name` | yes | string | +| `source` | yes | string | +| `path` | yes | string | +| `mode` | | `native` / `components` | +| `select` | | sequence of `skills` / `instructions` / `mcpServer` / `hook` / `subagent` / `command` / `lspServer` / `permissions` / `ignore` / `plugin` | +| `exclude` | | sequence of componentReference | + +## component + +one of: component_skills, component_instructions, component_mcpServer, component_hook, component_subagent, component_command, component_lspServer, component_permissions, component_ignore, component_plugin + +## use + +| Field | Required | Shape | +| --- | --- | --- | +| `group` | yes | string | +| `source` | | string | +| `condition` | | condition | + +## group + +| Field | Required | Shape | +| --- | --- | --- | +| `components` | | sequence of component | +| `uses` | | sequence of use | +| `condition` | | condition | diff --git a/Documentation/Reference/Presentation.md b/Documentation/Reference/Presentation.md index 2a9550a..9fd7909 100644 --- a/Documentation/Reference/Presentation.md +++ b/Documentation/Reference/Presentation.md @@ -51,7 +51,7 @@ containing the skill fixture above. Unset `CODEX_HOME`, `CLAUDE_CONFIG_DIR`, The expected stdout is `review` followed by a newline. Verify that `.agents/skills/review` in the scratch project links to `skills/review` and that -`.agent/Agents.swift` and `.agent/agents.resolved` record the selection. Remove +`.agent/agents.yaml` and `.agent/agents.resolved` record the selection. Remove `.build/presentation/` after validation. [design]: https://github.com/agents-tools/.github/blob/master/DESIGN.md diff --git a/Documentation/Reference/README.md b/Documentation/Reference/README.md index 1399790..69730c4 100644 --- a/Documentation/Reference/README.md +++ b/Documentation/Reference/README.md @@ -4,8 +4,7 @@ This directory holds supporting reference material for `core`. ## Guides -- [Agents manifest language](Manifest.md): the `Agents.swift` language 1.0 - vocabulary, grammar, limits, document editing, evaluated dump and diagnostics. +- [Agents manifest language](Manifest.md): YAML field shapes, scalar semantics, limits, source edits, dump and diagnostics. - [Repository presentation](Presentation.md): the README Quick look fixture and standalone consumer validation. - [Release checklist](Release.md): preflight, signed version tags, GitHub diff --git a/Package.resolved b/Package.resolved index c2cdde8..15a738f 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "2c053518874423b9cbd21ad05cd15590e43cf4686b80c1421255af9007ac3963", + "originHash" : "ab09bed54f5aab76864fb60822b02f0a35a5f6a7d8c83569ee7317a964deef44", "pins" : [ { "identity" : "swift-asn1", @@ -38,12 +38,12 @@ } }, { - "identity" : "swift-syntax", + "identity" : "tree-sitter", "kind" : "remoteSourceControl", - "location" : "https://github.com/swiftlang/swift-syntax.git", + "location" : "https://github.com/tree-sitter/tree-sitter", "state" : { - "revision" : "050f1a346fbbac0ca2cfb15a95274f7bd1cf0ccf", - "version" : "604.0.0" + "revision" : "da6fe9beb4f7f67beb75914ca8e0d48ae48d6406", + "version" : "0.25.10" } }, { diff --git a/Package.swift b/Package.swift index 708612c..3128a5b 100644 --- a/Package.swift +++ b/Package.swift @@ -9,7 +9,6 @@ let package = Package( .macOS(.v15) ], products: [ - .library(name: "AgentsDescription", targets: ["AgentsDescription"]), .library(name: "AgentsManifest", targets: ["AgentsManifest"]), .library(name: "AgentsCore", targets: ["AgentsCore"]), .library(name: "AgentsSkills", targets: ["AgentsSkills"]), @@ -18,20 +17,22 @@ let package = Package( ], dependencies: [ .package(url: "https://github.com/apple/swift-crypto.git", from: "5.0.0"), - .package(url: "https://github.com/jpsim/Yams", from: "6.0.0"), + .package(url: "https://github.com/jpsim/Yams", exact: "6.2.2"), .package(url: "https://github.com/swiftlang/swift-markdown.git", from: "0.9.0"), - .package(url: "https://github.com/swiftlang/swift-syntax.git", exact: "604.0.0"), + .package(url: "https://github.com/tree-sitter/tree-sitter", exact: "0.25.10"), ], targets: [ .target(name: "CPlatform"), - .target(name: "AgentsDescription"), + .target( + name: "TreeSitterYAML", exclude: ["LICENSE", "provenance.json"], + sources: ["parser.c", "scanner.c"], publicHeadersPath: "include", + cSettings: [.headerSearchPath(".")]), .target( name: "AgentsManifest", dependencies: [ - "AgentsDescription", "AgentsCore", - .product(name: "SwiftSyntax", package: "swift-syntax"), - .product(name: "SwiftParser", package: "swift-syntax"), - ]), + "AgentsCore", "TreeSitterYAML", "Yams", + .product(name: "TreeSitter", package: "tree-sitter"), + ], resources: [.copy("Resources/agents.schema.json")]), .target( name: "AgentsCore", dependencies: ["CPlatform", .product(name: "Crypto", package: "swift-crypto")] @@ -77,17 +78,14 @@ let package = Package( path: "Tests/ManifestTestSupport"), .executableTarget( name: "ManifestTestProcess", - dependencies: ["AgentsManifest", "AgentsCore", "AgentsDescription", "ManifestTestSupport"], + dependencies: ["AgentsManifest", "AgentsCore", "ManifestTestSupport"], path: "Tests/ManifestTestProcess"), .testTarget( name: "AgentsManifestTests", dependencies: [ - "AgentsManifest", "AgentsDescription", "AgentsCore", "ManifestTestProcess", + "AgentsManifest", "AgentsCore", "ManifestTestProcess", "ManifestTestSupport", - .product(name: "SwiftParser", package: "swift-syntax"), - .product(name: "SwiftSyntax", package: "swift-syntax"), - ], - resources: [.copy("Fixtures")]), + ]), .testTarget( name: "AgentsUpdatesTests", dependencies: [ diff --git a/README.md b/README.md index 4a6ed4e..937ff5e 100644 --- a/README.md +++ b/README.md @@ -51,12 +51,10 @@ Both [agents](https://github.com/agents-tools/cli) and [skill](https://github.com/skill-cli/cli) consume this package. Consumers own command parsing, terminal output and executable distribution. -- **AgentsDescription**: standard-library-only types for authoring the Swift - manifest construction vocabulary. -- **AgentsManifest**: parses and statically evaluates `Agents.swift` snapshots - into declaration IR and source maps, prepares byte-preserving edits, and - connects the scope declaration to state: read-only `loadDeclaration()` and - `loadManifest()`, and the declaration writes of the domain modules. +- **AgentsManifest**: reads and edits `agents.yaml`, validates complete symbolic + declaration intent and prepares byte-preserving changes. It supplies read-only + `loadDeclaration()` and `loadManifest()` access and declaration writes for the + domain modules. - **AgentsCore**: source parsing and identity, Git requirements, declaration and resolved-state models, atomic state storage, bare mirrors and immutable source materializations, watch subscriptions, hashing, path safety, process execution @@ -104,7 +102,6 @@ targets: [ .executableTarget( name: "YourCLI", dependencies: [ - .product(name: "AgentsDescription", package: "core"), .product(name: "AgentsManifest", package: "core"), .product(name: "AgentsCore", package: "core"), .product(name: "AgentsSkills", package: "core"), @@ -124,10 +121,10 @@ requirement. Pin a reviewed revision when reproducibility is required. Use ### State and lifecycle -Project state lives in `.agent/Agents.swift`, `.agent/agents.resolved` and +Project state lives in `.agent/agents.yaml`, `.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. A -project commits its `Agents.swift` declaration and `agents.resolved` lock; keep +project commits its `agents.yaml` declaration and `agents.resolved` lock; keep `agents.watch`, `cache/`, `.agents.lock` and `transaction.json` out of version control. @@ -153,7 +150,7 @@ cache pruning. Corrupt watch state stops scope mutations before any replacement. Read-only access, including `loadResolved()`, `loadWatch()` and, with `import AgentsManifest`, `loadDeclaration()` and `loadManifest()`, never recovers and reports a pending transaction with `CoreError.recoveryPending`. A scope with a -lock or watch state but no `Agents.swift` reports +lock or watch state but no `agents.yaml` reports `CoreError.missingDeclaration`. ### Skills @@ -233,7 +230,7 @@ by bare name. `InstructionOperations` generates whole target files from them: 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 are declared with `.instructions(chatGPT:)`. + Prompts are declared in an instructions component’s `chatgpt` mapping. - `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. @@ -302,8 +299,8 @@ Read the [organization contributing guide][contributing] and the The generation commands in `.github/swift-package.json` run on the last compiler entry's runner, using `python3` and the toolchain's `swift format`. They regenerate into temporary directories and compare committed bytes. -`swift test` checks contract signatures and the complete compiler-backed fixture -inventory without invoking these generators. +`swift test` checks YAML admission, complete domain round trips, source maps, +lossless edits and the existing lifecycle contracts. Run the package's build, test, generation and formatting checks: @@ -312,8 +309,7 @@ swift build env -u CODEX_HOME -u CLAUDE_CONFIG_DIR -u XDG_CONFIG_HOME \ -u XDG_STATE_HOME -u XDG_CACHE_HOME swift test swift build -c release -python3 Scripts/generate-manifest-vocabulary.py --check -python3 Scripts/generate-manifest-fixtures.py --check +python3 Scripts/generate-manifest-schema.py --check swift format lint --strict --configuration .swift-format \ --recursive Package.swift Sources Tests ``` diff --git a/Scripts/ManifestVocabulary.json b/Scripts/ManifestVocabulary.json deleted file mode 100644 index 441d178..0000000 --- a/Scripts/ManifestVocabulary.json +++ /dev/null @@ -1,1912 +0,0 @@ -{ - "enums": { - "Agent": [ - { - "name": "claudeCode", - "parameters": [], - "loweredValue": "claude-code" - }, - { - "name": "codex", - "parameters": [] - }, - { - "name": "cursor", - "parameters": [] - }, - { - "name": "geminiCLI", - "parameters": [], - "loweredValue": "gemini-cli" - }, - { - "name": "openCode", - "parameters": [], - "loweredValue": "opencode" - } - ], - "Scope": [ - { - "name": "project", - "parameters": [] - }, - { - "name": "user", - "parameters": [] - } - ], - "Platform": [ - { - "name": "macOS", - "parameters": [], - "loweredValue": "macos" - }, - { - "name": "linux", - "parameters": [] - } - ], - "InstallMode": [ - { - "name": "link", - "parameters": [] - }, - { - "name": "copy", - "parameters": [] - }, - { - "name": "edit", - "parameters": [] - } - ], - "RuntimeValue": [ - { - "name": "literal", - "parameters": [ - { - "label": "_", - "name": "value", - "type": "String" - } - ] - }, - { - "name": "environment", - "parameters": [ - { - "label": "_", - "name": "value", - "type": "String" - } - ] - }, - { - "name": "secret", - "parameters": [ - { - "label": "_", - "name": "value", - "type": "String" - } - ] - } - ], - "ConfigurationValue": [ - { - "name": "string", - "parameters": [ - { - "label": "_", - "name": "value", - "type": "String" - } - ] - }, - { - "name": "integer", - "parameters": [ - { - "label": "_", - "name": "value", - "type": "Int" - } - ] - }, - { - "name": "decimal", - "parameters": [ - { - "label": "_", - "name": "value", - "type": "String" - } - ] - }, - { - "name": "boolean", - "parameters": [ - { - "label": "_", - "name": "value", - "type": "Bool" - } - ] - }, - { - "name": "null", - "parameters": [] - }, - { - "name": "array", - "parameters": [ - { - "label": "_", - "name": "value", - "type": "[ConfigurationValue]" - } - ] - }, - { - "name": "object", - "parameters": [ - { - "label": "_", - "name": "value", - "type": "[String: ConfigurationValue]" - } - ] - } - ], - "HookEvent": [ - { - "name": "beforeTool", - "parameters": [] - }, - { - "name": "afterTool", - "parameters": [] - }, - { - "name": "sessionStart", - "parameters": [] - }, - { - "name": "sessionEnd", - "parameters": [] - }, - { - "name": "native", - "parameters": [ - { - "label": "_", - "name": "value", - "type": "String" - } - ] - } - ], - "PermissionOperation": [ - { - "name": "read", - "parameters": [] - }, - { - "name": "write", - "parameters": [] - }, - { - "name": "execute", - "parameters": [] - }, - { - "name": "tool", - "parameters": [ - { - "label": "_", - "name": "value", - "type": "String" - } - ] - } - ], - "IgnorePurpose": [ - { - "name": "context", - "parameters": [] - }, - { - "name": "indexing", - "parameters": [] - } - ], - "PluginMode": [ - { - "name": "native", - "parameters": [] - }, - { - "name": "components", - "parameters": [] - } - ], - "ComponentKind": [ - { - "name": "skills", - "parameters": [] - }, - { - "name": "instructions", - "parameters": [] - }, - { - "name": "mcpServer", - "parameters": [] - }, - { - "name": "hook", - "parameters": [] - }, - { - "name": "subagent", - "parameters": [] - }, - { - "name": "command", - "parameters": [] - }, - { - "name": "lspServer", - "parameters": [] - }, - { - "name": "permissions", - "parameters": [] - }, - { - "name": "ignore", - "parameters": [] - }, - { - "name": "plugin", - "parameters": [] - } - ], - "ComponentReference": [ - { - "name": "skill", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - } - ] - }, - { - "name": "instruction", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - } - ] - }, - { - "name": "mcpServer", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - } - ] - }, - { - "name": "hook", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - } - ] - }, - { - "name": "subagent", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - } - ] - }, - { - "name": "command", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - } - ] - }, - { - "name": "lspServer", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - } - ] - }, - { - "name": "permissions", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - } - ] - }, - { - "name": "ignore", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - } - ] - }, - { - "name": "plugin", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - } - ] - } - ] - }, - "structs": [ - "Condition", - "Agents", - "Source", - "ComponentGroup", - "GroupReference", - "SkillSelection", - "SkillOverride", - "SectionReference", - "ChatGPTPrompt", - "Resource", - "PromptContent", - "ExecutableInvocation", - "MCPTransport", - "PromptParameter", - "PermissionRule", - "Component" - ], - "factories": [ - { - "type": "Condition", - "name": "when", - "parameters": [ - { - "label": "agents", - "name": "agents", - "default": "nil", - "type": "[Agent]?" - }, - { - "label": "scopes", - "name": "scopes", - "default": "nil", - "type": "[Scope]?" - }, - { - "label": "platforms", - "name": "platforms", - "default": "nil", - "type": "[Platform]?" - } - ] - }, - { - "type": "Agents", - "name": "Agents", - "parameters": [ - { - "label": "defaultAgents", - "name": "defaultAgents", - "default": "nil", - "type": "[Agent]?" - }, - { - "label": "exports", - "name": "exports", - "default": "[]", - "type": "[String]" - }, - { - "label": "sources", - "name": "sources", - "default": "[]", - "type": "[Source]" - }, - { - "label": "components", - "name": "components", - "default": "[]", - "type": "[Component]" - }, - { - "label": "groups", - "name": "groups", - "default": "[]", - "type": "[ComponentGroup]" - }, - { - "label": "uses", - "name": "uses", - "default": "[]", - "type": "[GroupReference]" - }, - { - "label": "watch", - "name": "watch", - "default": "[]", - "type": "[String]" - } - ], - "initializer": true - }, - { - "type": "Source", - "name": "source", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "url", - "name": "url", - "type": "String" - }, - { - "label": "subpath", - "name": "subpath", - "default": "nil", - "type": "String?" - } - ] - }, - { - "type": "Source", - "name": "source", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "url", - "name": "url", - "type": "String" - }, - { - "label": "from", - "name": "from", - "type": "Version" - }, - { - "label": "subpath", - "name": "subpath", - "default": "nil", - "type": "String?" - } - ] - }, - { - "type": "Source", - "name": "source", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "url", - "name": "url", - "type": "String" - }, - { - "label": "exact", - "name": "exact", - "type": "Version" - }, - { - "label": "subpath", - "name": "subpath", - "default": "nil", - "type": "String?" - } - ] - }, - { - "type": "Source", - "name": "source", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "url", - "name": "url", - "type": "String" - }, - { - "label": "branch", - "name": "branch", - "type": "String" - }, - { - "label": "subpath", - "name": "subpath", - "default": "nil", - "type": "String?" - } - ] - }, - { - "type": "Source", - "name": "source", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "url", - "name": "url", - "type": "String" - }, - { - "label": "revision", - "name": "revision", - "type": "String" - }, - { - "label": "subpath", - "name": "subpath", - "default": "nil", - "type": "String?" - } - ] - }, - { - "type": "Source", - "name": "source", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "url", - "name": "url", - "type": "String" - }, - { - "label": "_", - "name": "range", - "type": "Range" - }, - { - "label": "subpath", - "name": "subpath", - "default": "nil", - "type": "String?" - } - ] - }, - { - "type": "Source", - "name": "source", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "path", - "name": "path", - "type": "String" - }, - { - "label": "subpath", - "name": "subpath", - "default": "nil", - "type": "String?" - } - ] - }, - { - "type": "Source", - "name": "source", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "path", - "name": "path", - "type": "String" - }, - { - "label": "from", - "name": "from", - "type": "Version" - }, - { - "label": "subpath", - "name": "subpath", - "default": "nil", - "type": "String?" - } - ] - }, - { - "type": "Source", - "name": "source", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "path", - "name": "path", - "type": "String" - }, - { - "label": "exact", - "name": "exact", - "type": "Version" - }, - { - "label": "subpath", - "name": "subpath", - "default": "nil", - "type": "String?" - } - ] - }, - { - "type": "Source", - "name": "source", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "path", - "name": "path", - "type": "String" - }, - { - "label": "branch", - "name": "branch", - "type": "String" - }, - { - "label": "subpath", - "name": "subpath", - "default": "nil", - "type": "String?" - } - ] - }, - { - "type": "Source", - "name": "source", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "path", - "name": "path", - "type": "String" - }, - { - "label": "revision", - "name": "revision", - "type": "String" - }, - { - "label": "subpath", - "name": "subpath", - "default": "nil", - "type": "String?" - } - ] - }, - { - "type": "Source", - "name": "source", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "path", - "name": "path", - "type": "String" - }, - { - "label": "_", - "name": "range", - "type": "Range" - }, - { - "label": "subpath", - "name": "subpath", - "default": "nil", - "type": "String?" - } - ] - }, - { - "type": "Source", - "name": "source", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "index", - "name": "index", - "type": "String" - }, - { - "label": "subpath", - "name": "subpath", - "default": "nil", - "type": "String?" - } - ] - }, - { - "type": "ComponentGroup", - "name": "group", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "components", - "name": "components", - "default": "[]", - "type": "[Component]" - }, - { - "label": "uses", - "name": "uses", - "default": "[]", - "type": "[GroupReference]" - }, - { - "label": "condition", - "name": "condition", - "default": "nil", - "type": "Condition?" - } - ] - }, - { - "type": "GroupReference", - "name": "group", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "condition", - "name": "condition", - "default": "nil", - "type": "Condition?" - } - ] - }, - { - "type": "GroupReference", - "name": "group", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "source", - "name": "source", - "type": "String" - }, - { - "label": "condition", - "name": "condition", - "default": "nil", - "type": "Condition?" - } - ] - }, - { - "type": "SkillSelection", - "name": "all", - "property": true, - "parameters": [] - }, - { - "type": "SkillOverride", - "name": "skill", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "mode", - "name": "mode", - "default": "nil", - "type": "InstallMode?" - }, - { - "label": "agents", - "name": "agents", - "default": "nil", - "type": "[Agent]?" - } - ] - }, - { - "type": "SectionReference", - "name": "section", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "source", - "name": "source", - "default": "nil", - "type": "String?" - }, - { - "label": "condition", - "name": "condition", - "default": "nil", - "type": "Condition?" - } - ] - }, - { - "type": "ChatGPTPrompt", - "name": "prompt", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "sections", - "name": "sections", - "type": "[SectionReference]" - }, - { - "label": "append", - "name": "append", - "default": "nil", - "type": "String?" - }, - { - "label": "condition", - "name": "condition", - "default": "nil", - "type": "Condition?" - } - ] - }, - { - "type": "Resource", - "name": "path", - "parameters": [ - { - "label": "_", - "name": "path", - "type": "String" - }, - { - "label": "source", - "name": "source", - "default": "nil", - "type": "String?" - } - ] - }, - { - "type": "PromptContent", - "name": "file", - "parameters": [ - { - "label": "_", - "name": "path", - "type": "String" - }, - { - "label": "source", - "name": "source", - "default": "nil", - "type": "String?" - } - ] - }, - { - "type": "ExecutableInvocation", - "name": "executable", - "parameters": [ - { - "label": "_", - "name": "executable", - "type": "String" - }, - { - "label": "arguments", - "name": "arguments", - "default": "[]", - "type": "[String]" - }, - { - "label": "environment", - "name": "environment", - "default": "[:]", - "type": "[String: RuntimeValue]" - }, - { - "label": "workingDirectory", - "name": "workingDirectory", - "default": "nil", - "type": "Resource?" - } - ] - }, - { - "type": "MCPTransport", - "name": "stdio", - "parameters": [ - { - "label": "_", - "name": "executable", - "type": "String" - }, - { - "label": "arguments", - "name": "arguments", - "default": "[]", - "type": "[String]" - }, - { - "label": "environment", - "name": "environment", - "default": "[:]", - "type": "[String: RuntimeValue]" - }, - { - "label": "workingDirectory", - "name": "workingDirectory", - "default": "nil", - "type": "Resource?" - } - ] - }, - { - "type": "MCPTransport", - "name": "streamableHTTP", - "parameters": [ - { - "label": "url", - "name": "url", - "type": "String" - }, - { - "label": "headers", - "name": "headers", - "default": "[:]", - "type": "[String: RuntimeValue]" - } - ] - }, - { - "type": "MCPTransport", - "name": "sse", - "parameters": [ - { - "label": "url", - "name": "url", - "type": "String" - }, - { - "label": "headers", - "name": "headers", - "default": "[:]", - "type": "[String: RuntimeValue]" - } - ] - }, - { - "type": "PromptParameter", - "name": "parameter", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "description", - "name": "description", - "type": "String" - }, - { - "label": "defaultValue", - "name": "defaultValue", - "default": "nil", - "type": "String?" - } - ] - }, - { - "type": "PermissionRule", - "name": "allow", - "parameters": [ - { - "label": "_", - "name": "operation", - "type": "PermissionOperation" - }, - { - "label": "_", - "name": "pattern", - "type": "String" - } - ] - }, - { - "type": "PermissionRule", - "name": "ask", - "parameters": [ - { - "label": "_", - "name": "operation", - "type": "PermissionOperation" - }, - { - "label": "_", - "name": "pattern", - "type": "String" - } - ] - }, - { - "type": "PermissionRule", - "name": "deny", - "parameters": [ - { - "label": "_", - "name": "operation", - "type": "PermissionOperation" - }, - { - "label": "_", - "name": "pattern", - "type": "String" - } - ] - }, - { - "type": "Component", - "name": "skills", - "parameters": [ - { - "label": "source", - "name": "source", - "type": "String" - }, - { - "label": "select", - "name": "select", - "default": ".all", - "type": "SkillSelection" - }, - { - "label": "exclude", - "name": "exclude", - "default": "[]", - "type": "[String]" - }, - { - "label": "mode", - "name": "mode", - "default": "nil", - "type": "InstallMode?" - }, - { - "label": "overrides", - "name": "overrides", - "default": "[]", - "type": "[SkillOverride]" - }, - { - "label": "agents", - "name": "agents", - "default": "nil", - "type": "[Agent]?" - }, - { - "label": "condition", - "name": "condition", - "default": "nil", - "type": "Condition?" - }, - { - "label": "native", - "name": "native", - "default": "[:]", - "type": "NativeConfiguration" - } - ] - }, - { - "type": "Component", - "name": "instructions", - "parameters": [ - { - "label": "sections", - "name": "sections", - "default": "[]", - "type": "[SectionReference]" - }, - { - "label": "chatGPT", - "name": "chatGPT", - "default": "[]", - "type": "[ChatGPTPrompt]" - }, - { - "label": "agents", - "name": "agents", - "default": "nil", - "type": "[Agent]?" - }, - { - "label": "condition", - "name": "condition", - "default": "nil", - "type": "Condition?" - }, - { - "label": "native", - "name": "native", - "default": "[:]", - "type": "NativeConfiguration" - } - ] - }, - { - "type": "Component", - "name": "mcpServer", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "transport", - "name": "transport", - "type": "MCPTransport" - }, - { - "label": "agents", - "name": "agents", - "default": "nil", - "type": "[Agent]?" - }, - { - "label": "condition", - "name": "condition", - "default": "nil", - "type": "Condition?" - }, - { - "label": "native", - "name": "native", - "default": "[:]", - "type": "NativeConfiguration" - } - ] - }, - { - "type": "Component", - "name": "hook", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "event", - "name": "event", - "type": "HookEvent" - }, - { - "label": "run", - "name": "run", - "type": "ExecutableInvocation" - }, - { - "label": "matcher", - "name": "matcher", - "default": "nil", - "type": "String?" - }, - { - "label": "timeoutSeconds", - "name": "timeoutSeconds", - "default": "nil", - "type": "Int?" - }, - { - "label": "agents", - "name": "agents", - "default": "nil", - "type": "[Agent]?" - }, - { - "label": "condition", - "name": "condition", - "default": "nil", - "type": "Condition?" - }, - { - "label": "native", - "name": "native", - "default": "[:]", - "type": "NativeConfiguration" - } - ] - }, - { - "type": "Component", - "name": "subagent", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "description", - "name": "description", - "type": "String" - }, - { - "label": "prompt", - "name": "prompt", - "type": "PromptContent" - }, - { - "label": "model", - "name": "model", - "default": "nil", - "type": "String?" - }, - { - "label": "tools", - "name": "tools", - "default": "nil", - "type": "[String]?" - }, - { - "label": "agents", - "name": "agents", - "default": "nil", - "type": "[Agent]?" - }, - { - "label": "condition", - "name": "condition", - "default": "nil", - "type": "Condition?" - }, - { - "label": "native", - "name": "native", - "default": "[:]", - "type": "NativeConfiguration" - } - ] - }, - { - "type": "Component", - "name": "command", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "description", - "name": "description", - "type": "String" - }, - { - "label": "prompt", - "name": "prompt", - "type": "PromptContent" - }, - { - "label": "parameters", - "name": "parameters", - "default": "[]", - "type": "[PromptParameter]" - }, - { - "label": "agents", - "name": "agents", - "default": "nil", - "type": "[Agent]?" - }, - { - "label": "condition", - "name": "condition", - "default": "nil", - "type": "Condition?" - }, - { - "label": "native", - "name": "native", - "default": "[:]", - "type": "NativeConfiguration" - } - ] - }, - { - "type": "Component", - "name": "lspServer", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "run", - "name": "run", - "type": "ExecutableInvocation" - }, - { - "label": "languages", - "name": "languages", - "type": "[String: String]" - }, - { - "label": "initializationOptions", - "name": "initializationOptions", - "default": "[:]", - "type": "[String: ConfigurationValue]" - }, - { - "label": "agents", - "name": "agents", - "default": "nil", - "type": "[Agent]?" - }, - { - "label": "condition", - "name": "condition", - "default": "nil", - "type": "Condition?" - }, - { - "label": "native", - "name": "native", - "default": "[:]", - "type": "NativeConfiguration" - } - ] - }, - { - "type": "Component", - "name": "permissions", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "rules", - "name": "rules", - "type": "[PermissionRule]" - }, - { - "label": "agents", - "name": "agents", - "default": "nil", - "type": "[Agent]?" - }, - { - "label": "condition", - "name": "condition", - "default": "nil", - "type": "Condition?" - }, - { - "label": "native", - "name": "native", - "default": "[:]", - "type": "NativeConfiguration" - } - ] - }, - { - "type": "Component", - "name": "ignore", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "patterns", - "name": "patterns", - "type": "[String]" - }, - { - "label": "purpose", - "name": "purpose", - "default": ".context", - "type": "IgnorePurpose" - }, - { - "label": "agents", - "name": "agents", - "default": "nil", - "type": "[Agent]?" - }, - { - "label": "condition", - "name": "condition", - "default": "nil", - "type": "Condition?" - }, - { - "label": "native", - "name": "native", - "default": "[:]", - "type": "NativeConfiguration" - } - ] - }, - { - "type": "Component", - "name": "plugin", - "parameters": [ - { - "label": "name", - "name": "name", - "type": "String" - }, - { - "label": "path", - "name": "path", - "type": "String" - }, - { - "label": "source", - "name": "source", - "type": "String" - }, - { - "label": "mode", - "name": "mode", - "default": ".components", - "type": "PluginMode" - }, - { - "label": "select", - "name": "select", - "default": "nil", - "type": "[ComponentKind]?" - }, - { - "label": "exclude", - "name": "exclude", - "default": "[]", - "type": "[ComponentReference]" - }, - { - "label": "agents", - "name": "agents", - "default": "nil", - "type": "[Agent]?" - }, - { - "label": "condition", - "name": "condition", - "default": "nil", - "type": "Condition?" - }, - { - "label": "native", - "name": "native", - "default": "[:]", - "type": "NativeConfiguration" - } - ] - } - ], - "literals": { - "SectionReference": { - "protocols": [ - "ExpressibleByStringLiteral" - ], - "kinds": [ - "string" - ], - "conversions": { - "string": { - "member": "section", - "payload": "name", - "payloadType": "String", - "defaults": { - "source": "nil", - "condition": "nil" - } - } - } - }, - "GroupReference": { - "protocols": [ - "ExpressibleByStringLiteral" - ], - "kinds": [ - "string" - ], - "conversions": { - "string": { - "member": "group", - "payload": "name", - "payloadType": "String", - "defaults": { - "source": "nil", - "condition": "nil" - } - } - } - }, - "PromptContent": { - "protocols": [ - "ExpressibleByStringLiteral" - ], - "kinds": [ - "string" - ], - "conversions": { - "string": { - "member": "literal", - "payload": "value", - "payloadType": "String" - } - } - }, - "RuntimeValue": { - "protocols": [ - "ExpressibleByStringLiteral" - ], - "kinds": [ - "string" - ], - "conversions": { - "string": { - "member": "literal", - "payload": "value", - "payloadType": "String" - } - } - }, - "SkillSelection": { - "protocols": [ - "ExpressibleByArrayLiteral" - ], - "kinds": [ - "array" - ], - "conversions": { - "array": { - "member": "names", - "payload": "names", - "payloadType": "[String]" - } - } - }, - "ConfigurationValue": { - "protocols": [ - "ExpressibleByStringLiteral", - "ExpressibleByIntegerLiteral", - "ExpressibleByBooleanLiteral", - "ExpressibleByNilLiteral", - "ExpressibleByArrayLiteral", - "ExpressibleByDictionaryLiteral" - ], - "kinds": [ - "string", - "integer", - "boolean", - "nil", - "array", - "dictionary" - ], - "conversions": { - "string": { - "member": "string", - "payload": "value", - "payloadType": "String" - }, - "integer": { - "member": "integer", - "payload": "value", - "payloadType": "Int" - }, - "boolean": { - "member": "boolean", - "payload": "value", - "payloadType": "Bool" - }, - "nil": { - "member": "null" - }, - "array": { - "member": "array", - "payload": "value", - "payloadType": "[ConfigurationValue]" - }, - "dictionary": { - "member": "object", - "payload": "value", - "payloadType": "[String: ConfigurationValue]" - } - } - }, - "Version": { - "protocols": [ - "ExpressibleByStringLiteral" - ], - "kinds": [ - "string" - ], - "conversions": {} - } - }, - "aliases": { - "NativeConfiguration": "[String: [String: ConfigurationValue]]" - }, - "recursiveEnums": [ - "ConfigurationValue" - ], - "taggedRecordTypes": [ - "Source", - "Component", - "MCPTransport", - "ExecutableInvocation", - "GroupReference", - "PromptContent", - "RuntimeValue", - "ConfigurationValue", - "HookEvent", - "PermissionOperation", - "ComponentReference", - "PermissionRule" - ], - "rangeFactories": [ - { - "type": "VersionRange", - "name": "upToNextMajor", - "parameters": [ - { - "label": "from", - "name": "from", - "type": "Version" - } - ] - }, - { - "type": "VersionRange", - "name": "upToNextMinor", - "parameters": [ - { - "label": "from", - "name": "from", - "type": "Version" - } - ] - } - ], - "staticValueFactories": [ - { - "type": "ConfigurationValue", - "name": "configuration" - }, - { - "type": "Component", - "name": "component" - }, - { - "type": "Source", - "name": "source" - }, - { - "type": "SectionReference", - "name": "section" - }, - { - "type": "GroupReference", - "name": "groupReference" - }, - { - "type": "Version", - "name": "version" - }, - { - "type": "RuntimeValue", - "name": "runtime" - }, - { - "type": "Condition", - "name": "condition" - }, - { - "type": "SkillSelection", - "name": "selection" - }, - { - "type": "SkillOverride", - "name": "skillOverride" - }, - { - "type": "ChatGPTPrompt", - "name": "prompt" - }, - { - "type": "Resource", - "name": "resource" - }, - { - "type": "PromptContent", - "name": "promptContent" - }, - { - "type": "ExecutableInvocation", - "name": "executable" - }, - { - "type": "MCPTransport", - "name": "transport" - }, - { - "type": "PromptParameter", - "name": "parameter" - }, - { - "type": "PermissionRule", - "name": "permissionRule" - }, - { - "type": "Agent", - "name": "agent" - }, - { - "type": "Scope", - "name": "scope" - }, - { - "type": "Platform", - "name": "platform" - }, - { - "type": "InstallMode", - "name": "installMode" - }, - { - "type": "HookEvent", - "name": "hookEvent" - }, - { - "type": "PermissionOperation", - "name": "permissionOperation" - }, - { - "type": "IgnorePurpose", - "name": "ignorePurpose" - }, - { - "type": "PluginMode", - "name": "pluginMode" - }, - { - "type": "ComponentKind", - "name": "componentKind" - }, - { - "type": "ComponentReference", - "name": "componentReference" - }, - { - "type": "ComponentGroup", - "name": "group" - }, - { - "type": "Agents", - "name": "agents" - } - ], - "primitiveTypes": [ - "String", - "Int", - "Bool" - ], - "customTypes": [ - "Version" - ], - "contextualTypes": { - "Range": "VersionRange" - } -} diff --git a/Scripts/generate-manifest-fixtures.py b/Scripts/generate-manifest-fixtures.py deleted file mode 100644 index 98c088d..0000000 --- a/Scripts/generate-manifest-fixtures.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python3 -"""Generate compiler-backed values for every complete positive manifest fixture.""" -import sys - -# Imports must not leave bytecode caches in the source tree. -sys.dont_write_bytecode = True - -import json -import re -from pathlib import Path - -from manifest_generation import run_generator - -ROOT = Path(__file__).resolve().parent.parent -FIXTURES = ROOT / "Tests/AgentsManifestTests/Fixtures" -DESTINATION = Path("Tests/AgentsManifestTests/CompiledFixtures.swift") -HEADER = "// Generated from Tests/AgentsManifestTests/Fixtures. Run Scripts/generate-manifest-fixtures.py." -BINDING = re.compile(r"^let ([A-Za-z_][A-Za-z_0-9]*)\b", re.MULTILINE) - - -def function_name(path): - return "compiled" + path.name.removesuffix(".swift.txt") - - -def fixture_function(path): - # Imports stay at file scope; all bindings remain ordinary Swift inside the function. - lines = [line for line in path.read_text().splitlines() if line != "import AgentsDescription"] - names = BINDING.findall("\n".join(lines)) - result = ["private func " + function_name(path) + "() -> CompiledManifestFixture {"] - result += [" " + line if line else "" for line in lines] - result += [" return CompiledManifestFixture(", " name: " + json.dumps(path.name) + ", agents: agents, constants: ["] - result += [" " + json.dumps(name) + ": " + name + ".constructionValue," for name in names] - return result + [" ])", "}", ""] - - -def generated_source(paths): - lines = [HEADER, "", "import AgentsDescription", "import Foundation", "", - "#if canImport(SwiftUI)", " import SwiftUI", "#endif", "", - "struct CompiledManifestFixture {", " let name: String", " let agents: Agents", - " let constants: [String: ConstructionValue]", "}", "", - "func compiledFixtures() -> [CompiledManifestFixture] {", " ["] - lines += [" " + function_name(path) + "()," for path in paths] - lines += [" ]", "}", ""] - for path in paths: - lines += fixture_function(path) - return "\n".join(lines) - - -def main(): - paths = sorted(FIXTURES.glob("*.swift.txt")) - run_generator( - {DESTINATION: generated_source(paths)}, repository=ROOT, generator=Path(__file__).resolve() - ) - - -if __name__ == "__main__": - main() diff --git a/Scripts/generate-manifest-schema.py b/Scripts/generate-manifest-schema.py new file mode 100644 index 0000000..440b903 --- /dev/null +++ b/Scripts/generate-manifest-schema.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +"""Compile the finite field shapes used by the shipped manifest schema.""" +import argparse,json,subprocess +from pathlib import Path +root=Path(__file__).resolve().parent.parent +source=root/'Sources/AgentsManifest/Resources/agents.schema.json' +schema=json.loads(source.read_text()) +allowed={'$schema','$id','$defs','$ref','title','description','examples','type','properties','required','additionalProperties','items','enum','const','oneOf','minimum','maxItems','maxProperties','x-agents-scalar-kind','x-agents-native-value'} +def q(s):return json.dumps(s,ensure_ascii=False) +def emit(v): + unknown=set(v)-allowed + if unknown:raise ValueError('unsupported schema keywords: '+str(unknown)) + if '$ref' in v:return '.named('+q(v['$ref'].removeprefix('#/$defs/'))+')' + if v.get('x-agents-native-value'):return '.native' + if 'oneOf' in v:return '.oneOf(['+', '.join(emit(x) for x in v['oneOf'])+'])' + if 'const' in v:return '.constant('+q(str(v['const']))+')' if isinstance(v['const'],str) else '.version' + if 'enum' in v:return '.enumeration(['+', '.join(q(x) for x in v['enum'])+'])' + kind=v['type'] + if kind=='string':return '.string' + if kind=='integer':return '.integer(minimum: '+str(v.get('minimum',-9223372036854775808))+')' + if kind=='array':return '.array('+emit(v['items'])+')' + if kind=='object': + if isinstance(v['additionalProperties'],dict):return '.dictionary('+emit(v['additionalProperties'])+')' + props=', '.join(q(k)+': '+emit(x) for k,x in v.get('properties',{}).items()) + return '.object(['+props+'], required: ['+', '.join(q(x) for x in v.get('required',[]))+'])' + raise ValueError('unsupported field shape '+kind) +text='// Generated by Scripts/generate-manifest-schema.py.\n\nenum ManifestSchema {\n static let root: YAMLRule = '+emit(schema)+'\n static let definitions: [String: YAMLRule] = [\n' +text+=''.join(' '+q(k)+': '+emit(v)+',\n' for k,v in schema['$defs'].items())+' ]\n}\n' +text=subprocess.run(['xcrun','swift-format','format','--configuration',str(root/'.swift-format')],input=text,text=True,capture_output=True,check=True).stdout +path=root/'Sources/AgentsManifest/ManifestSchema.swift' +def describe(v): + if '$ref' in v:return v['$ref'].removeprefix('#/$defs/') + if v.get('x-agents-native-value'):return 'NativeValue' + if 'const' in v:return '`'+str(v['const'])+'`' + if 'enum' in v:return ' / '.join('`'+str(x)+'`' for x in v['enum']) + if 'oneOf' in v:return 'one of: '+', '.join(describe(x) for x in v['oneOf']) + if v.get('type')=='array':return 'sequence of '+describe(v['items']) + if v.get('type')=='object':return 'name → '+describe(v['additionalProperties']) if isinstance(v.get('additionalProperties'),dict) else 'mapping' + return v.get('type','value') +help='# Manifest Field Shapes\n\nGenerated from `Sources/AgentsManifest/Resources/agents.schema.json`.\n' +for name,definition in [('Declaration',schema)]+list(schema['$defs'].items()): + help+='\n## '+name+'\n\n' + if 'properties' in definition: + help+='| Field | Required | Shape |\n| --- | --- | --- |\n' + for key,value in definition['properties'].items():help+='| `'+key+'` | '+('yes' if key in definition.get('required',[]) else '')+' | '+describe(value)+' |\n' + else:help+=describe(definition)+'\n' +help_path=root/'Documentation/Reference/ManifestSchema.md' +p=argparse.ArgumentParser();p.add_argument('--check',action='store_true');args=p.parse_args() +if args.check: + if not path.exists() or path.read_text()!=text or not help_path.exists() or help_path.read_text()!=help:raise SystemExit('generated manifest schema/help is stale') +else: + path.write_text(text) + help_path.write_text(help) diff --git a/Scripts/generate-manifest-vocabulary.py b/Scripts/generate-manifest-vocabulary.py deleted file mode 100644 index acad9a7..0000000 --- a/Scripts/generate-manifest-vocabulary.py +++ /dev/null @@ -1,181 +0,0 @@ -#!/usr/bin/env python3 -"""Generate authoring types, evaluation metadata and editor factories from one inventory.""" -import sys - -# Imports must not leave bytecode caches in the source tree. -sys.dont_write_bytecode = True - -import json -from pathlib import Path - -from manifest_generation import run_generator - -ROOT = Path(__file__).resolve().parent.parent -SPEC = json.loads((ROOT / "Scripts/ManifestVocabulary.json").read_text()) -HEADER = "// Generated from Scripts/ManifestVocabulary.json. Run Scripts/generate-manifest-vocabulary.py.\n" - - -def quoted(value): - return json.dumps(value, ensure_ascii=False) - - -def type_expression(spelling): - if spelling in SPEC["aliases"]: - return type_expression(SPEC["aliases"][spelling]) - if spelling.endswith("?"): - return ".optional(" + type_expression(spelling[:-1]) + ")" - if spelling.startswith("["): - inner = spelling[1:-1] - if inner.startswith("String: "): - return ".dictionary(" + type_expression(inner[8:]) + ")" - return ".array(" + type_expression(inner) + ")" - if spelling in SPEC["contextualTypes"]: - return ".named(" + quoted(SPEC["contextualTypes"][spelling]) + ")" - return ".named(" + quoted(spelling) + ")" - - -def parameters_declaration(parameters): - result = [] - for parameter in parameters: - label, name = parameter["label"], parameter["name"] - spelling = (label + " " if label != name else "") + name + ": " + parameter["type"] - if "default" in parameter: - spelling += " = " + parameter["default"] - result.append(spelling) - return ", ".join(result) - - -def fields_expression(parameters): - return dictionary_expression({p["name"]: p["name"] + ".constructionValue" for p in parameters}) - - -def dictionary_expression(fields): - return "[" + (", ".join(quoted(k) + ": " + v for k, v in fields.items()) or ":") + "]" - - -def literal_initializers(name): - result = [] - for kind, conversion in SPEC["literals"].get(name, {}).get("conversions", {}).items(): - payload_type = conversion.get("payloadType") - if kind == "nil": - declaration, payload = "nilLiteral: ()", None - elif kind == "array": - declaration, payload = "arrayLiteral elements: " + payload_type[1:-1] + "...", "elements" - elif kind == "dictionary": - element_type = payload_type[len("[String: "):-1] - declaration = "dictionaryLiteral elements: (String, " + element_type + ")..." - payload = "Dictionary(elements, uniquingKeysWith: { _, last in last })" - else: - declaration, payload = kind + "Literal value: " + payload_type, "value" - member = conversion["member"] - if name in SPEC["enums"]: - body = "self = ." + member + ("(" + payload + ")" if payload else "") - else: - fields = {k: ".none" if v == "nil" else v for k, v in conversion.get("defaults", {}).items()} - if payload: - fields[conversion["payload"]] = payload + ".constructionValue" - body = "self.init(value: .construct(type: " + quoted(name) + ", member: " + quoted(member) + ", fields: " + dictionary_expression(fields) + "))" - result.append(" public init(" + declaration + ") { " + body + " }") - return result - - -def authoring_source(): - lines = [HEADER] - for name, cases in SPEC["enums"].items(): - recursive = "indirect " if name in SPEC["recursiveEnums"] else "" - protocols = ["Sendable", "Equatable"] + SPEC["literals"].get(name, {}).get("protocols", []) - lines.append("public " + recursive + "enum " + name + ": " + ", ".join(protocols) + " {") - for case in cases: - parameters = case.get("parameters", []) - declaration = case["name"] - if parameters: - declaration += "(" + ", ".join((p["label"] + ": " if p["label"] != "_" else "") + p["type"] for p in parameters) + ")" - lines.append(" case " + declaration) - lines += literal_initializers(name) - lines += ["}", "", "extension " + name + ": ConstructionRepresentable {", " package var constructionValue: ConstructionValue {", " switch self {"] - for case in cases: - parameters = case.get("parameters", []) - pattern = "." + case["name"] - if parameters: - pattern += "(" + ", ".join("let " + p["name"] for p in parameters) + ")" - lines.append(" case " + pattern + ": .node(type: " + quoted(name) + ", member: " + quoted(case["name"]) + ", fields: " + fields_expression(parameters) + ")") - lines += [" }", " }", "}", ""] - for name in SPEC["structs"]: - protocols = ["Sendable", "Equatable"] + SPEC["literals"].get(name, {}).get("protocols", []) - lines += ["public struct " + name + ": " + ", ".join(protocols) + " {", " private let storage: ConstructionValue", " package var constructionValue: ConstructionValue { storage }", " package init(value: ConstructionValue) { storage = value }"] - lines += literal_initializers(name) - for factory in SPEC["factories"]: - if factory["type"] != name: - continue - member = factory["name"] - parameters = factory.get("parameters", []) - construct = "ConstructionValue.construct(type: " + quoted(name) + ", member: " + quoted(member) + ", fields: " + fields_expression(parameters) + ")" - if factory.get("property"): - declaration = "public static var " + member + ": " + name - body = "Self(value: " + construct + ")" - elif factory.get("initializer"): - declaration = "public init(" + parameters_declaration(parameters) + ")" - body = "self.init(value: " + construct + ")" - else: - declaration = "public static func " + member + "(" + parameters_declaration(parameters) + ") -> " + name - body = "Self(value: " + construct + ")" - lines.append(" " + declaration + " { " + body + " }") - lines += ["}", "extension " + name + ": ConstructionRepresentable {}", ""] - for name, spelling in SPEC["aliases"].items(): - lines += ["public typealias " + name + " = " + spelling, ""] - return "\n".join(lines) - - -def registration_source(): - type_names = SPEC["primitiveTypes"] + SPEC["customTypes"] + list(SPEC["aliases"]) + list(SPEC["enums"]) + SPEC["structs"] - lines = [HEADER, "package enum Vocabulary {", " package static let typeNames: Set = [" + ", ".join(map(quoted, type_names)) + "]", " package static let signatures: [ConstructionSignature] = ["] - enum_cases = [dict(type=name, name=case["name"], parameters=case.get("parameters", []), enumCase=True) for name, cases in SPEC["enums"].items() for case in cases] - for factory in SPEC["factories"] + enum_cases + SPEC["rangeFactories"]: - parameters = [] - for parameter in factory.get("parameters", []): - default = parameter.get("default") - value = "nil" if default is None else "(" + default + " as " + parameter["type"] + ").constructionValue" - parameters.append("ConstructionParameter(label: " + quoted(parameter["label"]) + ", name: " + quoted(parameter["name"]) + ", type: " + type_expression(parameter["type"]) + ", defaultValue: " + value + ")") - callable_member = not factory.get("property") and (not factory.get("enumCase") or bool(factory.get("parameters"))) - lines.append(" ConstructionSignature(type: " + quoted(factory["type"]) + ", member: " + quoted(factory["name"]) + ", parameters: [" + ", ".join(parameters) + "], callable: " + str(callable_member).lower() + "),") - lines += [" ]", " package static let literalTypes: [String: Set] = ["] - literal_case = lambda kind: ".nilLiteral" if kind == "nil" else "." + kind - for name, literal in SPEC["literals"].items(): - lines.append(" " + quoted(name) + ": [" + ", ".join(map(literal_case, literal["kinds"])) + "],") - lines += [" ]", " package static let literalConstructions: [String: [LiteralKind: LiteralConstruction]] = ["] - for name, literal in SPEC["literals"].items(): - if not literal["conversions"]: - continue - lines.append(" " + quoted(name) + ": [") - for kind, conversion in literal["conversions"].items(): - defaults = {k: ".none" if v == "nil" else v for k, v in conversion.get("defaults", {}).items()} - lines.append(" " + literal_case(kind) + ": LiteralConstruction(member: " + quoted(conversion["member"]) + ", payload: " + (quoted(conversion["payload"]) if "payload" in conversion else "nil") + ", payloadType: " + (type_expression(conversion["payloadType"]) if "payloadType" in conversion else "nil") + ", defaults: " + dictionary_expression(defaults) + "),") - lines.append(" ],") - lines += [" ]", " package static let scalarValues: [String: [String: String]] = ["] - for name, cases in SPEC["enums"].items(): - if all(not case.get("parameters") for case in cases): - fields = {case["name"]: quoted(case.get("loweredValue", case["name"])) for case in cases} - lines.append(" " + quoted(name) + ": " + dictionary_expression(fields) + ",") - lines += [" ]", " package static let taggedRecordTypes: Set = [" + ", ".join(map(quoted, SPEC["taggedRecordTypes"])) + "]", " package static let aliasTypes: [String: ConstructionType] = " + dictionary_expression({k: type_expression(v) for k, v in SPEC["aliases"].items()}), "}", ""] - return "\n".join(lines) - - -def editor_factories_source(): - lines = [HEADER, "import AgentsDescription", "", "extension StaticValue {"] - for factory in SPEC["staticValueFactories"]: - name, value_type = factory["name"], factory["type"] - lines += [" public static func " + name + "(_ value: AgentsDescription." + value_type + ") -> Self {", " Self.checked(value.constructionValue, type: .named(" + quoted(value_type) + "))", " }"] - return "\n".join(lines + ["}", ""]) - - -def main(): - outputs = { - Path("Sources/AgentsDescription/Vocabulary.swift"): authoring_source(), - Path("Sources/AgentsDescription/VocabularyInventory.swift"): registration_source(), - Path("Sources/AgentsManifest/StaticValueVocabulary.swift"): editor_factories_source(), - } - run_generator(outputs, repository=ROOT, generator=Path(__file__).resolve()) - - -if __name__ == "__main__": - main() diff --git a/Scripts/manifest_generation.py b/Scripts/manifest_generation.py deleted file mode 100644 index ae4f992..0000000 --- a/Scripts/manifest_generation.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Write formatted Swift sources or check committed sources for generation drift.""" -import argparse -import subprocess -import sys -import tempfile -from pathlib import Path - - -def write_generated(outputs: dict[Path, str], destination: Path, *, configuration: Path): - paths = [] - for relative, source in outputs.items(): - path = destination / relative - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(source) - paths.append(str(path)) - subprocess.run([ - "swift", "format", "format", "--in-place", "--configuration", - str(configuration), *paths, - ], check=True) - - -def check_generated(outputs: dict[Path, str], repository: Path, *, generator: Path): - scratch = repository / ".build/manifest-generation" - scratch.mkdir(parents=True, exist_ok=True) - with tempfile.TemporaryDirectory(dir=scratch) as directory: - generated = Path(directory) - write_generated(outputs, generated, configuration=repository / ".swift-format") - drift = [relative for relative in outputs - if not (repository / relative).exists() - or (repository / relative).read_bytes() != (generated / relative).read_bytes()] - if drift: - for relative in drift: - print(f"generated drift: {relative}", file=sys.stderr) - print(f"Regenerate with: python3 {generator.relative_to(repository)}", file=sys.stderr) - raise SystemExit(1) - - -def run_generator(outputs: dict[Path, str], *, repository: Path, generator: Path): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--check", action="store_true", help="fail on committed source drift") - arguments = parser.parse_args() - if arguments.check: - check_generated(outputs, repository, generator=generator) - else: - write_generated(outputs, repository, configuration=repository / ".swift-format") diff --git a/Sources/AgentsCore/StateStore.swift b/Sources/AgentsCore/StateStore.swift index 752cd78..c89bd2b 100644 --- a/Sources/AgentsCore/StateStore.swift +++ b/Sources/AgentsCore/StateStore.swift @@ -20,7 +20,7 @@ public struct StateStore: Sendable { public var watchURL: URL { directory.appendingPathComponent(Self.watchFileName) } public var cacheDirectory: URL { directory.appendingPathComponent("cache") } - package static let declarationFileName = "Agents.swift" + package static let declarationFileName = "agents.yaml" package static let resolvedFileName = "agents.resolved" package static let watchFileName = "agents.watch" /// The scope files a state transaction may replace. diff --git a/Sources/AgentsDescription/ConstructionValue.swift b/Sources/AgentsDescription/ConstructionValue.swift deleted file mode 100644 index 8eb46fb..0000000 --- a/Sources/AgentsDescription/ConstructionValue.swift +++ /dev/null @@ -1,118 +0,0 @@ -package indirect enum ConstructionType: Sendable, Hashable { - /// No contextual type: nil literals and synthesized provenance fields. - case untyped - case named(String) - case array(ConstructionType) - case dictionary(ConstructionType) - case optional(ConstructionType) - - package var unwrapped: ConstructionType { - if case .optional(let type) = self { return type } - return self - } -} - -package struct ConstructionParameter: Sendable { - package let label: String - package let name: String - package let type: ConstructionType - package let defaultValue: ConstructionValue? -} - -package struct ConstructionSignature: Sendable { - package let type: String - package let member: String - package let parameters: [ConstructionParameter] - package let callable: Bool -} - -package enum LiteralKind: String, Sendable, Hashable { - case string, integer, boolean, array, dictionary - case nilLiteral = "nil" -} - -package struct LiteralConstruction: Sendable { - package let member: String - package let payload: String? - package let payloadType: ConstructionType? - package let defaults: [String: ConstructionValue] -} - -package indirect enum ConstructionValue: Sendable, Equatable { - case text(String) - case integer(Int) - case boolean(Bool) - case none - case array([ConstructionValue]) - case object([String: ConstructionValue]) - case node(type: String, member: String, fields: [String: ConstructionValue]) - case version(Version) - case range(Range) - - package static func construct( - type: String, member: String, fields: [String: ConstructionValue] - ) -> Self { - if type == "GroupReference" { - var result = fields - if result["source"] == nil { result["source"] = ConstructionValue.none } - return .node(type: type, member: member, fields: result) - } - if type == "Source" { - var result = fields - if case .version(let lower) = result.removeValue(forKey: "from") { - result["requirement"] = .range(.upToNextMajor(from: lower)) - } else if let range = result.removeValue(forKey: "range") { - result["requirement"] = range - } else if let exact = result.removeValue(forKey: "exact") { - let value: ConstructionValue - if case .version(let version) = exact { - value = .text(version.normalized) - } else { - value = exact - } - result["requirement"] = .node( - type: "Requirement", member: "exact", fields: ["value": value]) - } else if let branch = result.removeValue(forKey: "branch") { - result["requirement"] = .node( - type: "Requirement", member: "branch", fields: ["value": branch]) - } else if let revision = result.removeValue(forKey: "revision") { - result["requirement"] = .node( - type: "Requirement", member: "revision", fields: ["value": revision]) - } else { - result["requirement"] = ConstructionValue.none - } - return .node(type: type, member: member, fields: result) - } - if type == "VersionRange", case .version(let lower) = fields["from"] { - return .range( - member == "upToNextMajor" ? .upToNextMajor(from: lower) : .upToNextMinor(from: lower)) - } - return .node(type: type, member: member, fields: fields) - } -} - -package protocol ConstructionRepresentable { - var constructionValue: ConstructionValue { get } -} -extension String: ConstructionRepresentable { - package var constructionValue: ConstructionValue { .text(self) } -} -extension Int: ConstructionRepresentable { - package var constructionValue: ConstructionValue { .integer(self) } -} -extension Bool: ConstructionRepresentable { - package var constructionValue: ConstructionValue { .boolean(self) } -} -extension Optional: ConstructionRepresentable where Wrapped: ConstructionRepresentable { - package var constructionValue: ConstructionValue { self?.constructionValue ?? .none } -} -extension Array: ConstructionRepresentable where Element: ConstructionRepresentable { - package var constructionValue: ConstructionValue { .array(map(\.constructionValue)) } -} -extension Dictionary: ConstructionRepresentable -where Key == String, Value: ConstructionRepresentable { - package var constructionValue: ConstructionValue { .object(mapValues(\.constructionValue)) } -} -extension Range: ConstructionRepresentable where Bound == Version { - package var constructionValue: ConstructionValue { .range(self) } -} diff --git a/Sources/AgentsDescription/Version.swift b/Sources/AgentsDescription/Version.swift deleted file mode 100644 index e67b049..0000000 --- a/Sources/AgentsDescription/Version.swift +++ /dev/null @@ -1,103 +0,0 @@ -/// A semantic version literal. Manifest domain validation diagnoses invalid spellings. -public struct Version: Sendable, Comparable, ExpressibleByStringLiteral { - package let major: Int - package let minor: Int - package let patch: Int - package let prerelease: [String] - package let metadata: [String] - package let valid: Bool - package let normalized: String - - public init(stringLiteral value: String) { - var body = value.drop(while: \.isWhitespace) - while body.last?.isWhitespace == true { body = body.dropLast() } - if body.first == "v" || body.first == "V" { body = body.dropFirst() } - let builds = body.split(separator: "+", maxSplits: 1, omittingEmptySubsequences: false) - let releases = builds[0].split(separator: "-", maxSplits: 1, omittingEmptySubsequences: false) - let numbers = releases[0].split(separator: ".", omittingEmptySubsequences: false) - let parsed = numbers.map { Int($0) } - let pre = - releases.count == 2 - ? releases[1].split(separator: ".", omittingEmptySubsequences: false).map(String.init) : [] - let meta = - builds.count == 2 - ? builds[1].split(separator: ".", omittingEmptySubsequences: false).map(String.init) : [] - major = parsed.first.flatMap { $0 } ?? 0 - minor = parsed.count > 1 ? parsed[1] ?? 0 : 0 - patch = parsed.count > 2 ? parsed[2] ?? 0 : 0 - prerelease = pre - metadata = meta - valid = - numbers.count == 3 && parsed.allSatisfy { $0 != nil } - && numbers.allSatisfy { Self.numeric(String($0)) && ($0.count == 1 || !$0.hasPrefix("0")) } - && pre.allSatisfy { - Self.identifier($0) && (!Self.numeric($0) || $0.count == 1 || !$0.hasPrefix("0")) - } - && meta.allSatisfy(Self.identifier) - normalized = String(body) - } - - private init(major: Int, minor: Int, patch: Int, valid: Bool = true) { - self.major = major - self.minor = minor - self.patch = patch - prerelease = [] - metadata = [] - self.valid = valid - normalized = "\(major).\(minor).\(patch)" - } - - public static func == (lhs: Version, rhs: Version) -> Bool { - lhs.major == rhs.major && lhs.minor == rhs.minor && lhs.patch == rhs.patch - && lhs.prerelease == rhs.prerelease && lhs.valid == rhs.valid - } - - public static func < (lhs: Version, rhs: Version) -> Bool { - if lhs.major != rhs.major { return lhs.major < rhs.major } - if lhs.minor != rhs.minor { return lhs.minor < rhs.minor } - if lhs.patch != rhs.patch { return lhs.patch < rhs.patch } - if lhs.prerelease.isEmpty || rhs.prerelease.isEmpty { - return !lhs.prerelease.isEmpty && rhs.prerelease.isEmpty - } - for (left, right) in zip(lhs.prerelease, rhs.prerelease) { - if left == right { continue } - let ln = numeric(left) - let rn = numeric(right) - if ln && rn && left.count != right.count { return left.count < right.count } - if ln != rn { return ln } - return left < right - } - return lhs.prerelease.count < rhs.prerelease.count - } - - package func successor(major incrementMajor: Bool) -> Version { - let (next, overflow) = (incrementMajor ? major : minor).addingReportingOverflow(1) - if overflow || !valid { return Version(major: major, minor: minor, patch: patch, valid: false) } - return Version(major: incrementMajor ? next : major, minor: incrementMajor ? 0 : next, patch: 0) - } - - private static func numeric(_ value: String) -> Bool { - !value.isEmpty && value.utf8.allSatisfy { (48...57).contains($0) } - } - - private static func identifier(_ value: String) -> Bool { - !value.isEmpty - && value.utf8.allSatisfy { - $0 == 45 || (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) - } - } -} - -extension Version: ConstructionRepresentable { - package var constructionValue: ConstructionValue { .version(self) } -} - -extension Range where Bound == Version { - public static func upToNextMajor(from version: Version) -> Range { - Range(uncheckedBounds: (version, version.successor(major: true))) - } - - public static func upToNextMinor(from version: Version) -> Range { - Range(uncheckedBounds: (version, version.successor(major: false))) - } -} diff --git a/Sources/AgentsDescription/Vocabulary.swift b/Sources/AgentsDescription/Vocabulary.swift deleted file mode 100644 index c0f2c0b..0000000 --- a/Sources/AgentsDescription/Vocabulary.swift +++ /dev/null @@ -1,862 +0,0 @@ -// Generated from Scripts/ManifestVocabulary.json. Run Scripts/generate-manifest-vocabulary.py. - -public enum Agent: Sendable, Equatable { - case claudeCode - case codex - case cursor - case geminiCLI - case openCode -} - -extension Agent: ConstructionRepresentable { - package var constructionValue: ConstructionValue { - switch self { - case .claudeCode: .node(type: "Agent", member: "claudeCode", fields: [:]) - case .codex: .node(type: "Agent", member: "codex", fields: [:]) - case .cursor: .node(type: "Agent", member: "cursor", fields: [:]) - case .geminiCLI: .node(type: "Agent", member: "geminiCLI", fields: [:]) - case .openCode: .node(type: "Agent", member: "openCode", fields: [:]) - } - } -} - -public enum Scope: Sendable, Equatable { - case project - case user -} - -extension Scope: ConstructionRepresentable { - package var constructionValue: ConstructionValue { - switch self { - case .project: .node(type: "Scope", member: "project", fields: [:]) - case .user: .node(type: "Scope", member: "user", fields: [:]) - } - } -} - -public enum Platform: Sendable, Equatable { - case macOS - case linux -} - -extension Platform: ConstructionRepresentable { - package var constructionValue: ConstructionValue { - switch self { - case .macOS: .node(type: "Platform", member: "macOS", fields: [:]) - case .linux: .node(type: "Platform", member: "linux", fields: [:]) - } - } -} - -public enum InstallMode: Sendable, Equatable { - case link - case copy - case edit -} - -extension InstallMode: ConstructionRepresentable { - package var constructionValue: ConstructionValue { - switch self { - case .link: .node(type: "InstallMode", member: "link", fields: [:]) - case .copy: .node(type: "InstallMode", member: "copy", fields: [:]) - case .edit: .node(type: "InstallMode", member: "edit", fields: [:]) - } - } -} - -public enum RuntimeValue: Sendable, Equatable, ExpressibleByStringLiteral { - case literal(String) - case environment(String) - case secret(String) - public init(stringLiteral value: String) { self = .literal(value) } -} - -extension RuntimeValue: ConstructionRepresentable { - package var constructionValue: ConstructionValue { - switch self { - case .literal(let value): - .node(type: "RuntimeValue", member: "literal", fields: ["value": value.constructionValue]) - case .environment(let value): - .node(type: "RuntimeValue", member: "environment", fields: ["value": value.constructionValue]) - case .secret(let value): - .node(type: "RuntimeValue", member: "secret", fields: ["value": value.constructionValue]) - } - } -} - -public indirect enum ConfigurationValue: Sendable, Equatable, ExpressibleByStringLiteral, - ExpressibleByIntegerLiteral, ExpressibleByBooleanLiteral, ExpressibleByNilLiteral, - ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral -{ - case string(String) - case integer(Int) - case decimal(String) - case boolean(Bool) - case null - case array([ConfigurationValue]) - case object([String: ConfigurationValue]) - public init(stringLiteral value: String) { self = .string(value) } - public init(integerLiteral value: Int) { self = .integer(value) } - public init(booleanLiteral value: Bool) { self = .boolean(value) } - public init(nilLiteral: ()) { self = .null } - public init(arrayLiteral elements: ConfigurationValue...) { self = .array(elements) } - public init(dictionaryLiteral elements: (String, ConfigurationValue)...) { - self = .object(Dictionary(elements, uniquingKeysWith: { _, last in last })) - } -} - -extension ConfigurationValue: ConstructionRepresentable { - package var constructionValue: ConstructionValue { - switch self { - case .string(let value): - .node( - type: "ConfigurationValue", member: "string", fields: ["value": value.constructionValue]) - case .integer(let value): - .node( - type: "ConfigurationValue", member: "integer", fields: ["value": value.constructionValue]) - case .decimal(let value): - .node( - type: "ConfigurationValue", member: "decimal", fields: ["value": value.constructionValue]) - case .boolean(let value): - .node( - type: "ConfigurationValue", member: "boolean", fields: ["value": value.constructionValue]) - case .null: .node(type: "ConfigurationValue", member: "null", fields: [:]) - case .array(let value): - .node(type: "ConfigurationValue", member: "array", fields: ["value": value.constructionValue]) - case .object(let value): - .node( - type: "ConfigurationValue", member: "object", fields: ["value": value.constructionValue]) - } - } -} - -public enum HookEvent: Sendable, Equatable { - case beforeTool - case afterTool - case sessionStart - case sessionEnd - case native(String) -} - -extension HookEvent: ConstructionRepresentable { - package var constructionValue: ConstructionValue { - switch self { - case .beforeTool: .node(type: "HookEvent", member: "beforeTool", fields: [:]) - case .afterTool: .node(type: "HookEvent", member: "afterTool", fields: [:]) - case .sessionStart: .node(type: "HookEvent", member: "sessionStart", fields: [:]) - case .sessionEnd: .node(type: "HookEvent", member: "sessionEnd", fields: [:]) - case .native(let value): - .node(type: "HookEvent", member: "native", fields: ["value": value.constructionValue]) - } - } -} - -public enum PermissionOperation: Sendable, Equatable { - case read - case write - case execute - case tool(String) -} - -extension PermissionOperation: ConstructionRepresentable { - package var constructionValue: ConstructionValue { - switch self { - case .read: .node(type: "PermissionOperation", member: "read", fields: [:]) - case .write: .node(type: "PermissionOperation", member: "write", fields: [:]) - case .execute: .node(type: "PermissionOperation", member: "execute", fields: [:]) - case .tool(let value): - .node(type: "PermissionOperation", member: "tool", fields: ["value": value.constructionValue]) - } - } -} - -public enum IgnorePurpose: Sendable, Equatable { - case context - case indexing -} - -extension IgnorePurpose: ConstructionRepresentable { - package var constructionValue: ConstructionValue { - switch self { - case .context: .node(type: "IgnorePurpose", member: "context", fields: [:]) - case .indexing: .node(type: "IgnorePurpose", member: "indexing", fields: [:]) - } - } -} - -public enum PluginMode: Sendable, Equatable { - case native - case components -} - -extension PluginMode: ConstructionRepresentable { - package var constructionValue: ConstructionValue { - switch self { - case .native: .node(type: "PluginMode", member: "native", fields: [:]) - case .components: .node(type: "PluginMode", member: "components", fields: [:]) - } - } -} - -public enum ComponentKind: Sendable, Equatable { - case skills - case instructions - case mcpServer - case hook - case subagent - case command - case lspServer - case permissions - case ignore - case plugin -} - -extension ComponentKind: ConstructionRepresentable { - package var constructionValue: ConstructionValue { - switch self { - case .skills: .node(type: "ComponentKind", member: "skills", fields: [:]) - case .instructions: .node(type: "ComponentKind", member: "instructions", fields: [:]) - case .mcpServer: .node(type: "ComponentKind", member: "mcpServer", fields: [:]) - case .hook: .node(type: "ComponentKind", member: "hook", fields: [:]) - case .subagent: .node(type: "ComponentKind", member: "subagent", fields: [:]) - case .command: .node(type: "ComponentKind", member: "command", fields: [:]) - case .lspServer: .node(type: "ComponentKind", member: "lspServer", fields: [:]) - case .permissions: .node(type: "ComponentKind", member: "permissions", fields: [:]) - case .ignore: .node(type: "ComponentKind", member: "ignore", fields: [:]) - case .plugin: .node(type: "ComponentKind", member: "plugin", fields: [:]) - } - } -} - -public enum ComponentReference: Sendable, Equatable { - case skill(name: String) - case instruction(name: String) - case mcpServer(name: String) - case hook(name: String) - case subagent(name: String) - case command(name: String) - case lspServer(name: String) - case permissions(name: String) - case ignore(name: String) - case plugin(name: String) -} - -extension ComponentReference: ConstructionRepresentable { - package var constructionValue: ConstructionValue { - switch self { - case .skill(let name): - .node(type: "ComponentReference", member: "skill", fields: ["name": name.constructionValue]) - case .instruction(let name): - .node( - type: "ComponentReference", member: "instruction", fields: ["name": name.constructionValue]) - case .mcpServer(let name): - .node( - type: "ComponentReference", member: "mcpServer", fields: ["name": name.constructionValue]) - case .hook(let name): - .node(type: "ComponentReference", member: "hook", fields: ["name": name.constructionValue]) - case .subagent(let name): - .node( - type: "ComponentReference", member: "subagent", fields: ["name": name.constructionValue]) - case .command(let name): - .node(type: "ComponentReference", member: "command", fields: ["name": name.constructionValue]) - case .lspServer(let name): - .node( - type: "ComponentReference", member: "lspServer", fields: ["name": name.constructionValue]) - case .permissions(let name): - .node( - type: "ComponentReference", member: "permissions", fields: ["name": name.constructionValue]) - case .ignore(let name): - .node(type: "ComponentReference", member: "ignore", fields: ["name": name.constructionValue]) - case .plugin(let name): - .node(type: "ComponentReference", member: "plugin", fields: ["name": name.constructionValue]) - } - } -} - -public struct Condition: Sendable, Equatable { - private let storage: ConstructionValue - package var constructionValue: ConstructionValue { storage } - package init(value: ConstructionValue) { storage = value } - public static func when( - agents: [Agent]? = nil, scopes: [Scope]? = nil, platforms: [Platform]? = nil - ) -> Condition { - Self( - value: ConstructionValue.construct( - type: "Condition", member: "when", - fields: [ - "agents": agents.constructionValue, "scopes": scopes.constructionValue, - "platforms": platforms.constructionValue, - ])) - } -} -extension Condition: ConstructionRepresentable {} - -public struct Agents: Sendable, Equatable { - private let storage: ConstructionValue - package var constructionValue: ConstructionValue { storage } - package init(value: ConstructionValue) { storage = value } - public init( - defaultAgents: [Agent]? = nil, exports: [String] = [], sources: [Source] = [], - components: [Component] = [], groups: [ComponentGroup] = [], uses: [GroupReference] = [], - watch: [String] = [] - ) { - self.init( - value: ConstructionValue.construct( - type: "Agents", member: "Agents", - fields: [ - "defaultAgents": defaultAgents.constructionValue, "exports": exports.constructionValue, - "sources": sources.constructionValue, "components": components.constructionValue, - "groups": groups.constructionValue, "uses": uses.constructionValue, - "watch": watch.constructionValue, - ])) - } -} -extension Agents: ConstructionRepresentable {} - -public struct Source: Sendable, Equatable { - private let storage: ConstructionValue - package var constructionValue: ConstructionValue { storage } - package init(value: ConstructionValue) { storage = value } - public static func source(name: String, url: String, subpath: String? = nil) -> Source { - Self( - value: ConstructionValue.construct( - type: "Source", member: "source", - fields: [ - "name": name.constructionValue, "url": url.constructionValue, - "subpath": subpath.constructionValue, - ])) - } - public static func source(name: String, url: String, from: Version, subpath: String? = nil) - -> Source - { - Self( - value: ConstructionValue.construct( - type: "Source", member: "source", - fields: [ - "name": name.constructionValue, "url": url.constructionValue, - "from": from.constructionValue, "subpath": subpath.constructionValue, - ])) - } - public static func source(name: String, url: String, exact: Version, subpath: String? = nil) - -> Source - { - Self( - value: ConstructionValue.construct( - type: "Source", member: "source", - fields: [ - "name": name.constructionValue, "url": url.constructionValue, - "exact": exact.constructionValue, "subpath": subpath.constructionValue, - ])) - } - public static func source(name: String, url: String, branch: String, subpath: String? = nil) - -> Source - { - Self( - value: ConstructionValue.construct( - type: "Source", member: "source", - fields: [ - "name": name.constructionValue, "url": url.constructionValue, - "branch": branch.constructionValue, "subpath": subpath.constructionValue, - ])) - } - public static func source(name: String, url: String, revision: String, subpath: String? = nil) - -> Source - { - Self( - value: ConstructionValue.construct( - type: "Source", member: "source", - fields: [ - "name": name.constructionValue, "url": url.constructionValue, - "revision": revision.constructionValue, "subpath": subpath.constructionValue, - ])) - } - public static func source( - name: String, url: String, _ range: Range, subpath: String? = nil - ) -> Source { - Self( - value: ConstructionValue.construct( - type: "Source", member: "source", - fields: [ - "name": name.constructionValue, "url": url.constructionValue, - "range": range.constructionValue, "subpath": subpath.constructionValue, - ])) - } - public static func source(name: String, path: String, subpath: String? = nil) -> Source { - Self( - value: ConstructionValue.construct( - type: "Source", member: "source", - fields: [ - "name": name.constructionValue, "path": path.constructionValue, - "subpath": subpath.constructionValue, - ])) - } - public static func source(name: String, path: String, from: Version, subpath: String? = nil) - -> Source - { - Self( - value: ConstructionValue.construct( - type: "Source", member: "source", - fields: [ - "name": name.constructionValue, "path": path.constructionValue, - "from": from.constructionValue, "subpath": subpath.constructionValue, - ])) - } - public static func source(name: String, path: String, exact: Version, subpath: String? = nil) - -> Source - { - Self( - value: ConstructionValue.construct( - type: "Source", member: "source", - fields: [ - "name": name.constructionValue, "path": path.constructionValue, - "exact": exact.constructionValue, "subpath": subpath.constructionValue, - ])) - } - public static func source(name: String, path: String, branch: String, subpath: String? = nil) - -> Source - { - Self( - value: ConstructionValue.construct( - type: "Source", member: "source", - fields: [ - "name": name.constructionValue, "path": path.constructionValue, - "branch": branch.constructionValue, "subpath": subpath.constructionValue, - ])) - } - public static func source(name: String, path: String, revision: String, subpath: String? = nil) - -> Source - { - Self( - value: ConstructionValue.construct( - type: "Source", member: "source", - fields: [ - "name": name.constructionValue, "path": path.constructionValue, - "revision": revision.constructionValue, "subpath": subpath.constructionValue, - ])) - } - public static func source( - name: String, path: String, _ range: Range, subpath: String? = nil - ) -> Source { - Self( - value: ConstructionValue.construct( - type: "Source", member: "source", - fields: [ - "name": name.constructionValue, "path": path.constructionValue, - "range": range.constructionValue, "subpath": subpath.constructionValue, - ])) - } - public static func source(name: String, index: String, subpath: String? = nil) -> Source { - Self( - value: ConstructionValue.construct( - type: "Source", member: "source", - fields: [ - "name": name.constructionValue, "index": index.constructionValue, - "subpath": subpath.constructionValue, - ])) - } -} -extension Source: ConstructionRepresentable {} - -public struct ComponentGroup: Sendable, Equatable { - private let storage: ConstructionValue - package var constructionValue: ConstructionValue { storage } - package init(value: ConstructionValue) { storage = value } - public static func group( - name: String, components: [Component] = [], uses: [GroupReference] = [], - condition: Condition? = nil - ) -> ComponentGroup { - Self( - value: ConstructionValue.construct( - type: "ComponentGroup", member: "group", - fields: [ - "name": name.constructionValue, "components": components.constructionValue, - "uses": uses.constructionValue, "condition": condition.constructionValue, - ])) - } -} -extension ComponentGroup: ConstructionRepresentable {} - -public struct GroupReference: Sendable, Equatable, ExpressibleByStringLiteral { - private let storage: ConstructionValue - package var constructionValue: ConstructionValue { storage } - package init(value: ConstructionValue) { storage = value } - public init(stringLiteral value: String) { - self.init( - value: .construct( - type: "GroupReference", member: "group", - fields: ["source": .none, "condition": .none, "name": value.constructionValue])) - } - public static func group(name: String, condition: Condition? = nil) -> GroupReference { - Self( - value: ConstructionValue.construct( - type: "GroupReference", member: "group", - fields: ["name": name.constructionValue, "condition": condition.constructionValue])) - } - public static func group(name: String, source: String, condition: Condition? = nil) - -> GroupReference - { - Self( - value: ConstructionValue.construct( - type: "GroupReference", member: "group", - fields: [ - "name": name.constructionValue, "source": source.constructionValue, - "condition": condition.constructionValue, - ])) - } -} -extension GroupReference: ConstructionRepresentable {} - -public struct SkillSelection: Sendable, Equatable, ExpressibleByArrayLiteral { - private let storage: ConstructionValue - package var constructionValue: ConstructionValue { storage } - package init(value: ConstructionValue) { storage = value } - public init(arrayLiteral elements: String...) { - self.init( - value: .construct( - type: "SkillSelection", member: "names", fields: ["names": elements.constructionValue])) - } - public static var all: SkillSelection { - Self(value: ConstructionValue.construct(type: "SkillSelection", member: "all", fields: [:])) - } -} -extension SkillSelection: ConstructionRepresentable {} - -public struct SkillOverride: Sendable, Equatable { - private let storage: ConstructionValue - package var constructionValue: ConstructionValue { storage } - package init(value: ConstructionValue) { storage = value } - public static func skill(name: String, mode: InstallMode? = nil, agents: [Agent]? = nil) - -> SkillOverride - { - Self( - value: ConstructionValue.construct( - type: "SkillOverride", member: "skill", - fields: [ - "name": name.constructionValue, "mode": mode.constructionValue, - "agents": agents.constructionValue, - ])) - } -} -extension SkillOverride: ConstructionRepresentable {} - -public struct SectionReference: Sendable, Equatable, ExpressibleByStringLiteral { - private let storage: ConstructionValue - package var constructionValue: ConstructionValue { storage } - package init(value: ConstructionValue) { storage = value } - public init(stringLiteral value: String) { - self.init( - value: .construct( - type: "SectionReference", member: "section", - fields: ["source": .none, "condition": .none, "name": value.constructionValue])) - } - public static func section(name: String, source: String? = nil, condition: Condition? = nil) - -> SectionReference - { - Self( - value: ConstructionValue.construct( - type: "SectionReference", member: "section", - fields: [ - "name": name.constructionValue, "source": source.constructionValue, - "condition": condition.constructionValue, - ])) - } -} -extension SectionReference: ConstructionRepresentable {} - -public struct ChatGPTPrompt: Sendable, Equatable { - private let storage: ConstructionValue - package var constructionValue: ConstructionValue { storage } - package init(value: ConstructionValue) { storage = value } - public static func prompt( - name: String, sections: [SectionReference], append: String? = nil, condition: Condition? = nil - ) -> ChatGPTPrompt { - Self( - value: ConstructionValue.construct( - type: "ChatGPTPrompt", member: "prompt", - fields: [ - "name": name.constructionValue, "sections": sections.constructionValue, - "append": append.constructionValue, "condition": condition.constructionValue, - ])) - } -} -extension ChatGPTPrompt: ConstructionRepresentable {} - -public struct Resource: Sendable, Equatable { - private let storage: ConstructionValue - package var constructionValue: ConstructionValue { storage } - package init(value: ConstructionValue) { storage = value } - public static func path(_ path: String, source: String? = nil) -> Resource { - Self( - value: ConstructionValue.construct( - type: "Resource", member: "path", - fields: ["path": path.constructionValue, "source": source.constructionValue])) - } -} -extension Resource: ConstructionRepresentable {} - -public struct PromptContent: Sendable, Equatable, ExpressibleByStringLiteral { - private let storage: ConstructionValue - package var constructionValue: ConstructionValue { storage } - package init(value: ConstructionValue) { storage = value } - public init(stringLiteral value: String) { - self.init( - value: .construct( - type: "PromptContent", member: "literal", fields: ["value": value.constructionValue])) - } - public static func file(_ path: String, source: String? = nil) -> PromptContent { - Self( - value: ConstructionValue.construct( - type: "PromptContent", member: "file", - fields: ["path": path.constructionValue, "source": source.constructionValue])) - } -} -extension PromptContent: ConstructionRepresentable {} - -public struct ExecutableInvocation: Sendable, Equatable { - private let storage: ConstructionValue - package var constructionValue: ConstructionValue { storage } - package init(value: ConstructionValue) { storage = value } - public static func executable( - _ executable: String, arguments: [String] = [], environment: [String: RuntimeValue] = [:], - workingDirectory: Resource? = nil - ) -> ExecutableInvocation { - Self( - value: ConstructionValue.construct( - type: "ExecutableInvocation", member: "executable", - fields: [ - "executable": executable.constructionValue, "arguments": arguments.constructionValue, - "environment": environment.constructionValue, - "workingDirectory": workingDirectory.constructionValue, - ])) - } -} -extension ExecutableInvocation: ConstructionRepresentable {} - -public struct MCPTransport: Sendable, Equatable { - private let storage: ConstructionValue - package var constructionValue: ConstructionValue { storage } - package init(value: ConstructionValue) { storage = value } - public static func stdio( - _ executable: String, arguments: [String] = [], environment: [String: RuntimeValue] = [:], - workingDirectory: Resource? = nil - ) -> MCPTransport { - Self( - value: ConstructionValue.construct( - type: "MCPTransport", member: "stdio", - fields: [ - "executable": executable.constructionValue, "arguments": arguments.constructionValue, - "environment": environment.constructionValue, - "workingDirectory": workingDirectory.constructionValue, - ])) - } - public static func streamableHTTP(url: String, headers: [String: RuntimeValue] = [:]) - -> MCPTransport - { - Self( - value: ConstructionValue.construct( - type: "MCPTransport", member: "streamableHTTP", - fields: ["url": url.constructionValue, "headers": headers.constructionValue])) - } - public static func sse(url: String, headers: [String: RuntimeValue] = [:]) -> MCPTransport { - Self( - value: ConstructionValue.construct( - type: "MCPTransport", member: "sse", - fields: ["url": url.constructionValue, "headers": headers.constructionValue])) - } -} -extension MCPTransport: ConstructionRepresentable {} - -public struct PromptParameter: Sendable, Equatable { - private let storage: ConstructionValue - package var constructionValue: ConstructionValue { storage } - package init(value: ConstructionValue) { storage = value } - public static func parameter(name: String, description: String, defaultValue: String? = nil) - -> PromptParameter - { - Self( - value: ConstructionValue.construct( - type: "PromptParameter", member: "parameter", - fields: [ - "name": name.constructionValue, "description": description.constructionValue, - "defaultValue": defaultValue.constructionValue, - ])) - } -} -extension PromptParameter: ConstructionRepresentable {} - -public struct PermissionRule: Sendable, Equatable { - private let storage: ConstructionValue - package var constructionValue: ConstructionValue { storage } - package init(value: ConstructionValue) { storage = value } - public static func allow(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule { - Self( - value: ConstructionValue.construct( - type: "PermissionRule", member: "allow", - fields: ["operation": operation.constructionValue, "pattern": pattern.constructionValue])) - } - public static func ask(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule { - Self( - value: ConstructionValue.construct( - type: "PermissionRule", member: "ask", - fields: ["operation": operation.constructionValue, "pattern": pattern.constructionValue])) - } - public static func deny(_ operation: PermissionOperation, _ pattern: String) -> PermissionRule { - Self( - value: ConstructionValue.construct( - type: "PermissionRule", member: "deny", - fields: ["operation": operation.constructionValue, "pattern": pattern.constructionValue])) - } -} -extension PermissionRule: ConstructionRepresentable {} - -public struct Component: Sendable, Equatable { - private let storage: ConstructionValue - package var constructionValue: ConstructionValue { storage } - package init(value: ConstructionValue) { storage = value } - public static func skills( - source: String, select: SkillSelection = .all, exclude: [String] = [], mode: InstallMode? = nil, - overrides: [SkillOverride] = [], agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component { - Self( - value: ConstructionValue.construct( - type: "Component", member: "skills", - fields: [ - "source": source.constructionValue, "select": select.constructionValue, - "exclude": exclude.constructionValue, "mode": mode.constructionValue, - "overrides": overrides.constructionValue, "agents": agents.constructionValue, - "condition": condition.constructionValue, "native": native.constructionValue, - ])) - } - public static func instructions( - sections: [SectionReference] = [], chatGPT: [ChatGPTPrompt] = [], agents: [Agent]? = nil, - condition: Condition? = nil, native: NativeConfiguration = [:] - ) -> Component { - Self( - value: ConstructionValue.construct( - type: "Component", member: "instructions", - fields: [ - "sections": sections.constructionValue, "chatGPT": chatGPT.constructionValue, - "agents": agents.constructionValue, "condition": condition.constructionValue, - "native": native.constructionValue, - ])) - } - public static func mcpServer( - name: String, transport: MCPTransport, agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component { - Self( - value: ConstructionValue.construct( - type: "Component", member: "mcpServer", - fields: [ - "name": name.constructionValue, "transport": transport.constructionValue, - "agents": agents.constructionValue, "condition": condition.constructionValue, - "native": native.constructionValue, - ])) - } - public static func hook( - name: String, event: HookEvent, run: ExecutableInvocation, matcher: String? = nil, - timeoutSeconds: Int? = nil, agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component { - Self( - value: ConstructionValue.construct( - type: "Component", member: "hook", - fields: [ - "name": name.constructionValue, "event": event.constructionValue, - "run": run.constructionValue, "matcher": matcher.constructionValue, - "timeoutSeconds": timeoutSeconds.constructionValue, "agents": agents.constructionValue, - "condition": condition.constructionValue, "native": native.constructionValue, - ])) - } - public static func subagent( - name: String, description: String, prompt: PromptContent, model: String? = nil, - tools: [String]? = nil, agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component { - Self( - value: ConstructionValue.construct( - type: "Component", member: "subagent", - fields: [ - "name": name.constructionValue, "description": description.constructionValue, - "prompt": prompt.constructionValue, "model": model.constructionValue, - "tools": tools.constructionValue, "agents": agents.constructionValue, - "condition": condition.constructionValue, "native": native.constructionValue, - ])) - } - public static func command( - name: String, description: String, prompt: PromptContent, parameters: [PromptParameter] = [], - agents: [Agent]? = nil, condition: Condition? = nil, native: NativeConfiguration = [:] - ) -> Component { - Self( - value: ConstructionValue.construct( - type: "Component", member: "command", - fields: [ - "name": name.constructionValue, "description": description.constructionValue, - "prompt": prompt.constructionValue, "parameters": parameters.constructionValue, - "agents": agents.constructionValue, "condition": condition.constructionValue, - "native": native.constructionValue, - ])) - } - public static func lspServer( - name: String, run: ExecutableInvocation, languages: [String: String], - initializationOptions: [String: ConfigurationValue] = [:], agents: [Agent]? = nil, - condition: Condition? = nil, native: NativeConfiguration = [:] - ) -> Component { - Self( - value: ConstructionValue.construct( - type: "Component", member: "lspServer", - fields: [ - "name": name.constructionValue, "run": run.constructionValue, - "languages": languages.constructionValue, - "initializationOptions": initializationOptions.constructionValue, - "agents": agents.constructionValue, "condition": condition.constructionValue, - "native": native.constructionValue, - ])) - } - public static func permissions( - name: String, rules: [PermissionRule], agents: [Agent]? = nil, condition: Condition? = nil, - native: NativeConfiguration = [:] - ) -> Component { - Self( - value: ConstructionValue.construct( - type: "Component", member: "permissions", - fields: [ - "name": name.constructionValue, "rules": rules.constructionValue, - "agents": agents.constructionValue, "condition": condition.constructionValue, - "native": native.constructionValue, - ])) - } - public static func ignore( - name: String, patterns: [String], purpose: IgnorePurpose = .context, agents: [Agent]? = nil, - condition: Condition? = nil, native: NativeConfiguration = [:] - ) -> Component { - Self( - value: ConstructionValue.construct( - type: "Component", member: "ignore", - fields: [ - "name": name.constructionValue, "patterns": patterns.constructionValue, - "purpose": purpose.constructionValue, "agents": agents.constructionValue, - "condition": condition.constructionValue, "native": native.constructionValue, - ])) - } - public static func plugin( - name: String, path: String, source: String, mode: PluginMode = .components, - select: [ComponentKind]? = nil, exclude: [ComponentReference] = [], agents: [Agent]? = nil, - condition: Condition? = nil, native: NativeConfiguration = [:] - ) -> Component { - Self( - value: ConstructionValue.construct( - type: "Component", member: "plugin", - fields: [ - "name": name.constructionValue, "path": path.constructionValue, - "source": source.constructionValue, "mode": mode.constructionValue, - "select": select.constructionValue, "exclude": exclude.constructionValue, - "agents": agents.constructionValue, "condition": condition.constructionValue, - "native": native.constructionValue, - ])) - } -} -extension Component: ConstructionRepresentable {} - -public typealias NativeConfiguration = [String: [String: ConfigurationValue]] diff --git a/Sources/AgentsDescription/VocabularyInventory.swift b/Sources/AgentsDescription/VocabularyInventory.swift deleted file mode 100644 index f72ee30..0000000 --- a/Sources/AgentsDescription/VocabularyInventory.swift +++ /dev/null @@ -1,866 +0,0 @@ -// Generated from Scripts/ManifestVocabulary.json. Run Scripts/generate-manifest-vocabulary.py. - -package enum Vocabulary { - package static let typeNames: Set = [ - "String", "Int", "Bool", "Version", "NativeConfiguration", "Agent", "Scope", "Platform", - "InstallMode", "RuntimeValue", "ConfigurationValue", "HookEvent", "PermissionOperation", - "IgnorePurpose", "PluginMode", "ComponentKind", "ComponentReference", "Condition", "Agents", - "Source", "ComponentGroup", "GroupReference", "SkillSelection", "SkillOverride", - "SectionReference", "ChatGPTPrompt", "Resource", "PromptContent", "ExecutableInvocation", - "MCPTransport", "PromptParameter", "PermissionRule", "Component", - ] - package static let signatures: [ConstructionSignature] = [ - ConstructionSignature( - type: "Condition", member: "when", - parameters: [ - ConstructionParameter( - label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), - ConstructionParameter( - label: "scopes", name: "scopes", type: .optional(.array(.named("Scope"))), - defaultValue: (nil as [Scope]?).constructionValue), - ConstructionParameter( - label: "platforms", name: "platforms", type: .optional(.array(.named("Platform"))), - defaultValue: (nil as [Platform]?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Agents", member: "Agents", - parameters: [ - ConstructionParameter( - label: "defaultAgents", name: "defaultAgents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), - ConstructionParameter( - label: "exports", name: "exports", type: .array(.named("String")), - defaultValue: ([] as [String]).constructionValue), - ConstructionParameter( - label: "sources", name: "sources", type: .array(.named("Source")), - defaultValue: ([] as [Source]).constructionValue), - ConstructionParameter( - label: "components", name: "components", type: .array(.named("Component")), - defaultValue: ([] as [Component]).constructionValue), - ConstructionParameter( - label: "groups", name: "groups", type: .array(.named("ComponentGroup")), - defaultValue: ([] as [ComponentGroup]).constructionValue), - ConstructionParameter( - label: "uses", name: "uses", type: .array(.named("GroupReference")), - defaultValue: ([] as [GroupReference]).constructionValue), - ConstructionParameter( - label: "watch", name: "watch", type: .array(.named("String")), - defaultValue: ([] as [String]).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Source", member: "source", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Source", member: "source", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "from", name: "from", type: .named("Version"), defaultValue: nil), - ConstructionParameter( - label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Source", member: "source", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "exact", name: "exact", type: .named("Version"), defaultValue: nil), - ConstructionParameter( - label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Source", member: "source", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "branch", name: "branch", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Source", member: "source", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "revision", name: "revision", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Source", member: "source", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "_", name: "range", type: .named("VersionRange"), defaultValue: nil), - ConstructionParameter( - label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Source", member: "source", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Source", member: "source", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "from", name: "from", type: .named("Version"), defaultValue: nil), - ConstructionParameter( - label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Source", member: "source", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "exact", name: "exact", type: .named("Version"), defaultValue: nil), - ConstructionParameter( - label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Source", member: "source", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "branch", name: "branch", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Source", member: "source", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "revision", name: "revision", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Source", member: "source", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "_", name: "range", type: .named("VersionRange"), defaultValue: nil), - ConstructionParameter( - label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Source", member: "source", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "index", name: "index", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "subpath", name: "subpath", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "ComponentGroup", member: "group", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "components", name: "components", type: .array(.named("Component")), - defaultValue: ([] as [Component]).constructionValue), - ConstructionParameter( - label: "uses", name: "uses", type: .array(.named("GroupReference")), - defaultValue: ([] as [GroupReference]).constructionValue), - ConstructionParameter( - label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "GroupReference", member: "group", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "GroupReference", member: "group", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "source", name: "source", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), - ], callable: true), - ConstructionSignature(type: "SkillSelection", member: "all", parameters: [], callable: false), - ConstructionSignature( - type: "SkillOverride", member: "skill", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "mode", name: "mode", type: .optional(.named("InstallMode")), - defaultValue: (nil as InstallMode?).constructionValue), - ConstructionParameter( - label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "SectionReference", member: "section", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "source", name: "source", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ConstructionParameter( - label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "ChatGPTPrompt", member: "prompt", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "sections", name: "sections", type: .array(.named("SectionReference")), - defaultValue: nil), - ConstructionParameter( - label: "append", name: "append", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ConstructionParameter( - label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Resource", member: "path", - parameters: [ - ConstructionParameter(label: "_", name: "path", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "source", name: "source", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "PromptContent", member: "file", - parameters: [ - ConstructionParameter(label: "_", name: "path", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "source", name: "source", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "ExecutableInvocation", member: "executable", - parameters: [ - ConstructionParameter( - label: "_", name: "executable", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "arguments", name: "arguments", type: .array(.named("String")), - defaultValue: ([] as [String]).constructionValue), - ConstructionParameter( - label: "environment", name: "environment", type: .dictionary(.named("RuntimeValue")), - defaultValue: ([:] as [String: RuntimeValue]).constructionValue), - ConstructionParameter( - label: "workingDirectory", name: "workingDirectory", type: .optional(.named("Resource")), - defaultValue: (nil as Resource?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "MCPTransport", member: "stdio", - parameters: [ - ConstructionParameter( - label: "_", name: "executable", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "arguments", name: "arguments", type: .array(.named("String")), - defaultValue: ([] as [String]).constructionValue), - ConstructionParameter( - label: "environment", name: "environment", type: .dictionary(.named("RuntimeValue")), - defaultValue: ([:] as [String: RuntimeValue]).constructionValue), - ConstructionParameter( - label: "workingDirectory", name: "workingDirectory", type: .optional(.named("Resource")), - defaultValue: (nil as Resource?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "MCPTransport", member: "streamableHTTP", - parameters: [ - ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "headers", name: "headers", type: .dictionary(.named("RuntimeValue")), - defaultValue: ([:] as [String: RuntimeValue]).constructionValue), - ], callable: true), - ConstructionSignature( - type: "MCPTransport", member: "sse", - parameters: [ - ConstructionParameter(label: "url", name: "url", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "headers", name: "headers", type: .dictionary(.named("RuntimeValue")), - defaultValue: ([:] as [String: RuntimeValue]).constructionValue), - ], callable: true), - ConstructionSignature( - type: "PromptParameter", member: "parameter", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "description", name: "description", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "defaultValue", name: "defaultValue", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ], callable: true), - ConstructionSignature( - type: "PermissionRule", member: "allow", - parameters: [ - ConstructionParameter( - label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil), - ConstructionParameter( - label: "_", name: "pattern", type: .named("String"), defaultValue: nil), - ], callable: true), - ConstructionSignature( - type: "PermissionRule", member: "ask", - parameters: [ - ConstructionParameter( - label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil), - ConstructionParameter( - label: "_", name: "pattern", type: .named("String"), defaultValue: nil), - ], callable: true), - ConstructionSignature( - type: "PermissionRule", member: "deny", - parameters: [ - ConstructionParameter( - label: "_", name: "operation", type: .named("PermissionOperation"), defaultValue: nil), - ConstructionParameter( - label: "_", name: "pattern", type: .named("String"), defaultValue: nil), - ], callable: true), - ConstructionSignature( - type: "Component", member: "skills", - parameters: [ - ConstructionParameter( - label: "source", name: "source", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "select", name: "select", type: .named("SkillSelection"), - defaultValue: (.all as SkillSelection).constructionValue), - ConstructionParameter( - label: "exclude", name: "exclude", type: .array(.named("String")), - defaultValue: ([] as [String]).constructionValue), - ConstructionParameter( - label: "mode", name: "mode", type: .optional(.named("InstallMode")), - defaultValue: (nil as InstallMode?).constructionValue), - ConstructionParameter( - label: "overrides", name: "overrides", type: .array(.named("SkillOverride")), - defaultValue: ([] as [SkillOverride]).constructionValue), - ConstructionParameter( - label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), - ConstructionParameter( - label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), - ConstructionParameter( - label: "native", name: "native", - type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Component", member: "instructions", - parameters: [ - ConstructionParameter( - label: "sections", name: "sections", type: .array(.named("SectionReference")), - defaultValue: ([] as [SectionReference]).constructionValue), - ConstructionParameter( - label: "chatGPT", name: "chatGPT", type: .array(.named("ChatGPTPrompt")), - defaultValue: ([] as [ChatGPTPrompt]).constructionValue), - ConstructionParameter( - label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), - ConstructionParameter( - label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), - ConstructionParameter( - label: "native", name: "native", - type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Component", member: "mcpServer", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "transport", name: "transport", type: .named("MCPTransport"), defaultValue: nil), - ConstructionParameter( - label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), - ConstructionParameter( - label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), - ConstructionParameter( - label: "native", name: "native", - type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Component", member: "hook", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "event", name: "event", type: .named("HookEvent"), defaultValue: nil), - ConstructionParameter( - label: "run", name: "run", type: .named("ExecutableInvocation"), defaultValue: nil), - ConstructionParameter( - label: "matcher", name: "matcher", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ConstructionParameter( - label: "timeoutSeconds", name: "timeoutSeconds", type: .optional(.named("Int")), - defaultValue: (nil as Int?).constructionValue), - ConstructionParameter( - label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), - ConstructionParameter( - label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), - ConstructionParameter( - label: "native", name: "native", - type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Component", member: "subagent", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "description", name: "description", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "prompt", name: "prompt", type: .named("PromptContent"), defaultValue: nil), - ConstructionParameter( - label: "model", name: "model", type: .optional(.named("String")), - defaultValue: (nil as String?).constructionValue), - ConstructionParameter( - label: "tools", name: "tools", type: .optional(.array(.named("String"))), - defaultValue: (nil as [String]?).constructionValue), - ConstructionParameter( - label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), - ConstructionParameter( - label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), - ConstructionParameter( - label: "native", name: "native", - type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Component", member: "command", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "description", name: "description", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "prompt", name: "prompt", type: .named("PromptContent"), defaultValue: nil), - ConstructionParameter( - label: "parameters", name: "parameters", type: .array(.named("PromptParameter")), - defaultValue: ([] as [PromptParameter]).constructionValue), - ConstructionParameter( - label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), - ConstructionParameter( - label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), - ConstructionParameter( - label: "native", name: "native", - type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Component", member: "lspServer", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "run", name: "run", type: .named("ExecutableInvocation"), defaultValue: nil), - ConstructionParameter( - label: "languages", name: "languages", type: .dictionary(.named("String")), - defaultValue: nil), - ConstructionParameter( - label: "initializationOptions", name: "initializationOptions", - type: .dictionary(.named("ConfigurationValue")), - defaultValue: ([:] as [String: ConfigurationValue]).constructionValue), - ConstructionParameter( - label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), - ConstructionParameter( - label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), - ConstructionParameter( - label: "native", name: "native", - type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Component", member: "permissions", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "rules", name: "rules", type: .array(.named("PermissionRule")), defaultValue: nil), - ConstructionParameter( - label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), - ConstructionParameter( - label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), - ConstructionParameter( - label: "native", name: "native", - type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Component", member: "ignore", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "patterns", name: "patterns", type: .array(.named("String")), defaultValue: nil), - ConstructionParameter( - label: "purpose", name: "purpose", type: .named("IgnorePurpose"), - defaultValue: (.context as IgnorePurpose).constructionValue), - ConstructionParameter( - label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), - ConstructionParameter( - label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), - ConstructionParameter( - label: "native", name: "native", - type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), - ], callable: true), - ConstructionSignature( - type: "Component", member: "plugin", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "path", name: "path", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "source", name: "source", type: .named("String"), defaultValue: nil), - ConstructionParameter( - label: "mode", name: "mode", type: .named("PluginMode"), - defaultValue: (.components as PluginMode).constructionValue), - ConstructionParameter( - label: "select", name: "select", type: .optional(.array(.named("ComponentKind"))), - defaultValue: (nil as [ComponentKind]?).constructionValue), - ConstructionParameter( - label: "exclude", name: "exclude", type: .array(.named("ComponentReference")), - defaultValue: ([] as [ComponentReference]).constructionValue), - ConstructionParameter( - label: "agents", name: "agents", type: .optional(.array(.named("Agent"))), - defaultValue: (nil as [Agent]?).constructionValue), - ConstructionParameter( - label: "condition", name: "condition", type: .optional(.named("Condition")), - defaultValue: (nil as Condition?).constructionValue), - ConstructionParameter( - label: "native", name: "native", - type: .dictionary(.dictionary(.named("ConfigurationValue"))), - defaultValue: ([:] as NativeConfiguration).constructionValue), - ], callable: true), - ConstructionSignature(type: "Agent", member: "claudeCode", parameters: [], callable: false), - ConstructionSignature(type: "Agent", member: "codex", parameters: [], callable: false), - ConstructionSignature(type: "Agent", member: "cursor", parameters: [], callable: false), - ConstructionSignature(type: "Agent", member: "geminiCLI", parameters: [], callable: false), - ConstructionSignature(type: "Agent", member: "openCode", parameters: [], callable: false), - ConstructionSignature(type: "Scope", member: "project", parameters: [], callable: false), - ConstructionSignature(type: "Scope", member: "user", parameters: [], callable: false), - ConstructionSignature(type: "Platform", member: "macOS", parameters: [], callable: false), - ConstructionSignature(type: "Platform", member: "linux", parameters: [], callable: false), - ConstructionSignature(type: "InstallMode", member: "link", parameters: [], callable: false), - ConstructionSignature(type: "InstallMode", member: "copy", parameters: [], callable: false), - ConstructionSignature(type: "InstallMode", member: "edit", parameters: [], callable: false), - ConstructionSignature( - type: "RuntimeValue", member: "literal", - parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "RuntimeValue", member: "environment", - parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "RuntimeValue", member: "secret", - parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "ConfigurationValue", member: "string", - parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "ConfigurationValue", member: "integer", - parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("Int"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "ConfigurationValue", member: "decimal", - parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "ConfigurationValue", member: "boolean", - parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("Bool"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "ConfigurationValue", member: "null", parameters: [], callable: false), - ConstructionSignature( - type: "ConfigurationValue", member: "array", - parameters: [ - ConstructionParameter( - label: "_", name: "value", type: .array(.named("ConfigurationValue")), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "ConfigurationValue", member: "object", - parameters: [ - ConstructionParameter( - label: "_", name: "value", type: .dictionary(.named("ConfigurationValue")), - defaultValue: nil) - ], callable: true), - ConstructionSignature(type: "HookEvent", member: "beforeTool", parameters: [], callable: false), - ConstructionSignature(type: "HookEvent", member: "afterTool", parameters: [], callable: false), - ConstructionSignature( - type: "HookEvent", member: "sessionStart", parameters: [], callable: false), - ConstructionSignature(type: "HookEvent", member: "sessionEnd", parameters: [], callable: false), - ConstructionSignature( - type: "HookEvent", member: "native", - parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "PermissionOperation", member: "read", parameters: [], callable: false), - ConstructionSignature( - type: "PermissionOperation", member: "write", parameters: [], callable: false), - ConstructionSignature( - type: "PermissionOperation", member: "execute", parameters: [], callable: false), - ConstructionSignature( - type: "PermissionOperation", member: "tool", - parameters: [ - ConstructionParameter(label: "_", name: "value", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "IgnorePurpose", member: "context", parameters: [], callable: false), - ConstructionSignature( - type: "IgnorePurpose", member: "indexing", parameters: [], callable: false), - ConstructionSignature(type: "PluginMode", member: "native", parameters: [], callable: false), - ConstructionSignature( - type: "PluginMode", member: "components", parameters: [], callable: false), - ConstructionSignature(type: "ComponentKind", member: "skills", parameters: [], callable: false), - ConstructionSignature( - type: "ComponentKind", member: "instructions", parameters: [], callable: false), - ConstructionSignature( - type: "ComponentKind", member: "mcpServer", parameters: [], callable: false), - ConstructionSignature(type: "ComponentKind", member: "hook", parameters: [], callable: false), - ConstructionSignature( - type: "ComponentKind", member: "subagent", parameters: [], callable: false), - ConstructionSignature( - type: "ComponentKind", member: "command", parameters: [], callable: false), - ConstructionSignature( - type: "ComponentKind", member: "lspServer", parameters: [], callable: false), - ConstructionSignature( - type: "ComponentKind", member: "permissions", parameters: [], callable: false), - ConstructionSignature(type: "ComponentKind", member: "ignore", parameters: [], callable: false), - ConstructionSignature(type: "ComponentKind", member: "plugin", parameters: [], callable: false), - ConstructionSignature( - type: "ComponentReference", member: "skill", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "ComponentReference", member: "instruction", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "ComponentReference", member: "mcpServer", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "ComponentReference", member: "hook", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "ComponentReference", member: "subagent", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "ComponentReference", member: "command", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "ComponentReference", member: "lspServer", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "ComponentReference", member: "permissions", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "ComponentReference", member: "ignore", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "ComponentReference", member: "plugin", - parameters: [ - ConstructionParameter( - label: "name", name: "name", type: .named("String"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "VersionRange", member: "upToNextMajor", - parameters: [ - ConstructionParameter( - label: "from", name: "from", type: .named("Version"), defaultValue: nil) - ], callable: true), - ConstructionSignature( - type: "VersionRange", member: "upToNextMinor", - parameters: [ - ConstructionParameter( - label: "from", name: "from", type: .named("Version"), defaultValue: nil) - ], callable: true), - ] - package static let literalTypes: [String: Set] = [ - "SectionReference": [.string], - "GroupReference": [.string], - "PromptContent": [.string], - "RuntimeValue": [.string], - "SkillSelection": [.array], - "ConfigurationValue": [.string, .integer, .boolean, .nilLiteral, .array, .dictionary], - "Version": [.string], - ] - package static let literalConstructions: [String: [LiteralKind: LiteralConstruction]] = [ - "SectionReference": [ - .string: LiteralConstruction( - member: "section", payload: "name", payloadType: .named("String"), - defaults: ["source": .none, "condition": .none]) - ], - "GroupReference": [ - .string: LiteralConstruction( - member: "group", payload: "name", payloadType: .named("String"), - defaults: ["source": .none, "condition": .none]) - ], - "PromptContent": [ - .string: LiteralConstruction( - member: "literal", payload: "value", payloadType: .named("String"), defaults: [:]) - ], - "RuntimeValue": [ - .string: LiteralConstruction( - member: "literal", payload: "value", payloadType: .named("String"), defaults: [:]) - ], - "SkillSelection": [ - .array: LiteralConstruction( - member: "names", payload: "names", payloadType: .array(.named("String")), defaults: [:]) - ], - "ConfigurationValue": [ - .string: LiteralConstruction( - member: "string", payload: "value", payloadType: .named("String"), defaults: [:]), - .integer: LiteralConstruction( - member: "integer", payload: "value", payloadType: .named("Int"), defaults: [:]), - .boolean: LiteralConstruction( - member: "boolean", payload: "value", payloadType: .named("Bool"), defaults: [:]), - .nilLiteral: LiteralConstruction( - member: "null", payload: nil, payloadType: nil, defaults: [:]), - .array: LiteralConstruction( - member: "array", payload: "value", payloadType: .array(.named("ConfigurationValue")), - defaults: [:]), - .dictionary: LiteralConstruction( - member: "object", payload: "value", payloadType: .dictionary(.named("ConfigurationValue")), - defaults: [:]), - ], - ] - package static let scalarValues: [String: [String: String]] = [ - "Agent": [ - "claudeCode": "claude-code", "codex": "codex", "cursor": "cursor", "geminiCLI": "gemini-cli", - "openCode": "opencode", - ], - "Scope": ["project": "project", "user": "user"], - "Platform": ["macOS": "macos", "linux": "linux"], - "InstallMode": ["link": "link", "copy": "copy", "edit": "edit"], - "IgnorePurpose": ["context": "context", "indexing": "indexing"], - "PluginMode": ["native": "native", "components": "components"], - "ComponentKind": [ - "skills": "skills", "instructions": "instructions", "mcpServer": "mcpServer", "hook": "hook", - "subagent": "subagent", "command": "command", "lspServer": "lspServer", - "permissions": "permissions", "ignore": "ignore", "plugin": "plugin", - ], - ] - package static let taggedRecordTypes: Set = [ - "Source", "Component", "MCPTransport", "ExecutableInvocation", "GroupReference", - "PromptContent", "RuntimeValue", "ConfigurationValue", "HookEvent", "PermissionOperation", - "ComponentReference", "PermissionRule", - ] - package static let aliasTypes: [String: ConstructionType] = [ - "NativeConfiguration": .dictionary(.dictionary(.named("ConfigurationValue"))) - ] -} diff --git a/Sources/AgentsManifest/Admission.swift b/Sources/AgentsManifest/Admission.swift deleted file mode 100644 index 35c9139..0000000 --- a/Sources/AgentsManifest/Admission.swift +++ /dev/null @@ -1,849 +0,0 @@ -import AgentsDescription -import Foundation - -private let utf8ByteOrderMark: [UInt8] = [0xEF, 0xBB, 0xBF] - -enum ProjectionKind: String, Sendable { - case string, integer, negative, boolean, array, dictionary, sequence, call, group - case member, reference, label, type, arrayType, dictionaryType - case importDeclaration = "import" - case letDeclaration = "let" - case nilLiteral = "nil" -} - -struct ProjectionEvent: Sendable, Equatable, Comparable { - let start: Int - let end: Int - let kind: ProjectionKind - let detail: String - static func < (lhs: Self, rhs: Self) -> Bool { - if lhs.start != rhs.start { return lhs.start < rhs.start } - if lhs.end != rhs.end { return lhs.end < rhs.end } - if lhs.kind != rhs.kind { return lhs.kind.rawValue < rhs.kind.rawValue } - return lhs.detail < rhs.detail - } -} - -enum LexemeKind: String, Sendable { - case identifier, string, integer - case rangeOperator = "..<" - case leftParenthesis = "(" - case rightParenthesis = ")" - case leftSquare = "[" - case rightSquare = "]" - case comma = "," - case colon = ":" - case period = "." - case assignment = "=" - case plus = "+" - case minus = "-" - case endOfFile = "eof" -} - -enum GrammarNodeKind: Sendable { - case string, integer, negative, boolean, array, dictionary, sequence, range, name, call, group - case nilLiteral -} - -extension GrammarNodeKind { - var projection: ProjectionKind? { - switch self { - case .string: .string - case .integer: .integer - case .negative: .negative - case .boolean: .boolean - case .array: .array - case .dictionary: .dictionary - case .sequence: .sequence - case .name, .range: nil - case .call: .call - case .group: .group - case .nilLiteral: .nilLiteral - } - } -} - -struct Lexeme: Sendable { - let text: String - let range: Range - let kind: LexemeKind - let decoded: String? -} - -struct GrammarArgument: Sendable { - let label: String - let labelRange: Range? - let value: Int -} - -struct GrammarNode: Sendable { - let kind: GrammarNodeKind - let range: Range - var text: String = "" - var children: [Int] = [] - var arguments: [GrammarArgument] = [] - var keys: [Lexeme] = [] -} - -struct GrammarDeclaration: Sendable { - let name: String - let nameRange: Range - let type: ConstructionType? - let expression: Int - let range: Range -} - -struct Admission: Sendable { - let nodes: [GrammarNode] - let declarations: [GrammarDeclaration] - let tokens: [Lexeme] - let comments: [Range] - let projection: [ProjectionEvent] - let reservation: Int -} - -final class Recognizer { - private let source: SourceText - private let bytes: [UInt8] - private var tokens: [Lexeme] = [] - private var comments: [Range] = [] - private var index = 0 - private var nodes: [GrammarNode] = [] - private var events: [ProjectionEvent] = [] - private var depth = 0 - private var square = 0 - private var literalUnits = 0 - private let reserved: Set = Set( - "_ Any Self as associatedtype break case catch class continue default defer deinit do else enum extension fallthrough false fileprivate for func guard if import in init inout internal is let nil open operator precedencegroup private protocol public repeat rethrows return self static struct subscript super switch throw throws true try typealias var where while" - .split(separator: " ").map(String.init)) - private let prefixes: Set = ["await", "copy", "consume", "each", "unsafe"] - - init(source: SourceText) { - self.source = source - bytes = source.bytes - } - - private func fail(_ message: String, at offset: Int, code: String = "manifest.syntax") - -> ManifestFailure - { - var metrics = FrontEndMetrics() - metrics.tokens = tokens.count - metrics.syntaxReservation = - ManifestLimits.Admission.reservationBase + ManifestLimits.Admission.reservationPerUnit - * (tokens.count + literalUnits) - return ManifestFailure( - ManifestDiagnostic(code: code, message: message, span: source.span(offset.. Admission { - if bytes.count > ManifestLimits.Input.bytes { - throw fail("input byte limit", at: ManifestLimits.Input.bytes, code: "manifest.limit") - } - try validateUTF8() - let header = bytes.starts(with: utf8ByteOrderMark) ? utf8ByteOrderMark.count : 0 - try version(at: header) - try lex(from: header) - let start = try take("import").range.lowerBound - let module = try take("AgentsDescription") - emit(.importDeclaration, start.. 1 || parts[0] > "1" || parts[0] == "1" && parts[1] != "0" - throw fail( - newer - ? "unsupported language version; upgrade the reader" - : "unsupported language version; use a supported converter", at: start, - code: "manifest.version.unsupported") - } - } - - private func validateUTF8() throws { - var i = 0 - while i < bytes.count { - let b = bytes[i] - if b < 128 { - i += 1 - continue - } - let length: Int - if b >= 194 && b <= 223 { - length = 2 - } else if b >= 224 && b <= 239 { - length = 3 - } else if b >= 240 && b <= 244 { - length = 4 - } else { - throw fail("invalid UTF-8", at: i) - } - guard i + length <= bytes.count else { throw fail("invalid UTF-8", at: i) } - for j in 1.. 191 { - throw fail("invalid UTF-8", at: i + j) - } - let next = bytes[i + 1] - if b == 224 && next < 160 || b == 237 && next >= 160 || b == 240 && next < 144 - || b == 244 && next >= 144 - { - throw fail("invalid UTF-8 scalar", at: i) - } - i += length - } - } - - private func isSpace(_ byte: UInt8) -> Bool { - byte == UInt8(ascii: " ") || byte == UInt8(ascii: "\t") || byte == UInt8(ascii: "\n") - || byte == UInt8(ascii: "\r") - } - private func isHead(_ byte: UInt8) -> Bool { - byte == UInt8(ascii: "_") || (UInt8(ascii: "A")...UInt8(ascii: "Z")).contains(byte) - || (UInt8(ascii: "a")...UInt8(ascii: "z")).contains(byte) - } - private func starts(_ spelling: [UInt8], at offset: Int) -> Bool { - offset + spelling.count <= bytes.count - && bytes[offset..<(offset + spelling.count)].elementsEqual(spelling) - } - private func canonical(_ op: String) -> String { - op == "=" ? "let value = -1" : op == "+" ? "left + right" : "\"1.2.0\"..<\"1.8.0\"" - } - - private func lex(from start: Int) throws { - var i = start - while i < bytes.count { - if isSpace(bytes[i]) { - i += 1 - continue - } - if starts([UInt8(ascii: "/"), UInt8(ascii: "/")], at: i) { - let first = i - i += 2 - while i < bytes.count && bytes[i] != UInt8(ascii: "\n") && bytes[i] != UInt8(ascii: "\r") { - i += 1 - } - let range = first.. 0 { - if starts([UInt8(ascii: "/"), UInt8(ascii: "*")], at: i) { - level += 1 - if level > ManifestLimits.Admission.commentDepth { - throw fail("block comment depth", at: i, code: "manifest.limit") - } - i += 2 - } else if starts([UInt8(ascii: "*"), UInt8(ascii: "/")], at: i) { - level -= 1 - i += 2 - } else { - i += 1 - } - } - if level != 0 { throw fail("unterminated comment", at: first) } - comments.append(first.. 0 && isSpace(bytes[first - 1])) != (i < bytes.count && isSpace(bytes[i])) { - throw fail( - "range requires balanced whitespace; canonical spelling: \(canonical(kind.rawValue))", - at: first) - } - } else if [ - UInt8(ascii: "("), UInt8(ascii: ")"), UInt8(ascii: "["), UInt8(ascii: "]"), - UInt8(ascii: ","), UInt8(ascii: ":"), UInt8(ascii: "."), UInt8(ascii: "="), - UInt8(ascii: "+"), UInt8(ascii: "-"), - ].contains(bytes[i]) { - let byte = bytes[i] - i += 1 - kind = LexemeKind(rawValue: String(UnicodeScalar(byte)))! - if byte == UInt8(ascii: "=") || byte == UInt8(ascii: "+") { - if first == 0 || i == bytes.count || !isSpace(bytes[first - 1]) || !isSpace(bytes[i]) { - throw fail( - "operator requires whitespace on both sides; canonical spelling: \(canonical(kind.rawValue))", - at: first) - } - } - if byte == UInt8(ascii: "-") { - if i == bytes.count || !(UInt8(ascii: "0")...UInt8(ascii: "9")).contains(bytes[i]) - || first == 0 - || !(isSpace(bytes[first - 1]) - || [UInt8(ascii: "("), UInt8(ascii: "["), UInt8(ascii: ","), UInt8(ascii: ":")] - .contains(bytes[first - 1])) - { - throw fail( - "negative integer requires an adjacent sign and separated boundary; canonical spelling: let value = -1", - at: first) - } - } - } else { - throw fail("token outside the lexical grammar", at: i) - } - if tokens.count == ManifestLimits.Admission.tokens { - throw fail("token count", at: first, code: "manifest.limit") - } - // Reserve container/wrapper storage before SwiftParser: the fixed base plus - // four nodes for every token, literal escape and physical literal line break. - // The independent all-node guard verifies this conservative reservation. - if ManifestLimits.Admission.reservationBase + ManifestLimits.Admission.reservationPerUnit - * (tokens.count + 1 + literalUnits) > ManifestLimits.Admission.syntaxReservation - { - throw fail("syntax storage reservation", at: first, code: "manifest.limit") - } - tokens.append( - Lexeme(text: source.spelling(first..= left.range.upperBound { - let op = ["=", "+", "..<"].contains(left.text) ? left : right - if ["=", "+", "..<"].contains(op.text) { - if comment.lowerBound == 0 || comment.upperBound == bytes.count - || !isSpace(bytes[comment.lowerBound - 1]) || !isSpace(bytes[comment.upperBound]) - { - throw fail( - "operator-adjacent comments require whitespace; canonical spelling: \(canonical(op.text))", - at: op.range.lowerBound) - } - } - } - ci += 1 - } - } - tokens.append( - Lexeme(text: "", range: bytes.count.. (Int, String?) { - let multiline = starts([UInt8(ascii: "\""), UInt8(ascii: "\""), UInt8(ascii: "\"")], at: start) - let width = multiline ? 3 : 1 - var i = start + width - var body = i - if multiline { - guard i < bytes.count && (bytes[i] == UInt8(ascii: "\n") || bytes[i] == UInt8(ascii: "\r")) - else { - throw fail("multiline opener requires a newline", at: i) - } - if starts([UInt8(ascii: "\r"), UInt8(ascii: "\n")], at: i) { i += 2 } else { i += 1 } - body = i - } - while i < bytes.count { - let byte = bytes[i] - if byte < UInt8(ascii: " ") && byte != UInt8(ascii: "\t") && byte != UInt8(ascii: "\n") - && byte != UInt8(ascii: "\r") - { - throw fail("control scalar in string", at: i) - } - if !multiline && (byte == UInt8(ascii: "\n") || byte == UInt8(ascii: "\r")) { - throw fail("newline in single-line string", at: i) - } - if byte == UInt8(ascii: "\\") { - let escape = i - i += 1 - if i < bytes.count - && [ - UInt8(ascii: "0"), UInt8(ascii: "\\"), UInt8(ascii: "t"), UInt8(ascii: "n"), - UInt8(ascii: "r"), UInt8(ascii: "\""), UInt8(ascii: "'"), - ].contains(bytes[i]) - { - i += 1 - continue - } - guard starts([UInt8(ascii: "u"), UInt8(ascii: "{")], at: i) else { - throw fail("unsupported escape or interpolation", at: escape) - } - i += 2 - let digits = i - var scalar: UInt32 = 0 - while i < bytes.count, let hex = hex(bytes[i]), i - digits < 9 { - scalar = scalar &* 16 &+ hex - i += 1 - } - guard (1...8).contains(i - digits), i < bytes.count, bytes[i] == UInt8(ascii: "}"), - scalar <= 0x10ffff, !(0xd800...0xdfff).contains(scalar) - else { throw fail("invalid Unicode escape", at: escape) } - i += 1 - continue - } - if byte == UInt8(ascii: "\"") - && (!multiline - || starts([UInt8(ascii: "\""), UInt8(ascii: "\""), UInt8(ascii: "\"")], at: i)) - { - let closing = i - let end = i + width - let content: [UInt8] - if multiline { - var lineStart = i - while lineStart > body && bytes[lineStart - 1] != UInt8(ascii: "\n") - && bytes[lineStart - 1] != UInt8(ascii: "\r") - { - lineStart -= 1 - } - let indent = i - lineStart - guard bytes[lineStart.. first - && (lineEnd - first < indent - || !bytes[first..<(first + indent)].allSatisfy({ $0 == UInt8(ascii: " ") })) - { - throw fail("nonempty multiline line requires full indentation", at: first) - } - let contentStart = lineEnd == first ? first : first + indent - decodedBody.append(contentsOf: bytes[contentStart.. UInt32? { - if (UInt8(ascii: "0")...UInt8(ascii: "9")).contains(b) { return UInt32(b - UInt8(ascii: "0")) } - if (UInt8(ascii: "A")...UInt8(ascii: "F")).contains(b) { - return UInt32(b - UInt8(ascii: "A")) + 10 - } - if (UInt8(ascii: "a")...UInt8(ascii: "f")).contains(b) { - return UInt32(b - UInt8(ascii: "a")) + 10 - } - return nil - } - - private func decode(_ raw: [UInt8]) -> String { - if !raw.contains(UInt8(ascii: "\\")) { return String(decoding: raw, as: UTF8.self) } - var result: [UInt8] = [] - var i = 0 - while i < raw.count { - if raw[i] != UInt8(ascii: "\\") { - result.append(raw[i]) - i += 1 - continue - } - i += 1 - switch raw[i] { - case UInt8(ascii: "0"): result.append(UInt8(ascii: "\0")) - case UInt8(ascii: "t"): result.append(UInt8(ascii: "\t")) - case UInt8(ascii: "n"): result.append(UInt8(ascii: "\n")) - case UInt8(ascii: "r"): result.append(UInt8(ascii: "\r")) - case UInt8(ascii: "u"): - i += 2 - var scalar: UInt32 = 0 - while raw[i] != UInt8(ascii: "}") { - scalar = scalar * 16 + hex(raw[i])! - i += 1 - } - result.append(contentsOf: String(UnicodeScalar(scalar)!).utf8) - default: result.append(raw[i]) - } - i += 1 - } - return String(decoding: result, as: UTF8.self) - } - - private func peek() -> Lexeme { tokens[index] } - private func peek(_ text: String) -> Bool { peek().text == text } - @discardableResult private func take(_ text: String? = nil) throws -> Lexeme { - let token = peek() - if let text, token.text != text { throw fail("expected \(text)", at: token.range.lowerBound) } - if token.kind != .endOfFile { index += 1 } - return token - } - private func identifier(bare: Bool = false) throws -> Lexeme { - let token = peek() - guard token.kind == .identifier, !reserved.contains(token.text), - !(bare && prefixes.contains(token.text)) - else { throw fail("expected an identifier", at: token.range.lowerBound) } - return try take() - } - private func open(_ text: String) throws -> Int { - let token = try take(text) - depth += 1 - if text == "[" { square += 1 } - if depth > ManifestLimits.Admission.delimiterDepth - || square > ManifestLimits.Admission.squareDepth - { - throw fail("grammar delimiter depth", at: token.range.lowerBound, code: "manifest.limit") - } - return token.range.lowerBound - } - private func close(_ text: String) throws -> Int { - let token = try take(text) - depth -= 1 - if text == "]" { square -= 1 } - return token.range.upperBound - } - private func emit(_ kind: ProjectionKind, _ range: Range, _ detail: String = "") { - events.append( - ProjectionEvent(start: range.lowerBound, end: range.upperBound, kind: kind, detail: detail)) - } - private func node(_ value: GrammarNode) -> Int { - let id = nodes.count - nodes.append(value) - if let kind = value.kind.projection { - let detail: String - switch kind { - case .string, .integer, .boolean, .nilLiteral: detail = source.spelling(value.range) - default: detail = "" - } - emit(kind, value.range, detail) - } - return id - } - - private func type() throws -> ConstructionType { - if peek("[") { - let start = try open("[") - let first = try type() - let result: ConstructionType - let kind: ProjectionKind - if peek(":") { - guard first == .named("String") else { - throw fail("dictionary key type must be String", at: start) - } - _ = try take(":") - result = .dictionary(try type()) - kind = .dictionaryType - } else { - result = .array(first) - kind = .arrayType - } - emit(kind, start..<(try close("]"))) - return result - } - let token = try identifier(bare: true) - guard Vocabulary.typeNames.contains(token.text) else { - throw fail("type outside construction vocabulary", at: token.range.lowerBound) - } - emit(.type, token.range, token.text) - return Vocabulary.aliasTypes[token.text] ?? .named(token.text) - } - - private func expression() throws -> Int { - let first = try primary() - var terms = [first] - while peek("+") { - let op = try take("+") - if terms.count == ManifestLimits.Admission.additiveTerms { - throw fail( - "additive chain exceeds 32 terms", at: op.range.lowerBound, code: "manifest.limit") - } - terms.append(try primary()) - } - if terms.count == 1 { return first } - return node( - GrammarNode( - kind: .sequence, - range: nodes[first].range.lowerBound.. Int { - let token = peek() - let start = token.range.lowerBound - if token.kind == .string || token.kind == .integer - || ["true", "false", "nil"].contains(token.text) - { - _ = try take() - let kind: GrammarNodeKind = - token.kind == .identifier - ? (token.text == "nil" ? .nilLiteral : .boolean) - : (token.kind == .string ? .string : .integer) - return node( - GrammarNode(kind: kind, range: token.range, text: token.decoded ?? token.text)) - } - if peek("-") { - _ = try take("-") - let integer = try take() - guard integer.kind == .integer, integer.range.lowerBound == token.range.upperBound else { - throw fail("minus requires adjacent decimal digits", at: integer.range.lowerBound) - } - emit(.integer, integer.range, integer.text) - return node( - GrammarNode(kind: .negative, range: start..? - if peek().kind == .identifier && tokens[index + 1].text == ":" { - let name = try identifier() - label = name.text - labelRange = name.range - emit(.label, name.range, name.text) - _ = try take(":") - } - arguments.append( - GrammarArgument(label: label, labelRange: labelRange, value: try expression())) - if !peek(",") { break } - _ = try take(",") - if peek(")") { throw fail("calls have no trailing comma", at: peek().range.lowerBound) } - } - } - let end = try close(")") - return node( - GrammarNode(kind: .call, range: start.. GrammarArgument { - let token = try take(label) - emit(.label, token.range, token.text) - _ = try take(":") - return GrammarArgument(label: label, labelRange: token.range, value: try expression()) - } - - private func sourceArguments() throws -> [GrammarArgument] { - var args = [try argument(label: "name")] - _ = try take(",") - let location = peek().text - guard SourceRequirements.locations.contains(location) else { - throw fail( - "source requires a location label: " - + SourceRequirements.locations.sorted().joined(separator: ", "), - at: peek().range.lowerBound) - } - args.append(try argument(label: location)) - if !peek(",") { return args } - _ = try take(",") - if peek("subpath") { - args.append(try argument(label: "subpath")) - return args - } - if !SourceRequirements.locationsWithRequirements.contains(location) { - throw fail("source location has no registered requirement", at: peek().range.lowerBound) - } - if SourceRequirements.labels.contains(peek().text) { - args.append(try argument(label: peek().text)) - } else if peek().kind == .string { - let first = try primary() - let op = try take("..<") - emit(.reference, op.range, "..<") - guard peek().kind == .string else { - throw fail("range endpoint must be a string literal", at: peek().range.lowerBound) - } - let second = try primary() - let range = nodes[first].range.lowerBound.. String { - var result = "\"" - for scalar in string.unicodeScalars { - switch scalar { - case "\"": result += "\\\"" - case "\\": result += "\\\\" - case "\n": result += "\\n" - case "\r": result += "\\r" - case "\t": result += "\\t" - case "\0"..<" ", "\u{7F}"..."\u{9F}": - result += "\\u{" + String(scalar.value, radix: 16) + "}" - default: result.unicodeScalars.append(scalar) - } - } - return result + "\"" -} - -struct PrintStyle { - var indent = " " - var newline = "\n" - var trailingComma = true -} - -/// A layout reserves its exact UTF-8 size before allocating emitted source bytes. -private struct Printed { - private indirect enum Content { - case text(String) - case quoted(String) - case parts([Printed]) - } - private let content: Content - let count: Int - - init(_ text: String) { - content = .text(text) - count = text.utf8.count - } - init(quoting text: String) { - content = .quoted(text) - var size = 2 - for scalar in text.unicodeScalars { - switch scalar { - case "\"", "\\", "\n", "\r", "\t": size = ValueCost.add(size, 2) - case "\0"..<" ", "\u{7F}"..."\u{9F}": - size = ValueCost.add(size, 4 + String(scalar.value, radix: 16).utf8.count) - default: size = ValueCost.add(size, scalar.utf8.count) - } - } - count = size - } - init(_ parts: [Printed]) { - content = .parts(parts) - count = parts.reduce(0) { ValueCost.add($0, $1.count) } - } - func append(to result: inout String) { - switch content { - case .text(let text): result += text - case .quoted(let text): result += quoted(text) - case .parts(let parts): for part in parts { part.append(to: &result) } - } - } - var string: String { - var result = "" - result.reserveCapacity(count) - append(to: &result) - return result - } -} - -struct CanonicalPrinter { - var style = PrintStyle() - - func render( - _ value: ConstructionValue, indentation: String = "", column: Int? = nil, trailing: Int = 1 - ) -> String { - layout( - value, indentation: indentation, column: column ?? indentation.utf8.count, - trailing: trailing - ).string - } - - func manifest(_ value: ConstructionValue) throws -> [UInt8] { - let prefix = "// agents-tools-version: 1.0\nimport AgentsDescription\n\nlet agents = " - let result = Printed([ - Printed(prefix), layout(value, indentation: "", column: 13, trailing: 0), Printed("\n"), - ]) - guard result.count <= ManifestLimits.Input.bytes else { - throw ManifestFailure( - ManifestDiagnostic( - code: "manifest.limit", message: "generated source bytes", - span: SourceSpan( - document: DocumentIdentity("manifest"), start: 0, end: 0, line: 1, column: 1))) - } - return Array(result.string.utf8) - } - - /// The parenthesized argument list of a call whose opening parenthesis is at `column`. - func argumentList( - _ arguments: [(String, ConstructionValue)], indentation: String, column: Int, trailing: Int - ) -> String { - call("", arguments: arguments, indentation: indentation, column: column, trailing: trailing) - .string - } - - private func layout( - _ value: ConstructionValue, indentation: String, column: Int, trailing: Int - ) -> Printed { - switch value { - case .text(let text): return Printed(quoting: text) - case .integer(let value): return Printed(String(value)) - case .boolean(let value): return Printed(value ? "true" : "false") - case .none: return Printed("nil") - case .version(let version): return Printed(quoting: version.normalized) - case .range(let range): - let requirement = Lowering.requirement(range) - if case .upToNextMajor(let lower) = requirement { - return call( - ".upToNextMajor", arguments: [("from", .text(lower))], - indentation: indentation, column: column, trailing: trailing) - } - if case .upToNextMinor(let lower) = requirement { - return call( - ".upToNextMinor", arguments: [("from", .text(lower))], - indentation: indentation, column: column, trailing: trailing) - } - return Printed([ - Printed(quoting: range.lowerBound.normalized), Printed("..<"), - Printed(quoting: range.upperBound.normalized), - ]) - case .array(let values): - let parts = values.enumerated().map { index, value in - layout( - value, indentation: indentation + style.indent, - column: (indentation + style.indent).utf8.count, - trailing: style.trailingComma || index < values.count - 1 ? 1 : 0) - } - return collection( - parts, dictionary: false, forceMultiline: values.contains(where: nested), - indentation: indentation, column: column, trailing: trailing) - case .object(let fields): - let keys = fields.keys.sorted(by: utf8Less) - let parts = keys.enumerated().map { index, key in - let prefix = Printed([Printed(quoting: key), Printed(": ")]) - return Printed([ - prefix, - layout( - fields[key]!, indentation: indentation + style.indent, - column: (indentation + style.indent).utf8.count + prefix.count, - trailing: style.trailingComma || index < keys.count - 1 ? 1 : 0), - ]) - } - return collection( - parts, dictionary: true, forceMultiline: fields.values.contains(where: nested), - indentation: indentation, column: column, trailing: trailing) - case .node(let type, let member, let fields): - if type == "SkillSelection" { - return member == "all" - ? Printed(".all") - : layout(fields["names"]!, indentation: indentation, column: column, trailing: trailing) - } - if type == "VersionRange", let lower = fields["from"] { - return call( - "." + member, arguments: [("from", lower)], - indentation: indentation, column: column, trailing: trailing) - } - if type == "PromptContent" && member == "literal" - || type == "RuntimeValue" && member == "literal" - { - return layout( - fields["value"]!, indentation: indentation, column: column, trailing: trailing) - } - if ["SectionReference", "GroupReference"].contains(type), - fields["source"] == ConstructionValue.none, fields["condition"] == ConstructionValue.none - { - return layout(fields["name"]!, indentation: indentation, column: column, trailing: trailing) - } - if type == "ConfigurationValue" { - if member == "null" { return Printed("nil") } - if member != "decimal" { - return layout( - fields["value"]!, indentation: indentation, column: column, trailing: trailing) - } - } - if type == "Source" { - return source(fields, indentation: indentation, column: column, trailing: trailing) - } - let signature = Vocabulary.signatures.first { signature in - guard signature.type == type, signature.member == member else { return false } - let names = Set(signature.parameters.map(\.name)) - guard fields.allSatisfy({ names.contains($0.key) || $0.value == .none }) else { - return false - } - return signature.parameters.allSatisfy { parameter in - guard let value = fields[parameter.name] else { return parameter.defaultValue != nil } - if value == .none, parameter.defaultValue == nil { - if case .optional = parameter.type { return true } - return false - } - return true - } - } - guard let signature else { return Printed(".\(member)") } - var arguments: [(String, ConstructionValue)] = [] - for parameter in signature.parameters { - guard let value = fields[parameter.name] else { continue } - if let fallback = parameter.defaultValue, fallback == value { continue } - arguments.append((parameter.label, value)) - } - if !signature.callable { return Printed(".\(member)") } - return call( - type == "Agents" ? "Agents" : "." + member, arguments: arguments, - indentation: indentation, column: column, trailing: trailing) - } - } - - private func source( - _ fields: [String: ConstructionValue], indentation: String, column: Int, trailing: Int - ) -> Printed { - var args: [(String, ConstructionValue)] = [("name", fields["name"]!)] - for key in ["url", "path", "index"] { - if let value = fields[key] { - args.append( - ( - key, - key == "url" - ? .text(SourceDeclaration(kind: .git, location: value.text!).gitURL) : value - )) - } - } - if let requirement = fields["requirement"], requirement != .none { - if case .range(let range) = requirement { - if case .upToNextMajor(let lower) = Lowering.requirement(range) { - args.append(("from", .version(Version(stringLiteral: lower)))) - } else { - args.append(("_", requirement)) - } - } else if case .node(_, let member, let payload) = requirement { - args.append((member, payload["value"]!)) - } - } - if let subpath = fields["subpath"], subpath != .none { args.append(("subpath", subpath)) } - return call( - ".source", arguments: args, indentation: indentation, column: column, trailing: trailing) - } - - private func call( - _ callee: String, arguments: [(String, ConstructionValue)], indentation: String, - column: Int, trailing: Int - ) -> Printed { - let parts = arguments.enumerated().map { index, argument in - let (label, value) = argument - let prefix = label == "_" ? "" : label + ": " - return Printed([ - Printed(prefix), - layout( - value, indentation: indentation + style.indent, - column: (indentation + style.indent).utf8.count + prefix.utf8.count, - trailing: index < arguments.count - 1 ? 1 : 0), - ]) - } - let inline = joined(parts, open: callee + "(", close: ")", separator: ", ") - if parts.isEmpty - || !arguments.contains(where: { nested($0.1) }) - && column + inline.count + trailing <= 80 - { - return inline - } - return multiline( - parts, open: callee + "(", close: ")", indentation: indentation, collection: false) - } - - private func collection( - _ parts: [Printed], dictionary: Bool, forceMultiline: Bool, indentation: String, - column: Int, trailing: Int - ) -> Printed { - if parts.isEmpty { return Printed(dictionary ? "[:]" : "[]") } - let inline = joined(parts, open: "[", close: "]", separator: ", ") - if !forceMultiline && column + inline.count + trailing <= 80 { return inline } - return multiline(parts, open: "[", close: "]", indentation: indentation, collection: true) - } - - private func joined(_ parts: [Printed], open: String, close: String, separator: String) -> Printed - { - var output = [Printed(open)] - for (index, part) in parts.enumerated() { - if index > 0 { output.append(Printed(separator)) } - output.append(part) - } - output.append(Printed(close)) - return Printed(output) - } - - private func multiline( - _ parts: [Printed], open: String, close: String, indentation: String, collection: Bool - ) -> Printed { - var output = [Printed(open + style.newline)] - for (index, part) in parts.enumerated() { - output += [Printed(indentation + style.indent), part] - if index < parts.count - 1 || collection && style.trailingComma { - output.append(Printed(",")) - } - output.append(Printed(style.newline)) - } - output.append(Printed(indentation + close)) - return Printed(output) - } - - private func nested(_ value: ConstructionValue) -> Bool { - switch value { - case .array, .object: return true - case .node(let type, let member, let fields): - if Vocabulary.scalarValues[type] != nil || type == "SkillSelection" && member == "all" { - return false - } - if ["SectionReference", "GroupReference"].contains(type), - fields["source"] == ConstructionValue.none, fields["condition"] == ConstructionValue.none - { - return false - } - if ["PromptContent", "RuntimeValue"].contains(type), member == "literal" { return false } - if type == "ConfigurationValue" { - if member == "null" { return false } - if member != "decimal", let payload = fields["value"] { return nested(payload) } - } - return true - case .range: return true - default: return false - } - } -} - -func utf8Less(_ lhs: String, _ rhs: String) -> Bool { - lhs.utf8.lexicographicallyPrecedes(rhs.utf8) -} diff --git a/Sources/AgentsManifest/CompleteDeclarationPlanner.swift b/Sources/AgentsManifest/CompleteDeclarationPlanner.swift deleted file mode 100644 index 94c0b61..0000000 --- a/Sources/AgentsManifest/CompleteDeclarationPlanner.swift +++ /dev/null @@ -1,225 +0,0 @@ -import AgentsCore -import AgentsDescription - -/// Diffs full symbolic values against their source locations. Direct constructions are edited -/// by field, ordered arrays by occurrence, and assembled expressions remain read-only. -struct CompleteDeclarationPlanner { - let document: DeclarationDocument - let current: Declaration - let next: Declaration - let environment: RuntimeEnvironment - - func plan() throws -> [DocumentOperation] { - var operations: [DocumentOperation] = [] - var desired = try DeclarationConstruction.root(next).constructionValue - if case .node(let type, let member, var fields) = desired { - let originals = document.evaluation.root.value.fields["sources"]!.array! - fields["sources"] = .array( - try next.sourceDeclarations.map { entry in - let matches = current.sourceDeclarations.indices.filter { - current.sourceDeclarations[$0].name == entry.name - } - if matches.count > 1 { - let spans = matches.compactMap { - document.sourceMap.locations(at: "/sources/\($0)").first?.span - } - throw ManifestFailure( - ManifestDiagnostic( - code: "manifest.ambiguous", message: "multiple matching source declarations", - span: spans.first ?? document.source.span(0..<0), related: Array(spans.dropFirst())) - ) - } - if let index = matches.first, - ManifestProjection.equivalent( - current.sourceDeclarations[index].source, entry.source, environment: environment) - { - return originals[index] - } - return try DeclarationConstruction.source(alias: entry.name, entry.source) - .constructionValue - }) - desired = .node(type: type, member: member, fields: fields) - } - try difference(document.evaluation.root.value, desired, at: "", into: &operations) - return operations - } - - private func handle(_ pointer: String) throws -> NodeID { - guard let handle = document.node(at: pointer) else { - throw DeclarationEditPlan.failure( - "manifest.edit.readOnly", "value has no independent source location", - span: document.source.span(0..<0)) - } - return handle - } - - private func difference( - _ old: ConstructionValue, _ new: ConstructionValue, at pointer: String, - into operations: inout [DocumentOperation] - ) throws { - if Lowering.lower(old) == Lowering.lower(new) { return } - switch (old, new) { - case (.node("SkillSelection", "names", let left), .node("SkillSelection", "names", let right)): - try array(left["names"]!.array!, right["names"]!.array!, at: pointer, into: &operations) - case (.node(let type, let member, let fields), .node(let newType, let newMember, let desired)) - where type == newType && member == newMember && type != "Source" && type != "SkillSelection": - if let value = document.values[pointer], document.admission.nodes[value.syntax].kind != .call, - type != "ConfigurationValue" || !["array", "object"].contains(member) - { - operations.append(.replaceValue(try handle(pointer), new)) - return - } - // Vocabulary order keeps the batch deterministic and respects constructor argument order. - let signature = Vocabulary.signatures.filter { $0.type == type && $0.member == member }.max { - $0.parameters.count < $1.parameters.count - } - let names = signature?.parameters.map(\.name) ?? [] - if names.isEmpty { - operations.append(.replaceValue(try handle(pointer), new)) - return - } - for name in names { - guard let left = fields[name], let right = desired[name], - Lowering.lower(left) != Lowering.lower(right) - else { continue } - let child = pointer + "/" + pointerEscape(name) - let explicit = document.values[child].map { !$0.defaulted } ?? false - if explicit, canDescend(left, right) { - try difference(left, right, at: child, into: &operations) - } else { - operations.append(.setArgument(try handle(pointer), field: name, value: right)) - } - } - case (.array(let left), .array(let right)): - try array(left, right, at: pointer, into: &operations) - case (.object(let left), .object(let right)): - for key in right.keys.sorted(by: utf8Less) { - if let old = left[key] { - try difference( - old, right[key]!, at: pointer + "/" + pointerEscape(key), into: &operations) - } else { - operations.append(.dictionaryEntry(try handle(pointer), key: key, value: right[key]!)) - } - } - for key in left.keys.sorted(by: utf8Less) where right[key] == nil { - operations.append(.dictionaryEntry(try handle(pointer), key: key, value: nil)) - } - default: - operations.append(.replaceValue(try handle(pointer), new)) - } - } - - private func canDescend(_ old: ConstructionValue, _ new: ConstructionValue) -> Bool { - switch (old, new) { - case (.array, .array), (.object, .object): return true - case (.node(let a, let b, _), .node(let x, let y, _)): - return a == x && b == y && a != "Source" && (a != "SkillSelection" || b == "names") - default: return false - } - } - - private func identity(_ value: ConstructionValue) -> String? { - guard case .node(let type, let member, let fields) = value else { return nil } - if let name = fields["name"]?.text { - if type == "GroupReference" || type == "SectionReference" { - let kind = Lowering.recordKind(type: type, member: member, fields: fields) - return type + ":" + kind + ":" + (fields["source"]?.text ?? ".") + ":" + name - } - return type + ":" + member + ":" + name - } - if type == "Component", let source = fields["source"]?.text { - return type + ":" + member + ":" + source - } - if type == "Component", member == "instructions" { return type + ":" + member } - return nil - } - - private func array( - _ old: [ConstructionValue], _ new: [ConstructionValue], at pointer: String, - into operations: inout [DocumentOperation] - ) throws { - // Equal-length occurrence-addressed changes retain each position, including repeated names. - if old.count == new.count, zip(old, new).allSatisfy({ identity($0) == identity($1) }) { - for index in old.indices { - try difference(old[index], new[index], at: pointer + "/\(index)", into: &operations) - } - return - } - let (count, overflow) = (old.count + 1).multipliedReportingOverflow(by: new.count + 1) - guard !overflow, count <= ManifestLimits.Editing.comparisonPairs else { - throw DeclarationEditPlan.failure( - "manifest.limit", "declaration comparison pairs", span: document.source.span(0..<0)) - } - func matches(_ a: ConstructionValue, _ b: ConstructionValue) -> Bool { - if let identity = identity(a), identity == self.identity(b) { return true } - return Lowering.lower(a) == Lowering.lower(b) - } - // A named edit across a length change cannot infer which conditional occurrence survives. - let keys = old.compactMap(identity) - for key in Set(keys) where keys.filter({ $0 == key }).count > 1 { - if old != new, new.contains(where: { identity($0) == key }) { - let candidates = old.indices.filter { identity(old[$0]) == key }.map { pointer + "/\($0)" } - let spans = candidates.compactMap { document.sourceMap.locations(at: $0).first?.span } - throw ManifestFailure( - ManifestDiagnostic( - code: "manifest.ambiguous", - message: "multiple matching occurrences require an occurrence-addressed edit", - span: spans.first ?? document.source.span(0..<0), related: Array(spans.dropFirst()))) - } - } - let width = new.count + 1 - var lengths = [Int](repeating: 0, count: count) - for i in old.indices.reversed() { - for j in new.indices.reversed() { - lengths[i * width + j] = - matches(old[i], new[j]) - ? lengths[(i + 1) * width + j + 1] + 1 - : max(lengths[(i + 1) * width + j], lengths[i * width + j + 1]) - } - } - var pairs: [(Int, Int)] = [] - var (i, j) = (0, 0) - while i < old.count && j < new.count { - if matches(old[i], new[j]) { - pairs.append((i, j)) - i += 1 - j += 1 - } else if lengths[(i + 1) * width + j] >= lengths[i * width + j + 1] { - i += 1 - } else { - j += 1 - } - } - let anchors = pairs - var keptOld = Set(pairs.map(\.0)) - let anchoredNew = Set(pairs.map(\.1)) - var moved: [Int: Int] = [:] - for j in new.indices where !anchoredNew.contains(j) { - let candidates = old.indices.filter { !keptOld.contains($0) && matches(old[$0], new[j]) } - if candidates.count == 1, let i = candidates.first { - moved[j] = i - keptOld.insert(i) - pairs.append((i, j)) - } - } - // Field edits precede moves so original occurrence handles still address their owners. - for (i, j) in pairs { - try difference(old[i], new[j], at: pointer + "/\(i)", into: &operations) - } - for j in new.indices where !anchoredNew.contains(j) { - let anchor = try anchors.first { $0.1 > j }.map { - InsertionPosition.before(try handle(pointer + "/\($0.0)")) - } - if let i = moved[j] { - operations.append( - .moveElement( - try handle(pointer + "/\(i)"), into: try handle(pointer), at: anchor ?? .last)) - } else { - operations.append(.insertElement(new[j], into: try handle(pointer), at: anchor ?? .last)) - } - } - for i in old.indices where !keptOld.contains(i) { - operations.append(.removeElement(try handle(pointer + "/\(i)"))) - } - } -} diff --git a/Sources/AgentsManifest/ComponentConstruction.swift b/Sources/AgentsManifest/ComponentConstruction.swift deleted file mode 100644 index de5a900..0000000 --- a/Sources/AgentsManifest/ComponentConstruction.swift +++ /dev/null @@ -1,174 +0,0 @@ -import AgentsCore -import AgentsDescription - -extension DeclarationConstruction { - static func condition(_ condition: DeclarationCondition?) -> Condition? { - condition.map { - .when( - agents: $0.agents.map { $0.map(agent) }, - scopes: $0.scopes.map { $0.map { $0 == .project ? .project : .user } }, - platforms: $0.platforms.map { $0.map { $0 == .macOS ? .macOS : .linux } }) - } - } - - static func nativeValue(_ value: NativeValue) -> ConfigurationValue { - switch value { - case .string(let v): .string(v) - case .integer(let v): .integer(v) - case .decimal(let v): .decimal(v) - case .boolean(let v): .boolean(v) - case .null: .null - case .array(let v): .array(v.map(nativeValue)) - case .object(let v): .object(v.mapValues(nativeValue)) - } - } - - static func native(_ native: AgentsCore.NativeConfiguration) - -> AgentsDescription.NativeConfiguration - { native.mapValues { $0.mapValues(nativeValue) } } - - static func binding(_ value: RuntimeBinding) -> RuntimeValue { - switch value { - case .literal(let v): .literal(v) - case .environment(let v): .environment(v) - case .secret(let v): .secret(v) - } - } - static func resource(_ value: ResourceDeclaration) -> Resource { - .path(value.path, source: value.source) - } - static func promptBody(_ value: PromptBody) -> PromptContent { - switch value { - case .literal(let v): PromptContent(stringLiteral: v) - case .file(let v): .file(v.path, source: v.source) - } - } - static func executable(_ value: ExecutableDeclaration) -> ExecutableInvocation { - .executable( - value.executable, arguments: value.arguments, - environment: value.environment.mapValues(binding), - workingDirectory: value.workingDirectory.map(resource)) - } - static func transport(_ value: MCPTransportDeclaration) -> MCPTransport { - switch value { - case .stdio(let v): - .stdio( - v.executable, arguments: v.arguments, environment: v.environment.mapValues(binding), - workingDirectory: v.workingDirectory.map(resource)) - case .streamableHTTP(let url, let headers): - .streamableHTTP(url: url, headers: headers.mapValues(binding)) - case .sse(let url, let headers): .sse(url: url, headers: headers.mapValues(binding)) - } - } - static func event(_ value: HookEventDeclaration) -> HookEvent { - switch value { - case .beforeTool: .beforeTool - case .afterTool: .afterTool - case .sessionStart: .sessionStart - case .sessionEnd: .sessionEnd - case .native(let v): .native(v) - } - } - static func operation(_ value: PermissionOperationDeclaration) -> PermissionOperation { - switch value { - case .read: .read - case .write: .write - case .execute: .execute - case .tool(let v): .tool(v) - } - } - static func rule(_ value: PermissionRuleDeclaration) -> PermissionRule { - switch value { - case .allow(let op, let pattern): .allow(operation(op), pattern) - case .ask(let op, let pattern): .ask(operation(op), pattern) - case .deny(let op, let pattern): .deny(operation(op), pattern) - } - } - static func reference(_ value: ComponentReferenceDeclaration) -> ComponentReference { - switch value { - case .skill(let n): .skill(name: n) - case .instruction(let n): .instruction(name: n) - case .mcpServer(let n): .mcpServer(name: n) - case .hook(let n): .hook(name: n) - case .subagent(let n): .subagent(name: n) - case .command(let n): .command(name: n) - case .lspServer(let n): .lspServer(name: n) - case .permissions(let n): .permissions(name: n) - case .ignore(let n): .ignore(name: n) - case .plugin(let n): .plugin(name: n) - } - } - static func kind(_ value: DeclaredComponentKind) -> AgentsDescription.ComponentKind { - switch value { - case .skills: .skills - case .instructions: .instructions - case .mcpServer: .mcpServer - case .hook: .hook - case .subagent: .subagent - case .command: .command - case .lspServer: .lspServer - case .permissions: .permissions - case .ignore: .ignore - case .plugin: .plugin - } - } - static func use(_ value: GroupUseDeclaration) -> GroupReference { - if let source = value.source { - return .group(name: value.name, source: source, condition: condition(value.condition)) - } - return .group(name: value.name, condition: condition(value.condition)) - } - static func group(_ value: ComponentGroupDeclaration) -> ComponentGroup { - .group( - name: value.name, components: value.components.map(component), uses: value.uses.map(use), - condition: condition(value.condition)) - } - static func component(_ value: ComponentDeclaration) -> Component { - switch value { - case .skills(let source, let v): return skills(alias: source, v) - case .instructions(let v): return instructions(v) - case .mcpServer(let name, let v, let agents, let when, let config): - return .mcpServer( - name: name, transport: transport(v), agents: agents.map { $0.map(agent) }, - condition: condition(when), native: native(config)) - case .hook(let name, let e, let run, let matcher, let timeout, let agents, let when, let config): - return .hook( - name: name, event: event(e), run: executable(run), matcher: matcher, - timeoutSeconds: timeout, agents: agents.map { $0.map(agent) }, condition: condition(when), - native: native(config)) - case .subagent( - let name, let description, let prompt, let model, let tools, let agents, let when, let config): - return .subagent( - name: name, description: description, prompt: promptBody(prompt), model: model, - tools: tools, agents: agents.map { $0.map(agent) }, condition: condition(when), - native: native(config)) - case .command( - let name, let description, let prompt, let parameters, let agents, let when, let config): - return .command( - name: name, description: description, prompt: promptBody(prompt), - parameters: parameters.map { - .parameter(name: $0.name, description: $0.description, defaultValue: $0.defaultValue) - }, agents: agents.map { $0.map(agent) }, condition: condition(when), native: native(config)) - case .lspServer(let name, let run, let languages, let options, let agents, let when, let config): - return .lspServer( - name: name, run: executable(run), languages: languages, - initializationOptions: options.mapValues(nativeValue), agents: agents.map { $0.map(agent) }, - condition: condition(when), native: native(config)) - case .permissions(let name, let rules, let agents, let when, let config): - return .permissions( - name: name, rules: rules.map(rule), agents: agents.map { $0.map(agent) }, - condition: condition(when), native: native(config)) - case .ignore(let name, let patterns, let purpose, let agents, let when, let config): - return .ignore( - name: name, patterns: patterns, purpose: purpose == .context ? .context : .indexing, - agents: agents.map { $0.map(agent) }, condition: condition(when), native: native(config)) - case .plugin( - let name, let path, let source, let mode, let select, let exclude, let agents, let when, - let config): - return .plugin( - name: name, path: path, source: source, mode: mode == .native ? .native : .components, - select: select.map { $0.map(kind) }, exclude: exclude.map(reference), - agents: agents.map { $0.map(agent) }, condition: condition(when), native: native(config)) - } - } -} diff --git a/Sources/AgentsManifest/ConstructionValueAccessors.swift b/Sources/AgentsManifest/ConstructionValueAccessors.swift deleted file mode 100644 index e686e76..0000000 --- a/Sources/AgentsManifest/ConstructionValueAccessors.swift +++ /dev/null @@ -1,21 +0,0 @@ -import AgentsDescription - -extension ConstructionValue { - var text: String? { - if case .text(let value) = self { return value } - return nil - } - var array: [ConstructionValue]? { - if case .array(let value) = self { return value } - return nil - } - var strings: [String]? { array?.compactMap(\.text) } - var fields: [String: ConstructionValue] { - if case .node(_, _, let fields) = self { return fields } - return [:] - } - var member: String { - if case .node(_, let member, _) = self { return member } - return "" - } -} diff --git a/Sources/AgentsManifest/DeclarationConstruction.swift b/Sources/AgentsManifest/DeclarationConstruction.swift deleted file mode 100644 index ab95f3d..0000000 --- a/Sources/AgentsManifest/DeclarationConstruction.swift +++ /dev/null @@ -1,141 +0,0 @@ -import AgentsCore -import AgentsDescription - -/// Constructs the complete symbolic declaration without linking or evaluating conditions. -package enum DeclarationConstruction { - package static func root(_ declaration: Declaration) throws -> Agents { - Agents( - defaultAgents: declaration.agents.map { $0.map(agent) }, exports: declaration.exports, - sources: try declaration.sourceDeclarations.map { try source(alias: $0.name, $0.source) }, - components: declaration.components.map(component), groups: declaration.groups.map(group), - uses: declaration.uses.map(use), watch: declaration.watch ?? []) - } - - /// Git sources use complete transport URLs. Version ranges are checked before construction. - package static func source(alias: String, _ source: SourceDeclaration) throws -> Source { - let subpath = source.path - guard source.kind != .wellKnown else { - guard source.requirement == nil else { - throw CoreError.invalidState("well-known sources take no Git requirement") - } - return .source(name: alias, index: source.location, subpath: subpath) - } - let git = source.kind == .git - let location = git ? source.gitURL : source.location - guard let requirement = source.requirement else { - return git - ? .source(name: alias, url: location, subpath: subpath) - : .source(name: alias, path: location, subpath: subpath) - } - switch requirement { - case .branch(let branch): - return git - ? .source(name: alias, url: location, branch: branch, subpath: subpath) - : .source(name: alias, path: location, branch: branch, subpath: subpath) - case .revision(let revision): - return git - ? .source(name: alias, url: location, revision: revision, subpath: subpath) - : .source(name: alias, path: location, revision: revision, subpath: subpath) - case .exact(let version): - let exact = Version(stringLiteral: version) - return git - ? .source(name: alias, url: location, exact: exact, subpath: subpath) - : .source(name: alias, path: location, exact: exact, subpath: subpath) - case .upToNextMajor(let lower): - let from = Version(stringLiteral: lower) - return git - ? .source(name: alias, url: location, from: from, subpath: subpath) - : .source(name: alias, path: location, from: from, subpath: subpath) - case .upToNextMinor(let lower), .range(let lower, _): - let range: Range - if case .range(_, let upper) = requirement { - let (from, to) = (Version(stringLiteral: lower), Version(stringLiteral: upper)) - guard from < to else { throw CoreError.invalidState("invalid version range") } - range = from.. Component { - return .skills( - source: alias, select: selection(skills.select), - exclude: skills.exclude ?? [], mode: skills.mode.map(mode), - overrides: skills.overrideDeclarations.map { override(name: $0.name, $0.override) }, - agents: skills.agents.map { $0.map(agent) }, condition: condition(skills.condition), - native: native(skills.native)) - } - - package static func selection( - _ selection: AgentsCore.SkillSelection - ) -> AgentsDescription.SkillSelection { - switch selection { - case .all: return .all - case .names(let names): - return AgentsDescription.SkillSelection( - value: .construct( - type: "SkillSelection", member: "names", - fields: ["names": names.constructionValue])) - } - } - - package static func override( - name: String, _ override: AgentsCore.SkillOverride - ) -> AgentsDescription.SkillOverride { - .skill(name: name, mode: override.mode.map(mode), agents: override.agents.map { $0.map(agent) }) - } - - package static func instructions(_ instructions: InstructionsDeclaration) -> Component { - .instructions( - sections: instructions.sectionReferences.map(section), - chatGPT: instructions.prompts.map { prompt(name: $0.name, $0.prompt) }, - agents: instructions.agents.map { $0.map(agent) }, - condition: condition(instructions.condition), native: native(instructions.native)) - } - - package static func prompt(name: String, _ prompt: PromptDeclaration) -> ChatGPTPrompt { - .prompt( - name: name, sections: prompt.sectionReferences.map(section), append: prompt.append, - condition: condition(prompt.condition)) - } - - package static func section(_ section: SectionDeclaration) -> SectionReference { - .section(name: section.name, source: section.source, condition: condition(section.condition)) - } - - /// `alias:name` names a source section; a bare name is the declaring project's own section. - package static func section(_ reference: String) -> SectionReference { - guard let colon = reference.firstIndex(of: ":") else { - return SectionReference(stringLiteral: reference) - } - return .section( - name: String(reference[reference.index(after: colon)...]), - source: String(reference[.. [Agent]? { - agents.map { Set($0).sorted { utf8Less($0.rawValue, $1.rawValue) }.map(agent) } - } - - package static func agent(_ agent: AgentID) -> Agent { - switch agent { - case .claudeCode: .claudeCode - case .codex: .codex - case .cursor: .cursor - case .geminiCLI: .geminiCLI - case .opencode: .openCode - } - } - - package static func mode(_ mode: AgentsCore.InstallMode) -> AgentsDescription.InstallMode { - switch mode { - case .link: .link - case .copy: .copy - case .edit: .edit - } - } -} diff --git a/Sources/AgentsManifest/DeclarationDocument.swift b/Sources/AgentsManifest/DeclarationDocument.swift index b2398d0..07fd9d4 100644 --- a/Sources/AgentsManifest/DeclarationDocument.swift +++ b/Sources/AgentsManifest/DeclarationDocument.swift @@ -1,150 +1,85 @@ import AgentsCore -import AgentsDescription import Foundation -import SwiftSyntax +/// A fully admitted, schema-checked and domain-valid immutable YAML declaration snapshot. public struct DeclarationDocument: Sendable { public let declaration: DeclarationIR public let diagnostics: [ManifestDiagnostic] public let sourceMap: DeclarationSourceMap public let digest: String - package let metrics: FrontEndMetrics public var bytes: [UInt8] { source.bytes } + package let metrics: FrontEndMetrics let source: SourceText - let admission: Admission - let syntax: SourceFileSyntax - let evaluation: Evaluation - let locations: [String: NodeID] - let values: [String: EvaluatedValue] + let root: YAMLNode + let locations: [String: YAMLNode] + let defaulted: Set + let comments: [Range] public init(bytes: [UInt8], identity: DocumentIdentity) throws { try self.init(bytes: bytes, identity: identity, validateDomain: true) } + /// Private drafts remain parser/schema/budget checked; only the edit composer can construct + /// them, and it validates the complete final domain before any bytes leave preparation. init( bytes: [UInt8], identity: DocumentIdentity, validateDomain: Bool, observe: ((FrontEndStage, FrontEndMetrics) -> Void)? = nil ) throws { - let result = try ManifestFrontEnd.run( - bytes: bytes, identity: identity, checking: .declaration, - validateDomain: validateDomain, observe: observe) - source = result.source - admission = result.admission - syntax = result.syntax - let values = result.declaration! - evaluation = values.evaluation - declaration = values.ir - diagnostics = values.diagnostics - digest = values.digest - sourceMap = DeclarationSourceMap(entries: values.map.entries) - locations = values.map.locations - self.values = values.map.values - metrics = result.metrics - } - - /// A JSON Pointer into the lowered declaration: empty string denotes the root, - /// arrays use decimal indexes, and object keys escape `~` as `~0` and `/` as `~1`. - /// Source requirements and literal wrappers use their lowered fields (for example `/value`). - public func node(at pointer: String) -> NodeID? { locations[pointer] } - /// Addresses a constant definition by its Swift identifier, without pointer escaping. - public func constant(named name: String) -> NodeID? { - locations["/constants/" + pointerEscape(name)] - } - /// Returns snapshot handles for all direct and transitive uses of this Swift identifier. - public func uses(ofConstant name: String) -> [NodeID] { - var pending = [name] - var seen = Set() - var references = Set() - while let name = pending.popLast() { - if !seen.insert(name).inserted { continue } - for id in evaluation.references[name] ?? [] { - references.insert(id) - let offset = admission.nodes[id].range.lowerBound - if let owner = admission.declarations.first(where: { $0.range.contains(offset) }), - owner.name != "agents" - { - pending.append(owner.name) - } - } + source = SourceText(Array(bytes.prefix(ManifestLimits.Input.bytes + 1)), identity: identity) + let parsed = try YAMLParser.parse(source, observe: observe) + let validation = YAMLValidation(source: source) + do { try validation.validate(parsed.root) } catch let failure as ManifestFailure { + throw ManifestFailure(failure.diagnostics[0], metrics: parsed.metrics, stage: .decoding) } - return references.sorted().map { - NodeID(digest: digest, pointer: "/references/\($0)", syntax: $0) + observe?(.lowering, parsed.metrics) + let projection = YAMLProjection(source: source) + declaration = try projection.declaration(parsed.root) + try validateIRBudget(IRTree.root(declaration), source: source) + observe?(.domain, parsed.metrics) + var diagnostics: [ManifestDiagnostic] = [] + if validateDomain { + do { + diagnostics = try YAMLDomainValidation( + declaration: declaration, source: source, locations: projection.locations + ).validate() + } catch let failure as ManifestFailure { + throw ManifestFailure(failure.diagnostics[0], metrics: parsed.metrics, stage: .domain) + } } + defaulted = Set(projection.entries.filter(\.defaulted).map(\.pointer)) + comments = parsed.comments + root = parsed.root + locations = projection.locations + sourceMap = DeclarationSourceMap(entries: projection.entries) + digest = "sha256:" + FileHash.sha256Hex(data: Data(bytes)) + self.diagnostics = diagnostics + var metrics = parsed.metrics + metrics.parserCalls = 1 + metrics.syntaxNodes = parsed.nodes + metrics.syntaxDepth = parsed.depth + metrics.evaluationSteps = validation.work + metrics.expandedNodes = IRTree.count(IRTree.root(declaration)) + metrics.decodedBytes = validation.strings + observe?(.sourceMap, metrics) + self.metrics = metrics } - /// Agrees with the editor: elements and entries of a direct collection literal and signature - /// arguments of a direct construction, including omitted ones, are direct, as are member values - /// such as `.copy`. References, concatenations, normalized fields such as source requirements - /// and component kinds, and everything inside a read-only value are read-only. - public func editability(of node: NodeID) -> Editability { - guard node.digest == digest, values[node.pointer]?.syntax == node.syntax else { - return .readOnly(reason: "stale snapshot handle") - } - if node.pointer.hasPrefix("/constants/") { - let name = pointerUnescape(String(node.pointer.dropFirst("/constants/".count))) - return .sharedConstant(uses: uses(ofConstant: name)) - } - return editability(at: node.pointer) + /// JSON Pointers address complete semantic IR, including indexed sources, groups and prompts. + public func node(at pointer: String) -> NodeID? { + locations[pointer].map { NodeID(digest: digest, pointer: pointer, syntax: $0.range.lowerBound) } } - private func editability(at pointer: String) -> Editability { - guard let value = values[pointer] else { + public func editability(of node: NodeID) -> Editability { + guard node.digest == digest, locations[node.pointer]?.range.lowerBound == node.syntax else { return .readOnly(reason: "stale snapshot handle") } - // Containing values are checked by the recursion below, so each entry costs its depth. - if value.referent != nil { - return .readOnly( - reason: "shared constant or assembled value; replace its definition explicitly") - } - if admission.nodes[value.syntax].kind == .sequence { - return .readOnly(reason: "concatenated value has no independent source range") - } - guard let slash = pointer.lastIndex(of: "/") else { return .direct } - let parent = String(pointer[.. Bool { - var prefix = pointer - while let slash = prefix.lastIndex(of: "/"), slash != prefix.startIndex { - prefix = String(prefix[.. DocumentChange { try DocumentEditor(document: self).prepare(edits) } - - package func preparing(operations: [DocumentOperation]) throws -> DocumentChange { - try DocumentEditor(document: self).prepare(operations: operations) - } } diff --git a/Sources/AgentsManifest/DeclarationEditPlan.swift b/Sources/AgentsManifest/DeclarationEditPlan.swift index b9303ee..268d2a2 100644 --- a/Sources/AgentsManifest/DeclarationEditPlan.swift +++ b/Sources/AgentsManifest/DeclarationEditPlan.swift @@ -1,470 +1,88 @@ import AgentsCore -import AgentsDescription -/// Turns a declaration change into source bytes. Existing documents receive the smallest edits -/// that express the semantic difference, including ordered occurrence changes. Bytes outside -/// the edited ranges, including comments, are unchanged. Batches hold at most 100 requests and are replanned -/// against the bytes each batch produces. The final document must project to `next`. package enum DeclarationEditPlan { - /// Returns `nil` when `next` is semantically equal to `previous`. Without existing bytes, the - /// canonical printer writes the complete document, and a semantically empty `next` writes none. - /// `previous` must equal the projection of `bytes`; `manifest.edit.baseline` reports a caller - /// whose preparation no longer describes the document. package static func bytes( replacing previous: Declaration, with next: Declaration, in bytes: [UInt8]?, identity: DocumentIdentity, environment: RuntimeEnvironment ) throws -> [UInt8]? { - try self.bytes( - replacing: previous, with: next, in: bytes, identity: identity, environment: environment, - planning: { $0 }) - } - - // A module-internal seam alters planned batches to exercise the final comparison. - static func bytes( - replacing previous: Declaration, with next: Declaration, in bytes: [UInt8]?, - identity: DocumentIdentity, environment: RuntimeEnvironment, - planning adjust: ([DocumentOperation]) -> [DocumentOperation] - ) throws -> [UInt8]? { - func equivalent(_ lhs: Declaration, _ rhs: Declaration) -> Bool { - ManifestProjection.equivalent(lhs, rhs, environment: environment) - } + try next.validate(environment: environment) guard let bytes else { - guard equivalent(previous, Declaration()) else { - throw failure( - "manifest.edit.baseline", "the declaration has no document to edit", - span: SourceSpan(document: identity, start: 0, end: 0, line: 1, column: 1)) + if ManifestProjection.equivalent(previous, next, environment: environment) { return nil } + let ir = YAMLConstruction.root(next) + try validateIRBudget(IRTree.root(ir), source: SourceText([], identity: identity)) + let output = YAMLWriter.manifest(ir) + let document = try DeclarationDocument(bytes: output, identity: identity) + guard + ManifestProjection.equivalent( + try ManifestProjection.declaration(of: document, environment: environment), next, + environment: environment) + else { + throw document.source.failure( + "manifest.edit.mismatch", "constructed declaration differs from intended domain", 0) } - if equivalent(next, Declaration()) { return nil } - let output = try CanonicalPrinter().manifest( - DeclarationConstruction.root(next).constructionValue) - try verify( - DeclarationDocument(bytes: output, identity: identity), next, environment: environment) return output } - var document = try DeclarationDocument(bytes: bytes, identity: identity) - var current = try ManifestProjection.declaration(of: document, environment: environment) - guard equivalent(current, previous) else { - throw failure( - "manifest.edit.baseline", "the document changed after the declaration was read", - span: document.source.span(0..<0)) - } - if equivalent(previous, next) { return nil } - let target = try DeclarationConstruction.root(next).constructionValue - let targetCost = try DocumentEditor(document: document).valueCost(target) - // Direct differences finalize fields, insert/delete occurrences, or move them toward - // retained subsequence anchors. Each original/target node needs at most a field edit and - // an occurrence edit. Replanning must also strictly reduce the remaining operation count. - var operationBudget = 2 * (document.evaluation.root.cost.nodes + targetCost.nodes) - var remaining = Int.max - // Keep operation counts comparable across drafts: a source move can make a complete - // edit eligible for the flat path, whose insertion/deletion counts use different units. - let complete = Planner( - document: document, current: current, next: next, environment: environment - ).requiresCompletePlanning - while true { - var planner = Planner( - document: document, current: current, next: next, environment: environment) - let operations = adjust(try planner.plan(complete: complete)) - if operations.isEmpty { break } - guard operations.count < remaining else { - throw failure( - "manifest.edit.mismatch", "an edit batch made no progress", - span: document.source.span(0..<0)) - } - // Each operation re-evaluates the snapshot, scans syntax for local style and checks - // expected values. Size the prefix from that snapshot work, leaving room for growth - // and the final IR comparison. Actual charges still enforce the batch budget; failures - // are never retried with a fresh counter. - let snapshotWork = - document.metrics.evaluationSteps + document.metrics.syntaxNodes - + document.admission.nodes.count + 4 * document.evaluation.root.cost.nodes - let workRequests = max(1, ManifestLimits.Editing.steps / (2 * snapshotWork)) - let batch = Array(operations.prefix(min(ManifestLimits.Editing.requests, workRequests))) - guard batch.count <= operationBudget else { - throw failure( - "manifest.limit", "declaration composition operation budget", - span: document.source.span(0..<0)) - } - operationBudget -= batch.count - let draft = try DocumentEditor(document: document).prepareDraft(operations: batch) - guard draft.document.bytes != document.bytes else { - throw failure( - "manifest.edit.mismatch", "an edit batch made no progress", - span: document.source.span(0..<0)) - } - remaining = operations.count - document = draft.document - current = try ManifestProjection.draftDeclaration(of: document, environment: environment) - } - let validated = try DeclarationDocument(bytes: document.bytes, identity: identity) - try verify(validated, next, environment: environment) - return validated.bytes - } - - private static func verify( - _ document: DeclarationDocument, _ next: Declaration, environment: RuntimeEnvironment - ) throws { - let result = try ManifestProjection.declaration(of: document, environment: environment) - guard ManifestProjection.equivalent(result, next, environment: environment) else { - throw failure( - "manifest.edit.mismatch", "the edited document differs from the intended declaration", - span: document.source.span(0..<0)) - } - } - - static func failure(_ code: String, _ message: String, span: SourceSpan) -> ManifestFailure { - ManifestFailure(ManifestDiagnostic(code: code, message: message, span: span)) - } -} - -/// Plans skill/instruction edits or delegates complete occurrence changes over one snapshot. -/// Collections receive insertions before removals, so retained elements stay insertion anchors. -/// Internal drafts defer domain validation until the complete edit is ready. -private struct Planner { - let document: DeclarationDocument - let current: Declaration - let next: Declaration - let environment: RuntimeEnvironment - var operations: [DocumentOperation] = [] - - var requiresCompletePlanning: Bool { - !flat(current) || !flat(next) || !flatOrder() || current.groups != next.groups - || current.uses != next.uses || current.exports != next.exports - } - - mutating func plan(complete: Bool) throws -> [DocumentOperation] { - if complete { - return try CompleteDeclarationPlanner( - document: document, current: current, next: next, environment: environment - ).plan() - } - // Flat operations preserve this shape and uniqueness even while domain constraints are - // deferred. Reject a malformed draft rather than switching strategy or using lossy views. - guard flat(current) else { - throw DeclarationEditPlan.failure( - "manifest.ambiguous", "draft is no longer an unambiguous flat declaration", - span: document.source.span(0..<0)) - } - var skillComponents: [String: Int] = [:] - var instructionsComponent: Int? - for (index, component) in document.declaration.components.enumerated() { - if component.kind == "skills", let alias = component["source"]?.string { - skillComponents[alias] = index - } else if component.kind == "instructions" { - instructionsComponent = index - } - } - for alias in next.sources.keys.sorted(by: utf8Less) { - let source = next.sources[alias]! - if let existing = current.sources[alias], - ManifestProjection.equivalent(existing, source, environment: environment) + let original = try DeclarationDocument(bytes: bytes, identity: identity) + let current = try ManifestProjection.declaration(of: original, environment: environment) + guard ManifestProjection.equivalent(current, previous, environment: environment) else { + throw original.source.failure( + "manifest.edit.baseline", "declaration changed during preparation", 0) + } + if ManifestProjection.equivalent(current, next, environment: environment) { return nil } + var target = next + // Retained sources preserve their spelling and comments when identity, requirement and + // subpath agree in their declaring environments. Their authored order still participates. + for index in target.sourceDeclarations.indices { + if let old = current.sourceDeclarations.first(where: { + $0.name == target.sourceDeclarations[index].name + }), + ManifestProjection.equivalent( + old.source, target.sourceDeclarations[index].source, environment: environment) { - continue - } - operations.append( - .edit(.upsertSource(try DeclarationConstruction.source(alias: alias, source)))) - } - try recipients(owner: "", field: "defaultAgents", current.agents, next.agents) - - let currentSkills = (try current.skills) ?? [:] - let nextSkills = (try next.skills) ?? [:] - let retainedInstructions = - (try next.instructions) == nil - ? nil : try instructionsComponent.map { try handle("/components/\($0)") } - for alias in nextSkills.keys.sorted(by: utf8Less) { - if let existing = currentSkills[alias] { - try skills(at: "/components/\(skillComponents[alias]!)", existing, nextSkills[alias]!) - } else { - operations.append( - .edit( - .insertComponent( - DeclarationConstruction.skills(alias: alias, nextSkills[alias]!), into: .root, - at: retainedInstructions.map { .before($0) } ?? .last))) - } - } - switch (instructionsComponent, (try next.instructions)) { - case (let index?, let instructions?): - try self.instructions(at: "/components/\(index)", (try current.instructions)!, instructions) - case (nil, let instructions?): - operations.append( - .edit( - .insertComponent( - DeclarationConstruction.instructions(instructions), into: .root, at: .last))) - case (let index?, nil): - operations.append(.edit(.removeComponent(try handle("/components/\(index)")))) - case (nil, nil): break - } - for alias in currentSkills.keys.sorted(by: utf8Less) where nextSkills[alias] == nil { - operations.append( - .edit(.removeComponent(try handle("/components/\(skillComponents[alias]!)")))) - } - - let watch = (next.watch ?? []).sorted(by: utf8Less) - if Set(current.watch ?? []) != Set(watch) { - if explicit("/watch") { - let changes = try elements(at: "/watch", watch, value: { .text($0) }) - operations += changes.insertions + changes.removals - } else { - operations.append(.edit(.setWatch(watch))) - } - } - for alias in current.sources.keys.sorted(by: utf8Less) where next.sources[alias] == nil { - operations.append(.edit(.removeSource(alias: alias))) - } - return operations - } - - func flatOrder() -> Bool { - func keys(_ declaration: Declaration) -> [String] { - declaration.components.map { component in - switch component { - case .skills(let source, _): "skills:" + source - default: "instructions" - } + target.sourceDeclarations[index].source = old.source } } - let old = keys(current) - let desired = keys(next) - let desiredSet = Set(desired) - var planned = old.filter(desiredSet.contains) - let added = desired.filter { !Set(old).contains($0) && $0 != "instructions" }.sorted( - by: utf8Less) - planned.insert( - contentsOf: added, at: planned.firstIndex(of: "instructions") ?? planned.endIndex) - if desiredSet.contains("instructions"), !old.contains("instructions") { - planned.append("instructions") - } - let oldSources = current.sourceDeclarations.map(\.name) - let newSources = next.sourceDeclarations.map(\.name) - let newSet = Set(newSources) - let sourceOrder = - oldSources.filter(newSet.contains) - + newSources.filter { !Set(oldSources).contains($0) }.sorted(by: utf8Less) - let oldPrompts = (try? current.instructions)?.prompts.map(\.name) ?? [] - let newPrompts = (try? next.instructions)?.prompts.map(\.name) ?? [] - let promptSet = Set(newPrompts) - let promptOrder = - oldPrompts.filter(promptSet.contains) - + newPrompts.filter { !Set(oldPrompts).contains($0) }.sorted(by: utf8Less) - return planned == desired && sourceOrder == newSources && promptOrder == newPrompts - } - - func flat(_ value: Declaration) -> Bool { - let sources = value.sourceDeclarations.map(\.name) - guard Set(sources).count == sources.count else { return false } - var aliases = Set() - var instructions = false - for component in value.components { - switch component { - case .skills(let source, let selection): - let overrides = selection.overrideDeclarations.map(\.name) - if !aliases.insert(source).inserted || selection.condition != nil - || !selection.native.isEmpty || Set(overrides).count != overrides.count - { - return false - } - case .instructions(let selection): - let prompts = selection.prompts.map(\.name) - if instructions || selection.condition != nil || !selection.native.isEmpty - || Set(prompts).count != prompts.count - || selection.sectionReferences.contains(where: { $0.condition != nil }) - || selection.prompts.contains(where: { - $0.prompt.condition != nil - || $0.prompt.sectionReferences.contains(where: { $0.condition != nil }) - }) - { - return false - } - instructions = true - default: return false - } - } - return true - } - - mutating func skills( - at pointer: String, _ current: SkillDeclaration, _ next: SkillDeclaration - ) throws { - let owner = try handle(pointer) - var reductions: [DocumentOperation] = [] - switch (current.select, next.select) { - case (.all, .all): break - case (.names(let old), .names(let new)) where Set(old) == Set(new): break - case (.names, .names(let names)): - let changes = try elements( - at: pointer + "/select", names.sorted(by: utf8Less), value: { .text($0) }) - operations += changes.insertions - reductions = changes.removals - case (.names, .all): - operations.append(.edit(.setSkillSelection(owner, .all))) - case (.all, .names(let names)): - reductions = [ - .edit( - .setSkillSelection( - owner, DeclarationConstruction.selection(.names(names.sorted(by: utf8Less))))) - ] - } - let currentOverrides = current.overrides ?? [:] - let nextOverrides = next.overrides ?? [:] - for name in nextOverrides.keys.sorted(by: utf8Less) { - let override = nextOverrides[name]! - if let existing = currentOverrides[name], ManifestProjection.equivalent(existing, override) { - continue - } - operations.append( - .edit( - .upsertSkillOverride(owner, DeclarationConstruction.override(name: name, override)))) - } - for name in currentOverrides.keys.sorted(by: utf8Less) where nextOverrides[name] == nil { - operations.append(.edit(.removeSkillOverride(owner, name: name))) - } - operations += reductions - let exclude = (next.exclude ?? []).sorted(by: utf8Less) - if Set(current.exclude ?? []) != Set(exclude) { - if explicit(pointer + "/exclude") { - let changes = try elements(at: pointer + "/exclude", exclude, value: { .text($0) }) - operations += changes.insertions + changes.removals - } else { - operations.append( - .setArgument(owner, field: "exclude", value: exclude.constructionValue)) - } - } - if current.mode != next.mode { - operations.append( - .setArgument( - owner, field: "mode", value: next.mode.map(DeclarationConstruction.mode).constructionValue - )) - } - try recipients(owner: pointer, field: "agents", current.agents, next.agents) - } - - mutating func instructions( - at pointer: String, _ current: InstructionsDeclaration, _ next: InstructionsDeclaration - ) throws { - let owner = try handle(pointer) - try recipients(owner: pointer, field: "agents", current.agents, next.agents) - if current.sections != next.sections { - let kept = try commonSubsequence(current.sections, next.sections) - let keptCurrent = Set(kept.map(\.0)) - let keptNext = Set(kept.map(\.1)) - for index in next.sections.indices where !keptNext.contains(index) { - // Inserting before the next retained section keeps several insertions in order. - let anchor = try kept.first { $0.1 > index }.map { - InsertionPosition.before(try handle(pointer + "/sections/\($0.0)")) - } - operations.append( - .edit( - .insertSection( - DeclarationConstruction.section(next.sections[index]), into: owner, - at: anchor ?? .last))) - } - for index in current.sections.indices where !keptCurrent.contains(index) { - operations.append(.edit(.removeSection(try handle(pointer + "/sections/\(index)")))) - } - } - let currentPrompts = current.chatgpt ?? [:] - let nextPrompts = next.chatgpt ?? [:] - for name in nextPrompts.keys.sorted(by: utf8Less) - where currentPrompts[name] != nextPrompts[name] { - operations.append( - .edit(.upsertPrompt(owner, DeclarationConstruction.prompt(name: name, nextPrompts[name]!)))) - } - for name in currentPrompts.keys.sorted(by: utf8Less) where nextPrompts[name] == nil { - operations.append(.edit(.removePrompt(owner, name: name))) - } - } - - /// Present arrays change element by element; inheritance and its replacement change the - /// whole argument. - mutating func recipients( - owner: String, field: String, _ current: [AgentID]?, _ next: [AgentID]? - ) throws { - guard !ManifestProjection.sameRecipients(current, next) else { return } - let pointer = owner + "/" + field - let agents = DeclarationConstruction.recipients(next) - if current != nil, let agents, explicit(pointer) { - let changes = try elements( - at: pointer, agents.map { Lowering.lower($0.constructionValue).string! }, - value: { DeclarationConstruction.agent(AgentID(rawValue: $0)!).constructionValue }) - operations += changes.insertions + changes.removals - } else if owner.isEmpty { - operations.append(.edit(.setDefaultAgents(agents))) - } else { - operations.append( - .setArgument(try handle(owner), field: field, value: agents.constructionValue)) - } + let intended = IRTree.root(YAMLConstruction.root(target)) + let initial = IRTree.root(original.declaration) + var diff = IRDiff() + try diff.compare(initial, intended) + return try compose( + diff.edits, original: original, intended: intended, next: next, environment: environment) } - /// Element edits that turn the array at `pointer` into canonically ordered `desired`. - /// Insertions keep canonical order when the retained elements already have it. - func elements( - at pointer: String, _ desired: [String], value: (String) -> ConstructionValue - ) throws -> (insertions: [DocumentOperation], removals: [DocumentOperation]) { - let wanted = Set(desired) - let existing = - document.values[pointer].map { Lowering.lower($0.value).elements ?? [] }? - .compactMap(\.string) ?? [] - let kept = existing.enumerated().filter { wanted.contains($0.element) } - let present = Set(kept.map(\.element)) - let ordered = zip(kept, kept.dropFirst()).allSatisfy { utf8Less($0.element, $1.element) } - let container = try handle(pointer) - var insertions: [DocumentOperation] = [] - for element in desired where !present.contains(element) { - let anchor = ordered ? kept.first { utf8Less(element, $0.element) } : nil - insertions.append( - .insertElement( - value(element), into: container, - at: try anchor.map { .before(try handle(pointer + "/\($0.offset)")) } ?? .last)) - } - let removals = try existing.indices.filter { !wanted.contains(existing[$0]) }.map { - DocumentOperation.removeElement(try handle(pointer + "/\($0)")) - } - return (insertions, removals) - } - - func explicit(_ pointer: String) -> Bool { - document.values[pointer].map { !$0.defaulted } ?? false - } - - func handle(_ pointer: String) throws -> NodeID { - guard let node = document.node(at: pointer) else { - throw DeclarationEditPlan.failure( - "manifest.edit.mismatch", "planned edit has no source location", - span: document.source.span(0..<0)) - } - return node - } - - /// Index pairs of a longest common subsequence; duplicates are matched in order. - func commonSubsequence(_ lhs: [String], _ rhs: [String]) throws -> [(Int, Int)] { - let (pairs, overflow) = (lhs.count + 1).multipliedReportingOverflow(by: rhs.count + 1) - guard !overflow, pairs <= ManifestLimits.Editing.comparisonPairs else { - throw DeclarationEditPlan.failure( - "manifest.limit", "section comparison pairs", span: document.source.span(0..<0)) - } - let width = rhs.count + 1 - var lengths = [Int](repeating: 0, count: (lhs.count + 1) * width) - for i in stride(from: lhs.count - 1, through: 0, by: -1) { - for j in stride(from: rhs.count - 1, through: 0, by: -1) { - lengths[i * width + j] = - lhs[i] == rhs[j] - ? lengths[(i + 1) * width + j + 1] + 1 - : max(lengths[(i + 1) * width + j], lengths[i * width + j + 1]) - } - } - var kept: [(Int, Int)] = [] - var (i, j) = (0, 0) - while i < lhs.count && j < rhs.count { - if lhs[i] == rhs[j] { - kept.append((i, j)) - i += 1 - j += 1 - } else if lengths[(i + 1) * width + j] >= lengths[i * width + j + 1] { - i += 1 - } else { - j += 1 - } - } - return kept + static func compose( + _ edits: [IREdit], original: DeclarationDocument, intended: DeclarationValue, next: Declaration, + environment: RuntimeEnvironment + ) throws -> [UInt8] { + let initial = IRTree.root(original.declaration) + // The direct script fixes target positions/fields once. Its length is bounded by the two + // admitted IR structures, independently of how batches are sized or sources transition. + let peakNodes = IRTree.count(initial) + IRTree.count(intended) + let maximum = 2 * peakNodes + guard edits.count <= maximum else { + throw original.source.failure("manifest.limit", "edit composition bound", 0) + } + var currentDocument = original + var offset = 0 + while offset < edits.count { + let cost = 2 * peakNodes + 2 * ManifestLimits.Syntax.nodes + let count = min( + ManifestLimits.Editing.requests, max(1, ManifestLimits.Editing.steps / max(1, cost))) + let end = min(edits.count, offset + count) + currentDocument = try DocumentEditor.draft(Array(edits[offset..? = nil) -> ManifestFailure { - current.source.failure( - code, message, (range ?? 0..<0).lowerBound, end: (range ?? 0..<0).upperBound) - } - func charge(_ count: Int) throws { - if count > ManifestLimits.Editing.steps - steps { - throw fail("manifest.limit", "edit batch work steps") + func prepare(_ edits: [ManifestEdit]) throws -> DocumentChange { + guard edits.count <= ManifestLimits.Editing.requests else { + throw failure("manifest.limit", "edit request limit") } - steps += count - } - func valueCost(_ value: ConstructionValue) throws -> ValueCost { - // Iterative preflight bounds external vocabulary values before recursive consumers. - var pending: [(ConstructionValue, Int)] = [(value, 1)] - var nodes = 0 - var strings = 0 - while let (value, depth) = pending.popLast() { - try charge(1) - nodes += 1 - if nodes > ManifestLimits.Values.nodes || depth > ManifestLimits.Values.depth { - throw fail("manifest.limit", "edit value node/depth budget") - } - let children: [ConstructionValue] - switch value { - case .text(let text): - strings = ValueCost.add(strings, text.utf8.count) - children = [] - case .array(let values): - if values.count > ManifestLimits.Values.entries { - throw fail("manifest.limit", "edit collection entries") - } - children = values - case .object(let fields), .node(_, _, let fields): - if fields.count > ManifestLimits.Values.entries { - throw fail("manifest.limit", "edit dictionary entries") + var current = document + var pointers: [String] = [] + var work = 0 + var comparisons = 0 + var handles = Dictionary(uniqueKeysWithValues: document.locations.keys.map { ($0, $0) }) + for edit in edits { + let requested = try operations(edit, in: current, handles: handles) + var operations: [IREdit] = [] + for request in requested { + if case .set(let pointer, let replacement?) = request, + let old = IRTree.value(IRTree.root(current.declaration), at: pointer) + { + var diff = IRDiff(comparisons: comparisons) + try diff.compare(old, replacement, at: pointer) + comparisons = diff.comparisons + operations += diff.edits + } else { + operations.append(request) } - strings = ValueCost.add(strings, fields.keys.reduce(0) { ValueCost.add($0, $1.utf8.count) }) - children = Array(fields.values) - case .version(let version): - strings = ValueCost.add(strings, version.normalized.utf8.count) - children = [] - case .range(let range): children = [.version(range.lowerBound), .version(range.upperBound)] - default: children = [] } - if strings > ManifestLimits.Values.stringBytes - || pending.count + children.count > ManifestLimits.Values.nodes - { - throw fail("manifest.limit", "edit expanded value bytes/nodes") + var offset = 0 + while offset < operations.count { + let end = min(operations.count, offset + ManifestLimits.Editing.requests) + let batch = try Self.draft(Array(operations[offset.. DocumentChange { - try prepare(operations: edits.map(DocumentOperation.edit)) - } - - func prepare(operations: [DocumentOperation]) throws -> DocumentChange { - let draft = try prepareDraft(operations: operations) - // Public prepared changes always have valid final domain semantics, including no-ops - // prepared from a module-internal draft snapshot. - let candidate = try DeclarationDocument( - bytes: draft.document.bytes, identity: original.source.identity) - if candidate.bytes == original.bytes { - return DocumentChange( - originalDigest: original.digest, patches: [], bytes: candidate.bytes, - digest: candidate.digest, expectedDeclaration: candidate.declaration, - impactedReferences: [], diagnostics: candidate.diagnostics, - delta: SemanticDelta(changedPointers: [])) + let final = try DeclarationDocument(bytes: current.bytes, identity: document.source.identity) + guard final.declaration == current.declaration else { + throw failure("manifest.edit.mismatch", "final declaration differs from intended IR") } - return DocumentChange( - originalDigest: original.digest, patches: table.patches(), bytes: candidate.bytes, - digest: candidate.digest, expectedDeclaration: candidate.declaration, - impactedReferences: Array(Set(impacted)).sorted { $0.syntax < $1.syntax }, - diagnostics: candidate.diagnostics, delta: try semanticDelta()) - } - - /// A checked static snapshot for composing a complete declaration edit. It is not a - /// publishable change; only the composition owner may validate and return its final bytes. - struct DraftBatch { - let document: DeclarationDocument + return Self.change(from: document, to: final, pointers: pointers) } - func prepareDraft(operations: [DocumentOperation]) throws -> DraftBatch { - if operations.count > ManifestLimits.Editing.requests { - throw fail("manifest.limit", "edit batch has more than 100 requests") + /// Drafts cannot be published. Every operation refreshes the CST/source map and checks full + /// expected IR; only domain reference validation is deferred across private composition. + static func draft(_ edits: [IREdit], in document: DeclarationDocument) throws -> DraftBatch { + guard edits.count <= ManifestLimits.Editing.requests else { + throw document.source.failure("manifest.limit", "edit request limit", 0) } - for operation in operations { - let before = history.count - try apply(operation) - if before != history.count { - current = try DeclarationDocument( - bytes: table.bytes, identity: original.source.identity, validateDomain: false) - try charge(current.metrics.evaluationSteps + current.metrics.syntaxNodes) - } - } - let expectedCost = try valueCost(expected) - try charge(expectedCost.nodes) - let bytes = table.bytes - let candidate = try DeclarationDocument( - bytes: bytes, identity: original.source.identity, validateDomain: false) - let actualCost = candidate.evaluation.root.cost - if expectedCost.nodes + actualCost.nodes > ManifestLimits.Editing.comparisonPairs { - throw fail("manifest.limit", "comparison node-pair budget") - } - try charge(expectedCost.nodes + actualCost.nodes) - let expectedIR = Lowering.declaration(expected) - guard candidate.declaration == expectedIR else { - throw fail( - "manifest.edit.mismatch", "complete candidate differs from the expected declaration") - } - return DraftBatch(document: candidate) + var work = 0 + return try draft(edits, in: document, work: &work) } - func semanticDelta() throws -> SemanticDelta { - var pending: [(DeclarationValue, DeclarationValue, String)] = [ - (Lowering.lower(original.evaluation.root.value), Lowering.lower(expected), "") - ] - var visited = 0 - var pointers: [String] = [] - while let (left, right, pointer) = pending.popLast() { - try charge(1) - visited += 1 - if visited > ManifestLimits.Editing.comparisonPairs { - throw fail("manifest.limit", "semantic delta comparison node pairs") + private static func draft(_ edits: [IREdit], in document: DeclarationDocument, work: inout Int) + throws -> DraftBatch + { + var current = document + var changed: [String] = [] + for edit in edits { + let old = IRTree.root(current.declaration) + let expected = edit.applying(to: old) + work += + IRTree.count(old) + IRTree.count(expected) + current.metrics.syntaxNodes + + current.comments.count + try validateIRBudget(expected, source: document.source) + guard work <= ManifestLimits.Editing.steps else { + throw document.source.failure("manifest.limit", "edit batch work steps", 0) + } + if expected == old { continue } + let patches = try YAMLPatches(document: current).patches(for: edit, expected: expected) + var bytes = current.bytes + let sorted = patches.sorted { $0.range.lowerBound > $1.range.lowerBound } + var boundary = bytes.count + for patch in sorted { + guard patch.range.lowerBound >= 0, patch.range.upperBound <= boundary else { + throw document.source.failure("manifest.edit.mismatch", "overlapping edit patches", 0) + } + bytes.replaceSubrange(patch.range, with: patch.replacement) + boundary = patch.range.lowerBound } - switch (left, right) { - case (.array(let a), .array(let b)) where a.count == b.count: - for index in a.indices { pending.append((a[index], b[index], pointer + "/\(index)")) } - case (.dictionary(let a), .dictionary(let b)) where a.keys == b.keys: - for key in a.keys { pending.append((a[key]!, b[key]!, pointer + "/" + pointerEscape(key))) } - case (.record(let a), .record(let b)) where a.kind == b.kind: - pending.append((.dictionary(a.fields), .dictionary(b.fields), pointer)) - default: - if left != right { pointers.append(pointer) } + let next = try DeclarationDocument( + bytes: bytes, identity: document.source.identity, validateDomain: false) + guard IRTree.root(next.declaration) == expected else { + throw document.source.failure( + "manifest.edit.mismatch", "edit differs from full expected declaration", 0) } - if pending.count > ManifestLimits.Editing.comparisonPairs - visited { - throw fail("manifest.limit", "semantic delta scheduled pairs") + guard next.bytes != current.bytes else { + throw document.source.failure("manifest.edit.mismatch", "an edit batch made no progress", 0) + } + current = next + switch edit { + case .set(let pointer, _), .insert(let pointer, _, _), .remove(let pointer, _), + .move(let pointer, _, _): + changed.append(pointer) + case .relocate(let origin, _, let destination, _): changed += [origin, destination] } } - return SemanticDelta(changedPointers: pointers.sorted()) + return DraftBatch(document: current, changedPointers: changed) } - func requireType(_ pointer: String, _ type: String, member: String? = nil) throws { - guard current.values[pointer]?.type.unwrapped == .named(type), - member == nil || current.values[pointer]?.value.member == member - else { throw fail("manifest.edit.readOnly", "handle has the wrong domain kind") } - } - func resolve(_ handle: NodeID) throws -> String { - guard handle.digest == original.digest, let originalValue = original.values[handle.pointer], - originalValue.syntax == handle.syntax - else { throw fail("manifest.edit.stale", "handle belongs to a different snapshot") } - let mapped = try translated(original.admission.nodes[handle.syntax].range) - if handle.pointer.hasPrefix("/constants/"), let value = current.values[handle.pointer], - current.admission.nodes[value.syntax].range == mapped - { - return handle.pointer + static func change( + from original: DeclarationDocument, to final: DeclarationDocument, pointers: [String] + ) -> DocumentChange { + let a = original.bytes + let b = final.bytes + var first = 0 + while first < min(a.count, b.count) && a[first] == b[first] { first += 1 } + var tail = 0 + while tail < min(a.count, b.count) - first && a[a.count - tail - 1] == b[b.count - tail - 1] { + tail += 1 } - guard - let pointer = current.values.keys.sorted().first(where: { key in - guard let value = current.values[key], !value.defaulted else { return false } - return value.type == originalValue.type - && current.admission.nodes[value.syntax].range == mapped - }) - else { throw fail("manifest.edit.stale", "the addressed occurrence was removed or replaced") } - return pointer + let patches = + a == b + ? [] + : [ + SourcePatch( + range: first..<(a.count - tail), replacement: Array(b[first..<(b.count - tail)])) + ] + return DocumentChange( + originalDigest: original.digest, patches: patches, bytes: b, digest: final.digest, + expectedDeclaration: final.declaration, diagnostics: final.diagnostics, + delta: SemanticDelta(changedPointers: Array(Set(pointers)).sorted(by: utf8Less))) } - /// History ranges use the snapshot immediately before each patch. Earlier siblings - /// translate both bounds; contained edits resize the owner. Crossing an owner boundary - /// cannot preserve occurrence identity and is rejected instead of guessing a pointer. - func translated(_ originalRange: Range) throws -> Range { - var range = originalRange - for patch in history { - let delta = patch.replacement.count - patch.range.count - if patch.range.isEmpty && patch.range.lowerBound == range.lowerBound { - range = (range.lowerBound + delta)..<(range.upperBound + delta) - } else if patch.range.upperBound <= range.lowerBound { - range = (range.lowerBound + delta)..<(range.upperBound + delta) - } else if patch.range.lowerBound >= range.upperBound { - continue - } else if patch.range.lowerBound >= range.lowerBound - && patch.range.upperBound <= range.upperBound - { - if patch.range == range && patch.replacement.isEmpty { - throw fail("manifest.edit.stale", "addressed occurrence was removed") + + private func operations( + _ edit: ManifestEdit, in current: DeclarationDocument, handles: [String: String] + ) throws -> [IREdit] { + let root = IRTree.root(current.declaration) + func pointer(_ id: NodeID) throws -> String { + guard id.digest == document.digest, document.node(at: id.pointer) == id, + let mapped = handles[id.pointer], IRTree.value(root, at: mapped) != nil + else { throw failure("manifest.edit.stale", "stale snapshot handle") } + return mapped + } + func container(_ id: ContainerID, _ field: String) throws -> String { + switch id { + case .root: return "/" + field + case .group(let id): + let path = try pointer(id) + guard IRTree.value(root, at: path)?.record?.kind == "group" else { + throw failure("manifest.edit.readOnly", "expected a group occurrence") } - range = range.lowerBound..<(range.upperBound + delta) - } else { - throw fail("manifest.edit.overlap", "edit overlaps a previously changed occurrence") + return path + "/" + field } } - return range - } - /// Member values such as `.copy` are direct; bare names are references and have referents. - func direct(_ pointer: String) throws -> EvaluatedValue { - guard let value = current.values[pointer], !value.defaulted, value.referent == nil, - !current.hasAssembledAncestor(pointer), - current.admission.nodes[value.syntax].kind != .sequence - else { - throw fail( - "manifest.edit.readOnly", - "target is a shared constant, assembled value or inherited default") + func index(_ position: InsertionPosition, in path: String) throws -> Int { + guard let values = IRTree.value(root, at: path)?.elements else { + throw failure("manifest.edit.readOnly", "expected an ordered collection") + } + switch position { + case .first: return 0 + case .last: return values.count + case .before(let id), .after(let id): + let target = try pointer(id) + guard target.hasPrefix(path + "/"), let i = Int(target.dropFirst(path.count + 1)), + i < values.count + else { throw failure("manifest.edit.stale", "position is outside collection") } + if case .after = position { return i + 1 } + return i + } } - return value - } - func containerPath(_ container: ContainerID) throws -> String { - switch container { - case .root: return "" - case .group(let handle): - let pointer = try resolve(handle) - try requireType(pointer, "ComponentGroup") - return pointer + func upsert(_ path: String, _ value: DeclarationRecord) throws -> [IREdit] { + guard let values = IRTree.value(root, at: path)?.elements else { + throw failure("manifest.edit.readOnly", "expected a named collection") + } + if let index = values.firstIndex(where: { $0.record?["name"] == value["name"] }) { + return [.set(path + "/\(index)", .record(value))] + } + return [.insert(path, values.count, .record(value))] } - } - func parent(_ pointer: String) -> String { - String(pointer[.. String { - pointerUnescape(String(pointer[pointer.index(after: pointer.lastIndex(of: "/")!)...])) - } - - func patch(_ range: Range, _ text: String) throws { - try patch(range, bytes: Array(text.utf8)) - } - func patch(_ range: Range, bytes: [UInt8]) throws { - guard range.lowerBound >= 0, range.upperBound <= table.count else { - throw fail("manifest.edit.overlap", "patch is outside the snapshot") + func removeNamed(_ path: String, _ name: String) throws -> [IREdit] { + guard let values = IRTree.value(root, at: path)?.elements else { + throw failure("manifest.edit.readOnly", "expected a named collection") + } + return values.firstIndex(where: { $0.record?["name"]?.string == name }).map { + [.remove(path, $0)] + } ?? [] } - if table.count - range.count + bytes.count > ManifestLimits.Input.bytes { - throw fail("manifest.limit", "generated manifest input bytes") + func remove(_ id: NodeID) throws -> [IREdit] { + let path = try pointer(id) + let slash = path.lastIndex(of: "/")! + guard let index = Int(path[path.index(after: slash)...]) else { + throw failure("manifest.edit.readOnly", "expected an occurrence") + } + let parent = String(path[.. ConstructionValue { - try charge(1) - if depth == parts.count { return replacement } - let part = parts[depth] + func move(_ id: NodeID, into path: String, at position: InsertionPosition) throws -> [IREdit] { + let old = try pointer(id) + let slash = old.lastIndex(of: "/")! + let parent = String(old[.. from ? target - 1 : target)] } + return [.relocate(parent, from, path, target)] + } + switch edit { + case .setDefaultAgents(let agents): + return [.set("/defaultAgents", YAMLConstruction.agents(agents))] + case .upsertSource(let source): return try upsert("/sources", YAMLConstruction.source(source)) + case .removeSource(let alias): return try removeNamed("/sources", alias) + case .insertComponent(let value, let owner, let position): + let path = try container(owner, "components") + return try [ + .insert(path, index(position, in: path), .record(YAMLConstruction.component(value))) + ] + case .replaceComponent(let id, let value): + return try [.set(pointer(id), .record(YAMLConstruction.component(value)))] + case .removeComponent(let id), .removeSection(let id), .removeGroupReference(let id): + return try remove(id) + case .moveComponent(let id, let owner, let position): + return try move(id, into: container(owner, "components"), at: position) + case .setSkillSelection(let id, let value): + let owner = try pointer(id) + guard IRTree.value(root, at: owner)?.record?.kind == "skills" else { + throw failure("manifest.edit.readOnly", "expected a skills occurrence") + } + let path = owner + "/select" switch value { - case .node("SkillSelection", "names", var fields) where Int(part) != nil: - guard let names = fields["names"] else { - throw fail("manifest.edit.mismatch", "expected skill selection is missing") - } - fields["names"] = try update(names, depth) - return .node(type: "SkillSelection", member: "names", fields: fields) - case .node(let type, let member, var fields): - guard let child = fields[part] else { - throw fail("manifest.edit.mismatch", "expected field is missing") - } - fields[part] = try update(child, depth + 1) - return .node(type: type, member: member, fields: fields) - case .object(var fields): - guard let child = fields[part] else { - throw fail("manifest.edit.mismatch", "expected dictionary field is missing") - } - fields[part] = try update(child, depth + 1) - return .object(fields) - case .array(var values): - guard let index = Int(part), values.indices.contains(index) else { - throw fail("manifest.edit.mismatch", "expected array occurrence is missing") - } - values[index] = try update(values[index], depth + 1) - return .array(values) - default: throw fail("manifest.edit.readOnly", "value has no editable child") + case .all: return [.set(path, .string("all"))] + case .names(let names): return [.set(path, YAMLConstruction.strings(names))] } - } - expected = try update(expected, 0) - _ = try valueCost(expected) - } - - func replacementText(_ value: ConstructionValue, at range: Range) throws -> String { - _ = try valueCost(value) - let (style, indentation) = try style(at: range) - let lineEnd = - current.bytes[range.upperBound...].firstIndex(where: { $0 == 10 || $0 == 13 }) - ?? current.bytes.count - var text = CanonicalPrinter(style: style).render( - value, indentation: indentation, column: range.lowerBound - lineStart(range.lowerBound), - trailing: lineEnd - range.upperBound) - if text.hasPrefix("-"), range.lowerBound > 0 { - let previous = current.bytes[range.lowerBound - 1] - if ![ - UInt8(ascii: " "), UInt8(ascii: "\t"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), - UInt8(ascii: "("), UInt8(ascii: "["), UInt8(ascii: ","), UInt8(ascii: ":"), - ].contains(previous) { - text = " " + text + case .upsertSkillOverride(let id, let value): + return try upsert(pointer(id) + "/overrides", YAMLConstruction.override(value)) + case .removeSkillOverride(let id, let name): + return try removeNamed(pointer(id) + "/overrides", name) + case .insertSection(let value, let id, let position): + let path = try pointer(id) + "/sections" + return try [ + .insert(path, index(position, in: path), .record(YAMLConstruction.section(value))) + ] + case .moveSection(let id, let position): + let path = try pointer(id) + let slash = path.lastIndex(of: "/")! + return try move(id, into: String(path[.. ConstructionValue - { - _ = try valueCost(input.value) - if input.type == context || input.type == context.unwrapped { return input.value } - guard input.literal else { - throw fail("manifest.type", "replacement has the wrong contextual type") + private static func remap(_ handles: [String: String], after edit: IREdit) -> [String: String] { + var result: [String: String] = [:] + if case .relocate(let origin, let from, let destination, let to) = edit { + let prefix = origin + "/" + String(from) + let carried = handles.filter { $0.value == prefix || $0.value.hasPrefix(prefix + "/") } + let shifted = remap( + remap(handles, after: .remove(origin, from)), after: .insert(destination, to, .null)) + return shifted.merging( + carried.mapValues { destination + "/" + String(to) + $0.dropFirst(prefix.count) } + ) { _, value in value } } - let result: ConstructionValue - do { - result = try LiteralConversion.convert(input.value, to: context) { try charge(1) } - } catch let error as LiteralConversionError { - throw fail(error.code, error.message) + for (original, path) in handles { + switch edit { + case .set(let pointer, _): + if !path.hasPrefix(pointer + "/") { result[original] = path } + case .insert(let pointer, let index, _), .remove(let pointer, let index), + .move(let pointer, let index, _): + guard path.hasPrefix(pointer + "/") else { + result[original] = path + continue + } + let suffix = path.dropFirst(pointer.count + 1) + let segments = suffix.split(separator: "/", maxSplits: 1) + guard let current = Int(segments[0]) else { + result[original] = path + continue + } + let next: Int + switch edit { + case .insert: next = current >= index ? current + 1 : current + case .remove: + if current == index { continue } + next = current > index ? current - 1 : current + case .move(_, _, let to): + if current == index { + next = to + } else if index < to && current > index && current <= to { + next = current - 1 + } else if index > to && current >= to && current < index { + next = current + 1 + } else { + next = current + } + default: next = current + } + result[original] = + pointer + "/" + String(next) + (segments.count == 2 ? "/" + segments[1] : "") + case .relocate: break + } } - _ = try valueCost(result) return result } - + private func failure(_ code: String, _ message: String) -> ManifestFailure { + document.source.failure(code, message, 0) + } } diff --git a/Sources/AgentsManifest/DocumentEdits.swift b/Sources/AgentsManifest/DocumentEdits.swift deleted file mode 100644 index eb30e8d..0000000 --- a/Sources/AgentsManifest/DocumentEdits.swift +++ /dev/null @@ -1,700 +0,0 @@ -import AgentsCore -import AgentsDescription -import Foundation - -extension DocumentEditor { - func apply(_ operation: DocumentOperation) throws { - switch operation { - case .edit(let edit): try apply(edit) - case .setArgument(let handle, let field, let value): try setField(resolve(handle), field, value) - case .insertElement(let value, let handle, let position): - try insert(value, into: resolve(handle), at: position) - case .removeElement(let handle): try remove(resolve(handle)) - case .moveElement(let handle, let container, let position): - try move(resolve(handle), into: resolve(container), at: position) - case .replaceValue(let handle, let value): try replace(resolve(handle), with: value) - case .dictionaryEntry(let handle, let key, let value): - let pointer = try resolve(handle) - guard case .dictionary(let type) = current.values[pointer]?.type.unwrapped else { - throw fail("manifest.edit.readOnly", "target is not a typed dictionary") - } - try dictionary(pointer, key: key, value: value.map { StaticValue.checked($0, type: type) }) - } - } - - func apply(_ edit: ManifestEdit) throws { - switch edit { - case .setDefaultAgents(let agents): try setField("", "defaultAgents", agents.constructionValue) - case .setExports(let exports): try setField("", "exports", exports.constructionValue) - case .setWatch(let watch): try setField("", "watch", watch.constructionValue) - case .upsertSource(let source): - try upsert(source.constructionValue, collection: "/sources", key: "name") - case .removeSource(let alias): try removeNamed(alias, collection: "/sources", key: "name") - case .upsertGroup(let group): - try upsert(group.constructionValue, collection: "/groups", key: "name") - case .removeGroup(let name): try removeNamed(name, collection: "/groups", key: "name") - case .insertComponent(let component, let container, let position): - try insert( - component.constructionValue, into: containerPath(container) + "/components", at: position) - case .replaceComponent(let handle, let component): - let pointer = try resolve(handle) - try requireType(pointer, "Component") - try replace(pointer, with: component.constructionValue) - case .removeComponent(let handle): - let pointer = try resolve(handle) - try requireType(pointer, "Component") - try remove(pointer) - case .moveComponent(let handle, let container, let position): - let pointer = try resolve(handle) - try requireType(pointer, "Component") - try move(pointer, into: containerPath(container) + "/components", at: position) - case .setSkillSelection(let handle, let selection): - let pointer = try resolve(handle) - try requireType(pointer, "Component", member: "skills") - try setField(pointer, "select", selection.constructionValue) - case .upsertSkillOverride(let handle, let override): - let pointer = try resolve(handle) - try requireType(pointer, "Component", member: "skills") - try upsert(override.constructionValue, collection: pointer + "/overrides", key: "name") - case .removeSkillOverride(let handle, let name): - let pointer = try resolve(handle) - try requireType(pointer, "Component", member: "skills") - try removeNamed(name, collection: pointer + "/overrides", key: "name") - case .insertSection(let section, let handle, let position): - let pointer = try resolve(handle) - guard current.values[pointer]?.value.fields["sections"] != nil else { - throw fail("manifest.edit.readOnly", "target has no instruction sections") - } - try insert(section.constructionValue, into: pointer + "/sections", at: position) - case .removeSection(let handle): - let pointer = try resolve(handle) - try requireType(pointer, "SectionReference") - try remove(pointer) - case .moveSection(let handle, let position): - let pointer = try resolve(handle) - try requireType(pointer, "SectionReference") - try move(pointer, into: parent(pointer), at: position) - case .upsertPrompt(let handle, let prompt): - let pointer = try resolve(handle) - try requireType(pointer, "Component", member: "instructions") - try upsert(prompt.constructionValue, collection: pointer + "/chatGPT", key: "name") - case .removePrompt(let handle, let name): - let pointer = try resolve(handle) - try requireType(pointer, "Component", member: "instructions") - try removeNamed(name, collection: pointer + "/chatGPT", key: "name") - case .insertGroupReference(let reference, let container, let position): - try insert( - reference.constructionValue, into: containerPath(container) + "/uses", at: position) - case .removeGroupReference(let handle): - let pointer = try resolve(handle) - try requireType(pointer, "GroupReference") - try remove(pointer) - case .setDictionaryEntry(let handle, let key, let value): - let pointer = try resolve(handle) - try dictionary(pointer, key: key, value: value) - case .removeDictionaryEntry(let handle, let key): - try dictionary(resolve(handle), key: key, value: nil) - case .replaceConstant(let handle, let value, let accepted): - try constant(handle, value: value, accepted: accepted) - } - } - - func setField( - _ pointer: String, _ field: String, _ value: ConstructionValue, spelling: String? = nil - ) throws { - let owner = try direct(pointer) - let node = current.admission.nodes[owner.syntax] - guard node.kind == .call, let old = owner.value.fields[field] else { - throw fail("manifest.edit.readOnly", "target is not a direct construction") - } - _ = try valueCost(value) - if Lowering.lower(old) == Lowering.lower(value) { return } - if let child = owner.field(field), !child.defaulted { - try replace(pointer + "/" + pointerEscape(field), with: value) - return - } - guard case .named(let type) = owner.type.unwrapped else { - throw fail("manifest.edit.readOnly", "target has no named construction type") - } - let signatures = Vocabulary.signatures.filter { - $0.type == type && $0.member == owner.value.member - } - guard - let signature = signatures.first(where: { - $0.parameters.contains(where: { $0.name == field }) - }), let position = signature.parameters.firstIndex(where: { $0.name == field }) - else { throw fail("manifest.edit.readOnly", "unknown construction field") } - let next = node.arguments.first { argument in - let index = signature.parameters.firstIndex { $0.label == argument.label } ?? -1 - return index > position - } - let (style, indentation) = try style(at: node.range) - let multiline = hasNewline(node.range) - let label = field + ": " - let content = - label - + (spelling - ?? CanonicalPrinter(style: style).render( - value, indentation: indentation + style.indent, - column: (indentation + style.indent + label).utf8.count, - trailing: multiline && next == nil ? 0 : 1)) - if !multiline, !node.arguments.isEmpty, content.utf8.contains(10) || content.utf8.contains(13) { - try multilineArgument( - content, before: next, call: node, style: style, indentation: indentation) - } else if let next { - let start = - next.labelRange?.lowerBound ?? current.admission.nodes[next.value].range.lowerBound - if multiline { - let line = lineStart(start) - if current.bytes[line.. Range { - var start = offset - while start > call.range.lowerBound && blank(start - 1) { start -= 1 } - return start.., - style: PrintStyle, indentation: String - ) throws { - let close = range.upperBound - 1 - guard - let open = current.admission.tokens.last(where: { - $0.text == "(" && $0.range.lowerBound >= range.lowerBound && $0.range.upperBound <= close - }) - else { throw fail("manifest.edit.readOnly", "call has no argument list", range: range) } - let interior = open.range.upperBound.. Int { - switch position { - case .first: return 0 - case .last: return count - case .before(let handle), .after(let handle): - let pointer = try resolve(handle) - guard parent(pointer) == collection, let index = Int(key(pointer)) else { - throw fail("manifest.edit.impact", "insertion anchor belongs to another container") - } - if case .after = position { return index + 1 } - return index - } - } - - func insert( - _ value: ConstructionValue, into pointer: String, at position: InsertionPosition, - carried: CarriedElement? = nil - ) throws { - guard let collection = current.values[pointer], - let previous = arrayElements(collection.value) - else { throw fail("manifest.edit.readOnly", "target is not an array") } - let incoming = try valueCost(value) - guard previous.count < ManifestLimits.Values.entries else { - throw fail("manifest.limit", "edited array entries") - } - let combined = ValueCost.container(collection.elementsForUse.map(\.cost) + [incoming]) - let total = current.evaluation.total - let projected = ValueCost( - nodes: total.nodes - collection.cost.nodes + combined.nodes, - strings: total.strings - collection.cost.strings + combined.strings, - encoded: total.encoded - collection.cost.encoded + combined.encoded, - depth: max(total.depth, incoming.depth + pointer.split(separator: "/").count + 1), - origins: total.origins - collection.cost.origins + combined.origins) - guard combined.fits, projected.fits else { - throw fail("manifest.limit", "edited expanded document budget") - } - let index = try self.position(position, collection: pointer, count: previous.count) - var expectedValues = previous - expectedValues.insert(value, at: index) - if collection.defaulted { - if let carried { - let owner = try direct(parent(pointer)) - let (style, indentation) = try style(at: current.admission.nodes[owner.syntax].range) - let text = - "[" + style.newline + indentation + style.indent + style.indent - + carried.render( - indentation: indentation + style.indent + style.indent, newline: style.newline) - + style.newline + indentation + style.indent - + "]" - try setField(parent(pointer), key(pointer), .array(expectedValues), spelling: text) - } else { - try setField(parent(pointer), key(pointer), .array(expectedValues)) - } - return - } - _ = try direct(pointer) - let node = current.admission.nodes[collection.syntax] - guard node.kind == .array else { - throw fail("manifest.edit.readOnly", "target is an assembled array") - } - let (style, indentation) = try style(at: node.range) - let multiline = - hasNewline(node.range) - || carried?.isMultiline == true - let rendered = - carried.map { $0.render(indentation: indentation + style.indent, newline: style.newline) } - ?? CanonicalPrinter(style: style).render( - value, indentation: multiline ? indentation + style.indent : indentation) - if previous.isEmpty { - let interior = (node.range.lowerBound + 1)..<(node.range.upperBound - 1) - if !current.bytes[interior].allSatisfy({ - [UInt8(ascii: " "), UInt8(ascii: "\t"), UInt8(ascii: "\n"), UInt8(ascii: "\r")].contains($0) - }) { - throw fail( - "manifest.edit.readOnly", "comment-only container insertion is ambiguous", range: interior - ) - } - try patch( - interior, - multiline - ? style.newline + indentation + style.indent + rendered + (carried == nil ? "," : "") - + style.newline + indentation : rendered) - } else if index < previous.count { - let child = collection.elementsForUse[index] - let owned = try ownedRange(child, container: node, index: index) - if multiline { - guard owned.lowerBound == lineStart(owned.lowerBound) else { - throw fail("manifest.edit.readOnly", "mixed inline and multiline collection layout") - } - try patch( - owned.lowerBound..= range.upperBound && $0.range.upperBound <= close - } - let gap = range.upperBound..= current.admission.nodes[value.syntax].range.upperBound - && $0.range.upperBound <= range.upperBound - } - // An inline element also takes the spacing that separates it from its neighbor. - let inline = !hasNewline(range) - let following = - index + 1 < node.children.count - ? current.admission.nodes[node.children[index + 1]].range.lowerBound - : node.range.upperBound - 1 - while inline && hasComma && range.upperBound < following && blank(range.upperBound) { - range = range.lowerBound..<(range.upperBound + 1) - } - var patches = [SourcePatch(range: range, replacement: [])] - if !hasComma && index > 0 { - let previous = current.admission.nodes[node.children[index - 1]].range.upperBound - if let comma = current.admission.tokens.last(where: { - $0.text == "," && $0.range.lowerBound >= previous && $0.range.upperBound <= range.lowerBound - }) { - if inline && (comma.range.upperBound.. $1.range.lowerBound }) { - try self.patch(patch.range, bytes: patch.replacement) - } - try mutate(collectionPointer, replacingElements(collection.value, with: values)) - } - - func blank(_ offset: Int) -> Bool { - current.bytes[offset] == UInt8(ascii: " ") || current.bytes[offset] == UInt8(ascii: "\t") - } - - /// Array literals evaluate to arrays, except explicit skill selections, whose names they hold. - func arrayElements(_ value: ConstructionValue) -> [ConstructionValue]? { - if case .node("SkillSelection", "names", let fields) = value { return fields["names"]?.array } - return value.array - } - func replacingElements(_ value: ConstructionValue, with elements: [ConstructionValue]) - -> ConstructionValue - { - if case .node("SkillSelection", "names", _) = value { - return .node(type: "SkillSelection", member: "names", fields: ["names": .array(elements)]) - } - return .array(elements) - } - - func move(_ pointer: String, into collection: String, at position: InsertionPosition) - throws - { - let value = try direct(pointer) - let from = parent(pointer) - guard let old = current.values[from], let index = Int(key(pointer)), - let target = current.values[collection], arrayElements(target.value) != nil - else { throw fail("manifest.edit.readOnly", "move requires array containers") } - let destination = try self.position( - position, collection: collection, count: target.elementsForUse.count) - if from == collection && (destination == index || destination == index + 1) { return } - let node = current.admission.nodes[old.syntax] - let owned = try ownedRange(value, container: node, index: index) - let expression = current.admission.nodes[value.syntax].range - let leading = current.source.spelling(owned.lowerBound..= expression.upperBound - && $0.range.upperBound <= owned.upperBound - } - let beforeComma = - comma.map { current.source.spelling(expression.upperBound..<$0.range.lowerBound) } ?? "" - let afterComma = current.source.spelling( - (comma?.range.upperBound ?? expression.upperBound).. index ? destination - 1 : destination - let count = current.values[refreshed]?.elementsForUse.count ?? 0 - let insertion: InsertionPosition - if adjusted == 0 { - insertion = .first - } else if adjusted == count { - insertion = .last - } else { - // Use a current local anchor for the internal move only. - try insertAtIndex(value.value, pointer: refreshed, index: adjusted, carried: carried) - return - } - try insert(value.value, into: refreshed, at: insertion, carried: carried) - } - - func insertAtIndex( - _ value: ConstructionValue, pointer: String, index: Int, carried: CarriedElement - ) throws { - // A direct byte anchor avoids manufacturing a public snapshot handle. - let collection = try direct(pointer) - let node = current.admission.nodes[collection.syntax] - let owned = try ownedRange(collection.elementsForUse[index], container: node, index: index) - let (style, indentation) = try style(at: node.range) - let multiline = hasNewline(node.range) - try patch( - owned.lowerBound.. String - { - // Removing a root component cannot move a group definition, and group moves never nest groups. - if let value = current.values[pointer], value.type == previous.type { return pointer } - throw fail("manifest.edit.stale", "destination container changed during move") - } - - func dictionary(_ pointer: String, key: String, value replacement: StaticValue?) throws { - let value = try direct(pointer) - if value.type == .named("ConfigurationValue"), value.value.member == "object" { - try dictionary(pointer + "/value", key: key, value: replacement) - return - } - let node = current.admission.nodes[value.syntax] - guard node.kind == .dictionary, case .dictionary(let elementType) = value.type.unwrapped, - case .object(var fields) = value.value - else { throw fail("manifest.edit.readOnly", "target is not a direct dictionary") } - if let replacement { - let replacementValue = try contextualValue(replacement, as: elementType) - if node.keys.contains(where: { $0.decoded == key }) { - let childPointer = pointer + "/" + pointerEscape(key) - try replace(childPointer, with: replacementValue) - return - } - let close = node.range.upperBound - 1 - let (style, indentation) = try style(at: node.range) - let text = - quoted(key) + ": " - + CanonicalPrinter(style: style).render( - replacementValue, indentation: indentation + style.indent) - let multiline = hasNewline(node.range) - if node.children.isEmpty { - let interior = (node.range.lowerBound + 1)..= end && $0.range.upperBound <= close - } - if multiline { - let at = comma?.range.upperBound ?? end - try patch( - at..= childEnd && $0.range.upperBound <= range.upperBound - } - var patches = [SourcePatch(range: range, replacement: [])] - if !hasComma && index > 0 { - let previous = current.admission.nodes[node.children[index - 1]].range.upperBound - guard - let comma = current.admission.tokens.last(where: { - $0.text == "," && $0.range.lowerBound >= previous - && $0.range.upperBound <= range.lowerBound - }) - else { throw fail("manifest.edit.readOnly", "dictionary separator is ambiguous") } - patches.append(SourcePatch(range: comma.range, replacement: [])) - } - for patch in patches.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { - try self.patch(patch.range, bytes: patch.replacement) - } - fields.removeValue(forKey: key) - if fields.isEmpty { - // The colon is necessary even if retained container whitespace/comments remain. - let opener = node.range.lowerBound + 1 - try patch(opener.. ConstructionValue - { - try charge(1) - if old == new { return expected } - switch (old, new, expected) { - case (.array(let a), .array(let b), .array(let e)) - where a.count == b.count && a.count == e.count: - return .array(try a.indices.map { try merge(a[$0], b[$0], e[$0]) }) - case (.node(let t, let m, let a), .node(let nt, let nm, let b), .node(_, _, let e)) - where t == nt && m == nm && a.keys == b.keys && a.keys == e.keys: - var result = e - for key in a.keys { result[key] = try merge(a[key]!, b[key]!, e[key]!) } - return .node(type: t, member: m, fields: result) - case (.object(let a), .object(let b), .object(let e)) - where a.keys == b.keys && a.keys == e.keys: - var result = e - for key in a.keys { result[key] = try merge(a[key]!, b[key]!, e[key]!) } - return .object(result) - default: return new - } - } - expected = try merge(current.evaluation.root.value, altered.root.value, expected) - impacted += uses - try patch(range, replacementText(replacementValue, at: range)) - if let declaration = current.admission.declarations.first(where: { $0.name == name }), - declaration.type == nil, - needsContext(replacementValue, type: old.type) - { - let offset = declaration.nameRange.upperBound - try patch(offset.. Bool { - switch (value, type) { - case (.text, .named("String")), (.integer, .named("Int")), (.boolean, .named("Bool")): - return false - case (.node(let type, _, _), _) where type == "Agents": return false - case (.array(let values), .array(let element)): - return values.first.map { needsContext($0, type: element) } ?? true - case (.object(let fields), .dictionary(let element)): - return fields.keys.sorted(by: utf8Less).first.map { needsContext(fields[$0]!, type: element) } - ?? true - default: return true - } - } - - func typeSpelling(_ type: ConstructionType) throws -> String { - switch type { - case .untyped: throw fail("manifest.edit.readOnly", "value has no construction type") - case .named(let name): return name - case .array(let element): return "[" + (try typeSpelling(element)) + "]" - case .dictionary(let element): return "[String: " + (try typeSpelling(element)) + "]" - case .optional(let element): return try typeSpelling(element) - } - } -} diff --git a/Sources/AgentsManifest/DocumentModels.swift b/Sources/AgentsManifest/DocumentModels.swift index e971c97..005c1b9 100644 --- a/Sources/AgentsManifest/DocumentModels.swift +++ b/Sources/AgentsManifest/DocumentModels.swift @@ -1,5 +1,4 @@ import AgentsCore -import AgentsDescription /// An occurrence in one immutable document snapshot, never a persistent component identity. public struct NodeID: Sendable, Hashable { @@ -12,123 +11,50 @@ public enum ContainerID: Sendable { case root case group(NodeID) } - public enum InsertionPosition: Sendable { - case first - case last + case first, last case before(NodeID) case after(NodeID) } - public enum Editability: Sendable, Equatable { case direct - case sharedConstant(uses: [NodeID]) case readOnly(reason: String) } -/// Checked values are constructed from the vocabulary or literal algebra, never source text. -public struct StaticValue: Sendable { - let value: ConstructionValue - let type: ConstructionType - let literal: Bool - private init(_ value: ConstructionValue, _ type: ConstructionType, literal: Bool = false) { - self.value = value - self.type = type - self.literal = literal - } - static func checked(_ value: ConstructionValue, type: ConstructionType) -> Self { - Self(value, type) - } - - public static var null: Self { Self(.none, .untyped, literal: true) } - - public static func string(_ value: String) -> Self { - Self(.text(value), .named("String"), literal: true) - } - public static func integer(_ value: Int) -> Self { - Self(.integer(value), .named("Int"), literal: true) - } - public static func boolean(_ value: Bool) -> Self { - Self(.boolean(value), .named("Bool"), literal: true) - } - public static func array(_ values: [StaticValue]) -> Self { - Self(.array(values.map(\.value)), .array(values.first?.type ?? .named("String")), literal: true) - } - public static func dictionary(_ values: [String: StaticValue]) -> Self { - Self( - .object(values.mapValues(\.value)), - .dictionary(values.values.first?.type ?? .named("String")), literal: true - ) - } -} - +/// Edits carry complete domain intent. They never contain parser nodes or source programs. public enum ManifestEdit: Sendable { - case setDefaultAgents([Agent]?) - case upsertSource(Source) + case setDefaultAgents([AgentID]?) + case upsertSource(NamedSourceDeclaration) case removeSource(alias: String) - case insertComponent(Component, into: ContainerID, at: InsertionPosition) - case replaceComponent(NodeID, with: Component) + case insertComponent(ComponentDeclaration, into: ContainerID, at: InsertionPosition) + case replaceComponent(NodeID, with: ComponentDeclaration) case removeComponent(NodeID) case moveComponent(NodeID, into: ContainerID, at: InsertionPosition) - case setSkillSelection(NodeID, AgentsDescription.SkillSelection) - case upsertSkillOverride(NodeID, AgentsDescription.SkillOverride) + case setSkillSelection(NodeID, SkillSelection) + case upsertSkillOverride(NodeID, NamedSkillOverrideDeclaration) case removeSkillOverride(NodeID, name: String) - case insertSection(SectionReference, into: NodeID, at: InsertionPosition) + case insertSection(SectionDeclaration, into: NodeID, at: InsertionPosition) case removeSection(NodeID) case moveSection(NodeID, at: InsertionPosition) - case upsertPrompt(NodeID, ChatGPTPrompt) + case upsertPrompt(NodeID, NamedPromptDeclaration) case removePrompt(NodeID, name: String) - case upsertGroup(ComponentGroup) + case upsertGroup(ComponentGroupDeclaration) case removeGroup(name: String) - case insertGroupReference(GroupReference, into: ContainerID, at: InsertionPosition) + case insertGroupReference(GroupUseDeclaration, into: ContainerID, at: InsertionPosition) case removeGroupReference(NodeID) case setExports([String]) case setWatch([String]) - case setDictionaryEntry(NodeID, key: String, value: StaticValue) + case setDictionaryEntry(NodeID, key: String, value: NativeValue) case removeDictionaryEntry(NodeID, key: String) - case replaceConstant(NodeID, with: StaticValue, acceptingUses: [NodeID]) -} - -/// Edits below component granularity. Argument and element handles address direct -/// constructions and array literals, including explicit skill selections; comments follow the -/// ownership rules of the other edits. -package enum DocumentOperation: Sendable { - case edit(ManifestEdit) - /// Replaces a present argument, writing an explicit default rather than removing it, or - /// inserts a missing one in signature order. A missing argument set to its default is a no-op. - case setArgument(NodeID, field: String, value: ConstructionValue) - case insertElement(ConstructionValue, into: NodeID, at: InsertionPosition) - case removeElement(NodeID) - case moveElement(NodeID, into: NodeID, at: InsertionPosition) - case replaceValue(NodeID, ConstructionValue) - case dictionaryEntry(NodeID, key: String, value: ConstructionValue?) -} - -public struct SemanticDelta: Sendable, Equatable { - public let changedPointers: [String] } +public struct SemanticDelta: Sendable, Equatable { public let changedPointers: [String] } public struct DocumentChange: Sendable { public let originalDigest: String public let patches: [SourcePatch] public let bytes: [UInt8] public let digest: String public let expectedDeclaration: DeclarationIR - public let impactedReferences: [NodeID] public let diagnostics: [ManifestDiagnostic] public let delta: SemanticDelta - package init( - originalDigest: String, patches: [SourcePatch], bytes: [UInt8], digest: String, - expectedDeclaration: DeclarationIR, impactedReferences: [NodeID], - diagnostics: [ManifestDiagnostic], delta: SemanticDelta - ) { - self.originalDigest = originalDigest - self.patches = patches - self.bytes = bytes - self.digest = digest - self.expectedDeclaration = expectedDeclaration - self.impactedReferences = impactedReferences - self.diagnostics = diagnostics - self.delta = delta - } } diff --git a/Sources/AgentsManifest/DocumentStyle.swift b/Sources/AgentsManifest/DocumentStyle.swift deleted file mode 100644 index e613144..0000000 --- a/Sources/AgentsManifest/DocumentStyle.swift +++ /dev/null @@ -1,82 +0,0 @@ -import AgentsCore -import AgentsDescription -import Foundation - -extension DocumentEditor { - func style(at range: Range) throws -> (PrintStyle, String) { - try charge(current.admission.nodes.count) - let bytes = current.bytes - var endings = Set() - var cursor = 0 - while cursor < bytes.count { - if bytes[cursor] == UInt8(ascii: "\r") { - if cursor + 1 < bytes.count && bytes[cursor + 1] == UInt8(ascii: "\n") { - endings.insert("\r\n") - cursor += 1 - } else { - endings.insert("\r") - } - } else if bytes[cursor] == UInt8(ascii: "\n") { - endings.insert("\n") - } - cursor += 1 - } - guard endings.count <= 1 else { - throw fail("manifest.edit.readOnly", "conflicting newline styles", range: range) - } - let indentation = indentation(at: range.lowerBound) - let candidates = current.admission.nodes.filter { node in - [.array, .dictionary, .call].contains(node.kind) - && node.range.lowerBound <= range.lowerBound && node.range.upperBound >= range.upperBound - } - var unit: String? - var trailingComma = true - for container in candidates.sorted(by: { $0.range.count < $1.range.count }) { - var units = Set() - let base = self.indentation(at: container.range.lowerBound) - let offsets = - container.kind == .dictionary - ? container.keys.map { $0.range.lowerBound } - : container.kind == .array - ? container.children.map { current.admission.nodes[$0].range.lowerBound } - : container.arguments.map { - $0.labelRange?.lowerBound ?? current.admission.nodes[$0.value].range.lowerBound - } - for offset in offsets { - let start = lineStart(offset) - let prefix = current.source.spelling(start.. base.count else { - throw fail("manifest.edit.readOnly", "conflicting local indentation", range: range) - } - units.insert(String(prefix.dropFirst(base.count))) - } - guard units.count <= 1 else { - throw fail("manifest.edit.readOnly", "conflicting local indentation", range: range) - } - if let evidence = units.first { - unit = evidence - break - } - } - for container in candidates.sorted(by: { $0.range.count < $1.range.count }) - where container.kind == .array || container.kind == .dictionary { - guard let last = container.children.last, - let token = current.admission.tokens.first(where: { - $0.range.lowerBound >= current.admission.nodes[last].range.upperBound - }) - else { continue } - trailingComma = token.text == "," - break - } - return ( - PrintStyle( - indent: unit ?? " ", newline: endings.first ?? "\n", trailingComma: trailingComma), - indentation - ) - } - - func indentation(at offset: Int) -> String { - String(current.source.spelling(lineStart(offset)..) -> Bool { - current.admission.comments.contains { - $0.lowerBound >= range.lowerBound && $0.upperBound <= range.upperBound - } - } - - func lineStart(_ offset: Int) -> Int { - var result = offset - while result > 0 && current.bytes[result - 1] != UInt8(ascii: "\n") - && current.bytes[result - 1] != UInt8(ascii: "\r") - { - result -= 1 - } - return result - } - - func lineEnd(_ offset: Int) -> Int { - var result = offset - while result < current.bytes.count && current.bytes[result] != UInt8(ascii: "\n") - && current.bytes[result] != UInt8(ascii: "\r") - { result += 1 } - return result - } - - func blankLine(_ range: Range) -> Bool { - let normalized = current.source.spelling(range).replacingOccurrences(of: "\r\n", with: "\n") - .replacingOccurrences(of: "\r", with: "\n") - return normalized.split(separator: "\n", omittingEmptySubsequences: false).dropFirst() - .dropLast().contains { $0.allSatisfy { $0 == " " || $0 == "\t" } } - } - - /// Own contiguous leading comment lines and same-line trailing comments, stopping - /// at blank lines and sibling boundaries. The separator and line ending travel together. - func ownedRange(_ value: EvaluatedValue, container: GrammarNode, index: Int) throws - -> Range - { - let expressionRange = current.admission.nodes[value.syntax].range - let range = - container.kind == .dictionary - ? container.keys[index].range.lowerBound..= previous && $0.upperBound <= start - } - for comment in preceding.reversed() { - if blankLine(comment.upperBound..= previous, - current.bytes[line..= previous - && current.bytes[line..= end && $0.range.upperBound <= next - } - if let comma { end = comma.range.upperBound } - for comment in current.admission.comments - where comment.lowerBound >= range.upperBound && comment.upperBound <= next { - if comment.lowerBound <= (comma?.range.lowerBound ?? range.upperBound) - || lineStart(comment.lowerBound) == lineStart(end) - { - end = max(end, comment.upperBound) - } - } - let ending = lineEnd(end) - if start == lineStart(start), ending <= next, - current.bytes[end..) -> Bool { - current.bytes[range].contains(UInt8(ascii: "\n")) - || current.bytes[range].contains(UInt8(ascii: "\r")) - } -} - -/// Relative indentation is carried with the element; the destination supplies the -/// common prefix and line ending. Empty lines stay empty, including inside strings. -struct CarriedElement { - let text: String - let indentation: String - - var isMultiline: Bool { text.contains("\n") || text.contains("\r") } - - func render(indentation target: String, newline: String) -> String { - let bytes = Array(text.utf8) - var lines: [String] = [] - var start = 0 - while start < bytes.count { - var end = start - while end < bytes.count && bytes[end] != UInt8(ascii: "\n") - && bytes[end] != UInt8(ascii: "\r") - { end += 1 } - let line = String(decoding: bytes[start.. ManifestFailure { - ManifestFailure( - ManifestDiagnostic( - code: code, message: message, span: source.span(admission.nodes[value.syntax].range), - related: related)) - } - - func validate() throws -> [ManifestDiagnostic] { - let root = evaluation.root - let fields = root.value.fields - var identities: [String: EvaluatedValue] = [:] - let sources = root.field("sources")?.elementsForUse ?? [] - for value in sources { - let f = value.value.fields - let name = f["name"]?.text ?? "" - guard !name.isEmpty, name != ".", !name.contains(":"), aliases[name] == nil else { - throw failure("invalid or duplicate source alias", value) - } - aliases[name] = value.value - let identity: String - if let url = f["url"]?.text { - let declaration = SourceDeclaration(kind: .git, location: url) - do { identity = try declaration.transportIdentity() } catch { - throw failure("invalid Git URL", value.field("url") ?? value) - } - if declaration.gitURL != url { - let target = value.field("url") ?? value - let range = admission.nodes[target.syntax].range - if diagnostics.count < ManifestLimits.Diagnostics.warnings { - diagnostics.append( - ManifestDiagnostic( - code: "manifest.domain", severity: .warning, - message: "use the complete Git transport URL", span: source.span(range), - fixIt: SourcePatch( - range: range, replacement: Array(quoted(declaration.gitURL).utf8)))) - } else if diagnostics.count == ManifestLimits.Diagnostics.warnings { - diagnostics.append( - ManifestDiagnostic( - code: "manifest.diagnostics.truncated", severity: .warning, - message: "further diagnostics omitted", span: source.span(range))) - } - } - } else if let index = f["index"]?.text { - do { - identity = try SourceDeclaration(kind: .wellKnown, location: index).transportIdentity() - } catch { throw failure("invalid index URL", value) } - } else { - let location = f["path"]?.text ?? "" - if location.isEmpty || location.contains("\0") { - throw failure("empty or invalid local source", value) - } - identity = "local:" + lexicalPath(location) - } - if let original = identities[identity] { - throw failure( - "two aliases normalize to the same source identity", value, - related: [source.span(admission.nodes[original.syntax].range)]) - } - identities[identity] = value - } - for value in root.field("groups")?.elementsForUse ?? [] { - let name = value.value.fields["name"]?.text ?? "" - if groups[name] != nil { throw failure("duplicate group name", value) } - groups[name] = value - } - try unique(fields["exports"]?.array ?? [], at: root, message: "duplicate export") - for name in fields["exports"]?.strings ?? [] where groups[name] == nil { - throw failure("unknown exported group: \(name)", root, code: "manifest.group.missing") - } - try unique(fields["watch"]?.array ?? [], at: root, message: "duplicate watch subscription") - for name in fields["watch"]?.strings ?? [] where aliases[name] == nil { - throw failure("unknown watch source: \(name)", root) - } - // All definitions, including unused constants and inactive values, get domain checks. - for value in evaluation.constants.values { try walk(value, anchor: value) } - var completed = Set() - for (name, value) in groups { - try cycle(name, stack: [], spans: [], value: value, completed: &completed) - } - return diagnostics.sorted { ($0.span.start, $0.code) < ($1.span.start, $1.code) } - } - - private func walk(_ value: EvaluatedValue, anchor: EvaluatedValue) throws { - var pending = [(value, anchor)] - while let (value, anchor) = pending.popLast() { - work += 1 - if work > ManifestLimits.Domain.steps { - throw failure("domain traversal budget", anchor, code: "manifest.limit") - } - if let referent = value.referent { - pending.append((referent, value)) - continue - } - try check(value.value, at: value) - let children = - !value.fields.isEmpty - ? Array(value.fields.values) : value.elements - if children.isEmpty { - try checkChildren(value.value, at: value) - } else { - for child in children { pending.append((child, anchor)) } - } - } - } - - private func checkChildren(_ value: ConstructionValue, at anchor: EvaluatedValue) throws { - let children: [ConstructionValue] - switch value { - case .node(_, _, let fields), .object(let fields): children = Array(fields.values) - case .array(let values): children = values - default: return - } - for child in children { - work += 1 - if work > ManifestLimits.Domain.steps { - throw failure("domain traversal budget", anchor, code: "manifest.limit") - } - try check(child, at: anchor) - try checkChildren(child, at: anchor) - } - } - - private func check(_ value: ConstructionValue, at anchor: EvaluatedValue) throws { - guard case .node(let type, let member, let f) = value else { return } - if let agents = f["agents"]?.array { - try unique(agents, at: anchor, message: "duplicate recipients") - } - switch type { - case "Agents": - if let defaults = f["defaultAgents"]?.array { - try unique(defaults, at: anchor, message: "duplicate default recipients") - } - case "Condition": - for dimension in ["agents", "scopes", "platforms"] { - if let array = f[dimension]?.array { - try unique(array, at: anchor, message: "duplicate condition member") - } - } - case "Source": - let alias = f["name"]?.text ?? "" - if alias.isEmpty || alias == "." || alias.contains(":") { - throw failure("invalid source alias", anchor) - } - if let url = f["url"]?.text { - do { _ = try SourceDeclaration(kind: .git, location: url).transportIdentity() } catch { - throw failure("invalid Git URL", anchor) - } - } else if let index = f["index"]?.text { - do { - _ = try SourceDeclaration(kind: .wellKnown, location: index).transportIdentity() - } catch { throw failure("invalid index URL", anchor) } - } else if let path = f["path"]?.text, path.isEmpty || path.contains("\0") { - throw failure("invalid local source location", anchor) - } - if let path = f["subpath"]?.text { try resource(path, anchor) } - if let requirement = f["requirement"] { - if case .node(_, let kind, let fields) = requirement, ["branch", "revision"].contains(kind) - { - let text = fields["value"]?.text ?? "" - if text.isEmpty || text.hasPrefix("-") || text.contains("\0") { - throw failure("invalid source requirement", anchor) - } - } - } - case "SkillSelection": - if let names = f["names"]?.strings { try skillNames(names, anchor) } - case "SkillOverride": try skillNames([f["name"]?.text ?? ""], anchor) - case "ComponentGroup": try name(f["name"]?.text ?? "", anchor) - case "GroupReference": - let group = f["name"]?.text ?? "" - try name(group, anchor) - if let alias = f["source"]?.text { - try sourceAlias(alias, anchor) - } else if groups[group] == nil { - throw failure("unknown local group: \(group)", anchor, code: "manifest.group.missing") - } - case "SectionReference": - if !Declaration.isInstructionName(f["name"]?.text ?? "") { - throw failure("invalid instruction section name", anchor) - } - if let alias = f["source"]?.text { try sourceAlias(alias, anchor) } - case "ChatGPTPrompt": - if let append = f["append"]?.text { try resource(append, anchor) } - case "Resource", "PromptContent": - if let path = f["path"]?.text { try resource(path, anchor) } - if let alias = f["source"]?.text { try sourceAlias(alias, anchor) } - case "ExecutableInvocation", "MCPTransport": - if let executable = f["executable"]?.text { - if executable.isEmpty || executable.contains("\0") { - throw failure("invalid executable", anchor) - } - if executable.contains("/") || executable.hasPrefix("~") { - try resource(executable, anchor) - } - } - if type == "MCPTransport" && member != "stdio" { try http(f["url"]?.text ?? "", anchor) } - case "ConfigurationValue": - if member == "decimal" { - let text = f["value"]?.text ?? "" - let valid = - text.range( - of: #"^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?$"#, options: .regularExpression) - != nil - if !valid || Double(text)?.isFinite != true { - throw failure("decimal requires finite JSON-number text", anchor) - } - } - case "PromptParameter": - let n = f["name"]?.text ?? "" - if n.isEmpty || n.contains("}") || n.contains(":") || n.contains("\0") { - throw failure("invalid prompt parameter name", anchor) - } - case "ComponentReference": try name(f["name"]?.text ?? "", anchor) - case "PermissionRule": - if ["read", "write"].contains(f["operation"]?.member ?? "") { - try resource(f["pattern"]?.text ?? "", anchor) - } - case "Component": try component(member, fields: f, anchor: anchor) - default: break - } - } - - private func component( - _ kind: String, fields f: [String: ConstructionValue], anchor: EvaluatedValue - ) throws { - if let n = f["name"]?.text { try name(n, anchor) } - if kind == "skills" { - let alias = f["source"]?.text ?? "" - try sourceAlias(alias, anchor) - let selection = f["select"]! - let names = selection.fields["names"]?.strings - try skillNames(f["exclude"]?.strings ?? [], anchor) - let overrides = f["overrides"]?.array ?? [] - try uniqueNames(overrides, anchor) - for override in overrides { - let n = override.fields["name"]?.text ?? "" - if let names, !names.contains(n) { - throw failure("override is outside explicit skill selection", anchor) - } - } - let modes = [f["mode"]].compactMap { $0 } + overrides.compactMap { $0.fields["mode"] } - if modes.contains(where: { $0.member == "edit" }) { - if alias != ".", let source = aliases[alias], - source.fields["path"]?.text == nil - || source.fields["requirement"] != ConstructionValue.none - { - throw failure("edit mode needs a local source without a requirement", anchor) - } - } - } - if kind == "instructions" { try uniqueNames(f["chatGPT"]?.array ?? [], anchor) } - if kind == "hook" { - if case .integer(let timeout) = f["timeoutSeconds"], timeout <= 0 { - throw failure("hook timeout must be positive", anchor) - } - if f["event"]?.member == "native", f["agents"]?.array?.count != 1 { - throw failure("native hook event requires exactly one explicit recipient", anchor) - } - } - if kind == "plugin" { - try sourceAlias(f["source"]?.text ?? "", anchor) - try resource(f["path"]?.text ?? "", anchor) - if f["mode"]?.member == "native" { - if f["agents"]?.array?.count != 1 || f["select"] != ConstructionValue.none - || !(f["exclude"]?.array ?? []).isEmpty - { - throw failure( - "native plugin requires one explicit recipient and no selection/exclusions", anchor) - } - } - if let selection = f["select"]?.array { - try unique(selection, at: anchor, message: "duplicate plugin selection") - } - try unique(f["exclude"]?.array ?? [], at: anchor, message: "duplicate plugin exclusion") - } - if kind == "lspServer", case .object(let languages) = f["languages"] { - if languages.keys.contains(where: { - !$0.hasPrefix(".") || $0.count <= 1 || $0.contains("/") || $0.contains("\0") - }) || languages.values.contains(where: { $0.text?.isEmpty != false }) { - throw failure("invalid language extension mapping", anchor) - } - } - if kind == "command" { - let parameters = f["parameters"]?.array ?? [] - try uniqueNames(parameters, anchor) - let declared = Set(parameters.compactMap { $0.fields["name"]?.text }) - if f["prompt"]?.member == "literal", let prompt = f["prompt"]?.fields["value"]?.text { - let bytes = Array(prompt.utf8) - var i = 0 - let escapedDollars = Array("$$".utf8) - let input = Array("${input:".utf8) - let escapedInput = escapedDollars + input.dropFirst() - while i < bytes.count { - if bytes[i...].starts(with: escapedInput) { - i += escapedDollars.count - while i < bytes.count && bytes[i] != UInt8(ascii: "}") { i += 1 } - } else if bytes[i...].starts(with: input) { - let first = i + input.count - i = first - while i < bytes.count && bytes[i] != UInt8(ascii: "}") { i += 1 } - if i == bytes.count - || !declared.contains(String(decoding: bytes[first.. - ) throws { - if stack.contains(name) { - throw failure( - "local group reference cycle: \((stack + [name]).joined(separator: " -> "))", value, - code: "manifest.group.cycle", related: spans) - } - if completed.contains(name) { return } - if stack.count == ManifestLimits.Groups.activeReferences { - throw failure("local group reference depth", value, code: "manifest.limit") - } - for reference in value.field("uses")?.elementsForUse ?? [] - where reference.value.fields["source"] == ConstructionValue.none { - let next = reference.value.fields["name"]?.text ?? "" - if let child = groups[next] { - try cycle( - next, stack: stack + [name], - spans: spans + [source.span(admission.nodes[reference.syntax].range)], value: child, - completed: &completed) - } - } - completed.insert(name) - } - - private func sourceAlias(_ alias: String, _ anchor: EvaluatedValue) throws { - if alias != "." && aliases[alias] == nil { - throw failure("unknown source alias: \(alias)", anchor) - } - } - private func unique(_ values: [ConstructionValue], at anchor: EvaluatedValue, message: String) - throws - { - var seen = Set() - for value in values { - let key = value.text ?? value.member + ":" + (value.fields["name"]?.text ?? "") - if !seen.insert(key).inserted { throw failure(message, anchor) } - } - } - private func uniqueNames(_ values: [ConstructionValue], _ anchor: EvaluatedValue) throws { - try unique( - values.map { .text($0.fields["name"]?.text ?? "") }, at: anchor, - message: "duplicate named member") - } - private func skillNames(_ names: [String], _ anchor: EvaluatedValue) throws { - do { try Declaration.validateNames(names) } catch { - throw failure("invalid or duplicate skill names", anchor) - } - } - private func name(_ value: String, _ anchor: EvaluatedValue) throws { - let parts = value.split(separator: "/", omittingEmptySubsequences: false) - if parts.isEmpty || parts.contains(where: { $0.isEmpty || $0 == "." || $0 == ".." }) - || value.contains(":") || value.contains("\\") - || value.unicodeScalars.contains(where: { $0.value < 0x20 || $0.value == 0x7f }) - { - throw failure("invalid relative name", anchor) - } - } - private func resource(_ path: String, _ anchor: EvaluatedValue) throws { - if path == "~" || path.hasPrefix("~/") { - throw failure("resource needs a safe relative path", anchor) - } - do { _ = try PathSafety.sanitizeSubpath(path) } catch { - throw failure("resource needs a safe relative path", anchor) - } - } - private func http(_ text: String, _ anchor: EvaluatedValue) throws { - guard let url = URLComponents(string: text), - ["http", "https"].contains(url.scheme?.lowercased() ?? ""), - url.host?.isEmpty == false, url.user == nil, url.password == nil, url.fragment == nil - else { throw failure("transport needs an HTTP(S) URL without credentials or fragment", anchor) } - } - private func lexicalPath(_ path: String) -> String { - let prefix = path.hasPrefix("/") ? "/" : path.hasPrefix("~/") ? "~/" : "" - let body = prefix.isEmpty ? path[...] : path.dropFirst(prefix.count) - var parts: [Substring] = [] - for part in body.split(separator: "/") { - if part == "." { continue } - if part == "..", let last = parts.last, last != ".." { - parts.removeLast() - } else { - parts.append(part) - } - } - return prefix + parts.joined(separator: "/") - } -} diff --git a/Sources/AgentsManifest/EvaluatedValue.swift b/Sources/AgentsManifest/EvaluatedValue.swift deleted file mode 100644 index f877939..0000000 --- a/Sources/AgentsManifest/EvaluatedValue.swift +++ /dev/null @@ -1,44 +0,0 @@ -import AgentsDescription - -final class EvaluatedValue: Sendable { - enum Representation: Sendable { - case scalarLiteral, collectionLiteral, construction, reference, synthetic - } - let representation: Representation - let type: ConstructionType - let value: ConstructionValue - let cost: ValueCost - let syntax: Int - let fields: [String: EvaluatedValue] - let elements: [EvaluatedValue] - let referent: EvaluatedValue? - let defaulted: Bool - let referenceDepth: Int - - init( - type: ConstructionType, value: ConstructionValue, cost: ValueCost, syntax: Int, - fields: [String: EvaluatedValue] = [:], elements: [EvaluatedValue] = [], - referent: EvaluatedValue? = nil, defaulted: Bool = false, - representation: Representation = .construction - ) { - self.representation = representation - self.type = type - self.value = value - self.cost = cost - self.syntax = syntax - self.fields = fields - self.elements = elements - self.referent = referent - self.defaulted = defaulted - referenceDepth = (referent?.referenceDepth ?? 0) + (referent == nil ? 0 : 1) - } -} - -extension EvaluatedValue { - var elementsForUse: [EvaluatedValue] { - var value = self - while let next = value.referent { value = next } - return value.elements - } - func field(_ name: String) -> EvaluatedValue? { referent?.field(name) ?? fields[name] } -} diff --git a/Sources/AgentsManifest/Evaluation.swift b/Sources/AgentsManifest/Evaluation.swift deleted file mode 100644 index 9932f51..0000000 --- a/Sources/AgentsManifest/Evaluation.swift +++ /dev/null @@ -1,349 +0,0 @@ -import AgentsDescription - -struct Evaluation: Sendable { - let root: EvaluatedValue - let constants: [String: EvaluatedValue] - let expressions: [Int: EvaluatedValue] - let references: [String: [Int]] - let steps: Int - let total: ValueCost -} - -final class Evaluator { - private let source: SourceText - private let admission: Admission - private let replacements: [String: StaticValue] - private var constants: [String: EvaluatedValue] = [:] - private var expressions: [Int: EvaluatedValue] = [:] - private var references: [String: [Int]] = [:] - private var steps = 0 - private var frames = 0 - private var total = ValueCost(nodes: 0, strings: 0, encoded: 0, depth: 0, origins: 0) - - init(source: SourceText, admission: Admission, replacements: [String: StaticValue] = [:]) { - self.source = source - self.admission = admission - self.replacements = replacements - } - - private func fail(_ code: String, _ message: String, _ id: Int) -> ManifestFailure { - source.failure( - code, message, admission.nodes[id].range.lowerBound, end: admission.nodes[id].range.upperBound - ) - } - private func charge(_ amount: Int = 1, at id: Int) throws { - guard amount <= ManifestLimits.Evaluation.steps - steps else { - throw fail("manifest.limit", "evaluation work steps", id) - } - steps += amount - } - private func check(_ cost: ValueCost, at id: Int) throws { - guard cost.fits else { - throw fail("manifest.limit", "expanded value budget (nodes, bytes, depth or origins)", id) - } - } - - func evaluate() throws -> Evaluation { - for declaration in admission.declarations { - if constants[declaration.name] != nil || Vocabulary.typeNames.contains(declaration.name) { - throw source.failure( - "manifest.reference", "duplicate or shadowing constant", declaration.nameRange.lowerBound, - end: declaration.nameRange.upperBound) - } - let value: EvaluatedValue - if let replacement = replacements[declaration.name] { - let cost = constructionCost(replacement.value) - try check(cost, at: declaration.expression) - value = EvaluatedValue( - type: replacement.type, value: replacement.value, cost: cost, - syntax: declaration.expression) - } else { - value = try evaluate(declaration.expression, context: declaration.type) - } - try check(value.cost, at: declaration.expression) - let next = ValueCost( - nodes: ValueCost.add(total.nodes, value.cost.nodes), - strings: ValueCost.add(total.strings, value.cost.strings), - encoded: ValueCost.add(total.encoded, value.cost.encoded), - depth: max(total.depth, value.cost.depth), - origins: ValueCost.add(total.origins, value.cost.origins)) - try check(next, at: declaration.expression) - total = next - constants[declaration.name] = value - } - guard let root = constants["agents"], root.type == .named("Agents"), - let declaration = admission.declarations.first(where: { $0.name == "agents" }), - admission.nodes[declaration.expression].kind == .call, - admission.nodes[declaration.expression].text == "Agents" - else { - throw source.failure( - "manifest.type", "one let agents = Agents(...) is required", source.bytes.count) - } - return Evaluation( - root: root, constants: constants, expressions: expressions, references: references, - steps: steps, total: total) - } - - private func evaluate(_ id: Int, context: ConstructionType?) throws -> EvaluatedValue { - try charge(at: id) - frames += 1 - defer { frames -= 1 } - guard frames <= ManifestLimits.Evaluation.frames else { - throw fail("manifest.limit", "evaluation frames", id) - } - let node = admission.nodes[id] - let expected = context?.unwrapped - let result: EvaluatedValue - if node.kind == .nilLiteral, case .optional = context { - result = EvaluatedValue(type: context!, value: .none, cost: ValueCost(), syntax: id) - } else { - switch node.kind { - case .group: - let child = try evaluate(node.children[0], context: context) - result = EvaluatedValue( - type: child.type, value: child.value, cost: child.cost, syntax: id, referent: child, - representation: .reference) - case .string: - result = try literal( - .text(node.text), inferred: .named("String"), context: expected, id: id) - case .integer, .negative: - let raw = (node.kind == .negative ? "-" : "") + node.text.filter { $0 != "_" } - guard let integer = Int(raw) else { - throw fail("manifest.type", "integer literal must fit signed 64-bit Int", id) - } - result = try literal( - .integer(integer), inferred: .named("Int"), context: expected, id: id) - case .boolean: - result = try literal( - .boolean(node.text == "true"), inferred: .named("Bool"), context: expected, - id: id) - case .nilLiteral: - result = try literal(.none, inferred: .untyped, context: expected, id: id) - case .array, .dictionary: result = try collection(id, context: expected) - case .sequence: - var arrayType = expected - if let expected, case .array = expected { - } else if expected != nil { - throw fail("manifest.operator", "+ requires exact Swift array operands", id) - } - var operands: [EvaluatedValue] = [] - var count = 0 - var costs: [ValueCost] = [] - for child in node.children { - let value = try evaluate(child, context: arrayType) - guard case .array = value.type, case .array = value.value else { - throw fail("manifest.operator", "+ requires exact Swift arrays", child) - } - arrayType = value.type - count += value.elementsForUse.count - if count > ManifestLimits.Values.entries { - throw fail("manifest.limit", "concatenation entries", id) - } - // Cost is combined before copying any concatenated elements. - operands.append(value) - costs.append(contentsOf: value.elementsForUse.map(\.cost)) - } - let cost = ValueCost.container(costs) - try check(cost, at: id) - try charge(count, at: id) - let elements = operands.flatMap(\.elementsForUse) - result = EvaluatedValue( - type: arrayType!, value: .array(elements.map(\.value)), cost: cost, syntax: id, - elements: elements) - case .range: - let lower = try evaluate(node.children[0], context: .named("Version")) - let upper = try evaluate(node.children[1], context: .named("Version")) - guard case .version(let l) = lower.value, case .version(let u) = upper.value, l < u else { - throw fail("manifest.domain", "version range must be increasing", id) - } - let cost = ValueCost.container([lower.cost, upper.cost]) - try check(cost, at: id) - result = EvaluatedValue( - type: .named("VersionRange"), value: .range(l..= ManifestLimits.Evaluation.frames - 1 { - throw fail("manifest.limit", "active reference frames", id) - } - references[node.text, default: []].append(id) - var cost = bound.cost - cost.origins = ValueCost.add(cost.origins, cost.nodes) - try check(cost, at: id) - result = EvaluatedValue( - type: bound.type, value: bound.value, cost: cost, syntax: id, referent: bound, - representation: .reference) - } else { - result = try call(id, context: expected) - } - } - } - try check(result.cost, at: id) - if let context { - if result.type != context && result.type != context.unwrapped { - throw fail("manifest.type", "value does not match contextual type", id) - } - } - try charge(at: id) - expressions[id] = result - return result - } - - private func literal( - _ value: ConstructionValue, inferred: ConstructionType, context: ConstructionType?, id: Int - ) throws -> EvaluatedValue { - let type = context ?? inferred - let converted: ConstructionValue - do { - converted = try LiteralConversion.convert(value, to: type) { try charge(at: id) } - } catch let error as LiteralConversionError { - throw fail(error.code, error.message, id) - } - return EvaluatedValue( - type: type, value: converted, cost: constructionCost(converted), syntax: id, - representation: .scalarLiteral) - } - - private func collection(_ id: Int, context: ConstructionType?) throws -> EvaluatedValue { - let node = admission.nodes[id] - let dictionary = node.kind == .dictionary - if node.children.count > ManifestLimits.Values.entries { - throw fail("manifest.limit", "collection entries", id) - } - var elementType: ConstructionType? - do { - elementType = try LiteralConversion.elementType( - for: dictionary ? .dictionary : .array, context: context) - } catch let error as LiteralConversionError { - throw fail(error.code, error.message, id) - } - let wrapped = context.map { if case .named = $0 { true } else { false } } ?? false - var values: [EvaluatedValue] = [] - var fields: [String: EvaluatedValue] = [:] - var keySpans: [String: Range] = [:] - for (offset, child) in node.children.enumerated() { - if dictionary { - let key = node.keys[offset].decoded! - if let original = keySpans[key] { - throw ManifestFailure( - ManifestDiagnostic( - code: "manifest.dictionary.duplicateKey", message: "duplicate decoded dictionary key", - span: source.span(node.keys[offset].range), related: [source.span(original)])) - } - keySpans[key] = node.keys[offset].range - } - let value = try evaluate(child, context: elementType) - if elementType == nil { elementType = value.type } - values.append(value) - if dictionary { fields[node.keys[offset].decoded!] = value } - } - guard let elementType else { - throw fail("manifest.type", "empty collection needs a contextual type", id) - } - var cost = ValueCost.container( - values.map(\.cost), keys: dictionary ? node.keys.map { $0.decoded! } : []) - if wrapped { - cost.nodes += 1 - cost.depth += 1 - cost.encoded += 32 - } - try check(cost, at: id) - let inferred: ConstructionType = dictionary ? .dictionary(elementType) : .array(elementType) - let type = context ?? inferred - let value: ConstructionValue - do { - value = try LiteralConversion.collection( - dictionary ? .object(fields.mapValues(\.value)) : .array(values.map(\.value)), - to: type - ) { try charge(at: id) } - } catch let error as LiteralConversionError { - throw fail(error.code, error.message, id) - } - return EvaluatedValue( - type: type, value: value, cost: cost, syntax: id, fields: fields, - elements: dictionary ? [] : values, representation: .collectionLiteral) - } - - private func call(_ id: Int, context: ConstructionType?) throws -> EvaluatedValue { - let node = admission.nodes[id] - let parts = node.text.split(separator: ".", omittingEmptySubsequences: false).map(String.init) - let name: String - let member: String - if node.text == "Agents", node.kind == .call { - name = "Agents" - member = "Agents" - } else if parts.count == 2, parts[0].isEmpty { - guard case .named(let expected) = context else { - throw fail("manifest.type", "shorthand factory or member needs a named context", id) - } - name = expected - member = parts[1] - } else if parts.count == 2, Vocabulary.typeNames.contains(parts[0]) { - name = parts[0] - member = parts[1] - } else { - throw fail("manifest.call", "unlisted call or member", id) - } - let candidates = Vocabulary.signatures.filter { - $0.type == name && $0.member == member && $0.callable == (node.kind == .call) - } - var match: ConstructionSignature? - for signature in candidates { - var argument = 0 - var valid = true - for parameter in signature.parameters { - if argument < node.arguments.count && node.arguments[argument].label == parameter.label { - argument += 1 - } else if parameter.defaultValue == nil { - valid = false - break - } - } - if valid && argument == node.arguments.count { - match = signature - break - } - } - guard let signature = match else { - throw fail("manifest.call", "unlisted factory/case or incorrect labels/order", id) - } - var fields: [String: EvaluatedValue] = [:] - var argument = 0 - for parameter in signature.parameters { - if argument < node.arguments.count && node.arguments[argument].label == parameter.label { - fields[parameter.name] = try evaluate( - node.arguments[argument].value, context: parameter.type) - argument += 1 - } else { - let value = parameter.defaultValue! - fields[parameter.name] = EvaluatedValue( - type: parameter.type, value: value, cost: constructionCost(value), syntax: id, - defaulted: true) - } - } - var cost = ValueCost.container( - fields.values.map(\.cost), keys: [name, member] + Array(fields.keys)) - if name == "VersionRange" { - guard case .version(let lower) = fields["from"]?.value, - lower.successor(major: member == "upToNextMajor").valid - else { throw fail("manifest.domain", "version successor overflow", id) } - } - if name == "Source", case .version(let lower) = fields["from"]?.value, - !lower.successor(major: true).valid - { - throw fail("manifest.domain", "version successor overflow", id) - } - try check(cost, at: id) - try charge(fields.count + 1, at: id) - let value = ConstructionValue.construct( - type: name, member: member, fields: fields.mapValues(\.value)) - // Canonical source requirements charge both range endpoints before lowering. - if name == "Source" { cost = constructionCost(value) } - try check(cost, at: id) - return EvaluatedValue(type: .named(name), value: value, cost: cost, syntax: id, fields: fields) - } -} diff --git a/Sources/AgentsManifest/IRTree.swift b/Sources/AgentsManifest/IRTree.swift new file mode 100644 index 0000000..e2d8d1e --- /dev/null +++ b/Sources/AgentsManifest/IRTree.swift @@ -0,0 +1,249 @@ +import AgentsCore + +/// A single complete IR tree is used for edit intent and comparison; no mutable domain mirror +/// is retained alongside it. +enum IRTree { + static func root(_ ir: DeclarationIR) -> DeclarationValue { + .record( + DeclarationRecord( + kind: "declaration", + fields: [ + "defaultAgents": ir.defaultAgents.map(YAMLConstruction.strings) ?? .null, + "sources": .array(ir.sources.map(DeclarationValue.record)), + "components": .array(ir.components.map(DeclarationValue.record)), + "groups": .array(ir.groups.map(DeclarationValue.record)), + "uses": .array(ir.uses.map(DeclarationValue.record)), + "exports": YAMLConstruction.strings(ir.exports), + "watch": YAMLConstruction.strings(ir.watch), + ])) + } + static func declaration(_ root: DeclarationValue) -> DeclarationIR { + let f = root.record!.fields + func records(_ key: String) -> [DeclarationRecord] { f[key]!.elements!.map { $0.record! } } + func strings(_ key: String) -> [String] { f[key]!.elements!.map { $0.string! } } + return DeclarationIR( + defaultAgents: f["defaultAgents"]?.elements.map { $0.map { $0.string! } }, + exports: strings("exports"), sources: records("sources"), components: records("components"), + groups: records("groups"), uses: records("uses"), watch: strings("watch")) + } + static func segments(_ pointer: String) -> [String] { + pointer.split(separator: "/", omittingEmptySubsequences: true).map { + pointerUnescape(String($0)) + } + } + static func value(_ root: DeclarationValue, at pointer: String) -> DeclarationValue? { + var value = root + for key in segments(pointer) { + switch value { + case .record(let record): + guard let next = record[key] else { return nil } + value = next + case .dictionary(let fields): + guard let next = fields[key] else { return nil } + value = next + case .array(let items): + guard let index = Int(key), items.indices.contains(index) else { return nil } + value = items[index] + default: return nil + } + } + return value + } + static func replacing( + _ root: DeclarationValue, at pointer: String, with replacement: DeclarationValue? + ) -> DeclarationValue { + let keys = segments(pointer) + func update(_ value: DeclarationValue, _ depth: Int) -> DeclarationValue { + if depth == keys.count { return replacement ?? .null } + let key = keys[depth] + switch value { + case .record(let record): + var fields = record.fields + if depth + 1 == keys.count && replacement == nil { + fields.removeValue(forKey: key) + } else { + fields[key] = update(fields[key] ?? .null, depth + 1) + } + return .record(DeclarationRecord(kind: record.kind, fields: fields)) + case .dictionary(var fields): + if depth + 1 == keys.count && replacement == nil { + fields.removeValue(forKey: key) + } else { + fields[key] = update(fields[key] ?? .null, depth + 1) + } + return .dictionary(fields) + case .array(var values): + let index = Int(key)! + if depth + 1 == keys.count && replacement == nil { + values.remove(at: index) + } else { + values[index] = update(values[index], depth + 1) + } + return .array(values) + default: preconditionFailure("checked IR pointer") + } + } + return update(root, 0) + } + static func count(_ value: DeclarationValue) -> Int { + switch value { + case .record(let record): return 1 + record.fields.values.reduce(0) { $0 + count($1) } + case .dictionary(let fields): return 1 + fields.values.reduce(0) { $0 + count($1) } + case .array(let values): return 1 + values.reduce(0) { $0 + count($1) } + default: return 1 + } + } +} + +enum IREdit { + case set(String, DeclarationValue?) + case insert(String, Int, DeclarationValue) + case remove(String, Int) + case move(String, Int, Int) + case relocate(String, Int, String, Int) + + func applying(to root: DeclarationValue) -> DeclarationValue { + switch self { + case .set(let pointer, let value): return IRTree.replacing(root, at: pointer, with: value) + case .insert(let pointer, let index, let value): + var values = IRTree.value(root, at: pointer)!.elements! + values.insert(value, at: index) + return IRTree.replacing(root, at: pointer, with: .array(values)) + case .remove(let pointer, let index): + var values = IRTree.value(root, at: pointer)!.elements! + values.remove(at: index) + return IRTree.replacing(root, at: pointer, with: .array(values)) + case .relocate(let source, let from, let destination, let to): + let value = IRTree.value(root, at: source)!.elements![from] + let removed = IREdit.remove(source, from).applying(to: root) + return IREdit.insert(destination, to, value).applying(to: removed) + case .move(let pointer, let from, let to): + var values = IRTree.value(root, at: pointer)!.elements! + let value = values.remove(at: from) + values.insert(value, at: to) + return IRTree.replacing(root, at: pointer, with: .array(values)) + } + } +} + +/// Computes one direct script in comparable operation units. The script is finite: each array +/// step fixes the next target position or removes a surplus occurrence; each field is visited once. +struct IRDiff { + private(set) var comparisons = 0 + + init(comparisons: Int = 0) { self.comparisons = comparisons } + private(set) var edits: [IREdit] = [] + + mutating func compare(_ old: DeclarationValue, _ new: DeclarationValue, at pointer: String = "") + throws + { + if try equal(old, new) { return } + switch (old, new) { + case (.record(let a), .record(let b)) where a.kind == b.kind: + try fields(a.fields, b.fields, at: pointer) + case (.dictionary(let a), .dictionary(let b)): try fields(a, b, at: pointer) + case (.array(var a), .array(let b)): + for index in b.indices { + if index >= a.count { + edits.append(.insert(pointer, index, b[index])) + a.insert(b[index], at: index) + continue + } + if try equal(a[index], b[index]) { continue } + var exact: Int? + var matches: [Int] = [] + for candidate in a.indices.dropFirst(index + 1) { + if try equal(a[candidate], b[index]) { + exact = candidate + break + } + if identity(a[candidate]) != nil && identity(a[candidate]) == identity(b[index]) { + matches.append(candidate) + } + } + let sameIdentity = identity(a[index]) != nil && identity(a[index]) == identity(b[index]) + if exact == nil && !sameIdentity && matches.count > 1 { + throw ManifestFailure( + ManifestDiagnostic( + code: "manifest.ambiguous", message: "ambiguous matching occurrences", + span: SourceSpan( + document: DocumentIdentity("manifest"), start: 0, end: 0, line: 1, column: 1))) + } + if let match = exact ?? (sameIdentity ? nil : matches.first) { + edits.append(.move(pointer, match, index)) + a.insert(a.remove(at: match), at: index) + } else if !sameIdentity { + var retained = false + for later in b.indices.dropFirst(index + 1) { + if try equal(a[index], b[later]) { + retained = true + break + } + if identity(a[index]) != nil && identity(a[index]) == identity(b[later]) { + retained = true + break + } + } + if retained { + edits.append(.insert(pointer, index, b[index])) + a.insert(b[index], at: index) + continue + } + } + try compare(a[index], b[index], at: pointer + "/\(index)") + a[index] = b[index] + } + while a.count > b.count { + edits.append(.remove(pointer, a.count - 1)) + a.removeLast() + } + default: edits.append(.set(pointer, new)) + } + } + private mutating func fields( + _ old: [String: DeclarationValue], _ new: [String: DeclarationValue], at pointer: String + ) throws { + for key in Set(old.keys).union(new.keys).sorted(by: utf8Less) { + let path = pointer + "/" + pointerEscape(key) + if let a = old[key], let b = new[key] { + try compare(a, b, at: path) + } else { + edits.append(.set(path, new[key])) + } + } + } + private mutating func equal(_ lhs: DeclarationValue, _ rhs: DeclarationValue) throws -> Bool { + var pending = [(lhs, rhs)] + while let (a, b) = pending.popLast() { + comparisons += 1 + guard comparisons <= ManifestLimits.Editing.comparisonPairs else { throw limit() } + switch (a, b) { + case (.record(let x), .record(let y)): + guard x.kind == y.kind, x.fields.keys == y.fields.keys else { return false } + for key in x.fields.keys.sorted(by: utf8Less) { + pending.append((x.fields[key]!, y.fields[key]!)) + } + case (.dictionary(let x), .dictionary(let y)): + guard x.keys == y.keys else { return false } + for key in x.keys.sorted(by: utf8Less) { pending.append((x[key]!, y[key]!)) } + case (.array(let x), .array(let y)): + guard x.count == y.count else { return false } + pending += zip(x, y) + default: if a != b { return false } + } + } + return true + } + private func identity(_ value: DeclarationValue) -> String? { + guard let record = value.record else { return nil } + return record["name"]?.string.map { record.kind + ":" + $0 } + ?? (record.kind == "skills" ? record["source"]?.string.map { "skills:" + $0 } : nil) + } + private func limit() -> ManifestFailure { + ManifestFailure( + ManifestDiagnostic( + code: "manifest.limit", message: "edit comparison limit", + span: SourceSpan( + document: DocumentIdentity("manifest"), start: 0, end: 0, line: 1, column: 1))) + } +} diff --git a/Sources/AgentsManifest/LiteralConversion.swift b/Sources/AgentsManifest/LiteralConversion.swift deleted file mode 100644 index 6779a06..0000000 --- a/Sources/AgentsManifest/LiteralConversion.swift +++ /dev/null @@ -1,118 +0,0 @@ -import AgentsDescription - -enum LiteralConversionError: Error { - case incompatible, invalidVersion - - var code: String { self == .invalidVersion ? "manifest.domain" : "manifest.type" } - var message: String { - self == .invalidVersion ? "invalid semantic version" : "literal needs a compatible context" - } -} - -/// Closed literal conversions shared by static evaluation and domain edits. -/// Contextually evaluated collections retain their typed descendants; untyped edit -/// payloads use recursive conversion with an explicit work budget. -enum LiteralConversion { - static func kind(of value: ConstructionValue) -> LiteralKind? { - switch value { - case .text: .string - case .integer: .integer - case .boolean: .boolean - case .none: .nilLiteral - case .array: .array - case .object: .dictionary - default: nil - } - } - - static func elementType( - for kind: LiteralKind, context: ConstructionType? - ) throws -> ConstructionType? { - guard let context = context?.unwrapped else { return nil } - let payload: ConstructionType - if case .named(let name) = context { - guard let type = Vocabulary.literalConstructions[name]?[kind]?.payloadType else { - throw LiteralConversionError.incompatible - } - payload = type - } else { - payload = context - } - switch (kind, payload) { - case (.array, .array(let element)), (.dictionary, .dictionary(let element)): return element - default: throw LiteralConversionError.incompatible - } - } - - static func convert( - _ value: ConstructionValue, to context: ConstructionType, - charge: () throws -> Void - ) throws -> ConstructionValue { - try charge() - if case .optional(let wrapped) = context { - return value == .none ? .none : try convert(value, to: wrapped, charge: charge) - } - switch (value, context) { - case (.text, .named("String")), (.integer, .named("Int")), (.boolean, .named("Bool")): - return value - case (.version, .named("Version")), (.range, .named("VersionRange")): return value - case (.node(let type, _, _), .named(let expected)) where type == expected: return value - case (.array(let values), .array(let element)): - return .array(try values.map { try convert($0, to: element, charge: charge) }) - case (.object(let fields), .dictionary(let element)): - return .object(try fields.mapValues { try convert($0, to: element, charge: charge) }) - case (.text(let text), .named("Version")): - let version = Version(stringLiteral: text) - guard version.valid else { throw LiteralConversionError.invalidVersion } - return .version(version) - default: break - } - guard case .named(let name) = context, let kind = kind(of: value), - let construction = Vocabulary.literalConstructions[name]?[kind] - else { throw LiteralConversionError.incompatible } - let payload: ConstructionValue - if let type = construction.payloadType { - payload = try convert(value, to: type, charge: charge) - } else { - payload = value - } - return try construct(payload, name: name, using: construction, charge: charge) - } - - /// Elements have already been checked in their payload context. Only the new - /// container and its optional vocabulary wrapper need work; descendants stay shared. - static func collection( - _ payload: @autoclosure () -> ConstructionValue, - to context: ConstructionType, - charge: () throws -> Void - ) throws -> ConstructionValue { - try charge() - let value = payload() - let kind: LiteralKind - switch value { - case .array: kind = .array - case .object: kind = .dictionary - default: throw LiteralConversionError.incompatible - } - let context = context.unwrapped - switch (kind, context) { - case (.array, .array), (.dictionary, .dictionary): return value - default: break - } - guard case .named(let name) = context, - let construction = Vocabulary.literalConstructions[name]?[kind] - else { throw LiteralConversionError.incompatible } - return try construct(value, name: name, using: construction, charge: charge) - } - - private static func construct( - _ payload: ConstructionValue, name: String, using construction: LiteralConstruction, - charge: () throws -> Void - ) throws -> ConstructionValue { - try charge() - var fields = construction.defaults - for _ in fields { try charge() } - if let key = construction.payload { fields[key] = payload } - return .node(type: name, member: construction.member, fields: fields) - } -} diff --git a/Sources/AgentsManifest/Lowering.swift b/Sources/AgentsManifest/Lowering.swift deleted file mode 100644 index 2328de3..0000000 --- a/Sources/AgentsManifest/Lowering.swift +++ /dev/null @@ -1,64 +0,0 @@ -import AgentsCore -import AgentsDescription - -enum Lowering { - static func declaration(_ value: ConstructionValue) -> DeclarationIR { - let fields = value.fields - return DeclarationIR( - defaultAgents: fields["defaultAgents"]?.array?.compactMap { lower($0).string }, - exports: fields["exports"]?.strings ?? [], - sources: (fields["sources"]?.array ?? []).compactMap { lower($0).record }, - components: (fields["components"]?.array ?? []).compactMap { lower($0).record }, - groups: (fields["groups"]?.array ?? []).compactMap { lower($0).record }, - uses: (fields["uses"]?.array ?? []).compactMap { lower($0).record }, - watch: fields["watch"]?.strings ?? []) - } - - static func requirement(_ range: Range) -> SourceRequirement { - SourceRequirement.range( - from: range.lowerBound.normalized, to: range.upperBound.normalized - ).canonical - } - - static func recordKind( - type: String, member: String, fields: [String: ConstructionValue] - ) -> String { - if type == "Source" { - return fields["url"] != nil ? "git" : fields["path"] != nil ? "local" : "index" - } - if type == "GroupReference" { return fields["source"]?.text == nil ? "local" : "exported" } - return member - } - - static func lower(_ value: ConstructionValue) -> DeclarationValue { - switch value { - case .text(let text): return .string(text) - case .integer(let integer): return .integer(integer) - case .boolean(let boolean): return .boolean(boolean) - case .none: return .null - case .version(let version): return .string(version.normalized) - case .range(let range): return .requirement(requirement(range)) - case .array(let values): return .array(values.map(lower)) - case .object(let fields): return .dictionary(fields.mapValues(lower)) - case .node(let type, let member, let fields): - if let spelling = Vocabulary.scalarValues[type]?[member] { - return .string(spelling) - } - if type == "SkillSelection" { - return member == "all" ? .string("all") : .array((fields["names"]?.array ?? []).map(lower)) - } - if type == "Requirement", let text = fields["value"]?.text { - return .requirement( - member == "exact" ? .exact(text) : member == "branch" ? .branch(text) : .revision(text)) - } - var lowered = fields.mapValues(lower) - let kind = recordKind(type: type, member: member, fields: fields) - if type == "Source" { - if let url = fields["url"]?.text { - lowered["url"] = .string(SourceDeclaration(kind: .git, location: url).gitURL) - } - } - return .record(DeclarationRecord(kind: kind, fields: lowered)) - } - } -} diff --git a/Sources/AgentsManifest/ManifestDiagnostic.swift b/Sources/AgentsManifest/ManifestDiagnostic.swift index a4e7275..c864f61 100644 --- a/Sources/AgentsManifest/ManifestDiagnostic.swift +++ b/Sources/AgentsManifest/ManifestDiagnostic.swift @@ -47,8 +47,7 @@ public struct SourcePatch: Sendable, Equatable { package struct FrontEndMetrics: Sendable, Codable { package var parserCalls = 0 - package var tokens = 0 - package var syntaxReservation = 0 + package var parserCallbacks = 0 package var syntaxNodes = 0 package var syntaxDepth = 0 package var evaluationSteps = 0 diff --git a/Sources/AgentsManifest/ManifestDump.swift b/Sources/AgentsManifest/ManifestDump.swift index 496dab8..cc09c31 100644 --- a/Sources/AgentsManifest/ManifestDump.swift +++ b/Sources/AgentsManifest/ManifestDump.swift @@ -1,7 +1,6 @@ import AgentsCore -import AgentsDescription -/// Local evaluated values and source coordinates. Construction performs no linking or source I/O. +/// Complete local intent and semantic source coordinates. No source resolution occurs. public struct ManifestDump: Sendable { public struct Location: Sendable { public let pointer: String @@ -10,10 +9,10 @@ public struct ManifestDump: Sendable { public let defaulted: Bool public let editability: ManifestJSONValue } - - public let schemaVersion = 1 + public let schemaVersion = 2 public let kind = "manifest" - public let languageVersion = "1.0" + public let format = "yaml" + public let manifestVersion = 1 public let sourceDigest: String public let declaration: ManifestJSONValue public let locations: [Location] @@ -23,187 +22,95 @@ public struct ManifestDump: Sendable { try self.init( document: DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest"))) } - public init(document: DeclarationDocument) throws { - var projection = DumpProjection() - declaration = projection.value(document.evaluation.root.value, old: "", new: "") sourceDigest = document.digest - locations = try document.sourceMap.entries.map { entry -> Location in - guard let pointer = projection.pointers[entry.pointer], - let node = document.node(at: entry.pointer) - else { - throw document.source.failure( - "manifest.dump.mismatch", "source map pointer is absent from the evaluated declaration", - entry.span.start) - } + let ir = document.declaration + let fields: [String: ManifestJSONValue] = [ + "defaultAgents": ir.defaultAgents.map { .array($0.map(ManifestJSONValue.string)) } ?? .null, + "sources": .array(ir.sources.map { Self.value(.record($0)) }), + "components": .array(ir.components.map { Self.value(.record($0)) }), + "groups": .array(ir.groups.map { Self.value(.record($0)) }), + "uses": .array(ir.uses.map { Self.value(.record($0)) }), + "exports": .array(ir.exports.map(ManifestJSONValue.string)), + "watch": .array(ir.watch.map(ManifestJSONValue.string)), + ] + declaration = .object(fields) + locations = document.sourceMap.entries.map { let editability: ManifestJSONValue - switch document.editability(of: node) { - case .direct: editability = .object(["kind": .string("direct")]) - case .readOnly(let reason): - editability = .object(["kind": .string("readOnly"), "reason": .string(reason)]) - case .sharedConstant(let uses): + if $0.pointer.hasSuffix("/kind") { editability = .object([ - "kind": .string("sharedConstant"), - "uses": .array( - uses.map { spanJSON(document.source.span(document.admission.nodes[$0.syntax].range)) }), + "kind": .string("readOnly"), + "reason": .string("record kind; replace its containing value"), ]) + } else { + editability = .object(["kind": .string("direct")]) } return Location( - pointer: pointer, span: manifestSpan(entry.span), origins: entry.origins.map(manifestSpan), - defaulted: entry.defaulted, editability: editability) - }.sorted { - $0.pointer == $1.pointer ? $0.span.start < $1.span.start : utf8Less($0.pointer, $1.pointer) - } + pointer: $0.pointer, span: Self.span($0.span), origins: $0.origins.map(Self.span), + defaulted: $0.defaulted, editability: editability) + }.sorted { utf8Less($0.pointer, $1.pointer) } diagnostics = document.diagnostics.map { ManifestDiagnostic( - code: $0.code, severity: $0.severity, message: $0.message, span: manifestSpan($0.span), - related: $0.related.map(manifestSpan)) - }.sorted { ($0.span.start, $0.code) < ($1.span.start, $1.code) } - _ = try locationJSON.encodedCount( - limit: ManifestLimits.SourceMap.encodedBytes, budget: "source map encoded bytes") + code: $0.code, severity: $0.severity, message: $0.message, span: Self.span($0.span), + related: $0.related.map(Self.span)) + } _ = try json.encodedCount(limit: ManifestLimits.Output.encodedBytes - 1) } - public func encodedJSON() throws -> [UInt8] { try json.encodedJSON() } - private var locationJSON: ManifestJSONValue { - .array( - locations.map { location in - .object([ - "pointer": .string(location.pointer), "span": spanJSON(location.span), - "origins": .array(location.origins.map(spanJSON)), - "defaulted": .boolean(location.defaulted), - "editability": location.editability, - ]) - }) - } - private var json: ManifestJSONValue { .object([ - "schemaVersion": .integer(schemaVersion), "kind": .string(kind), - "languageVersion": .string(languageVersion), - "sourceDigest": .string(sourceDigest), "declaration": declaration, "locations": locationJSON, + "schemaVersion": .integer(schemaVersion), "kind": .string(kind), "format": .string(format), + "manifestVersion": .integer(manifestVersion), "sourceDigest": .string(sourceDigest), + "declaration": declaration, + "locations": .array( + locations.map { + .object([ + "pointer": .string($0.pointer), "span": Self.spanJSON($0.span), + "origins": .array($0.origins.map(Self.spanJSON)), "defaulted": .boolean($0.defaulted), + "editability": $0.editability, + ]) + }), "diagnostics": .array( diagnostics.map { .object([ "code": .string($0.code), "severity": .string($0.severity.rawValue), - "message": .string($0.message), - "span": spanJSON($0.span), "related": .array($0.related.map(spanJSON)), + "message": .string($0.message), "span": Self.spanJSON($0.span), + "related": .array($0.related.map(Self.spanJSON)), ]) }), ]) } -} - -private func manifestSpan(_ span: SourceSpan) -> SourceSpan { - SourceSpan( - document: DocumentIdentity("manifest"), start: span.start, end: span.end, line: span.line, - column: span.column) -} - -private func spanJSON(_ span: SourceSpan) -> ManifestJSONValue { - .object([ - "document": .string("manifest"), "start": .integer(span.start), "end": .integer(span.end), - "line": .integer(span.line), "column": .integer(span.column), - ]) -} - -private struct DumpProjection { - var pointers: [String: String] = [:] - - mutating func value(_ value: ConstructionValue, old: String, new: String) -> ManifestJSONValue { - pointers[old] = new - switch value { - case .text(let text): return .string(text) - case .integer(let number): return .integer(number) - case .boolean(let flag): return .boolean(flag) - case .none: return .null - case .version(let version): return .string(version.normalized) - case .range(let range): return requirement(Lowering.requirement(range), old: old, new: new) - case .object(let fields): - var result: [String: ManifestJSONValue] = [:] - for key in fields.keys.sorted(by: utf8Less) { - let suffix = "/" + pointerEscape(key) - result[key] = self.value(fields[key]!, old: old + suffix, new: new + suffix) - } - return .object(result) - case .array(let values): - return array(values, old: old, new: new, sort: nil) - case .node(let type, let member, let fields): - if let spelling = Vocabulary.scalarValues[type]?[member] { return .string(spelling) } - if type == "SkillSelection" { - return member == "all" - ? .string("all") : array(fields["names"]!.array!, old: old, new: new, sort: scalarKey) - } - if type == "Requirement", case .requirement(let requirement) = Lowering.lower(value) { - return self.requirement(requirement, old: old, new: new) - } - var result: [String: ManifestJSONValue] = [:] - if Vocabulary.taggedRecordTypes.contains(type) { - let kind = Lowering.recordKind(type: type, member: member, fields: fields) - pointers[old + "/kind"] = new + "/kind" - result["kind"] = .string(kind) - } - for key in fields.keys.sorted(by: utf8Less) { - let suffix = "/" + pointerEscape(key) - let field = fields[key]! - if type == "Source", key == "url", let url = field.text { - pointers[old + suffix] = new + suffix - result[key] = .string(SourceDeclaration(kind: .git, location: url).gitURL) - } else if case .array(let values) = field { - let sort: ((ConstructionValue) -> String)? - if ["agents", "defaultAgents", "exports", "watch", "scopes", "platforms", "exclude"] - .contains(key) - { - sort = scalarKey - } else if ["sources", "groups", "chatGPT", "overrides"].contains(key) { - sort = { $0.fields["name"]?.text ?? "" } - } else { - sort = nil - } - pointers[old + suffix] = new + suffix - result[key] = array(values, old: old + suffix, new: new + suffix, sort: sort) - } else { - result[key] = self.value(field, old: old + suffix, new: new + suffix) - } - } - return .object(result) - } + private static func span(_ value: SourceSpan) -> SourceSpan { + SourceSpan( + document: DocumentIdentity("manifest"), start: value.start, end: value.end, line: value.line, + column: value.column) } - - private mutating func array( - _ values: [ConstructionValue], old: String, new: String, sort: ((ConstructionValue) -> String)? - ) -> ManifestJSONValue { - var entries = Array(values.enumerated()) - if let sort { entries.sort { utf8Less(sort($0.element), sort($1.element)) } } - var result: [ManifestJSONValue] = [] - for (index, entry) in entries.enumerated() { - result.append(value(entry.element, old: old + "/\(entry.offset)", new: new + "/\(index)")) - } - return .array(result) - } - - private mutating func requirement(_ requirement: SourceRequirement, old: String, new: String) - -> ManifestJSONValue - { - let fields: [String: ManifestJSONValue] - switch requirement { - case .branch(let text): fields = ["branch": .string(text)] - case .revision(let text): fields = ["revision": .string(text)] - case .exact(let text): fields = ["exact": .string(text)] - case .upToNextMajor(let text): fields = ["from": .string(text)] - case .upToNextMinor(let text): fields = ["upToNextMinor": .string(text)] - case .range(let lower, let upper): fields = ["from": .string(lower), "to": .string(upper)] - } - for key in fields.keys { pointers[old + "/" + key] = new + "/" + key } - return .object(fields) + private static func spanJSON(_ value: SourceSpan) -> ManifestJSONValue { + .object([ + "document": .string("manifest"), "start": .integer(value.start), "end": .integer(value.end), + "line": .integer(value.line), "column": .integer(value.column), + ]) } - - private func scalarKey(_ value: ConstructionValue) -> String { - if let text = Lowering.lower(value).string { return text } - if case .node("ComponentReference", let kind, let fields) = value { - return kind + "\0" + (fields["name"]?.text ?? "") + private static func value(_ value: DeclarationValue) -> ManifestJSONValue { + switch value { + case .string(let value): return .string(value) + case .integer(let value): return .integer(value) + case .boolean(let value): return .boolean(value) + case .null: return .null + case .array(let values): return .array(values.map(Self.value)) + case .dictionary(let values): return .object(values.mapValues(Self.value)) + case .record(let record): + return .object( + record.fields.mapValues(Self.value).merging(["kind": .string(record.kind)]) { _, value in + value + }) + case .requirement(let requirement): + var fields = [ + "kind": ManifestJSONValue.string(requirement.kind), "value": .string(requirement.value), + ] + if let upper = requirement.upperBound { fields["to"] = .string(upper) } + return .object(fields) } - return (value.fields["kind"]?.member ?? "") + "\0" + (value.fields["name"]?.text ?? "") } } diff --git a/Sources/AgentsManifest/ManifestFrontEnd.swift b/Sources/AgentsManifest/ManifestFrontEnd.swift index c541347..6cbc937 100644 --- a/Sources/AgentsManifest/ManifestFrontEnd.swift +++ b/Sources/AgentsManifest/ManifestFrontEnd.swift @@ -1,128 +1,18 @@ import AgentsCore -import AgentsDescription -import Foundation -import SwiftSyntax package enum FrontEndStage: String, Sendable, Codable { - case admission, parser, evaluation, domain, lowering, sourceMap, teardown + case admission, parser, decoding, domain, lowering, sourceMap, teardown } - -package enum FrontEndCheck: Sendable, Equatable { - case syntax, declaration -} - -struct FrontEndDeclaration { - let evaluation: Evaluation - let ir: DeclarationIR - let diagnostics: [ManifestDiagnostic] - let digest: String - let map: BuiltMap -} - -struct FrontEndResult { - let source: SourceText - let admission: Admission - let syntax: SourceFileSyntax - let declaration: FrontEndDeclaration? - let metrics: FrontEndMetrics -} - -/// Owns phase ordering for document construction and bounded syntax inspection. -/// Observers receive phase-entry metrics; failures retain the phase and work already done. +package enum FrontEndCheck: Sendable, Equatable { case syntax, declaration } package enum ManifestFrontEnd { - /// `.syntax` runs admission, parsing, tree guards and projection comparison. - /// `.declaration` also evaluates and validates values, lowers IR and builds source maps. - /// Both release the retained syntax tree before returning. package static func inspect( bytes: [UInt8], identity: DocumentIdentity, checking: FrontEndCheck, observe: ((FrontEndStage, FrontEndMetrics) -> Void)? = nil ) throws -> FrontEndMetrics { - var result: FrontEndResult? = try run( - bytes: bytes, identity: identity, checking: checking, observe: observe) - var metrics = result!.metrics - observe?(.teardown, metrics) - let clock = ContinuousClock() - let start = clock.now - // Keep ARC from releasing the tree before teardown timing starts. - withExtendedLifetime(result) {} - result = nil - metrics.teardownSeconds = seconds(start.duration(to: clock.now)) - return metrics - } - - static func run( - bytes: [UInt8], identity: DocumentIdentity, checking: FrontEndCheck, - validateDomain: Bool = true, observe: ((FrontEndStage, FrontEndMetrics) -> Void)? = nil - ) throws -> FrontEndResult { - let clock = ContinuousClock() - var stage = FrontEndStage.admission - var stageStart = clock.now - var metrics = FrontEndMetrics() - let source = SourceText(Array(bytes.prefix(ManifestLimits.Input.bytes + 1)), identity: identity) - func enter(_ next: FrontEndStage) { - stage = next - stageStart = clock.now - var progress = metrics - if next == .parser { progress.parserCalls += 1 } - observe?(next, progress) - } - enter(.admission) - do { - if bytes.count > ManifestLimits.Input.bytes { - throw source.failure("manifest.limit", "input byte limit", ManifestLimits.Input.bytes) - } - let admission = try Recognizer(source: source).recognize() - metrics.admissionSeconds = seconds(stageStart.duration(to: clock.now)) - metrics.tokens = admission.tokens.count - metrics.syntaxReservation = admission.reservation - enter(.parser) - let checked = try SyntaxValidation.parse(source, admission: admission, metrics: metrics) - metrics = checked.metrics - if checking == .syntax { - return FrontEndResult( - source: source, admission: admission, syntax: checked.tree, declaration: nil, - metrics: metrics) - } - enter(.evaluation) - let evaluation = try Evaluator(source: source, admission: admission).evaluate() - metrics.evaluationSeconds = seconds(stageStart.duration(to: clock.now)) - metrics.evaluationSteps = evaluation.steps - metrics.expandedNodes = evaluation.total.nodes - metrics.decodedBytes = evaluation.total.strings - enter(.domain) - let diagnostics = - validateDomain - ? try DomainValidator(source: source, admission: admission, evaluation: evaluation) - .validate() - : [] - metrics.domainSeconds = seconds(stageStart.duration(to: clock.now)) - enter(.lowering) - let ir = Lowering.declaration(evaluation.root.value) - metrics.loweringSeconds = seconds(stageStart.duration(to: clock.now)) - enter(.sourceMap) - let digest = "sha256:" + FileHash.sha256Hex(data: Data(bytes)) - let map = try MapBuilder(source: source, admission: admission, digest: digest).build( - evaluation) - metrics.sourceMapSeconds = seconds(stageStart.duration(to: clock.now)) - return FrontEndResult( - source: source, admission: admission, syntax: checked.tree, - declaration: FrontEndDeclaration( - evaluation: evaluation, ir: ir, diagnostics: diagnostics, digest: digest, map: map), - metrics: metrics) - } catch let failure as ManifestFailure { - let elapsed = seconds(stageStart.duration(to: clock.now)) - switch stage { - case .admission: - metrics = failure.metrics - metrics.admissionSeconds = elapsed - case .parser: metrics = failure.metrics - case .evaluation: metrics.evaluationSeconds = elapsed - case .domain: metrics.domainSeconds = elapsed - case .lowering: metrics.loweringSeconds = elapsed - case .sourceMap: metrics.sourceMapSeconds = elapsed - default: break - } - throw ManifestFailure(failure.diagnostics[0], metrics: metrics, stage: stage) - } + observe?(.admission, FrontEndMetrics()) + let document = try DeclarationDocument( + bytes: bytes, identity: identity, validateDomain: checking == .declaration, observe: observe) + observe?(.teardown, document.metrics) + return document.metrics } } diff --git a/Sources/AgentsManifest/ManifestLimits.swift b/Sources/AgentsManifest/ManifestLimits.swift index 60f52b1..0c8060a 100644 --- a/Sources/AgentsManifest/ManifestLimits.swift +++ b/Sources/AgentsManifest/ManifestLimits.swift @@ -1,21 +1,10 @@ -/// Language 1.0 front-end bounds, grouped by their owner in the manifest contract. +/// YAML declaration bounds, grouped by their owner in the manifest contract. /// Counts are charged by occurrence, including unused definitions and repeated origins. package enum ManifestLimits { package enum Input { package static let bytes = 2_097_152 } - enum Admission { - static let tokens = 100_000 - static let syntaxReservation = 100_000 - static let reservationBase = 16 - static let reservationPerUnit = 4 - static let squareDepth = 8 - static let delimiterDepth = 20 - static let commentDepth = 20 - static let additiveTerms = 32 - } enum Syntax { - static let parserNesting = 20 static let depth = 128 static let nodes = 100_000 } diff --git a/Sources/AgentsManifest/ManifestProjection.swift b/Sources/AgentsManifest/ManifestProjection.swift index 6e3e365..963d460 100644 --- a/Sources/AgentsManifest/ManifestProjection.swift +++ b/Sources/AgentsManifest/ManifestProjection.swift @@ -39,7 +39,7 @@ package enum ManifestProjection { ComponentGroupDeclaration( name: record["name"]!.string!, components: try projection.records(record["components"]).map(projection.component), - uses: try projection.records(record["uses"]).map(projection.use), + uses: projection.records(record["uses"]).map(projection.use), condition: projection.condition(record["condition"])) }, uses: ir.uses.map(projection.use), exports: ir.exports, watch: ir.watch.isEmpty ? nil : ir.watch) @@ -123,7 +123,7 @@ package enum ManifestProjection { } } -/// Static evaluation checks vocabulary and field types before conversion, including in drafts. +/// Schema validation checks field types before conversion, including private drafts. private struct Projection { let document: DeclarationDocument diff --git a/Sources/AgentsManifest/ManifestSchema.swift b/Sources/AgentsManifest/ManifestSchema.swift new file mode 100644 index 0000000..fda91cc --- /dev/null +++ b/Sources/AgentsManifest/ManifestSchema.swift @@ -0,0 +1,174 @@ +// Generated by Scripts/generate-manifest-schema.py. + +enum ManifestSchema { + static let root: YAMLRule = .object( + [ + "version": .version, "defaultAgents": .array(.named("agent")), + "sources": .dictionary(.named("source")), "components": .array(.named("component")), + "groups": .dictionary(.named("group")), "uses": .array(.named("use")), + "exports": .array(.string), "watch": .array(.string), + ], required: ["version"]) + static let definitions: [String: YAMLRule] = [ + "agent": .enumeration(["codex", "claude-code", "cursor", "gemini-cli", "opencode"]), + "condition": .object( + [ + "agents": .array(.named("agent")), "scopes": .array(.enumeration(["project", "user"])), + "platforms": .array(.enumeration(["macos", "linux"])), + ], required: []), + "resource": .object(["path": .string, "source": .string], required: ["path"]), + "section": .object( + ["name": .string, "source": .string, "condition": .named("condition")], required: ["name"]), + "binding": .oneOf([ + .string, .object(["env": .string], required: ["env"]), + .object(["secret": .string], required: ["secret"]), + ]), + "prompt": .oneOf([.string, .object(["file": .named("resource")], required: ["file"])]), + "run": .object( + [ + "executable": .string, "arguments": .array(.string), + "environment": .dictionary(.named("binding")), "workingDirectory": .named("resource"), + ], required: ["executable"]), + "transport": .oneOf([ + .object( + [ + "kind": .constant("stdio"), "executable": .string, "arguments": .array(.string), + "environment": .dictionary(.named("binding")), "workingDirectory": .named("resource"), + ], required: ["kind", "executable"]), + .object( + [ + "kind": .enumeration(["streamableHTTP", "sse"]), "url": .string, + "headers": .dictionary(.named("binding")), + ], required: ["kind", "url"]), + ]), + "event": .oneOf([ + .enumeration(["beforeTool", "afterTool", "sessionStart", "sessionEnd"]), + .object(["native": .string], required: ["native"]), + ]), + "operation": .oneOf([ + .enumeration(["read", "write", "execute"]), .object(["tool": .string], required: ["tool"]), + ]), + "rule": .object( + [ + "effect": .enumeration(["allow", "ask", "deny"]), "operation": .named("operation"), + "pattern": .string, + ], required: ["effect", "operation", "pattern"]), + "parameter": .object( + ["name": .string, "description": .string, "defaultValue": .string], + required: ["name", "description"]), + "promptDeclaration": .object( + ["sections": .array(.named("section")), "append": .string, "condition": .named("condition")], + required: []), + "override": .object( + ["agents": .array(.named("agent")), "mode": .enumeration(["link", "copy", "edit"])], + required: []), + "requirement": .oneOf([ + .object(["branch": .string], required: ["branch"]), + .object(["revision": .string], required: ["revision"]), + .object(["exact": .string], required: ["exact"]), + .object(["from": .string], required: ["from"]), + .object(["upToNextMinor": .string], required: ["upToNextMinor"]), + .object(["from": .string, "to": .string], required: ["from", "to"]), + ]), + "source": .oneOf([ + .object( + ["url": .string, "subpath": .string, "requirement": .named("requirement")], + required: ["url"]), + .object( + ["path": .string, "subpath": .string, "requirement": .named("requirement")], + required: ["path"]), .object(["index": .string, "subpath": .string], required: ["index"]), + ]), + "componentReference": .object( + [ + "kind": .enumeration([ + "skill", "instruction", "mcpServer", "hook", "subagent", "command", "lspServer", + "permissions", "ignore", "plugin", + ]), "name": .string, + ], required: ["kind", "name"]), + "component_skills": .object( + [ + "kind": .constant("skills"), "agents": .array(.named("agent")), + "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), + "source": .string, "select": .oneOf([.constant("all"), .array(.string)]), + "exclude": .array(.string), "mode": .enumeration(["link", "copy", "edit"]), + "overrides": .dictionary(.named("override")), + ], required: ["kind", "source"]), + "component_instructions": .object( + [ + "kind": .constant("instructions"), "agents": .array(.named("agent")), + "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), + "sections": .array(.named("section")), "chatgpt": .dictionary(.named("promptDeclaration")), + ], required: ["kind"]), + "component_mcpServer": .object( + [ + "kind": .constant("mcpServer"), "agents": .array(.named("agent")), + "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), + "name": .string, "transport": .named("transport"), + ], required: ["kind", "name", "transport"]), + "component_hook": .object( + [ + "kind": .constant("hook"), "agents": .array(.named("agent")), + "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), + "name": .string, "event": .named("event"), "run": .named("run"), "matcher": .string, + "timeoutSeconds": .integer(minimum: 1), + ], required: ["kind", "name", "event", "run"]), + "component_subagent": .object( + [ + "kind": .constant("subagent"), "agents": .array(.named("agent")), + "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), + "name": .string, "description": .string, "prompt": .named("prompt"), "model": .string, + "tools": .array(.string), + ], required: ["kind", "name", "description", "prompt"]), + "component_command": .object( + [ + "kind": .constant("command"), "agents": .array(.named("agent")), + "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), + "name": .string, "description": .string, "prompt": .named("prompt"), + "parameters": .array(.named("parameter")), + ], required: ["kind", "name", "description", "prompt"]), + "component_lspServer": .object( + [ + "kind": .constant("lspServer"), "agents": .array(.named("agent")), + "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), + "name": .string, "run": .named("run"), "languages": .dictionary(.string), + "initializationOptions": .dictionary(.native), + ], required: ["kind", "name", "run", "languages"]), + "component_permissions": .object( + [ + "kind": .constant("permissions"), "agents": .array(.named("agent")), + "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), + "name": .string, "rules": .array(.named("rule")), + ], required: ["kind", "name", "rules"]), + "component_ignore": .object( + [ + "kind": .constant("ignore"), "agents": .array(.named("agent")), + "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), + "name": .string, "patterns": .array(.string), + "purpose": .enumeration(["context", "indexing"]), + ], required: ["kind", "name", "patterns"]), + "component_plugin": .object( + [ + "kind": .constant("plugin"), "agents": .array(.named("agent")), + "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), + "name": .string, "source": .string, "path": .string, + "mode": .enumeration(["native", "components"]), + "select": .array( + .enumeration([ + "skills", "instructions", "mcpServer", "hook", "subagent", "command", "lspServer", + "permissions", "ignore", "plugin", + ])), "exclude": .array(.named("componentReference")), + ], required: ["kind", "name", "source", "path"]), + "component": .oneOf([ + .named("component_skills"), .named("component_instructions"), .named("component_mcpServer"), + .named("component_hook"), .named("component_subagent"), .named("component_command"), + .named("component_lspServer"), .named("component_permissions"), .named("component_ignore"), + .named("component_plugin"), + ]), + "use": .object( + ["group": .string, "source": .string, "condition": .named("condition")], required: ["group"]), + "group": .object( + [ + "components": .array(.named("component")), "uses": .array(.named("use")), + "condition": .named("condition"), + ], required: []), + ] +} diff --git a/Sources/AgentsManifest/ManifestState.swift b/Sources/AgentsManifest/ManifestState.swift index dd3c90b..8122a7d 100644 --- a/Sources/AgentsManifest/ManifestState.swift +++ b/Sources/AgentsManifest/ManifestState.swift @@ -1,5 +1,4 @@ import AgentsCore -import AgentsDescription import Foundation /// Declaration access for scope state. Core owns the file, its captured bytes, the missing @@ -58,8 +57,7 @@ extension StateStore { if change == nil, try declarationBytes(prepared: baseline) == nil { change = DeclarationChange( bytes: Data( - try CanonicalPrinter().manifest( - DeclarationConstruction.root(declaration).constructionValue))) + YAMLWriter.manifest(YAMLConstruction.root(declaration)))) } let transaction = FileTransaction(store: self) transaction.requireUnchanged(since: baseline) diff --git a/Sources/AgentsManifest/MapBuilder.swift b/Sources/AgentsManifest/MapBuilder.swift deleted file mode 100644 index dac54f4..0000000 --- a/Sources/AgentsManifest/MapBuilder.swift +++ /dev/null @@ -1,204 +0,0 @@ -import AgentsCore -import AgentsDescription - -struct BuiltMap { - var entries: [SourceMapEntry] = [] - var locations: [String: NodeID] = [:] - var values: [String: EvaluatedValue] = [:] -} - -final class MapBuilder { - private let source: SourceText - private let admission: Admission - private let digest: String - private var result = BuiltMap() - private var budget = SourceMapBudget() - - init(source: SourceText, admission: Admission, digest: String) { - self.source = source - self.admission = admission - self.digest = digest - } - - func build(_ evaluation: Evaluation) throws -> BuiltMap { - try append(evaluation.root, pointer: "", origins: [], use: nil) - // Constants are separately addressable; declaration locations remain language independent. - for (name, value) in evaluation.constants where name != "agents" { - let pointer = "/constants/" + pointerEscape(name) - result.locations[pointer] = NodeID(digest: digest, pointer: pointer, syntax: value.syntax) - result.values[pointer] = value - } - result.entries.sort { ($0.pointer, $0.span.start) < ($1.pointer, $1.span.start) } - return result - } - - private func append( - _ value: EvaluatedValue, pointer: String, origins: [SourceSpan], use: SourceSpan?, - ownOrigins: [SourceSpan] = [] - ) throws { - let range = admission.nodes[value.syntax].range - let span = use ?? source.span(range) - var inherited = origins - let definition = source.span(range) - if use != nil, definition != span, inherited.last != definition { inherited.append(definition) } - var resolved = value - while let next = resolved.referent { - inherited.append(source.span(admission.nodes[next.syntax].range)) - resolved = next - } - if value.referent != nil { - guard resolved.cost.nodes <= budget.remainingLocations, - value.cost.origins <= budget.remainingOrigins - else { - throw source.failure("manifest.limit", "reference source map expansion", range.lowerBound) - } - } - let recordedOrigins = inherited + ownOrigins - guard budget.consume(pointer: pointer, span: span, origins: recordedOrigins) else { - throw source.failure( - "manifest.limit", "source map locations, origins or encoded bytes", range.lowerBound) - } - result.entries.append( - SourceMapEntry( - pointer: pointer, span: span, origins: recordedOrigins, defaulted: value.defaulted)) - result.locations[pointer] = NodeID(digest: digest, pointer: pointer, syntax: value.syntax) - result.values[pointer] = value - let useSpan = value.referent != nil || use != nil ? span : nil - if case .node(let type, let member, let fields) = resolved.value { - if Vocabulary.taggedRecordTypes.contains(type), - case .record(let record) = Lowering.lower(resolved.value) - { - let discriminator = EvaluatedValue( - type: .untyped, value: .text(record.kind), cost: ValueCost.scalar(record.kind), - syntax: resolved.syntax, representation: .synthetic) - try append(discriminator, pointer: pointer + "/kind", origins: inherited, use: useSpan) - } - if type == "SkillSelection" { - for (offset, child) in resolved.elementsForUse.enumerated() { - try append(child, pointer: pointer + "/\(offset)", origins: inherited, use: useSpan) - } - return - } - if type == "ConfigurationValue", - resolved.representation == .scalarLiteral || resolved.representation == .collectionLiteral, - let payload = fields["value"] - { - guard - let childType = Vocabulary.literalConstructions[type]?.values.first(where: { - $0.member == member - })?.payloadType - else { - throw source.failure( - "manifest.type", "literal payload has no registered type", range.lowerBound) - } - let child = EvaluatedValue( - type: childType, value: payload, cost: resolved.cost, syntax: resolved.syntax, - fields: resolved.fields, elements: resolved.elements) - try append(child, pointer: pointer + "/value", origins: inherited, use: useSpan) - return - } - for (key, childValue) in fields { - if type == "Source", key == "requirement" { - let trace = SourceRequirements.parameters.compactMap { - resolved.fields[$0.name] - }.first - if let trace, childValue != .none { - let shape = requirementShape(childValue, trace: trace) - var definitions: [SourceSpan] = [] - var referent = trace.referent - while let definition = referent { - definitions.append(source.span(admission.nodes[definition.syntax].range)) - referent = definition.referent - } - try append( - shape, pointer: pointer + "/requirement", origins: inherited, use: useSpan, - ownOrigins: definitions) - } else { - let absent = EvaluatedValue( - type: .untyped, value: .none, cost: ValueCost(), syntax: resolved.syntax, - defaulted: true, representation: .synthetic) - try append(absent, pointer: pointer + "/requirement", origins: inherited, use: useSpan) - } - continue - } - let child: EvaluatedValue - if let field = resolved.fields[key] { - child = field - } else { - child = EvaluatedValue( - type: .untyped, value: childValue, cost: ValueCost(), syntax: resolved.syntax, - defaulted: (key == "source" || key == "condition") && childValue == .none - || resolved.defaulted, representation: .synthetic) - } - try append( - child, pointer: pointer + "/" + pointerEscape(key), origins: inherited, use: useSpan) - } - } else if !resolved.fields.isEmpty { - for (key, child) in resolved.fields { - try append( - child, pointer: pointer + "/" + pointerEscape(key), origins: inherited, use: useSpan) - } - } else if !resolved.elements.isEmpty { - for (offset, child) in resolved.elements.enumerated() { - try append(child, pointer: pointer + "/\(offset)", origins: inherited, use: useSpan) - } - } else { - try synthetic( - resolved.value, syntax: resolved.syntax, pointer: pointer, span: span, origins: inherited, - defaulted: value.defaulted) - } - } - - private func requirementShape(_ value: ConstructionValue, trace: EvaluatedValue) -> EvaluatedValue - { - let requirement = Lowering.lower(value) - var fields: [String: ConstructionValue] = [:] - var traces: [String: EvaluatedValue] = [:] - if case .requirement(let requirement) = requirement { - let lower = trace.field("from") ?? trace.elementsForUse.first ?? trace - switch requirement { - case .branch(let text): - fields["branch"] = .text(text) - traces["branch"] = trace - case .revision(let text): - fields["revision"] = .text(text) - traces["revision"] = trace - case .exact(let text): - fields["exact"] = .text(text) - traces["exact"] = trace - case .upToNextMajor(let text): - fields["from"] = .text(text) - traces["from"] = lower - case .upToNextMinor(let text): - fields["upToNextMinor"] = .text(text) - traces["upToNextMinor"] = lower - case .range(let from, let to): - fields["from"] = .text(from) - fields["to"] = .text(to) - traces["from"] = lower - traces["to"] = trace.elementsForUse.last ?? trace - } - } - return EvaluatedValue( - type: .named("Requirement"), value: .object(fields), cost: trace.cost, syntax: trace.syntax, - fields: traces, representation: .synthetic) - } - - private func synthetic( - _ value: ConstructionValue, syntax: Int, pointer: String, span: SourceSpan, - origins: [SourceSpan], defaulted: Bool - ) throws { - let fields: [(String, ConstructionValue)] - switch value { - case .node(_, _, let values), .object(let values): fields = Array(values) - case .array(let values): fields = values.enumerated().map { (String($0.offset), $0.element) } - default: return - } - for (key, child) in fields { - let v = EvaluatedValue( - type: .untyped, value: child, cost: ValueCost(), syntax: syntax, defaulted: defaulted, - representation: .synthetic) - try append(v, pointer: pointer + "/" + pointerEscape(key), origins: origins, use: span) - } - } -} diff --git a/Sources/AgentsManifest/PieceTable.swift b/Sources/AgentsManifest/PieceTable.swift deleted file mode 100644 index 612eb9e..0000000 --- a/Sources/AgentsManifest/PieceTable.swift +++ /dev/null @@ -1,78 +0,0 @@ -struct PieceTable { - private enum Piece { - case original(Range) - case inserted([UInt8]) - var count: Int { - switch self { - case .original(let range): range.count - case .inserted(let bytes): bytes.count - } - } - func slice(_ range: Range) -> Piece { - switch self { - case .original(let original): - return .original( - (original.lowerBound + range.lowerBound)..<(original.lowerBound + range.upperBound)) - case .inserted(let bytes): return .inserted(Array(bytes[range])) - } - } - } - private let original: [UInt8] - private var pieces: [Piece] - init(_ bytes: [UInt8]) { - original = bytes - pieces = [.original(0.., with replacement: [UInt8]) { - var result: [Piece] = [] - var offset = 0 - var inserted = false - for piece in pieces { - let end = offset + piece.count - if offset < range.lowerBound { - let kept = min(end, range.lowerBound) - offset - if kept > 0 { result.append(piece.slice(0..= range.lowerBound { - if !replacement.isEmpty { result.append(.inserted(replacement)) } - inserted = true - } - if end > range.upperBound { - let first = max(offset, range.upperBound) - offset - if first < piece.count { result.append(piece.slice(first.. [SourcePatch] { - var result: [SourcePatch] = [] - var consumed = 0 - var replacement: [UInt8] = [] - for piece in pieces { - switch piece { - case .inserted(let bytes): replacement.append(contentsOf: bytes) - case .original(let range): - if range.lowerBound > consumed || !replacement.isEmpty { - result.append(SourcePatch(range: consumed..() - return signatures.flatMap { - $0.parameters.dropFirst(2) - }.filter { $0.defaultValue == nil && names.insert($0.name).inserted } - }() - - static let labels = Set(parameters.map(\.label).filter { $0 != "_" }) -} diff --git a/Sources/AgentsManifest/SourceText.swift b/Sources/AgentsManifest/SourceText.swift index 4fac150..c1d085e 100644 --- a/Sources/AgentsManifest/SourceText.swift +++ b/Sources/AgentsManifest/SourceText.swift @@ -46,3 +46,5 @@ struct SourceText: Sendable { String(decoding: bytes[range], as: UTF8.self) } } + +func utf8Less(_ lhs: String, _ rhs: String) -> Bool { lhs.utf8.lexicographicallyPrecedes(rhs.utf8) } diff --git a/Sources/AgentsManifest/StaticValueVocabulary.swift b/Sources/AgentsManifest/StaticValueVocabulary.swift deleted file mode 100644 index 9f21406..0000000 --- a/Sources/AgentsManifest/StaticValueVocabulary.swift +++ /dev/null @@ -1,93 +0,0 @@ -// Generated from Scripts/ManifestVocabulary.json. Run Scripts/generate-manifest-vocabulary.py. - -import AgentsDescription - -extension StaticValue { - public static func configuration(_ value: AgentsDescription.ConfigurationValue) -> Self { - Self.checked(value.constructionValue, type: .named("ConfigurationValue")) - } - public static func component(_ value: AgentsDescription.Component) -> Self { - Self.checked(value.constructionValue, type: .named("Component")) - } - public static func source(_ value: AgentsDescription.Source) -> Self { - Self.checked(value.constructionValue, type: .named("Source")) - } - public static func section(_ value: AgentsDescription.SectionReference) -> Self { - Self.checked(value.constructionValue, type: .named("SectionReference")) - } - public static func groupReference(_ value: AgentsDescription.GroupReference) -> Self { - Self.checked(value.constructionValue, type: .named("GroupReference")) - } - public static func version(_ value: AgentsDescription.Version) -> Self { - Self.checked(value.constructionValue, type: .named("Version")) - } - public static func runtime(_ value: AgentsDescription.RuntimeValue) -> Self { - Self.checked(value.constructionValue, type: .named("RuntimeValue")) - } - public static func condition(_ value: AgentsDescription.Condition) -> Self { - Self.checked(value.constructionValue, type: .named("Condition")) - } - public static func selection(_ value: AgentsDescription.SkillSelection) -> Self { - Self.checked(value.constructionValue, type: .named("SkillSelection")) - } - public static func skillOverride(_ value: AgentsDescription.SkillOverride) -> Self { - Self.checked(value.constructionValue, type: .named("SkillOverride")) - } - public static func prompt(_ value: AgentsDescription.ChatGPTPrompt) -> Self { - Self.checked(value.constructionValue, type: .named("ChatGPTPrompt")) - } - public static func resource(_ value: AgentsDescription.Resource) -> Self { - Self.checked(value.constructionValue, type: .named("Resource")) - } - public static func promptContent(_ value: AgentsDescription.PromptContent) -> Self { - Self.checked(value.constructionValue, type: .named("PromptContent")) - } - public static func executable(_ value: AgentsDescription.ExecutableInvocation) -> Self { - Self.checked(value.constructionValue, type: .named("ExecutableInvocation")) - } - public static func transport(_ value: AgentsDescription.MCPTransport) -> Self { - Self.checked(value.constructionValue, type: .named("MCPTransport")) - } - public static func parameter(_ value: AgentsDescription.PromptParameter) -> Self { - Self.checked(value.constructionValue, type: .named("PromptParameter")) - } - public static func permissionRule(_ value: AgentsDescription.PermissionRule) -> Self { - Self.checked(value.constructionValue, type: .named("PermissionRule")) - } - public static func agent(_ value: AgentsDescription.Agent) -> Self { - Self.checked(value.constructionValue, type: .named("Agent")) - } - public static func scope(_ value: AgentsDescription.Scope) -> Self { - Self.checked(value.constructionValue, type: .named("Scope")) - } - public static func platform(_ value: AgentsDescription.Platform) -> Self { - Self.checked(value.constructionValue, type: .named("Platform")) - } - public static func installMode(_ value: AgentsDescription.InstallMode) -> Self { - Self.checked(value.constructionValue, type: .named("InstallMode")) - } - public static func hookEvent(_ value: AgentsDescription.HookEvent) -> Self { - Self.checked(value.constructionValue, type: .named("HookEvent")) - } - public static func permissionOperation(_ value: AgentsDescription.PermissionOperation) -> Self { - Self.checked(value.constructionValue, type: .named("PermissionOperation")) - } - public static func ignorePurpose(_ value: AgentsDescription.IgnorePurpose) -> Self { - Self.checked(value.constructionValue, type: .named("IgnorePurpose")) - } - public static func pluginMode(_ value: AgentsDescription.PluginMode) -> Self { - Self.checked(value.constructionValue, type: .named("PluginMode")) - } - public static func componentKind(_ value: AgentsDescription.ComponentKind) -> Self { - Self.checked(value.constructionValue, type: .named("ComponentKind")) - } - public static func componentReference(_ value: AgentsDescription.ComponentReference) -> Self { - Self.checked(value.constructionValue, type: .named("ComponentReference")) - } - public static func group(_ value: AgentsDescription.ComponentGroup) -> Self { - Self.checked(value.constructionValue, type: .named("ComponentGroup")) - } - public static func agents(_ value: AgentsDescription.Agents) -> Self { - Self.checked(value.constructionValue, type: .named("Agents")) - } -} diff --git a/Sources/AgentsManifest/SyntaxValidation.swift b/Sources/AgentsManifest/SyntaxValidation.swift deleted file mode 100644 index 912d1e0..0000000 --- a/Sources/AgentsManifest/SyntaxValidation.swift +++ /dev/null @@ -1,154 +0,0 @@ -import AgentsCore -import Foundation -import SwiftParser -import SwiftSyntax - -struct CheckedSyntax: Sendable { - let tree: SourceFileSyntax - let metrics: FrontEndMetrics -} - -enum SyntaxValidation { - /// All-nodes view, with cached lengths only until the complete tree fits. - static func guardTree(_ root: Syntax, source: SourceText) throws -> ( - nodes: Int, depth: Int - ) { - var pending: [(Syntax, Int, Int)] = [(root, 1, 0)] - var scheduled = 1 - var count = 0 - var maximum = 0 - while let (node, depth, offset) = pending.popLast() { - if depth > ManifestLimits.Syntax.depth { - throw source.failure("manifest.limit", "syntax tree depth", offset) - } - count += 1 - maximum = max(maximum, depth) - var childOffset = offset - for child in node.children(viewMode: .all) { - if scheduled == ManifestLimits.Syntax.nodes { - throw source.failure("manifest.limit", "syntax tree nodes", childOffset) - } - if depth == ManifestLimits.Syntax.depth { - throw source.failure("manifest.limit", "syntax tree depth", childOffset) - } - scheduled += 1 - pending.append((child, depth + 1, childOffset)) - childOffset += child.totalLength.utf8Length - } - } - return (count, maximum) - } - - static func parse( - _ source: SourceText, admission: Admission, metrics initial: FrontEndMetrics - ) throws -> CheckedSyntax { - var metrics = initial - let clock = ContinuousClock() - let parseStart = clock.now - let tree = source.bytes.withUnsafeBufferPointer { - Parser.parse(source: $0, maximumNestingLevel: ManifestLimits.Syntax.parserNesting) - } - metrics.parserCalls += 1 - metrics.parsingSeconds = seconds(parseStart.duration(to: clock.now)) - let guardStart = clock.now - do { - let bounds = try guardTree(Syntax(tree), source: source) - metrics.syntaxNodes = bounds.nodes - metrics.syntaxDepth = bounds.depth - } catch let failure as ManifestFailure { - metrics.guardSeconds = seconds(guardStart.duration(to: clock.now)) - throw ManifestFailure(failure.diagnostics[0], metrics: metrics) - } - metrics.guardSeconds = seconds(guardStart.duration(to: clock.now)) - let inspectionStart = clock.now - if tree.hasError { - metrics.inspectionSeconds = seconds(inspectionStart.duration(to: clock.now)) - throw ManifestFailure( - ManifestDiagnostic( - code: "manifest.syntax", message: "SwiftParser disagreed with grammar admission", - span: source.span(0..<0)), metrics: metrics) - } - // This independent projection is also a dependency-upgrade regression gate. - let actual = projection(Syntax(tree), source: source) - metrics.inspectionSeconds = seconds(inspectionStart.duration(to: clock.now)) - guard actual == admission.projection, metrics.syntaxNodes <= admission.reservation else { - let offset = zip(actual, admission.projection).first(where: { $0 != $1 })?.0.start ?? 0 - throw ManifestFailure( - ManifestDiagnostic( - code: "manifest.syntax", - message: "SwiftParser projection or syntax reservation disagreed with admission", - span: source.span(offset.. [ProjectionEvent] { - var pending = [root] - var events: [ProjectionEvent] = [] - func emit(_ node: Syntax, _ kind: ProjectionKind, _ detail: String = "") { - events.append( - ProjectionEvent( - start: node.positionAfterSkippingLeadingTrivia.utf8Offset, - end: node.endPositionBeforeTrailingTrivia.utf8Offset, kind: kind, detail: detail)) - } - func literal(_ node: Syntax, _ kind: ProjectionKind) { - emit( - node, kind, - source.spelling( - node.positionAfterSkippingLeadingTrivia - .utf8Offset.. Double { - Double(duration.components.seconds) + Double(duration.components.attoseconds) / 1e18 -} diff --git a/Sources/AgentsManifest/ValueBudget.swift b/Sources/AgentsManifest/ValueBudget.swift index 121da09..2ab01e4 100644 --- a/Sources/AgentsManifest/ValueBudget.swift +++ b/Sources/AgentsManifest/ValueBudget.swift @@ -1,5 +1,4 @@ import AgentsCore -import AgentsDescription struct ValueCost: Sendable { var nodes = 1 @@ -75,18 +74,35 @@ struct SourceMapBudget { } } -func constructionCost(_ value: ConstructionValue) -> ValueCost { - switch value { - case .text(let text): return .scalar(text) - case .version(let version): return .scalar(version.normalized) - case .range(let range): - return .container([.scalar(range.lowerBound.normalized), .scalar(range.upperBound.normalized)]) - case .array(let values): return .container(values.map(constructionCost)) - case .object(let fields): - return .container(fields.values.map(constructionCost), keys: Array(fields.keys)) - case .node(let type, let member, let fields): - return .container( - fields.values.map(constructionCost), keys: [type, member] + Array(fields.keys)) - case .none, .integer, .boolean: return ValueCost() +func validateIRBudget(_ value: DeclarationValue, source: SourceText) throws { + var work = 0 + func cost(_ value: DeclarationValue, depth: Int) throws -> ValueCost { + work += 1 + guard depth <= ManifestLimits.Values.depth, work <= ManifestLimits.Values.nodes else { + throw source.failure("manifest.limit", "domain value depth/node limit", 0) + } + let result: ValueCost + switch value { + case .string(let value): result = .scalar(value) + case .array(let values): + guard values.count <= ManifestLimits.Values.entries else { + throw source.failure("manifest.limit", "container entry limit", 0) + } + result = try .container(values.map { try cost($0, depth: depth + 1) }) + case .dictionary(let fields): + guard fields.count <= ManifestLimits.Values.entries else { + throw source.failure("manifest.limit", "container entry limit", 0) + } + result = try .container( + fields.values.map { try cost($0, depth: depth + 1) }, keys: Array(fields.keys)) + case .record(let record): + result = try cost(.dictionary(record.fields), depth: depth) + case .requirement(let value): + result = .container([.scalar(value.value)] + (value.upperBound.map { [.scalar($0)] } ?? [])) + default: result = ValueCost() + } + guard result.fits else { throw source.failure("manifest.limit", "domain value budget", 0) } + return result } + _ = try cost(value, depth: 1) } diff --git a/Sources/AgentsManifest/YAMLConstruction.swift b/Sources/AgentsManifest/YAMLConstruction.swift new file mode 100644 index 0000000..dd8b0bb --- /dev/null +++ b/Sources/AgentsManifest/YAMLConstruction.swift @@ -0,0 +1,353 @@ +import AgentsCore + +/// Complete domain-to-IR construction. Optional recipients and condition dimensions retain +/// their presence; only dictionary-backed convenience inputs use canonical key ordering. +enum YAMLConstruction { + static func root(_ value: Declaration) -> DeclarationIR { + DeclarationIR( + defaultAgents: value.agents.map { $0.map(\.rawValue) }, exports: value.exports, + sources: value.sourceDeclarations.map(source), components: value.components.map(component), + groups: value.groups.map(group), uses: value.uses.map(use), watch: value.watch ?? []) + } + static func record(_ kind: String, _ fields: [String: DeclarationValue]) -> DeclarationRecord { + DeclarationRecord(kind: kind, fields: fields) + } + static func text(_ value: String?) -> DeclarationValue { + value.map(DeclarationValue.string) ?? .null + } + static func strings(_ values: [String]) -> DeclarationValue { + .array(values.map(DeclarationValue.string)) + } + static func agents(_ values: [AgentID]?) -> DeclarationValue { + values.map { strings($0.map(\.rawValue)) } ?? .null + } + static func condition(_ value: DeclarationCondition?) -> DeclarationValue { + value.map { + .record( + record( + "when", + [ + "agents": agents($0.agents), + "scopes": $0.scopes.map { strings($0.map(\.rawValue)) } ?? .null, + "platforms": $0.platforms.map { strings($0.map(\.rawValue)) } ?? .null, + ])) + } ?? .null + } + static func source(_ value: NamedSourceDeclaration) -> DeclarationRecord { + let source = value.source + return record( + source.kind == .git ? "git" : source.kind == .local ? "local" : "index", + [ + "name": .string(value.name), + source.kind == .git ? "url" : source.kind == .local ? "path" : "index": .string( + source.kind == .git ? source.gitURL : source.location), + "subpath": text(source.path), + "requirement": source.requirement.map(DeclarationValue.requirement) ?? .null, + ]) + } + static func use(_ value: GroupUseDeclaration) -> DeclarationRecord { + record( + value.source == nil ? "local" : "exported", + [ + "name": .string(value.name), "source": text(value.source), + "condition": condition(value.condition), + ]) + } + static func group(_ value: ComponentGroupDeclaration) -> DeclarationRecord { + record( + "group", + [ + "name": .string(value.name), + "components": .array(value.components.map { .record(component($0)) }), + "uses": .array(value.uses.map { .record(use($0)) }), + "condition": condition(value.condition), + ]) + } + static func section(_ value: SectionDeclaration) -> DeclarationRecord { + record( + "section", + [ + "name": .string(value.name), "source": text(value.source), + "condition": condition(value.condition), + ]) + } + static func promptDeclaration(_ value: NamedPromptDeclaration) -> DeclarationRecord { + record( + "prompt", + [ + "name": .string(value.name), + "sections": .array(value.prompt.sectionReferences.map { .record(section($0)) }), + "append": text(value.prompt.append), "condition": condition(value.prompt.condition), + ]) + } + static func override(_ value: NamedSkillOverrideDeclaration) -> DeclarationRecord { + record( + "skill", + [ + "name": .string(value.name), "agents": agents(value.override.agents), + "mode": text(value.override.mode?.rawValue), + ]) + } + static func nativeValue(_ value: NativeValue) -> DeclarationValue { + let kind: String + let payload: DeclarationValue? + switch value { + case .string(let value): + kind = "string" + payload = .string(value) + case .integer(let value): + kind = "integer" + payload = .integer(value) + case .decimal(let value): + kind = "decimal" + payload = .string(value) + case .boolean(let value): + kind = "boolean" + payload = .boolean(value) + case .null: + kind = "null" + payload = nil + case .array(let value): + kind = "array" + payload = .array(value.map(nativeValue)) + case .object(let value): + kind = "object" + payload = .dictionary(value.mapValues(nativeValue)) + } + return .record(record(kind, payload.map { ["value": $0] } ?? [:])) + } + static func native(_ value: NativeConfiguration) -> DeclarationValue { + .dictionary(value.mapValues { .dictionary($0.mapValues(nativeValue)) }) + } + static func binding(_ value: RuntimeBinding) -> DeclarationValue { + let kind: String + let text: String + switch value { + case .literal(let value): + kind = "literal" + text = value + case .environment(let value): + kind = "environment" + text = value + case .secret(let value): + kind = "secret" + text = value + } + return .record(record(kind, ["value": .string(text)])) + } + static func resource(_ value: ResourceDeclaration) -> DeclarationRecord { + record("path", ["path": .string(value.path), "source": text(value.source)]) + } + static func prompt(_ value: PromptBody) -> DeclarationValue { + switch value { + case .literal(let value): return .record(record("literal", ["value": .string(value)])) + case .file(let value): return .record(record("file", resource(value).fields)) + } + } + static func run(_ value: ExecutableDeclaration, kind: String = "executable") -> DeclarationRecord + { + record( + kind, + [ + "executable": .string(value.executable), "arguments": strings(value.arguments), + "environment": .dictionary(value.environment.mapValues(binding)), + "workingDirectory": value.workingDirectory.map { .record(resource($0)) } ?? .null, + ]) + } + static func transport(_ value: MCPTransportDeclaration) -> DeclarationValue { + switch value { + case .stdio(let value): return .record(run(value, kind: "stdio")) + case .streamableHTTP(let url, let headers): + return .record( + record( + "streamableHTTP", + ["url": .string(url), "headers": .dictionary(headers.mapValues(binding))])) + case .sse(let url, let headers): + return .record( + record("sse", ["url": .string(url), "headers": .dictionary(headers.mapValues(binding))])) + } + } + static func event(_ value: HookEventDeclaration) -> DeclarationValue { + let kind: String + switch value { + case .beforeTool: kind = "beforeTool" + case .afterTool: kind = "afterTool" + case .sessionStart: kind = "sessionStart" + case .sessionEnd: kind = "sessionEnd" + case .native(let value): return .record(record("native", ["value": .string(value)])) + } + return .record(record(kind, [:])) + } + static func operation(_ value: PermissionOperationDeclaration) -> DeclarationValue { + let kind: String + switch value { + case .read: kind = "read" + case .write: kind = "write" + case .execute: kind = "execute" + case .tool(let value): return .record(record("tool", ["value": .string(value)])) + } + return .record(record(kind, [:])) + } + static func rule(_ value: PermissionRuleDeclaration) -> DeclarationValue { + switch value { + case .allow(let op, let pattern): + return .record(record("allow", ["operation": operation(op), "pattern": .string(pattern)])) + case .ask(let op, let pattern): + return .record(record("ask", ["operation": operation(op), "pattern": .string(pattern)])) + case .deny(let op, let pattern): + return .record(record("deny", ["operation": operation(op), "pattern": .string(pattern)])) + } + } + static func reference(_ value: ComponentReferenceDeclaration) -> DeclarationValue { + let kind: String + let name: String + switch value { + case .skill(let value): + kind = "skill" + name = value + case .instruction(let value): + kind = "instruction" + name = value + case .mcpServer(let value): + kind = "mcpServer" + name = value + case .hook(let value): + kind = "hook" + name = value + case .subagent(let value): + kind = "subagent" + name = value + case .command(let value): + kind = "command" + name = value + case .lspServer(let value): + kind = "lspServer" + name = value + case .permissions(let value): + kind = "permissions" + name = value + case .ignore(let value): + kind = "ignore" + name = value + case .plugin(let value): + kind = "plugin" + name = value + } + return .record(record(kind, ["name": .string(name)])) + } + static func component(_ value: ComponentDeclaration) -> DeclarationRecord { + let kind: String + var fields: [String: DeclarationValue] + let recipients: [AgentID]? + let when: DeclarationCondition? + let config: NativeConfiguration + switch value { + case .skills(let source, let value): + kind = "skills" + recipients = value.agents + when = value.condition + config = value.native + let selection: DeclarationValue + switch value.select { + case .all: selection = .string("all") + case .names(let values): selection = strings(values) + } + fields = [ + "source": .string(source), "select": selection, "exclude": strings(value.exclude ?? []), + "mode": text(value.mode?.rawValue), + "overrides": .array(value.overrideDeclarations.map { .record(override($0)) }), + ] + case .instructions(let value): + kind = "instructions" + recipients = value.agents + when = value.condition + config = value.native + fields = [ + "sections": .array(value.sectionReferences.map { .record(section($0)) }), + "chatGPT": .array(value.prompts.map { .record(promptDeclaration($0)) }), + ] + case .mcpServer(let name, let value, let a, let c, let n): + kind = "mcpServer" + recipients = a + when = c + config = n + fields = ["name": .string(name), "transport": transport(value)] + case .hook(let name, let e, let r, let matcher, let timeout, let a, let c, let n): + kind = "hook" + recipients = a + when = c + config = n + fields = [ + "name": .string(name), "event": event(e), "run": .record(run(r)), "matcher": text(matcher), + "timeoutSeconds": timeout.map(DeclarationValue.integer) ?? .null, + ] + case .subagent(let name, let description, let p, let model, let tools, let a, let c, let n): + kind = "subagent" + recipients = a + when = c + config = n + fields = [ + "name": .string(name), "description": .string(description), "prompt": prompt(p), + "model": text(model), "tools": tools.map(strings) ?? .null, + ] + case .command(let name, let description, let p, let parameters, let a, let c, let n): + kind = "command" + recipients = a + when = c + config = n + fields = [ + "name": .string(name), "description": .string(description), "prompt": prompt(p), + "parameters": .array( + parameters.map { + .record( + record( + "parameter", + [ + "name": .string($0.name), "description": .string($0.description), + "defaultValue": text($0.defaultValue), + ])) + }), + ] + case .lspServer(let name, let r, let languages, let options, let a, let c, let n): + kind = "lspServer" + recipients = a + when = c + config = n + fields = [ + "name": .string(name), "run": .record(run(r)), + "languages": .dictionary(languages.mapValues(DeclarationValue.string)), + "initializationOptions": .dictionary(options.mapValues(nativeValue)), + ] + case .permissions(let name, let rules, let a, let c, let n): + kind = "permissions" + recipients = a + when = c + config = n + fields = ["name": .string(name), "rules": .array(rules.map(rule))] + case .ignore(let name, let patterns, let purpose, let a, let c, let n): + kind = "ignore" + recipients = a + when = c + config = n + fields = [ + "name": .string(name), "patterns": strings(patterns), "purpose": .string(purpose.rawValue), + ] + case .plugin( + let name, let path, let source, let mode, let select, let exclude, let a, let c, let n): + kind = "plugin" + recipients = a + when = c + config = n + fields = [ + "name": .string(name), "path": .string(path), "source": .string(source), + "mode": .string(mode.rawValue), + "select": select.map { strings($0.map(\.rawValue)) } ?? .null, + "exclude": .array(exclude.map(reference)), + ] + } + fields["agents"] = agents(recipients) + fields["condition"] = condition(when) + fields["native"] = native(config) + return record(kind, fields) + } +} diff --git a/Sources/AgentsManifest/YAMLDomainValidation.swift b/Sources/AgentsManifest/YAMLDomainValidation.swift new file mode 100644 index 0000000..7f57756 --- /dev/null +++ b/Sources/AgentsManifest/YAMLDomainValidation.swift @@ -0,0 +1,303 @@ +import AgentsCore +import Foundation + +struct YAMLDomainValidation { + let declaration: DeclarationIR + let source: SourceText + let locations: [String: YAMLNode] + private let sources: [String: DeclarationRecord] + private let groups: [String: DeclarationRecord] + + init(declaration: DeclarationIR, source: SourceText, locations: [String: YAMLNode]) { + self.declaration = declaration + self.source = source + self.locations = locations + sources = Dictionary( + uniqueKeysWithValues: declaration.sources.map { ($0["name"]!.string!, $0) }) + groups = Dictionary(uniqueKeysWithValues: declaration.groups.map { ($0["name"]!.string!, $0) }) + } + + func validate() throws -> [ManifestDiagnostic] { + var diagnostics: [ManifestDiagnostic] = [] + var identities = Set() + for (index, record) in declaration.sources.enumerated() { + let path = "/sources/\(index)" + let alias = record["name"]!.string! + guard !alias.isEmpty, alias != ".", !alias.contains(":") else { + throw fail(path, "invalid source alias") + } + let location = record[ + record.kind == "git" ? "url" : record.kind == "local" ? "path" : "index"]!.string! + let identity: String + if record.kind == "local" { + guard !location.isEmpty, !location.contains("\0") else { + throw fail(path, "invalid local source") + } + identity = + URL(fileURLWithPath: location, relativeTo: URL(fileURLWithPath: "/")).standardizedFileURL + .path + } else { + do { + identity = try SourceDeclaration( + kind: record.kind == "git" ? .git : .wellKnown, location: location + ).transportIdentity() + } catch { throw fail(path, "invalid source URL") } + } + if record.kind == "git", let node = locations[path + "/url"], let raw = node.text { + let canonical = SourceDeclaration(kind: .git, location: raw).gitURL + if raw != canonical, diagnostics.count < ManifestLimits.Diagnostics.warnings { + diagnostics.append( + ManifestDiagnostic( + code: "manifest.domain", severity: .warning, + message: "use the complete Git transport URL", span: source.span(node.range), + fixIt: SourcePatch( + range: node.range, replacement: Array(YAMLWriter.quote(canonical).utf8)))) + } else if raw != canonical, diagnostics.count == ManifestLimits.Diagnostics.warnings { + diagnostics.append( + ManifestDiagnostic( + code: "manifest.diagnostics.truncated", severity: .warning, + message: "further diagnostics omitted", span: source.span(node.range))) + } + } + guard identities.insert(identity).inserted else { + throw fail(path, "two aliases normalize to the same source identity") + } + if case .requirement(let requirement) = record["requirement"] { + do { try requirement.validate() } catch { + throw fail(path + "/requirement", "invalid source requirement") + } + } + if let subpath = record["subpath"]?.string { try resource(subpath, path) } + } + try unique(declaration.defaultAgents ?? [], "/defaultAgents") + try unique(declaration.exports, "/exports") + try unique(declaration.watch, "/watch") + for name in declaration.exports where groups[name] == nil { + throw fail("/exports", "unknown exported group: \(name)", code: "manifest.group.missing") + } + for name in declaration.watch { try alias(name, "/watch") } + for (index, record) in declaration.components.enumerated() { + try component(record, "/components/\(index)") + } + for (index, record) in declaration.groups.enumerated() { + let path = "/groups/\(index)" + try name(record["name"]!.string!, path) + try condition(record["condition"], path + "/condition") + for (i, value) in (record["components"]?.elements ?? []).enumerated() { + try component(value.record!, path + "/components/\(i)") + } + for (i, value) in (record["uses"]?.elements ?? []).enumerated() { + try use(value.record!, path + "/uses/\(i)") + } + } + for (index, record) in declaration.uses.enumerated() { try use(record, "/uses/\(index)") } + var completed = Set() + func cycle(_ name: String, stack: [String]) throws { + guard stack.count < ManifestLimits.Groups.activeReferences else { + throw fail("/groups", "group reference depth limit", code: "manifest.limit") + } + if stack.contains(name) { + throw fail("/groups", "group reference cycle", code: "manifest.group.cycle") + } + if completed.contains(name) { return } + for value in groups[name]?["uses"]?.elements ?? [] { + let record = value.record! + if record["source"]?.string == nil { + try cycle(record["name"]!.string!, stack: stack + [name]) + } + } + completed.insert(name) + } + for group in declaration.groups { try cycle(group["name"]!.string!, stack: []) } + return diagnostics + } + + private func fail(_ pointer: String, _ message: String, code: String = "manifest.domain") + -> ManifestFailure + { + source.failure(code, message, locations[pointer]?.range.lowerBound ?? 0) + } + private func strings(_ value: DeclarationValue?) -> [String] { + (value?.elements ?? []).map { $0.string! } + } + private func unique(_ values: [String], _ pointer: String) throws { + guard Set(values).count == values.count else { throw fail(pointer, "duplicate value") } + } + private func name(_ text: String, _ pointer: String) throws { + let parts = text.split(separator: "/", omittingEmptySubsequences: false) + guard !parts.isEmpty, !parts.contains(where: { $0.isEmpty || $0 == "." || $0 == ".." }), + !text.contains(":"), !text.contains("\\"), + !text.unicodeScalars.contains(where: { $0.value < 0x20 || $0.value == 0x7F }) + else { throw fail(pointer, "invalid relative name") } + } + private func resource(_ text: String, _ pointer: String) throws { + if text == "~" || text.hasPrefix("~/") { throw fail(pointer, "unsafe resource path") } + do { _ = try PathSafety.sanitizeSubpath(text) } catch { + throw fail(pointer, "unsafe resource path") + } + } + private func alias(_ text: String, _ pointer: String) throws { + guard text == "." || sources[text] != nil else { + throw fail(pointer, "unknown source alias: \(text)") + } + } + private func condition(_ value: DeclarationValue?, _ pointer: String) throws { + guard let record = value?.record else { return } + for field in ["agents", "scopes", "platforms"] { + try unique(strings(record[field]), pointer + "/" + field) + } + } + private func use(_ record: DeclarationRecord, _ pointer: String) throws { + let group = record["name"]!.string! + try name(group, pointer) + if let source = record["source"]?.string { + try alias(source, pointer) + } else if groups[group] == nil { + throw fail(pointer, "unknown local group: \(group)", code: "manifest.group.missing") + } + try condition(record["condition"], pointer + "/condition") + } + private func section(_ record: DeclarationRecord, _ pointer: String) throws { + guard Declaration.isInstructionName(record["name"]!.string!) else { + throw fail(pointer, "invalid section name") + } + if let source = record["source"]?.string { try alias(source, pointer) } + try condition(record["condition"], pointer + "/condition") + } + private func resource(_ record: DeclarationRecord, _ pointer: String) throws { + try resource(record["path"]!.string!, pointer) + if let source = record["source"]?.string { try alias(source, pointer) } + } + private func run(_ record: DeclarationRecord, _ pointer: String) throws { + let executable = record["executable"]!.string! + guard !executable.isEmpty, !executable.contains("\0") else { + throw fail(pointer, "invalid executable") + } + if executable.contains("/") || executable.hasPrefix("~") { try resource(executable, pointer) } + if let directory = record["workingDirectory"]?.record { try resource(directory, pointer) } + } + private func component(_ record: DeclarationRecord, _ pointer: String) throws { + try unique(strings(record["agents"]), pointer + "/agents") + try condition(record["condition"], pointer + "/condition") + if let n = record["name"]?.string { try name(n, pointer + "/name") } + switch record.kind { + case "skills": + let source = record["source"]!.string! + try alias(source, pointer) + let selected = record["select"]?.elements.map { $0.map { $0.string! } } + let excluded = strings(record["exclude"]) + do { + try Declaration.validateNames(selected ?? []) + try Declaration.validateNames(excluded) + } catch { throw fail(pointer, "invalid skill names") } + let overrides = (record["overrides"]?.elements ?? []).map { $0.record! } + let names = overrides.map { $0["name"]!.string! } + do { try Declaration.validateNames(names) } catch { + throw fail(pointer, "invalid skill overrides") + } + for override in overrides { + if let selected, !selected.contains(override["name"]!.string!) { + throw fail(pointer, "override is outside explicit skill selection") + } + try unique(strings(override["agents"]), pointer) + } + if ([record["mode"]?.string] + overrides.map { $0["mode"]?.string }).contains("edit"), + source != ".", + sources[source]?.kind != "local" || sources[source]?["requirement"] != .null + { + throw fail(pointer, "edit mode needs a local source without a requirement") + } + case "instructions": + for value in record["sections"]!.elements! { try section(value.record!, pointer) } + for value in record["chatGPT"]!.elements! { + let prompt = value.record! + for sectionValue in prompt["sections"]!.elements! { + try section(sectionValue.record!, pointer) + } + if let append = prompt["append"]?.string { try resource(append, pointer) } + try condition(prompt["condition"], pointer) + } + case "mcpServer": + let transport = record["transport"]!.record! + if transport.kind == "stdio" { + try run(transport, pointer) + } else { + let url = URLComponents(string: transport["url"]!.string!) + guard ["http", "https"].contains(url?.scheme?.lowercased() ?? ""), + url?.host?.isEmpty == false, url?.user == nil, url?.password == nil, url?.fragment == nil + else { throw fail(pointer, "invalid HTTP transport URL") } + } + case "hook": + try run(record["run"]!.record!, pointer) + if record["event"]!.record!.kind == "native", record["agents"]?.elements?.count != 1 { + throw fail(pointer, "native hook event requires exactly one explicit recipient") + } + case "subagent", "command": + let prompt = record["prompt"]!.record! + if prompt.kind == "file" { try resource(prompt, pointer) } + if record.kind == "command" { + let parameters = (record["parameters"]?.elements ?? []).map { $0.record! } + let names = parameters.map { $0["name"]!.string! } + try unique(names, pointer) + guard + names.allSatisfy({ + !$0.isEmpty && !$0.contains("}") && !$0.contains(":") && !$0.contains("\0") + }) + else { throw fail(pointer, "invalid prompt parameter name") } + if prompt.kind == "literal" { + let bytes = Array(prompt["value"]!.string!.utf8) + let escaped = Array("$${input:".utf8) + let token = Array("${input:".utf8) + var i = 0 + while i < bytes.count { + if bytes[i...].starts(with: escaped) { + i += escaped.count + while i < bytes.count && bytes[i] != 125 { i += 1 } + } else if bytes[i...].starts(with: token) { + let start = i + token.count + i = start + while i < bytes.count && bytes[i] != 125 { i += 1 } + guard i < bytes.count, + names.contains(String(decoding: bytes[start.. 1, !ext.contains("/"), !ext.contains("\0"), + value.string?.isEmpty == false + else { throw fail(pointer, "invalid language extension mapping") } + } + } + case "permissions": + for value in record["rules"]!.elements! { + let rule = value.record! + if ["read", "write"].contains(rule["operation"]!.record!.kind) { + try resource(rule["pattern"]!.string!, pointer) + } + } + case "plugin": + try alias(record["source"]!.string!, pointer) + try resource(record["path"]!.string!, pointer) + try unique(strings(record["select"]), pointer) + let excluded = record["exclude"]!.elements! + guard + Set(excluded.map { $0.record!.kind + ":" + $0.record!["name"]!.string! }).count + == excluded.count + else { throw fail(pointer, "duplicate plugin exclusion") } + for value in excluded { try name(value.record!["name"]!.string!, pointer) } + if record["mode"]?.string == "native", + record["agents"]?.elements?.count != 1 || record["select"] != .null || !excluded.isEmpty + { + throw fail( + pointer, "native plugin requires one explicit recipient and no selection/exclusions") + } + default: break + } + } +} diff --git a/Sources/AgentsManifest/YAMLParser.swift b/Sources/AgentsManifest/YAMLParser.swift new file mode 100644 index 0000000..6cc9757 --- /dev/null +++ b/Sources/AgentsManifest/YAMLParser.swift @@ -0,0 +1,322 @@ +import AgentsCore +import Foundation +import TreeSitter +import TreeSitterYAML +import Yams + +/// Ordered, decoded data with concrete UTF-8 ranges. Mapping order is retained independently +/// of the domain's dictionary semantics. The parser tree never escapes this module. +indirect enum YAMLData: Sendable, Equatable { + case scalar(String, quoted: Bool, decimalTag: Bool) + case sequence([YAMLNode]) + case mapping([(key: YAMLNode, value: YAMLNode)]) + + static func == (lhs: Self, rhs: Self) -> Bool { + switch (lhs, rhs) { + case (.scalar(let a, let q, let t), .scalar(let b, let r, let u)): + return a == b && q == r && t == u + case (.sequence(let a), .sequence(let b)): return a == b + case (.mapping(let a), .mapping(let b)): + return a.count == b.count && zip(a, b).allSatisfy { $0.key == $1.key && $0.value == $1.value } + default: return false + } + } +} + +struct YAMLNode: Sendable, Equatable { + let data: YAMLData + let range: Range + let entryRange: Range + let flow: Bool + + var text: String? { + if case .scalar(let text, _, _) = data { return text } + return nil + } + var pairs: [(key: YAMLNode, value: YAMLNode)]? { + if case .mapping(let pairs) = data { return pairs } + return nil + } + var items: [YAMLNode]? { + if case .sequence(let items) = data { return items } + return nil + } +} + +private struct YAMLParseInput { + let bytes: UnsafePointer + let count: Int + var callbacks = 0 + var offset = 0 + var failed = false + var cancelled = false +} + +struct YAMLParseResult { + let root: YAMLNode + let callbacks: Int + let nodes: Int + let depth: Int + let comments: [Range] + let metrics: FrontEndMetrics +} + +enum YAMLParser { + // The pinned runtime reports periodic parse progress, including weighted tree compression. + // Scalar scanning remains input-byte bounded. This measured work policy is not an allocation bound. + static let callbackLimit = 16_000 + + static func parse( + _ source: SourceText, observe: ((FrontEndStage, FrontEndMetrics) -> Void)? = nil + ) throws -> YAMLParseResult { + try Task.checkCancellation() + let clock = ContinuousClock() + var start = clock.now + var metrics = FrontEndMetrics() + var stage = FrontEndStage.admission + observe?(stage, metrics) + do { + guard source.bytes.count <= ManifestLimits.Input.bytes else { + throw source.failure("manifest.limit", "input byte limit", ManifestLimits.Input.bytes) + } + guard let text = String(bytes: source.bytes, encoding: .utf8) else { + throw source.failure("manifest.encoding", "expected UTF-8", 0) + } + var offset = 0 + for scalar in text.unicodeScalars { + let value = scalar.value + if value == 0 || value == 0x85 || value == 0x2028 || value == 0x2029 + || value < 0x20 && ![9, 10, 13].contains(value) + || (0x7F...0x9F).contains(value) || value == 0xFFFE || value == 0xFFFF + + { + throw source.failure( + "manifest.character", "unsupported raw source character", offset, + end: offset + scalar.utf8.count) + } + offset += scalar.utf8.count + } + metrics.admissionSeconds = seconds(start.duration(to: clock.now)) + start = clock.now + stage = .parser + metrics.parserCalls = 1 + observe?(stage, metrics) + guard let parser = ts_parser_new() else { + throw source.failure("manifest.parser", "could not allocate YAML parser", 0) + } + defer { ts_parser_delete(parser) } + guard ts_parser_set_language(parser, tree_sitter_yaml()) else { + throw source.failure("manifest.parser", "YAML grammar ABI mismatch", 0) + } + var callbacks = 0 + var parserOffset = 0 + var cancelled = false + let tree = source.bytes.withUnsafeBytes { raw -> OpaquePointer? in + // A stable non-null pointer is required for empty input too. + var empty: CChar = 0 + return withUnsafePointer(to: &empty) { emptyPointer in + var state = YAMLParseInput( + bytes: raw.baseAddress?.assumingMemoryBound(to: CChar.self) ?? emptyPointer, + count: raw.count) + return withUnsafeMutablePointer(to: &state) { pointer in + let input = TSInput( + payload: UnsafeMutableRawPointer(pointer), + read: { payload, index, _, count in + let state = payload!.assumingMemoryBound(to: YAMLParseInput.self).pointee + let offset = min(Int(index), state.count) + count!.pointee = UInt32(state.count - offset) + return state.bytes.advanced(by: offset) + }, encoding: TSInputEncodingUTF8, decode: nil) + let options = TSParseOptions( + payload: UnsafeMutableRawPointer(pointer), + progress_callback: { progress in + let state = progress!.pointee.payload!.assumingMemoryBound(to: YAMLParseInput.self) + state.pointee.callbacks += 1 + state.pointee.offset = Int(progress!.pointee.current_byte_offset) + state.pointee.failed = progress!.pointee.has_error + state.pointee.cancelled = Task.isCancelled + return state.pointee.cancelled || state.pointee.failed + || state.pointee.callbacks > YAMLParser.callbackLimit + }) + let result = ts_parser_parse_with_options(parser, nil, input, options) + callbacks = pointer.pointee.callbacks + parserOffset = pointer.pointee.offset + cancelled = pointer.pointee.cancelled + return result + } + } + } + metrics.parsingSeconds = seconds(start.duration(to: clock.now)) + metrics.parserCallbacks = callbacks + guard let tree else { + if cancelled { throw CancellationError() } + throw source.failure( + callbacks > callbackLimit ? "manifest.limit" : "manifest.syntax", + callbacks > callbackLimit ? "YAML parser work limit" : "invalid YAML", parserOffset) + } + defer { ts_tree_delete(tree) } + try Task.checkCancellation() + start = clock.now + let root = ts_tree_root_node(tree) + var pending: [(TSNode, Int)] = [(root, 1)] + var count = 0 + var depth = 0 + var documents = 0 + var comments: [Range] = [] + while let (node, level) = pending.popLast() { + count += 1 + depth = max(depth, level) + metrics.syntaxNodes = count + metrics.syntaxDepth = depth + let start = Int(ts_node_start_byte(node)) + if count > ManifestLimits.Syntax.nodes || level > ManifestLimits.Syntax.depth { + throw source.failure("manifest.limit", "YAML CST node/depth limit", start) + } + let kind = String(cString: ts_node_type(node)) + if kind == "document" { documents += 1 } + if kind == "comment" { comments.append(nodeRange(node)) } + if ["anchor", "alias", "yaml_directive", "tag_directive", "reserved_directive"].contains( + kind) + { + throw source.failure("manifest.unsupported", "unsupported YAML \(kind)", start) + } + if kind == "tag", source.spelling(nodeRange(node)) != "!!float" { + throw source.failure("manifest.tag", "only NativeValue !!float is supported", start) + } + if ts_node_is_error(node) || ts_node_is_missing(node) { + throw source.failure("manifest.syntax", "invalid YAML", start) + } + for index in 0.. Double { + let parts = duration.components + return Double(parts.seconds) + Double(parts.attoseconds) / 1e18 + } + + private static func nodeRange(_ node: TSNode) -> Range { + Int(ts_node_start_byte(node)).. [TSNode] { + (0.. YAMLNode + { + let kind = String(cString: ts_node_type(syntax)) + let children = children(syntax) + let range = nodeRange(syntax) + let tags = children.filter { String(cString: ts_node_type($0)) == "tag" } + let content = children.filter { String(cString: ts_node_type($0)) != "tag" } + if ["stream", "document", "block_node", "flow_node", "block_sequence_item"].contains(kind), + content.count == 1 + { + let node = try pair(content[0], semantic, source: source) + let tagged = !tags.isEmpty + if tagged { + guard case .scalar(let text, let quoted, _) = node.data, + semantic.tag.rawValue == "tag:yaml.org,2002:float" + else { throw source.failure("manifest.tag", "!!float requires a scalar", range.lowerBound) } + return YAMLNode( + data: .scalar(text, quoted: quoted, decimalTag: true), range: range, + entryRange: range, flow: node.flow) + } + return YAMLNode(data: node.data, range: node.range, entryRange: range, flow: node.flow) + } + if ["block_mapping", "flow_mapping", "flow_pair"].contains(kind), let mapping = semantic.mapping + { + let syntaxPairs = kind == "flow_pair" ? [syntax] : children + guard syntaxPairs.count == mapping.count else { + throw source.failure( + "manifest.parser.mismatch", "YAML parsers disagree on mapping", range.lowerBound) + } + var pairs: [(key: YAMLNode, value: YAMLNode)] = [] + var keys = Set() + for (syntaxPair, semanticPair) in zip(syntaxPairs, mapping) { + let key = field(syntaxPair, "key") + let value = field(syntaxPair, "value") + guard !ts_node_is_null(key), !ts_node_is_null(value) else { + throw source.failure( + "manifest.schema", "mapping entries require explicit keys and values", + Int(ts_node_start_byte(syntaxPair))) + } + let keyNode = try pair(key, semanticPair.key, source: source) + guard case .scalar(let name, let quoted, let tag) = keyNode.data, + !tag, quoted || YAMLScalar.classify(name) == .string + else { + throw source.failure( + "manifest.key", "mapping key must be a string", keyNode.range.lowerBound) + } + guard keys.insert(name).inserted else { + throw source.failure( + "manifest.key.duplicate", "duplicate decoded mapping key: \(name)", + keyNode.range.lowerBound) + } + let node = try pair(value, semanticPair.value, source: source) + pairs.append( + ( + keyNode, + YAMLNode( + data: node.data, range: node.range, entryRange: nodeRange(syntaxPair), flow: node.flow + ) + )) + } + return YAMLNode( + data: .mapping(pairs), range: range, entryRange: range, flow: kind != "block_mapping") + } + if kind == "block_sequence" || kind == "flow_sequence", let sequence = semantic.sequence { + guard children.count == sequence.count else { + throw source.failure( + "manifest.parser.mismatch", "YAML parsers disagree on sequence", range.lowerBound) + } + return YAMLNode( + data: .sequence(try zip(children, sequence).map { try pair($0, $1, source: source) }), + range: range, entryRange: range, flow: kind == "flow_sequence") + } + if let scalar = semantic.scalar, + ["plain_scalar", "single_quote_scalar", "double_quote_scalar", "block_scalar"].contains(kind) + { + return YAMLNode( + data: .scalar(scalar.string, quoted: kind != "plain_scalar", decimalTag: false), + range: range, entryRange: range, flow: true) + } + throw source.failure( + "manifest.parser.mismatch", "YAML parsers disagree on structure", range.lowerBound) + } + + private static func field(_ node: TSNode, _ name: String) -> TSNode { + name.withCString { ts_node_child_by_field_name(node, $0, UInt32(name.utf8.count)) } + } +} diff --git a/Sources/AgentsManifest/YAMLPatches.swift b/Sources/AgentsManifest/YAMLPatches.swift new file mode 100644 index 0000000..66c332b --- /dev/null +++ b/Sources/AgentsManifest/YAMLPatches.swift @@ -0,0 +1,448 @@ +import AgentsCore +import Foundation + +/// Concrete collection and field changes. A patch owns only the selected value/entry and its +/// attached trivia. Structural ambiguity is reported before a candidate can be published. +struct YAMLPatches { + let document: DeclarationDocument + private var source: SourceText { document.source } + private var bytes: [UInt8] { document.bytes } + + func patches(for edit: IREdit, expected: DeclarationValue) throws -> [SourcePatch] { + switch edit { + case .set(let pointer, let value): return try set(pointer, value) + case .insert(let pointer, let index, let value): return try insert(pointer, index, value) + case .remove(let pointer, let index): return try remove(pointer, index, retainComments: true) + case .relocate(let origin, let from, let destination, let to): + let nodes = try children(origin) + let originalContainer = document.locations[origin]! + let node = nodes[from] + let value = IRTree.value(IRTree.root(document.declaration), at: origin)!.elements![from] + let removal = try remove(origin, from, retainComments: false) + var insertion = try insert(destination, to, value) + let carried = document.comments.filter { + owned(node, container: originalContainer).contains($0.lowerBound) + }.map { source.spelling($0) } + let target = document.locations[destination]! + if !originalContainer.flow, !target.flow, !document.defaulted.contains(destination) { + let raw = source.spelling(owned(node, container: originalContainer)) + let oldIndent = indentation(at: node.entryRange.lowerBound) + let targetNodes = try children(destination) + let newIndent = + targetNodes.first.map { indentation(at: $0.entryRange.lowerBound) } + ?? indentation(at: target.range.lowerBound) + let shifted = raw.components(separatedBy: newline).map { line in + line.hasPrefix(oldIndent) ? newIndent + line.dropFirst(oldIndent.count) : line + }.joined(separator: newline) + insertion = insertion.map { SourcePatch(range: $0.range, replacement: Array(shifted.utf8)) } + } else if !carried.isEmpty { + let rendered = YAMLWriter.flow(value) + let prefix = newline + carried.map { " " + $0 + newline }.joined() + " " + insertion = insertion.map { + let text = String(decoding: $0.replacement, as: UTF8.self).replacingOccurrences( + of: rendered, with: prefix + rendered) + return SourcePatch(range: $0.range, replacement: Array(text.utf8)) + } + } + return removal + insertion + case .move(let pointer, let from, let to): + guard let container = document.locations[pointer], !document.defaulted.contains(pointer) + else { throw readOnly(pointer, "missing collection") } + if container.flow { + if document.comments.contains(where: { container.range.contains($0.lowerBound) }) { + var content = flowContent(container) + content.entries.insert(content.entries.remove(at: from), at: to) + return [ + SourcePatch( + range: container.range, + replacement: Array(renderFlow(content, container: container).utf8)) + ] + } + // Common flow collections retain the exact moved value and comments. Delimiters are + // reconstructed within the collection; nested values and their spelling remain owned. + let values = IRTree.value(IRTree.root(document.declaration), at: pointer)!.elements! + var order = Array(values.indices) + order.insert(order.remove(at: from), at: to) + let children = try children(pointer) + let named = isNamed(pointer) + let text = order.map { i -> String in + let node = children[i] + let range = named ? node.entryRange : node.range + return source.spelling(range) + }.joined(separator: ", ") + let opening = named ? "{" : "[" + let closing = named ? "}" : "]" + return [ + SourcePatch(range: container.range, replacement: Array((opening + text + closing).utf8)) + ] + } + let children = try children(pointer) + let moved = children[from] + let range = owned(moved, container: container) + let remaining = children.indices.filter { $0 != from } + let offset: Int + if to < remaining.count { + offset = owned(children[remaining[to]], container: container).lowerBound + } else { + offset = owned(children[remaining.last ?? from], container: container).upperBound + } + return [ + SourcePatch(range: range, replacement: []), + SourcePatch(range: offset.. [SourcePatch] { + let (parent, key) = split(pointer) + let absent = document.defaulted.contains(pointer) || document.locations[pointer] == nil + if absent { + guard let value, value != .null else { return [] } + return try addField(parent, key, value) + } + let node = document.locations[pointer]! + if value == nil || value == .null { + guard let container = document.locations[parent], + let pair = container.pairs?.first(where: { $0.key.text == yamlKey(key, parent: parent) }) + else { + throw readOnly(pointer, "value has no removable mapping entry") + } + return try removeEntry(pair.value, container: container, retainComments: true) + } + if let next = value?.record, ["git", "local", "index"].contains(next.kind), + field(pointer) == "sources", + let old = IRTree.value(IRTree.root(document.declaration), at: pointer)?.record, + old.kind != next.kind + { + let oldKey = old.kind == "git" ? "url" : old.kind == "local" ? "path" : "index" + let newKey = next.kind == "git" ? "url" : next.kind == "local" ? "path" : "index" + guard let pair = node.pairs?.first(where: { $0.key.text == oldKey }) else { + throw readOnly(pointer, "source location has no concrete field") + } + var patches = [ + SourcePatch(range: pair.key.range, replacement: Array(YAMLWriter.quote(newKey).utf8)), + SourcePatch( + range: pair.value.range, replacement: Array(YAMLWriter.flow(next[newKey]!).utf8)), + ] + for field in ["name", "requirement", "subpath"] where old[field] != next[field] { + patches += try set(pointer + "/" + field, next[field]) + } + return patches + } + var rendered = YAMLWriter.flow(value!, field: field(pointer)) + if key == "value", + IRTree.value(IRTree.root(document.declaration), at: parent)?.record?.kind == "decimal", + let text = value?.string + { + rendered = "!!float " + YAMLWriter.quote(text) + } + // Comments inside a block scalar belong to its header, never its decoded payload. + let comments = document.comments.filter { node.range.contains($0.lowerBound) } + if !comments.isEmpty { + if comments.count == 1, !rendered.contains("\n") { + rendered += " " + source.spelling(comments[0]) + } else if let container = document.locations[parent], container.items != nil, + let index = Int(key) + { + if container.flow { + var content = flowContent(container) + content.entries[index].text = rendered + content.entries[index].leading += comments.map { source.spelling($0) } + return [ + SourcePatch( + range: container.range, + replacement: Array(renderFlow(content, container: container).utf8)) + ] + } + let indent = indentation(at: node.entryRange.lowerBound) + let prefix = comments.map { source.spelling($0) + newline + indent }.joined() + return [ + SourcePatch(range: node.entryRange, replacement: Array((prefix + "- " + rendered).utf8)) + ] + } else { + throw readOnly(pointer, "replacement has comments without a precise entry boundary") + } + } + if node.range.upperBound > node.range.lowerBound, bytes[node.range.upperBound - 1] == 10, + !rendered.hasSuffix("\n") + { + rendered += newline + } + return [SourcePatch(range: node.range, replacement: Array(rendered.utf8))] + } + + private func addField(_ parent: String, _ key: String, _ value: DeclarationValue) throws + -> [SourcePatch] + { + guard let container = document.locations[parent] else { + throw readOnly(parent, "missing owning mapping") + } + if document.defaulted.contains(parent) { + let (owner, field) = split(parent) + return try addField(owner, field, .dictionary([key: value])) + } + let key = yamlKey(key, parent: parent) + let text = YAMLWriter.quote(key) + ": " + YAMLWriter.flow(value, field: key) + guard let pairs = container.pairs else { + throw readOnly(parent, "field owner is not a mapping") + } + if container.flow { + if bytes[container.range.lowerBound] != UInt8(ascii: "{") { + return [ + SourcePatch( + range: container.range, + replacement: Array(("{" + source.spelling(container.range) + ", " + text + "}").utf8)) + ] + } + let end = container.range.upperBound - 1 + return [ + SourcePatch(range: end.. 0 && bytes[end - 1] != 10 ? newline : "" + return [ + SourcePatch(range: end.. [SourcePatch] + { + guard let container = document.locations[pointer] else { + throw readOnly(pointer, "missing collection") + } + let children = try children(pointer) + let named = isNamed(pointer) + let text: String + if named { + let record = value.record! + text = + YAMLWriter.quote(record["name"]!.string!) + ": " + + YAMLWriter.flow(value, field: field(pointer)) + } else { + text = YAMLWriter.flow(value) + } + if document.defaulted.contains(pointer) { + let (parent, key) = split(pointer) + return try addField(parent, key, .array([value])) + } + if container.flow { + if document.comments.contains(where: { container.range.contains($0.lowerBound) }) { + var content = flowContent(container) + content.entries.insert(FlowEntry(text: text), at: index) + return [ + SourcePatch( + range: container.range, + replacement: Array(renderFlow(content, container: container).utf8)) + ] + } + if index < children.count { + let offset = (named ? children[index].entryRange : children[index].range).lowerBound + return [SourcePatch(range: offset.. [SourcePatch] + { + guard let container = document.locations[pointer] else { + throw readOnly(pointer, "missing collection") + } + let children = try children(pointer) + guard children.indices.contains(index) else { throw readOnly(pointer, "missing occurrence") } + return try removeEntry(children[index], container: container, retainComments: retainComments) + } + + private func removeEntry(_ node: YAMLNode, container: YAMLNode, retainComments: Bool) throws + -> [SourcePatch] + { + if container.flow { + let all = container.items ?? container.pairs!.map(\.value) + guard let index = all.firstIndex(where: { $0.range == node.range }) else { + throw readOnly("", "entry is not in its container") + } + var range = container.pairs == nil ? node.range : node.entryRange + if index + 1 < all.count { + let end = + container.pairs == nil + ? all[index + 1].range.lowerBound : all[index + 1].entryRange.lowerBound + range = range.lowerBound.. 0 { + let start = + container.pairs == nil + ? all[index - 1].range.upperBound : all[index - 1].entryRange.upperBound + range = start.. FlowContent { + let nodes = container.items ?? container.pairs!.map(\.value) + let ranges = nodes.map { container.pairs == nil ? $0.range : $0.entryRange } + var result = FlowContent(entries: ranges.map { FlowEntry(text: source.spelling($0)) }) + var index = 0 + for comment in document.comments + where container.range.contains(comment.lowerBound) { + while index < ranges.count && ranges[index].upperBound <= comment.lowerBound { index += 1 } + if index < ranges.count && ranges[index].contains(comment.lowerBound) { continue } + let text = source.spelling(comment) + if index > 0 && lineStart(comment.lowerBound) == lineStart(ranges[index - 1].upperBound - 1) { + result.entries[index - 1].trailing.append(text) + } else if index < ranges.count { + let gap = source.spelling(comment.upperBound.. String { + let base = indentation(at: container.range.lowerBound) + let indent = base + " " + var text = (container.pairs == nil ? "[" : "{") + newline + for comment in content.header { text += indent + comment + newline } + for entry in content.entries { + for comment in entry.leading { text += indent + comment + newline } + text += indent + entry.text + "," + if let first = entry.trailing.first { text += " " + first } + text += newline + for comment in entry.trailing.dropFirst() { text += indent + comment + newline } + } + for comment in content.footer { text += indent + comment + newline } + return text + base + (container.pairs == nil ? "]" : "}") + } + + private func children(_ pointer: String) throws -> [YAMLNode] { + guard let node = document.locations[pointer] else { + throw readOnly(pointer, "missing collection") + } + if document.defaulted.contains(pointer) { return [] } + if let items = node.items { return items } + if let pairs = node.pairs { return pairs.map(\.value) } + throw readOnly(pointer, "expected a collection") + } + private func owned(_ node: YAMLNode, container: YAMLNode) -> Range { + var start = lineStart(node.entryRange.lowerBound) + while start > 0 { + let end = start - 1 + let previous = lineStart(end) + let line = source.spelling(previous.. Int { + var index = min(offset, bytes.count) + while index > 0 && bytes[index - 1] != 10 { index -= 1 } + return index + } + private func lineEnd(_ offset: Int) -> Int { + if offset > 0 && bytes[offset - 1] == 10 { return offset } + var index = offset + while index < bytes.count && bytes[index] != 10 { index += 1 } + return min(bytes.count, index + 1) + } + private func indentation(at offset: Int) -> String { + let start = lineStart(offset) + var end = start + while end < bytes.count && bytes[end] == 32 { end += 1 } + return String(decoding: bytes[start.. (String, String) { + let index = pointer.lastIndex(of: "/")! + return ( + String(pointer[.. String { + let parts = IRTree.segments(pointer) + if parts.last.flatMap(Int.init) != nil { return parts.dropLast().last ?? "" } + return parts.last ?? "" + } + private func isNamed(_ pointer: String) -> Bool { + ["sources", "groups", "overrides", "chatGPT"].contains(field(pointer)) + } + private func yamlKey(_ field: String, parent: String) -> String { + if field == "chatGPT" { return "chatgpt" } + if field == "name", parent.contains("/uses/") { return "group" } + return field + } + private func readOnly(_ pointer: String, _ message: String) -> ManifestFailure { + source.failure( + "manifest.edit.readOnly", message, document.locations[pointer]?.range.lowerBound ?? 0) + } +} diff --git a/Sources/AgentsManifest/YAMLProjection.swift b/Sources/AgentsManifest/YAMLProjection.swift new file mode 100644 index 0000000..9bd0af8 --- /dev/null +++ b/Sources/AgentsManifest/YAMLProjection.swift @@ -0,0 +1,357 @@ +import AgentsCore + +/// Converts validated YAML data into the syntax-independent complete declaration, recording +/// semantic indexed pointers while the concrete mapping keys are still available. +final class YAMLProjection { + let source: SourceText + private(set) var locations: [String: YAMLNode] = [:] + private(set) var entries: [SourceMapEntry] = [] + private var budget = SourceMapBudget() + private var entryIndexes: [String: Int] = [:] + + init(source: SourceText) { self.source = source } + + func declaration(_ root: YAMLNode) throws -> DeclarationIR { + try mark(root, "") + let fields = fields(root) + let sources = try named(fields["sources"], at: "/sources", owner: root, role: "source") + let components = try records( + fields["components"], at: "/components", owner: root, role: "component") + let groups = try named(fields["groups"], at: "/groups", owner: root, role: "group") + let uses = try records(fields["uses"], at: "/uses", owner: root, role: "use") + let defaults = try field( + fields["defaultAgents"], at: "/defaultAgents", owner: root, default: .null) + let exports = try field(fields["exports"], at: "/exports", owner: root, default: .array([])) + let watch = try field(fields["watch"], at: "/watch", owner: root, default: .array([])) + return DeclarationIR( + defaultAgents: defaults.elements.map { $0.map { $0.string! } }, + exports: exports.elements!.map { $0.string! }, sources: sources, components: components, + groups: groups, uses: uses, watch: watch.elements!.map { $0.string! }) + } + + private func fields(_ node: YAMLNode) -> [String: YAMLNode] { + Dictionary(uniqueKeysWithValues: (node.pairs ?? []).map { ($0.key.text!, $0.value) }) + } + + private func mark(_ node: YAMLNode, _ pointer: String, defaulted: Bool = false) throws { + let span = source.span(node.range) + if let index = entryIndexes[pointer] { + locations[pointer] = node + entries[index] = SourceMapEntry(pointer: pointer, span: span, defaulted: defaulted) + return + } + guard budget.consume(pointer: pointer, span: span, origins: []) else { + throw source.failure("manifest.limit", "source map budget", node.range.lowerBound) + } + locations[pointer] = node + entryIndexes[pointer] = entries.count + entries.append(SourceMapEntry(pointer: pointer, span: span, defaulted: defaulted)) + } + + private func field( + _ node: YAMLNode?, at pointer: String, owner: YAMLNode, default fallback: DeclarationValue + ) throws -> DeclarationValue { + guard let node else { + try mark(owner, pointer, defaulted: true) + return fallback + } + return try plain(node, at: pointer) + } + + private func plain(_ node: YAMLNode, at pointer: String) throws -> DeclarationValue { + try mark(node, pointer) + switch node.data { + case .scalar(let text, let quoted, _): + if quoted { return .string(text) } + switch YAMLScalar.classify(text) { + case .integer: return .integer(YAMLScalar.integer(text)!) + case .boolean: return .boolean(text.lowercased() == "true") + case .null: return .null + default: return .string(text) + } + case .sequence(let items): + return try .array( + items.enumerated().map { try plain($0.element, at: pointer + "/\($0.offset)") }) + case .mapping(let pairs): + var result: [String: DeclarationValue] = [:] + for pair in pairs { + result[pair.key.text!] = try plain( + pair.value, at: pointer + "/" + pointerEscape(pair.key.text!)) + } + return .dictionary(result) + } + } + + private func records(_ node: YAMLNode?, at pointer: String, owner: YAMLNode, role: String) throws + -> [DeclarationRecord] + { + try mark(node ?? owner, pointer, defaulted: node == nil) + return try (node?.items ?? []).enumerated().map { + try record($0.element, at: pointer + "/\($0.offset)", role: role) + } + } + + private func named(_ node: YAMLNode?, at pointer: String, owner: YAMLNode, role: String) throws + -> [DeclarationRecord] + { + try mark(node ?? owner, pointer, defaulted: node == nil) + return try (node?.pairs ?? []).enumerated().map { index, pair in + let path = pointer + "/\(index)" + var value = try record(pair.value, at: path, role: role).fields + value["name"] = .string(pair.key.text!) + try mark(pair.key, path + "/name") + return DeclarationRecord(kind: kind(pair.value, role: role), fields: value) + } + } + + private func kind(_ node: YAMLNode, role: String) -> String { + let f = fields(node) + switch role { + case "component", "transport", "reference": return f["kind"]!.text! + case "source": return f["url"] != nil ? "git" : f["path"] != nil ? "local" : "index" + case "use": return f["source"] == nil ? "local" : "exported" + case "condition": return "when" + case "section": return "section" + case "group": return "group" + case "override": return "skill" + case "promptDeclaration": return "prompt" + case "resource": return "path" + case "run": return "executable" + case "parameter": return "parameter" + case "rule": return f["effect"]!.text! + default: return role + } + } + + private func record(_ node: YAMLNode, at pointer: String, role: String) throws + -> DeclarationRecord + { + try mark(node, pointer) + let input = fields(node) + let kind = kind(node, role: role) + if let explicit = input["kind"] { + try mark(explicit, pointer + "/kind") + } else if role == "source", + let key = node.pairs?.first(where: { ["url", "path", "index"].contains($0.key.text!) })?.key + { + try mark(key, pointer + "/kind") + } else if role == "rule", let effect = input["effect"] { + try mark(effect, pointer + "/kind") + } else { + try mark(node, pointer + "/kind", defaulted: true) + } + var output: [String: DeclarationValue] = [:] + var defaults: [String: DeclarationValue] = [:] + if role == "component" { + defaults = ["agents": .null, "condition": .null, "native": .dictionary([:])] + } + switch role == "component" ? kind : role { + case "source": defaults = ["subpath": .null, "requirement": .null] + case "condition": defaults = ["agents": .null, "scopes": .null, "platforms": .null] + case "group": defaults = ["components": .array([]), "uses": .array([]), "condition": .null] + case "use", "section": defaults = ["source": .null, "condition": .null] + case "override": defaults = ["agents": .null, "mode": .null] + case "promptDeclaration": + defaults = ["sections": .array([]), "append": .null, "condition": .null] + case "resource": defaults = ["source": .null] + case "run", "transport": + defaults = [ + "arguments": .array([]), "environment": .dictionary([:]), "workingDirectory": .null, + ] + case "parameter": defaults = ["defaultValue": .null] + case "skills": + defaults.merge([ + "select": .string("all"), "exclude": .array([]), "mode": .null, "overrides": .array([]), + ]) { _, r in r } + case "instructions": + defaults.merge(["sections": .array([]), "chatGPT": .array([])]) { _, r in r } + case "hook": defaults.merge(["matcher": .null, "timeoutSeconds": .null]) { _, r in r } + case "subagent": defaults.merge(["model": .null, "tools": .null]) { _, r in r } + case "command": defaults["parameters"] = .array([]) + case "lspServer": defaults["initializationOptions"] = .dictionary([:]) + case "ignore": defaults["purpose"] = .string("context") + case "plugin": + defaults.merge(["mode": .string("components"), "select": .null, "exclude": .array([])]) { + _, r in r + } + default: break + } + if role == "transport", kind != "stdio" { defaults = ["headers": .dictionary([:])] } + for (name, fallback) in defaults { + let yamlName = name == "chatGPT" ? "chatgpt" : name + if input[yamlName] == nil { + try mark(node, pointer + "/" + name, defaulted: true) + output[name] = fallback + } + } + for (name, value) in input { + if name == "kind" || role == "rule" && name == "effect" { continue } + let field = name == "chatgpt" ? "chatGPT" : role == "use" && name == "group" ? "name" : name + let path = pointer + "/" + pointerEscape(field) + switch name { + case "condition": output[field] = try .record(record(value, at: path, role: "condition")) + case "components": + output[field] = try .array( + records(value, at: path, owner: node, role: "component").map(DeclarationValue.record)) + case "uses": + output[field] = try .array( + records(value, at: path, owner: node, role: "use").map(DeclarationValue.record)) + case "overrides": + output[field] = try .array( + named(value, at: path, owner: node, role: "override").map(DeclarationValue.record)) + case "chatgpt": + output[field] = try .array( + named(value, at: path, owner: node, role: "promptDeclaration").map( + DeclarationValue.record)) + case "sections", "parameters", "rules": + let childRole = name == "sections" ? "section" : name == "parameters" ? "parameter" : "rule" + output[field] = try .array( + records(value, at: path, owner: node, role: childRole).map(DeclarationValue.record)) + case "transport", "run", "workingDirectory": + output[field] = try .record( + record(value, at: path, role: name == "workingDirectory" ? "resource" : name)) + case "prompt": output[field] = try prompt(value, at: path) + case "event", "operation": output[field] = try symbol(value, at: path, role: name) + case "environment", "headers": + try mark(value, path) + var result: [String: DeclarationValue] = [:] + for pair in value.pairs! { + result[pair.key.text!] = try binding( + pair.value, at: path + "/" + pointerEscape(pair.key.text!)) + } + output[field] = .dictionary(result) + case "native": + try mark(value, path) + var schemas: [String: DeclarationValue] = [:] + for pair in value.pairs! { + schemas[pair.key.text!] = try nativeDictionary( + pair.value, at: path + "/" + pointerEscape(pair.key.text!)) + } + output[field] = .dictionary(schemas) + case "initializationOptions": output[field] = try nativeDictionary(value, at: path) + case "exclude" where role == "component" && kind == "plugin": + output[field] = try .array( + records(value, at: path, owner: node, role: "reference").map(DeclarationValue.record)) + case "requirement": + try mark(value, path) + let requirement = fields(value) + let text = requirement.values.first!.text! + let parsed: SourceRequirement + if let branch = requirement["branch"]?.text { + parsed = .branch(branch) + } else if let revision = requirement["revision"]?.text { + parsed = .revision(revision) + } else if let exact = requirement["exact"]?.text { + parsed = .exact(exact) + } else if let minor = requirement["upToNextMinor"]?.text { + parsed = .upToNextMinor(from: minor) + } else if let upper = requirement["to"]?.text { + parsed = .range(from: requirement["from"]!.text!, to: upper) + } else { + parsed = .upToNextMajor(from: text) + } + let canonical = parsed.canonical + output[field] = .requirement(canonical) + let lower = + requirement["from"] ?? requirement["upToNextMinor"] ?? requirement["branch"] + ?? requirement["revision"] ?? requirement["exact"]! + try mark(lower, path + "/value") + try mark(value.pairs!.first!.key, path + "/kind") + if canonical.upperBound != nil, let upper = requirement["to"] { + try mark(upper, path + "/to") + } + case "url" where role == "source": + try mark(value, path) + output[field] = .string(SourceDeclaration(kind: .git, location: value.text!).gitURL) + default: output[field] = try plain(value, at: path) + } + } + return DeclarationRecord(kind: kind, fields: output) + } + + private func prompt(_ node: YAMLNode, at pointer: String) throws -> DeclarationValue { + if let text = node.text { + try mark(node, pointer) + try mark(node, pointer + "/kind", defaulted: true) + try mark(node, pointer + "/value") + return .record(DeclarationRecord(kind: "literal", fields: ["value": .string(text)])) + } + let resource = try record(fields(node)["file"]!, at: pointer, role: "resource") + try mark(node.pairs!.first!.key, pointer + "/kind") + return .record(DeclarationRecord(kind: "file", fields: resource.fields)) + } + + private func symbol(_ node: YAMLNode, at pointer: String, role: String) throws -> DeclarationValue + { + try mark(node, pointer) + try mark(node, pointer + "/kind") + if let text = node.text { return .record(DeclarationRecord(kind: text, fields: [:])) } + let pair = node.pairs!.first! + try mark(pair.value, pointer + "/value") + return .record( + DeclarationRecord(kind: pair.key.text!, fields: ["value": .string(pair.value.text!)])) + } + + private func binding(_ node: YAMLNode, at pointer: String) throws -> DeclarationValue { + try mark(node, pointer) + let kind: String + let value: YAMLNode + if node.text != nil { + kind = "literal" + value = node + } else { + let pair = node.pairs!.first! + kind = pair.key.text == "env" ? "environment" : "secret" + value = pair.value + } + try mark(value, pointer + "/value") + try mark(node, pointer + "/kind", defaulted: node.text != nil) + return .record(DeclarationRecord(kind: kind, fields: ["value": .string(value.text!)])) + } + + private func nativeDictionary(_ node: YAMLNode, at pointer: String) throws -> DeclarationValue { + try mark(node, pointer) + var values: [String: DeclarationValue] = [:] + for pair in node.pairs! { + values[pair.key.text!] = try native( + pair.value, at: pointer + "/" + pointerEscape(pair.key.text!)) + } + return .dictionary(values) + } + + private func native(_ node: YAMLNode, at pointer: String) throws -> DeclarationValue { + try mark(node, pointer) + try mark(node, pointer + "/kind") + let kind: String + let payload: DeclarationValue? + switch node.data { + case .scalar(let text, let quoted, let tag): + switch tag ? YAMLScalar.decimal : quoted ? .string : YAMLScalar.classify(text) { + case .string: + kind = "string" + payload = .string(text) + case .integer: + kind = "integer" + payload = .integer(YAMLScalar.integer(text)!) + case .boolean: + kind = "boolean" + payload = .boolean(text.lowercased() == "true") + case .null: + kind = "null" + payload = nil + case .decimal: + kind = "decimal" + payload = .string(YAMLScalar.decimal(text, explicit: tag)!) + } + case .sequence(let items): + kind = "array" + payload = try .array( + items.enumerated().map { try native($0.element, at: pointer + "/value/\($0.offset)") }) + case .mapping: + kind = "object" + payload = try nativeDictionary(node, at: pointer + "/value") + } + if payload != nil { try mark(node, pointer + "/value") } + return .record(DeclarationRecord(kind: kind, fields: payload.map { ["value": $0] } ?? [:])) + } +} diff --git a/Sources/AgentsManifest/YAMLScalar.swift b/Sources/AgentsManifest/YAMLScalar.swift new file mode 100644 index 0000000..da930bd --- /dev/null +++ b/Sources/AgentsManifest/YAMLScalar.swift @@ -0,0 +1,67 @@ +import AgentsCore +import Foundation + +/// YAML 1.2 Core resolution. Number conversion never passes through floating-point formatting. +enum YAMLScalar: Equatable { + case string, integer, decimal, boolean, null + + static func classify(_ text: String) -> Self { + if ["", "~", "null", "Null", "NULL"].contains(text) { return .null } + if ["true", "True", "TRUE", "false", "False", "FALSE"].contains(text) { return .boolean } + if matches(text, #"^[-+]?(0o[0-7]+|0x[0-9a-fA-F]+|[0-9]+)$"#) { return .integer } + if matches(text, #"^[-+]?(([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][-+]?[0-9]+)?|\.(inf|Inf|INF))$"#) + || [".nan", ".NaN", ".NAN"].contains(text) + { + return .decimal + } + return .string + } + + static func integer(_ text: String) -> Int? { + var digits = text + let negative = digits.hasPrefix("-") + if digits.hasPrefix("-") || digits.hasPrefix("+") { digits.removeFirst() } + let radix: Int + if digits.hasPrefix("0o") { + radix = 8 + digits.removeFirst(2) + } else if digits.hasPrefix("0x") { + radix = 16 + digits.removeFirst(2) + } else { + radix = 10 + } + return Int((negative ? "-" : "") + digits, radix: radix) + } + + static func decimal(_ text: String, explicit: Bool) -> String? { + if explicit { return validDecimal(text) ? text : nil } + var result = text + if result.hasPrefix("+") { result.removeFirst() } + let negative = result.hasPrefix("-") + if negative { result.removeFirst() } + let exponent = result.firstIndex { $0 == "e" || $0 == "E" } + let suffix = exponent.map { String(result[$0...]) } ?? "" + var mantissa = exponent.map { String(result[..<$0]) } ?? result + if mantissa.hasPrefix(".") { mantissa = "0" + mantissa } + if mantissa.hasSuffix(".") { mantissa += "0" } + if let dot = mantissa.firstIndex(of: ".") { + var whole = String(mantissa[.. 1 && whole.hasPrefix("0") { whole.removeFirst() } + mantissa = whole + mantissa[dot...] + } else { + while mantissa.count > 1 && mantissa.hasPrefix("0") { mantissa.removeFirst() } + } + result = (negative ? "-" : "") + mantissa + suffix + return validDecimal(result) ? result : nil + } + + static func validDecimal(_ text: String) -> Bool { + matches(text, #"^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?$"#) + && Double(text)?.isFinite == true + } + + private static func matches(_ text: String, _ pattern: String) -> Bool { + text.range(of: pattern, options: .regularExpression) != nil + } +} diff --git a/Sources/AgentsManifest/YAMLValidation.swift b/Sources/AgentsManifest/YAMLValidation.swift new file mode 100644 index 0000000..ea73920 --- /dev/null +++ b/Sources/AgentsManifest/YAMLValidation.swift @@ -0,0 +1,177 @@ +import AgentsCore + +/// The finite constraints compiled from the bundled declaration schema. No caller supplies rules. +indirect enum YAMLRule: Sendable { + case string, native, version + case integer(minimum: Int) + case constant(String) + case enumeration([String]) + case named(String) + case array(YAMLRule) + case dictionary(YAMLRule) + case object([String: YAMLRule], required: [String]) + case oneOf([YAMLRule]) +} + +final class YAMLValidation { + let source: SourceText + private(set) var work = 0 + private(set) var strings = 0 + private var nodes = 0 + + init(source: SourceText) { self.source = source } + + func validate(_ node: YAMLNode) throws { + try inspect(node, depth: 1) + try check(node, ManifestSchema.root) + } + + private func spend(_ node: YAMLNode) throws { + work += 1 + guard work <= ManifestLimits.Domain.steps else { + throw source.failure("manifest.limit", "schema work limit", node.range.lowerBound) + } + } + + private func inspect(_ node: YAMLNode, depth: Int) throws { + nodes += 1 + guard nodes <= ManifestLimits.Values.nodes, depth <= ManifestLimits.Values.depth else { + throw source.failure( + "manifest.limit", "decoded value node/depth limit", node.range.lowerBound) + } + switch node.data { + case .scalar(let text, _, _): strings += text.utf8.count + case .sequence(let items): + guard items.count <= ManifestLimits.Values.entries else { + throw source.failure("manifest.limit", "container entry limit", node.range.lowerBound) + } + for item in items { try inspect(item, depth: depth + 1) } + case .mapping(let pairs): + guard pairs.count <= ManifestLimits.Values.entries else { + throw source.failure("manifest.limit", "container entry limit", node.range.lowerBound) + } + for pair in pairs { + try inspect(pair.key, depth: depth + 1) + try inspect(pair.value, depth: depth + 1) + } + } + guard strings <= ManifestLimits.Values.stringBytes else { + throw source.failure("manifest.limit", "decoded string byte limit", node.range.lowerBound) + } + } + + private func check(_ node: YAMLNode, _ rule: YAMLRule) throws { + try spend(node) + func fail(_ message: String) -> ManifestFailure { + source.failure("manifest.schema", message, node.range.lowerBound, end: node.range.upperBound) + } + func string() throws -> String { + guard case .scalar(let text, let quoted, let tag) = node.data, + !tag, quoted || YAMLScalar.classify(text) == .string + else { throw fail("expected a string") } + return text + } + switch rule { + case .named(let name): try check(node, ManifestSchema.definitions[name]!) + case .string: _ = try string() + case .constant(let expected): + guard try string() == expected else { throw fail("expected \(expected)") } + case .enumeration(let values): + guard try values.contains(string()) else { + throw fail("expected one of \(values.joined(separator: ", "))") + } + case .integer, .version: + guard case .scalar(let text, let quoted, let tag) = node.data, + !quoted, !tag, YAMLScalar.classify(text) == .integer, let integer = YAMLScalar.integer(text) + else { throw fail("expected a representable plain integer") } + switch rule { + case .version: guard integer == 1 else { throw fail("unsupported manifest version") } + case .integer(let minimum): + guard integer >= minimum else { throw fail("integer is below its minimum") } + default: break + } + case .array(let item): + guard let items = node.items else { throw fail("expected a sequence") } + for node in items { try check(node, item) } + case .dictionary(let value): + guard let pairs = node.pairs else { throw fail("expected a mapping") } + for pair in pairs { try check(pair.value, value) } + case .object(let fields, let required): + guard let pairs = node.pairs else { throw fail("expected a mapping") } + let present = Set(pairs.map { $0.key.text! }) + for name in required where !present.contains(name) { throw fail("missing field: \(name)") } + for pair in pairs { + let name = pair.key.text! + guard let rule = fields[name] else { + throw source.failure( + "manifest.schema", "unknown field: \(name)", pair.key.range.lowerBound) + } + try check(pair.value, rule) + } + case .oneOf(let choices): + // Component and transport records have a literal discriminator in the generated schema. + // Select that branch before traversing descendants, rather than rescanning whole subtrees. + if let kind = node.pairs?.first(where: { $0.key.text == "kind" })?.value.text { + for candidate in choices { + let resolved: YAMLRule + if case .named(let name) = candidate { + resolved = ManifestSchema.definitions[name]! + } else { + resolved = candidate + } + if case .object(let fields, _) = resolved, + let discriminator = fields["kind"] + { + switch discriminator { + case .constant(let value) where value == kind: + try check(node, candidate) + return + case .enumeration(let values) where values.contains(kind): + try check(node, candidate) + return + default: continue + } + } + } + } + var matches = 0 + var firstFailure: ManifestFailure? + for choice in choices { + do { + try check(node, choice) + matches += 1 + } catch let failure as ManifestFailure { + if failure.diagnostics.first?.code == "manifest.limit" { throw failure } + firstFailure = firstFailure ?? failure + } + } + guard matches == 1 else { + if matches == 0, let firstFailure { throw firstFailure } + throw fail("ambiguous field shape") + } + case .native: + switch node.data { + case .scalar(let text, let quoted, let tag): + if tag { + guard YAMLScalar.decimal(text, explicit: true) != nil else { + throw fail("!!float requires exact finite JSON-number text") + } + } else if !quoted { + switch YAMLScalar.classify(text) { + case .integer: + guard YAMLScalar.integer(text) != nil else { + throw fail("integer overflow; use !!float for a decimal value") + } + case .decimal: + guard YAMLScalar.decimal(text, explicit: false) != nil else { + throw fail("expected a finite decimal") + } + default: break + } + } + case .sequence(let items): for item in items { try check(item, .native) } + case .mapping(let pairs): for pair in pairs { try check(pair.value, .native) } + } + } + } +} diff --git a/Sources/AgentsManifest/YAMLWriter.swift b/Sources/AgentsManifest/YAMLWriter.swift new file mode 100644 index 0000000..895002b --- /dev/null +++ b/Sources/AgentsManifest/YAMLWriter.swift @@ -0,0 +1,144 @@ +import AgentsCore + +/// Canonical output is used for new documents and owned replacement values. Existing documents +/// are changed through concrete ranges; their unrelated bytes are never reprinted. +enum YAMLWriter { + static func manifest(_ value: DeclarationIR) -> [UInt8] { + var result = "version: 1\n" + if let agents = value.defaultAgents { + result += "defaultAgents: " + flow(YAMLConstruction.strings(agents)) + "\n" + } + if !value.sources.isEmpty { result += namedBlock("sources", value.sources) } + if !value.components.isEmpty { + result += "components:\n" + for component in value.components { result += " - " + flow(.record(component)) + "\n" } + } + if !value.groups.isEmpty { result += namedBlock("groups", value.groups) } + if !value.uses.isEmpty { + result += "uses: " + flow(.array(value.uses.map(DeclarationValue.record))) + "\n" + } + if !value.exports.isEmpty { + result += "exports: " + flow(YAMLConstruction.strings(value.exports)) + "\n" + } + if !value.watch.isEmpty { + result += "watch: " + flow(YAMLConstruction.strings(value.watch)) + "\n" + } + return Array(result.utf8) + } + + private static func namedBlock(_ field: String, _ records: [DeclarationRecord]) -> String { + field + ":\n" + + records.map { + " " + quote($0["name"]!.string!) + ": " + flow(.record($0), field: field) + "\n" + }.joined() + } + + static func quote(_ text: String) -> String { + var result = "\"" + for scalar in text.unicodeScalars { + switch scalar { + case "\"": result += "\\\"" + case "\\": result += "\\\\" + case "\n": result += "\\n" + case "\r": result += "\\r" + case "\t": result += "\\t" + case "\0"..<" ", "\u{7F}"..."\u{9F}", "\u{2028}", "\u{2029}", "\u{FFFE}", "\u{FFFF}": + let hex = String(scalar.value, radix: 16) + result += "\\u" + String(repeating: "0", count: max(0, 4 - hex.count)) + hex + default: result += String(scalar) + } + } + return result + "\"" + } + + static func flow(_ value: DeclarationValue, field: String = "") -> String { + switch value { + case .null: return "null" + case .string(let value): return quote(value) + case .integer(let value): return String(value) + case .boolean(let value): return value ? "true" : "false" + case .dictionary(let values): + return mapping(values.keys.sorted(by: utf8Less).map { ($0, flow(values[$0]!, field: $0)) }) + case .array(let values): + if ["sources", "groups", "overrides", "chatGPT"].contains(field) { + return mapping( + values.map { value in + let record = value.record! + return (record["name"]!.string!, flow(value, field: field)) + }) + } + return "[" + values.map { flow($0) }.joined(separator: ", ") + "]" + case .requirement(let value): + let key: String + switch value { + case .branch: key = "branch" + case .revision: key = "revision" + case .exact: key = "exact" + case .upToNextMajor, .range: key = "from" + case .upToNextMinor: key = "upToNextMinor" + } + var fields = [(key, quote(value.value))] + if let upper = value.upperBound { fields.append(("to", quote(upper))) } + return mapping(fields) + case .record(let record): + let f = record.fields + if ["string", "integer", "boolean", "array", "object"].contains(record.kind), + let payload = f["value"] + { + return flow(payload) + } + if record.kind == "decimal" { return "!!float " + quote(f["value"]!.string!) } + if record.kind == "null" { return "null" } + if record.kind == "literal" { return quote(f["value"]!.string!) } + if ["environment", "secret", "native", "tool"].contains(record.kind) { + return mapping([ + (record.kind == "environment" ? "env" : record.kind, quote(f["value"]!.string!)) + ]) + } + if record.kind == "file" { + return mapping([("file", flow(.record(DeclarationRecord(kind: "path", fields: f))))]) + } + if f.isEmpty { return quote(record.kind) } + let componentKinds = [ + "skills", "instructions", "mcpServer", "hook", "subagent", "command", "lspServer", + "permissions", "ignore", "plugin", + ] + var pairs: [(String, String)] = [] + if componentKinds.contains(record.kind) + || ["stdio", "streamableHTTP", "sse"].contains(record.kind) + { + pairs.append(("kind", quote(record.kind))) + } + if ["allow", "ask", "deny"].contains(record.kind) { + pairs.append(("effect", quote(record.kind))) + } + let named = ["sources", "groups", "overrides", "chatGPT"].contains(field) + let order = [ + "name", "source", "url", "path", "index", "requirement", "subpath", "select", "exclude", + "mode", "overrides", "sections", "chatGPT", "description", "prompt", "model", "tools", + "parameters", "transport", "event", "run", "matcher", "timeoutSeconds", "executable", + "arguments", "environment", "workingDirectory", "headers", "languages", + "initializationOptions", "rules", "operation", "pattern", "patterns", "purpose", + "components", "uses", "append", "agents", "scopes", "platforms", "condition", "native", + ] + let keys = f.keys.sorted { left, right in + let a = order.firstIndex(of: left) ?? order.count + let b = order.firstIndex(of: right) ?? order.count + return a == b ? utf8Less(left, right) : a < b + } + for key in keys where f[key] != .null && !(named && key == "name") { + let yamlKey = + key == "chatGPT" + ? "chatgpt" + : ["local", "exported"].contains(record.kind) && f["path"] == nil && key == "name" + ? "group" : key + pairs.append((yamlKey, flow(f[key]!, field: key))) + } + return mapping(pairs) + } + } + + static func mapping(_ values: [(String, String)]) -> String { + "{" + values.map { quote($0.0) + ": " + $0.1 }.joined(separator: ", ") + "}" + } +} diff --git a/Sources/Components/ComponentLinker.swift b/Sources/Components/ComponentLinker.swift index cd82119..3fb2b29 100644 --- a/Sources/Components/ComponentLinker.swift +++ b/Sources/Components/ComponentLinker.swift @@ -90,7 +90,7 @@ final class Linking { session.register(root) let context = LinkingDocument( declaration: declaration, document: document, view: root, - manifestPath: store.scope == .user ? "Agents.swift" : ".agent/Agents.swift", + manifestPath: store.scope == .user ? "agents.yaml" : ".agent/agents.yaml", producer: false) try budget.manifest(root.snapshot, path: context.manifestPath, bytes: document.bytes.count) guard let result = try search(root: context, choices: pins) else { @@ -271,7 +271,7 @@ final class Linking { if let existing = documents[key] { return existing } let root = try view.directory() let file = root.appendingPathComponent( - root.lastPathComponent == ".agent" ? "Agents.swift" : ".agent/Agents.swift") + root.lastPathComponent == ".agent" ? "agents.yaml" : ".agent/agents.yaml") let relative = try view.relativePath(file) let handle = try FileHandle(forReadingFrom: view.resource(relative)) defer { try? handle.close() } diff --git a/Sources/Components/Expansion.swift b/Sources/Components/Expansion.swift index 7b2f98a..8729c79 100644 --- a/Sources/Components/Expansion.swift +++ b/Sources/Components/Expansion.swift @@ -523,7 +523,7 @@ final class Expansion { revision: context.view.pin?.revision, artifactDigest: context.view.snapshot.revision.hasPrefix("sha256:") ? context.view.snapshot.revision : nil, - relativePath: context.manifestPath, format: "Agents.swift", adapterVersion: "1.0", + relativePath: context.manifestPath, format: "yaml", adapterVersion: "1", group: group, referenceChain: chain) let origin = ContributionOrigin( occurrence: occurrence, provenance: provenance, diff --git a/Sources/TreeSitterYAML/LICENSE b/Sources/TreeSitterYAML/LICENSE new file mode 100644 index 0000000..262eb46 --- /dev/null +++ b/Sources/TreeSitterYAML/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2024 tree-sitter-grammars contributors +Copyright (c) 2019-2021 Ika + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Sources/TreeSitterYAML/include/yaml.h b/Sources/TreeSitterYAML/include/yaml.h new file mode 100644 index 0000000..ce248bb --- /dev/null +++ b/Sources/TreeSitterYAML/include/yaml.h @@ -0,0 +1,16 @@ +#ifndef TREE_SITTER_YAML_H_ +#define TREE_SITTER_YAML_H_ + +typedef struct TSLanguage TSLanguage; + +#ifdef __cplusplus +extern "C" { +#endif + +const TSLanguage *tree_sitter_yaml(void); + +#ifdef __cplusplus +} +#endif + +#endif // TREE_SITTER_YAML_H_ diff --git a/Sources/TreeSitterYAML/parser.c b/Sources/TreeSitterYAML/parser.c new file mode 100644 index 0000000..34fe31b --- /dev/null +++ b/Sources/TreeSitterYAML/parser.c @@ -0,0 +1,41384 @@ +/* Automatically @generated by tree-sitter v0.25.10 */ + +#include "tree_sitter/parser.h" + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#endif + +#define LANGUAGE_VERSION 14 +#define STATE_COUNT 1579 +#define LARGE_STATE_COUNT 96 +#define SYMBOL_COUNT 301 +#define ALIAS_COUNT 0 +#define TOKEN_COUNT 114 +#define EXTERNAL_TOKEN_COUNT 113 +#define FIELD_COUNT 2 +#define MAX_ALIAS_SEQUENCE_LENGTH 5 +#define MAX_RESERVED_WORD_SET_SIZE 0 +#define PRODUCTION_ID_COUNT 12 +#define SUPERTYPE_COUNT 0 + +enum ts_symbol_identifiers { + sym__eof = 1, + sym__s_dir_yml_bgn = 2, + sym__r_dir_yml_ver = 3, + sym__s_dir_tag_bgn = 4, + sym__r_dir_tag_hdl = 5, + sym__r_dir_tag_pfx = 6, + sym__s_dir_rsv_bgn = 7, + sym__r_dir_rsv_prm = 8, + sym__s_drs_end = 9, + sym__s_doc_end = 10, + sym__r_blk_seq_bgn = 11, + sym__br_blk_seq_bgn = 12, + sym__b_blk_seq_bgn = 13, + sym__r_blk_key_bgn = 14, + sym__br_blk_key_bgn = 15, + sym__b_blk_key_bgn = 16, + sym__r_blk_val_bgn = 17, + sym__br_blk_val_bgn = 18, + sym__b_blk_val_bgn = 19, + sym__r_blk_imp_bgn = 20, + sym__r_blk_lit_bgn = 21, + sym__br_blk_lit_bgn = 22, + sym__r_blk_fld_bgn = 23, + sym__br_blk_fld_bgn = 24, + sym__br_blk_str_ctn = 25, + sym__r_flw_seq_bgn = 26, + sym__br_flw_seq_bgn = 27, + sym__b_flw_seq_bgn = 28, + sym__r_flw_seq_end = 29, + sym__br_flw_seq_end = 30, + sym__b_flw_seq_end = 31, + sym__r_flw_map_bgn = 32, + sym__br_flw_map_bgn = 33, + sym__b_flw_map_bgn = 34, + sym__r_flw_map_end = 35, + sym__br_flw_map_end = 36, + sym__b_flw_map_end = 37, + sym__r_flw_sep_bgn = 38, + sym__br_flw_sep_bgn = 39, + sym__r_flw_key_bgn = 40, + sym__br_flw_key_bgn = 41, + sym__r_flw_jsv_bgn = 42, + sym__br_flw_jsv_bgn = 43, + sym__r_flw_njv_bgn = 44, + sym__br_flw_njv_bgn = 45, + sym__r_dqt_str_bgn = 46, + sym__br_dqt_str_bgn = 47, + sym__b_dqt_str_bgn = 48, + sym__r_dqt_str_ctn = 49, + sym__br_dqt_str_ctn = 50, + sym__r_dqt_esc_nwl = 51, + sym__br_dqt_esc_nwl = 52, + sym__r_dqt_esc_seq = 53, + sym__br_dqt_esc_seq = 54, + sym__r_dqt_str_end = 55, + sym__br_dqt_str_end = 56, + sym__r_sqt_str_bgn = 57, + sym__br_sqt_str_bgn = 58, + sym__b_sqt_str_bgn = 59, + sym__r_sqt_str_ctn = 60, + sym__br_sqt_str_ctn = 61, + sym__r_sqt_esc_sqt = 62, + sym__br_sqt_esc_sqt = 63, + sym__r_sqt_str_end = 64, + sym__br_sqt_str_end = 65, + sym__r_sgl_pln_nul_blk = 66, + sym__br_sgl_pln_nul_blk = 67, + sym__b_sgl_pln_nul_blk = 68, + sym__r_sgl_pln_nul_flw = 69, + sym__br_sgl_pln_nul_flw = 70, + sym__r_sgl_pln_bol_blk = 71, + sym__br_sgl_pln_bol_blk = 72, + sym__b_sgl_pln_bol_blk = 73, + sym__r_sgl_pln_bol_flw = 74, + sym__br_sgl_pln_bol_flw = 75, + sym__r_sgl_pln_int_blk = 76, + sym__br_sgl_pln_int_blk = 77, + sym__b_sgl_pln_int_blk = 78, + sym__r_sgl_pln_int_flw = 79, + sym__br_sgl_pln_int_flw = 80, + sym__r_sgl_pln_flt_blk = 81, + sym__br_sgl_pln_flt_blk = 82, + sym__b_sgl_pln_flt_blk = 83, + sym__r_sgl_pln_flt_flw = 84, + sym__br_sgl_pln_flt_flw = 85, + sym__r_sgl_pln_tms_blk = 86, + sym__br_sgl_pln_tms_blk = 87, + sym__b_sgl_pln_tms_blk = 88, + sym__r_sgl_pln_tms_flw = 89, + sym__br_sgl_pln_tms_flw = 90, + sym__r_sgl_pln_str_blk = 91, + sym__br_sgl_pln_str_blk = 92, + sym__b_sgl_pln_str_blk = 93, + sym__r_sgl_pln_str_flw = 94, + sym__br_sgl_pln_str_flw = 95, + sym__r_mtl_pln_str_blk = 96, + sym__br_mtl_pln_str_blk = 97, + sym__r_mtl_pln_str_flw = 98, + sym__br_mtl_pln_str_flw = 99, + sym__r_tag = 100, + sym__br_tag = 101, + sym__b_tag = 102, + sym__r_acr_bgn = 103, + sym__br_acr_bgn = 104, + sym__b_acr_bgn = 105, + sym__r_acr_ctn = 106, + sym__r_als_bgn = 107, + sym__br_als_bgn = 108, + sym__b_als_bgn = 109, + sym__r_als_ctn = 110, + sym__bl = 111, + sym_comment = 112, + sym__err_rec = 113, + sym_stream = 114, + sym__doc_w_bgn_w_end_seq = 115, + sym__doc_w_bgn_wo_end_seq = 116, + sym__doc_wo_bgn_w_end_seq = 117, + sym__doc_wo_bgn_wo_end_seq = 118, + sym__doc_w_bgn_w_end = 119, + sym__doc_w_bgn_wo_end = 120, + sym__doc_wo_bgn_w_end = 121, + sym__doc_wo_bgn_wo_end = 122, + sym__bgn_imp_doc = 123, + sym__drs_doc = 124, + sym__exp_doc = 125, + sym__imp_doc = 126, + sym__drs_doc_end = 127, + sym__exp_doc_end = 128, + sym__imp_doc_end = 129, + sym__bgn_imp_doc_end = 130, + sym__doc_end = 131, + sym__exp_doc_tal = 132, + sym__s_dir = 133, + sym__s_dir_yml = 134, + sym__s_dir_tag = 135, + sym__s_dir_rsv = 136, + sym__r_prp_val = 137, + sym__br_prp_val = 138, + sym__r_sgl_prp_val = 139, + sym__br_sgl_prp_val = 140, + sym__b_sgl_prp_val = 141, + sym__r_prp = 142, + sym__br_prp = 143, + sym__r_sgl_prp = 144, + sym__br_sgl_prp = 145, + sym__b_sgl_prp = 146, + sym__r_blk_seq_r_val = 147, + sym__r_blk_seq_br_val = 148, + sym__br_blk_seq_val = 149, + sym__r_blk_seq_spc_val = 150, + sym__br_blk_seq_spc_val = 151, + sym__b_blk_seq_spc_val = 152, + sym__r_blk_seq = 153, + sym__br_blk_seq = 154, + sym__b_blk_seq_spc = 155, + sym__r_blk_seq_itm = 156, + sym__br_blk_seq_itm = 157, + sym__b_blk_seq_itm = 158, + sym__blk_seq_itm_tal = 159, + sym__r_blk_map_r_val = 160, + sym__r_blk_map_br_val = 161, + sym__br_blk_map_val = 162, + sym__r_blk_map = 163, + sym__br_blk_map = 164, + sym__r_blk_map_itm = 165, + sym__br_blk_map_itm = 166, + sym__b_blk_map_itm = 167, + sym__r_blk_exp_itm = 168, + sym__br_blk_exp_itm = 169, + sym__b_blk_exp_itm = 170, + sym__r_blk_key_itm = 171, + sym__br_blk_key_itm = 172, + sym__b_blk_key_itm = 173, + sym__r_blk_val_itm = 174, + sym__br_blk_val_itm = 175, + sym__b_blk_val_itm = 176, + sym__r_blk_imp_itm = 177, + sym__br_blk_imp_itm = 178, + sym__b_blk_imp_itm = 179, + sym__blk_exp_itm_tal = 180, + sym__blk_imp_itm_tal = 181, + sym__r_blk_str_val = 182, + sym__br_blk_str_val = 183, + sym__r_blk_str = 184, + sym__br_blk_str = 185, + sym__r_flw_seq_val = 186, + sym__br_flw_seq_val = 187, + sym__r_sgl_flw_seq_val = 188, + sym__br_sgl_flw_seq_val = 189, + sym__b_sgl_flw_seq_val = 190, + sym__r_flw_seq = 191, + sym__br_flw_seq = 192, + sym__r_sgl_flw_seq = 193, + sym__br_sgl_flw_seq = 194, + sym__b_sgl_flw_seq = 195, + sym__flw_seq_tal = 196, + sym__sgl_flw_seq_tal = 197, + sym__r_flw_map_val = 198, + sym__br_flw_map_val = 199, + sym__r_sgl_flw_map_val = 200, + sym__br_sgl_flw_map_val = 201, + sym__b_sgl_flw_map_val = 202, + sym__r_flw_map = 203, + sym__br_flw_map = 204, + sym__r_sgl_flw_map = 205, + sym__br_sgl_flw_map = 206, + sym__b_sgl_flw_map = 207, + sym__flw_map_tal = 208, + sym__sgl_flw_map_tal = 209, + sym__r_flw_seq_dat = 210, + sym__br_flw_seq_dat = 211, + sym__r_flw_map_dat = 212, + sym__br_flw_map_dat = 213, + sym__r_sgl_flw_col_dat = 214, + sym__flw_seq_dat_rpt = 215, + sym__flw_map_dat_rpt = 216, + sym__sgl_flw_col_dat_rpt = 217, + sym__r_flw_seq_itm = 218, + sym__br_flw_seq_itm = 219, + sym__r_flw_map_itm = 220, + sym__br_flw_map_itm = 221, + sym__r_sgl_flw_col_itm = 222, + sym__r_flw_exp_par = 223, + sym__br_flw_exp_par = 224, + sym__r_sgl_flw_exp_par = 225, + sym__r_flw_imp_r_par = 226, + sym__r_flw_imp_br_par = 227, + sym__br_flw_imp_r_par = 228, + sym__br_flw_imp_br_par = 229, + sym__r_sgl_flw_imp_par = 230, + sym__r_flw_jsl_ann_par = 231, + sym__br_flw_jsl_ann_par = 232, + sym__r_sgl_flw_jsl_ann_par = 233, + sym__r_flw_njl_ann_par = 234, + sym__br_flw_njl_ann_par = 235, + sym__r_sgl_flw_njl_ann_par = 236, + sym__flw_ann_par_tal = 237, + sym__sgl_flw_ann_par_tal = 238, + sym__r_dqt_str_val = 239, + sym__br_dqt_str_val = 240, + sym__r_sgl_dqt_str_val = 241, + sym__br_sgl_dqt_str_val = 242, + sym__b_sgl_dqt_str_val = 243, + sym__r_dqt_str = 244, + sym__br_dqt_str = 245, + sym__r_sgl_dqt_str = 246, + sym__br_sgl_dqt_str = 247, + sym__b_sgl_dqt_str = 248, + aux_sym__r_sgl_dqt_ctn = 249, + sym__br_mtl_dqt_ctn = 250, + sym__r_sqt_str_val = 251, + sym__br_sqt_str_val = 252, + sym__r_sgl_sqt_str_val = 253, + sym__br_sgl_sqt_str_val = 254, + sym__b_sgl_sqt_str_val = 255, + sym__r_sqt_str = 256, + sym__br_sqt_str = 257, + sym__r_sgl_sqt_str = 258, + sym__br_sgl_sqt_str = 259, + sym__b_sgl_sqt_str = 260, + aux_sym__r_sgl_sqt_ctn = 261, + sym__br_mtl_sqt_ctn = 262, + sym__r_pln_blk_val = 263, + sym__br_pln_blk_val = 264, + sym__r_sgl_pln_blk_val = 265, + sym__br_sgl_pln_blk_val = 266, + sym__b_sgl_pln_blk_val = 267, + sym__r_pln_flw_val = 268, + sym__br_pln_flw_val = 269, + sym__r_sgl_pln_flw_val = 270, + sym__r_sgl_pln_blk = 271, + sym__br_sgl_pln_blk = 272, + sym__b_sgl_pln_blk = 273, + sym__r_sgl_pln_flw = 274, + sym__br_sgl_pln_flw = 275, + sym__r_mtl_pln_blk = 276, + sym__br_mtl_pln_blk = 277, + sym__r_mtl_pln_flw = 278, + sym__br_mtl_pln_flw = 279, + sym__r_als_val = 280, + sym__br_als_val = 281, + sym__b_als_val = 282, + sym__r_als = 283, + sym__br_als = 284, + sym__b_als = 285, + sym__r_acr = 286, + sym__br_acr = 287, + sym__b_acr = 288, + aux_sym__drs_doc_repeat1 = 289, + aux_sym__s_dir_rsv_repeat1 = 290, + aux_sym__r_blk_seq_repeat1 = 291, + aux_sym__r_blk_map_repeat1 = 292, + aux_sym__r_blk_str_repeat1 = 293, + aux_sym__r_flw_seq_dat_repeat1 = 294, + aux_sym__r_flw_map_dat_repeat1 = 295, + aux_sym__r_sgl_flw_col_dat_repeat1 = 296, + aux_sym__r_dqt_str_repeat1 = 297, + aux_sym__br_mtl_dqt_ctn_repeat1 = 298, + aux_sym__r_sqt_str_repeat1 = 299, + aux_sym__br_mtl_sqt_ctn_repeat1 = 300, +}; + +static const char * const ts_symbol_names[] = { + [ts_builtin_sym_end] = "end", + [sym__eof] = "_eof", + [sym__s_dir_yml_bgn] = "_s_dir_yml_bgn", + [sym__r_dir_yml_ver] = "yaml_version", + [sym__s_dir_tag_bgn] = "_s_dir_tag_bgn", + [sym__r_dir_tag_hdl] = "tag_handle", + [sym__r_dir_tag_pfx] = "tag_prefix", + [sym__s_dir_rsv_bgn] = "directive_name", + [sym__r_dir_rsv_prm] = "directive_parameter", + [sym__s_drs_end] = "---", + [sym__s_doc_end] = "...", + [sym__r_blk_seq_bgn] = "-", + [sym__br_blk_seq_bgn] = "-", + [sym__b_blk_seq_bgn] = "-", + [sym__r_blk_key_bgn] = "\?", + [sym__br_blk_key_bgn] = "\?", + [sym__b_blk_key_bgn] = "\?", + [sym__r_blk_val_bgn] = ":", + [sym__br_blk_val_bgn] = ":", + [sym__b_blk_val_bgn] = ":", + [sym__r_blk_imp_bgn] = ":", + [sym__r_blk_lit_bgn] = "|", + [sym__br_blk_lit_bgn] = "|", + [sym__r_blk_fld_bgn] = ">", + [sym__br_blk_fld_bgn] = ">", + [sym__br_blk_str_ctn] = "_br_blk_str_ctn", + [sym__r_flw_seq_bgn] = "[", + [sym__br_flw_seq_bgn] = "[", + [sym__b_flw_seq_bgn] = "[", + [sym__r_flw_seq_end] = "]", + [sym__br_flw_seq_end] = "]", + [sym__b_flw_seq_end] = "]", + [sym__r_flw_map_bgn] = "{", + [sym__br_flw_map_bgn] = "{", + [sym__b_flw_map_bgn] = "{", + [sym__r_flw_map_end] = "}", + [sym__br_flw_map_end] = "}", + [sym__b_flw_map_end] = "}", + [sym__r_flw_sep_bgn] = ",", + [sym__br_flw_sep_bgn] = ",", + [sym__r_flw_key_bgn] = "\?", + [sym__br_flw_key_bgn] = "\?", + [sym__r_flw_jsv_bgn] = ":", + [sym__br_flw_jsv_bgn] = ":", + [sym__r_flw_njv_bgn] = ":", + [sym__br_flw_njv_bgn] = ":", + [sym__r_dqt_str_bgn] = "\"", + [sym__br_dqt_str_bgn] = "\"", + [sym__b_dqt_str_bgn] = "\"", + [sym__r_dqt_str_ctn] = "_r_dqt_str_ctn", + [sym__br_dqt_str_ctn] = "_br_dqt_str_ctn", + [sym__r_dqt_esc_nwl] = "escape_sequence", + [sym__br_dqt_esc_nwl] = "escape_sequence", + [sym__r_dqt_esc_seq] = "escape_sequence", + [sym__br_dqt_esc_seq] = "escape_sequence", + [sym__r_dqt_str_end] = "\"", + [sym__br_dqt_str_end] = "\"", + [sym__r_sqt_str_bgn] = "'", + [sym__br_sqt_str_bgn] = "'", + [sym__b_sqt_str_bgn] = "'", + [sym__r_sqt_str_ctn] = "_r_sqt_str_ctn", + [sym__br_sqt_str_ctn] = "_br_sqt_str_ctn", + [sym__r_sqt_esc_sqt] = "escape_sequence", + [sym__br_sqt_esc_sqt] = "escape_sequence", + [sym__r_sqt_str_end] = "'", + [sym__br_sqt_str_end] = "'", + [sym__r_sgl_pln_nul_blk] = "null_scalar", + [sym__br_sgl_pln_nul_blk] = "null_scalar", + [sym__b_sgl_pln_nul_blk] = "null_scalar", + [sym__r_sgl_pln_nul_flw] = "null_scalar", + [sym__br_sgl_pln_nul_flw] = "null_scalar", + [sym__r_sgl_pln_bol_blk] = "boolean_scalar", + [sym__br_sgl_pln_bol_blk] = "boolean_scalar", + [sym__b_sgl_pln_bol_blk] = "boolean_scalar", + [sym__r_sgl_pln_bol_flw] = "boolean_scalar", + [sym__br_sgl_pln_bol_flw] = "boolean_scalar", + [sym__r_sgl_pln_int_blk] = "integer_scalar", + [sym__br_sgl_pln_int_blk] = "integer_scalar", + [sym__b_sgl_pln_int_blk] = "integer_scalar", + [sym__r_sgl_pln_int_flw] = "integer_scalar", + [sym__br_sgl_pln_int_flw] = "integer_scalar", + [sym__r_sgl_pln_flt_blk] = "float_scalar", + [sym__br_sgl_pln_flt_blk] = "float_scalar", + [sym__b_sgl_pln_flt_blk] = "float_scalar", + [sym__r_sgl_pln_flt_flw] = "float_scalar", + [sym__br_sgl_pln_flt_flw] = "float_scalar", + [sym__r_sgl_pln_tms_blk] = "timestamp_scalar", + [sym__br_sgl_pln_tms_blk] = "timestamp_scalar", + [sym__b_sgl_pln_tms_blk] = "timestamp_scalar", + [sym__r_sgl_pln_tms_flw] = "timestamp_scalar", + [sym__br_sgl_pln_tms_flw] = "timestamp_scalar", + [sym__r_sgl_pln_str_blk] = "string_scalar", + [sym__br_sgl_pln_str_blk] = "string_scalar", + [sym__b_sgl_pln_str_blk] = "string_scalar", + [sym__r_sgl_pln_str_flw] = "string_scalar", + [sym__br_sgl_pln_str_flw] = "string_scalar", + [sym__r_mtl_pln_str_blk] = "string_scalar", + [sym__br_mtl_pln_str_blk] = "string_scalar", + [sym__r_mtl_pln_str_flw] = "string_scalar", + [sym__br_mtl_pln_str_flw] = "string_scalar", + [sym__r_tag] = "tag", + [sym__br_tag] = "tag", + [sym__b_tag] = "tag", + [sym__r_acr_bgn] = "&", + [sym__br_acr_bgn] = "&", + [sym__b_acr_bgn] = "&", + [sym__r_acr_ctn] = "anchor_name", + [sym__r_als_bgn] = "*", + [sym__br_als_bgn] = "*", + [sym__b_als_bgn] = "*", + [sym__r_als_ctn] = "alias_name", + [sym__bl] = "_bl", + [sym_comment] = "comment", + [sym__err_rec] = "_err_rec", + [sym_stream] = "stream", + [sym__doc_w_bgn_w_end_seq] = "_doc_w_bgn_w_end_seq", + [sym__doc_w_bgn_wo_end_seq] = "_doc_w_bgn_wo_end_seq", + [sym__doc_wo_bgn_w_end_seq] = "_doc_wo_bgn_w_end_seq", + [sym__doc_wo_bgn_wo_end_seq] = "_doc_wo_bgn_wo_end_seq", + [sym__doc_w_bgn_w_end] = "_doc_w_bgn_w_end", + [sym__doc_w_bgn_wo_end] = "_doc_w_bgn_wo_end", + [sym__doc_wo_bgn_w_end] = "_doc_wo_bgn_w_end", + [sym__doc_wo_bgn_wo_end] = "_doc_wo_bgn_wo_end", + [sym__bgn_imp_doc] = "_bgn_imp_doc", + [sym__drs_doc] = "_drs_doc", + [sym__exp_doc] = "_exp_doc", + [sym__imp_doc] = "_imp_doc", + [sym__drs_doc_end] = "document", + [sym__exp_doc_end] = "document", + [sym__imp_doc_end] = "document", + [sym__bgn_imp_doc_end] = "document", + [sym__doc_end] = "document", + [sym__exp_doc_tal] = "_exp_doc_tal", + [sym__s_dir] = "_s_dir", + [sym__s_dir_yml] = "yaml_directive", + [sym__s_dir_tag] = "tag_directive", + [sym__s_dir_rsv] = "reserved_directive", + [sym__r_prp_val] = "flow_node", + [sym__br_prp_val] = "flow_node", + [sym__r_sgl_prp_val] = "flow_node", + [sym__br_sgl_prp_val] = "flow_node", + [sym__b_sgl_prp_val] = "flow_node", + [sym__r_prp] = "_r_prp", + [sym__br_prp] = "_br_prp", + [sym__r_sgl_prp] = "_r_sgl_prp", + [sym__br_sgl_prp] = "_br_sgl_prp", + [sym__b_sgl_prp] = "_b_sgl_prp", + [sym__r_blk_seq_r_val] = "block_node", + [sym__r_blk_seq_br_val] = "block_node", + [sym__br_blk_seq_val] = "block_node", + [sym__r_blk_seq_spc_val] = "block_node", + [sym__br_blk_seq_spc_val] = "block_node", + [sym__b_blk_seq_spc_val] = "block_node", + [sym__r_blk_seq] = "block_sequence", + [sym__br_blk_seq] = "block_sequence", + [sym__b_blk_seq_spc] = "block_sequence", + [sym__r_blk_seq_itm] = "block_sequence_item", + [sym__br_blk_seq_itm] = "block_sequence_item", + [sym__b_blk_seq_itm] = "block_sequence_item", + [sym__blk_seq_itm_tal] = "_blk_seq_itm_tal", + [sym__r_blk_map_r_val] = "block_node", + [sym__r_blk_map_br_val] = "block_node", + [sym__br_blk_map_val] = "block_node", + [sym__r_blk_map] = "block_mapping", + [sym__br_blk_map] = "block_mapping", + [sym__r_blk_map_itm] = "_r_blk_map_itm", + [sym__br_blk_map_itm] = "_br_blk_map_itm", + [sym__b_blk_map_itm] = "_b_blk_map_itm", + [sym__r_blk_exp_itm] = "block_mapping_pair", + [sym__br_blk_exp_itm] = "block_mapping_pair", + [sym__b_blk_exp_itm] = "block_mapping_pair", + [sym__r_blk_key_itm] = "_r_blk_key_itm", + [sym__br_blk_key_itm] = "_br_blk_key_itm", + [sym__b_blk_key_itm] = "_b_blk_key_itm", + [sym__r_blk_val_itm] = "_r_blk_val_itm", + [sym__br_blk_val_itm] = "_br_blk_val_itm", + [sym__b_blk_val_itm] = "_b_blk_val_itm", + [sym__r_blk_imp_itm] = "block_mapping_pair", + [sym__br_blk_imp_itm] = "block_mapping_pair", + [sym__b_blk_imp_itm] = "block_mapping_pair", + [sym__blk_exp_itm_tal] = "_blk_exp_itm_tal", + [sym__blk_imp_itm_tal] = "_blk_imp_itm_tal", + [sym__r_blk_str_val] = "block_node", + [sym__br_blk_str_val] = "block_node", + [sym__r_blk_str] = "block_scalar", + [sym__br_blk_str] = "block_scalar", + [sym__r_flw_seq_val] = "flow_node", + [sym__br_flw_seq_val] = "flow_node", + [sym__r_sgl_flw_seq_val] = "flow_node", + [sym__br_sgl_flw_seq_val] = "flow_node", + [sym__b_sgl_flw_seq_val] = "flow_node", + [sym__r_flw_seq] = "flow_sequence", + [sym__br_flw_seq] = "flow_sequence", + [sym__r_sgl_flw_seq] = "flow_sequence", + [sym__br_sgl_flw_seq] = "flow_sequence", + [sym__b_sgl_flw_seq] = "flow_sequence", + [sym__flw_seq_tal] = "_flw_seq_tal", + [sym__sgl_flw_seq_tal] = "_sgl_flw_seq_tal", + [sym__r_flw_map_val] = "flow_node", + [sym__br_flw_map_val] = "flow_node", + [sym__r_sgl_flw_map_val] = "flow_node", + [sym__br_sgl_flw_map_val] = "flow_node", + [sym__b_sgl_flw_map_val] = "flow_node", + [sym__r_flw_map] = "flow_mapping", + [sym__br_flw_map] = "flow_mapping", + [sym__r_sgl_flw_map] = "flow_mapping", + [sym__br_sgl_flw_map] = "flow_mapping", + [sym__b_sgl_flw_map] = "flow_mapping", + [sym__flw_map_tal] = "_flw_map_tal", + [sym__sgl_flw_map_tal] = "_sgl_flw_map_tal", + [sym__r_flw_seq_dat] = "_r_flw_seq_dat", + [sym__br_flw_seq_dat] = "_br_flw_seq_dat", + [sym__r_flw_map_dat] = "_r_flw_map_dat", + [sym__br_flw_map_dat] = "_br_flw_map_dat", + [sym__r_sgl_flw_col_dat] = "_r_sgl_flw_col_dat", + [sym__flw_seq_dat_rpt] = "_flw_seq_dat_rpt", + [sym__flw_map_dat_rpt] = "_flw_map_dat_rpt", + [sym__sgl_flw_col_dat_rpt] = "_sgl_flw_col_dat_rpt", + [sym__r_flw_seq_itm] = "_r_flw_seq_itm", + [sym__br_flw_seq_itm] = "_br_flw_seq_itm", + [sym__r_flw_map_itm] = "_r_flw_map_itm", + [sym__br_flw_map_itm] = "_br_flw_map_itm", + [sym__r_sgl_flw_col_itm] = "_r_sgl_flw_col_itm", + [sym__r_flw_exp_par] = "flow_pair", + [sym__br_flw_exp_par] = "flow_pair", + [sym__r_sgl_flw_exp_par] = "flow_pair", + [sym__r_flw_imp_r_par] = "_r_flw_imp_r_par", + [sym__r_flw_imp_br_par] = "_r_flw_imp_br_par", + [sym__br_flw_imp_r_par] = "_br_flw_imp_r_par", + [sym__br_flw_imp_br_par] = "_br_flw_imp_br_par", + [sym__r_sgl_flw_imp_par] = "_r_sgl_flw_imp_par", + [sym__r_flw_jsl_ann_par] = "_r_flw_jsl_ann_par", + [sym__br_flw_jsl_ann_par] = "_br_flw_jsl_ann_par", + [sym__r_sgl_flw_jsl_ann_par] = "_r_sgl_flw_jsl_ann_par", + [sym__r_flw_njl_ann_par] = "_r_flw_njl_ann_par", + [sym__br_flw_njl_ann_par] = "_br_flw_njl_ann_par", + [sym__r_sgl_flw_njl_ann_par] = "_r_sgl_flw_njl_ann_par", + [sym__flw_ann_par_tal] = "_flw_ann_par_tal", + [sym__sgl_flw_ann_par_tal] = "_sgl_flw_ann_par_tal", + [sym__r_dqt_str_val] = "flow_node", + [sym__br_dqt_str_val] = "flow_node", + [sym__r_sgl_dqt_str_val] = "flow_node", + [sym__br_sgl_dqt_str_val] = "flow_node", + [sym__b_sgl_dqt_str_val] = "flow_node", + [sym__r_dqt_str] = "double_quote_scalar", + [sym__br_dqt_str] = "double_quote_scalar", + [sym__r_sgl_dqt_str] = "double_quote_scalar", + [sym__br_sgl_dqt_str] = "double_quote_scalar", + [sym__b_sgl_dqt_str] = "double_quote_scalar", + [aux_sym__r_sgl_dqt_ctn] = "_r_sgl_dqt_ctn", + [sym__br_mtl_dqt_ctn] = "_br_mtl_dqt_ctn", + [sym__r_sqt_str_val] = "flow_node", + [sym__br_sqt_str_val] = "flow_node", + [sym__r_sgl_sqt_str_val] = "flow_node", + [sym__br_sgl_sqt_str_val] = "flow_node", + [sym__b_sgl_sqt_str_val] = "flow_node", + [sym__r_sqt_str] = "single_quote_scalar", + [sym__br_sqt_str] = "single_quote_scalar", + [sym__r_sgl_sqt_str] = "single_quote_scalar", + [sym__br_sgl_sqt_str] = "single_quote_scalar", + [sym__b_sgl_sqt_str] = "single_quote_scalar", + [aux_sym__r_sgl_sqt_ctn] = "_r_sgl_sqt_ctn", + [sym__br_mtl_sqt_ctn] = "_br_mtl_sqt_ctn", + [sym__r_pln_blk_val] = "flow_node", + [sym__br_pln_blk_val] = "flow_node", + [sym__r_sgl_pln_blk_val] = "flow_node", + [sym__br_sgl_pln_blk_val] = "flow_node", + [sym__b_sgl_pln_blk_val] = "flow_node", + [sym__r_pln_flw_val] = "flow_node", + [sym__br_pln_flw_val] = "flow_node", + [sym__r_sgl_pln_flw_val] = "flow_node", + [sym__r_sgl_pln_blk] = "plain_scalar", + [sym__br_sgl_pln_blk] = "plain_scalar", + [sym__b_sgl_pln_blk] = "plain_scalar", + [sym__r_sgl_pln_flw] = "plain_scalar", + [sym__br_sgl_pln_flw] = "plain_scalar", + [sym__r_mtl_pln_blk] = "plain_scalar", + [sym__br_mtl_pln_blk] = "plain_scalar", + [sym__r_mtl_pln_flw] = "plain_scalar", + [sym__br_mtl_pln_flw] = "plain_scalar", + [sym__r_als_val] = "flow_node", + [sym__br_als_val] = "flow_node", + [sym__b_als_val] = "flow_node", + [sym__r_als] = "alias", + [sym__br_als] = "alias", + [sym__b_als] = "alias", + [sym__r_acr] = "anchor", + [sym__br_acr] = "anchor", + [sym__b_acr] = "anchor", + [aux_sym__drs_doc_repeat1] = "_drs_doc_repeat1", + [aux_sym__s_dir_rsv_repeat1] = "_s_dir_rsv_repeat1", + [aux_sym__r_blk_seq_repeat1] = "_r_blk_seq_repeat1", + [aux_sym__r_blk_map_repeat1] = "_r_blk_map_repeat1", + [aux_sym__r_blk_str_repeat1] = "_r_blk_str_repeat1", + [aux_sym__r_flw_seq_dat_repeat1] = "_r_flw_seq_dat_repeat1", + [aux_sym__r_flw_map_dat_repeat1] = "_r_flw_map_dat_repeat1", + [aux_sym__r_sgl_flw_col_dat_repeat1] = "_r_sgl_flw_col_dat_repeat1", + [aux_sym__r_dqt_str_repeat1] = "_r_dqt_str_repeat1", + [aux_sym__br_mtl_dqt_ctn_repeat1] = "_br_mtl_dqt_ctn_repeat1", + [aux_sym__r_sqt_str_repeat1] = "_r_sqt_str_repeat1", + [aux_sym__br_mtl_sqt_ctn_repeat1] = "_br_mtl_sqt_ctn_repeat1", +}; + +static const TSSymbol ts_symbol_map[] = { + [ts_builtin_sym_end] = ts_builtin_sym_end, + [sym__eof] = sym__eof, + [sym__s_dir_yml_bgn] = sym__s_dir_yml_bgn, + [sym__r_dir_yml_ver] = sym__r_dir_yml_ver, + [sym__s_dir_tag_bgn] = sym__s_dir_tag_bgn, + [sym__r_dir_tag_hdl] = sym__r_dir_tag_hdl, + [sym__r_dir_tag_pfx] = sym__r_dir_tag_pfx, + [sym__s_dir_rsv_bgn] = sym__s_dir_rsv_bgn, + [sym__r_dir_rsv_prm] = sym__r_dir_rsv_prm, + [sym__s_drs_end] = sym__s_drs_end, + [sym__s_doc_end] = sym__s_doc_end, + [sym__r_blk_seq_bgn] = sym__r_blk_seq_bgn, + [sym__br_blk_seq_bgn] = sym__r_blk_seq_bgn, + [sym__b_blk_seq_bgn] = sym__r_blk_seq_bgn, + [sym__r_blk_key_bgn] = sym__r_blk_key_bgn, + [sym__br_blk_key_bgn] = sym__r_blk_key_bgn, + [sym__b_blk_key_bgn] = sym__r_blk_key_bgn, + [sym__r_blk_val_bgn] = sym__r_blk_val_bgn, + [sym__br_blk_val_bgn] = sym__r_blk_val_bgn, + [sym__b_blk_val_bgn] = sym__r_blk_val_bgn, + [sym__r_blk_imp_bgn] = sym__r_blk_val_bgn, + [sym__r_blk_lit_bgn] = sym__r_blk_lit_bgn, + [sym__br_blk_lit_bgn] = sym__r_blk_lit_bgn, + [sym__r_blk_fld_bgn] = sym__r_blk_fld_bgn, + [sym__br_blk_fld_bgn] = sym__r_blk_fld_bgn, + [sym__br_blk_str_ctn] = sym__br_blk_str_ctn, + [sym__r_flw_seq_bgn] = sym__r_flw_seq_bgn, + [sym__br_flw_seq_bgn] = sym__r_flw_seq_bgn, + [sym__b_flw_seq_bgn] = sym__r_flw_seq_bgn, + [sym__r_flw_seq_end] = sym__r_flw_seq_end, + [sym__br_flw_seq_end] = sym__r_flw_seq_end, + [sym__b_flw_seq_end] = sym__r_flw_seq_end, + [sym__r_flw_map_bgn] = sym__r_flw_map_bgn, + [sym__br_flw_map_bgn] = sym__r_flw_map_bgn, + [sym__b_flw_map_bgn] = sym__r_flw_map_bgn, + [sym__r_flw_map_end] = sym__r_flw_map_end, + [sym__br_flw_map_end] = sym__r_flw_map_end, + [sym__b_flw_map_end] = sym__r_flw_map_end, + [sym__r_flw_sep_bgn] = sym__r_flw_sep_bgn, + [sym__br_flw_sep_bgn] = sym__r_flw_sep_bgn, + [sym__r_flw_key_bgn] = sym__r_blk_key_bgn, + [sym__br_flw_key_bgn] = sym__r_blk_key_bgn, + [sym__r_flw_jsv_bgn] = sym__r_blk_val_bgn, + [sym__br_flw_jsv_bgn] = sym__r_blk_val_bgn, + [sym__r_flw_njv_bgn] = sym__r_blk_val_bgn, + [sym__br_flw_njv_bgn] = sym__r_blk_val_bgn, + [sym__r_dqt_str_bgn] = sym__r_dqt_str_bgn, + [sym__br_dqt_str_bgn] = sym__r_dqt_str_bgn, + [sym__b_dqt_str_bgn] = sym__r_dqt_str_bgn, + [sym__r_dqt_str_ctn] = sym__r_dqt_str_ctn, + [sym__br_dqt_str_ctn] = sym__br_dqt_str_ctn, + [sym__r_dqt_esc_nwl] = sym__r_dqt_esc_nwl, + [sym__br_dqt_esc_nwl] = sym__r_dqt_esc_nwl, + [sym__r_dqt_esc_seq] = sym__r_dqt_esc_nwl, + [sym__br_dqt_esc_seq] = sym__r_dqt_esc_nwl, + [sym__r_dqt_str_end] = sym__r_dqt_str_bgn, + [sym__br_dqt_str_end] = sym__r_dqt_str_bgn, + [sym__r_sqt_str_bgn] = sym__r_sqt_str_bgn, + [sym__br_sqt_str_bgn] = sym__r_sqt_str_bgn, + [sym__b_sqt_str_bgn] = sym__r_sqt_str_bgn, + [sym__r_sqt_str_ctn] = sym__r_sqt_str_ctn, + [sym__br_sqt_str_ctn] = sym__br_sqt_str_ctn, + [sym__r_sqt_esc_sqt] = sym__r_dqt_esc_nwl, + [sym__br_sqt_esc_sqt] = sym__r_dqt_esc_nwl, + [sym__r_sqt_str_end] = sym__r_sqt_str_bgn, + [sym__br_sqt_str_end] = sym__r_sqt_str_bgn, + [sym__r_sgl_pln_nul_blk] = sym__r_sgl_pln_nul_blk, + [sym__br_sgl_pln_nul_blk] = sym__r_sgl_pln_nul_blk, + [sym__b_sgl_pln_nul_blk] = sym__r_sgl_pln_nul_blk, + [sym__r_sgl_pln_nul_flw] = sym__r_sgl_pln_nul_blk, + [sym__br_sgl_pln_nul_flw] = sym__r_sgl_pln_nul_blk, + [sym__r_sgl_pln_bol_blk] = sym__r_sgl_pln_bol_blk, + [sym__br_sgl_pln_bol_blk] = sym__r_sgl_pln_bol_blk, + [sym__b_sgl_pln_bol_blk] = sym__r_sgl_pln_bol_blk, + [sym__r_sgl_pln_bol_flw] = sym__r_sgl_pln_bol_blk, + [sym__br_sgl_pln_bol_flw] = sym__r_sgl_pln_bol_blk, + [sym__r_sgl_pln_int_blk] = sym__r_sgl_pln_int_blk, + [sym__br_sgl_pln_int_blk] = sym__r_sgl_pln_int_blk, + [sym__b_sgl_pln_int_blk] = sym__r_sgl_pln_int_blk, + [sym__r_sgl_pln_int_flw] = sym__r_sgl_pln_int_blk, + [sym__br_sgl_pln_int_flw] = sym__r_sgl_pln_int_blk, + [sym__r_sgl_pln_flt_blk] = sym__r_sgl_pln_flt_blk, + [sym__br_sgl_pln_flt_blk] = sym__r_sgl_pln_flt_blk, + [sym__b_sgl_pln_flt_blk] = sym__r_sgl_pln_flt_blk, + [sym__r_sgl_pln_flt_flw] = sym__r_sgl_pln_flt_blk, + [sym__br_sgl_pln_flt_flw] = sym__r_sgl_pln_flt_blk, + [sym__r_sgl_pln_tms_blk] = sym__r_sgl_pln_tms_blk, + [sym__br_sgl_pln_tms_blk] = sym__r_sgl_pln_tms_blk, + [sym__b_sgl_pln_tms_blk] = sym__r_sgl_pln_tms_blk, + [sym__r_sgl_pln_tms_flw] = sym__r_sgl_pln_tms_blk, + [sym__br_sgl_pln_tms_flw] = sym__r_sgl_pln_tms_blk, + [sym__r_sgl_pln_str_blk] = sym__r_sgl_pln_str_blk, + [sym__br_sgl_pln_str_blk] = sym__r_sgl_pln_str_blk, + [sym__b_sgl_pln_str_blk] = sym__r_sgl_pln_str_blk, + [sym__r_sgl_pln_str_flw] = sym__r_sgl_pln_str_blk, + [sym__br_sgl_pln_str_flw] = sym__r_sgl_pln_str_blk, + [sym__r_mtl_pln_str_blk] = sym__r_sgl_pln_str_blk, + [sym__br_mtl_pln_str_blk] = sym__r_sgl_pln_str_blk, + [sym__r_mtl_pln_str_flw] = sym__r_sgl_pln_str_blk, + [sym__br_mtl_pln_str_flw] = sym__r_sgl_pln_str_blk, + [sym__r_tag] = sym__r_tag, + [sym__br_tag] = sym__r_tag, + [sym__b_tag] = sym__r_tag, + [sym__r_acr_bgn] = sym__r_acr_bgn, + [sym__br_acr_bgn] = sym__r_acr_bgn, + [sym__b_acr_bgn] = sym__r_acr_bgn, + [sym__r_acr_ctn] = sym__r_acr_ctn, + [sym__r_als_bgn] = sym__r_als_bgn, + [sym__br_als_bgn] = sym__r_als_bgn, + [sym__b_als_bgn] = sym__r_als_bgn, + [sym__r_als_ctn] = sym__r_als_ctn, + [sym__bl] = sym__bl, + [sym_comment] = sym_comment, + [sym__err_rec] = sym__err_rec, + [sym_stream] = sym_stream, + [sym__doc_w_bgn_w_end_seq] = sym__doc_w_bgn_w_end_seq, + [sym__doc_w_bgn_wo_end_seq] = sym__doc_w_bgn_wo_end_seq, + [sym__doc_wo_bgn_w_end_seq] = sym__doc_wo_bgn_w_end_seq, + [sym__doc_wo_bgn_wo_end_seq] = sym__doc_wo_bgn_wo_end_seq, + [sym__doc_w_bgn_w_end] = sym__doc_w_bgn_w_end, + [sym__doc_w_bgn_wo_end] = sym__doc_w_bgn_wo_end, + [sym__doc_wo_bgn_w_end] = sym__doc_wo_bgn_w_end, + [sym__doc_wo_bgn_wo_end] = sym__doc_wo_bgn_wo_end, + [sym__bgn_imp_doc] = sym__bgn_imp_doc, + [sym__drs_doc] = sym__drs_doc, + [sym__exp_doc] = sym__exp_doc, + [sym__imp_doc] = sym__imp_doc, + [sym__drs_doc_end] = sym__drs_doc_end, + [sym__exp_doc_end] = sym__drs_doc_end, + [sym__imp_doc_end] = sym__drs_doc_end, + [sym__bgn_imp_doc_end] = sym__drs_doc_end, + [sym__doc_end] = sym__drs_doc_end, + [sym__exp_doc_tal] = sym__exp_doc_tal, + [sym__s_dir] = sym__s_dir, + [sym__s_dir_yml] = sym__s_dir_yml, + [sym__s_dir_tag] = sym__s_dir_tag, + [sym__s_dir_rsv] = sym__s_dir_rsv, + [sym__r_prp_val] = sym__r_prp_val, + [sym__br_prp_val] = sym__r_prp_val, + [sym__r_sgl_prp_val] = sym__r_prp_val, + [sym__br_sgl_prp_val] = sym__r_prp_val, + [sym__b_sgl_prp_val] = sym__r_prp_val, + [sym__r_prp] = sym__r_prp, + [sym__br_prp] = sym__br_prp, + [sym__r_sgl_prp] = sym__r_sgl_prp, + [sym__br_sgl_prp] = sym__br_sgl_prp, + [sym__b_sgl_prp] = sym__b_sgl_prp, + [sym__r_blk_seq_r_val] = sym__r_blk_seq_r_val, + [sym__r_blk_seq_br_val] = sym__r_blk_seq_r_val, + [sym__br_blk_seq_val] = sym__r_blk_seq_r_val, + [sym__r_blk_seq_spc_val] = sym__r_blk_seq_r_val, + [sym__br_blk_seq_spc_val] = sym__r_blk_seq_r_val, + [sym__b_blk_seq_spc_val] = sym__r_blk_seq_r_val, + [sym__r_blk_seq] = sym__r_blk_seq, + [sym__br_blk_seq] = sym__r_blk_seq, + [sym__b_blk_seq_spc] = sym__r_blk_seq, + [sym__r_blk_seq_itm] = sym__r_blk_seq_itm, + [sym__br_blk_seq_itm] = sym__r_blk_seq_itm, + [sym__b_blk_seq_itm] = sym__r_blk_seq_itm, + [sym__blk_seq_itm_tal] = sym__blk_seq_itm_tal, + [sym__r_blk_map_r_val] = sym__r_blk_seq_r_val, + [sym__r_blk_map_br_val] = sym__r_blk_seq_r_val, + [sym__br_blk_map_val] = sym__r_blk_seq_r_val, + [sym__r_blk_map] = sym__r_blk_map, + [sym__br_blk_map] = sym__r_blk_map, + [sym__r_blk_map_itm] = sym__r_blk_map_itm, + [sym__br_blk_map_itm] = sym__br_blk_map_itm, + [sym__b_blk_map_itm] = sym__b_blk_map_itm, + [sym__r_blk_exp_itm] = sym__r_blk_exp_itm, + [sym__br_blk_exp_itm] = sym__r_blk_exp_itm, + [sym__b_blk_exp_itm] = sym__r_blk_exp_itm, + [sym__r_blk_key_itm] = sym__r_blk_key_itm, + [sym__br_blk_key_itm] = sym__br_blk_key_itm, + [sym__b_blk_key_itm] = sym__b_blk_key_itm, + [sym__r_blk_val_itm] = sym__r_blk_val_itm, + [sym__br_blk_val_itm] = sym__br_blk_val_itm, + [sym__b_blk_val_itm] = sym__b_blk_val_itm, + [sym__r_blk_imp_itm] = sym__r_blk_exp_itm, + [sym__br_blk_imp_itm] = sym__r_blk_exp_itm, + [sym__b_blk_imp_itm] = sym__r_blk_exp_itm, + [sym__blk_exp_itm_tal] = sym__blk_exp_itm_tal, + [sym__blk_imp_itm_tal] = sym__blk_imp_itm_tal, + [sym__r_blk_str_val] = sym__r_blk_seq_r_val, + [sym__br_blk_str_val] = sym__r_blk_seq_r_val, + [sym__r_blk_str] = sym__r_blk_str, + [sym__br_blk_str] = sym__r_blk_str, + [sym__r_flw_seq_val] = sym__r_prp_val, + [sym__br_flw_seq_val] = sym__r_prp_val, + [sym__r_sgl_flw_seq_val] = sym__r_prp_val, + [sym__br_sgl_flw_seq_val] = sym__r_prp_val, + [sym__b_sgl_flw_seq_val] = sym__r_prp_val, + [sym__r_flw_seq] = sym__r_flw_seq, + [sym__br_flw_seq] = sym__r_flw_seq, + [sym__r_sgl_flw_seq] = sym__r_flw_seq, + [sym__br_sgl_flw_seq] = sym__r_flw_seq, + [sym__b_sgl_flw_seq] = sym__r_flw_seq, + [sym__flw_seq_tal] = sym__flw_seq_tal, + [sym__sgl_flw_seq_tal] = sym__sgl_flw_seq_tal, + [sym__r_flw_map_val] = sym__r_prp_val, + [sym__br_flw_map_val] = sym__r_prp_val, + [sym__r_sgl_flw_map_val] = sym__r_prp_val, + [sym__br_sgl_flw_map_val] = sym__r_prp_val, + [sym__b_sgl_flw_map_val] = sym__r_prp_val, + [sym__r_flw_map] = sym__r_flw_map, + [sym__br_flw_map] = sym__r_flw_map, + [sym__r_sgl_flw_map] = sym__r_flw_map, + [sym__br_sgl_flw_map] = sym__r_flw_map, + [sym__b_sgl_flw_map] = sym__r_flw_map, + [sym__flw_map_tal] = sym__flw_map_tal, + [sym__sgl_flw_map_tal] = sym__sgl_flw_map_tal, + [sym__r_flw_seq_dat] = sym__r_flw_seq_dat, + [sym__br_flw_seq_dat] = sym__br_flw_seq_dat, + [sym__r_flw_map_dat] = sym__r_flw_map_dat, + [sym__br_flw_map_dat] = sym__br_flw_map_dat, + [sym__r_sgl_flw_col_dat] = sym__r_sgl_flw_col_dat, + [sym__flw_seq_dat_rpt] = sym__flw_seq_dat_rpt, + [sym__flw_map_dat_rpt] = sym__flw_map_dat_rpt, + [sym__sgl_flw_col_dat_rpt] = sym__sgl_flw_col_dat_rpt, + [sym__r_flw_seq_itm] = sym__r_flw_seq_itm, + [sym__br_flw_seq_itm] = sym__br_flw_seq_itm, + [sym__r_flw_map_itm] = sym__r_flw_map_itm, + [sym__br_flw_map_itm] = sym__br_flw_map_itm, + [sym__r_sgl_flw_col_itm] = sym__r_sgl_flw_col_itm, + [sym__r_flw_exp_par] = sym__r_flw_exp_par, + [sym__br_flw_exp_par] = sym__r_flw_exp_par, + [sym__r_sgl_flw_exp_par] = sym__r_flw_exp_par, + [sym__r_flw_imp_r_par] = sym__r_flw_imp_r_par, + [sym__r_flw_imp_br_par] = sym__r_flw_imp_br_par, + [sym__br_flw_imp_r_par] = sym__br_flw_imp_r_par, + [sym__br_flw_imp_br_par] = sym__br_flw_imp_br_par, + [sym__r_sgl_flw_imp_par] = sym__r_sgl_flw_imp_par, + [sym__r_flw_jsl_ann_par] = sym__r_flw_jsl_ann_par, + [sym__br_flw_jsl_ann_par] = sym__br_flw_jsl_ann_par, + [sym__r_sgl_flw_jsl_ann_par] = sym__r_sgl_flw_jsl_ann_par, + [sym__r_flw_njl_ann_par] = sym__r_flw_njl_ann_par, + [sym__br_flw_njl_ann_par] = sym__br_flw_njl_ann_par, + [sym__r_sgl_flw_njl_ann_par] = sym__r_sgl_flw_njl_ann_par, + [sym__flw_ann_par_tal] = sym__flw_ann_par_tal, + [sym__sgl_flw_ann_par_tal] = sym__sgl_flw_ann_par_tal, + [sym__r_dqt_str_val] = sym__r_prp_val, + [sym__br_dqt_str_val] = sym__r_prp_val, + [sym__r_sgl_dqt_str_val] = sym__r_prp_val, + [sym__br_sgl_dqt_str_val] = sym__r_prp_val, + [sym__b_sgl_dqt_str_val] = sym__r_prp_val, + [sym__r_dqt_str] = sym__r_dqt_str, + [sym__br_dqt_str] = sym__r_dqt_str, + [sym__r_sgl_dqt_str] = sym__r_dqt_str, + [sym__br_sgl_dqt_str] = sym__r_dqt_str, + [sym__b_sgl_dqt_str] = sym__r_dqt_str, + [aux_sym__r_sgl_dqt_ctn] = aux_sym__r_sgl_dqt_ctn, + [sym__br_mtl_dqt_ctn] = sym__br_mtl_dqt_ctn, + [sym__r_sqt_str_val] = sym__r_prp_val, + [sym__br_sqt_str_val] = sym__r_prp_val, + [sym__r_sgl_sqt_str_val] = sym__r_prp_val, + [sym__br_sgl_sqt_str_val] = sym__r_prp_val, + [sym__b_sgl_sqt_str_val] = sym__r_prp_val, + [sym__r_sqt_str] = sym__r_sqt_str, + [sym__br_sqt_str] = sym__r_sqt_str, + [sym__r_sgl_sqt_str] = sym__r_sqt_str, + [sym__br_sgl_sqt_str] = sym__r_sqt_str, + [sym__b_sgl_sqt_str] = sym__r_sqt_str, + [aux_sym__r_sgl_sqt_ctn] = aux_sym__r_sgl_sqt_ctn, + [sym__br_mtl_sqt_ctn] = sym__br_mtl_sqt_ctn, + [sym__r_pln_blk_val] = sym__r_prp_val, + [sym__br_pln_blk_val] = sym__r_prp_val, + [sym__r_sgl_pln_blk_val] = sym__r_prp_val, + [sym__br_sgl_pln_blk_val] = sym__r_prp_val, + [sym__b_sgl_pln_blk_val] = sym__r_prp_val, + [sym__r_pln_flw_val] = sym__r_prp_val, + [sym__br_pln_flw_val] = sym__r_prp_val, + [sym__r_sgl_pln_flw_val] = sym__r_prp_val, + [sym__r_sgl_pln_blk] = sym__r_sgl_pln_blk, + [sym__br_sgl_pln_blk] = sym__r_sgl_pln_blk, + [sym__b_sgl_pln_blk] = sym__r_sgl_pln_blk, + [sym__r_sgl_pln_flw] = sym__r_sgl_pln_blk, + [sym__br_sgl_pln_flw] = sym__r_sgl_pln_blk, + [sym__r_mtl_pln_blk] = sym__r_sgl_pln_blk, + [sym__br_mtl_pln_blk] = sym__r_sgl_pln_blk, + [sym__r_mtl_pln_flw] = sym__r_sgl_pln_blk, + [sym__br_mtl_pln_flw] = sym__r_sgl_pln_blk, + [sym__r_als_val] = sym__r_prp_val, + [sym__br_als_val] = sym__r_prp_val, + [sym__b_als_val] = sym__r_prp_val, + [sym__r_als] = sym__r_als, + [sym__br_als] = sym__r_als, + [sym__b_als] = sym__r_als, + [sym__r_acr] = sym__r_acr, + [sym__br_acr] = sym__r_acr, + [sym__b_acr] = sym__r_acr, + [aux_sym__drs_doc_repeat1] = aux_sym__drs_doc_repeat1, + [aux_sym__s_dir_rsv_repeat1] = aux_sym__s_dir_rsv_repeat1, + [aux_sym__r_blk_seq_repeat1] = aux_sym__r_blk_seq_repeat1, + [aux_sym__r_blk_map_repeat1] = aux_sym__r_blk_map_repeat1, + [aux_sym__r_blk_str_repeat1] = aux_sym__r_blk_str_repeat1, + [aux_sym__r_flw_seq_dat_repeat1] = aux_sym__r_flw_seq_dat_repeat1, + [aux_sym__r_flw_map_dat_repeat1] = aux_sym__r_flw_map_dat_repeat1, + [aux_sym__r_sgl_flw_col_dat_repeat1] = aux_sym__r_sgl_flw_col_dat_repeat1, + [aux_sym__r_dqt_str_repeat1] = aux_sym__r_dqt_str_repeat1, + [aux_sym__br_mtl_dqt_ctn_repeat1] = aux_sym__br_mtl_dqt_ctn_repeat1, + [aux_sym__r_sqt_str_repeat1] = aux_sym__r_sqt_str_repeat1, + [aux_sym__br_mtl_sqt_ctn_repeat1] = aux_sym__br_mtl_sqt_ctn_repeat1, +}; + +static const TSSymbolMetadata ts_symbol_metadata[] = { + [ts_builtin_sym_end] = { + .visible = false, + .named = true, + }, + [sym__eof] = { + .visible = false, + .named = true, + }, + [sym__s_dir_yml_bgn] = { + .visible = false, + .named = true, + }, + [sym__r_dir_yml_ver] = { + .visible = true, + .named = true, + }, + [sym__s_dir_tag_bgn] = { + .visible = false, + .named = true, + }, + [sym__r_dir_tag_hdl] = { + .visible = true, + .named = true, + }, + [sym__r_dir_tag_pfx] = { + .visible = true, + .named = true, + }, + [sym__s_dir_rsv_bgn] = { + .visible = true, + .named = true, + }, + [sym__r_dir_rsv_prm] = { + .visible = true, + .named = true, + }, + [sym__s_drs_end] = { + .visible = true, + .named = false, + }, + [sym__s_doc_end] = { + .visible = true, + .named = false, + }, + [sym__r_blk_seq_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_blk_seq_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_blk_seq_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_blk_key_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_blk_key_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_blk_key_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_blk_val_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_blk_val_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_blk_val_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_blk_imp_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_blk_lit_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_blk_lit_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_blk_fld_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_blk_fld_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_blk_str_ctn] = { + .visible = false, + .named = true, + }, + [sym__r_flw_seq_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_flw_seq_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_flw_seq_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_flw_seq_end] = { + .visible = true, + .named = false, + }, + [sym__br_flw_seq_end] = { + .visible = true, + .named = false, + }, + [sym__b_flw_seq_end] = { + .visible = true, + .named = false, + }, + [sym__r_flw_map_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_flw_map_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_flw_map_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_flw_map_end] = { + .visible = true, + .named = false, + }, + [sym__br_flw_map_end] = { + .visible = true, + .named = false, + }, + [sym__b_flw_map_end] = { + .visible = true, + .named = false, + }, + [sym__r_flw_sep_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_flw_sep_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_flw_key_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_flw_key_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_flw_jsv_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_flw_jsv_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_flw_njv_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_flw_njv_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_dqt_str_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_dqt_str_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_dqt_str_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_dqt_str_ctn] = { + .visible = false, + .named = true, + }, + [sym__br_dqt_str_ctn] = { + .visible = false, + .named = true, + }, + [sym__r_dqt_esc_nwl] = { + .visible = true, + .named = true, + }, + [sym__br_dqt_esc_nwl] = { + .visible = true, + .named = true, + }, + [sym__r_dqt_esc_seq] = { + .visible = true, + .named = true, + }, + [sym__br_dqt_esc_seq] = { + .visible = true, + .named = true, + }, + [sym__r_dqt_str_end] = { + .visible = true, + .named = false, + }, + [sym__br_dqt_str_end] = { + .visible = true, + .named = false, + }, + [sym__r_sqt_str_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_sqt_str_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_sqt_str_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_sqt_str_ctn] = { + .visible = false, + .named = true, + }, + [sym__br_sqt_str_ctn] = { + .visible = false, + .named = true, + }, + [sym__r_sqt_esc_sqt] = { + .visible = true, + .named = true, + }, + [sym__br_sqt_esc_sqt] = { + .visible = true, + .named = true, + }, + [sym__r_sqt_str_end] = { + .visible = true, + .named = false, + }, + [sym__br_sqt_str_end] = { + .visible = true, + .named = false, + }, + [sym__r_sgl_pln_nul_blk] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_nul_blk] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_pln_nul_blk] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_nul_flw] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_nul_flw] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_bol_blk] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_bol_blk] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_pln_bol_blk] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_bol_flw] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_bol_flw] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_int_blk] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_int_blk] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_pln_int_blk] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_int_flw] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_int_flw] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_flt_blk] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_flt_blk] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_pln_flt_blk] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_flt_flw] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_flt_flw] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_tms_blk] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_tms_blk] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_pln_tms_blk] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_tms_flw] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_tms_flw] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_str_blk] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_str_blk] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_pln_str_blk] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_str_flw] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_str_flw] = { + .visible = true, + .named = true, + }, + [sym__r_mtl_pln_str_blk] = { + .visible = true, + .named = true, + }, + [sym__br_mtl_pln_str_blk] = { + .visible = true, + .named = true, + }, + [sym__r_mtl_pln_str_flw] = { + .visible = true, + .named = true, + }, + [sym__br_mtl_pln_str_flw] = { + .visible = true, + .named = true, + }, + [sym__r_tag] = { + .visible = true, + .named = true, + }, + [sym__br_tag] = { + .visible = true, + .named = true, + }, + [sym__b_tag] = { + .visible = true, + .named = true, + }, + [sym__r_acr_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_acr_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_acr_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_acr_ctn] = { + .visible = true, + .named = true, + }, + [sym__r_als_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_als_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_als_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_als_ctn] = { + .visible = true, + .named = true, + }, + [sym__bl] = { + .visible = false, + .named = true, + }, + [sym_comment] = { + .visible = true, + .named = true, + }, + [sym__err_rec] = { + .visible = false, + .named = true, + }, + [sym_stream] = { + .visible = true, + .named = true, + }, + [sym__doc_w_bgn_w_end_seq] = { + .visible = false, + .named = true, + }, + [sym__doc_w_bgn_wo_end_seq] = { + .visible = false, + .named = true, + }, + [sym__doc_wo_bgn_w_end_seq] = { + .visible = false, + .named = true, + }, + [sym__doc_wo_bgn_wo_end_seq] = { + .visible = false, + .named = true, + }, + [sym__doc_w_bgn_w_end] = { + .visible = false, + .named = true, + }, + [sym__doc_w_bgn_wo_end] = { + .visible = false, + .named = true, + }, + [sym__doc_wo_bgn_w_end] = { + .visible = false, + .named = true, + }, + [sym__doc_wo_bgn_wo_end] = { + .visible = false, + .named = true, + }, + [sym__bgn_imp_doc] = { + .visible = false, + .named = true, + }, + [sym__drs_doc] = { + .visible = false, + .named = true, + }, + [sym__exp_doc] = { + .visible = false, + .named = true, + }, + [sym__imp_doc] = { + .visible = false, + .named = true, + }, + [sym__drs_doc_end] = { + .visible = true, + .named = true, + }, + [sym__exp_doc_end] = { + .visible = true, + .named = true, + }, + [sym__imp_doc_end] = { + .visible = true, + .named = true, + }, + [sym__bgn_imp_doc_end] = { + .visible = true, + .named = true, + }, + [sym__doc_end] = { + .visible = true, + .named = true, + }, + [sym__exp_doc_tal] = { + .visible = false, + .named = true, + }, + [sym__s_dir] = { + .visible = false, + .named = true, + }, + [sym__s_dir_yml] = { + .visible = true, + .named = true, + }, + [sym__s_dir_tag] = { + .visible = true, + .named = true, + }, + [sym__s_dir_rsv] = { + .visible = true, + .named = true, + }, + [sym__r_prp_val] = { + .visible = true, + .named = true, + }, + [sym__br_prp_val] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_prp_val] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_prp_val] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_prp_val] = { + .visible = true, + .named = true, + }, + [sym__r_prp] = { + .visible = false, + .named = true, + }, + [sym__br_prp] = { + .visible = false, + .named = true, + }, + [sym__r_sgl_prp] = { + .visible = false, + .named = true, + }, + [sym__br_sgl_prp] = { + .visible = false, + .named = true, + }, + [sym__b_sgl_prp] = { + .visible = false, + .named = true, + }, + [sym__r_blk_seq_r_val] = { + .visible = true, + .named = true, + }, + [sym__r_blk_seq_br_val] = { + .visible = true, + .named = true, + }, + [sym__br_blk_seq_val] = { + .visible = true, + .named = true, + }, + [sym__r_blk_seq_spc_val] = { + .visible = true, + .named = true, + }, + [sym__br_blk_seq_spc_val] = { + .visible = true, + .named = true, + }, + [sym__b_blk_seq_spc_val] = { + .visible = true, + .named = true, + }, + [sym__r_blk_seq] = { + .visible = true, + .named = true, + }, + [sym__br_blk_seq] = { + .visible = true, + .named = true, + }, + [sym__b_blk_seq_spc] = { + .visible = true, + .named = true, + }, + [sym__r_blk_seq_itm] = { + .visible = true, + .named = true, + }, + [sym__br_blk_seq_itm] = { + .visible = true, + .named = true, + }, + [sym__b_blk_seq_itm] = { + .visible = true, + .named = true, + }, + [sym__blk_seq_itm_tal] = { + .visible = false, + .named = true, + }, + [sym__r_blk_map_r_val] = { + .visible = true, + .named = true, + }, + [sym__r_blk_map_br_val] = { + .visible = true, + .named = true, + }, + [sym__br_blk_map_val] = { + .visible = true, + .named = true, + }, + [sym__r_blk_map] = { + .visible = true, + .named = true, + }, + [sym__br_blk_map] = { + .visible = true, + .named = true, + }, + [sym__r_blk_map_itm] = { + .visible = false, + .named = true, + }, + [sym__br_blk_map_itm] = { + .visible = false, + .named = true, + }, + [sym__b_blk_map_itm] = { + .visible = false, + .named = true, + }, + [sym__r_blk_exp_itm] = { + .visible = true, + .named = true, + }, + [sym__br_blk_exp_itm] = { + .visible = true, + .named = true, + }, + [sym__b_blk_exp_itm] = { + .visible = true, + .named = true, + }, + [sym__r_blk_key_itm] = { + .visible = false, + .named = true, + }, + [sym__br_blk_key_itm] = { + .visible = false, + .named = true, + }, + [sym__b_blk_key_itm] = { + .visible = false, + .named = true, + }, + [sym__r_blk_val_itm] = { + .visible = false, + .named = true, + }, + [sym__br_blk_val_itm] = { + .visible = false, + .named = true, + }, + [sym__b_blk_val_itm] = { + .visible = false, + .named = true, + }, + [sym__r_blk_imp_itm] = { + .visible = true, + .named = true, + }, + [sym__br_blk_imp_itm] = { + .visible = true, + .named = true, + }, + [sym__b_blk_imp_itm] = { + .visible = true, + .named = true, + }, + [sym__blk_exp_itm_tal] = { + .visible = false, + .named = true, + }, + [sym__blk_imp_itm_tal] = { + .visible = false, + .named = true, + }, + [sym__r_blk_str_val] = { + .visible = true, + .named = true, + }, + [sym__br_blk_str_val] = { + .visible = true, + .named = true, + }, + [sym__r_blk_str] = { + .visible = true, + .named = true, + }, + [sym__br_blk_str] = { + .visible = true, + .named = true, + }, + [sym__r_flw_seq_val] = { + .visible = true, + .named = true, + }, + [sym__br_flw_seq_val] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_flw_seq_val] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_flw_seq_val] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_flw_seq_val] = { + .visible = true, + .named = true, + }, + [sym__r_flw_seq] = { + .visible = true, + .named = true, + }, + [sym__br_flw_seq] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_flw_seq] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_flw_seq] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_flw_seq] = { + .visible = true, + .named = true, + }, + [sym__flw_seq_tal] = { + .visible = false, + .named = true, + }, + [sym__sgl_flw_seq_tal] = { + .visible = false, + .named = true, + }, + [sym__r_flw_map_val] = { + .visible = true, + .named = true, + }, + [sym__br_flw_map_val] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_flw_map_val] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_flw_map_val] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_flw_map_val] = { + .visible = true, + .named = true, + }, + [sym__r_flw_map] = { + .visible = true, + .named = true, + }, + [sym__br_flw_map] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_flw_map] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_flw_map] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_flw_map] = { + .visible = true, + .named = true, + }, + [sym__flw_map_tal] = { + .visible = false, + .named = true, + }, + [sym__sgl_flw_map_tal] = { + .visible = false, + .named = true, + }, + [sym__r_flw_seq_dat] = { + .visible = false, + .named = true, + }, + [sym__br_flw_seq_dat] = { + .visible = false, + .named = true, + }, + [sym__r_flw_map_dat] = { + .visible = false, + .named = true, + }, + [sym__br_flw_map_dat] = { + .visible = false, + .named = true, + }, + [sym__r_sgl_flw_col_dat] = { + .visible = false, + .named = true, + }, + [sym__flw_seq_dat_rpt] = { + .visible = false, + .named = true, + }, + [sym__flw_map_dat_rpt] = { + .visible = false, + .named = true, + }, + [sym__sgl_flw_col_dat_rpt] = { + .visible = false, + .named = true, + }, + [sym__r_flw_seq_itm] = { + .visible = false, + .named = true, + }, + [sym__br_flw_seq_itm] = { + .visible = false, + .named = true, + }, + [sym__r_flw_map_itm] = { + .visible = false, + .named = true, + }, + [sym__br_flw_map_itm] = { + .visible = false, + .named = true, + }, + [sym__r_sgl_flw_col_itm] = { + .visible = false, + .named = true, + }, + [sym__r_flw_exp_par] = { + .visible = true, + .named = true, + }, + [sym__br_flw_exp_par] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_flw_exp_par] = { + .visible = true, + .named = true, + }, + [sym__r_flw_imp_r_par] = { + .visible = false, + .named = true, + }, + [sym__r_flw_imp_br_par] = { + .visible = false, + .named = true, + }, + [sym__br_flw_imp_r_par] = { + .visible = false, + .named = true, + }, + [sym__br_flw_imp_br_par] = { + .visible = false, + .named = true, + }, + [sym__r_sgl_flw_imp_par] = { + .visible = false, + .named = true, + }, + [sym__r_flw_jsl_ann_par] = { + .visible = false, + .named = true, + }, + [sym__br_flw_jsl_ann_par] = { + .visible = false, + .named = true, + }, + [sym__r_sgl_flw_jsl_ann_par] = { + .visible = false, + .named = true, + }, + [sym__r_flw_njl_ann_par] = { + .visible = false, + .named = true, + }, + [sym__br_flw_njl_ann_par] = { + .visible = false, + .named = true, + }, + [sym__r_sgl_flw_njl_ann_par] = { + .visible = false, + .named = true, + }, + [sym__flw_ann_par_tal] = { + .visible = false, + .named = true, + }, + [sym__sgl_flw_ann_par_tal] = { + .visible = false, + .named = true, + }, + [sym__r_dqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__br_dqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_dqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_dqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_dqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__r_dqt_str] = { + .visible = true, + .named = true, + }, + [sym__br_dqt_str] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_dqt_str] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_dqt_str] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_dqt_str] = { + .visible = true, + .named = true, + }, + [aux_sym__r_sgl_dqt_ctn] = { + .visible = false, + .named = false, + }, + [sym__br_mtl_dqt_ctn] = { + .visible = false, + .named = true, + }, + [sym__r_sqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__br_sqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_sqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_sqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_sqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__r_sqt_str] = { + .visible = true, + .named = true, + }, + [sym__br_sqt_str] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_sqt_str] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_sqt_str] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_sqt_str] = { + .visible = true, + .named = true, + }, + [aux_sym__r_sgl_sqt_ctn] = { + .visible = false, + .named = false, + }, + [sym__br_mtl_sqt_ctn] = { + .visible = false, + .named = true, + }, + [sym__r_pln_blk_val] = { + .visible = true, + .named = true, + }, + [sym__br_pln_blk_val] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_blk_val] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_blk_val] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_pln_blk_val] = { + .visible = true, + .named = true, + }, + [sym__r_pln_flw_val] = { + .visible = true, + .named = true, + }, + [sym__br_pln_flw_val] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_flw_val] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_blk] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_blk] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_pln_blk] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_flw] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_flw] = { + .visible = true, + .named = true, + }, + [sym__r_mtl_pln_blk] = { + .visible = true, + .named = true, + }, + [sym__br_mtl_pln_blk] = { + .visible = true, + .named = true, + }, + [sym__r_mtl_pln_flw] = { + .visible = true, + .named = true, + }, + [sym__br_mtl_pln_flw] = { + .visible = true, + .named = true, + }, + [sym__r_als_val] = { + .visible = true, + .named = true, + }, + [sym__br_als_val] = { + .visible = true, + .named = true, + }, + [sym__b_als_val] = { + .visible = true, + .named = true, + }, + [sym__r_als] = { + .visible = true, + .named = true, + }, + [sym__br_als] = { + .visible = true, + .named = true, + }, + [sym__b_als] = { + .visible = true, + .named = true, + }, + [sym__r_acr] = { + .visible = true, + .named = true, + }, + [sym__br_acr] = { + .visible = true, + .named = true, + }, + [sym__b_acr] = { + .visible = true, + .named = true, + }, + [aux_sym__drs_doc_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__s_dir_rsv_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__r_blk_seq_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__r_blk_map_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__r_blk_str_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__r_flw_seq_dat_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__r_flw_map_dat_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__r_sgl_flw_col_dat_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__r_dqt_str_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__br_mtl_dqt_ctn_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__r_sqt_str_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__br_mtl_sqt_ctn_repeat1] = { + .visible = false, + .named = false, + }, +}; + +enum ts_field_identifiers { + field_key = 1, + field_value = 2, +}; + +static const char * const ts_field_names[] = { + [0] = NULL, + [field_key] = "key", + [field_value] = "value", +}; + +static const TSMapSlice ts_field_map_slices[PRODUCTION_ID_COUNT] = { + [1] = {.index = 0, .length = 2}, + [2] = {.index = 2, .length = 1}, + [3] = {.index = 3, .length = 1}, + [4] = {.index = 4, .length = 1}, + [5] = {.index = 5, .length = 1}, + [6] = {.index = 0, .length = 2}, + [7] = {.index = 3, .length = 1}, + [9] = {.index = 6, .length = 2}, + [10] = {.index = 8, .length = 2}, + [11] = {.index = 10, .length = 2}, +}; + +static const TSFieldMapEntry ts_field_map_entries[] = { + [0] = + {field_key, 0, .inherited = true}, + {field_value, 0, .inherited = true}, + [2] = + {field_key, 0, .inherited = true}, + [3] = + {field_value, 0, .inherited = true}, + [4] = + {field_key, 1}, + [5] = + {field_value, 1}, + [6] = + {field_key, 0}, + {field_value, 1, .inherited = true}, + [8] = + {field_key, 0, .inherited = true}, + {field_value, 1, .inherited = true}, + [10] = + {field_key, 1, .inherited = true}, + {field_value, 1, .inherited = true}, +}; + +static const TSSymbol ts_alias_sequences[PRODUCTION_ID_COUNT][MAX_ALIAS_SEQUENCE_LENGTH] = { + [0] = {0}, + [6] = { + [0] = sym__r_flw_exp_par, + }, + [7] = { + [0] = sym__r_flw_exp_par, + }, + [8] = { + [0] = sym__drs_doc_end, + }, +}; + +static const uint16_t ts_non_terminal_alias_map[] = { + sym__bgn_imp_doc, 2, + sym__bgn_imp_doc, + sym__drs_doc_end, + sym__drs_doc, 2, + sym__drs_doc, + sym__drs_doc_end, + sym__exp_doc, 2, + sym__exp_doc, + sym__drs_doc_end, + sym__imp_doc, 2, + sym__imp_doc, + sym__drs_doc_end, + sym__r_flw_imp_r_par, 2, + sym__r_flw_imp_r_par, + sym__r_flw_exp_par, + sym__r_flw_imp_br_par, 2, + sym__r_flw_imp_br_par, + sym__r_flw_exp_par, + sym__br_flw_imp_r_par, 2, + sym__br_flw_imp_r_par, + sym__r_flw_exp_par, + sym__br_flw_imp_br_par, 2, + sym__br_flw_imp_br_par, + sym__r_flw_exp_par, + sym__r_sgl_flw_imp_par, 2, + sym__r_sgl_flw_imp_par, + sym__r_flw_exp_par, + sym__r_flw_njl_ann_par, 2, + sym__r_flw_njl_ann_par, + sym__r_flw_exp_par, + sym__br_flw_njl_ann_par, 2, + sym__br_flw_njl_ann_par, + sym__r_flw_exp_par, + sym__r_sgl_flw_njl_ann_par, 2, + sym__r_sgl_flw_njl_ann_par, + sym__r_flw_exp_par, + 0, +}; + +static const TSStateId ts_primary_state_ids[STATE_COUNT] = { + [0] = 0, + [1] = 1, + [2] = 2, + [3] = 3, + [4] = 4, + [5] = 5, + [6] = 6, + [7] = 7, + [8] = 8, + [9] = 9, + [10] = 10, + [11] = 11, + [12] = 12, + [13] = 13, + [14] = 14, + [15] = 13, + [16] = 14, + [17] = 14, + [18] = 13, + [19] = 13, + [20] = 13, + [21] = 13, + [22] = 13, + [23] = 13, + [24] = 24, + [25] = 25, + [26] = 24, + [27] = 25, + [28] = 24, + [29] = 25, + [30] = 24, + [31] = 24, + [32] = 24, + [33] = 24, + [34] = 24, + [35] = 35, + [36] = 36, + [37] = 37, + [38] = 38, + [39] = 39, + [40] = 40, + [41] = 40, + [42] = 42, + [43] = 43, + [44] = 43, + [45] = 43, + [46] = 43, + [47] = 42, + [48] = 42, + [49] = 43, + [50] = 42, + [51] = 43, + [52] = 43, + [53] = 42, + [54] = 43, + [55] = 55, + [56] = 56, + [57] = 56, + [58] = 58, + [59] = 56, + [60] = 58, + [61] = 56, + [62] = 56, + [63] = 58, + [64] = 58, + [65] = 56, + [66] = 58, + [67] = 56, + [68] = 56, + [69] = 55, + [70] = 70, + [71] = 71, + [72] = 72, + [73] = 73, + [74] = 74, + [75] = 75, + [76] = 76, + [77] = 77, + [78] = 78, + [79] = 79, + [80] = 80, + [81] = 81, + [82] = 81, + [83] = 80, + [84] = 84, + [85] = 85, + [86] = 84, + [87] = 85, + [88] = 88, + [89] = 89, + [90] = 90, + [91] = 88, + [92] = 89, + [93] = 90, + [94] = 94, + [95] = 94, + [96] = 96, + [97] = 97, + [98] = 98, + [99] = 99, + [100] = 100, + [101] = 101, + [102] = 102, + [103] = 103, + [104] = 104, + [105] = 105, + [106] = 101, + [107] = 101, + [108] = 108, + [109] = 109, + [110] = 102, + [111] = 101, + [112] = 112, + [113] = 113, + [114] = 112, + [115] = 113, + [116] = 97, + [117] = 112, + [118] = 96, + [119] = 113, + [120] = 112, + [121] = 113, + [122] = 96, + [123] = 97, + [124] = 98, + [125] = 125, + [126] = 126, + [127] = 101, + [128] = 128, + [129] = 102, + [130] = 130, + [131] = 100, + [132] = 132, + [133] = 126, + [134] = 125, + [135] = 130, + [136] = 132, + [137] = 126, + [138] = 138, + [139] = 139, + [140] = 140, + [141] = 141, + [142] = 125, + [143] = 130, + [144] = 138, + [145] = 139, + [146] = 99, + [147] = 132, + [148] = 126, + [149] = 138, + [150] = 139, + [151] = 132, + [152] = 126, + [153] = 132, + [154] = 126, + [155] = 132, + [156] = 102, + [157] = 100, + [158] = 99, + [159] = 101, + [160] = 105, + [161] = 101, + [162] = 113, + [163] = 101, + [164] = 112, + [165] = 103, + [166] = 104, + [167] = 167, + [168] = 103, + [169] = 109, + [170] = 101, + [171] = 102, + [172] = 104, + [173] = 101, + [174] = 167, + [175] = 175, + [176] = 108, + [177] = 175, + [178] = 108, + [179] = 109, + [180] = 102, + [181] = 181, + [182] = 181, + [183] = 96, + [184] = 184, + [185] = 98, + [186] = 184, + [187] = 98, + [188] = 96, + [189] = 189, + [190] = 105, + [191] = 100, + [192] = 98, + [193] = 184, + [194] = 102, + [195] = 98, + [196] = 101, + [197] = 197, + [198] = 96, + [199] = 199, + [200] = 199, + [201] = 96, + [202] = 202, + [203] = 202, + [204] = 184, + [205] = 189, + [206] = 101, + [207] = 100, + [208] = 102, + [209] = 105, + [210] = 197, + [211] = 101, + [212] = 102, + [213] = 105, + [214] = 105, + [215] = 100, + [216] = 102, + [217] = 101, + [218] = 197, + [219] = 103, + [220] = 100, + [221] = 108, + [222] = 109, + [223] = 101, + [224] = 197, + [225] = 102, + [226] = 96, + [227] = 101, + [228] = 102, + [229] = 98, + [230] = 103, + [231] = 108, + [232] = 109, + [233] = 184, + [234] = 109, + [235] = 102, + [236] = 108, + [237] = 102, + [238] = 103, + [239] = 101, + [240] = 108, + [241] = 101, + [242] = 103, + [243] = 109, + [244] = 100, + [245] = 105, + [246] = 101, + [247] = 102, + [248] = 197, + [249] = 249, + [250] = 250, + [251] = 251, + [252] = 252, + [253] = 253, + [254] = 254, + [255] = 255, + [256] = 101, + [257] = 103, + [258] = 108, + [259] = 102, + [260] = 109, + [261] = 261, + [262] = 262, + [263] = 263, + [264] = 264, + [265] = 261, + [266] = 266, + [267] = 267, + [268] = 268, + [269] = 269, + [270] = 270, + [271] = 271, + [272] = 272, + [273] = 273, + [274] = 261, + [275] = 275, + [276] = 261, + [277] = 277, + [278] = 278, + [279] = 279, + [280] = 280, + [281] = 281, + [282] = 282, + [283] = 283, + [284] = 284, + [285] = 285, + [286] = 286, + [287] = 287, + [288] = 288, + [289] = 289, + [290] = 290, + [291] = 291, + [292] = 292, + [293] = 293, + [294] = 294, + [295] = 295, + [296] = 296, + [297] = 297, + [298] = 298, + [299] = 299, + [300] = 300, + [301] = 301, + [302] = 302, + [303] = 303, + [304] = 304, + [305] = 305, + [306] = 306, + [307] = 307, + [308] = 308, + [309] = 309, + [310] = 310, + [311] = 311, + [312] = 312, + [313] = 313, + [314] = 314, + [315] = 273, + [316] = 316, + [317] = 317, + [318] = 318, + [319] = 319, + [320] = 320, + [321] = 321, + [322] = 322, + [323] = 323, + [324] = 324, + [325] = 325, + [326] = 326, + [327] = 327, + [328] = 328, + [329] = 329, + [330] = 266, + [331] = 331, + [332] = 332, + [333] = 275, + [334] = 334, + [335] = 335, + [336] = 336, + [337] = 337, + [338] = 338, + [339] = 339, + [340] = 340, + [341] = 341, + [342] = 342, + [343] = 343, + [344] = 344, + [345] = 345, + [346] = 346, + [347] = 347, + [348] = 348, + [349] = 349, + [350] = 350, + [351] = 351, + [352] = 352, + [353] = 353, + [354] = 354, + [355] = 355, + [356] = 356, + [357] = 357, + [358] = 358, + [359] = 359, + [360] = 360, + [361] = 361, + [362] = 362, + [363] = 363, + [364] = 364, + [365] = 261, + [366] = 366, + [367] = 367, + [368] = 368, + [369] = 369, + [370] = 370, + [371] = 371, + [372] = 372, + [373] = 373, + [374] = 374, + [375] = 375, + [376] = 376, + [377] = 377, + [378] = 378, + [379] = 379, + [380] = 380, + [381] = 381, + [382] = 382, + [383] = 383, + [384] = 384, + [385] = 385, + [386] = 386, + [387] = 387, + [388] = 388, + [389] = 389, + [390] = 390, + [391] = 391, + [392] = 392, + [393] = 392, + [394] = 392, + [395] = 395, + [396] = 392, + [397] = 101, + [398] = 395, + [399] = 101, + [400] = 101, + [401] = 395, + [402] = 101, + [403] = 392, + [404] = 395, + [405] = 405, + [406] = 406, + [407] = 101, + [408] = 406, + [409] = 409, + [410] = 101, + [411] = 101, + [412] = 101, + [413] = 395, + [414] = 101, + [415] = 415, + [416] = 416, + [417] = 406, + [418] = 102, + [419] = 406, + [420] = 420, + [421] = 421, + [422] = 422, + [423] = 423, + [424] = 101, + [425] = 425, + [426] = 423, + [427] = 427, + [428] = 428, + [429] = 421, + [430] = 421, + [431] = 431, + [432] = 432, + [433] = 433, + [434] = 433, + [435] = 422, + [436] = 423, + [437] = 427, + [438] = 101, + [439] = 421, + [440] = 431, + [441] = 431, + [442] = 432, + [443] = 427, + [444] = 422, + [445] = 406, + [446] = 427, + [447] = 428, + [448] = 427, + [449] = 421, + [450] = 431, + [451] = 432, + [452] = 422, + [453] = 423, + [454] = 427, + [455] = 422, + [456] = 432, + [457] = 421, + [458] = 422, + [459] = 428, + [460] = 432, + [461] = 427, + [462] = 431, + [463] = 421, + [464] = 432, + [465] = 432, + [466] = 422, + [467] = 433, + [468] = 427, + [469] = 469, + [470] = 421, + [471] = 432, + [472] = 422, + [473] = 423, + [474] = 474, + [475] = 475, + [476] = 476, + [477] = 477, + [478] = 478, + [479] = 479, + [480] = 480, + [481] = 481, + [482] = 482, + [483] = 483, + [484] = 484, + [485] = 485, + [486] = 486, + [487] = 482, + [488] = 488, + [489] = 489, + [490] = 485, + [491] = 488, + [492] = 492, + [493] = 493, + [494] = 483, + [495] = 495, + [496] = 484, + [497] = 484, + [498] = 498, + [499] = 499, + [500] = 495, + [501] = 482, + [502] = 502, + [503] = 503, + [504] = 504, + [505] = 485, + [506] = 484, + [507] = 488, + [508] = 495, + [509] = 489, + [510] = 495, + [511] = 485, + [512] = 503, + [513] = 482, + [514] = 482, + [515] = 482, + [516] = 482, + [517] = 489, + [518] = 488, + [519] = 485, + [520] = 485, + [521] = 488, + [522] = 522, + [523] = 485, + [524] = 495, + [525] = 483, + [526] = 488, + [527] = 489, + [528] = 482, + [529] = 503, + [530] = 484, + [531] = 488, + [532] = 485, + [533] = 489, + [534] = 488, + [535] = 495, + [536] = 495, + [537] = 495, + [538] = 538, + [539] = 539, + [540] = 347, + [541] = 541, + [542] = 348, + [543] = 543, + [544] = 544, + [545] = 349, + [546] = 546, + [547] = 350, + [548] = 351, + [549] = 352, + [550] = 353, + [551] = 283, + [552] = 552, + [553] = 553, + [554] = 554, + [555] = 284, + [556] = 556, + [557] = 557, + [558] = 553, + [559] = 559, + [560] = 560, + [561] = 539, + [562] = 562, + [563] = 563, + [564] = 564, + [565] = 565, + [566] = 366, + [567] = 567, + [568] = 367, + [569] = 285, + [570] = 369, + [571] = 370, + [572] = 286, + [573] = 372, + [574] = 373, + [575] = 541, + [576] = 288, + [577] = 543, + [578] = 544, + [579] = 546, + [580] = 374, + [581] = 376, + [582] = 559, + [583] = 560, + [584] = 539, + [585] = 562, + [586] = 586, + [587] = 557, + [588] = 553, + [589] = 559, + [590] = 560, + [591] = 539, + [592] = 562, + [593] = 290, + [594] = 382, + [595] = 383, + [596] = 384, + [597] = 385, + [598] = 378, + [599] = 327, + [600] = 298, + [601] = 355, + [602] = 320, + [603] = 321, + [604] = 324, + [605] = 541, + [606] = 269, + [607] = 543, + [608] = 544, + [609] = 546, + [610] = 354, + [611] = 271, + [612] = 363, + [613] = 371, + [614] = 614, + [615] = 615, + [616] = 293, + [617] = 557, + [618] = 553, + [619] = 559, + [620] = 560, + [621] = 539, + [622] = 562, + [623] = 346, + [624] = 295, + [625] = 541, + [626] = 296, + [627] = 543, + [628] = 544, + [629] = 543, + [630] = 546, + [631] = 541, + [632] = 297, + [633] = 543, + [634] = 544, + [635] = 546, + [636] = 391, + [637] = 637, + [638] = 266, + [639] = 639, + [640] = 544, + [641] = 557, + [642] = 553, + [643] = 559, + [644] = 560, + [645] = 645, + [646] = 562, + [647] = 546, + [648] = 648, + [649] = 649, + [650] = 557, + [651] = 553, + [652] = 559, + [653] = 560, + [654] = 539, + [655] = 541, + [656] = 562, + [657] = 543, + [658] = 544, + [659] = 546, + [660] = 660, + [661] = 661, + [662] = 275, + [663] = 663, + [664] = 557, + [665] = 553, + [666] = 559, + [667] = 560, + [668] = 539, + [669] = 562, + [670] = 670, + [671] = 671, + [672] = 672, + [673] = 673, + [674] = 674, + [675] = 675, + [676] = 541, + [677] = 677, + [678] = 541, + [679] = 679, + [680] = 543, + [681] = 544, + [682] = 546, + [683] = 683, + [684] = 684, + [685] = 557, + [686] = 557, + [687] = 553, + [688] = 559, + [689] = 560, + [690] = 539, + [691] = 562, + [692] = 294, + [693] = 693, + [694] = 694, + [695] = 677, + [696] = 679, + [697] = 683, + [698] = 698, + [699] = 684, + [700] = 637, + [701] = 639, + [702] = 346, + [703] = 347, + [704] = 348, + [705] = 349, + [706] = 350, + [707] = 351, + [708] = 352, + [709] = 353, + [710] = 283, + [711] = 284, + [712] = 366, + [713] = 367, + [714] = 285, + [715] = 369, + [716] = 370, + [717] = 286, + [718] = 372, + [719] = 373, + [720] = 288, + [721] = 374, + [722] = 376, + [723] = 290, + [724] = 382, + [725] = 383, + [726] = 384, + [727] = 385, + [728] = 378, + [729] = 327, + [730] = 298, + [731] = 355, + [732] = 320, + [733] = 321, + [734] = 324, + [735] = 269, + [736] = 354, + [737] = 271, + [738] = 363, + [739] = 371, + [740] = 293, + [741] = 741, + [742] = 295, + [743] = 296, + [744] = 297, + [745] = 391, + [746] = 266, + [747] = 556, + [748] = 563, + [749] = 564, + [750] = 750, + [751] = 751, + [752] = 741, + [753] = 275, + [754] = 754, + [755] = 754, + [756] = 693, + [757] = 693, + [758] = 758, + [759] = 750, + [760] = 741, + [761] = 754, + [762] = 693, + [763] = 750, + [764] = 741, + [765] = 754, + [766] = 693, + [767] = 750, + [768] = 741, + [769] = 754, + [770] = 693, + [771] = 750, + [772] = 741, + [773] = 754, + [774] = 693, + [775] = 750, + [776] = 741, + [777] = 754, + [778] = 750, + [779] = 741, + [780] = 754, + [781] = 693, + [782] = 750, + [783] = 294, + [784] = 366, + [785] = 556, + [786] = 563, + [787] = 787, + [788] = 788, + [789] = 789, + [790] = 790, + [791] = 791, + [792] = 564, + [793] = 793, + [794] = 794, + [795] = 795, + [796] = 679, + [797] = 683, + [798] = 684, + [799] = 799, + [800] = 800, + [801] = 556, + [802] = 563, + [803] = 564, + [804] = 804, + [805] = 805, + [806] = 806, + [807] = 807, + [808] = 808, + [809] = 809, + [810] = 810, + [811] = 637, + [812] = 639, + [813] = 677, + [814] = 814, + [815] = 815, + [816] = 816, + [817] = 346, + [818] = 347, + [819] = 348, + [820] = 349, + [821] = 350, + [822] = 351, + [823] = 352, + [824] = 353, + [825] = 825, + [826] = 826, + [827] = 284, + [828] = 366, + [829] = 367, + [830] = 285, + [831] = 369, + [832] = 370, + [833] = 286, + [834] = 372, + [835] = 373, + [836] = 288, + [837] = 374, + [838] = 376, + [839] = 839, + [840] = 840, + [841] = 841, + [842] = 382, + [843] = 383, + [844] = 384, + [845] = 385, + [846] = 378, + [847] = 327, + [848] = 298, + [849] = 355, + [850] = 320, + [851] = 321, + [852] = 324, + [853] = 269, + [854] = 354, + [855] = 271, + [856] = 363, + [857] = 371, + [858] = 293, + [859] = 294, + [860] = 295, + [861] = 296, + [862] = 297, + [863] = 391, + [864] = 864, + [865] = 346, + [866] = 347, + [867] = 348, + [868] = 349, + [869] = 350, + [870] = 351, + [871] = 352, + [872] = 353, + [873] = 266, + [874] = 283, + [875] = 875, + [876] = 284, + [877] = 367, + [878] = 285, + [879] = 369, + [880] = 370, + [881] = 286, + [882] = 372, + [883] = 373, + [884] = 288, + [885] = 374, + [886] = 376, + [887] = 887, + [888] = 888, + [889] = 889, + [890] = 275, + [891] = 290, + [892] = 382, + [893] = 383, + [894] = 384, + [895] = 385, + [896] = 378, + [897] = 327, + [898] = 298, + [899] = 355, + [900] = 320, + [901] = 321, + [902] = 269, + [903] = 354, + [904] = 271, + [905] = 363, + [906] = 371, + [907] = 293, + [908] = 294, + [909] = 295, + [910] = 296, + [911] = 297, + [912] = 391, + [913] = 266, + [914] = 283, + [915] = 275, + [916] = 290, + [917] = 917, + [918] = 918, + [919] = 919, + [920] = 920, + [921] = 921, + [922] = 922, + [923] = 923, + [924] = 924, + [925] = 925, + [926] = 926, + [927] = 804, + [928] = 805, + [929] = 806, + [930] = 637, + [931] = 807, + [932] = 808, + [933] = 809, + [934] = 810, + [935] = 919, + [936] = 920, + [937] = 921, + [938] = 923, + [939] = 939, + [940] = 940, + [941] = 941, + [942] = 639, + [943] = 922, + [944] = 944, + [945] = 945, + [946] = 787, + [947] = 788, + [948] = 924, + [949] = 793, + [950] = 940, + [951] = 816, + [952] = 941, + [953] = 925, + [954] = 864, + [955] = 677, + [956] = 944, + [957] = 679, + [958] = 683, + [959] = 684, + [960] = 926, + [961] = 945, + [962] = 324, + [963] = 963, + [964] = 964, + [965] = 965, + [966] = 966, + [967] = 262, + [968] = 968, + [969] = 264, + [970] = 970, + [971] = 971, + [972] = 972, + [973] = 973, + [974] = 974, + [975] = 975, + [976] = 976, + [977] = 977, + [978] = 978, + [979] = 979, + [980] = 980, + [981] = 980, + [982] = 971, + [983] = 972, + [984] = 984, + [985] = 272, + [986] = 964, + [987] = 271, + [988] = 285, + [989] = 269, + [990] = 270, + [991] = 984, + [992] = 977, + [993] = 977, + [994] = 978, + [995] = 974, + [996] = 286, + [997] = 282, + [998] = 973, + [999] = 266, + [1000] = 287, + [1001] = 283, + [1002] = 965, + [1003] = 966, + [1004] = 965, + [1005] = 288, + [1006] = 977, + [1007] = 978, + [1008] = 289, + [1009] = 1009, + [1010] = 971, + [1011] = 972, + [1012] = 1012, + [1013] = 978, + [1014] = 1014, + [1015] = 1015, + [1016] = 1012, + [1017] = 971, + [1018] = 1018, + [1019] = 972, + [1020] = 977, + [1021] = 978, + [1022] = 973, + [1023] = 502, + [1024] = 615, + [1025] = 1025, + [1026] = 974, + [1027] = 971, + [1028] = 972, + [1029] = 1029, + [1030] = 273, + [1031] = 1009, + [1032] = 977, + [1033] = 978, + [1034] = 963, + [1035] = 1018, + [1036] = 280, + [1037] = 267, + [1038] = 976, + [1039] = 275, + [1040] = 268, + [1041] = 1041, + [1042] = 971, + [1043] = 972, + [1044] = 290, + [1045] = 1025, + [1046] = 281, + [1047] = 284, + [1048] = 966, + [1049] = 266, + [1050] = 1050, + [1051] = 1051, + [1052] = 1052, + [1053] = 1053, + [1054] = 1054, + [1055] = 305, + [1056] = 1056, + [1057] = 307, + [1058] = 1058, + [1059] = 677, + [1060] = 350, + [1061] = 1061, + [1062] = 1062, + [1063] = 362, + [1064] = 1064, + [1065] = 299, + [1066] = 1066, + [1067] = 1067, + [1068] = 1068, + [1069] = 292, + [1070] = 348, + [1071] = 349, + [1072] = 1072, + [1073] = 321, + [1074] = 1074, + [1075] = 324, + [1076] = 370, + [1077] = 677, + [1078] = 1078, + [1079] = 275, + [1080] = 301, + [1081] = 1081, + [1082] = 354, + [1083] = 344, + [1084] = 1084, + [1085] = 1085, + [1086] = 363, + [1087] = 351, + [1088] = 361, + [1089] = 1089, + [1090] = 371, + [1091] = 368, + [1092] = 293, + [1093] = 294, + [1094] = 356, + [1095] = 357, + [1096] = 295, + [1097] = 266, + [1098] = 296, + [1099] = 275, + [1100] = 266, + [1101] = 275, + [1102] = 372, + [1103] = 345, + [1104] = 297, + [1105] = 391, + [1106] = 273, + [1107] = 280, + [1108] = 373, + [1109] = 367, + [1110] = 1110, + [1111] = 1078, + [1112] = 1081, + [1113] = 1113, + [1114] = 1114, + [1115] = 346, + [1116] = 1116, + [1117] = 281, + [1118] = 282, + [1119] = 358, + [1120] = 1089, + [1121] = 1066, + [1122] = 283, + [1123] = 1123, + [1124] = 1058, + [1125] = 1125, + [1126] = 374, + [1127] = 352, + [1128] = 284, + [1129] = 353, + [1130] = 376, + [1131] = 366, + [1132] = 1132, + [1133] = 369, + [1134] = 320, + [1135] = 336, + [1136] = 375, + [1137] = 266, + [1138] = 1125, + [1139] = 1050, + [1140] = 1078, + [1141] = 1081, + [1142] = 337, + [1143] = 1143, + [1144] = 285, + [1145] = 1064, + [1146] = 286, + [1147] = 1089, + [1148] = 1066, + [1149] = 287, + [1150] = 288, + [1151] = 1058, + [1152] = 1125, + [1153] = 289, + [1154] = 340, + [1155] = 1155, + [1156] = 347, + [1157] = 275, + [1158] = 290, + [1159] = 267, + [1160] = 268, + [1161] = 1051, + [1162] = 1052, + [1163] = 1053, + [1164] = 1054, + [1165] = 1058, + [1166] = 1125, + [1167] = 1167, + [1168] = 1168, + [1169] = 1169, + [1170] = 341, + [1171] = 1084, + [1172] = 1058, + [1173] = 1125, + [1174] = 1061, + [1175] = 342, + [1176] = 387, + [1177] = 379, + [1178] = 1062, + [1179] = 269, + [1180] = 270, + [1181] = 271, + [1182] = 1058, + [1183] = 1125, + [1184] = 272, + [1185] = 380, + [1186] = 381, + [1187] = 1132, + [1188] = 382, + [1189] = 1067, + [1190] = 1068, + [1191] = 383, + [1192] = 384, + [1193] = 1058, + [1194] = 1125, + [1195] = 1072, + [1196] = 1074, + [1197] = 385, + [1198] = 273, + [1199] = 386, + [1200] = 343, + [1201] = 388, + [1202] = 389, + [1203] = 390, + [1204] = 378, + [1205] = 327, + [1206] = 298, + [1207] = 355, + [1208] = 335, + [1209] = 1110, + [1210] = 1113, + [1211] = 1058, + [1212] = 1125, + [1213] = 1114, + [1214] = 1116, + [1215] = 377, + [1216] = 679, + [1217] = 352, + [1218] = 353, + [1219] = 1110, + [1220] = 356, + [1221] = 357, + [1222] = 564, + [1223] = 1113, + [1224] = 1114, + [1225] = 1225, + [1226] = 1226, + [1227] = 1227, + [1228] = 1116, + [1229] = 361, + [1230] = 362, + [1231] = 1051, + [1232] = 1052, + [1233] = 1053, + [1234] = 1054, + [1235] = 1235, + [1236] = 1084, + [1237] = 1237, + [1238] = 1061, + [1239] = 1239, + [1240] = 1240, + [1241] = 1062, + [1242] = 1242, + [1243] = 556, + [1244] = 1242, + [1245] = 1245, + [1246] = 266, + [1247] = 366, + [1248] = 275, + [1249] = 1067, + [1250] = 1225, + [1251] = 1240, + [1252] = 1252, + [1253] = 1252, + [1254] = 290, + [1255] = 1068, + [1256] = 367, + [1257] = 1050, + [1258] = 369, + [1259] = 370, + [1260] = 372, + [1261] = 373, + [1262] = 683, + [1263] = 684, + [1264] = 1064, + [1265] = 374, + [1266] = 376, + [1267] = 1267, + [1268] = 1268, + [1269] = 1084, + [1270] = 1072, + [1271] = 1074, + [1272] = 283, + [1273] = 379, + [1274] = 380, + [1275] = 381, + [1276] = 382, + [1277] = 383, + [1278] = 384, + [1279] = 385, + [1280] = 386, + [1281] = 273, + [1282] = 346, + [1283] = 347, + [1284] = 388, + [1285] = 389, + [1286] = 390, + [1287] = 378, + [1288] = 327, + [1289] = 298, + [1290] = 355, + [1291] = 335, + [1292] = 1292, + [1293] = 677, + [1294] = 358, + [1295] = 368, + [1296] = 299, + [1297] = 301, + [1298] = 677, + [1299] = 1299, + [1300] = 305, + [1301] = 1110, + [1302] = 348, + [1303] = 307, + [1304] = 349, + [1305] = 1113, + [1306] = 350, + [1307] = 351, + [1308] = 1114, + [1309] = 352, + [1310] = 353, + [1311] = 1116, + [1312] = 1292, + [1313] = 1313, + [1314] = 284, + [1315] = 677, + [1316] = 366, + [1317] = 1050, + [1318] = 367, + [1319] = 1319, + [1320] = 285, + [1321] = 369, + [1322] = 1064, + [1323] = 370, + [1324] = 391, + [1325] = 286, + [1326] = 1132, + [1327] = 1327, + [1328] = 372, + [1329] = 373, + [1330] = 288, + [1331] = 374, + [1332] = 1235, + [1333] = 320, + [1334] = 376, + [1335] = 1335, + [1336] = 1132, + [1337] = 1335, + [1338] = 382, + [1339] = 383, + [1340] = 384, + [1341] = 385, + [1342] = 378, + [1343] = 327, + [1344] = 321, + [1345] = 563, + [1346] = 298, + [1347] = 324, + [1348] = 266, + [1349] = 355, + [1350] = 354, + [1351] = 363, + [1352] = 275, + [1353] = 266, + [1354] = 1051, + [1355] = 371, + [1356] = 275, + [1357] = 1052, + [1358] = 1053, + [1359] = 1239, + [1360] = 1054, + [1361] = 320, + [1362] = 375, + [1363] = 377, + [1364] = 387, + [1365] = 292, + [1366] = 1061, + [1367] = 321, + [1368] = 1062, + [1369] = 324, + [1370] = 269, + [1371] = 1327, + [1372] = 1245, + [1373] = 354, + [1374] = 271, + [1375] = 293, + [1376] = 294, + [1377] = 295, + [1378] = 296, + [1379] = 1319, + [1380] = 336, + [1381] = 337, + [1382] = 297, + [1383] = 391, + [1384] = 363, + [1385] = 371, + [1386] = 340, + [1387] = 341, + [1388] = 342, + [1389] = 343, + [1390] = 344, + [1391] = 1067, + [1392] = 1068, + [1393] = 345, + [1394] = 346, + [1395] = 347, + [1396] = 293, + [1397] = 294, + [1398] = 637, + [1399] = 295, + [1400] = 639, + [1401] = 348, + [1402] = 349, + [1403] = 296, + [1404] = 350, + [1405] = 1072, + [1406] = 1074, + [1407] = 351, + [1408] = 297, + [1409] = 1226, + [1410] = 1410, + [1411] = 1116, + [1412] = 1412, + [1413] = 1062, + [1414] = 1061, + [1415] = 1415, + [1416] = 1416, + [1417] = 1417, + [1418] = 1418, + [1419] = 1419, + [1420] = 1110, + [1421] = 1072, + [1422] = 1064, + [1423] = 1050, + [1424] = 290, + [1425] = 1074, + [1426] = 1426, + [1427] = 1427, + [1428] = 1428, + [1429] = 1429, + [1430] = 1410, + [1431] = 1431, + [1432] = 1432, + [1433] = 1410, + [1434] = 1431, + [1435] = 1432, + [1436] = 1436, + [1437] = 1436, + [1438] = 1410, + [1439] = 1431, + [1440] = 1432, + [1441] = 1436, + [1442] = 1113, + [1443] = 1443, + [1444] = 1444, + [1445] = 1445, + [1446] = 1446, + [1447] = 1447, + [1448] = 1062, + [1449] = 1449, + [1450] = 1450, + [1451] = 1067, + [1452] = 1452, + [1453] = 1114, + [1454] = 1454, + [1455] = 266, + [1456] = 1456, + [1457] = 1447, + [1458] = 1068, + [1459] = 1447, + [1460] = 1449, + [1461] = 1461, + [1462] = 275, + [1463] = 1114, + [1464] = 1464, + [1465] = 1465, + [1466] = 1052, + [1467] = 1116, + [1468] = 1447, + [1469] = 1053, + [1470] = 1084, + [1471] = 1449, + [1472] = 1410, + [1473] = 1447, + [1474] = 1432, + [1475] = 677, + [1476] = 1449, + [1477] = 1067, + [1478] = 1410, + [1479] = 1431, + [1480] = 1432, + [1481] = 1436, + [1482] = 1054, + [1483] = 1431, + [1484] = 1484, + [1485] = 1485, + [1486] = 1436, + [1487] = 283, + [1488] = 1488, + [1489] = 1489, + [1490] = 1490, + [1491] = 1491, + [1492] = 1492, + [1493] = 1493, + [1494] = 1432, + [1495] = 1072, + [1496] = 1496, + [1497] = 1497, + [1498] = 1410, + [1499] = 1499, + [1500] = 1068, + [1501] = 1061, + [1502] = 1502, + [1503] = 1431, + [1504] = 1432, + [1505] = 1436, + [1506] = 1110, + [1507] = 1074, + [1508] = 1436, + [1509] = 1050, + [1510] = 1410, + [1511] = 1431, + [1512] = 1432, + [1513] = 1436, + [1514] = 1514, + [1515] = 1515, + [1516] = 1449, + [1517] = 1064, + [1518] = 1132, + [1519] = 1431, + [1520] = 1520, + [1521] = 1051, + [1522] = 273, + [1523] = 1052, + [1524] = 1053, + [1525] = 1447, + [1526] = 1526, + [1527] = 1449, + [1528] = 1054, + [1529] = 1529, + [1530] = 1530, + [1531] = 1531, + [1532] = 1532, + [1533] = 1533, + [1534] = 1113, + [1535] = 1051, + [1536] = 1536, + [1537] = 1537, + [1538] = 1410, + [1539] = 1431, + [1540] = 1432, + [1541] = 1436, + [1542] = 1410, + [1543] = 1431, + [1544] = 1432, + [1545] = 1410, + [1546] = 1431, + [1547] = 1432, + [1548] = 1410, + [1549] = 1431, + [1550] = 1432, + [1551] = 1551, + [1552] = 1431, + [1553] = 1432, + [1554] = 1410, + [1555] = 1431, + [1556] = 1432, + [1557] = 1410, + [1558] = 1431, + [1559] = 1432, + [1560] = 1410, + [1561] = 1431, + [1562] = 1410, + [1563] = 1431, + [1564] = 1410, + [1565] = 1410, + [1566] = 1410, + [1567] = 1410, + [1568] = 1410, + [1569] = 1410, + [1570] = 1410, + [1571] = 1410, + [1572] = 1410, + [1573] = 1410, + [1574] = 1410, + [1575] = 1410, + [1576] = 1410, + [1577] = 1410, + [1578] = 1410, +}; + +static bool ts_lex(TSLexer *lexer, TSStateId state) { + START_LEXER(); + eof = lexer->eof(lexer); + switch (state) { + case 0: + ACCEPT_TOKEN(ts_builtin_sym_end); + if (eof) ADVANCE(1); + END_STATE(); + case 1: + ACCEPT_TOKEN(ts_builtin_sym_end); + END_STATE(); + default: + return false; + } +} + +static const TSLexMode ts_lex_modes[STATE_COUNT] = { + [0] = {.lex_state = 0, .external_lex_state = 1}, + [1] = {.lex_state = 0, .external_lex_state = 2}, + [2] = {.lex_state = 0, .external_lex_state = 3}, + [3] = {.lex_state = 0, .external_lex_state = 3}, + [4] = {.lex_state = 0, .external_lex_state = 3}, + [5] = {.lex_state = 0, .external_lex_state = 3}, + [6] = {.lex_state = 0, .external_lex_state = 3}, + [7] = {.lex_state = 0, .external_lex_state = 3}, + [8] = {.lex_state = 0, .external_lex_state = 4}, + [9] = {.lex_state = 0, .external_lex_state = 4}, + [10] = {.lex_state = 0, .external_lex_state = 4}, + [11] = {.lex_state = 0, .external_lex_state = 5}, + [12] = {.lex_state = 0, .external_lex_state = 6}, + [13] = {.lex_state = 0, .external_lex_state = 7}, + [14] = {.lex_state = 0, .external_lex_state = 7}, + [15] = {.lex_state = 0, .external_lex_state = 7}, + [16] = {.lex_state = 0, .external_lex_state = 7}, + [17] = {.lex_state = 0, .external_lex_state = 7}, + [18] = {.lex_state = 0, .external_lex_state = 7}, + [19] = {.lex_state = 0, .external_lex_state = 7}, + [20] = {.lex_state = 0, .external_lex_state = 7}, + [21] = {.lex_state = 0, .external_lex_state = 7}, + [22] = {.lex_state = 0, .external_lex_state = 7}, + [23] = {.lex_state = 0, .external_lex_state = 7}, + [24] = {.lex_state = 0, .external_lex_state = 8}, + [25] = {.lex_state = 0, .external_lex_state = 8}, + [26] = {.lex_state = 0, .external_lex_state = 8}, + [27] = {.lex_state = 0, .external_lex_state = 8}, + [28] = {.lex_state = 0, .external_lex_state = 8}, + [29] = {.lex_state = 0, .external_lex_state = 8}, + [30] = {.lex_state = 0, .external_lex_state = 8}, + [31] = {.lex_state = 0, .external_lex_state = 8}, + [32] = {.lex_state = 0, .external_lex_state = 8}, + [33] = {.lex_state = 0, .external_lex_state = 8}, + [34] = {.lex_state = 0, .external_lex_state = 8}, + [35] = {.lex_state = 0, .external_lex_state = 9}, + [36] = {.lex_state = 0, .external_lex_state = 9}, + [37] = {.lex_state = 0, .external_lex_state = 10}, + [38] = {.lex_state = 0, .external_lex_state = 10}, + [39] = {.lex_state = 0, .external_lex_state = 10}, + [40] = {.lex_state = 0, .external_lex_state = 11}, + [41] = {.lex_state = 0, .external_lex_state = 12}, + [42] = {.lex_state = 0, .external_lex_state = 7}, + [43] = {.lex_state = 0, .external_lex_state = 7}, + [44] = {.lex_state = 0, .external_lex_state = 7}, + [45] = {.lex_state = 0, .external_lex_state = 7}, + [46] = {.lex_state = 0, .external_lex_state = 7}, + [47] = {.lex_state = 0, .external_lex_state = 7}, + [48] = {.lex_state = 0, .external_lex_state = 7}, + [49] = {.lex_state = 0, .external_lex_state = 7}, + [50] = {.lex_state = 0, .external_lex_state = 7}, + [51] = {.lex_state = 0, .external_lex_state = 7}, + [52] = {.lex_state = 0, .external_lex_state = 7}, + [53] = {.lex_state = 0, .external_lex_state = 7}, + [54] = {.lex_state = 0, .external_lex_state = 7}, + [55] = {.lex_state = 0, .external_lex_state = 12}, + [56] = {.lex_state = 0, .external_lex_state = 8}, + [57] = {.lex_state = 0, .external_lex_state = 8}, + [58] = {.lex_state = 0, .external_lex_state = 8}, + [59] = {.lex_state = 0, .external_lex_state = 8}, + [60] = {.lex_state = 0, .external_lex_state = 8}, + [61] = {.lex_state = 0, .external_lex_state = 8}, + [62] = {.lex_state = 0, .external_lex_state = 8}, + [63] = {.lex_state = 0, .external_lex_state = 8}, + [64] = {.lex_state = 0, .external_lex_state = 8}, + [65] = {.lex_state = 0, .external_lex_state = 8}, + [66] = {.lex_state = 0, .external_lex_state = 8}, + [67] = {.lex_state = 0, .external_lex_state = 8}, + [68] = {.lex_state = 0, .external_lex_state = 8}, + [69] = {.lex_state = 0, .external_lex_state = 11}, + [70] = {.lex_state = 0, .external_lex_state = 7}, + [71] = {.lex_state = 0, .external_lex_state = 7}, + [72] = {.lex_state = 0, .external_lex_state = 7}, + [73] = {.lex_state = 0, .external_lex_state = 7}, + [74] = {.lex_state = 0, .external_lex_state = 8}, + [75] = {.lex_state = 0, .external_lex_state = 8}, + [76] = {.lex_state = 0, .external_lex_state = 8}, + [77] = {.lex_state = 0, .external_lex_state = 8}, + [78] = {.lex_state = 0, .external_lex_state = 13}, + [79] = {.lex_state = 0, .external_lex_state = 13}, + [80] = {.lex_state = 0, .external_lex_state = 14}, + [81] = {.lex_state = 0, .external_lex_state = 14}, + [82] = {.lex_state = 0, .external_lex_state = 15}, + [83] = {.lex_state = 0, .external_lex_state = 15}, + [84] = {.lex_state = 0, .external_lex_state = 11}, + [85] = {.lex_state = 0, .external_lex_state = 12}, + [86] = {.lex_state = 0, .external_lex_state = 12}, + [87] = {.lex_state = 0, .external_lex_state = 11}, + [88] = {.lex_state = 0, .external_lex_state = 11}, + [89] = {.lex_state = 0, .external_lex_state = 11}, + [90] = {.lex_state = 0, .external_lex_state = 12}, + [91] = {.lex_state = 0, .external_lex_state = 12}, + [92] = {.lex_state = 0, .external_lex_state = 12}, + [93] = {.lex_state = 0, .external_lex_state = 11}, + [94] = {.lex_state = 0, .external_lex_state = 11}, + [95] = {.lex_state = 0, .external_lex_state = 12}, + [96] = {.lex_state = 0, .external_lex_state = 16}, + [97] = {.lex_state = 0, .external_lex_state = 16}, + [98] = {.lex_state = 0, .external_lex_state = 17}, + [99] = {.lex_state = 0, .external_lex_state = 18}, + [100] = {.lex_state = 0, .external_lex_state = 18}, + [101] = {.lex_state = 0, .external_lex_state = 18}, + [102] = {.lex_state = 0, .external_lex_state = 18}, + [103] = {.lex_state = 0, .external_lex_state = 19}, + [104] = {.lex_state = 0, .external_lex_state = 19}, + [105] = {.lex_state = 0, .external_lex_state = 20}, + [106] = {.lex_state = 0, .external_lex_state = 20}, + [107] = {.lex_state = 0, .external_lex_state = 19}, + [108] = {.lex_state = 0, .external_lex_state = 9}, + [109] = {.lex_state = 0, .external_lex_state = 9}, + [110] = {.lex_state = 0, .external_lex_state = 9}, + [111] = {.lex_state = 0, .external_lex_state = 9}, + [112] = {.lex_state = 0, .external_lex_state = 21}, + [113] = {.lex_state = 0, .external_lex_state = 21}, + [114] = {.lex_state = 0, .external_lex_state = 22}, + [115] = {.lex_state = 0, .external_lex_state = 22}, + [116] = {.lex_state = 0, .external_lex_state = 23}, + [117] = {.lex_state = 0, .external_lex_state = 24}, + [118] = {.lex_state = 0, .external_lex_state = 23}, + [119] = {.lex_state = 0, .external_lex_state = 25}, + [120] = {.lex_state = 0, .external_lex_state = 25}, + [121] = {.lex_state = 0, .external_lex_state = 24}, + [122] = {.lex_state = 0, .external_lex_state = 26}, + [123] = {.lex_state = 0, .external_lex_state = 26}, + [124] = {.lex_state = 0, .external_lex_state = 27}, + [125] = {.lex_state = 0, .external_lex_state = 28}, + [126] = {.lex_state = 0, .external_lex_state = 29}, + [127] = {.lex_state = 0, .external_lex_state = 30}, + [128] = {.lex_state = 0, .external_lex_state = 28}, + [129] = {.lex_state = 0, .external_lex_state = 30}, + [130] = {.lex_state = 0, .external_lex_state = 28}, + [131] = {.lex_state = 0, .external_lex_state = 30}, + [132] = {.lex_state = 0, .external_lex_state = 31}, + [133] = {.lex_state = 0, .external_lex_state = 29}, + [134] = {.lex_state = 0, .external_lex_state = 28}, + [135] = {.lex_state = 0, .external_lex_state = 28}, + [136] = {.lex_state = 0, .external_lex_state = 31}, + [137] = {.lex_state = 0, .external_lex_state = 29}, + [138] = {.lex_state = 0, .external_lex_state = 28}, + [139] = {.lex_state = 0, .external_lex_state = 28}, + [140] = {.lex_state = 0, .external_lex_state = 31}, + [141] = {.lex_state = 0, .external_lex_state = 29}, + [142] = {.lex_state = 0, .external_lex_state = 28}, + [143] = {.lex_state = 0, .external_lex_state = 28}, + [144] = {.lex_state = 0, .external_lex_state = 28}, + [145] = {.lex_state = 0, .external_lex_state = 28}, + [146] = {.lex_state = 0, .external_lex_state = 30}, + [147] = {.lex_state = 0, .external_lex_state = 31}, + [148] = {.lex_state = 0, .external_lex_state = 29}, + [149] = {.lex_state = 0, .external_lex_state = 28}, + [150] = {.lex_state = 0, .external_lex_state = 28}, + [151] = {.lex_state = 0, .external_lex_state = 31}, + [152] = {.lex_state = 0, .external_lex_state = 29}, + [153] = {.lex_state = 0, .external_lex_state = 31}, + [154] = {.lex_state = 0, .external_lex_state = 29}, + [155] = {.lex_state = 0, .external_lex_state = 31}, + [156] = {.lex_state = 0, .external_lex_state = 32}, + [157] = {.lex_state = 0, .external_lex_state = 32}, + [158] = {.lex_state = 0, .external_lex_state = 32}, + [159] = {.lex_state = 0, .external_lex_state = 33}, + [160] = {.lex_state = 0, .external_lex_state = 34}, + [161] = {.lex_state = 0, .external_lex_state = 34}, + [162] = {.lex_state = 0, .external_lex_state = 35}, + [163] = {.lex_state = 0, .external_lex_state = 32}, + [164] = {.lex_state = 0, .external_lex_state = 35}, + [165] = {.lex_state = 0, .external_lex_state = 33}, + [166] = {.lex_state = 0, .external_lex_state = 33}, + [167] = {.lex_state = 0, .external_lex_state = 31}, + [168] = {.lex_state = 0, .external_lex_state = 36}, + [169] = {.lex_state = 0, .external_lex_state = 14}, + [170] = {.lex_state = 0, .external_lex_state = 14}, + [171] = {.lex_state = 0, .external_lex_state = 14}, + [172] = {.lex_state = 0, .external_lex_state = 36}, + [173] = {.lex_state = 0, .external_lex_state = 36}, + [174] = {.lex_state = 0, .external_lex_state = 29}, + [175] = {.lex_state = 0, .external_lex_state = 29}, + [176] = {.lex_state = 0, .external_lex_state = 14}, + [177] = {.lex_state = 0, .external_lex_state = 31}, + [178] = {.lex_state = 0, .external_lex_state = 15}, + [179] = {.lex_state = 0, .external_lex_state = 15}, + [180] = {.lex_state = 0, .external_lex_state = 15}, + [181] = {.lex_state = 0, .external_lex_state = 37}, + [182] = {.lex_state = 0, .external_lex_state = 37}, + [183] = {.lex_state = 0, .external_lex_state = 38}, + [184] = {.lex_state = 0, .external_lex_state = 38}, + [185] = {.lex_state = 0, .external_lex_state = 38}, + [186] = {.lex_state = 0, .external_lex_state = 39}, + [187] = {.lex_state = 0, .external_lex_state = 39}, + [188] = {.lex_state = 0, .external_lex_state = 39}, + [189] = {.lex_state = 0, .external_lex_state = 40}, + [190] = {.lex_state = 0, .external_lex_state = 41}, + [191] = {.lex_state = 0, .external_lex_state = 41}, + [192] = {.lex_state = 0, .external_lex_state = 42}, + [193] = {.lex_state = 0, .external_lex_state = 43}, + [194] = {.lex_state = 0, .external_lex_state = 41}, + [195] = {.lex_state = 0, .external_lex_state = 43}, + [196] = {.lex_state = 0, .external_lex_state = 41}, + [197] = {.lex_state = 0, .external_lex_state = 41}, + [198] = {.lex_state = 0, .external_lex_state = 42}, + [199] = {.lex_state = 0, .external_lex_state = 44}, + [200] = {.lex_state = 0, .external_lex_state = 40}, + [201] = {.lex_state = 0, .external_lex_state = 43}, + [202] = {.lex_state = 0, .external_lex_state = 40}, + [203] = {.lex_state = 0, .external_lex_state = 44}, + [204] = {.lex_state = 0, .external_lex_state = 42}, + [205] = {.lex_state = 0, .external_lex_state = 44}, + [206] = {.lex_state = 0, .external_lex_state = 45}, + [207] = {.lex_state = 0, .external_lex_state = 45}, + [208] = {.lex_state = 0, .external_lex_state = 45}, + [209] = {.lex_state = 0, .external_lex_state = 45}, + [210] = {.lex_state = 0, .external_lex_state = 45}, + [211] = {.lex_state = 0, .external_lex_state = 46}, + [212] = {.lex_state = 0, .external_lex_state = 46}, + [213] = {.lex_state = 0, .external_lex_state = 46}, + [214] = {.lex_state = 0, .external_lex_state = 47}, + [215] = {.lex_state = 0, .external_lex_state = 47}, + [216] = {.lex_state = 0, .external_lex_state = 21}, + [217] = {.lex_state = 0, .external_lex_state = 21}, + [218] = {.lex_state = 0, .external_lex_state = 46}, + [219] = {.lex_state = 0, .external_lex_state = 21}, + [220] = {.lex_state = 0, .external_lex_state = 46}, + [221] = {.lex_state = 0, .external_lex_state = 21}, + [222] = {.lex_state = 0, .external_lex_state = 21}, + [223] = {.lex_state = 0, .external_lex_state = 47}, + [224] = {.lex_state = 0, .external_lex_state = 47}, + [225] = {.lex_state = 0, .external_lex_state = 47}, + [226] = {.lex_state = 0, .external_lex_state = 48}, + [227] = {.lex_state = 0, .external_lex_state = 22}, + [228] = {.lex_state = 0, .external_lex_state = 22}, + [229] = {.lex_state = 0, .external_lex_state = 48}, + [230] = {.lex_state = 0, .external_lex_state = 22}, + [231] = {.lex_state = 0, .external_lex_state = 22}, + [232] = {.lex_state = 0, .external_lex_state = 22}, + [233] = {.lex_state = 0, .external_lex_state = 48}, + [234] = {.lex_state = 0, .external_lex_state = 24}, + [235] = {.lex_state = 0, .external_lex_state = 24}, + [236] = {.lex_state = 0, .external_lex_state = 24}, + [237] = {.lex_state = 0, .external_lex_state = 25}, + [238] = {.lex_state = 0, .external_lex_state = 24}, + [239] = {.lex_state = 0, .external_lex_state = 24}, + [240] = {.lex_state = 0, .external_lex_state = 25}, + [241] = {.lex_state = 0, .external_lex_state = 25}, + [242] = {.lex_state = 0, .external_lex_state = 25}, + [243] = {.lex_state = 0, .external_lex_state = 25}, + [244] = {.lex_state = 0, .external_lex_state = 49}, + [245] = {.lex_state = 0, .external_lex_state = 49}, + [246] = {.lex_state = 0, .external_lex_state = 49}, + [247] = {.lex_state = 0, .external_lex_state = 49}, + [248] = {.lex_state = 0, .external_lex_state = 49}, + [249] = {.lex_state = 0, .external_lex_state = 10}, + [250] = {.lex_state = 0, .external_lex_state = 10}, + [251] = {.lex_state = 0, .external_lex_state = 10}, + [252] = {.lex_state = 0, .external_lex_state = 10}, + [253] = {.lex_state = 0, .external_lex_state = 10}, + [254] = {.lex_state = 0, .external_lex_state = 10}, + [255] = {.lex_state = 0, .external_lex_state = 10}, + [256] = {.lex_state = 0, .external_lex_state = 35}, + [257] = {.lex_state = 0, .external_lex_state = 35}, + [258] = {.lex_state = 0, .external_lex_state = 35}, + [259] = {.lex_state = 0, .external_lex_state = 35}, + [260] = {.lex_state = 0, .external_lex_state = 35}, + [261] = {.lex_state = 0, .external_lex_state = 50}, + [262] = {.lex_state = 0, .external_lex_state = 51}, + [263] = {.lex_state = 0, .external_lex_state = 51}, + [264] = {.lex_state = 0, .external_lex_state = 51}, + [265] = {.lex_state = 0, .external_lex_state = 52}, + [266] = {.lex_state = 0, .external_lex_state = 51}, + [267] = {.lex_state = 0, .external_lex_state = 51}, + [268] = {.lex_state = 0, .external_lex_state = 51}, + [269] = {.lex_state = 0, .external_lex_state = 51}, + [270] = {.lex_state = 0, .external_lex_state = 51}, + [271] = {.lex_state = 0, .external_lex_state = 51}, + [272] = {.lex_state = 0, .external_lex_state = 51}, + [273] = {.lex_state = 0, .external_lex_state = 51}, + [274] = {.lex_state = 0, .external_lex_state = 53}, + [275] = {.lex_state = 0, .external_lex_state = 51}, + [276] = {.lex_state = 0, .external_lex_state = 54}, + [277] = {.lex_state = 0, .external_lex_state = 28}, + [278] = {.lex_state = 0, .external_lex_state = 28}, + [279] = {.lex_state = 0, .external_lex_state = 28}, + [280] = {.lex_state = 0, .external_lex_state = 51}, + [281] = {.lex_state = 0, .external_lex_state = 51}, + [282] = {.lex_state = 0, .external_lex_state = 51}, + [283] = {.lex_state = 0, .external_lex_state = 51}, + [284] = {.lex_state = 0, .external_lex_state = 51}, + [285] = {.lex_state = 0, .external_lex_state = 51}, + [286] = {.lex_state = 0, .external_lex_state = 51}, + [287] = {.lex_state = 0, .external_lex_state = 51}, + [288] = {.lex_state = 0, .external_lex_state = 51}, + [289] = {.lex_state = 0, .external_lex_state = 51}, + [290] = {.lex_state = 0, .external_lex_state = 51}, + [291] = {.lex_state = 0, .external_lex_state = 28}, + [292] = {.lex_state = 0, .external_lex_state = 28}, + [293] = {.lex_state = 0, .external_lex_state = 28}, + [294] = {.lex_state = 0, .external_lex_state = 28}, + [295] = {.lex_state = 0, .external_lex_state = 28}, + [296] = {.lex_state = 0, .external_lex_state = 28}, + [297] = {.lex_state = 0, .external_lex_state = 28}, + [298] = {.lex_state = 0, .external_lex_state = 28}, + [299] = {.lex_state = 0, .external_lex_state = 28}, + [300] = {.lex_state = 0, .external_lex_state = 28}, + [301] = {.lex_state = 0, .external_lex_state = 28}, + [302] = {.lex_state = 0, .external_lex_state = 28}, + [303] = {.lex_state = 0, .external_lex_state = 28}, + [304] = {.lex_state = 0, .external_lex_state = 28}, + [305] = {.lex_state = 0, .external_lex_state = 28}, + [306] = {.lex_state = 0, .external_lex_state = 28}, + [307] = {.lex_state = 0, .external_lex_state = 28}, + [308] = {.lex_state = 0, .external_lex_state = 55}, + [309] = {.lex_state = 0, .external_lex_state = 55}, + [310] = {.lex_state = 0, .external_lex_state = 28}, + [311] = {.lex_state = 0, .external_lex_state = 28}, + [312] = {.lex_state = 0, .external_lex_state = 28}, + [313] = {.lex_state = 0, .external_lex_state = 28}, + [314] = {.lex_state = 0, .external_lex_state = 28}, + [315] = {.lex_state = 0, .external_lex_state = 28}, + [316] = {.lex_state = 0, .external_lex_state = 28}, + [317] = {.lex_state = 0, .external_lex_state = 28}, + [318] = {.lex_state = 0, .external_lex_state = 28}, + [319] = {.lex_state = 0, .external_lex_state = 28}, + [320] = {.lex_state = 0, .external_lex_state = 28}, + [321] = {.lex_state = 0, .external_lex_state = 28}, + [322] = {.lex_state = 0, .external_lex_state = 55}, + [323] = {.lex_state = 0, .external_lex_state = 28}, + [324] = {.lex_state = 0, .external_lex_state = 28}, + [325] = {.lex_state = 0, .external_lex_state = 28}, + [326] = {.lex_state = 0, .external_lex_state = 28}, + [327] = {.lex_state = 0, .external_lex_state = 28}, + [328] = {.lex_state = 0, .external_lex_state = 28}, + [329] = {.lex_state = 0, .external_lex_state = 28}, + [330] = {.lex_state = 0, .external_lex_state = 28}, + [331] = {.lex_state = 0, .external_lex_state = 28}, + [332] = {.lex_state = 0, .external_lex_state = 28}, + [333] = {.lex_state = 0, .external_lex_state = 28}, + [334] = {.lex_state = 0, .external_lex_state = 28}, + [335] = {.lex_state = 0, .external_lex_state = 28}, + [336] = {.lex_state = 0, .external_lex_state = 28}, + [337] = {.lex_state = 0, .external_lex_state = 28}, + [338] = {.lex_state = 0, .external_lex_state = 28}, + [339] = {.lex_state = 0, .external_lex_state = 28}, + [340] = {.lex_state = 0, .external_lex_state = 28}, + [341] = {.lex_state = 0, .external_lex_state = 28}, + [342] = {.lex_state = 0, .external_lex_state = 28}, + [343] = {.lex_state = 0, .external_lex_state = 28}, + [344] = {.lex_state = 0, .external_lex_state = 28}, + [345] = {.lex_state = 0, .external_lex_state = 28}, + [346] = {.lex_state = 0, .external_lex_state = 28}, + [347] = {.lex_state = 0, .external_lex_state = 28}, + [348] = {.lex_state = 0, .external_lex_state = 28}, + [349] = {.lex_state = 0, .external_lex_state = 28}, + [350] = {.lex_state = 0, .external_lex_state = 28}, + [351] = {.lex_state = 0, .external_lex_state = 28}, + [352] = {.lex_state = 0, .external_lex_state = 28}, + [353] = {.lex_state = 0, .external_lex_state = 28}, + [354] = {.lex_state = 0, .external_lex_state = 28}, + [355] = {.lex_state = 0, .external_lex_state = 28}, + [356] = {.lex_state = 0, .external_lex_state = 28}, + [357] = {.lex_state = 0, .external_lex_state = 28}, + [358] = {.lex_state = 0, .external_lex_state = 28}, + [359] = {.lex_state = 0, .external_lex_state = 28}, + [360] = {.lex_state = 0, .external_lex_state = 28}, + [361] = {.lex_state = 0, .external_lex_state = 28}, + [362] = {.lex_state = 0, .external_lex_state = 28}, + [363] = {.lex_state = 0, .external_lex_state = 28}, + [364] = {.lex_state = 0, .external_lex_state = 28}, + [365] = {.lex_state = 0, .external_lex_state = 56}, + [366] = {.lex_state = 0, .external_lex_state = 28}, + [367] = {.lex_state = 0, .external_lex_state = 28}, + [368] = {.lex_state = 0, .external_lex_state = 28}, + [369] = {.lex_state = 0, .external_lex_state = 28}, + [370] = {.lex_state = 0, .external_lex_state = 28}, + [371] = {.lex_state = 0, .external_lex_state = 28}, + [372] = {.lex_state = 0, .external_lex_state = 28}, + [373] = {.lex_state = 0, .external_lex_state = 28}, + [374] = {.lex_state = 0, .external_lex_state = 28}, + [375] = {.lex_state = 0, .external_lex_state = 28}, + [376] = {.lex_state = 0, .external_lex_state = 28}, + [377] = {.lex_state = 0, .external_lex_state = 28}, + [378] = {.lex_state = 0, .external_lex_state = 28}, + [379] = {.lex_state = 0, .external_lex_state = 28}, + [380] = {.lex_state = 0, .external_lex_state = 28}, + [381] = {.lex_state = 0, .external_lex_state = 28}, + [382] = {.lex_state = 0, .external_lex_state = 28}, + [383] = {.lex_state = 0, .external_lex_state = 28}, + [384] = {.lex_state = 0, .external_lex_state = 28}, + [385] = {.lex_state = 0, .external_lex_state = 28}, + [386] = {.lex_state = 0, .external_lex_state = 28}, + [387] = {.lex_state = 0, .external_lex_state = 28}, + [388] = {.lex_state = 0, .external_lex_state = 28}, + [389] = {.lex_state = 0, .external_lex_state = 28}, + [390] = {.lex_state = 0, .external_lex_state = 28}, + [391] = {.lex_state = 0, .external_lex_state = 28}, + [392] = {.lex_state = 0, .external_lex_state = 57}, + [393] = {.lex_state = 0, .external_lex_state = 58}, + [394] = {.lex_state = 0, .external_lex_state = 59}, + [395] = {.lex_state = 0, .external_lex_state = 60}, + [396] = {.lex_state = 0, .external_lex_state = 61}, + [397] = {.lex_state = 0, .external_lex_state = 60}, + [398] = {.lex_state = 0, .external_lex_state = 62}, + [399] = {.lex_state = 0, .external_lex_state = 62}, + [400] = {.lex_state = 0, .external_lex_state = 52}, + [401] = {.lex_state = 0, .external_lex_state = 63}, + [402] = {.lex_state = 0, .external_lex_state = 50}, + [403] = {.lex_state = 0, .external_lex_state = 64}, + [404] = {.lex_state = 0, .external_lex_state = 65}, + [405] = {.lex_state = 0, .external_lex_state = 66}, + [406] = {.lex_state = 0, .external_lex_state = 50}, + [407] = {.lex_state = 0, .external_lex_state = 63}, + [408] = {.lex_state = 0, .external_lex_state = 52}, + [409] = {.lex_state = 0, .external_lex_state = 66}, + [410] = {.lex_state = 0, .external_lex_state = 65}, + [411] = {.lex_state = 0, .external_lex_state = 53}, + [412] = {.lex_state = 0, .external_lex_state = 67}, + [413] = {.lex_state = 0, .external_lex_state = 67}, + [414] = {.lex_state = 0, .external_lex_state = 54}, + [415] = {.lex_state = 0, .external_lex_state = 68}, + [416] = {.lex_state = 0, .external_lex_state = 68}, + [417] = {.lex_state = 0, .external_lex_state = 53}, + [418] = {.lex_state = 0, .external_lex_state = 68}, + [419] = {.lex_state = 0, .external_lex_state = 54}, + [420] = {.lex_state = 0, .external_lex_state = 68}, + [421] = {.lex_state = 0, .external_lex_state = 69}, + [422] = {.lex_state = 0, .external_lex_state = 69}, + [423] = {.lex_state = 0, .external_lex_state = 69}, + [424] = {.lex_state = 0, .external_lex_state = 55}, + [425] = {.lex_state = 0, .external_lex_state = 55}, + [426] = {.lex_state = 0, .external_lex_state = 69}, + [427] = {.lex_state = 0, .external_lex_state = 69}, + [428] = {.lex_state = 0, .external_lex_state = 69}, + [429] = {.lex_state = 0, .external_lex_state = 69}, + [430] = {.lex_state = 0, .external_lex_state = 69}, + [431] = {.lex_state = 0, .external_lex_state = 69}, + [432] = {.lex_state = 0, .external_lex_state = 69}, + [433] = {.lex_state = 0, .external_lex_state = 69}, + [434] = {.lex_state = 0, .external_lex_state = 69}, + [435] = {.lex_state = 0, .external_lex_state = 69}, + [436] = {.lex_state = 0, .external_lex_state = 69}, + [437] = {.lex_state = 0, .external_lex_state = 69}, + [438] = {.lex_state = 0, .external_lex_state = 56}, + [439] = {.lex_state = 0, .external_lex_state = 69}, + [440] = {.lex_state = 0, .external_lex_state = 69}, + [441] = {.lex_state = 0, .external_lex_state = 69}, + [442] = {.lex_state = 0, .external_lex_state = 69}, + [443] = {.lex_state = 0, .external_lex_state = 69}, + [444] = {.lex_state = 0, .external_lex_state = 69}, + [445] = {.lex_state = 0, .external_lex_state = 56}, + [446] = {.lex_state = 0, .external_lex_state = 69}, + [447] = {.lex_state = 0, .external_lex_state = 69}, + [448] = {.lex_state = 0, .external_lex_state = 69}, + [449] = {.lex_state = 0, .external_lex_state = 69}, + [450] = {.lex_state = 0, .external_lex_state = 69}, + [451] = {.lex_state = 0, .external_lex_state = 69}, + [452] = {.lex_state = 0, .external_lex_state = 69}, + [453] = {.lex_state = 0, .external_lex_state = 69}, + [454] = {.lex_state = 0, .external_lex_state = 69}, + [455] = {.lex_state = 0, .external_lex_state = 69}, + [456] = {.lex_state = 0, .external_lex_state = 69}, + [457] = {.lex_state = 0, .external_lex_state = 69}, + [458] = {.lex_state = 0, .external_lex_state = 69}, + [459] = {.lex_state = 0, .external_lex_state = 69}, + [460] = {.lex_state = 0, .external_lex_state = 69}, + [461] = {.lex_state = 0, .external_lex_state = 69}, + [462] = {.lex_state = 0, .external_lex_state = 69}, + [463] = {.lex_state = 0, .external_lex_state = 69}, + [464] = {.lex_state = 0, .external_lex_state = 69}, + [465] = {.lex_state = 0, .external_lex_state = 69}, + [466] = {.lex_state = 0, .external_lex_state = 69}, + [467] = {.lex_state = 0, .external_lex_state = 69}, + [468] = {.lex_state = 0, .external_lex_state = 69}, + [469] = {.lex_state = 0, .external_lex_state = 55}, + [470] = {.lex_state = 0, .external_lex_state = 69}, + [471] = {.lex_state = 0, .external_lex_state = 69}, + [472] = {.lex_state = 0, .external_lex_state = 69}, + [473] = {.lex_state = 0, .external_lex_state = 69}, + [474] = {.lex_state = 0, .external_lex_state = 70}, + [475] = {.lex_state = 0, .external_lex_state = 71}, + [476] = {.lex_state = 0, .external_lex_state = 70}, + [477] = {.lex_state = 0, .external_lex_state = 70}, + [478] = {.lex_state = 0, .external_lex_state = 72}, + [479] = {.lex_state = 0, .external_lex_state = 70}, + [480] = {.lex_state = 0, .external_lex_state = 70}, + [481] = {.lex_state = 0, .external_lex_state = 69}, + [482] = {.lex_state = 0, .external_lex_state = 73}, + [483] = {.lex_state = 0, .external_lex_state = 73}, + [484] = {.lex_state = 0, .external_lex_state = 73}, + [485] = {.lex_state = 0, .external_lex_state = 73}, + [486] = {.lex_state = 0, .external_lex_state = 69}, + [487] = {.lex_state = 0, .external_lex_state = 73}, + [488] = {.lex_state = 0, .external_lex_state = 73}, + [489] = {.lex_state = 0, .external_lex_state = 73}, + [490] = {.lex_state = 0, .external_lex_state = 73}, + [491] = {.lex_state = 0, .external_lex_state = 73}, + [492] = {.lex_state = 0, .external_lex_state = 71}, + [493] = {.lex_state = 0, .external_lex_state = 71}, + [494] = {.lex_state = 0, .external_lex_state = 73}, + [495] = {.lex_state = 0, .external_lex_state = 73}, + [496] = {.lex_state = 0, .external_lex_state = 73}, + [497] = {.lex_state = 0, .external_lex_state = 73}, + [498] = {.lex_state = 0, .external_lex_state = 74}, + [499] = {.lex_state = 0, .external_lex_state = 69}, + [500] = {.lex_state = 0, .external_lex_state = 73}, + [501] = {.lex_state = 0, .external_lex_state = 73}, + [502] = {.lex_state = 0, .external_lex_state = 69}, + [503] = {.lex_state = 0, .external_lex_state = 73}, + [504] = {.lex_state = 0, .external_lex_state = 74}, + [505] = {.lex_state = 0, .external_lex_state = 73}, + [506] = {.lex_state = 0, .external_lex_state = 73}, + [507] = {.lex_state = 0, .external_lex_state = 73}, + [508] = {.lex_state = 0, .external_lex_state = 73}, + [509] = {.lex_state = 0, .external_lex_state = 73}, + [510] = {.lex_state = 0, .external_lex_state = 73}, + [511] = {.lex_state = 0, .external_lex_state = 73}, + [512] = {.lex_state = 0, .external_lex_state = 73}, + [513] = {.lex_state = 0, .external_lex_state = 73}, + [514] = {.lex_state = 0, .external_lex_state = 73}, + [515] = {.lex_state = 0, .external_lex_state = 73}, + [516] = {.lex_state = 0, .external_lex_state = 73}, + [517] = {.lex_state = 0, .external_lex_state = 73}, + [518] = {.lex_state = 0, .external_lex_state = 73}, + [519] = {.lex_state = 0, .external_lex_state = 73}, + [520] = {.lex_state = 0, .external_lex_state = 73}, + [521] = {.lex_state = 0, .external_lex_state = 73}, + [522] = {.lex_state = 0, .external_lex_state = 72}, + [523] = {.lex_state = 0, .external_lex_state = 73}, + [524] = {.lex_state = 0, .external_lex_state = 73}, + [525] = {.lex_state = 0, .external_lex_state = 73}, + [526] = {.lex_state = 0, .external_lex_state = 73}, + [527] = {.lex_state = 0, .external_lex_state = 73}, + [528] = {.lex_state = 0, .external_lex_state = 73}, + [529] = {.lex_state = 0, .external_lex_state = 73}, + [530] = {.lex_state = 0, .external_lex_state = 73}, + [531] = {.lex_state = 0, .external_lex_state = 73}, + [532] = {.lex_state = 0, .external_lex_state = 73}, + [533] = {.lex_state = 0, .external_lex_state = 73}, + [534] = {.lex_state = 0, .external_lex_state = 73}, + [535] = {.lex_state = 0, .external_lex_state = 73}, + [536] = {.lex_state = 0, .external_lex_state = 73}, + [537] = {.lex_state = 0, .external_lex_state = 73}, + [538] = {.lex_state = 0, .external_lex_state = 75}, + [539] = {.lex_state = 0, .external_lex_state = 76}, + [540] = {.lex_state = 0, .external_lex_state = 74}, + [541] = {.lex_state = 0, .external_lex_state = 76}, + [542] = {.lex_state = 0, .external_lex_state = 74}, + [543] = {.lex_state = 0, .external_lex_state = 76}, + [544] = {.lex_state = 0, .external_lex_state = 76}, + [545] = {.lex_state = 0, .external_lex_state = 74}, + [546] = {.lex_state = 0, .external_lex_state = 76}, + [547] = {.lex_state = 0, .external_lex_state = 74}, + [548] = {.lex_state = 0, .external_lex_state = 74}, + [549] = {.lex_state = 0, .external_lex_state = 74}, + [550] = {.lex_state = 0, .external_lex_state = 74}, + [551] = {.lex_state = 0, .external_lex_state = 71}, + [552] = {.lex_state = 0, .external_lex_state = 77}, + [553] = {.lex_state = 0, .external_lex_state = 76}, + [554] = {.lex_state = 0, .external_lex_state = 78}, + [555] = {.lex_state = 0, .external_lex_state = 74}, + [556] = {.lex_state = 0, .external_lex_state = 71}, + [557] = {.lex_state = 0, .external_lex_state = 76}, + [558] = {.lex_state = 0, .external_lex_state = 76}, + [559] = {.lex_state = 0, .external_lex_state = 76}, + [560] = {.lex_state = 0, .external_lex_state = 76}, + [561] = {.lex_state = 0, .external_lex_state = 76}, + [562] = {.lex_state = 0, .external_lex_state = 76}, + [563] = {.lex_state = 0, .external_lex_state = 71}, + [564] = {.lex_state = 0, .external_lex_state = 71}, + [565] = {.lex_state = 0, .external_lex_state = 76}, + [566] = {.lex_state = 0, .external_lex_state = 74}, + [567] = {.lex_state = 0, .external_lex_state = 79}, + [568] = {.lex_state = 0, .external_lex_state = 74}, + [569] = {.lex_state = 0, .external_lex_state = 74}, + [570] = {.lex_state = 0, .external_lex_state = 74}, + [571] = {.lex_state = 0, .external_lex_state = 74}, + [572] = {.lex_state = 0, .external_lex_state = 74}, + [573] = {.lex_state = 0, .external_lex_state = 74}, + [574] = {.lex_state = 0, .external_lex_state = 74}, + [575] = {.lex_state = 0, .external_lex_state = 76}, + [576] = {.lex_state = 0, .external_lex_state = 74}, + [577] = {.lex_state = 0, .external_lex_state = 76}, + [578] = {.lex_state = 0, .external_lex_state = 76}, + [579] = {.lex_state = 0, .external_lex_state = 76}, + [580] = {.lex_state = 0, .external_lex_state = 74}, + [581] = {.lex_state = 0, .external_lex_state = 74}, + [582] = {.lex_state = 0, .external_lex_state = 76}, + [583] = {.lex_state = 0, .external_lex_state = 76}, + [584] = {.lex_state = 0, .external_lex_state = 76}, + [585] = {.lex_state = 0, .external_lex_state = 76}, + [586] = {.lex_state = 0, .external_lex_state = 73}, + [587] = {.lex_state = 0, .external_lex_state = 76}, + [588] = {.lex_state = 0, .external_lex_state = 76}, + [589] = {.lex_state = 0, .external_lex_state = 76}, + [590] = {.lex_state = 0, .external_lex_state = 76}, + [591] = {.lex_state = 0, .external_lex_state = 76}, + [592] = {.lex_state = 0, .external_lex_state = 76}, + [593] = {.lex_state = 0, .external_lex_state = 71}, + [594] = {.lex_state = 0, .external_lex_state = 74}, + [595] = {.lex_state = 0, .external_lex_state = 74}, + [596] = {.lex_state = 0, .external_lex_state = 74}, + [597] = {.lex_state = 0, .external_lex_state = 74}, + [598] = {.lex_state = 0, .external_lex_state = 74}, + [599] = {.lex_state = 0, .external_lex_state = 74}, + [600] = {.lex_state = 0, .external_lex_state = 74}, + [601] = {.lex_state = 0, .external_lex_state = 74}, + [602] = {.lex_state = 0, .external_lex_state = 74}, + [603] = {.lex_state = 0, .external_lex_state = 74}, + [604] = {.lex_state = 0, .external_lex_state = 74}, + [605] = {.lex_state = 0, .external_lex_state = 76}, + [606] = {.lex_state = 0, .external_lex_state = 74}, + [607] = {.lex_state = 0, .external_lex_state = 76}, + [608] = {.lex_state = 0, .external_lex_state = 76}, + [609] = {.lex_state = 0, .external_lex_state = 76}, + [610] = {.lex_state = 0, .external_lex_state = 74}, + [611] = {.lex_state = 0, .external_lex_state = 74}, + [612] = {.lex_state = 0, .external_lex_state = 74}, + [613] = {.lex_state = 0, .external_lex_state = 74}, + [614] = {.lex_state = 0, .external_lex_state = 73}, + [615] = {.lex_state = 0, .external_lex_state = 73}, + [616] = {.lex_state = 0, .external_lex_state = 74}, + [617] = {.lex_state = 0, .external_lex_state = 76}, + [618] = {.lex_state = 0, .external_lex_state = 76}, + [619] = {.lex_state = 0, .external_lex_state = 76}, + [620] = {.lex_state = 0, .external_lex_state = 76}, + [621] = {.lex_state = 0, .external_lex_state = 76}, + [622] = {.lex_state = 0, .external_lex_state = 76}, + [623] = {.lex_state = 0, .external_lex_state = 74}, + [624] = {.lex_state = 0, .external_lex_state = 74}, + [625] = {.lex_state = 0, .external_lex_state = 76}, + [626] = {.lex_state = 0, .external_lex_state = 74}, + [627] = {.lex_state = 0, .external_lex_state = 76}, + [628] = {.lex_state = 0, .external_lex_state = 76}, + [629] = {.lex_state = 0, .external_lex_state = 76}, + [630] = {.lex_state = 0, .external_lex_state = 76}, + [631] = {.lex_state = 0, .external_lex_state = 76}, + [632] = {.lex_state = 0, .external_lex_state = 74}, + [633] = {.lex_state = 0, .external_lex_state = 76}, + [634] = {.lex_state = 0, .external_lex_state = 76}, + [635] = {.lex_state = 0, .external_lex_state = 76}, + [636] = {.lex_state = 0, .external_lex_state = 74}, + [637] = {.lex_state = 0, .external_lex_state = 71}, + [638] = {.lex_state = 0, .external_lex_state = 71}, + [639] = {.lex_state = 0, .external_lex_state = 71}, + [640] = {.lex_state = 0, .external_lex_state = 76}, + [641] = {.lex_state = 0, .external_lex_state = 76}, + [642] = {.lex_state = 0, .external_lex_state = 76}, + [643] = {.lex_state = 0, .external_lex_state = 76}, + [644] = {.lex_state = 0, .external_lex_state = 76}, + [645] = {.lex_state = 0, .external_lex_state = 78}, + [646] = {.lex_state = 0, .external_lex_state = 76}, + [647] = {.lex_state = 0, .external_lex_state = 76}, + [648] = {.lex_state = 0, .external_lex_state = 73}, + [649] = {.lex_state = 0, .external_lex_state = 77}, + [650] = {.lex_state = 0, .external_lex_state = 76}, + [651] = {.lex_state = 0, .external_lex_state = 76}, + [652] = {.lex_state = 0, .external_lex_state = 76}, + [653] = {.lex_state = 0, .external_lex_state = 76}, + [654] = {.lex_state = 0, .external_lex_state = 76}, + [655] = {.lex_state = 0, .external_lex_state = 76}, + [656] = {.lex_state = 0, .external_lex_state = 76}, + [657] = {.lex_state = 0, .external_lex_state = 76}, + [658] = {.lex_state = 0, .external_lex_state = 76}, + [659] = {.lex_state = 0, .external_lex_state = 76}, + [660] = {.lex_state = 0, .external_lex_state = 77}, + [661] = {.lex_state = 0, .external_lex_state = 77}, + [662] = {.lex_state = 0, .external_lex_state = 71}, + [663] = {.lex_state = 0, .external_lex_state = 77}, + [664] = {.lex_state = 0, .external_lex_state = 76}, + [665] = {.lex_state = 0, .external_lex_state = 76}, + [666] = {.lex_state = 0, .external_lex_state = 76}, + [667] = {.lex_state = 0, .external_lex_state = 76}, + [668] = {.lex_state = 0, .external_lex_state = 76}, + [669] = {.lex_state = 0, .external_lex_state = 76}, + [670] = {.lex_state = 0, .external_lex_state = 79}, + [671] = {.lex_state = 0, .external_lex_state = 79}, + [672] = {.lex_state = 0, .external_lex_state = 75}, + [673] = {.lex_state = 0, .external_lex_state = 79}, + [674] = {.lex_state = 0, .external_lex_state = 75}, + [675] = {.lex_state = 0, .external_lex_state = 79}, + [676] = {.lex_state = 0, .external_lex_state = 76}, + [677] = {.lex_state = 0, .external_lex_state = 71}, + [678] = {.lex_state = 0, .external_lex_state = 76}, + [679] = {.lex_state = 0, .external_lex_state = 71}, + [680] = {.lex_state = 0, .external_lex_state = 76}, + [681] = {.lex_state = 0, .external_lex_state = 76}, + [682] = {.lex_state = 0, .external_lex_state = 76}, + [683] = {.lex_state = 0, .external_lex_state = 71}, + [684] = {.lex_state = 0, .external_lex_state = 71}, + [685] = {.lex_state = 0, .external_lex_state = 76}, + [686] = {.lex_state = 0, .external_lex_state = 76}, + [687] = {.lex_state = 0, .external_lex_state = 76}, + [688] = {.lex_state = 0, .external_lex_state = 76}, + [689] = {.lex_state = 0, .external_lex_state = 76}, + [690] = {.lex_state = 0, .external_lex_state = 76}, + [691] = {.lex_state = 0, .external_lex_state = 76}, + [692] = {.lex_state = 0, .external_lex_state = 74}, + [693] = {.lex_state = 0, .external_lex_state = 80}, + [694] = {.lex_state = 0, .external_lex_state = 81}, + [695] = {.lex_state = 0, .external_lex_state = 75}, + [696] = {.lex_state = 0, .external_lex_state = 75}, + [697] = {.lex_state = 0, .external_lex_state = 75}, + [698] = {.lex_state = 0, .external_lex_state = 81}, + [699] = {.lex_state = 0, .external_lex_state = 75}, + [700] = {.lex_state = 0, .external_lex_state = 75}, + [701] = {.lex_state = 0, .external_lex_state = 75}, + [702] = {.lex_state = 0, .external_lex_state = 78}, + [703] = {.lex_state = 0, .external_lex_state = 78}, + [704] = {.lex_state = 0, .external_lex_state = 78}, + [705] = {.lex_state = 0, .external_lex_state = 78}, + [706] = {.lex_state = 0, .external_lex_state = 78}, + [707] = {.lex_state = 0, .external_lex_state = 78}, + [708] = {.lex_state = 0, .external_lex_state = 78}, + [709] = {.lex_state = 0, .external_lex_state = 78}, + [710] = {.lex_state = 0, .external_lex_state = 75}, + [711] = {.lex_state = 0, .external_lex_state = 78}, + [712] = {.lex_state = 0, .external_lex_state = 78}, + [713] = {.lex_state = 0, .external_lex_state = 78}, + [714] = {.lex_state = 0, .external_lex_state = 78}, + [715] = {.lex_state = 0, .external_lex_state = 78}, + [716] = {.lex_state = 0, .external_lex_state = 78}, + [717] = {.lex_state = 0, .external_lex_state = 78}, + [718] = {.lex_state = 0, .external_lex_state = 78}, + [719] = {.lex_state = 0, .external_lex_state = 78}, + [720] = {.lex_state = 0, .external_lex_state = 78}, + [721] = {.lex_state = 0, .external_lex_state = 78}, + [722] = {.lex_state = 0, .external_lex_state = 78}, + [723] = {.lex_state = 0, .external_lex_state = 75}, + [724] = {.lex_state = 0, .external_lex_state = 78}, + [725] = {.lex_state = 0, .external_lex_state = 78}, + [726] = {.lex_state = 0, .external_lex_state = 78}, + [727] = {.lex_state = 0, .external_lex_state = 78}, + [728] = {.lex_state = 0, .external_lex_state = 78}, + [729] = {.lex_state = 0, .external_lex_state = 78}, + [730] = {.lex_state = 0, .external_lex_state = 78}, + [731] = {.lex_state = 0, .external_lex_state = 78}, + [732] = {.lex_state = 0, .external_lex_state = 78}, + [733] = {.lex_state = 0, .external_lex_state = 78}, + [734] = {.lex_state = 0, .external_lex_state = 78}, + [735] = {.lex_state = 0, .external_lex_state = 78}, + [736] = {.lex_state = 0, .external_lex_state = 78}, + [737] = {.lex_state = 0, .external_lex_state = 78}, + [738] = {.lex_state = 0, .external_lex_state = 78}, + [739] = {.lex_state = 0, .external_lex_state = 78}, + [740] = {.lex_state = 0, .external_lex_state = 78}, + [741] = {.lex_state = 0, .external_lex_state = 80}, + [742] = {.lex_state = 0, .external_lex_state = 78}, + [743] = {.lex_state = 0, .external_lex_state = 78}, + [744] = {.lex_state = 0, .external_lex_state = 78}, + [745] = {.lex_state = 0, .external_lex_state = 78}, + [746] = {.lex_state = 0, .external_lex_state = 75}, + [747] = {.lex_state = 0, .external_lex_state = 75}, + [748] = {.lex_state = 0, .external_lex_state = 75}, + [749] = {.lex_state = 0, .external_lex_state = 75}, + [750] = {.lex_state = 0, .external_lex_state = 80}, + [751] = {.lex_state = 0, .external_lex_state = 80}, + [752] = {.lex_state = 0, .external_lex_state = 80}, + [753] = {.lex_state = 0, .external_lex_state = 75}, + [754] = {.lex_state = 0, .external_lex_state = 80}, + [755] = {.lex_state = 0, .external_lex_state = 80}, + [756] = {.lex_state = 0, .external_lex_state = 80}, + [757] = {.lex_state = 0, .external_lex_state = 80}, + [758] = {.lex_state = 0, .external_lex_state = 81}, + [759] = {.lex_state = 0, .external_lex_state = 80}, + [760] = {.lex_state = 0, .external_lex_state = 80}, + [761] = {.lex_state = 0, .external_lex_state = 80}, + [762] = {.lex_state = 0, .external_lex_state = 80}, + [763] = {.lex_state = 0, .external_lex_state = 80}, + [764] = {.lex_state = 0, .external_lex_state = 80}, + [765] = {.lex_state = 0, .external_lex_state = 80}, + [766] = {.lex_state = 0, .external_lex_state = 80}, + [767] = {.lex_state = 0, .external_lex_state = 80}, + [768] = {.lex_state = 0, .external_lex_state = 80}, + [769] = {.lex_state = 0, .external_lex_state = 80}, + [770] = {.lex_state = 0, .external_lex_state = 80}, + [771] = {.lex_state = 0, .external_lex_state = 80}, + [772] = {.lex_state = 0, .external_lex_state = 80}, + [773] = {.lex_state = 0, .external_lex_state = 80}, + [774] = {.lex_state = 0, .external_lex_state = 80}, + [775] = {.lex_state = 0, .external_lex_state = 80}, + [776] = {.lex_state = 0, .external_lex_state = 80}, + [777] = {.lex_state = 0, .external_lex_state = 80}, + [778] = {.lex_state = 0, .external_lex_state = 80}, + [779] = {.lex_state = 0, .external_lex_state = 80}, + [780] = {.lex_state = 0, .external_lex_state = 80}, + [781] = {.lex_state = 0, .external_lex_state = 80}, + [782] = {.lex_state = 0, .external_lex_state = 80}, + [783] = {.lex_state = 0, .external_lex_state = 78}, + [784] = {.lex_state = 0, .external_lex_state = 79}, + [785] = {.lex_state = 0, .external_lex_state = 77}, + [786] = {.lex_state = 0, .external_lex_state = 77}, + [787] = {.lex_state = 0, .external_lex_state = 79}, + [788] = {.lex_state = 0, .external_lex_state = 79}, + [789] = {.lex_state = 0, .external_lex_state = 77}, + [790] = {.lex_state = 0, .external_lex_state = 77}, + [791] = {.lex_state = 0, .external_lex_state = 77}, + [792] = {.lex_state = 0, .external_lex_state = 77}, + [793] = {.lex_state = 0, .external_lex_state = 79}, + [794] = {.lex_state = 0, .external_lex_state = 76}, + [795] = {.lex_state = 0, .external_lex_state = 77}, + [796] = {.lex_state = 0, .external_lex_state = 79}, + [797] = {.lex_state = 0, .external_lex_state = 79}, + [798] = {.lex_state = 0, .external_lex_state = 79}, + [799] = {.lex_state = 0, .external_lex_state = 77}, + [800] = {.lex_state = 0, .external_lex_state = 77}, + [801] = {.lex_state = 0, .external_lex_state = 79}, + [802] = {.lex_state = 0, .external_lex_state = 79}, + [803] = {.lex_state = 0, .external_lex_state = 79}, + [804] = {.lex_state = 0, .external_lex_state = 77}, + [805] = {.lex_state = 0, .external_lex_state = 82}, + [806] = {.lex_state = 0, .external_lex_state = 77}, + [807] = {.lex_state = 0, .external_lex_state = 77}, + [808] = {.lex_state = 0, .external_lex_state = 77}, + [809] = {.lex_state = 0, .external_lex_state = 77}, + [810] = {.lex_state = 0, .external_lex_state = 77}, + [811] = {.lex_state = 0, .external_lex_state = 79}, + [812] = {.lex_state = 0, .external_lex_state = 79}, + [813] = {.lex_state = 0, .external_lex_state = 79}, + [814] = {.lex_state = 0, .external_lex_state = 79}, + [815] = {.lex_state = 0, .external_lex_state = 79}, + [816] = {.lex_state = 0, .external_lex_state = 77}, + [817] = {.lex_state = 0, .external_lex_state = 77}, + [818] = {.lex_state = 0, .external_lex_state = 77}, + [819] = {.lex_state = 0, .external_lex_state = 77}, + [820] = {.lex_state = 0, .external_lex_state = 77}, + [821] = {.lex_state = 0, .external_lex_state = 77}, + [822] = {.lex_state = 0, .external_lex_state = 77}, + [823] = {.lex_state = 0, .external_lex_state = 77}, + [824] = {.lex_state = 0, .external_lex_state = 77}, + [825] = {.lex_state = 0, .external_lex_state = 77}, + [826] = {.lex_state = 0, .external_lex_state = 79}, + [827] = {.lex_state = 0, .external_lex_state = 77}, + [828] = {.lex_state = 0, .external_lex_state = 77}, + [829] = {.lex_state = 0, .external_lex_state = 77}, + [830] = {.lex_state = 0, .external_lex_state = 77}, + [831] = {.lex_state = 0, .external_lex_state = 77}, + [832] = {.lex_state = 0, .external_lex_state = 77}, + [833] = {.lex_state = 0, .external_lex_state = 77}, + [834] = {.lex_state = 0, .external_lex_state = 77}, + [835] = {.lex_state = 0, .external_lex_state = 77}, + [836] = {.lex_state = 0, .external_lex_state = 77}, + [837] = {.lex_state = 0, .external_lex_state = 77}, + [838] = {.lex_state = 0, .external_lex_state = 77}, + [839] = {.lex_state = 0, .external_lex_state = 79}, + [840] = {.lex_state = 0, .external_lex_state = 79}, + [841] = {.lex_state = 0, .external_lex_state = 79}, + [842] = {.lex_state = 0, .external_lex_state = 77}, + [843] = {.lex_state = 0, .external_lex_state = 77}, + [844] = {.lex_state = 0, .external_lex_state = 77}, + [845] = {.lex_state = 0, .external_lex_state = 77}, + [846] = {.lex_state = 0, .external_lex_state = 77}, + [847] = {.lex_state = 0, .external_lex_state = 77}, + [848] = {.lex_state = 0, .external_lex_state = 77}, + [849] = {.lex_state = 0, .external_lex_state = 77}, + [850] = {.lex_state = 0, .external_lex_state = 77}, + [851] = {.lex_state = 0, .external_lex_state = 77}, + [852] = {.lex_state = 0, .external_lex_state = 77}, + [853] = {.lex_state = 0, .external_lex_state = 77}, + [854] = {.lex_state = 0, .external_lex_state = 77}, + [855] = {.lex_state = 0, .external_lex_state = 77}, + [856] = {.lex_state = 0, .external_lex_state = 77}, + [857] = {.lex_state = 0, .external_lex_state = 77}, + [858] = {.lex_state = 0, .external_lex_state = 77}, + [859] = {.lex_state = 0, .external_lex_state = 77}, + [860] = {.lex_state = 0, .external_lex_state = 77}, + [861] = {.lex_state = 0, .external_lex_state = 77}, + [862] = {.lex_state = 0, .external_lex_state = 77}, + [863] = {.lex_state = 0, .external_lex_state = 77}, + [864] = {.lex_state = 0, .external_lex_state = 79}, + [865] = {.lex_state = 0, .external_lex_state = 79}, + [866] = {.lex_state = 0, .external_lex_state = 79}, + [867] = {.lex_state = 0, .external_lex_state = 79}, + [868] = {.lex_state = 0, .external_lex_state = 79}, + [869] = {.lex_state = 0, .external_lex_state = 79}, + [870] = {.lex_state = 0, .external_lex_state = 79}, + [871] = {.lex_state = 0, .external_lex_state = 79}, + [872] = {.lex_state = 0, .external_lex_state = 79}, + [873] = {.lex_state = 0, .external_lex_state = 77}, + [874] = {.lex_state = 0, .external_lex_state = 77}, + [875] = {.lex_state = 0, .external_lex_state = 79}, + [876] = {.lex_state = 0, .external_lex_state = 79}, + [877] = {.lex_state = 0, .external_lex_state = 79}, + [878] = {.lex_state = 0, .external_lex_state = 79}, + [879] = {.lex_state = 0, .external_lex_state = 79}, + [880] = {.lex_state = 0, .external_lex_state = 79}, + [881] = {.lex_state = 0, .external_lex_state = 79}, + [882] = {.lex_state = 0, .external_lex_state = 79}, + [883] = {.lex_state = 0, .external_lex_state = 79}, + [884] = {.lex_state = 0, .external_lex_state = 79}, + [885] = {.lex_state = 0, .external_lex_state = 79}, + [886] = {.lex_state = 0, .external_lex_state = 79}, + [887] = {.lex_state = 0, .external_lex_state = 79}, + [888] = {.lex_state = 0, .external_lex_state = 79}, + [889] = {.lex_state = 0, .external_lex_state = 76}, + [890] = {.lex_state = 0, .external_lex_state = 77}, + [891] = {.lex_state = 0, .external_lex_state = 77}, + [892] = {.lex_state = 0, .external_lex_state = 79}, + [893] = {.lex_state = 0, .external_lex_state = 79}, + [894] = {.lex_state = 0, .external_lex_state = 79}, + [895] = {.lex_state = 0, .external_lex_state = 79}, + [896] = {.lex_state = 0, .external_lex_state = 79}, + [897] = {.lex_state = 0, .external_lex_state = 79}, + [898] = {.lex_state = 0, .external_lex_state = 79}, + [899] = {.lex_state = 0, .external_lex_state = 79}, + [900] = {.lex_state = 0, .external_lex_state = 79}, + [901] = {.lex_state = 0, .external_lex_state = 79}, + [902] = {.lex_state = 0, .external_lex_state = 79}, + [903] = {.lex_state = 0, .external_lex_state = 79}, + [904] = {.lex_state = 0, .external_lex_state = 79}, + [905] = {.lex_state = 0, .external_lex_state = 79}, + [906] = {.lex_state = 0, .external_lex_state = 79}, + [907] = {.lex_state = 0, .external_lex_state = 79}, + [908] = {.lex_state = 0, .external_lex_state = 79}, + [909] = {.lex_state = 0, .external_lex_state = 79}, + [910] = {.lex_state = 0, .external_lex_state = 79}, + [911] = {.lex_state = 0, .external_lex_state = 79}, + [912] = {.lex_state = 0, .external_lex_state = 79}, + [913] = {.lex_state = 0, .external_lex_state = 79}, + [914] = {.lex_state = 0, .external_lex_state = 79}, + [915] = {.lex_state = 0, .external_lex_state = 79}, + [916] = {.lex_state = 0, .external_lex_state = 79}, + [917] = {.lex_state = 0, .external_lex_state = 83}, + [918] = {.lex_state = 0, .external_lex_state = 83}, + [919] = {.lex_state = 0, .external_lex_state = 77}, + [920] = {.lex_state = 0, .external_lex_state = 77}, + [921] = {.lex_state = 0, .external_lex_state = 77}, + [922] = {.lex_state = 0, .external_lex_state = 77}, + [923] = {.lex_state = 0, .external_lex_state = 77}, + [924] = {.lex_state = 0, .external_lex_state = 79}, + [925] = {.lex_state = 0, .external_lex_state = 79}, + [926] = {.lex_state = 0, .external_lex_state = 79}, + [927] = {.lex_state = 0, .external_lex_state = 79}, + [928] = {.lex_state = 0, .external_lex_state = 82}, + [929] = {.lex_state = 0, .external_lex_state = 79}, + [930] = {.lex_state = 0, .external_lex_state = 77}, + [931] = {.lex_state = 0, .external_lex_state = 79}, + [932] = {.lex_state = 0, .external_lex_state = 79}, + [933] = {.lex_state = 0, .external_lex_state = 79}, + [934] = {.lex_state = 0, .external_lex_state = 79}, + [935] = {.lex_state = 0, .external_lex_state = 79}, + [936] = {.lex_state = 0, .external_lex_state = 79}, + [937] = {.lex_state = 0, .external_lex_state = 79}, + [938] = {.lex_state = 0, .external_lex_state = 79}, + [939] = {.lex_state = 0, .external_lex_state = 83}, + [940] = {.lex_state = 0, .external_lex_state = 79}, + [941] = {.lex_state = 0, .external_lex_state = 79}, + [942] = {.lex_state = 0, .external_lex_state = 77}, + [943] = {.lex_state = 0, .external_lex_state = 79}, + [944] = {.lex_state = 0, .external_lex_state = 77}, + [945] = {.lex_state = 0, .external_lex_state = 77}, + [946] = {.lex_state = 0, .external_lex_state = 77}, + [947] = {.lex_state = 0, .external_lex_state = 77}, + [948] = {.lex_state = 0, .external_lex_state = 77}, + [949] = {.lex_state = 0, .external_lex_state = 77}, + [950] = {.lex_state = 0, .external_lex_state = 77}, + [951] = {.lex_state = 0, .external_lex_state = 79}, + [952] = {.lex_state = 0, .external_lex_state = 77}, + [953] = {.lex_state = 0, .external_lex_state = 77}, + [954] = {.lex_state = 0, .external_lex_state = 77}, + [955] = {.lex_state = 0, .external_lex_state = 77}, + [956] = {.lex_state = 0, .external_lex_state = 79}, + [957] = {.lex_state = 0, .external_lex_state = 77}, + [958] = {.lex_state = 0, .external_lex_state = 77}, + [959] = {.lex_state = 0, .external_lex_state = 77}, + [960] = {.lex_state = 0, .external_lex_state = 77}, + [961] = {.lex_state = 0, .external_lex_state = 79}, + [962] = {.lex_state = 0, .external_lex_state = 79}, + [963] = {.lex_state = 0, .external_lex_state = 84}, + [964] = {.lex_state = 0, .external_lex_state = 85}, + [965] = {.lex_state = 0, .external_lex_state = 86}, + [966] = {.lex_state = 0, .external_lex_state = 86}, + [967] = {.lex_state = 0, .external_lex_state = 87}, + [968] = {.lex_state = 0, .external_lex_state = 72}, + [969] = {.lex_state = 0, .external_lex_state = 87}, + [970] = {.lex_state = 0, .external_lex_state = 88}, + [971] = {.lex_state = 0, .external_lex_state = 88}, + [972] = {.lex_state = 0, .external_lex_state = 89}, + [973] = {.lex_state = 0, .external_lex_state = 86}, + [974] = {.lex_state = 0, .external_lex_state = 86}, + [975] = {.lex_state = 0, .external_lex_state = 89}, + [976] = {.lex_state = 0, .external_lex_state = 90}, + [977] = {.lex_state = 0, .external_lex_state = 88}, + [978] = {.lex_state = 0, .external_lex_state = 89}, + [979] = {.lex_state = 0, .external_lex_state = 86}, + [980] = {.lex_state = 0, .external_lex_state = 82}, + [981] = {.lex_state = 0, .external_lex_state = 82}, + [982] = {.lex_state = 0, .external_lex_state = 88}, + [983] = {.lex_state = 0, .external_lex_state = 89}, + [984] = {.lex_state = 0, .external_lex_state = 82}, + [985] = {.lex_state = 0, .external_lex_state = 83}, + [986] = {.lex_state = 0, .external_lex_state = 84}, + [987] = {.lex_state = 0, .external_lex_state = 83}, + [988] = {.lex_state = 0, .external_lex_state = 83}, + [989] = {.lex_state = 0, .external_lex_state = 83}, + [990] = {.lex_state = 0, .external_lex_state = 83}, + [991] = {.lex_state = 0, .external_lex_state = 82}, + [992] = {.lex_state = 0, .external_lex_state = 88}, + [993] = {.lex_state = 0, .external_lex_state = 88}, + [994] = {.lex_state = 0, .external_lex_state = 89}, + [995] = {.lex_state = 0, .external_lex_state = 86}, + [996] = {.lex_state = 0, .external_lex_state = 83}, + [997] = {.lex_state = 0, .external_lex_state = 83}, + [998] = {.lex_state = 0, .external_lex_state = 86}, + [999] = {.lex_state = 0, .external_lex_state = 83}, + [1000] = {.lex_state = 0, .external_lex_state = 83}, + [1001] = {.lex_state = 0, .external_lex_state = 83}, + [1002] = {.lex_state = 0, .external_lex_state = 86}, + [1003] = {.lex_state = 0, .external_lex_state = 86}, + [1004] = {.lex_state = 0, .external_lex_state = 86}, + [1005] = {.lex_state = 0, .external_lex_state = 83}, + [1006] = {.lex_state = 0, .external_lex_state = 88}, + [1007] = {.lex_state = 0, .external_lex_state = 89}, + [1008] = {.lex_state = 0, .external_lex_state = 83}, + [1009] = {.lex_state = 0, .external_lex_state = 91}, + [1010] = {.lex_state = 0, .external_lex_state = 88}, + [1011] = {.lex_state = 0, .external_lex_state = 89}, + [1012] = {.lex_state = 0, .external_lex_state = 85}, + [1013] = {.lex_state = 0, .external_lex_state = 89}, + [1014] = {.lex_state = 0, .external_lex_state = 88}, + [1015] = {.lex_state = 0, .external_lex_state = 72}, + [1016] = {.lex_state = 0, .external_lex_state = 84}, + [1017] = {.lex_state = 0, .external_lex_state = 88}, + [1018] = {.lex_state = 0, .external_lex_state = 91}, + [1019] = {.lex_state = 0, .external_lex_state = 89}, + [1020] = {.lex_state = 0, .external_lex_state = 88}, + [1021] = {.lex_state = 0, .external_lex_state = 89}, + [1022] = {.lex_state = 0, .external_lex_state = 86}, + [1023] = {.lex_state = 0, .external_lex_state = 88}, + [1024] = {.lex_state = 0, .external_lex_state = 89}, + [1025] = {.lex_state = 0, .external_lex_state = 92}, + [1026] = {.lex_state = 0, .external_lex_state = 86}, + [1027] = {.lex_state = 0, .external_lex_state = 88}, + [1028] = {.lex_state = 0, .external_lex_state = 89}, + [1029] = {.lex_state = 0, .external_lex_state = 89}, + [1030] = {.lex_state = 0, .external_lex_state = 83}, + [1031] = {.lex_state = 0, .external_lex_state = 91}, + [1032] = {.lex_state = 0, .external_lex_state = 88}, + [1033] = {.lex_state = 0, .external_lex_state = 89}, + [1034] = {.lex_state = 0, .external_lex_state = 85}, + [1035] = {.lex_state = 0, .external_lex_state = 91}, + [1036] = {.lex_state = 0, .external_lex_state = 83}, + [1037] = {.lex_state = 0, .external_lex_state = 83}, + [1038] = {.lex_state = 0, .external_lex_state = 93}, + [1039] = {.lex_state = 0, .external_lex_state = 83}, + [1040] = {.lex_state = 0, .external_lex_state = 83}, + [1041] = {.lex_state = 0, .external_lex_state = 86}, + [1042] = {.lex_state = 0, .external_lex_state = 88}, + [1043] = {.lex_state = 0, .external_lex_state = 89}, + [1044] = {.lex_state = 0, .external_lex_state = 83}, + [1045] = {.lex_state = 0, .external_lex_state = 94}, + [1046] = {.lex_state = 0, .external_lex_state = 83}, + [1047] = {.lex_state = 0, .external_lex_state = 83}, + [1048] = {.lex_state = 0, .external_lex_state = 86}, + [1049] = {.lex_state = 0, .external_lex_state = 70}, + [1050] = {.lex_state = 0, .external_lex_state = 94}, + [1051] = {.lex_state = 0, .external_lex_state = 94}, + [1052] = {.lex_state = 0, .external_lex_state = 94}, + [1053] = {.lex_state = 0, .external_lex_state = 94}, + [1054] = {.lex_state = 0, .external_lex_state = 94}, + [1055] = {.lex_state = 0, .external_lex_state = 70}, + [1056] = {.lex_state = 0, .external_lex_state = 95}, + [1057] = {.lex_state = 0, .external_lex_state = 70}, + [1058] = {.lex_state = 0, .external_lex_state = 96}, + [1059] = {.lex_state = 0, .external_lex_state = 93}, + [1060] = {.lex_state = 0, .external_lex_state = 70}, + [1061] = {.lex_state = 0, .external_lex_state = 94}, + [1062] = {.lex_state = 0, .external_lex_state = 94}, + [1063] = {.lex_state = 0, .external_lex_state = 70}, + [1064] = {.lex_state = 0, .external_lex_state = 94}, + [1065] = {.lex_state = 0, .external_lex_state = 70}, + [1066] = {.lex_state = 0, .external_lex_state = 95}, + [1067] = {.lex_state = 0, .external_lex_state = 94}, + [1068] = {.lex_state = 0, .external_lex_state = 94}, + [1069] = {.lex_state = 0, .external_lex_state = 70}, + [1070] = {.lex_state = 0, .external_lex_state = 70}, + [1071] = {.lex_state = 0, .external_lex_state = 70}, + [1072] = {.lex_state = 0, .external_lex_state = 94}, + [1073] = {.lex_state = 0, .external_lex_state = 70}, + [1074] = {.lex_state = 0, .external_lex_state = 94}, + [1075] = {.lex_state = 0, .external_lex_state = 70}, + [1076] = {.lex_state = 0, .external_lex_state = 70}, + [1077] = {.lex_state = 0, .external_lex_state = 90}, + [1078] = {.lex_state = 0, .external_lex_state = 95}, + [1079] = {.lex_state = 0, .external_lex_state = 87}, + [1080] = {.lex_state = 0, .external_lex_state = 70}, + [1081] = {.lex_state = 0, .external_lex_state = 95}, + [1082] = {.lex_state = 0, .external_lex_state = 70}, + [1083] = {.lex_state = 0, .external_lex_state = 70}, + [1084] = {.lex_state = 0, .external_lex_state = 90}, + [1085] = {.lex_state = 0, .external_lex_state = 70}, + [1086] = {.lex_state = 0, .external_lex_state = 70}, + [1087] = {.lex_state = 0, .external_lex_state = 70}, + [1088] = {.lex_state = 0, .external_lex_state = 70}, + [1089] = {.lex_state = 0, .external_lex_state = 95}, + [1090] = {.lex_state = 0, .external_lex_state = 70}, + [1091] = {.lex_state = 0, .external_lex_state = 70}, + [1092] = {.lex_state = 0, .external_lex_state = 70}, + [1093] = {.lex_state = 0, .external_lex_state = 70}, + [1094] = {.lex_state = 0, .external_lex_state = 70}, + [1095] = {.lex_state = 0, .external_lex_state = 70}, + [1096] = {.lex_state = 0, .external_lex_state = 70}, + [1097] = {.lex_state = 0, .external_lex_state = 90}, + [1098] = {.lex_state = 0, .external_lex_state = 70}, + [1099] = {.lex_state = 0, .external_lex_state = 90}, + [1100] = {.lex_state = 0, .external_lex_state = 93}, + [1101] = {.lex_state = 0, .external_lex_state = 93}, + [1102] = {.lex_state = 0, .external_lex_state = 70}, + [1103] = {.lex_state = 0, .external_lex_state = 70}, + [1104] = {.lex_state = 0, .external_lex_state = 70}, + [1105] = {.lex_state = 0, .external_lex_state = 70}, + [1106] = {.lex_state = 0, .external_lex_state = 70}, + [1107] = {.lex_state = 0, .external_lex_state = 87}, + [1108] = {.lex_state = 0, .external_lex_state = 70}, + [1109] = {.lex_state = 0, .external_lex_state = 70}, + [1110] = {.lex_state = 0, .external_lex_state = 92}, + [1111] = {.lex_state = 0, .external_lex_state = 95}, + [1112] = {.lex_state = 0, .external_lex_state = 95}, + [1113] = {.lex_state = 0, .external_lex_state = 92}, + [1114] = {.lex_state = 0, .external_lex_state = 92}, + [1115] = {.lex_state = 0, .external_lex_state = 70}, + [1116] = {.lex_state = 0, .external_lex_state = 92}, + [1117] = {.lex_state = 0, .external_lex_state = 87}, + [1118] = {.lex_state = 0, .external_lex_state = 87}, + [1119] = {.lex_state = 0, .external_lex_state = 70}, + [1120] = {.lex_state = 0, .external_lex_state = 95}, + [1121] = {.lex_state = 0, .external_lex_state = 95}, + [1122] = {.lex_state = 0, .external_lex_state = 87}, + [1123] = {.lex_state = 0, .external_lex_state = 70}, + [1124] = {.lex_state = 0, .external_lex_state = 96}, + [1125] = {.lex_state = 0, .external_lex_state = 97}, + [1126] = {.lex_state = 0, .external_lex_state = 70}, + [1127] = {.lex_state = 0, .external_lex_state = 70}, + [1128] = {.lex_state = 0, .external_lex_state = 87}, + [1129] = {.lex_state = 0, .external_lex_state = 70}, + [1130] = {.lex_state = 0, .external_lex_state = 70}, + [1131] = {.lex_state = 0, .external_lex_state = 70}, + [1132] = {.lex_state = 0, .external_lex_state = 90}, + [1133] = {.lex_state = 0, .external_lex_state = 70}, + [1134] = {.lex_state = 0, .external_lex_state = 70}, + [1135] = {.lex_state = 0, .external_lex_state = 70}, + [1136] = {.lex_state = 0, .external_lex_state = 70}, + [1137] = {.lex_state = 0, .external_lex_state = 87}, + [1138] = {.lex_state = 0, .external_lex_state = 97}, + [1139] = {.lex_state = 0, .external_lex_state = 92}, + [1140] = {.lex_state = 0, .external_lex_state = 95}, + [1141] = {.lex_state = 0, .external_lex_state = 95}, + [1142] = {.lex_state = 0, .external_lex_state = 70}, + [1143] = {.lex_state = 0, .external_lex_state = 70}, + [1144] = {.lex_state = 0, .external_lex_state = 87}, + [1145] = {.lex_state = 0, .external_lex_state = 92}, + [1146] = {.lex_state = 0, .external_lex_state = 87}, + [1147] = {.lex_state = 0, .external_lex_state = 95}, + [1148] = {.lex_state = 0, .external_lex_state = 95}, + [1149] = {.lex_state = 0, .external_lex_state = 87}, + [1150] = {.lex_state = 0, .external_lex_state = 87}, + [1151] = {.lex_state = 0, .external_lex_state = 96}, + [1152] = {.lex_state = 0, .external_lex_state = 97}, + [1153] = {.lex_state = 0, .external_lex_state = 87}, + [1154] = {.lex_state = 0, .external_lex_state = 70}, + [1155] = {.lex_state = 0, .external_lex_state = 70}, + [1156] = {.lex_state = 0, .external_lex_state = 70}, + [1157] = {.lex_state = 0, .external_lex_state = 70}, + [1158] = {.lex_state = 0, .external_lex_state = 87}, + [1159] = {.lex_state = 0, .external_lex_state = 87}, + [1160] = {.lex_state = 0, .external_lex_state = 87}, + [1161] = {.lex_state = 0, .external_lex_state = 92}, + [1162] = {.lex_state = 0, .external_lex_state = 92}, + [1163] = {.lex_state = 0, .external_lex_state = 92}, + [1164] = {.lex_state = 0, .external_lex_state = 92}, + [1165] = {.lex_state = 0, .external_lex_state = 96}, + [1166] = {.lex_state = 0, .external_lex_state = 97}, + [1167] = {.lex_state = 0, .external_lex_state = 70}, + [1168] = {.lex_state = 0, .external_lex_state = 70}, + [1169] = {.lex_state = 0, .external_lex_state = 70}, + [1170] = {.lex_state = 0, .external_lex_state = 70}, + [1171] = {.lex_state = 0, .external_lex_state = 93}, + [1172] = {.lex_state = 0, .external_lex_state = 96}, + [1173] = {.lex_state = 0, .external_lex_state = 97}, + [1174] = {.lex_state = 0, .external_lex_state = 92}, + [1175] = {.lex_state = 0, .external_lex_state = 70}, + [1176] = {.lex_state = 0, .external_lex_state = 70}, + [1177] = {.lex_state = 0, .external_lex_state = 70}, + [1178] = {.lex_state = 0, .external_lex_state = 92}, + [1179] = {.lex_state = 0, .external_lex_state = 87}, + [1180] = {.lex_state = 0, .external_lex_state = 87}, + [1181] = {.lex_state = 0, .external_lex_state = 87}, + [1182] = {.lex_state = 0, .external_lex_state = 96}, + [1183] = {.lex_state = 0, .external_lex_state = 97}, + [1184] = {.lex_state = 0, .external_lex_state = 87}, + [1185] = {.lex_state = 0, .external_lex_state = 70}, + [1186] = {.lex_state = 0, .external_lex_state = 70}, + [1187] = {.lex_state = 0, .external_lex_state = 93}, + [1188] = {.lex_state = 0, .external_lex_state = 70}, + [1189] = {.lex_state = 0, .external_lex_state = 92}, + [1190] = {.lex_state = 0, .external_lex_state = 92}, + [1191] = {.lex_state = 0, .external_lex_state = 70}, + [1192] = {.lex_state = 0, .external_lex_state = 70}, + [1193] = {.lex_state = 0, .external_lex_state = 96}, + [1194] = {.lex_state = 0, .external_lex_state = 97}, + [1195] = {.lex_state = 0, .external_lex_state = 92}, + [1196] = {.lex_state = 0, .external_lex_state = 92}, + [1197] = {.lex_state = 0, .external_lex_state = 70}, + [1198] = {.lex_state = 0, .external_lex_state = 87}, + [1199] = {.lex_state = 0, .external_lex_state = 70}, + [1200] = {.lex_state = 0, .external_lex_state = 70}, + [1201] = {.lex_state = 0, .external_lex_state = 70}, + [1202] = {.lex_state = 0, .external_lex_state = 70}, + [1203] = {.lex_state = 0, .external_lex_state = 70}, + [1204] = {.lex_state = 0, .external_lex_state = 70}, + [1205] = {.lex_state = 0, .external_lex_state = 70}, + [1206] = {.lex_state = 0, .external_lex_state = 70}, + [1207] = {.lex_state = 0, .external_lex_state = 70}, + [1208] = {.lex_state = 0, .external_lex_state = 70}, + [1209] = {.lex_state = 0, .external_lex_state = 94}, + [1210] = {.lex_state = 0, .external_lex_state = 94}, + [1211] = {.lex_state = 0, .external_lex_state = 96}, + [1212] = {.lex_state = 0, .external_lex_state = 97}, + [1213] = {.lex_state = 0, .external_lex_state = 94}, + [1214] = {.lex_state = 0, .external_lex_state = 94}, + [1215] = {.lex_state = 0, .external_lex_state = 70}, + [1216] = {.lex_state = 0, .external_lex_state = 82}, + [1217] = {.lex_state = 0, .external_lex_state = 86}, + [1218] = {.lex_state = 0, .external_lex_state = 86}, + [1219] = {.lex_state = 0, .external_lex_state = 84}, + [1220] = {.lex_state = 0, .external_lex_state = 86}, + [1221] = {.lex_state = 0, .external_lex_state = 86}, + [1222] = {.lex_state = 0, .external_lex_state = 82}, + [1223] = {.lex_state = 0, .external_lex_state = 84}, + [1224] = {.lex_state = 0, .external_lex_state = 84}, + [1225] = {.lex_state = 0, .external_lex_state = 84}, + [1226] = {.lex_state = 0, .external_lex_state = 84}, + [1227] = {.lex_state = 0, .external_lex_state = 98}, + [1228] = {.lex_state = 0, .external_lex_state = 84}, + [1229] = {.lex_state = 0, .external_lex_state = 86}, + [1230] = {.lex_state = 0, .external_lex_state = 86}, + [1231] = {.lex_state = 0, .external_lex_state = 84}, + [1232] = {.lex_state = 0, .external_lex_state = 84}, + [1233] = {.lex_state = 0, .external_lex_state = 84}, + [1234] = {.lex_state = 0, .external_lex_state = 84}, + [1235] = {.lex_state = 0, .external_lex_state = 84}, + [1236] = {.lex_state = 0, .external_lex_state = 85}, + [1237] = {.lex_state = 0, .external_lex_state = 98}, + [1238] = {.lex_state = 0, .external_lex_state = 84}, + [1239] = {.lex_state = 0, .external_lex_state = 99}, + [1240] = {.lex_state = 0, .external_lex_state = 84}, + [1241] = {.lex_state = 0, .external_lex_state = 84}, + [1242] = {.lex_state = 0, .external_lex_state = 100}, + [1243] = {.lex_state = 0, .external_lex_state = 82}, + [1244] = {.lex_state = 0, .external_lex_state = 100}, + [1245] = {.lex_state = 0, .external_lex_state = 84}, + [1246] = {.lex_state = 0, .external_lex_state = 82}, + [1247] = {.lex_state = 0, .external_lex_state = 86}, + [1248] = {.lex_state = 0, .external_lex_state = 82}, + [1249] = {.lex_state = 0, .external_lex_state = 84}, + [1250] = {.lex_state = 0, .external_lex_state = 85}, + [1251] = {.lex_state = 0, .external_lex_state = 85}, + [1252] = {.lex_state = 0, .external_lex_state = 85}, + [1253] = {.lex_state = 0, .external_lex_state = 84}, + [1254] = {.lex_state = 0, .external_lex_state = 82}, + [1255] = {.lex_state = 0, .external_lex_state = 84}, + [1256] = {.lex_state = 0, .external_lex_state = 86}, + [1257] = {.lex_state = 0, .external_lex_state = 84}, + [1258] = {.lex_state = 0, .external_lex_state = 86}, + [1259] = {.lex_state = 0, .external_lex_state = 86}, + [1260] = {.lex_state = 0, .external_lex_state = 86}, + [1261] = {.lex_state = 0, .external_lex_state = 86}, + [1262] = {.lex_state = 0, .external_lex_state = 82}, + [1263] = {.lex_state = 0, .external_lex_state = 82}, + [1264] = {.lex_state = 0, .external_lex_state = 84}, + [1265] = {.lex_state = 0, .external_lex_state = 86}, + [1266] = {.lex_state = 0, .external_lex_state = 86}, + [1267] = {.lex_state = 0, .external_lex_state = 86}, + [1268] = {.lex_state = 0, .external_lex_state = 86}, + [1269] = {.lex_state = 0, .external_lex_state = 84}, + [1270] = {.lex_state = 0, .external_lex_state = 84}, + [1271] = {.lex_state = 0, .external_lex_state = 84}, + [1272] = {.lex_state = 0, .external_lex_state = 82}, + [1273] = {.lex_state = 0, .external_lex_state = 86}, + [1274] = {.lex_state = 0, .external_lex_state = 86}, + [1275] = {.lex_state = 0, .external_lex_state = 86}, + [1276] = {.lex_state = 0, .external_lex_state = 86}, + [1277] = {.lex_state = 0, .external_lex_state = 86}, + [1278] = {.lex_state = 0, .external_lex_state = 86}, + [1279] = {.lex_state = 0, .external_lex_state = 86}, + [1280] = {.lex_state = 0, .external_lex_state = 86}, + [1281] = {.lex_state = 0, .external_lex_state = 86}, + [1282] = {.lex_state = 0, .external_lex_state = 91}, + [1283] = {.lex_state = 0, .external_lex_state = 91}, + [1284] = {.lex_state = 0, .external_lex_state = 86}, + [1285] = {.lex_state = 0, .external_lex_state = 86}, + [1286] = {.lex_state = 0, .external_lex_state = 86}, + [1287] = {.lex_state = 0, .external_lex_state = 86}, + [1288] = {.lex_state = 0, .external_lex_state = 86}, + [1289] = {.lex_state = 0, .external_lex_state = 86}, + [1290] = {.lex_state = 0, .external_lex_state = 86}, + [1291] = {.lex_state = 0, .external_lex_state = 86}, + [1292] = {.lex_state = 0, .external_lex_state = 84}, + [1293] = {.lex_state = 0, .external_lex_state = 84}, + [1294] = {.lex_state = 0, .external_lex_state = 86}, + [1295] = {.lex_state = 0, .external_lex_state = 86}, + [1296] = {.lex_state = 0, .external_lex_state = 86}, + [1297] = {.lex_state = 0, .external_lex_state = 86}, + [1298] = {.lex_state = 0, .external_lex_state = 85}, + [1299] = {.lex_state = 0, .external_lex_state = 98}, + [1300] = {.lex_state = 0, .external_lex_state = 86}, + [1301] = {.lex_state = 0, .external_lex_state = 85}, + [1302] = {.lex_state = 0, .external_lex_state = 91}, + [1303] = {.lex_state = 0, .external_lex_state = 86}, + [1304] = {.lex_state = 0, .external_lex_state = 91}, + [1305] = {.lex_state = 0, .external_lex_state = 85}, + [1306] = {.lex_state = 0, .external_lex_state = 91}, + [1307] = {.lex_state = 0, .external_lex_state = 91}, + [1308] = {.lex_state = 0, .external_lex_state = 85}, + [1309] = {.lex_state = 0, .external_lex_state = 91}, + [1310] = {.lex_state = 0, .external_lex_state = 91}, + [1311] = {.lex_state = 0, .external_lex_state = 85}, + [1312] = {.lex_state = 0, .external_lex_state = 85}, + [1313] = {.lex_state = 0, .external_lex_state = 86}, + [1314] = {.lex_state = 0, .external_lex_state = 91}, + [1315] = {.lex_state = 0, .external_lex_state = 82}, + [1316] = {.lex_state = 0, .external_lex_state = 91}, + [1317] = {.lex_state = 0, .external_lex_state = 85}, + [1318] = {.lex_state = 0, .external_lex_state = 91}, + [1319] = {.lex_state = 0, .external_lex_state = 85}, + [1320] = {.lex_state = 0, .external_lex_state = 91}, + [1321] = {.lex_state = 0, .external_lex_state = 91}, + [1322] = {.lex_state = 0, .external_lex_state = 85}, + [1323] = {.lex_state = 0, .external_lex_state = 91}, + [1324] = {.lex_state = 0, .external_lex_state = 91}, + [1325] = {.lex_state = 0, .external_lex_state = 91}, + [1326] = {.lex_state = 0, .external_lex_state = 84}, + [1327] = {.lex_state = 0, .external_lex_state = 84}, + [1328] = {.lex_state = 0, .external_lex_state = 91}, + [1329] = {.lex_state = 0, .external_lex_state = 91}, + [1330] = {.lex_state = 0, .external_lex_state = 91}, + [1331] = {.lex_state = 0, .external_lex_state = 91}, + [1332] = {.lex_state = 0, .external_lex_state = 85}, + [1333] = {.lex_state = 0, .external_lex_state = 86}, + [1334] = {.lex_state = 0, .external_lex_state = 91}, + [1335] = {.lex_state = 0, .external_lex_state = 84}, + [1336] = {.lex_state = 0, .external_lex_state = 85}, + [1337] = {.lex_state = 0, .external_lex_state = 85}, + [1338] = {.lex_state = 0, .external_lex_state = 91}, + [1339] = {.lex_state = 0, .external_lex_state = 91}, + [1340] = {.lex_state = 0, .external_lex_state = 91}, + [1341] = {.lex_state = 0, .external_lex_state = 91}, + [1342] = {.lex_state = 0, .external_lex_state = 91}, + [1343] = {.lex_state = 0, .external_lex_state = 91}, + [1344] = {.lex_state = 0, .external_lex_state = 86}, + [1345] = {.lex_state = 0, .external_lex_state = 82}, + [1346] = {.lex_state = 0, .external_lex_state = 91}, + [1347] = {.lex_state = 0, .external_lex_state = 86}, + [1348] = {.lex_state = 0, .external_lex_state = 84}, + [1349] = {.lex_state = 0, .external_lex_state = 91}, + [1350] = {.lex_state = 0, .external_lex_state = 86}, + [1351] = {.lex_state = 0, .external_lex_state = 86}, + [1352] = {.lex_state = 0, .external_lex_state = 84}, + [1353] = {.lex_state = 0, .external_lex_state = 85}, + [1354] = {.lex_state = 0, .external_lex_state = 85}, + [1355] = {.lex_state = 0, .external_lex_state = 86}, + [1356] = {.lex_state = 0, .external_lex_state = 85}, + [1357] = {.lex_state = 0, .external_lex_state = 85}, + [1358] = {.lex_state = 0, .external_lex_state = 85}, + [1359] = {.lex_state = 0, .external_lex_state = 99}, + [1360] = {.lex_state = 0, .external_lex_state = 85}, + [1361] = {.lex_state = 0, .external_lex_state = 91}, + [1362] = {.lex_state = 0, .external_lex_state = 86}, + [1363] = {.lex_state = 0, .external_lex_state = 86}, + [1364] = {.lex_state = 0, .external_lex_state = 86}, + [1365] = {.lex_state = 0, .external_lex_state = 86}, + [1366] = {.lex_state = 0, .external_lex_state = 85}, + [1367] = {.lex_state = 0, .external_lex_state = 91}, + [1368] = {.lex_state = 0, .external_lex_state = 85}, + [1369] = {.lex_state = 0, .external_lex_state = 91}, + [1370] = {.lex_state = 0, .external_lex_state = 91}, + [1371] = {.lex_state = 0, .external_lex_state = 85}, + [1372] = {.lex_state = 0, .external_lex_state = 85}, + [1373] = {.lex_state = 0, .external_lex_state = 91}, + [1374] = {.lex_state = 0, .external_lex_state = 91}, + [1375] = {.lex_state = 0, .external_lex_state = 86}, + [1376] = {.lex_state = 0, .external_lex_state = 86}, + [1377] = {.lex_state = 0, .external_lex_state = 86}, + [1378] = {.lex_state = 0, .external_lex_state = 86}, + [1379] = {.lex_state = 0, .external_lex_state = 84}, + [1380] = {.lex_state = 0, .external_lex_state = 86}, + [1381] = {.lex_state = 0, .external_lex_state = 86}, + [1382] = {.lex_state = 0, .external_lex_state = 86}, + [1383] = {.lex_state = 0, .external_lex_state = 86}, + [1384] = {.lex_state = 0, .external_lex_state = 91}, + [1385] = {.lex_state = 0, .external_lex_state = 91}, + [1386] = {.lex_state = 0, .external_lex_state = 86}, + [1387] = {.lex_state = 0, .external_lex_state = 86}, + [1388] = {.lex_state = 0, .external_lex_state = 86}, + [1389] = {.lex_state = 0, .external_lex_state = 86}, + [1390] = {.lex_state = 0, .external_lex_state = 86}, + [1391] = {.lex_state = 0, .external_lex_state = 85}, + [1392] = {.lex_state = 0, .external_lex_state = 85}, + [1393] = {.lex_state = 0, .external_lex_state = 86}, + [1394] = {.lex_state = 0, .external_lex_state = 86}, + [1395] = {.lex_state = 0, .external_lex_state = 86}, + [1396] = {.lex_state = 0, .external_lex_state = 91}, + [1397] = {.lex_state = 0, .external_lex_state = 91}, + [1398] = {.lex_state = 0, .external_lex_state = 82}, + [1399] = {.lex_state = 0, .external_lex_state = 91}, + [1400] = {.lex_state = 0, .external_lex_state = 82}, + [1401] = {.lex_state = 0, .external_lex_state = 86}, + [1402] = {.lex_state = 0, .external_lex_state = 86}, + [1403] = {.lex_state = 0, .external_lex_state = 91}, + [1404] = {.lex_state = 0, .external_lex_state = 86}, + [1405] = {.lex_state = 0, .external_lex_state = 85}, + [1406] = {.lex_state = 0, .external_lex_state = 85}, + [1407] = {.lex_state = 0, .external_lex_state = 86}, + [1408] = {.lex_state = 0, .external_lex_state = 91}, + [1409] = {.lex_state = 0, .external_lex_state = 85}, + [1410] = {.lex_state = 0, .external_lex_state = 101}, + [1411] = {.lex_state = 0, .external_lex_state = 98}, + [1412] = {.lex_state = 0, .external_lex_state = 98}, + [1413] = {.lex_state = 0, .external_lex_state = 98}, + [1414] = {.lex_state = 0, .external_lex_state = 100}, + [1415] = {.lex_state = 0, .external_lex_state = 98}, + [1416] = {.lex_state = 0, .external_lex_state = 98}, + [1417] = {.lex_state = 0, .external_lex_state = 98}, + [1418] = {.lex_state = 0, .external_lex_state = 98}, + [1419] = {.lex_state = 0, .external_lex_state = 98}, + [1420] = {.lex_state = 0, .external_lex_state = 98}, + [1421] = {.lex_state = 0, .external_lex_state = 98}, + [1422] = {.lex_state = 0, .external_lex_state = 100}, + [1423] = {.lex_state = 0, .external_lex_state = 98}, + [1424] = {.lex_state = 0, .external_lex_state = 98}, + [1425] = {.lex_state = 0, .external_lex_state = 98}, + [1426] = {.lex_state = 0, .external_lex_state = 102}, + [1427] = {.lex_state = 0, .external_lex_state = 103}, + [1428] = {.lex_state = 0, .external_lex_state = 104}, + [1429] = {.lex_state = 0, .external_lex_state = 102}, + [1430] = {.lex_state = 0, .external_lex_state = 101}, + [1431] = {.lex_state = 0, .external_lex_state = 101}, + [1432] = {.lex_state = 0, .external_lex_state = 105}, + [1433] = {.lex_state = 0, .external_lex_state = 101}, + [1434] = {.lex_state = 0, .external_lex_state = 101}, + [1435] = {.lex_state = 0, .external_lex_state = 105}, + [1436] = {.lex_state = 0, .external_lex_state = 105}, + [1437] = {.lex_state = 0, .external_lex_state = 105}, + [1438] = {.lex_state = 0, .external_lex_state = 101}, + [1439] = {.lex_state = 0, .external_lex_state = 101}, + [1440] = {.lex_state = 0, .external_lex_state = 105}, + [1441] = {.lex_state = 0, .external_lex_state = 105}, + [1442] = {.lex_state = 0, .external_lex_state = 98}, + [1443] = {.lex_state = 0, .external_lex_state = 98}, + [1444] = {.lex_state = 0, .external_lex_state = 98}, + [1445] = {.lex_state = 0, .external_lex_state = 98}, + [1446] = {.lex_state = 0, .external_lex_state = 98}, + [1447] = {.lex_state = 0, .external_lex_state = 106}, + [1448] = {.lex_state = 0, .external_lex_state = 100}, + [1449] = {.lex_state = 0, .external_lex_state = 107}, + [1450] = {.lex_state = 0, .external_lex_state = 98}, + [1451] = {.lex_state = 0, .external_lex_state = 100}, + [1452] = {.lex_state = 0, .external_lex_state = 102}, + [1453] = {.lex_state = 0, .external_lex_state = 98}, + [1454] = {.lex_state = 0, .external_lex_state = 108}, + [1455] = {.lex_state = 0, .external_lex_state = 99}, + [1456] = {.lex_state = 0, .external_lex_state = 104}, + [1457] = {.lex_state = 0, .external_lex_state = 106}, + [1458] = {.lex_state = 0, .external_lex_state = 100}, + [1459] = {.lex_state = 0, .external_lex_state = 106}, + [1460] = {.lex_state = 0, .external_lex_state = 107}, + [1461] = {.lex_state = 0, .external_lex_state = 98}, + [1462] = {.lex_state = 0, .external_lex_state = 99}, + [1463] = {.lex_state = 0, .external_lex_state = 100}, + [1464] = {.lex_state = 0, .external_lex_state = 98}, + [1465] = {.lex_state = 0, .external_lex_state = 102}, + [1466] = {.lex_state = 0, .external_lex_state = 100}, + [1467] = {.lex_state = 0, .external_lex_state = 100}, + [1468] = {.lex_state = 0, .external_lex_state = 106}, + [1469] = {.lex_state = 0, .external_lex_state = 100}, + [1470] = {.lex_state = 0, .external_lex_state = 99}, + [1471] = {.lex_state = 0, .external_lex_state = 107}, + [1472] = {.lex_state = 0, .external_lex_state = 101}, + [1473] = {.lex_state = 0, .external_lex_state = 106}, + [1474] = {.lex_state = 0, .external_lex_state = 105}, + [1475] = {.lex_state = 0, .external_lex_state = 99}, + [1476] = {.lex_state = 0, .external_lex_state = 107}, + [1477] = {.lex_state = 0, .external_lex_state = 98}, + [1478] = {.lex_state = 0, .external_lex_state = 101}, + [1479] = {.lex_state = 0, .external_lex_state = 101}, + [1480] = {.lex_state = 0, .external_lex_state = 105}, + [1481] = {.lex_state = 0, .external_lex_state = 105}, + [1482] = {.lex_state = 0, .external_lex_state = 100}, + [1483] = {.lex_state = 0, .external_lex_state = 101}, + [1484] = {.lex_state = 0, .external_lex_state = 101}, + [1485] = {.lex_state = 0, .external_lex_state = 98}, + [1486] = {.lex_state = 0, .external_lex_state = 105}, + [1487] = {.lex_state = 0, .external_lex_state = 98}, + [1488] = {.lex_state = 0, .external_lex_state = 105}, + [1489] = {.lex_state = 0, .external_lex_state = 104}, + [1490] = {.lex_state = 0, .external_lex_state = 104}, + [1491] = {.lex_state = 0, .external_lex_state = 98}, + [1492] = {.lex_state = 0, .external_lex_state = 98}, + [1493] = {.lex_state = 0, .external_lex_state = 98}, + [1494] = {.lex_state = 0, .external_lex_state = 105}, + [1495] = {.lex_state = 0, .external_lex_state = 100}, + [1496] = {.lex_state = 0, .external_lex_state = 98}, + [1497] = {.lex_state = 0, .external_lex_state = 98}, + [1498] = {.lex_state = 0, .external_lex_state = 101}, + [1499] = {.lex_state = 0, .external_lex_state = 98}, + [1500] = {.lex_state = 0, .external_lex_state = 98}, + [1501] = {.lex_state = 0, .external_lex_state = 98}, + [1502] = {.lex_state = 0, .external_lex_state = 98}, + [1503] = {.lex_state = 0, .external_lex_state = 101}, + [1504] = {.lex_state = 0, .external_lex_state = 105}, + [1505] = {.lex_state = 0, .external_lex_state = 105}, + [1506] = {.lex_state = 0, .external_lex_state = 100}, + [1507] = {.lex_state = 0, .external_lex_state = 100}, + [1508] = {.lex_state = 0, .external_lex_state = 105}, + [1509] = {.lex_state = 0, .external_lex_state = 100}, + [1510] = {.lex_state = 0, .external_lex_state = 101}, + [1511] = {.lex_state = 0, .external_lex_state = 101}, + [1512] = {.lex_state = 0, .external_lex_state = 105}, + [1513] = {.lex_state = 0, .external_lex_state = 105}, + [1514] = {.lex_state = 0, .external_lex_state = 98}, + [1515] = {.lex_state = 0, .external_lex_state = 109}, + [1516] = {.lex_state = 0, .external_lex_state = 107}, + [1517] = {.lex_state = 0, .external_lex_state = 98}, + [1518] = {.lex_state = 0, .external_lex_state = 99}, + [1519] = {.lex_state = 0, .external_lex_state = 101}, + [1520] = {.lex_state = 0, .external_lex_state = 98}, + [1521] = {.lex_state = 0, .external_lex_state = 98}, + [1522] = {.lex_state = 0, .external_lex_state = 98}, + [1523] = {.lex_state = 0, .external_lex_state = 98}, + [1524] = {.lex_state = 0, .external_lex_state = 98}, + [1525] = {.lex_state = 0, .external_lex_state = 106}, + [1526] = {.lex_state = 0, .external_lex_state = 104}, + [1527] = {.lex_state = 0, .external_lex_state = 107}, + [1528] = {.lex_state = 0, .external_lex_state = 98}, + [1529] = {.lex_state = 0, .external_lex_state = 98}, + [1530] = {.lex_state = 0, .external_lex_state = 98}, + [1531] = {.lex_state = 0, .external_lex_state = 98}, + [1532] = {.lex_state = 0, .external_lex_state = 98}, + [1533] = {.lex_state = 0, .external_lex_state = 98}, + [1534] = {.lex_state = 0, .external_lex_state = 100}, + [1535] = {.lex_state = 0, .external_lex_state = 100}, + [1536] = {.lex_state = 0, .external_lex_state = 98}, + [1537] = {.lex_state = 0, .external_lex_state = 98}, + [1538] = {.lex_state = 0, .external_lex_state = 101}, + [1539] = {.lex_state = 0, .external_lex_state = 101}, + [1540] = {.lex_state = 0, .external_lex_state = 105}, + [1541] = {.lex_state = 0, .external_lex_state = 105}, + [1542] = {.lex_state = 0, .external_lex_state = 101}, + [1543] = {.lex_state = 0, .external_lex_state = 101}, + [1544] = {.lex_state = 0, .external_lex_state = 105}, + [1545] = {.lex_state = 0, .external_lex_state = 101}, + [1546] = {.lex_state = 0, .external_lex_state = 101}, + [1547] = {.lex_state = 0, .external_lex_state = 105}, + [1548] = {.lex_state = 0, .external_lex_state = 101}, + [1549] = {.lex_state = 0, .external_lex_state = 101}, + [1550] = {.lex_state = 0, .external_lex_state = 105}, + [1551] = {.lex_state = 0, .external_lex_state = 98}, + [1552] = {.lex_state = 0, .external_lex_state = 101}, + [1553] = {.lex_state = 0, .external_lex_state = 105}, + [1554] = {.lex_state = 0, .external_lex_state = 101}, + [1555] = {.lex_state = 0, .external_lex_state = 101}, + [1556] = {.lex_state = 0, .external_lex_state = 105}, + [1557] = {.lex_state = 0, .external_lex_state = 101}, + [1558] = {.lex_state = 0, .external_lex_state = 101}, + [1559] = {.lex_state = 0, .external_lex_state = 105}, + [1560] = {.lex_state = 0, .external_lex_state = 101}, + [1561] = {.lex_state = 0, .external_lex_state = 101}, + [1562] = {.lex_state = 0, .external_lex_state = 101}, + [1563] = {.lex_state = 0, .external_lex_state = 101}, + [1564] = {.lex_state = 0, .external_lex_state = 101}, + [1565] = {.lex_state = 0, .external_lex_state = 101}, + [1566] = {.lex_state = 0, .external_lex_state = 101}, + [1567] = {.lex_state = 0, .external_lex_state = 101}, + [1568] = {.lex_state = 0, .external_lex_state = 101}, + [1569] = {.lex_state = 0, .external_lex_state = 101}, + [1570] = {.lex_state = 0, .external_lex_state = 101}, + [1571] = {.lex_state = 0, .external_lex_state = 101}, + [1572] = {.lex_state = 0, .external_lex_state = 101}, + [1573] = {.lex_state = 0, .external_lex_state = 101}, + [1574] = {.lex_state = 0, .external_lex_state = 101}, + [1575] = {.lex_state = 0, .external_lex_state = 101}, + [1576] = {.lex_state = 0, .external_lex_state = 101}, + [1577] = {.lex_state = 0, .external_lex_state = 101}, + [1578] = {.lex_state = 0, .external_lex_state = 101}, +}; + +static const uint16_t ts_parse_table[LARGE_STATE_COUNT][SYMBOL_COUNT] = { + [STATE(0)] = { + [ts_builtin_sym_end] = ACTIONS(1), + [sym__eof] = ACTIONS(1), + [sym__s_dir_yml_bgn] = ACTIONS(1), + [sym__r_dir_yml_ver] = ACTIONS(1), + [sym__s_dir_tag_bgn] = ACTIONS(1), + [sym__r_dir_tag_hdl] = ACTIONS(1), + [sym__r_dir_tag_pfx] = ACTIONS(1), + [sym__s_dir_rsv_bgn] = ACTIONS(1), + [sym__r_dir_rsv_prm] = ACTIONS(1), + [sym__s_drs_end] = ACTIONS(1), + [sym__s_doc_end] = ACTIONS(1), + [sym__r_blk_seq_bgn] = ACTIONS(1), + [sym__br_blk_seq_bgn] = ACTIONS(1), + [sym__b_blk_seq_bgn] = ACTIONS(1), + [sym__r_blk_key_bgn] = ACTIONS(1), + [sym__br_blk_key_bgn] = ACTIONS(1), + [sym__b_blk_key_bgn] = ACTIONS(1), + [sym__r_blk_val_bgn] = ACTIONS(1), + [sym__br_blk_val_bgn] = ACTIONS(1), + [sym__b_blk_val_bgn] = ACTIONS(1), + [sym__r_blk_imp_bgn] = ACTIONS(1), + [sym__r_blk_lit_bgn] = ACTIONS(1), + [sym__br_blk_lit_bgn] = ACTIONS(1), + [sym__r_blk_fld_bgn] = ACTIONS(1), + [sym__br_blk_fld_bgn] = ACTIONS(1), + [sym__br_blk_str_ctn] = ACTIONS(1), + [sym__r_flw_seq_bgn] = ACTIONS(1), + [sym__br_flw_seq_bgn] = ACTIONS(1), + [sym__b_flw_seq_bgn] = ACTIONS(1), + [sym__r_flw_seq_end] = ACTIONS(1), + [sym__br_flw_seq_end] = ACTIONS(1), + [sym__b_flw_seq_end] = ACTIONS(1), + [sym__r_flw_map_bgn] = ACTIONS(1), + [sym__br_flw_map_bgn] = ACTIONS(1), + [sym__b_flw_map_bgn] = ACTIONS(1), + [sym__r_flw_map_end] = ACTIONS(1), + [sym__br_flw_map_end] = ACTIONS(1), + [sym__b_flw_map_end] = ACTIONS(1), + [sym__r_flw_sep_bgn] = ACTIONS(1), + [sym__br_flw_sep_bgn] = ACTIONS(1), + [sym__r_flw_key_bgn] = ACTIONS(1), + [sym__br_flw_key_bgn] = ACTIONS(1), + [sym__r_flw_jsv_bgn] = ACTIONS(1), + [sym__br_flw_jsv_bgn] = ACTIONS(1), + [sym__r_flw_njv_bgn] = ACTIONS(1), + [sym__br_flw_njv_bgn] = ACTIONS(1), + [sym__r_dqt_str_bgn] = ACTIONS(1), + [sym__br_dqt_str_bgn] = ACTIONS(1), + [sym__b_dqt_str_bgn] = ACTIONS(1), + [sym__r_dqt_str_ctn] = ACTIONS(1), + [sym__br_dqt_str_ctn] = ACTIONS(1), + [sym__r_dqt_esc_nwl] = ACTIONS(1), + [sym__br_dqt_esc_nwl] = ACTIONS(1), + [sym__r_dqt_esc_seq] = ACTIONS(1), + [sym__br_dqt_esc_seq] = ACTIONS(1), + [sym__r_dqt_str_end] = ACTIONS(1), + [sym__br_dqt_str_end] = ACTIONS(1), + [sym__r_sqt_str_bgn] = ACTIONS(1), + [sym__br_sqt_str_bgn] = ACTIONS(1), + [sym__b_sqt_str_bgn] = ACTIONS(1), + [sym__r_sqt_str_ctn] = ACTIONS(1), + [sym__br_sqt_str_ctn] = ACTIONS(1), + [sym__r_sqt_esc_sqt] = ACTIONS(1), + [sym__br_sqt_esc_sqt] = ACTIONS(1), + [sym__r_sqt_str_end] = ACTIONS(1), + [sym__br_sqt_str_end] = ACTIONS(1), + [sym__r_sgl_pln_nul_blk] = ACTIONS(1), + [sym__br_sgl_pln_nul_blk] = ACTIONS(1), + [sym__b_sgl_pln_nul_blk] = ACTIONS(1), + [sym__r_sgl_pln_nul_flw] = ACTIONS(1), + [sym__br_sgl_pln_nul_flw] = ACTIONS(1), + [sym__r_sgl_pln_bol_blk] = ACTIONS(1), + [sym__br_sgl_pln_bol_blk] = ACTIONS(1), + [sym__b_sgl_pln_bol_blk] = ACTIONS(1), + [sym__r_sgl_pln_bol_flw] = ACTIONS(1), + [sym__br_sgl_pln_bol_flw] = ACTIONS(1), + [sym__r_sgl_pln_int_blk] = ACTIONS(1), + [sym__br_sgl_pln_int_blk] = ACTIONS(1), + [sym__b_sgl_pln_int_blk] = ACTIONS(1), + [sym__r_sgl_pln_int_flw] = ACTIONS(1), + [sym__br_sgl_pln_int_flw] = ACTIONS(1), + [sym__r_sgl_pln_flt_blk] = ACTIONS(1), + [sym__br_sgl_pln_flt_blk] = ACTIONS(1), + [sym__b_sgl_pln_flt_blk] = ACTIONS(1), + [sym__r_sgl_pln_flt_flw] = ACTIONS(1), + [sym__br_sgl_pln_flt_flw] = ACTIONS(1), + [sym__r_sgl_pln_tms_blk] = ACTIONS(1), + [sym__br_sgl_pln_tms_blk] = ACTIONS(1), + [sym__b_sgl_pln_tms_blk] = ACTIONS(1), + [sym__r_sgl_pln_tms_flw] = ACTIONS(1), + [sym__br_sgl_pln_tms_flw] = ACTIONS(1), + [sym__r_sgl_pln_str_blk] = ACTIONS(1), + [sym__br_sgl_pln_str_blk] = ACTIONS(1), + [sym__b_sgl_pln_str_blk] = ACTIONS(1), + [sym__r_sgl_pln_str_flw] = ACTIONS(1), + [sym__br_sgl_pln_str_flw] = ACTIONS(1), + [sym__r_mtl_pln_str_blk] = ACTIONS(1), + [sym__br_mtl_pln_str_blk] = ACTIONS(1), + [sym__r_mtl_pln_str_flw] = ACTIONS(1), + [sym__br_mtl_pln_str_flw] = ACTIONS(1), + [sym__r_tag] = ACTIONS(1), + [sym__br_tag] = ACTIONS(1), + [sym__b_tag] = ACTIONS(1), + [sym__r_acr_bgn] = ACTIONS(1), + [sym__br_acr_bgn] = ACTIONS(1), + [sym__b_acr_bgn] = ACTIONS(1), + [sym__r_acr_ctn] = ACTIONS(1), + [sym__r_als_bgn] = ACTIONS(1), + [sym__br_als_bgn] = ACTIONS(1), + [sym__b_als_bgn] = ACTIONS(1), + [sym__r_als_ctn] = ACTIONS(1), + [sym__bl] = ACTIONS(1), + [sym_comment] = ACTIONS(3), + [sym__err_rec] = ACTIONS(1), + }, + [STATE(1)] = { + [sym_stream] = STATE(1429), + [sym__bgn_imp_doc] = STATE(474), + [sym__drs_doc] = STATE(477), + [sym__exp_doc] = STATE(479), + [sym__drs_doc_end] = STATE(37), + [sym__exp_doc_end] = STATE(37), + [sym__bgn_imp_doc_end] = STATE(37), + [sym__doc_end] = STATE(37), + [sym__exp_doc_tal] = STATE(1123), + [sym__s_dir] = STATE(478), + [sym__s_dir_yml] = STATE(478), + [sym__s_dir_tag] = STATE(478), + [sym__s_dir_rsv] = STATE(478), + [sym__r_prp_val] = STATE(1123), + [sym__br_prp_val] = STATE(1123), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(81), + [sym__br_prp] = STATE(80), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(1123), + [sym__r_blk_seq_br_val] = STATE(1123), + [sym__br_blk_seq_val] = STATE(1123), + [sym__r_blk_seq] = STATE(1154), + [sym__br_blk_seq] = STATE(1170), + [sym__r_blk_seq_itm] = STATE(1004), + [sym__br_blk_seq_itm] = STATE(1048), + [sym__r_blk_map_r_val] = STATE(1123), + [sym__r_blk_map_br_val] = STATE(1123), + [sym__br_blk_map_val] = STATE(1123), + [sym__r_blk_map] = STATE(1175), + [sym__br_blk_map] = STATE(1200), + [sym__r_blk_map_itm] = STATE(125), + [sym__br_blk_map_itm] = STATE(130), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str_val] = STATE(1123), + [sym__br_blk_str_val] = STATE(1123), + [sym__r_blk_str] = STATE(1083), + [sym__br_blk_str] = STATE(1103), + [sym__r_flw_seq_val] = STATE(1123), + [sym__br_flw_seq_val] = STATE(1123), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1115), + [sym__br_flw_seq] = STATE(1156), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(1123), + [sym__br_flw_map_val] = STATE(1123), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1070), + [sym__br_flw_map] = STATE(1071), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(1123), + [sym__br_dqt_str_val] = STATE(1123), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1060), + [sym__br_dqt_str] = STATE(1087), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(1123), + [sym__br_sqt_str_val] = STATE(1123), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1127), + [sym__br_sqt_str] = STATE(1129), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(1123), + [sym__br_pln_blk_val] = STATE(1123), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1046), + [sym__br_sgl_pln_blk] = STATE(997), + [sym__r_mtl_pln_blk] = STATE(1094), + [sym__br_mtl_pln_blk] = STATE(1095), + [sym__r_als_val] = STATE(917), + [sym__br_als_val] = STATE(918), + [sym__r_als] = STATE(999), + [sym__br_als] = STATE(1001), + [sym__r_acr] = STATE(131), + [sym__br_acr] = STATE(146), + [aux_sym__drs_doc_repeat1] = STATE(478), + [sym__eof] = ACTIONS(5), + [sym__s_dir_yml_bgn] = ACTIONS(7), + [sym__s_dir_tag_bgn] = ACTIONS(9), + [sym__s_dir_rsv_bgn] = ACTIONS(11), + [sym__s_drs_end] = ACTIONS(13), + [sym__s_doc_end] = ACTIONS(15), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(29), + [sym__br_blk_lit_bgn] = ACTIONS(31), + [sym__r_blk_fld_bgn] = ACTIONS(29), + [sym__br_blk_fld_bgn] = ACTIONS(31), + [sym__r_flw_seq_bgn] = ACTIONS(33), + [sym__br_flw_seq_bgn] = ACTIONS(35), + [sym__r_flw_map_bgn] = ACTIONS(37), + [sym__br_flw_map_bgn] = ACTIONS(39), + [sym__r_dqt_str_bgn] = ACTIONS(41), + [sym__br_dqt_str_bgn] = ACTIONS(43), + [sym__r_sqt_str_bgn] = ACTIONS(45), + [sym__br_sqt_str_bgn] = ACTIONS(47), + [sym__r_sgl_pln_nul_blk] = ACTIONS(49), + [sym__br_sgl_pln_nul_blk] = ACTIONS(51), + [sym__r_sgl_pln_bol_blk] = ACTIONS(49), + [sym__br_sgl_pln_bol_blk] = ACTIONS(51), + [sym__r_sgl_pln_int_blk] = ACTIONS(49), + [sym__br_sgl_pln_int_blk] = ACTIONS(51), + [sym__r_sgl_pln_flt_blk] = ACTIONS(49), + [sym__br_sgl_pln_flt_blk] = ACTIONS(51), + [sym__r_sgl_pln_tms_blk] = ACTIONS(49), + [sym__br_sgl_pln_tms_blk] = ACTIONS(51), + [sym__r_sgl_pln_str_blk] = ACTIONS(49), + [sym__br_sgl_pln_str_blk] = ACTIONS(51), + [sym__r_mtl_pln_str_blk] = ACTIONS(53), + [sym__br_mtl_pln_str_blk] = ACTIONS(55), + [sym__r_tag] = ACTIONS(57), + [sym__br_tag] = ACTIONS(59), + [sym__r_acr_bgn] = ACTIONS(61), + [sym__br_acr_bgn] = ACTIONS(63), + [sym__r_als_bgn] = ACTIONS(65), + [sym__br_als_bgn] = ACTIONS(67), + [sym_comment] = ACTIONS(3), + }, + [STATE(2)] = { + [sym__r_prp_val] = STATE(316), + [sym__br_prp_val] = STATE(316), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(36), + [sym__br_prp] = STATE(35), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(316), + [sym__r_blk_seq_br_val] = STATE(316), + [sym__br_blk_seq_val] = STATE(316), + [sym__r_blk_seq_spc_val] = STATE(316), + [sym__br_blk_seq_spc_val] = STATE(316), + [sym__b_blk_seq_spc_val] = STATE(316), + [sym__r_blk_seq] = STATE(340), + [sym__br_blk_seq] = STATE(341), + [sym__b_blk_seq_spc] = STATE(310), + [sym__r_blk_seq_itm] = STATE(965), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__blk_seq_itm_tal] = STATE(316), + [sym__r_blk_map_r_val] = STATE(316), + [sym__r_blk_map_br_val] = STATE(316), + [sym__br_blk_map_val] = STATE(316), + [sym__r_blk_map] = STATE(342), + [sym__br_blk_map] = STATE(343), + [sym__r_blk_map_itm] = STATE(142), + [sym__br_blk_map_itm] = STATE(143), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__blk_exp_itm_tal] = STATE(316), + [sym__r_blk_str_val] = STATE(316), + [sym__br_blk_str_val] = STATE(316), + [sym__r_blk_str] = STATE(344), + [sym__br_blk_str] = STATE(345), + [sym__r_flw_seq_val] = STATE(316), + [sym__br_flw_seq_val] = STATE(316), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(346), + [sym__br_flw_seq] = STATE(347), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(316), + [sym__br_flw_map_val] = STATE(316), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(348), + [sym__br_flw_map] = STATE(349), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(316), + [sym__br_dqt_str_val] = STATE(316), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(350), + [sym__br_dqt_str] = STATE(351), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(316), + [sym__br_sqt_str_val] = STATE(316), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(352), + [sym__br_sqt_str] = STATE(353), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(316), + [sym__br_pln_blk_val] = STATE(316), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(281), + [sym__br_sgl_pln_blk] = STATE(282), + [sym__r_mtl_pln_blk] = STATE(356), + [sym__br_mtl_pln_blk] = STATE(357), + [sym__r_als_val] = STATE(262), + [sym__br_als_val] = STATE(264), + [sym__r_als] = STATE(266), + [sym__br_als] = STATE(283), + [sym__r_acr] = STATE(100), + [sym__br_acr] = STATE(99), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(71), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(71), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(77), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(71), + [sym__r_flw_map_bgn] = ACTIONS(81), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(71), + [sym__r_dqt_str_bgn] = ACTIONS(85), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(71), + [sym__r_sqt_str_bgn] = ACTIONS(89), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(71), + [sym__r_sgl_pln_nul_blk] = ACTIONS(93), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(71), + [sym__r_sgl_pln_bol_blk] = ACTIONS(93), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(71), + [sym__r_sgl_pln_int_blk] = ACTIONS(93), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(71), + [sym__r_sgl_pln_flt_blk] = ACTIONS(93), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(71), + [sym__r_sgl_pln_tms_blk] = ACTIONS(93), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(71), + [sym__r_sgl_pln_str_blk] = ACTIONS(93), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(71), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__r_tag] = ACTIONS(101), + [sym__br_tag] = ACTIONS(103), + [sym__b_tag] = ACTIONS(71), + [sym__r_acr_bgn] = ACTIONS(105), + [sym__br_acr_bgn] = ACTIONS(107), + [sym__b_acr_bgn] = ACTIONS(71), + [sym__r_als_bgn] = ACTIONS(109), + [sym__br_als_bgn] = ACTIONS(111), + [sym__b_als_bgn] = ACTIONS(71), + [sym__bl] = ACTIONS(71), + [sym_comment] = ACTIONS(3), + }, + [STATE(3)] = { + [sym__r_prp_val] = STATE(311), + [sym__br_prp_val] = STATE(311), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(36), + [sym__br_prp] = STATE(35), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(311), + [sym__r_blk_seq_br_val] = STATE(311), + [sym__br_blk_seq_val] = STATE(311), + [sym__r_blk_seq_spc_val] = STATE(311), + [sym__br_blk_seq_spc_val] = STATE(311), + [sym__b_blk_seq_spc_val] = STATE(311), + [sym__r_blk_seq] = STATE(340), + [sym__br_blk_seq] = STATE(341), + [sym__b_blk_seq_spc] = STATE(310), + [sym__r_blk_seq_itm] = STATE(965), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__blk_seq_itm_tal] = STATE(311), + [sym__r_blk_map_r_val] = STATE(311), + [sym__r_blk_map_br_val] = STATE(311), + [sym__br_blk_map_val] = STATE(311), + [sym__r_blk_map] = STATE(342), + [sym__br_blk_map] = STATE(343), + [sym__r_blk_map_itm] = STATE(142), + [sym__br_blk_map_itm] = STATE(143), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__blk_exp_itm_tal] = STATE(311), + [sym__r_blk_str_val] = STATE(311), + [sym__br_blk_str_val] = STATE(311), + [sym__r_blk_str] = STATE(344), + [sym__br_blk_str] = STATE(345), + [sym__r_flw_seq_val] = STATE(311), + [sym__br_flw_seq_val] = STATE(311), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(346), + [sym__br_flw_seq] = STATE(347), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(311), + [sym__br_flw_map_val] = STATE(311), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(348), + [sym__br_flw_map] = STATE(349), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(311), + [sym__br_dqt_str_val] = STATE(311), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(350), + [sym__br_dqt_str] = STATE(351), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(311), + [sym__br_sqt_str_val] = STATE(311), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(352), + [sym__br_sqt_str] = STATE(353), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(311), + [sym__br_pln_blk_val] = STATE(311), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(281), + [sym__br_sgl_pln_blk] = STATE(282), + [sym__r_mtl_pln_blk] = STATE(356), + [sym__br_mtl_pln_blk] = STATE(357), + [sym__r_als_val] = STATE(262), + [sym__br_als_val] = STATE(264), + [sym__r_als] = STATE(266), + [sym__br_als] = STATE(283), + [sym__r_acr] = STATE(100), + [sym__br_acr] = STATE(99), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(113), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(113), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(77), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(113), + [sym__r_flw_map_bgn] = ACTIONS(81), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(113), + [sym__r_dqt_str_bgn] = ACTIONS(85), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(113), + [sym__r_sqt_str_bgn] = ACTIONS(89), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(113), + [sym__r_sgl_pln_nul_blk] = ACTIONS(93), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(113), + [sym__r_sgl_pln_bol_blk] = ACTIONS(93), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(113), + [sym__r_sgl_pln_int_blk] = ACTIONS(93), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(113), + [sym__r_sgl_pln_flt_blk] = ACTIONS(93), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(113), + [sym__r_sgl_pln_tms_blk] = ACTIONS(93), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(113), + [sym__r_sgl_pln_str_blk] = ACTIONS(93), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(113), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__r_tag] = ACTIONS(101), + [sym__br_tag] = ACTIONS(103), + [sym__b_tag] = ACTIONS(113), + [sym__r_acr_bgn] = ACTIONS(105), + [sym__br_acr_bgn] = ACTIONS(107), + [sym__b_acr_bgn] = ACTIONS(113), + [sym__r_als_bgn] = ACTIONS(109), + [sym__br_als_bgn] = ACTIONS(111), + [sym__b_als_bgn] = ACTIONS(113), + [sym__bl] = ACTIONS(113), + [sym_comment] = ACTIONS(3), + }, + [STATE(4)] = { + [sym__r_prp_val] = STATE(312), + [sym__br_prp_val] = STATE(312), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(36), + [sym__br_prp] = STATE(35), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(312), + [sym__r_blk_seq_br_val] = STATE(312), + [sym__br_blk_seq_val] = STATE(312), + [sym__r_blk_seq_spc_val] = STATE(312), + [sym__br_blk_seq_spc_val] = STATE(312), + [sym__b_blk_seq_spc_val] = STATE(312), + [sym__r_blk_seq] = STATE(340), + [sym__br_blk_seq] = STATE(341), + [sym__b_blk_seq_spc] = STATE(310), + [sym__r_blk_seq_itm] = STATE(965), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__blk_seq_itm_tal] = STATE(312), + [sym__r_blk_map_r_val] = STATE(312), + [sym__r_blk_map_br_val] = STATE(312), + [sym__br_blk_map_val] = STATE(312), + [sym__r_blk_map] = STATE(342), + [sym__br_blk_map] = STATE(343), + [sym__r_blk_map_itm] = STATE(142), + [sym__br_blk_map_itm] = STATE(143), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__blk_exp_itm_tal] = STATE(312), + [sym__r_blk_str_val] = STATE(312), + [sym__br_blk_str_val] = STATE(312), + [sym__r_blk_str] = STATE(344), + [sym__br_blk_str] = STATE(345), + [sym__r_flw_seq_val] = STATE(312), + [sym__br_flw_seq_val] = STATE(312), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(346), + [sym__br_flw_seq] = STATE(347), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(312), + [sym__br_flw_map_val] = STATE(312), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(348), + [sym__br_flw_map] = STATE(349), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(312), + [sym__br_dqt_str_val] = STATE(312), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(350), + [sym__br_dqt_str] = STATE(351), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(312), + [sym__br_sqt_str_val] = STATE(312), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(352), + [sym__br_sqt_str] = STATE(353), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(312), + [sym__br_pln_blk_val] = STATE(312), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(281), + [sym__br_sgl_pln_blk] = STATE(282), + [sym__r_mtl_pln_blk] = STATE(356), + [sym__br_mtl_pln_blk] = STATE(357), + [sym__r_als_val] = STATE(262), + [sym__br_als_val] = STATE(264), + [sym__r_als] = STATE(266), + [sym__br_als] = STATE(283), + [sym__r_acr] = STATE(100), + [sym__br_acr] = STATE(99), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(115), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(115), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(77), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(115), + [sym__r_flw_map_bgn] = ACTIONS(81), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(115), + [sym__r_dqt_str_bgn] = ACTIONS(85), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(115), + [sym__r_sqt_str_bgn] = ACTIONS(89), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(115), + [sym__r_sgl_pln_nul_blk] = ACTIONS(93), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(115), + [sym__r_sgl_pln_bol_blk] = ACTIONS(93), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(115), + [sym__r_sgl_pln_int_blk] = ACTIONS(93), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(115), + [sym__r_sgl_pln_flt_blk] = ACTIONS(93), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(115), + [sym__r_sgl_pln_tms_blk] = ACTIONS(93), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(115), + [sym__r_sgl_pln_str_blk] = ACTIONS(93), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(115), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__r_tag] = ACTIONS(101), + [sym__br_tag] = ACTIONS(103), + [sym__b_tag] = ACTIONS(115), + [sym__r_acr_bgn] = ACTIONS(105), + [sym__br_acr_bgn] = ACTIONS(107), + [sym__b_acr_bgn] = ACTIONS(115), + [sym__r_als_bgn] = ACTIONS(109), + [sym__br_als_bgn] = ACTIONS(111), + [sym__b_als_bgn] = ACTIONS(115), + [sym__bl] = ACTIONS(115), + [sym_comment] = ACTIONS(3), + }, + [STATE(5)] = { + [sym__r_prp_val] = STATE(317), + [sym__br_prp_val] = STATE(317), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(36), + [sym__br_prp] = STATE(35), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(317), + [sym__r_blk_seq_br_val] = STATE(317), + [sym__br_blk_seq_val] = STATE(317), + [sym__r_blk_seq_spc_val] = STATE(317), + [sym__br_blk_seq_spc_val] = STATE(317), + [sym__b_blk_seq_spc_val] = STATE(317), + [sym__r_blk_seq] = STATE(340), + [sym__br_blk_seq] = STATE(341), + [sym__b_blk_seq_spc] = STATE(310), + [sym__r_blk_seq_itm] = STATE(965), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__blk_seq_itm_tal] = STATE(317), + [sym__r_blk_map_r_val] = STATE(317), + [sym__r_blk_map_br_val] = STATE(317), + [sym__br_blk_map_val] = STATE(317), + [sym__r_blk_map] = STATE(342), + [sym__br_blk_map] = STATE(343), + [sym__r_blk_map_itm] = STATE(142), + [sym__br_blk_map_itm] = STATE(143), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__blk_exp_itm_tal] = STATE(317), + [sym__r_blk_str_val] = STATE(317), + [sym__br_blk_str_val] = STATE(317), + [sym__r_blk_str] = STATE(344), + [sym__br_blk_str] = STATE(345), + [sym__r_flw_seq_val] = STATE(317), + [sym__br_flw_seq_val] = STATE(317), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(346), + [sym__br_flw_seq] = STATE(347), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(317), + [sym__br_flw_map_val] = STATE(317), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(348), + [sym__br_flw_map] = STATE(349), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(317), + [sym__br_dqt_str_val] = STATE(317), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(350), + [sym__br_dqt_str] = STATE(351), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(317), + [sym__br_sqt_str_val] = STATE(317), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(352), + [sym__br_sqt_str] = STATE(353), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(317), + [sym__br_pln_blk_val] = STATE(317), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(281), + [sym__br_sgl_pln_blk] = STATE(282), + [sym__r_mtl_pln_blk] = STATE(356), + [sym__br_mtl_pln_blk] = STATE(357), + [sym__r_als_val] = STATE(262), + [sym__br_als_val] = STATE(264), + [sym__r_als] = STATE(266), + [sym__br_als] = STATE(283), + [sym__r_acr] = STATE(100), + [sym__br_acr] = STATE(99), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(117), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(117), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(77), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(117), + [sym__r_flw_map_bgn] = ACTIONS(81), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(117), + [sym__r_dqt_str_bgn] = ACTIONS(85), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(117), + [sym__r_sqt_str_bgn] = ACTIONS(89), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(117), + [sym__r_sgl_pln_nul_blk] = ACTIONS(93), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(117), + [sym__r_sgl_pln_bol_blk] = ACTIONS(93), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(117), + [sym__r_sgl_pln_int_blk] = ACTIONS(93), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(117), + [sym__r_sgl_pln_flt_blk] = ACTIONS(93), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(117), + [sym__r_sgl_pln_tms_blk] = ACTIONS(93), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(117), + [sym__r_sgl_pln_str_blk] = ACTIONS(93), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(117), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__r_tag] = ACTIONS(101), + [sym__br_tag] = ACTIONS(103), + [sym__b_tag] = ACTIONS(117), + [sym__r_acr_bgn] = ACTIONS(105), + [sym__br_acr_bgn] = ACTIONS(107), + [sym__b_acr_bgn] = ACTIONS(117), + [sym__r_als_bgn] = ACTIONS(109), + [sym__br_als_bgn] = ACTIONS(111), + [sym__b_als_bgn] = ACTIONS(117), + [sym__bl] = ACTIONS(117), + [sym_comment] = ACTIONS(3), + }, + [STATE(6)] = { + [sym__r_prp_val] = STATE(302), + [sym__br_prp_val] = STATE(302), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(36), + [sym__br_prp] = STATE(35), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(302), + [sym__r_blk_seq_br_val] = STATE(302), + [sym__br_blk_seq_val] = STATE(302), + [sym__r_blk_seq_spc_val] = STATE(302), + [sym__br_blk_seq_spc_val] = STATE(302), + [sym__b_blk_seq_spc_val] = STATE(302), + [sym__r_blk_seq] = STATE(340), + [sym__br_blk_seq] = STATE(341), + [sym__b_blk_seq_spc] = STATE(310), + [sym__r_blk_seq_itm] = STATE(965), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__blk_seq_itm_tal] = STATE(302), + [sym__r_blk_map_r_val] = STATE(302), + [sym__r_blk_map_br_val] = STATE(302), + [sym__br_blk_map_val] = STATE(302), + [sym__r_blk_map] = STATE(342), + [sym__br_blk_map] = STATE(343), + [sym__r_blk_map_itm] = STATE(142), + [sym__br_blk_map_itm] = STATE(143), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__blk_exp_itm_tal] = STATE(302), + [sym__r_blk_str_val] = STATE(302), + [sym__br_blk_str_val] = STATE(302), + [sym__r_blk_str] = STATE(344), + [sym__br_blk_str] = STATE(345), + [sym__r_flw_seq_val] = STATE(302), + [sym__br_flw_seq_val] = STATE(302), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(346), + [sym__br_flw_seq] = STATE(347), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(302), + [sym__br_flw_map_val] = STATE(302), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(348), + [sym__br_flw_map] = STATE(349), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(302), + [sym__br_dqt_str_val] = STATE(302), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(350), + [sym__br_dqt_str] = STATE(351), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(302), + [sym__br_sqt_str_val] = STATE(302), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(352), + [sym__br_sqt_str] = STATE(353), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(302), + [sym__br_pln_blk_val] = STATE(302), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(281), + [sym__br_sgl_pln_blk] = STATE(282), + [sym__r_mtl_pln_blk] = STATE(356), + [sym__br_mtl_pln_blk] = STATE(357), + [sym__r_als_val] = STATE(262), + [sym__br_als_val] = STATE(264), + [sym__r_als] = STATE(266), + [sym__br_als] = STATE(283), + [sym__r_acr] = STATE(100), + [sym__br_acr] = STATE(99), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(119), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(119), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(77), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(119), + [sym__r_flw_map_bgn] = ACTIONS(81), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(119), + [sym__r_dqt_str_bgn] = ACTIONS(85), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(119), + [sym__r_sqt_str_bgn] = ACTIONS(89), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(119), + [sym__r_sgl_pln_nul_blk] = ACTIONS(93), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(119), + [sym__r_sgl_pln_bol_blk] = ACTIONS(93), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(119), + [sym__r_sgl_pln_int_blk] = ACTIONS(93), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(119), + [sym__r_sgl_pln_flt_blk] = ACTIONS(93), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(119), + [sym__r_sgl_pln_tms_blk] = ACTIONS(93), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(119), + [sym__r_sgl_pln_str_blk] = ACTIONS(93), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(119), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__r_tag] = ACTIONS(101), + [sym__br_tag] = ACTIONS(103), + [sym__b_tag] = ACTIONS(119), + [sym__r_acr_bgn] = ACTIONS(105), + [sym__br_acr_bgn] = ACTIONS(107), + [sym__b_acr_bgn] = ACTIONS(119), + [sym__r_als_bgn] = ACTIONS(109), + [sym__br_als_bgn] = ACTIONS(111), + [sym__b_als_bgn] = ACTIONS(119), + [sym__bl] = ACTIONS(119), + [sym_comment] = ACTIONS(3), + }, + [STATE(7)] = { + [sym__r_prp_val] = STATE(303), + [sym__br_prp_val] = STATE(303), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(36), + [sym__br_prp] = STATE(35), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(303), + [sym__r_blk_seq_br_val] = STATE(303), + [sym__br_blk_seq_val] = STATE(303), + [sym__r_blk_seq_spc_val] = STATE(303), + [sym__br_blk_seq_spc_val] = STATE(303), + [sym__b_blk_seq_spc_val] = STATE(303), + [sym__r_blk_seq] = STATE(340), + [sym__br_blk_seq] = STATE(341), + [sym__b_blk_seq_spc] = STATE(310), + [sym__r_blk_seq_itm] = STATE(965), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__blk_seq_itm_tal] = STATE(303), + [sym__r_blk_map_r_val] = STATE(303), + [sym__r_blk_map_br_val] = STATE(303), + [sym__br_blk_map_val] = STATE(303), + [sym__r_blk_map] = STATE(342), + [sym__br_blk_map] = STATE(343), + [sym__r_blk_map_itm] = STATE(142), + [sym__br_blk_map_itm] = STATE(143), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__blk_exp_itm_tal] = STATE(303), + [sym__r_blk_str_val] = STATE(303), + [sym__br_blk_str_val] = STATE(303), + [sym__r_blk_str] = STATE(344), + [sym__br_blk_str] = STATE(345), + [sym__r_flw_seq_val] = STATE(303), + [sym__br_flw_seq_val] = STATE(303), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(346), + [sym__br_flw_seq] = STATE(347), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(303), + [sym__br_flw_map_val] = STATE(303), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(348), + [sym__br_flw_map] = STATE(349), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(303), + [sym__br_dqt_str_val] = STATE(303), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(350), + [sym__br_dqt_str] = STATE(351), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(303), + [sym__br_sqt_str_val] = STATE(303), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(352), + [sym__br_sqt_str] = STATE(353), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(303), + [sym__br_pln_blk_val] = STATE(303), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(281), + [sym__br_sgl_pln_blk] = STATE(282), + [sym__r_mtl_pln_blk] = STATE(356), + [sym__br_mtl_pln_blk] = STATE(357), + [sym__r_als_val] = STATE(262), + [sym__br_als_val] = STATE(264), + [sym__r_als] = STATE(266), + [sym__br_als] = STATE(283), + [sym__r_acr] = STATE(100), + [sym__br_acr] = STATE(99), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(121), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(121), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(77), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(121), + [sym__r_flw_map_bgn] = ACTIONS(81), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(121), + [sym__r_dqt_str_bgn] = ACTIONS(85), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(121), + [sym__r_sqt_str_bgn] = ACTIONS(89), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(121), + [sym__r_sgl_pln_nul_blk] = ACTIONS(93), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(121), + [sym__r_sgl_pln_bol_blk] = ACTIONS(93), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(121), + [sym__r_sgl_pln_int_blk] = ACTIONS(93), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(121), + [sym__r_sgl_pln_flt_blk] = ACTIONS(93), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(121), + [sym__r_sgl_pln_tms_blk] = ACTIONS(93), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(121), + [sym__r_sgl_pln_str_blk] = ACTIONS(93), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(121), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__r_tag] = ACTIONS(101), + [sym__br_tag] = ACTIONS(103), + [sym__b_tag] = ACTIONS(121), + [sym__r_acr_bgn] = ACTIONS(105), + [sym__br_acr_bgn] = ACTIONS(107), + [sym__b_acr_bgn] = ACTIONS(121), + [sym__r_als_bgn] = ACTIONS(109), + [sym__br_als_bgn] = ACTIONS(111), + [sym__b_als_bgn] = ACTIONS(121), + [sym__bl] = ACTIONS(121), + [sym_comment] = ACTIONS(3), + }, + [STATE(8)] = { + [sym__r_prp_val] = STATE(1268), + [sym__br_prp_val] = STATE(1268), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(82), + [sym__br_prp] = STATE(83), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(1268), + [sym__r_blk_seq_br_val] = STATE(1268), + [sym__br_blk_seq_val] = STATE(1268), + [sym__r_blk_seq] = STATE(1386), + [sym__br_blk_seq] = STATE(1387), + [sym__r_blk_seq_itm] = STATE(1002), + [sym__br_blk_seq_itm] = STATE(1003), + [sym__blk_seq_itm_tal] = STATE(1268), + [sym__r_blk_map_r_val] = STATE(1268), + [sym__r_blk_map_br_val] = STATE(1268), + [sym__br_blk_map_val] = STATE(1268), + [sym__r_blk_map] = STATE(1388), + [sym__br_blk_map] = STATE(1389), + [sym__r_blk_map_itm] = STATE(134), + [sym__br_blk_map_itm] = STATE(135), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str_val] = STATE(1268), + [sym__br_blk_str_val] = STATE(1268), + [sym__r_blk_str] = STATE(1390), + [sym__br_blk_str] = STATE(1393), + [sym__r_flw_seq_val] = STATE(1268), + [sym__br_flw_seq_val] = STATE(1268), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1394), + [sym__br_flw_seq] = STATE(1395), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(1268), + [sym__br_flw_map_val] = STATE(1268), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1401), + [sym__br_flw_map] = STATE(1402), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(1268), + [sym__br_dqt_str_val] = STATE(1268), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1404), + [sym__br_dqt_str] = STATE(1407), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(1268), + [sym__br_sqt_str_val] = STATE(1268), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1217), + [sym__br_sqt_str] = STATE(1218), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(1268), + [sym__br_pln_blk_val] = STATE(1268), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1117), + [sym__br_sgl_pln_blk] = STATE(1118), + [sym__r_mtl_pln_blk] = STATE(1220), + [sym__br_mtl_pln_blk] = STATE(1221), + [sym__r_als_val] = STATE(967), + [sym__br_als_val] = STATE(969), + [sym__r_als] = STATE(1137), + [sym__br_als] = STATE(1122), + [sym__r_acr] = STATE(157), + [sym__br_acr] = STATE(158), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(123), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(125), + [sym__br_blk_lit_bgn] = ACTIONS(127), + [sym__r_blk_fld_bgn] = ACTIONS(125), + [sym__br_blk_fld_bgn] = ACTIONS(127), + [sym__r_flw_seq_bgn] = ACTIONS(129), + [sym__br_flw_seq_bgn] = ACTIONS(131), + [sym__r_flw_map_bgn] = ACTIONS(133), + [sym__br_flw_map_bgn] = ACTIONS(135), + [sym__r_dqt_str_bgn] = ACTIONS(137), + [sym__br_dqt_str_bgn] = ACTIONS(139), + [sym__r_sqt_str_bgn] = ACTIONS(141), + [sym__br_sqt_str_bgn] = ACTIONS(143), + [sym__r_sgl_pln_nul_blk] = ACTIONS(145), + [sym__br_sgl_pln_nul_blk] = ACTIONS(147), + [sym__r_sgl_pln_bol_blk] = ACTIONS(145), + [sym__br_sgl_pln_bol_blk] = ACTIONS(147), + [sym__r_sgl_pln_int_blk] = ACTIONS(145), + [sym__br_sgl_pln_int_blk] = ACTIONS(147), + [sym__r_sgl_pln_flt_blk] = ACTIONS(145), + [sym__br_sgl_pln_flt_blk] = ACTIONS(147), + [sym__r_sgl_pln_tms_blk] = ACTIONS(145), + [sym__br_sgl_pln_tms_blk] = ACTIONS(147), + [sym__r_sgl_pln_str_blk] = ACTIONS(145), + [sym__br_sgl_pln_str_blk] = ACTIONS(147), + [sym__r_mtl_pln_str_blk] = ACTIONS(149), + [sym__br_mtl_pln_str_blk] = ACTIONS(151), + [sym__r_tag] = ACTIONS(153), + [sym__br_tag] = ACTIONS(155), + [sym__r_acr_bgn] = ACTIONS(157), + [sym__br_acr_bgn] = ACTIONS(159), + [sym__r_als_bgn] = ACTIONS(161), + [sym__br_als_bgn] = ACTIONS(163), + [sym__bl] = ACTIONS(123), + [sym_comment] = ACTIONS(3), + }, + [STATE(9)] = { + [sym__r_prp_val] = STATE(1313), + [sym__br_prp_val] = STATE(1313), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(82), + [sym__br_prp] = STATE(83), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(1313), + [sym__r_blk_seq_br_val] = STATE(1313), + [sym__br_blk_seq_val] = STATE(1313), + [sym__r_blk_seq] = STATE(1386), + [sym__br_blk_seq] = STATE(1387), + [sym__r_blk_seq_itm] = STATE(1002), + [sym__br_blk_seq_itm] = STATE(1003), + [sym__blk_seq_itm_tal] = STATE(1313), + [sym__r_blk_map_r_val] = STATE(1313), + [sym__r_blk_map_br_val] = STATE(1313), + [sym__br_blk_map_val] = STATE(1313), + [sym__r_blk_map] = STATE(1388), + [sym__br_blk_map] = STATE(1389), + [sym__r_blk_map_itm] = STATE(134), + [sym__br_blk_map_itm] = STATE(135), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str_val] = STATE(1313), + [sym__br_blk_str_val] = STATE(1313), + [sym__r_blk_str] = STATE(1390), + [sym__br_blk_str] = STATE(1393), + [sym__r_flw_seq_val] = STATE(1313), + [sym__br_flw_seq_val] = STATE(1313), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1394), + [sym__br_flw_seq] = STATE(1395), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(1313), + [sym__br_flw_map_val] = STATE(1313), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1401), + [sym__br_flw_map] = STATE(1402), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(1313), + [sym__br_dqt_str_val] = STATE(1313), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1404), + [sym__br_dqt_str] = STATE(1407), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(1313), + [sym__br_sqt_str_val] = STATE(1313), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1217), + [sym__br_sqt_str] = STATE(1218), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(1313), + [sym__br_pln_blk_val] = STATE(1313), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1117), + [sym__br_sgl_pln_blk] = STATE(1118), + [sym__r_mtl_pln_blk] = STATE(1220), + [sym__br_mtl_pln_blk] = STATE(1221), + [sym__r_als_val] = STATE(967), + [sym__br_als_val] = STATE(969), + [sym__r_als] = STATE(1137), + [sym__br_als] = STATE(1122), + [sym__r_acr] = STATE(157), + [sym__br_acr] = STATE(158), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(165), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(125), + [sym__br_blk_lit_bgn] = ACTIONS(127), + [sym__r_blk_fld_bgn] = ACTIONS(125), + [sym__br_blk_fld_bgn] = ACTIONS(127), + [sym__r_flw_seq_bgn] = ACTIONS(129), + [sym__br_flw_seq_bgn] = ACTIONS(131), + [sym__r_flw_map_bgn] = ACTIONS(133), + [sym__br_flw_map_bgn] = ACTIONS(135), + [sym__r_dqt_str_bgn] = ACTIONS(137), + [sym__br_dqt_str_bgn] = ACTIONS(139), + [sym__r_sqt_str_bgn] = ACTIONS(141), + [sym__br_sqt_str_bgn] = ACTIONS(143), + [sym__r_sgl_pln_nul_blk] = ACTIONS(145), + [sym__br_sgl_pln_nul_blk] = ACTIONS(147), + [sym__r_sgl_pln_bol_blk] = ACTIONS(145), + [sym__br_sgl_pln_bol_blk] = ACTIONS(147), + [sym__r_sgl_pln_int_blk] = ACTIONS(145), + [sym__br_sgl_pln_int_blk] = ACTIONS(147), + [sym__r_sgl_pln_flt_blk] = ACTIONS(145), + [sym__br_sgl_pln_flt_blk] = ACTIONS(147), + [sym__r_sgl_pln_tms_blk] = ACTIONS(145), + [sym__br_sgl_pln_tms_blk] = ACTIONS(147), + [sym__r_sgl_pln_str_blk] = ACTIONS(145), + [sym__br_sgl_pln_str_blk] = ACTIONS(147), + [sym__r_mtl_pln_str_blk] = ACTIONS(149), + [sym__br_mtl_pln_str_blk] = ACTIONS(151), + [sym__r_tag] = ACTIONS(153), + [sym__br_tag] = ACTIONS(155), + [sym__r_acr_bgn] = ACTIONS(157), + [sym__br_acr_bgn] = ACTIONS(159), + [sym__r_als_bgn] = ACTIONS(161), + [sym__br_als_bgn] = ACTIONS(163), + [sym__bl] = ACTIONS(165), + [sym_comment] = ACTIONS(3), + }, + [STATE(10)] = { + [sym__r_prp_val] = STATE(1267), + [sym__br_prp_val] = STATE(1267), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(82), + [sym__br_prp] = STATE(83), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(1267), + [sym__r_blk_seq_br_val] = STATE(1267), + [sym__br_blk_seq_val] = STATE(1267), + [sym__r_blk_seq] = STATE(1386), + [sym__br_blk_seq] = STATE(1387), + [sym__r_blk_seq_itm] = STATE(1002), + [sym__br_blk_seq_itm] = STATE(1003), + [sym__blk_seq_itm_tal] = STATE(1267), + [sym__r_blk_map_r_val] = STATE(1267), + [sym__r_blk_map_br_val] = STATE(1267), + [sym__br_blk_map_val] = STATE(1267), + [sym__r_blk_map] = STATE(1388), + [sym__br_blk_map] = STATE(1389), + [sym__r_blk_map_itm] = STATE(134), + [sym__br_blk_map_itm] = STATE(135), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str_val] = STATE(1267), + [sym__br_blk_str_val] = STATE(1267), + [sym__r_blk_str] = STATE(1390), + [sym__br_blk_str] = STATE(1393), + [sym__r_flw_seq_val] = STATE(1267), + [sym__br_flw_seq_val] = STATE(1267), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1394), + [sym__br_flw_seq] = STATE(1395), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(1267), + [sym__br_flw_map_val] = STATE(1267), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1401), + [sym__br_flw_map] = STATE(1402), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(1267), + [sym__br_dqt_str_val] = STATE(1267), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1404), + [sym__br_dqt_str] = STATE(1407), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(1267), + [sym__br_sqt_str_val] = STATE(1267), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1217), + [sym__br_sqt_str] = STATE(1218), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(1267), + [sym__br_pln_blk_val] = STATE(1267), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1117), + [sym__br_sgl_pln_blk] = STATE(1118), + [sym__r_mtl_pln_blk] = STATE(1220), + [sym__br_mtl_pln_blk] = STATE(1221), + [sym__r_als_val] = STATE(967), + [sym__br_als_val] = STATE(969), + [sym__r_als] = STATE(1137), + [sym__br_als] = STATE(1122), + [sym__r_acr] = STATE(157), + [sym__br_acr] = STATE(158), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(167), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(125), + [sym__br_blk_lit_bgn] = ACTIONS(127), + [sym__r_blk_fld_bgn] = ACTIONS(125), + [sym__br_blk_fld_bgn] = ACTIONS(127), + [sym__r_flw_seq_bgn] = ACTIONS(129), + [sym__br_flw_seq_bgn] = ACTIONS(131), + [sym__r_flw_map_bgn] = ACTIONS(133), + [sym__br_flw_map_bgn] = ACTIONS(135), + [sym__r_dqt_str_bgn] = ACTIONS(137), + [sym__br_dqt_str_bgn] = ACTIONS(139), + [sym__r_sqt_str_bgn] = ACTIONS(141), + [sym__br_sqt_str_bgn] = ACTIONS(143), + [sym__r_sgl_pln_nul_blk] = ACTIONS(145), + [sym__br_sgl_pln_nul_blk] = ACTIONS(147), + [sym__r_sgl_pln_bol_blk] = ACTIONS(145), + [sym__br_sgl_pln_bol_blk] = ACTIONS(147), + [sym__r_sgl_pln_int_blk] = ACTIONS(145), + [sym__br_sgl_pln_int_blk] = ACTIONS(147), + [sym__r_sgl_pln_flt_blk] = ACTIONS(145), + [sym__br_sgl_pln_flt_blk] = ACTIONS(147), + [sym__r_sgl_pln_tms_blk] = ACTIONS(145), + [sym__br_sgl_pln_tms_blk] = ACTIONS(147), + [sym__r_sgl_pln_str_blk] = ACTIONS(145), + [sym__br_sgl_pln_str_blk] = ACTIONS(147), + [sym__r_mtl_pln_str_blk] = ACTIONS(149), + [sym__br_mtl_pln_str_blk] = ACTIONS(151), + [sym__r_tag] = ACTIONS(153), + [sym__br_tag] = ACTIONS(155), + [sym__r_acr_bgn] = ACTIONS(157), + [sym__br_acr_bgn] = ACTIONS(159), + [sym__r_als_bgn] = ACTIONS(161), + [sym__br_als_bgn] = ACTIONS(163), + [sym__bl] = ACTIONS(167), + [sym_comment] = ACTIONS(3), + }, + [STATE(11)] = { + [sym__r_prp_val] = STATE(300), + [sym__br_prp_val] = STATE(300), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(36), + [sym__br_prp] = STATE(35), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_br_val] = STATE(300), + [sym__br_blk_seq_val] = STATE(300), + [sym__r_blk_seq_spc_val] = STATE(300), + [sym__br_blk_seq_spc_val] = STATE(300), + [sym__b_blk_seq_spc_val] = STATE(300), + [sym__br_blk_seq] = STATE(341), + [sym__b_blk_seq_spc] = STATE(310), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__r_blk_map_br_val] = STATE(300), + [sym__br_blk_map_val] = STATE(300), + [sym__br_blk_map] = STATE(343), + [sym__br_blk_map_itm] = STATE(143), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str_val] = STATE(300), + [sym__br_blk_str_val] = STATE(300), + [sym__r_blk_str] = STATE(344), + [sym__br_blk_str] = STATE(345), + [sym__r_flw_seq_val] = STATE(300), + [sym__br_flw_seq_val] = STATE(300), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(346), + [sym__br_flw_seq] = STATE(347), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(300), + [sym__br_flw_map_val] = STATE(300), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(348), + [sym__br_flw_map] = STATE(349), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(300), + [sym__br_dqt_str_val] = STATE(300), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(350), + [sym__br_dqt_str] = STATE(351), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(300), + [sym__br_sqt_str_val] = STATE(300), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(352), + [sym__br_sqt_str] = STATE(353), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(300), + [sym__br_pln_blk_val] = STATE(300), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(356), + [sym__br_sgl_pln_blk] = STATE(282), + [sym__r_mtl_pln_blk] = STATE(356), + [sym__br_mtl_pln_blk] = STATE(357), + [sym__r_als_val] = STATE(300), + [sym__br_als_val] = STATE(263), + [sym__r_als] = STATE(330), + [sym__br_als] = STATE(283), + [sym__r_acr] = STATE(105), + [sym__br_acr] = STATE(99), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(169), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(169), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(171), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(169), + [sym__r_flw_map_bgn] = ACTIONS(173), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(169), + [sym__r_dqt_str_bgn] = ACTIONS(175), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(169), + [sym__r_sqt_str_bgn] = ACTIONS(177), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(169), + [sym__r_sgl_pln_nul_blk] = ACTIONS(179), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(169), + [sym__r_sgl_pln_bol_blk] = ACTIONS(179), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(169), + [sym__r_sgl_pln_int_blk] = ACTIONS(179), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(169), + [sym__r_sgl_pln_flt_blk] = ACTIONS(179), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(169), + [sym__r_sgl_pln_tms_blk] = ACTIONS(179), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(169), + [sym__r_sgl_pln_str_blk] = ACTIONS(179), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(169), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__r_tag] = ACTIONS(181), + [sym__br_tag] = ACTIONS(103), + [sym__b_tag] = ACTIONS(169), + [sym__r_acr_bgn] = ACTIONS(183), + [sym__br_acr_bgn] = ACTIONS(107), + [sym__b_acr_bgn] = ACTIONS(169), + [sym__r_als_bgn] = ACTIONS(185), + [sym__br_als_bgn] = ACTIONS(111), + [sym__b_als_bgn] = ACTIONS(169), + [sym__bl] = ACTIONS(169), + [sym_comment] = ACTIONS(3), + }, + [STATE(12)] = { + [sym__exp_doc_tal] = STATE(1143), + [sym__r_prp_val] = STATE(1143), + [sym__br_prp_val] = STATE(1143), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(81), + [sym__br_prp] = STATE(80), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_br_val] = STATE(1143), + [sym__br_blk_seq_val] = STATE(1143), + [sym__br_blk_seq] = STATE(1170), + [sym__br_blk_seq_itm] = STATE(1048), + [sym__r_blk_map_br_val] = STATE(1143), + [sym__br_blk_map_val] = STATE(1143), + [sym__br_blk_map] = STATE(1200), + [sym__br_blk_map_itm] = STATE(130), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str_val] = STATE(1143), + [sym__br_blk_str_val] = STATE(1143), + [sym__r_blk_str] = STATE(1083), + [sym__br_blk_str] = STATE(1103), + [sym__r_flw_seq_val] = STATE(1143), + [sym__br_flw_seq_val] = STATE(1143), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1115), + [sym__br_flw_seq] = STATE(1156), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(1143), + [sym__br_flw_map_val] = STATE(1143), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1070), + [sym__br_flw_map] = STATE(1071), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(1143), + [sym__br_dqt_str_val] = STATE(1143), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1060), + [sym__br_dqt_str] = STATE(1087), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(1143), + [sym__br_sqt_str_val] = STATE(1143), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1127), + [sym__br_sqt_str] = STATE(1129), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(1143), + [sym__br_pln_blk_val] = STATE(1143), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1094), + [sym__br_sgl_pln_blk] = STATE(997), + [sym__r_mtl_pln_blk] = STATE(1094), + [sym__br_mtl_pln_blk] = STATE(1095), + [sym__r_als_val] = STATE(1143), + [sym__br_als_val] = STATE(918), + [sym__r_als] = STATE(1049), + [sym__br_als] = STATE(1001), + [sym__r_acr] = STATE(160), + [sym__br_acr] = STATE(146), + [sym__eof] = ACTIONS(187), + [sym__s_drs_end] = ACTIONS(187), + [sym__s_doc_end] = ACTIONS(187), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(29), + [sym__br_blk_lit_bgn] = ACTIONS(31), + [sym__r_blk_fld_bgn] = ACTIONS(29), + [sym__br_blk_fld_bgn] = ACTIONS(31), + [sym__r_flw_seq_bgn] = ACTIONS(189), + [sym__br_flw_seq_bgn] = ACTIONS(35), + [sym__r_flw_map_bgn] = ACTIONS(191), + [sym__br_flw_map_bgn] = ACTIONS(39), + [sym__r_dqt_str_bgn] = ACTIONS(193), + [sym__br_dqt_str_bgn] = ACTIONS(43), + [sym__r_sqt_str_bgn] = ACTIONS(195), + [sym__br_sqt_str_bgn] = ACTIONS(47), + [sym__r_sgl_pln_nul_blk] = ACTIONS(197), + [sym__br_sgl_pln_nul_blk] = ACTIONS(51), + [sym__r_sgl_pln_bol_blk] = ACTIONS(197), + [sym__br_sgl_pln_bol_blk] = ACTIONS(51), + [sym__r_sgl_pln_int_blk] = ACTIONS(197), + [sym__br_sgl_pln_int_blk] = ACTIONS(51), + [sym__r_sgl_pln_flt_blk] = ACTIONS(197), + [sym__br_sgl_pln_flt_blk] = ACTIONS(51), + [sym__r_sgl_pln_tms_blk] = ACTIONS(197), + [sym__br_sgl_pln_tms_blk] = ACTIONS(51), + [sym__r_sgl_pln_str_blk] = ACTIONS(197), + [sym__br_sgl_pln_str_blk] = ACTIONS(51), + [sym__r_mtl_pln_str_blk] = ACTIONS(53), + [sym__br_mtl_pln_str_blk] = ACTIONS(55), + [sym__r_tag] = ACTIONS(199), + [sym__br_tag] = ACTIONS(59), + [sym__r_acr_bgn] = ACTIONS(201), + [sym__br_acr_bgn] = ACTIONS(63), + [sym__r_als_bgn] = ACTIONS(203), + [sym__br_als_bgn] = ACTIONS(67), + [sym_comment] = ACTIONS(3), + }, + [STATE(13)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(1133), + [sym__sgl_flw_map_tal] = STATE(1517), + [sym__r_flw_map_dat] = STATE(1138), + [sym__br_flw_map_dat] = STATE(1138), + [sym__r_sgl_flw_col_dat] = STATE(1516), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(213), + [sym__br_flw_map_end] = ACTIONS(215), + [sym__b_flw_map_end] = ACTIONS(215), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(14)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(1076), + [sym__sgl_flw_map_tal] = STATE(1450), + [sym__r_flw_map_dat] = STATE(1138), + [sym__br_flw_map_dat] = STATE(1138), + [sym__r_sgl_flw_col_dat] = STATE(1516), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(213), + [sym__br_flw_map_end] = ACTIONS(253), + [sym__b_flw_map_end] = ACTIONS(253), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(15)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(1258), + [sym__sgl_flw_map_tal] = STATE(1517), + [sym__r_flw_map_dat] = STATE(1125), + [sym__br_flw_map_dat] = STATE(1125), + [sym__r_sgl_flw_col_dat] = STATE(1516), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(255), + [sym__br_flw_map_end] = ACTIONS(257), + [sym__b_flw_map_end] = ACTIONS(257), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(16)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(370), + [sym__sgl_flw_map_tal] = STATE(1450), + [sym__r_flw_map_dat] = STATE(1152), + [sym__br_flw_map_dat] = STATE(1152), + [sym__r_sgl_flw_col_dat] = STATE(1516), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(259), + [sym__br_flw_map_end] = ACTIONS(261), + [sym__b_flw_map_end] = ACTIONS(261), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(17)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(1259), + [sym__sgl_flw_map_tal] = STATE(1450), + [sym__r_flw_map_dat] = STATE(1125), + [sym__br_flw_map_dat] = STATE(1125), + [sym__r_sgl_flw_col_dat] = STATE(1516), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(255), + [sym__br_flw_map_end] = ACTIONS(263), + [sym__b_flw_map_end] = ACTIONS(263), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(18)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(369), + [sym__sgl_flw_map_tal] = STATE(1517), + [sym__r_flw_map_dat] = STATE(1152), + [sym__br_flw_map_dat] = STATE(1152), + [sym__r_sgl_flw_col_dat] = STATE(1516), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(259), + [sym__br_flw_map_end] = ACTIONS(265), + [sym__b_flw_map_end] = ACTIONS(265), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(19)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(570), + [sym__sgl_flw_map_tal] = STATE(1064), + [sym__r_flw_map_dat] = STATE(1173), + [sym__br_flw_map_dat] = STATE(1173), + [sym__r_sgl_flw_col_dat] = STATE(1476), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(267), + [sym__br_flw_map_end] = ACTIONS(269), + [sym__b_flw_map_end] = ACTIONS(269), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(20)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(1321), + [sym__sgl_flw_map_tal] = STATE(1422), + [sym__r_flw_map_dat] = STATE(1183), + [sym__br_flw_map_dat] = STATE(1183), + [sym__r_sgl_flw_col_dat] = STATE(1460), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(271), + [sym__br_flw_map_end] = ACTIONS(273), + [sym__b_flw_map_end] = ACTIONS(273), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(21)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(715), + [sym__sgl_flw_map_tal] = STATE(1145), + [sym__r_flw_map_dat] = STATE(1166), + [sym__br_flw_map_dat] = STATE(1166), + [sym__r_sgl_flw_col_dat] = STATE(1471), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(275), + [sym__br_flw_map_end] = ACTIONS(277), + [sym__b_flw_map_end] = ACTIONS(277), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(22)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(831), + [sym__sgl_flw_map_tal] = STATE(1264), + [sym__r_flw_map_dat] = STATE(1194), + [sym__br_flw_map_dat] = STATE(1194), + [sym__r_sgl_flw_col_dat] = STATE(1527), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(279), + [sym__br_flw_map_end] = ACTIONS(281), + [sym__b_flw_map_end] = ACTIONS(281), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(23)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(879), + [sym__sgl_flw_map_tal] = STATE(1322), + [sym__r_flw_map_dat] = STATE(1212), + [sym__br_flw_map_dat] = STATE(1212), + [sym__r_sgl_flw_col_dat] = STATE(1449), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(283), + [sym__br_flw_map_end] = ACTIONS(285), + [sym__b_flw_map_end] = ACTIONS(285), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(24)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(566), + [sym__sgl_flw_seq_tal] = STATE(1050), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1172), + [sym__br_flw_seq_dat] = STATE(1172), + [sym__r_sgl_flw_col_dat] = STATE(1473), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(291), + [sym__br_flw_seq_end] = ACTIONS(293), + [sym__b_flw_seq_end] = ACTIONS(293), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(25)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(367), + [sym__sgl_flw_seq_tal] = STATE(1416), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1151), + [sym__br_flw_seq_dat] = STATE(1151), + [sym__r_sgl_flw_col_dat] = STATE(1459), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(335), + [sym__br_flw_seq_end] = ACTIONS(337), + [sym__b_flw_seq_end] = ACTIONS(337), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(26)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(366), + [sym__sgl_flw_seq_tal] = STATE(1423), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1151), + [sym__br_flw_seq_dat] = STATE(1151), + [sym__r_sgl_flw_col_dat] = STATE(1459), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(335), + [sym__br_flw_seq_end] = ACTIONS(339), + [sym__b_flw_seq_end] = ACTIONS(339), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(27)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(1109), + [sym__sgl_flw_seq_tal] = STATE(1416), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1058), + [sym__br_flw_seq_dat] = STATE(1058), + [sym__r_sgl_flw_col_dat] = STATE(1459), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(341), + [sym__br_flw_seq_end] = ACTIONS(343), + [sym__b_flw_seq_end] = ACTIONS(343), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(28)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(1247), + [sym__sgl_flw_seq_tal] = STATE(1423), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1124), + [sym__br_flw_seq_dat] = STATE(1124), + [sym__r_sgl_flw_col_dat] = STATE(1459), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(345), + [sym__br_flw_seq_end] = ACTIONS(347), + [sym__b_flw_seq_end] = ACTIONS(347), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(29)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(1256), + [sym__sgl_flw_seq_tal] = STATE(1416), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1124), + [sym__br_flw_seq_dat] = STATE(1124), + [sym__r_sgl_flw_col_dat] = STATE(1459), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(345), + [sym__br_flw_seq_end] = ACTIONS(349), + [sym__b_flw_seq_end] = ACTIONS(349), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(30)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(712), + [sym__sgl_flw_seq_tal] = STATE(1139), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1165), + [sym__br_flw_seq_dat] = STATE(1165), + [sym__r_sgl_flw_col_dat] = STATE(1468), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(351), + [sym__br_flw_seq_end] = ACTIONS(353), + [sym__b_flw_seq_end] = ACTIONS(353), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(31)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(828), + [sym__sgl_flw_seq_tal] = STATE(1257), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1193), + [sym__br_flw_seq_dat] = STATE(1193), + [sym__r_sgl_flw_col_dat] = STATE(1525), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(355), + [sym__br_flw_seq_end] = ACTIONS(357), + [sym__b_flw_seq_end] = ACTIONS(357), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(32)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(1131), + [sym__sgl_flw_seq_tal] = STATE(1423), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1058), + [sym__br_flw_seq_dat] = STATE(1058), + [sym__r_sgl_flw_col_dat] = STATE(1459), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(341), + [sym__br_flw_seq_end] = ACTIONS(359), + [sym__b_flw_seq_end] = ACTIONS(359), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(33)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(1316), + [sym__sgl_flw_seq_tal] = STATE(1509), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1182), + [sym__br_flw_seq_dat] = STATE(1182), + [sym__r_sgl_flw_col_dat] = STATE(1457), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(361), + [sym__br_flw_seq_end] = ACTIONS(363), + [sym__b_flw_seq_end] = ACTIONS(363), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(34)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(784), + [sym__sgl_flw_seq_tal] = STATE(1317), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1211), + [sym__br_flw_seq_dat] = STATE(1211), + [sym__r_sgl_flw_col_dat] = STATE(1447), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(365), + [sym__br_flw_seq_end] = ACTIONS(367), + [sym__b_flw_seq_end] = ACTIONS(367), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(35)] = { + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq] = STATE(388), + [sym__b_blk_seq_spc] = STATE(339), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__br_blk_map] = STATE(389), + [sym__br_blk_map_itm] = STATE(143), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str] = STATE(390), + [sym__br_blk_str] = STATE(390), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(378), + [sym__br_flw_seq] = STATE(378), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(327), + [sym__br_flw_map] = STATE(327), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(298), + [sym__br_dqt_str] = STATE(298), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(355), + [sym__br_sqt_str] = STATE(355), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(335), + [sym__br_sgl_pln_blk] = STATE(268), + [sym__r_mtl_pln_blk] = STATE(335), + [sym__br_mtl_pln_blk] = STATE(335), + [sym__br_als_val] = STATE(1237), + [sym__br_als] = STATE(1487), + [sym__br_acr] = STATE(415), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(369), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(369), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(171), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(369), + [sym__r_flw_map_bgn] = ACTIONS(173), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(369), + [sym__r_dqt_str_bgn] = ACTIONS(175), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(369), + [sym__r_sqt_str_bgn] = ACTIONS(177), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(369), + [sym__r_sgl_pln_nul_blk] = ACTIONS(179), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(369), + [sym__r_sgl_pln_bol_blk] = ACTIONS(179), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(369), + [sym__r_sgl_pln_int_blk] = ACTIONS(179), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(369), + [sym__r_sgl_pln_flt_blk] = ACTIONS(179), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(369), + [sym__r_sgl_pln_tms_blk] = ACTIONS(179), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(369), + [sym__r_sgl_pln_str_blk] = ACTIONS(179), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(369), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__br_tag] = ACTIONS(371), + [sym__b_tag] = ACTIONS(369), + [sym__br_acr_bgn] = ACTIONS(373), + [sym__b_acr_bgn] = ACTIONS(369), + [sym__br_als_bgn] = ACTIONS(375), + [sym__b_als_bgn] = ACTIONS(369), + [sym__bl] = ACTIONS(369), + [sym_comment] = ACTIONS(3), + }, + [STATE(36)] = { + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq] = STATE(379), + [sym__b_blk_seq_spc] = STATE(338), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__br_blk_map] = STATE(380), + [sym__br_blk_map_itm] = STATE(143), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str] = STATE(381), + [sym__br_blk_str] = STATE(381), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(382), + [sym__br_flw_seq] = STATE(382), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(383), + [sym__br_flw_map] = STATE(383), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(384), + [sym__br_dqt_str] = STATE(384), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(385), + [sym__br_sqt_str] = STATE(385), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(386), + [sym__br_sgl_pln_blk] = STATE(267), + [sym__r_mtl_pln_blk] = STATE(386), + [sym__br_mtl_pln_blk] = STATE(386), + [sym__br_als_val] = STATE(1237), + [sym__br_als] = STATE(1487), + [sym__br_acr] = STATE(415), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(377), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(377), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(171), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(377), + [sym__r_flw_map_bgn] = ACTIONS(173), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(377), + [sym__r_dqt_str_bgn] = ACTIONS(175), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(377), + [sym__r_sqt_str_bgn] = ACTIONS(177), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(377), + [sym__r_sgl_pln_nul_blk] = ACTIONS(179), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(377), + [sym__r_sgl_pln_bol_blk] = ACTIONS(179), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(377), + [sym__r_sgl_pln_int_blk] = ACTIONS(179), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(377), + [sym__r_sgl_pln_flt_blk] = ACTIONS(179), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(377), + [sym__r_sgl_pln_tms_blk] = ACTIONS(179), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(377), + [sym__r_sgl_pln_str_blk] = ACTIONS(179), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(377), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__br_tag] = ACTIONS(371), + [sym__b_tag] = ACTIONS(377), + [sym__br_acr_bgn] = ACTIONS(373), + [sym__b_acr_bgn] = ACTIONS(377), + [sym__br_als_bgn] = ACTIONS(375), + [sym__b_als_bgn] = ACTIONS(377), + [sym__bl] = ACTIONS(377), + [sym_comment] = ACTIONS(3), + }, + [STATE(37)] = { + [sym__doc_w_bgn_w_end_seq] = STATE(1428), + [sym__doc_w_bgn_wo_end_seq] = STATE(1428), + [sym__doc_wo_bgn_w_end_seq] = STATE(1428), + [sym__doc_wo_bgn_wo_end_seq] = STATE(1428), + [sym__doc_w_bgn_w_end] = STATE(38), + [sym__doc_w_bgn_wo_end] = STATE(476), + [sym__doc_wo_bgn_w_end] = STATE(39), + [sym__doc_wo_bgn_wo_end] = STATE(480), + [sym__drs_doc] = STATE(1167), + [sym__exp_doc] = STATE(1155), + [sym__imp_doc] = STATE(1168), + [sym__drs_doc_end] = STATE(39), + [sym__exp_doc_end] = STATE(38), + [sym__imp_doc_end] = STATE(39), + [sym__doc_end] = STATE(38), + [sym__s_dir] = STATE(478), + [sym__s_dir_yml] = STATE(478), + [sym__s_dir_tag] = STATE(478), + [sym__s_dir_rsv] = STATE(478), + [sym__br_prp_val] = STATE(1169), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_prp] = STATE(80), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq_val] = STATE(1169), + [sym__br_blk_seq] = STATE(1170), + [sym__br_blk_seq_itm] = STATE(1048), + [sym__br_blk_map_val] = STATE(1169), + [sym__br_blk_map] = STATE(1200), + [sym__br_blk_map_itm] = STATE(130), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__br_blk_str_val] = STATE(1169), + [sym__br_blk_str] = STATE(1103), + [sym__br_flw_seq_val] = STATE(1169), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__br_flw_seq] = STATE(1156), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_flw_map_val] = STATE(1169), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__br_flw_map] = STATE(1071), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_dqt_str_val] = STATE(1169), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__br_dqt_str] = STATE(1087), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sqt_str_val] = STATE(1169), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__br_sqt_str] = STATE(1129), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_pln_blk_val] = STATE(1169), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__br_sgl_pln_blk] = STATE(997), + [sym__br_mtl_pln_blk] = STATE(1095), + [sym__br_als_val] = STATE(939), + [sym__br_als] = STATE(1001), + [sym__br_acr] = STATE(146), + [aux_sym__drs_doc_repeat1] = STATE(478), + [sym__eof] = ACTIONS(379), + [sym__s_dir_yml_bgn] = ACTIONS(7), + [sym__s_dir_tag_bgn] = ACTIONS(9), + [sym__s_dir_rsv_bgn] = ACTIONS(11), + [sym__s_drs_end] = ACTIONS(13), + [sym__s_doc_end] = ACTIONS(15), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__br_blk_lit_bgn] = ACTIONS(31), + [sym__br_blk_fld_bgn] = ACTIONS(31), + [sym__br_flw_seq_bgn] = ACTIONS(35), + [sym__br_flw_map_bgn] = ACTIONS(39), + [sym__br_dqt_str_bgn] = ACTIONS(43), + [sym__br_sqt_str_bgn] = ACTIONS(47), + [sym__br_sgl_pln_nul_blk] = ACTIONS(51), + [sym__br_sgl_pln_bol_blk] = ACTIONS(51), + [sym__br_sgl_pln_int_blk] = ACTIONS(51), + [sym__br_sgl_pln_flt_blk] = ACTIONS(51), + [sym__br_sgl_pln_tms_blk] = ACTIONS(51), + [sym__br_sgl_pln_str_blk] = ACTIONS(51), + [sym__br_mtl_pln_str_blk] = ACTIONS(55), + [sym__br_tag] = ACTIONS(59), + [sym__br_acr_bgn] = ACTIONS(63), + [sym__br_als_bgn] = ACTIONS(67), + [sym_comment] = ACTIONS(3), + }, + [STATE(38)] = { + [sym__doc_w_bgn_w_end_seq] = STATE(1456), + [sym__doc_w_bgn_wo_end_seq] = STATE(1456), + [sym__doc_wo_bgn_w_end_seq] = STATE(1456), + [sym__doc_wo_bgn_wo_end_seq] = STATE(1456), + [sym__doc_w_bgn_w_end] = STATE(38), + [sym__doc_w_bgn_wo_end] = STATE(476), + [sym__doc_wo_bgn_w_end] = STATE(39), + [sym__doc_wo_bgn_wo_end] = STATE(480), + [sym__drs_doc] = STATE(1167), + [sym__exp_doc] = STATE(1155), + [sym__imp_doc] = STATE(1168), + [sym__drs_doc_end] = STATE(39), + [sym__exp_doc_end] = STATE(38), + [sym__imp_doc_end] = STATE(39), + [sym__doc_end] = STATE(38), + [sym__s_dir] = STATE(478), + [sym__s_dir_yml] = STATE(478), + [sym__s_dir_tag] = STATE(478), + [sym__s_dir_rsv] = STATE(478), + [sym__br_prp_val] = STATE(1169), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_prp] = STATE(80), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq_val] = STATE(1169), + [sym__br_blk_seq] = STATE(1170), + [sym__br_blk_seq_itm] = STATE(1048), + [sym__br_blk_map_val] = STATE(1169), + [sym__br_blk_map] = STATE(1200), + [sym__br_blk_map_itm] = STATE(130), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__br_blk_str_val] = STATE(1169), + [sym__br_blk_str] = STATE(1103), + [sym__br_flw_seq_val] = STATE(1169), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__br_flw_seq] = STATE(1156), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_flw_map_val] = STATE(1169), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__br_flw_map] = STATE(1071), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_dqt_str_val] = STATE(1169), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__br_dqt_str] = STATE(1087), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sqt_str_val] = STATE(1169), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__br_sqt_str] = STATE(1129), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_pln_blk_val] = STATE(1169), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__br_sgl_pln_blk] = STATE(997), + [sym__br_mtl_pln_blk] = STATE(1095), + [sym__br_als_val] = STATE(939), + [sym__br_als] = STATE(1001), + [sym__br_acr] = STATE(146), + [aux_sym__drs_doc_repeat1] = STATE(478), + [sym__eof] = ACTIONS(381), + [sym__s_dir_yml_bgn] = ACTIONS(7), + [sym__s_dir_tag_bgn] = ACTIONS(9), + [sym__s_dir_rsv_bgn] = ACTIONS(11), + [sym__s_drs_end] = ACTIONS(13), + [sym__s_doc_end] = ACTIONS(15), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__br_blk_lit_bgn] = ACTIONS(31), + [sym__br_blk_fld_bgn] = ACTIONS(31), + [sym__br_flw_seq_bgn] = ACTIONS(35), + [sym__br_flw_map_bgn] = ACTIONS(39), + [sym__br_dqt_str_bgn] = ACTIONS(43), + [sym__br_sqt_str_bgn] = ACTIONS(47), + [sym__br_sgl_pln_nul_blk] = ACTIONS(51), + [sym__br_sgl_pln_bol_blk] = ACTIONS(51), + [sym__br_sgl_pln_int_blk] = ACTIONS(51), + [sym__br_sgl_pln_flt_blk] = ACTIONS(51), + [sym__br_sgl_pln_tms_blk] = ACTIONS(51), + [sym__br_sgl_pln_str_blk] = ACTIONS(51), + [sym__br_mtl_pln_str_blk] = ACTIONS(55), + [sym__br_tag] = ACTIONS(59), + [sym__br_acr_bgn] = ACTIONS(63), + [sym__br_als_bgn] = ACTIONS(67), + [sym_comment] = ACTIONS(3), + }, + [STATE(39)] = { + [sym__doc_w_bgn_w_end_seq] = STATE(1489), + [sym__doc_w_bgn_wo_end_seq] = STATE(1489), + [sym__doc_wo_bgn_w_end_seq] = STATE(1489), + [sym__doc_wo_bgn_wo_end_seq] = STATE(1489), + [sym__doc_w_bgn_w_end] = STATE(38), + [sym__doc_w_bgn_wo_end] = STATE(476), + [sym__doc_wo_bgn_w_end] = STATE(39), + [sym__doc_wo_bgn_wo_end] = STATE(480), + [sym__drs_doc] = STATE(1167), + [sym__exp_doc] = STATE(1155), + [sym__imp_doc] = STATE(1168), + [sym__drs_doc_end] = STATE(39), + [sym__exp_doc_end] = STATE(38), + [sym__imp_doc_end] = STATE(39), + [sym__doc_end] = STATE(38), + [sym__s_dir] = STATE(478), + [sym__s_dir_yml] = STATE(478), + [sym__s_dir_tag] = STATE(478), + [sym__s_dir_rsv] = STATE(478), + [sym__br_prp_val] = STATE(1169), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_prp] = STATE(80), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq_val] = STATE(1169), + [sym__br_blk_seq] = STATE(1170), + [sym__br_blk_seq_itm] = STATE(1048), + [sym__br_blk_map_val] = STATE(1169), + [sym__br_blk_map] = STATE(1200), + [sym__br_blk_map_itm] = STATE(130), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__br_blk_str_val] = STATE(1169), + [sym__br_blk_str] = STATE(1103), + [sym__br_flw_seq_val] = STATE(1169), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__br_flw_seq] = STATE(1156), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_flw_map_val] = STATE(1169), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__br_flw_map] = STATE(1071), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_dqt_str_val] = STATE(1169), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__br_dqt_str] = STATE(1087), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sqt_str_val] = STATE(1169), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__br_sqt_str] = STATE(1129), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_pln_blk_val] = STATE(1169), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__br_sgl_pln_blk] = STATE(997), + [sym__br_mtl_pln_blk] = STATE(1095), + [sym__br_als_val] = STATE(939), + [sym__br_als] = STATE(1001), + [sym__br_acr] = STATE(146), + [aux_sym__drs_doc_repeat1] = STATE(478), + [sym__eof] = ACTIONS(383), + [sym__s_dir_yml_bgn] = ACTIONS(7), + [sym__s_dir_tag_bgn] = ACTIONS(9), + [sym__s_dir_rsv_bgn] = ACTIONS(11), + [sym__s_drs_end] = ACTIONS(13), + [sym__s_doc_end] = ACTIONS(15), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__br_blk_lit_bgn] = ACTIONS(31), + [sym__br_blk_fld_bgn] = ACTIONS(31), + [sym__br_flw_seq_bgn] = ACTIONS(35), + [sym__br_flw_map_bgn] = ACTIONS(39), + [sym__br_dqt_str_bgn] = ACTIONS(43), + [sym__br_sqt_str_bgn] = ACTIONS(47), + [sym__br_sgl_pln_nul_blk] = ACTIONS(51), + [sym__br_sgl_pln_bol_blk] = ACTIONS(51), + [sym__br_sgl_pln_int_blk] = ACTIONS(51), + [sym__br_sgl_pln_flt_blk] = ACTIONS(51), + [sym__br_sgl_pln_tms_blk] = ACTIONS(51), + [sym__br_sgl_pln_str_blk] = ACTIONS(51), + [sym__br_mtl_pln_str_blk] = ACTIONS(55), + [sym__br_tag] = ACTIONS(59), + [sym__br_acr_bgn] = ACTIONS(63), + [sym__br_als_bgn] = ACTIONS(67), + [sym_comment] = ACTIONS(3), + }, + [STATE(40)] = { + [sym__r_prp_val] = STATE(981), + [sym__br_prp_val] = STATE(984), + [sym__r_sgl_prp_val] = STATE(1239), + [sym__r_prp] = STATE(162), + [sym__br_prp] = STATE(164), + [sym__r_sgl_prp] = STATE(365), + [sym__r_flw_seq_val] = STATE(1031), + [sym__br_flw_seq_val] = STATE(1035), + [sym__r_sgl_flw_seq_val] = STATE(1242), + [sym__r_flw_seq] = STATE(1282), + [sym__br_flw_seq] = STATE(1283), + [sym__r_sgl_flw_seq] = STATE(1506), + [sym__r_flw_map_val] = STATE(1031), + [sym__br_flw_map_val] = STATE(1035), + [sym__r_sgl_flw_map_val] = STATE(1242), + [sym__r_flw_map] = STATE(1302), + [sym__br_flw_map] = STATE(1304), + [sym__r_sgl_flw_map] = STATE(1534), + [sym__r_flw_imp_r_par] = STATE(924), + [sym__r_flw_imp_br_par] = STATE(925), + [sym__br_flw_imp_r_par] = STATE(926), + [sym__br_flw_imp_br_par] = STATE(927), + [sym__r_sgl_flw_imp_par] = STATE(1312), + [sym__r_dqt_str_val] = STATE(1031), + [sym__br_dqt_str_val] = STATE(1035), + [sym__r_sgl_dqt_str_val] = STATE(1242), + [sym__r_dqt_str] = STATE(1306), + [sym__br_dqt_str] = STATE(1307), + [sym__r_sgl_dqt_str] = STATE(1463), + [sym__r_sqt_str_val] = STATE(1031), + [sym__br_sqt_str_val] = STATE(1035), + [sym__r_sgl_sqt_str_val] = STATE(1242), + [sym__r_sqt_str] = STATE(1309), + [sym__br_sqt_str] = STATE(1310), + [sym__r_sgl_sqt_str] = STATE(1467), + [sym__r_pln_flw_val] = STATE(981), + [sym__br_pln_flw_val] = STATE(984), + [sym__r_sgl_pln_flw_val] = STATE(1239), + [sym__r_sgl_pln_flw] = STATE(1243), + [sym__br_sgl_pln_flw] = STATE(1345), + [sym__r_mtl_pln_flw] = STATE(1222), + [sym__br_mtl_pln_flw] = STATE(1345), + [sym__r_als_val] = STATE(928), + [sym__br_als_val] = STATE(984), + [sym__r_als] = STATE(1246), + [sym__br_als] = STATE(1272), + [sym__r_acr] = STATE(244), + [sym__br_acr] = STATE(248), + [sym__r_flw_seq_bgn] = ACTIONS(385), + [sym__br_flw_seq_bgn] = ACTIONS(387), + [sym__r_flw_map_bgn] = ACTIONS(389), + [sym__br_flw_map_bgn] = ACTIONS(391), + [sym__r_flw_map_end] = ACTIONS(393), + [sym__br_flw_map_end] = ACTIONS(396), + [sym__b_flw_map_end] = ACTIONS(396), + [sym__r_flw_sep_bgn] = ACTIONS(393), + [sym__br_flw_sep_bgn] = ACTIONS(396), + [sym__r_dqt_str_bgn] = ACTIONS(398), + [sym__br_dqt_str_bgn] = ACTIONS(400), + [sym__r_sqt_str_bgn] = ACTIONS(402), + [sym__br_sqt_str_bgn] = ACTIONS(404), + [sym__r_sgl_pln_nul_flw] = ACTIONS(406), + [sym__br_sgl_pln_nul_flw] = ACTIONS(408), + [sym__r_sgl_pln_bol_flw] = ACTIONS(406), + [sym__br_sgl_pln_bol_flw] = ACTIONS(408), + [sym__r_sgl_pln_int_flw] = ACTIONS(406), + [sym__br_sgl_pln_int_flw] = ACTIONS(408), + [sym__r_sgl_pln_flt_flw] = ACTIONS(406), + [sym__br_sgl_pln_flt_flw] = ACTIONS(408), + [sym__r_sgl_pln_tms_flw] = ACTIONS(406), + [sym__br_sgl_pln_tms_flw] = ACTIONS(408), + [sym__r_sgl_pln_str_flw] = ACTIONS(406), + [sym__br_sgl_pln_str_flw] = ACTIONS(408), + [sym__r_mtl_pln_str_flw] = ACTIONS(410), + [sym__br_mtl_pln_str_flw] = ACTIONS(412), + [sym__r_tag] = ACTIONS(414), + [sym__br_tag] = ACTIONS(416), + [sym__r_acr_bgn] = ACTIONS(418), + [sym__br_acr_bgn] = ACTIONS(420), + [sym__r_als_bgn] = ACTIONS(422), + [sym__br_als_bgn] = ACTIONS(424), + [sym_comment] = ACTIONS(3), + }, + [STATE(41)] = { + [sym__r_prp_val] = STATE(980), + [sym__br_prp_val] = STATE(991), + [sym__r_sgl_prp_val] = STATE(1359), + [sym__r_prp] = STATE(162), + [sym__br_prp] = STATE(164), + [sym__r_sgl_prp] = STATE(365), + [sym__r_flw_seq_val] = STATE(1009), + [sym__br_flw_seq_val] = STATE(1018), + [sym__r_sgl_flw_seq_val] = STATE(1244), + [sym__r_flw_seq] = STATE(1282), + [sym__br_flw_seq] = STATE(1283), + [sym__r_sgl_flw_seq] = STATE(1506), + [sym__r_flw_map_val] = STATE(1009), + [sym__br_flw_map_val] = STATE(1018), + [sym__r_sgl_flw_map_val] = STATE(1244), + [sym__r_flw_map] = STATE(1302), + [sym__br_flw_map] = STATE(1304), + [sym__r_sgl_flw_map] = STATE(1534), + [sym__r_flw_imp_r_par] = STATE(948), + [sym__r_flw_imp_br_par] = STATE(953), + [sym__br_flw_imp_r_par] = STATE(960), + [sym__br_flw_imp_br_par] = STATE(804), + [sym__r_sgl_flw_imp_par] = STATE(1292), + [sym__r_dqt_str_val] = STATE(1009), + [sym__br_dqt_str_val] = STATE(1018), + [sym__r_sgl_dqt_str_val] = STATE(1244), + [sym__r_dqt_str] = STATE(1306), + [sym__br_dqt_str] = STATE(1307), + [sym__r_sgl_dqt_str] = STATE(1463), + [sym__r_sqt_str_val] = STATE(1009), + [sym__br_sqt_str_val] = STATE(1018), + [sym__r_sgl_sqt_str_val] = STATE(1244), + [sym__r_sqt_str] = STATE(1309), + [sym__br_sqt_str] = STATE(1310), + [sym__r_sgl_sqt_str] = STATE(1467), + [sym__r_pln_flw_val] = STATE(980), + [sym__br_pln_flw_val] = STATE(991), + [sym__r_sgl_pln_flw_val] = STATE(1359), + [sym__r_sgl_pln_flw] = STATE(1243), + [sym__br_sgl_pln_flw] = STATE(1345), + [sym__r_mtl_pln_flw] = STATE(1222), + [sym__br_mtl_pln_flw] = STATE(1345), + [sym__r_als_val] = STATE(805), + [sym__br_als_val] = STATE(991), + [sym__r_als] = STATE(1246), + [sym__br_als] = STATE(1272), + [sym__r_acr] = STATE(244), + [sym__br_acr] = STATE(248), + [sym__r_flw_seq_bgn] = ACTIONS(385), + [sym__br_flw_seq_bgn] = ACTIONS(387), + [sym__r_flw_seq_end] = ACTIONS(393), + [sym__br_flw_seq_end] = ACTIONS(396), + [sym__b_flw_seq_end] = ACTIONS(396), + [sym__r_flw_map_bgn] = ACTIONS(389), + [sym__br_flw_map_bgn] = ACTIONS(391), + [sym__r_flw_sep_bgn] = ACTIONS(393), + [sym__br_flw_sep_bgn] = ACTIONS(396), + [sym__r_dqt_str_bgn] = ACTIONS(398), + [sym__br_dqt_str_bgn] = ACTIONS(400), + [sym__r_sqt_str_bgn] = ACTIONS(402), + [sym__br_sqt_str_bgn] = ACTIONS(404), + [sym__r_sgl_pln_nul_flw] = ACTIONS(406), + [sym__br_sgl_pln_nul_flw] = ACTIONS(408), + [sym__r_sgl_pln_bol_flw] = ACTIONS(406), + [sym__br_sgl_pln_bol_flw] = ACTIONS(408), + [sym__r_sgl_pln_int_flw] = ACTIONS(406), + [sym__br_sgl_pln_int_flw] = ACTIONS(408), + [sym__r_sgl_pln_flt_flw] = ACTIONS(406), + [sym__br_sgl_pln_flt_flw] = ACTIONS(408), + [sym__r_sgl_pln_tms_flw] = ACTIONS(406), + [sym__br_sgl_pln_tms_flw] = ACTIONS(408), + [sym__r_sgl_pln_str_flw] = ACTIONS(406), + [sym__br_sgl_pln_str_flw] = ACTIONS(408), + [sym__r_mtl_pln_str_flw] = ACTIONS(410), + [sym__br_mtl_pln_str_flw] = ACTIONS(412), + [sym__r_tag] = ACTIONS(414), + [sym__br_tag] = ACTIONS(416), + [sym__r_acr_bgn] = ACTIONS(418), + [sym__br_acr_bgn] = ACTIONS(420), + [sym__r_als_bgn] = ACTIONS(422), + [sym__br_als_bgn] = ACTIONS(424), + [sym_comment] = ACTIONS(3), + }, + [STATE(42)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(571), + [sym__r_flw_map_dat] = STATE(1173), + [sym__br_flw_map_dat] = STATE(1173), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(430), + [sym__br_flw_map_end] = ACTIONS(430), + [sym__b_flw_map_end] = ACTIONS(430), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(43)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(715), + [sym__r_flw_map_dat] = STATE(1166), + [sym__br_flw_map_dat] = STATE(1166), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(277), + [sym__br_flw_map_end] = ACTIONS(277), + [sym__b_flw_map_end] = ACTIONS(277), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(44)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(879), + [sym__r_flw_map_dat] = STATE(1212), + [sym__br_flw_map_dat] = STATE(1212), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(285), + [sym__br_flw_map_end] = ACTIONS(285), + [sym__b_flw_map_end] = ACTIONS(285), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(45)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(1133), + [sym__r_flw_map_dat] = STATE(1138), + [sym__br_flw_map_dat] = STATE(1138), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(215), + [sym__br_flw_map_end] = ACTIONS(215), + [sym__b_flw_map_end] = ACTIONS(215), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(46)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(570), + [sym__r_flw_map_dat] = STATE(1173), + [sym__br_flw_map_dat] = STATE(1173), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(269), + [sym__br_flw_map_end] = ACTIONS(269), + [sym__b_flw_map_end] = ACTIONS(269), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(47)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(1323), + [sym__r_flw_map_dat] = STATE(1183), + [sym__br_flw_map_dat] = STATE(1183), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(442), + [sym__br_flw_map_end] = ACTIONS(442), + [sym__b_flw_map_end] = ACTIONS(442), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(48)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(832), + [sym__r_flw_map_dat] = STATE(1194), + [sym__br_flw_map_dat] = STATE(1194), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(444), + [sym__br_flw_map_end] = ACTIONS(444), + [sym__b_flw_map_end] = ACTIONS(444), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(49)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(369), + [sym__r_flw_map_dat] = STATE(1152), + [sym__br_flw_map_dat] = STATE(1152), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(265), + [sym__br_flw_map_end] = ACTIONS(265), + [sym__b_flw_map_end] = ACTIONS(265), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(50)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(880), + [sym__r_flw_map_dat] = STATE(1212), + [sym__br_flw_map_dat] = STATE(1212), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(446), + [sym__br_flw_map_end] = ACTIONS(446), + [sym__b_flw_map_end] = ACTIONS(446), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(51)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(1321), + [sym__r_flw_map_dat] = STATE(1183), + [sym__br_flw_map_dat] = STATE(1183), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(273), + [sym__br_flw_map_end] = ACTIONS(273), + [sym__b_flw_map_end] = ACTIONS(273), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(52)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(1258), + [sym__r_flw_map_dat] = STATE(1125), + [sym__br_flw_map_dat] = STATE(1125), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(257), + [sym__br_flw_map_end] = ACTIONS(257), + [sym__b_flw_map_end] = ACTIONS(257), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(53)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(716), + [sym__r_flw_map_dat] = STATE(1166), + [sym__br_flw_map_dat] = STATE(1166), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(448), + [sym__br_flw_map_end] = ACTIONS(448), + [sym__b_flw_map_end] = ACTIONS(448), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(54)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(831), + [sym__r_flw_map_dat] = STATE(1194), + [sym__br_flw_map_dat] = STATE(1194), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(281), + [sym__br_flw_map_end] = ACTIONS(281), + [sym__b_flw_map_end] = ACTIONS(281), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(55)] = { + [sym__r_prp_val] = STATE(810), + [sym__br_prp_val] = STATE(810), + [sym__r_sgl_prp_val] = STATE(1379), + [sym__r_prp] = STATE(121), + [sym__br_prp] = STATE(117), + [sym__r_sgl_prp] = STATE(274), + [sym__r_flw_seq_val] = STATE(810), + [sym__br_flw_seq_val] = STATE(810), + [sym__r_sgl_flw_seq_val] = STATE(1379), + [sym__r_flw_seq] = STATE(817), + [sym__br_flw_seq] = STATE(818), + [sym__r_sgl_flw_seq] = STATE(1219), + [sym__r_flw_map_val] = STATE(810), + [sym__br_flw_map_val] = STATE(810), + [sym__r_sgl_flw_map_val] = STATE(1379), + [sym__r_flw_map] = STATE(819), + [sym__br_flw_map] = STATE(820), + [sym__r_sgl_flw_map] = STATE(1223), + [sym__flw_ann_par_tal] = STATE(810), + [sym__sgl_flw_ann_par_tal] = STATE(1379), + [sym__r_dqt_str_val] = STATE(810), + [sym__br_dqt_str_val] = STATE(810), + [sym__r_sgl_dqt_str_val] = STATE(1379), + [sym__r_dqt_str] = STATE(821), + [sym__br_dqt_str] = STATE(822), + [sym__r_sgl_dqt_str] = STATE(1224), + [sym__r_sqt_str_val] = STATE(810), + [sym__br_sqt_str_val] = STATE(810), + [sym__r_sgl_sqt_str_val] = STATE(1379), + [sym__r_sqt_str] = STATE(823), + [sym__br_sqt_str] = STATE(824), + [sym__r_sgl_sqt_str] = STATE(1228), + [sym__r_pln_flw_val] = STATE(810), + [sym__br_pln_flw_val] = STATE(810), + [sym__r_sgl_pln_flw_val] = STATE(1379), + [sym__r_sgl_pln_flw] = STATE(785), + [sym__br_sgl_pln_flw] = STATE(786), + [sym__r_mtl_pln_flw] = STATE(792), + [sym__br_mtl_pln_flw] = STATE(786), + [sym__r_als_val] = STATE(919), + [sym__br_als_val] = STATE(810), + [sym__r_als] = STATE(873), + [sym__br_als] = STATE(874), + [sym__r_acr] = STATE(215), + [sym__br_acr] = STATE(224), + [sym__r_flw_seq_bgn] = ACTIONS(450), + [sym__br_flw_seq_bgn] = ACTIONS(452), + [sym__r_flw_seq_end] = ACTIONS(454), + [sym__br_flw_seq_end] = ACTIONS(457), + [sym__b_flw_seq_end] = ACTIONS(457), + [sym__r_flw_map_bgn] = ACTIONS(459), + [sym__br_flw_map_bgn] = ACTIONS(461), + [sym__r_flw_sep_bgn] = ACTIONS(454), + [sym__br_flw_sep_bgn] = ACTIONS(457), + [sym__r_dqt_str_bgn] = ACTIONS(463), + [sym__br_dqt_str_bgn] = ACTIONS(465), + [sym__r_sqt_str_bgn] = ACTIONS(467), + [sym__br_sqt_str_bgn] = ACTIONS(469), + [sym__r_sgl_pln_nul_flw] = ACTIONS(471), + [sym__br_sgl_pln_nul_flw] = ACTIONS(473), + [sym__r_sgl_pln_bol_flw] = ACTIONS(471), + [sym__br_sgl_pln_bol_flw] = ACTIONS(473), + [sym__r_sgl_pln_int_flw] = ACTIONS(471), + [sym__br_sgl_pln_int_flw] = ACTIONS(473), + [sym__r_sgl_pln_flt_flw] = ACTIONS(471), + [sym__br_sgl_pln_flt_flw] = ACTIONS(473), + [sym__r_sgl_pln_tms_flw] = ACTIONS(471), + [sym__br_sgl_pln_tms_flw] = ACTIONS(473), + [sym__r_sgl_pln_str_flw] = ACTIONS(471), + [sym__br_sgl_pln_str_flw] = ACTIONS(473), + [sym__r_mtl_pln_str_flw] = ACTIONS(475), + [sym__br_mtl_pln_str_flw] = ACTIONS(477), + [sym__r_tag] = ACTIONS(479), + [sym__br_tag] = ACTIONS(481), + [sym__r_acr_bgn] = ACTIONS(483), + [sym__br_acr_bgn] = ACTIONS(485), + [sym__r_als_bgn] = ACTIONS(487), + [sym__br_als_bgn] = ACTIONS(489), + [sym_comment] = ACTIONS(3), + }, + [STATE(56)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(784), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1211), + [sym__br_flw_seq_dat] = STATE(1211), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(367), + [sym__br_flw_seq_end] = ACTIONS(367), + [sym__b_flw_seq_end] = ACTIONS(367), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(57)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(1131), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1058), + [sym__br_flw_seq_dat] = STATE(1058), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(359), + [sym__br_flw_seq_end] = ACTIONS(359), + [sym__b_flw_seq_end] = ACTIONS(359), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(58)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(1318), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1182), + [sym__br_flw_seq_dat] = STATE(1182), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(505), + [sym__br_flw_seq_end] = ACTIONS(505), + [sym__b_flw_seq_end] = ACTIONS(505), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(59)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(712), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1165), + [sym__br_flw_seq_dat] = STATE(1165), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(353), + [sym__br_flw_seq_end] = ACTIONS(353), + [sym__b_flw_seq_end] = ACTIONS(353), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(60)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(568), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1172), + [sym__br_flw_seq_dat] = STATE(1172), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(507), + [sym__br_flw_seq_end] = ACTIONS(507), + [sym__b_flw_seq_end] = ACTIONS(507), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(61)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(566), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1172), + [sym__br_flw_seq_dat] = STATE(1172), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(293), + [sym__br_flw_seq_end] = ACTIONS(293), + [sym__b_flw_seq_end] = ACTIONS(293), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(62)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(1247), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1124), + [sym__br_flw_seq_dat] = STATE(1124), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(347), + [sym__br_flw_seq_end] = ACTIONS(347), + [sym__b_flw_seq_end] = ACTIONS(347), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(63)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(829), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1193), + [sym__br_flw_seq_dat] = STATE(1193), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(509), + [sym__br_flw_seq_end] = ACTIONS(509), + [sym__b_flw_seq_end] = ACTIONS(509), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(64)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(713), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1165), + [sym__br_flw_seq_dat] = STATE(1165), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(511), + [sym__br_flw_seq_end] = ACTIONS(511), + [sym__b_flw_seq_end] = ACTIONS(511), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(65)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(366), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1151), + [sym__br_flw_seq_dat] = STATE(1151), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(339), + [sym__br_flw_seq_end] = ACTIONS(339), + [sym__b_flw_seq_end] = ACTIONS(339), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(66)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(877), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1211), + [sym__br_flw_seq_dat] = STATE(1211), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(513), + [sym__br_flw_seq_end] = ACTIONS(513), + [sym__b_flw_seq_end] = ACTIONS(513), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(67)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(1316), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1182), + [sym__br_flw_seq_dat] = STATE(1182), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(363), + [sym__br_flw_seq_end] = ACTIONS(363), + [sym__b_flw_seq_end] = ACTIONS(363), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(68)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(828), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1193), + [sym__br_flw_seq_dat] = STATE(1193), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(357), + [sym__br_flw_seq_end] = ACTIONS(357), + [sym__b_flw_seq_end] = ACTIONS(357), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(69)] = { + [sym__r_prp_val] = STATE(934), + [sym__br_prp_val] = STATE(934), + [sym__r_sgl_prp_val] = STATE(1319), + [sym__r_prp] = STATE(119), + [sym__br_prp] = STATE(120), + [sym__r_sgl_prp] = STATE(276), + [sym__r_flw_seq_val] = STATE(934), + [sym__br_flw_seq_val] = STATE(934), + [sym__r_sgl_flw_seq_val] = STATE(1319), + [sym__r_flw_seq] = STATE(865), + [sym__br_flw_seq] = STATE(866), + [sym__r_sgl_flw_seq] = STATE(1301), + [sym__r_flw_map_val] = STATE(934), + [sym__br_flw_map_val] = STATE(934), + [sym__r_sgl_flw_map_val] = STATE(1319), + [sym__r_flw_map] = STATE(867), + [sym__br_flw_map] = STATE(868), + [sym__r_sgl_flw_map] = STATE(1305), + [sym__flw_ann_par_tal] = STATE(934), + [sym__sgl_flw_ann_par_tal] = STATE(1319), + [sym__r_dqt_str_val] = STATE(934), + [sym__br_dqt_str_val] = STATE(934), + [sym__r_sgl_dqt_str_val] = STATE(1319), + [sym__r_dqt_str] = STATE(869), + [sym__br_dqt_str] = STATE(870), + [sym__r_sgl_dqt_str] = STATE(1308), + [sym__r_sqt_str_val] = STATE(934), + [sym__br_sqt_str_val] = STATE(934), + [sym__r_sgl_sqt_str_val] = STATE(1319), + [sym__r_sqt_str] = STATE(871), + [sym__br_sqt_str] = STATE(872), + [sym__r_sgl_sqt_str] = STATE(1311), + [sym__r_pln_flw_val] = STATE(934), + [sym__br_pln_flw_val] = STATE(934), + [sym__r_sgl_pln_flw_val] = STATE(1319), + [sym__r_sgl_pln_flw] = STATE(801), + [sym__br_sgl_pln_flw] = STATE(802), + [sym__r_mtl_pln_flw] = STATE(803), + [sym__br_mtl_pln_flw] = STATE(802), + [sym__r_als_val] = STATE(935), + [sym__br_als_val] = STATE(934), + [sym__r_als] = STATE(913), + [sym__br_als] = STATE(914), + [sym__r_acr] = STATE(220), + [sym__br_acr] = STATE(218), + [sym__r_flw_seq_bgn] = ACTIONS(515), + [sym__br_flw_seq_bgn] = ACTIONS(517), + [sym__r_flw_map_bgn] = ACTIONS(519), + [sym__br_flw_map_bgn] = ACTIONS(521), + [sym__r_flw_map_end] = ACTIONS(454), + [sym__br_flw_map_end] = ACTIONS(457), + [sym__b_flw_map_end] = ACTIONS(457), + [sym__r_flw_sep_bgn] = ACTIONS(454), + [sym__br_flw_sep_bgn] = ACTIONS(457), + [sym__r_dqt_str_bgn] = ACTIONS(523), + [sym__br_dqt_str_bgn] = ACTIONS(525), + [sym__r_sqt_str_bgn] = ACTIONS(527), + [sym__br_sqt_str_bgn] = ACTIONS(529), + [sym__r_sgl_pln_nul_flw] = ACTIONS(531), + [sym__br_sgl_pln_nul_flw] = ACTIONS(533), + [sym__r_sgl_pln_bol_flw] = ACTIONS(531), + [sym__br_sgl_pln_bol_flw] = ACTIONS(533), + [sym__r_sgl_pln_int_flw] = ACTIONS(531), + [sym__br_sgl_pln_int_flw] = ACTIONS(533), + [sym__r_sgl_pln_flt_flw] = ACTIONS(531), + [sym__br_sgl_pln_flt_flw] = ACTIONS(533), + [sym__r_sgl_pln_tms_flw] = ACTIONS(531), + [sym__br_sgl_pln_tms_flw] = ACTIONS(533), + [sym__r_sgl_pln_str_flw] = ACTIONS(531), + [sym__br_sgl_pln_str_flw] = ACTIONS(533), + [sym__r_mtl_pln_str_flw] = ACTIONS(535), + [sym__br_mtl_pln_str_flw] = ACTIONS(537), + [sym__r_tag] = ACTIONS(539), + [sym__br_tag] = ACTIONS(541), + [sym__r_acr_bgn] = ACTIONS(543), + [sym__br_acr_bgn] = ACTIONS(545), + [sym__r_als_bgn] = ACTIONS(547), + [sym__br_als_bgn] = ACTIONS(549), + [sym_comment] = ACTIONS(3), + }, + [STATE(70)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_flw_map_itm] = STATE(875), + [sym__br_flw_map_itm] = STATE(875), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(551), + [sym__br_flw_map_end] = ACTIONS(551), + [sym__b_flw_map_end] = ACTIONS(551), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(71)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_flw_map_itm] = STATE(875), + [sym__br_flw_map_itm] = STATE(875), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(553), + [sym__br_flw_map_end] = ACTIONS(553), + [sym__b_flw_map_end] = ACTIONS(553), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(72)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_flw_map_itm] = STATE(875), + [sym__br_flw_map_itm] = STATE(875), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(555), + [sym__br_flw_map_end] = ACTIONS(555), + [sym__b_flw_map_end] = ACTIONS(555), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(73)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_flw_map_itm] = STATE(875), + [sym__br_flw_map_itm] = STATE(875), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(557), + [sym__br_flw_map_end] = ACTIONS(557), + [sym__b_flw_map_end] = ACTIONS(557), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(74)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_itm] = STATE(825), + [sym__br_flw_seq_itm] = STATE(825), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(559), + [sym__br_flw_seq_end] = ACTIONS(559), + [sym__b_flw_seq_end] = ACTIONS(559), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(75)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_itm] = STATE(825), + [sym__br_flw_seq_itm] = STATE(825), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(561), + [sym__br_flw_seq_end] = ACTIONS(561), + [sym__b_flw_seq_end] = ACTIONS(561), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(76)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_itm] = STATE(825), + [sym__br_flw_seq_itm] = STATE(825), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(563), + [sym__br_flw_seq_end] = ACTIONS(563), + [sym__b_flw_seq_end] = ACTIONS(563), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(77)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_itm] = STATE(825), + [sym__br_flw_seq_itm] = STATE(825), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(565), + [sym__br_flw_seq_end] = ACTIONS(565), + [sym__b_flw_seq_end] = ACTIONS(565), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(78)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_flw_map_itm] = STATE(875), + [sym__br_flw_map_itm] = STATE(875), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(79)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_itm] = STATE(825), + [sym__br_flw_seq_itm] = STATE(825), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(80)] = { + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq] = STATE(1201), + [sym__br_blk_seq_itm] = STATE(1048), + [sym__br_blk_map] = STATE(1202), + [sym__br_blk_map_itm] = STATE(130), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str] = STATE(1203), + [sym__br_blk_str] = STATE(1203), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1204), + [sym__br_flw_seq] = STATE(1204), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1205), + [sym__br_flw_map] = STATE(1205), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1206), + [sym__br_dqt_str] = STATE(1206), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1207), + [sym__br_sqt_str] = STATE(1207), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1208), + [sym__br_sgl_pln_blk] = STATE(1040), + [sym__r_mtl_pln_blk] = STATE(1208), + [sym__br_mtl_pln_blk] = STATE(1208), + [sym__br_als_val] = STATE(1237), + [sym__br_als] = STATE(1487), + [sym__br_acr] = STATE(415), + [sym__eof] = ACTIONS(369), + [sym__s_drs_end] = ACTIONS(369), + [sym__s_doc_end] = ACTIONS(369), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(29), + [sym__br_blk_lit_bgn] = ACTIONS(31), + [sym__r_blk_fld_bgn] = ACTIONS(29), + [sym__br_blk_fld_bgn] = ACTIONS(31), + [sym__r_flw_seq_bgn] = ACTIONS(189), + [sym__br_flw_seq_bgn] = ACTIONS(35), + [sym__r_flw_map_bgn] = ACTIONS(191), + [sym__br_flw_map_bgn] = ACTIONS(39), + [sym__r_dqt_str_bgn] = ACTIONS(193), + [sym__br_dqt_str_bgn] = ACTIONS(43), + [sym__r_sqt_str_bgn] = ACTIONS(195), + [sym__br_sqt_str_bgn] = ACTIONS(47), + [sym__r_sgl_pln_nul_blk] = ACTIONS(197), + [sym__br_sgl_pln_nul_blk] = ACTIONS(51), + [sym__r_sgl_pln_bol_blk] = ACTIONS(197), + [sym__br_sgl_pln_bol_blk] = ACTIONS(51), + [sym__r_sgl_pln_int_blk] = ACTIONS(197), + [sym__br_sgl_pln_int_blk] = ACTIONS(51), + [sym__r_sgl_pln_flt_blk] = ACTIONS(197), + [sym__br_sgl_pln_flt_blk] = ACTIONS(51), + [sym__r_sgl_pln_tms_blk] = ACTIONS(197), + [sym__br_sgl_pln_tms_blk] = ACTIONS(51), + [sym__r_sgl_pln_str_blk] = ACTIONS(197), + [sym__br_sgl_pln_str_blk] = ACTIONS(51), + [sym__r_mtl_pln_str_blk] = ACTIONS(53), + [sym__br_mtl_pln_str_blk] = ACTIONS(55), + [sym__br_tag] = ACTIONS(371), + [sym__br_acr_bgn] = ACTIONS(373), + [sym__br_als_bgn] = ACTIONS(375), + [sym_comment] = ACTIONS(3), + }, + [STATE(81)] = { + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq] = STATE(1177), + [sym__br_blk_seq_itm] = STATE(1048), + [sym__br_blk_map] = STATE(1185), + [sym__br_blk_map_itm] = STATE(130), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str] = STATE(1186), + [sym__br_blk_str] = STATE(1186), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1188), + [sym__br_flw_seq] = STATE(1188), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1191), + [sym__br_flw_map] = STATE(1191), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1192), + [sym__br_dqt_str] = STATE(1192), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1197), + [sym__br_sqt_str] = STATE(1197), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1199), + [sym__br_sgl_pln_blk] = STATE(1037), + [sym__r_mtl_pln_blk] = STATE(1199), + [sym__br_mtl_pln_blk] = STATE(1199), + [sym__br_als_val] = STATE(1237), + [sym__br_als] = STATE(1487), + [sym__br_acr] = STATE(415), + [sym__eof] = ACTIONS(377), + [sym__s_drs_end] = ACTIONS(377), + [sym__s_doc_end] = ACTIONS(377), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(29), + [sym__br_blk_lit_bgn] = ACTIONS(31), + [sym__r_blk_fld_bgn] = ACTIONS(29), + [sym__br_blk_fld_bgn] = ACTIONS(31), + [sym__r_flw_seq_bgn] = ACTIONS(189), + [sym__br_flw_seq_bgn] = ACTIONS(35), + [sym__r_flw_map_bgn] = ACTIONS(191), + [sym__br_flw_map_bgn] = ACTIONS(39), + [sym__r_dqt_str_bgn] = ACTIONS(193), + [sym__br_dqt_str_bgn] = ACTIONS(43), + [sym__r_sqt_str_bgn] = ACTIONS(195), + [sym__br_sqt_str_bgn] = ACTIONS(47), + [sym__r_sgl_pln_nul_blk] = ACTIONS(197), + [sym__br_sgl_pln_nul_blk] = ACTIONS(51), + [sym__r_sgl_pln_bol_blk] = ACTIONS(197), + [sym__br_sgl_pln_bol_blk] = ACTIONS(51), + [sym__r_sgl_pln_int_blk] = ACTIONS(197), + [sym__br_sgl_pln_int_blk] = ACTIONS(51), + [sym__r_sgl_pln_flt_blk] = ACTIONS(197), + [sym__br_sgl_pln_flt_blk] = ACTIONS(51), + [sym__r_sgl_pln_tms_blk] = ACTIONS(197), + [sym__br_sgl_pln_tms_blk] = ACTIONS(51), + [sym__r_sgl_pln_str_blk] = ACTIONS(197), + [sym__br_sgl_pln_str_blk] = ACTIONS(51), + [sym__r_mtl_pln_str_blk] = ACTIONS(53), + [sym__br_mtl_pln_str_blk] = ACTIONS(55), + [sym__br_tag] = ACTIONS(371), + [sym__br_acr_bgn] = ACTIONS(373), + [sym__br_als_bgn] = ACTIONS(375), + [sym_comment] = ACTIONS(3), + }, + [STATE(82)] = { + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq] = STATE(1273), + [sym__br_blk_seq_itm] = STATE(1003), + [sym__br_blk_map] = STATE(1274), + [sym__br_blk_map_itm] = STATE(135), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str] = STATE(1275), + [sym__br_blk_str] = STATE(1275), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1276), + [sym__br_flw_seq] = STATE(1276), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1277), + [sym__br_flw_map] = STATE(1277), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1278), + [sym__br_dqt_str] = STATE(1278), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1279), + [sym__br_sqt_str] = STATE(1279), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1280), + [sym__br_sgl_pln_blk] = STATE(1159), + [sym__r_mtl_pln_blk] = STATE(1280), + [sym__br_mtl_pln_blk] = STATE(1280), + [sym__br_als_val] = STATE(1237), + [sym__br_als] = STATE(1487), + [sym__br_acr] = STATE(415), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(377), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(125), + [sym__br_blk_lit_bgn] = ACTIONS(127), + [sym__r_blk_fld_bgn] = ACTIONS(125), + [sym__br_blk_fld_bgn] = ACTIONS(127), + [sym__r_flw_seq_bgn] = ACTIONS(567), + [sym__br_flw_seq_bgn] = ACTIONS(131), + [sym__r_flw_map_bgn] = ACTIONS(569), + [sym__br_flw_map_bgn] = ACTIONS(135), + [sym__r_dqt_str_bgn] = ACTIONS(571), + [sym__br_dqt_str_bgn] = ACTIONS(139), + [sym__r_sqt_str_bgn] = ACTIONS(573), + [sym__br_sqt_str_bgn] = ACTIONS(143), + [sym__r_sgl_pln_nul_blk] = ACTIONS(575), + [sym__br_sgl_pln_nul_blk] = ACTIONS(147), + [sym__r_sgl_pln_bol_blk] = ACTIONS(575), + [sym__br_sgl_pln_bol_blk] = ACTIONS(147), + [sym__r_sgl_pln_int_blk] = ACTIONS(575), + [sym__br_sgl_pln_int_blk] = ACTIONS(147), + [sym__r_sgl_pln_flt_blk] = ACTIONS(575), + [sym__br_sgl_pln_flt_blk] = ACTIONS(147), + [sym__r_sgl_pln_tms_blk] = ACTIONS(575), + [sym__br_sgl_pln_tms_blk] = ACTIONS(147), + [sym__r_sgl_pln_str_blk] = ACTIONS(575), + [sym__br_sgl_pln_str_blk] = ACTIONS(147), + [sym__r_mtl_pln_str_blk] = ACTIONS(149), + [sym__br_mtl_pln_str_blk] = ACTIONS(151), + [sym__br_tag] = ACTIONS(371), + [sym__br_acr_bgn] = ACTIONS(373), + [sym__br_als_bgn] = ACTIONS(375), + [sym__bl] = ACTIONS(377), + [sym_comment] = ACTIONS(3), + }, + [STATE(83)] = { + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq] = STATE(1284), + [sym__br_blk_seq_itm] = STATE(1003), + [sym__br_blk_map] = STATE(1285), + [sym__br_blk_map_itm] = STATE(135), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str] = STATE(1286), + [sym__br_blk_str] = STATE(1286), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1287), + [sym__br_flw_seq] = STATE(1287), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1288), + [sym__br_flw_map] = STATE(1288), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1289), + [sym__br_dqt_str] = STATE(1289), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1290), + [sym__br_sqt_str] = STATE(1290), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1291), + [sym__br_sgl_pln_blk] = STATE(1160), + [sym__r_mtl_pln_blk] = STATE(1291), + [sym__br_mtl_pln_blk] = STATE(1291), + [sym__br_als_val] = STATE(1237), + [sym__br_als] = STATE(1487), + [sym__br_acr] = STATE(415), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(369), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(125), + [sym__br_blk_lit_bgn] = ACTIONS(127), + [sym__r_blk_fld_bgn] = ACTIONS(125), + [sym__br_blk_fld_bgn] = ACTIONS(127), + [sym__r_flw_seq_bgn] = ACTIONS(567), + [sym__br_flw_seq_bgn] = ACTIONS(131), + [sym__r_flw_map_bgn] = ACTIONS(569), + [sym__br_flw_map_bgn] = ACTIONS(135), + [sym__r_dqt_str_bgn] = ACTIONS(571), + [sym__br_dqt_str_bgn] = ACTIONS(139), + [sym__r_sqt_str_bgn] = ACTIONS(573), + [sym__br_sqt_str_bgn] = ACTIONS(143), + [sym__r_sgl_pln_nul_blk] = ACTIONS(575), + [sym__br_sgl_pln_nul_blk] = ACTIONS(147), + [sym__r_sgl_pln_bol_blk] = ACTIONS(575), + [sym__br_sgl_pln_bol_blk] = ACTIONS(147), + [sym__r_sgl_pln_int_blk] = ACTIONS(575), + [sym__br_sgl_pln_int_blk] = ACTIONS(147), + [sym__r_sgl_pln_flt_blk] = ACTIONS(575), + [sym__br_sgl_pln_flt_blk] = ACTIONS(147), + [sym__r_sgl_pln_tms_blk] = ACTIONS(575), + [sym__br_sgl_pln_tms_blk] = ACTIONS(147), + [sym__r_sgl_pln_str_blk] = ACTIONS(575), + [sym__br_sgl_pln_str_blk] = ACTIONS(147), + [sym__r_mtl_pln_str_blk] = ACTIONS(149), + [sym__br_mtl_pln_str_blk] = ACTIONS(151), + [sym__br_tag] = ACTIONS(371), + [sym__br_acr_bgn] = ACTIONS(373), + [sym__br_als_bgn] = ACTIONS(375), + [sym__bl] = ACTIONS(369), + [sym_comment] = ACTIONS(3), + }, + [STATE(84)] = { + [sym__r_prp_val] = STATE(981), + [sym__br_prp_val] = STATE(984), + [sym__r_prp] = STATE(162), + [sym__br_prp] = STATE(164), + [sym__r_flw_seq_val] = STATE(1031), + [sym__br_flw_seq_val] = STATE(1035), + [sym__r_flw_seq] = STATE(1282), + [sym__br_flw_seq] = STATE(1283), + [sym__r_flw_map_val] = STATE(1031), + [sym__br_flw_map_val] = STATE(1035), + [sym__r_flw_map] = STATE(1302), + [sym__br_flw_map] = STATE(1304), + [sym__r_flw_imp_r_par] = STATE(929), + [sym__r_flw_imp_br_par] = STATE(931), + [sym__br_flw_imp_r_par] = STATE(932), + [sym__br_flw_imp_br_par] = STATE(933), + [sym__r_dqt_str_val] = STATE(1031), + [sym__br_dqt_str_val] = STATE(1035), + [sym__r_dqt_str] = STATE(1306), + [sym__br_dqt_str] = STATE(1307), + [sym__r_sqt_str_val] = STATE(1031), + [sym__br_sqt_str_val] = STATE(1035), + [sym__r_sqt_str] = STATE(1309), + [sym__br_sqt_str] = STATE(1310), + [sym__r_pln_flw_val] = STATE(981), + [sym__br_pln_flw_val] = STATE(984), + [sym__r_sgl_pln_flw] = STATE(1222), + [sym__br_sgl_pln_flw] = STATE(1345), + [sym__r_mtl_pln_flw] = STATE(1222), + [sym__br_mtl_pln_flw] = STATE(1345), + [sym__r_als_val] = STATE(981), + [sym__br_als_val] = STATE(984), + [sym__r_als] = STATE(1246), + [sym__br_als] = STATE(1272), + [sym__r_acr] = STATE(245), + [sym__br_acr] = STATE(248), + [sym__r_flw_seq_bgn] = ACTIONS(577), + [sym__br_flw_seq_bgn] = ACTIONS(387), + [sym__r_flw_map_bgn] = ACTIONS(579), + [sym__br_flw_map_bgn] = ACTIONS(391), + [sym__r_flw_map_end] = ACTIONS(581), + [sym__br_flw_map_end] = ACTIONS(581), + [sym__b_flw_map_end] = ACTIONS(581), + [sym__r_flw_sep_bgn] = ACTIONS(581), + [sym__br_flw_sep_bgn] = ACTIONS(581), + [sym__r_dqt_str_bgn] = ACTIONS(583), + [sym__br_dqt_str_bgn] = ACTIONS(400), + [sym__r_sqt_str_bgn] = ACTIONS(585), + [sym__br_sqt_str_bgn] = ACTIONS(404), + [sym__r_sgl_pln_nul_flw] = ACTIONS(406), + [sym__br_sgl_pln_nul_flw] = ACTIONS(408), + [sym__r_sgl_pln_bol_flw] = ACTIONS(406), + [sym__br_sgl_pln_bol_flw] = ACTIONS(408), + [sym__r_sgl_pln_int_flw] = ACTIONS(406), + [sym__br_sgl_pln_int_flw] = ACTIONS(408), + [sym__r_sgl_pln_flt_flw] = ACTIONS(406), + [sym__br_sgl_pln_flt_flw] = ACTIONS(408), + [sym__r_sgl_pln_tms_flw] = ACTIONS(406), + [sym__br_sgl_pln_tms_flw] = ACTIONS(408), + [sym__r_sgl_pln_str_flw] = ACTIONS(406), + [sym__br_sgl_pln_str_flw] = ACTIONS(408), + [sym__r_mtl_pln_str_flw] = ACTIONS(410), + [sym__br_mtl_pln_str_flw] = ACTIONS(412), + [sym__r_tag] = ACTIONS(587), + [sym__br_tag] = ACTIONS(416), + [sym__r_acr_bgn] = ACTIONS(418), + [sym__br_acr_bgn] = ACTIONS(420), + [sym__r_als_bgn] = ACTIONS(422), + [sym__br_als_bgn] = ACTIONS(424), + [sym_comment] = ACTIONS(3), + }, + [STATE(85)] = { + [sym__r_prp_val] = STATE(980), + [sym__br_prp_val] = STATE(991), + [sym__r_prp] = STATE(162), + [sym__br_prp] = STATE(164), + [sym__r_flw_seq_val] = STATE(1009), + [sym__br_flw_seq_val] = STATE(1018), + [sym__r_flw_seq] = STATE(1282), + [sym__br_flw_seq] = STATE(1283), + [sym__r_flw_map_val] = STATE(1009), + [sym__br_flw_map_val] = STATE(1018), + [sym__r_flw_map] = STATE(1302), + [sym__br_flw_map] = STATE(1304), + [sym__r_flw_imp_r_par] = STATE(948), + [sym__r_flw_imp_br_par] = STATE(953), + [sym__br_flw_imp_r_par] = STATE(960), + [sym__br_flw_imp_br_par] = STATE(804), + [sym__r_dqt_str_val] = STATE(1009), + [sym__br_dqt_str_val] = STATE(1018), + [sym__r_dqt_str] = STATE(1306), + [sym__br_dqt_str] = STATE(1307), + [sym__r_sqt_str_val] = STATE(1009), + [sym__br_sqt_str_val] = STATE(1018), + [sym__r_sqt_str] = STATE(1309), + [sym__br_sqt_str] = STATE(1310), + [sym__r_pln_flw_val] = STATE(980), + [sym__br_pln_flw_val] = STATE(991), + [sym__r_sgl_pln_flw] = STATE(1222), + [sym__br_sgl_pln_flw] = STATE(1345), + [sym__r_mtl_pln_flw] = STATE(1222), + [sym__br_mtl_pln_flw] = STATE(1345), + [sym__r_als_val] = STATE(980), + [sym__br_als_val] = STATE(991), + [sym__r_als] = STATE(1246), + [sym__br_als] = STATE(1272), + [sym__r_acr] = STATE(245), + [sym__br_acr] = STATE(248), + [sym__r_flw_seq_bgn] = ACTIONS(577), + [sym__br_flw_seq_bgn] = ACTIONS(387), + [sym__r_flw_seq_end] = ACTIONS(396), + [sym__br_flw_seq_end] = ACTIONS(396), + [sym__b_flw_seq_end] = ACTIONS(396), + [sym__r_flw_map_bgn] = ACTIONS(579), + [sym__br_flw_map_bgn] = ACTIONS(391), + [sym__r_flw_sep_bgn] = ACTIONS(396), + [sym__br_flw_sep_bgn] = ACTIONS(396), + [sym__r_dqt_str_bgn] = ACTIONS(583), + [sym__br_dqt_str_bgn] = ACTIONS(400), + [sym__r_sqt_str_bgn] = ACTIONS(585), + [sym__br_sqt_str_bgn] = ACTIONS(404), + [sym__r_sgl_pln_nul_flw] = ACTIONS(406), + [sym__br_sgl_pln_nul_flw] = ACTIONS(408), + [sym__r_sgl_pln_bol_flw] = ACTIONS(406), + [sym__br_sgl_pln_bol_flw] = ACTIONS(408), + [sym__r_sgl_pln_int_flw] = ACTIONS(406), + [sym__br_sgl_pln_int_flw] = ACTIONS(408), + [sym__r_sgl_pln_flt_flw] = ACTIONS(406), + [sym__br_sgl_pln_flt_flw] = ACTIONS(408), + [sym__r_sgl_pln_tms_flw] = ACTIONS(406), + [sym__br_sgl_pln_tms_flw] = ACTIONS(408), + [sym__r_sgl_pln_str_flw] = ACTIONS(406), + [sym__br_sgl_pln_str_flw] = ACTIONS(408), + [sym__r_mtl_pln_str_flw] = ACTIONS(410), + [sym__br_mtl_pln_str_flw] = ACTIONS(412), + [sym__r_tag] = ACTIONS(587), + [sym__br_tag] = ACTIONS(416), + [sym__r_acr_bgn] = ACTIONS(418), + [sym__br_acr_bgn] = ACTIONS(420), + [sym__r_als_bgn] = ACTIONS(422), + [sym__br_als_bgn] = ACTIONS(424), + [sym_comment] = ACTIONS(3), + }, + [STATE(86)] = { + [sym__r_prp_val] = STATE(980), + [sym__br_prp_val] = STATE(991), + [sym__r_prp] = STATE(162), + [sym__br_prp] = STATE(164), + [sym__r_flw_seq_val] = STATE(1009), + [sym__br_flw_seq_val] = STATE(1018), + [sym__r_flw_seq] = STATE(1282), + [sym__br_flw_seq] = STATE(1283), + [sym__r_flw_map_val] = STATE(1009), + [sym__br_flw_map_val] = STATE(1018), + [sym__r_flw_map] = STATE(1302), + [sym__br_flw_map] = STATE(1304), + [sym__r_flw_imp_r_par] = STATE(806), + [sym__r_flw_imp_br_par] = STATE(807), + [sym__br_flw_imp_r_par] = STATE(808), + [sym__br_flw_imp_br_par] = STATE(809), + [sym__r_dqt_str_val] = STATE(1009), + [sym__br_dqt_str_val] = STATE(1018), + [sym__r_dqt_str] = STATE(1306), + [sym__br_dqt_str] = STATE(1307), + [sym__r_sqt_str_val] = STATE(1009), + [sym__br_sqt_str_val] = STATE(1018), + [sym__r_sqt_str] = STATE(1309), + [sym__br_sqt_str] = STATE(1310), + [sym__r_pln_flw_val] = STATE(980), + [sym__br_pln_flw_val] = STATE(991), + [sym__r_sgl_pln_flw] = STATE(1222), + [sym__br_sgl_pln_flw] = STATE(1345), + [sym__r_mtl_pln_flw] = STATE(1222), + [sym__br_mtl_pln_flw] = STATE(1345), + [sym__r_als_val] = STATE(980), + [sym__br_als_val] = STATE(991), + [sym__r_als] = STATE(1246), + [sym__br_als] = STATE(1272), + [sym__r_acr] = STATE(245), + [sym__br_acr] = STATE(248), + [sym__r_flw_seq_bgn] = ACTIONS(577), + [sym__br_flw_seq_bgn] = ACTIONS(387), + [sym__r_flw_seq_end] = ACTIONS(581), + [sym__br_flw_seq_end] = ACTIONS(581), + [sym__b_flw_seq_end] = ACTIONS(581), + [sym__r_flw_map_bgn] = ACTIONS(579), + [sym__br_flw_map_bgn] = ACTIONS(391), + [sym__r_flw_sep_bgn] = ACTIONS(581), + [sym__br_flw_sep_bgn] = ACTIONS(581), + [sym__r_dqt_str_bgn] = ACTIONS(583), + [sym__br_dqt_str_bgn] = ACTIONS(400), + [sym__r_sqt_str_bgn] = ACTIONS(585), + [sym__br_sqt_str_bgn] = ACTIONS(404), + [sym__r_sgl_pln_nul_flw] = ACTIONS(406), + [sym__br_sgl_pln_nul_flw] = ACTIONS(408), + [sym__r_sgl_pln_bol_flw] = ACTIONS(406), + [sym__br_sgl_pln_bol_flw] = ACTIONS(408), + [sym__r_sgl_pln_int_flw] = ACTIONS(406), + [sym__br_sgl_pln_int_flw] = ACTIONS(408), + [sym__r_sgl_pln_flt_flw] = ACTIONS(406), + [sym__br_sgl_pln_flt_flw] = ACTIONS(408), + [sym__r_sgl_pln_tms_flw] = ACTIONS(406), + [sym__br_sgl_pln_tms_flw] = ACTIONS(408), + [sym__r_sgl_pln_str_flw] = ACTIONS(406), + [sym__br_sgl_pln_str_flw] = ACTIONS(408), + [sym__r_mtl_pln_str_flw] = ACTIONS(410), + [sym__br_mtl_pln_str_flw] = ACTIONS(412), + [sym__r_tag] = ACTIONS(587), + [sym__br_tag] = ACTIONS(416), + [sym__r_acr_bgn] = ACTIONS(418), + [sym__br_acr_bgn] = ACTIONS(420), + [sym__r_als_bgn] = ACTIONS(422), + [sym__br_als_bgn] = ACTIONS(424), + [sym_comment] = ACTIONS(3), + }, + [STATE(87)] = { + [sym__r_prp_val] = STATE(981), + [sym__br_prp_val] = STATE(984), + [sym__r_prp] = STATE(162), + [sym__br_prp] = STATE(164), + [sym__r_flw_seq_val] = STATE(1031), + [sym__br_flw_seq_val] = STATE(1035), + [sym__r_flw_seq] = STATE(1282), + [sym__br_flw_seq] = STATE(1283), + [sym__r_flw_map_val] = STATE(1031), + [sym__br_flw_map_val] = STATE(1035), + [sym__r_flw_map] = STATE(1302), + [sym__br_flw_map] = STATE(1304), + [sym__r_flw_imp_r_par] = STATE(924), + [sym__r_flw_imp_br_par] = STATE(925), + [sym__br_flw_imp_r_par] = STATE(926), + [sym__br_flw_imp_br_par] = STATE(927), + [sym__r_dqt_str_val] = STATE(1031), + [sym__br_dqt_str_val] = STATE(1035), + [sym__r_dqt_str] = STATE(1306), + [sym__br_dqt_str] = STATE(1307), + [sym__r_sqt_str_val] = STATE(1031), + [sym__br_sqt_str_val] = STATE(1035), + [sym__r_sqt_str] = STATE(1309), + [sym__br_sqt_str] = STATE(1310), + [sym__r_pln_flw_val] = STATE(981), + [sym__br_pln_flw_val] = STATE(984), + [sym__r_sgl_pln_flw] = STATE(1222), + [sym__br_sgl_pln_flw] = STATE(1345), + [sym__r_mtl_pln_flw] = STATE(1222), + [sym__br_mtl_pln_flw] = STATE(1345), + [sym__r_als_val] = STATE(981), + [sym__br_als_val] = STATE(984), + [sym__r_als] = STATE(1246), + [sym__br_als] = STATE(1272), + [sym__r_acr] = STATE(245), + [sym__br_acr] = STATE(248), + [sym__r_flw_seq_bgn] = ACTIONS(577), + [sym__br_flw_seq_bgn] = ACTIONS(387), + [sym__r_flw_map_bgn] = ACTIONS(579), + [sym__br_flw_map_bgn] = ACTIONS(391), + [sym__r_flw_map_end] = ACTIONS(396), + [sym__br_flw_map_end] = ACTIONS(396), + [sym__b_flw_map_end] = ACTIONS(396), + [sym__r_flw_sep_bgn] = ACTIONS(396), + [sym__br_flw_sep_bgn] = ACTIONS(396), + [sym__r_dqt_str_bgn] = ACTIONS(583), + [sym__br_dqt_str_bgn] = ACTIONS(400), + [sym__r_sqt_str_bgn] = ACTIONS(585), + [sym__br_sqt_str_bgn] = ACTIONS(404), + [sym__r_sgl_pln_nul_flw] = ACTIONS(406), + [sym__br_sgl_pln_nul_flw] = ACTIONS(408), + [sym__r_sgl_pln_bol_flw] = ACTIONS(406), + [sym__br_sgl_pln_bol_flw] = ACTIONS(408), + [sym__r_sgl_pln_int_flw] = ACTIONS(406), + [sym__br_sgl_pln_int_flw] = ACTIONS(408), + [sym__r_sgl_pln_flt_flw] = ACTIONS(406), + [sym__br_sgl_pln_flt_flw] = ACTIONS(408), + [sym__r_sgl_pln_tms_flw] = ACTIONS(406), + [sym__br_sgl_pln_tms_flw] = ACTIONS(408), + [sym__r_sgl_pln_str_flw] = ACTIONS(406), + [sym__br_sgl_pln_str_flw] = ACTIONS(408), + [sym__r_mtl_pln_str_flw] = ACTIONS(410), + [sym__br_mtl_pln_str_flw] = ACTIONS(412), + [sym__r_tag] = ACTIONS(587), + [sym__br_tag] = ACTIONS(416), + [sym__r_acr_bgn] = ACTIONS(418), + [sym__br_acr_bgn] = ACTIONS(420), + [sym__r_als_bgn] = ACTIONS(422), + [sym__br_als_bgn] = ACTIONS(424), + [sym_comment] = ACTIONS(3), + }, + [STATE(88)] = { + [sym__r_prp_val] = STATE(934), + [sym__br_prp_val] = STATE(934), + [sym__r_prp] = STATE(119), + [sym__br_prp] = STATE(120), + [sym__r_flw_seq_val] = STATE(934), + [sym__br_flw_seq_val] = STATE(934), + [sym__r_flw_seq] = STATE(865), + [sym__br_flw_seq] = STATE(866), + [sym__r_flw_map_val] = STATE(934), + [sym__br_flw_map_val] = STATE(934), + [sym__r_flw_map] = STATE(867), + [sym__br_flw_map] = STATE(868), + [sym__flw_ann_par_tal] = STATE(934), + [sym__r_dqt_str_val] = STATE(934), + [sym__br_dqt_str_val] = STATE(934), + [sym__r_dqt_str] = STATE(869), + [sym__br_dqt_str] = STATE(870), + [sym__r_sqt_str_val] = STATE(934), + [sym__br_sqt_str_val] = STATE(934), + [sym__r_sqt_str] = STATE(871), + [sym__br_sqt_str] = STATE(872), + [sym__r_pln_flw_val] = STATE(934), + [sym__br_pln_flw_val] = STATE(934), + [sym__r_sgl_pln_flw] = STATE(803), + [sym__br_sgl_pln_flw] = STATE(802), + [sym__r_mtl_pln_flw] = STATE(803), + [sym__br_mtl_pln_flw] = STATE(802), + [sym__r_als_val] = STATE(934), + [sym__br_als_val] = STATE(934), + [sym__r_als] = STATE(913), + [sym__br_als] = STATE(914), + [sym__r_acr] = STATE(213), + [sym__br_acr] = STATE(218), + [sym__r_flw_seq_bgn] = ACTIONS(589), + [sym__br_flw_seq_bgn] = ACTIONS(517), + [sym__r_flw_map_bgn] = ACTIONS(591), + [sym__br_flw_map_bgn] = ACTIONS(521), + [sym__r_flw_map_end] = ACTIONS(457), + [sym__br_flw_map_end] = ACTIONS(457), + [sym__b_flw_map_end] = ACTIONS(457), + [sym__r_flw_sep_bgn] = ACTIONS(457), + [sym__br_flw_sep_bgn] = ACTIONS(457), + [sym__r_dqt_str_bgn] = ACTIONS(593), + [sym__br_dqt_str_bgn] = ACTIONS(525), + [sym__r_sqt_str_bgn] = ACTIONS(595), + [sym__br_sqt_str_bgn] = ACTIONS(529), + [sym__r_sgl_pln_nul_flw] = ACTIONS(531), + [sym__br_sgl_pln_nul_flw] = ACTIONS(533), + [sym__r_sgl_pln_bol_flw] = ACTIONS(531), + [sym__br_sgl_pln_bol_flw] = ACTIONS(533), + [sym__r_sgl_pln_int_flw] = ACTIONS(531), + [sym__br_sgl_pln_int_flw] = ACTIONS(533), + [sym__r_sgl_pln_flt_flw] = ACTIONS(531), + [sym__br_sgl_pln_flt_flw] = ACTIONS(533), + [sym__r_sgl_pln_tms_flw] = ACTIONS(531), + [sym__br_sgl_pln_tms_flw] = ACTIONS(533), + [sym__r_sgl_pln_str_flw] = ACTIONS(531), + [sym__br_sgl_pln_str_flw] = ACTIONS(533), + [sym__r_mtl_pln_str_flw] = ACTIONS(535), + [sym__br_mtl_pln_str_flw] = ACTIONS(537), + [sym__r_tag] = ACTIONS(597), + [sym__br_tag] = ACTIONS(541), + [sym__r_acr_bgn] = ACTIONS(543), + [sym__br_acr_bgn] = ACTIONS(545), + [sym__r_als_bgn] = ACTIONS(547), + [sym__br_als_bgn] = ACTIONS(549), + [sym_comment] = ACTIONS(3), + }, + [STATE(89)] = { + [sym__r_prp_val] = STATE(951), + [sym__br_prp_val] = STATE(951), + [sym__r_prp] = STATE(119), + [sym__br_prp] = STATE(120), + [sym__r_flw_seq_val] = STATE(951), + [sym__br_flw_seq_val] = STATE(951), + [sym__r_flw_seq] = STATE(865), + [sym__br_flw_seq] = STATE(866), + [sym__r_flw_map_val] = STATE(951), + [sym__br_flw_map_val] = STATE(951), + [sym__r_flw_map] = STATE(867), + [sym__br_flw_map] = STATE(868), + [sym__flw_ann_par_tal] = STATE(951), + [sym__r_dqt_str_val] = STATE(951), + [sym__br_dqt_str_val] = STATE(951), + [sym__r_dqt_str] = STATE(869), + [sym__br_dqt_str] = STATE(870), + [sym__r_sqt_str_val] = STATE(951), + [sym__br_sqt_str_val] = STATE(951), + [sym__r_sqt_str] = STATE(871), + [sym__br_sqt_str] = STATE(872), + [sym__r_pln_flw_val] = STATE(951), + [sym__br_pln_flw_val] = STATE(951), + [sym__r_sgl_pln_flw] = STATE(803), + [sym__br_sgl_pln_flw] = STATE(802), + [sym__r_mtl_pln_flw] = STATE(803), + [sym__br_mtl_pln_flw] = STATE(802), + [sym__r_als_val] = STATE(951), + [sym__br_als_val] = STATE(951), + [sym__r_als] = STATE(913), + [sym__br_als] = STATE(914), + [sym__r_acr] = STATE(213), + [sym__br_acr] = STATE(218), + [sym__r_flw_seq_bgn] = ACTIONS(589), + [sym__br_flw_seq_bgn] = ACTIONS(517), + [sym__r_flw_map_bgn] = ACTIONS(591), + [sym__br_flw_map_bgn] = ACTIONS(521), + [sym__r_flw_map_end] = ACTIONS(599), + [sym__br_flw_map_end] = ACTIONS(599), + [sym__b_flw_map_end] = ACTIONS(599), + [sym__r_flw_sep_bgn] = ACTIONS(599), + [sym__br_flw_sep_bgn] = ACTIONS(599), + [sym__r_dqt_str_bgn] = ACTIONS(593), + [sym__br_dqt_str_bgn] = ACTIONS(525), + [sym__r_sqt_str_bgn] = ACTIONS(595), + [sym__br_sqt_str_bgn] = ACTIONS(529), + [sym__r_sgl_pln_nul_flw] = ACTIONS(531), + [sym__br_sgl_pln_nul_flw] = ACTIONS(533), + [sym__r_sgl_pln_bol_flw] = ACTIONS(531), + [sym__br_sgl_pln_bol_flw] = ACTIONS(533), + [sym__r_sgl_pln_int_flw] = ACTIONS(531), + [sym__br_sgl_pln_int_flw] = ACTIONS(533), + [sym__r_sgl_pln_flt_flw] = ACTIONS(531), + [sym__br_sgl_pln_flt_flw] = ACTIONS(533), + [sym__r_sgl_pln_tms_flw] = ACTIONS(531), + [sym__br_sgl_pln_tms_flw] = ACTIONS(533), + [sym__r_sgl_pln_str_flw] = ACTIONS(531), + [sym__br_sgl_pln_str_flw] = ACTIONS(533), + [sym__r_mtl_pln_str_flw] = ACTIONS(535), + [sym__br_mtl_pln_str_flw] = ACTIONS(537), + [sym__r_tag] = ACTIONS(597), + [sym__br_tag] = ACTIONS(541), + [sym__r_acr_bgn] = ACTIONS(543), + [sym__br_acr_bgn] = ACTIONS(545), + [sym__r_als_bgn] = ACTIONS(547), + [sym__br_als_bgn] = ACTIONS(549), + [sym_comment] = ACTIONS(3), + }, + [STATE(90)] = { + [sym__r_prp_val] = STATE(954), + [sym__br_prp_val] = STATE(954), + [sym__r_prp] = STATE(121), + [sym__br_prp] = STATE(117), + [sym__r_flw_seq_val] = STATE(954), + [sym__br_flw_seq_val] = STATE(954), + [sym__r_flw_seq] = STATE(817), + [sym__br_flw_seq] = STATE(818), + [sym__r_flw_map_val] = STATE(954), + [sym__br_flw_map_val] = STATE(954), + [sym__r_flw_map] = STATE(819), + [sym__br_flw_map] = STATE(820), + [sym__flw_ann_par_tal] = STATE(954), + [sym__r_dqt_str_val] = STATE(954), + [sym__br_dqt_str_val] = STATE(954), + [sym__r_dqt_str] = STATE(821), + [sym__br_dqt_str] = STATE(822), + [sym__r_sqt_str_val] = STATE(954), + [sym__br_sqt_str_val] = STATE(954), + [sym__r_sqt_str] = STATE(823), + [sym__br_sqt_str] = STATE(824), + [sym__r_pln_flw_val] = STATE(954), + [sym__br_pln_flw_val] = STATE(954), + [sym__r_sgl_pln_flw] = STATE(792), + [sym__br_sgl_pln_flw] = STATE(786), + [sym__r_mtl_pln_flw] = STATE(792), + [sym__br_mtl_pln_flw] = STATE(786), + [sym__r_als_val] = STATE(954), + [sym__br_als_val] = STATE(954), + [sym__r_als] = STATE(873), + [sym__br_als] = STATE(874), + [sym__r_acr] = STATE(214), + [sym__br_acr] = STATE(224), + [sym__r_flw_seq_bgn] = ACTIONS(601), + [sym__br_flw_seq_bgn] = ACTIONS(452), + [sym__r_flw_seq_end] = ACTIONS(603), + [sym__br_flw_seq_end] = ACTIONS(603), + [sym__b_flw_seq_end] = ACTIONS(603), + [sym__r_flw_map_bgn] = ACTIONS(605), + [sym__br_flw_map_bgn] = ACTIONS(461), + [sym__r_flw_sep_bgn] = ACTIONS(603), + [sym__br_flw_sep_bgn] = ACTIONS(603), + [sym__r_dqt_str_bgn] = ACTIONS(607), + [sym__br_dqt_str_bgn] = ACTIONS(465), + [sym__r_sqt_str_bgn] = ACTIONS(609), + [sym__br_sqt_str_bgn] = ACTIONS(469), + [sym__r_sgl_pln_nul_flw] = ACTIONS(471), + [sym__br_sgl_pln_nul_flw] = ACTIONS(473), + [sym__r_sgl_pln_bol_flw] = ACTIONS(471), + [sym__br_sgl_pln_bol_flw] = ACTIONS(473), + [sym__r_sgl_pln_int_flw] = ACTIONS(471), + [sym__br_sgl_pln_int_flw] = ACTIONS(473), + [sym__r_sgl_pln_flt_flw] = ACTIONS(471), + [sym__br_sgl_pln_flt_flw] = ACTIONS(473), + [sym__r_sgl_pln_tms_flw] = ACTIONS(471), + [sym__br_sgl_pln_tms_flw] = ACTIONS(473), + [sym__r_sgl_pln_str_flw] = ACTIONS(471), + [sym__br_sgl_pln_str_flw] = ACTIONS(473), + [sym__r_mtl_pln_str_flw] = ACTIONS(475), + [sym__br_mtl_pln_str_flw] = ACTIONS(477), + [sym__r_tag] = ACTIONS(611), + [sym__br_tag] = ACTIONS(481), + [sym__r_acr_bgn] = ACTIONS(483), + [sym__br_acr_bgn] = ACTIONS(485), + [sym__r_als_bgn] = ACTIONS(487), + [sym__br_als_bgn] = ACTIONS(489), + [sym_comment] = ACTIONS(3), + }, + [STATE(91)] = { + [sym__r_prp_val] = STATE(810), + [sym__br_prp_val] = STATE(810), + [sym__r_prp] = STATE(121), + [sym__br_prp] = STATE(117), + [sym__r_flw_seq_val] = STATE(810), + [sym__br_flw_seq_val] = STATE(810), + [sym__r_flw_seq] = STATE(817), + [sym__br_flw_seq] = STATE(818), + [sym__r_flw_map_val] = STATE(810), + [sym__br_flw_map_val] = STATE(810), + [sym__r_flw_map] = STATE(819), + [sym__br_flw_map] = STATE(820), + [sym__flw_ann_par_tal] = STATE(810), + [sym__r_dqt_str_val] = STATE(810), + [sym__br_dqt_str_val] = STATE(810), + [sym__r_dqt_str] = STATE(821), + [sym__br_dqt_str] = STATE(822), + [sym__r_sqt_str_val] = STATE(810), + [sym__br_sqt_str_val] = STATE(810), + [sym__r_sqt_str] = STATE(823), + [sym__br_sqt_str] = STATE(824), + [sym__r_pln_flw_val] = STATE(810), + [sym__br_pln_flw_val] = STATE(810), + [sym__r_sgl_pln_flw] = STATE(792), + [sym__br_sgl_pln_flw] = STATE(786), + [sym__r_mtl_pln_flw] = STATE(792), + [sym__br_mtl_pln_flw] = STATE(786), + [sym__r_als_val] = STATE(810), + [sym__br_als_val] = STATE(810), + [sym__r_als] = STATE(873), + [sym__br_als] = STATE(874), + [sym__r_acr] = STATE(214), + [sym__br_acr] = STATE(224), + [sym__r_flw_seq_bgn] = ACTIONS(601), + [sym__br_flw_seq_bgn] = ACTIONS(452), + [sym__r_flw_seq_end] = ACTIONS(457), + [sym__br_flw_seq_end] = ACTIONS(457), + [sym__b_flw_seq_end] = ACTIONS(457), + [sym__r_flw_map_bgn] = ACTIONS(605), + [sym__br_flw_map_bgn] = ACTIONS(461), + [sym__r_flw_sep_bgn] = ACTIONS(457), + [sym__br_flw_sep_bgn] = ACTIONS(457), + [sym__r_dqt_str_bgn] = ACTIONS(607), + [sym__br_dqt_str_bgn] = ACTIONS(465), + [sym__r_sqt_str_bgn] = ACTIONS(609), + [sym__br_sqt_str_bgn] = ACTIONS(469), + [sym__r_sgl_pln_nul_flw] = ACTIONS(471), + [sym__br_sgl_pln_nul_flw] = ACTIONS(473), + [sym__r_sgl_pln_bol_flw] = ACTIONS(471), + [sym__br_sgl_pln_bol_flw] = ACTIONS(473), + [sym__r_sgl_pln_int_flw] = ACTIONS(471), + [sym__br_sgl_pln_int_flw] = ACTIONS(473), + [sym__r_sgl_pln_flt_flw] = ACTIONS(471), + [sym__br_sgl_pln_flt_flw] = ACTIONS(473), + [sym__r_sgl_pln_tms_flw] = ACTIONS(471), + [sym__br_sgl_pln_tms_flw] = ACTIONS(473), + [sym__r_sgl_pln_str_flw] = ACTIONS(471), + [sym__br_sgl_pln_str_flw] = ACTIONS(473), + [sym__r_mtl_pln_str_flw] = ACTIONS(475), + [sym__br_mtl_pln_str_flw] = ACTIONS(477), + [sym__r_tag] = ACTIONS(611), + [sym__br_tag] = ACTIONS(481), + [sym__r_acr_bgn] = ACTIONS(483), + [sym__br_acr_bgn] = ACTIONS(485), + [sym__r_als_bgn] = ACTIONS(487), + [sym__br_als_bgn] = ACTIONS(489), + [sym_comment] = ACTIONS(3), + }, + [STATE(92)] = { + [sym__r_prp_val] = STATE(816), + [sym__br_prp_val] = STATE(816), + [sym__r_prp] = STATE(121), + [sym__br_prp] = STATE(117), + [sym__r_flw_seq_val] = STATE(816), + [sym__br_flw_seq_val] = STATE(816), + [sym__r_flw_seq] = STATE(817), + [sym__br_flw_seq] = STATE(818), + [sym__r_flw_map_val] = STATE(816), + [sym__br_flw_map_val] = STATE(816), + [sym__r_flw_map] = STATE(819), + [sym__br_flw_map] = STATE(820), + [sym__flw_ann_par_tal] = STATE(816), + [sym__r_dqt_str_val] = STATE(816), + [sym__br_dqt_str_val] = STATE(816), + [sym__r_dqt_str] = STATE(821), + [sym__br_dqt_str] = STATE(822), + [sym__r_sqt_str_val] = STATE(816), + [sym__br_sqt_str_val] = STATE(816), + [sym__r_sqt_str] = STATE(823), + [sym__br_sqt_str] = STATE(824), + [sym__r_pln_flw_val] = STATE(816), + [sym__br_pln_flw_val] = STATE(816), + [sym__r_sgl_pln_flw] = STATE(792), + [sym__br_sgl_pln_flw] = STATE(786), + [sym__r_mtl_pln_flw] = STATE(792), + [sym__br_mtl_pln_flw] = STATE(786), + [sym__r_als_val] = STATE(816), + [sym__br_als_val] = STATE(816), + [sym__r_als] = STATE(873), + [sym__br_als] = STATE(874), + [sym__r_acr] = STATE(214), + [sym__br_acr] = STATE(224), + [sym__r_flw_seq_bgn] = ACTIONS(601), + [sym__br_flw_seq_bgn] = ACTIONS(452), + [sym__r_flw_seq_end] = ACTIONS(599), + [sym__br_flw_seq_end] = ACTIONS(599), + [sym__b_flw_seq_end] = ACTIONS(599), + [sym__r_flw_map_bgn] = ACTIONS(605), + [sym__br_flw_map_bgn] = ACTIONS(461), + [sym__r_flw_sep_bgn] = ACTIONS(599), + [sym__br_flw_sep_bgn] = ACTIONS(599), + [sym__r_dqt_str_bgn] = ACTIONS(607), + [sym__br_dqt_str_bgn] = ACTIONS(465), + [sym__r_sqt_str_bgn] = ACTIONS(609), + [sym__br_sqt_str_bgn] = ACTIONS(469), + [sym__r_sgl_pln_nul_flw] = ACTIONS(471), + [sym__br_sgl_pln_nul_flw] = ACTIONS(473), + [sym__r_sgl_pln_bol_flw] = ACTIONS(471), + [sym__br_sgl_pln_bol_flw] = ACTIONS(473), + [sym__r_sgl_pln_int_flw] = ACTIONS(471), + [sym__br_sgl_pln_int_flw] = ACTIONS(473), + [sym__r_sgl_pln_flt_flw] = ACTIONS(471), + [sym__br_sgl_pln_flt_flw] = ACTIONS(473), + [sym__r_sgl_pln_tms_flw] = ACTIONS(471), + [sym__br_sgl_pln_tms_flw] = ACTIONS(473), + [sym__r_sgl_pln_str_flw] = ACTIONS(471), + [sym__br_sgl_pln_str_flw] = ACTIONS(473), + [sym__r_mtl_pln_str_flw] = ACTIONS(475), + [sym__br_mtl_pln_str_flw] = ACTIONS(477), + [sym__r_tag] = ACTIONS(611), + [sym__br_tag] = ACTIONS(481), + [sym__r_acr_bgn] = ACTIONS(483), + [sym__br_acr_bgn] = ACTIONS(485), + [sym__r_als_bgn] = ACTIONS(487), + [sym__br_als_bgn] = ACTIONS(489), + [sym_comment] = ACTIONS(3), + }, + [STATE(93)] = { + [sym__r_prp_val] = STATE(864), + [sym__br_prp_val] = STATE(864), + [sym__r_prp] = STATE(119), + [sym__br_prp] = STATE(120), + [sym__r_flw_seq_val] = STATE(864), + [sym__br_flw_seq_val] = STATE(864), + [sym__r_flw_seq] = STATE(865), + [sym__br_flw_seq] = STATE(866), + [sym__r_flw_map_val] = STATE(864), + [sym__br_flw_map_val] = STATE(864), + [sym__r_flw_map] = STATE(867), + [sym__br_flw_map] = STATE(868), + [sym__flw_ann_par_tal] = STATE(864), + [sym__r_dqt_str_val] = STATE(864), + [sym__br_dqt_str_val] = STATE(864), + [sym__r_dqt_str] = STATE(869), + [sym__br_dqt_str] = STATE(870), + [sym__r_sqt_str_val] = STATE(864), + [sym__br_sqt_str_val] = STATE(864), + [sym__r_sqt_str] = STATE(871), + [sym__br_sqt_str] = STATE(872), + [sym__r_pln_flw_val] = STATE(864), + [sym__br_pln_flw_val] = STATE(864), + [sym__r_sgl_pln_flw] = STATE(803), + [sym__br_sgl_pln_flw] = STATE(802), + [sym__r_mtl_pln_flw] = STATE(803), + [sym__br_mtl_pln_flw] = STATE(802), + [sym__r_als_val] = STATE(864), + [sym__br_als_val] = STATE(864), + [sym__r_als] = STATE(913), + [sym__br_als] = STATE(914), + [sym__r_acr] = STATE(213), + [sym__br_acr] = STATE(218), + [sym__r_flw_seq_bgn] = ACTIONS(589), + [sym__br_flw_seq_bgn] = ACTIONS(517), + [sym__r_flw_map_bgn] = ACTIONS(591), + [sym__br_flw_map_bgn] = ACTIONS(521), + [sym__r_flw_map_end] = ACTIONS(603), + [sym__br_flw_map_end] = ACTIONS(603), + [sym__b_flw_map_end] = ACTIONS(603), + [sym__r_flw_sep_bgn] = ACTIONS(603), + [sym__br_flw_sep_bgn] = ACTIONS(603), + [sym__r_dqt_str_bgn] = ACTIONS(593), + [sym__br_dqt_str_bgn] = ACTIONS(525), + [sym__r_sqt_str_bgn] = ACTIONS(595), + [sym__br_sqt_str_bgn] = ACTIONS(529), + [sym__r_sgl_pln_nul_flw] = ACTIONS(531), + [sym__br_sgl_pln_nul_flw] = ACTIONS(533), + [sym__r_sgl_pln_bol_flw] = ACTIONS(531), + [sym__br_sgl_pln_bol_flw] = ACTIONS(533), + [sym__r_sgl_pln_int_flw] = ACTIONS(531), + [sym__br_sgl_pln_int_flw] = ACTIONS(533), + [sym__r_sgl_pln_flt_flw] = ACTIONS(531), + [sym__br_sgl_pln_flt_flw] = ACTIONS(533), + [sym__r_sgl_pln_tms_flw] = ACTIONS(531), + [sym__br_sgl_pln_tms_flw] = ACTIONS(533), + [sym__r_sgl_pln_str_flw] = ACTIONS(531), + [sym__br_sgl_pln_str_flw] = ACTIONS(533), + [sym__r_mtl_pln_str_flw] = ACTIONS(535), + [sym__br_mtl_pln_str_flw] = ACTIONS(537), + [sym__r_tag] = ACTIONS(597), + [sym__br_tag] = ACTIONS(541), + [sym__r_acr_bgn] = ACTIONS(543), + [sym__br_acr_bgn] = ACTIONS(545), + [sym__r_als_bgn] = ACTIONS(547), + [sym__br_als_bgn] = ACTIONS(549), + [sym_comment] = ACTIONS(3), + }, + [STATE(94)] = { + [sym__r_prp_val] = STATE(936), + [sym__br_prp_val] = STATE(936), + [sym__r_prp] = STATE(119), + [sym__br_prp] = STATE(120), + [sym__r_flw_seq_val] = STATE(936), + [sym__br_flw_seq_val] = STATE(936), + [sym__r_flw_seq] = STATE(865), + [sym__br_flw_seq] = STATE(866), + [sym__r_flw_map_val] = STATE(936), + [sym__br_flw_map_val] = STATE(936), + [sym__r_flw_map] = STATE(867), + [sym__br_flw_map] = STATE(868), + [sym__flw_ann_par_tal] = STATE(936), + [sym__r_dqt_str_val] = STATE(936), + [sym__br_dqt_str_val] = STATE(936), + [sym__r_dqt_str] = STATE(869), + [sym__br_dqt_str] = STATE(870), + [sym__r_sqt_str_val] = STATE(936), + [sym__br_sqt_str_val] = STATE(936), + [sym__r_sqt_str] = STATE(871), + [sym__br_sqt_str] = STATE(872), + [sym__r_pln_flw_val] = STATE(936), + [sym__br_pln_flw_val] = STATE(936), + [sym__r_sgl_pln_flw] = STATE(803), + [sym__br_sgl_pln_flw] = STATE(802), + [sym__r_mtl_pln_flw] = STATE(803), + [sym__br_mtl_pln_flw] = STATE(802), + [sym__r_als_val] = STATE(936), + [sym__br_als_val] = STATE(936), + [sym__r_als] = STATE(913), + [sym__br_als] = STATE(914), + [sym__r_acr] = STATE(213), + [sym__br_acr] = STATE(218), + [sym__r_flw_seq_bgn] = ACTIONS(589), + [sym__br_flw_seq_bgn] = ACTIONS(517), + [sym__r_flw_map_bgn] = ACTIONS(591), + [sym__br_flw_map_bgn] = ACTIONS(521), + [sym__r_flw_map_end] = ACTIONS(613), + [sym__br_flw_map_end] = ACTIONS(613), + [sym__b_flw_map_end] = ACTIONS(613), + [sym__r_flw_sep_bgn] = ACTIONS(613), + [sym__br_flw_sep_bgn] = ACTIONS(613), + [sym__r_dqt_str_bgn] = ACTIONS(593), + [sym__br_dqt_str_bgn] = ACTIONS(525), + [sym__r_sqt_str_bgn] = ACTIONS(595), + [sym__br_sqt_str_bgn] = ACTIONS(529), + [sym__r_sgl_pln_nul_flw] = ACTIONS(531), + [sym__br_sgl_pln_nul_flw] = ACTIONS(533), + [sym__r_sgl_pln_bol_flw] = ACTIONS(531), + [sym__br_sgl_pln_bol_flw] = ACTIONS(533), + [sym__r_sgl_pln_int_flw] = ACTIONS(531), + [sym__br_sgl_pln_int_flw] = ACTIONS(533), + [sym__r_sgl_pln_flt_flw] = ACTIONS(531), + [sym__br_sgl_pln_flt_flw] = ACTIONS(533), + [sym__r_sgl_pln_tms_flw] = ACTIONS(531), + [sym__br_sgl_pln_tms_flw] = ACTIONS(533), + [sym__r_sgl_pln_str_flw] = ACTIONS(531), + [sym__br_sgl_pln_str_flw] = ACTIONS(533), + [sym__r_mtl_pln_str_flw] = ACTIONS(535), + [sym__br_mtl_pln_str_flw] = ACTIONS(537), + [sym__r_tag] = ACTIONS(597), + [sym__br_tag] = ACTIONS(541), + [sym__r_acr_bgn] = ACTIONS(543), + [sym__br_acr_bgn] = ACTIONS(545), + [sym__r_als_bgn] = ACTIONS(547), + [sym__br_als_bgn] = ACTIONS(549), + [sym_comment] = ACTIONS(3), + }, + [STATE(95)] = { + [sym__r_prp_val] = STATE(920), + [sym__br_prp_val] = STATE(920), + [sym__r_prp] = STATE(121), + [sym__br_prp] = STATE(117), + [sym__r_flw_seq_val] = STATE(920), + [sym__br_flw_seq_val] = STATE(920), + [sym__r_flw_seq] = STATE(817), + [sym__br_flw_seq] = STATE(818), + [sym__r_flw_map_val] = STATE(920), + [sym__br_flw_map_val] = STATE(920), + [sym__r_flw_map] = STATE(819), + [sym__br_flw_map] = STATE(820), + [sym__flw_ann_par_tal] = STATE(920), + [sym__r_dqt_str_val] = STATE(920), + [sym__br_dqt_str_val] = STATE(920), + [sym__r_dqt_str] = STATE(821), + [sym__br_dqt_str] = STATE(822), + [sym__r_sqt_str_val] = STATE(920), + [sym__br_sqt_str_val] = STATE(920), + [sym__r_sqt_str] = STATE(823), + [sym__br_sqt_str] = STATE(824), + [sym__r_pln_flw_val] = STATE(920), + [sym__br_pln_flw_val] = STATE(920), + [sym__r_sgl_pln_flw] = STATE(792), + [sym__br_sgl_pln_flw] = STATE(786), + [sym__r_mtl_pln_flw] = STATE(792), + [sym__br_mtl_pln_flw] = STATE(786), + [sym__r_als_val] = STATE(920), + [sym__br_als_val] = STATE(920), + [sym__r_als] = STATE(873), + [sym__br_als] = STATE(874), + [sym__r_acr] = STATE(214), + [sym__br_acr] = STATE(224), + [sym__r_flw_seq_bgn] = ACTIONS(601), + [sym__br_flw_seq_bgn] = ACTIONS(452), + [sym__r_flw_seq_end] = ACTIONS(613), + [sym__br_flw_seq_end] = ACTIONS(613), + [sym__b_flw_seq_end] = ACTIONS(613), + [sym__r_flw_map_bgn] = ACTIONS(605), + [sym__br_flw_map_bgn] = ACTIONS(461), + [sym__r_flw_sep_bgn] = ACTIONS(613), + [sym__br_flw_sep_bgn] = ACTIONS(613), + [sym__r_dqt_str_bgn] = ACTIONS(607), + [sym__br_dqt_str_bgn] = ACTIONS(465), + [sym__r_sqt_str_bgn] = ACTIONS(609), + [sym__br_sqt_str_bgn] = ACTIONS(469), + [sym__r_sgl_pln_nul_flw] = ACTIONS(471), + [sym__br_sgl_pln_nul_flw] = ACTIONS(473), + [sym__r_sgl_pln_bol_flw] = ACTIONS(471), + [sym__br_sgl_pln_bol_flw] = ACTIONS(473), + [sym__r_sgl_pln_int_flw] = ACTIONS(471), + [sym__br_sgl_pln_int_flw] = ACTIONS(473), + [sym__r_sgl_pln_flt_flw] = ACTIONS(471), + [sym__br_sgl_pln_flt_flw] = ACTIONS(473), + [sym__r_sgl_pln_tms_flw] = ACTIONS(471), + [sym__br_sgl_pln_tms_flw] = ACTIONS(473), + [sym__r_sgl_pln_str_flw] = ACTIONS(471), + [sym__br_sgl_pln_str_flw] = ACTIONS(473), + [sym__r_mtl_pln_str_flw] = ACTIONS(475), + [sym__br_mtl_pln_str_flw] = ACTIONS(477), + [sym__r_tag] = ACTIONS(611), + [sym__br_tag] = ACTIONS(481), + [sym__r_acr_bgn] = ACTIONS(483), + [sym__br_acr_bgn] = ACTIONS(485), + [sym__r_als_bgn] = ACTIONS(487), + [sym__br_als_bgn] = ACTIONS(489), + [sym_comment] = ACTIONS(3), + }, +}; + +static const uint16_t ts_small_parse_table[] = { + [0] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(617), 1, + sym__r_blk_imp_bgn, + ACTIONS(622), 1, + sym__r_acr_bgn, + ACTIONS(624), 1, + sym__br_acr_bgn, + STATE(103), 1, + sym__r_acr, + STATE(108), 1, + sym__br_acr, + ACTIONS(619), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(615), 38, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [71] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(622), 1, + sym__r_acr_bgn, + ACTIONS(629), 1, + sym__r_blk_imp_bgn, + ACTIONS(634), 1, + sym__br_acr_bgn, + STATE(104), 1, + sym__r_acr, + STATE(109), 1, + sym__br_acr, + ACTIONS(631), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(627), 38, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [142] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(624), 1, + sym__br_acr_bgn, + ACTIONS(637), 1, + sym__r_acr_bgn, + STATE(108), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(615), 48, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [206] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(629), 1, + sym__r_blk_imp_bgn, + ACTIONS(639), 1, + sym__r_tag, + ACTIONS(641), 1, + sym__br_tag, + ACTIONS(631), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(627), 38, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [271] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(617), 1, + sym__r_blk_imp_bgn, + ACTIONS(644), 1, + sym__r_tag, + ACTIONS(646), 1, + sym__br_tag, + ACTIONS(619), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(615), 38, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [336] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 51, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__r_tag, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [393] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 51, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__r_tag, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [450] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(655), 1, + sym__r_blk_imp_bgn, + ACTIONS(657), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(653), 39, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [510] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(662), 1, + sym__r_blk_imp_bgn, + ACTIONS(664), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(660), 39, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [570] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(646), 1, + sym__br_tag, + ACTIONS(667), 1, + sym__r_tag, + ACTIONS(615), 48, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [630] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 50, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__r_tag, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [686] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 50, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [742] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(653), 49, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [797] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(660), 49, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [852] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 49, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [907] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 49, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [962] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(207), 1, + sym__br_flw_seq_bgn, + ACTIONS(211), 1, + sym__br_flw_map_bgn, + ACTIONS(227), 1, + sym__br_dqt_str_bgn, + ACTIONS(231), 1, + sym__br_sqt_str_bgn, + ACTIONS(237), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(239), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(426), 1, + sym__r_flw_seq_bgn, + ACTIONS(428), 1, + sym__r_flw_map_bgn, + ACTIONS(436), 1, + sym__r_dqt_str_bgn, + ACTIONS(438), 1, + sym__r_sqt_str_bgn, + STATE(598), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(599), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(600), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(601), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(639), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(233), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(235), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + ACTIONS(369), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [1043] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(207), 1, + sym__br_flw_seq_bgn, + ACTIONS(211), 1, + sym__br_flw_map_bgn, + ACTIONS(227), 1, + sym__br_dqt_str_bgn, + ACTIONS(231), 1, + sym__br_sqt_str_bgn, + ACTIONS(237), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(239), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(426), 1, + sym__r_flw_seq_bgn, + ACTIONS(428), 1, + sym__r_flw_map_bgn, + ACTIONS(436), 1, + sym__r_dqt_str_bgn, + ACTIONS(438), 1, + sym__r_sqt_str_bgn, + STATE(594), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(595), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(596), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(597), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(637), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(233), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(235), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + ACTIONS(377), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [1124] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(289), 1, + sym__br_flw_seq_bgn, + ACTIONS(297), 1, + sym__br_flw_map_bgn, + ACTIONS(309), 1, + sym__br_dqt_str_bgn, + ACTIONS(313), 1, + sym__br_sqt_str_bgn, + ACTIONS(319), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(321), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(491), 1, + sym__r_flw_seq_bgn, + ACTIONS(493), 1, + sym__r_flw_map_bgn, + ACTIONS(499), 1, + sym__r_dqt_str_bgn, + ACTIONS(501), 1, + sym__r_sqt_str_bgn, + STATE(728), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(729), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(730), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(731), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(701), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(315), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(317), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + ACTIONS(369), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [1204] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(289), 1, + sym__br_flw_seq_bgn, + ACTIONS(297), 1, + sym__br_flw_map_bgn, + ACTIONS(309), 1, + sym__br_dqt_str_bgn, + ACTIONS(313), 1, + sym__br_sqt_str_bgn, + ACTIONS(319), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(321), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(491), 1, + sym__r_flw_seq_bgn, + ACTIONS(493), 1, + sym__r_flw_map_bgn, + ACTIONS(499), 1, + sym__r_dqt_str_bgn, + ACTIONS(501), 1, + sym__r_sqt_str_bgn, + STATE(724), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(725), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(726), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(727), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(700), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(315), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(317), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + ACTIONS(377), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [1284] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(629), 1, + sym__r_blk_imp_bgn, + ACTIONS(669), 1, + sym__r_acr_bgn, + ACTIONS(671), 1, + sym__br_acr_bgn, + STATE(166), 1, + sym__r_acr, + STATE(169), 1, + sym__br_acr, + ACTIONS(631), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(627), 24, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_als_bgn, + [1341] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(452), 1, + sym__br_flw_seq_bgn, + ACTIONS(461), 1, + sym__br_flw_map_bgn, + ACTIONS(465), 1, + sym__br_dqt_str_bgn, + ACTIONS(469), 1, + sym__br_sqt_str_bgn, + ACTIONS(475), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(477), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(601), 1, + sym__r_flw_seq_bgn, + ACTIONS(605), 1, + sym__r_flw_map_bgn, + ACTIONS(607), 1, + sym__r_dqt_str_bgn, + ACTIONS(609), 1, + sym__r_sqt_str_bgn, + STATE(846), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(847), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(848), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(849), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(942), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(369), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + ACTIONS(471), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(473), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + [1420] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(617), 1, + sym__r_blk_imp_bgn, + ACTIONS(669), 1, + sym__r_acr_bgn, + ACTIONS(674), 1, + sym__br_acr_bgn, + STATE(165), 1, + sym__r_acr, + STATE(176), 1, + sym__br_acr, + ACTIONS(619), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(615), 24, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_als_bgn, + [1477] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(517), 1, + sym__br_flw_seq_bgn, + ACTIONS(521), 1, + sym__br_flw_map_bgn, + ACTIONS(525), 1, + sym__br_dqt_str_bgn, + ACTIONS(529), 1, + sym__br_sqt_str_bgn, + ACTIONS(535), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(537), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(589), 1, + sym__r_flw_seq_bgn, + ACTIONS(591), 1, + sym__r_flw_map_bgn, + ACTIONS(593), 1, + sym__r_dqt_str_bgn, + ACTIONS(595), 1, + sym__r_sqt_str_bgn, + STATE(892), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(893), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(894), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(895), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(811), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(377), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + ACTIONS(531), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(533), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + [1556] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(517), 1, + sym__br_flw_seq_bgn, + ACTIONS(521), 1, + sym__br_flw_map_bgn, + ACTIONS(525), 1, + sym__br_dqt_str_bgn, + ACTIONS(529), 1, + sym__br_sqt_str_bgn, + ACTIONS(535), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(537), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(589), 1, + sym__r_flw_seq_bgn, + ACTIONS(591), 1, + sym__r_flw_map_bgn, + ACTIONS(593), 1, + sym__r_dqt_str_bgn, + ACTIONS(595), 1, + sym__r_sqt_str_bgn, + STATE(896), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(897), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(898), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(899), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(812), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(369), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + ACTIONS(531), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(533), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + [1635] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(452), 1, + sym__br_flw_seq_bgn, + ACTIONS(461), 1, + sym__br_flw_map_bgn, + ACTIONS(465), 1, + sym__br_dqt_str_bgn, + ACTIONS(469), 1, + sym__br_sqt_str_bgn, + ACTIONS(475), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(477), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(601), 1, + sym__r_flw_seq_bgn, + ACTIONS(605), 1, + sym__r_flw_map_bgn, + ACTIONS(607), 1, + sym__r_dqt_str_bgn, + ACTIONS(609), 1, + sym__r_sqt_str_bgn, + STATE(842), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(843), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(844), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(845), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(930), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(377), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + ACTIONS(471), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(473), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + [1714] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(617), 1, + sym__r_blk_imp_bgn, + ACTIONS(677), 1, + sym__r_acr_bgn, + ACTIONS(679), 1, + sym__br_acr_bgn, + STATE(168), 1, + sym__r_acr, + STATE(178), 1, + sym__br_acr, + ACTIONS(619), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(615), 23, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_als_bgn, + sym__bl, + [1770] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(629), 1, + sym__r_blk_imp_bgn, + ACTIONS(677), 1, + sym__r_acr_bgn, + ACTIONS(682), 1, + sym__br_acr_bgn, + STATE(172), 1, + sym__r_acr, + STATE(179), 1, + sym__br_acr, + ACTIONS(631), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(627), 23, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_als_bgn, + sym__bl, + [1826] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(674), 1, + sym__br_acr_bgn, + ACTIONS(685), 1, + sym__r_acr_bgn, + STATE(176), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(615), 34, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_als_bgn, + [1876] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(707), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(144), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [1967] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(713), 1, + sym__r_flw_map_end, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(964), 1, + sym__r_sgl_flw_col_itm, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1322), 1, + sym__sgl_flw_map_tal, + STATE(1449), 1, + sym__r_sgl_flw_col_dat, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [2062] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 37, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__r_tag, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [2105] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(731), 1, + sym__b_blk_key_bgn, + ACTIONS(734), 1, + sym__b_blk_val_bgn, + ACTIONS(737), 1, + sym__b_flw_seq_bgn, + ACTIONS(740), 1, + sym__b_flw_map_bgn, + ACTIONS(743), 1, + sym__b_dqt_str_bgn, + ACTIONS(746), 1, + sym__b_sqt_str_bgn, + ACTIONS(752), 1, + sym__b_tag, + ACTIONS(755), 1, + sym__b_acr_bgn, + ACTIONS(758), 1, + sym__b_als_bgn, + ACTIONS(761), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(128), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(749), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [2196] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 37, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__r_tag, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [2239] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(763), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(145), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [2330] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(617), 1, + sym__r_blk_imp_bgn, + ACTIONS(765), 1, + sym__r_tag, + ACTIONS(767), 1, + sym__br_tag, + ACTIONS(619), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(615), 24, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_acr_bgn, + sym__br_als_bgn, + [2381] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(772), 1, + sym__r_flw_seq_end, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(986), 1, + sym__r_sgl_flw_col_itm, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1423), 1, + sym__sgl_flw_seq_tal, + STATE(1459), 1, + sym__r_sgl_flw_col_dat, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [2476] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + ACTIONS(792), 1, + sym__r_flw_map_end, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(964), 1, + sym__r_sgl_flw_col_itm, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1516), 1, + sym__r_sgl_flw_col_dat, + STATE(1517), 1, + sym__sgl_flw_map_tal, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [2571] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(794), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(138), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [2662] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(796), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(139), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [2753] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + ACTIONS(798), 1, + sym__r_flw_seq_end, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(986), 1, + sym__r_sgl_flw_col_itm, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1139), 1, + sym__sgl_flw_seq_tal, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1468), 1, + sym__r_sgl_flw_col_dat, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [2848] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + ACTIONS(800), 1, + sym__r_flw_map_end, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(964), 1, + sym__r_sgl_flw_col_itm, + STATE(1100), 1, + sym__r_als, + STATE(1145), 1, + sym__sgl_flw_map_tal, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1471), 1, + sym__r_sgl_flw_col_dat, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [2943] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(802), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(128), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [3034] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(804), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(128), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [3125] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + ACTIONS(806), 1, + sym__r_flw_seq_end, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(986), 1, + sym__r_sgl_flw_col_itm, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1445), 1, + sym__sgl_flw_seq_tal, + STATE(1459), 1, + sym__r_sgl_flw_col_dat, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [3220] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + ACTIONS(808), 1, + sym__r_flw_map_end, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(964), 1, + sym__r_sgl_flw_col_itm, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1496), 1, + sym__sgl_flw_map_tal, + STATE(1516), 1, + sym__r_sgl_flw_col_dat, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [3315] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(810), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(149), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [3406] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(812), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(150), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [3497] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(814), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(128), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [3588] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(816), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(128), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [3679] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(629), 1, + sym__r_blk_imp_bgn, + ACTIONS(818), 1, + sym__r_tag, + ACTIONS(820), 1, + sym__br_tag, + ACTIONS(631), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(627), 24, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_acr_bgn, + sym__br_als_bgn, + [3730] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + ACTIONS(823), 1, + sym__r_flw_seq_end, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(986), 1, + sym__r_sgl_flw_col_itm, + STATE(1050), 1, + sym__sgl_flw_seq_tal, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1473), 1, + sym__r_sgl_flw_col_dat, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [3825] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + ACTIONS(825), 1, + sym__r_flw_map_end, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(964), 1, + sym__r_sgl_flw_col_itm, + STATE(1064), 1, + sym__sgl_flw_map_tal, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1476), 1, + sym__r_sgl_flw_col_dat, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [3920] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(827), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(128), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [4011] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(829), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(128), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [4102] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + ACTIONS(831), 1, + sym__r_flw_seq_end, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(986), 1, + sym__r_sgl_flw_col_itm, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1457), 1, + sym__r_sgl_flw_col_dat, + STATE(1509), 1, + sym__sgl_flw_seq_tal, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [4197] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + ACTIONS(833), 1, + sym__r_flw_map_end, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(964), 1, + sym__r_sgl_flw_col_itm, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1422), 1, + sym__sgl_flw_map_tal, + STATE(1460), 1, + sym__r_sgl_flw_col_dat, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [4292] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + ACTIONS(835), 1, + sym__r_flw_seq_end, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(986), 1, + sym__r_sgl_flw_col_itm, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1257), 1, + sym__sgl_flw_seq_tal, + STATE(1525), 1, + sym__r_sgl_flw_col_dat, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [4387] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + ACTIONS(837), 1, + sym__r_flw_map_end, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(964), 1, + sym__r_sgl_flw_col_itm, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1264), 1, + sym__sgl_flw_map_tal, + STATE(1527), 1, + sym__r_sgl_flw_col_dat, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [4482] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + ACTIONS(839), 1, + sym__r_flw_seq_end, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(986), 1, + sym__r_sgl_flw_col_itm, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1317), 1, + sym__sgl_flw_seq_tal, + STATE(1447), 1, + sym__r_sgl_flw_col_dat, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [4577] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 36, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__r_tag, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [4619] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(617), 1, + sym__r_blk_imp_bgn, + ACTIONS(841), 1, + sym__r_tag, + ACTIONS(843), 1, + sym__br_tag, + ACTIONS(619), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(615), 23, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [4669] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(629), 1, + sym__r_blk_imp_bgn, + ACTIONS(846), 1, + sym__r_tag, + ACTIONS(848), 1, + sym__br_tag, + ACTIONS(631), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(627), 23, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [4719] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 36, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [4761] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(767), 1, + sym__br_tag, + ACTIONS(851), 1, + sym__r_tag, + ACTIONS(615), 34, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_acr_bgn, + sym__br_als_bgn, + [4807] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 36, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__r_tag, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [4849] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(387), 1, + sym__br_flw_seq_bgn, + ACTIONS(391), 1, + sym__br_flw_map_bgn, + ACTIONS(400), 1, + sym__br_dqt_str_bgn, + ACTIONS(404), 1, + sym__br_sqt_str_bgn, + ACTIONS(410), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(412), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(577), 1, + sym__r_flw_seq_bgn, + ACTIONS(579), 1, + sym__r_flw_map_bgn, + ACTIONS(583), 1, + sym__r_dqt_str_bgn, + ACTIONS(585), 1, + sym__r_sqt_str_bgn, + ACTIONS(377), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + STATE(1338), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(1339), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(1340), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(1341), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(1398), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(406), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(408), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + [4925] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 36, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__r_tag, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [4967] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(387), 1, + sym__br_flw_seq_bgn, + ACTIONS(391), 1, + sym__br_flw_map_bgn, + ACTIONS(400), 1, + sym__br_dqt_str_bgn, + ACTIONS(404), 1, + sym__br_sqt_str_bgn, + ACTIONS(410), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(412), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(577), 1, + sym__r_flw_seq_bgn, + ACTIONS(579), 1, + sym__r_flw_map_bgn, + ACTIONS(583), 1, + sym__r_dqt_str_bgn, + ACTIONS(585), 1, + sym__r_sqt_str_bgn, + ACTIONS(369), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + STATE(1342), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(1343), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(1346), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(1349), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(1400), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(406), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(408), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + [5043] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(655), 1, + sym__r_blk_imp_bgn, + ACTIONS(657), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(653), 25, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [5089] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(662), 1, + sym__r_blk_imp_bgn, + ACTIONS(664), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(660), 25, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [5135] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + ACTIONS(853), 1, + sym__r_flw_seq_end, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1245), 1, + sym__r_sgl_flw_col_itm, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [5224] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(655), 1, + sym__r_blk_imp_bgn, + ACTIONS(657), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(653), 24, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [5269] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(660), 35, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [5310] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 35, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [5351] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 35, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [5392] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(662), 1, + sym__r_blk_imp_bgn, + ACTIONS(664), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(660), 24, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [5437] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 35, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [5478] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + ACTIONS(853), 1, + sym__r_flw_map_end, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1372), 1, + sym__r_sgl_flw_col_itm, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [5567] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + ACTIONS(855), 1, + sym__r_flw_map_end, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1372), 1, + sym__r_sgl_flw_col_itm, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [5656] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(653), 35, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [5697] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + ACTIONS(855), 1, + sym__r_flw_seq_end, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1245), 1, + sym__r_sgl_flw_col_itm, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [5786] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(653), 34, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [5826] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(660), 34, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [5866] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 34, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [5906] = 25, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1245), 1, + sym__r_sgl_flw_col_itm, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [5992] = 25, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1372), 1, + sym__r_sgl_flw_col_itm, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [6078] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(857), 1, + sym__r_acr_bgn, + ACTIONS(859), 1, + sym__br_acr_bgn, + STATE(219), 1, + sym__r_acr, + STATE(221), 1, + sym__br_acr, + ACTIONS(619), 13, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 16, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_njv_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6127] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(857), 1, + sym__r_acr_bgn, + ACTIONS(859), 1, + sym__br_acr_bgn, + STATE(222), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(627), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6172] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(857), 1, + sym__r_acr_bgn, + ACTIONS(859), 1, + sym__br_acr_bgn, + STATE(221), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(615), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6217] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(861), 1, + sym__r_acr_bgn, + ACTIONS(863), 1, + sym__br_acr_bgn, + STATE(232), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(627), 28, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6261] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(861), 1, + sym__r_acr_bgn, + ACTIONS(863), 1, + sym__br_acr_bgn, + STATE(231), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(615), 28, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6305] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(861), 1, + sym__r_acr_bgn, + ACTIONS(863), 1, + sym__br_acr_bgn, + STATE(230), 1, + sym__r_acr, + STATE(231), 1, + sym__br_acr, + ACTIONS(619), 13, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 15, + sym__br_flw_seq_bgn, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_map_bgn, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6353] = 21, + ACTIONS(3), 1, + sym_comment, + ACTIONS(865), 1, + sym__r_flw_seq_bgn, + ACTIONS(867), 1, + sym__r_flw_map_bgn, + ACTIONS(871), 1, + sym__r_dqt_str_bgn, + ACTIONS(873), 1, + sym__r_sqt_str_bgn, + ACTIONS(877), 1, + sym__r_tag, + ACTIONS(879), 1, + sym__r_acr_bgn, + ACTIONS(881), 1, + sym__r_als_bgn, + STATE(365), 1, + sym__r_sgl_prp, + STATE(413), 1, + sym__r_acr, + STATE(1312), 1, + sym__r_sgl_flw_imp_par, + STATE(1455), 1, + sym__r_als, + STATE(1463), 1, + sym__r_sgl_dqt_str, + STATE(1467), 1, + sym__r_sgl_sqt_str, + STATE(1506), 1, + sym__r_sgl_flw_seq, + STATE(1518), 1, + sym__r_sgl_pln_flw, + STATE(1534), 1, + sym__r_sgl_flw_map, + ACTIONS(869), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + STATE(1239), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1242), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(875), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [6428] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(883), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(615), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6467] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(883), 1, + sym__br_tag, + ACTIONS(885), 1, + sym__r_tag, + ACTIONS(619), 13, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 16, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_njv_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6510] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(887), 1, + sym__r_acr_bgn, + ACTIONS(889), 1, + sym__br_acr_bgn, + STATE(236), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(615), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6553] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(891), 1, + sym__r_acr_bgn, + ACTIONS(893), 1, + sym__br_acr_bgn, + STATE(243), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(627), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6596] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 31, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [6633] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(891), 1, + sym__r_acr_bgn, + ACTIONS(893), 1, + sym__br_acr_bgn, + STATE(240), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(615), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6676] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 31, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [6713] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(895), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(627), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6752] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(887), 1, + sym__r_acr_bgn, + ACTIONS(889), 1, + sym__br_acr_bgn, + STATE(236), 1, + sym__br_acr, + STATE(238), 1, + sym__r_acr, + ACTIONS(619), 12, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 15, + sym__br_flw_seq_bgn, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_map_bgn, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6799] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(897), 1, + sym__r_flw_seq_bgn, + ACTIONS(901), 1, + sym__r_flw_map_bgn, + ACTIONS(903), 1, + sym__r_dqt_str_bgn, + ACTIONS(905), 1, + sym__r_sqt_str_bgn, + ACTIONS(909), 1, + sym__r_tag, + ACTIONS(911), 1, + sym__r_acr_bgn, + ACTIONS(913), 1, + sym__r_als_bgn, + STATE(274), 1, + sym__r_sgl_prp, + STATE(401), 1, + sym__r_acr, + STATE(1219), 1, + sym__r_sgl_flw_seq, + STATE(1223), 1, + sym__r_sgl_flw_map, + STATE(1224), 1, + sym__r_sgl_dqt_str, + STATE(1228), 1, + sym__r_sgl_sqt_str, + STATE(1326), 1, + sym__r_sgl_pln_flw, + STATE(1348), 1, + sym__r_als, + ACTIONS(899), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(907), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + STATE(1379), 8, + sym__r_sgl_prp_val, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__sgl_flw_ann_par_tal, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + [6870] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(915), 1, + sym__r_flw_seq_bgn, + ACTIONS(917), 1, + sym__r_flw_map_bgn, + ACTIONS(919), 1, + sym__r_dqt_str_bgn, + ACTIONS(921), 1, + sym__r_sqt_str_bgn, + ACTIONS(925), 1, + sym__r_tag, + ACTIONS(927), 1, + sym__r_acr_bgn, + ACTIONS(929), 1, + sym__r_als_bgn, + STATE(276), 1, + sym__r_sgl_prp, + STATE(404), 1, + sym__r_acr, + STATE(1301), 1, + sym__r_sgl_flw_seq, + STATE(1305), 1, + sym__r_sgl_flw_map, + STATE(1308), 1, + sym__r_sgl_dqt_str, + STATE(1311), 1, + sym__r_sgl_sqt_str, + STATE(1336), 1, + sym__r_sgl_pln_flw, + STATE(1353), 1, + sym__r_als, + ACTIONS(899), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(923), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + STATE(1319), 8, + sym__r_sgl_prp_val, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__sgl_flw_ann_par_tal, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + [6941] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(891), 1, + sym__r_acr_bgn, + ACTIONS(893), 1, + sym__br_acr_bgn, + STATE(240), 1, + sym__br_acr, + STATE(242), 1, + sym__r_acr, + ACTIONS(619), 12, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 15, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6988] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(915), 1, + sym__r_flw_seq_bgn, + ACTIONS(917), 1, + sym__r_flw_map_bgn, + ACTIONS(919), 1, + sym__r_dqt_str_bgn, + ACTIONS(921), 1, + sym__r_sqt_str_bgn, + ACTIONS(925), 1, + sym__r_tag, + ACTIONS(927), 1, + sym__r_acr_bgn, + ACTIONS(929), 1, + sym__r_als_bgn, + STATE(276), 1, + sym__r_sgl_prp, + STATE(404), 1, + sym__r_acr, + STATE(1301), 1, + sym__r_sgl_flw_seq, + STATE(1305), 1, + sym__r_sgl_flw_map, + STATE(1308), 1, + sym__r_sgl_dqt_str, + STATE(1311), 1, + sym__r_sgl_sqt_str, + STATE(1336), 1, + sym__r_sgl_pln_flw, + STATE(1353), 1, + sym__r_als, + ACTIONS(931), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(923), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + STATE(1371), 8, + sym__r_sgl_prp_val, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__sgl_flw_ann_par_tal, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + [7059] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(897), 1, + sym__r_flw_seq_bgn, + ACTIONS(901), 1, + sym__r_flw_map_bgn, + ACTIONS(903), 1, + sym__r_dqt_str_bgn, + ACTIONS(905), 1, + sym__r_sqt_str_bgn, + ACTIONS(909), 1, + sym__r_tag, + ACTIONS(911), 1, + sym__r_acr_bgn, + ACTIONS(913), 1, + sym__r_als_bgn, + STATE(274), 1, + sym__r_sgl_prp, + STATE(401), 1, + sym__r_acr, + STATE(1219), 1, + sym__r_sgl_flw_seq, + STATE(1223), 1, + sym__r_sgl_flw_map, + STATE(1224), 1, + sym__r_sgl_dqt_str, + STATE(1228), 1, + sym__r_sgl_sqt_str, + STATE(1326), 1, + sym__r_sgl_pln_flw, + STATE(1348), 1, + sym__r_als, + ACTIONS(931), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(907), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + STATE(1327), 8, + sym__r_sgl_prp_val, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__sgl_flw_ann_par_tal, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + [7130] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(887), 1, + sym__r_acr_bgn, + ACTIONS(889), 1, + sym__br_acr_bgn, + STATE(234), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(627), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7173] = 21, + ACTIONS(3), 1, + sym_comment, + ACTIONS(865), 1, + sym__r_flw_seq_bgn, + ACTIONS(867), 1, + sym__r_flw_map_bgn, + ACTIONS(871), 1, + sym__r_dqt_str_bgn, + ACTIONS(873), 1, + sym__r_sqt_str_bgn, + ACTIONS(877), 1, + sym__r_tag, + ACTIONS(879), 1, + sym__r_acr_bgn, + ACTIONS(881), 1, + sym__r_als_bgn, + STATE(365), 1, + sym__r_sgl_prp, + STATE(413), 1, + sym__r_acr, + STATE(1292), 1, + sym__r_sgl_flw_imp_par, + STATE(1455), 1, + sym__r_als, + STATE(1463), 1, + sym__r_sgl_dqt_str, + STATE(1467), 1, + sym__r_sgl_sqt_str, + STATE(1506), 1, + sym__r_sgl_flw_seq, + STATE(1518), 1, + sym__r_sgl_pln_flw, + STATE(1534), 1, + sym__r_sgl_flw_map, + ACTIONS(869), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + STATE(1359), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1244), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(875), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [7248] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 30, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [7284] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(933), 1, + sym__r_tag, + ACTIONS(935), 1, + sym__br_tag, + ACTIONS(619), 13, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 15, + sym__br_flw_seq_bgn, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_map_bgn, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7326] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 30, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [7362] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(935), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(615), 28, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7400] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(937), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(627), 28, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7438] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [7473] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [7508] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(939), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(615), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7545] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(941), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(615), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7582] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(941), 1, + sym__br_tag, + ACTIONS(943), 1, + sym__r_tag, + ACTIONS(619), 12, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 15, + sym__br_flw_seq_bgn, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_map_bgn, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7623] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7658] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7693] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(945), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(627), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7730] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(657), 13, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(653), 16, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_njv_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7767] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(939), 1, + sym__br_tag, + ACTIONS(947), 1, + sym__r_tag, + ACTIONS(619), 12, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 15, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7808] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(653), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7843] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(660), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7878] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [7913] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(949), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(627), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7950] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [7985] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(951), 1, + sym__r_acr_bgn, + ACTIONS(953), 1, + sym__br_acr_bgn, + STATE(257), 1, + sym__r_acr, + STATE(258), 1, + sym__br_acr, + ACTIONS(619), 11, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 13, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_njv_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8029] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 28, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8063] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 28, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8097] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(951), 1, + sym__r_acr_bgn, + ACTIONS(953), 1, + sym__br_acr_bgn, + STATE(258), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(615), 24, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8137] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(657), 13, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(653), 15, + sym__br_flw_seq_bgn, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_map_bgn, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8173] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(653), 28, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8207] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(660), 28, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8241] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(951), 1, + sym__r_acr_bgn, + ACTIONS(953), 1, + sym__br_acr_bgn, + STATE(260), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(627), 24, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8281] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(660), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8314] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8347] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(653), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8380] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8413] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(657), 12, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(653), 15, + sym__br_flw_seq_bgn, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_map_bgn, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8448] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8481] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(653), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8514] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8547] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(657), 12, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(653), 15, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8582] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(660), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8615] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(955), 1, + sym__r_tag, + ACTIONS(957), 1, + sym__br_tag, + ACTIONS(619), 11, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 13, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_njv_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8653] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(957), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(615), 24, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8687] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 26, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [8719] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 26, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [8751] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(959), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(627), 24, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8785] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(961), 25, + sym__eof, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__br_blk_lit_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [8816] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(963), 25, + sym__eof, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__br_blk_lit_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [8847] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(961), 25, + sym__eof, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__br_blk_lit_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [8878] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(965), 25, + sym__eof, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__br_blk_lit_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [8909] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(967), 25, + sym__eof, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__br_blk_lit_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [8940] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(967), 25, + sym__eof, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__br_blk_lit_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [8971] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(969), 25, + sym__eof, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__br_blk_lit_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [9002] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 24, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [9032] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(657), 11, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(653), 13, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_njv_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [9064] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(653), 24, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [9094] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 24, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [9124] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(660), 24, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [9154] = 12, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + STATE(1084), 1, + sym__r_sgl_pln_flw, + STATE(1161), 1, + sym__r_sgl_flw_seq, + STATE(1162), 1, + sym__r_sgl_flw_map, + STATE(1163), 1, + sym__r_sgl_dqt_str, + STATE(1164), 1, + sym__r_sgl_sqt_str, + ACTIONS(971), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [9198] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(332), 1, + sym__blk_imp_itm_tal, + ACTIONS(973), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9226] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(334), 1, + sym__blk_imp_itm_tal, + ACTIONS(977), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9254] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(334), 1, + sym__blk_imp_itm_tal, + ACTIONS(973), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9282] = 12, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + STATE(1051), 1, + sym__r_sgl_flw_seq, + STATE(1052), 1, + sym__r_sgl_flw_map, + STATE(1053), 1, + sym__r_sgl_dqt_str, + STATE(1054), 1, + sym__r_sgl_sqt_str, + STATE(1171), 1, + sym__r_sgl_pln_flw, + ACTIONS(971), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [9326] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 17, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9349] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(981), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9374] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(985), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9399] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 1, + sym__r_blk_imp_bgn, + ACTIONS(987), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9424] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(993), 1, + sym__r_blk_imp_bgn, + ACTIONS(991), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9449] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 1, + sym__r_blk_imp_bgn, + ACTIONS(995), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9474] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1001), 1, + sym__r_blk_imp_bgn, + ACTIONS(999), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9499] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1003), 17, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9522] = 12, + ACTIONS(3), 1, + sym_comment, + ACTIONS(897), 1, + sym__r_flw_seq_bgn, + ACTIONS(901), 1, + sym__r_flw_map_bgn, + ACTIONS(903), 1, + sym__r_dqt_str_bgn, + ACTIONS(905), 1, + sym__r_sqt_str_bgn, + STATE(1231), 1, + sym__r_sgl_flw_seq, + STATE(1232), 1, + sym__r_sgl_flw_map, + STATE(1233), 1, + sym__r_sgl_dqt_str, + STATE(1234), 1, + sym__r_sgl_sqt_str, + STATE(1269), 1, + sym__r_sgl_pln_flw, + ACTIONS(971), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(907), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [9565] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 17, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9588] = 12, + ACTIONS(3), 1, + sym_comment, + ACTIONS(915), 1, + sym__r_flw_seq_bgn, + ACTIONS(917), 1, + sym__r_flw_map_bgn, + ACTIONS(919), 1, + sym__r_dqt_str_bgn, + ACTIONS(921), 1, + sym__r_sqt_str_bgn, + STATE(1236), 1, + sym__r_sgl_pln_flw, + STATE(1354), 1, + sym__r_sgl_flw_seq, + STATE(1357), 1, + sym__r_sgl_flw_map, + STATE(1358), 1, + sym__r_sgl_dqt_str, + STATE(1360), 1, + sym__r_sgl_sqt_str, + ACTIONS(971), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(923), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [9631] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + STATE(329), 1, + sym__b_blk_val_itm, + ACTIONS(1007), 15, + sym__b_blk_key_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9658] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + STATE(331), 1, + sym__b_blk_val_itm, + ACTIONS(1009), 15, + sym__b_blk_key_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9685] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + STATE(306), 1, + sym__b_blk_val_itm, + ACTIONS(1011), 15, + sym__b_blk_key_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9712] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1013), 17, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9735] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1017), 1, + sym__r_blk_imp_bgn, + ACTIONS(1015), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9760] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(1019), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9785] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 17, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9808] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1025), 1, + sym__r_blk_imp_bgn, + ACTIONS(1023), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9833] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1029), 1, + sym__r_blk_imp_bgn, + ACTIONS(1027), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9858] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 1, + sym__r_blk_imp_bgn, + ACTIONS(1031), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9883] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1037), 1, + sym__r_blk_imp_bgn, + ACTIONS(1035), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9908] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 1, + sym__r_blk_imp_bgn, + ACTIONS(1039), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9933] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1045), 1, + sym__r_blk_imp_bgn, + ACTIONS(1043), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9958] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 17, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9981] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1049), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10003] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1051), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10025] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1053), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10047] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1055), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10069] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1057), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10091] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1059), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10113] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1061), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10135] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1063), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10157] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1065), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10179] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(977), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10201] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1067), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10223] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1069), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10245] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1071), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10267] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1073), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10289] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1075), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10311] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1077), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10333] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1079), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10355] = 12, + ACTIONS(3), 1, + sym_comment, + ACTIONS(971), 1, + sym__r_blk_imp_bgn, + ACTIONS(1081), 1, + sym__r_flw_seq_bgn, + ACTIONS(1083), 1, + sym__r_flw_map_bgn, + ACTIONS(1085), 1, + sym__r_dqt_str_bgn, + ACTIONS(1087), 1, + sym__r_sqt_str_bgn, + STATE(1521), 1, + sym__r_sgl_flw_seq, + STATE(1523), 1, + sym__r_sgl_flw_map, + STATE(1524), 1, + sym__r_sgl_dqt_str, + STATE(1528), 1, + sym__r_sgl_sqt_str, + STATE(1529), 1, + sym__r_sgl_pln_blk, + ACTIONS(1089), 6, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [10397] = 12, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1081), 1, + sym__r_flw_seq_bgn, + ACTIONS(1083), 1, + sym__r_flw_map_bgn, + ACTIONS(1085), 1, + sym__r_dqt_str_bgn, + ACTIONS(1087), 1, + sym__r_sqt_str_bgn, + ACTIONS(1091), 1, + sym__r_blk_imp_bgn, + STATE(1530), 1, + sym__r_sgl_flw_seq, + STATE(1531), 1, + sym__r_sgl_flw_map, + STATE(1533), 1, + sym__r_sgl_dqt_str, + STATE(1536), 1, + sym__r_sgl_sqt_str, + STATE(1537), 1, + sym__r_sgl_pln_blk, + ACTIONS(1089), 6, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [10439] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1093), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10461] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1095), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10483] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1097), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10505] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1099), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10527] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1101), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10549] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1003), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10571] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1103), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10593] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1105), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10615] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1107), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10637] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1109), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10659] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1111), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10681] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1113), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10703] = 12, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1081), 1, + sym__r_flw_seq_bgn, + ACTIONS(1083), 1, + sym__r_flw_map_bgn, + ACTIONS(1085), 1, + sym__r_dqt_str_bgn, + ACTIONS(1087), 1, + sym__r_sqt_str_bgn, + ACTIONS(1115), 1, + sym__r_blk_imp_bgn, + STATE(1415), 1, + sym__r_sgl_dqt_str, + STATE(1418), 1, + sym__r_sgl_sqt_str, + STATE(1419), 1, + sym__r_sgl_pln_blk, + STATE(1491), 1, + sym__r_sgl_flw_seq, + STATE(1492), 1, + sym__r_sgl_flw_map, + ACTIONS(1089), 6, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [10745] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1117), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10767] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10789] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1119), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10811] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1117), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10833] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1121), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10855] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1123), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10877] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1125), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10899] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10921] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1127), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10943] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1099), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10965] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10987] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1101), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11009] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(985), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11031] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1129), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11053] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1131), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11075] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1133), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11097] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1135), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11119] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1137), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11141] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1139), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11163] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1141), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11185] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1143), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11207] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1145), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11229] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1147), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11251] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1149), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11273] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1151), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11295] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1153), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11317] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1155), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11339] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1157), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11361] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1159), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11383] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1161), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11405] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1163), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11427] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(991), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11449] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1165), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11471] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1015), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11493] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1019), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11515] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1167), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11537] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1169), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11559] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1107), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11581] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1171), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11603] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1173), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11625] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11647] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1109), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11669] = 12, + ACTIONS(3), 1, + sym_comment, + ACTIONS(865), 1, + sym__r_flw_seq_bgn, + ACTIONS(867), 1, + sym__r_flw_map_bgn, + ACTIONS(871), 1, + sym__r_dqt_str_bgn, + ACTIONS(873), 1, + sym__r_sqt_str_bgn, + ACTIONS(971), 1, + sym__r_flw_njv_bgn, + STATE(1466), 1, + sym__r_sgl_flw_map, + STATE(1469), 1, + sym__r_sgl_dqt_str, + STATE(1470), 1, + sym__r_sgl_pln_flw, + STATE(1482), 1, + sym__r_sgl_sqt_str, + STATE(1535), 1, + sym__r_sgl_flw_seq, + ACTIONS(875), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [11711] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1175), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11733] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1177), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11755] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1179), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11777] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1181), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11799] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1183), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11821] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(999), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11843] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11865] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1035), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11887] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11909] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1185), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11931] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1043), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11953] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1187), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11975] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1189), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11997] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1191), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12019] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1193), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12041] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1195), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12063] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1197), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12085] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1199), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12107] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1201), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12129] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1203), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12151] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(981), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12173] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1205), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12195] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1207), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12217] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1209), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12239] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1211), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12261] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1213), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12283] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1215), 1, + sym__r_acr_bgn, + STATE(406), 1, + sym__r_acr, + ACTIONS(617), 13, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12308] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1217), 1, + sym__r_acr_bgn, + STATE(408), 1, + sym__r_acr, + ACTIONS(617), 13, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12333] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1219), 1, + sym__r_acr_bgn, + STATE(419), 1, + sym__r_acr, + ACTIONS(617), 12, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12357] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1221), 1, + sym__r_tag, + ACTIONS(617), 13, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12379] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1223), 1, + sym__r_acr_bgn, + STATE(417), 1, + sym__r_acr, + ACTIONS(617), 12, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12403] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 14, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__r_tag, + [12423] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1225), 1, + sym__r_tag, + ACTIONS(617), 13, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12445] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 14, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__r_tag, + [12465] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 13, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12484] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1227), 1, + sym__r_tag, + ACTIONS(617), 12, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12505] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 13, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12524] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1229), 1, + sym__r_acr_bgn, + STATE(445), 1, + sym__r_acr, + ACTIONS(617), 11, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12547] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1231), 1, + sym__r_tag, + ACTIONS(617), 12, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12568] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1235), 1, + sym__r_acr_bgn, + STATE(425), 1, + sym__r_acr, + ACTIONS(1233), 11, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [12591] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(655), 13, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12610] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 13, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__r_tag, + [12629] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(655), 13, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12648] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1235), 1, + sym__r_acr_bgn, + STATE(469), 1, + sym__r_acr, + ACTIONS(629), 11, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [12671] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 13, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__r_tag, + [12690] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 12, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12708] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 12, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__r_tag, + [12726] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1237), 1, + sym__r_tag, + ACTIONS(617), 11, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12746] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 12, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12764] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1239), 1, + sym__r_tag, + ACTIONS(629), 11, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [12784] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1241), 12, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__r_tag, + [12802] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(655), 12, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12820] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 12, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__r_tag, + [12838] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(655), 12, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12856] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1243), 1, + sym__r_tag, + ACTIONS(1233), 11, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [12876] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1249), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1251), 1, + sym__br_dqt_esc_nwl, + STATE(458), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1245), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1253), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(633), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [12905] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1257), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1259), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1261), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(587), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [12934] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1263), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1265), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1267), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(619), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [12963] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 11, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [12980] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1269), 11, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [12997] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1271), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1273), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1275), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(589), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13026] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1279), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1281), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1283), 1, + sym__r_dqt_str_end, + ACTIONS(1285), 1, + sym__br_dqt_str_end, + STATE(432), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1277), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(543), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13057] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1289), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1291), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1293), 1, + sym__r_dqt_str_end, + ACTIONS(1295), 1, + sym__br_dqt_str_end, + STATE(433), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1287), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(546), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13088] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1299), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1301), 1, + sym__br_dqt_esc_nwl, + STATE(435), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1297), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1303), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(607), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13117] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1307), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1309), 1, + sym__br_dqt_esc_nwl, + STATE(455), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1305), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1311), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(629), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13146] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1315), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1317), 1, + sym__br_dqt_esc_nwl, + STATE(436), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1313), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1319), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(635), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13175] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1321), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1323), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1325), 1, + sym__r_dqt_str_end, + ACTIONS(1327), 1, + sym__br_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(557), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13206] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1329), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1331), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1333), 1, + sym__r_dqt_str_end, + ACTIONS(1335), 1, + sym__br_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(559), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13237] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1337), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1339), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1341), 1, + sym__r_dqt_str_end, + ACTIONS(1343), 1, + sym__br_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(582), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13268] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1345), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1347), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1349), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(617), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13297] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1351), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1353), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1355), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(643), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13326] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1359), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1361), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1363), 1, + sym__r_dqt_str_end, + ACTIONS(1365), 1, + sym__br_dqt_str_end, + STATE(442), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1357), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(577), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13357] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 11, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [13374] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1369), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1371), 1, + sym__br_dqt_esc_nwl, + STATE(444), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1367), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1373), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(627), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13403] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1377), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1379), 1, + sym__br_dqt_esc_nwl, + STATE(426), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1375), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1381), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(579), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13432] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1385), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1387), 1, + sym__br_dqt_esc_nwl, + STATE(473), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1383), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1389), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(659), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13461] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1257), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1259), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1261), 1, + sym__br_dqt_str_end, + ACTIONS(1391), 1, + sym__r_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(587), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13492] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1307), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1309), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1311), 1, + sym__br_dqt_str_end, + ACTIONS(1395), 1, + sym__r_dqt_str_end, + STATE(460), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1393), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(629), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13523] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1397), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1399), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1401), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(650), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13552] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(655), 11, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [13569] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1369), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1371), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1373), 1, + sym__br_dqt_str_end, + ACTIONS(1405), 1, + sym__r_dqt_str_end, + STATE(465), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1403), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(627), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13600] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1409), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1411), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1413), 1, + sym__r_dqt_str_end, + ACTIONS(1415), 1, + sym__br_dqt_str_end, + STATE(467), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1407), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(630), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13631] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1299), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1301), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1303), 1, + sym__br_dqt_str_end, + ACTIONS(1419), 1, + sym__r_dqt_str_end, + STATE(451), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1417), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(607), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13662] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1279), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1281), 1, + sym__br_dqt_esc_nwl, + STATE(452), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1285), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + ACTIONS(1421), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(543), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13691] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1425), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1427), 1, + sym__br_dqt_esc_nwl, + STATE(453), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1423), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1429), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(682), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13720] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1345), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1347), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1349), 1, + sym__br_dqt_str_end, + ACTIONS(1431), 1, + sym__r_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(617), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13751] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1321), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1323), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1327), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(557), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13780] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1433), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1435), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1437), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(688), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13809] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1249), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1251), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1253), 1, + sym__br_dqt_str_end, + ACTIONS(1441), 1, + sym__r_dqt_str_end, + STATE(456), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1439), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(633), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13840] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1443), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1445), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1447), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(685), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13869] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1449), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1451), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1453), 1, + sym__r_dqt_str_end, + ACTIONS(1455), 1, + sym__br_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(641), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13900] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1359), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1361), 1, + sym__br_dqt_esc_nwl, + STATE(422), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1365), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + ACTIONS(1457), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(577), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13929] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1449), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1451), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1455), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(641), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13958] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1461), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1463), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1465), 1, + sym__r_dqt_str_end, + ACTIONS(1467), 1, + sym__br_dqt_str_end, + STATE(434), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1459), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(647), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13989] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1443), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1445), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1447), 1, + sym__br_dqt_str_end, + ACTIONS(1469), 1, + sym__r_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(685), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14020] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1473), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1475), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1477), 1, + sym__r_dqt_str_end, + ACTIONS(1479), 1, + sym__br_dqt_str_end, + STATE(464), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1471), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(657), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14051] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1483), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1485), 1, + sym__br_dqt_esc_nwl, + STATE(423), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1481), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1487), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(609), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14080] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1473), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1475), 1, + sym__br_dqt_esc_nwl, + STATE(466), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1479), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + ACTIONS(1489), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(657), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14109] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1491), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1493), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1495), 1, + sym__r_dqt_str_end, + ACTIONS(1497), 1, + sym__br_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(664), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14140] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1397), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1399), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1401), 1, + sym__br_dqt_str_end, + ACTIONS(1499), 1, + sym__r_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(650), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14171] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1491), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1493), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1497), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(664), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14200] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1501), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1503), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1505), 1, + sym__r_dqt_str_end, + ACTIONS(1507), 1, + sym__br_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(652), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14231] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1511), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1513), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1515), 1, + sym__r_dqt_str_end, + ACTIONS(1517), 1, + sym__br_dqt_str_end, + STATE(471), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1509), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(680), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14262] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(662), 11, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [14279] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1511), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1513), 1, + sym__br_dqt_esc_nwl, + STATE(472), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1517), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + ACTIONS(1519), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(680), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14308] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1521), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1523), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1525), 1, + sym__r_dqt_str_end, + ACTIONS(1527), 1, + sym__br_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(686), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14339] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1521), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1523), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1527), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(686), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14368] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1529), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1531), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1533), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(666), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14397] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym__s_drs_end, + ACTIONS(379), 1, + sym__eof, + ACTIONS(1535), 1, + sym__s_doc_end, + STATE(476), 1, + sym__doc_w_bgn_wo_end, + STATE(1155), 1, + sym__exp_doc, + STATE(1428), 2, + sym__doc_w_bgn_w_end_seq, + sym__doc_w_bgn_wo_end_seq, + STATE(38), 3, + sym__doc_w_bgn_w_end, + sym__exp_doc_end, + sym__doc_end, + [14425] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(221), 1, + sym__r_flw_njv_bgn, + ACTIONS(223), 1, + sym__br_flw_njv_bgn, + STATE(793), 1, + sym__br_flw_njl_ann_par, + STATE(943), 1, + sym__r_flw_njl_ann_par, + STATE(1337), 1, + sym__r_sgl_flw_njl_ann_par, + ACTIONS(1537), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(1540), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [14453] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym__s_drs_end, + ACTIONS(15), 1, + sym__s_doc_end, + ACTIONS(1542), 1, + sym__eof, + STATE(476), 1, + sym__doc_w_bgn_wo_end, + STATE(1155), 1, + sym__exp_doc, + STATE(1526), 2, + sym__doc_w_bgn_w_end_seq, + sym__doc_w_bgn_wo_end_seq, + STATE(38), 3, + sym__doc_w_bgn_w_end, + sym__exp_doc_end, + sym__doc_end, + [14481] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym__s_drs_end, + ACTIONS(379), 1, + sym__eof, + ACTIONS(1544), 1, + sym__s_doc_end, + STATE(476), 1, + sym__doc_w_bgn_wo_end, + STATE(1155), 1, + sym__exp_doc, + STATE(1428), 2, + sym__doc_w_bgn_w_end_seq, + sym__doc_w_bgn_wo_end_seq, + STATE(38), 3, + sym__doc_w_bgn_w_end, + sym__exp_doc_end, + sym__doc_end, + [14509] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(7), 1, + sym__s_dir_yml_bgn, + ACTIONS(9), 1, + sym__s_dir_tag_bgn, + ACTIONS(11), 1, + sym__s_dir_rsv_bgn, + ACTIONS(13), 1, + sym__s_drs_end, + STATE(1085), 1, + sym__exp_doc, + STATE(522), 5, + sym__s_dir, + sym__s_dir_yml, + sym__s_dir_tag, + sym__s_dir_rsv, + aux_sym__drs_doc_repeat1, + [14535] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym__s_drs_end, + ACTIONS(379), 1, + sym__eof, + ACTIONS(1546), 1, + sym__s_doc_end, + STATE(476), 1, + sym__doc_w_bgn_wo_end, + STATE(1155), 1, + sym__exp_doc, + STATE(1428), 2, + sym__doc_w_bgn_w_end_seq, + sym__doc_w_bgn_wo_end_seq, + STATE(38), 3, + sym__doc_w_bgn_w_end, + sym__exp_doc_end, + sym__doc_end, + [14563] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym__s_drs_end, + ACTIONS(15), 1, + sym__s_doc_end, + ACTIONS(1548), 1, + sym__eof, + STATE(476), 1, + sym__doc_w_bgn_wo_end, + STATE(1155), 1, + sym__exp_doc, + STATE(1490), 2, + sym__doc_w_bgn_w_end_seq, + sym__doc_w_bgn_wo_end_seq, + STATE(38), 3, + sym__doc_w_bgn_w_end, + sym__exp_doc_end, + sym__doc_end, + [14591] = 4, + ACTIONS(3), 1, + sym_comment, + STATE(481), 1, + aux_sym__br_mtl_dqt_ctn_repeat1, + ACTIONS(1550), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1553), 6, + sym__br_dqt_str_ctn, + sym__r_dqt_esc_nwl, + sym__br_dqt_esc_nwl, + sym__br_dqt_esc_seq, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + [14610] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1559), 1, + sym__r_sqt_str_end, + ACTIONS(1561), 1, + sym__br_sqt_str_end, + STATE(526), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1555), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + STATE(755), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14635] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1565), 1, + sym__r_sqt_str_end, + ACTIONS(1567), 1, + sym__br_sqt_str_end, + STATE(529), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1563), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(756), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14660] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1571), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(779), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14683] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(495), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1573), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1575), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(761), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14706] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1581), 1, + sym__r_dqt_esc_nwl, + STATE(499), 1, + aux_sym__br_mtl_dqt_ctn_repeat1, + ACTIONS(1577), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1579), 5, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_nwl, + sym__br_dqt_esc_seq, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + [14727] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1575), 1, + sym__br_sqt_str_end, + ACTIONS(1585), 1, + sym__r_sqt_str_end, + STATE(488), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1583), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(761), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14752] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1587), 1, + sym__r_sqt_str_end, + ACTIONS(1589), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(763), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14777] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(497), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1591), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1593), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(781), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14800] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(508), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1595), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1597), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(754), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14823] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1599), 1, + sym__r_sqt_str_end, + ACTIONS(1601), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(771), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14848] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(223), 1, + sym__br_flw_njv_bgn, + ACTIONS(434), 1, + sym__r_flw_njv_bgn, + STATE(937), 1, + sym__r_flw_njl_ann_par, + STATE(956), 1, + sym__br_flw_njl_ann_par, + ACTIONS(1540), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [14871] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(223), 1, + sym__br_flw_njv_bgn, + ACTIONS(434), 1, + sym__r_flw_njv_bgn, + STATE(938), 1, + sym__r_flw_njl_ann_par, + STATE(961), 1, + sym__br_flw_njl_ann_par, + ACTIONS(1603), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [14894] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1607), 1, + sym__r_sqt_str_end, + ACTIONS(1609), 1, + sym__br_sqt_str_end, + STATE(503), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1605), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(762), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14919] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1589), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(763), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14942] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1611), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(768), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14965] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1613), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(741), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14988] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1615), 1, + sym__r_flw_jsv_bgn, + ACTIONS(1617), 1, + sym__br_flw_jsv_bgn, + STATE(787), 1, + sym__br_flw_jsl_ann_par, + STATE(940), 1, + sym__r_flw_jsl_ann_par, + ACTIONS(1540), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [15011] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1623), 1, + sym__r_dqt_esc_nwl, + STATE(481), 1, + aux_sym__br_mtl_dqt_ctn_repeat1, + ACTIONS(1619), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1621), 5, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_nwl, + sym__br_dqt_esc_seq, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + [15032] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1601), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(771), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15055] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1627), 1, + sym__r_sqt_str_end, + ACTIONS(1629), 1, + sym__br_sqt_str_end, + STATE(507), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1625), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(773), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15080] = 4, + ACTIONS(3), 1, + sym_comment, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1631), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1634), 6, + sym__br_dqt_str_ctn, + sym__r_dqt_esc_nwl, + sym__br_dqt_esc_nwl, + sym__br_dqt_esc_seq, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + [15099] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1636), 1, + sym__r_sqt_str_end, + ACTIONS(1638), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(764), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15124] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1615), 1, + sym__r_flw_jsv_bgn, + ACTIONS(1617), 1, + sym__br_flw_jsv_bgn, + STATE(788), 1, + sym__br_flw_jsl_ann_par, + STATE(941), 1, + sym__r_flw_jsl_ann_par, + ACTIONS(1603), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [15147] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(510), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1629), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + ACTIONS(1640), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(773), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15170] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1642), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(776), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15193] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1644), 1, + sym__r_sqt_str_end, + ACTIONS(1646), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(775), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15218] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1648), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(750), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15241] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(506), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1650), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1652), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(774), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15264] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1646), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(775), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15287] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(535), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1654), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1656), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(765), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15310] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1658), 1, + sym__r_sqt_str_end, + ACTIONS(1660), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(752), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15335] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1656), 1, + sym__br_sqt_str_end, + ACTIONS(1664), 1, + sym__r_sqt_str_end, + STATE(531), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1662), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(765), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15360] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1668), 1, + sym__r_sqt_str_end, + ACTIONS(1670), 1, + sym__br_sqt_str_end, + STATE(491), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1666), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(769), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15385] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1674), 1, + sym__r_sqt_str_end, + ACTIONS(1676), 1, + sym__br_sqt_str_end, + STATE(521), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1672), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(777), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15410] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1597), 1, + sym__br_sqt_str_end, + ACTIONS(1680), 1, + sym__r_sqt_str_end, + STATE(518), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1678), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(754), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15435] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(530), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1682), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1684), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(770), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15458] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1648), 1, + sym__br_sqt_str_end, + ACTIONS(1686), 1, + sym__r_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(750), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15483] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(524), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1676), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + ACTIONS(1688), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(777), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15506] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(537), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1561), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + ACTIONS(1690), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(755), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15529] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1692), 1, + sym__r_sqt_str_end, + ACTIONS(1694), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(778), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15554] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1696), 1, + sym__s_dir_yml_bgn, + ACTIONS(1699), 1, + sym__s_dir_tag_bgn, + ACTIONS(1702), 1, + sym__s_dir_rsv_bgn, + ACTIONS(1705), 1, + sym__s_drs_end, + STATE(522), 5, + sym__s_dir, + sym__s_dir_yml, + sym__s_dir_tag, + sym__s_dir_rsv, + aux_sym__drs_doc_repeat1, + [15577] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(500), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1670), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + ACTIONS(1707), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(769), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15600] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1694), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(778), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15623] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1711), 1, + sym__r_sqt_str_end, + ACTIONS(1713), 1, + sym__br_sqt_str_end, + STATE(512), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1709), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(757), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15648] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1715), 1, + sym__r_sqt_str_end, + ACTIONS(1717), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(759), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15673] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(484), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1719), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1721), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(693), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15696] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1725), 1, + sym__r_sqt_str_end, + ACTIONS(1727), 1, + sym__br_sqt_str_end, + STATE(534), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1723), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(780), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15721] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1729), 1, + sym__r_sqt_str_end, + ACTIONS(1731), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(760), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15746] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1733), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(772), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15769] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1735), 1, + sym__r_sqt_str_end, + ACTIONS(1737), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(767), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15794] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(536), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1727), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + ACTIONS(1739), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(780), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15817] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(496), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1741), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1743), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(766), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15840] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1745), 1, + sym__r_sqt_str_end, + ACTIONS(1747), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(782), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15865] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1737), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(767), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15888] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1747), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(782), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15911] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1717), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(759), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15934] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(303), 1, + sym__r_flw_njv_bgn, + STATE(922), 1, + sym__r_flw_njl_ann_par, + STATE(1335), 1, + sym__r_sgl_flw_njl_ann_par, + ACTIONS(1749), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(1752), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [15956] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1756), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [15975] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1151), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [15988] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1323), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1327), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(557), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16007] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1153), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16020] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1327), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16039] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1331), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1335), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(559), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16058] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1155), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16071] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1335), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16090] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1157), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16103] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1159), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16116] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1161), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16129] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1163), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16142] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [16155] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1760), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(552), 2, + sym__flw_seq_dat_rpt, + aux_sym__r_flw_seq_dat_repeat1, + ACTIONS(1758), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [16172] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1763), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1765), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(584), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16191] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1767), 1, + sym__r_flw_jsv_bgn, + STATE(950), 1, + sym__r_flw_jsl_ann_par, + ACTIONS(1752), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [16208] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1769), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + ACTIONS(1023), 4, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_jsv_bgn, + [16223] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1772), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + ACTIONS(1775), 4, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_njv_bgn, + [16238] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1777), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16257] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1779), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1777), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(561), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16276] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1781), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16295] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1783), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1781), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(562), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16314] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1785), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16333] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1787), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16352] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1789), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [16365] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1775), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [16378] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1794), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1791), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1797), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16397] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1175), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16410] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1801), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(567), 2, + sym__flw_map_dat_rpt, + aux_sym__r_flw_map_dat_repeat1, + ACTIONS(1799), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [16427] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1177), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16440] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1804), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + ACTIONS(1027), 4, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_jsv_bgn, + [16455] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1181), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16468] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1183), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16481] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1807), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + ACTIONS(1031), 4, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_jsv_bgn, + [16496] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16509] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1035), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16522] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1259), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1261), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(587), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16541] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1810), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + ACTIONS(1039), 4, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_jsv_bgn, + [16556] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1261), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16575] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1273), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1275), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(589), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16594] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1275), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16613] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16626] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1043), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16639] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1813), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16658] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1815), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1813), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(585), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16677] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1817), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16696] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1819), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16715] = 4, + ACTIONS(3), 1, + sym_comment, + STATE(586), 1, + aux_sym__br_mtl_sqt_ctn_repeat1, + ACTIONS(1821), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1824), 4, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + [16732] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1826), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16751] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1828), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1826), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(591), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16770] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1830), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16789] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1832), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1830), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(592), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16808] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1834), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16827] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1836), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16846] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [16859] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1197), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16872] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1199), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16885] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1201), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16898] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1203), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16911] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1189), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16924] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1121), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16937] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1063), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16950] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1165), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16963] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1111), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16976] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1113), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16989] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17002] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1347), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1349), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(617), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17021] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1838), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + ACTIONS(987), 4, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_jsv_bgn, + [17036] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1349), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17055] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1265), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1267), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(619), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17074] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1267), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17093] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(991), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17106] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1841), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + ACTIONS(995), 4, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_jsv_bgn, + [17121] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17134] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(999), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17147] = 4, + ACTIONS(3), 1, + sym_comment, + STATE(586), 1, + aux_sym__br_mtl_sqt_ctn_repeat1, + ACTIONS(1844), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1846), 4, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + [17164] = 4, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1848), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1851), 4, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + [17181] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1053), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17194] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1853), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17213] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1855), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1853), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(621), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17232] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1857), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17251] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1859), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1857), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(622), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17270] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1861), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17289] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1863), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17308] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1149), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17321] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1057), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17334] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1399), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1401), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(650), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17353] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1059), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17366] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1401), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17385] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1503), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1507), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(652), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17404] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1447), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17423] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1507), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17442] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1451), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1455), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(641), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17461] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1061), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17474] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1455), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17493] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1353), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1355), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(643), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17512] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1355), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17531] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1213), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17544] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1865), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [17557] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [17570] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1867), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [17583] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1339), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1343), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(582), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17602] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1869), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17621] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1871), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1869), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(539), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17640] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1873), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17659] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1875), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1873), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(646), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17678] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1767), 1, + sym__r_flw_jsv_bgn, + STATE(952), 1, + sym__r_flw_jsl_ann_par, + ACTIONS(1877), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [17695] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1879), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17714] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1343), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17733] = 4, + ACTIONS(3), 1, + sym_comment, + STATE(614), 1, + aux_sym__br_mtl_sqt_ctn_repeat1, + ACTIONS(1881), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1883), 4, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + [17750] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1887), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(660), 2, + sym__flw_seq_dat_rpt, + aux_sym__r_flw_seq_dat_repeat1, + ACTIONS(1885), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [17767] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1889), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17786] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1891), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1889), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(654), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17805] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1893), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17824] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1895), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1893), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(656), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17843] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1897), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17862] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1493), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1497), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(664), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17881] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1899), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17900] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1497), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17919] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1531), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1533), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(666), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17938] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1533), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17957] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1901), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(552), 2, + sym__flw_seq_dat_rpt, + aux_sym__r_flw_seq_dat_repeat1, + ACTIONS(559), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [17974] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1905), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(663), 2, + sym__flw_seq_dat_rpt, + aux_sym__r_flw_seq_dat_repeat1, + ACTIONS(1903), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [17991] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [18004] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1907), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(552), 2, + sym__flw_seq_dat_rpt, + aux_sym__r_flw_seq_dat_repeat1, + ACTIONS(561), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [18021] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1909), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18040] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1911), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1909), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(668), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18059] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1913), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18078] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1915), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1913), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(669), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18097] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1917), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18116] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1919), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18135] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1923), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(673), 2, + sym__flw_map_dat_rpt, + aux_sym__r_flw_map_dat_repeat1, + ACTIONS(1921), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [18152] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1927), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(675), 2, + sym__flw_map_dat_rpt, + aux_sym__r_flw_map_dat_repeat1, + ACTIONS(1925), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [18169] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(497), 1, + sym__r_flw_njv_bgn, + STATE(923), 1, + sym__r_flw_njl_ann_par, + ACTIONS(1877), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [18186] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1929), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(567), 2, + sym__flw_map_dat_rpt, + aux_sym__r_flw_map_dat_repeat1, + ACTIONS(553), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [18203] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(497), 1, + sym__r_flw_njv_bgn, + STATE(921), 1, + sym__r_flw_njl_ann_par, + ACTIONS(1752), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [18220] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1931), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(567), 2, + sym__flw_map_dat_rpt, + aux_sym__r_flw_map_dat_repeat1, + ACTIONS(551), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [18237] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1445), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1447), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(685), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18256] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [18269] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1523), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1527), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(686), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18288] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1935), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [18301] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1527), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18320] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1435), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1437), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(688), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18339] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1437), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18358] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1937), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [18371] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1939), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [18384] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1765), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18403] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1941), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18422] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1943), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1941), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(690), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18441] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1945), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18460] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1947), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1945), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(691), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18479] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1949), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18498] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1951), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18517] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1055), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [18530] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1571), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [18546] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1955), 1, + sym__r_dir_rsv_prm, + STATE(758), 1, + aux_sym__s_dir_rsv_repeat1, + ACTIONS(1953), 4, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + [18562] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [18574] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1935), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [18586] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1937), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [18598] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1959), 1, + sym__r_dir_rsv_prm, + STATE(698), 1, + aux_sym__s_dir_rsv_repeat1, + ACTIONS(1957), 4, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + [18614] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1939), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [18626] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1865), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [18638] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1867), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [18650] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1149), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18662] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1151), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18674] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1153), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18686] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1155), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18698] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1157), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18710] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1159), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18722] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1161), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18734] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1163), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18746] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [18758] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1023), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + ACTIONS(1769), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18772] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1175), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18784] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1177), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18796] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1027), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + ACTIONS(1804), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18810] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1181), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18822] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1183), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18834] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + ACTIONS(1807), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18848] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18860] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1035), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18872] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + ACTIONS(1810), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18886] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18898] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1043), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18910] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [18922] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1197), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18934] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1199), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18946] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1201), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18958] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1203), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18970] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1189), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18982] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1121), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18994] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1063), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19006] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1165), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19018] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1111), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19030] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1113), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19042] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19054] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + ACTIONS(1838), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19068] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(991), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19080] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + ACTIONS(1841), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19094] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19106] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(999), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19118] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1053), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19130] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1962), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19146] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1057), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19158] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1059), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19170] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1061), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19182] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1213), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19194] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [19206] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1772), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + ACTIONS(1775), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [19220] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1789), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [19232] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1775), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [19244] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1964), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19260] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1966), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1969), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19276] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1971), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19292] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [19304] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1648), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19320] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1717), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19336] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1731), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19352] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1660), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19368] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1975), 1, + sym__r_dir_rsv_prm, + STATE(698), 1, + aux_sym__s_dir_rsv_repeat1, + ACTIONS(1973), 4, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + [19384] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1977), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19400] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1979), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19416] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1589), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19432] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1638), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19448] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1981), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19464] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1983), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19480] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1737), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19496] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1611), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19512] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1985), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19528] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1987), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19544] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1601), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19560] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1733), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19576] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1989), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19592] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1991), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19608] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1646), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19624] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1642), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19640] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1993), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19656] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1995), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19672] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1694), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19688] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1997), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19704] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1999), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19720] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1747), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19736] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1613), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19752] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(2001), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19768] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1055), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19780] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1175), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19791] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1772), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(1775), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [19804] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1789), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19815] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2003), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19826] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2005), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19837] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2007), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19848] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2009), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19859] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2007), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19870] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1775), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19881] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2003), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19892] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1621), 5, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_nwl, + sym__br_dqt_esc_seq, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + [19903] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2009), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19914] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1935), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19925] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1937), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19936] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1939), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19947] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2011), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19958] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2013), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19969] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1772), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(1775), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [19982] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1789), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19993] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1775), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20004] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2015), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20015] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(303), 1, + sym__r_flw_njv_bgn, + ACTIONS(305), 1, + sym__br_flw_njv_bgn, + STATE(922), 1, + sym__r_flw_njl_ann_par, + STATE(949), 1, + sym__br_flw_njl_ann_par, + STATE(1335), 1, + sym__r_sgl_flw_njl_ann_par, + [20034] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2017), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20045] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2017), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20056] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2017), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20067] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2017), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20078] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2019), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20089] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1865), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20100] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1867), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20111] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20122] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2021), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20133] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2023), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20144] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2025), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20155] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1149), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20166] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1151), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20177] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1153), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20188] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1155), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20199] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1157), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20210] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1159), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20221] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1161), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20232] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1163), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20243] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2027), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20254] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2021), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20265] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1769), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(1023), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [20278] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1175), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20289] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1177), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20300] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1804), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(1027), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [20313] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1181), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20324] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1183), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20335] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1807), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(1031), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [20348] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20359] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1035), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20370] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1810), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(1039), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [20383] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20394] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1043), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20405] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2021), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20416] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2023), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20427] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2023), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20438] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1197), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20449] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1199), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20460] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1201), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20471] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1203), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20482] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1189), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20493] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1121), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20504] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1063), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20515] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1165), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20526] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1111), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20537] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1113), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20548] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20559] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1838), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(987), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [20572] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(991), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20583] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1841), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(995), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [20596] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20607] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(999), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20618] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1053), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20629] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1055), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20640] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1057), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20651] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1059), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20662] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1061), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20673] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1213), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20684] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2029), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20695] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1149), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20706] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1151), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20717] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1153), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20728] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1155), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20739] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1157), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20750] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1159), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20761] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1161), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20772] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1163), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20783] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20794] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20805] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2031), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20816] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1769), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(1023), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [20829] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1177), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20840] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1804), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(1027), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [20853] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1181), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20864] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1183), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20875] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1807), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(1031), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [20888] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20899] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1035), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20910] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1810), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(1039), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [20923] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20934] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1043), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20945] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2033), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20956] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2035), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20967] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2037), 5, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_nwl, + sym__br_dqt_esc_seq, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + [20978] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20989] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21000] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1197), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21011] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1199), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21022] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1201), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21033] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1203), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21044] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1189), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21055] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1121), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21066] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1063), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21077] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1165), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21088] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1111), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21099] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1113), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21110] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1838), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(987), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [21123] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(991), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21134] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1841), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(995), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [21147] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21158] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(999), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21169] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1053), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21180] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1055), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21191] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1057), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21202] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1059), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21213] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1061), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21224] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1213), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21235] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21246] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21257] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21268] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21279] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(332), 1, + sym__blk_imp_itm_tal, + ACTIONS(2039), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [21294] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(334), 1, + sym__blk_imp_itm_tal, + ACTIONS(2039), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [21309] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2041), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(2044), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [21322] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2046), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21333] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2048), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21344] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2048), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21355] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2050), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21366] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2015), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21377] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2015), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21388] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2015), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21399] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2015), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21410] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(221), 1, + sym__r_flw_njv_bgn, + ACTIONS(223), 1, + sym__br_flw_njv_bgn, + STATE(793), 1, + sym__br_flw_njl_ann_par, + STATE(943), 1, + sym__r_flw_njl_ann_par, + STATE(1337), 1, + sym__r_sgl_flw_njl_ann_par, + [21429] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2017), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21440] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1865), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21451] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2017), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21462] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2017), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21473] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2017), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21484] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2019), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21495] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2041), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(2044), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [21508] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2046), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21519] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2048), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21530] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2050), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21541] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(334), 1, + sym__blk_imp_itm_tal, + ACTIONS(2052), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [21556] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2048), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21567] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2050), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21578] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1867), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21589] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2048), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21600] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2003), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21611] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2005), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21622] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2003), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21633] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2005), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21644] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2015), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21655] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2003), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21666] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2048), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21677] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2025), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21688] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2050), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21699] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2015), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21710] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2029), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21721] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21732] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2003), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21743] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1935), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21754] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1937), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21765] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1939), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21776] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2015), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21787] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2005), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21798] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21809] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2054), 1, + sym__r_flw_seq_end, + ACTIONS(2056), 1, + sym__r_flw_sep_bgn, + STATE(963), 2, + sym__sgl_flw_col_dat_rpt, + aux_sym__r_sgl_flw_col_dat_repeat1, + [21823] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2059), 1, + sym__r_flw_map_end, + ACTIONS(2061), 1, + sym__r_flw_sep_bgn, + STATE(1012), 2, + sym__sgl_flw_col_dat_rpt, + aux_sym__r_sgl_flw_col_dat_repeat1, + [21837] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2063), 1, + sym__bl, + STATE(973), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [21851] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2065), 1, + sym__bl, + STATE(974), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [21865] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(332), 1, + sym__blk_imp_itm_tal, + ACTIONS(973), 2, + sym__b_blk_seq_bgn, + sym__bl, + [21879] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2067), 4, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + [21889] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(334), 1, + sym__blk_imp_itm_tal, + ACTIONS(973), 2, + sym__b_blk_seq_bgn, + sym__bl, + [21903] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2071), 1, + sym__r_dqt_str_end, + STATE(1014), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2069), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [21917] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2075), 1, + sym__r_dqt_str_end, + STATE(977), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2073), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [21931] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2079), 1, + sym__r_sqt_str_end, + STATE(978), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2077), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [21945] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2081), 1, + sym__bl, + STATE(979), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [21959] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2083), 1, + sym__bl, + STATE(979), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [21973] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2087), 1, + sym__r_sqt_str_end, + STATE(1029), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2085), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [21987] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + STATE(1226), 1, + sym__r_sgl_flw_njl_ann_par, + ACTIONS(2089), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [22001] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2093), 1, + sym__r_dqt_str_end, + STATE(1023), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2091), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22015] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2097), 1, + sym__r_sqt_str_end, + STATE(1024), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2095), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22029] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2099), 1, + sym__b_blk_seq_bgn, + ACTIONS(2102), 1, + sym__bl, + STATE(979), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22043] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(305), 1, + sym__br_flw_njv_bgn, + ACTIONS(497), 1, + sym__r_flw_njv_bgn, + STATE(921), 1, + sym__r_flw_njl_ann_par, + STATE(944), 1, + sym__br_flw_njl_ann_par, + [22059] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(223), 1, + sym__br_flw_njv_bgn, + ACTIONS(434), 1, + sym__r_flw_njv_bgn, + STATE(937), 1, + sym__r_flw_njl_ann_par, + STATE(956), 1, + sym__br_flw_njl_ann_par, + [22075] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2106), 1, + sym__r_dqt_str_end, + STATE(993), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2104), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22089] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2110), 1, + sym__r_sqt_str_end, + STATE(994), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2108), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22103] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(223), 1, + sym__br_flw_njv_bgn, + ACTIONS(434), 1, + sym__r_flw_njv_bgn, + STATE(938), 1, + sym__r_flw_njl_ann_par, + STATE(961), 1, + sym__br_flw_njl_ann_par, + [22119] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1001), 1, + sym__r_blk_imp_bgn, + ACTIONS(999), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22131] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2059), 1, + sym__r_flw_seq_end, + ACTIONS(2112), 1, + sym__r_flw_sep_bgn, + STATE(1016), 2, + sym__sgl_flw_col_dat_rpt, + aux_sym__r_sgl_flw_col_dat_repeat1, + [22145] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 1, + sym__r_blk_imp_bgn, + ACTIONS(995), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22157] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1029), 1, + sym__r_blk_imp_bgn, + ACTIONS(1027), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22169] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 1, + sym__r_blk_imp_bgn, + ACTIONS(987), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22181] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(993), 1, + sym__r_blk_imp_bgn, + ACTIONS(991), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22193] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(305), 1, + sym__br_flw_njv_bgn, + ACTIONS(497), 1, + sym__r_flw_njv_bgn, + STATE(923), 1, + sym__r_flw_njl_ann_par, + STATE(945), 1, + sym__br_flw_njl_ann_par, + [22209] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2114), 1, + sym__r_dqt_str_end, + STATE(1023), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2091), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22223] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2116), 1, + sym__r_dqt_str_end, + STATE(1023), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2091), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22237] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2118), 1, + sym__r_sqt_str_end, + STATE(1024), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2095), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22251] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2120), 1, + sym__bl, + STATE(979), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22265] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 1, + sym__r_blk_imp_bgn, + ACTIONS(1031), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22277] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(1019), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22289] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2122), 1, + sym__bl, + STATE(979), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22303] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 4, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__r_blk_imp_bgn, + [22313] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1037), 1, + sym__r_blk_imp_bgn, + ACTIONS(1035), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22325] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 4, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__r_blk_imp_bgn, + [22335] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2124), 1, + sym__bl, + STATE(1022), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22349] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2126), 1, + sym__bl, + STATE(1026), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22363] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2128), 1, + sym__bl, + STATE(998), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22377] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 1, + sym__r_blk_imp_bgn, + ACTIONS(1039), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22389] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2130), 1, + sym__r_dqt_str_end, + STATE(1023), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2091), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22403] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2132), 1, + sym__r_sqt_str_end, + STATE(1024), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2095), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22417] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1045), 1, + sym__r_blk_imp_bgn, + ACTIONS(1043), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22429] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1767), 1, + sym__r_flw_jsv_bgn, + ACTIONS(2134), 1, + sym__br_flw_jsv_bgn, + STATE(946), 1, + sym__br_flw_jsl_ann_par, + STATE(950), 1, + sym__r_flw_jsl_ann_par, + [22445] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2138), 1, + sym__r_dqt_str_end, + STATE(1020), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2136), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22459] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2142), 1, + sym__r_sqt_str_end, + STATE(1021), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2140), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22473] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(855), 1, + sym__r_flw_map_end, + ACTIONS(2144), 1, + sym__r_flw_sep_bgn, + STATE(1034), 2, + sym__sgl_flw_col_dat_rpt, + aux_sym__r_sgl_flw_col_dat_repeat1, + [22487] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2146), 1, + sym__r_sqt_str_end, + STATE(1024), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2095), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22501] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2148), 1, + sym__r_dqt_str_end, + STATE(1023), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2091), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22515] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2150), 4, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + [22525] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(855), 1, + sym__r_flw_seq_end, + ACTIONS(2152), 1, + sym__r_flw_sep_bgn, + STATE(963), 2, + sym__sgl_flw_col_dat_rpt, + aux_sym__r_sgl_flw_col_dat_repeat1, + [22539] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2156), 1, + sym__r_dqt_str_end, + STATE(1006), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2154), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22553] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1767), 1, + sym__r_flw_jsv_bgn, + ACTIONS(2134), 1, + sym__br_flw_jsv_bgn, + STATE(947), 1, + sym__br_flw_jsl_ann_par, + STATE(952), 1, + sym__r_flw_jsl_ann_par, + [22569] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2160), 1, + sym__r_sqt_str_end, + STATE(1007), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2158), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22583] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2162), 1, + sym__r_dqt_str_end, + STATE(1023), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2091), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22597] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2164), 1, + sym__r_sqt_str_end, + STATE(1024), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2095), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22611] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2166), 1, + sym__bl, + STATE(979), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22625] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1634), 1, + sym__r_dqt_str_end, + STATE(1023), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2168), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22639] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1851), 1, + sym__r_sqt_str_end, + STATE(1024), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2171), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22653] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2174), 1, + sym__r_flw_jsv_bgn, + STATE(1235), 1, + sym__r_sgl_flw_jsl_ann_par, + ACTIONS(2089), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [22667] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2176), 1, + sym__bl, + STATE(979), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22681] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2180), 1, + sym__r_dqt_str_end, + STATE(1032), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2178), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22695] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2184), 1, + sym__r_sqt_str_end, + STATE(1033), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2182), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22709] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2186), 1, + sym__r_sqt_str_end, + STATE(1024), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2095), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22723] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1003), 4, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__r_blk_imp_bgn, + [22733] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1615), 1, + sym__r_flw_jsv_bgn, + ACTIONS(1617), 1, + sym__br_flw_jsv_bgn, + STATE(787), 1, + sym__br_flw_jsl_ann_par, + STATE(940), 1, + sym__r_flw_jsl_ann_par, + [22749] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2188), 1, + sym__r_dqt_str_end, + STATE(1023), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2091), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22763] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2190), 1, + sym__r_sqt_str_end, + STATE(1024), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2095), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22777] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2054), 1, + sym__r_flw_map_end, + ACTIONS(2192), 1, + sym__r_flw_sep_bgn, + STATE(1034), 2, + sym__sgl_flw_col_dat_rpt, + aux_sym__r_sgl_flw_col_dat_repeat1, + [22791] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1615), 1, + sym__r_flw_jsv_bgn, + ACTIONS(1617), 1, + sym__br_flw_jsv_bgn, + STATE(788), 1, + sym__br_flw_jsl_ann_par, + STATE(941), 1, + sym__r_flw_jsl_ann_par, + [22807] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1013), 4, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__r_blk_imp_bgn, + [22817] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(981), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22829] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + STATE(1409), 1, + sym__r_sgl_flw_njl_ann_par, + ACTIONS(2089), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [22843] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 4, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__r_blk_imp_bgn, + [22853] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(985), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22865] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2195), 1, + sym__bl, + STATE(979), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22879] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2199), 1, + sym__r_dqt_str_end, + STATE(992), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2197), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22893] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2203), 1, + sym__r_sqt_str_end, + STATE(1013), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2201), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22907] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 4, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__r_blk_imp_bgn, + [22917] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2205), 1, + sym__r_flw_jsv_bgn, + STATE(1332), 1, + sym__r_sgl_flw_jsl_ann_par, + ACTIONS(2089), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [22931] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1017), 1, + sym__r_blk_imp_bgn, + ACTIONS(1015), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22943] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1025), 1, + sym__r_blk_imp_bgn, + ACTIONS(1023), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22955] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2207), 1, + sym__bl, + STATE(995), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22969] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22978] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2209), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [22987] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2211), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [22996] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2213), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23005] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2215), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23014] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2217), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23023] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1075), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23032] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2219), 1, + sym__br_blk_str_ctn, + ACTIONS(2222), 1, + sym__bl, + STATE(1056), 1, + aux_sym__r_blk_str_repeat1, + [23045] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1079), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23054] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2224), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [23063] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [23072] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1157), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23081] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2226), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23090] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2228), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23099] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1173), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23108] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2230), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23117] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1065), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23126] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2232), 1, + sym__br_blk_str_ctn, + ACTIONS(2234), 1, + sym__bl, + STATE(1056), 1, + aux_sym__r_blk_str_repeat1, + [23139] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23148] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23157] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1051), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23166] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1153), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23175] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1155), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23184] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23193] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1113), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23202] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23211] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23220] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1183), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23229] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [23238] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2236), 1, + sym__br_blk_str_ctn, + ACTIONS(2238), 1, + sym__bl, + STATE(1089), 1, + aux_sym__r_blk_str_repeat1, + [23251] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 3, + sym__b_blk_seq_bgn, + sym__r_blk_imp_bgn, + sym__bl, + [23260] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1067), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23269] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2240), 1, + sym__br_blk_str_ctn, + ACTIONS(2242), 1, + sym__bl, + STATE(1066), 1, + aux_sym__r_blk_str_repeat1, + [23282] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(991), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23291] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1145), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23300] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2244), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [23309] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2246), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23318] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23327] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1159), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23336] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1171), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23345] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2232), 1, + sym__br_blk_str_ctn, + ACTIONS(2248), 1, + sym__bl, + STATE(1056), 1, + aux_sym__r_blk_str_repeat1, + [23358] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(999), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23367] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1179), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23376] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1053), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23385] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1055), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23394] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1015), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23403] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1019), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23412] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1057), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23421] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [23430] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1059), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23439] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [23448] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [23457] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [23466] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23475] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1147), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23484] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1061), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23493] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1213), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23502] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1003), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23511] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1013), 3, + sym__b_blk_seq_bgn, + sym__r_blk_imp_bgn, + sym__bl, + [23520] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1035), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23529] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1177), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23538] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2250), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23547] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2252), 1, + sym__br_blk_str_ctn, + ACTIONS(2254), 1, + sym__bl, + STATE(1120), 1, + aux_sym__r_blk_str_repeat1, + [23560] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2256), 1, + sym__br_blk_str_ctn, + ACTIONS(2258), 1, + sym__bl, + STATE(1121), 1, + aux_sym__r_blk_str_repeat1, + [23573] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2260), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23582] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2262), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23591] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1149), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23600] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2264), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23609] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1017), 1, + sym__r_blk_imp_bgn, + ACTIONS(1015), 2, + sym__b_blk_seq_bgn, + sym__bl, + [23620] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(1019), 2, + sym__b_blk_seq_bgn, + sym__bl, + [23631] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1167), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23640] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2232), 1, + sym__br_blk_str_ctn, + ACTIONS(2266), 1, + sym__bl, + STATE(1056), 1, + aux_sym__r_blk_str_repeat1, + [23653] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2232), 1, + sym__br_blk_str_ctn, + ACTIONS(2268), 1, + sym__bl, + STATE(1056), 1, + aux_sym__r_blk_str_repeat1, + [23666] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 3, + sym__b_blk_seq_bgn, + sym__r_blk_imp_bgn, + sym__bl, + [23675] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2270), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23684] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2272), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [23693] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2274), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [23702] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23711] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1161), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23720] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1025), 1, + sym__r_blk_imp_bgn, + ACTIONS(1023), 2, + sym__b_blk_seq_bgn, + sym__bl, + [23731] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1163), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23740] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1043), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23749] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1175), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23758] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2276), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [23767] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1181), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23776] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1111), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23785] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1129), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23794] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1185), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23803] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 3, + sym__b_blk_seq_bgn, + sym__r_blk_imp_bgn, + sym__bl, + [23812] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2278), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [23821] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2209), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23830] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2280), 1, + sym__br_blk_str_ctn, + ACTIONS(2282), 1, + sym__bl, + STATE(1147), 1, + aux_sym__r_blk_str_repeat1, + [23843] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2284), 1, + sym__br_blk_str_ctn, + ACTIONS(2286), 1, + sym__bl, + STATE(1148), 1, + aux_sym__r_blk_str_repeat1, + [23856] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1131), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23865] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2288), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23874] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1029), 1, + sym__r_blk_imp_bgn, + ACTIONS(1027), 2, + sym__b_blk_seq_bgn, + sym__bl, + [23885] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2230), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23894] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 1, + sym__r_blk_imp_bgn, + ACTIONS(1031), 2, + sym__b_blk_seq_bgn, + sym__bl, + [23905] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2232), 1, + sym__br_blk_str_ctn, + ACTIONS(2290), 1, + sym__bl, + STATE(1056), 1, + aux_sym__r_blk_str_repeat1, + [23918] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2232), 1, + sym__br_blk_str_ctn, + ACTIONS(2292), 1, + sym__bl, + STATE(1056), 1, + aux_sym__r_blk_str_repeat1, + [23931] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1037), 1, + sym__r_blk_imp_bgn, + ACTIONS(1035), 2, + sym__b_blk_seq_bgn, + sym__bl, + [23942] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 1, + sym__r_blk_imp_bgn, + ACTIONS(1039), 2, + sym__b_blk_seq_bgn, + sym__bl, + [23953] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2294), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [23962] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2296), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [23971] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1045), 1, + sym__r_blk_imp_bgn, + ACTIONS(1043), 2, + sym__b_blk_seq_bgn, + sym__bl, + [23982] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1137), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23991] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2300), 1, + sym__s_doc_end, + ACTIONS(2298), 2, + sym__eof, + sym__s_drs_end, + [24002] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1151), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24011] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24020] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 3, + sym__b_blk_seq_bgn, + sym__r_blk_imp_bgn, + sym__bl, + [24029] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(981), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24040] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(985), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24051] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2211), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24060] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2213), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24069] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2215), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24078] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2217), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24087] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2302), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [24096] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2304), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [24105] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2308), 1, + sym__s_doc_end, + ACTIONS(2306), 2, + sym__eof, + sym__s_drs_end, + [24116] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2310), 1, + sym__s_doc_end, + ACTIONS(2306), 2, + sym__eof, + sym__s_drs_end, + [24127] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2052), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24136] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1139), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24145] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2244), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [24154] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2312), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [24163] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2314), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [24172] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2226), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24181] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1141), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24190] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1205), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24199] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1191), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24208] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2228), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24217] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 1, + sym__r_blk_imp_bgn, + ACTIONS(987), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24228] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(993), 1, + sym__r_blk_imp_bgn, + ACTIONS(991), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24239] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 1, + sym__r_blk_imp_bgn, + ACTIONS(995), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24250] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2316), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [24259] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2318), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [24268] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1001), 1, + sym__r_blk_imp_bgn, + ACTIONS(999), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24279] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1193), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24288] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1195), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24297] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2276), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [24306] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1197), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24315] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24324] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24333] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1199), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24342] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1201), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24351] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2320), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [24360] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2322), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [24369] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24378] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24387] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1203), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24396] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1003), 3, + sym__b_blk_seq_bgn, + sym__r_blk_imp_bgn, + sym__bl, + [24405] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(981), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24414] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1143), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24423] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1207), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24432] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1209), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24441] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1211), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24450] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1189), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24459] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1121), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24468] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1063), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24477] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1165), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24486] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(985), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24495] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2250), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24504] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2260), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24513] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2324), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [24522] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2326), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [24531] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2262), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24540] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2264), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24549] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1187), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24558] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1935), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [24566] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1161), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24574] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1163), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24582] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2250), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24590] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1015), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24598] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1019), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24606] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1775), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [24614] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2260), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24622] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2262), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24630] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2328), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24638] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2330), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24646] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(313), 1, + sym__blk_imp_itm_tal, + [24656] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2264), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24664] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1171), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24672] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1173), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24680] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2211), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24688] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2213), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24696] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2215), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24704] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2217), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24712] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2330), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24720] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2244), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [24728] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(314), 1, + sym__blk_imp_itm_tal, + [24738] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2226), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24746] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + STATE(1409), 1, + sym__r_sgl_flw_njl_ann_par, + [24756] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2328), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24764] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2228), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24772] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2205), 1, + sym__r_flw_jsv_bgn, + STATE(1332), 1, + sym__r_sgl_flw_jsl_ann_par, + [24782] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1772), 1, + sym__r_flw_njv_bgn, + ACTIONS(1775), 1, + sym__br_flw_njv_bgn, + [24792] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2174), 1, + sym__r_flw_jsv_bgn, + STATE(1235), 1, + sym__r_sgl_flw_jsl_ann_par, + [24802] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2332), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24810] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [24818] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1175), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24826] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [24834] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24842] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2328), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [24850] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2328), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [24858] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2334), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [24866] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2334), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24874] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [24882] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24890] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1177), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24898] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2209), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24906] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1181), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24914] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1183), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24922] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24930] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1035), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24938] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1937), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [24946] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1939), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [24954] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2230), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24962] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24970] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1043), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24978] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2336), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24986] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2338), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24994] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2244), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25002] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25010] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25018] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [25026] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1191), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25034] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1193), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25042] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1195), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25050] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1197), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25058] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1199), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25066] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1201), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25074] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1203), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25082] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(981), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25090] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1003), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25098] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1149), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25106] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1151), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25114] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1207), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25122] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1209), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25130] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1211), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25138] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1189), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25146] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1121), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25154] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1063), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25162] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1165), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25170] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(985), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25178] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2340), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25186] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25194] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1167), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25202] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1179), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25210] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1065), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25218] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1067), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25226] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25234] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(304), 1, + sym__blk_imp_itm_tal, + [25244] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1075), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25252] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2250), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25260] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1153), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25268] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1079), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25276] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1155), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25284] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2260), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25292] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1157), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25300] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1159), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25308] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2262), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25316] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1161), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25324] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1163), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25332] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2264), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25340] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2340), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25348] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2342), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25356] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1023), 1, + sym__br_flw_jsv_bgn, + ACTIONS(1769), 1, + sym__r_flw_jsv_bgn, + [25366] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [25374] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1175), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25382] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2209), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25390] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1177), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25398] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2344), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25406] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1027), 1, + sym__br_flw_jsv_bgn, + ACTIONS(1804), 1, + sym__r_flw_jsv_bgn, + [25416] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1181), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25424] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2230), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25432] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1183), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25440] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1213), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25448] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 1, + sym__br_flw_jsv_bgn, + ACTIONS(1807), 1, + sym__r_flw_jsv_bgn, + [25458] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2276), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25466] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2346), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25474] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25482] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1035), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25490] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 1, + sym__br_flw_jsv_bgn, + ACTIONS(1810), 1, + sym__r_flw_jsv_bgn, + [25500] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25508] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2330), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25516] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1111), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25524] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1043), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25532] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2330), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25540] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2276), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25548] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2330), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25556] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1197), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25564] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1199), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25572] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1201), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25580] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1203), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25588] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1189), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25596] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1121), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25604] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1113), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25612] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1789), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [25620] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1063), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25628] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25636] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25644] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1165), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25652] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(991), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25660] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25668] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25676] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25684] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2211), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25692] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(999), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25700] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25708] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2213), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25716] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2215), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25724] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + STATE(1226), 1, + sym__r_sgl_flw_njl_ann_par, + [25734] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2217), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25742] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1111), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25750] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1185), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25758] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1187), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25766] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1205), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25774] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1051), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25782] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2226), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25790] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1113), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25798] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2228), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25806] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25814] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 1, + sym__br_flw_jsv_bgn, + ACTIONS(1838), 1, + sym__r_flw_jsv_bgn, + [25824] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2346), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25832] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2332), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25840] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(991), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25848] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 1, + sym__br_flw_jsv_bgn, + ACTIONS(1841), 1, + sym__r_flw_jsv_bgn, + [25858] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1053), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25866] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1055), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25874] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1057), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25882] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1059), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25890] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2344), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25898] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1129), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25906] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1131), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25914] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1061), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25922] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1213), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25930] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25938] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(999), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25946] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1137), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25954] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1139), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25962] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1141), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25970] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1143), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25978] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1145), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25986] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25994] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [26002] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1147), 2, + sym__b_blk_seq_bgn, + sym__bl, + [26010] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1149), 2, + sym__b_blk_seq_bgn, + sym__bl, + [26018] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1151), 2, + sym__b_blk_seq_bgn, + sym__bl, + [26026] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1053), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [26034] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1055), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [26042] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1865), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [26050] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1057), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [26058] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1867), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [26066] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1153), 2, + sym__b_blk_seq_bgn, + sym__bl, + [26074] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1155), 2, + sym__b_blk_seq_bgn, + sym__bl, + [26082] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1059), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [26090] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1157), 2, + sym__b_blk_seq_bgn, + sym__bl, + [26098] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [26106] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [26114] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1159), 2, + sym__b_blk_seq_bgn, + sym__bl, + [26122] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1061), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [26130] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2330), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [26138] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2348), 1, + sym__r_acr_ctn, + [26145] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2264), 1, + sym__r_blk_imp_bgn, + [26152] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2350), 1, + sym__r_blk_imp_bgn, + [26159] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2228), 1, + sym__r_blk_imp_bgn, + [26166] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2226), 1, + sym__r_flw_jsv_bgn, + [26173] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2352), 1, + sym__r_blk_imp_bgn, + [26180] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2354), 1, + sym__r_blk_imp_bgn, + [26187] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2356), 1, + sym__r_blk_imp_bgn, + [26194] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2358), 1, + sym__r_blk_imp_bgn, + [26201] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2360), 1, + sym__r_blk_imp_bgn, + [26208] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2250), 1, + sym__r_blk_imp_bgn, + [26215] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 1, + sym__r_blk_imp_bgn, + [26222] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2230), 1, + sym__r_flw_jsv_bgn, + [26229] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2209), 1, + sym__r_blk_imp_bgn, + [26236] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 1, + sym__r_blk_imp_bgn, + [26243] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 1, + sym__r_blk_imp_bgn, + [26250] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2362), 1, + ts_builtin_sym_end, + [26257] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2364), 1, + sym__r_dir_yml_ver, + [26264] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2366), 1, + sym__eof, + [26271] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2368), 1, + ts_builtin_sym_end, + [26278] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2370), 1, + sym__r_acr_ctn, + [26285] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2372), 1, + sym__r_acr_ctn, + [26292] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2374), 1, + sym__r_als_ctn, + [26299] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2376), 1, + sym__r_acr_ctn, + [26306] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2378), 1, + sym__r_acr_ctn, + [26313] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2380), 1, + sym__r_als_ctn, + [26320] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2382), 1, + sym__r_als_ctn, + [26327] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2384), 1, + sym__r_als_ctn, + [26334] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2386), 1, + sym__r_acr_ctn, + [26341] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2388), 1, + sym__r_acr_ctn, + [26348] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2390), 1, + sym__r_als_ctn, + [26355] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2392), 1, + sym__r_als_ctn, + [26362] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2260), 1, + sym__r_blk_imp_bgn, + [26369] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2394), 1, + sym__r_blk_imp_bgn, + [26376] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2396), 1, + sym__r_blk_imp_bgn, + [26383] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2398), 1, + sym__r_blk_imp_bgn, + [26390] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2400), 1, + sym__r_blk_imp_bgn, + [26397] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2402), 1, + sym__r_flw_seq_end, + [26404] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2228), 1, + sym__r_flw_jsv_bgn, + [26411] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2404), 1, + sym__r_flw_map_end, + [26418] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2406), 1, + sym__r_blk_imp_bgn, + [26425] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 1, + sym__r_flw_jsv_bgn, + [26432] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2408), 1, + ts_builtin_sym_end, + [26439] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2262), 1, + sym__r_blk_imp_bgn, + [26446] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2410), 1, + sym__r_dir_tag_pfx, + [26453] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 1, + sym__r_flw_njv_bgn, + [26460] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2412), 1, + sym__eof, + [26467] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2414), 1, + sym__r_flw_seq_end, + [26474] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 1, + sym__r_flw_jsv_bgn, + [26481] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2416), 1, + sym__r_flw_seq_end, + [26488] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2418), 1, + sym__r_flw_map_end, + [26495] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2420), 1, + sym__r_blk_imp_bgn, + [26502] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 1, + sym__r_flw_njv_bgn, + [26509] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2262), 1, + sym__r_flw_jsv_bgn, + [26516] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2422), 1, + sym__r_blk_imp_bgn, + [26523] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2424), 1, + ts_builtin_sym_end, + [26530] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2213), 1, + sym__r_flw_jsv_bgn, + [26537] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2264), 1, + sym__r_flw_jsv_bgn, + [26544] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2426), 1, + sym__r_flw_seq_end, + [26551] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2215), 1, + sym__r_flw_jsv_bgn, + [26558] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2244), 1, + sym__r_flw_njv_bgn, + [26565] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2428), 1, + sym__r_flw_map_end, + [26572] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2430), 1, + sym__r_acr_ctn, + [26579] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2432), 1, + sym__r_flw_seq_end, + [26586] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2434), 1, + sym__r_als_ctn, + [26593] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 1, + sym__r_flw_njv_bgn, + [26600] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2436), 1, + sym__r_flw_map_end, + [26607] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 1, + sym__r_blk_imp_bgn, + [26614] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2438), 1, + sym__r_acr_ctn, + [26621] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2440), 1, + sym__r_acr_ctn, + [26628] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2442), 1, + sym__r_als_ctn, + [26635] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2444), 1, + sym__r_als_ctn, + [26642] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2217), 1, + sym__r_flw_jsv_bgn, + [26649] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2446), 1, + sym__r_acr_ctn, + [26656] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2448), 1, + sym__r_acr_ctn, + [26663] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2450), 1, + sym__r_blk_imp_bgn, + [26670] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2452), 1, + sym__r_als_ctn, + [26677] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 1, + sym__r_blk_imp_bgn, + [26684] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2454), 1, + sym__r_als_ctn, + [26691] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2456), 1, + sym__eof, + [26698] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2458), 1, + sym__eof, + [26705] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2460), 1, + sym__r_blk_imp_bgn, + [26712] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2462), 1, + sym__r_blk_imp_bgn, + [26719] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2464), 1, + sym__r_blk_imp_bgn, + [26726] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2466), 1, + sym__r_als_ctn, + [26733] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 1, + sym__r_flw_jsv_bgn, + [26740] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2468), 1, + sym__r_blk_imp_bgn, + [26747] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2470), 1, + sym__r_blk_imp_bgn, + [26754] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2472), 1, + sym__r_acr_ctn, + [26761] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2474), 1, + sym__r_blk_imp_bgn, + [26768] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 1, + sym__r_blk_imp_bgn, + [26775] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2226), 1, + sym__r_blk_imp_bgn, + [26782] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2476), 1, + sym__r_blk_imp_bgn, + [26789] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2478), 1, + sym__r_acr_ctn, + [26796] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2480), 1, + sym__r_als_ctn, + [26803] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2482), 1, + sym__r_als_ctn, + [26810] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2250), 1, + sym__r_flw_jsv_bgn, + [26817] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 1, + sym__r_flw_jsv_bgn, + [26824] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2484), 1, + sym__r_als_ctn, + [26831] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2209), 1, + sym__r_flw_jsv_bgn, + [26838] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2486), 1, + sym__r_acr_ctn, + [26845] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2488), 1, + sym__r_acr_ctn, + [26852] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2490), 1, + sym__r_als_ctn, + [26859] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2492), 1, + sym__r_als_ctn, + [26866] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2494), 1, + sym__r_blk_imp_bgn, + [26873] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2496), 1, + sym__r_dir_tag_hdl, + [26880] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2498), 1, + sym__r_flw_map_end, + [26887] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2230), 1, + sym__r_blk_imp_bgn, + [26894] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2276), 1, + sym__r_flw_njv_bgn, + [26901] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2500), 1, + sym__r_acr_ctn, + [26908] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2502), 1, + sym__r_blk_imp_bgn, + [26915] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2211), 1, + sym__r_blk_imp_bgn, + [26922] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1003), 1, + sym__r_blk_imp_bgn, + [26929] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2213), 1, + sym__r_blk_imp_bgn, + [26936] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2215), 1, + sym__r_blk_imp_bgn, + [26943] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2504), 1, + sym__r_flw_seq_end, + [26950] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2506), 1, + sym__eof, + [26957] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2508), 1, + sym__r_flw_map_end, + [26964] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2217), 1, + sym__r_blk_imp_bgn, + [26971] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2510), 1, + sym__r_blk_imp_bgn, + [26978] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2512), 1, + sym__r_blk_imp_bgn, + [26985] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2514), 1, + sym__r_blk_imp_bgn, + [26992] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2516), 1, + sym__r_blk_imp_bgn, + [26999] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2518), 1, + sym__r_blk_imp_bgn, + [27006] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2260), 1, + sym__r_flw_jsv_bgn, + [27013] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2211), 1, + sym__r_flw_jsv_bgn, + [27020] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2520), 1, + sym__r_blk_imp_bgn, + [27027] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2522), 1, + sym__r_blk_imp_bgn, + [27034] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2524), 1, + sym__r_acr_ctn, + [27041] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2526), 1, + sym__r_acr_ctn, + [27048] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2528), 1, + sym__r_als_ctn, + [27055] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2530), 1, + sym__r_als_ctn, + [27062] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2532), 1, + sym__r_acr_ctn, + [27069] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2534), 1, + sym__r_acr_ctn, + [27076] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2536), 1, + sym__r_als_ctn, + [27083] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2538), 1, + sym__r_acr_ctn, + [27090] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2540), 1, + sym__r_acr_ctn, + [27097] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2542), 1, + sym__r_als_ctn, + [27104] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2544), 1, + sym__r_acr_ctn, + [27111] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2546), 1, + sym__r_acr_ctn, + [27118] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2548), 1, + sym__r_als_ctn, + [27125] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2550), 1, + sym__r_blk_imp_bgn, + [27132] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2552), 1, + sym__r_acr_ctn, + [27139] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2554), 1, + sym__r_als_ctn, + [27146] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2556), 1, + sym__r_acr_ctn, + [27153] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2558), 1, + sym__r_acr_ctn, + [27160] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2560), 1, + sym__r_als_ctn, + [27167] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2562), 1, + sym__r_acr_ctn, + [27174] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2564), 1, + sym__r_acr_ctn, + [27181] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2566), 1, + sym__r_als_ctn, + [27188] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2568), 1, + sym__r_acr_ctn, + [27195] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2570), 1, + sym__r_acr_ctn, + [27202] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2572), 1, + sym__r_acr_ctn, + [27209] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2574), 1, + sym__r_acr_ctn, + [27216] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2576), 1, + sym__r_acr_ctn, + [27223] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2578), 1, + sym__r_acr_ctn, + [27230] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2580), 1, + sym__r_acr_ctn, + [27237] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2582), 1, + sym__r_acr_ctn, + [27244] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2584), 1, + sym__r_acr_ctn, + [27251] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2586), 1, + sym__r_acr_ctn, + [27258] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2588), 1, + sym__r_acr_ctn, + [27265] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2590), 1, + sym__r_acr_ctn, + [27272] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2592), 1, + sym__r_acr_ctn, + [27279] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2594), 1, + sym__r_acr_ctn, + [27286] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2596), 1, + sym__r_acr_ctn, + [27293] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2598), 1, + sym__r_acr_ctn, + [27300] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2600), 1, + sym__r_acr_ctn, + [27307] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2602), 1, + sym__r_acr_ctn, + [27314] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2604), 1, + sym__r_acr_ctn, +}; + +static const uint32_t ts_small_parse_table_map[] = { + [SMALL_STATE(96)] = 0, + [SMALL_STATE(97)] = 71, + [SMALL_STATE(98)] = 142, + [SMALL_STATE(99)] = 206, + [SMALL_STATE(100)] = 271, + [SMALL_STATE(101)] = 336, + [SMALL_STATE(102)] = 393, + [SMALL_STATE(103)] = 450, + [SMALL_STATE(104)] = 510, + [SMALL_STATE(105)] = 570, + [SMALL_STATE(106)] = 630, + [SMALL_STATE(107)] = 686, + [SMALL_STATE(108)] = 742, + [SMALL_STATE(109)] = 797, + [SMALL_STATE(110)] = 852, + [SMALL_STATE(111)] = 907, + [SMALL_STATE(112)] = 962, + [SMALL_STATE(113)] = 1043, + [SMALL_STATE(114)] = 1124, + [SMALL_STATE(115)] = 1204, + [SMALL_STATE(116)] = 1284, + [SMALL_STATE(117)] = 1341, + [SMALL_STATE(118)] = 1420, + [SMALL_STATE(119)] = 1477, + [SMALL_STATE(120)] = 1556, + [SMALL_STATE(121)] = 1635, + [SMALL_STATE(122)] = 1714, + [SMALL_STATE(123)] = 1770, + [SMALL_STATE(124)] = 1826, + [SMALL_STATE(125)] = 1876, + [SMALL_STATE(126)] = 1967, + [SMALL_STATE(127)] = 2062, + [SMALL_STATE(128)] = 2105, + [SMALL_STATE(129)] = 2196, + [SMALL_STATE(130)] = 2239, + [SMALL_STATE(131)] = 2330, + [SMALL_STATE(132)] = 2381, + [SMALL_STATE(133)] = 2476, + [SMALL_STATE(134)] = 2571, + [SMALL_STATE(135)] = 2662, + [SMALL_STATE(136)] = 2753, + [SMALL_STATE(137)] = 2848, + [SMALL_STATE(138)] = 2943, + [SMALL_STATE(139)] = 3034, + [SMALL_STATE(140)] = 3125, + [SMALL_STATE(141)] = 3220, + [SMALL_STATE(142)] = 3315, + [SMALL_STATE(143)] = 3406, + [SMALL_STATE(144)] = 3497, + [SMALL_STATE(145)] = 3588, + [SMALL_STATE(146)] = 3679, + [SMALL_STATE(147)] = 3730, + [SMALL_STATE(148)] = 3825, + [SMALL_STATE(149)] = 3920, + [SMALL_STATE(150)] = 4011, + [SMALL_STATE(151)] = 4102, + [SMALL_STATE(152)] = 4197, + [SMALL_STATE(153)] = 4292, + [SMALL_STATE(154)] = 4387, + [SMALL_STATE(155)] = 4482, + [SMALL_STATE(156)] = 4577, + [SMALL_STATE(157)] = 4619, + [SMALL_STATE(158)] = 4669, + [SMALL_STATE(159)] = 4719, + [SMALL_STATE(160)] = 4761, + [SMALL_STATE(161)] = 4807, + [SMALL_STATE(162)] = 4849, + [SMALL_STATE(163)] = 4925, + [SMALL_STATE(164)] = 4967, + [SMALL_STATE(165)] = 5043, + [SMALL_STATE(166)] = 5089, + [SMALL_STATE(167)] = 5135, + [SMALL_STATE(168)] = 5224, + [SMALL_STATE(169)] = 5269, + [SMALL_STATE(170)] = 5310, + [SMALL_STATE(171)] = 5351, + [SMALL_STATE(172)] = 5392, + [SMALL_STATE(173)] = 5437, + [SMALL_STATE(174)] = 5478, + [SMALL_STATE(175)] = 5567, + [SMALL_STATE(176)] = 5656, + [SMALL_STATE(177)] = 5697, + [SMALL_STATE(178)] = 5786, + [SMALL_STATE(179)] = 5826, + [SMALL_STATE(180)] = 5866, + [SMALL_STATE(181)] = 5906, + [SMALL_STATE(182)] = 5992, + [SMALL_STATE(183)] = 6078, + [SMALL_STATE(184)] = 6127, + [SMALL_STATE(185)] = 6172, + [SMALL_STATE(186)] = 6217, + [SMALL_STATE(187)] = 6261, + [SMALL_STATE(188)] = 6305, + [SMALL_STATE(189)] = 6353, + [SMALL_STATE(190)] = 6428, + [SMALL_STATE(191)] = 6467, + [SMALL_STATE(192)] = 6510, + [SMALL_STATE(193)] = 6553, + [SMALL_STATE(194)] = 6596, + [SMALL_STATE(195)] = 6633, + [SMALL_STATE(196)] = 6676, + [SMALL_STATE(197)] = 6713, + [SMALL_STATE(198)] = 6752, + [SMALL_STATE(199)] = 6799, + [SMALL_STATE(200)] = 6870, + [SMALL_STATE(201)] = 6941, + [SMALL_STATE(202)] = 6988, + [SMALL_STATE(203)] = 7059, + [SMALL_STATE(204)] = 7130, + [SMALL_STATE(205)] = 7173, + [SMALL_STATE(206)] = 7248, + [SMALL_STATE(207)] = 7284, + [SMALL_STATE(208)] = 7326, + [SMALL_STATE(209)] = 7362, + [SMALL_STATE(210)] = 7400, + [SMALL_STATE(211)] = 7438, + [SMALL_STATE(212)] = 7473, + [SMALL_STATE(213)] = 7508, + [SMALL_STATE(214)] = 7545, + [SMALL_STATE(215)] = 7582, + [SMALL_STATE(216)] = 7623, + [SMALL_STATE(217)] = 7658, + [SMALL_STATE(218)] = 7693, + [SMALL_STATE(219)] = 7730, + [SMALL_STATE(220)] = 7767, + [SMALL_STATE(221)] = 7808, + [SMALL_STATE(222)] = 7843, + [SMALL_STATE(223)] = 7878, + [SMALL_STATE(224)] = 7913, + [SMALL_STATE(225)] = 7950, + [SMALL_STATE(226)] = 7985, + [SMALL_STATE(227)] = 8029, + [SMALL_STATE(228)] = 8063, + [SMALL_STATE(229)] = 8097, + [SMALL_STATE(230)] = 8137, + [SMALL_STATE(231)] = 8173, + [SMALL_STATE(232)] = 8207, + [SMALL_STATE(233)] = 8241, + [SMALL_STATE(234)] = 8281, + [SMALL_STATE(235)] = 8314, + [SMALL_STATE(236)] = 8347, + [SMALL_STATE(237)] = 8380, + [SMALL_STATE(238)] = 8413, + [SMALL_STATE(239)] = 8448, + [SMALL_STATE(240)] = 8481, + [SMALL_STATE(241)] = 8514, + [SMALL_STATE(242)] = 8547, + [SMALL_STATE(243)] = 8582, + [SMALL_STATE(244)] = 8615, + [SMALL_STATE(245)] = 8653, + [SMALL_STATE(246)] = 8687, + [SMALL_STATE(247)] = 8719, + [SMALL_STATE(248)] = 8751, + [SMALL_STATE(249)] = 8785, + [SMALL_STATE(250)] = 8816, + [SMALL_STATE(251)] = 8847, + [SMALL_STATE(252)] = 8878, + [SMALL_STATE(253)] = 8909, + [SMALL_STATE(254)] = 8940, + [SMALL_STATE(255)] = 8971, + [SMALL_STATE(256)] = 9002, + [SMALL_STATE(257)] = 9032, + [SMALL_STATE(258)] = 9064, + [SMALL_STATE(259)] = 9094, + [SMALL_STATE(260)] = 9124, + [SMALL_STATE(261)] = 9154, + [SMALL_STATE(262)] = 9198, + [SMALL_STATE(263)] = 9226, + [SMALL_STATE(264)] = 9254, + [SMALL_STATE(265)] = 9282, + [SMALL_STATE(266)] = 9326, + [SMALL_STATE(267)] = 9349, + [SMALL_STATE(268)] = 9374, + [SMALL_STATE(269)] = 9399, + [SMALL_STATE(270)] = 9424, + [SMALL_STATE(271)] = 9449, + [SMALL_STATE(272)] = 9474, + [SMALL_STATE(273)] = 9499, + [SMALL_STATE(274)] = 9522, + [SMALL_STATE(275)] = 9565, + [SMALL_STATE(276)] = 9588, + [SMALL_STATE(277)] = 9631, + [SMALL_STATE(278)] = 9658, + [SMALL_STATE(279)] = 9685, + [SMALL_STATE(280)] = 9712, + [SMALL_STATE(281)] = 9735, + [SMALL_STATE(282)] = 9760, + [SMALL_STATE(283)] = 9785, + [SMALL_STATE(284)] = 9808, + [SMALL_STATE(285)] = 9833, + [SMALL_STATE(286)] = 9858, + [SMALL_STATE(287)] = 9883, + [SMALL_STATE(288)] = 9908, + [SMALL_STATE(289)] = 9933, + [SMALL_STATE(290)] = 9958, + [SMALL_STATE(291)] = 9981, + [SMALL_STATE(292)] = 10003, + [SMALL_STATE(293)] = 10025, + [SMALL_STATE(294)] = 10047, + [SMALL_STATE(295)] = 10069, + [SMALL_STATE(296)] = 10091, + [SMALL_STATE(297)] = 10113, + [SMALL_STATE(298)] = 10135, + [SMALL_STATE(299)] = 10157, + [SMALL_STATE(300)] = 10179, + [SMALL_STATE(301)] = 10201, + [SMALL_STATE(302)] = 10223, + [SMALL_STATE(303)] = 10245, + [SMALL_STATE(304)] = 10267, + [SMALL_STATE(305)] = 10289, + [SMALL_STATE(306)] = 10311, + [SMALL_STATE(307)] = 10333, + [SMALL_STATE(308)] = 10355, + [SMALL_STATE(309)] = 10397, + [SMALL_STATE(310)] = 10439, + [SMALL_STATE(311)] = 10461, + [SMALL_STATE(312)] = 10483, + [SMALL_STATE(313)] = 10505, + [SMALL_STATE(314)] = 10527, + [SMALL_STATE(315)] = 10549, + [SMALL_STATE(316)] = 10571, + [SMALL_STATE(317)] = 10593, + [SMALL_STATE(318)] = 10615, + [SMALL_STATE(319)] = 10637, + [SMALL_STATE(320)] = 10659, + [SMALL_STATE(321)] = 10681, + [SMALL_STATE(322)] = 10703, + [SMALL_STATE(323)] = 10745, + [SMALL_STATE(324)] = 10767, + [SMALL_STATE(325)] = 10789, + [SMALL_STATE(326)] = 10811, + [SMALL_STATE(327)] = 10833, + [SMALL_STATE(328)] = 10855, + [SMALL_STATE(329)] = 10877, + [SMALL_STATE(330)] = 10899, + [SMALL_STATE(331)] = 10921, + [SMALL_STATE(332)] = 10943, + [SMALL_STATE(333)] = 10965, + [SMALL_STATE(334)] = 10987, + [SMALL_STATE(335)] = 11009, + [SMALL_STATE(336)] = 11031, + [SMALL_STATE(337)] = 11053, + [SMALL_STATE(338)] = 11075, + [SMALL_STATE(339)] = 11097, + [SMALL_STATE(340)] = 11119, + [SMALL_STATE(341)] = 11141, + [SMALL_STATE(342)] = 11163, + [SMALL_STATE(343)] = 11185, + [SMALL_STATE(344)] = 11207, + [SMALL_STATE(345)] = 11229, + [SMALL_STATE(346)] = 11251, + [SMALL_STATE(347)] = 11273, + [SMALL_STATE(348)] = 11295, + [SMALL_STATE(349)] = 11317, + [SMALL_STATE(350)] = 11339, + [SMALL_STATE(351)] = 11361, + [SMALL_STATE(352)] = 11383, + [SMALL_STATE(353)] = 11405, + [SMALL_STATE(354)] = 11427, + [SMALL_STATE(355)] = 11449, + [SMALL_STATE(356)] = 11471, + [SMALL_STATE(357)] = 11493, + [SMALL_STATE(358)] = 11515, + [SMALL_STATE(359)] = 11537, + [SMALL_STATE(360)] = 11559, + [SMALL_STATE(361)] = 11581, + [SMALL_STATE(362)] = 11603, + [SMALL_STATE(363)] = 11625, + [SMALL_STATE(364)] = 11647, + [SMALL_STATE(365)] = 11669, + [SMALL_STATE(366)] = 11711, + [SMALL_STATE(367)] = 11733, + [SMALL_STATE(368)] = 11755, + [SMALL_STATE(369)] = 11777, + [SMALL_STATE(370)] = 11799, + [SMALL_STATE(371)] = 11821, + [SMALL_STATE(372)] = 11843, + [SMALL_STATE(373)] = 11865, + [SMALL_STATE(374)] = 11887, + [SMALL_STATE(375)] = 11909, + [SMALL_STATE(376)] = 11931, + [SMALL_STATE(377)] = 11953, + [SMALL_STATE(378)] = 11975, + [SMALL_STATE(379)] = 11997, + [SMALL_STATE(380)] = 12019, + [SMALL_STATE(381)] = 12041, + [SMALL_STATE(382)] = 12063, + [SMALL_STATE(383)] = 12085, + [SMALL_STATE(384)] = 12107, + [SMALL_STATE(385)] = 12129, + [SMALL_STATE(386)] = 12151, + [SMALL_STATE(387)] = 12173, + [SMALL_STATE(388)] = 12195, + [SMALL_STATE(389)] = 12217, + [SMALL_STATE(390)] = 12239, + [SMALL_STATE(391)] = 12261, + [SMALL_STATE(392)] = 12283, + [SMALL_STATE(393)] = 12308, + [SMALL_STATE(394)] = 12333, + [SMALL_STATE(395)] = 12357, + [SMALL_STATE(396)] = 12379, + [SMALL_STATE(397)] = 12403, + [SMALL_STATE(398)] = 12423, + [SMALL_STATE(399)] = 12445, + [SMALL_STATE(400)] = 12465, + [SMALL_STATE(401)] = 12484, + [SMALL_STATE(402)] = 12505, + [SMALL_STATE(403)] = 12524, + [SMALL_STATE(404)] = 12547, + [SMALL_STATE(405)] = 12568, + [SMALL_STATE(406)] = 12591, + [SMALL_STATE(407)] = 12610, + [SMALL_STATE(408)] = 12629, + [SMALL_STATE(409)] = 12648, + [SMALL_STATE(410)] = 12671, + [SMALL_STATE(411)] = 12690, + [SMALL_STATE(412)] = 12708, + [SMALL_STATE(413)] = 12726, + [SMALL_STATE(414)] = 12746, + [SMALL_STATE(415)] = 12764, + [SMALL_STATE(416)] = 12784, + [SMALL_STATE(417)] = 12802, + [SMALL_STATE(418)] = 12820, + [SMALL_STATE(419)] = 12838, + [SMALL_STATE(420)] = 12856, + [SMALL_STATE(421)] = 12876, + [SMALL_STATE(422)] = 12905, + [SMALL_STATE(423)] = 12934, + [SMALL_STATE(424)] = 12963, + [SMALL_STATE(425)] = 12980, + [SMALL_STATE(426)] = 12997, + [SMALL_STATE(427)] = 13026, + [SMALL_STATE(428)] = 13057, + [SMALL_STATE(429)] = 13088, + [SMALL_STATE(430)] = 13117, + [SMALL_STATE(431)] = 13146, + [SMALL_STATE(432)] = 13175, + [SMALL_STATE(433)] = 13206, + [SMALL_STATE(434)] = 13237, + [SMALL_STATE(435)] = 13268, + [SMALL_STATE(436)] = 13297, + [SMALL_STATE(437)] = 13326, + [SMALL_STATE(438)] = 13357, + [SMALL_STATE(439)] = 13374, + [SMALL_STATE(440)] = 13403, + [SMALL_STATE(441)] = 13432, + [SMALL_STATE(442)] = 13461, + [SMALL_STATE(443)] = 13492, + [SMALL_STATE(444)] = 13523, + [SMALL_STATE(445)] = 13552, + [SMALL_STATE(446)] = 13569, + [SMALL_STATE(447)] = 13600, + [SMALL_STATE(448)] = 13631, + [SMALL_STATE(449)] = 13662, + [SMALL_STATE(450)] = 13691, + [SMALL_STATE(451)] = 13720, + [SMALL_STATE(452)] = 13751, + [SMALL_STATE(453)] = 13780, + [SMALL_STATE(454)] = 13809, + [SMALL_STATE(455)] = 13840, + [SMALL_STATE(456)] = 13869, + [SMALL_STATE(457)] = 13900, + [SMALL_STATE(458)] = 13929, + [SMALL_STATE(459)] = 13958, + [SMALL_STATE(460)] = 13989, + [SMALL_STATE(461)] = 14020, + [SMALL_STATE(462)] = 14051, + [SMALL_STATE(463)] = 14080, + [SMALL_STATE(464)] = 14109, + [SMALL_STATE(465)] = 14140, + [SMALL_STATE(466)] = 14171, + [SMALL_STATE(467)] = 14200, + [SMALL_STATE(468)] = 14231, + [SMALL_STATE(469)] = 14262, + [SMALL_STATE(470)] = 14279, + [SMALL_STATE(471)] = 14308, + [SMALL_STATE(472)] = 14339, + [SMALL_STATE(473)] = 14368, + [SMALL_STATE(474)] = 14397, + [SMALL_STATE(475)] = 14425, + [SMALL_STATE(476)] = 14453, + [SMALL_STATE(477)] = 14481, + [SMALL_STATE(478)] = 14509, + [SMALL_STATE(479)] = 14535, + [SMALL_STATE(480)] = 14563, + [SMALL_STATE(481)] = 14591, + [SMALL_STATE(482)] = 14610, + [SMALL_STATE(483)] = 14635, + [SMALL_STATE(484)] = 14660, + [SMALL_STATE(485)] = 14683, + [SMALL_STATE(486)] = 14706, + [SMALL_STATE(487)] = 14727, + [SMALL_STATE(488)] = 14752, + [SMALL_STATE(489)] = 14777, + [SMALL_STATE(490)] = 14800, + [SMALL_STATE(491)] = 14823, + [SMALL_STATE(492)] = 14848, + [SMALL_STATE(493)] = 14871, + [SMALL_STATE(494)] = 14894, + [SMALL_STATE(495)] = 14919, + [SMALL_STATE(496)] = 14942, + [SMALL_STATE(497)] = 14965, + [SMALL_STATE(498)] = 14988, + [SMALL_STATE(499)] = 15011, + [SMALL_STATE(500)] = 15032, + [SMALL_STATE(501)] = 15055, + [SMALL_STATE(502)] = 15080, + [SMALL_STATE(503)] = 15099, + [SMALL_STATE(504)] = 15124, + [SMALL_STATE(505)] = 15147, + [SMALL_STATE(506)] = 15170, + [SMALL_STATE(507)] = 15193, + [SMALL_STATE(508)] = 15218, + [SMALL_STATE(509)] = 15241, + [SMALL_STATE(510)] = 15264, + [SMALL_STATE(511)] = 15287, + [SMALL_STATE(512)] = 15310, + [SMALL_STATE(513)] = 15335, + [SMALL_STATE(514)] = 15360, + [SMALL_STATE(515)] = 15385, + [SMALL_STATE(516)] = 15410, + [SMALL_STATE(517)] = 15435, + [SMALL_STATE(518)] = 15458, + [SMALL_STATE(519)] = 15483, + [SMALL_STATE(520)] = 15506, + [SMALL_STATE(521)] = 15529, + [SMALL_STATE(522)] = 15554, + [SMALL_STATE(523)] = 15577, + [SMALL_STATE(524)] = 15600, + [SMALL_STATE(525)] = 15623, + [SMALL_STATE(526)] = 15648, + [SMALL_STATE(527)] = 15673, + [SMALL_STATE(528)] = 15696, + [SMALL_STATE(529)] = 15721, + [SMALL_STATE(530)] = 15746, + [SMALL_STATE(531)] = 15769, + [SMALL_STATE(532)] = 15794, + [SMALL_STATE(533)] = 15817, + [SMALL_STATE(534)] = 15840, + [SMALL_STATE(535)] = 15865, + [SMALL_STATE(536)] = 15888, + [SMALL_STATE(537)] = 15911, + [SMALL_STATE(538)] = 15934, + [SMALL_STATE(539)] = 15956, + [SMALL_STATE(540)] = 15975, + [SMALL_STATE(541)] = 15988, + [SMALL_STATE(542)] = 16007, + [SMALL_STATE(543)] = 16020, + [SMALL_STATE(544)] = 16039, + [SMALL_STATE(545)] = 16058, + [SMALL_STATE(546)] = 16071, + [SMALL_STATE(547)] = 16090, + [SMALL_STATE(548)] = 16103, + [SMALL_STATE(549)] = 16116, + [SMALL_STATE(550)] = 16129, + [SMALL_STATE(551)] = 16142, + [SMALL_STATE(552)] = 16155, + [SMALL_STATE(553)] = 16172, + [SMALL_STATE(554)] = 16191, + [SMALL_STATE(555)] = 16208, + [SMALL_STATE(556)] = 16223, + [SMALL_STATE(557)] = 16238, + [SMALL_STATE(558)] = 16257, + [SMALL_STATE(559)] = 16276, + [SMALL_STATE(560)] = 16295, + [SMALL_STATE(561)] = 16314, + [SMALL_STATE(562)] = 16333, + [SMALL_STATE(563)] = 16352, + [SMALL_STATE(564)] = 16365, + [SMALL_STATE(565)] = 16378, + [SMALL_STATE(566)] = 16397, + [SMALL_STATE(567)] = 16410, + [SMALL_STATE(568)] = 16427, + [SMALL_STATE(569)] = 16440, + [SMALL_STATE(570)] = 16455, + [SMALL_STATE(571)] = 16468, + [SMALL_STATE(572)] = 16481, + [SMALL_STATE(573)] = 16496, + [SMALL_STATE(574)] = 16509, + [SMALL_STATE(575)] = 16522, + [SMALL_STATE(576)] = 16541, + [SMALL_STATE(577)] = 16556, + [SMALL_STATE(578)] = 16575, + [SMALL_STATE(579)] = 16594, + [SMALL_STATE(580)] = 16613, + [SMALL_STATE(581)] = 16626, + [SMALL_STATE(582)] = 16639, + [SMALL_STATE(583)] = 16658, + [SMALL_STATE(584)] = 16677, + [SMALL_STATE(585)] = 16696, + [SMALL_STATE(586)] = 16715, + [SMALL_STATE(587)] = 16732, + [SMALL_STATE(588)] = 16751, + [SMALL_STATE(589)] = 16770, + [SMALL_STATE(590)] = 16789, + [SMALL_STATE(591)] = 16808, + [SMALL_STATE(592)] = 16827, + [SMALL_STATE(593)] = 16846, + [SMALL_STATE(594)] = 16859, + [SMALL_STATE(595)] = 16872, + [SMALL_STATE(596)] = 16885, + [SMALL_STATE(597)] = 16898, + [SMALL_STATE(598)] = 16911, + [SMALL_STATE(599)] = 16924, + [SMALL_STATE(600)] = 16937, + [SMALL_STATE(601)] = 16950, + [SMALL_STATE(602)] = 16963, + [SMALL_STATE(603)] = 16976, + [SMALL_STATE(604)] = 16989, + [SMALL_STATE(605)] = 17002, + [SMALL_STATE(606)] = 17021, + [SMALL_STATE(607)] = 17036, + [SMALL_STATE(608)] = 17055, + [SMALL_STATE(609)] = 17074, + [SMALL_STATE(610)] = 17093, + [SMALL_STATE(611)] = 17106, + [SMALL_STATE(612)] = 17121, + [SMALL_STATE(613)] = 17134, + [SMALL_STATE(614)] = 17147, + [SMALL_STATE(615)] = 17164, + [SMALL_STATE(616)] = 17181, + [SMALL_STATE(617)] = 17194, + [SMALL_STATE(618)] = 17213, + [SMALL_STATE(619)] = 17232, + [SMALL_STATE(620)] = 17251, + [SMALL_STATE(621)] = 17270, + [SMALL_STATE(622)] = 17289, + [SMALL_STATE(623)] = 17308, + [SMALL_STATE(624)] = 17321, + [SMALL_STATE(625)] = 17334, + [SMALL_STATE(626)] = 17353, + [SMALL_STATE(627)] = 17366, + [SMALL_STATE(628)] = 17385, + [SMALL_STATE(629)] = 17404, + [SMALL_STATE(630)] = 17423, + [SMALL_STATE(631)] = 17442, + [SMALL_STATE(632)] = 17461, + [SMALL_STATE(633)] = 17474, + [SMALL_STATE(634)] = 17493, + [SMALL_STATE(635)] = 17512, + [SMALL_STATE(636)] = 17531, + [SMALL_STATE(637)] = 17544, + [SMALL_STATE(638)] = 17557, + [SMALL_STATE(639)] = 17570, + [SMALL_STATE(640)] = 17583, + [SMALL_STATE(641)] = 17602, + [SMALL_STATE(642)] = 17621, + [SMALL_STATE(643)] = 17640, + [SMALL_STATE(644)] = 17659, + [SMALL_STATE(645)] = 17678, + [SMALL_STATE(646)] = 17695, + [SMALL_STATE(647)] = 17714, + [SMALL_STATE(648)] = 17733, + [SMALL_STATE(649)] = 17750, + [SMALL_STATE(650)] = 17767, + [SMALL_STATE(651)] = 17786, + [SMALL_STATE(652)] = 17805, + [SMALL_STATE(653)] = 17824, + [SMALL_STATE(654)] = 17843, + [SMALL_STATE(655)] = 17862, + [SMALL_STATE(656)] = 17881, + [SMALL_STATE(657)] = 17900, + [SMALL_STATE(658)] = 17919, + [SMALL_STATE(659)] = 17938, + [SMALL_STATE(660)] = 17957, + [SMALL_STATE(661)] = 17974, + [SMALL_STATE(662)] = 17991, + [SMALL_STATE(663)] = 18004, + [SMALL_STATE(664)] = 18021, + [SMALL_STATE(665)] = 18040, + [SMALL_STATE(666)] = 18059, + [SMALL_STATE(667)] = 18078, + [SMALL_STATE(668)] = 18097, + [SMALL_STATE(669)] = 18116, + [SMALL_STATE(670)] = 18135, + [SMALL_STATE(671)] = 18152, + [SMALL_STATE(672)] = 18169, + [SMALL_STATE(673)] = 18186, + [SMALL_STATE(674)] = 18203, + [SMALL_STATE(675)] = 18220, + [SMALL_STATE(676)] = 18237, + [SMALL_STATE(677)] = 18256, + [SMALL_STATE(678)] = 18269, + [SMALL_STATE(679)] = 18288, + [SMALL_STATE(680)] = 18301, + [SMALL_STATE(681)] = 18320, + [SMALL_STATE(682)] = 18339, + [SMALL_STATE(683)] = 18358, + [SMALL_STATE(684)] = 18371, + [SMALL_STATE(685)] = 18384, + [SMALL_STATE(686)] = 18403, + [SMALL_STATE(687)] = 18422, + [SMALL_STATE(688)] = 18441, + [SMALL_STATE(689)] = 18460, + [SMALL_STATE(690)] = 18479, + [SMALL_STATE(691)] = 18498, + [SMALL_STATE(692)] = 18517, + [SMALL_STATE(693)] = 18530, + [SMALL_STATE(694)] = 18546, + [SMALL_STATE(695)] = 18562, + [SMALL_STATE(696)] = 18574, + [SMALL_STATE(697)] = 18586, + [SMALL_STATE(698)] = 18598, + [SMALL_STATE(699)] = 18614, + [SMALL_STATE(700)] = 18626, + [SMALL_STATE(701)] = 18638, + [SMALL_STATE(702)] = 18650, + [SMALL_STATE(703)] = 18662, + [SMALL_STATE(704)] = 18674, + [SMALL_STATE(705)] = 18686, + [SMALL_STATE(706)] = 18698, + [SMALL_STATE(707)] = 18710, + [SMALL_STATE(708)] = 18722, + [SMALL_STATE(709)] = 18734, + [SMALL_STATE(710)] = 18746, + [SMALL_STATE(711)] = 18758, + [SMALL_STATE(712)] = 18772, + [SMALL_STATE(713)] = 18784, + [SMALL_STATE(714)] = 18796, + [SMALL_STATE(715)] = 18810, + [SMALL_STATE(716)] = 18822, + [SMALL_STATE(717)] = 18834, + [SMALL_STATE(718)] = 18848, + [SMALL_STATE(719)] = 18860, + [SMALL_STATE(720)] = 18872, + [SMALL_STATE(721)] = 18886, + [SMALL_STATE(722)] = 18898, + [SMALL_STATE(723)] = 18910, + [SMALL_STATE(724)] = 18922, + [SMALL_STATE(725)] = 18934, + [SMALL_STATE(726)] = 18946, + [SMALL_STATE(727)] = 18958, + [SMALL_STATE(728)] = 18970, + [SMALL_STATE(729)] = 18982, + [SMALL_STATE(730)] = 18994, + [SMALL_STATE(731)] = 19006, + [SMALL_STATE(732)] = 19018, + [SMALL_STATE(733)] = 19030, + [SMALL_STATE(734)] = 19042, + [SMALL_STATE(735)] = 19054, + [SMALL_STATE(736)] = 19068, + [SMALL_STATE(737)] = 19080, + [SMALL_STATE(738)] = 19094, + [SMALL_STATE(739)] = 19106, + [SMALL_STATE(740)] = 19118, + [SMALL_STATE(741)] = 19130, + [SMALL_STATE(742)] = 19146, + [SMALL_STATE(743)] = 19158, + [SMALL_STATE(744)] = 19170, + [SMALL_STATE(745)] = 19182, + [SMALL_STATE(746)] = 19194, + [SMALL_STATE(747)] = 19206, + [SMALL_STATE(748)] = 19220, + [SMALL_STATE(749)] = 19232, + [SMALL_STATE(750)] = 19244, + [SMALL_STATE(751)] = 19260, + [SMALL_STATE(752)] = 19276, + [SMALL_STATE(753)] = 19292, + [SMALL_STATE(754)] = 19304, + [SMALL_STATE(755)] = 19320, + [SMALL_STATE(756)] = 19336, + [SMALL_STATE(757)] = 19352, + [SMALL_STATE(758)] = 19368, + [SMALL_STATE(759)] = 19384, + [SMALL_STATE(760)] = 19400, + [SMALL_STATE(761)] = 19416, + [SMALL_STATE(762)] = 19432, + [SMALL_STATE(763)] = 19448, + [SMALL_STATE(764)] = 19464, + [SMALL_STATE(765)] = 19480, + [SMALL_STATE(766)] = 19496, + [SMALL_STATE(767)] = 19512, + [SMALL_STATE(768)] = 19528, + [SMALL_STATE(769)] = 19544, + [SMALL_STATE(770)] = 19560, + [SMALL_STATE(771)] = 19576, + [SMALL_STATE(772)] = 19592, + [SMALL_STATE(773)] = 19608, + [SMALL_STATE(774)] = 19624, + [SMALL_STATE(775)] = 19640, + [SMALL_STATE(776)] = 19656, + [SMALL_STATE(777)] = 19672, + [SMALL_STATE(778)] = 19688, + [SMALL_STATE(779)] = 19704, + [SMALL_STATE(780)] = 19720, + [SMALL_STATE(781)] = 19736, + [SMALL_STATE(782)] = 19752, + [SMALL_STATE(783)] = 19768, + [SMALL_STATE(784)] = 19780, + [SMALL_STATE(785)] = 19791, + [SMALL_STATE(786)] = 19804, + [SMALL_STATE(787)] = 19815, + [SMALL_STATE(788)] = 19826, + [SMALL_STATE(789)] = 19837, + [SMALL_STATE(790)] = 19848, + [SMALL_STATE(791)] = 19859, + [SMALL_STATE(792)] = 19870, + [SMALL_STATE(793)] = 19881, + [SMALL_STATE(794)] = 19892, + [SMALL_STATE(795)] = 19903, + [SMALL_STATE(796)] = 19914, + [SMALL_STATE(797)] = 19925, + [SMALL_STATE(798)] = 19936, + [SMALL_STATE(799)] = 19947, + [SMALL_STATE(800)] = 19958, + [SMALL_STATE(801)] = 19969, + [SMALL_STATE(802)] = 19982, + [SMALL_STATE(803)] = 19993, + [SMALL_STATE(804)] = 20004, + [SMALL_STATE(805)] = 20015, + [SMALL_STATE(806)] = 20034, + [SMALL_STATE(807)] = 20045, + [SMALL_STATE(808)] = 20056, + [SMALL_STATE(809)] = 20067, + [SMALL_STATE(810)] = 20078, + [SMALL_STATE(811)] = 20089, + [SMALL_STATE(812)] = 20100, + [SMALL_STATE(813)] = 20111, + [SMALL_STATE(814)] = 20122, + [SMALL_STATE(815)] = 20133, + [SMALL_STATE(816)] = 20144, + [SMALL_STATE(817)] = 20155, + [SMALL_STATE(818)] = 20166, + [SMALL_STATE(819)] = 20177, + [SMALL_STATE(820)] = 20188, + [SMALL_STATE(821)] = 20199, + [SMALL_STATE(822)] = 20210, + [SMALL_STATE(823)] = 20221, + [SMALL_STATE(824)] = 20232, + [SMALL_STATE(825)] = 20243, + [SMALL_STATE(826)] = 20254, + [SMALL_STATE(827)] = 20265, + [SMALL_STATE(828)] = 20278, + [SMALL_STATE(829)] = 20289, + [SMALL_STATE(830)] = 20300, + [SMALL_STATE(831)] = 20313, + [SMALL_STATE(832)] = 20324, + [SMALL_STATE(833)] = 20335, + [SMALL_STATE(834)] = 20348, + [SMALL_STATE(835)] = 20359, + [SMALL_STATE(836)] = 20370, + [SMALL_STATE(837)] = 20383, + [SMALL_STATE(838)] = 20394, + [SMALL_STATE(839)] = 20405, + [SMALL_STATE(840)] = 20416, + [SMALL_STATE(841)] = 20427, + [SMALL_STATE(842)] = 20438, + [SMALL_STATE(843)] = 20449, + [SMALL_STATE(844)] = 20460, + [SMALL_STATE(845)] = 20471, + [SMALL_STATE(846)] = 20482, + [SMALL_STATE(847)] = 20493, + [SMALL_STATE(848)] = 20504, + [SMALL_STATE(849)] = 20515, + [SMALL_STATE(850)] = 20526, + [SMALL_STATE(851)] = 20537, + [SMALL_STATE(852)] = 20548, + [SMALL_STATE(853)] = 20559, + [SMALL_STATE(854)] = 20572, + [SMALL_STATE(855)] = 20583, + [SMALL_STATE(856)] = 20596, + [SMALL_STATE(857)] = 20607, + [SMALL_STATE(858)] = 20618, + [SMALL_STATE(859)] = 20629, + [SMALL_STATE(860)] = 20640, + [SMALL_STATE(861)] = 20651, + [SMALL_STATE(862)] = 20662, + [SMALL_STATE(863)] = 20673, + [SMALL_STATE(864)] = 20684, + [SMALL_STATE(865)] = 20695, + [SMALL_STATE(866)] = 20706, + [SMALL_STATE(867)] = 20717, + [SMALL_STATE(868)] = 20728, + [SMALL_STATE(869)] = 20739, + [SMALL_STATE(870)] = 20750, + [SMALL_STATE(871)] = 20761, + [SMALL_STATE(872)] = 20772, + [SMALL_STATE(873)] = 20783, + [SMALL_STATE(874)] = 20794, + [SMALL_STATE(875)] = 20805, + [SMALL_STATE(876)] = 20816, + [SMALL_STATE(877)] = 20829, + [SMALL_STATE(878)] = 20840, + [SMALL_STATE(879)] = 20853, + [SMALL_STATE(880)] = 20864, + [SMALL_STATE(881)] = 20875, + [SMALL_STATE(882)] = 20888, + [SMALL_STATE(883)] = 20899, + [SMALL_STATE(884)] = 20910, + [SMALL_STATE(885)] = 20923, + [SMALL_STATE(886)] = 20934, + [SMALL_STATE(887)] = 20945, + [SMALL_STATE(888)] = 20956, + [SMALL_STATE(889)] = 20967, + [SMALL_STATE(890)] = 20978, + [SMALL_STATE(891)] = 20989, + [SMALL_STATE(892)] = 21000, + [SMALL_STATE(893)] = 21011, + [SMALL_STATE(894)] = 21022, + [SMALL_STATE(895)] = 21033, + [SMALL_STATE(896)] = 21044, + [SMALL_STATE(897)] = 21055, + [SMALL_STATE(898)] = 21066, + [SMALL_STATE(899)] = 21077, + [SMALL_STATE(900)] = 21088, + [SMALL_STATE(901)] = 21099, + [SMALL_STATE(902)] = 21110, + [SMALL_STATE(903)] = 21123, + [SMALL_STATE(904)] = 21134, + [SMALL_STATE(905)] = 21147, + [SMALL_STATE(906)] = 21158, + [SMALL_STATE(907)] = 21169, + [SMALL_STATE(908)] = 21180, + [SMALL_STATE(909)] = 21191, + [SMALL_STATE(910)] = 21202, + [SMALL_STATE(911)] = 21213, + [SMALL_STATE(912)] = 21224, + [SMALL_STATE(913)] = 21235, + [SMALL_STATE(914)] = 21246, + [SMALL_STATE(915)] = 21257, + [SMALL_STATE(916)] = 21268, + [SMALL_STATE(917)] = 21279, + [SMALL_STATE(918)] = 21294, + [SMALL_STATE(919)] = 21309, + [SMALL_STATE(920)] = 21322, + [SMALL_STATE(921)] = 21333, + [SMALL_STATE(922)] = 21344, + [SMALL_STATE(923)] = 21355, + [SMALL_STATE(924)] = 21366, + [SMALL_STATE(925)] = 21377, + [SMALL_STATE(926)] = 21388, + [SMALL_STATE(927)] = 21399, + [SMALL_STATE(928)] = 21410, + [SMALL_STATE(929)] = 21429, + [SMALL_STATE(930)] = 21440, + [SMALL_STATE(931)] = 21451, + [SMALL_STATE(932)] = 21462, + [SMALL_STATE(933)] = 21473, + [SMALL_STATE(934)] = 21484, + [SMALL_STATE(935)] = 21495, + [SMALL_STATE(936)] = 21508, + [SMALL_STATE(937)] = 21519, + [SMALL_STATE(938)] = 21530, + [SMALL_STATE(939)] = 21541, + [SMALL_STATE(940)] = 21556, + [SMALL_STATE(941)] = 21567, + [SMALL_STATE(942)] = 21578, + [SMALL_STATE(943)] = 21589, + [SMALL_STATE(944)] = 21600, + [SMALL_STATE(945)] = 21611, + [SMALL_STATE(946)] = 21622, + [SMALL_STATE(947)] = 21633, + [SMALL_STATE(948)] = 21644, + [SMALL_STATE(949)] = 21655, + [SMALL_STATE(950)] = 21666, + [SMALL_STATE(951)] = 21677, + [SMALL_STATE(952)] = 21688, + [SMALL_STATE(953)] = 21699, + [SMALL_STATE(954)] = 21710, + [SMALL_STATE(955)] = 21721, + [SMALL_STATE(956)] = 21732, + [SMALL_STATE(957)] = 21743, + [SMALL_STATE(958)] = 21754, + [SMALL_STATE(959)] = 21765, + [SMALL_STATE(960)] = 21776, + [SMALL_STATE(961)] = 21787, + [SMALL_STATE(962)] = 21798, + [SMALL_STATE(963)] = 21809, + [SMALL_STATE(964)] = 21823, + [SMALL_STATE(965)] = 21837, + [SMALL_STATE(966)] = 21851, + [SMALL_STATE(967)] = 21865, + [SMALL_STATE(968)] = 21879, + [SMALL_STATE(969)] = 21889, + [SMALL_STATE(970)] = 21903, + [SMALL_STATE(971)] = 21917, + [SMALL_STATE(972)] = 21931, + [SMALL_STATE(973)] = 21945, + [SMALL_STATE(974)] = 21959, + [SMALL_STATE(975)] = 21973, + [SMALL_STATE(976)] = 21987, + [SMALL_STATE(977)] = 22001, + [SMALL_STATE(978)] = 22015, + [SMALL_STATE(979)] = 22029, + [SMALL_STATE(980)] = 22043, + [SMALL_STATE(981)] = 22059, + [SMALL_STATE(982)] = 22075, + [SMALL_STATE(983)] = 22089, + [SMALL_STATE(984)] = 22103, + [SMALL_STATE(985)] = 22119, + [SMALL_STATE(986)] = 22131, + [SMALL_STATE(987)] = 22145, + [SMALL_STATE(988)] = 22157, + [SMALL_STATE(989)] = 22169, + [SMALL_STATE(990)] = 22181, + [SMALL_STATE(991)] = 22193, + [SMALL_STATE(992)] = 22209, + [SMALL_STATE(993)] = 22223, + [SMALL_STATE(994)] = 22237, + [SMALL_STATE(995)] = 22251, + [SMALL_STATE(996)] = 22265, + [SMALL_STATE(997)] = 22277, + [SMALL_STATE(998)] = 22289, + [SMALL_STATE(999)] = 22303, + [SMALL_STATE(1000)] = 22313, + [SMALL_STATE(1001)] = 22325, + [SMALL_STATE(1002)] = 22335, + [SMALL_STATE(1003)] = 22349, + [SMALL_STATE(1004)] = 22363, + [SMALL_STATE(1005)] = 22377, + [SMALL_STATE(1006)] = 22389, + [SMALL_STATE(1007)] = 22403, + [SMALL_STATE(1008)] = 22417, + [SMALL_STATE(1009)] = 22429, + [SMALL_STATE(1010)] = 22445, + [SMALL_STATE(1011)] = 22459, + [SMALL_STATE(1012)] = 22473, + [SMALL_STATE(1013)] = 22487, + [SMALL_STATE(1014)] = 22501, + [SMALL_STATE(1015)] = 22515, + [SMALL_STATE(1016)] = 22525, + [SMALL_STATE(1017)] = 22539, + [SMALL_STATE(1018)] = 22553, + [SMALL_STATE(1019)] = 22569, + [SMALL_STATE(1020)] = 22583, + [SMALL_STATE(1021)] = 22597, + [SMALL_STATE(1022)] = 22611, + [SMALL_STATE(1023)] = 22625, + [SMALL_STATE(1024)] = 22639, + [SMALL_STATE(1025)] = 22653, + [SMALL_STATE(1026)] = 22667, + [SMALL_STATE(1027)] = 22681, + [SMALL_STATE(1028)] = 22695, + [SMALL_STATE(1029)] = 22709, + [SMALL_STATE(1030)] = 22723, + [SMALL_STATE(1031)] = 22733, + [SMALL_STATE(1032)] = 22749, + [SMALL_STATE(1033)] = 22763, + [SMALL_STATE(1034)] = 22777, + [SMALL_STATE(1035)] = 22791, + [SMALL_STATE(1036)] = 22807, + [SMALL_STATE(1037)] = 22817, + [SMALL_STATE(1038)] = 22829, + [SMALL_STATE(1039)] = 22843, + [SMALL_STATE(1040)] = 22853, + [SMALL_STATE(1041)] = 22865, + [SMALL_STATE(1042)] = 22879, + [SMALL_STATE(1043)] = 22893, + [SMALL_STATE(1044)] = 22907, + [SMALL_STATE(1045)] = 22917, + [SMALL_STATE(1046)] = 22931, + [SMALL_STATE(1047)] = 22943, + [SMALL_STATE(1048)] = 22955, + [SMALL_STATE(1049)] = 22969, + [SMALL_STATE(1050)] = 22978, + [SMALL_STATE(1051)] = 22987, + [SMALL_STATE(1052)] = 22996, + [SMALL_STATE(1053)] = 23005, + [SMALL_STATE(1054)] = 23014, + [SMALL_STATE(1055)] = 23023, + [SMALL_STATE(1056)] = 23032, + [SMALL_STATE(1057)] = 23045, + [SMALL_STATE(1058)] = 23054, + [SMALL_STATE(1059)] = 23063, + [SMALL_STATE(1060)] = 23072, + [SMALL_STATE(1061)] = 23081, + [SMALL_STATE(1062)] = 23090, + [SMALL_STATE(1063)] = 23099, + [SMALL_STATE(1064)] = 23108, + [SMALL_STATE(1065)] = 23117, + [SMALL_STATE(1066)] = 23126, + [SMALL_STATE(1067)] = 23139, + [SMALL_STATE(1068)] = 23148, + [SMALL_STATE(1069)] = 23157, + [SMALL_STATE(1070)] = 23166, + [SMALL_STATE(1071)] = 23175, + [SMALL_STATE(1072)] = 23184, + [SMALL_STATE(1073)] = 23193, + [SMALL_STATE(1074)] = 23202, + [SMALL_STATE(1075)] = 23211, + [SMALL_STATE(1076)] = 23220, + [SMALL_STATE(1077)] = 23229, + [SMALL_STATE(1078)] = 23238, + [SMALL_STATE(1079)] = 23251, + [SMALL_STATE(1080)] = 23260, + [SMALL_STATE(1081)] = 23269, + [SMALL_STATE(1082)] = 23282, + [SMALL_STATE(1083)] = 23291, + [SMALL_STATE(1084)] = 23300, + [SMALL_STATE(1085)] = 23309, + [SMALL_STATE(1086)] = 23318, + [SMALL_STATE(1087)] = 23327, + [SMALL_STATE(1088)] = 23336, + [SMALL_STATE(1089)] = 23345, + [SMALL_STATE(1090)] = 23358, + [SMALL_STATE(1091)] = 23367, + [SMALL_STATE(1092)] = 23376, + [SMALL_STATE(1093)] = 23385, + [SMALL_STATE(1094)] = 23394, + [SMALL_STATE(1095)] = 23403, + [SMALL_STATE(1096)] = 23412, + [SMALL_STATE(1097)] = 23421, + [SMALL_STATE(1098)] = 23430, + [SMALL_STATE(1099)] = 23439, + [SMALL_STATE(1100)] = 23448, + [SMALL_STATE(1101)] = 23457, + [SMALL_STATE(1102)] = 23466, + [SMALL_STATE(1103)] = 23475, + [SMALL_STATE(1104)] = 23484, + [SMALL_STATE(1105)] = 23493, + [SMALL_STATE(1106)] = 23502, + [SMALL_STATE(1107)] = 23511, + [SMALL_STATE(1108)] = 23520, + [SMALL_STATE(1109)] = 23529, + [SMALL_STATE(1110)] = 23538, + [SMALL_STATE(1111)] = 23547, + [SMALL_STATE(1112)] = 23560, + [SMALL_STATE(1113)] = 23573, + [SMALL_STATE(1114)] = 23582, + [SMALL_STATE(1115)] = 23591, + [SMALL_STATE(1116)] = 23600, + [SMALL_STATE(1117)] = 23609, + [SMALL_STATE(1118)] = 23620, + [SMALL_STATE(1119)] = 23631, + [SMALL_STATE(1120)] = 23640, + [SMALL_STATE(1121)] = 23653, + [SMALL_STATE(1122)] = 23666, + [SMALL_STATE(1123)] = 23675, + [SMALL_STATE(1124)] = 23684, + [SMALL_STATE(1125)] = 23693, + [SMALL_STATE(1126)] = 23702, + [SMALL_STATE(1127)] = 23711, + [SMALL_STATE(1128)] = 23720, + [SMALL_STATE(1129)] = 23731, + [SMALL_STATE(1130)] = 23740, + [SMALL_STATE(1131)] = 23749, + [SMALL_STATE(1132)] = 23758, + [SMALL_STATE(1133)] = 23767, + [SMALL_STATE(1134)] = 23776, + [SMALL_STATE(1135)] = 23785, + [SMALL_STATE(1136)] = 23794, + [SMALL_STATE(1137)] = 23803, + [SMALL_STATE(1138)] = 23812, + [SMALL_STATE(1139)] = 23821, + [SMALL_STATE(1140)] = 23830, + [SMALL_STATE(1141)] = 23843, + [SMALL_STATE(1142)] = 23856, + [SMALL_STATE(1143)] = 23865, + [SMALL_STATE(1144)] = 23874, + [SMALL_STATE(1145)] = 23885, + [SMALL_STATE(1146)] = 23894, + [SMALL_STATE(1147)] = 23905, + [SMALL_STATE(1148)] = 23918, + [SMALL_STATE(1149)] = 23931, + [SMALL_STATE(1150)] = 23942, + [SMALL_STATE(1151)] = 23953, + [SMALL_STATE(1152)] = 23962, + [SMALL_STATE(1153)] = 23971, + [SMALL_STATE(1154)] = 23982, + [SMALL_STATE(1155)] = 23991, + [SMALL_STATE(1156)] = 24002, + [SMALL_STATE(1157)] = 24011, + [SMALL_STATE(1158)] = 24020, + [SMALL_STATE(1159)] = 24029, + [SMALL_STATE(1160)] = 24040, + [SMALL_STATE(1161)] = 24051, + [SMALL_STATE(1162)] = 24060, + [SMALL_STATE(1163)] = 24069, + [SMALL_STATE(1164)] = 24078, + [SMALL_STATE(1165)] = 24087, + [SMALL_STATE(1166)] = 24096, + [SMALL_STATE(1167)] = 24105, + [SMALL_STATE(1168)] = 24116, + [SMALL_STATE(1169)] = 24127, + [SMALL_STATE(1170)] = 24136, + [SMALL_STATE(1171)] = 24145, + [SMALL_STATE(1172)] = 24154, + [SMALL_STATE(1173)] = 24163, + [SMALL_STATE(1174)] = 24172, + [SMALL_STATE(1175)] = 24181, + [SMALL_STATE(1176)] = 24190, + [SMALL_STATE(1177)] = 24199, + [SMALL_STATE(1178)] = 24208, + [SMALL_STATE(1179)] = 24217, + [SMALL_STATE(1180)] = 24228, + [SMALL_STATE(1181)] = 24239, + [SMALL_STATE(1182)] = 24250, + [SMALL_STATE(1183)] = 24259, + [SMALL_STATE(1184)] = 24268, + [SMALL_STATE(1185)] = 24279, + [SMALL_STATE(1186)] = 24288, + [SMALL_STATE(1187)] = 24297, + [SMALL_STATE(1188)] = 24306, + [SMALL_STATE(1189)] = 24315, + [SMALL_STATE(1190)] = 24324, + [SMALL_STATE(1191)] = 24333, + [SMALL_STATE(1192)] = 24342, + [SMALL_STATE(1193)] = 24351, + [SMALL_STATE(1194)] = 24360, + [SMALL_STATE(1195)] = 24369, + [SMALL_STATE(1196)] = 24378, + [SMALL_STATE(1197)] = 24387, + [SMALL_STATE(1198)] = 24396, + [SMALL_STATE(1199)] = 24405, + [SMALL_STATE(1200)] = 24414, + [SMALL_STATE(1201)] = 24423, + [SMALL_STATE(1202)] = 24432, + [SMALL_STATE(1203)] = 24441, + [SMALL_STATE(1204)] = 24450, + [SMALL_STATE(1205)] = 24459, + [SMALL_STATE(1206)] = 24468, + [SMALL_STATE(1207)] = 24477, + [SMALL_STATE(1208)] = 24486, + [SMALL_STATE(1209)] = 24495, + [SMALL_STATE(1210)] = 24504, + [SMALL_STATE(1211)] = 24513, + [SMALL_STATE(1212)] = 24522, + [SMALL_STATE(1213)] = 24531, + [SMALL_STATE(1214)] = 24540, + [SMALL_STATE(1215)] = 24549, + [SMALL_STATE(1216)] = 24558, + [SMALL_STATE(1217)] = 24566, + [SMALL_STATE(1218)] = 24574, + [SMALL_STATE(1219)] = 24582, + [SMALL_STATE(1220)] = 24590, + [SMALL_STATE(1221)] = 24598, + [SMALL_STATE(1222)] = 24606, + [SMALL_STATE(1223)] = 24614, + [SMALL_STATE(1224)] = 24622, + [SMALL_STATE(1225)] = 24630, + [SMALL_STATE(1226)] = 24638, + [SMALL_STATE(1227)] = 24646, + [SMALL_STATE(1228)] = 24656, + [SMALL_STATE(1229)] = 24664, + [SMALL_STATE(1230)] = 24672, + [SMALL_STATE(1231)] = 24680, + [SMALL_STATE(1232)] = 24688, + [SMALL_STATE(1233)] = 24696, + [SMALL_STATE(1234)] = 24704, + [SMALL_STATE(1235)] = 24712, + [SMALL_STATE(1236)] = 24720, + [SMALL_STATE(1237)] = 24728, + [SMALL_STATE(1238)] = 24738, + [SMALL_STATE(1239)] = 24746, + [SMALL_STATE(1240)] = 24756, + [SMALL_STATE(1241)] = 24764, + [SMALL_STATE(1242)] = 24772, + [SMALL_STATE(1243)] = 24782, + [SMALL_STATE(1244)] = 24792, + [SMALL_STATE(1245)] = 24802, + [SMALL_STATE(1246)] = 24810, + [SMALL_STATE(1247)] = 24818, + [SMALL_STATE(1248)] = 24826, + [SMALL_STATE(1249)] = 24834, + [SMALL_STATE(1250)] = 24842, + [SMALL_STATE(1251)] = 24850, + [SMALL_STATE(1252)] = 24858, + [SMALL_STATE(1253)] = 24866, + [SMALL_STATE(1254)] = 24874, + [SMALL_STATE(1255)] = 24882, + [SMALL_STATE(1256)] = 24890, + [SMALL_STATE(1257)] = 24898, + [SMALL_STATE(1258)] = 24906, + [SMALL_STATE(1259)] = 24914, + [SMALL_STATE(1260)] = 24922, + [SMALL_STATE(1261)] = 24930, + [SMALL_STATE(1262)] = 24938, + [SMALL_STATE(1263)] = 24946, + [SMALL_STATE(1264)] = 24954, + [SMALL_STATE(1265)] = 24962, + [SMALL_STATE(1266)] = 24970, + [SMALL_STATE(1267)] = 24978, + [SMALL_STATE(1268)] = 24986, + [SMALL_STATE(1269)] = 24994, + [SMALL_STATE(1270)] = 25002, + [SMALL_STATE(1271)] = 25010, + [SMALL_STATE(1272)] = 25018, + [SMALL_STATE(1273)] = 25026, + [SMALL_STATE(1274)] = 25034, + [SMALL_STATE(1275)] = 25042, + [SMALL_STATE(1276)] = 25050, + [SMALL_STATE(1277)] = 25058, + [SMALL_STATE(1278)] = 25066, + [SMALL_STATE(1279)] = 25074, + [SMALL_STATE(1280)] = 25082, + [SMALL_STATE(1281)] = 25090, + [SMALL_STATE(1282)] = 25098, + [SMALL_STATE(1283)] = 25106, + [SMALL_STATE(1284)] = 25114, + [SMALL_STATE(1285)] = 25122, + [SMALL_STATE(1286)] = 25130, + [SMALL_STATE(1287)] = 25138, + [SMALL_STATE(1288)] = 25146, + [SMALL_STATE(1289)] = 25154, + [SMALL_STATE(1290)] = 25162, + [SMALL_STATE(1291)] = 25170, + [SMALL_STATE(1292)] = 25178, + [SMALL_STATE(1293)] = 25186, + [SMALL_STATE(1294)] = 25194, + [SMALL_STATE(1295)] = 25202, + [SMALL_STATE(1296)] = 25210, + [SMALL_STATE(1297)] = 25218, + [SMALL_STATE(1298)] = 25226, + [SMALL_STATE(1299)] = 25234, + [SMALL_STATE(1300)] = 25244, + [SMALL_STATE(1301)] = 25252, + [SMALL_STATE(1302)] = 25260, + [SMALL_STATE(1303)] = 25268, + [SMALL_STATE(1304)] = 25276, + [SMALL_STATE(1305)] = 25284, + [SMALL_STATE(1306)] = 25292, + [SMALL_STATE(1307)] = 25300, + [SMALL_STATE(1308)] = 25308, + [SMALL_STATE(1309)] = 25316, + [SMALL_STATE(1310)] = 25324, + [SMALL_STATE(1311)] = 25332, + [SMALL_STATE(1312)] = 25340, + [SMALL_STATE(1313)] = 25348, + [SMALL_STATE(1314)] = 25356, + [SMALL_STATE(1315)] = 25366, + [SMALL_STATE(1316)] = 25374, + [SMALL_STATE(1317)] = 25382, + [SMALL_STATE(1318)] = 25390, + [SMALL_STATE(1319)] = 25398, + [SMALL_STATE(1320)] = 25406, + [SMALL_STATE(1321)] = 25416, + [SMALL_STATE(1322)] = 25424, + [SMALL_STATE(1323)] = 25432, + [SMALL_STATE(1324)] = 25440, + [SMALL_STATE(1325)] = 25448, + [SMALL_STATE(1326)] = 25458, + [SMALL_STATE(1327)] = 25466, + [SMALL_STATE(1328)] = 25474, + [SMALL_STATE(1329)] = 25482, + [SMALL_STATE(1330)] = 25490, + [SMALL_STATE(1331)] = 25500, + [SMALL_STATE(1332)] = 25508, + [SMALL_STATE(1333)] = 25516, + [SMALL_STATE(1334)] = 25524, + [SMALL_STATE(1335)] = 25532, + [SMALL_STATE(1336)] = 25540, + [SMALL_STATE(1337)] = 25548, + [SMALL_STATE(1338)] = 25556, + [SMALL_STATE(1339)] = 25564, + [SMALL_STATE(1340)] = 25572, + [SMALL_STATE(1341)] = 25580, + [SMALL_STATE(1342)] = 25588, + [SMALL_STATE(1343)] = 25596, + [SMALL_STATE(1344)] = 25604, + [SMALL_STATE(1345)] = 25612, + [SMALL_STATE(1346)] = 25620, + [SMALL_STATE(1347)] = 25628, + [SMALL_STATE(1348)] = 25636, + [SMALL_STATE(1349)] = 25644, + [SMALL_STATE(1350)] = 25652, + [SMALL_STATE(1351)] = 25660, + [SMALL_STATE(1352)] = 25668, + [SMALL_STATE(1353)] = 25676, + [SMALL_STATE(1354)] = 25684, + [SMALL_STATE(1355)] = 25692, + [SMALL_STATE(1356)] = 25700, + [SMALL_STATE(1357)] = 25708, + [SMALL_STATE(1358)] = 25716, + [SMALL_STATE(1359)] = 25724, + [SMALL_STATE(1360)] = 25734, + [SMALL_STATE(1361)] = 25742, + [SMALL_STATE(1362)] = 25750, + [SMALL_STATE(1363)] = 25758, + [SMALL_STATE(1364)] = 25766, + [SMALL_STATE(1365)] = 25774, + [SMALL_STATE(1366)] = 25782, + [SMALL_STATE(1367)] = 25790, + [SMALL_STATE(1368)] = 25798, + [SMALL_STATE(1369)] = 25806, + [SMALL_STATE(1370)] = 25814, + [SMALL_STATE(1371)] = 25824, + [SMALL_STATE(1372)] = 25832, + [SMALL_STATE(1373)] = 25840, + [SMALL_STATE(1374)] = 25848, + [SMALL_STATE(1375)] = 25858, + [SMALL_STATE(1376)] = 25866, + [SMALL_STATE(1377)] = 25874, + [SMALL_STATE(1378)] = 25882, + [SMALL_STATE(1379)] = 25890, + [SMALL_STATE(1380)] = 25898, + [SMALL_STATE(1381)] = 25906, + [SMALL_STATE(1382)] = 25914, + [SMALL_STATE(1383)] = 25922, + [SMALL_STATE(1384)] = 25930, + [SMALL_STATE(1385)] = 25938, + [SMALL_STATE(1386)] = 25946, + [SMALL_STATE(1387)] = 25954, + [SMALL_STATE(1388)] = 25962, + [SMALL_STATE(1389)] = 25970, + [SMALL_STATE(1390)] = 25978, + [SMALL_STATE(1391)] = 25986, + [SMALL_STATE(1392)] = 25994, + [SMALL_STATE(1393)] = 26002, + [SMALL_STATE(1394)] = 26010, + [SMALL_STATE(1395)] = 26018, + [SMALL_STATE(1396)] = 26026, + [SMALL_STATE(1397)] = 26034, + [SMALL_STATE(1398)] = 26042, + [SMALL_STATE(1399)] = 26050, + [SMALL_STATE(1400)] = 26058, + [SMALL_STATE(1401)] = 26066, + [SMALL_STATE(1402)] = 26074, + [SMALL_STATE(1403)] = 26082, + [SMALL_STATE(1404)] = 26090, + [SMALL_STATE(1405)] = 26098, + [SMALL_STATE(1406)] = 26106, + [SMALL_STATE(1407)] = 26114, + [SMALL_STATE(1408)] = 26122, + [SMALL_STATE(1409)] = 26130, + [SMALL_STATE(1410)] = 26138, + [SMALL_STATE(1411)] = 26145, + [SMALL_STATE(1412)] = 26152, + [SMALL_STATE(1413)] = 26159, + [SMALL_STATE(1414)] = 26166, + [SMALL_STATE(1415)] = 26173, + [SMALL_STATE(1416)] = 26180, + [SMALL_STATE(1417)] = 26187, + [SMALL_STATE(1418)] = 26194, + [SMALL_STATE(1419)] = 26201, + [SMALL_STATE(1420)] = 26208, + [SMALL_STATE(1421)] = 26215, + [SMALL_STATE(1422)] = 26222, + [SMALL_STATE(1423)] = 26229, + [SMALL_STATE(1424)] = 26236, + [SMALL_STATE(1425)] = 26243, + [SMALL_STATE(1426)] = 26250, + [SMALL_STATE(1427)] = 26257, + [SMALL_STATE(1428)] = 26264, + [SMALL_STATE(1429)] = 26271, + [SMALL_STATE(1430)] = 26278, + [SMALL_STATE(1431)] = 26285, + [SMALL_STATE(1432)] = 26292, + [SMALL_STATE(1433)] = 26299, + [SMALL_STATE(1434)] = 26306, + [SMALL_STATE(1435)] = 26313, + [SMALL_STATE(1436)] = 26320, + [SMALL_STATE(1437)] = 26327, + [SMALL_STATE(1438)] = 26334, + [SMALL_STATE(1439)] = 26341, + [SMALL_STATE(1440)] = 26348, + [SMALL_STATE(1441)] = 26355, + [SMALL_STATE(1442)] = 26362, + [SMALL_STATE(1443)] = 26369, + [SMALL_STATE(1444)] = 26376, + [SMALL_STATE(1445)] = 26383, + [SMALL_STATE(1446)] = 26390, + [SMALL_STATE(1447)] = 26397, + [SMALL_STATE(1448)] = 26404, + [SMALL_STATE(1449)] = 26411, + [SMALL_STATE(1450)] = 26418, + [SMALL_STATE(1451)] = 26425, + [SMALL_STATE(1452)] = 26432, + [SMALL_STATE(1453)] = 26439, + [SMALL_STATE(1454)] = 26446, + [SMALL_STATE(1455)] = 26453, + [SMALL_STATE(1456)] = 26460, + [SMALL_STATE(1457)] = 26467, + [SMALL_STATE(1458)] = 26474, + [SMALL_STATE(1459)] = 26481, + [SMALL_STATE(1460)] = 26488, + [SMALL_STATE(1461)] = 26495, + [SMALL_STATE(1462)] = 26502, + [SMALL_STATE(1463)] = 26509, + [SMALL_STATE(1464)] = 26516, + [SMALL_STATE(1465)] = 26523, + [SMALL_STATE(1466)] = 26530, + [SMALL_STATE(1467)] = 26537, + [SMALL_STATE(1468)] = 26544, + [SMALL_STATE(1469)] = 26551, + [SMALL_STATE(1470)] = 26558, + [SMALL_STATE(1471)] = 26565, + [SMALL_STATE(1472)] = 26572, + [SMALL_STATE(1473)] = 26579, + [SMALL_STATE(1474)] = 26586, + [SMALL_STATE(1475)] = 26593, + [SMALL_STATE(1476)] = 26600, + [SMALL_STATE(1477)] = 26607, + [SMALL_STATE(1478)] = 26614, + [SMALL_STATE(1479)] = 26621, + [SMALL_STATE(1480)] = 26628, + [SMALL_STATE(1481)] = 26635, + [SMALL_STATE(1482)] = 26642, + [SMALL_STATE(1483)] = 26649, + [SMALL_STATE(1484)] = 26656, + [SMALL_STATE(1485)] = 26663, + [SMALL_STATE(1486)] = 26670, + [SMALL_STATE(1487)] = 26677, + [SMALL_STATE(1488)] = 26684, + [SMALL_STATE(1489)] = 26691, + [SMALL_STATE(1490)] = 26698, + [SMALL_STATE(1491)] = 26705, + [SMALL_STATE(1492)] = 26712, + [SMALL_STATE(1493)] = 26719, + [SMALL_STATE(1494)] = 26726, + [SMALL_STATE(1495)] = 26733, + [SMALL_STATE(1496)] = 26740, + [SMALL_STATE(1497)] = 26747, + [SMALL_STATE(1498)] = 26754, + [SMALL_STATE(1499)] = 26761, + [SMALL_STATE(1500)] = 26768, + [SMALL_STATE(1501)] = 26775, + [SMALL_STATE(1502)] = 26782, + [SMALL_STATE(1503)] = 26789, + [SMALL_STATE(1504)] = 26796, + [SMALL_STATE(1505)] = 26803, + [SMALL_STATE(1506)] = 26810, + [SMALL_STATE(1507)] = 26817, + [SMALL_STATE(1508)] = 26824, + [SMALL_STATE(1509)] = 26831, + [SMALL_STATE(1510)] = 26838, + [SMALL_STATE(1511)] = 26845, + [SMALL_STATE(1512)] = 26852, + [SMALL_STATE(1513)] = 26859, + [SMALL_STATE(1514)] = 26866, + [SMALL_STATE(1515)] = 26873, + [SMALL_STATE(1516)] = 26880, + [SMALL_STATE(1517)] = 26887, + [SMALL_STATE(1518)] = 26894, + [SMALL_STATE(1519)] = 26901, + [SMALL_STATE(1520)] = 26908, + [SMALL_STATE(1521)] = 26915, + [SMALL_STATE(1522)] = 26922, + [SMALL_STATE(1523)] = 26929, + [SMALL_STATE(1524)] = 26936, + [SMALL_STATE(1525)] = 26943, + [SMALL_STATE(1526)] = 26950, + [SMALL_STATE(1527)] = 26957, + [SMALL_STATE(1528)] = 26964, + [SMALL_STATE(1529)] = 26971, + [SMALL_STATE(1530)] = 26978, + [SMALL_STATE(1531)] = 26985, + [SMALL_STATE(1532)] = 26992, + [SMALL_STATE(1533)] = 26999, + [SMALL_STATE(1534)] = 27006, + [SMALL_STATE(1535)] = 27013, + [SMALL_STATE(1536)] = 27020, + [SMALL_STATE(1537)] = 27027, + [SMALL_STATE(1538)] = 27034, + [SMALL_STATE(1539)] = 27041, + [SMALL_STATE(1540)] = 27048, + [SMALL_STATE(1541)] = 27055, + [SMALL_STATE(1542)] = 27062, + [SMALL_STATE(1543)] = 27069, + [SMALL_STATE(1544)] = 27076, + [SMALL_STATE(1545)] = 27083, + [SMALL_STATE(1546)] = 27090, + [SMALL_STATE(1547)] = 27097, + [SMALL_STATE(1548)] = 27104, + [SMALL_STATE(1549)] = 27111, + [SMALL_STATE(1550)] = 27118, + [SMALL_STATE(1551)] = 27125, + [SMALL_STATE(1552)] = 27132, + [SMALL_STATE(1553)] = 27139, + [SMALL_STATE(1554)] = 27146, + [SMALL_STATE(1555)] = 27153, + [SMALL_STATE(1556)] = 27160, + [SMALL_STATE(1557)] = 27167, + [SMALL_STATE(1558)] = 27174, + [SMALL_STATE(1559)] = 27181, + [SMALL_STATE(1560)] = 27188, + [SMALL_STATE(1561)] = 27195, + [SMALL_STATE(1562)] = 27202, + [SMALL_STATE(1563)] = 27209, + [SMALL_STATE(1564)] = 27216, + [SMALL_STATE(1565)] = 27223, + [SMALL_STATE(1566)] = 27230, + [SMALL_STATE(1567)] = 27237, + [SMALL_STATE(1568)] = 27244, + [SMALL_STATE(1569)] = 27251, + [SMALL_STATE(1570)] = 27258, + [SMALL_STATE(1571)] = 27265, + [SMALL_STATE(1572)] = 27272, + [SMALL_STATE(1573)] = 27279, + [SMALL_STATE(1574)] = 27286, + [SMALL_STATE(1575)] = 27293, + [SMALL_STATE(1576)] = 27300, + [SMALL_STATE(1577)] = 27307, + [SMALL_STATE(1578)] = 27314, +}; + +static const TSParseActionEntry ts_parse_actions[] = { + [0] = {.entry = {.count = 0, .reusable = false}}, + [1] = {.entry = {.count = 1, .reusable = false}}, RECOVER(), + [3] = {.entry = {.count = 1, .reusable = true}}, SHIFT_EXTRA(), + [5] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1465), + [7] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1427), + [9] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1515), + [11] = {.entry = {.count = 1, .reusable = true}}, SHIFT(694), + [13] = {.entry = {.count = 1, .reusable = true}}, SHIFT(12), + [15] = {.entry = {.count = 1, .reusable = true}}, SHIFT(250), + [17] = {.entry = {.count = 1, .reusable = true}}, SHIFT(10), + [19] = {.entry = {.count = 1, .reusable = true}}, SHIFT(8), + [21] = {.entry = {.count = 1, .reusable = true}}, SHIFT(3), + [23] = {.entry = {.count = 1, .reusable = true}}, SHIFT(4), + [25] = {.entry = {.count = 1, .reusable = true}}, SHIFT(2), + [27] = {.entry = {.count = 1, .reusable = true}}, SHIFT(5), + [29] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1078), + [31] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1081), + [33] = {.entry = {.count = 1, .reusable = true}}, SHIFT(32), + [35] = {.entry = {.count = 1, .reusable = true}}, SHIFT(27), + [37] = {.entry = {.count = 1, .reusable = true}}, SHIFT(13), + [39] = {.entry = {.count = 1, .reusable = true}}, SHIFT(14), + [41] = {.entry = {.count = 1, .reusable = true}}, SHIFT(443), + [43] = {.entry = {.count = 1, .reusable = true}}, SHIFT(459), + [45] = {.entry = {.count = 1, .reusable = true}}, SHIFT(516), + [47] = {.entry = {.count = 1, .reusable = true}}, SHIFT(525), + [49] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1030), + [51] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1036), + [53] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1135), + [55] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1142), + [57] = {.entry = {.count = 1, .reusable = true}}, SHIFT(118), + [59] = {.entry = {.count = 1, .reusable = true}}, SHIFT(116), + [61] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1498), + [63] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1519), + [65] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1474), + [67] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1486), + [69] = {.entry = {.count = 1, .reusable = true}}, SHIFT(9), + [71] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_val_itm, 1, 0, 0), + [73] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1140), + [75] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1141), + [77] = {.entry = {.count = 1, .reusable = true}}, SHIFT(26), + [79] = {.entry = {.count = 1, .reusable = true}}, SHIFT(25), + [81] = {.entry = {.count = 1, .reusable = true}}, SHIFT(18), + [83] = {.entry = {.count = 1, .reusable = true}}, SHIFT(16), + [85] = {.entry = {.count = 1, .reusable = true}}, SHIFT(427), + [87] = {.entry = {.count = 1, .reusable = true}}, SHIFT(428), + [89] = {.entry = {.count = 1, .reusable = true}}, SHIFT(487), + [91] = {.entry = {.count = 1, .reusable = true}}, SHIFT(494), + [93] = {.entry = {.count = 1, .reusable = true}}, SHIFT(273), + [95] = {.entry = {.count = 1, .reusable = true}}, SHIFT(280), + [97] = {.entry = {.count = 1, .reusable = true}}, SHIFT(336), + [99] = {.entry = {.count = 1, .reusable = true}}, SHIFT(337), + [101] = {.entry = {.count = 1, .reusable = true}}, SHIFT(96), + [103] = {.entry = {.count = 1, .reusable = true}}, SHIFT(97), + [105] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1433), + [107] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1431), + [109] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1435), + [111] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1437), + [113] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_key_itm, 1, 0, 0), + [115] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_key_itm, 1, 0, 0), + [117] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_val_itm, 1, 0, 0), + [119] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_key_itm, 1, 0, 0), + [121] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_val_itm, 1, 0, 0), + [123] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_seq_itm, 1, 0, 0), + [125] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1111), + [127] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1112), + [129] = {.entry = {.count = 1, .reusable = true}}, SHIFT(28), + [131] = {.entry = {.count = 1, .reusable = true}}, SHIFT(29), + [133] = {.entry = {.count = 1, .reusable = true}}, SHIFT(15), + [135] = {.entry = {.count = 1, .reusable = true}}, SHIFT(17), + [137] = {.entry = {.count = 1, .reusable = true}}, SHIFT(446), + [139] = {.entry = {.count = 1, .reusable = true}}, SHIFT(447), + [141] = {.entry = {.count = 1, .reusable = true}}, SHIFT(482), + [143] = {.entry = {.count = 1, .reusable = true}}, SHIFT(483), + [145] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1198), + [147] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1107), + [149] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1380), + [151] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1381), + [153] = {.entry = {.count = 1, .reusable = true}}, SHIFT(122), + [155] = {.entry = {.count = 1, .reusable = true}}, SHIFT(123), + [157] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1430), + [159] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1483), + [161] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1432), + [163] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1508), + [165] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_seq_itm, 1, 0, 0), + [167] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_seq_itm, 1, 0, 0), + [169] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__blk_imp_itm_tal, 1, 0, 0), + [171] = {.entry = {.count = 1, .reusable = true}}, SHIFT(65), + [173] = {.entry = {.count = 1, .reusable = true}}, SHIFT(49), + [175] = {.entry = {.count = 1, .reusable = true}}, SHIFT(449), + [177] = {.entry = {.count = 1, .reusable = true}}, SHIFT(485), + [179] = {.entry = {.count = 1, .reusable = true}}, SHIFT(315), + [181] = {.entry = {.count = 1, .reusable = true}}, SHIFT(98), + [183] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1560), + [185] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1544), + [187] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__exp_doc, 1, 0, 0), + [189] = {.entry = {.count = 1, .reusable = true}}, SHIFT(57), + [191] = {.entry = {.count = 1, .reusable = true}}, SHIFT(45), + [193] = {.entry = {.count = 1, .reusable = true}}, SHIFT(430), + [195] = {.entry = {.count = 1, .reusable = true}}, SHIFT(490), + [197] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1106), + [199] = {.entry = {.count = 1, .reusable = true}}, SHIFT(124), + [201] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1472), + [203] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1494), + [205] = {.entry = {.count = 1, .reusable = true}}, SHIFT(24), + [207] = {.entry = {.count = 1, .reusable = true}}, SHIFT(60), + [209] = {.entry = {.count = 1, .reusable = true}}, SHIFT(19), + [211] = {.entry = {.count = 1, .reusable = true}}, SHIFT(42), + [213] = {.entry = {.count = 1, .reusable = true}}, SHIFT(988), + [215] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1133), + [217] = {.entry = {.count = 1, .reusable = true}}, SHIFT(40), + [219] = {.entry = {.count = 1, .reusable = true}}, SHIFT(84), + [221] = {.entry = {.count = 1, .reusable = true}}, SHIFT(69), + [223] = {.entry = {.count = 1, .reusable = true}}, SHIFT(94), + [225] = {.entry = {.count = 1, .reusable = true}}, SHIFT(448), + [227] = {.entry = {.count = 1, .reusable = true}}, SHIFT(462), + [229] = {.entry = {.count = 1, .reusable = true}}, SHIFT(514), + [231] = {.entry = {.count = 1, .reusable = true}}, SHIFT(517), + [233] = {.entry = {.count = 1, .reusable = true}}, SHIFT(677), + [235] = {.entry = {.count = 1, .reusable = true}}, SHIFT(679), + [237] = {.entry = {.count = 1, .reusable = true}}, SHIFT(683), + [239] = {.entry = {.count = 1, .reusable = true}}, SHIFT(684), + [241] = {.entry = {.count = 1, .reusable = true}}, SHIFT(183), + [243] = {.entry = {.count = 1, .reusable = true}}, SHIFT(184), + [245] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1438), + [247] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1503), + [249] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1440), + [251] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1505), + [253] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1076), + [255] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1144), + [257] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1258), + [259] = {.entry = {.count = 1, .reusable = true}}, SHIFT(285), + [261] = {.entry = {.count = 1, .reusable = true}}, SHIFT(370), + [263] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1259), + [265] = {.entry = {.count = 1, .reusable = true}}, SHIFT(369), + [267] = {.entry = {.count = 1, .reusable = true}}, SHIFT(569), + [269] = {.entry = {.count = 1, .reusable = true}}, SHIFT(570), + [271] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1320), + [273] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1321), + [275] = {.entry = {.count = 1, .reusable = true}}, SHIFT(714), + [277] = {.entry = {.count = 1, .reusable = true}}, SHIFT(715), + [279] = {.entry = {.count = 1, .reusable = true}}, SHIFT(830), + [281] = {.entry = {.count = 1, .reusable = true}}, SHIFT(831), + [283] = {.entry = {.count = 1, .reusable = true}}, SHIFT(878), + [285] = {.entry = {.count = 1, .reusable = true}}, SHIFT(879), + [287] = {.entry = {.count = 1, .reusable = true}}, SHIFT(30), + [289] = {.entry = {.count = 1, .reusable = true}}, SHIFT(64), + [291] = {.entry = {.count = 1, .reusable = true}}, SHIFT(555), + [293] = {.entry = {.count = 1, .reusable = true}}, SHIFT(566), + [295] = {.entry = {.count = 1, .reusable = true}}, SHIFT(21), + [297] = {.entry = {.count = 1, .reusable = true}}, SHIFT(53), + [299] = {.entry = {.count = 1, .reusable = true}}, SHIFT(41), + [301] = {.entry = {.count = 1, .reusable = true}}, SHIFT(86), + [303] = {.entry = {.count = 1, .reusable = true}}, SHIFT(55), + [305] = {.entry = {.count = 1, .reusable = true}}, SHIFT(95), + [307] = {.entry = {.count = 1, .reusable = true}}, SHIFT(437), + [309] = {.entry = {.count = 1, .reusable = true}}, SHIFT(440), + [311] = {.entry = {.count = 1, .reusable = true}}, SHIFT(513), + [313] = {.entry = {.count = 1, .reusable = true}}, SHIFT(533), + [315] = {.entry = {.count = 1, .reusable = true}}, SHIFT(695), + [317] = {.entry = {.count = 1, .reusable = true}}, SHIFT(696), + [319] = {.entry = {.count = 1, .reusable = true}}, SHIFT(697), + [321] = {.entry = {.count = 1, .reusable = true}}, SHIFT(699), + [323] = {.entry = {.count = 1, .reusable = true}}, SHIFT(188), + [325] = {.entry = {.count = 1, .reusable = true}}, SHIFT(186), + [327] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1578), + [329] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1434), + [331] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1504), + [333] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1436), + [335] = {.entry = {.count = 1, .reusable = true}}, SHIFT(284), + [337] = {.entry = {.count = 1, .reusable = true}}, SHIFT(367), + [339] = {.entry = {.count = 1, .reusable = true}}, SHIFT(366), + [341] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1047), + [343] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1109), + [345] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1128), + [347] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1247), + [349] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1256), + [351] = {.entry = {.count = 1, .reusable = true}}, SHIFT(711), + [353] = {.entry = {.count = 1, .reusable = true}}, SHIFT(712), + [355] = {.entry = {.count = 1, .reusable = true}}, SHIFT(827), + [357] = {.entry = {.count = 1, .reusable = true}}, SHIFT(828), + [359] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1131), + [361] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1314), + [363] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1316), + [365] = {.entry = {.count = 1, .reusable = true}}, SHIFT(876), + [367] = {.entry = {.count = 1, .reusable = true}}, SHIFT(784), + [369] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_prp_val, 1, 0, 0), + [371] = {.entry = {.count = 1, .reusable = true}}, SHIFT(409), + [373] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1479), + [375] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1441), + [377] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_prp_val, 1, 0, 0), + [379] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1426), + [381] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_w_bgn_w_end_seq, 1, 0, 0), + [383] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_wo_bgn_w_end_seq, 1, 0, 0), + [385] = {.entry = {.count = 1, .reusable = true}}, SHIFT(33), + [387] = {.entry = {.count = 1, .reusable = true}}, SHIFT(58), + [389] = {.entry = {.count = 1, .reusable = true}}, SHIFT(20), + [391] = {.entry = {.count = 1, .reusable = true}}, SHIFT(47), + [393] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_flw_exp_par, 1, 0, 0), REDUCE(sym__r_sgl_flw_exp_par, 1, 0, 0), + [396] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_exp_par, 1, 0, 0), + [398] = {.entry = {.count = 1, .reusable = true}}, SHIFT(454), + [400] = {.entry = {.count = 1, .reusable = true}}, SHIFT(431), + [402] = {.entry = {.count = 1, .reusable = true}}, SHIFT(501), + [404] = {.entry = {.count = 1, .reusable = true}}, SHIFT(509), + [406] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1315), + [408] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1216), + [410] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1262), + [412] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1263), + [414] = {.entry = {.count = 1, .reusable = true}}, SHIFT(226), + [416] = {.entry = {.count = 1, .reusable = true}}, SHIFT(233), + [418] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1545), + [420] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1543), + [422] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1480), + [424] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1481), + [426] = {.entry = {.count = 1, .reusable = true}}, SHIFT(61), + [428] = {.entry = {.count = 1, .reusable = true}}, SHIFT(46), + [430] = {.entry = {.count = 1, .reusable = true}}, SHIFT(571), + [432] = {.entry = {.count = 1, .reusable = true}}, SHIFT(87), + [434] = {.entry = {.count = 1, .reusable = true}}, SHIFT(88), + [436] = {.entry = {.count = 1, .reusable = true}}, SHIFT(429), + [438] = {.entry = {.count = 1, .reusable = true}}, SHIFT(523), + [440] = {.entry = {.count = 1, .reusable = true}}, SHIFT(185), + [442] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1323), + [444] = {.entry = {.count = 1, .reusable = true}}, SHIFT(832), + [446] = {.entry = {.count = 1, .reusable = true}}, SHIFT(880), + [448] = {.entry = {.count = 1, .reusable = true}}, SHIFT(716), + [450] = {.entry = {.count = 1, .reusable = true}}, SHIFT(31), + [452] = {.entry = {.count = 1, .reusable = true}}, SHIFT(63), + [454] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_flw_njl_ann_par, 1, 0, 0), REDUCE(sym__r_sgl_flw_njl_ann_par, 1, 0, 0), + [457] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_njl_ann_par, 1, 0, 0), + [459] = {.entry = {.count = 1, .reusable = true}}, SHIFT(22), + [461] = {.entry = {.count = 1, .reusable = true}}, SHIFT(48), + [463] = {.entry = {.count = 1, .reusable = true}}, SHIFT(461), + [465] = {.entry = {.count = 1, .reusable = true}}, SHIFT(441), + [467] = {.entry = {.count = 1, .reusable = true}}, SHIFT(515), + [469] = {.entry = {.count = 1, .reusable = true}}, SHIFT(527), + [471] = {.entry = {.count = 1, .reusable = true}}, SHIFT(955), + [473] = {.entry = {.count = 1, .reusable = true}}, SHIFT(957), + [475] = {.entry = {.count = 1, .reusable = true}}, SHIFT(958), + [477] = {.entry = {.count = 1, .reusable = true}}, SHIFT(959), + [479] = {.entry = {.count = 1, .reusable = true}}, SHIFT(198), + [481] = {.entry = {.count = 1, .reusable = true}}, SHIFT(204), + [483] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1548), + [485] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1546), + [487] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1512), + [489] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1513), + [491] = {.entry = {.count = 1, .reusable = true}}, SHIFT(59), + [493] = {.entry = {.count = 1, .reusable = true}}, SHIFT(43), + [495] = {.entry = {.count = 1, .reusable = true}}, SHIFT(85), + [497] = {.entry = {.count = 1, .reusable = true}}, SHIFT(91), + [499] = {.entry = {.count = 1, .reusable = true}}, SHIFT(457), + [501] = {.entry = {.count = 1, .reusable = true}}, SHIFT(511), + [503] = {.entry = {.count = 1, .reusable = true}}, SHIFT(187), + [505] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1318), + [507] = {.entry = {.count = 1, .reusable = true}}, SHIFT(568), + [509] = {.entry = {.count = 1, .reusable = true}}, SHIFT(829), + [511] = {.entry = {.count = 1, .reusable = true}}, SHIFT(713), + [513] = {.entry = {.count = 1, .reusable = true}}, SHIFT(877), + [515] = {.entry = {.count = 1, .reusable = true}}, SHIFT(34), + [517] = {.entry = {.count = 1, .reusable = true}}, SHIFT(66), + [519] = {.entry = {.count = 1, .reusable = true}}, SHIFT(23), + [521] = {.entry = {.count = 1, .reusable = true}}, SHIFT(50), + [523] = {.entry = {.count = 1, .reusable = true}}, SHIFT(468), + [525] = {.entry = {.count = 1, .reusable = true}}, SHIFT(450), + [527] = {.entry = {.count = 1, .reusable = true}}, SHIFT(528), + [529] = {.entry = {.count = 1, .reusable = true}}, SHIFT(489), + [531] = {.entry = {.count = 1, .reusable = true}}, SHIFT(813), + [533] = {.entry = {.count = 1, .reusable = true}}, SHIFT(796), + [535] = {.entry = {.count = 1, .reusable = true}}, SHIFT(797), + [537] = {.entry = {.count = 1, .reusable = true}}, SHIFT(798), + [539] = {.entry = {.count = 1, .reusable = true}}, SHIFT(201), + [541] = {.entry = {.count = 1, .reusable = true}}, SHIFT(193), + [543] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1554), + [545] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1552), + [547] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1540), + [549] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1541), + [551] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map_dat, 2, 0, 0), + [553] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map_dat, 2, 0, 0), + [555] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map_dat, 3, 0, 0), + [557] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map_dat, 3, 0, 0), + [559] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq_dat, 2, 0, 0), + [561] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq_dat, 2, 0, 0), + [563] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq_dat, 3, 0, 0), + [565] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq_dat, 3, 0, 0), + [567] = {.entry = {.count = 1, .reusable = true}}, SHIFT(62), + [569] = {.entry = {.count = 1, .reusable = true}}, SHIFT(52), + [571] = {.entry = {.count = 1, .reusable = true}}, SHIFT(439), + [573] = {.entry = {.count = 1, .reusable = true}}, SHIFT(520), + [575] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1281), + [577] = {.entry = {.count = 1, .reusable = true}}, SHIFT(67), + [579] = {.entry = {.count = 1, .reusable = true}}, SHIFT(51), + [581] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_exp_par, 1, 0, 0), + [583] = {.entry = {.count = 1, .reusable = true}}, SHIFT(421), + [585] = {.entry = {.count = 1, .reusable = true}}, SHIFT(505), + [587] = {.entry = {.count = 1, .reusable = true}}, SHIFT(229), + [589] = {.entry = {.count = 1, .reusable = true}}, SHIFT(56), + [591] = {.entry = {.count = 1, .reusable = true}}, SHIFT(44), + [593] = {.entry = {.count = 1, .reusable = true}}, SHIFT(470), + [595] = {.entry = {.count = 1, .reusable = true}}, SHIFT(532), + [597] = {.entry = {.count = 1, .reusable = true}}, SHIFT(195), + [599] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_jsl_ann_par, 1, 0, 0), + [601] = {.entry = {.count = 1, .reusable = true}}, SHIFT(68), + [603] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_jsl_ann_par, 1, 0, 0), + [605] = {.entry = {.count = 1, .reusable = true}}, SHIFT(54), + [607] = {.entry = {.count = 1, .reusable = true}}, SHIFT(463), + [609] = {.entry = {.count = 1, .reusable = true}}, SHIFT(519), + [611] = {.entry = {.count = 1, .reusable = true}}, SHIFT(192), + [613] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_njl_ann_par, 1, 0, 0), + [615] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_prp, 1, 0, 0), + [617] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_prp, 1, 0, 0), + [619] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_prp, 1, 0, 0), REDUCE(sym__r_sgl_prp, 1, 0, 0), + [622] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1542), + [624] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_prp, 1, 0, 0), SHIFT(1539), + [627] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_prp, 1, 0, 0), + [629] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_prp, 1, 0, 0), + [631] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__br_prp, 1, 0, 0), REDUCE(sym__br_sgl_prp, 1, 0, 0), + [634] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__br_prp, 1, 0, 0), SHIFT(1539), + [637] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1571), + [639] = {.entry = {.count = 1, .reusable = true}}, SHIFT(104), + [641] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__br_prp, 1, 0, 0), SHIFT(109), + [644] = {.entry = {.count = 1, .reusable = true}}, SHIFT(103), + [646] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_prp, 1, 0, 0), SHIFT(108), + [649] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_acr, 2, 0, 0), + [651] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_acr, 2, 0, 0), + [653] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_prp, 2, 0, 0), + [655] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_prp, 2, 0, 0), + [657] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_prp, 2, 0, 0), REDUCE(sym__r_sgl_prp, 2, 0, 0), + [660] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_prp, 2, 0, 0), + [662] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_prp, 2, 0, 0), + [664] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__br_prp, 2, 0, 0), REDUCE(sym__br_sgl_prp, 2, 0, 0), + [667] = {.entry = {.count = 1, .reusable = true}}, SHIFT(108), + [669] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1478), + [671] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__br_prp, 1, 0, 0), SHIFT(1439), + [674] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_prp, 1, 0, 0), SHIFT(1439), + [677] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1538), + [679] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_prp, 1, 0, 0), SHIFT(1511), + [682] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__br_prp, 1, 0, 0), SHIFT(1511), + [685] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1510), + [687] = {.entry = {.count = 1, .reusable = true}}, SHIFT(6), + [689] = {.entry = {.count = 1, .reusable = true}}, SHIFT(7), + [691] = {.entry = {.count = 1, .reusable = true}}, SHIFT(140), + [693] = {.entry = {.count = 1, .reusable = true}}, SHIFT(141), + [695] = {.entry = {.count = 1, .reusable = true}}, SHIFT(970), + [697] = {.entry = {.count = 1, .reusable = true}}, SHIFT(975), + [699] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1461), + [701] = {.entry = {.count = 1, .reusable = true}}, SHIFT(405), + [703] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1484), + [705] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1488), + [707] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1065), + [709] = {.entry = {.count = 1, .reusable = true}}, SHIFT(147), + [711] = {.entry = {.count = 1, .reusable = true}}, SHIFT(148), + [713] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1322), + [715] = {.entry = {.count = 1, .reusable = true}}, SHIFT(189), + [717] = {.entry = {.count = 1, .reusable = true}}, SHIFT(200), + [719] = {.entry = {.count = 1, .reusable = true}}, SHIFT(971), + [721] = {.entry = {.count = 1, .reusable = true}}, SHIFT(972), + [723] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1059), + [725] = {.entry = {.count = 1, .reusable = true}}, SHIFT(393), + [727] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1565), + [729] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1550), + [731] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(6), + [734] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(7), + [737] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(140), + [740] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(141), + [743] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(970), + [746] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(975), + [749] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(1461), + [752] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(405), + [755] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(1484), + [758] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(1488), + [761] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), + [763] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1080), + [765] = {.entry = {.count = 1, .reusable = true}}, SHIFT(165), + [767] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_prp, 1, 0, 0), SHIFT(176), + [770] = {.entry = {.count = 1, .reusable = true}}, SHIFT(136), + [772] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1423), + [774] = {.entry = {.count = 1, .reusable = true}}, SHIFT(137), + [776] = {.entry = {.count = 1, .reusable = true}}, SHIFT(205), + [778] = {.entry = {.count = 1, .reusable = true}}, SHIFT(199), + [780] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1017), + [782] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1019), + [784] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1077), + [786] = {.entry = {.count = 1, .reusable = true}}, SHIFT(392), + [788] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1564), + [790] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1547), + [792] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1517), + [794] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1296), + [796] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1297), + [798] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1139), + [800] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1145), + [802] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1364), + [804] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1365), + [806] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1445), + [808] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1496), + [810] = {.entry = {.count = 1, .reusable = true}}, SHIFT(299), + [812] = {.entry = {.count = 1, .reusable = true}}, SHIFT(301), + [814] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1176), + [816] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1069), + [818] = {.entry = {.count = 1, .reusable = true}}, SHIFT(166), + [820] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__br_prp, 1, 0, 0), SHIFT(169), + [823] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1050), + [825] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1064), + [827] = {.entry = {.count = 1, .reusable = true}}, SHIFT(387), + [829] = {.entry = {.count = 1, .reusable = true}}, SHIFT(292), + [831] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1509), + [833] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1422), + [835] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1257), + [837] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1264), + [839] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1317), + [841] = {.entry = {.count = 1, .reusable = true}}, SHIFT(168), + [843] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_prp, 1, 0, 0), SHIFT(178), + [846] = {.entry = {.count = 1, .reusable = true}}, SHIFT(172), + [848] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__br_prp, 1, 0, 0), SHIFT(179), + [851] = {.entry = {.count = 1, .reusable = true}}, SHIFT(176), + [853] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_col_dat, 3, 0, 0), + [855] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_col_dat, 2, 0, 0), + [857] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1557), + [859] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1555), + [861] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1410), + [863] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1549), + [865] = {.entry = {.count = 1, .reusable = true}}, SHIFT(151), + [867] = {.entry = {.count = 1, .reusable = true}}, SHIFT(152), + [869] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_exp_par, 1, 0, 0), + [871] = {.entry = {.count = 1, .reusable = true}}, SHIFT(982), + [873] = {.entry = {.count = 1, .reusable = true}}, SHIFT(983), + [875] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1475), + [877] = {.entry = {.count = 1, .reusable = true}}, SHIFT(403), + [879] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1572), + [881] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1559), + [883] = {.entry = {.count = 1, .reusable = true}}, SHIFT(221), + [885] = {.entry = {.count = 1, .reusable = true}}, SHIFT(219), + [887] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1567), + [889] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1561), + [891] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1569), + [893] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1563), + [895] = {.entry = {.count = 1, .reusable = true}}, SHIFT(222), + [897] = {.entry = {.count = 1, .reusable = true}}, SHIFT(153), + [899] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_njl_ann_par, 1, 0, 0), + [901] = {.entry = {.count = 1, .reusable = true}}, SHIFT(154), + [903] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1010), + [905] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1011), + [907] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1293), + [909] = {.entry = {.count = 1, .reusable = true}}, SHIFT(396), + [911] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1568), + [913] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1553), + [915] = {.entry = {.count = 1, .reusable = true}}, SHIFT(155), + [917] = {.entry = {.count = 1, .reusable = true}}, SHIFT(126), + [919] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1027), + [921] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1028), + [923] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1298), + [925] = {.entry = {.count = 1, .reusable = true}}, SHIFT(394), + [927] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1570), + [929] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1556), + [931] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_jsl_ann_par, 1, 0, 0), + [933] = {.entry = {.count = 1, .reusable = true}}, SHIFT(230), + [935] = {.entry = {.count = 1, .reusable = true}}, SHIFT(231), + [937] = {.entry = {.count = 1, .reusable = true}}, SHIFT(232), + [939] = {.entry = {.count = 1, .reusable = true}}, SHIFT(240), + [941] = {.entry = {.count = 1, .reusable = true}}, SHIFT(236), + [943] = {.entry = {.count = 1, .reusable = true}}, SHIFT(238), + [945] = {.entry = {.count = 1, .reusable = true}}, SHIFT(243), + [947] = {.entry = {.count = 1, .reusable = true}}, SHIFT(242), + [949] = {.entry = {.count = 1, .reusable = true}}, SHIFT(234), + [951] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1566), + [953] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1558), + [955] = {.entry = {.count = 1, .reusable = true}}, SHIFT(257), + [957] = {.entry = {.count = 1, .reusable = true}}, SHIFT(258), + [959] = {.entry = {.count = 1, .reusable = true}}, SHIFT(260), + [961] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__drs_doc_end, 2, 0, 0), + [963] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_end, 1, 0, 0), + [965] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__bgn_imp_doc_end, 2, 0, 0), + [967] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__exp_doc_end, 2, 0, 0), + [969] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__imp_doc_end, 2, 0, 0), + [971] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_prp_val, 1, 0, 0), + [973] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__blk_seq_itm_tal, 1, 0, 0), + [975] = {.entry = {.count = 1, .reusable = true}}, SHIFT(11), + [977] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__blk_imp_itm_tal, 2, 0, 5), + [979] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_als_val, 1, 0, 0), + [981] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_pln_blk_val, 2, 0, 0), + [983] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_pln_blk_val, 1, 0, 0), + [985] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_pln_blk_val, 2, 0, 0), + [987] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_dqt_str, 3, 0, 0), + [989] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_dqt_str, 3, 0, 0), + [991] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_dqt_str, 3, 0, 0), + [993] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_dqt_str, 3, 0, 0), + [995] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sqt_str, 3, 0, 0), + [997] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_sqt_str, 3, 0, 0), + [999] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sqt_str, 3, 0, 0), + [1001] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_sqt_str, 3, 0, 0), + [1003] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_pln_blk, 1, 0, 0), + [1005] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_als, 2, 0, 0), + [1007] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_exp_itm, 1, 0, 2), + [1009] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_exp_itm, 1, 0, 2), + [1011] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_exp_itm, 1, 0, 2), + [1013] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_pln_blk, 1, 0, 0), + [1015] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_pln_blk_val, 1, 0, 0), + [1017] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_pln_blk_val, 1, 0, 0), + [1019] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_pln_blk_val, 1, 0, 0), + [1021] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_als_val, 1, 0, 0), + [1023] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__flw_seq_tal, 1, 0, 0), + [1025] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__sgl_flw_seq_tal, 1, 0, 0), + [1027] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__flw_map_tal, 1, 0, 0), + [1029] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__sgl_flw_map_tal, 1, 0, 0), + [1031] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_dqt_str, 2, 0, 0), + [1033] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_dqt_str, 2, 0, 0), + [1035] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_dqt_str, 2, 0, 0), + [1037] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_dqt_str, 2, 0, 0), + [1039] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sqt_str, 2, 0, 0), + [1041] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_sqt_str, 2, 0, 0), + [1043] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sqt_str, 2, 0, 0), + [1045] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_sqt_str, 2, 0, 0), + [1047] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_als, 2, 0, 0), + [1049] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_exp_itm, 1, 0, 3), + [1051] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_map, 3, 0, 0), + [1053] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_dqt_str, 4, 0, 0), + [1055] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_dqt_str, 4, 0, 0), + [1057] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sqt_str, 4, 0, 0), + [1059] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sqt_str, 4, 0, 0), + [1061] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_dqt_str, 5, 0, 0), + [1063] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_dqt_str_val, 2, 0, 0), + [1065] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_map, 2, 0, 0), + [1067] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_map, 2, 0, 0), + [1069] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_key_itm, 2, 0, 4), + [1071] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_val_itm, 2, 0, 5), + [1073] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_imp_itm, 2, 0, 9), + [1075] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_str, 3, 0, 0), + [1077] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_exp_itm, 2, 0, 10), + [1079] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_str, 3, 0, 0), + [1081] = {.entry = {.count = 1, .reusable = true}}, SHIFT(132), + [1083] = {.entry = {.count = 1, .reusable = true}}, SHIFT(133), + [1085] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1042), + [1087] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1043), + [1089] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1522), + [1091] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_prp_val, 1, 0, 0), + [1093] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_seq_spc_val, 1, 0, 0), + [1095] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_key_itm, 2, 0, 4), + [1097] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_key_itm, 2, 0, 4), + [1099] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_imp_itm, 2, 0, 9), + [1101] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_imp_itm, 2, 0, 9), + [1103] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_val_itm, 2, 0, 5), + [1105] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_val_itm, 2, 0, 5), + [1107] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_map_itm, 1, 0, 1), + [1109] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_map_itm, 1, 0, 1), + [1111] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__flw_seq_tal, 2, 0, 0), + [1113] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__flw_map_tal, 2, 0, 0), + [1115] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_prp_val, 1, 0, 0), + [1117] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_map_itm, 1, 0, 1), + [1119] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_exp_itm, 1, 0, 3), + [1121] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map_val, 2, 0, 0), + [1123] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_exp_itm, 1, 0, 3), + [1125] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_exp_itm, 2, 0, 10), + [1127] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_exp_itm, 2, 0, 10), + [1129] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_mtl_pln_blk, 1, 0, 0), + [1131] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_mtl_pln_blk, 1, 0, 0), + [1133] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_seq_spc_val, 2, 0, 0), + [1135] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_seq_spc_val, 2, 0, 0), + [1137] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_seq_r_val, 1, 0, 0), + [1139] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_seq_val, 1, 0, 0), + [1141] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_map_r_val, 1, 0, 0), + [1143] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_map_val, 1, 0, 0), + [1145] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_str_val, 1, 0, 0), + [1147] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_str_val, 1, 0, 0), + [1149] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq_val, 1, 0, 0), + [1151] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq_val, 1, 0, 0), + [1153] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map_val, 1, 0, 0), + [1155] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map_val, 1, 0, 0), + [1157] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_dqt_str_val, 1, 0, 0), + [1159] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_dqt_str_val, 1, 0, 0), + [1161] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sqt_str_val, 1, 0, 0), + [1163] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sqt_str_val, 1, 0, 0), + [1165] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sqt_str_val, 2, 0, 0), + [1167] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_seq, 2, 0, 0), + [1169] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_seq_spc, 2, 0, 0), + [1171] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_str, 2, 0, 0), + [1173] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_str, 2, 0, 0), + [1175] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq, 2, 0, 0), + [1177] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq, 2, 0, 0), + [1179] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_seq, 2, 0, 0), + [1181] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map, 2, 0, 0), + [1183] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map, 2, 0, 0), + [1185] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_seq, 3, 0, 0), + [1187] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_seq, 3, 0, 0), + [1189] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq_val, 2, 0, 0), + [1191] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_seq_br_val, 2, 0, 0), + [1193] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_map_br_val, 2, 0, 0), + [1195] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_str_val, 2, 0, 0), + [1197] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq_val, 2, 0, 0), + [1199] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map_val, 2, 0, 0), + [1201] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_dqt_str_val, 2, 0, 0), + [1203] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sqt_str_val, 2, 0, 0), + [1205] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_map, 3, 0, 0), + [1207] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_seq_val, 2, 0, 0), + [1209] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_map_val, 2, 0, 0), + [1211] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_str_val, 2, 0, 0), + [1213] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_dqt_str, 5, 0, 0), + [1215] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1573), + [1217] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1574), + [1219] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1576), + [1221] = {.entry = {.count = 1, .reusable = true}}, SHIFT(406), + [1223] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1575), + [1225] = {.entry = {.count = 1, .reusable = true}}, SHIFT(408), + [1227] = {.entry = {.count = 1, .reusable = true}}, SHIFT(417), + [1229] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1577), + [1231] = {.entry = {.count = 1, .reusable = true}}, SHIFT(419), + [1233] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_prp, 1, 0, 0), + [1235] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1562), + [1237] = {.entry = {.count = 1, .reusable = true}}, SHIFT(445), + [1239] = {.entry = {.count = 1, .reusable = true}}, SHIFT(469), + [1241] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_acr, 2, 0, 0), + [1243] = {.entry = {.count = 1, .reusable = true}}, SHIFT(425), + [1245] = {.entry = {.count = 1, .reusable = true}}, SHIFT(458), + [1247] = {.entry = {.count = 1, .reusable = true}}, SHIFT(486), + [1249] = {.entry = {.count = 1, .reusable = true}}, SHIFT(631), + [1251] = {.entry = {.count = 1, .reusable = true}}, SHIFT(633), + [1253] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1328), + [1255] = {.entry = {.count = 1, .reusable = true}}, SHIFT(502), + [1257] = {.entry = {.count = 1, .reusable = true}}, SHIFT(588), + [1259] = {.entry = {.count = 1, .reusable = true}}, SHIFT(587), + [1261] = {.entry = {.count = 1, .reusable = true}}, SHIFT(734), + [1263] = {.entry = {.count = 1, .reusable = true}}, SHIFT(620), + [1265] = {.entry = {.count = 1, .reusable = true}}, SHIFT(619), + [1267] = {.entry = {.count = 1, .reusable = true}}, SHIFT(610), + [1269] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_prp, 2, 0, 0), + [1271] = {.entry = {.count = 1, .reusable = true}}, SHIFT(590), + [1273] = {.entry = {.count = 1, .reusable = true}}, SHIFT(589), + [1275] = {.entry = {.count = 1, .reusable = true}}, SHIFT(736), + [1277] = {.entry = {.count = 1, .reusable = true}}, SHIFT(432), + [1279] = {.entry = {.count = 1, .reusable = true}}, SHIFT(541), + [1281] = {.entry = {.count = 1, .reusable = true}}, SHIFT(543), + [1283] = {.entry = {.count = 1, .reusable = true}}, SHIFT(286), + [1285] = {.entry = {.count = 1, .reusable = true}}, SHIFT(372), + [1287] = {.entry = {.count = 1, .reusable = true}}, SHIFT(433), + [1289] = {.entry = {.count = 1, .reusable = true}}, SHIFT(544), + [1291] = {.entry = {.count = 1, .reusable = true}}, SHIFT(546), + [1293] = {.entry = {.count = 1, .reusable = true}}, SHIFT(287), + [1295] = {.entry = {.count = 1, .reusable = true}}, SHIFT(373), + [1297] = {.entry = {.count = 1, .reusable = true}}, SHIFT(435), + [1299] = {.entry = {.count = 1, .reusable = true}}, SHIFT(605), + [1301] = {.entry = {.count = 1, .reusable = true}}, SHIFT(607), + [1303] = {.entry = {.count = 1, .reusable = true}}, SHIFT(573), + [1305] = {.entry = {.count = 1, .reusable = true}}, SHIFT(455), + [1307] = {.entry = {.count = 1, .reusable = true}}, SHIFT(676), + [1309] = {.entry = {.count = 1, .reusable = true}}, SHIFT(629), + [1311] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1102), + [1313] = {.entry = {.count = 1, .reusable = true}}, SHIFT(436), + [1315] = {.entry = {.count = 1, .reusable = true}}, SHIFT(634), + [1317] = {.entry = {.count = 1, .reusable = true}}, SHIFT(635), + [1319] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1329), + [1321] = {.entry = {.count = 1, .reusable = true}}, SHIFT(558), + [1323] = {.entry = {.count = 1, .reusable = true}}, SHIFT(557), + [1325] = {.entry = {.count = 1, .reusable = true}}, SHIFT(269), + [1327] = {.entry = {.count = 1, .reusable = true}}, SHIFT(324), + [1329] = {.entry = {.count = 1, .reusable = true}}, SHIFT(560), + [1331] = {.entry = {.count = 1, .reusable = true}}, SHIFT(559), + [1333] = {.entry = {.count = 1, .reusable = true}}, SHIFT(270), + [1335] = {.entry = {.count = 1, .reusable = true}}, SHIFT(354), + [1337] = {.entry = {.count = 1, .reusable = true}}, SHIFT(583), + [1339] = {.entry = {.count = 1, .reusable = true}}, SHIFT(582), + [1341] = {.entry = {.count = 1, .reusable = true}}, SHIFT(990), + [1343] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1082), + [1345] = {.entry = {.count = 1, .reusable = true}}, SHIFT(618), + [1347] = {.entry = {.count = 1, .reusable = true}}, SHIFT(617), + [1349] = {.entry = {.count = 1, .reusable = true}}, SHIFT(604), + [1351] = {.entry = {.count = 1, .reusable = true}}, SHIFT(644), + [1353] = {.entry = {.count = 1, .reusable = true}}, SHIFT(643), + [1355] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1373), + [1357] = {.entry = {.count = 1, .reusable = true}}, SHIFT(442), + [1359] = {.entry = {.count = 1, .reusable = true}}, SHIFT(575), + [1361] = {.entry = {.count = 1, .reusable = true}}, SHIFT(577), + [1363] = {.entry = {.count = 1, .reusable = true}}, SHIFT(717), + [1365] = {.entry = {.count = 1, .reusable = true}}, SHIFT(718), + [1367] = {.entry = {.count = 1, .reusable = true}}, SHIFT(444), + [1369] = {.entry = {.count = 1, .reusable = true}}, SHIFT(625), + [1371] = {.entry = {.count = 1, .reusable = true}}, SHIFT(627), + [1373] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1260), + [1375] = {.entry = {.count = 1, .reusable = true}}, SHIFT(426), + [1377] = {.entry = {.count = 1, .reusable = true}}, SHIFT(578), + [1379] = {.entry = {.count = 1, .reusable = true}}, SHIFT(579), + [1381] = {.entry = {.count = 1, .reusable = true}}, SHIFT(719), + [1383] = {.entry = {.count = 1, .reusable = true}}, SHIFT(473), + [1385] = {.entry = {.count = 1, .reusable = true}}, SHIFT(658), + [1387] = {.entry = {.count = 1, .reusable = true}}, SHIFT(659), + [1389] = {.entry = {.count = 1, .reusable = true}}, SHIFT(835), + [1391] = {.entry = {.count = 1, .reusable = true}}, SHIFT(735), + [1393] = {.entry = {.count = 1, .reusable = true}}, SHIFT(460), + [1395] = {.entry = {.count = 1, .reusable = true}}, SHIFT(996), + [1397] = {.entry = {.count = 1, .reusable = true}}, SHIFT(651), + [1399] = {.entry = {.count = 1, .reusable = true}}, SHIFT(650), + [1401] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1347), + [1403] = {.entry = {.count = 1, .reusable = true}}, SHIFT(465), + [1405] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1146), + [1407] = {.entry = {.count = 1, .reusable = true}}, SHIFT(467), + [1409] = {.entry = {.count = 1, .reusable = true}}, SHIFT(628), + [1411] = {.entry = {.count = 1, .reusable = true}}, SHIFT(630), + [1413] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1149), + [1415] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1261), + [1417] = {.entry = {.count = 1, .reusable = true}}, SHIFT(451), + [1419] = {.entry = {.count = 1, .reusable = true}}, SHIFT(572), + [1421] = {.entry = {.count = 1, .reusable = true}}, SHIFT(452), + [1423] = {.entry = {.count = 1, .reusable = true}}, SHIFT(453), + [1425] = {.entry = {.count = 1, .reusable = true}}, SHIFT(681), + [1427] = {.entry = {.count = 1, .reusable = true}}, SHIFT(682), + [1429] = {.entry = {.count = 1, .reusable = true}}, SHIFT(883), + [1431] = {.entry = {.count = 1, .reusable = true}}, SHIFT(606), + [1433] = {.entry = {.count = 1, .reusable = true}}, SHIFT(689), + [1435] = {.entry = {.count = 1, .reusable = true}}, SHIFT(688), + [1437] = {.entry = {.count = 1, .reusable = true}}, SHIFT(903), + [1439] = {.entry = {.count = 1, .reusable = true}}, SHIFT(456), + [1441] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1325), + [1443] = {.entry = {.count = 1, .reusable = true}}, SHIFT(553), + [1445] = {.entry = {.count = 1, .reusable = true}}, SHIFT(685), + [1447] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1075), + [1449] = {.entry = {.count = 1, .reusable = true}}, SHIFT(642), + [1451] = {.entry = {.count = 1, .reusable = true}}, SHIFT(641), + [1453] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1370), + [1455] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1369), + [1457] = {.entry = {.count = 1, .reusable = true}}, SHIFT(422), + [1459] = {.entry = {.count = 1, .reusable = true}}, SHIFT(434), + [1461] = {.entry = {.count = 1, .reusable = true}}, SHIFT(640), + [1463] = {.entry = {.count = 1, .reusable = true}}, SHIFT(647), + [1465] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1000), + [1467] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1108), + [1469] = {.entry = {.count = 1, .reusable = true}}, SHIFT(989), + [1471] = {.entry = {.count = 1, .reusable = true}}, SHIFT(464), + [1473] = {.entry = {.count = 1, .reusable = true}}, SHIFT(655), + [1475] = {.entry = {.count = 1, .reusable = true}}, SHIFT(657), + [1477] = {.entry = {.count = 1, .reusable = true}}, SHIFT(833), + [1479] = {.entry = {.count = 1, .reusable = true}}, SHIFT(834), + [1481] = {.entry = {.count = 1, .reusable = true}}, SHIFT(423), + [1483] = {.entry = {.count = 1, .reusable = true}}, SHIFT(608), + [1485] = {.entry = {.count = 1, .reusable = true}}, SHIFT(609), + [1487] = {.entry = {.count = 1, .reusable = true}}, SHIFT(574), + [1489] = {.entry = {.count = 1, .reusable = true}}, SHIFT(466), + [1491] = {.entry = {.count = 1, .reusable = true}}, SHIFT(665), + [1493] = {.entry = {.count = 1, .reusable = true}}, SHIFT(664), + [1495] = {.entry = {.count = 1, .reusable = true}}, SHIFT(853), + [1497] = {.entry = {.count = 1, .reusable = true}}, SHIFT(852), + [1499] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1179), + [1501] = {.entry = {.count = 1, .reusable = true}}, SHIFT(653), + [1503] = {.entry = {.count = 1, .reusable = true}}, SHIFT(652), + [1505] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1180), + [1507] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1350), + [1509] = {.entry = {.count = 1, .reusable = true}}, SHIFT(471), + [1511] = {.entry = {.count = 1, .reusable = true}}, SHIFT(678), + [1513] = {.entry = {.count = 1, .reusable = true}}, SHIFT(680), + [1515] = {.entry = {.count = 1, .reusable = true}}, SHIFT(881), + [1517] = {.entry = {.count = 1, .reusable = true}}, SHIFT(882), + [1519] = {.entry = {.count = 1, .reusable = true}}, SHIFT(472), + [1521] = {.entry = {.count = 1, .reusable = true}}, SHIFT(687), + [1523] = {.entry = {.count = 1, .reusable = true}}, SHIFT(686), + [1525] = {.entry = {.count = 1, .reusable = true}}, SHIFT(902), + [1527] = {.entry = {.count = 1, .reusable = true}}, SHIFT(962), + [1529] = {.entry = {.count = 1, .reusable = true}}, SHIFT(667), + [1531] = {.entry = {.count = 1, .reusable = true}}, SHIFT(666), + [1533] = {.entry = {.count = 1, .reusable = true}}, SHIFT(854), + [1535] = {.entry = {.count = 1, .reusable = true}}, SHIFT(252), + [1537] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_flw_map_itm, 1, 0, 0), REDUCE(sym__r_sgl_flw_col_itm, 1, 0, 0), + [1540] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map_itm, 1, 0, 0), + [1542] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_w_bgn_wo_end_seq, 1, 0, 0), + [1544] = {.entry = {.count = 1, .reusable = true}}, SHIFT(251), + [1546] = {.entry = {.count = 1, .reusable = true}}, SHIFT(253), + [1548] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_wo_bgn_wo_end_seq, 1, 0, 0), + [1550] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__br_mtl_dqt_ctn_repeat1, 2, 0, 0), SHIFT_REPEAT(481), + [1553] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__br_mtl_dqt_ctn_repeat1, 2, 0, 0), + [1555] = {.entry = {.count = 1, .reusable = true}}, SHIFT(526), + [1557] = {.entry = {.count = 1, .reusable = true}}, SHIFT(648), + [1559] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1150), + [1561] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1265), + [1563] = {.entry = {.count = 1, .reusable = true}}, SHIFT(529), + [1565] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1153), + [1567] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1266), + [1569] = {.entry = {.count = 1, .reusable = true}}, SHIFT(615), + [1571] = {.entry = {.count = 1, .reusable = true}}, SHIFT(857), + [1573] = {.entry = {.count = 1, .reusable = true}}, SHIFT(495), + [1575] = {.entry = {.count = 1, .reusable = true}}, SHIFT(374), + [1577] = {.entry = {.count = 1, .reusable = true}}, SHIFT(499), + [1579] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_mtl_dqt_ctn, 1, 0, 0), + [1581] = {.entry = {.count = 1, .reusable = true}}, SHIFT(794), + [1583] = {.entry = {.count = 1, .reusable = true}}, SHIFT(488), + [1585] = {.entry = {.count = 1, .reusable = true}}, SHIFT(288), + [1587] = {.entry = {.count = 1, .reusable = true}}, SHIFT(271), + [1589] = {.entry = {.count = 1, .reusable = true}}, SHIFT(363), + [1591] = {.entry = {.count = 1, .reusable = true}}, SHIFT(497), + [1593] = {.entry = {.count = 1, .reusable = true}}, SHIFT(886), + [1595] = {.entry = {.count = 1, .reusable = true}}, SHIFT(508), + [1597] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1126), + [1599] = {.entry = {.count = 1, .reusable = true}}, SHIFT(611), + [1601] = {.entry = {.count = 1, .reusable = true}}, SHIFT(612), + [1603] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map_itm, 1, 0, 0), + [1605] = {.entry = {.count = 1, .reusable = true}}, SHIFT(503), + [1607] = {.entry = {.count = 1, .reusable = true}}, SHIFT(289), + [1609] = {.entry = {.count = 1, .reusable = true}}, SHIFT(376), + [1611] = {.entry = {.count = 1, .reusable = true}}, SHIFT(739), + [1613] = {.entry = {.count = 1, .reusable = true}}, SHIFT(906), + [1615] = {.entry = {.count = 1, .reusable = true}}, SHIFT(89), + [1617] = {.entry = {.count = 1, .reusable = true}}, SHIFT(93), + [1619] = {.entry = {.count = 1, .reusable = true}}, SHIFT(481), + [1621] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_mtl_dqt_ctn, 2, 0, 0), + [1623] = {.entry = {.count = 1, .reusable = true}}, SHIFT(889), + [1625] = {.entry = {.count = 1, .reusable = true}}, SHIFT(507), + [1627] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1330), + [1629] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1331), + [1631] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_sgl_dqt_ctn, 2, 0, 0), SHIFT_REPEAT(502), + [1634] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_sgl_dqt_ctn, 2, 0, 0), + [1636] = {.entry = {.count = 1, .reusable = true}}, SHIFT(272), + [1638] = {.entry = {.count = 1, .reusable = true}}, SHIFT(371), + [1640] = {.entry = {.count = 1, .reusable = true}}, SHIFT(510), + [1642] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1385), + [1644] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1374), + [1646] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1384), + [1648] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1086), + [1650] = {.entry = {.count = 1, .reusable = true}}, SHIFT(506), + [1652] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1334), + [1654] = {.entry = {.count = 1, .reusable = true}}, SHIFT(535), + [1656] = {.entry = {.count = 1, .reusable = true}}, SHIFT(721), + [1658] = {.entry = {.count = 1, .reusable = true}}, SHIFT(985), + [1660] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1090), + [1662] = {.entry = {.count = 1, .reusable = true}}, SHIFT(531), + [1664] = {.entry = {.count = 1, .reusable = true}}, SHIFT(720), + [1666] = {.entry = {.count = 1, .reusable = true}}, SHIFT(491), + [1668] = {.entry = {.count = 1, .reusable = true}}, SHIFT(576), + [1670] = {.entry = {.count = 1, .reusable = true}}, SHIFT(580), + [1672] = {.entry = {.count = 1, .reusable = true}}, SHIFT(521), + [1674] = {.entry = {.count = 1, .reusable = true}}, SHIFT(836), + [1676] = {.entry = {.count = 1, .reusable = true}}, SHIFT(837), + [1678] = {.entry = {.count = 1, .reusable = true}}, SHIFT(518), + [1680] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1005), + [1682] = {.entry = {.count = 1, .reusable = true}}, SHIFT(530), + [1684] = {.entry = {.count = 1, .reusable = true}}, SHIFT(581), + [1686] = {.entry = {.count = 1, .reusable = true}}, SHIFT(987), + [1688] = {.entry = {.count = 1, .reusable = true}}, SHIFT(524), + [1690] = {.entry = {.count = 1, .reusable = true}}, SHIFT(537), + [1692] = {.entry = {.count = 1, .reusable = true}}, SHIFT(855), + [1694] = {.entry = {.count = 1, .reusable = true}}, SHIFT(856), + [1696] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__drs_doc_repeat1, 2, 0, 0), SHIFT_REPEAT(1427), + [1699] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__drs_doc_repeat1, 2, 0, 0), SHIFT_REPEAT(1515), + [1702] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__drs_doc_repeat1, 2, 0, 0), SHIFT_REPEAT(694), + [1705] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__drs_doc_repeat1, 2, 0, 0), + [1707] = {.entry = {.count = 1, .reusable = true}}, SHIFT(500), + [1709] = {.entry = {.count = 1, .reusable = true}}, SHIFT(512), + [1711] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1008), + [1713] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1130), + [1715] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1181), + [1717] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1351), + [1719] = {.entry = {.count = 1, .reusable = true}}, SHIFT(484), + [1721] = {.entry = {.count = 1, .reusable = true}}, SHIFT(838), + [1723] = {.entry = {.count = 1, .reusable = true}}, SHIFT(534), + [1725] = {.entry = {.count = 1, .reusable = true}}, SHIFT(884), + [1727] = {.entry = {.count = 1, .reusable = true}}, SHIFT(885), + [1729] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1184), + [1731] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1355), + [1733] = {.entry = {.count = 1, .reusable = true}}, SHIFT(613), + [1735] = {.entry = {.count = 1, .reusable = true}}, SHIFT(737), + [1737] = {.entry = {.count = 1, .reusable = true}}, SHIFT(738), + [1739] = {.entry = {.count = 1, .reusable = true}}, SHIFT(536), + [1741] = {.entry = {.count = 1, .reusable = true}}, SHIFT(496), + [1743] = {.entry = {.count = 1, .reusable = true}}, SHIFT(722), + [1745] = {.entry = {.count = 1, .reusable = true}}, SHIFT(904), + [1747] = {.entry = {.count = 1, .reusable = true}}, SHIFT(905), + [1749] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_flw_seq_itm, 1, 0, 0), REDUCE(sym__r_sgl_flw_col_itm, 1, 0, 0), + [1752] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq_itm, 1, 0, 0), + [1754] = {.entry = {.count = 1, .reusable = true}}, SHIFT(565), + [1756] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1408), + [1758] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_flw_seq_dat_repeat1, 2, 0, 0), + [1760] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_flw_seq_dat_repeat1, 2, 0, 0), SHIFT_REPEAT(79), + [1763] = {.entry = {.count = 1, .reusable = true}}, SHIFT(584), + [1765] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1092), + [1767] = {.entry = {.count = 1, .reusable = true}}, SHIFT(92), + [1769] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__flw_seq_tal, 1, 0, 0), REDUCE(sym__sgl_flw_seq_tal, 1, 0, 0), + [1772] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_pln_flw_val, 1, 0, 0), REDUCE(sym__r_sgl_pln_flw_val, 1, 0, 0), + [1775] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_pln_flw_val, 1, 0, 0), + [1777] = {.entry = {.count = 1, .reusable = true}}, SHIFT(293), + [1779] = {.entry = {.count = 1, .reusable = true}}, SHIFT(561), + [1781] = {.entry = {.count = 1, .reusable = true}}, SHIFT(294), + [1783] = {.entry = {.count = 1, .reusable = true}}, SHIFT(562), + [1785] = {.entry = {.count = 1, .reusable = true}}, SHIFT(297), + [1787] = {.entry = {.count = 1, .reusable = true}}, SHIFT(391), + [1789] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_pln_flw_val, 1, 0, 0), + [1791] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_dqt_str_repeat1, 2, 0, 0), SHIFT_REPEAT(486), + [1794] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_dqt_str_repeat1, 2, 0, 0), SHIFT_REPEAT(565), + [1797] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_dqt_str_repeat1, 2, 0, 0), + [1799] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_flw_map_dat_repeat1, 2, 0, 0), + [1801] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_flw_map_dat_repeat1, 2, 0, 0), SHIFT_REPEAT(78), + [1804] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__flw_map_tal, 1, 0, 0), REDUCE(sym__sgl_flw_map_tal, 1, 0, 0), + [1807] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_dqt_str, 2, 0, 0), REDUCE(sym__r_sgl_dqt_str, 2, 0, 0), + [1810] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_sqt_str, 2, 0, 0), REDUCE(sym__r_sgl_sqt_str, 2, 0, 0), + [1813] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1093), + [1815] = {.entry = {.count = 1, .reusable = true}}, SHIFT(585), + [1817] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1104), + [1819] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1105), + [1821] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__br_mtl_sqt_ctn_repeat1, 2, 0, 0), SHIFT_REPEAT(586), + [1824] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__br_mtl_sqt_ctn_repeat1, 2, 0, 0), + [1826] = {.entry = {.count = 1, .reusable = true}}, SHIFT(740), + [1828] = {.entry = {.count = 1, .reusable = true}}, SHIFT(591), + [1830] = {.entry = {.count = 1, .reusable = true}}, SHIFT(783), + [1832] = {.entry = {.count = 1, .reusable = true}}, SHIFT(592), + [1834] = {.entry = {.count = 1, .reusable = true}}, SHIFT(744), + [1836] = {.entry = {.count = 1, .reusable = true}}, SHIFT(745), + [1838] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_dqt_str, 3, 0, 0), REDUCE(sym__r_sgl_dqt_str, 3, 0, 0), + [1841] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_sqt_str, 3, 0, 0), REDUCE(sym__r_sgl_sqt_str, 3, 0, 0), + [1844] = {.entry = {.count = 1, .reusable = true}}, SHIFT(586), + [1846] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_mtl_sqt_ctn, 2, 0, 0), + [1848] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_sgl_sqt_ctn, 2, 0, 0), SHIFT_REPEAT(615), + [1851] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_sgl_sqt_ctn, 2, 0, 0), + [1853] = {.entry = {.count = 1, .reusable = true}}, SHIFT(616), + [1855] = {.entry = {.count = 1, .reusable = true}}, SHIFT(621), + [1857] = {.entry = {.count = 1, .reusable = true}}, SHIFT(692), + [1859] = {.entry = {.count = 1, .reusable = true}}, SHIFT(622), + [1861] = {.entry = {.count = 1, .reusable = true}}, SHIFT(632), + [1863] = {.entry = {.count = 1, .reusable = true}}, SHIFT(636), + [1865] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_pln_flw_val, 2, 0, 0), + [1867] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_pln_flw_val, 2, 0, 0), + [1869] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1396), + [1871] = {.entry = {.count = 1, .reusable = true}}, SHIFT(539), + [1873] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1397), + [1875] = {.entry = {.count = 1, .reusable = true}}, SHIFT(646), + [1877] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq_itm, 1, 0, 0), + [1879] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1324), + [1881] = {.entry = {.count = 1, .reusable = true}}, SHIFT(614), + [1883] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_mtl_sqt_ctn, 1, 0, 0), + [1885] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq_dat, 1, 0, 0), + [1887] = {.entry = {.count = 1, .reusable = true}}, SHIFT(74), + [1889] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1375), + [1891] = {.entry = {.count = 1, .reusable = true}}, SHIFT(654), + [1893] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1376), + [1895] = {.entry = {.count = 1, .reusable = true}}, SHIFT(656), + [1897] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1382), + [1899] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1383), + [1901] = {.entry = {.count = 1, .reusable = true}}, SHIFT(76), + [1903] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq_dat, 1, 0, 0), + [1905] = {.entry = {.count = 1, .reusable = true}}, SHIFT(75), + [1907] = {.entry = {.count = 1, .reusable = true}}, SHIFT(77), + [1909] = {.entry = {.count = 1, .reusable = true}}, SHIFT(858), + [1911] = {.entry = {.count = 1, .reusable = true}}, SHIFT(668), + [1913] = {.entry = {.count = 1, .reusable = true}}, SHIFT(859), + [1915] = {.entry = {.count = 1, .reusable = true}}, SHIFT(669), + [1917] = {.entry = {.count = 1, .reusable = true}}, SHIFT(862), + [1919] = {.entry = {.count = 1, .reusable = true}}, SHIFT(863), + [1921] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map_dat, 1, 0, 0), + [1923] = {.entry = {.count = 1, .reusable = true}}, SHIFT(71), + [1925] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map_dat, 1, 0, 0), + [1927] = {.entry = {.count = 1, .reusable = true}}, SHIFT(70), + [1929] = {.entry = {.count = 1, .reusable = true}}, SHIFT(72), + [1931] = {.entry = {.count = 1, .reusable = true}}, SHIFT(73), + [1933] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_pln_flw, 1, 0, 0), + [1935] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_pln_flw, 1, 0, 0), + [1937] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_mtl_pln_flw, 1, 0, 0), + [1939] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_mtl_pln_flw, 1, 0, 0), + [1941] = {.entry = {.count = 1, .reusable = true}}, SHIFT(907), + [1943] = {.entry = {.count = 1, .reusable = true}}, SHIFT(690), + [1945] = {.entry = {.count = 1, .reusable = true}}, SHIFT(908), + [1947] = {.entry = {.count = 1, .reusable = true}}, SHIFT(691), + [1949] = {.entry = {.count = 1, .reusable = true}}, SHIFT(911), + [1951] = {.entry = {.count = 1, .reusable = true}}, SHIFT(912), + [1953] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__s_dir_rsv, 1, 0, 0), + [1955] = {.entry = {.count = 1, .reusable = true}}, SHIFT(758), + [1957] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__s_dir_rsv_repeat1, 2, 0, 0), + [1959] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__s_dir_rsv_repeat1, 2, 0, 0), SHIFT_REPEAT(698), + [1962] = {.entry = {.count = 1, .reusable = true}}, SHIFT(910), + [1964] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1096), + [1966] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_sqt_str_repeat1, 2, 0, 0), SHIFT_REPEAT(648), + [1969] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_sqt_str_repeat1, 2, 0, 0), + [1971] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1098), + [1973] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__s_dir_rsv, 2, 0, 0), + [1975] = {.entry = {.count = 1, .reusable = true}}, SHIFT(698), + [1977] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1377), + [1979] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1378), + [1981] = {.entry = {.count = 1, .reusable = true}}, SHIFT(295), + [1983] = {.entry = {.count = 1, .reusable = true}}, SHIFT(296), + [1985] = {.entry = {.count = 1, .reusable = true}}, SHIFT(742), + [1987] = {.entry = {.count = 1, .reusable = true}}, SHIFT(743), + [1989] = {.entry = {.count = 1, .reusable = true}}, SHIFT(624), + [1991] = {.entry = {.count = 1, .reusable = true}}, SHIFT(626), + [1993] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1399), + [1995] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1403), + [1997] = {.entry = {.count = 1, .reusable = true}}, SHIFT(860), + [1999] = {.entry = {.count = 1, .reusable = true}}, SHIFT(861), + [2001] = {.entry = {.count = 1, .reusable = true}}, SHIFT(909), + [2003] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_imp_br_par, 2, 0, 9), + [2005] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_imp_br_par, 2, 0, 9), + [2007] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq_itm, 1, 0, 6), + [2009] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq_itm, 1, 0, 6), + [2011] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq_itm, 1, 0, 7), + [2013] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq_itm, 1, 0, 7), + [2015] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_exp_par, 2, 0, 11), + [2017] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_exp_par, 2, 0, 11), + [2019] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_njl_ann_par, 2, 0, 5), + [2021] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map_itm, 1, 0, 6), + [2023] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map_itm, 1, 0, 6), + [2025] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_jsl_ann_par, 2, 0, 5), + [2027] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__flw_seq_dat_rpt, 2, 0, 0), + [2029] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_jsl_ann_par, 2, 0, 5), + [2031] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__flw_map_dat_rpt, 2, 0, 0), + [2033] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map_itm, 1, 0, 7), + [2035] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map_itm, 1, 0, 7), + [2037] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_mtl_dqt_ctn, 3, 0, 0), + [2039] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__exp_doc_tal, 1, 0, 0), + [2041] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__flw_ann_par_tal, 1, 0, 0), REDUCE(sym__sgl_flw_ann_par_tal, 1, 0, 0), + [2044] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__flw_ann_par_tal, 1, 0, 0), + [2046] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_njl_ann_par, 2, 0, 5), + [2048] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_imp_r_par, 2, 0, 9), + [2050] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_imp_r_par, 2, 0, 9), + [2052] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__imp_doc, 1, 0, 0), + [2054] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_sgl_flw_col_dat_repeat1, 2, 0, 0), + [2056] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_sgl_flw_col_dat_repeat1, 2, 0, 0), SHIFT_REPEAT(181), + [2059] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_col_dat, 1, 0, 0), + [2061] = {.entry = {.count = 1, .reusable = true}}, SHIFT(175), + [2063] = {.entry = {.count = 1, .reusable = true}}, SHIFT(358), + [2065] = {.entry = {.count = 1, .reusable = true}}, SHIFT(368), + [2067] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__s_dir_tag, 3, 0, 0), + [2069] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1014), + [2071] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1497), + [2073] = {.entry = {.count = 1, .reusable = true}}, SHIFT(977), + [2075] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1067), + [2077] = {.entry = {.count = 1, .reusable = true}}, SHIFT(978), + [2079] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1068), + [2081] = {.entry = {.count = 1, .reusable = true}}, SHIFT(375), + [2083] = {.entry = {.count = 1, .reusable = true}}, SHIFT(377), + [2085] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1029), + [2087] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1499), + [2089] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_col_itm, 1, 0, 0), + [2091] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1023), + [2093] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1072), + [2095] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1024), + [2097] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1074), + [2099] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_seq_repeat1, 2, 0, 0), SHIFT_REPEAT(9), + [2102] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_blk_seq_repeat1, 2, 0, 0), + [2104] = {.entry = {.count = 1, .reusable = true}}, SHIFT(993), + [2106] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1451), + [2108] = {.entry = {.count = 1, .reusable = true}}, SHIFT(994), + [2110] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1458), + [2112] = {.entry = {.count = 1, .reusable = true}}, SHIFT(177), + [2114] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1421), + [2116] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1495), + [2118] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1507), + [2120] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1215), + [2122] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1136), + [2124] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1294), + [2126] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1295), + [2128] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1119), + [2130] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1195), + [2132] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1196), + [2134] = {.entry = {.count = 1, .reusable = true}}, SHIFT(90), + [2136] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1020), + [2138] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1249), + [2140] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1021), + [2142] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1255), + [2144] = {.entry = {.count = 1, .reusable = true}}, SHIFT(174), + [2146] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1425), + [2148] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1443), + [2150] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__s_dir_yml, 2, 0, 0), + [2152] = {.entry = {.count = 1, .reusable = true}}, SHIFT(167), + [2154] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1006), + [2156] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1189), + [2158] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1007), + [2160] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1190), + [2162] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1270), + [2164] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1271), + [2166] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1362), + [2168] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_sgl_dqt_ctn, 2, 0, 0), SHIFT_REPEAT(1023), + [2171] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_sgl_sqt_ctn, 2, 0, 0), SHIFT_REPEAT(1024), + [2174] = {.entry = {.count = 1, .reusable = true}}, SHIFT(203), + [2176] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1363), + [2178] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1032), + [2180] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1391), + [2182] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1033), + [2184] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1392), + [2186] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1444), + [2188] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1405), + [2190] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1406), + [2192] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_sgl_flw_col_dat_repeat1, 2, 0, 0), SHIFT_REPEAT(182), + [2195] = {.entry = {.count = 1, .reusable = true}}, SHIFT(359), + [2197] = {.entry = {.count = 1, .reusable = true}}, SHIFT(992), + [2199] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1477), + [2201] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1013), + [2203] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1500), + [2205] = {.entry = {.count = 1, .reusable = true}}, SHIFT(202), + [2207] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1091), + [2209] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_seq, 2, 0, 0), + [2211] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_seq_val, 2, 0, 0), + [2213] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_map_val, 2, 0, 0), + [2215] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_dqt_str_val, 2, 0, 0), + [2217] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_sqt_str_val, 2, 0, 0), + [2219] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_str_repeat1, 2, 0, 0), SHIFT_REPEAT(1056), + [2222] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_blk_str_repeat1, 2, 0, 0), + [2224] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1134), + [2226] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__sgl_flw_seq_tal, 2, 0, 0), + [2228] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__sgl_flw_map_tal, 2, 0, 0), + [2230] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_map, 2, 0, 0), + [2232] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1056), + [2234] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1057), + [2236] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1089), + [2238] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1088), + [2240] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1066), + [2242] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1063), + [2244] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_pln_flw_val, 2, 0, 0), + [2246] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__drs_doc, 2, 0, 0), + [2248] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1055), + [2250] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_seq_val, 1, 0, 0), + [2252] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1120), + [2254] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1229), + [2256] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1121), + [2258] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1230), + [2260] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_map_val, 1, 0, 0), + [2262] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_dqt_str_val, 1, 0, 0), + [2264] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_sqt_str_val, 1, 0, 0), + [2266] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1300), + [2268] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1303), + [2270] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__bgn_imp_doc, 1, 0, 0), + [2272] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1333), + [2274] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1344), + [2276] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_pln_flw_val, 1, 0, 0), + [2278] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1073), + [2280] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1147), + [2282] = {.entry = {.count = 1, .reusable = true}}, SHIFT(361), + [2284] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1148), + [2286] = {.entry = {.count = 1, .reusable = true}}, SHIFT(362), + [2288] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__exp_doc, 2, 0, 0), + [2290] = {.entry = {.count = 1, .reusable = true}}, SHIFT(305), + [2292] = {.entry = {.count = 1, .reusable = true}}, SHIFT(307), + [2294] = {.entry = {.count = 1, .reusable = true}}, SHIFT(320), + [2296] = {.entry = {.count = 1, .reusable = true}}, SHIFT(321), + [2298] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_w_bgn_wo_end, 1, 0, 8), + [2300] = {.entry = {.count = 1, .reusable = true}}, SHIFT(254), + [2302] = {.entry = {.count = 1, .reusable = true}}, SHIFT(732), + [2304] = {.entry = {.count = 1, .reusable = true}}, SHIFT(733), + [2306] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_wo_bgn_wo_end, 1, 0, 8), + [2308] = {.entry = {.count = 1, .reusable = true}}, SHIFT(249), + [2310] = {.entry = {.count = 1, .reusable = true}}, SHIFT(255), + [2312] = {.entry = {.count = 1, .reusable = true}}, SHIFT(602), + [2314] = {.entry = {.count = 1, .reusable = true}}, SHIFT(603), + [2316] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1361), + [2318] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1367), + [2320] = {.entry = {.count = 1, .reusable = true}}, SHIFT(850), + [2322] = {.entry = {.count = 1, .reusable = true}}, SHIFT(851), + [2324] = {.entry = {.count = 1, .reusable = true}}, SHIFT(900), + [2326] = {.entry = {.count = 1, .reusable = true}}, SHIFT(901), + [2328] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_col_itm, 1, 0, 6), + [2330] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_imp_par, 2, 0, 9), + [2332] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__sgl_flw_col_dat_rpt, 2, 0, 0), + [2334] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_col_itm, 1, 0, 7), + [2336] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_seq_itm, 2, 0, 0), + [2338] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_seq_itm, 2, 0, 0), + [2340] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_exp_par, 2, 0, 11), + [2342] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_seq_itm, 2, 0, 0), + [2344] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_njl_ann_par, 2, 0, 5), + [2346] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_jsl_ann_par, 2, 0, 5), + [2348] = {.entry = {.count = 1, .reusable = true}}, SHIFT(227), + [2350] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_als_val, 1, 0, 0), + [2352] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_dqt_str_val, 2, 0, 0), + [2354] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_flw_seq, 2, 0, 0), + [2356] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_sqt_str_val, 1, 0, 0), + [2358] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_sqt_str_val, 2, 0, 0), + [2360] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_pln_blk_val, 2, 0, 0), + [2362] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_stream, 2, 0, 8), + [2364] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1015), + [2366] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1452), + [2368] = {.entry = {.count = 1, .reusable = true}}, ACCEPT_INPUT(), + [2370] = {.entry = {.count = 1, .reusable = true}}, SHIFT(163), + [2372] = {.entry = {.count = 1, .reusable = true}}, SHIFT(102), + [2374] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1079), + [2376] = {.entry = {.count = 1, .reusable = true}}, SHIFT(101), + [2378] = {.entry = {.count = 1, .reusable = true}}, SHIFT(208), + [2380] = {.entry = {.count = 1, .reusable = true}}, SHIFT(275), + [2382] = {.entry = {.count = 1, .reusable = true}}, SHIFT(723), + [2384] = {.entry = {.count = 1, .reusable = true}}, SHIFT(290), + [2386] = {.entry = {.count = 1, .reusable = true}}, SHIFT(196), + [2388] = {.entry = {.count = 1, .reusable = true}}, SHIFT(171), + [2390] = {.entry = {.count = 1, .reusable = true}}, SHIFT(662), + [2392] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1424), + [2394] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_dqt_str, 3, 0, 0), + [2396] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_sqt_str, 3, 0, 0), + [2398] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_flw_seq, 2, 0, 0), + [2400] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_dqt_str_val, 1, 0, 0), + [2402] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1366), + [2404] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1368), + [2406] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_flw_map, 2, 0, 0), + [2408] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_stream, 3, 0, 8), + [2410] = {.entry = {.count = 1, .reusable = true}}, SHIFT(968), + [2412] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_w_bgn_w_end_seq, 2, 0, 0), + [2414] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1414), + [2416] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1501), + [2418] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1448), + [2420] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_pln_blk, 1, 0, 0), + [2422] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_dqt_str_val, 1, 0, 0), + [2424] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_stream, 1, 0, 0), + [2426] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1174), + [2428] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1178), + [2430] = {.entry = {.count = 1, .reusable = true}}, SHIFT(161), + [2432] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1061), + [2434] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1039), + [2436] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1062), + [2438] = {.entry = {.count = 1, .reusable = true}}, SHIFT(159), + [2440] = {.entry = {.count = 1, .reusable = true}}, SHIFT(418), + [2442] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1248), + [2444] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1254), + [2446] = {.entry = {.count = 1, .reusable = true}}, SHIFT(156), + [2448] = {.entry = {.count = 1, .reusable = true}}, SHIFT(416), + [2450] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_als, 2, 0, 0), + [2452] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1044), + [2454] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1485), + [2456] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_wo_bgn_w_end_seq, 2, 0, 0), + [2458] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_wo_bgn_wo_end_seq, 2, 0, 0), + [2460] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_flw_seq_val, 2, 0, 0), + [2462] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_flw_map_val, 2, 0, 0), + [2464] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_flw_seq_val, 1, 0, 0), + [2466] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1157), + [2468] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_flw_map, 2, 0, 0), + [2470] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_dqt_str, 2, 0, 0), + [2472] = {.entry = {.count = 1, .reusable = true}}, SHIFT(127), + [2474] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_sqt_str, 2, 0, 0), + [2476] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_flw_map_val, 1, 0, 0), + [2478] = {.entry = {.count = 1, .reusable = true}}, SHIFT(194), + [2480] = {.entry = {.count = 1, .reusable = true}}, SHIFT(753), + [2482] = {.entry = {.count = 1, .reusable = true}}, SHIFT(593), + [2484] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1158), + [2486] = {.entry = {.count = 1, .reusable = true}}, SHIFT(170), + [2488] = {.entry = {.count = 1, .reusable = true}}, SHIFT(180), + [2490] = {.entry = {.count = 1, .reusable = true}}, SHIFT(890), + [2492] = {.entry = {.count = 1, .reusable = true}}, SHIFT(891), + [2494] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_flw_map_val, 1, 0, 0), + [2496] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1454), + [2498] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1413), + [2500] = {.entry = {.count = 1, .reusable = true}}, SHIFT(129), + [2502] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_sqt_str_val, 1, 0, 0), + [2504] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1238), + [2506] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_w_bgn_wo_end_seq, 2, 0, 0), + [2508] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1241), + [2510] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_pln_blk_val, 2, 0, 0), + [2512] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_flw_seq_val, 2, 0, 0), + [2514] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_flw_map_val, 2, 0, 0), + [2516] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_pln_blk_val, 1, 0, 0), + [2518] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_dqt_str_val, 2, 0, 0), + [2520] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_sqt_str_val, 2, 0, 0), + [2522] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_pln_blk_val, 2, 0, 0), + [2524] = {.entry = {.count = 1, .reusable = true}}, SHIFT(173), + [2526] = {.entry = {.count = 1, .reusable = true}}, SHIFT(110), + [2528] = {.entry = {.count = 1, .reusable = true}}, SHIFT(915), + [2530] = {.entry = {.count = 1, .reusable = true}}, SHIFT(916), + [2532] = {.entry = {.count = 1, .reusable = true}}, SHIFT(107), + [2534] = {.entry = {.count = 1, .reusable = true}}, SHIFT(247), + [2536] = {.entry = {.count = 1, .reusable = true}}, SHIFT(333), + [2538] = {.entry = {.count = 1, .reusable = true}}, SHIFT(246), + [2540] = {.entry = {.count = 1, .reusable = true}}, SHIFT(225), + [2542] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1099), + [2544] = {.entry = {.count = 1, .reusable = true}}, SHIFT(223), + [2546] = {.entry = {.count = 1, .reusable = true}}, SHIFT(228), + [2548] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1101), + [2550] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_flw_seq_val, 1, 0, 0), + [2552] = {.entry = {.count = 1, .reusable = true}}, SHIFT(212), + [2554] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1352), + [2556] = {.entry = {.count = 1, .reusable = true}}, SHIFT(211), + [2558] = {.entry = {.count = 1, .reusable = true}}, SHIFT(216), + [2560] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1356), + [2562] = {.entry = {.count = 1, .reusable = true}}, SHIFT(217), + [2564] = {.entry = {.count = 1, .reusable = true}}, SHIFT(259), + [2566] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1462), + [2568] = {.entry = {.count = 1, .reusable = true}}, SHIFT(106), + [2570] = {.entry = {.count = 1, .reusable = true}}, SHIFT(235), + [2572] = {.entry = {.count = 1, .reusable = true}}, SHIFT(424), + [2574] = {.entry = {.count = 1, .reusable = true}}, SHIFT(237), + [2576] = {.entry = {.count = 1, .reusable = true}}, SHIFT(397), + [2578] = {.entry = {.count = 1, .reusable = true}}, SHIFT(399), + [2580] = {.entry = {.count = 1, .reusable = true}}, SHIFT(256), + [2582] = {.entry = {.count = 1, .reusable = true}}, SHIFT(239), + [2584] = {.entry = {.count = 1, .reusable = true}}, SHIFT(407), + [2586] = {.entry = {.count = 1, .reusable = true}}, SHIFT(241), + [2588] = {.entry = {.count = 1, .reusable = true}}, SHIFT(410), + [2590] = {.entry = {.count = 1, .reusable = true}}, SHIFT(111), + [2592] = {.entry = {.count = 1, .reusable = true}}, SHIFT(412), + [2594] = {.entry = {.count = 1, .reusable = true}}, SHIFT(402), + [2596] = {.entry = {.count = 1, .reusable = true}}, SHIFT(400), + [2598] = {.entry = {.count = 1, .reusable = true}}, SHIFT(411), + [2600] = {.entry = {.count = 1, .reusable = true}}, SHIFT(414), + [2602] = {.entry = {.count = 1, .reusable = true}}, SHIFT(438), + [2604] = {.entry = {.count = 1, .reusable = true}}, SHIFT(206), +}; + +enum ts_external_scanner_symbol_identifiers { + ts_external_token__eof = 0, + ts_external_token__s_dir_yml_bgn = 1, + ts_external_token__r_dir_yml_ver = 2, + ts_external_token__s_dir_tag_bgn = 3, + ts_external_token__r_dir_tag_hdl = 4, + ts_external_token__r_dir_tag_pfx = 5, + ts_external_token__s_dir_rsv_bgn = 6, + ts_external_token__r_dir_rsv_prm = 7, + ts_external_token__s_drs_end = 8, + ts_external_token__s_doc_end = 9, + ts_external_token__r_blk_seq_bgn = 10, + ts_external_token__br_blk_seq_bgn = 11, + ts_external_token__b_blk_seq_bgn = 12, + ts_external_token__r_blk_key_bgn = 13, + ts_external_token__br_blk_key_bgn = 14, + ts_external_token__b_blk_key_bgn = 15, + ts_external_token__r_blk_val_bgn = 16, + ts_external_token__br_blk_val_bgn = 17, + ts_external_token__b_blk_val_bgn = 18, + ts_external_token__r_blk_imp_bgn = 19, + ts_external_token__r_blk_lit_bgn = 20, + ts_external_token__br_blk_lit_bgn = 21, + ts_external_token__r_blk_fld_bgn = 22, + ts_external_token__br_blk_fld_bgn = 23, + ts_external_token__br_blk_str_ctn = 24, + ts_external_token__r_flw_seq_bgn = 25, + ts_external_token__br_flw_seq_bgn = 26, + ts_external_token__b_flw_seq_bgn = 27, + ts_external_token__r_flw_seq_end = 28, + ts_external_token__br_flw_seq_end = 29, + ts_external_token__b_flw_seq_end = 30, + ts_external_token__r_flw_map_bgn = 31, + ts_external_token__br_flw_map_bgn = 32, + ts_external_token__b_flw_map_bgn = 33, + ts_external_token__r_flw_map_end = 34, + ts_external_token__br_flw_map_end = 35, + ts_external_token__b_flw_map_end = 36, + ts_external_token__r_flw_sep_bgn = 37, + ts_external_token__br_flw_sep_bgn = 38, + ts_external_token__r_flw_key_bgn = 39, + ts_external_token__br_flw_key_bgn = 40, + ts_external_token__r_flw_jsv_bgn = 41, + ts_external_token__br_flw_jsv_bgn = 42, + ts_external_token__r_flw_njv_bgn = 43, + ts_external_token__br_flw_njv_bgn = 44, + ts_external_token__r_dqt_str_bgn = 45, + ts_external_token__br_dqt_str_bgn = 46, + ts_external_token__b_dqt_str_bgn = 47, + ts_external_token__r_dqt_str_ctn = 48, + ts_external_token__br_dqt_str_ctn = 49, + ts_external_token__r_dqt_esc_nwl = 50, + ts_external_token__br_dqt_esc_nwl = 51, + ts_external_token__r_dqt_esc_seq = 52, + ts_external_token__br_dqt_esc_seq = 53, + ts_external_token__r_dqt_str_end = 54, + ts_external_token__br_dqt_str_end = 55, + ts_external_token__r_sqt_str_bgn = 56, + ts_external_token__br_sqt_str_bgn = 57, + ts_external_token__b_sqt_str_bgn = 58, + ts_external_token__r_sqt_str_ctn = 59, + ts_external_token__br_sqt_str_ctn = 60, + ts_external_token__r_sqt_esc_sqt = 61, + ts_external_token__br_sqt_esc_sqt = 62, + ts_external_token__r_sqt_str_end = 63, + ts_external_token__br_sqt_str_end = 64, + ts_external_token__r_sgl_pln_nul_blk = 65, + ts_external_token__br_sgl_pln_nul_blk = 66, + ts_external_token__b_sgl_pln_nul_blk = 67, + ts_external_token__r_sgl_pln_nul_flw = 68, + ts_external_token__br_sgl_pln_nul_flw = 69, + ts_external_token__r_sgl_pln_bol_blk = 70, + ts_external_token__br_sgl_pln_bol_blk = 71, + ts_external_token__b_sgl_pln_bol_blk = 72, + ts_external_token__r_sgl_pln_bol_flw = 73, + ts_external_token__br_sgl_pln_bol_flw = 74, + ts_external_token__r_sgl_pln_int_blk = 75, + ts_external_token__br_sgl_pln_int_blk = 76, + ts_external_token__b_sgl_pln_int_blk = 77, + ts_external_token__r_sgl_pln_int_flw = 78, + ts_external_token__br_sgl_pln_int_flw = 79, + ts_external_token__r_sgl_pln_flt_blk = 80, + ts_external_token__br_sgl_pln_flt_blk = 81, + ts_external_token__b_sgl_pln_flt_blk = 82, + ts_external_token__r_sgl_pln_flt_flw = 83, + ts_external_token__br_sgl_pln_flt_flw = 84, + ts_external_token__r_sgl_pln_tms_blk = 85, + ts_external_token__br_sgl_pln_tms_blk = 86, + ts_external_token__b_sgl_pln_tms_blk = 87, + ts_external_token__r_sgl_pln_tms_flw = 88, + ts_external_token__br_sgl_pln_tms_flw = 89, + ts_external_token__r_sgl_pln_str_blk = 90, + ts_external_token__br_sgl_pln_str_blk = 91, + ts_external_token__b_sgl_pln_str_blk = 92, + ts_external_token__r_sgl_pln_str_flw = 93, + ts_external_token__br_sgl_pln_str_flw = 94, + ts_external_token__r_mtl_pln_str_blk = 95, + ts_external_token__br_mtl_pln_str_blk = 96, + ts_external_token__r_mtl_pln_str_flw = 97, + ts_external_token__br_mtl_pln_str_flw = 98, + ts_external_token__r_tag = 99, + ts_external_token__br_tag = 100, + ts_external_token__b_tag = 101, + ts_external_token__r_acr_bgn = 102, + ts_external_token__br_acr_bgn = 103, + ts_external_token__b_acr_bgn = 104, + ts_external_token__r_acr_ctn = 105, + ts_external_token__r_als_bgn = 106, + ts_external_token__br_als_bgn = 107, + ts_external_token__b_als_bgn = 108, + ts_external_token__r_als_ctn = 109, + ts_external_token__bl = 110, + ts_external_token_comment = 111, + ts_external_token__err_rec = 112, +}; + +static const TSSymbol ts_external_scanner_symbol_map[EXTERNAL_TOKEN_COUNT] = { + [ts_external_token__eof] = sym__eof, + [ts_external_token__s_dir_yml_bgn] = sym__s_dir_yml_bgn, + [ts_external_token__r_dir_yml_ver] = sym__r_dir_yml_ver, + [ts_external_token__s_dir_tag_bgn] = sym__s_dir_tag_bgn, + [ts_external_token__r_dir_tag_hdl] = sym__r_dir_tag_hdl, + [ts_external_token__r_dir_tag_pfx] = sym__r_dir_tag_pfx, + [ts_external_token__s_dir_rsv_bgn] = sym__s_dir_rsv_bgn, + [ts_external_token__r_dir_rsv_prm] = sym__r_dir_rsv_prm, + [ts_external_token__s_drs_end] = sym__s_drs_end, + [ts_external_token__s_doc_end] = sym__s_doc_end, + [ts_external_token__r_blk_seq_bgn] = sym__r_blk_seq_bgn, + [ts_external_token__br_blk_seq_bgn] = sym__br_blk_seq_bgn, + [ts_external_token__b_blk_seq_bgn] = sym__b_blk_seq_bgn, + [ts_external_token__r_blk_key_bgn] = sym__r_blk_key_bgn, + [ts_external_token__br_blk_key_bgn] = sym__br_blk_key_bgn, + [ts_external_token__b_blk_key_bgn] = sym__b_blk_key_bgn, + [ts_external_token__r_blk_val_bgn] = sym__r_blk_val_bgn, + [ts_external_token__br_blk_val_bgn] = sym__br_blk_val_bgn, + [ts_external_token__b_blk_val_bgn] = sym__b_blk_val_bgn, + [ts_external_token__r_blk_imp_bgn] = sym__r_blk_imp_bgn, + [ts_external_token__r_blk_lit_bgn] = sym__r_blk_lit_bgn, + [ts_external_token__br_blk_lit_bgn] = sym__br_blk_lit_bgn, + [ts_external_token__r_blk_fld_bgn] = sym__r_blk_fld_bgn, + [ts_external_token__br_blk_fld_bgn] = sym__br_blk_fld_bgn, + [ts_external_token__br_blk_str_ctn] = sym__br_blk_str_ctn, + [ts_external_token__r_flw_seq_bgn] = sym__r_flw_seq_bgn, + [ts_external_token__br_flw_seq_bgn] = sym__br_flw_seq_bgn, + [ts_external_token__b_flw_seq_bgn] = sym__b_flw_seq_bgn, + [ts_external_token__r_flw_seq_end] = sym__r_flw_seq_end, + [ts_external_token__br_flw_seq_end] = sym__br_flw_seq_end, + [ts_external_token__b_flw_seq_end] = sym__b_flw_seq_end, + [ts_external_token__r_flw_map_bgn] = sym__r_flw_map_bgn, + [ts_external_token__br_flw_map_bgn] = sym__br_flw_map_bgn, + [ts_external_token__b_flw_map_bgn] = sym__b_flw_map_bgn, + [ts_external_token__r_flw_map_end] = sym__r_flw_map_end, + [ts_external_token__br_flw_map_end] = sym__br_flw_map_end, + [ts_external_token__b_flw_map_end] = sym__b_flw_map_end, + [ts_external_token__r_flw_sep_bgn] = sym__r_flw_sep_bgn, + [ts_external_token__br_flw_sep_bgn] = sym__br_flw_sep_bgn, + [ts_external_token__r_flw_key_bgn] = sym__r_flw_key_bgn, + [ts_external_token__br_flw_key_bgn] = sym__br_flw_key_bgn, + [ts_external_token__r_flw_jsv_bgn] = sym__r_flw_jsv_bgn, + [ts_external_token__br_flw_jsv_bgn] = sym__br_flw_jsv_bgn, + [ts_external_token__r_flw_njv_bgn] = sym__r_flw_njv_bgn, + [ts_external_token__br_flw_njv_bgn] = sym__br_flw_njv_bgn, + [ts_external_token__r_dqt_str_bgn] = sym__r_dqt_str_bgn, + [ts_external_token__br_dqt_str_bgn] = sym__br_dqt_str_bgn, + [ts_external_token__b_dqt_str_bgn] = sym__b_dqt_str_bgn, + [ts_external_token__r_dqt_str_ctn] = sym__r_dqt_str_ctn, + [ts_external_token__br_dqt_str_ctn] = sym__br_dqt_str_ctn, + [ts_external_token__r_dqt_esc_nwl] = sym__r_dqt_esc_nwl, + [ts_external_token__br_dqt_esc_nwl] = sym__br_dqt_esc_nwl, + [ts_external_token__r_dqt_esc_seq] = sym__r_dqt_esc_seq, + [ts_external_token__br_dqt_esc_seq] = sym__br_dqt_esc_seq, + [ts_external_token__r_dqt_str_end] = sym__r_dqt_str_end, + [ts_external_token__br_dqt_str_end] = sym__br_dqt_str_end, + [ts_external_token__r_sqt_str_bgn] = sym__r_sqt_str_bgn, + [ts_external_token__br_sqt_str_bgn] = sym__br_sqt_str_bgn, + [ts_external_token__b_sqt_str_bgn] = sym__b_sqt_str_bgn, + [ts_external_token__r_sqt_str_ctn] = sym__r_sqt_str_ctn, + [ts_external_token__br_sqt_str_ctn] = sym__br_sqt_str_ctn, + [ts_external_token__r_sqt_esc_sqt] = sym__r_sqt_esc_sqt, + [ts_external_token__br_sqt_esc_sqt] = sym__br_sqt_esc_sqt, + [ts_external_token__r_sqt_str_end] = sym__r_sqt_str_end, + [ts_external_token__br_sqt_str_end] = sym__br_sqt_str_end, + [ts_external_token__r_sgl_pln_nul_blk] = sym__r_sgl_pln_nul_blk, + [ts_external_token__br_sgl_pln_nul_blk] = sym__br_sgl_pln_nul_blk, + [ts_external_token__b_sgl_pln_nul_blk] = sym__b_sgl_pln_nul_blk, + [ts_external_token__r_sgl_pln_nul_flw] = sym__r_sgl_pln_nul_flw, + [ts_external_token__br_sgl_pln_nul_flw] = sym__br_sgl_pln_nul_flw, + [ts_external_token__r_sgl_pln_bol_blk] = sym__r_sgl_pln_bol_blk, + [ts_external_token__br_sgl_pln_bol_blk] = sym__br_sgl_pln_bol_blk, + [ts_external_token__b_sgl_pln_bol_blk] = sym__b_sgl_pln_bol_blk, + [ts_external_token__r_sgl_pln_bol_flw] = sym__r_sgl_pln_bol_flw, + [ts_external_token__br_sgl_pln_bol_flw] = sym__br_sgl_pln_bol_flw, + [ts_external_token__r_sgl_pln_int_blk] = sym__r_sgl_pln_int_blk, + [ts_external_token__br_sgl_pln_int_blk] = sym__br_sgl_pln_int_blk, + [ts_external_token__b_sgl_pln_int_blk] = sym__b_sgl_pln_int_blk, + [ts_external_token__r_sgl_pln_int_flw] = sym__r_sgl_pln_int_flw, + [ts_external_token__br_sgl_pln_int_flw] = sym__br_sgl_pln_int_flw, + [ts_external_token__r_sgl_pln_flt_blk] = sym__r_sgl_pln_flt_blk, + [ts_external_token__br_sgl_pln_flt_blk] = sym__br_sgl_pln_flt_blk, + [ts_external_token__b_sgl_pln_flt_blk] = sym__b_sgl_pln_flt_blk, + [ts_external_token__r_sgl_pln_flt_flw] = sym__r_sgl_pln_flt_flw, + [ts_external_token__br_sgl_pln_flt_flw] = sym__br_sgl_pln_flt_flw, + [ts_external_token__r_sgl_pln_tms_blk] = sym__r_sgl_pln_tms_blk, + [ts_external_token__br_sgl_pln_tms_blk] = sym__br_sgl_pln_tms_blk, + [ts_external_token__b_sgl_pln_tms_blk] = sym__b_sgl_pln_tms_blk, + [ts_external_token__r_sgl_pln_tms_flw] = sym__r_sgl_pln_tms_flw, + [ts_external_token__br_sgl_pln_tms_flw] = sym__br_sgl_pln_tms_flw, + [ts_external_token__r_sgl_pln_str_blk] = sym__r_sgl_pln_str_blk, + [ts_external_token__br_sgl_pln_str_blk] = sym__br_sgl_pln_str_blk, + [ts_external_token__b_sgl_pln_str_blk] = sym__b_sgl_pln_str_blk, + [ts_external_token__r_sgl_pln_str_flw] = sym__r_sgl_pln_str_flw, + [ts_external_token__br_sgl_pln_str_flw] = sym__br_sgl_pln_str_flw, + [ts_external_token__r_mtl_pln_str_blk] = sym__r_mtl_pln_str_blk, + [ts_external_token__br_mtl_pln_str_blk] = sym__br_mtl_pln_str_blk, + [ts_external_token__r_mtl_pln_str_flw] = sym__r_mtl_pln_str_flw, + [ts_external_token__br_mtl_pln_str_flw] = sym__br_mtl_pln_str_flw, + [ts_external_token__r_tag] = sym__r_tag, + [ts_external_token__br_tag] = sym__br_tag, + [ts_external_token__b_tag] = sym__b_tag, + [ts_external_token__r_acr_bgn] = sym__r_acr_bgn, + [ts_external_token__br_acr_bgn] = sym__br_acr_bgn, + [ts_external_token__b_acr_bgn] = sym__b_acr_bgn, + [ts_external_token__r_acr_ctn] = sym__r_acr_ctn, + [ts_external_token__r_als_bgn] = sym__r_als_bgn, + [ts_external_token__br_als_bgn] = sym__br_als_bgn, + [ts_external_token__b_als_bgn] = sym__b_als_bgn, + [ts_external_token__r_als_ctn] = sym__r_als_ctn, + [ts_external_token__bl] = sym__bl, + [ts_external_token_comment] = sym_comment, + [ts_external_token__err_rec] = sym__err_rec, +}; + +static const bool ts_external_scanner_states[110][EXTERNAL_TOKEN_COUNT] = { + [1] = { + [ts_external_token__eof] = true, + [ts_external_token__s_dir_yml_bgn] = true, + [ts_external_token__r_dir_yml_ver] = true, + [ts_external_token__s_dir_tag_bgn] = true, + [ts_external_token__r_dir_tag_hdl] = true, + [ts_external_token__r_dir_tag_pfx] = true, + [ts_external_token__s_dir_rsv_bgn] = true, + [ts_external_token__r_dir_rsv_prm] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__r_blk_seq_bgn] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__r_blk_key_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__r_blk_val_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__br_blk_str_ctn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_key_bgn] = true, + [ts_external_token__br_flw_key_bgn] = true, + [ts_external_token__r_flw_jsv_bgn] = true, + [ts_external_token__br_flw_jsv_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_dqt_str_ctn] = true, + [ts_external_token__br_dqt_str_ctn] = true, + [ts_external_token__r_dqt_esc_nwl] = true, + [ts_external_token__br_dqt_esc_nwl] = true, + [ts_external_token__r_dqt_esc_seq] = true, + [ts_external_token__br_dqt_esc_seq] = true, + [ts_external_token__r_dqt_str_end] = true, + [ts_external_token__br_dqt_str_end] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sqt_str_ctn] = true, + [ts_external_token__br_sqt_str_ctn] = true, + [ts_external_token__r_sqt_esc_sqt] = true, + [ts_external_token__br_sqt_esc_sqt] = true, + [ts_external_token__r_sqt_str_end] = true, + [ts_external_token__br_sqt_str_end] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__r_acr_ctn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__r_als_ctn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + [ts_external_token__err_rec] = true, + }, + [2] = { + [ts_external_token__eof] = true, + [ts_external_token__s_dir_yml_bgn] = true, + [ts_external_token__s_dir_tag_bgn] = true, + [ts_external_token__s_dir_rsv_bgn] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__r_blk_seq_bgn] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__r_blk_key_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__r_blk_val_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [3] = { + [ts_external_token__r_blk_seq_bgn] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__r_blk_key_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__r_blk_val_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [4] = { + [ts_external_token__r_blk_seq_bgn] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__r_blk_key_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__r_blk_val_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [5] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [6] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [7] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_key_bgn] = true, + [ts_external_token__br_flw_key_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [8] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_key_bgn] = true, + [ts_external_token__br_flw_key_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [9] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [10] = { + [ts_external_token__eof] = true, + [ts_external_token__s_dir_yml_bgn] = true, + [ts_external_token__s_dir_tag_bgn] = true, + [ts_external_token__s_dir_rsv_bgn] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [11] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [12] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [13] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_key_bgn] = true, + [ts_external_token__br_flw_key_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [14] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [15] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [16] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [17] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [18] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [19] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [20] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [21] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [22] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [23] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [24] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [25] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [26] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [27] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [28] = { + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [29] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_key_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [30] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [31] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_key_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [32] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [33] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [34] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [35] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [36] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [37] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_key_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [38] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [39] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [40] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [41] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token_comment] = true, + }, + [42] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [43] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [44] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [45] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token_comment] = true, + }, + [46] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token_comment] = true, + }, + [47] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token_comment] = true, + }, + [48] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [49] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token_comment] = true, + }, + [50] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [51] = { + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [52] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [53] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [54] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [55] = { + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token_comment] = true, + }, + [56] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [57] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [58] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [59] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [60] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token_comment] = true, + }, + [61] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [62] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token_comment] = true, + }, + [63] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token_comment] = true, + }, + [64] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [65] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token_comment] = true, + }, + [66] = { + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [67] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token_comment] = true, + }, + [68] = { + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token_comment] = true, + }, + [69] = { + [ts_external_token__r_dqt_str_ctn] = true, + [ts_external_token__br_dqt_str_ctn] = true, + [ts_external_token__r_dqt_esc_nwl] = true, + [ts_external_token__br_dqt_esc_nwl] = true, + [ts_external_token__r_dqt_esc_seq] = true, + [ts_external_token__br_dqt_esc_seq] = true, + [ts_external_token__r_dqt_str_end] = true, + [ts_external_token__br_dqt_str_end] = true, + [ts_external_token_comment] = true, + }, + [70] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token_comment] = true, + }, + [71] = { + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token_comment] = true, + }, + [72] = { + [ts_external_token__s_dir_yml_bgn] = true, + [ts_external_token__s_dir_tag_bgn] = true, + [ts_external_token__s_dir_rsv_bgn] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token_comment] = true, + }, + [73] = { + [ts_external_token__r_sqt_str_ctn] = true, + [ts_external_token__br_sqt_str_ctn] = true, + [ts_external_token__r_sqt_esc_sqt] = true, + [ts_external_token__br_sqt_esc_sqt] = true, + [ts_external_token__r_sqt_str_end] = true, + [ts_external_token__br_sqt_str_end] = true, + [ts_external_token_comment] = true, + }, + [74] = { + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_jsv_bgn] = true, + [ts_external_token__br_flw_jsv_bgn] = true, + [ts_external_token_comment] = true, + }, + [75] = { + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token_comment] = true, + }, + [76] = { + [ts_external_token__br_dqt_str_ctn] = true, + [ts_external_token__br_dqt_esc_nwl] = true, + [ts_external_token__br_dqt_esc_seq] = true, + [ts_external_token__r_dqt_str_end] = true, + [ts_external_token__br_dqt_str_end] = true, + [ts_external_token_comment] = true, + }, + [77] = { + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token_comment] = true, + }, + [78] = { + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_jsv_bgn] = true, + [ts_external_token_comment] = true, + }, + [79] = { + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token_comment] = true, + }, + [80] = { + [ts_external_token__br_sqt_str_ctn] = true, + [ts_external_token__br_sqt_esc_sqt] = true, + [ts_external_token__r_sqt_str_end] = true, + [ts_external_token__br_sqt_str_end] = true, + [ts_external_token_comment] = true, + }, + [81] = { + [ts_external_token__s_dir_yml_bgn] = true, + [ts_external_token__s_dir_tag_bgn] = true, + [ts_external_token__s_dir_rsv_bgn] = true, + [ts_external_token__r_dir_rsv_prm] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token_comment] = true, + }, + [82] = { + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token_comment] = true, + }, + [83] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token_comment] = true, + }, + [84] = { + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token_comment] = true, + }, + [85] = { + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token_comment] = true, + }, + [86] = { + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [87] = { + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [88] = { + [ts_external_token__r_dqt_str_ctn] = true, + [ts_external_token__r_dqt_esc_seq] = true, + [ts_external_token__r_dqt_str_end] = true, + [ts_external_token_comment] = true, + }, + [89] = { + [ts_external_token__r_sqt_str_ctn] = true, + [ts_external_token__r_sqt_esc_sqt] = true, + [ts_external_token__r_sqt_str_end] = true, + [ts_external_token_comment] = true, + }, + [90] = { + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token_comment] = true, + }, + [91] = { + [ts_external_token__r_flw_jsv_bgn] = true, + [ts_external_token__br_flw_jsv_bgn] = true, + [ts_external_token_comment] = true, + }, + [92] = { + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_jsv_bgn] = true, + [ts_external_token_comment] = true, + }, + [93] = { + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token_comment] = true, + }, + [94] = { + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_jsv_bgn] = true, + [ts_external_token_comment] = true, + }, + [95] = { + [ts_external_token__br_blk_str_ctn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [96] = { + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token_comment] = true, + }, + [97] = { + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token_comment] = true, + }, + [98] = { + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token_comment] = true, + }, + [99] = { + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token_comment] = true, + }, + [100] = { + [ts_external_token__r_flw_jsv_bgn] = true, + [ts_external_token_comment] = true, + }, + [101] = { + [ts_external_token__r_acr_ctn] = true, + [ts_external_token_comment] = true, + }, + [102] = { + [ts_external_token_comment] = true, + }, + [103] = { + [ts_external_token__r_dir_yml_ver] = true, + [ts_external_token_comment] = true, + }, + [104] = { + [ts_external_token__eof] = true, + [ts_external_token_comment] = true, + }, + [105] = { + [ts_external_token__r_als_ctn] = true, + [ts_external_token_comment] = true, + }, + [106] = { + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token_comment] = true, + }, + [107] = { + [ts_external_token__r_flw_map_end] = true, + [ts_external_token_comment] = true, + }, + [108] = { + [ts_external_token__r_dir_tag_pfx] = true, + [ts_external_token_comment] = true, + }, + [109] = { + [ts_external_token__r_dir_tag_hdl] = true, + [ts_external_token_comment] = true, + }, +}; + +#ifdef __cplusplus +extern "C" { +#endif +void *tree_sitter_yaml_external_scanner_create(void); +void tree_sitter_yaml_external_scanner_destroy(void *); +bool tree_sitter_yaml_external_scanner_scan(void *, TSLexer *, const bool *); +unsigned tree_sitter_yaml_external_scanner_serialize(void *, char *); +void tree_sitter_yaml_external_scanner_deserialize(void *, const char *, unsigned); + +#ifdef TREE_SITTER_HIDE_SYMBOLS +#define TS_PUBLIC +#elif defined(_WIN32) +#define TS_PUBLIC __declspec(dllexport) +#else +#define TS_PUBLIC __attribute__((visibility("default"))) +#endif + +TS_PUBLIC const TSLanguage *tree_sitter_yaml(void) { + static const TSLanguage language = { + .abi_version = LANGUAGE_VERSION, + .symbol_count = SYMBOL_COUNT, + .alias_count = ALIAS_COUNT, + .token_count = TOKEN_COUNT, + .external_token_count = EXTERNAL_TOKEN_COUNT, + .state_count = STATE_COUNT, + .large_state_count = LARGE_STATE_COUNT, + .production_id_count = PRODUCTION_ID_COUNT, + .field_count = FIELD_COUNT, + .max_alias_sequence_length = MAX_ALIAS_SEQUENCE_LENGTH, + .parse_table = &ts_parse_table[0][0], + .small_parse_table = ts_small_parse_table, + .small_parse_table_map = ts_small_parse_table_map, + .parse_actions = ts_parse_actions, + .symbol_names = ts_symbol_names, + .field_names = ts_field_names, + .field_map_slices = ts_field_map_slices, + .field_map_entries = ts_field_map_entries, + .symbol_metadata = ts_symbol_metadata, + .public_symbol_map = ts_symbol_map, + .alias_map = ts_non_terminal_alias_map, + .alias_sequences = &ts_alias_sequences[0][0], + .lex_modes = (const void*)ts_lex_modes, + .lex_fn = ts_lex, + .external_scanner = { + &ts_external_scanner_states[0][0], + ts_external_scanner_symbol_map, + tree_sitter_yaml_external_scanner_create, + tree_sitter_yaml_external_scanner_destroy, + tree_sitter_yaml_external_scanner_scan, + tree_sitter_yaml_external_scanner_serialize, + tree_sitter_yaml_external_scanner_deserialize, + }, + .primary_state_ids = ts_primary_state_ids, + }; + return &language; +} +#ifdef __cplusplus +} +#endif diff --git a/Sources/TreeSitterYAML/provenance.json b/Sources/TreeSitterYAML/provenance.json new file mode 100644 index 0000000..18a53e8 --- /dev/null +++ b/Sources/TreeSitterYAML/provenance.json @@ -0,0 +1,38 @@ +{ + "upstream": "https://github.com/tree-sitter-grammars/tree-sitter-yaml", + "revision": "7708026449bed86239b1cd5bce6e3c34dbca6415", + "files": { + "parser.c": { + "source": "src/parser.c", + "sha256": "8a3baaab33fb63cf9a89f97ec61dbb3ab0d4ef69be9f0f229092c79d129617c9" + }, + "scanner.c": { + "source": "src/scanner.c", + "sha256": "9cd962f7c7541247cfc7ebf661abaa5d9b642d27de16575c87093496557aae59" + }, + "schema.core.c": { + "source": "src/schema.core.c", + "sha256": "91e56c3f3ae6fad1803b739ce4eb4568a782a9aec710f733db2f3e38d407a4d5" + }, + "tree_sitter/alloc.h": { + "source": "src/tree_sitter/alloc.h", + "sha256": "b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea" + }, + "tree_sitter/array.h": { + "source": "src/tree_sitter/array.h", + "sha256": "5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94" + }, + "tree_sitter/parser.h": { + "source": "src/tree_sitter/parser.h", + "sha256": "180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2" + }, + "include/yaml.h": { + "source": "bindings/swift/TreeSitterYAML/yaml.h", + "sha256": "b03b74d6fca5ff3e9339610153ea1772e9f2e1d6189acb918a249de0a3fb6107" + }, + "LICENSE": { + "source": "LICENSE", + "sha256": "2d181298822a124f6d106118dcc69c8d4d26ac668559be29682c452e712b0947" + } + } +} diff --git a/Sources/TreeSitterYAML/scanner.c b/Sources/TreeSitterYAML/scanner.c new file mode 100644 index 0000000..7168d53 --- /dev/null +++ b/Sources/TreeSitterYAML/scanner.c @@ -0,0 +1,1415 @@ +#include "tree_sitter/array.h" +#include "tree_sitter/parser.h" + +#define _str(x) #x +#define _file(x) _str(schema.x.c) + +#ifndef YAML_SCHEMA +#define YAML_SCHEMA core +#endif + +#include _file(YAML_SCHEMA) + +// clang-format off + +typedef enum { + END_OF_FILE, + + S_DIR_YML_BGN, R_DIR_YML_VER, + S_DIR_TAG_BGN, R_DIR_TAG_HDL, R_DIR_TAG_PFX, + S_DIR_RSV_BGN, R_DIR_RSV_PRM, + S_DRS_END, + S_DOC_END, + R_BLK_SEQ_BGN, BR_BLK_SEQ_BGN, B_BLK_SEQ_BGN, + R_BLK_KEY_BGN, BR_BLK_KEY_BGN, B_BLK_KEY_BGN, + R_BLK_VAL_BGN, BR_BLK_VAL_BGN, B_BLK_VAL_BGN, + R_BLK_IMP_BGN, + R_BLK_LIT_BGN, BR_BLK_LIT_BGN, + R_BLK_FLD_BGN, BR_BLK_FLD_BGN, + BR_BLK_STR_CTN, + R_FLW_SEQ_BGN, BR_FLW_SEQ_BGN, B_FLW_SEQ_BGN, + R_FLW_SEQ_END, BR_FLW_SEQ_END, B_FLW_SEQ_END, + R_FLW_MAP_BGN, BR_FLW_MAP_BGN, B_FLW_MAP_BGN, + R_FLW_MAP_END, BR_FLW_MAP_END, B_FLW_MAP_END, + R_FLW_SEP_BGN, BR_FLW_SEP_BGN, + R_FLW_KEY_BGN, BR_FLW_KEY_BGN, + R_FLW_JSV_BGN, BR_FLW_JSV_BGN, + R_FLW_NJV_BGN, BR_FLW_NJV_BGN, + R_DQT_STR_BGN, BR_DQT_STR_BGN, B_DQT_STR_BGN, + R_DQT_STR_CTN, BR_DQT_STR_CTN, + R_DQT_ESC_NWL, BR_DQT_ESC_NWL, + R_DQT_ESC_SEQ, BR_DQT_ESC_SEQ, + R_DQT_STR_END, BR_DQT_STR_END, + R_SQT_STR_BGN, BR_SQT_STR_BGN, B_SQT_STR_BGN, + R_SQT_STR_CTN, BR_SQT_STR_CTN, + R_SQT_ESC_SQT, BR_SQT_ESC_SQT, + R_SQT_STR_END, BR_SQT_STR_END, + + R_SGL_PLN_NUL_BLK, BR_SGL_PLN_NUL_BLK, B_SGL_PLN_NUL_BLK, R_SGL_PLN_NUL_FLW, BR_SGL_PLN_NUL_FLW, + R_SGL_PLN_BOL_BLK, BR_SGL_PLN_BOL_BLK, B_SGL_PLN_BOL_BLK, R_SGL_PLN_BOL_FLW, BR_SGL_PLN_BOL_FLW, + R_SGL_PLN_INT_BLK, BR_SGL_PLN_INT_BLK, B_SGL_PLN_INT_BLK, R_SGL_PLN_INT_FLW, BR_SGL_PLN_INT_FLW, + R_SGL_PLN_FLT_BLK, BR_SGL_PLN_FLT_BLK, B_SGL_PLN_FLT_BLK, R_SGL_PLN_FLT_FLW, BR_SGL_PLN_FLT_FLW, + R_SGL_PLN_TMS_BLK, BR_SGL_PLN_TMS_BLK, B_SGL_PLN_TMS_BLK, R_SGL_PLN_TMS_FLW, BR_SGL_PLN_TMS_FLW, + R_SGL_PLN_STR_BLK, BR_SGL_PLN_STR_BLK, B_SGL_PLN_STR_BLK, R_SGL_PLN_STR_FLW, BR_SGL_PLN_STR_FLW, + + R_MTL_PLN_STR_BLK, BR_MTL_PLN_STR_BLK, + R_MTL_PLN_STR_FLW, BR_MTL_PLN_STR_FLW, + + R_TAG, BR_TAG, B_TAG, + R_ACR_BGN, BR_ACR_BGN, B_ACR_BGN, R_ACR_CTN, + R_ALS_BGN, BR_ALS_BGN, B_ALS_BGN, R_ALS_CTN, + + BL, + COMMENT, + + ERR_REC, +} TokenType; + +// clang-format on + +#define SCN_SUCC 1 +#define SCN_STOP 0 +#define SCN_FAIL (-1) + +#define IND_ROT 'r' +#define IND_MAP 'm' +#define IND_SEQ 'q' +#define IND_STR 's' + +#define RET_SYM(RESULT_SYMBOL) \ + { \ + flush(scanner); \ + lexer->result_symbol = RESULT_SYMBOL; \ + return true; \ + } + +#define POP_IND() \ + { \ + /* incorrect status caused by error recovering */ \ + if (scanner->ind_typ_stk.size == 1) { \ + return false; \ + } \ + pop_ind(scanner); \ + } + +#define PUSH_IND(TYP, LEN) push_ind(scanner, TYP, LEN) + +#define PUSH_BGN_IND(TYP) \ + { \ + if (has_tab_ind) \ + return false; \ + push_ind(scanner, TYP, bgn_col); \ + } + +#define MAY_PUSH_IMP_IND(TYP) \ + { \ + if (cur_ind != scanner->blk_imp_col) { \ + if (scanner->blk_imp_tab) \ + return false; \ + push_ind(scanner, IND_MAP, scanner->blk_imp_col); \ + } \ + } + +#define MAY_PUSH_SPC_SEQ_IND() \ + { \ + if (cur_ind_typ == IND_MAP) { \ + push_ind(scanner, IND_SEQ, bgn_col); \ + } \ + } + +#define MAY_UPD_IMP_COL() \ + { \ + if (scanner->blk_imp_row != bgn_row) { \ + scanner->blk_imp_row = bgn_row; \ + scanner->blk_imp_col = bgn_col; \ + scanner->blk_imp_tab = has_tab_ind; \ + } \ + } + +#if HAS_TIMESTAMP +#define SGL_PLN_SYM(POS, CTX) \ + (scanner->rlt_sch == RS_NULL ? POS##_SGL_PLN_NUL_##CTX \ + : scanner->rlt_sch == RS_BOOL ? POS##_SGL_PLN_BOL_##CTX \ + : scanner->rlt_sch == RS_INT ? POS##_SGL_PLN_INT_##CTX \ + : scanner->rlt_sch == RS_FLOAT ? POS##_SGL_PLN_FLT_##CTX \ + : scanner->rlt_sch == RS_TIMESTAMP ? POS##_SGL_PLN_TMS_##CTX \ + : POS##_SGL_PLN_STR_##CTX) +#else +#define SGL_PLN_SYM(POS, CTX) \ + (scanner->rlt_sch == RS_NULL ? POS##_SGL_PLN_NUL_##CTX \ + : scanner->rlt_sch == RS_BOOL ? POS##_SGL_PLN_BOL_##CTX \ + : scanner->rlt_sch == RS_INT ? POS##_SGL_PLN_INT_##CTX \ + : scanner->rlt_sch == RS_FLOAT ? POS##_SGL_PLN_FLT_##CTX \ + : POS##_SGL_PLN_STR_##CTX) +#endif + +typedef struct { + int16_t row; + int16_t col; + int16_t blk_imp_row; + int16_t blk_imp_col; + int16_t blk_imp_tab; + Array(int16_t) ind_typ_stk; + Array(int16_t) ind_len_stk; + + // temp + int16_t end_row; + int16_t end_col; + int16_t cur_row; + int16_t cur_col; + int32_t cur_chr; + int8_t sch_stt; + ResultSchema rlt_sch; +} Scanner; + +static unsigned serialize(Scanner *scanner, char *buffer) { + size_t size = 0; + *(int16_t *)&buffer[size] = scanner->row; + size += sizeof(int16_t); + *(int16_t *)&buffer[size] = scanner->col; + size += sizeof(int16_t); + *(int16_t *)&buffer[size] = scanner->blk_imp_row; + size += sizeof(int16_t); + *(int16_t *)&buffer[size] = scanner->blk_imp_col; + size += sizeof(int16_t); + *(int16_t *)&buffer[size] = scanner->blk_imp_tab; + size += sizeof(int16_t); + int16_t *typ_itr = scanner->ind_typ_stk.contents + 1; + int16_t *typ_end = scanner->ind_typ_stk.contents + scanner->ind_typ_stk.size; + int16_t *len_itr = scanner->ind_len_stk.contents + 1; + for (; typ_itr != typ_end && size < TREE_SITTER_SERIALIZATION_BUFFER_SIZE; ++typ_itr, ++len_itr) { + *(int16_t *)&buffer[size] = *typ_itr; + size += sizeof(int16_t); + *(int16_t *)&buffer[size] = *len_itr; + size += sizeof(int16_t); + } + return size; +} + +static void deserialize(Scanner *scanner, const char *buffer, unsigned length) { + scanner->row = 0; + scanner->col = 0; + scanner->blk_imp_row = -1; + scanner->blk_imp_col = -1; + scanner->blk_imp_tab = 0; + array_delete(&scanner->ind_typ_stk); + array_push(&scanner->ind_typ_stk, IND_ROT); + array_delete(&scanner->ind_len_stk); + array_push(&scanner->ind_len_stk, -1); + if (length > 0) { + size_t size = 0; + scanner->row = *(int16_t *)&buffer[size]; + size += sizeof(int16_t); + scanner->col = *(int16_t *)&buffer[size]; + size += sizeof(int16_t); + scanner->blk_imp_row = *(int16_t *)&buffer[size]; + size += sizeof(int16_t); + scanner->blk_imp_col = *(int16_t *)&buffer[size]; + size += sizeof(int16_t); + scanner->blk_imp_tab = *(int16_t *)&buffer[size]; + size += sizeof(int16_t); + while (size < length) { + array_push(&scanner->ind_typ_stk, *(int16_t *)&buffer[size]); + size += sizeof(int16_t); + array_push(&scanner->ind_len_stk, *(int16_t *)&buffer[size]); + size += sizeof(int16_t); + } + assert(size == length); + } +} + +static inline void adv(Scanner *scanner, TSLexer *lexer) { + scanner->cur_col++; + scanner->cur_chr = lexer->lookahead; + lexer->advance(lexer, false); +} + +static inline void adv_nwl(Scanner *scanner, TSLexer *lexer) { + scanner->cur_row++; + scanner->cur_col = 0; + scanner->cur_chr = lexer->lookahead; + lexer->advance(lexer, false); +} + +static inline void skp(Scanner *scanner, TSLexer *lexer) { + scanner->cur_col++; + scanner->cur_chr = lexer->lookahead; + lexer->advance(lexer, true); +} + +static inline void skp_nwl(Scanner *scanner, TSLexer *lexer) { + scanner->cur_row++; + scanner->cur_col = 0; + scanner->cur_chr = lexer->lookahead; + lexer->advance(lexer, true); +} + +static inline void mrk_end(Scanner *scanner, TSLexer *lexer) { + scanner->end_row = scanner->cur_row; + scanner->end_col = scanner->cur_col; + lexer->mark_end(lexer); +} + +static inline void init(Scanner *scanner) { + scanner->cur_row = scanner->row; + scanner->cur_col = scanner->col; + scanner->cur_chr = 0; + scanner->sch_stt = 0; + scanner->rlt_sch = RS_STR; +} + +static inline void flush(Scanner *scanner) { + scanner->row = scanner->end_row; + scanner->col = scanner->end_col; +} + +static inline void pop_ind(Scanner *scanner) { + array_pop(&scanner->ind_len_stk); + array_pop(&scanner->ind_typ_stk); +} + +static inline void push_ind(Scanner *scanner, int16_t typ, int16_t len) { + array_push(&scanner->ind_len_stk, len); + array_push(&scanner->ind_typ_stk, typ); +} + +static inline bool is_wsp(int32_t c) { return c == ' ' || c == '\t'; } + +static inline bool is_nwl(int32_t c) { return c == '\r' || c == '\n'; } + +static inline bool is_wht(int32_t c) { return is_wsp(c) || is_nwl(c) || c == 0; } + +static inline bool is_ns_dec_digit(int32_t c) { return c >= '0' && c <= '9'; } + +static inline bool is_ns_hex_digit(int32_t c) { + return is_ns_dec_digit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); +} + +static inline bool is_ns_word_char(int32_t c) { + return c == '-' || (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); +} + +static inline bool is_nb_json(int32_t c) { return c == 0x09 || (c >= 0x20 && c <= 0x10ffff); } + +static inline bool is_nb_double_char(int32_t c) { return is_nb_json(c) && c != '\\' && c != '"'; } + +static inline bool is_nb_single_char(int32_t c) { return is_nb_json(c) && c != '\''; } + +static inline bool is_ns_char(int32_t c) { + return (c >= 0x21 && c <= 0x7e) || c == 0x85 || (c >= 0xa0 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xfefe) || + (c >= 0xff00 && c <= 0xfffd) || (c >= 0x10000 && c <= 0x10ffff); +} + +static inline bool is_c_indicator(int32_t c) { + return c == '-' || c == '?' || c == ':' || c == ',' || c == '[' || c == ']' || c == '{' || c == '}' || c == '#' || + c == '&' || c == '*' || c == '!' || c == '|' || c == '>' || c == '\'' || c == '"' || c == '%' || c == '@' || + c == '`'; +} + +static inline bool is_c_flow_indicator(int32_t c) { return c == ',' || c == '[' || c == ']' || c == '{' || c == '}'; } + +static inline bool is_plain_safe_in_block(int32_t c) { return is_ns_char(c); } + +static inline bool is_plain_safe_in_flow(int32_t c) { return is_ns_char(c) && !is_c_flow_indicator(c); } + +static inline bool is_ns_uri_char(int32_t c) { + return is_ns_word_char(c) || c == '#' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' || + c == '=' || c == '+' || c == '$' || c == ',' || c == '_' || c == '.' || c == '!' || c == '~' || c == '*' || + c == '\'' || c == '(' || c == ')' || c == '[' || c == ']'; +} + +static inline bool is_ns_tag_char(int32_t c) { + return is_ns_word_char(c) || c == '#' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' || + c == '=' || c == '+' || c == '$' || c == '_' || c == '.' || c == '~' || c == '*' || c == '\'' || c == '(' || + c == ')'; +} + +static inline bool is_ns_anchor_char(int32_t c) { return is_ns_char(c) && !is_c_flow_indicator(c); } + +static char scn_uri_esc(Scanner *scanner, TSLexer *lexer) { + if (lexer->lookahead != '%') { + return SCN_STOP; + } + mrk_end(scanner, lexer); + adv(scanner, lexer); + if (!is_ns_hex_digit(lexer->lookahead)) { + return SCN_FAIL; + } + adv(scanner, lexer); + if (!is_ns_hex_digit(lexer->lookahead)) { + return SCN_FAIL; + } + adv(scanner, lexer); + return SCN_SUCC; +} + +static char scn_ns_uri_char(Scanner *scanner, TSLexer *lexer) { + if (is_ns_uri_char(lexer->lookahead)) { + adv(scanner, lexer); + return SCN_SUCC; + } + return scn_uri_esc(scanner, lexer); +} + +static char scn_ns_tag_char(Scanner *scanner, TSLexer *lexer) { + if (is_ns_tag_char(lexer->lookahead)) { + adv(scanner, lexer); + return SCN_SUCC; + } + return scn_uri_esc(scanner, lexer); +} + +static bool scn_dir_bgn(Scanner *scanner, TSLexer *lexer) { + adv(scanner, lexer); + if (lexer->lookahead == 'Y') { + adv(scanner, lexer); + if (lexer->lookahead == 'A') { + adv(scanner, lexer); + if (lexer->lookahead == 'M') { + adv(scanner, lexer); + if (lexer->lookahead == 'L') { + adv(scanner, lexer); + if (is_wht(lexer->lookahead)) { + mrk_end(scanner, lexer); + RET_SYM(S_DIR_YML_BGN); + } + } + } + } + } else if (lexer->lookahead == 'T') { + adv(scanner, lexer); + if (lexer->lookahead == 'A') { + adv(scanner, lexer); + if (lexer->lookahead == 'G') { + adv(scanner, lexer); + if (is_wht(lexer->lookahead)) { + mrk_end(scanner, lexer); + RET_SYM(S_DIR_TAG_BGN); + } + } + } + } + for (;;) { + if (!is_ns_char(lexer->lookahead)) { + break; + } + adv(scanner, lexer); + } + if (scanner->cur_col > 1 && is_wht(lexer->lookahead)) { + mrk_end(scanner, lexer); + RET_SYM(S_DIR_RSV_BGN); + } + return false; +} + +static bool scn_dir_yml_ver(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + uint16_t n1 = 0; + uint16_t n2 = 0; + while (is_ns_dec_digit(lexer->lookahead)) { + adv(scanner, lexer); + n1++; + } + if (lexer->lookahead != '.') { + return false; + } + adv(scanner, lexer); + while (is_ns_dec_digit(lexer->lookahead)) { + adv(scanner, lexer); + n2++; + } + if (n1 == 0 || n2 == 0) { + return false; + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_tag_hdl_tal(Scanner *scanner, TSLexer *lexer) { + if (lexer->lookahead == '!') { + adv(scanner, lexer); + return true; + } + uint16_t n = 0; + while (is_ns_word_char(lexer->lookahead)) { + adv(scanner, lexer); + n++; + } + if (n == 0) { + return true; + } + if (lexer->lookahead == '!') { + adv(scanner, lexer); + return true; + } + return false; +} + +static bool scn_dir_tag_hdl(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (lexer->lookahead == '!') { + adv(scanner, lexer); + if (scn_tag_hdl_tal(scanner, lexer)) { + mrk_end(scanner, lexer); + RET_SYM(result_symbol); + } + } + return false; +} + +static bool scn_dir_tag_pfx(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (lexer->lookahead == '!') { + adv(scanner, lexer); + } else if (scn_ns_tag_char(scanner, lexer) == SCN_SUCC) { + ; + } else { + return false; + } + for (;;) { + switch (scn_ns_uri_char(scanner, lexer)) { + case SCN_STOP: + mrk_end(scanner, lexer); + case SCN_FAIL: + RET_SYM(result_symbol); + default: + break; + } + } +} + +static bool scn_dir_rsv_prm(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (!is_ns_char(lexer->lookahead)) { + return false; + } + adv(scanner, lexer); + while (is_ns_char(lexer->lookahead)) { + adv(scanner, lexer); + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_tag(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (lexer->lookahead != '!') { + return false; + } + adv(scanner, lexer); + if (is_wht(lexer->lookahead)) { + mrk_end(scanner, lexer); + RET_SYM(result_symbol); + } + if (lexer->lookahead == '<') { + adv(scanner, lexer); + if (scn_ns_uri_char(scanner, lexer) != SCN_SUCC) { + return false; + } + for (;;) { + switch (scn_ns_uri_char(scanner, lexer)) { + case SCN_STOP: + if (lexer->lookahead == '>') { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(result_symbol); + } + case SCN_FAIL: + return false; + default: + break; + } + } + } else { + if (scn_tag_hdl_tal(scanner, lexer) && scn_ns_tag_char(scanner, lexer) != SCN_SUCC) { + return false; + } + for (;;) { + switch (scn_ns_tag_char(scanner, lexer)) { + case SCN_STOP: + mrk_end(scanner, lexer); + case SCN_FAIL: + RET_SYM(result_symbol); + default: + break; + } + } + } + return false; +} + +static bool scn_acr_bgn(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (lexer->lookahead != '&') { + return false; + } + adv(scanner, lexer); + if (!is_ns_anchor_char(lexer->lookahead)) { + return false; + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_acr_ctn(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + while (is_ns_anchor_char(lexer->lookahead)) { + adv(scanner, lexer); + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_als_bgn(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (lexer->lookahead != '*') { + return false; + } + adv(scanner, lexer); + if (!is_ns_anchor_char(lexer->lookahead)) { + return false; + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_als_ctn(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + while (is_ns_anchor_char(lexer->lookahead)) { + adv(scanner, lexer); + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_dqt_esc_seq(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + uint16_t i; + switch (lexer->lookahead) { + case '0': + case 'a': + case 'b': + case 't': + case '\t': + case 'n': + case 'v': + case 'r': + case 'e': + case 'f': + case ' ': + case '"': + case '/': + case '\\': + case 'N': + case '_': + case 'L': + case 'P': + adv(scanner, lexer); + break; + case 'U': + adv(scanner, lexer); + for (i = 0; i < 8; i++) { + if (is_ns_hex_digit(lexer->lookahead)) { + adv(scanner, lexer); + } else { + return false; + } + } + break; + case 'u': + adv(scanner, lexer); + for (i = 0; i < 4; i++) { + if (is_ns_hex_digit(lexer->lookahead)) { + adv(scanner, lexer); + } else { + return false; + } + } + break; + case 'x': + adv(scanner, lexer); + for (i = 0; i < 2; i++) { + if (is_ns_hex_digit(lexer->lookahead)) { + adv(scanner, lexer); + } else { + return false; + } + } + break; + default: + return false; + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_drs_doc_end(Scanner *scanner, TSLexer *lexer) { + if (lexer->lookahead != '-' && lexer->lookahead != '.') { + return false; + } + int32_t delimeter = lexer->lookahead; + adv(scanner, lexer); + if (lexer->lookahead == delimeter) { + adv(scanner, lexer); + if (lexer->lookahead == delimeter) { + adv(scanner, lexer); + if (is_wht(lexer->lookahead)) { + return true; + } + } + } + mrk_end(scanner, lexer); + return false; +} + +static bool scn_dqt_str_cnt(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (!is_nb_double_char(lexer->lookahead)) { + return false; + } + if (scanner->cur_col == 0 && scn_drs_doc_end(scanner, lexer)) { + mrk_end(scanner, lexer); + RET_SYM(scanner->cur_chr == '-' ? S_DRS_END : S_DOC_END); + } else { + adv(scanner, lexer); + } + while (is_nb_double_char(lexer->lookahead)) { + adv(scanner, lexer); + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_sqt_str_cnt(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (!is_nb_single_char(lexer->lookahead)) { + return false; + } + if (scanner->cur_col == 0 && scn_drs_doc_end(scanner, lexer)) { + mrk_end(scanner, lexer); + RET_SYM(scanner->cur_chr == '-' ? S_DRS_END : S_DOC_END); + } else { + adv(scanner, lexer); + } + while (is_nb_single_char(lexer->lookahead)) { + adv(scanner, lexer); + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_blk_str_bgn(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (lexer->lookahead != '|' && lexer->lookahead != '>') { + return false; + } + adv(scanner, lexer); + int16_t cur_ind = *array_back(&scanner->ind_len_stk); + int16_t ind = -1; + if (lexer->lookahead >= '1' && lexer->lookahead <= '9') { + ind = lexer->lookahead - '1'; + adv(scanner, lexer); + if (lexer->lookahead == '+' || lexer->lookahead == '-') { + adv(scanner, lexer); + } + } else if (lexer->lookahead == '+' || lexer->lookahead == '-') { + adv(scanner, lexer); + if (lexer->lookahead >= '1' && lexer->lookahead <= '9') { + ind = lexer->lookahead - '1'; + adv(scanner, lexer); + } + } + if (!is_wht(lexer->lookahead)) { + return false; + } + mrk_end(scanner, lexer); + if (ind != -1) { + ind += cur_ind; + } else { + ind = cur_ind; + while (is_wsp(lexer->lookahead)) { + adv(scanner, lexer); + } + if (lexer->lookahead == '#') { + adv(scanner, lexer); + while (!is_nwl(lexer->lookahead) && lexer->lookahead != 0) { + adv(scanner, lexer); + } + } + if (is_nwl(lexer->lookahead)) { + adv_nwl(scanner, lexer); + } + while (lexer->lookahead != 0) { + if (lexer->lookahead == ' ') { + adv(scanner, lexer); + } else if (is_nwl(lexer->lookahead)) { + if (scanner->cur_col - 1 < ind) { + break; + } + ind = scanner->cur_col - 1; + adv_nwl(scanner, lexer); + } else { + if (scanner->cur_col - 1 > ind) { + ind = scanner->cur_col - 1; + } + break; + } + } + } + PUSH_IND(IND_STR, ind); + RET_SYM(result_symbol); +} + +static bool scn_blk_str_cnt(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (!is_ns_char(lexer->lookahead)) { + return false; + } + if (scanner->cur_col == 0 && scn_drs_doc_end(scanner, lexer)) { + POP_IND(); + RET_SYM(BL); + } else { + adv(scanner, lexer); + } + mrk_end(scanner, lexer); + for (;;) { + if (is_ns_char(lexer->lookahead)) { + adv(scanner, lexer); + while (is_ns_char(lexer->lookahead)) { + adv(scanner, lexer); + } + mrk_end(scanner, lexer); + } + if (is_wsp(lexer->lookahead)) { + adv(scanner, lexer); + while (is_wsp(lexer->lookahead)) { + adv(scanner, lexer); + } + } else { + break; + } + } + RET_SYM(result_symbol); +} + +static char scn_pln_cnt(Scanner *scanner, TSLexer *lexer, bool (*is_plain_safe)(int32_t)) { + bool is_cur_wsp = is_wsp(scanner->cur_chr); + bool is_cur_saf = is_plain_safe(scanner->cur_chr); + bool is_lka_wsp = is_wsp(lexer->lookahead); + bool is_lka_saf = is_plain_safe(lexer->lookahead); + if (is_lka_saf || is_lka_wsp) { + for (;;) { + if (is_lka_saf && lexer->lookahead != '#' && lexer->lookahead != ':') { + adv(scanner, lexer); + mrk_end(scanner, lexer); + scanner->sch_stt = adv_sch_stt(scanner->sch_stt, scanner->cur_chr, &scanner->rlt_sch); + } else if (is_cur_saf && lexer->lookahead == '#') { + adv(scanner, lexer); + mrk_end(scanner, lexer); + scanner->sch_stt = adv_sch_stt(scanner->sch_stt, scanner->cur_chr, &scanner->rlt_sch); + } else if (is_lka_wsp) { + adv(scanner, lexer); + scanner->sch_stt = adv_sch_stt(scanner->sch_stt, scanner->cur_chr, &scanner->rlt_sch); + } else if (lexer->lookahead == ':') { + adv(scanner, lexer); // check later + } else { + break; + } + + is_cur_wsp = is_lka_wsp; + is_cur_saf = is_lka_saf; + is_lka_wsp = is_wsp(lexer->lookahead); + is_lka_saf = is_plain_safe(lexer->lookahead); + + if (scanner->cur_chr == ':') { + if (is_lka_saf) { + mrk_end(scanner, lexer); + scanner->sch_stt = adv_sch_stt(scanner->sch_stt, scanner->cur_chr, &scanner->rlt_sch); + } else { + return SCN_FAIL; + } + } + } + } else { + return SCN_STOP; + } + return SCN_SUCC; +} + +static bool scan(Scanner *scanner, TSLexer *lexer, const bool *valid_symbols) { + init(scanner); + mrk_end(scanner, lexer); + + bool allow_comment = !(valid_symbols[R_DQT_STR_CTN] || valid_symbols[BR_DQT_STR_CTN] || + valid_symbols[R_SQT_STR_CTN] || valid_symbols[BR_SQT_STR_CTN]); + int16_t *ind_ptr = scanner->ind_len_stk.contents + scanner->ind_len_stk.size - 1; + int16_t *ind_end = scanner->ind_len_stk.contents - 1; + int16_t cur_ind = *ind_ptr--; + int16_t prt_ind = ind_ptr == ind_end ? -1 : *ind_ptr; + int16_t cur_ind_typ = *array_back(&scanner->ind_typ_stk); + + bool has_tab_ind = false; + int16_t leading_spaces = 0; + + for (;;) { + if (lexer->lookahead == ' ') { + if (!has_tab_ind) { + leading_spaces++; + } + skp(scanner, lexer); + } else if (lexer->lookahead == '\t') { + has_tab_ind = true; + skp(scanner, lexer); + } else if (is_nwl(lexer->lookahead)) { + has_tab_ind = false; + leading_spaces = 0; + skp_nwl(scanner, lexer); + } else if (allow_comment && lexer->lookahead == '#') { + if (valid_symbols[BR_BLK_STR_CTN] && valid_symbols[BL] && scanner->cur_col <= cur_ind) { + POP_IND(); + RET_SYM(BL); + } + if (valid_symbols[BR_BLK_STR_CTN] + ? scanner->cur_row == scanner->row + : scanner->cur_col == 0 || scanner->cur_row != scanner->row || scanner->cur_col > scanner->col) { + adv(scanner, lexer); + while (!is_nwl(lexer->lookahead) && lexer->lookahead != 0) { + adv(scanner, lexer); + } + mrk_end(scanner, lexer); + RET_SYM(COMMENT); + } else { + break; + } + } else { + break; + } + } + + if (lexer->lookahead == 0) { + if (valid_symbols[BL]) { + mrk_end(scanner, lexer); + POP_IND(); + RET_SYM(BL) + } + if (valid_symbols[END_OF_FILE]) { + mrk_end(scanner, lexer); + RET_SYM(END_OF_FILE) + } + return false; + } + + int16_t bgn_row = scanner->cur_row; + int16_t bgn_col = scanner->cur_col; + int32_t bgn_chr = lexer->lookahead; + + if (valid_symbols[BL] && bgn_col <= cur_ind && !has_tab_ind) { + if (cur_ind == prt_ind && cur_ind_typ == IND_SEQ ? bgn_col < cur_ind || lexer->lookahead != '-' + : bgn_col <= prt_ind || cur_ind_typ == IND_STR) { + POP_IND(); + RET_SYM(BL); + } + } + + bool has_nwl = scanner->cur_row > scanner->row; + bool is_r = !has_nwl; + bool is_br = has_nwl && leading_spaces > cur_ind; + bool is_b = has_nwl && leading_spaces == cur_ind && !has_tab_ind; + bool is_s = bgn_col == 0; + + if (valid_symbols[R_DIR_YML_VER] && is_r) { + return scn_dir_yml_ver(scanner, lexer, R_DIR_YML_VER); + } + if (valid_symbols[R_DIR_TAG_HDL] && is_r) { + return scn_dir_tag_hdl(scanner, lexer, R_DIR_TAG_HDL); + } + if (valid_symbols[R_DIR_TAG_PFX] && is_r) { + return scn_dir_tag_pfx(scanner, lexer, R_DIR_TAG_PFX); + } + if (valid_symbols[R_DIR_RSV_PRM] && is_r) { + return scn_dir_rsv_prm(scanner, lexer, R_DIR_RSV_PRM); + } + if (valid_symbols[BR_BLK_STR_CTN] && is_br && scn_blk_str_cnt(scanner, lexer, BR_BLK_STR_CTN)) { + return true; + } + + if ((valid_symbols[R_DQT_STR_CTN] && is_r && scn_dqt_str_cnt(scanner, lexer, R_DQT_STR_CTN)) || + (valid_symbols[BR_DQT_STR_CTN] && is_br && scn_dqt_str_cnt(scanner, lexer, BR_DQT_STR_CTN))) { + return true; + } + + if ((valid_symbols[R_SQT_STR_CTN] && is_r && scn_sqt_str_cnt(scanner, lexer, R_SQT_STR_CTN)) || + (valid_symbols[BR_SQT_STR_CTN] && is_br && scn_sqt_str_cnt(scanner, lexer, BR_SQT_STR_CTN))) { + return true; + } + + if (valid_symbols[R_ACR_CTN] && is_r) { + return scn_acr_ctn(scanner, lexer, R_ACR_CTN); + } + if (valid_symbols[R_ALS_CTN] && is_r) { + return scn_als_ctn(scanner, lexer, R_ALS_CTN); + } + + if (lexer->lookahead == '%') { + if (valid_symbols[S_DIR_YML_BGN] && is_s) { + return scn_dir_bgn(scanner, lexer); + } + } else if (lexer->lookahead == '*') { + if (valid_symbols[R_ALS_BGN] && is_r) { + MAY_UPD_IMP_COL(); + return scn_als_bgn(scanner, lexer, R_ALS_BGN); + } + if (valid_symbols[BR_ALS_BGN] && is_br) { + MAY_UPD_IMP_COL(); + return scn_als_bgn(scanner, lexer, BR_ALS_BGN); + } + if (valid_symbols[B_ALS_BGN] && is_b) { + MAY_UPD_IMP_COL(); + return scn_als_bgn(scanner, lexer, B_ALS_BGN); + } + } else if (lexer->lookahead == '&') { + if (valid_symbols[R_ACR_BGN] && is_r) { + MAY_UPD_IMP_COL(); + return scn_acr_bgn(scanner, lexer, R_ACR_BGN); + } + if (valid_symbols[BR_ACR_BGN] && is_br) { + MAY_UPD_IMP_COL(); + return scn_acr_bgn(scanner, lexer, BR_ACR_BGN); + } + if (valid_symbols[B_ACR_BGN] && is_b) { + MAY_UPD_IMP_COL(); + return scn_acr_bgn(scanner, lexer, B_ACR_BGN); + } + } else if (lexer->lookahead == '!') { + if (valid_symbols[R_TAG] && is_r) { + MAY_UPD_IMP_COL(); + return scn_tag(scanner, lexer, R_TAG); + } + if (valid_symbols[BR_TAG] && is_br) { + MAY_UPD_IMP_COL(); + return scn_tag(scanner, lexer, BR_TAG); + } + if (valid_symbols[B_TAG] && is_b) { + MAY_UPD_IMP_COL(); + return scn_tag(scanner, lexer, B_TAG); + } + } else if (lexer->lookahead == '[') { + if (valid_symbols[R_FLW_SEQ_BGN] && is_r) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_FLW_SEQ_BGN) + } + if (valid_symbols[BR_FLW_SEQ_BGN] && is_br) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_SEQ_BGN) + } + if (valid_symbols[B_FLW_SEQ_BGN] && is_b) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(B_FLW_SEQ_BGN) + } + } else if (lexer->lookahead == ']') { + if (valid_symbols[R_FLW_SEQ_END] && is_r) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_FLW_SEQ_END) + } + if (valid_symbols[BR_FLW_SEQ_END] && is_br) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_SEQ_END) + } + if (valid_symbols[B_FLW_SEQ_END] && is_b) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_SEQ_END) + } + } else if (lexer->lookahead == '{') { + if (valid_symbols[R_FLW_MAP_BGN] && is_r) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_FLW_MAP_BGN) + } + if (valid_symbols[BR_FLW_MAP_BGN] && is_br) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_MAP_BGN) + } + if (valid_symbols[B_FLW_MAP_BGN] && is_b) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(B_FLW_MAP_BGN) + } + } else if (lexer->lookahead == '}') { + if (valid_symbols[R_FLW_MAP_END] && is_r) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_FLW_MAP_END) + } + if (valid_symbols[BR_FLW_MAP_END] && is_br) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_MAP_END) + } + if (valid_symbols[B_FLW_MAP_END] && is_b) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_MAP_END) + } + } else if (lexer->lookahead == ',') { + if (valid_symbols[R_FLW_SEP_BGN] && is_r) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_FLW_SEP_BGN) + } + if (valid_symbols[BR_FLW_SEP_BGN] && is_br) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_SEP_BGN) + } + } else if (lexer->lookahead == '"') { + if (valid_symbols[R_DQT_STR_BGN] && is_r) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_DQT_STR_BGN) + } + if (valid_symbols[BR_DQT_STR_BGN] && is_br) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_DQT_STR_BGN) + } + if (valid_symbols[B_DQT_STR_BGN] && is_b) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(B_DQT_STR_BGN) + } + if (valid_symbols[R_DQT_STR_END] && is_r) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_DQT_STR_END) + } + if (valid_symbols[BR_DQT_STR_END] && is_br) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_DQT_STR_END) + } + } else if (lexer->lookahead == '\'') { + if (valid_symbols[R_SQT_STR_BGN] && is_r) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_SQT_STR_BGN) + } + if (valid_symbols[BR_SQT_STR_BGN] && is_br) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_SQT_STR_BGN) + } + if (valid_symbols[B_SQT_STR_BGN] && is_b) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(B_SQT_STR_BGN) + } + if (valid_symbols[R_SQT_STR_END] && is_r) { + adv(scanner, lexer); + if (lexer->lookahead == '\'') { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_SQT_ESC_SQT) + } else { + mrk_end(scanner, lexer); + RET_SYM(R_SQT_STR_END) + } + } + if (valid_symbols[BR_SQT_STR_END] && is_br) { + adv(scanner, lexer); + if (lexer->lookahead == '\'') { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_SQT_ESC_SQT) + } else { + mrk_end(scanner, lexer); + RET_SYM(BR_SQT_STR_END) + } + } + } else if (lexer->lookahead == '?') { + bool is_r_blk_key_bgn = valid_symbols[R_BLK_KEY_BGN] && is_r; + bool is_br_blk_key_bgn = valid_symbols[BR_BLK_KEY_BGN] && is_br; + bool is_b_blk_key_bgn = valid_symbols[B_BLK_KEY_BGN] && is_b; + bool is_r_flw_key_bgn = valid_symbols[R_FLW_KEY_BGN] && is_r; + bool is_br_flw_key_bgn = valid_symbols[BR_FLW_KEY_BGN] && is_br; + if (is_r_blk_key_bgn || is_br_blk_key_bgn || is_b_blk_key_bgn || is_r_flw_key_bgn || is_br_flw_key_bgn) { + adv(scanner, lexer); + if (is_wht(lexer->lookahead)) { + mrk_end(scanner, lexer); + if (is_r_blk_key_bgn) { + PUSH_BGN_IND(IND_MAP); + RET_SYM(R_BLK_KEY_BGN); + } + if (is_br_blk_key_bgn) { + PUSH_BGN_IND(IND_MAP); + RET_SYM(BR_BLK_KEY_BGN); + } + if (is_b_blk_key_bgn) + RET_SYM(B_BLK_KEY_BGN); + if (is_r_flw_key_bgn) + RET_SYM(R_FLW_KEY_BGN); + if (is_br_flw_key_bgn) + RET_SYM(BR_FLW_KEY_BGN); + } + } + } else if (lexer->lookahead == ':') { + if (valid_symbols[R_FLW_JSV_BGN] && is_r) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_FLW_JSV_BGN); + } + if (valid_symbols[BR_FLW_JSV_BGN] && is_br) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_JSV_BGN); + } + bool is_r_blk_val_bgn = valid_symbols[R_BLK_VAL_BGN] && is_r; + bool is_br_blk_val_bgn = valid_symbols[BR_BLK_VAL_BGN] && is_br; + bool is_b_blk_val_bgn = valid_symbols[B_BLK_VAL_BGN] && is_b; + bool is_r_blk_imp_bgn = valid_symbols[R_BLK_IMP_BGN] && is_r; + bool is_r_flw_njv_bgn = valid_symbols[R_FLW_NJV_BGN] && is_r; + bool is_br_flw_njv_bgn = valid_symbols[BR_FLW_NJV_BGN] && is_br; + if (is_r_blk_val_bgn || is_br_blk_val_bgn || is_b_blk_val_bgn || is_r_blk_imp_bgn || is_r_flw_njv_bgn || + is_br_flw_njv_bgn) { + adv(scanner, lexer); + bool is_lka_wht = is_wht(lexer->lookahead); + if (is_lka_wht) { + if (is_r_blk_val_bgn) { + PUSH_BGN_IND(IND_MAP); + mrk_end(scanner, lexer); + RET_SYM(R_BLK_VAL_BGN); + } + if (is_br_blk_val_bgn) { + PUSH_BGN_IND(IND_MAP); + mrk_end(scanner, lexer); + RET_SYM(BR_BLK_VAL_BGN); + } + if (is_b_blk_val_bgn) { + mrk_end(scanner, lexer); + RET_SYM(B_BLK_VAL_BGN); + } + if (is_r_blk_imp_bgn) { + MAY_PUSH_IMP_IND(); + mrk_end(scanner, lexer); + RET_SYM(R_BLK_IMP_BGN); + } + } + if (is_lka_wht || lexer->lookahead == ',' || lexer->lookahead == ']' || lexer->lookahead == '}') { + if (is_r_flw_njv_bgn) { + mrk_end(scanner, lexer); + RET_SYM(R_FLW_NJV_BGN); + } + if (is_br_flw_njv_bgn) { + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_NJV_BGN); + } + } + } + } else if (lexer->lookahead == '-') { + bool is_r_blk_seq_bgn = valid_symbols[R_BLK_SEQ_BGN] && is_r; + bool is_br_blk_seq_bgn = valid_symbols[BR_BLK_SEQ_BGN] && is_br; + bool is_b_blk_seq_bgn = valid_symbols[B_BLK_SEQ_BGN] && is_b; + bool is_s_drs_end = is_s; + if (is_r_blk_seq_bgn || is_br_blk_seq_bgn || is_b_blk_seq_bgn || is_s_drs_end) { + adv(scanner, lexer); + if (is_wht(lexer->lookahead)) { + if (is_r_blk_seq_bgn) { + PUSH_BGN_IND(IND_SEQ); + mrk_end(scanner, lexer); + RET_SYM(R_BLK_SEQ_BGN) + } + if (is_br_blk_seq_bgn) { + PUSH_BGN_IND(IND_SEQ); + mrk_end(scanner, lexer); + RET_SYM(BR_BLK_SEQ_BGN) + } + if (is_b_blk_seq_bgn) { + MAY_PUSH_SPC_SEQ_IND(); + mrk_end(scanner, lexer); + RET_SYM(B_BLK_SEQ_BGN) + } + } else if (lexer->lookahead == '-' && is_s_drs_end) { + adv(scanner, lexer); + if (lexer->lookahead == '-') { + adv(scanner, lexer); + if (is_wht(lexer->lookahead)) { + if (valid_symbols[BL]) { + POP_IND(); + RET_SYM(BL); + } + mrk_end(scanner, lexer); + RET_SYM(S_DRS_END); + } + } + } + } + } else if (lexer->lookahead == '.') { + if (is_s) { + adv(scanner, lexer); + if (lexer->lookahead == '.') { + adv(scanner, lexer); + if (lexer->lookahead == '.') { + adv(scanner, lexer); + if (is_wht(lexer->lookahead)) { + if (valid_symbols[BL]) { + POP_IND(); + RET_SYM(BL); + } + mrk_end(scanner, lexer); + RET_SYM(S_DOC_END); + } + } + } + } + } else if (lexer->lookahead == '\\') { + bool is_r_dqt_esc_nwl = valid_symbols[R_DQT_ESC_NWL] && is_r; + bool is_br_dqt_esc_nwl = valid_symbols[BR_DQT_ESC_NWL] && is_br; + bool is_r_dqt_esc_seq = valid_symbols[R_DQT_ESC_SEQ] && is_r; + bool is_br_dqt_esc_seq = valid_symbols[BR_DQT_ESC_SEQ] && is_br; + if (is_r_dqt_esc_nwl || is_br_dqt_esc_nwl || is_r_dqt_esc_seq || is_br_dqt_esc_seq) { + adv(scanner, lexer); + if (is_nwl(lexer->lookahead)) { + if (is_r_dqt_esc_nwl) { + mrk_end(scanner, lexer); + RET_SYM(R_DQT_ESC_NWL) + } + if (is_br_dqt_esc_nwl) { + mrk_end(scanner, lexer); + RET_SYM(BR_DQT_ESC_NWL) + } + } + if (is_r_dqt_esc_seq) { + return scn_dqt_esc_seq(scanner, lexer, R_DQT_ESC_SEQ); + } + if (is_br_dqt_esc_seq) { + return scn_dqt_esc_seq(scanner, lexer, BR_DQT_ESC_SEQ); + } + return false; + } + } else if (lexer->lookahead == '|') { + if (valid_symbols[R_BLK_LIT_BGN] && is_r) { + return scn_blk_str_bgn(scanner, lexer, R_BLK_LIT_BGN); + } + if (valid_symbols[BR_BLK_LIT_BGN] && is_br) { + return scn_blk_str_bgn(scanner, lexer, BR_BLK_LIT_BGN); + } + } else if (lexer->lookahead == '>') { + if (valid_symbols[R_BLK_FLD_BGN] && is_r) { + return scn_blk_str_bgn(scanner, lexer, R_BLK_FLD_BGN); + } + if (valid_symbols[BR_BLK_FLD_BGN] && is_br) { + return scn_blk_str_bgn(scanner, lexer, BR_BLK_FLD_BGN); + } + } + + bool maybe_sgl_pln_blk = (valid_symbols[R_SGL_PLN_STR_BLK] && is_r) || + (valid_symbols[BR_SGL_PLN_STR_BLK] && is_br) || (valid_symbols[B_SGL_PLN_STR_BLK] && is_b); + bool maybe_sgl_pln_flw = (valid_symbols[R_SGL_PLN_STR_FLW] && is_r) || (valid_symbols[BR_SGL_PLN_STR_FLW] && is_br); + bool maybe_mtl_pln_blk = (valid_symbols[R_MTL_PLN_STR_BLK] && is_r) || (valid_symbols[BR_MTL_PLN_STR_BLK] && is_br); + bool maybe_mtl_pln_flw = (valid_symbols[R_MTL_PLN_STR_FLW] && is_r) || (valid_symbols[BR_MTL_PLN_STR_FLW] && is_br); + + if (maybe_sgl_pln_blk || maybe_sgl_pln_flw || maybe_mtl_pln_blk || maybe_mtl_pln_flw) { + bool is_in_blk = maybe_sgl_pln_blk || maybe_mtl_pln_blk; + bool (*is_plain_safe)(int32_t) = is_in_blk ? is_plain_safe_in_block : is_plain_safe_in_flow; + if (scanner->cur_col - bgn_col == 0) { + adv(scanner, lexer); + } + if (scanner->cur_col - bgn_col == 1) { + bool is_plain_first = + (is_ns_char(bgn_chr) && !is_c_indicator(bgn_chr)) || + ((bgn_chr == '-' || bgn_chr == '?' || bgn_chr == ':') && is_plain_safe(lexer->lookahead)); + if (!is_plain_first) { + return false; + } + scanner->sch_stt = adv_sch_stt(scanner->sch_stt, scanner->cur_chr, &scanner->rlt_sch); + } else { + // no need to check the following cases: + // ..X + // ...X + // --X + // ---X + // X: lookahead + scanner->sch_stt = SCH_STT_FRZ; // must be RS_STR + } + + mrk_end(scanner, lexer); + + for (;;) { + if (!is_nwl(lexer->lookahead)) { + if (scn_pln_cnt(scanner, lexer, is_plain_safe) != SCN_SUCC) { + break; + } + } + if (lexer->lookahead == 0 || !is_nwl(lexer->lookahead)) { + break; + } + for (;;) { + if (is_nwl(lexer->lookahead)) { + adv_nwl(scanner, lexer); + } else if (is_wsp(lexer->lookahead)) { + adv(scanner, lexer); + } else { + break; + } + } + if (lexer->lookahead == 0 || scanner->cur_col <= cur_ind) { + break; + } + if (scanner->cur_col == 0 && scn_drs_doc_end(scanner, lexer)) { + break; + } + } + + if (scanner->end_row == bgn_row) { + if (maybe_sgl_pln_blk) { + MAY_UPD_IMP_COL(); + RET_SYM(is_r ? SGL_PLN_SYM(R, BLK) : is_br ? SGL_PLN_SYM(BR, BLK) : SGL_PLN_SYM(B, BLK)); + } + if (maybe_sgl_pln_flw) + RET_SYM(is_r ? SGL_PLN_SYM(R, FLW) : SGL_PLN_SYM(BR, FLW)); + } else { + if (maybe_mtl_pln_blk) { + MAY_UPD_IMP_COL(); + RET_SYM(is_r ? R_MTL_PLN_STR_BLK : BR_MTL_PLN_STR_BLK); + } + if (maybe_mtl_pln_flw) + RET_SYM(is_r ? R_MTL_PLN_STR_FLW : BR_MTL_PLN_STR_FLW); + } + + return false; + } + + return !valid_symbols[ERR_REC]; +} + +void *tree_sitter_yaml_external_scanner_create() { + Scanner *scanner = ts_calloc(1, sizeof(Scanner)); + deserialize(scanner, NULL, 0); + return scanner; +} + +void tree_sitter_yaml_external_scanner_destroy(void *payload) { + Scanner *scanner = (Scanner *)payload; + array_delete(&scanner->ind_len_stk); + array_delete(&scanner->ind_typ_stk); + ts_free(scanner); +} + +unsigned tree_sitter_yaml_external_scanner_serialize(void *payload, char *buffer) { + Scanner *scanner = (Scanner *)payload; + return serialize(scanner, buffer); +} + +void tree_sitter_yaml_external_scanner_deserialize(void *payload, const char *buffer, unsigned length) { + Scanner *scanner = (Scanner *)payload; + deserialize(scanner, buffer, length); +} + +bool tree_sitter_yaml_external_scanner_scan(void *payload, TSLexer *lexer, const bool *valid_symbols) { + Scanner *scanner = (Scanner *)payload; + return scan(scanner, lexer, valid_symbols); +} diff --git a/Sources/TreeSitterYAML/schema.core.c b/Sources/TreeSitterYAML/schema.core.c new file mode 100644 index 0000000..ae7812a --- /dev/null +++ b/Sources/TreeSitterYAML/schema.core.c @@ -0,0 +1,204 @@ +#include + +#include + +#define SCH_STT_FRZ -1 + +#define HAS_TIMESTAMP 0 + +typedef enum { + RS_STR, + RS_INT, + RS_NULL, + RS_BOOL, + RS_FLOAT, +} ResultSchema; + +static int8_t adv_sch_stt(int8_t sch_stt, int32_t cur_chr, ResultSchema *rlt_sch) { + switch (sch_stt) { + case SCH_STT_FRZ: + break; + case 0: + if (cur_chr == '.') {*rlt_sch = RS_STR; return 6;} + if (cur_chr == '0') {*rlt_sch = RS_INT; return 37;} + if (cur_chr == 'F') {*rlt_sch = RS_STR; return 2;} + if (cur_chr == 'N') {*rlt_sch = RS_STR; return 16;} + if (cur_chr == 'T') {*rlt_sch = RS_STR; return 13;} + if (cur_chr == 'f') {*rlt_sch = RS_STR; return 17;} + if (cur_chr == 'n') {*rlt_sch = RS_STR; return 29;} + if (cur_chr == 't') {*rlt_sch = RS_STR; return 26;} + if (cur_chr == '~') {*rlt_sch = RS_NULL; return 35;} + if (cur_chr == '+') {*rlt_sch = RS_STR; return 1;} + if (cur_chr == '-') {*rlt_sch = RS_STR; return 1;} + if (('1' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_INT; return 38;} + break; + case 1: + if (cur_chr == '.') {*rlt_sch = RS_STR; return 7;} + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_INT; return 38;} + break; + case 2: + if (cur_chr == 'A') {*rlt_sch = RS_STR; return 9;} + if (cur_chr == 'a') {*rlt_sch = RS_STR; return 22;} + break; + case 3: + if (cur_chr == 'A') {*rlt_sch = RS_STR; return 12;} + if (cur_chr == 'a') {*rlt_sch = RS_STR; return 12;} + break; + case 4: + if (cur_chr == 'E') {*rlt_sch = RS_BOOL; return 36;} + break; + case 5: + if (cur_chr == 'F') {*rlt_sch = RS_FLOAT; return 41;} + break; + case 6: + if (cur_chr == 'I') {*rlt_sch = RS_STR; return 11;} + if (cur_chr == 'N') {*rlt_sch = RS_STR; return 3;} + if (cur_chr == 'i') {*rlt_sch = RS_STR; return 24;} + if (cur_chr == 'n') {*rlt_sch = RS_STR; return 18;} + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_FLOAT; return 42;} + break; + case 7: + if (cur_chr == 'I') {*rlt_sch = RS_STR; return 11;} + if (cur_chr == 'i') {*rlt_sch = RS_STR; return 24;} + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_FLOAT; return 42;} + break; + case 8: + if (cur_chr == 'L') {*rlt_sch = RS_NULL; return 35;} + break; + case 9: + if (cur_chr == 'L') {*rlt_sch = RS_STR; return 14;} + break; + case 10: + if (cur_chr == 'L') {*rlt_sch = RS_STR; return 8;} + break; + case 11: + if (cur_chr == 'N') {*rlt_sch = RS_STR; return 5;} + if (cur_chr == 'n') {*rlt_sch = RS_STR; return 20;} + break; + case 12: + if (cur_chr == 'N') {*rlt_sch = RS_FLOAT; return 41;} + break; + case 13: + if (cur_chr == 'R') {*rlt_sch = RS_STR; return 15;} + if (cur_chr == 'r') {*rlt_sch = RS_STR; return 28;} + break; + case 14: + if (cur_chr == 'S') {*rlt_sch = RS_STR; return 4;} + break; + case 15: + if (cur_chr == 'U') {*rlt_sch = RS_STR; return 4;} + break; + case 16: + if (cur_chr == 'U') {*rlt_sch = RS_STR; return 10;} + if (cur_chr == 'u') {*rlt_sch = RS_STR; return 23;} + break; + case 17: + if (cur_chr == 'a') {*rlt_sch = RS_STR; return 22;} + break; + case 18: + if (cur_chr == 'a') {*rlt_sch = RS_STR; return 25;} + break; + case 19: + if (cur_chr == 'e') {*rlt_sch = RS_BOOL; return 36;} + break; + case 20: + if (cur_chr == 'f') {*rlt_sch = RS_FLOAT; return 41;} + break; + case 21: + if (cur_chr == 'l') {*rlt_sch = RS_NULL; return 35;} + break; + case 22: + if (cur_chr == 'l') {*rlt_sch = RS_STR; return 27;} + break; + case 23: + if (cur_chr == 'l') {*rlt_sch = RS_STR; return 21;} + break; + case 24: + if (cur_chr == 'n') {*rlt_sch = RS_STR; return 20;} + break; + case 25: + if (cur_chr == 'n') {*rlt_sch = RS_FLOAT; return 41;} + break; + case 26: + if (cur_chr == 'r') {*rlt_sch = RS_STR; return 28;} + break; + case 27: + if (cur_chr == 's') {*rlt_sch = RS_STR; return 19;} + break; + case 28: + if (cur_chr == 'u') {*rlt_sch = RS_STR; return 19;} + break; + case 29: + if (cur_chr == 'u') {*rlt_sch = RS_STR; return 23;} + break; + case 30: + if (cur_chr == '+' || + cur_chr == '-') {*rlt_sch = RS_STR; return 32;} + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_FLOAT; return 43;} + break; + case 31: + if (('0' <= cur_chr && cur_chr <= '7')) {*rlt_sch = RS_INT; return 39;} + break; + case 32: + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_FLOAT; return 43;} + break; + case 33: + if (('0' <= cur_chr && cur_chr <= '9') || + ('A' <= cur_chr && cur_chr <= 'F') || + ('a' <= cur_chr && cur_chr <= 'f')) {*rlt_sch = RS_INT; return 40;} + break; + case 34: + abort(); + break; + case 35: + *rlt_sch = RS_NULL; + break; + case 36: + *rlt_sch = RS_BOOL; + break; + case 37: + *rlt_sch = RS_INT; + if (cur_chr == '.') {*rlt_sch = RS_FLOAT; return 42;} + if (cur_chr == 'o') {*rlt_sch = RS_STR; return 31;} + if (cur_chr == 'x') {*rlt_sch = RS_STR; return 33;} + if (cur_chr == 'E' || + cur_chr == 'e') {*rlt_sch = RS_STR; return 30;} + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_INT; return 38;} + break; + case 38: + *rlt_sch = RS_INT; + if (cur_chr == '.') {*rlt_sch = RS_FLOAT; return 42;} + if (cur_chr == 'E' || + cur_chr == 'e') {*rlt_sch = RS_STR; return 30;} + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_INT; return 38;} + break; + case 39: + *rlt_sch = RS_INT; + if (('0' <= cur_chr && cur_chr <= '7')) {*rlt_sch = RS_INT; return 39;} + break; + case 40: + *rlt_sch = RS_INT; + if (('0' <= cur_chr && cur_chr <= '9') || + ('A' <= cur_chr && cur_chr <= 'F') || + ('a' <= cur_chr && cur_chr <= 'f')) {*rlt_sch = RS_INT; return 40;} + break; + case 41: + *rlt_sch = RS_FLOAT; + break; + case 42: + *rlt_sch = RS_FLOAT; + if (cur_chr == 'E' || + cur_chr == 'e') {*rlt_sch = RS_STR; return 30;} + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_FLOAT; return 42;} + break; + case 43: + *rlt_sch = RS_FLOAT; + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_FLOAT; return 43;} + break; + default: + *rlt_sch = RS_STR; + return SCH_STT_FRZ; + } + if (cur_chr != '\r' && cur_chr != '\n' && cur_chr != ' ' && cur_chr != 0) *rlt_sch = RS_STR; + return SCH_STT_FRZ; +} diff --git a/Sources/TreeSitterYAML/tree_sitter/alloc.h b/Sources/TreeSitterYAML/tree_sitter/alloc.h new file mode 100644 index 0000000..1abdd12 --- /dev/null +++ b/Sources/TreeSitterYAML/tree_sitter/alloc.h @@ -0,0 +1,54 @@ +#ifndef TREE_SITTER_ALLOC_H_ +#define TREE_SITTER_ALLOC_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +// Allow clients to override allocation functions +#ifdef TREE_SITTER_REUSE_ALLOCATOR + +extern void *(*ts_current_malloc)(size_t size); +extern void *(*ts_current_calloc)(size_t count, size_t size); +extern void *(*ts_current_realloc)(void *ptr, size_t size); +extern void (*ts_current_free)(void *ptr); + +#ifndef ts_malloc +#define ts_malloc ts_current_malloc +#endif +#ifndef ts_calloc +#define ts_calloc ts_current_calloc +#endif +#ifndef ts_realloc +#define ts_realloc ts_current_realloc +#endif +#ifndef ts_free +#define ts_free ts_current_free +#endif + +#else + +#ifndef ts_malloc +#define ts_malloc malloc +#endif +#ifndef ts_calloc +#define ts_calloc calloc +#endif +#ifndef ts_realloc +#define ts_realloc realloc +#endif +#ifndef ts_free +#define ts_free free +#endif + +#endif + +#ifdef __cplusplus +} +#endif + +#endif // TREE_SITTER_ALLOC_H_ diff --git a/Sources/TreeSitterYAML/tree_sitter/array.h b/Sources/TreeSitterYAML/tree_sitter/array.h new file mode 100644 index 0000000..a17a574 --- /dev/null +++ b/Sources/TreeSitterYAML/tree_sitter/array.h @@ -0,0 +1,291 @@ +#ifndef TREE_SITTER_ARRAY_H_ +#define TREE_SITTER_ARRAY_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "./alloc.h" + +#include +#include +#include +#include +#include + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4101) +#elif defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-variable" +#endif + +#define Array(T) \ + struct { \ + T *contents; \ + uint32_t size; \ + uint32_t capacity; \ + } + +/// Initialize an array. +#define array_init(self) \ + ((self)->size = 0, (self)->capacity = 0, (self)->contents = NULL) + +/// Create an empty array. +#define array_new() \ + { NULL, 0, 0 } + +/// Get a pointer to the element at a given `index` in the array. +#define array_get(self, _index) \ + (assert((uint32_t)(_index) < (self)->size), &(self)->contents[_index]) + +/// Get a pointer to the first element in the array. +#define array_front(self) array_get(self, 0) + +/// Get a pointer to the last element in the array. +#define array_back(self) array_get(self, (self)->size - 1) + +/// Clear the array, setting its size to zero. Note that this does not free any +/// memory allocated for the array's contents. +#define array_clear(self) ((self)->size = 0) + +/// Reserve `new_capacity` elements of space in the array. If `new_capacity` is +/// less than the array's current capacity, this function has no effect. +#define array_reserve(self, new_capacity) \ + _array__reserve((Array *)(self), array_elem_size(self), new_capacity) + +/// Free any memory allocated for this array. Note that this does not free any +/// memory allocated for the array's contents. +#define array_delete(self) _array__delete((Array *)(self)) + +/// Push a new `element` onto the end of the array. +#define array_push(self, element) \ + (_array__grow((Array *)(self), 1, array_elem_size(self)), \ + (self)->contents[(self)->size++] = (element)) + +/// Increase the array's size by `count` elements. +/// New elements are zero-initialized. +#define array_grow_by(self, count) \ + do { \ + if ((count) == 0) break; \ + _array__grow((Array *)(self), count, array_elem_size(self)); \ + memset((self)->contents + (self)->size, 0, (count) * array_elem_size(self)); \ + (self)->size += (count); \ + } while (0) + +/// Append all elements from one array to the end of another. +#define array_push_all(self, other) \ + array_extend((self), (other)->size, (other)->contents) + +/// Append `count` elements to the end of the array, reading their values from the +/// `contents` pointer. +#define array_extend(self, count, contents) \ + _array__splice( \ + (Array *)(self), array_elem_size(self), (self)->size, \ + 0, count, contents \ + ) + +/// Remove `old_count` elements from the array starting at the given `index`. At +/// the same index, insert `new_count` new elements, reading their values from the +/// `new_contents` pointer. +#define array_splice(self, _index, old_count, new_count, new_contents) \ + _array__splice( \ + (Array *)(self), array_elem_size(self), _index, \ + old_count, new_count, new_contents \ + ) + +/// Insert one `element` into the array at the given `index`. +#define array_insert(self, _index, element) \ + _array__splice((Array *)(self), array_elem_size(self), _index, 0, 1, &(element)) + +/// Remove one element from the array at the given `index`. +#define array_erase(self, _index) \ + _array__erase((Array *)(self), array_elem_size(self), _index) + +/// Pop the last element off the array, returning the element by value. +#define array_pop(self) ((self)->contents[--(self)->size]) + +/// Assign the contents of one array to another, reallocating if necessary. +#define array_assign(self, other) \ + _array__assign((Array *)(self), (const Array *)(other), array_elem_size(self)) + +/// Swap one array with another +#define array_swap(self, other) \ + _array__swap((Array *)(self), (Array *)(other)) + +/// Get the size of the array contents +#define array_elem_size(self) (sizeof *(self)->contents) + +/// Search a sorted array for a given `needle` value, using the given `compare` +/// callback to determine the order. +/// +/// If an existing element is found to be equal to `needle`, then the `index` +/// out-parameter is set to the existing value's index, and the `exists` +/// out-parameter is set to true. Otherwise, `index` is set to an index where +/// `needle` should be inserted in order to preserve the sorting, and `exists` +/// is set to false. +#define array_search_sorted_with(self, compare, needle, _index, _exists) \ + _array__search_sorted(self, 0, compare, , needle, _index, _exists) + +/// Search a sorted array for a given `needle` value, using integer comparisons +/// of a given struct field (specified with a leading dot) to determine the order. +/// +/// See also `array_search_sorted_with`. +#define array_search_sorted_by(self, field, needle, _index, _exists) \ + _array__search_sorted(self, 0, _compare_int, field, needle, _index, _exists) + +/// Insert a given `value` into a sorted array, using the given `compare` +/// callback to determine the order. +#define array_insert_sorted_with(self, compare, value) \ + do { \ + unsigned _index, _exists; \ + array_search_sorted_with(self, compare, &(value), &_index, &_exists); \ + if (!_exists) array_insert(self, _index, value); \ + } while (0) + +/// Insert a given `value` into a sorted array, using integer comparisons of +/// a given struct field (specified with a leading dot) to determine the order. +/// +/// See also `array_search_sorted_by`. +#define array_insert_sorted_by(self, field, value) \ + do { \ + unsigned _index, _exists; \ + array_search_sorted_by(self, field, (value) field, &_index, &_exists); \ + if (!_exists) array_insert(self, _index, value); \ + } while (0) + +// Private + +typedef Array(void) Array; + +/// This is not what you're looking for, see `array_delete`. +static inline void _array__delete(Array *self) { + if (self->contents) { + ts_free(self->contents); + self->contents = NULL; + self->size = 0; + self->capacity = 0; + } +} + +/// This is not what you're looking for, see `array_erase`. +static inline void _array__erase(Array *self, size_t element_size, + uint32_t index) { + assert(index < self->size); + char *contents = (char *)self->contents; + memmove(contents + index * element_size, contents + (index + 1) * element_size, + (self->size - index - 1) * element_size); + self->size--; +} + +/// This is not what you're looking for, see `array_reserve`. +static inline void _array__reserve(Array *self, size_t element_size, uint32_t new_capacity) { + if (new_capacity > self->capacity) { + if (self->contents) { + self->contents = ts_realloc(self->contents, new_capacity * element_size); + } else { + self->contents = ts_malloc(new_capacity * element_size); + } + self->capacity = new_capacity; + } +} + +/// This is not what you're looking for, see `array_assign`. +static inline void _array__assign(Array *self, const Array *other, size_t element_size) { + _array__reserve(self, element_size, other->size); + self->size = other->size; + memcpy(self->contents, other->contents, self->size * element_size); +} + +/// This is not what you're looking for, see `array_swap`. +static inline void _array__swap(Array *self, Array *other) { + Array swap = *other; + *other = *self; + *self = swap; +} + +/// This is not what you're looking for, see `array_push` or `array_grow_by`. +static inline void _array__grow(Array *self, uint32_t count, size_t element_size) { + uint32_t new_size = self->size + count; + if (new_size > self->capacity) { + uint32_t new_capacity = self->capacity * 2; + if (new_capacity < 8) new_capacity = 8; + if (new_capacity < new_size) new_capacity = new_size; + _array__reserve(self, element_size, new_capacity); + } +} + +/// This is not what you're looking for, see `array_splice`. +static inline void _array__splice(Array *self, size_t element_size, + uint32_t index, uint32_t old_count, + uint32_t new_count, const void *elements) { + uint32_t new_size = self->size + new_count - old_count; + uint32_t old_end = index + old_count; + uint32_t new_end = index + new_count; + assert(old_end <= self->size); + + _array__reserve(self, element_size, new_size); + + char *contents = (char *)self->contents; + if (self->size > old_end) { + memmove( + contents + new_end * element_size, + contents + old_end * element_size, + (self->size - old_end) * element_size + ); + } + if (new_count > 0) { + if (elements) { + memcpy( + (contents + index * element_size), + elements, + new_count * element_size + ); + } else { + memset( + (contents + index * element_size), + 0, + new_count * element_size + ); + } + } + self->size += new_count - old_count; +} + +/// A binary search routine, based on Rust's `std::slice::binary_search_by`. +/// This is not what you're looking for, see `array_search_sorted_with` or `array_search_sorted_by`. +#define _array__search_sorted(self, start, compare, suffix, needle, _index, _exists) \ + do { \ + *(_index) = start; \ + *(_exists) = false; \ + uint32_t size = (self)->size - *(_index); \ + if (size == 0) break; \ + int comparison; \ + while (size > 1) { \ + uint32_t half_size = size / 2; \ + uint32_t mid_index = *(_index) + half_size; \ + comparison = compare(&((self)->contents[mid_index] suffix), (needle)); \ + if (comparison <= 0) *(_index) = mid_index; \ + size -= half_size; \ + } \ + comparison = compare(&((self)->contents[*(_index)] suffix), (needle)); \ + if (comparison == 0) *(_exists) = true; \ + else if (comparison < 0) *(_index) += 1; \ + } while (0) + +/// Helper macro for the `_sorted_by` routines below. This takes the left (existing) +/// parameter by reference in order to work with the generic sorting function above. +#define _compare_int(a, b) ((int)*(a) - (int)(b)) + +#ifdef _MSC_VER +#pragma warning(pop) +#elif defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#ifdef __cplusplus +} +#endif + +#endif // TREE_SITTER_ARRAY_H_ diff --git a/Sources/TreeSitterYAML/tree_sitter/parser.h b/Sources/TreeSitterYAML/tree_sitter/parser.h new file mode 100644 index 0000000..858107d --- /dev/null +++ b/Sources/TreeSitterYAML/tree_sitter/parser.h @@ -0,0 +1,286 @@ +#ifndef TREE_SITTER_PARSER_H_ +#define TREE_SITTER_PARSER_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +#define ts_builtin_sym_error ((TSSymbol)-1) +#define ts_builtin_sym_end 0 +#define TREE_SITTER_SERIALIZATION_BUFFER_SIZE 1024 + +#ifndef TREE_SITTER_API_H_ +typedef uint16_t TSStateId; +typedef uint16_t TSSymbol; +typedef uint16_t TSFieldId; +typedef struct TSLanguage TSLanguage; +typedef struct TSLanguageMetadata { + uint8_t major_version; + uint8_t minor_version; + uint8_t patch_version; +} TSLanguageMetadata; +#endif + +typedef struct { + TSFieldId field_id; + uint8_t child_index; + bool inherited; +} TSFieldMapEntry; + +// Used to index the field and supertype maps. +typedef struct { + uint16_t index; + uint16_t length; +} TSMapSlice; + +typedef struct { + bool visible; + bool named; + bool supertype; +} TSSymbolMetadata; + +typedef struct TSLexer TSLexer; + +struct TSLexer { + int32_t lookahead; + TSSymbol result_symbol; + void (*advance)(TSLexer *, bool); + void (*mark_end)(TSLexer *); + uint32_t (*get_column)(TSLexer *); + bool (*is_at_included_range_start)(const TSLexer *); + bool (*eof)(const TSLexer *); + void (*log)(const TSLexer *, const char *, ...); +}; + +typedef enum { + TSParseActionTypeShift, + TSParseActionTypeReduce, + TSParseActionTypeAccept, + TSParseActionTypeRecover, +} TSParseActionType; + +typedef union { + struct { + uint8_t type; + TSStateId state; + bool extra; + bool repetition; + } shift; + struct { + uint8_t type; + uint8_t child_count; + TSSymbol symbol; + int16_t dynamic_precedence; + uint16_t production_id; + } reduce; + uint8_t type; +} TSParseAction; + +typedef struct { + uint16_t lex_state; + uint16_t external_lex_state; +} TSLexMode; + +typedef struct { + uint16_t lex_state; + uint16_t external_lex_state; + uint16_t reserved_word_set_id; +} TSLexerMode; + +typedef union { + TSParseAction action; + struct { + uint8_t count; + bool reusable; + } entry; +} TSParseActionEntry; + +typedef struct { + int32_t start; + int32_t end; +} TSCharacterRange; + +struct TSLanguage { + uint32_t abi_version; + uint32_t symbol_count; + uint32_t alias_count; + uint32_t token_count; + uint32_t external_token_count; + uint32_t state_count; + uint32_t large_state_count; + uint32_t production_id_count; + uint32_t field_count; + uint16_t max_alias_sequence_length; + const uint16_t *parse_table; + const uint16_t *small_parse_table; + const uint32_t *small_parse_table_map; + const TSParseActionEntry *parse_actions; + const char * const *symbol_names; + const char * const *field_names; + const TSMapSlice *field_map_slices; + const TSFieldMapEntry *field_map_entries; + const TSSymbolMetadata *symbol_metadata; + const TSSymbol *public_symbol_map; + const uint16_t *alias_map; + const TSSymbol *alias_sequences; + const TSLexerMode *lex_modes; + bool (*lex_fn)(TSLexer *, TSStateId); + bool (*keyword_lex_fn)(TSLexer *, TSStateId); + TSSymbol keyword_capture_token; + struct { + const bool *states; + const TSSymbol *symbol_map; + void *(*create)(void); + void (*destroy)(void *); + bool (*scan)(void *, TSLexer *, const bool *symbol_whitelist); + unsigned (*serialize)(void *, char *); + void (*deserialize)(void *, const char *, unsigned); + } external_scanner; + const TSStateId *primary_state_ids; + const char *name; + const TSSymbol *reserved_words; + uint16_t max_reserved_word_set_size; + uint32_t supertype_count; + const TSSymbol *supertype_symbols; + const TSMapSlice *supertype_map_slices; + const TSSymbol *supertype_map_entries; + TSLanguageMetadata metadata; +}; + +static inline bool set_contains(const TSCharacterRange *ranges, uint32_t len, int32_t lookahead) { + uint32_t index = 0; + uint32_t size = len - index; + while (size > 1) { + uint32_t half_size = size / 2; + uint32_t mid_index = index + half_size; + const TSCharacterRange *range = &ranges[mid_index]; + if (lookahead >= range->start && lookahead <= range->end) { + return true; + } else if (lookahead > range->end) { + index = mid_index; + } + size -= half_size; + } + const TSCharacterRange *range = &ranges[index]; + return (lookahead >= range->start && lookahead <= range->end); +} + +/* + * Lexer Macros + */ + +#ifdef _MSC_VER +#define UNUSED __pragma(warning(suppress : 4101)) +#else +#define UNUSED __attribute__((unused)) +#endif + +#define START_LEXER() \ + bool result = false; \ + bool skip = false; \ + UNUSED \ + bool eof = false; \ + int32_t lookahead; \ + goto start; \ + next_state: \ + lexer->advance(lexer, skip); \ + start: \ + skip = false; \ + lookahead = lexer->lookahead; + +#define ADVANCE(state_value) \ + { \ + state = state_value; \ + goto next_state; \ + } + +#define ADVANCE_MAP(...) \ + { \ + static const uint16_t map[] = { __VA_ARGS__ }; \ + for (uint32_t i = 0; i < sizeof(map) / sizeof(map[0]); i += 2) { \ + if (map[i] == lookahead) { \ + state = map[i + 1]; \ + goto next_state; \ + } \ + } \ + } + +#define SKIP(state_value) \ + { \ + skip = true; \ + state = state_value; \ + goto next_state; \ + } + +#define ACCEPT_TOKEN(symbol_value) \ + result = true; \ + lexer->result_symbol = symbol_value; \ + lexer->mark_end(lexer); + +#define END_STATE() return result; + +/* + * Parse Table Macros + */ + +#define SMALL_STATE(id) ((id) - LARGE_STATE_COUNT) + +#define STATE(id) id + +#define ACTIONS(id) id + +#define SHIFT(state_value) \ + {{ \ + .shift = { \ + .type = TSParseActionTypeShift, \ + .state = (state_value) \ + } \ + }} + +#define SHIFT_REPEAT(state_value) \ + {{ \ + .shift = { \ + .type = TSParseActionTypeShift, \ + .state = (state_value), \ + .repetition = true \ + } \ + }} + +#define SHIFT_EXTRA() \ + {{ \ + .shift = { \ + .type = TSParseActionTypeShift, \ + .extra = true \ + } \ + }} + +#define REDUCE(symbol_name, children, precedence, prod_id) \ + {{ \ + .reduce = { \ + .type = TSParseActionTypeReduce, \ + .symbol = symbol_name, \ + .child_count = children, \ + .dynamic_precedence = precedence, \ + .production_id = prod_id \ + }, \ + }} + +#define RECOVER() \ + {{ \ + .type = TSParseActionTypeRecover \ + }} + +#define ACCEPT_INPUT() \ + {{ \ + .type = TSParseActionTypeAccept \ + }} + +#ifdef __cplusplus +} +#endif + +#endif // TREE_SITTER_PARSER_H_ diff --git a/Tests/AgentsCoreTests/DeclarationStateTests.swift b/Tests/AgentsCoreTests/DeclarationStateTests.swift index 7e31629..ef84fc1 100644 --- a/Tests/AgentsCoreTests/DeclarationStateTests.swift +++ b/Tests/AgentsCoreTests/DeclarationStateTests.swift @@ -77,7 +77,7 @@ struct DeclarationStateTests { #expect(try store.loadWatch() == WatchState()) #expect(try FileHash.folderHash(fixture.root) == before) - let bytes = manifestText("defaultAgents: [.cursor]") + let bytes = manifestText("defaultAgents: [\"cursor\"]\n") try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) try bytes.write(to: store.declarationURL) let declared = try FileHash.folderHash(fixture.root) @@ -94,13 +94,9 @@ struct DeclarationStateTests { try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) let bytes = manifestText( """ - sources: [.source(name: "remote", url: "https://does-not-exist.invalid/repo.git")], - components: [ - .mcpServer(name: "tools", transport: .stdio("program-does-not-exist")), - .hook(name: "hook", event: .sessionStart, run: .executable("program-does-not-exist")), - .subagent(name: "agent", description: "d", prompt: .file("missing.md", source: "remote")), - ], - groups: [.group(name: "unused", components: [.ignore(name: "i", patterns: [], condition: .when(agents: []))])] + sources: {"remote": {"url": "https://does-not-exist.invalid/repo.git"}} + components: [{"kind": "mcpServer", "name": "tools", "transport": {"kind": "stdio", "executable": "program-does-not-exist"}}, {"kind": "hook", "name": "hook", "event": "sessionStart", "run": {"executable": "program-does-not-exist"}}, {"kind": "subagent", "name": "agent", "description": "d", "prompt": {"file": {"path": "missing.md", "source": "remote"}}}] + groups: {"unused": {"components": [{"kind": "ignore", "name": "i", "patterns": [], "condition": {"agents": []}}]}} """) try bytes.write(to: store.declarationURL) let before = try FileHash.folderHash(fixture.root) @@ -200,7 +196,7 @@ struct DeclarationStateTests { try fixture.mirrorGit(["update-ref", "refs/agents-watch/" + stale, stale]) let marker = fixture.store.directory.appendingPathComponent("watch-refs.pending") try Data().write(to: marker) - let unreadable = Data("let agents = \n".utf8) + let unreadable = Data("version: [\n".utf8) try unreadable.write(to: fixture.store.declarationURL) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { @@ -215,11 +211,11 @@ struct DeclarationStateTests { @Test func stateTransactionsAcceptOnlyTheCurrentStateFiles() throws { let fixture = try ScopeFixture() let paths = TransactionPaths(store: fixture.store) - #expect(try paths.path(for: fixture.store.declarationURL) == "state/Agents.swift") - for name in ["Agents.swift", "agents.resolved", "agents.watch"] { + #expect(try paths.path(for: fixture.store.declarationURL) == "state/agents.yaml") + for name in ["agents.yaml", "agents.resolved", "agents.watch"] { #expect(try paths.components("state/" + name).descendants == [name]) } - for name in ["other.json", "agents.swift", "Agents.swift.new"] { + for name in ["other.json", "agents.swift", "agents.yaml.new"] { #expect(throws: CoreError.unsafePath("unmanaged state transaction path")) { try paths.components("state/" + name) } diff --git a/Tests/AgentsCoreTests/InstructionTransactionTests.swift b/Tests/AgentsCoreTests/InstructionTransactionTests.swift index e901cb4..09b5787 100644 --- a/Tests/AgentsCoreTests/InstructionTransactionTests.swift +++ b/Tests/AgentsCoreTests/InstructionTransactionTests.swift @@ -38,7 +38,7 @@ struct InstructionTransactionTests { try transaction.replace(file.resolvingSymlinksInPath(), with: .data(Data("new".utf8))) } try transaction.replace( - store.declarationURL, with: .data(manifestText("defaultAgents: [.codex]"))) + store.declarationURL, with: .data(manifestText("defaultAgents: [\"codex\"]\n"))) #expect(throws: Interrupted.self) { try transaction.commit() } } for file in files { #expect(try Data(contentsOf: file) == Data("original".utf8)) } diff --git a/Tests/AgentsCoreTests/PublicationTests.swift b/Tests/AgentsCoreTests/PublicationTests.swift index d732144..1f8ad56 100644 --- a/Tests/AgentsCoreTests/PublicationTests.swift +++ b/Tests/AgentsCoreTests/PublicationTests.swift @@ -390,7 +390,7 @@ struct PublicationTests { let directory = try #require(try fixture.store.openDirectoryIfPresent()) let backup = directory.url.appendingPathComponent(".agents-\(id.uuidString)-0.old") try FileManager.default.moveItem(at: fixture.store.declarationURL, to: backup) - try manifestText("defaultAgents: [.codex]").write(to: fixture.store.declarationURL) + try manifestText("defaultAgents: [\"codex\"]\n").write(to: fixture.store.declarationURL) var old = try StateStore.encode( LegacyJournal( id: id, scope: directory.identity, diff --git a/Tests/AgentsCoreTests/StateTransactionTests.swift b/Tests/AgentsCoreTests/StateTransactionTests.swift index 826f9b4..78b59ed 100644 --- a/Tests/AgentsCoreTests/StateTransactionTests.swift +++ b/Tests/AgentsCoreTests/StateTransactionTests.swift @@ -150,7 +150,7 @@ final class TransactionFixture { root.appendingPathComponent(".agents/skills/target"), with: .copy(root.appendingPathComponent("new"))) try transaction.replace( - store.declarationURL, with: .data(manifestText("defaultAgents: [.codex]"))) + store.declarationURL, with: .data(manifestText("defaultAgents: [\"codex\"]\n"))) try transaction.replace( store.resolvedURL, with: .data( @@ -363,7 +363,7 @@ extension StateTransactionTests { try Data("keep".utf8).write(to: victim.appendingPathComponent("sentinel")) let maliciousPaths = [ victim.path, "file://" + victim.path, "state/../../Documents/victim", "state/cache/../victim", - "state/Agents.swift/child", "codex/../victim", "codex/other/child", "unknown/victim", + "state/agents.yaml/child", "codex/../victim", "codex/other/child", "unknown/victim", "state/cache/artifact-content/../../victim", ] for path in maliciousPaths { @@ -616,7 +616,7 @@ extension StateTransactionTests { try transaction.replace(target, with: .copy(fixture.root.appendingPathComponent("new"))) } try transaction.replace( - store.declarationURL, with: .data(manifestText("defaultAgents: [.codex]"))) + store.declarationURL, with: .data(manifestText("defaultAgents: [\"codex\"]\n"))) try transaction.replace( store.resolvedURL, with: .data( diff --git a/Tests/AgentsCoreTests/TransactionCostTests.swift b/Tests/AgentsCoreTests/TransactionCostTests.swift index 93b3768..e256862 100644 --- a/Tests/AgentsCoreTests/TransactionCostTests.swift +++ b/Tests/AgentsCoreTests/TransactionCostTests.swift @@ -56,7 +56,7 @@ struct TransactionCostTests { try transaction.replace( root.appendingPathComponent("AGENTS.md"), with: .data(Data("after".utf8))) try transaction.replace( - store.declarationURL, with: .data(manifestText("defaultAgents: [.codex]"))) + store.declarationURL, with: .data(manifestText("defaultAgents: [\"codex\"]\n"))) try transaction.commit() } #expect(steps.contains(TransactionCheckpoint.containerCreated(1).name)) diff --git a/Tests/AgentsCoreTests/WatchStateTests.swift b/Tests/AgentsCoreTests/WatchStateTests.swift index d8ff0b1..b618224 100644 --- a/Tests/AgentsCoreTests/WatchStateTests.swift +++ b/Tests/AgentsCoreTests/WatchStateTests.swift @@ -18,15 +18,9 @@ struct WatchStateTests { )) try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) let text = """ - // agents-tools-version: 1.0 - import AgentsDescription - - // Preserve this layout. - let agents = Agents(sources: [ - .source(name: "web", url: "https://example.test/repo.git"), - .source(name: "git", path: "missing"), - ], watch: ["web", "git"]) - + version: 1 + sources: {"web": {"url": "https://example.test/repo.git"}, "git": {"path": "missing"}} + watch: ["web", "git"] """ let bytes = Data(text.utf8) try bytes.write(to: store.declarationURL) diff --git a/Tests/AgentsInstructionsTests/DeclarationDocumentTests.swift b/Tests/AgentsInstructionsTests/DeclarationDocumentTests.swift index 802b97a..baa3bf9 100644 --- a/Tests/AgentsInstructionsTests/DeclarationDocumentTests.swift +++ b/Tests/AgentsInstructionsTests/DeclarationDocumentTests.swift @@ -4,7 +4,7 @@ import AgentsManifest import Foundation import Testing -/// Instruction writes through the scope's `Agents.swift` declaration document. +/// Instruction writes through the scope's `agents.yaml` declaration document. @Suite("Instruction declaration documents") struct DeclarationDocumentTests { @Test func instructionEditsKeepCommentsAndUntouchedBytes() throws { @@ -13,18 +13,15 @@ struct DeclarationDocumentTests { try fixture.own("style") let declaration = fixture.store().declarationURL let header = """ - // agents-tools-version: 1.0 - import AgentsDescription - - // Project instructions. - let agents = Agents( - components: [ - // Shared guidance first. + # Project instructions. + version: 1 + components: + # Shared guidance first. """ - let closing = " ]\n)\n" + let closing = "\n" try fixture.write( - header + " .instructions(sections: [\"guide\"], agents: [.codex]),\n" + closing, + header + " - {kind: instructions, sections: [{name: guide}], agents: [codex]}" + closing, to: declaration) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) func text() throws -> String { @@ -40,7 +37,8 @@ struct DeclarationDocumentTests { agents: [.claudeCode, .codex], environment: fixture.environment, apply: true) #expect( try text() - == header + " .instructions(sections: [\"style\"], agents: [.claudeCode, .codex]),\n" + == header + + " - {kind: instructions, sections: [{\"name\": \"style\"}], agents: [\"claude-code\", codex]}" + closing) #expect(try fixture.store().loadResolved().instructions.sections.map(\.name) == ["style"]) } @@ -52,7 +50,7 @@ struct DeclarationDocumentTests { try fixture.own("guide") let store = fixture.store() let external = Data( - "// agents-tools-version: 1.0\nimport AgentsDescription\n\nlet agents = Agents()\n".utf8) + "version: 1\n".utf8) #expect(throws: CoreError.self) { try InstructionOperations.add( InstructionAddOptions(source: ".", names: ["guide"], environment: fixture.environment), @@ -65,22 +63,17 @@ struct DeclarationDocumentTests { atPath: fixture.project.appendingPathComponent("AGENTS.md").path)) } - /// Sections held in a constant have no direct source range, so the add stops before the - /// callback and any write. - @Test func readOnlySectionsStopBeforeTheCallback() throws { + /// Unsupported shared aliases fail before the callback and any write. + @Test func unsupportedSectionsStopBeforeTheCallback() throws { let fixture = try InstructionFixture() try fixture.own("guide") try fixture.own("style") + _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) try fixture.write( """ - // agents-tools-version: 1.0 - import AgentsDescription - - let shared: [SectionReference] = ["guide"] - let agents = Agents(components: [.instructions(sections: shared, agents: [.codex])]) - + version: 1 + components: [{kind: instructions, sections: &shared [{name: guide}], agents: [codex]}] """, to: fixture.store().declarationURL) - _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) let before = try fixture.snapshot() var called = false #expect { @@ -88,7 +81,7 @@ struct DeclarationDocumentTests { InstructionAddOptions(source: ".", names: ["style"], environment: fixture.environment), beforeApply: { _ in called = true }) } throws: { error in - (error as? ManifestFailure)?.diagnostics.first?.code == "manifest.edit.readOnly" + (error as? ManifestFailure)?.diagnostics.first?.code == "manifest.unsupported" } #expect(!called) #expect(try fixture.snapshot() == before) diff --git a/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift b/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift index 5df67c7..636c370 100644 --- a/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift +++ b/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift @@ -158,13 +158,8 @@ struct OwnershipAndPlacementTests { try fixture.own("guide") try fixture.write( """ - // agents-tools-version: 1.0 - import AgentsDescription - - let agents = Agents( - components: [.instructions(chatGPT: [.prompt(name: "weekly", sections: ["guide"])])] - ) - + version: 1 + components: [{"kind": "instructions", "chatgpt": {"weekly": {"sections": [{"name": "guide"}]}}}] """, to: fixture.store().declarationURL) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) #expect( diff --git a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift index a31ca24..caa60f2 100644 --- a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift @@ -67,18 +67,8 @@ struct TargetLifecycleTests { let lockFile = fixture.store().resolvedURL #expect( String(decoding: try Data(contentsOf: declarationFile), as: UTF8.self) == """ - // agents-tools-version: 1.0 - import AgentsDescription - - let agents = Agents( - components: [ - .instructions( - sections: ["guide"], - agents: [.codex] - ), - ] - ) - + version: 1 + components: [{"kind": "instructions", "sections": [{"name": "guide"}], "agents": ["codex"]}] """) let lockText = String(decoding: try Data(contentsOf: lockFile), as: UTF8.self) #expect(lockText.contains("\"chatgpt\": {}") && lockText.contains("\"skills\": {}")) @@ -86,12 +76,8 @@ struct TargetLifecycleTests { // The same intent in another layout, with a comment, is not rewritten. let declaration = Data( """ - // agents-tools-version: 1.0 - import AgentsDescription - - // Project instructions. - let agents = Agents(components: [.instructions(sections: ["guide"], agents: [.codex])]) - + version: 1 + components: [{"kind": "instructions", "sections": [{"name": "guide"}], "agents": ["codex"]}] """.utf8) try declaration.write(to: declarationFile) let existingLockBytes = try StateStore.encode(fixture.store().loadResolved()) diff --git a/Tests/AgentsManifestTests/AdversarialTests.swift b/Tests/AgentsManifestTests/AdversarialTests.swift deleted file mode 100644 index bfe7482..0000000 --- a/Tests/AgentsManifestTests/AdversarialTests.swift +++ /dev/null @@ -1,321 +0,0 @@ -import AgentsCore -import Foundation -import ManifestTestSupport -import SwiftSyntax -import Testing - -@testable import AgentsManifest - -struct AdmissionCase { - let name: String - let bytes: [UInt8] - let expected: String? - init(_ name: String, _ expression: String, expected: String? = nil, complete: Bool = false) { - self.name = name - bytes = Array((complete ? expression : manifestHeader + "let value = " + expression).utf8) - self.expected = expected - } - init(_ name: String, bytes: [UInt8], expected: String?) { - self.name = name - self.bytes = bytes - self.expected = expected - } -} - -func fixedAdmissionCases() -> [AdmissionCase] { - var cases: [AdmissionCase] = [] - for depth in [7, 8, 9, 20, 200, 20_000] { - for (name, left, right) in [ - ("squares", "[", "]"), ("mixed", "f([", "])"), ("dictionaries", "[\"k\":", "]"), - ("calls", ".f(", ")"), ("parentheses", "(", ")"), - ] { - cases.append( - AdmissionCase( - "\(name)-\(depth)", - String(repeating: left, count: depth) + "0" + String(repeating: right, count: depth), - expected: name == "squares" && depth <= 8 || name == "dictionaries" && depth <= 8 - || name == "mixed" && depth <= 8 - || name == "parentheses" && depth <= 20 || name == "calls" && depth <= 20 - ? "accepted" : nil)) - cases.append( - AdmissionCase( - "\(name)-unbalanced-\(depth)", String(repeating: left, count: depth) + "0", expected: nil) - ) - } - } - for (name, expression) in [ - ( - "brace-nests", - String(repeating: "{", count: 20_000) + "0" + String(repeating: "}", count: 20_000) - ), - ("generic-small", "let value: A = 0"), - ( - "generic-large", - "let value: " + String(repeating: "A<", count: 20_000) + "B" - + String(repeating: ">", count: 20_000) + " = 0" - ), - ("ambiguous-angle", String(repeating: "a<", count: 200_000) + "b"), - ("members", "a" + String(repeating: ".b", count: 200_000)), - ("numeric-prefix", String(repeating: "-", count: 200_000) + "1"), - ("force-unwrap", "a" + String(repeating: "!", count: 200_000)), - ("postfix-calls", "a" + String(repeating: "()", count: 200_000)), - ("subscripts", "a" + String(repeating: "[0]", count: 200_000)), - ("plus-chain", "1" + String(repeating: " + 1", count: 200_000)), - ] { cases.append(AdmissionCase(name, expression, expected: nil)) } - for word in ["copy", "await", "consume", "each", "unsafe"] { - for count in [2, 200_000] { - cases.append( - AdmissionCase( - "prefix-\(word)-\(count)", String(repeating: word + " ", count: count) + "x", - expected: count == 2 ? "manifest.syntax" : nil)) - } - cases.append(AdmissionCase("label-\(word)", "f(\(word): 0)", expected: "accepted")) - cases.append(AdmissionCase("member-\(word)", ".\(word)", expected: "accepted")) - cases.append( - AdmissionCase( - "binding-\(word)", manifestHeader + "let \(word) = 0", expected: "manifest.syntax", - complete: true)) - } - for body in [ - "#\"\"\"#\nlet danger: A> = 0\n// \"\"\"#", "#\"raw\"#", "##\"\"\"\ntext\n\"\"\"##", - ] { cases.append(AdmissionCase("raw-\(cases.count)", body, expected: "manifest.syntax")) } - for bad in [ - "x y", "f(x y)", "`x`", "é", "$x", "1.0", "0x1", "1e2", "- 1", "--1", "+1", "a+b", "a +b", - "a+ b", "f(0,)", "(0,)", "[key: 0]", "a[0]", "(a).b", "a.b.c", "a()()", "a.b().c()", - "a /* x */ .b", "\"\\q\"", "\"\\u{D800}\"", "\"\\u{110000}\"", "\"\\u{}\"", "\"\\(x)\"", - "/*unterminated", "\"unterminated", - ] { cases.append(AdmissionCase("forbidden-\(cases.count)", bad, expected: "manifest.syntax")) } - for value in [ - "\"\\0\\t\\n\\r\\\"\\'\\\\\"", "\"\\u{0}\\u{1F600}\"", "\"é😀\"", "-1_000", "1_", - "\"\\\\(literal)\"", "/* nested /* comment */ */ 0", - String(repeating: "/*", count: 20) + "x" + String(repeating: "*/", count: 20) + " 0", - ] { cases.append(AdmissionCase("literal-\(cases.count)", value, expected: "accepted")) } - cases.append( - AdmissionCase( - "comments-21", - String(repeating: "/*", count: 21) + "x" + String(repeating: "*/", count: 21) + "0", - expected: "manifest.limit")) - for newline in ["\n", "\r\n", "\r"] { - for (content, closing, good) in [ - ("", " ", true), (" ", " ", false), (" ", " ", true), (" ", " ", true), - ("\t", " ", false), (" \ttext", " ", false), (" text\ttail", " ", true), - (" text", " ", true), ("", "\t", false), - ] { - cases.append( - AdmissionCase( - "indent-\(cases.count)", "\"\"\"" + newline + content + newline + closing + "\"\"\"", - expected: good ? "accepted" : "manifest.syntax")) - } - } - let gaps = ["", " ", "\t", "\n", "\r\n"] - for left in gaps { - for right in gaps { - cases.append( - AdmissionCase( - "assignment-\(cases.count)", manifestHeader + "let value" + left + "=" + right + "-1", - expected: !left.isEmpty && !right.isEmpty ? "accepted" : "manifest.syntax", complete: true - )) - cases.append( - AdmissionCase( - "plus-spacing-\(cases.count)", "[]" + left + "+" + right + "[]", - expected: !left.isEmpty && !right.isEmpty ? "accepted" : "manifest.syntax")) - cases.append( - AdmissionCase( - "range-spacing-\(cases.count)", - ".source(name: \"s\", path: \"s\", \"1.2.0\"" + left + "..<" + right + "\"2.0.0\")", - expected: left.isEmpty == right.isEmpty ? "accepted" : "manifest.syntax")) - } - } - for op in ["=", "+", "..<"] { - for (left, right, good) in [ - (" /*a*/ ", " /*b*/ ", true), ("/*a*/ ", " ", false), (" /*a*/", " ", false), - (" ", "/*a*/ ", false), (" /*a*//*b*/ ", " ", false), (" /*a*/ /*b*/ ", " ", true), - (" //a\n", " ", true), - ] { - let expression = - op == "=" - ? manifestHeader + "let value" + left + op + right + "0" - : op == "+" - ? "[]" + left + op + right + "[]" - : ".source(name: \"s\", path: \"s\", \"1.2.0\"" + left + op + right + "\"2.0.0\")" - cases.append( - AdmissionCase( - "operator-comments-\(op)-\(cases.count)", expression, - expected: good ? "accepted" : "manifest.syntax", complete: op == "=")) - } - } - for body in ["-1", "(-1)", "[-1]", "[0,-1]", "[\"k\":-1]", "f(-1)", "f(label:-1)", "/*c*/ -1"] { - cases.append(AdmissionCase("negative-good-\(cases.count)", body, expected: "accepted")) - } - for body in ["a-1", "1-1", ")-1", "]-1", ".-1", "--1", "+-1", "/*c*/-1", "-\n1"] { - cases.append(AdmissionCase("negative-bad-\(cases.count)", body, expected: "manifest.syntax")) - } - for range in [ - "\"1.2.0\"...\"2.0.0\"", "\"1.2.0\"..<\"2.0.0\"..<\"3.0.0\"", "lower..<\"2.0.0\"", - "\"1.2.0\".. [CompiledManifestFixture] { - [ - compiledConsumerExample(), - compiledCoreExample(), - compiledDumpSymbolic(), - compiledExportedGroup(), - compiledInstructionRecipients(), - compiledLiteralCoverage(), - compiledPrintedEmpty(), - compiledPrintedEscapes(), - compiledPrintedExplicitEmpty(), - compiledPrintedFields(), - compiledPrintedRanges(), - compiledPrintedWidth(), - compiledProducerExample(), - compiledRecipientConditions(), - compiledRequirementValues(), - compiledRequirementsExample(), - compiledSectionConcatenation(), - compiledSharedRules(), - compiledSketchExample(), - compiledSkillsExample(), - compiledTeamConfiguration(), - compiledVersionCollections(), - compiledVocabularyDepthExample(), - ] -} - -private func compiledConsumerExample() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let base: [SectionReference] = ["guide"] - let sections = base + [.section(name: "engineering", source: "rules")] - let reviewer: Component = .subagent( - name: "reviewer", - description: "Review correctness and tests.", - prompt: "Check invariants and explain concrete failures.", - agents: [.claudeCode], - condition: .when(platforms: [.macOS]), - native: ["claude-code/subagent@1": ["memory": "project"]] - ) - - let agents = Agents( - sources: [ - .source(name: "team", path: "./team"), - .source(name: "drafts", path: "./draft-skills"), - .source(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), - .source(name: "catalog", index: "https://example.org/skills/index.json"), - .source(name: "vendor", url: "https://example.org/vendor/tools.git", exact: "2.1.0"), - ], - components: [ - .skills( - source: "rules", exclude: ["experimental"], mode: .copy, - overrides: [.skill(name: "testing", mode: .link, agents: [.codex])] - ), - .skills( - source: "drafts", select: ["draft"], mode: .edit, - condition: .when(agents: [.claudeCode], scopes: [.project]) - ), - .instructions( - sections: sections, - chatGPT: [.prompt(name: "weekly", sections: base, append: "notes/weekly.md")] - ), - .mcpServer( - name: "workspace", - transport: .stdio( - "workspace-tools", arguments: ["serve"], - environment: ["TOKEN": .secret("workspace-token"), "LOG_LEVEL": "info"] - ), - agents: [.claudeCode] - ), - .mcpServer( - name: "reference", - transport: .streamableHTTP( - url: "https://example.org/mcp", headers: ["Authorization": .environment("MCP_AUTH")] - ), - agents: [.openCode] - ), - .hook( - name: "format", event: .afterTool, - run: .executable( - "swift", arguments: ["format", "--in-place", "Sources"], - workingDirectory: .path("tools", source: "rules") - ), - timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) - ), - .command( - name: "review/change", description: "Review a selected change.", - prompt: "Review ${input:change} and cite evidence.", - parameters: [.parameter(name: "change", description: "The change to review.")], - agents: [.claudeCode] - ), - .lspServer( - name: "swift", run: .executable("sourcekit-lsp"), - languages: [".swift": "swift"], - initializationOptions: ["backgroundIndexing": true], - agents: [.claudeCode], condition: .when(platforms: [.macOS]) - ), - .permissions( - name: "private-files", - rules: [.deny(.read, "secrets/**")], - agents: [.claudeCode], condition: .when(scopes: [.project]) - ), - .ignore( - name: "build-products", patterns: [".build/", "DerivedData/"], purpose: .indexing, - agents: [.cursor], condition: .when(scopes: [.project]) - ), - .plugin( - name: "vendor-tools", path: "plugins/tools", source: "vendor", mode: .native, - agents: [.claudeCode], condition: .when(scopes: [.user]) - ), - .plugin( - name: "shared-tools", path: "plugins/shared", source: "vendor", - exclude: [.hook(name: "format")], condition: .when(scopes: [.project]) - ), - ], - groups: [ - .group( - name: "review-tools", components: [reviewer], - uses: [.group(name: "review", source: "team", condition: .when(agents: [.codex]))] - ) - ], - uses: ["review-tools"], - watch: ["rules", "catalog"] - ) - return CompiledManifestFixture( - name: "ConsumerExample.swift.txt", agents: agents, - constants: [ - "base": base.constructionValue, - "sections": sections.constructionValue, - "reviewer": reviewer.constructionValue, - "agents": agents.constructionValue, - ]) -} - -private func compiledCoreExample() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - sources: [ - .source( - name: "agents-tools", - url: "https://github.com/agents-tools/.github", - branch: "master", - subpath: ".agent" - ) - ], - components: [ - .instructions( - sections: [ - "guide", - .section(name: "shared/swift-package-route", source: "agents-tools"), - .section(name: "shared/swift-package-tests", source: "agents-tools"), - ], - agents: [.claudeCode, .codex] - ) - ] - ) - return CompiledManifestFixture( - name: "CoreExample.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledDumpSymbolic() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let shared: Condition = .when( - agents: [.openCode, .codex], scopes: [.user, .project], platforms: [.linux, .macOS]) - let agents = Agents( - defaultAgents: [], - exports: ["z", "a"], - sources: [ - .source(name: "z", url: "intranet/team.git", "1.2.0"..<"1.3.0"), - .source(name: "a", path: "./a"), - ], - components: [ - .instructions( - sections: ["own", .section(name: "rule", source: "z", condition: shared)], - chatGPT: [.prompt(name: "z", sections: []), .prompt(name: "a", sections: ["own"])], - agents: []), - .skills( - source: "z", select: ["z", "a"], exclude: ["z", "a"], - overrides: [.skill(name: "z", agents: []), .skill(name: "a")]), - .plugin( - name: "bundle", path: "bundle", source: "z", - exclude: [ - .hook(name: "aaa"), .command(name: "zzz"), .hook(name: "bbb"), .skill(name: "ccc"), - ]), - ], - groups: [.group(name: "z", condition: shared), .group(name: "a")], - uses: [.group(name: "review", source: "z", condition: shared), "a"], - watch: ["z", "a"] - ) - return CompiledManifestFixture( - name: "DumpSymbolic.swift.txt", agents: agents, - constants: [ - "shared": shared.constructionValue, - "agents": agents.constructionValue, - ]) -} - -private func compiledExportedGroup() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - exports: ["review"], - groups: [ - .group( - name: "review", - components: [ - .instructions(sections: ["review-principles"], agents: [.claudeCode, .codex]), - .skills(source: ".", select: ["review"], mode: .copy, agents: [.claudeCode, .codex]), - ], - condition: .when(scopes: [.project]) - ) - ] - ) - return CompiledManifestFixture( - name: "ExportedGroup.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledInstructionRecipients() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - components: [ - .instructions( - sections: ["guide", "code-review-rules"], - agents: [.claudeCode, .codex] - ) - ] - ) - return CompiledManifestFixture( - name: "InstructionRecipients.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledLiteralCoverage() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let text: PromptContent = "Review invariants." - let section: SectionReference = "guide" - let local: GroupReference = "review" - let selection: SkillSelection = ["review", "testing"] - let configuration: ConfigurationValue = [ - "string": "value", "integer": -1, "boolean": true, "null": nil, - "array": [1, "two", false, nil], "object": ["enabled": true], "decimal": .decimal("1.25"), - ] - let environment: [String: RuntimeValue] = ["LEVEL": "info", "TOKEN": .secret("token")] - let emptySelection: SkillSelection = [] - let emptyObject: ConfigurationValue = [:] - let emptyArray: ConfigurationValue = [] - let emptyTools: Component = .subagent( - name: "empty-tools", description: "No tools", prompt: "Read", tools: []) - let invocation: ExecutableInvocation = .executable( - "server", environment: environment, workingDirectory: .path("tools", source: "vendor")) - let runtime: RuntimeValue = .literal("literal") - let scalar: ConfigurationValue = .string("x") - let integer: ConfigurationValue = .integer(-9_223_372_036_854_775_808) - let boolean: ConfigurationValue = .boolean(false) - let null: ConfigurationValue = .null - let array: ConfigurationValue = .array([scalar, integer, boolean, null]) - let object: ConfigurationValue = .object(["array": array]) - let agents = Agents( - exports: ["review"], - sources: [.source(name: "team", path: "team"), .source(name: "vendor", path: "vendor")], - components: [ - .mcpServer(name: "tools", transport: .stdio("server", environment: environment)), - .mcpServer(name: "sse", transport: .sse(url: "https://example.org/events")), - .command(name: "review", description: "Review", prompt: text), - .instructions(sections: [section]), - .skills( - source: "team", select: selection, - overrides: [.skill(name: "review", mode: .copy, agents: [.codex])]), - .lspServer( - name: "swift", run: invocation, languages: [".swift": "swift"], - initializationOptions: ["config": configuration]), - .permissions( - name: "policy", - rules: [ - .allow(.read, "Sources/**"), .ask(.write, "**"), .deny(.execute, "rm *"), - .deny(.tool("fetch"), "*"), - ]), - .plugin( - name: "tools", path: "plugins/tools", source: "vendor", - select: [ - .skills, .instructions, .mcpServer, .hook, .subagent, .command, .lspServer, .permissions, - .ignore, .plugin, - ], - exclude: [ - .skill(name: "a"), .instruction(name: "a"), .mcpServer(name: "a"), .hook(name: "a"), - .subagent(name: "a"), .command(name: "a"), .lspServer(name: "a"), .permissions(name: "a"), - .ignore(name: "a"), .plugin(name: "a"), - ]), - .hook(name: "native", event: .native("Event"), run: invocation, agents: [.codex]), - .ignore( - name: "context", patterns: [], purpose: .context, agents: [], - condition: .when(scopes: [.project, .user], platforms: [.macOS, .linux])), - emptyTools, - ], - groups: [.group(name: "review")], - uses: [local, .group(name: "review", condition: .when(agents: [.codex]))] - ) - return CompiledManifestFixture( - name: "LiteralCoverage.swift.txt", agents: agents, - constants: [ - "text": text.constructionValue, - "section": section.constructionValue, - "local": local.constructionValue, - "selection": selection.constructionValue, - "configuration": configuration.constructionValue, - "environment": environment.constructionValue, - "emptySelection": emptySelection.constructionValue, - "emptyObject": emptyObject.constructionValue, - "emptyArray": emptyArray.constructionValue, - "emptyTools": emptyTools.constructionValue, - "invocation": invocation.constructionValue, - "runtime": runtime.constructionValue, - "scalar": scalar.constructionValue, - "integer": integer.constructionValue, - "boolean": boolean.constructionValue, - "null": null.constructionValue, - "array": array.constructionValue, - "object": object.constructionValue, - "agents": agents.constructionValue, - ]) -} - -private func compiledPrintedEmpty() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents() - return CompiledManifestFixture( - name: "PrintedEmpty.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledPrintedEscapes() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - defaultAgents: [], - sources: [ - .source( - name: "é/别名~\"\\\n\r\t\u{1}\u{7f}\u{85}", - url: "https://example.org/escape.git" - ) - ], - components: [ - .skills( - source: "é/别名~\"\\\n\r\t\u{1}\u{7f}\u{85}", - select: ["selected"] - ), - .instructions( - chatGPT: [ - .prompt( - name: "\"\\\n\r\t\u{1}\u{7f}\u{85} é 😀", - sections: ["own"], - append: "notes/内容.md" - ) - ] - ), - ] - ) - return CompiledManifestFixture( - name: "PrintedEscapes.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledPrintedExplicitEmpty() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - defaultAgents: [], - components: [ - .instructions( - agents: [] - ) - ] - ) - return CompiledManifestFixture( - name: "PrintedExplicitEmpty.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledPrintedFields() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - defaultAgents: [.claudeCode, .codex, .openCode], - sources: [ - .source(name: "empty", path: "./live"), - .source( - name: "git", - url: "https://intranet/team.git", - branch: "main", - subpath: "skills" - ), - .source( - name: "index", - index: "https://example.org/.well-known/skills/index.json", - subpath: "bundle" - ), - .source(name: "local", path: "./drafts", revision: "abc123"), - ], - components: [ - .skills(source: "empty", mode: .edit), - .skills( - source: "git", - select: ["a", "b"], - exclude: ["b"], - mode: .copy, - overrides: [ - .skill( - name: "a", - mode: .link, - agents: [.codex] - ), - .skill( - name: "b", - agents: [] - ), - ], - agents: [] - ), - .skills( - source: "index", - select: [] - ), - .skills( - source: "local", - overrides: [ - .skill(name: "future", mode: .copy) - ] - ), - .instructions( - sections: [ - "own", - .section(name: "rule", source: "git"), - "own", - .section(name: "nested/rule", source: "local"), - ], - chatGPT: [ - .prompt( - name: "", - sections: [] - ), - .prompt( - name: "周报", - sections: [ - .section(name: "rule", source: "git"), - "own", - ], - append: "notes/周报.md" - ), - ], - agents: [.codex, .geminiCLI] - ), - ], - watch: ["git", "index", "local"] - ) - return CompiledManifestFixture( - name: "PrintedFields.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledPrintedRanges() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - sources: [ - .source(name: "a", url: "https://Example.org/a.git", exact: "1.2.3+build"), - .source(name: "b", path: "./b", from: "1.2.0"), - .source( - name: "c", - path: "./c", - .upToNextMinor(from: "1.2.0-beta+build") - ), - .source(name: "d", path: "./d", from: "1.2.0"), - .source( - name: "e", - path: "./e", - .upToNextMinor(from: "1.2.0+lower") - ), - .source( - name: "f", - path: "./f", - "1.2.0"..<"1.8.0-beta+bound" - ), - .source( - name: "g", - path: "./g", - .upToNextMinor(from: "9223372036854775807.1.0") - ), - .source( - name: "h", - url: "ssh://User@INTRANET:2222/team/h.git", - revision: "abc123" - ), - .source( - name: "i", - path: "./i", - .upToNextMinor( - from: - "1.2.0-alphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalpha" - ) - ), - .source(name: "j", url: "https://intranet/team@variant"), - ] - ) - return CompiledManifestFixture( - name: "PrintedRanges.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledPrintedWidth() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - sources: [ - .source(name: "s", path: "./s"), - .source(name: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", path: "p"), - .source( - name: "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy", - path: "p2" - ), - ], - components: [ - .skills( - source: "s", - select: ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbb"], - exclude: [ - "ccccccccccccccccccccccccccccccccc", - "dddddddddddddddddddddddd", - ], - mode: .link - ) - ] - ) - return CompiledManifestFixture( - name: "PrintedWidth.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledProducerExample() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - exports: ["review"], - groups: [ - .group( - name: "review", - components: [ - .instructions(sections: ["review-principles"], agents: [.claudeCode, .codex]), - .skills(source: ".", select: ["review"], mode: .copy, agents: [.claudeCode, .codex]), - ], - condition: .when(scopes: [.project]) - ) - ] - ) - return CompiledManifestFixture( - name: "ProducerExample.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledRecipientConditions() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - defaultAgents: [.cursor], - sources: [.source(name: "team", path: "./team")], - components: [ - .ignore( - name: "build-products", patterns: [".build/"], purpose: .indexing, - condition: .when(scopes: [.project]) - ) - ], - uses: [ - .group(name: "review", source: "team", condition: .when(agents: [.codex])) - ] - ) - return CompiledManifestFixture( - name: "RecipientConditions.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledRequirementValues() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let majorFrom: Source = .source( - name: "rules", url: "https://example.org/rules.git", from: "1.2.0") - let majorHelper: Source = .source( - name: "rules", url: "https://example.org/rules.git", .upToNextMajor(from: "1.2.0")) - let majorRange: Source = .source( - name: "rules", url: "https://example.org/rules.git", "1.2.0"..<"2.0.0") - let minorHelper: Source = .source( - name: "rules", url: "https://example.org/rules.git", .upToNextMinor(from: "1.2.0")) - let minorRange: Source = .source( - name: "rules", url: "https://example.org/rules.git", "1.2.0"..<"1.3.0") - let prereleaseFrom: Source = .source( - name: "rules", url: "https://example.org/rules.git", from: "1.2.3-beta.1+build.7") - let prereleaseHelper: Source = .source( - name: "rules", url: "https://example.org/rules.git", - .upToNextMajor(from: "1.2.3-beta.1+build.7")) - let prereleaseRange: Source = .source( - name: "rules", url: "https://example.org/rules.git", "1.2.3-beta.1+build.7"..<"2.0.0") - let prereleaseMinor: Source = .source( - name: "rules", url: "https://example.org/rules.git", - .upToNextMinor(from: "1.2.3-beta.1+build.7")) - let prereleaseMinorRange: Source = .source( - name: "rules", url: "https://example.org/rules.git", "1.2.3-beta.1+build.7"..<"1.3.0") - let localLiteral: GroupReference = "review" - let localFactory: GroupReference = .group(name: "review") - let agents = Agents( - exports: ["review"], - sources: [majorFrom], - components: [ - .plugin(name: "tools", path: "tools", source: "rules", exclude: [.hook(name: "format")]) - ], - groups: [.group(name: "review")], - uses: [localLiteral] - ) - return CompiledManifestFixture( - name: "RequirementValues.swift.txt", agents: agents, - constants: [ - "majorFrom": majorFrom.constructionValue, - "majorHelper": majorHelper.constructionValue, - "majorRange": majorRange.constructionValue, - "minorHelper": minorHelper.constructionValue, - "minorRange": minorRange.constructionValue, - "prereleaseFrom": prereleaseFrom.constructionValue, - "prereleaseHelper": prereleaseHelper.constructionValue, - "prereleaseRange": prereleaseRange.constructionValue, - "prereleaseMinor": prereleaseMinor.constructionValue, - "prereleaseMinorRange": prereleaseMinorRange.constructionValue, - "localLiteral": localLiteral.constructionValue, - "localFactory": localFactory.constructionValue, - "agents": agents.constructionValue, - ]) -} - -private func compiledRequirementsExample() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let minimum: Version = "1.2.0" - let review: ComponentGroup = .group( - name: "review", - components: [ - .skills(source: ".", overrides: [.skill(name: "review", mode: .copy)]), - .instructions( - sections: [.section(name: "guide", source: ".")], - chatGPT: [.prompt(name: "weekly", sections: ["guide"])] - ), - .command( - name: "review", description: "Review a change", prompt: .file("review.md", source: "."), - parameters: [ - .parameter(name: "change", description: "Change identifier", defaultValue: "HEAD") - ] - ), - .hook( - name: "format", event: .afterTool, - run: .executable("swift", workingDirectory: .path("Sources", source: ".")) - ), - ] - ) - let agents = Agents( - exports: ["review"], - sources: [ - .source(name: "major", url: "https://example.org/major.git", from: minimum), - .source(name: "exact", url: "https://example.org/exact.git", exact: "1.2.0"), - .source(name: "branch", url: "https://example.org/branch.git", branch: "main"), - .source(name: "revision", url: "https://example.org/revision.git", revision: "abc123"), - .source(name: "range", url: "https://example.org/range.git", "1.2.0"..<"2.0.0"), - .source(name: "minor", url: "https://example.org/minor.git", .upToNextMinor(from: "1.2.0")), - .source( - name: "explicit-major", url: "https://example.org/explicit.git", - .upToNextMajor(from: minimum)), - .source(name: "local-major", path: "./major", from: "1.2.0"), - .source(name: "local-exact", path: "./exact", exact: "1.2.0"), - .source(name: "local-branch", path: "./branch", branch: "main"), - .source(name: "local-revision", path: "./revision", revision: "abc123"), - .source(name: "local-range", path: "./range", "1.2.0"..<"2.0.0", subpath: "tools"), - .source(name: "local-minor", path: "./minor", .upToNextMinor(from: "1.2.0")), - .source(name: "local-explicit-major", path: "./explicit", .upToNextMajor(from: "1.2.0")), - .source(name: "unversioned", url: "https://example.org/unversioned.git"), - .source(name: "local", path: "./local"), - .source(name: "catalog", index: "https://example.org/index.json", subpath: "tools"), - ], - groups: [review, .group(name: "quality", uses: ["review"])], - uses: ["quality", .group(name: "review", source: "major")] - ) - return CompiledManifestFixture( - name: "RequirementsExample.swift.txt", agents: agents, - constants: [ - "minimum": minimum.constructionValue, - "review": review.constructionValue, - "agents": agents.constructionValue, - ]) -} - -private func compiledSectionConcatenation() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let base: [SectionReference] = ["guide"] - let sections = base + [.section(name: "engineering", source: "rules")] - let reviewer: Component = .subagent( - name: "reviewer", - description: "Review correctness and tests.", - prompt: "Check invariants and explain concrete failures.", - agents: [.claudeCode], - condition: .when(platforms: [.macOS]), - native: ["claude-code/subagent@1": ["memory": "project"]] - ) - - let agents = Agents( - sources: [ - .source(name: "team", path: "./team"), - .source(name: "drafts", path: "./draft-skills"), - .source(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), - .source(name: "catalog", index: "https://example.org/skills/index.json"), - .source(name: "vendor", url: "https://example.org/vendor/tools.git", exact: "2.1.0"), - ], - components: [ - .skills( - source: "rules", exclude: ["experimental"], mode: .copy, - overrides: [.skill(name: "testing", mode: .link, agents: [.codex])] - ), - .skills( - source: "drafts", select: ["draft"], mode: .edit, - condition: .when(agents: [.claudeCode], scopes: [.project]) - ), - .instructions( - sections: sections, - chatGPT: [.prompt(name: "weekly", sections: base, append: "notes/weekly.md")] - ), - .mcpServer( - name: "workspace", - transport: .stdio( - "workspace-tools", arguments: ["serve"], - environment: ["TOKEN": .secret("workspace-token"), "LOG_LEVEL": "info"] - ), - agents: [.claudeCode] - ), - .mcpServer( - name: "reference", - transport: .streamableHTTP( - url: "https://example.org/mcp", headers: ["Authorization": .environment("MCP_AUTH")] - ), - agents: [.openCode] - ), - .hook( - name: "format", event: .afterTool, - run: .executable( - "swift", arguments: ["format", "--in-place", "Sources"], - workingDirectory: .path("tools", source: "rules") - ), - timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) - ), - .command( - name: "review/change", description: "Review a selected change.", - prompt: "Review ${input:change} and cite evidence.", - parameters: [.parameter(name: "change", description: "The change to review.")], - agents: [.claudeCode] - ), - .lspServer( - name: "swift", run: .executable("sourcekit-lsp"), - languages: [".swift": "swift"], - initializationOptions: ["backgroundIndexing": true], - agents: [.claudeCode], condition: .when(platforms: [.macOS]) - ), - .permissions( - name: "private-files", - rules: [.deny(.read, "secrets/**")], - agents: [.claudeCode], condition: .when(scopes: [.project]) - ), - .ignore( - name: "build-products", patterns: [".build/", "DerivedData/"], purpose: .indexing, - agents: [.cursor], condition: .when(scopes: [.project]) - ), - .plugin( - name: "vendor-tools", path: "plugins/tools", source: "vendor", mode: .native, - agents: [.claudeCode], condition: .when(scopes: [.user]) - ), - .plugin( - name: "shared-tools", path: "plugins/shared", source: "vendor", - exclude: [.hook(name: "format")], condition: .when(scopes: [.project]) - ), - ], - groups: [ - .group( - name: "review-tools", components: [reviewer], - uses: [.group(name: "review", source: "team", condition: .when(agents: [.codex]))] - ) - ], - uses: ["review-tools"], - watch: ["rules", "catalog"] - ) - return CompiledManifestFixture( - name: "SectionConcatenation.swift.txt", agents: agents, - constants: [ - "base": base.constructionValue, - "sections": sections.constructionValue, - "reviewer": reviewer.constructionValue, - "agents": agents.constructionValue, - ]) -} - -private func compiledSharedRules() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - sources: [ - .source( - name: "agents-tools", - url: "https://github.com/agents-tools/.github", - branch: "master", - subpath: ".agent" - ) - ], - components: [ - .instructions( - sections: [ - "guide", - .section(name: "shared/swift-package-route", source: "agents-tools"), - .section(name: "shared/swift-package-tests", source: "agents-tools"), - ], - agents: [.claudeCode, .codex] - ) - ] - ) - return CompiledManifestFixture( - name: "SharedRules.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledSketchExample() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - defaultAgents: [.cursor], - sources: [.source(name: "team", path: "./team")], - components: [ - .ignore( - name: "build-products", patterns: [".build/"], purpose: .indexing, - condition: .when(scopes: [.project]) - ) - ], - uses: [ - .group(name: "review", source: "team", condition: .when(agents: [.codex])) - ] - ) - return CompiledManifestFixture( - name: "SketchExample.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledSkillsExample() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - components: [ - .instructions( - sections: ["guide", "code-review-rules"], - agents: [.claudeCode, .codex] - ) - ] - ) - return CompiledManifestFixture( - name: "SkillsExample.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} - -private func compiledTeamConfiguration() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - // A team repository's .agent/Agents.swift. - // Everything here is a declaration: agents reads it, never runs it. - - let reviewer: Component = .subagent( - name: "reviewer", - description: "Review correctness and tests.", - prompt: "Check invariants and explain concrete failures.", - agents: [.claudeCode] - ) - - let agents = Agents( - // Components without their own `agents:` go to these. - defaultAgents: [.claudeCode, .codex], - - sources: [ - .source( - name: "org", url: "https://github.com/acme/.github", branch: "main", subpath: ".agent"), - .source(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), - .source(name: "drafts", path: "./draft-skills"), - ], - - components: [ - // AGENTS.md / CLAUDE.md, assembled from sections. - .instructions( - sections: [ - "guide", - .section(name: "shared/swift-package-route", source: "org"), - ] - ), - - // Every skill from `rules` except one; Codex gets `testing` as a link. - .skills( - source: "rules", exclude: ["experimental"], mode: .copy, - overrides: [.skill(name: "testing", mode: .link, agents: [.codex])] - ), - - // Work-in-progress skills, only for Claude Code in this project. - .skills( - source: "drafts", select: ["draft"], mode: .edit, - condition: .when(agents: [.claudeCode], scopes: [.project]) - ), - - .mcpServer( - name: "workspace", - transport: .stdio( - "workspace-tools", arguments: ["serve"], - environment: ["TOKEN": .secret("workspace-token"), "LOG_LEVEL": "info"] - ) - ), - - .hook( - name: "format", event: .afterTool, - run: .executable("swift", arguments: ["format", "--in-place", "Sources"]), - timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) - ), - - .lspServer( - name: "swift", run: .executable("sourcekit-lsp"), - languages: [".swift": "swift"], - agents: [.claudeCode], condition: .when(platforms: [.macOS]) - ), - - .permissions( - name: "private-files", - rules: [.deny(.read, "secrets/**")], - condition: .when(scopes: [.project]) - ), - - .ignore( - name: "build-products", patterns: [".build/", "DerivedData/"], purpose: .indexing, - agents: [.cursor] - ), - - reviewer, - ], - - // Re-check these sources for updates. - watch: ["rules"] - ) - return CompiledManifestFixture( - name: "TeamConfiguration.swift.txt", agents: agents, - constants: [ - "reviewer": reviewer.constructionValue, - "agents": agents.constructionValue, - ]) -} - -private func compiledVersionCollections() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let versions: [Version] = ["1.2.3"] - let namedVersions: [String: Version] = ["stable": "1.2.3"] - let version: Version = "1.2.3" - let referencedVersions: [Version] = [version] - let agents = Agents() - return CompiledManifestFixture( - name: "VersionCollections.swift.txt", agents: agents, - constants: [ - "versions": versions.constructionValue, - "namedVersions": namedVersions.constructionValue, - "version": version.constructionValue, - "referencedVersions": referencedVersions.constructionValue, - "agents": agents.constructionValue, - ]) -} - -private func compiledVocabularyDepthExample() -> CompiledManifestFixture { - // agents-tools-version: 1.0 - - let agents = Agents( - groups: [ - .group( - name: "review", - components: [ - .instructions( - chatGPT: [ - .prompt( - name: "review", - sections: [ - .section(name: "guide", condition: .when(agents: [.codex])) - ] - ) - ] - ) - ] - ) - ] - ) - return CompiledManifestFixture( - name: "VocabularyDepthExample.swift.txt", agents: agents, - constants: [ - "agents": agents.constructionValue - ]) -} diff --git a/Tests/AgentsManifestTests/DeclarationProgressTests.swift b/Tests/AgentsManifestTests/DeclarationProgressTests.swift index 36091f4..bbc347b 100644 --- a/Tests/AgentsManifestTests/DeclarationProgressTests.swift +++ b/Tests/AgentsManifestTests/DeclarationProgressTests.swift @@ -1,5 +1,4 @@ import AgentsCore -import AgentsDescription import Foundation import Testing @@ -15,13 +14,11 @@ struct DeclarationProgressTests { names.map { "\"\($0)\"" }.joined(separator: ", ") } let body = """ - let agents = Agents( - sources: [.source(name: "a", path: "a"), .source(name: "b", path: "b")], - components: [ - .skills(source: "a", select: [\(literals(old))]), - .skills(source: "b", select: [\(literals(keep))]), - ] - ) + version: 1 + sources: {a: {path: a}, b: {path: b}} + components: + - {kind: skills, source: a, select: [\(literals(old))]} + - {kind: skills, source: b, select: [\(literals(keep))]} """ let previous = try projected(body) var next = previous @@ -30,7 +27,7 @@ struct DeclarationProgressTests { let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) #expect( document.declaration - == Lowering.declaration(try DeclarationConstruction.root(next).constructionValue)) + == YAMLConstruction.root(next)) let result = try ManifestProjection.declaration( of: document, environment: projectionEnvironment) #expect(try result.skills?["b"]?.select == .names(keep)) @@ -45,16 +42,11 @@ struct DeclarationProgressTests { names.map { "\"\($0)\"" }.joined(separator: ", ") } let body = """ - let agents = Agents( - sources: [ - .source(name: "b", path: "b"), - .source(name: "a", path: "a"), - ], - components: [ - .skills(source: "a", select: [\(literals(old))]), - .skills(source: "b", select: [\(literals(keep))]), - ] - ) + version: 1 + sources: {b: {path: b}, a: {path: a}} + components: + - {kind: skills, source: a, select: [\(literals(old))]} + - {kind: skills, source: b, select: [\(literals(keep))]} """ let previous = try projected(body) var next = previous @@ -72,7 +64,7 @@ struct DeclarationProgressTests { let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) #expect( document.declaration - == Lowering.declaration(try DeclarationConstruction.root(next).constructionValue)) + == YAMLConstruction.root(next)) let result = try ManifestProjection.declaration( of: document, environment: projectionEnvironment) #expect(try planned(result, next, in: String(decoding: bytes, as: UTF8.self)) == nil) diff --git a/Tests/AgentsManifestTests/DeclarationPropertyTests.swift b/Tests/AgentsManifestTests/DeclarationPropertyTests.swift deleted file mode 100644 index 909c224..0000000 --- a/Tests/AgentsManifestTests/DeclarationPropertyTests.swift +++ /dev/null @@ -1,209 +0,0 @@ -import AgentsCore -import Foundation -import Testing - -@testable import AgentsManifest - -/// Deterministic declarations over a small alias, name and section vocabulary. -private struct DeclarationGenerator { - var random = ManifestRandom(state: 0x5eed_2026_1030) - - mutating func flip() -> Bool { random.next(2) == 0 } - - mutating func subset(_ values: [T]) -> [T] { values.filter { _ in flip() } } - - mutating func recipients() -> [AgentID]? { - switch random.next(3) { - case 0: return nil - case 1: return [] - default: return subset(AgentID.allCases) - } - } - - mutating func source(_ alias: String) -> SourceDeclaration { - let requirements: [SourceRequirement?] = [ - nil, .branch("main"), .revision("abc123"), .exact("1.2.3"), .upToNextMajor(from: "1.2.0"), - .upToNextMinor(from: "1.2.0"), .range(from: "1.2.0", to: "1.5.0"), - ] - let subpath = flip() ? nil : "skills" - switch random.next(3) { - case 0: - return SourceDeclaration( - kind: .git, location: "example.org/team/\(alias).git", - requirement: requirements[random.next(requirements.count)], path: subpath) - case 1: - return SourceDeclaration( - kind: .local, location: "./\(alias)", - requirement: requirements[random.next(requirements.count)], path: subpath) - default: - return SourceDeclaration( - kind: .wellKnown, location: "https://example.org/\(alias)/index.json", path: subpath) - } - } - - mutating func skills() -> SkillDeclaration { - let names = ["x", "y", "z"] - let select: SkillSelection = flip() ? .all : .names(subset(names)) - var overrides: [String: SkillOverride] = [:] - let candidates: [String] - if case .names(let selected) = select { candidates = selected } else { candidates = names } - for name in subset(candidates) { - overrides[name] = SkillOverride( - agents: recipients(), mode: [nil, .copy, .link][random.next(3)]) - } - return SkillDeclaration( - select: select, exclude: flip() ? nil : subset(names), agents: recipients(), - mode: [nil, .copy, .link][random.next(3)], overrides: flip() ? nil : overrides) - } - - mutating func sections(_ aliases: [String]) -> [String] { - let pool = ["guide", "rules"] + aliases.map { $0 + ":guide" } - return (0.. InstructionsDeclaration? { - guard flip() else { return nil } - var prompts: [String: PromptDeclaration] = [:] - for name in subset(["daily", "weekly"]) { - prompts[name] = PromptDeclaration( - sections: sections(aliases), append: flip() ? nil : "notes/\(name).md") - } - return InstructionsDeclaration( - agents: recipients(), sections: sections(aliases), chatgpt: flip() ? nil : prompts) - } - - mutating func declaration() throws -> Declaration { - var declaration = Declaration(agents: recipients()) - for alias in subset(["a", "b", "c", "d"]) { - declaration.sources[alias] = source(alias) - } - let aliases = declaration.sources.keys.sorted() - var skills: [String: SkillDeclaration] = [:] - for alias in subset(aliases) { skills[alias] = self.skills() } - try declaration.setSkills(skills.isEmpty && flip() ? nil : skills) - try declaration.setInstructions(instructions(aliases)) - declaration.watch = flip() ? nil : subset(aliases) - return declaration - } - - /// A neighbor of `base`: each part is kept, changed or removed, and references follow sources. - mutating func change(_ base: Declaration) throws -> Declaration { - var result = base - if random.next(3) == 0 { result.agents = recipients() } - for alias in base.sources.keys.sorted() { - switch random.next(4) { - case 0: result.sources[alias] = nil - case 1: result.sources[alias] = source(alias) - default: break - } - } - for alias in ["e", "f"] where random.next(3) == 0 { result.sources[alias] = source(alias) } - let aliases = result.sources.keys.sorted() - var skills = ((try result.skills) ?? [:]).filter { result.sources[$0.key] != nil } - for alias in aliases where random.next(3) == 0 { - skills[alias] = flip() ? nil : self.skills() - } - try result.setSkills(skills) - let referenced = (try result.instructions).map { - ($0.sections + ($0.chatgpt ?? [:]).values.flatMap(\.sections)).allSatisfy { - !$0.contains(":") || result.sources[String($0.split(separator: ":")[0])] != nil - } - } - if referenced == false || random.next(3) == 0 { - try result.setInstructions(instructions(aliases)) - } - result.watch = random.next(3) == 0 ? subset(aliases) : result.watch?.filter(aliases.contains) - return result - } -} - -private func equivalent(_ lhs: Declaration, _ rhs: Declaration) -> Bool { - ManifestProjection.equivalent(lhs, rhs, environment: projectionEnvironment) -} - -private func projection(of bytes: [UInt8]) throws -> Declaration { - try ManifestProjection.declaration( - of: DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")), - environment: projectionEnvironment) -} - -/// Comments above every source, skills and instructions entry that `next` keeps unchanged. -private func commented(_ text: String, keeping kept: [String]) -> String { - var lines = text.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) - for marker in kept { - let (call, name) = (marker.split(separator: " ")[0], marker.split(separator: " ")[1]) - guard - let index = lines.indices.first(where: { index in - let line = lines[index].trimmingCharacters(in: .whitespaces) - let next = index + 1 < lines.count ? lines[index + 1] : "" - return line.hasPrefix(String(call) + "(") - && (line.contains("\"\(name)\"") - || !line.hasSuffix(")") && !line.hasSuffix("),") - && next.contains("\"\(name)\"")) - }) - else { continue } - let indentation = lines[index].prefix { $0 == " " } - lines.insert(indentation + "// keep " + marker, at: index) - } - lines.insert("// file comment", at: 3) - return lines.joined(separator: "\n") + "// end of file\n" -} - -@Suite("Declaration properties") -struct DeclarationPropertyTests { - @Test func printedDeclarationsProjectToThemselves() throws { - var generator = DeclarationGenerator() - for _ in 0..<96 { - let declaration = try generator.declaration() - try declaration.validate(environment: projectionEnvironment) - guard let bytes = try planned(Declaration(), declaration, in: nil) else { - #expect(equivalent(declaration, Declaration())) - continue - } - #expect(try planned(Declaration(), declaration, in: nil) == bytes) - #expect(equivalent(try projection(of: bytes), declaration), "\(declaration)") - } - } - - @Test func plansReachTheirTargetAndKeepCommentsOfUnchangedEntries() throws { - var generator = DeclarationGenerator() - var (edited, markers) = (0, 0) - for _ in 0..<96 { - let previous = try generator.declaration() - let next = try generator.change(previous) - try next.validate(environment: projectionEnvironment) - let printed = String( - decoding: try planned(Declaration(), previous, in: nil) ?? [], as: UTF8.self) - guard !printed.isEmpty else { continue } - var kept: [String] = [] - for alias in previous.sources.keys.sorted() { - if let source = next.sources[alias], source == previous.sources[alias] { - kept.append(".source \(alias)") - } - } - for alias in ((try previous.skills) ?? [:]).keys.sorted() - where (try next.skills)?[alias] == (try previous.skills)?[alias] { - kept.append(".skills \(alias)") - } - let text = commented(printed, keeping: kept) - let bytes = try planned(previous, next, in: text) - guard let bytes else { - #expect(equivalent(previous, next)) - continue - } - #expect(equivalent(try projection(of: bytes), next), "\(previous) -> \(next)") - let result = String(decoding: bytes, as: UTF8.self) - #expect( - result.contains( - "// agents-tools-version: 1.0\nimport AgentsDescription\n\n// file comment\n")) - #expect(result.hasSuffix(")\n// end of file\n")) - for marker in kept { - #expect(result.components(separatedBy: "// keep " + marker + "\n").count == 2, "\(marker)") - } - edited += 1 - markers += kept.count - } - // The seed must exercise edits and retained comments, not only no-op or empty plans. - #expect(edited >= 64 && markers >= 64) - } -} diff --git a/Tests/AgentsManifestTests/DifferentialFuzzTests.swift b/Tests/AgentsManifestTests/DifferentialFuzzTests.swift deleted file mode 100644 index a83f699..0000000 --- a/Tests/AgentsManifestTests/DifferentialFuzzTests.swift +++ /dev/null @@ -1,152 +0,0 @@ -import Foundation -import ManifestTestSupport -import Testing - -@testable import AgentsManifest - -struct ManifestRandom { - static let seed: UInt64 = 0xa631_2026_1029 - var state = seed - mutating func next(_ upper: Int) -> Int { - state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407 - return Int((state >> 24) % UInt64(upper)) - } - mutating func choose(_ values: [String]) -> String { values[next(values.count)] } - mutating func expression(depth: Int = 0) -> String { - let leaves = [ - "0", "-1", "1_000", "true", "false", "nil", "value", "\"text\"", "\"é😀\"", "\"\\u{1F600}\"", - "\"\"\"\n line\n \\\"quote\n \"\"\"", ".copy", "Type.member", "[]", "[:]", - ] - if depth == 3 || next(4) == 0 { return choose(leaves) } - switch next(7) { - case 0: - return "[" + (0.. [AdmissionCase] { - var rng = ManifestRandom() - var cases: [AdmissionCase] = [] - var generated: [String] = [] - for index in 0..<256 { - var expression = rng.expression() - if index == 255 { - expression = "[" + Array(repeating: "0", count: 12_450).joined(separator: ",") + "]" - } - generated.append(expression) - let type = rng.choose([ - "", ": String", ": [Int]", ": [String: ConfigurationValue]", ": Component", - ": [[String: [Bool]]]", - ]) - let text = - manifestHeader + "let base: [String] = []\nlet value" + type + " = " + expression + "\n" - cases.append(AdmissionCase("grammar-\(index)", text, expected: "accepted", complete: true)) - } - let tokens = [ - "let", "import", "copy", "await", "consume", "each", "unsafe", "x", "0", "\"s\"", "(", ")", "[", - "]", ",", ":", ".", "=", "+", "-1", - ] - for index in 0..<128 { - let sequence = (0..<(1 + rng.next(48))).map { _ in rng.choose(tokens) }.joined(separator: " ") - cases.append(AdmissionCase("tokens-\(index)", sequence)) - } - for index in 0..<128 { - cases.append( - AdmissionCase( - "injected-\(index)", - rng.expression() + " " - + rng.choose(["<", ">", "{", "}", "#", "?", "!", "&", "*", "/", "`x`", "$x"]), - expected: "manifest.syntax")) - } - for (index, source) in generated.enumerated() { - let bytes = Array(source.utf8) - let point = rng.next(bytes.count + 1) - let skip = min(rng.next(2), bytes.count - point) - let mutation = Array( - rng.choose(["", "copy ", "#\"\"\"#", "/*", "\"", "[", ")", " + ", " "]).utf8) - cases.append( - AdmissionCase( - "mutation-\(index)", - bytes: Array((manifestHeader + "let value = ").utf8) + bytes[.. 0 && attempts < 64 { - var offset = manifestHeader.utf8.count - var found = false - while offset + chunk <= minimized.count && attempts < 64 { - var candidate = minimized - candidate.removeSubrange(offset..<(offset + chunk)) - attempts += 1 - let check = try probe("minimize", candidate, in: directory) - if check.report.stage == .parser { - minimized = candidate - found = true - break - } - offset += chunk - } - if !found { chunk /= 2 } - } - try Data(minimized).write( - to: retained.appendingPathComponent(fixture.name + ".minimal.swift")) - Issue.record( - "differential counterexample retained: \(fixture.name), seed=\(ManifestRandom.seed)") - } - if let expected = fixture.expected { - #expect(result.report.status == expected, "\(fixture.name): \(result.report.message)") - } - results.append(result) - } - let slowest = results.max { $0.wallSeconds < $1.wallSeconds }! - let accepted = results.filter { $0.report.status == "accepted" }.count - print( - "MANIFEST_FUZZ configuration=\(probeConfiguration) watchdogSeconds=\(probeWatchdogSeconds) seed=\(ManifestRandom.seed) grammar=256 tokens=128 injected=128 mutations=256 ranges=128 cases=\(results.count) accepted=\(accepted) slowest=\(slowest.name) seconds=\(slowest.wallSeconds) peakMemory=\(results.map { $0.report.peakMemoryBytes }.max()!)" - ) - try recordProbeResults(results, name: "differential-run") - } -} diff --git a/Tests/AgentsManifestTests/DumpTests.swift b/Tests/AgentsManifestTests/DumpTests.swift deleted file mode 100644 index bc8dd26..0000000 --- a/Tests/AgentsManifestTests/DumpTests.swift +++ /dev/null @@ -1,150 +0,0 @@ -import AgentsCore -import Foundation -import Testing - -@testable import AgentsManifest - -@Suite("Evaluated manifest dump") -struct DumpTests { - @Test(arguments: [ - "PrintedEmpty", "PrintedFields", "DumpSymbolic", "ConsumerExample", "LiteralCoverage", - ]) - func completeGoldenObjectsAndLocationsAreByteExact(_ name: String) throws { - let bytes = try manifestFixture(name + ".swift.txt") - let dump = try ManifestDump(bytes: bytes) - let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) - #expect(dump.locations.count == document.sourceMap.entries.count) - let output = try dump.encodedJSON() - #expect(try output == manifestFixture(name + ".dump.json")) - #expect(try output == dump.encodedJSON()) - #expect(output.last == 10) - #expect(dump.sourceDigest == "sha256:" + FileHash.sha256Hex(data: Data(bytes))) - let root = try #require(JSONSerialization.jsonObject(with: Data(output)) as? [String: Any]) - #expect( - root.keys.sorted() == [ - "declaration", "diagnostics", "kind", "languageVersion", "locations", "schemaVersion", - "sourceDigest", - ]) - #expect(root["schemaVersion"] as? Int == 1) - let declaration = try #require(root["declaration"]) - for location in dump.locations { - #expect(resolve(location.pointer, in: declaration) != nil, "\(name): \(location.pointer)") - #expect(location.span.document.rawValue == "manifest") - #expect(location.origins.allSatisfy { $0.document.rawValue == "manifest" }) - } - } - - @Test func symbolicConditionsGroupsExplicitRecipientsAndNormalizedPointersSurvive() throws { - let bytes = try manifestFixture("DumpSymbolic.swift.txt") - let dump = try ManifestDump(bytes: bytes) - let root = try #require( - JSONSerialization.jsonObject(with: Data(dump.encodedJSON())) as? [String: Any]) - let declaration = try #require(root["declaration"]) - #expect(resolve("/defaultAgents", in: declaration) as? [String] == []) - #expect(resolve("/components/0/agents", in: declaration) as? [String] == []) - #expect(resolve("/components/1/agents", in: declaration) is NSNull) - #expect(resolve("/sources/0/name", in: declaration) as? String == "a") - #expect(resolve("/sources/1/url", in: declaration) as? String == "https://intranet/team.git") - #expect(resolve("/sources/1/requirement/upToNextMinor", in: declaration) as? String == "1.2.0") - #expect(resolve("/components/1/select", in: declaration) as? [String] == ["a", "z"]) - #expect(resolve("/components/1/overrides/0/name", in: declaration) as? String == "a") - #expect(resolve("/components/2/exclude/0/kind", in: declaration) as? String == "command") - #expect(resolve("/components/2/exclude/0/name", in: declaration) as? String == "zzz") - #expect(resolve("/components/2/exclude/1/kind", in: declaration) as? String == "hook") - #expect(resolve("/components/2/exclude/1/name", in: declaration) as? String == "aaa") - #expect(resolve("/components/2/exclude/2/name", in: declaration) as? String == "bbb") - #expect(resolve("/components/2/exclude/3/kind", in: declaration) as? String == "skill") - #expect(resolve("/components/0/chatGPT/0/name", in: declaration) as? String == "a") - #expect(resolve("/uses/0/kind", in: declaration) as? String == "exported") - #expect(resolve("/uses/0/source", in: declaration) as? String == "z") - #expect(resolve("/uses/1/kind", in: declaration) as? String == "local") - #expect(resolve("/uses/1/source", in: declaration) is NSNull) - #expect( - resolve("/uses/0/condition/agents", in: declaration) as? [String] == ["codex", "opencode"]) - let location = try #require(dump.locations.first { $0.pointer == "/sources/1/name" }) - #expect( - String(decoding: bytes[location.span.start.. Any? { - if pointer.isEmpty { return value } - var current = value - for segment in pointer.dropFirst().split(separator: "/", omittingEmptySubsequences: false) { - let key = pointerUnescape(String(segment)) - if let fields = current as? [String: Any], let child = fields[key] { - current = child - } else if let values = current as? [Any], let index = Int(key), values.indices.contains(index) - { - current = values[index] - } else { - return nil - } - } - return current - } -} diff --git a/Tests/AgentsManifestTests/EditPlanTests.swift b/Tests/AgentsManifestTests/EditPlanTests.swift index a17d58f..728b2dc 100644 --- a/Tests/AgentsManifestTests/EditPlanTests.swift +++ b/Tests/AgentsManifestTests/EditPlanTests.swift @@ -1,5 +1,4 @@ import AgentsCore -import AgentsDescription import Foundation import Testing @@ -11,40 +10,18 @@ func planned(_ previous: Declaration, _ next: Declaration, in text: String?) thr identity: DocumentIdentity("manifest"), environment: projectionEnvironment) } -private func expectChange( - _ body: String, to expected: String, sourceLocation: SourceLocation = #_sourceLocation, - _ update: (inout Declaration) throws -> Void -) throws { - let result = try changed(body, update) - #expect(result == expected, sourceLocation: sourceLocation) -} - -/// Plans a change to a manifest body and returns the edited body, checked against the intent. -private func changed(_ body: String, _ update: (inout Declaration) throws -> Void) throws -> String -{ - let previous = try projected(body) - var next = previous - try update(&next) - let bytes = try #require(try planned(previous, next, in: manifestHeader + body)) - let text = String(decoding: bytes, as: UTF8.self) - #expect(text.hasPrefix(manifestHeader)) - let result = String(text.dropFirst(manifestHeader.count)) - let reparsed = try projected(result) - #expect(ManifestProjection.equivalent(reparsed, next, environment: projectionEnvironment)) - return result -} - -private let local = SourceDeclaration(kind: .local, location: "s") - @Suite("Declaration edit planning") struct EditPlanTests { - @Test func equivalentSpellingsAndLayoutPlanNoEdit() throws { + @Test func equivalentSpellingsAndWatchOrderPreserveEveryByte() throws { let body = """ - let agents = Agents(defaultAgents:[.codex,.claudeCode], - sources: [.source(name: "g", url: "github.com/team/skills", "1.2.0" ..< "2.0.0"), - .source(name: "l", path: "./rules/", subpath: "./skills"),], - components: [.skills(source: "g", select: ["b", "a"], exclude: [])], - watch: ["l", "g"]) + # header + version: 1 + defaultAgents: [codex, claude-code] + sources: + g: {url: https://github.com/team/skills, requirement: {from: "1.2.0", to: "2.0.0"}} + l: {path: ./rules/, subpath: ./skills} # retained + components: [{kind: skills, source: g, select: [b, a], exclude: []}] + watch: [l, g] """ let previous = try projected(body) var next = previous @@ -56,576 +33,129 @@ struct EditPlanTests { kind: .local, location: "/work/project/rules", path: "skills") try next.updateSkills { $0?["g"] = SkillDeclaration(select: .names(["a", "b"])) } next.watch = ["g", "l"] - #expect(try planned(previous, next, in: manifestHeader + body) == nil) + #expect(try planned(previous, next, in: body) == nil) #expect(try planned(Declaration(), Declaration(), in: nil) == nil) } - - @Test func defaultAgentsChangeByElementOrWholeArgument() throws { - let body = """ - let agents = Agents( - // recipients - defaultAgents: [.codex /* keep */, .openCode], - watch: [] - ) - """ - try expectChange( - body, - to: """ - let agents = Agents( - // recipients - defaultAgents: [.claudeCode, .codex /* keep */], - watch: [] - ) - """ - ) { $0.agents = [.codex, .claudeCode] } - expectManifestFailure("manifest.edit.readOnly") { try changed(body) { $0.agents = nil } } - try expectChange( - "let agents = Agents(defaultAgents: [.codex], watch: [])", - to: "let agents = Agents(defaultAgents: nil, watch: [])" - ) { $0.agents = nil } - try expectChange( - "let agents = Agents(watch: [])", - to: "let agents = Agents(defaultAgents: [.codex, .cursor], watch: [])" - ) { $0.agents = [.cursor, .codex] } - } - - @Test func sourcesAppendReplaceInPlaceAndLeaveWithTheirReferences() throws { - let body = """ - let agents = Agents( - sources: [ - // team - .source(name: "team", url: "https://e.org/t", branch: "main"), // pin - .source(name: "s", path: "s"), - ], - components: [ - .skills(source: "s"), - ], - watch: ["s"] - ) - """ - try expectChange( - body, - to: """ - let agents = Agents( - sources: [ - // team - .source(name: "team", url: "https://e.org/t", revision: "abc123"), // pin - .source(name: "s", path: "s"), - .source(name: "new", url: "https://github.com/a/new"), - ], - components: [ - .skills(source: "s"), - ], - watch: ["s"] - ) - """ - ) { - $0.sources["team"]?.requirement = .revision("abc123") - $0.sources["new"] = SourceDeclaration(kind: .git, location: "github.com/a/new") - } - try expectChange( - body, - to: """ - let agents = Agents( - sources: [ - // team - .source(name: "team", url: "https://e.org/t", branch: "main"), // pin - ], - components: [ - ], - watch: [] - ) - """ - ) { - $0.sources["s"] = nil - try $0.setSkills(nil) - $0.watch = nil - } - } - - @Test func newSkillsComponentsPrecedeInstructionsOrAppend() throws { - let body = """ - let agents = Agents( - sources: [.source(name: "a", path: "a"), .source(name: "b", path: "b")], - components: [ - // rules - .instructions(sections: ["guide"]), - ] - ) - """ - try expectChange( - body, - to: """ - let agents = Agents( - sources: [.source(name: "a", path: "a"), .source(name: "b", path: "b")], - components: [ - .skills( - source: "a", - select: ["x"] - ), - .skills(source: "b"), - // rules - .instructions(sections: ["guide"]), - ] - ) - """ - ) { - try $0.setSkills([ - "b": SkillDeclaration(select: .all), "a": SkillDeclaration(select: .names(["x"])), - ]) - } - try expectChange( - "let agents = Agents(sources: [.source(name: \"a\", path: \"a\")])", - to: """ - let agents = Agents( - sources: [.source(name: "a", path: "a")], - components: [ - .skills(source: "a"), - ] - ) - """ - ) { try $0.setSkills(["a": SkillDeclaration(select: .all)]) } - } - - @Test func selectionSwitchesAndNameEditsKeepOrder() throws { - let body = """ - let agents = Agents( - sources: [.source(name: "s", path: "s")], - components: [ - .skills(source: "s", select: ["a", "c" /* c */, "e"]), - ] - ) - """ - try expectChange( - body, - to: """ - let agents = Agents( - sources: [.source(name: "s", path: "s")], - components: [ - .skills(source: "s", select: ["b", "c" /* c */, "d", "e"]), - ] - ) - """ - ) { try $0.updateSkills { $0?["s"]?.select = .names(["b", "c", "d", "e"]) } } - expectManifestFailure("manifest.edit.readOnly") { - try changed(body) { try $0.updateSkills { $0?["s"]?.select = .all } } - } - let plain = """ - let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ - .skills(source: "s", select: .all), - ]) - """ - try expectChange( - plain, - to: """ - let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ - .skills(source: "s", select: ["y", "z"]), - ]) - """ - ) { try $0.updateSkills { $0?["s"]?.select = .names(["z", "y"]) } } - try expectChange( - plain.replacingOccurrences(of: ".all", with: "[\"a\"]"), - to: plain - ) { try $0.updateSkills { $0?["s"]?.select = .all } } - } - - @Test func excludeAgentsAndModeAreArgumentEdits() throws { - let body = """ - let agents = Agents( - sources: [.source(name: "s", path: "s")], - components: [ - .skills( - // all team skills - source: "s", - mode: .copy - ), - ] - ) - """ - try expectChange( - body, - to: """ - let agents = Agents( - sources: [.source(name: "s", path: "s")], - components: [ - .skills( - // all team skills - source: "s", - exclude: ["x"], - mode: nil, - agents: [] - ), - ] - ) - """ - ) { - try $0.updateSkills { $0?["s"]?.exclude = ["x"] } - try $0.updateSkills { $0?["s"]?.mode = nil } - try $0.updateSkills { $0?["s"]?.agents = [] } - } - try expectChange( - """ - let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ - .skills(source: "s", exclude: ["a", "c"], agents: [.codex]), - ]) - """, - to: """ - let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ - .skills(source: "s", exclude: ["b", "c"], mode: .link, agents: [.claudeCode, .codex]), - ]) - """ - ) { - try $0.updateSkills { $0?["s"]?.exclude = ["b", "c"] } - try $0.updateSkills { $0?["s"]?.agents = [.codex, .claudeCode] } - try $0.updateSkills { $0?["s"]?.mode = .link } - } - } - - @Test func overridesAreUpsertedAndRemovedByName() throws { - let body = """ - let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ - .skills(source: "s", select: ["a", "b"], overrides: [ - .skill(name: "a", mode: .copy), // copy a - .skill(name: "b"), - ]), - ]) - """ - try expectChange( - body, - to: """ - let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ - .skills(source: "s", select: ["a", "c"], overrides: [ - .skill(name: "a", mode: .copy), // copy a - .skill( - name: "c", - agents: [.codex] - ), - ]), - ]) - """ - ) { - try $0.updateSkills { - $0?["s"]?.overrides = [ - "a": SkillOverride(mode: .copy), "c": SkillOverride(agents: [.codex]), - ] - } - try $0.updateSkills { $0?["s"]?.select = .names(["a", "c"]) } - } - } - - @Test func instructionsComponentsAreAddedRemovedAndRetargeted() throws { - try expectChange( - """ - let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ - // skills - .skills(source: "s"), - ]) - """, - to: """ - let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ - // skills - .skills(source: "s"), - .instructions( - sections: ["guide"] - ), - ]) - """ - ) { try $0.setInstructions(InstructionsDeclaration(sections: ["guide"])) } - let body = """ - let agents = Agents(components: [ - // rules - .instructions(sections: ["guide"], agents: [.codex]), - ]) - """ - try expectChange(body, to: "let agents = Agents(components: [\n])") { - try $0.setInstructions(nil) - } - try expectChange( - body, - to: """ - let agents = Agents(components: [ - // rules - .instructions(sections: ["guide"], agents: [.cursor]), - ]) - """ - ) { try $0.updateInstructions { $0?.agents = [.cursor] } } - } - - @Test func sectionsFollowTheLongestCommonSubsequenceAndKeepDuplicates() throws { - let body = """ - let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ - .instructions(sections: [ - "a", // first a - "b", - "a", - .section(name: "c", source: "s"), - ]), - ]) - """ - try expectChange( - body, - to: """ - let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ - .instructions(sections: [ - "a", // first a - "x", - "a", - .section(name: "c", source: "s"), - "a", - "y", - ]), - ]) - """ - ) { try $0.updateInstructions { $0?.sections = ["a", "x", "a", "s:c", "a", "y"] } } - try expectChange( - body, - to: """ - let agents = Agents(sources: [.source(name: "s", path: "s")], components: [ - .instructions(sections: [ - "b", - ]), - ]) - """ - ) { try $0.updateInstructions { $0?.sections = ["b"] } } - } - - @Test func promptsAreUpsertedAndRemovedByName() throws { - let body = """ - let agents = Agents(components: [ - .instructions(chatGPT: [ - .prompt(name: "daily", sections: ["guide"]), // daily - .prompt(name: "weekly", sections: ["guide"]), - ]), + @Test func defaultRecipientsCanBeInsertedReplacedAndOmitted() throws { + var previous = try projected("version: 1\n") + var bytes = Array("version: 1\n".utf8) + for recipients: [AgentID]? in [[], [.codex, .claudeCode], nil] { + var next = previous + next.agents = recipients + bytes = try #require(try planned(previous, next, in: String(decoding: bytes, as: UTF8.self))) + #expect(try projected(String(decoding: bytes, as: UTF8.self)).agents == recipients) + previous = next + } + } + @Test func missingCollectionsAndLastElementRemovalKeepValidDocuments() throws { + let doc = try document("# header\r\nversion: 1\r\n") + let added = try doc.preparing([ + .insertComponent( + .instructions(InstructionsDeclaration(sections: ["guide"])), into: .root, at: .last) + ]) + let populated = try DeclarationDocument( + bytes: added.bytes, identity: DocumentIdentity("manifest")) + let removed = try populated.preparing([ + .removeComponent(#require(populated.node(at: "/components/0"))) + ]) + #expect( + try DeclarationDocument(bytes: removed.bytes, identity: DocumentIdentity("manifest")) + .declaration.components.isEmpty) + #expect(String(decoding: removed.bytes, as: UTF8.self).hasPrefix("# header\r\n")) + } + @Test func preparationRejectsOversizedIntentBeforeRendering() throws { + let doc = try document("version: 1\n") + expectManifestFailure("manifest.limit") { + try doc.preparing([ + .insertComponent( + .ignore(name: "large", patterns: [String(repeating: "x", count: 20_000_000)]), + into: .root, at: .first) ]) - """ - try expectChange( - body, - to: """ - let agents = Agents(components: [ - .instructions(chatGPT: [ - .prompt( - name: "daily", - sections: ["guide", "notes"] - ), // daily - .prompt( - name: "monthly", - sections: [], - append: "notes/monthly.md" - ), - ]), - ]) - """ - ) { - try $0.updateInstructions { - $0?.chatgpt = [ - "daily": PromptDeclaration(sections: ["guide", "notes"]), - "monthly": PromptDeclaration(sections: [], append: "notes/monthly.md"), - ] - } } } +} - @Test func watchChangesByElementOrWholeArgument() throws { - let sources = - "sources: [.source(name: \"a\", path: \"a\"), .source(name: \"b\", path: \"b\"), .source(name: \"c\", path: \"c\")]" - try expectChange( - "let agents = Agents(\n \(sources),\n watch: [\"a\", \"c\"] // watched\n)", - to: "let agents = Agents(\n \(sources),\n watch: [\"b\", \"c\"] // watched\n)" - ) { $0.watch = ["b", "c"] } - try expectChange( - "let agents = Agents(sources: [.source(name: \"a\", path: \"a\")])", - to: "let agents = Agents(sources: [.source(name: \"a\", path: \"a\")], watch: [\"a\"])" - ) { $0.watch = ["a"] } +extension EditPlanTests { + @Test func blockAndFlowMovesCarryCommentsAcrossContainers() throws { + let doc = try document( + """ + version: 1 + components: + # owned entry + - kind: ignore + name: moving + patterns: [] # owned tail + groups: + target: + components: + - {kind: ignore, name: existing, patterns: []} + """) + let change = try doc.preparing([ + .moveComponent( + #require(doc.node(at: "/components/0")), into: .group(#require(doc.node(at: "/groups/0"))), + at: .last) + ]) + let result = try DeclarationDocument( + bytes: change.bytes, identity: DocumentIdentity("manifest")) + #expect(result.declaration.components.isEmpty) + #expect(result.declaration.groups[0]["components"]?.elements?.count == 2) + let text = String(decoding: change.bytes, as: UTF8.self) + #expect(text.contains("# owned entry\n - kind: ignore")) + #expect(text.contains("patterns: [] # owned tail")) + let flow = try document( + "version: 1\ncomponents: [{kind: ignore, name: moving, patterns: []}]\ngroups: {target: {}}\n" + ) + let moved = try flow.preparing([ + .moveComponent( + #require(flow.node(at: "/components/0")), + into: .group(#require(flow.node(at: "/groups/0"))), at: .first) + ]) + #expect( + try DeclarationDocument(bytes: moved.bytes, identity: DocumentIdentity("manifest")) + .declaration.groups[0]["components"]?.elements?.count == 1) } - @Test func sharedConstantsAndCommentedReplacementsAreReadOnly() throws { - let constant = """ - let picked: SkillSelection = ["a"] - let agents = Agents(sources: [.source(name: "s", path: "s")], components: [.skills(source: "s", select: picked)]) - """ - let previous = try projected(constant) + @Test func sourceKindChangeRetainsInternalCommentsAndUnchangedFields() throws { + let body = + "version: 1\nsources:\n s:\n path: ./s # location\n # root comment\n subpath: rules\ncomponents: [{kind: skills, source: s, mode: edit}]\n" + let previous = try projected(body) var next = previous - try next.updateSkills { $0?["s"]?.select = .names(["a", "b"]) } - expectManifestFailure("manifest.edit.readOnly") { - try planned(previous, next, in: manifestHeader + constant) - } - let commented = """ - let agents = Agents(sources: [.source(name: "s", /* pinned */ url: "https://e.org/s.git", branch: "main")]) - """ - let source = try projected(commented) - var moved = source - moved.sources["s"]?.requirement = .branch("next") - expectManifestFailure("manifest.edit.readOnly") { - try planned(source, moved, in: manifestHeader + commented) - } - } - - @Test func largeChangesAreSplitIntoReplannedBatches() throws { - var next = Declaration() - for alias in (0..<150).map({ "s\($0)" }).sorted(by: utf8Less) { - next.sources[alias] = SourceDeclaration(kind: .local, location: alias) - } - var batches: [Int] = [] - let bytes = try #require( - try DeclarationEditPlan.bytes( - replacing: Declaration(), with: next, - in: Array((manifestHeader + "let agents = Agents()").utf8), - identity: DocumentIdentity("manifest"), environment: projectionEnvironment, - planning: { - batches.append($0.count) - return $0 - })) - #expect(batches == [150, 50, 0]) - let result = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) - #expect(result.declaration.sources.count == 150) - } - - @Test func previousMustDescribeTheDocument() throws { - let body = "let agents = Agents(sources: [.source(name: \"s\", path: \"s\")])" - let stale = Declaration(sources: ["s": local, "t": local]) - expectManifestFailure("manifest.edit.baseline") { - try planned(stale, stale, in: manifestHeader + body) - } - expectManifestFailure("manifest.edit.baseline") { - try planned(Declaration(sources: ["s": local]), Declaration(), in: nil) + next.sourceDeclarations[0].source = SourceDeclaration( + kind: .git, location: "https://example.invalid/repo.git", path: "rules") + try next.updateSkills { $0?["s"]?.mode = .copy } + let bytes = try #require(try planned(previous, next, in: body)) + let text = String(decoding: bytes, as: UTF8.self) + #expect(text.contains("# root comment\n subpath: rules")) + #expect(text.contains("# location")) + #expect(try projected(text).components == next.components) + } + + @Test func unrelatedHandlesAndLiteralKindsAreRejectedWithoutTrapping() throws { + let doc = try document("version: 1\ncomponents: [{kind: ignore, name: i, patterns: []}]\n") + let scalar = try #require(doc.node(at: "/components/0/name")) + for edit in [ + ManifestEdit.setSkillSelection(scalar, .all), .moveComponent(scalar, into: .root, at: .first), + .setDictionaryEntry(scalar, key: "k", value: .string("v")), + ] { + expectManifestFailure("manifest.edit.readOnly") { try doc.preparing([edit]) } } } +} - @Test func plannerOmissionsFailTheFinalComparison() throws { - var next = Declaration(sources: ["s": local]) - next.watch = ["s"] - expectManifestFailure("manifest.edit.mismatch") { - try DeclarationEditPlan.bytes( - replacing: Declaration(), with: next, - in: Array((manifestHeader + "let agents = Agents()").utf8), - identity: DocumentIdentity("manifest"), environment: projectionEnvironment, - planning: { Array($0.dropLast()) }) - } - } - - @Test func repeatedEditsOfACommentedManifestKeepUnrelatedBytes() throws { - var body = """ - // Team manifest: keep this header. - let agents = Agents( - // Recipients for everything below. - defaultAgents: [.claudeCode, .codex], - sources: [ - // Shared team skills. - .source(name: "team", url: "https://github.com/team/skills", from: "1.0.0"), - // Local drafts stay editable. - .source(name: "drafts", path: "./drafts"), - ], - components: [ - // Everything from the team. - .skills( - // pinned upstream - source: "team" - ), - // Drafts linked for editing. - .skills(source: "drafts", mode: .edit), - // House rules. - .instructions( - sections: [ - "guide", // first - .section(name: "rules", source: "team"), - ] - ), - ], - // Watched for upstream changes. - watch: ["team"] - ) - // trailing note - - """ - let kept = [ - "// Team manifest: keep this header.\nlet agents = Agents(\n", - " // Recipients for everything below.\n defaultAgents: [.claudeCode, .codex],\n", - " // Shared team skills.\n .source(name: \"team\", url: \"https://github.com/team/skills\", from: \"1.0.0\"),\n", - " // Everything from the team.\n .skills(\n // pinned upstream\n source: \"team\"", - " // House rules.\n .instructions(\n sections: [\n \"guide\", // first\n", - " .section(name: \"rules\", source: \"team\"),\n", - " // Watched for upstream changes.\n watch: [", - ")\n// trailing note\n", - ] - func expectKept(_ text: String, sourceLocation: SourceLocation = #_sourceLocation) { - var remainder = text[...] - for segment in kept { - guard let range = remainder.range(of: segment) else { - Issue.record("missing unchanged bytes: \(segment)", sourceLocation: sourceLocation) - return - } - remainder = remainder[range.upperBound...] - } - } - let steps: [(inout Declaration) throws -> Void] = [ - { try $0.updateSkills { $0?["team"]?.exclude = ["deprecated"] } }, - { - $0.sources["extra"] = SourceDeclaration(kind: .git, location: "github.com/team/extra") - try $0.updateSkills { $0?["extra"] = SkillDeclaration(select: .names(["one"])) } - }, - { - try $0.updateInstructions { $0?.sections.append("extra:style") } - try $0.updateInstructions { $0?.agents = [.codex] } - }, - { $0.watch?.append("extra") }, - { - $0.sources["drafts"] = nil - try $0.updateSkills { $0?["drafts"] = nil } - }, - { - try $0.updateInstructions { - $0?.chatgpt = ["weekly": PromptDeclaration(sections: ["guide"])] - } - }, - ] - for step in steps { - body = try changed(body, step) - expectKept(body) - } - #expect(!body.contains("drafts")) +extension EditPlanTests { + @Test func blockScalarHeaderCommentsAndFollowingFieldsSurviveReplacement() throws { + let doc = try document( + "version: 1\ncomponents:\n - kind: subagent\n name: a\n description: d\n prompt: |- # owned header\n before\n model: keep\n# tail\n" + ) + let change = try doc.preparing([ + .replaceComponent( + #require(doc.node(at: "/components/0")), + with: .subagent(name: "a", description: "d", prompt: .literal("after"), model: "keep")) + ]) + let text = String(decoding: change.bytes, as: UTF8.self) + #expect(text.contains("# owned header\n model: keep\n# tail\n")) #expect( - body == """ - // Team manifest: keep this header. - let agents = Agents( - // Recipients for everything below. - defaultAgents: [.claudeCode, .codex], - sources: [ - // Shared team skills. - .source(name: "team", url: "https://github.com/team/skills", from: "1.0.0"), - .source(name: "extra", url: "https://github.com/team/extra"), - ], - components: [ - // Everything from the team. - .skills( - // pinned upstream - source: "team", - exclude: ["deprecated"] - ), - .skills( - source: "extra", - select: ["one"] - ), - // House rules. - .instructions( - sections: [ - "guide", // first - .section(name: "rules", source: "team"), - .section(name: "style", source: "extra"), - ], - chatGPT: [ - .prompt( - name: "weekly", - sections: ["guide"] - ), - ], - agents: [.codex] - ), - ], - // Watched for upstream changes. - watch: ["extra", "team"] - ) - // trailing note - - """) + try DeclarationDocument(bytes: change.bytes, identity: DocumentIdentity("manifest")) + .declaration == change.expectedDeclaration) } } diff --git a/Tests/AgentsManifestTests/EditingTests.swift b/Tests/AgentsManifestTests/EditingTests.swift deleted file mode 100644 index cab0950..0000000 --- a/Tests/AgentsManifestTests/EditingTests.swift +++ /dev/null @@ -1,763 +0,0 @@ -import AgentsCore -import AgentsDescription -import Foundation -import Testing - -@testable import AgentsManifest - -func edited(_ doc: DeclarationDocument, _ edits: [ManifestEdit]) throws -> DeclarationDocument { - let change = try doc.preparing(edits) - #expect(change.originalDigest == doc.digest) - var applied = doc.bytes - for patch in change.patches.reversed() { - applied.replaceSubrange(patch.range, with: patch.replacement) - } - #expect(applied == change.bytes) - for pair in zip(change.patches, change.patches.dropFirst()) { - #expect(pair.0.range.upperBound <= pair.1.range.lowerBound) - } - let result = try DeclarationDocument(bytes: change.bytes, identity: DocumentIdentity("manifest")) - #expect(result.declaration == change.expectedDeclaration) - return result -} - -@Suite("Manifest document editing") -struct EditingTests { - @Test(arguments: [(" ", "\n"), (" ", "\r\n"), ("\t", "\n"), ("\t", "\r\n")]) - func multilineArgumentInsertionExpandsOnlyItsCall(_ indent: String, _ newline: String) throws { - let prefix = - manifestHeader + """ - let alias = "fixture" - let recipients: [Agent] = [.codex] - let agents = Agents( - sources: [.source(name: "fixture", path: "./fixture")], - components: [ - // Keep this component. - - """ - let suffix = ", // Keep its neighbor.\n .instructions(sections: []),\n ]\n)" - let old = - ".skills(source : alias /* source */, /* source note */ exclude: [] /* exclude */, agents: recipients)" - let text = (prefix + " " + old + suffix).replacingOccurrences(of: " ", with: indent) - .replacingOccurrences(of: "\n", with: newline) - let doc = try DeclarationDocument( - bytes: Array(text.utf8), identity: DocumentIdentity("manifest")) - let override = SkillOverride.skill(name: "review", mode: .copy, agents: [.cursor]) - let handle = try #require(doc.node(at: "/components/0")) - let change = try doc.preparing([.upsertSkillOverride(handle, override)]) - let expanded = """ - .skills( - source : alias /* source */, /* source note */ - exclude: [] /* exclude */, - overrides: [ - .skill( - name: "review", - mode: .copy, - agents: [.cursor] - ), - ], - agents: recipients - ) - """ - .replacingOccurrences(of: " ", with: indent) - .replacingOccurrences(of: "\n", with: newline) - #expect( - String(decoding: change.bytes, as: UTF8.self) - == text.replacingOccurrences(of: old, with: expanded)) - let call = doc.admission.nodes[handle.syntax].range - #expect( - change.patches.allSatisfy { - $0.range.lowerBound >= call.lowerBound && $0.range.upperBound <= call.upperBound - }) - let result = try DeclarationDocument( - bytes: change.bytes, identity: DocumentIdentity("manifest")) - #expect(result.declaration == change.expectedDeclaration) - let noOp = try result.preparing([ - .upsertSkillOverride(result.node(at: "/components/0")!, override) - ]) - #expect(noOp.bytes == result.bytes && noOp.patches.isEmpty) - let batched = try doc.preparing(operations: [ - .edit(.upsertSkillOverride(handle, override)), - .insertElement(.text("unused"), into: doc.node(at: "/components/0/exclude")!, at: .last), - ]) - #expect( - String(decoding: batched.bytes, as: UTF8.self).contains("exclude: [\"unused\"] /* exclude */") - ) - } - - @Test func multilineArgumentCanPrecedeTheFirstExistingArgument() throws { - let doc = try document("let agents = Agents(watch: [])") - let result = try edited(doc, [.upsertSource(.source(name: "s", path: "./s"))]) - #expect( - String(decoding: result.bytes, as: UTF8.self) == manifestHeader + """ - let agents = Agents( - sources: [ - .source(name: "s", path: "./s"), - ], - watch: [] - ) - """) - } - - @Test func multilineArgumentAppendsToSingleLineCallsAndScalarEditsStayInline() throws { - let old = ".skills(source: \"fixture\", exclude: [])" - let doc = try document( - "let agents = Agents(sources: [.source(name: \"fixture\", path: \"./fixture\")], components: [\(old)])" - ) - let handle = try #require(doc.node(at: "/components/0")) - let result = try edited( - doc, [.upsertSkillOverride(handle, .skill(name: "review", mode: .copy))]) - let expanded = """ - .skills( - source: "fixture", - exclude: [], - overrides: [ - .skill(name: "review", mode: .copy) - ] - ) - """ - #expect( - result.bytes - == Array( - String(decoding: doc.bytes, as: UTF8.self).replacingOccurrences(of: old, with: expanded) - .utf8)) - let scalar = try doc.preparing(operations: [ - .setArgument(handle, field: "mode", value: InstallMode.copy.constructionValue) - ]) - #expect( - String(decoding: scalar.bytes, as: UTF8.self) - == String(decoding: doc.bytes, as: UTF8.self).replacingOccurrences( - of: old, with: ".skills(source: \"fixture\", exclude: [], mode: .copy)")) - let commented = try document( - "let agents = Agents(sources: [.source(name: \"fixture\", path: \"./fixture\")], components: [.skills(source: \"fixture\" /* trailing */)])" - ) - expectManifestFailure("manifest.edit.readOnly") { - try commented.preparing([ - .upsertSkillOverride( - commented.node(at: "/components/0")!, .skill(name: "review", mode: .copy)) - ]) - } - #expect(try doc.preparing([.setSkillSelection(handle, .all)]).bytes == doc.bytes) - } - - @Test func rootArgumentsUseSignatureOrderAndCanonicalSourceRequirements() throws { - let initial = try document("let agents = Agents()") - let result = try edited( - initial, - [ - .setWatch(["rules"]), .setExports(["review"]), - .upsertGroup(.group(name: "review")), - .upsertSource(.source(name: "rules", url: "intranet/team.git", "1.2.0"..<"1.3.0")), - .setDefaultAgents([.codex]), - ]) - let source = String(decoding: result.bytes, as: UTF8.self) - let order = ["defaultAgents:", "exports:", "sources:", "groups:", "watch:"].map { - source.range(of: $0)!.lowerBound - } - #expect(zip(order, order.dropFirst()).allSatisfy { $0 < $1 }) - #expect(source.contains("https://intranet/team.git")) - #expect(source.contains(".upToNextMinor(from: \"1.2.0\")")) - #expect(result.declaration.defaultAgents == ["codex"]) - let major = try edited( - result, - [.upsertSource(.source(name: "rules", url: "https://intranet/team.git", "1.2.0"..<"2.0.0"))]) - #expect(String(decoding: major.bytes, as: UTF8.self).contains("from: \"1.2.0\"")) - let range = try edited( - major, - [.upsertSource(.source(name: "rules", url: "https://intranet/team.git", "1.2.0"..<"1.8.0"))]) - #expect(String(decoding: range.bytes, as: UTF8.self).contains("\"1.2.0\"..<\"1.8.0\"")) - } - - @Test func everyComponentSectionPromptAndOverrideOperation() throws { - var doc = try document( - "let agents = Agents(sources: [.source(name: \"s\", path: \"s\")], components: [.skills(source: \"s\"), .instructions(sections: [\"guide\", \"second\"])], groups: [.group(name: \"g\")])" - ) - doc = try edited( - doc, [.insertComponent(.ignore(name: "ignore", patterns: []), into: .root, at: .first)]) - doc = try edited( - doc, - [ - .replaceComponent( - doc.node(at: "/components/0")!, with: .ignore(name: "replacement", patterns: [".build/"])) - ]) - doc = try edited(doc, [.setSkillSelection(doc.node(at: "/components/1")!, ["a", "b"])]) - doc = try edited( - doc, [.upsertSkillOverride(doc.node(at: "/components/1")!, .skill(name: "a", mode: .copy))]) - doc = try edited(doc, [.removeSkillOverride(doc.node(at: "/components/1")!, name: "a")]) - doc = try edited( - doc, [.insertSection("third", into: doc.node(at: "/components/2")!, at: .last)]) - doc = try edited(doc, [.moveSection(doc.node(at: "/components/2/sections/2")!, at: .first)]) - #expect( - doc.declaration.components[2]["sections"]?.elements?.first?.record?["name"] - == .string("third")) - doc = try edited(doc, [.removeSection(doc.node(at: "/components/2/sections/1")!)]) - doc = try edited( - doc, - [.upsertPrompt(doc.node(at: "/components/2")!, .prompt(name: "weekly", sections: ["guide"]))]) - doc = try edited(doc, [.removePrompt(doc.node(at: "/components/2")!, name: "weekly")]) - doc = try edited( - doc, - [ - .moveComponent( - doc.node(at: "/components/0")!, into: .group(doc.node(at: "/groups/0")!), at: .last) - ]) - #expect(doc.declaration.components.count == 2) - #expect(doc.declaration.groups[0]["components"]?.elements?.count == 1) - doc = try edited(doc, [.insertGroupReference("g", into: .root, at: .first)]) - doc = try edited(doc, [.removeGroupReference(doc.node(at: "/uses/0")!)]) - doc = try edited(doc, [.removeComponent(doc.node(at: "/groups/0/components/0")!)]) - doc = try edited(doc, [.removeGroup(name: "g")]) - doc = try edited( - doc, [.removeComponent(doc.node(at: "/components/0")!), .removeSource(alias: "s")]) - #expect(doc.declaration.sources.isEmpty) - } - - @Test func dictionaryEntryEditsPreserveUnrelatedBytesAndHandleNegativeBoundaries() throws { - var doc = try document( - "let agents = Agents(components: [.lspServer(name: \"s\", run: .executable(\"tool\"), languages: [\".swift\": \"swift\"], initializationOptions: [\"x\":/* note */0, \"other\": true])])" - ) - let original = String(decoding: doc.bytes, as: UTF8.self) - doc = try edited( - doc, - [ - .setDictionaryEntry( - doc.node(at: "/components/0/initializationOptions")!, key: "x", value: .configuration(-1)) - ]) - let replaced = String(decoding: doc.bytes, as: UTF8.self) - #expect(replaced == original.replacingOccurrences(of: "/* note */0", with: "/* note */ -1")) - doc = try edited( - doc, - [ - .setDictionaryEntry( - doc.node(at: "/components/0/initializationOptions")!, key: "added", - value: .configuration(["nested": nil])) - ]) - doc = try edited( - doc, - [.removeDictionaryEntry(doc.node(at: "/components/0/initializationOptions")!, key: "added")]) - #expect(String(decoding: doc.bytes, as: UTF8.self).contains("\"other\": true")) - expectManifestFailure("manifest.type") { - try doc.preparing([ - .setDictionaryEntry( - doc.node(at: "/components/0/languages")!, key: ".js", value: .integer(3)) - ]) - } - } - - @Test func wholeDefinitionReplacementAcceptsAllTransitiveUses() throws { - let doc = try document( - "let base: [String] = [\"one\"]\nlet alias = base\nlet agents = Agents(components: [.ignore(name: \"a\", patterns: base), .ignore(name: \"b\", patterns: alias)])" - ) - let handle = doc.constant(named: "base")! - let uses = doc.uses(ofConstant: "base") - #expect(uses.count == 3) - expectManifestFailure("manifest.edit.impact") { - try doc.preparing([ - .replaceConstant(handle, with: .array([.string("two")]), acceptingUses: []) - ]) - } - let changed = try doc.preparing([ - .replaceConstant(handle, with: .array([.string("two")]), acceptingUses: uses) - ]) - #expect(changed.impactedReferences.count == 3) - let result = try DeclarationDocument( - bytes: changed.bytes, identity: DocumentIdentity("manifest")) - #expect(result.declaration.components[0]["patterns"] == .array([.string("two")])) - #expect(result.declaration.components[1]["patterns"] == .array([.string("two")])) - } - - @Test func commentsBOMCRLFFinalNewlineAndUnchangedRangesSurvive() throws { - let text = - "\u{feff}" - + (manifestHeader - + "// file\nlet agents = Agents(\n components: [\n // first owner\n .ignore(name: \"first\", patterns: []), // trailing owner\n\n // second owner\n .ignore(name: \"second\", patterns: [])\n ]\n)") - .replacingOccurrences(of: "\n", with: "\r\n") - let doc = try DeclarationDocument( - bytes: Array(text.utf8), identity: DocumentIdentity("manifest")) - let result = try edited(doc, [.removeComponent(doc.node(at: "/components/0")!)]) - let source = String(decoding: result.bytes, as: UTF8.self) - #expect(source.hasPrefix("\u{feff}// agents-tools-version: 1.0\r\n")) - #expect(!source.hasSuffix("\n")) - #expect(!source.contains("first owner")) - #expect(!source.contains("trailing owner")) - #expect(source.contains("// second owner\r\n .ignore(name: \"second\"")) - #expect(source.contains("// file\r\n")) - } - - @Test func equivalentRangeSourceUpsertKeepsOriginalBytes() throws { - let doc = try document( - "let agents = Agents(sources: [.source(name: \"b\", path: \"./b\", from: \"1.2.0\")])") - let change = try doc.preparing([ - .upsertSource(.source(name: "b", path: "./b", "1.2.0"..<"2.0.0")) - ]) - #expect(change.bytes == doc.bytes && change.patches.isEmpty) - } - - @Test func printedWidthCountsLabelsCommasAndUTF8Bytes() { - let printer = CanonicalPrinter() - let atBoundary = Source.source(name: String(repeating: "a", count: 47), path: "p") - .constructionValue - let overBoundary = Source.source(name: String(repeating: "a", count: 48), path: "p") - .constructionValue - #expect(!printer.render(atBoundary, indentation: " ").contains("\n")) - #expect(printer.render(overBoundary, indentation: " ").contains("\n")) - let unicode = Source.source(name: String(repeating: "é", count: 24), path: "p") - .constructionValue - #expect(printer.render(unicode, indentation: " ").contains("\n")) - } - - @Test func editabilityReportsExactlyTheValuesTheEditorChangesDirectly() throws { - let doc = try document( - """ - let shared: [String] = ["x"] - let base = "guide" - let agents = Agents( - defaultAgents: [.codex, .claudeCode], - exports: ["review"], - sources: [ - .source(name: "team", url: "https://e.org/team.git", branch: "main", subpath: "skills"), - .source(name: "local", path: "./drafts", "1.2.0"..<"1.5.0"), - .source(name: "pinned", url: "https://e.org/p.git", from: "1.0.0"), - ], - components: [ - .skills( - source: "team", select: ["a", "b"], exclude: shared, mode: .copy, - overrides: [.skill(name: "a", mode: .link, agents: [.cursor])], agents: [.codex]), - .skills(source: "local"), - .instructions( - sections: ["guide", .section(name: base, source: "team")], - chatGPT: [.prompt(name: "weekly", sections: ["guide"], append: "notes/w.md")], - agents: []), - ], - groups: [ - .group( - name: "review", - components: [ - .ignore(name: "i", patterns: ["a"] + shared), - .lspServer( - name: "l", run: .executable("tool", arguments: ["-v"]), - languages: [".swift": "swift"], - initializationOptions: [ - "k": 1, "o": ["n": true], "c": .object(["m": nil]), "a": [1, "s"], - ]), - ]) - ], - watch: ["team"] - ) - """) - var checked = (direct: 0, readOnly: 0) - for pointer in doc.values.keys.sorted() - where !pointer.isEmpty && !pointer.hasPrefix("/constants/") { - let node = try #require(doc.node(at: pointer)) - let slash = pointer.lastIndex(of: "/")! - let parent = String(pointer[.. 80 && checked.readOnly > 30) - for pointer in ["/components/0/mode", "/defaultAgents/0", "/components/1/agents"] { - #expect(doc.editability(of: doc.node(at: pointer)!) == .direct, "\(pointer)") - } - for pointer in ["/components/0/exclude", "/groups/0/components/0/patterns"] { - #expect(doc.editability(of: doc.node(at: pointer)!) != .direct, "\(pointer)") - } - } - - @Test func noOpsKeepOriginalBytesAndUnsafeEditsPublishNothing() throws { - let doc = try document( - "let agents = Agents(defaultAgents: nil, sources: [.source(name: \"s\", url: \"https://example.org/s.git\", \"1.2.0\" ..< \"2.0.0\")], components: [/*container*/])" - ) - let noOp = try doc.preparing([ - .setDefaultAgents(nil), - .upsertSource(.source(name: "s", url: "https://example.org/s.git", from: "1.2.0")), - ]) - #expect(noOp.bytes == doc.bytes) - #expect(noOp.patches.isEmpty) - expectManifestFailure("manifest.edit.readOnly") { - try doc.preparing([.insertComponent(.instructions(), into: .root, at: .first)]) - } - let unrelated = try document("let agents = Agents()") - expectManifestFailure("manifest.edit.stale") { - try unrelated.preparing([.removeComponent(doc.node(at: "/sources/0")!)]) - } - #expect(doc.bytes == noOp.bytes) - } - - @Test func symbolicReferencesNeedCompleteRepairBatch() throws { - let doc = try document( - "let agents = Agents(exports: [\"g\"], sources: [.source(name: \"s\", path: \"s\")], groups: [.group(name: \"g\", components: [.skills(source: \"s\")])], uses: [\"g\"], watch: [\"s\"])" - ) - expectManifestFailure("manifest.domain") { try doc.preparing([.removeSource(alias: "s")]) } - expectManifestFailure("manifest.group.missing") { try doc.preparing([.removeGroup(name: "g")]) } - let repaired = try edited( - doc, - [ - .removeSource(alias: "s"), .removeGroup(name: "g"), - .removeGroupReference(doc.node(at: "/uses/0")!), .setExports([]), .setWatch([]), - ]) - #expect(repaired.declaration.sources.isEmpty) - #expect(repaired.declaration.groups.isEmpty) - } - - @Test func replacementKeepsVersionSlotAndNegativeConstantBoundariesValid() throws { - let doc = try document( - "let number: [Int] = [/*keep*/0]\nlet minimum: Version = \"1.2.0\"\nlet agents = Agents(sources: [.source(name: \"s\", path: \"s\", from: minimum)])" - ) - let changed = try edited( - doc, - [ - .replaceConstant( - doc.constant(named: "minimum")!, with: .version("1.3.0"), - acceptingUses: doc.uses(ofConstant: "minimum")) - ]) - #expect( - changed.declaration.sources[0]["requirement"] == .requirement(.upToNextMajor(from: "1.3.0"))) - let n = try document("let number: [Int] = [/*keep*/0]\nlet agents = Agents()") - let scalar = try document("let number = 0\nlet agents = Agents()") - let negative = try edited( - scalar, - [.replaceConstant(scalar.constant(named: "number")!, with: .integer(-1), acceptingUses: [])]) - #expect(String(decoding: negative.bytes, as: UTF8.self).contains("let number = -1")) - expectManifestFailure("manifest.edit.readOnly") { - try n.preparing([ - .replaceConstant( - n.constant(named: "number")!, with: .array([.integer(-1)]), acceptingUses: []) - ]) - } - } - @Test func movesCarryLeadingAndTrailingCommentsAndDictionaryEntriesOwnTheirTrivia() throws { - let doc = try document( - """ - let agents = Agents( - components: [ - // follows first - .ignore(name: "first", patterns: []), // inline owner - .ignore(name: "second", patterns: []) - ], - groups: [.group(name: "g")] - ) - """) - let moved = try edited( - doc, - [ - .moveComponent( - doc.node(at: "/components/0")!, into: .group(doc.node(at: "/groups/0")!), at: .last) - ]) - let text = String(decoding: moved.bytes, as: UTF8.self) - #expect(text.range(of: "// follows first")!.lowerBound > text.range(of: "groups:")!.lowerBound) - #expect(text.contains("// inline owner")) - let dictionary = try document( - """ - let agents = Agents(components: [.lspServer( - name: "s", run: .executable("tool"), languages: [".swift": "swift"], - initializationOptions: [ - // remove with x - "x": /* inside x */ 1, // after x - - // keep with y - "y": true - ] - )]) - """) - let removed = try edited( - dictionary, - [ - .removeDictionaryEntry( - dictionary.node(at: "/components/0/initializationOptions")!, key: "x") - ]) - let result = String(decoding: removed.bytes, as: UTF8.self) - #expect(!result.contains("remove with x")) - #expect(!result.contains("inside x")) - #expect(!result.contains("after x")) - #expect(result.contains("keep with y")) - } - - @Test func inferredConstantsRetainContextDuringReplacement() throws { - let doc = try document( - "let recipient = Agent.codex\nlet agents = Agents(defaultAgents: [recipient])") - let change = try edited( - doc, - [ - .replaceConstant( - doc.constant(named: "recipient")!, with: .agent(.cursor), - acceptingUses: doc.uses(ofConstant: "recipient")) - ]) - #expect(change.declaration.defaultAgents == ["cursor"]) - let array = try document( - "let recipients = [Agent.codex]\nlet agents = Agents(defaultAgents: recipients)") - let changed = try edited( - array, - [ - .replaceConstant( - array.constant(named: "recipients")!, with: .array([.agent(.cursor)]), - acceptingUses: array.uses(ofConstant: "recipients")) - ]) - #expect(changed.declaration.defaultAgents == ["cursor"]) - let unused = try document("let recipient = Agent.codex\nlet agents = Agents()") - let unusedChange = try unused.preparing([ - .replaceConstant( - unused.constant(named: "recipient")!, with: .agent(.cursor), acceptingUses: []) - ]) - #expect(unusedChange.delta.changedPointers.isEmpty) - #expect(!unusedChange.patches.isEmpty) - let changedDefault = try doc.preparing([ - .replaceConstant( - doc.constant(named: "recipient")!, with: .agent(.cursor), - acceptingUses: doc.uses(ofConstant: "recipient")) - ]) - #expect(changedDefault.delta.changedPointers == ["/defaultAgents/0"]) - } - - @Test func consistentFourSpaceIndentationIsInheritedAndConflictsAreRejected() throws { - let doc = try document( - """ - let agents = Agents( - components: [ - .ignore(name: "first", patterns: []), - ] - ) - """) - let change = try edited(doc, [.insertComponent(.instructions(), into: .root, at: .last)]) - #expect(String(decoding: change.bytes, as: UTF8.self).contains("\n .instructions(),")) - let replacement = try edited( - doc, - [.replaceComponent(doc.node(at: "/components/0")!, with: .ignore(name: "new", patterns: []))]) - #expect( - String(decoding: replacement.bytes, as: UTF8.self).contains("\n name: \"new\",")) - let withoutComma = try document( - """ - let agents = Agents( - components: [ - .ignore(name: "first", patterns: []) - ] - ) - """) - let longPattern = String(repeating: "x", count: 80) - let replaced = try edited( - withoutComma, - [ - .replaceComponent( - withoutComma.node(at: "/components/0")!, - with: .ignore(name: "new", patterns: [longPattern])) - ]) - #expect(String(decoding: replaced.bytes, as: UTF8.self).contains("\"\(longPattern)\"\n")) - let multiline = try document( - """ - let agents = Agents( - components: [ - .ignore( - name: "first", - patterns: [ - "first", - ] - ), - ] - ) - """) - let withComma = try edited( - multiline, - [ - .replaceComponent( - multiline.node(at: "/components/0")!, - with: .ignore(name: "new", patterns: [longPattern])) - ]) - #expect(String(decoding: withComma.bytes, as: UTF8.self).contains("\"\(longPattern)\",\n")) - let mixed = try document( - """ - let agents = Agents( - components: [ - .ignore(name: "first", patterns: []), - .ignore(name: "second", patterns: []), - ] - ) - """) - expectManifestFailure("manifest.edit.readOnly") { - try mixed.preparing([.insertComponent(.instructions(), into: .root, at: .last)]) - } - } - - @Test func configurationDictionariesKeepValueKeysAndAllowEntryEdits() throws { - for expression in ["[\"value\": 1, \"other\": 2]", ".object([\"value\": 1, \"other\": 2])"] { - let body = - "let agents = Agents(components: [.lspServer(name: \"s\", run: .executable(\"tool\"), languages: [\".swift\": \"swift\"], initializationOptions: [\"options\": " - + expression + "])])" - let doc = try document(body) - let handle = try #require(doc.node(at: "/components/0/initializationOptions/options")) - #expect(doc.editability(of: handle) == .direct) - let changed = try edited(doc, [.setDictionaryEntry(handle, key: "other", value: .integer(3))]) - #expect( - changed.bytes - == Array( - (manifestHeader + body.replacingOccurrences(of: "\"other\": 2", with: "\"other\": 3")) - .utf8)) - let removed = try edited( - changed, - [ - .removeDictionaryEntry( - changed.node(at: "/components/0/initializationOptions/options")!, key: "value") - ]) - #expect(removed.node(at: "/components/0/initializationOptions/options/value/other") != nil) - } - } - - @Test func replacingAnOwnerRejectsAnOverlappingChildHandle() throws { - let doc = try document( - "let agents = Agents(components: [.instructions(sections: [\"guide\"])])") - expectManifestFailure("manifest.edit.overlap") { - try doc.preparing([ - .replaceComponent(doc.node(at: "/components/0")!, with: .ignore(name: "x", patterns: [])), - .removeSection(doc.node(at: "/components/0/sections/0")!), - ]) - } - } - - @Test func movesPreserveCRLFAndIndentEveryOwnedCommentLine() throws { - let before = """ - let agents = Agents( - components: [ - // first owner - .ignore(name: "first", patterns: []), // inline owner - // second owner - .ignore(name: "second", patterns: []), - .instructions(), - ] - ) - """ - let expected = """ - let agents = Agents( - components: [ - // second owner - .ignore(name: "second", patterns: []), - // first owner - .ignore(name: "first", patterns: []), // inline owner - .instructions(), - ] - ) - """ - for newline in ["\n", "\r\n"] { - let bytes = Array( - (manifestHeader + before).replacingOccurrences(of: "\n", with: newline).utf8) - let doc = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) - let moved = try edited( - doc, - [ - .moveComponent( - doc.node(at: "/components/0")!, into: .root, at: .before(doc.node(at: "/components/2")!) - ) - ]) - #expect( - moved.bytes - == Array((manifestHeader + expected).replacingOccurrences(of: "\n", with: newline).utf8)) - } - } - - @Test func movesReindentOwnedTriviaAtADifferentContainerDepth() throws { - let before = """ - let agents = Agents( - components: [ - // follows first - .ignore(name: "first", patterns: []), // inline owner - ], - groups: [ - .group( - name: "g", - components: [ - .instructions(), - ] - ), - ] - ) - """ - let expected = """ - let agents = Agents( - components: [ - ], - groups: [ - .group( - name: "g", - components: [ - .instructions(), - // follows first - .ignore(name: "first", patterns: []), // inline owner - ] - ), - ] - ) - """ - let doc = try DeclarationDocument( - bytes: Array((manifestHeader + before).replacingOccurrences(of: "\n", with: "\r\n").utf8), - identity: DocumentIdentity("manifest")) - let moved = try edited( - doc, - [ - .moveComponent( - doc.node(at: "/components/0")!, into: .group(doc.node(at: "/groups/0")!), at: .last) - ]) - #expect( - moved.bytes - == Array((manifestHeader + expected).replacingOccurrences(of: "\n", with: "\r\n").utf8)) - } - - @Test func dictionaryPointersPreserveEscapedAndEmptyKeySegments() throws { - let doc = try document( - "let agents = Agents(components: [.lspServer(name: \"s\", run: .executable(\"tool\"), languages: [\".swift\": \"swift\"], initializationOptions: [\"\": 1, \"a/b~c\": 2])])" - ) - let root = "/components/0/initializationOptions" - #expect(doc.node(at: root + "/") != nil) - #expect(doc.node(at: root + "/a~1b~0c") != nil) - let changed = try edited( - doc, - [ - .setDictionaryEntry(doc.node(at: root)!, key: "", value: .integer(3)), - .setDictionaryEntry(doc.node(at: root)!, key: "a/b~c", value: .integer(4)), - ]) - #expect( - changed.bytes - == Array( - String(decoding: doc.bytes, as: UTF8.self).replacingOccurrences( - of: "\"\": 1", with: "\"\": 3" - ).replacingOccurrences(of: "\"a/b~c\": 2", with: "\"a/b~c\": 4").utf8)) - } - - @Test func expectedDeclarationComparisonRejectsDivergentIntent() throws { - let doc = try document("let agents = Agents()") - for edits: [ManifestEdit] in [[], [.insertComponent(.instructions(), into: .root, at: .last)]] { - let editor = DocumentEditor(document: doc) - editor.expected = Agents(defaultAgents: [.codex]).constructionValue - expectManifestFailure("manifest.edit.mismatch") { try editor.prepare(edits) } - #expect(doc.bytes == Array((manifestHeader + "let agents = Agents()").utf8)) - } - } - -} diff --git a/Tests/AgentsManifestTests/ExpansionBudgetTests.swift b/Tests/AgentsManifestTests/ExpansionBudgetTests.swift index 879dc7a..e13babf 100644 --- a/Tests/AgentsManifestTests/ExpansionBudgetTests.swift +++ b/Tests/AgentsManifestTests/ExpansionBudgetTests.swift @@ -9,9 +9,8 @@ struct ExpansionBudgetTests { let document = try DeclarationDocument( bytes: Array( """ - // agents-tools-version: 1.0 - import AgentsDescription - let agents = Agents(components: [.command(name: "review", description: "Review", prompt: "p")]) + version: 1 + components: [{"kind": "command", "name": "review", "description": "Review", "prompt": "p"}] """.utf8), identity: DocumentIdentity("producer")) let record = try #require(document.declaration.components.first) let locations = document.sourceMap.entries.filter { @@ -33,9 +32,8 @@ struct ExpansionBudgetTests { let document = try DeclarationDocument( bytes: Array( """ - // agents-tools-version: 1.0 - import AgentsDescription - let agents = Agents(components: [.command(name: "review", description: "Review", prompt: "p")]) + version: 1 + components: [{"kind": "command", "name": "review", "description": "Review", "prompt": "p"}] """.utf8), identity: DocumentIdentity(String(repeating: "source", count: 5_000))) let record = try #require(document.declaration.components.first) let locations = document.sourceMap.entries.filter { diff --git a/Tests/AgentsManifestTests/Fixtures/ConsumerExample.dump.json b/Tests/AgentsManifestTests/Fixtures/ConsumerExample.dump.json deleted file mode 100644 index 362af07..0000000 --- a/Tests/AgentsManifestTests/Fixtures/ConsumerExample.dump.json +++ /dev/null @@ -1,5611 +0,0 @@ -{ - "declaration": { - "components": [ - { - "agents": null, - "condition": null, - "exclude": [ - "experimental" - ], - "kind": "skills", - "mode": "copy", - "native": {}, - "overrides": [ - { - "agents": [ - "codex" - ], - "mode": "link", - "name": "testing" - } - ], - "select": "all", - "source": "rules" - }, - { - "agents": null, - "condition": { - "agents": [ - "claude-code" - ], - "platforms": null, - "scopes": [ - "project" - ] - }, - "exclude": [], - "kind": "skills", - "mode": "edit", - "native": {}, - "overrides": [], - "select": [ - "draft" - ], - "source": "drafts" - }, - { - "agents": null, - "chatGPT": [ - { - "append": "notes/weekly.md", - "condition": null, - "name": "weekly", - "sections": [ - { - "condition": null, - "name": "guide", - "source": null - } - ] - } - ], - "condition": null, - "kind": "instructions", - "native": {}, - "sections": [ - { - "condition": null, - "name": "guide", - "source": null - }, - { - "condition": null, - "name": "engineering", - "source": "rules" - } - ] - }, - { - "agents": [ - "claude-code" - ], - "condition": null, - "kind": "mcpServer", - "name": "workspace", - "native": {}, - "transport": { - "arguments": [ - "serve" - ], - "environment": { - "LOG_LEVEL": { - "kind": "literal", - "value": "info" - }, - "TOKEN": { - "kind": "secret", - "value": "workspace-token" - } - }, - "executable": "workspace-tools", - "kind": "stdio", - "workingDirectory": null - } - }, - { - "agents": [ - "opencode" - ], - "condition": null, - "kind": "mcpServer", - "name": "reference", - "native": {}, - "transport": { - "headers": { - "Authorization": { - "kind": "environment", - "value": "MCP_AUTH" - } - }, - "kind": "streamableHTTP", - "url": "https://example.org/mcp" - } - }, - { - "agents": [ - "claude-code" - ], - "condition": { - "agents": null, - "platforms": null, - "scopes": [ - "project" - ] - }, - "event": { - "kind": "afterTool" - }, - "kind": "hook", - "matcher": null, - "name": "format", - "native": {}, - "run": { - "arguments": [ - "format", - "--in-place", - "Sources" - ], - "environment": {}, - "executable": "swift", - "kind": "executable", - "workingDirectory": { - "path": "tools", - "source": "rules" - } - }, - "timeoutSeconds": 30 - }, - { - "agents": [ - "claude-code" - ], - "condition": null, - "description": "Review a selected change.", - "kind": "command", - "name": "review/change", - "native": {}, - "parameters": [ - { - "defaultValue": null, - "description": "The change to review.", - "name": "change" - } - ], - "prompt": { - "kind": "literal", - "value": "Review ${input:change} and cite evidence." - } - }, - { - "agents": [ - "claude-code" - ], - "condition": { - "agents": null, - "platforms": [ - "macos" - ], - "scopes": null - }, - "initializationOptions": { - "backgroundIndexing": { - "kind": "boolean", - "value": true - } - }, - "kind": "lspServer", - "languages": { - ".swift": "swift" - }, - "name": "swift", - "native": {}, - "run": { - "arguments": [], - "environment": {}, - "executable": "sourcekit-lsp", - "kind": "executable", - "workingDirectory": null - } - }, - { - "agents": [ - "claude-code" - ], - "condition": { - "agents": null, - "platforms": null, - "scopes": [ - "project" - ] - }, - "kind": "permissions", - "name": "private-files", - "native": {}, - "rules": [ - { - "kind": "deny", - "operation": { - "kind": "read" - }, - "pattern": "secrets/**" - } - ] - }, - { - "agents": [ - "cursor" - ], - "condition": { - "agents": null, - "platforms": null, - "scopes": [ - "project" - ] - }, - "kind": "ignore", - "name": "build-products", - "native": {}, - "patterns": [ - ".build/", - "DerivedData/" - ], - "purpose": "indexing" - }, - { - "agents": [ - "claude-code" - ], - "condition": { - "agents": null, - "platforms": null, - "scopes": [ - "user" - ] - }, - "exclude": [], - "kind": "plugin", - "mode": "native", - "name": "vendor-tools", - "native": {}, - "path": "plugins/tools", - "select": null, - "source": "vendor" - }, - { - "agents": null, - "condition": { - "agents": null, - "platforms": null, - "scopes": [ - "project" - ] - }, - "exclude": [ - { - "kind": "hook", - "name": "format" - } - ], - "kind": "plugin", - "mode": "components", - "name": "shared-tools", - "native": {}, - "path": "plugins/shared", - "select": null, - "source": "vendor" - } - ], - "defaultAgents": null, - "exports": [], - "groups": [ - { - "components": [ - { - "agents": [ - "claude-code" - ], - "condition": { - "agents": null, - "platforms": [ - "macos" - ], - "scopes": null - }, - "description": "Review correctness and tests.", - "kind": "subagent", - "model": null, - "name": "reviewer", - "native": { - "claude-code/subagent@1": { - "memory": { - "kind": "string", - "value": "project" - } - } - }, - "prompt": { - "kind": "literal", - "value": "Check invariants and explain concrete failures." - }, - "tools": null - } - ], - "condition": null, - "name": "review-tools", - "uses": [ - { - "condition": { - "agents": [ - "codex" - ], - "platforms": null, - "scopes": null - }, - "kind": "exported", - "name": "review", - "source": "team" - } - ] - } - ], - "sources": [ - { - "index": "https://example.org/skills/index.json", - "kind": "index", - "name": "catalog", - "requirement": null, - "subpath": null - }, - { - "kind": "local", - "name": "drafts", - "path": "./draft-skills", - "requirement": null, - "subpath": null - }, - { - "kind": "git", - "name": "rules", - "requirement": { - "from": "1.2.0" - }, - "subpath": null, - "url": "https://example.org/team/rules.git" - }, - { - "kind": "local", - "name": "team", - "path": "./team", - "requirement": null, - "subpath": null - }, - { - "kind": "git", - "name": "vendor", - "requirement": { - "exact": "2.1.0" - }, - "subpath": null, - "url": "https://example.org/vendor/tools.git" - } - ], - "uses": [ - { - "condition": null, - "kind": "local", - "name": "review-tools", - "source": null - } - ], - "watch": [ - "catalog", - "rules" - ] - }, - "diagnostics": [], - "kind": "manifest", - "languageVersion": "1.0", - "locations": [ - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "", - "span": { - "column": 14, - "document": "manifest", - "end": 3467, - "line": 15, - "start": 475 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components", - "span": { - "column": 15, - "document": "manifest", - "end": 3231, - "line": 23, - "start": 865 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0", - "span": { - "column": 5, - "document": "manifest", - "end": 1022, - "line": 24, - "start": 871 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 1022, - "line": 24, - "start": 871 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 1022, - "line": 24, - "start": 871 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/exclude", - "span": { - "column": 33, - "document": "manifest", - "end": 928, - "line": 25, - "start": 912 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/exclude/0", - "span": { - "column": 34, - "document": "manifest", - "end": 927, - "line": 25, - "start": 913 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/0/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 1022, - "line": 24, - "start": 871 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/mode", - "span": { - "column": 57, - "document": "manifest", - "end": 941, - "line": 25, - "start": 936 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/native", - "span": { - "column": 5, - "document": "manifest", - "end": 1022, - "line": 24, - "start": 871 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/overrides", - "span": { - "column": 18, - "document": "manifest", - "end": 1016, - "line": 26, - "start": 960 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/overrides/0", - "span": { - "column": 19, - "document": "manifest", - "end": 1015, - "line": 26, - "start": 961 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/overrides/0/agents", - "span": { - "column": 64, - "document": "manifest", - "end": 1014, - "line": 26, - "start": 1006 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/overrides/0/agents/0", - "span": { - "column": 65, - "document": "manifest", - "end": 1013, - "line": 26, - "start": 1007 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/overrides/0/mode", - "span": { - "column": 49, - "document": "manifest", - "end": 996, - "line": 26, - "start": 991 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/overrides/0/name", - "span": { - "column": 32, - "document": "manifest", - "end": 983, - "line": 26, - "start": 974 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/select", - "span": { - "column": 5, - "document": "manifest", - "end": 1022, - "line": 24, - "start": 871 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/source", - "span": { - "column": 15, - "document": "manifest", - "end": 901, - "line": 25, - "start": 894 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1", - "span": { - "column": 5, - "document": "manifest", - "end": 1164, - "line": 28, - "start": 1028 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 1164, - "line": 28, - "start": 1028 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/condition", - "span": { - "column": 18, - "document": "manifest", - "end": 1158, - "line": 30, - "start": 1110 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/condition/agents", - "span": { - "column": 32, - "document": "manifest", - "end": 1137, - "line": 30, - "start": 1124 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/condition/agents/0", - "span": { - "column": 33, - "document": "manifest", - "end": 1136, - "line": 30, - "start": 1125 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/condition/platforms", - "span": { - "column": 18, - "document": "manifest", - "end": 1158, - "line": 30, - "start": 1110 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/condition/scopes", - "span": { - "column": 55, - "document": "manifest", - "end": 1157, - "line": 30, - "start": 1147 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/condition/scopes/0", - "span": { - "column": 56, - "document": "manifest", - "end": 1156, - "line": 30, - "start": 1148 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/exclude", - "span": { - "column": 5, - "document": "manifest", - "end": 1164, - "line": 28, - "start": 1028 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/1/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 1164, - "line": 28, - "start": 1028 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/mode", - "span": { - "column": 50, - "document": "manifest", - "end": 1091, - "line": 29, - "start": 1086 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/native", - "span": { - "column": 5, - "document": "manifest", - "end": 1164, - "line": 28, - "start": 1028 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides", - "span": { - "column": 5, - "document": "manifest", - "end": 1164, - "line": 28, - "start": 1028 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/select", - "span": { - "column": 33, - "document": "manifest", - "end": 1078, - "line": 29, - "start": 1069 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/select/0", - "span": { - "column": 34, - "document": "manifest", - "end": 1077, - "line": 29, - "start": 1070 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/source", - "span": { - "column": 15, - "document": "manifest", - "end": 1059, - "line": 29, - "start": 1051 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/10", - "span": { - "column": 5, - "document": "manifest", - "end": 3059, - "line": 80, - "start": 2898 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/10/agents", - "span": { - "column": 15, - "document": "manifest", - "end": 3018, - "line": 82, - "start": 3005 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/10/agents/0", - "span": { - "column": 16, - "document": "manifest", - "end": 3017, - "line": 82, - "start": 3006 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/10/condition", - "span": { - "column": 41, - "document": "manifest", - "end": 3053, - "line": 82, - "start": 3031 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/10/condition/agents", - "span": { - "column": 41, - "document": "manifest", - "end": 3053, - "line": 82, - "start": 3031 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/10/condition/platforms", - "span": { - "column": 41, - "document": "manifest", - "end": 3053, - "line": 82, - "start": 3031 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/10/condition/scopes", - "span": { - "column": 55, - "document": "manifest", - "end": 3052, - "line": 82, - "start": 3045 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/10/condition/scopes/0", - "span": { - "column": 56, - "document": "manifest", - "end": 3051, - "line": 82, - "start": 3046 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/10/exclude", - "span": { - "column": 5, - "document": "manifest", - "end": 3059, - "line": 80, - "start": 2898 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/10/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 3059, - "line": 80, - "start": 2898 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/10/mode", - "span": { - "column": 76, - "document": "manifest", - "end": 2989, - "line": 81, - "start": 2982 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/10/name", - "span": { - "column": 13, - "document": "manifest", - "end": 2933, - "line": 81, - "start": 2919 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/10/native", - "span": { - "column": 5, - "document": "manifest", - "end": 3059, - "line": 80, - "start": 2898 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/10/path", - "span": { - "column": 35, - "document": "manifest", - "end": 2956, - "line": 81, - "start": 2941 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/10/select", - "span": { - "column": 5, - "document": "manifest", - "end": 3059, - "line": 80, - "start": 2898 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/10/source", - "span": { - "column": 60, - "document": "manifest", - "end": 2974, - "line": 81, - "start": 2966 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/11", - "span": { - "column": 5, - "document": "manifest", - "end": 3226, - "line": 84, - "start": 3065 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/11/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 3226, - "line": 84, - "start": 3065 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/11/condition", - "span": { - "column": 52, - "document": "manifest", - "end": 3220, - "line": 86, - "start": 3195 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/11/condition/agents", - "span": { - "column": 52, - "document": "manifest", - "end": 3220, - "line": 86, - "start": 3195 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/11/condition/platforms", - "span": { - "column": 52, - "document": "manifest", - "end": 3220, - "line": 86, - "start": 3195 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/11/condition/scopes", - "span": { - "column": 66, - "document": "manifest", - "end": 3219, - "line": 86, - "start": 3209 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/11/condition/scopes/0", - "span": { - "column": 67, - "document": "manifest", - "end": 3218, - "line": 86, - "start": 3210 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/11/exclude", - "span": { - "column": 16, - "document": "manifest", - "end": 3182, - "line": 86, - "start": 3159 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/11/exclude/0", - "span": { - "column": 17, - "document": "manifest", - "end": 3181, - "line": 86, - "start": 3160 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/11/exclude/0/kind", - "span": { - "column": 17, - "document": "manifest", - "end": 3181, - "line": 86, - "start": 3160 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/11/exclude/0/name", - "span": { - "column": 29, - "document": "manifest", - "end": 3180, - "line": 86, - "start": 3172 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/11/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 3226, - "line": 84, - "start": 3065 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/11/mode", - "span": { - "column": 5, - "document": "manifest", - "end": 3226, - "line": 84, - "start": 3065 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/11/name", - "span": { - "column": 13, - "document": "manifest", - "end": 3100, - "line": 85, - "start": 3086 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/11/native", - "span": { - "column": 5, - "document": "manifest", - "end": 3226, - "line": 84, - "start": 3065 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/11/path", - "span": { - "column": 35, - "document": "manifest", - "end": 3124, - "line": 85, - "start": 3108 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/11/select", - "span": { - "column": 5, - "document": "manifest", - "end": 3226, - "line": 84, - "start": 3065 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/11/source", - "span": { - "column": 61, - "document": "manifest", - "end": 3142, - "line": 85, - "start": 3134 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2", - "span": { - "column": 5, - "document": "manifest", - "end": 1300, - "line": 32, - "start": 1170 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 1300, - "line": 32, - "start": 1170 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/chatGPT", - "span": { - "column": 16, - "document": "manifest", - "end": 1294, - "line": 34, - "start": 1226 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/chatGPT/0", - "span": { - "column": 17, - "document": "manifest", - "end": 1293, - "line": 34, - "start": 1227 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/chatGPT/0/append", - "span": { - "column": 65, - "document": "manifest", - "end": 1292, - "line": 34, - "start": 1275 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/chatGPT/0/condition", - "span": { - "column": 17, - "document": "manifest", - "end": 1293, - "line": 34, - "start": 1227 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/chatGPT/0/name", - "span": { - "column": 31, - "document": "manifest", - "end": 1249, - "line": 34, - "start": 1241 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 32, - "document": "manifest", - "end": 95, - "line": 4, - "start": 86 - } - ], - "pointer": "/components/2/chatGPT/0/sections", - "span": { - "column": 51, - "document": "manifest", - "end": 1265, - "line": 34, - "start": 1261 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 32, - "document": "manifest", - "end": 95, - "line": 4, - "start": 86 - }, - { - "column": 33, - "document": "manifest", - "end": 94, - "line": 4, - "start": 87 - } - ], - "pointer": "/components/2/chatGPT/0/sections/0", - "span": { - "column": 51, - "document": "manifest", - "end": 1265, - "line": 34, - "start": 1261 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 32, - "document": "manifest", - "end": 95, - "line": 4, - "start": 86 - }, - { - "column": 33, - "document": "manifest", - "end": 94, - "line": 4, - "start": 87 - } - ], - "pointer": "/components/2/chatGPT/0/sections/0/condition", - "span": { - "column": 51, - "document": "manifest", - "end": 1265, - "line": 34, - "start": 1261 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 32, - "document": "manifest", - "end": 95, - "line": 4, - "start": 86 - }, - { - "column": 33, - "document": "manifest", - "end": 94, - "line": 4, - "start": 87 - } - ], - "pointer": "/components/2/chatGPT/0/sections/0/name", - "span": { - "column": 51, - "document": "manifest", - "end": 1265, - "line": 34, - "start": 1261 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 32, - "document": "manifest", - "end": 95, - "line": 4, - "start": 86 - }, - { - "column": 33, - "document": "manifest", - "end": 94, - "line": 4, - "start": 87 - } - ], - "pointer": "/components/2/chatGPT/0/sections/0/source", - "span": { - "column": 51, - "document": "manifest", - "end": 1265, - "line": 34, - "start": 1261 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 1300, - "line": 32, - "start": 1170 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/2/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 1300, - "line": 32, - "start": 1170 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/native", - "span": { - "column": 5, - "document": "manifest", - "end": 1300, - "line": 32, - "start": 1170 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 16, - "document": "manifest", - "end": 166, - "line": 5, - "start": 111 - } - ], - "pointer": "/components/2/sections", - "span": { - "column": 17, - "document": "manifest", - "end": 1209, - "line": 33, - "start": 1201 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 16, - "document": "manifest", - "end": 166, - "line": 5, - "start": 111 - }, - { - "column": 33, - "document": "manifest", - "end": 94, - "line": 4, - "start": 87 - } - ], - "pointer": "/components/2/sections/0", - "span": { - "column": 17, - "document": "manifest", - "end": 1209, - "line": 33, - "start": 1201 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 16, - "document": "manifest", - "end": 166, - "line": 5, - "start": 111 - }, - { - "column": 33, - "document": "manifest", - "end": 94, - "line": 4, - "start": 87 - } - ], - "pointer": "/components/2/sections/0/condition", - "span": { - "column": 17, - "document": "manifest", - "end": 1209, - "line": 33, - "start": 1201 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 16, - "document": "manifest", - "end": 166, - "line": 5, - "start": 111 - }, - { - "column": 33, - "document": "manifest", - "end": 94, - "line": 4, - "start": 87 - } - ], - "pointer": "/components/2/sections/0/name", - "span": { - "column": 17, - "document": "manifest", - "end": 1209, - "line": 33, - "start": 1201 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 16, - "document": "manifest", - "end": 166, - "line": 5, - "start": 111 - }, - { - "column": 33, - "document": "manifest", - "end": 94, - "line": 4, - "start": 87 - } - ], - "pointer": "/components/2/sections/0/source", - "span": { - "column": 17, - "document": "manifest", - "end": 1209, - "line": 33, - "start": 1201 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 16, - "document": "manifest", - "end": 166, - "line": 5, - "start": 111 - }, - { - "column": 24, - "document": "manifest", - "end": 165, - "line": 5, - "start": 119 - } - ], - "pointer": "/components/2/sections/1", - "span": { - "column": 17, - "document": "manifest", - "end": 1209, - "line": 33, - "start": 1201 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 16, - "document": "manifest", - "end": 166, - "line": 5, - "start": 111 - }, - { - "column": 24, - "document": "manifest", - "end": 165, - "line": 5, - "start": 119 - } - ], - "pointer": "/components/2/sections/1/condition", - "span": { - "column": 17, - "document": "manifest", - "end": 1209, - "line": 33, - "start": 1201 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 16, - "document": "manifest", - "end": 166, - "line": 5, - "start": 111 - }, - { - "column": 24, - "document": "manifest", - "end": 165, - "line": 5, - "start": 119 - }, - { - "column": 39, - "document": "manifest", - "end": 147, - "line": 5, - "start": 134 - } - ], - "pointer": "/components/2/sections/1/name", - "span": { - "column": 17, - "document": "manifest", - "end": 1209, - "line": 33, - "start": 1201 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 16, - "document": "manifest", - "end": 166, - "line": 5, - "start": 111 - }, - { - "column": 24, - "document": "manifest", - "end": 165, - "line": 5, - "start": 119 - }, - { - "column": 62, - "document": "manifest", - "end": 164, - "line": 5, - "start": 157 - } - ], - "pointer": "/components/2/sections/1/source", - "span": { - "column": 17, - "document": "manifest", - "end": 1209, - "line": 33, - "start": 1201 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3", - "span": { - "column": 5, - "document": "manifest", - "end": 1539, - "line": 36, - "start": 1306 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/agents", - "span": { - "column": 15, - "document": "manifest", - "end": 1533, - "line": 42, - "start": 1520 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/agents/0", - "span": { - "column": 16, - "document": "manifest", - "end": 1532, - "line": 42, - "start": 1521 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 1539, - "line": 36, - "start": 1306 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/3/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 1539, - "line": 36, - "start": 1306 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/name", - "span": { - "column": 13, - "document": "manifest", - "end": 1341, - "line": 37, - "start": 1330 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/native", - "span": { - "column": 5, - "document": "manifest", - "end": 1539, - "line": 36, - "start": 1306 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/transport", - "span": { - "column": 18, - "document": "manifest", - "end": 1504, - "line": 38, - "start": 1360 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/transport/arguments", - "span": { - "column": 39, - "document": "manifest", - "end": 1415, - "line": 39, - "start": 1406 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/transport/arguments/0", - "span": { - "column": 40, - "document": "manifest", - "end": 1414, - "line": 39, - "start": 1407 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/transport/environment", - "span": { - "column": 22, - "document": "manifest", - "end": 1496, - "line": 40, - "start": 1438 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/transport/environment/LOG_LEVEL", - "span": { - "column": 73, - "document": "manifest", - "end": 1495, - "line": 40, - "start": 1489 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/3/transport/environment/LOG_LEVEL/kind", - "span": { - "column": 73, - "document": "manifest", - "end": 1495, - "line": 40, - "start": 1489 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/3/transport/environment/LOG_LEVEL/value", - "span": { - "column": 73, - "document": "manifest", - "end": 1495, - "line": 40, - "start": 1489 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/transport/environment/TOKEN", - "span": { - "column": 32, - "document": "manifest", - "end": 1474, - "line": 40, - "start": 1448 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/3/transport/environment/TOKEN/kind", - "span": { - "column": 32, - "document": "manifest", - "end": 1474, - "line": 40, - "start": 1448 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/transport/environment/TOKEN/value", - "span": { - "column": 40, - "document": "manifest", - "end": 1473, - "line": 40, - "start": 1456 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/transport/executable", - "span": { - "column": 9, - "document": "manifest", - "end": 1393, - "line": 39, - "start": 1376 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/3/transport/kind", - "span": { - "column": 18, - "document": "manifest", - "end": 1504, - "line": 38, - "start": 1360 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/transport/workingDirectory", - "span": { - "column": 18, - "document": "manifest", - "end": 1504, - "line": 38, - "start": 1360 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4", - "span": { - "column": 5, - "document": "manifest", - "end": 1749, - "line": 44, - "start": 1545 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/agents", - "span": { - "column": 15, - "document": "manifest", - "end": 1743, - "line": 49, - "start": 1732 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/agents/0", - "span": { - "column": 16, - "document": "manifest", - "end": 1742, - "line": 49, - "start": 1733 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 1749, - "line": 44, - "start": 1545 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/4/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 1749, - "line": 44, - "start": 1545 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/name", - "span": { - "column": 13, - "document": "manifest", - "end": 1580, - "line": 45, - "start": 1569 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/native", - "span": { - "column": 5, - "document": "manifest", - "end": 1749, - "line": 44, - "start": 1545 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/transport", - "span": { - "column": 18, - "document": "manifest", - "end": 1716, - "line": 46, - "start": 1599 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/transport/headers", - "span": { - "column": 50, - "document": "manifest", - "end": 1708, - "line": 47, - "start": 1665 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/transport/headers/Authorization", - "span": { - "column": 68, - "document": "manifest", - "end": 1707, - "line": 47, - "start": 1683 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/4/transport/headers/Authorization/kind", - "span": { - "column": 68, - "document": "manifest", - "end": 1707, - "line": 47, - "start": 1683 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/transport/headers/Authorization/value", - "span": { - "column": 81, - "document": "manifest", - "end": 1706, - "line": 47, - "start": 1696 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/4/transport/kind", - "span": { - "column": 18, - "document": "manifest", - "end": 1716, - "line": 46, - "start": 1599 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/transport/url", - "span": { - "column": 14, - "document": "manifest", - "end": 1654, - "line": 47, - "start": 1629 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5", - "span": { - "column": 5, - "document": "manifest", - "end": 2050, - "line": 51, - "start": 1755 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/agents", - "span": { - "column": 35, - "document": "manifest", - "end": 2006, - "line": 57, - "start": 1993 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/agents/0", - "span": { - "column": 36, - "document": "manifest", - "end": 2005, - "line": 57, - "start": 1994 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/condition", - "span": { - "column": 61, - "document": "manifest", - "end": 2044, - "line": 57, - "start": 2019 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/condition/agents", - "span": { - "column": 61, - "document": "manifest", - "end": 2044, - "line": 57, - "start": 2019 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/condition/platforms", - "span": { - "column": 61, - "document": "manifest", - "end": 2044, - "line": 57, - "start": 2019 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/condition/scopes", - "span": { - "column": 75, - "document": "manifest", - "end": 2043, - "line": 57, - "start": 2033 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/condition/scopes/0", - "span": { - "column": 76, - "document": "manifest", - "end": 2042, - "line": 57, - "start": 2034 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/event", - "span": { - "column": 30, - "document": "manifest", - "end": 1801, - "line": 52, - "start": 1791 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/5/event/kind", - "span": { - "column": 30, - "document": "manifest", - "end": 1801, - "line": 52, - "start": 1791 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/5/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 2050, - "line": 51, - "start": 1755 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/matcher", - "span": { - "column": 5, - "document": "manifest", - "end": 2050, - "line": 51, - "start": 1755 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/name", - "span": { - "column": 13, - "document": "manifest", - "end": 1782, - "line": 52, - "start": 1774 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/native", - "span": { - "column": 5, - "document": "manifest", - "end": 2050, - "line": 51, - "start": 1755 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/run", - "span": { - "column": 12, - "document": "manifest", - "end": 1957, - "line": 53, - "start": 1814 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/run/arguments", - "span": { - "column": 29, - "document": "manifest", - "end": 1890, - "line": 54, - "start": 1855 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/run/arguments/0", - "span": { - "column": 30, - "document": "manifest", - "end": 1864, - "line": 54, - "start": 1856 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/run/arguments/1", - "span": { - "column": 40, - "document": "manifest", - "end": 1878, - "line": 54, - "start": 1866 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/run/arguments/2", - "span": { - "column": 54, - "document": "manifest", - "end": 1889, - "line": 54, - "start": 1880 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/run/environment", - "span": { - "column": 12, - "document": "manifest", - "end": 1957, - "line": 53, - "start": 1814 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/run/executable", - "span": { - "column": 9, - "document": "manifest", - "end": 1842, - "line": 54, - "start": 1835 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/5/run/kind", - "span": { - "column": 12, - "document": "manifest", - "end": 1957, - "line": 53, - "start": 1814 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/run/workingDirectory", - "span": { - "column": 27, - "document": "manifest", - "end": 1949, - "line": 55, - "start": 1918 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/run/workingDirectory/path", - "span": { - "column": 33, - "document": "manifest", - "end": 1931, - "line": 55, - "start": 1924 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/run/workingDirectory/source", - "span": { - "column": 50, - "document": "manifest", - "end": 1948, - "line": 55, - "start": 1941 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/timeoutSeconds", - "span": { - "column": 23, - "document": "manifest", - "end": 1983, - "line": 57, - "start": 1981 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6", - "span": { - "column": 5, - "document": "manifest", - "end": 2315, - "line": 59, - "start": 2056 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/agents", - "span": { - "column": 15, - "document": "manifest", - "end": 2309, - "line": 63, - "start": 2296 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/agents/0", - "span": { - "column": 16, - "document": "manifest", - "end": 2308, - "line": 63, - "start": 2297 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 2315, - "line": 59, - "start": 2056 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/description", - "span": { - "column": 43, - "document": "manifest", - "end": 2135, - "line": 60, - "start": 2108 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/6/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 2315, - "line": 59, - "start": 2056 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/name", - "span": { - "column": 13, - "document": "manifest", - "end": 2093, - "line": 60, - "start": 2078 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/native", - "span": { - "column": 5, - "document": "manifest", - "end": 2315, - "line": 59, - "start": 2056 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/parameters", - "span": { - "column": 19, - "document": "manifest", - "end": 2280, - "line": 62, - "start": 2214 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/parameters/0", - "span": { - "column": 20, - "document": "manifest", - "end": 2279, - "line": 62, - "start": 2215 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/parameters/0/defaultValue", - "span": { - "column": 20, - "document": "manifest", - "end": 2279, - "line": 62, - "start": 2215 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/parameters/0/description", - "span": { - "column": 60, - "document": "manifest", - "end": 2278, - "line": 62, - "start": 2255 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/parameters/0/name", - "span": { - "column": 37, - "document": "manifest", - "end": 2240, - "line": 62, - "start": 2232 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/prompt", - "span": { - "column": 15, - "document": "manifest", - "end": 2194, - "line": 61, - "start": 2151 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/6/prompt/kind", - "span": { - "column": 15, - "document": "manifest", - "end": 2194, - "line": 61, - "start": 2151 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/6/prompt/value", - "span": { - "column": 15, - "document": "manifest", - "end": 2194, - "line": 61, - "start": 2151 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7", - "span": { - "column": 5, - "document": "manifest", - "end": 2558, - "line": 65, - "start": 2321 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/agents", - "span": { - "column": 15, - "document": "manifest", - "end": 2513, - "line": 69, - "start": 2500 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/agents/0", - "span": { - "column": 16, - "document": "manifest", - "end": 2512, - "line": 69, - "start": 2501 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/condition", - "span": { - "column": 41, - "document": "manifest", - "end": 2552, - "line": 69, - "start": 2526 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/condition/agents", - "span": { - "column": 41, - "document": "manifest", - "end": 2552, - "line": 69, - "start": 2526 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/condition/platforms", - "span": { - "column": 58, - "document": "manifest", - "end": 2551, - "line": 69, - "start": 2543 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/condition/platforms/0", - "span": { - "column": 59, - "document": "manifest", - "end": 2550, - "line": 69, - "start": 2544 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/condition/scopes", - "span": { - "column": 41, - "document": "manifest", - "end": 2552, - "line": 69, - "start": 2526 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/initializationOptions", - "span": { - "column": 30, - "document": "manifest", - "end": 2484, - "line": 68, - "start": 2456 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/initializationOptions/backgroundIndexing", - "span": { - "column": 53, - "document": "manifest", - "end": 2483, - "line": 68, - "start": 2479 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/7/initializationOptions/backgroundIndexing/kind", - "span": { - "column": 53, - "document": "manifest", - "end": 2483, - "line": 68, - "start": 2479 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/7/initializationOptions/backgroundIndexing/value", - "span": { - "column": 53, - "document": "manifest", - "end": 2483, - "line": 68, - "start": 2479 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/7/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 2558, - "line": 65, - "start": 2321 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/languages", - "span": { - "column": 18, - "document": "manifest", - "end": 2425, - "line": 67, - "start": 2406 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/languages/.swift", - "span": { - "column": 29, - "document": "manifest", - "end": 2424, - "line": 67, - "start": 2417 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/name", - "span": { - "column": 13, - "document": "manifest", - "end": 2352, - "line": 66, - "start": 2345 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/native", - "span": { - "column": 5, - "document": "manifest", - "end": 2558, - "line": 65, - "start": 2321 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/run", - "span": { - "column": 27, - "document": "manifest", - "end": 2387, - "line": 66, - "start": 2359 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/run/arguments", - "span": { - "column": 27, - "document": "manifest", - "end": 2387, - "line": 66, - "start": 2359 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/run/environment", - "span": { - "column": 27, - "document": "manifest", - "end": 2387, - "line": 66, - "start": 2359 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/run/executable", - "span": { - "column": 39, - "document": "manifest", - "end": 2386, - "line": 66, - "start": 2371 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/7/run/kind", - "span": { - "column": 27, - "document": "manifest", - "end": 2387, - "line": 66, - "start": 2359 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/run/workingDirectory", - "span": { - "column": 27, - "document": "manifest", - "end": 2387, - "line": 66, - "start": 2359 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8", - "span": { - "column": 5, - "document": "manifest", - "end": 2721, - "line": 71, - "start": 2564 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/agents", - "span": { - "column": 15, - "document": "manifest", - "end": 2677, - "line": 74, - "start": 2664 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/agents/0", - "span": { - "column": 16, - "document": "manifest", - "end": 2676, - "line": 74, - "start": 2665 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/condition", - "span": { - "column": 41, - "document": "manifest", - "end": 2715, - "line": 74, - "start": 2690 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/condition/agents", - "span": { - "column": 41, - "document": "manifest", - "end": 2715, - "line": 74, - "start": 2690 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/condition/platforms", - "span": { - "column": 41, - "document": "manifest", - "end": 2715, - "line": 74, - "start": 2690 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/condition/scopes", - "span": { - "column": 55, - "document": "manifest", - "end": 2714, - "line": 74, - "start": 2704 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/condition/scopes/0", - "span": { - "column": 56, - "document": "manifest", - "end": 2713, - "line": 74, - "start": 2705 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/8/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 2721, - "line": 71, - "start": 2564 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/name", - "span": { - "column": 13, - "document": "manifest", - "end": 2605, - "line": 72, - "start": 2590 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/native", - "span": { - "column": 5, - "document": "manifest", - "end": 2721, - "line": 71, - "start": 2564 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/rules", - "span": { - "column": 14, - "document": "manifest", - "end": 2648, - "line": 73, - "start": 2620 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/rules/0", - "span": { - "column": 15, - "document": "manifest", - "end": 2647, - "line": 73, - "start": 2621 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/8/rules/0/kind", - "span": { - "column": 15, - "document": "manifest", - "end": 2647, - "line": 73, - "start": 2621 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/rules/0/operation", - "span": { - "column": 21, - "document": "manifest", - "end": 2632, - "line": 73, - "start": 2627 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/8/rules/0/operation/kind", - "span": { - "column": 21, - "document": "manifest", - "end": 2632, - "line": 73, - "start": 2627 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/rules/0/pattern", - "span": { - "column": 28, - "document": "manifest", - "end": 2646, - "line": 73, - "start": 2634 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9", - "span": { - "column": 5, - "document": "manifest", - "end": 2892, - "line": 76, - "start": 2727 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/agents", - "span": { - "column": 15, - "document": "manifest", - "end": 2848, - "line": 78, - "start": 2839 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/agents/0", - "span": { - "column": 16, - "document": "manifest", - "end": 2847, - "line": 78, - "start": 2840 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/condition", - "span": { - "column": 37, - "document": "manifest", - "end": 2886, - "line": 78, - "start": 2861 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/condition/agents", - "span": { - "column": 37, - "document": "manifest", - "end": 2886, - "line": 78, - "start": 2861 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/condition/platforms", - "span": { - "column": 37, - "document": "manifest", - "end": 2886, - "line": 78, - "start": 2861 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/condition/scopes", - "span": { - "column": 51, - "document": "manifest", - "end": 2885, - "line": 78, - "start": 2875 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/condition/scopes/0", - "span": { - "column": 52, - "document": "manifest", - "end": 2884, - "line": 78, - "start": 2876 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/9/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 2892, - "line": 76, - "start": 2727 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/name", - "span": { - "column": 13, - "document": "manifest", - "end": 2764, - "line": 77, - "start": 2748 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/native", - "span": { - "column": 5, - "document": "manifest", - "end": 2892, - "line": 76, - "start": 2727 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/patterns", - "span": { - "column": 41, - "document": "manifest", - "end": 2803, - "line": 77, - "start": 2776 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/patterns/0", - "span": { - "column": 42, - "document": "manifest", - "end": 2786, - "line": 77, - "start": 2777 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/patterns/1", - "span": { - "column": 53, - "document": "manifest", - "end": 2802, - "line": 77, - "start": 2788 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/purpose", - "span": { - "column": 79, - "document": "manifest", - "end": 2823, - "line": 77, - "start": 2814 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/defaultAgents", - "span": { - "column": 14, - "document": "manifest", - "end": 3467, - "line": 15, - "start": 475 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/exports", - "span": { - "column": 14, - "document": "manifest", - "end": 3467, - "line": 15, - "start": 475 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups", - "span": { - "column": 11, - "document": "manifest", - "end": 3408, - "line": 89, - "start": 3243 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0", - "span": { - "column": 5, - "document": "manifest", - "end": 3403, - "line": 90, - "start": 3249 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/components", - "span": { - "column": 41, - "document": "manifest", - "end": 3307, - "line": 91, - "start": 3297 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - } - ], - "pointer": "/groups/0/components/0", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 11, - "document": "manifest", - "end": 356, - "line": 10, - "start": 343 - } - ], - "pointer": "/groups/0/components/0/agents", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 11, - "document": "manifest", - "end": 356, - "line": 10, - "start": 343 - }, - { - "column": 12, - "document": "manifest", - "end": 355, - "line": 10, - "start": 344 - } - ], - "pointer": "/groups/0/components/0/agents/0", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 14, - "document": "manifest", - "end": 397, - "line": 11, - "start": 371 - } - ], - "pointer": "/groups/0/components/0/condition", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 14, - "document": "manifest", - "end": 397, - "line": 11, - "start": 371 - } - ], - "pointer": "/groups/0/components/0/condition/agents", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 14, - "document": "manifest", - "end": 397, - "line": 11, - "start": 371 - }, - { - "column": 31, - "document": "manifest", - "end": 396, - "line": 11, - "start": 388 - } - ], - "pointer": "/groups/0/components/0/condition/platforms", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 14, - "document": "manifest", - "end": 397, - "line": 11, - "start": 371 - }, - { - "column": 31, - "document": "manifest", - "end": 396, - "line": 11, - "start": 388 - }, - { - "column": 32, - "document": "manifest", - "end": 395, - "line": 11, - "start": 389 - } - ], - "pointer": "/groups/0/components/0/condition/platforms/0", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 14, - "document": "manifest", - "end": 397, - "line": 11, - "start": 371 - } - ], - "pointer": "/groups/0/components/0/condition/scopes", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 16, - "document": "manifest", - "end": 270, - "line": 8, - "start": 239 - } - ], - "pointer": "/groups/0/components/0/description", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - } - ], - "pointer": "/groups/0/components/0/kind", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - } - ], - "pointer": "/groups/0/components/0/model", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 9, - "document": "manifest", - "end": 222, - "line": 7, - "start": 212 - } - ], - "pointer": "/groups/0/components/0/name", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 11, - "document": "manifest", - "end": 458, - "line": 12, - "start": 409 - } - ], - "pointer": "/groups/0/components/0/native", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 11, - "document": "manifest", - "end": 458, - "line": 12, - "start": 409 - }, - { - "column": 38, - "document": "manifest", - "end": 457, - "line": 12, - "start": 436 - } - ], - "pointer": "/groups/0/components/0/native/claude-code~1subagent@1", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 11, - "document": "manifest", - "end": 458, - "line": 12, - "start": 409 - }, - { - "column": 38, - "document": "manifest", - "end": 457, - "line": 12, - "start": 436 - }, - { - "column": 49, - "document": "manifest", - "end": 456, - "line": 12, - "start": 447 - } - ], - "pointer": "/groups/0/components/0/native/claude-code~1subagent@1/memory", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 11, - "document": "manifest", - "end": 458, - "line": 12, - "start": 409 - }, - { - "column": 38, - "document": "manifest", - "end": 457, - "line": 12, - "start": 436 - }, - { - "column": 49, - "document": "manifest", - "end": 456, - "line": 12, - "start": 447 - } - ], - "pointer": "/groups/0/components/0/native/claude-code~1subagent@1/memory/kind", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 11, - "document": "manifest", - "end": 458, - "line": 12, - "start": 409 - }, - { - "column": 38, - "document": "manifest", - "end": 457, - "line": 12, - "start": 436 - }, - { - "column": 49, - "document": "manifest", - "end": 456, - "line": 12, - "start": 447 - } - ], - "pointer": "/groups/0/components/0/native/claude-code~1subagent@1/memory/value", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 11, - "document": "manifest", - "end": 331, - "line": 9, - "start": 282 - } - ], - "pointer": "/groups/0/components/0/prompt", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 11, - "document": "manifest", - "end": 331, - "line": 9, - "start": 282 - } - ], - "pointer": "/groups/0/components/0/prompt/kind", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - }, - { - "column": 11, - "document": "manifest", - "end": 331, - "line": 9, - "start": 282 - } - ], - "pointer": "/groups/0/components/0/prompt/value", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 460, - "line": 6, - "start": 193 - } - ], - "pointer": "/groups/0/components/0/tools", - "span": { - "column": 42, - "document": "manifest", - "end": 3306, - "line": 91, - "start": 3298 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 3403, - "line": 90, - "start": 3249 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/name", - "span": { - "column": 13, - "document": "manifest", - "end": 3283, - "line": 91, - "start": 3269 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/uses", - "span": { - "column": 13, - "document": "manifest", - "end": 3397, - "line": 92, - "start": 3321 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/uses/0", - "span": { - "column": 14, - "document": "manifest", - "end": 3396, - "line": 92, - "start": 3322 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/uses/0/condition", - "span": { - "column": 64, - "document": "manifest", - "end": 3395, - "line": 92, - "start": 3372 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/uses/0/condition/agents", - "span": { - "column": 78, - "document": "manifest", - "end": 3394, - "line": 92, - "start": 3386 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/uses/0/condition/agents/0", - "span": { - "column": 79, - "document": "manifest", - "end": 3393, - "line": 92, - "start": 3387 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/uses/0/condition/platforms", - "span": { - "column": 64, - "document": "manifest", - "end": 3395, - "line": 92, - "start": 3372 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/uses/0/condition/scopes", - "span": { - "column": 64, - "document": "manifest", - "end": 3395, - "line": 92, - "start": 3372 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/groups/0/uses/0/kind", - "span": { - "column": 14, - "document": "manifest", - "end": 3396, - "line": 92, - "start": 3322 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/uses/0/name", - "span": { - "column": 27, - "document": "manifest", - "end": 3343, - "line": 92, - "start": 3335 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/uses/0/source", - "span": { - "column": 45, - "document": "manifest", - "end": 3359, - "line": 92, - "start": 3353 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources", - "span": { - "column": 12, - "document": "manifest", - "end": 849, - "line": 16, - "start": 494 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/0", - "span": { - "column": 5, - "document": "manifest", - "end": 754, - "line": 20, - "start": 682 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/0/index", - "span": { - "column": 37, - "document": "manifest", - "end": 753, - "line": 20, - "start": 714 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/0/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 754, - "line": 20, - "start": 682 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/0/name", - "span": { - "column": 19, - "document": "manifest", - "end": 705, - "line": 20, - "start": 696 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/0/requirement", - "span": { - "column": 5, - "document": "manifest", - "end": 754, - "line": 20, - "start": 682 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/0/subpath", - "span": { - "column": 5, - "document": "manifest", - "end": 754, - "line": 20, - "start": 682 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/1", - "span": { - "column": 5, - "document": "manifest", - "end": 590, - "line": 18, - "start": 543 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/1/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 590, - "line": 18, - "start": 543 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/1/name", - "span": { - "column": 19, - "document": "manifest", - "end": 565, - "line": 18, - "start": 557 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/1/path", - "span": { - "column": 35, - "document": "manifest", - "end": 589, - "line": 18, - "start": 573 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/1/requirement", - "span": { - "column": 5, - "document": "manifest", - "end": 590, - "line": 18, - "start": 543 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/1/subpath", - "span": { - "column": 5, - "document": "manifest", - "end": 590, - "line": 18, - "start": 543 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/2", - "span": { - "column": 5, - "document": "manifest", - "end": 676, - "line": 19, - "start": 596 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/2/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 676, - "line": 19, - "start": 596 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/2/name", - "span": { - "column": 19, - "document": "manifest", - "end": 617, - "line": 19, - "start": 610 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/2/requirement", - "span": { - "column": 77, - "document": "manifest", - "end": 675, - "line": 19, - "start": 668 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/2/requirement/from", - "span": { - "column": 77, - "document": "manifest", - "end": 675, - "line": 19, - "start": 668 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/2/subpath", - "span": { - "column": 5, - "document": "manifest", - "end": 676, - "line": 19, - "start": 596 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/2/url", - "span": { - "column": 33, - "document": "manifest", - "end": 660, - "line": 19, - "start": 624 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/3", - "span": { - "column": 5, - "document": "manifest", - "end": 537, - "line": 17, - "start": 500 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/3/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 537, - "line": 17, - "start": 500 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/3/name", - "span": { - "column": 19, - "document": "manifest", - "end": 520, - "line": 17, - "start": 514 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/3/path", - "span": { - "column": 33, - "document": "manifest", - "end": 536, - "line": 17, - "start": 528 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/3/requirement", - "span": { - "column": 5, - "document": "manifest", - "end": 537, - "line": 17, - "start": 500 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/3/subpath", - "span": { - "column": 5, - "document": "manifest", - "end": 537, - "line": 17, - "start": 500 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/4", - "span": { - "column": 5, - "document": "manifest", - "end": 844, - "line": 21, - "start": 760 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/4/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 844, - "line": 21, - "start": 760 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/4/name", - "span": { - "column": 19, - "document": "manifest", - "end": 782, - "line": 21, - "start": 774 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/4/requirement", - "span": { - "column": 81, - "document": "manifest", - "end": 843, - "line": 21, - "start": 836 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/4/requirement/exact", - "span": { - "column": 81, - "document": "manifest", - "end": 843, - "line": 21, - "start": 836 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/4/subpath", - "span": { - "column": 5, - "document": "manifest", - "end": 844, - "line": 21, - "start": 760 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/4/url", - "span": { - "column": 34, - "document": "manifest", - "end": 827, - "line": 21, - "start": 789 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses", - "span": { - "column": 9, - "document": "manifest", - "end": 3434, - "line": 95, - "start": 3418 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses/0", - "span": { - "column": 10, - "document": "manifest", - "end": 3433, - "line": 95, - "start": 3419 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/uses/0/condition", - "span": { - "column": 10, - "document": "manifest", - "end": 3433, - "line": 95, - "start": 3419 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/uses/0/kind", - "span": { - "column": 10, - "document": "manifest", - "end": 3433, - "line": 95, - "start": 3419 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/uses/0/name", - "span": { - "column": 10, - "document": "manifest", - "end": 3433, - "line": 95, - "start": 3419 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/uses/0/source", - "span": { - "column": 10, - "document": "manifest", - "end": 3433, - "line": 95, - "start": 3419 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/watch", - "span": { - "column": 10, - "document": "manifest", - "end": 3465, - "line": 96, - "start": 3445 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/watch/0", - "span": { - "column": 20, - "document": "manifest", - "end": 3464, - "line": 96, - "start": 3455 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/watch/1", - "span": { - "column": 11, - "document": "manifest", - "end": 3453, - "line": 96, - "start": 3446 - } - } - ], - "schemaVersion": 1, - "sourceDigest": "sha256:62b31c7e40fb0b847ed6fb2fd5ef2b7895da18b8f65b4bbef90383be64eb061a" -} diff --git a/Tests/AgentsManifestTests/Fixtures/ConsumerExample.swift.txt b/Tests/AgentsManifestTests/Fixtures/ConsumerExample.swift.txt deleted file mode 100644 index d31bf3b..0000000 --- a/Tests/AgentsManifestTests/Fixtures/ConsumerExample.swift.txt +++ /dev/null @@ -1,97 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let base: [SectionReference] = ["guide"] -let sections = base + [.section(name: "engineering", source: "rules")] -let reviewer: Component = .subagent( - name: "reviewer", - description: "Review correctness and tests.", - prompt: "Check invariants and explain concrete failures.", - agents: [.claudeCode], - condition: .when(platforms: [.macOS]), - native: ["claude-code/subagent@1": ["memory": "project"]] -) - -let agents = Agents( - sources: [ - .source(name: "team", path: "./team"), - .source(name: "drafts", path: "./draft-skills"), - .source(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), - .source(name: "catalog", index: "https://example.org/skills/index.json"), - .source(name: "vendor", url: "https://example.org/vendor/tools.git", exact: "2.1.0"), - ], - components: [ - .skills( - source: "rules", exclude: ["experimental"], mode: .copy, - overrides: [.skill(name: "testing", mode: .link, agents: [.codex])] - ), - .skills( - source: "drafts", select: ["draft"], mode: .edit, - condition: .when(agents: [.claudeCode], scopes: [.project]) - ), - .instructions( - sections: sections, - chatGPT: [.prompt(name: "weekly", sections: base, append: "notes/weekly.md")] - ), - .mcpServer( - name: "workspace", - transport: .stdio( - "workspace-tools", arguments: ["serve"], - environment: ["TOKEN": .secret("workspace-token"), "LOG_LEVEL": "info"] - ), - agents: [.claudeCode] - ), - .mcpServer( - name: "reference", - transport: .streamableHTTP( - url: "https://example.org/mcp", headers: ["Authorization": .environment("MCP_AUTH")] - ), - agents: [.openCode] - ), - .hook( - name: "format", event: .afterTool, - run: .executable( - "swift", arguments: ["format", "--in-place", "Sources"], - workingDirectory: .path("tools", source: "rules") - ), - timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) - ), - .command( - name: "review/change", description: "Review a selected change.", - prompt: "Review ${input:change} and cite evidence.", - parameters: [.parameter(name: "change", description: "The change to review.")], - agents: [.claudeCode] - ), - .lspServer( - name: "swift", run: .executable("sourcekit-lsp"), - languages: [".swift": "swift"], - initializationOptions: ["backgroundIndexing": true], - agents: [.claudeCode], condition: .when(platforms: [.macOS]) - ), - .permissions( - name: "private-files", - rules: [.deny(.read, "secrets/**")], - agents: [.claudeCode], condition: .when(scopes: [.project]) - ), - .ignore( - name: "build-products", patterns: [".build/", "DerivedData/"], purpose: .indexing, - agents: [.cursor], condition: .when(scopes: [.project]) - ), - .plugin( - name: "vendor-tools", path: "plugins/tools", source: "vendor", mode: .native, - agents: [.claudeCode], condition: .when(scopes: [.user]) - ), - .plugin( - name: "shared-tools", path: "plugins/shared", source: "vendor", - exclude: [.hook(name: "format")], condition: .when(scopes: [.project]) - ), - ], - groups: [ - .group( - name: "review-tools", components: [reviewer], - uses: [.group(name: "review", source: "team", condition: .when(agents: [.codex]))] - ), - ], - uses: ["review-tools"], - watch: ["rules", "catalog"] -) diff --git a/Tests/AgentsManifestTests/Fixtures/CoreExample.swift.txt b/Tests/AgentsManifestTests/Fixtures/CoreExample.swift.txt deleted file mode 100644 index 44f9882..0000000 --- a/Tests/AgentsManifestTests/Fixtures/CoreExample.swift.txt +++ /dev/null @@ -1,23 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - sources: [ - .source( - name: "agents-tools", - url: "https://github.com/agents-tools/.github", - branch: "master", - subpath: ".agent" - ), - ], - components: [ - .instructions( - sections: [ - "guide", - .section(name: "shared/swift-package-route", source: "agents-tools"), - .section(name: "shared/swift-package-tests", source: "agents-tools"), - ], - agents: [.claudeCode, .codex] - ), - ] -) diff --git a/Tests/AgentsManifestTests/Fixtures/DumpSymbolic.dump.json b/Tests/AgentsManifestTests/Fixtures/DumpSymbolic.dump.json deleted file mode 100644 index c0acf14..0000000 --- a/Tests/AgentsManifestTests/Fixtures/DumpSymbolic.dump.json +++ /dev/null @@ -1,3014 +0,0 @@ -{ - "declaration": { - "components": [ - { - "agents": [], - "chatGPT": [ - { - "append": null, - "condition": null, - "name": "a", - "sections": [ - { - "condition": null, - "name": "own", - "source": null - } - ] - }, - { - "append": null, - "condition": null, - "name": "z", - "sections": [] - } - ], - "condition": null, - "kind": "instructions", - "native": {}, - "sections": [ - { - "condition": null, - "name": "own", - "source": null - }, - { - "condition": { - "agents": [ - "codex", - "opencode" - ], - "platforms": [ - "linux", - "macos" - ], - "scopes": [ - "project", - "user" - ] - }, - "name": "rule", - "source": "z" - } - ] - }, - { - "agents": null, - "condition": null, - "exclude": [ - "a", - "z" - ], - "kind": "skills", - "mode": null, - "native": {}, - "overrides": [ - { - "agents": null, - "mode": null, - "name": "a" - }, - { - "agents": [], - "mode": null, - "name": "z" - } - ], - "select": [ - "a", - "z" - ], - "source": "z" - }, - { - "agents": null, - "condition": null, - "exclude": [ - { - "kind": "command", - "name": "zzz" - }, - { - "kind": "hook", - "name": "aaa" - }, - { - "kind": "hook", - "name": "bbb" - }, - { - "kind": "skill", - "name": "ccc" - } - ], - "kind": "plugin", - "mode": "components", - "name": "bundle", - "native": {}, - "path": "bundle", - "select": null, - "source": "z" - } - ], - "defaultAgents": [], - "exports": [ - "a", - "z" - ], - "groups": [ - { - "components": [], - "condition": null, - "name": "a", - "uses": [] - }, - { - "components": [], - "condition": { - "agents": [ - "codex", - "opencode" - ], - "platforms": [ - "linux", - "macos" - ], - "scopes": [ - "project", - "user" - ] - }, - "name": "z", - "uses": [] - } - ], - "sources": [ - { - "kind": "local", - "name": "a", - "path": "./a", - "requirement": null, - "subpath": null - }, - { - "kind": "git", - "name": "z", - "requirement": { - "upToNextMinor": "1.2.0" - }, - "subpath": null, - "url": "https://intranet/team.git" - } - ], - "uses": [ - { - "condition": { - "agents": [ - "codex", - "opencode" - ], - "platforms": [ - "linux", - "macos" - ], - "scopes": [ - "project", - "user" - ] - }, - "kind": "exported", - "name": "review", - "source": "z" - }, - { - "condition": null, - "kind": "local", - "name": "a", - "source": null - } - ], - "watch": [ - "a", - "z" - ] - }, - "diagnostics": [ - { - "code": "manifest.domain", - "message": "use the complete Git transport URL", - "related": [], - "severity": "warning", - "span": { - "column": 29, - "document": "manifest", - "end": 295, - "line": 9, - "start": 276 - } - } - ], - "kind": "manifest", - "languageVersion": "1.0", - "locations": [ - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "", - "span": { - "column": 14, - "document": "manifest", - "end": 1014, - "line": 5, - "start": 183 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components", - "span": { - "column": 15, - "document": "manifest", - "end": 851, - "line": 12, - "start": 373 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0", - "span": { - "column": 5, - "document": "manifest", - "end": 563, - "line": 13, - "start": 379 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/agents", - "span": { - "column": 186, - "document": "manifest", - "end": 562, - "line": 13, - "start": 560 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/chatGPT", - "span": { - "column": 103, - "document": "manifest", - "end": 550, - "line": 13, - "start": 477 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/chatGPT/0", - "span": { - "column": 138, - "document": "manifest", - "end": 549, - "line": 13, - "start": 512 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/chatGPT/0/append", - "span": { - "column": 138, - "document": "manifest", - "end": 549, - "line": 13, - "start": 512 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/chatGPT/0/condition", - "span": { - "column": 138, - "document": "manifest", - "end": 549, - "line": 13, - "start": 512 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/chatGPT/0/name", - "span": { - "column": 152, - "document": "manifest", - "end": 529, - "line": 13, - "start": 526 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/chatGPT/0/sections", - "span": { - "column": 167, - "document": "manifest", - "end": 548, - "line": 13, - "start": 541 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/chatGPT/0/sections/0", - "span": { - "column": 168, - "document": "manifest", - "end": 547, - "line": 13, - "start": 542 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/0/chatGPT/0/sections/0/condition", - "span": { - "column": 168, - "document": "manifest", - "end": 547, - "line": 13, - "start": 542 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/0/chatGPT/0/sections/0/name", - "span": { - "column": 168, - "document": "manifest", - "end": 547, - "line": 13, - "start": 542 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/0/chatGPT/0/sections/0/source", - "span": { - "column": 168, - "document": "manifest", - "end": 547, - "line": 13, - "start": 542 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/chatGPT/1", - "span": { - "column": 104, - "document": "manifest", - "end": 510, - "line": 13, - "start": 478 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/chatGPT/1/append", - "span": { - "column": 104, - "document": "manifest", - "end": 510, - "line": 13, - "start": 478 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/chatGPT/1/condition", - "span": { - "column": 104, - "document": "manifest", - "end": 510, - "line": 13, - "start": 478 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/chatGPT/1/name", - "span": { - "column": 118, - "document": "manifest", - "end": 495, - "line": 13, - "start": 492 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/chatGPT/1/sections", - "span": { - "column": 133, - "document": "manifest", - "end": 509, - "line": 13, - "start": 507 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 563, - "line": 13, - "start": 379 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/0/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 563, - "line": 13, - "start": 379 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/native", - "span": { - "column": 5, - "document": "manifest", - "end": 563, - "line": 13, - "start": 379 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/sections", - "span": { - "column": 29, - "document": "manifest", - "end": 466, - "line": 13, - "start": 403 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/sections/0", - "span": { - "column": 30, - "document": "manifest", - "end": 409, - "line": 13, - "start": 404 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/0/sections/0/condition", - "span": { - "column": 30, - "document": "manifest", - "end": 409, - "line": 13, - "start": 404 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/0/sections/0/name", - "span": { - "column": 30, - "document": "manifest", - "end": 409, - "line": 13, - "start": 404 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/0/sections/0/source", - "span": { - "column": 30, - "document": "manifest", - "end": 409, - "line": 13, - "start": 404 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/sections/1", - "span": { - "column": 37, - "document": "manifest", - "end": 465, - "line": 13, - "start": 411 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - } - ], - "pointer": "/components/0/sections/1/condition", - "span": { - "column": 84, - "document": "manifest", - "end": 464, - "line": 13, - "start": 458 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 39, - "document": "manifest", - "end": 112, - "line": 4, - "start": 93 - } - ], - "pointer": "/components/0/sections/1/condition/agents", - "span": { - "column": 84, - "document": "manifest", - "end": 464, - "line": 13, - "start": 458 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 39, - "document": "manifest", - "end": 112, - "line": 4, - "start": 93 - }, - { - "column": 51, - "document": "manifest", - "end": 111, - "line": 4, - "start": 105 - } - ], - "pointer": "/components/0/sections/1/condition/agents/0", - "span": { - "column": 84, - "document": "manifest", - "end": 464, - "line": 13, - "start": 458 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 39, - "document": "manifest", - "end": 112, - "line": 4, - "start": 93 - }, - { - "column": 40, - "document": "manifest", - "end": 103, - "line": 4, - "start": 94 - } - ], - "pointer": "/components/0/sections/1/condition/agents/1", - "span": { - "column": 84, - "document": "manifest", - "end": 464, - "line": 13, - "start": 458 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 98, - "document": "manifest", - "end": 168, - "line": 4, - "start": 152 - } - ], - "pointer": "/components/0/sections/1/condition/platforms", - "span": { - "column": 84, - "document": "manifest", - "end": 464, - "line": 13, - "start": 458 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 98, - "document": "manifest", - "end": 168, - "line": 4, - "start": 152 - }, - { - "column": 99, - "document": "manifest", - "end": 159, - "line": 4, - "start": 153 - } - ], - "pointer": "/components/0/sections/1/condition/platforms/0", - "span": { - "column": 84, - "document": "manifest", - "end": 464, - "line": 13, - "start": 458 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 98, - "document": "manifest", - "end": 168, - "line": 4, - "start": 152 - }, - { - "column": 107, - "document": "manifest", - "end": 167, - "line": 4, - "start": 161 - } - ], - "pointer": "/components/0/sections/1/condition/platforms/1", - "span": { - "column": 84, - "document": "manifest", - "end": 464, - "line": 13, - "start": 458 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 68, - "document": "manifest", - "end": 139, - "line": 4, - "start": 122 - } - ], - "pointer": "/components/0/sections/1/condition/scopes", - "span": { - "column": 84, - "document": "manifest", - "end": 464, - "line": 13, - "start": 458 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 68, - "document": "manifest", - "end": 139, - "line": 4, - "start": 122 - }, - { - "column": 76, - "document": "manifest", - "end": 138, - "line": 4, - "start": 130 - } - ], - "pointer": "/components/0/sections/1/condition/scopes/0", - "span": { - "column": 84, - "document": "manifest", - "end": 464, - "line": 13, - "start": 458 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 68, - "document": "manifest", - "end": 139, - "line": 4, - "start": 122 - }, - { - "column": 69, - "document": "manifest", - "end": 128, - "line": 4, - "start": 123 - } - ], - "pointer": "/components/0/sections/1/condition/scopes/1", - "span": { - "column": 84, - "document": "manifest", - "end": 464, - "line": 13, - "start": 458 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/sections/1/name", - "span": { - "column": 52, - "document": "manifest", - "end": 432, - "line": 13, - "start": 426 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/sections/1/source", - "span": { - "column": 68, - "document": "manifest", - "end": 445, - "line": 13, - "start": 442 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1", - "span": { - "column": 5, - "document": "manifest", - "end": 693, - "line": 14, - "start": 569 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 693, - "line": 14, - "start": 569 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 693, - "line": 14, - "start": 569 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/exclude", - "span": { - "column": 55, - "document": "manifest", - "end": 629, - "line": 14, - "start": 619 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/exclude/0", - "span": { - "column": 61, - "document": "manifest", - "end": 628, - "line": 14, - "start": 625 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/exclude/1", - "span": { - "column": 56, - "document": "manifest", - "end": 623, - "line": 14, - "start": 620 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/1/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 693, - "line": 14, - "start": 569 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/mode", - "span": { - "column": 5, - "document": "manifest", - "end": 693, - "line": 14, - "start": 569 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/native", - "span": { - "column": 5, - "document": "manifest", - "end": 693, - "line": 14, - "start": 569 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides", - "span": { - "column": 78, - "document": "manifest", - "end": 692, - "line": 14, - "start": 642 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/0", - "span": { - "column": 110, - "document": "manifest", - "end": 691, - "line": 14, - "start": 674 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/0/agents", - "span": { - "column": 110, - "document": "manifest", - "end": 691, - "line": 14, - "start": 674 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/0/mode", - "span": { - "column": 110, - "document": "manifest", - "end": 691, - "line": 14, - "start": 674 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/0/name", - "span": { - "column": 123, - "document": "manifest", - "end": 690, - "line": 14, - "start": 687 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/1", - "span": { - "column": 79, - "document": "manifest", - "end": 672, - "line": 14, - "start": 643 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/1/agents", - "span": { - "column": 105, - "document": "manifest", - "end": 671, - "line": 14, - "start": 669 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/1/mode", - "span": { - "column": 79, - "document": "manifest", - "end": 672, - "line": 14, - "start": 643 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/1/name", - "span": { - "column": 92, - "document": "manifest", - "end": 659, - "line": 14, - "start": 656 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/select", - "span": { - "column": 34, - "document": "manifest", - "end": 608, - "line": 14, - "start": 598 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/select/0", - "span": { - "column": 40, - "document": "manifest", - "end": 607, - "line": 14, - "start": 604 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/select/1", - "span": { - "column": 35, - "document": "manifest", - "end": 602, - "line": 14, - "start": 599 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/source", - "span": { - "column": 21, - "document": "manifest", - "end": 588, - "line": 14, - "start": 585 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2", - "span": { - "column": 5, - "document": "manifest", - "end": 846, - "line": 15, - "start": 699 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 846, - "line": 15, - "start": 699 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 846, - "line": 15, - "start": 699 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/exclude", - "span": { - "column": 67, - "document": "manifest", - "end": 845, - "line": 15, - "start": 761 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/exclude/0", - "span": { - "column": 88, - "document": "manifest", - "end": 803, - "line": 15, - "start": 782 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/2/exclude/0/kind", - "span": { - "column": 88, - "document": "manifest", - "end": 803, - "line": 15, - "start": 782 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/exclude/0/name", - "span": { - "column": 103, - "document": "manifest", - "end": 802, - "line": 15, - "start": 797 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/exclude/1", - "span": { - "column": 68, - "document": "manifest", - "end": 780, - "line": 15, - "start": 762 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/2/exclude/1/kind", - "span": { - "column": 68, - "document": "manifest", - "end": 780, - "line": 15, - "start": 762 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/exclude/1/name", - "span": { - "column": 80, - "document": "manifest", - "end": 779, - "line": 15, - "start": 774 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/exclude/2", - "span": { - "column": 111, - "document": "manifest", - "end": 823, - "line": 15, - "start": 805 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/2/exclude/2/kind", - "span": { - "column": 111, - "document": "manifest", - "end": 823, - "line": 15, - "start": 805 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/exclude/2/name", - "span": { - "column": 123, - "document": "manifest", - "end": 822, - "line": 15, - "start": 817 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/exclude/3", - "span": { - "column": 131, - "document": "manifest", - "end": 844, - "line": 15, - "start": 825 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/2/exclude/3/kind", - "span": { - "column": 131, - "document": "manifest", - "end": 844, - "line": 15, - "start": 825 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/exclude/3/name", - "span": { - "column": 144, - "document": "manifest", - "end": 843, - "line": 15, - "start": 838 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/2/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 846, - "line": 15, - "start": 699 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/mode", - "span": { - "column": 5, - "document": "manifest", - "end": 846, - "line": 15, - "start": 699 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/name", - "span": { - "column": 19, - "document": "manifest", - "end": 721, - "line": 15, - "start": 713 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/native", - "span": { - "column": 5, - "document": "manifest", - "end": 846, - "line": 15, - "start": 699 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/path", - "span": { - "column": 35, - "document": "manifest", - "end": 737, - "line": 15, - "start": 729 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/select", - "span": { - "column": 5, - "document": "manifest", - "end": 846, - "line": 15, - "start": 699 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/source", - "span": { - "column": 53, - "document": "manifest", - "end": 750, - "line": 15, - "start": 747 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/defaultAgents", - "span": { - "column": 18, - "document": "manifest", - "end": 210, - "line": 6, - "start": 208 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/exports", - "span": { - "column": 12, - "document": "manifest", - "end": 233, - "line": 7, - "start": 223 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/exports/0", - "span": { - "column": 18, - "document": "manifest", - "end": 232, - "line": 7, - "start": 229 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/exports/1", - "span": { - "column": 13, - "document": "manifest", - "end": 227, - "line": 7, - "start": 224 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups", - "span": { - "column": 11, - "document": "manifest", - "end": 920, - "line": 17, - "start": 863 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0", - "span": { - "column": 50, - "document": "manifest", - "end": 919, - "line": 17, - "start": 902 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/components", - "span": { - "column": 50, - "document": "manifest", - "end": 919, - "line": 17, - "start": 902 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/condition", - "span": { - "column": 50, - "document": "manifest", - "end": 919, - "line": 17, - "start": 902 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/name", - "span": { - "column": 63, - "document": "manifest", - "end": 918, - "line": 17, - "start": 915 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/uses", - "span": { - "column": 50, - "document": "manifest", - "end": 919, - "line": 17, - "start": 902 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/1", - "span": { - "column": 12, - "document": "manifest", - "end": 900, - "line": 17, - "start": 864 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/1/components", - "span": { - "column": 12, - "document": "manifest", - "end": 900, - "line": 17, - "start": 864 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - } - ], - "pointer": "/groups/1/condition", - "span": { - "column": 41, - "document": "manifest", - "end": 899, - "line": 17, - "start": 893 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 39, - "document": "manifest", - "end": 112, - "line": 4, - "start": 93 - } - ], - "pointer": "/groups/1/condition/agents", - "span": { - "column": 41, - "document": "manifest", - "end": 899, - "line": 17, - "start": 893 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 39, - "document": "manifest", - "end": 112, - "line": 4, - "start": 93 - }, - { - "column": 51, - "document": "manifest", - "end": 111, - "line": 4, - "start": 105 - } - ], - "pointer": "/groups/1/condition/agents/0", - "span": { - "column": 41, - "document": "manifest", - "end": 899, - "line": 17, - "start": 893 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 39, - "document": "manifest", - "end": 112, - "line": 4, - "start": 93 - }, - { - "column": 40, - "document": "manifest", - "end": 103, - "line": 4, - "start": 94 - } - ], - "pointer": "/groups/1/condition/agents/1", - "span": { - "column": 41, - "document": "manifest", - "end": 899, - "line": 17, - "start": 893 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 98, - "document": "manifest", - "end": 168, - "line": 4, - "start": 152 - } - ], - "pointer": "/groups/1/condition/platforms", - "span": { - "column": 41, - "document": "manifest", - "end": 899, - "line": 17, - "start": 893 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 98, - "document": "manifest", - "end": 168, - "line": 4, - "start": 152 - }, - { - "column": 99, - "document": "manifest", - "end": 159, - "line": 4, - "start": 153 - } - ], - "pointer": "/groups/1/condition/platforms/0", - "span": { - "column": 41, - "document": "manifest", - "end": 899, - "line": 17, - "start": 893 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 98, - "document": "manifest", - "end": 168, - "line": 4, - "start": 152 - }, - { - "column": 107, - "document": "manifest", - "end": 167, - "line": 4, - "start": 161 - } - ], - "pointer": "/groups/1/condition/platforms/1", - "span": { - "column": 41, - "document": "manifest", - "end": 899, - "line": 17, - "start": 893 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 68, - "document": "manifest", - "end": 139, - "line": 4, - "start": 122 - } - ], - "pointer": "/groups/1/condition/scopes", - "span": { - "column": 41, - "document": "manifest", - "end": 899, - "line": 17, - "start": 893 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 68, - "document": "manifest", - "end": 139, - "line": 4, - "start": 122 - }, - { - "column": 76, - "document": "manifest", - "end": 138, - "line": 4, - "start": 130 - } - ], - "pointer": "/groups/1/condition/scopes/0", - "span": { - "column": 41, - "document": "manifest", - "end": 899, - "line": 17, - "start": 893 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 68, - "document": "manifest", - "end": 139, - "line": 4, - "start": 122 - }, - { - "column": 69, - "document": "manifest", - "end": 128, - "line": 4, - "start": 123 - } - ], - "pointer": "/groups/1/condition/scopes/1", - "span": { - "column": 41, - "document": "manifest", - "end": 899, - "line": 17, - "start": 893 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/1/name", - "span": { - "column": 25, - "document": "manifest", - "end": 880, - "line": 17, - "start": 877 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/1/uses", - "span": { - "column": 12, - "document": "manifest", - "end": 900, - "line": 17, - "start": 864 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources", - "span": { - "column": 12, - "document": "manifest", - "end": 357, - "line": 8, - "start": 246 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/0", - "span": { - "column": 5, - "document": "manifest", - "end": 352, - "line": 10, - "start": 321 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/0/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 352, - "line": 10, - "start": 321 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/0/name", - "span": { - "column": 19, - "document": "manifest", - "end": 338, - "line": 10, - "start": 335 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/0/path", - "span": { - "column": 30, - "document": "manifest", - "end": 351, - "line": 10, - "start": 346 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/0/requirement", - "span": { - "column": 5, - "document": "manifest", - "end": 352, - "line": 10, - "start": 321 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/0/subpath", - "span": { - "column": 5, - "document": "manifest", - "end": 352, - "line": 10, - "start": 321 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/1", - "span": { - "column": 5, - "document": "manifest", - "end": 315, - "line": 9, - "start": 252 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/1/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 315, - "line": 9, - "start": 252 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/1/name", - "span": { - "column": 19, - "document": "manifest", - "end": 269, - "line": 9, - "start": 266 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/1/requirement", - "span": { - "column": 50, - "document": "manifest", - "end": 314, - "line": 9, - "start": 297 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/1/requirement/upToNextMinor", - "span": { - "column": 50, - "document": "manifest", - "end": 304, - "line": 9, - "start": 297 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/1/subpath", - "span": { - "column": 5, - "document": "manifest", - "end": 315, - "line": 9, - "start": 252 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/1/url", - "span": { - "column": 29, - "document": "manifest", - "end": 295, - "line": 9, - "start": 276 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses", - "span": { - "column": 9, - "document": "manifest", - "end": 991, - "line": 18, - "start": 930 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses/0", - "span": { - "column": 10, - "document": "manifest", - "end": 985, - "line": 18, - "start": 931 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - } - ], - "pointer": "/uses/0/condition", - "span": { - "column": 57, - "document": "manifest", - "end": 984, - "line": 18, - "start": 978 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 39, - "document": "manifest", - "end": 112, - "line": 4, - "start": 93 - } - ], - "pointer": "/uses/0/condition/agents", - "span": { - "column": 57, - "document": "manifest", - "end": 984, - "line": 18, - "start": 978 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 39, - "document": "manifest", - "end": 112, - "line": 4, - "start": 93 - }, - { - "column": 51, - "document": "manifest", - "end": 111, - "line": 4, - "start": 105 - } - ], - "pointer": "/uses/0/condition/agents/0", - "span": { - "column": 57, - "document": "manifest", - "end": 984, - "line": 18, - "start": 978 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 39, - "document": "manifest", - "end": 112, - "line": 4, - "start": 93 - }, - { - "column": 40, - "document": "manifest", - "end": 103, - "line": 4, - "start": 94 - } - ], - "pointer": "/uses/0/condition/agents/1", - "span": { - "column": 57, - "document": "manifest", - "end": 984, - "line": 18, - "start": 978 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 98, - "document": "manifest", - "end": 168, - "line": 4, - "start": 152 - } - ], - "pointer": "/uses/0/condition/platforms", - "span": { - "column": 57, - "document": "manifest", - "end": 984, - "line": 18, - "start": 978 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 98, - "document": "manifest", - "end": 168, - "line": 4, - "start": 152 - }, - { - "column": 99, - "document": "manifest", - "end": 159, - "line": 4, - "start": 153 - } - ], - "pointer": "/uses/0/condition/platforms/0", - "span": { - "column": 57, - "document": "manifest", - "end": 984, - "line": 18, - "start": 978 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 98, - "document": "manifest", - "end": 168, - "line": 4, - "start": 152 - }, - { - "column": 107, - "document": "manifest", - "end": 167, - "line": 4, - "start": 161 - } - ], - "pointer": "/uses/0/condition/platforms/1", - "span": { - "column": 57, - "document": "manifest", - "end": 984, - "line": 18, - "start": 978 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 68, - "document": "manifest", - "end": 139, - "line": 4, - "start": 122 - } - ], - "pointer": "/uses/0/condition/scopes", - "span": { - "column": 57, - "document": "manifest", - "end": 984, - "line": 18, - "start": 978 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 68, - "document": "manifest", - "end": 139, - "line": 4, - "start": 122 - }, - { - "column": 76, - "document": "manifest", - "end": 138, - "line": 4, - "start": 130 - } - ], - "pointer": "/uses/0/condition/scopes/0", - "span": { - "column": 57, - "document": "manifest", - "end": 984, - "line": 18, - "start": 978 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 25, - "document": "manifest", - "end": 169, - "line": 4, - "start": 79 - }, - { - "column": 68, - "document": "manifest", - "end": 139, - "line": 4, - "start": 122 - }, - { - "column": 69, - "document": "manifest", - "end": 128, - "line": 4, - "start": 123 - } - ], - "pointer": "/uses/0/condition/scopes/1", - "span": { - "column": 57, - "document": "manifest", - "end": 984, - "line": 18, - "start": 978 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/uses/0/kind", - "span": { - "column": 10, - "document": "manifest", - "end": 985, - "line": 18, - "start": 931 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses/0/name", - "span": { - "column": 23, - "document": "manifest", - "end": 952, - "line": 18, - "start": 944 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses/0/source", - "span": { - "column": 41, - "document": "manifest", - "end": 965, - "line": 18, - "start": 962 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses/1", - "span": { - "column": 66, - "document": "manifest", - "end": 990, - "line": 18, - "start": 987 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/uses/1/condition", - "span": { - "column": 66, - "document": "manifest", - "end": 990, - "line": 18, - "start": 987 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/uses/1/kind", - "span": { - "column": 66, - "document": "manifest", - "end": 990, - "line": 18, - "start": 987 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/uses/1/name", - "span": { - "column": 66, - "document": "manifest", - "end": 990, - "line": 18, - "start": 987 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/uses/1/source", - "span": { - "column": 66, - "document": "manifest", - "end": 990, - "line": 18, - "start": 987 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/watch", - "span": { - "column": 10, - "document": "manifest", - "end": 1012, - "line": 19, - "start": 1002 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/watch/0", - "span": { - "column": 16, - "document": "manifest", - "end": 1011, - "line": 19, - "start": 1008 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/watch/1", - "span": { - "column": 11, - "document": "manifest", - "end": 1006, - "line": 19, - "start": 1003 - } - } - ], - "schemaVersion": 1, - "sourceDigest": "sha256:73195ad7498783349149ee18e3f9ce13fae38d8c682d449bdd9d2861bc6f1c74" -} diff --git a/Tests/AgentsManifestTests/Fixtures/DumpSymbolic.swift.txt b/Tests/AgentsManifestTests/Fixtures/DumpSymbolic.swift.txt deleted file mode 100644 index 84b18ae..0000000 --- a/Tests/AgentsManifestTests/Fixtures/DumpSymbolic.swift.txt +++ /dev/null @@ -1,20 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let shared: Condition = .when(agents: [.openCode, .codex], scopes: [.user, .project], platforms: [.linux, .macOS]) -let agents = Agents( - defaultAgents: [], - exports: ["z", "a"], - sources: [ - .source(name: "z", url: "intranet/team.git", "1.2.0"..<"1.3.0"), - .source(name: "a", path: "./a"), - ], - components: [ - .instructions(sections: ["own", .section(name: "rule", source: "z", condition: shared)], chatGPT: [.prompt(name: "z", sections: []), .prompt(name: "a", sections: ["own"])], agents: []), - .skills(source: "z", select: ["z", "a"], exclude: ["z", "a"], overrides: [.skill(name: "z", agents: []), .skill(name: "a")]), - .plugin(name: "bundle", path: "bundle", source: "z", exclude: [.hook(name: "aaa"), .command(name: "zzz"), .hook(name: "bbb"), .skill(name: "ccc")]), - ], - groups: [.group(name: "z", condition: shared), .group(name: "a")], - uses: [.group(name: "review", source: "z", condition: shared), "a"], - watch: ["z", "a"] -) diff --git a/Tests/AgentsManifestTests/Fixtures/ExportedGroup.swift.txt b/Tests/AgentsManifestTests/Fixtures/ExportedGroup.swift.txt deleted file mode 100644 index 91bbf6a..0000000 --- a/Tests/AgentsManifestTests/Fixtures/ExportedGroup.swift.txt +++ /dev/null @@ -1,16 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - exports: ["review"], - groups: [ - .group( - name: "review", - components: [ - .instructions(sections: ["review-principles"], agents: [.claudeCode, .codex]), - .skills(source: ".", select: ["review"], mode: .copy, agents: [.claudeCode, .codex]), - ], - condition: .when(scopes: [.project]) - ), - ] -) diff --git a/Tests/AgentsManifestTests/Fixtures/InstructionRecipients.swift.txt b/Tests/AgentsManifestTests/Fixtures/InstructionRecipients.swift.txt deleted file mode 100644 index a8fb88d..0000000 --- a/Tests/AgentsManifestTests/Fixtures/InstructionRecipients.swift.txt +++ /dev/null @@ -1,11 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - components: [ - .instructions( - sections: ["guide", "code-review-rules"], - agents: [.claudeCode, .codex] - ), - ] -) diff --git a/Tests/AgentsManifestTests/Fixtures/LiteralCoverage.dump.json b/Tests/AgentsManifestTests/Fixtures/LiteralCoverage.dump.json deleted file mode 100644 index b29b3e9..0000000 --- a/Tests/AgentsManifestTests/Fixtures/LiteralCoverage.dump.json +++ /dev/null @@ -1,6637 +0,0 @@ -{ - "declaration": { - "components": [ - { - "agents": null, - "condition": null, - "kind": "mcpServer", - "name": "tools", - "native": {}, - "transport": { - "arguments": [], - "environment": { - "LEVEL": { - "kind": "literal", - "value": "info" - }, - "TOKEN": { - "kind": "secret", - "value": "token" - } - }, - "executable": "server", - "kind": "stdio", - "workingDirectory": null - } - }, - { - "agents": null, - "condition": null, - "kind": "mcpServer", - "name": "sse", - "native": {}, - "transport": { - "headers": {}, - "kind": "sse", - "url": "https://example.org/events" - } - }, - { - "agents": null, - "condition": null, - "description": "Review", - "kind": "command", - "name": "review", - "native": {}, - "parameters": [], - "prompt": { - "kind": "literal", - "value": "Review invariants." - } - }, - { - "agents": null, - "chatGPT": [], - "condition": null, - "kind": "instructions", - "native": {}, - "sections": [ - { - "condition": null, - "name": "guide", - "source": null - } - ] - }, - { - "agents": null, - "condition": null, - "exclude": [], - "kind": "skills", - "mode": null, - "native": {}, - "overrides": [ - { - "agents": [ - "codex" - ], - "mode": "copy", - "name": "review" - } - ], - "select": [ - "review", - "testing" - ], - "source": "team" - }, - { - "agents": null, - "condition": null, - "initializationOptions": { - "config": { - "kind": "object", - "value": { - "array": { - "kind": "array", - "value": [ - { - "kind": "integer", - "value": 1 - }, - { - "kind": "string", - "value": "two" - }, - { - "kind": "boolean", - "value": false - }, - { - "kind": "null" - } - ] - }, - "boolean": { - "kind": "boolean", - "value": true - }, - "decimal": { - "kind": "decimal", - "value": "1.25" - }, - "integer": { - "kind": "integer", - "value": -1 - }, - "null": { - "kind": "null" - }, - "object": { - "kind": "object", - "value": { - "enabled": { - "kind": "boolean", - "value": true - } - } - }, - "string": { - "kind": "string", - "value": "value" - } - } - } - }, - "kind": "lspServer", - "languages": { - ".swift": "swift" - }, - "name": "swift", - "native": {}, - "run": { - "arguments": [], - "environment": { - "LEVEL": { - "kind": "literal", - "value": "info" - }, - "TOKEN": { - "kind": "secret", - "value": "token" - } - }, - "executable": "server", - "kind": "executable", - "workingDirectory": { - "path": "tools", - "source": "vendor" - } - } - }, - { - "agents": null, - "condition": null, - "kind": "permissions", - "name": "policy", - "native": {}, - "rules": [ - { - "kind": "allow", - "operation": { - "kind": "read" - }, - "pattern": "Sources/**" - }, - { - "kind": "ask", - "operation": { - "kind": "write" - }, - "pattern": "**" - }, - { - "kind": "deny", - "operation": { - "kind": "execute" - }, - "pattern": "rm *" - }, - { - "kind": "deny", - "operation": { - "kind": "tool", - "value": "fetch" - }, - "pattern": "*" - } - ] - }, - { - "agents": null, - "condition": null, - "exclude": [ - { - "kind": "command", - "name": "a" - }, - { - "kind": "hook", - "name": "a" - }, - { - "kind": "ignore", - "name": "a" - }, - { - "kind": "instruction", - "name": "a" - }, - { - "kind": "lspServer", - "name": "a" - }, - { - "kind": "mcpServer", - "name": "a" - }, - { - "kind": "permissions", - "name": "a" - }, - { - "kind": "plugin", - "name": "a" - }, - { - "kind": "skill", - "name": "a" - }, - { - "kind": "subagent", - "name": "a" - } - ], - "kind": "plugin", - "mode": "components", - "name": "tools", - "native": {}, - "path": "plugins/tools", - "select": [ - "skills", - "instructions", - "mcpServer", - "hook", - "subagent", - "command", - "lspServer", - "permissions", - "ignore", - "plugin" - ], - "source": "vendor" - }, - { - "agents": [ - "codex" - ], - "condition": null, - "event": { - "kind": "native", - "value": "Event" - }, - "kind": "hook", - "matcher": null, - "name": "native", - "native": {}, - "run": { - "arguments": [], - "environment": { - "LEVEL": { - "kind": "literal", - "value": "info" - }, - "TOKEN": { - "kind": "secret", - "value": "token" - } - }, - "executable": "server", - "kind": "executable", - "workingDirectory": { - "path": "tools", - "source": "vendor" - } - }, - "timeoutSeconds": null - }, - { - "agents": [], - "condition": { - "agents": null, - "platforms": [ - "linux", - "macos" - ], - "scopes": [ - "project", - "user" - ] - }, - "kind": "ignore", - "name": "context", - "native": {}, - "patterns": [], - "purpose": "context" - }, - { - "agents": null, - "condition": null, - "description": "No tools", - "kind": "subagent", - "model": null, - "name": "empty-tools", - "native": {}, - "prompt": { - "kind": "literal", - "value": "Read" - }, - "tools": [] - } - ], - "defaultAgents": null, - "exports": [ - "review" - ], - "groups": [ - { - "components": [], - "condition": null, - "name": "review", - "uses": [] - } - ], - "sources": [ - { - "kind": "local", - "name": "team", - "path": "team", - "requirement": null, - "subpath": null - }, - { - "kind": "local", - "name": "vendor", - "path": "vendor", - "requirement": null, - "subpath": null - } - ], - "uses": [ - { - "condition": null, - "kind": "local", - "name": "review", - "source": null - }, - { - "condition": { - "agents": [ - "codex" - ], - "platforms": null, - "scopes": null - }, - "kind": "local", - "name": "review", - "source": null - } - ], - "watch": [] - }, - "diagnostics": [], - "kind": "manifest", - "languageVersion": "1.0", - "locations": [ - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "", - "span": { - "column": 14, - "document": "manifest", - "end": 2871, - "line": 25, - "start": 1285 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components", - "span": { - "column": 15, - "document": "manifest", - "end": 2756, - "line": 28, - "start": 1421 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0", - "span": { - "column": 5, - "document": "manifest", - "end": 1507, - "line": 29, - "start": 1427 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 1507, - "line": 29, - "start": 1427 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 1507, - "line": 29, - "start": 1427 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/0/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 1507, - "line": 29, - "start": 1427 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/name", - "span": { - "column": 22, - "document": "manifest", - "end": 1451, - "line": 29, - "start": 1444 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/native", - "span": { - "column": 5, - "document": "manifest", - "end": 1507, - "line": 29, - "start": 1427 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/transport", - "span": { - "column": 42, - "document": "manifest", - "end": 1506, - "line": 29, - "start": 1464 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/transport/arguments", - "span": { - "column": 42, - "document": "manifest", - "end": 1506, - "line": 29, - "start": 1464 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - } - ], - "pointer": "/components/0/transport/environment", - "span": { - "column": 72, - "document": "manifest", - "end": 1505, - "line": 29, - "start": 1494 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 53, - "document": "manifest", - "end": 493, - "line": 12, - "start": 487 - } - ], - "pointer": "/components/0/transport/environment/LEVEL", - "span": { - "column": 72, - "document": "manifest", - "end": 1505, - "line": 29, - "start": 1494 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 53, - "document": "manifest", - "end": 493, - "line": 12, - "start": 487 - } - ], - "pointer": "/components/0/transport/environment/LEVEL/kind", - "span": { - "column": 72, - "document": "manifest", - "end": 1505, - "line": 29, - "start": 1494 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 53, - "document": "manifest", - "end": 493, - "line": 12, - "start": 487 - } - ], - "pointer": "/components/0/transport/environment/LEVEL/value", - "span": { - "column": 72, - "document": "manifest", - "end": 1505, - "line": 29, - "start": 1494 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 70, - "document": "manifest", - "end": 520, - "line": 12, - "start": 504 - } - ], - "pointer": "/components/0/transport/environment/TOKEN", - "span": { - "column": 72, - "document": "manifest", - "end": 1505, - "line": 29, - "start": 1494 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 70, - "document": "manifest", - "end": 520, - "line": 12, - "start": 504 - } - ], - "pointer": "/components/0/transport/environment/TOKEN/kind", - "span": { - "column": 72, - "document": "manifest", - "end": 1505, - "line": 29, - "start": 1494 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 70, - "document": "manifest", - "end": 520, - "line": 12, - "start": 504 - }, - { - "column": 78, - "document": "manifest", - "end": 519, - "line": 12, - "start": 512 - } - ], - "pointer": "/components/0/transport/environment/TOKEN/value", - "span": { - "column": 72, - "document": "manifest", - "end": 1505, - "line": 29, - "start": 1494 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/transport/executable", - "span": { - "column": 49, - "document": "manifest", - "end": 1479, - "line": 29, - "start": 1471 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/0/transport/kind", - "span": { - "column": 42, - "document": "manifest", - "end": 1506, - "line": 29, - "start": 1464 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/transport/workingDirectory", - "span": { - "column": 42, - "document": "manifest", - "end": 1506, - "line": 29, - "start": 1464 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1", - "span": { - "column": 5, - "document": "manifest", - "end": 1588, - "line": 30, - "start": 1513 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 1588, - "line": 30, - "start": 1513 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 1588, - "line": 30, - "start": 1513 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/1/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 1588, - "line": 30, - "start": 1513 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/name", - "span": { - "column": 22, - "document": "manifest", - "end": 1535, - "line": 30, - "start": 1530 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/native", - "span": { - "column": 5, - "document": "manifest", - "end": 1588, - "line": 30, - "start": 1513 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/transport", - "span": { - "column": 40, - "document": "manifest", - "end": 1587, - "line": 30, - "start": 1548 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/transport/headers", - "span": { - "column": 40, - "document": "manifest", - "end": 1587, - "line": 30, - "start": 1548 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/1/transport/kind", - "span": { - "column": 40, - "document": "manifest", - "end": 1587, - "line": 30, - "start": 1548 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/transport/url", - "span": { - "column": 50, - "document": "manifest", - "end": 1586, - "line": 30, - "start": 1558 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 754, - "line": 16, - "start": 672 - } - ], - "pointer": "/components/10", - "span": { - "column": 5, - "document": "manifest", - "end": 2752, - "line": 39, - "start": 2742 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 754, - "line": 16, - "start": 672 - } - ], - "pointer": "/components/10/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 2752, - "line": 39, - "start": 2742 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 754, - "line": 16, - "start": 672 - } - ], - "pointer": "/components/10/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 2752, - "line": 39, - "start": 2742 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 754, - "line": 16, - "start": 672 - }, - { - "column": 73, - "document": "manifest", - "end": 726, - "line": 16, - "start": 716 - } - ], - "pointer": "/components/10/description", - "span": { - "column": 5, - "document": "manifest", - "end": 2752, - "line": 39, - "start": 2742 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 754, - "line": 16, - "start": 672 - } - ], - "pointer": "/components/10/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 2752, - "line": 39, - "start": 2742 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 754, - "line": 16, - "start": 672 - } - ], - "pointer": "/components/10/model", - "span": { - "column": 5, - "document": "manifest", - "end": 2752, - "line": 39, - "start": 2742 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 754, - "line": 16, - "start": 672 - }, - { - "column": 45, - "document": "manifest", - "end": 701, - "line": 16, - "start": 688 - } - ], - "pointer": "/components/10/name", - "span": { - "column": 5, - "document": "manifest", - "end": 2752, - "line": 39, - "start": 2742 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 754, - "line": 16, - "start": 672 - } - ], - "pointer": "/components/10/native", - "span": { - "column": 5, - "document": "manifest", - "end": 2752, - "line": 39, - "start": 2742 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 754, - "line": 16, - "start": 672 - }, - { - "column": 93, - "document": "manifest", - "end": 742, - "line": 16, - "start": 736 - } - ], - "pointer": "/components/10/prompt", - "span": { - "column": 5, - "document": "manifest", - "end": 2752, - "line": 39, - "start": 2742 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 754, - "line": 16, - "start": 672 - }, - { - "column": 93, - "document": "manifest", - "end": 742, - "line": 16, - "start": 736 - } - ], - "pointer": "/components/10/prompt/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 2752, - "line": 39, - "start": 2742 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 754, - "line": 16, - "start": 672 - }, - { - "column": 93, - "document": "manifest", - "end": 742, - "line": 16, - "start": 736 - } - ], - "pointer": "/components/10/prompt/value", - "span": { - "column": 5, - "document": "manifest", - "end": 2752, - "line": 39, - "start": 2742 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 754, - "line": 16, - "start": 672 - }, - { - "column": 108, - "document": "manifest", - "end": 753, - "line": 16, - "start": 751 - } - ], - "pointer": "/components/10/tools", - "span": { - "column": 5, - "document": "manifest", - "end": 2752, - "line": 39, - "start": 2742 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2", - "span": { - "column": 5, - "document": "manifest", - "end": 1655, - "line": 31, - "start": 1594 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 1655, - "line": 31, - "start": 1594 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 1655, - "line": 31, - "start": 1594 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/description", - "span": { - "column": 43, - "document": "manifest", - "end": 1640, - "line": 31, - "start": 1632 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/2/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 1655, - "line": 31, - "start": 1594 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/name", - "span": { - "column": 20, - "document": "manifest", - "end": 1617, - "line": 31, - "start": 1609 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/native", - "span": { - "column": 5, - "document": "manifest", - "end": 1655, - "line": 31, - "start": 1594 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/parameters", - "span": { - "column": 5, - "document": "manifest", - "end": 1655, - "line": 31, - "start": 1594 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 101, - "line": 4, - "start": 81 - } - ], - "pointer": "/components/2/prompt", - "span": { - "column": 61, - "document": "manifest", - "end": 1654, - "line": 31, - "start": 1650 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 101, - "line": 4, - "start": 81 - } - ], - "pointer": "/components/2/prompt/kind", - "span": { - "column": 61, - "document": "manifest", - "end": 1654, - "line": 31, - "start": 1650 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 27, - "document": "manifest", - "end": 101, - "line": 4, - "start": 81 - } - ], - "pointer": "/components/2/prompt/value", - "span": { - "column": 61, - "document": "manifest", - "end": 1654, - "line": 31, - "start": 1650 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3", - "span": { - "column": 5, - "document": "manifest", - "end": 1695, - "line": 32, - "start": 1661 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 1695, - "line": 32, - "start": 1661 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/chatGPT", - "span": { - "column": 5, - "document": "manifest", - "end": 1695, - "line": 32, - "start": 1661 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 1695, - "line": 32, - "start": 1661 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/3/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 1695, - "line": 32, - "start": 1661 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/native", - "span": { - "column": 5, - "document": "manifest", - "end": 1695, - "line": 32, - "start": 1661 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/sections", - "span": { - "column": 29, - "document": "manifest", - "end": 1694, - "line": 32, - "start": 1685 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 33, - "document": "manifest", - "end": 141, - "line": 5, - "start": 134 - } - ], - "pointer": "/components/3/sections/0", - "span": { - "column": 30, - "document": "manifest", - "end": 1693, - "line": 32, - "start": 1686 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 33, - "document": "manifest", - "end": 141, - "line": 5, - "start": 134 - } - ], - "pointer": "/components/3/sections/0/condition", - "span": { - "column": 30, - "document": "manifest", - "end": 1693, - "line": 32, - "start": 1686 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 33, - "document": "manifest", - "end": 141, - "line": 5, - "start": 134 - } - ], - "pointer": "/components/3/sections/0/name", - "span": { - "column": 30, - "document": "manifest", - "end": 1693, - "line": 32, - "start": 1686 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 33, - "document": "manifest", - "end": 141, - "line": 5, - "start": 134 - } - ], - "pointer": "/components/3/sections/0/source", - "span": { - "column": 30, - "document": "manifest", - "end": 1693, - "line": 32, - "start": 1686 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4", - "span": { - "column": 5, - "document": "manifest", - "end": 1811, - "line": 33, - "start": 1701 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 1811, - "line": 33, - "start": 1701 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 1811, - "line": 33, - "start": 1701 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/exclude", - "span": { - "column": 5, - "document": "manifest", - "end": 1811, - "line": 33, - "start": 1701 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/4/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 1811, - "line": 33, - "start": 1701 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/mode", - "span": { - "column": 5, - "document": "manifest", - "end": 1811, - "line": 33, - "start": 1701 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/native", - "span": { - "column": 5, - "document": "manifest", - "end": 1811, - "line": 33, - "start": 1701 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/overrides", - "span": { - "column": 59, - "document": "manifest", - "end": 1810, - "line": 33, - "start": 1755 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/overrides/0", - "span": { - "column": 60, - "document": "manifest", - "end": 1809, - "line": 33, - "start": 1756 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/overrides/0/agents", - "span": { - "column": 104, - "document": "manifest", - "end": 1808, - "line": 33, - "start": 1800 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/overrides/0/agents/0", - "span": { - "column": 105, - "document": "manifest", - "end": 1807, - "line": 33, - "start": 1801 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/overrides/0/mode", - "span": { - "column": 89, - "document": "manifest", - "end": 1790, - "line": 33, - "start": 1785 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/overrides/0/name", - "span": { - "column": 73, - "document": "manifest", - "end": 1777, - "line": 33, - "start": 1769 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 33, - "document": "manifest", - "end": 232, - "line": 7, - "start": 211 - } - ], - "pointer": "/components/4/select", - "span": { - "column": 37, - "document": "manifest", - "end": 1742, - "line": 33, - "start": 1733 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 33, - "document": "manifest", - "end": 232, - "line": 7, - "start": 211 - }, - { - "column": 34, - "document": "manifest", - "end": 220, - "line": 7, - "start": 212 - } - ], - "pointer": "/components/4/select/0", - "span": { - "column": 37, - "document": "manifest", - "end": 1742, - "line": 33, - "start": 1733 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 33, - "document": "manifest", - "end": 232, - "line": 7, - "start": 211 - }, - { - "column": 44, - "document": "manifest", - "end": 231, - "line": 7, - "start": 222 - } - ], - "pointer": "/components/4/select/1", - "span": { - "column": 37, - "document": "manifest", - "end": 1742, - "line": 33, - "start": 1733 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/source", - "span": { - "column": 21, - "document": "manifest", - "end": 1723, - "line": 33, - "start": 1717 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5", - "span": { - "column": 5, - "document": "manifest", - "end": 1941, - "line": 34, - "start": 1817 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 1941, - "line": 34, - "start": 1817 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 1941, - "line": 34, - "start": 1817 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/initializationOptions", - "span": { - "column": 103, - "document": "manifest", - "end": 1940, - "line": 34, - "start": 1915 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - } - ], - "pointer": "/components/5/initializationOptions/config", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - } - ], - "pointer": "/components/5/initializationOptions/config/kind", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - } - ], - "pointer": "/components/5/initializationOptions/config/value", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 12, - "document": "manifest", - "end": 374, - "line": 10, - "start": 352 - } - ], - "pointer": "/components/5/initializationOptions/config/value/array", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 12, - "document": "manifest", - "end": 374, - "line": 10, - "start": 352 - } - ], - "pointer": "/components/5/initializationOptions/config/value/array/kind", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 12, - "document": "manifest", - "end": 374, - "line": 10, - "start": 352 - } - ], - "pointer": "/components/5/initializationOptions/config/value/array/value", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 12, - "document": "manifest", - "end": 374, - "line": 10, - "start": 352 - }, - { - "column": 13, - "document": "manifest", - "end": 354, - "line": 10, - "start": 353 - } - ], - "pointer": "/components/5/initializationOptions/config/value/array/value/0", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 12, - "document": "manifest", - "end": 374, - "line": 10, - "start": 352 - }, - { - "column": 13, - "document": "manifest", - "end": 354, - "line": 10, - "start": 353 - } - ], - "pointer": "/components/5/initializationOptions/config/value/array/value/0/kind", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 12, - "document": "manifest", - "end": 374, - "line": 10, - "start": 352 - }, - { - "column": 13, - "document": "manifest", - "end": 354, - "line": 10, - "start": 353 - } - ], - "pointer": "/components/5/initializationOptions/config/value/array/value/0/value", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 12, - "document": "manifest", - "end": 374, - "line": 10, - "start": 352 - }, - { - "column": 16, - "document": "manifest", - "end": 361, - "line": 10, - "start": 356 - } - ], - "pointer": "/components/5/initializationOptions/config/value/array/value/1", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 12, - "document": "manifest", - "end": 374, - "line": 10, - "start": 352 - }, - { - "column": 16, - "document": "manifest", - "end": 361, - "line": 10, - "start": 356 - } - ], - "pointer": "/components/5/initializationOptions/config/value/array/value/1/kind", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 12, - "document": "manifest", - "end": 374, - "line": 10, - "start": 352 - }, - { - "column": 16, - "document": "manifest", - "end": 361, - "line": 10, - "start": 356 - } - ], - "pointer": "/components/5/initializationOptions/config/value/array/value/1/value", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 12, - "document": "manifest", - "end": 374, - "line": 10, - "start": 352 - }, - { - "column": 23, - "document": "manifest", - "end": 368, - "line": 10, - "start": 363 - } - ], - "pointer": "/components/5/initializationOptions/config/value/array/value/2", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 12, - "document": "manifest", - "end": 374, - "line": 10, - "start": 352 - }, - { - "column": 23, - "document": "manifest", - "end": 368, - "line": 10, - "start": 363 - } - ], - "pointer": "/components/5/initializationOptions/config/value/array/value/2/kind", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 12, - "document": "manifest", - "end": 374, - "line": 10, - "start": 352 - }, - { - "column": 23, - "document": "manifest", - "end": 368, - "line": 10, - "start": 363 - } - ], - "pointer": "/components/5/initializationOptions/config/value/array/value/2/value", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 12, - "document": "manifest", - "end": 374, - "line": 10, - "start": 352 - }, - { - "column": 30, - "document": "manifest", - "end": 373, - "line": 10, - "start": 370 - } - ], - "pointer": "/components/5/initializationOptions/config/value/array/value/3", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 12, - "document": "manifest", - "end": 374, - "line": 10, - "start": 352 - }, - { - "column": 30, - "document": "manifest", - "end": 373, - "line": 10, - "start": 370 - } - ], - "pointer": "/components/5/initializationOptions/config/value/array/value/3/kind", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 48, - "document": "manifest", - "end": 326, - "line": 9, - "start": 322 - } - ], - "pointer": "/components/5/initializationOptions/config/value/boolean", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 48, - "document": "manifest", - "end": 326, - "line": 9, - "start": 322 - } - ], - "pointer": "/components/5/initializationOptions/config/value/boolean/kind", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 48, - "document": "manifest", - "end": 326, - "line": 9, - "start": 322 - } - ], - "pointer": "/components/5/initializationOptions/config/value/boolean/value", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 76, - "document": "manifest", - "end": 432, - "line": 10, - "start": 416 - } - ], - "pointer": "/components/5/initializationOptions/config/value/decimal", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 76, - "document": "manifest", - "end": 432, - "line": 10, - "start": 416 - } - ], - "pointer": "/components/5/initializationOptions/config/value/decimal/kind", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 76, - "document": "manifest", - "end": 432, - "line": 10, - "start": 416 - }, - { - "column": 85, - "document": "manifest", - "end": 431, - "line": 10, - "start": 425 - } - ], - "pointer": "/components/5/initializationOptions/config/value/decimal/value", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 33, - "document": "manifest", - "end": 309, - "line": 9, - "start": 307 - } - ], - "pointer": "/components/5/initializationOptions/config/value/integer", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 33, - "document": "manifest", - "end": 309, - "line": 9, - "start": 307 - } - ], - "pointer": "/components/5/initializationOptions/config/value/integer/kind", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 33, - "document": "manifest", - "end": 309, - "line": 9, - "start": 307 - } - ], - "pointer": "/components/5/initializationOptions/config/value/integer/value", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 62, - "document": "manifest", - "end": 339, - "line": 9, - "start": 336 - } - ], - "pointer": "/components/5/initializationOptions/config/value/null", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 62, - "document": "manifest", - "end": 339, - "line": 9, - "start": 336 - } - ], - "pointer": "/components/5/initializationOptions/config/value/null/kind", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 46, - "document": "manifest", - "end": 403, - "line": 10, - "start": 386 - } - ], - "pointer": "/components/5/initializationOptions/config/value/object", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 46, - "document": "manifest", - "end": 403, - "line": 10, - "start": 386 - } - ], - "pointer": "/components/5/initializationOptions/config/value/object/kind", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 46, - "document": "manifest", - "end": 403, - "line": 10, - "start": 386 - } - ], - "pointer": "/components/5/initializationOptions/config/value/object/value", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 46, - "document": "manifest", - "end": 403, - "line": 10, - "start": 386 - }, - { - "column": 58, - "document": "manifest", - "end": 402, - "line": 10, - "start": 398 - } - ], - "pointer": "/components/5/initializationOptions/config/value/object/value/enabled", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 46, - "document": "manifest", - "end": 403, - "line": 10, - "start": 386 - }, - { - "column": 58, - "document": "manifest", - "end": 402, - "line": 10, - "start": 398 - } - ], - "pointer": "/components/5/initializationOptions/config/value/object/value/enabled/kind", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 46, - "document": "manifest", - "end": 403, - "line": 10, - "start": 386 - }, - { - "column": 58, - "document": "manifest", - "end": 402, - "line": 10, - "start": 398 - } - ], - "pointer": "/components/5/initializationOptions/config/value/object/value/enabled/value", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 13, - "document": "manifest", - "end": 294, - "line": 9, - "start": 287 - } - ], - "pointer": "/components/5/initializationOptions/config/value/string", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 13, - "document": "manifest", - "end": 294, - "line": 9, - "start": 287 - } - ], - "pointer": "/components/5/initializationOptions/config/value/string/kind", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 41, - "document": "manifest", - "end": 434, - "line": 8, - "start": 273 - }, - { - "column": 13, - "document": "manifest", - "end": 294, - "line": 9, - "start": 287 - } - ], - "pointer": "/components/5/initializationOptions/config/value/string/value", - "span": { - "column": 114, - "document": "manifest", - "end": 1939, - "line": 34, - "start": 1926 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/5/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 1941, - "line": 34, - "start": 1817 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/languages", - "span": { - "column": 59, - "document": "manifest", - "end": 1890, - "line": 34, - "start": 1871 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/languages/.swift", - "span": { - "column": 70, - "document": "manifest", - "end": 1889, - "line": 34, - "start": 1882 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/name", - "span": { - "column": 22, - "document": "manifest", - "end": 1841, - "line": 34, - "start": 1834 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/5/native", - "span": { - "column": 5, - "document": "manifest", - "end": 1941, - "line": 34, - "start": 1817 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - } - ], - "pointer": "/components/5/run", - "span": { - "column": 36, - "document": "manifest", - "end": 1858, - "line": 34, - "start": 1848 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - } - ], - "pointer": "/components/5/run/arguments", - "span": { - "column": 36, - "document": "manifest", - "end": 1858, - "line": 34, - "start": 1848 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 75, - "document": "manifest", - "end": 840, - "line": 17, - "start": 829 - }, - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - } - ], - "pointer": "/components/5/run/environment", - "span": { - "column": 36, - "document": "manifest", - "end": 1858, - "line": 34, - "start": 1848 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 75, - "document": "manifest", - "end": 840, - "line": 17, - "start": 829 - }, - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 53, - "document": "manifest", - "end": 493, - "line": 12, - "start": 487 - } - ], - "pointer": "/components/5/run/environment/LEVEL", - "span": { - "column": 36, - "document": "manifest", - "end": 1858, - "line": 34, - "start": 1848 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 75, - "document": "manifest", - "end": 840, - "line": 17, - "start": 829 - }, - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 53, - "document": "manifest", - "end": 493, - "line": 12, - "start": 487 - } - ], - "pointer": "/components/5/run/environment/LEVEL/kind", - "span": { - "column": 36, - "document": "manifest", - "end": 1858, - "line": 34, - "start": 1848 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 75, - "document": "manifest", - "end": 840, - "line": 17, - "start": 829 - }, - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 53, - "document": "manifest", - "end": 493, - "line": 12, - "start": 487 - } - ], - "pointer": "/components/5/run/environment/LEVEL/value", - "span": { - "column": 36, - "document": "manifest", - "end": 1858, - "line": 34, - "start": 1848 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 75, - "document": "manifest", - "end": 840, - "line": 17, - "start": 829 - }, - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 70, - "document": "manifest", - "end": 520, - "line": 12, - "start": 504 - } - ], - "pointer": "/components/5/run/environment/TOKEN", - "span": { - "column": 36, - "document": "manifest", - "end": 1858, - "line": 34, - "start": 1848 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 75, - "document": "manifest", - "end": 840, - "line": 17, - "start": 829 - }, - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 70, - "document": "manifest", - "end": 520, - "line": 12, - "start": 504 - } - ], - "pointer": "/components/5/run/environment/TOKEN/kind", - "span": { - "column": 36, - "document": "manifest", - "end": 1858, - "line": 34, - "start": 1848 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 75, - "document": "manifest", - "end": 840, - "line": 17, - "start": 829 - }, - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 70, - "document": "manifest", - "end": 520, - "line": 12, - "start": 504 - }, - { - "column": 78, - "document": "manifest", - "end": 519, - "line": 12, - "start": 512 - } - ], - "pointer": "/components/5/run/environment/TOKEN/value", - "span": { - "column": 36, - "document": "manifest", - "end": 1858, - "line": 34, - "start": 1848 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 52, - "document": "manifest", - "end": 814, - "line": 17, - "start": 806 - } - ], - "pointer": "/components/5/run/executable", - "span": { - "column": 36, - "document": "manifest", - "end": 1858, - "line": 34, - "start": 1848 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - } - ], - "pointer": "/components/5/run/kind", - "span": { - "column": 36, - "document": "manifest", - "end": 1858, - "line": 34, - "start": 1848 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 106, - "document": "manifest", - "end": 892, - "line": 17, - "start": 860 - } - ], - "pointer": "/components/5/run/workingDirectory", - "span": { - "column": 36, - "document": "manifest", - "end": 1858, - "line": 34, - "start": 1848 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 106, - "document": "manifest", - "end": 892, - "line": 17, - "start": 860 - }, - { - "column": 112, - "document": "manifest", - "end": 873, - "line": 17, - "start": 866 - } - ], - "pointer": "/components/5/run/workingDirectory/path", - "span": { - "column": 36, - "document": "manifest", - "end": 1858, - "line": 34, - "start": 1848 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 106, - "document": "manifest", - "end": 892, - "line": 17, - "start": 860 - }, - { - "column": 129, - "document": "manifest", - "end": 891, - "line": 17, - "start": 883 - } - ], - "pointer": "/components/5/run/workingDirectory/source", - "span": { - "column": 36, - "document": "manifest", - "end": 1858, - "line": 34, - "start": 1848 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6", - "span": { - "column": 5, - "document": "manifest", - "end": 2086, - "line": 35, - "start": 1947 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 2086, - "line": 35, - "start": 1947 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 2086, - "line": 35, - "start": 1947 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/6/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 2086, - "line": 35, - "start": 1947 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/name", - "span": { - "column": 24, - "document": "manifest", - "end": 1974, - "line": 35, - "start": 1966 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/native", - "span": { - "column": 5, - "document": "manifest", - "end": 2086, - "line": 35, - "start": 1947 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/rules", - "span": { - "column": 41, - "document": "manifest", - "end": 2085, - "line": 35, - "start": 1983 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/rules/0", - "span": { - "column": 42, - "document": "manifest", - "end": 2011, - "line": 35, - "start": 1984 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/6/rules/0/kind", - "span": { - "column": 42, - "document": "manifest", - "end": 2011, - "line": 35, - "start": 1984 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/rules/0/operation", - "span": { - "column": 49, - "document": "manifest", - "end": 1996, - "line": 35, - "start": 1991 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/6/rules/0/operation/kind", - "span": { - "column": 49, - "document": "manifest", - "end": 1996, - "line": 35, - "start": 1991 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/rules/0/pattern", - "span": { - "column": 56, - "document": "manifest", - "end": 2010, - "line": 35, - "start": 1998 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/rules/1", - "span": { - "column": 71, - "document": "manifest", - "end": 2031, - "line": 35, - "start": 2013 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/6/rules/1/kind", - "span": { - "column": 71, - "document": "manifest", - "end": 2031, - "line": 35, - "start": 2013 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/rules/1/operation", - "span": { - "column": 76, - "document": "manifest", - "end": 2024, - "line": 35, - "start": 2018 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/6/rules/1/operation/kind", - "span": { - "column": 76, - "document": "manifest", - "end": 2024, - "line": 35, - "start": 2018 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/rules/1/pattern", - "span": { - "column": 84, - "document": "manifest", - "end": 2030, - "line": 35, - "start": 2026 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/rules/2", - "span": { - "column": 91, - "document": "manifest", - "end": 2056, - "line": 35, - "start": 2033 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/6/rules/2/kind", - "span": { - "column": 91, - "document": "manifest", - "end": 2056, - "line": 35, - "start": 2033 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/rules/2/operation", - "span": { - "column": 97, - "document": "manifest", - "end": 2047, - "line": 35, - "start": 2039 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/6/rules/2/operation/kind", - "span": { - "column": 97, - "document": "manifest", - "end": 2047, - "line": 35, - "start": 2039 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/rules/2/pattern", - "span": { - "column": 107, - "document": "manifest", - "end": 2055, - "line": 35, - "start": 2049 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/rules/3", - "span": { - "column": 116, - "document": "manifest", - "end": 2084, - "line": 35, - "start": 2058 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/6/rules/3/kind", - "span": { - "column": 116, - "document": "manifest", - "end": 2084, - "line": 35, - "start": 2058 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/rules/3/operation", - "span": { - "column": 122, - "document": "manifest", - "end": 2078, - "line": 35, - "start": 2064 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/6/rules/3/operation/kind", - "span": { - "column": 122, - "document": "manifest", - "end": 2078, - "line": 35, - "start": 2064 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/rules/3/operation/value", - "span": { - "column": 128, - "document": "manifest", - "end": 2077, - "line": 35, - "start": 2070 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/6/rules/3/pattern", - "span": { - "column": 138, - "document": "manifest", - "end": 2083, - "line": 35, - "start": 2080 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7", - "span": { - "column": 5, - "document": "manifest", - "end": 2500, - "line": 36, - "start": 2092 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 2500, - "line": 36, - "start": 2092 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 2500, - "line": 36, - "start": 2092 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude", - "span": { - "column": 196, - "document": "manifest", - "end": 2499, - "line": 36, - "start": 2283 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/0", - "span": { - "column": 304, - "document": "manifest", - "end": 2410, - "line": 36, - "start": 2391 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/7/exclude/0/kind", - "span": { - "column": 304, - "document": "manifest", - "end": 2410, - "line": 36, - "start": 2391 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/0/name", - "span": { - "column": 319, - "document": "manifest", - "end": 2409, - "line": 36, - "start": 2406 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/1", - "span": { - "column": 264, - "document": "manifest", - "end": 2367, - "line": 36, - "start": 2351 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/7/exclude/1/kind", - "span": { - "column": 264, - "document": "manifest", - "end": 2367, - "line": 36, - "start": 2351 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/1/name", - "span": { - "column": 276, - "document": "manifest", - "end": 2366, - "line": 36, - "start": 2363 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/2", - "span": { - "column": 373, - "document": "manifest", - "end": 2478, - "line": 36, - "start": 2460 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/7/exclude/2/kind", - "span": { - "column": 373, - "document": "manifest", - "end": 2478, - "line": 36, - "start": 2460 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/2/name", - "span": { - "column": 387, - "document": "manifest", - "end": 2477, - "line": 36, - "start": 2474 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/3", - "span": { - "column": 216, - "document": "manifest", - "end": 2326, - "line": 36, - "start": 2303 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/7/exclude/3/kind", - "span": { - "column": 216, - "document": "manifest", - "end": 2326, - "line": 36, - "start": 2303 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/3/name", - "span": { - "column": 235, - "document": "manifest", - "end": 2325, - "line": 36, - "start": 2322 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/4", - "span": { - "column": 325, - "document": "manifest", - "end": 2433, - "line": 36, - "start": 2412 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/7/exclude/4/kind", - "span": { - "column": 325, - "document": "manifest", - "end": 2433, - "line": 36, - "start": 2412 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/4/name", - "span": { - "column": 342, - "document": "manifest", - "end": 2432, - "line": 36, - "start": 2429 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/5", - "span": { - "column": 241, - "document": "manifest", - "end": 2349, - "line": 36, - "start": 2328 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/7/exclude/5/kind", - "span": { - "column": 241, - "document": "manifest", - "end": 2349, - "line": 36, - "start": 2328 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/5/name", - "span": { - "column": 258, - "document": "manifest", - "end": 2348, - "line": 36, - "start": 2345 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/6", - "span": { - "column": 348, - "document": "manifest", - "end": 2458, - "line": 36, - "start": 2435 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/7/exclude/6/kind", - "span": { - "column": 348, - "document": "manifest", - "end": 2458, - "line": 36, - "start": 2435 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/6/name", - "span": { - "column": 367, - "document": "manifest", - "end": 2457, - "line": 36, - "start": 2454 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/7", - "span": { - "column": 393, - "document": "manifest", - "end": 2498, - "line": 36, - "start": 2480 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/7/exclude/7/kind", - "span": { - "column": 393, - "document": "manifest", - "end": 2498, - "line": 36, - "start": 2480 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/7/name", - "span": { - "column": 407, - "document": "manifest", - "end": 2497, - "line": 36, - "start": 2494 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/8", - "span": { - "column": 197, - "document": "manifest", - "end": 2301, - "line": 36, - "start": 2284 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/7/exclude/8/kind", - "span": { - "column": 197, - "document": "manifest", - "end": 2301, - "line": 36, - "start": 2284 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/8/name", - "span": { - "column": 210, - "document": "manifest", - "end": 2300, - "line": 36, - "start": 2297 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/9", - "span": { - "column": 282, - "document": "manifest", - "end": 2389, - "line": 36, - "start": 2369 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/7/exclude/9/kind", - "span": { - "column": 282, - "document": "manifest", - "end": 2389, - "line": 36, - "start": 2369 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/exclude/9/name", - "span": { - "column": 298, - "document": "manifest", - "end": 2388, - "line": 36, - "start": 2385 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/7/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 2500, - "line": 36, - "start": 2092 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/mode", - "span": { - "column": 5, - "document": "manifest", - "end": 2500, - "line": 36, - "start": 2092 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/name", - "span": { - "column": 19, - "document": "manifest", - "end": 2113, - "line": 36, - "start": 2106 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/native", - "span": { - "column": 5, - "document": "manifest", - "end": 2500, - "line": 36, - "start": 2092 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/path", - "span": { - "column": 34, - "document": "manifest", - "end": 2136, - "line": 36, - "start": 2121 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/select", - "span": { - "column": 77, - "document": "manifest", - "end": 2272, - "line": 36, - "start": 2164 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/select/0", - "span": { - "column": 78, - "document": "manifest", - "end": 2172, - "line": 36, - "start": 2165 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/select/1", - "span": { - "column": 87, - "document": "manifest", - "end": 2187, - "line": 36, - "start": 2174 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/select/2", - "span": { - "column": 102, - "document": "manifest", - "end": 2199, - "line": 36, - "start": 2189 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/select/3", - "span": { - "column": 114, - "document": "manifest", - "end": 2206, - "line": 36, - "start": 2201 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/select/4", - "span": { - "column": 121, - "document": "manifest", - "end": 2217, - "line": 36, - "start": 2208 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/select/5", - "span": { - "column": 132, - "document": "manifest", - "end": 2227, - "line": 36, - "start": 2219 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/select/6", - "span": { - "column": 142, - "document": "manifest", - "end": 2239, - "line": 36, - "start": 2229 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/select/7", - "span": { - "column": 154, - "document": "manifest", - "end": 2253, - "line": 36, - "start": 2241 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/select/8", - "span": { - "column": 168, - "document": "manifest", - "end": 2262, - "line": 36, - "start": 2255 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/select/9", - "span": { - "column": 177, - "document": "manifest", - "end": 2271, - "line": 36, - "start": 2264 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/7/source", - "span": { - "column": 59, - "document": "manifest", - "end": 2154, - "line": 36, - "start": 2146 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8", - "span": { - "column": 5, - "document": "manifest", - "end": 2587, - "line": 37, - "start": 2506 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/agents", - "span": { - "column": 77, - "document": "manifest", - "end": 2586, - "line": 37, - "start": 2578 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/agents/0", - "span": { - "column": 78, - "document": "manifest", - "end": 2585, - "line": 37, - "start": 2579 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 2587, - "line": 37, - "start": 2506 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/event", - "span": { - "column": 34, - "document": "manifest", - "end": 2551, - "line": 37, - "start": 2535 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/8/event/kind", - "span": { - "column": 34, - "document": "manifest", - "end": 2551, - "line": 37, - "start": 2535 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/event/value", - "span": { - "column": 42, - "document": "manifest", - "end": 2550, - "line": 37, - "start": 2543 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/8/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 2587, - "line": 37, - "start": 2506 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/matcher", - "span": { - "column": 5, - "document": "manifest", - "end": 2587, - "line": 37, - "start": 2506 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/name", - "span": { - "column": 17, - "document": "manifest", - "end": 2526, - "line": 37, - "start": 2518 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/native", - "span": { - "column": 5, - "document": "manifest", - "end": 2587, - "line": 37, - "start": 2506 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - } - ], - "pointer": "/components/8/run", - "span": { - "column": 57, - "document": "manifest", - "end": 2568, - "line": 37, - "start": 2558 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - } - ], - "pointer": "/components/8/run/arguments", - "span": { - "column": 57, - "document": "manifest", - "end": 2568, - "line": 37, - "start": 2558 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 75, - "document": "manifest", - "end": 840, - "line": 17, - "start": 829 - }, - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - } - ], - "pointer": "/components/8/run/environment", - "span": { - "column": 57, - "document": "manifest", - "end": 2568, - "line": 37, - "start": 2558 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 75, - "document": "manifest", - "end": 840, - "line": 17, - "start": 829 - }, - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 53, - "document": "manifest", - "end": 493, - "line": 12, - "start": 487 - } - ], - "pointer": "/components/8/run/environment/LEVEL", - "span": { - "column": 57, - "document": "manifest", - "end": 2568, - "line": 37, - "start": 2558 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 75, - "document": "manifest", - "end": 840, - "line": 17, - "start": 829 - }, - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 53, - "document": "manifest", - "end": 493, - "line": 12, - "start": 487 - } - ], - "pointer": "/components/8/run/environment/LEVEL/kind", - "span": { - "column": 57, - "document": "manifest", - "end": 2568, - "line": 37, - "start": 2558 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 75, - "document": "manifest", - "end": 840, - "line": 17, - "start": 829 - }, - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 53, - "document": "manifest", - "end": 493, - "line": 12, - "start": 487 - } - ], - "pointer": "/components/8/run/environment/LEVEL/value", - "span": { - "column": 57, - "document": "manifest", - "end": 2568, - "line": 37, - "start": 2558 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 75, - "document": "manifest", - "end": 840, - "line": 17, - "start": 829 - }, - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 70, - "document": "manifest", - "end": 520, - "line": 12, - "start": 504 - } - ], - "pointer": "/components/8/run/environment/TOKEN", - "span": { - "column": 57, - "document": "manifest", - "end": 2568, - "line": 37, - "start": 2558 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 75, - "document": "manifest", - "end": 840, - "line": 17, - "start": 829 - }, - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 70, - "document": "manifest", - "end": 520, - "line": 12, - "start": 504 - } - ], - "pointer": "/components/8/run/environment/TOKEN/kind", - "span": { - "column": 57, - "document": "manifest", - "end": 2568, - "line": 37, - "start": 2558 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 75, - "document": "manifest", - "end": 840, - "line": 17, - "start": 829 - }, - { - "column": 43, - "document": "manifest", - "end": 521, - "line": 12, - "start": 477 - }, - { - "column": 70, - "document": "manifest", - "end": 520, - "line": 12, - "start": 504 - }, - { - "column": 78, - "document": "manifest", - "end": 519, - "line": 12, - "start": 512 - } - ], - "pointer": "/components/8/run/environment/TOKEN/value", - "span": { - "column": 57, - "document": "manifest", - "end": 2568, - "line": 37, - "start": 2558 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 52, - "document": "manifest", - "end": 814, - "line": 17, - "start": 806 - } - ], - "pointer": "/components/8/run/executable", - "span": { - "column": 57, - "document": "manifest", - "end": 2568, - "line": 37, - "start": 2558 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - } - ], - "pointer": "/components/8/run/kind", - "span": { - "column": 57, - "document": "manifest", - "end": 2568, - "line": 37, - "start": 2558 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 106, - "document": "manifest", - "end": 892, - "line": 17, - "start": 860 - } - ], - "pointer": "/components/8/run/workingDirectory", - "span": { - "column": 57, - "document": "manifest", - "end": 2568, - "line": 37, - "start": 2558 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 106, - "document": "manifest", - "end": 892, - "line": 17, - "start": 860 - }, - { - "column": 112, - "document": "manifest", - "end": 873, - "line": 17, - "start": 866 - } - ], - "pointer": "/components/8/run/workingDirectory/path", - "span": { - "column": 57, - "document": "manifest", - "end": 2568, - "line": 37, - "start": 2558 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 40, - "document": "manifest", - "end": 893, - "line": 17, - "start": 794 - }, - { - "column": 106, - "document": "manifest", - "end": 892, - "line": 17, - "start": 860 - }, - { - "column": 129, - "document": "manifest", - "end": 891, - "line": 17, - "start": 883 - } - ], - "pointer": "/components/8/run/workingDirectory/source", - "span": { - "column": 57, - "document": "manifest", - "end": 2568, - "line": 37, - "start": 2558 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/8/timeoutSeconds", - "span": { - "column": 5, - "document": "manifest", - "end": 2587, - "line": 37, - "start": 2506 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9", - "span": { - "column": 5, - "document": "manifest", - "end": 2736, - "line": 38, - "start": 2593 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/agents", - "span": { - "column": 71, - "document": "manifest", - "end": 2661, - "line": 38, - "start": 2659 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/condition", - "span": { - "column": 86, - "document": "manifest", - "end": 2735, - "line": 38, - "start": 2674 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/condition/agents", - "span": { - "column": 86, - "document": "manifest", - "end": 2735, - "line": 38, - "start": 2674 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/condition/platforms", - "span": { - "column": 130, - "document": "manifest", - "end": 2734, - "line": 38, - "start": 2718 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/condition/platforms/0", - "span": { - "column": 139, - "document": "manifest", - "end": 2733, - "line": 38, - "start": 2727 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/condition/platforms/1", - "span": { - "column": 131, - "document": "manifest", - "end": 2725, - "line": 38, - "start": 2719 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/condition/scopes", - "span": { - "column": 100, - "document": "manifest", - "end": 2705, - "line": 38, - "start": 2688 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/condition/scopes/0", - "span": { - "column": 101, - "document": "manifest", - "end": 2697, - "line": 38, - "start": 2689 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/condition/scopes/1", - "span": { - "column": 111, - "document": "manifest", - "end": 2704, - "line": 38, - "start": 2699 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/9/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 2736, - "line": 38, - "start": 2593 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/name", - "span": { - "column": 19, - "document": "manifest", - "end": 2616, - "line": 38, - "start": 2607 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/native", - "span": { - "column": 5, - "document": "manifest", - "end": 2736, - "line": 38, - "start": 2593 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/patterns", - "span": { - "column": 40, - "document": "manifest", - "end": 2630, - "line": 38, - "start": 2628 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/9/purpose", - "span": { - "column": 53, - "document": "manifest", - "end": 2649, - "line": 38, - "start": 2641 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/defaultAgents", - "span": { - "column": 14, - "document": "manifest", - "end": 2871, - "line": 25, - "start": 1285 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/exports", - "span": { - "column": 12, - "document": "manifest", - "end": 1314, - "line": 26, - "start": 1304 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/exports/0", - "span": { - "column": 13, - "document": "manifest", - "end": 1313, - "line": 26, - "start": 1305 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups", - "span": { - "column": 11, - "document": "manifest", - "end": 2792, - "line": 41, - "start": 2768 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0", - "span": { - "column": 12, - "document": "manifest", - "end": 2791, - "line": 41, - "start": 2769 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/components", - "span": { - "column": 12, - "document": "manifest", - "end": 2791, - "line": 41, - "start": 2769 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/condition", - "span": { - "column": 12, - "document": "manifest", - "end": 2791, - "line": 41, - "start": 2769 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/name", - "span": { - "column": 25, - "document": "manifest", - "end": 2790, - "line": 41, - "start": 2782 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups/0/uses", - "span": { - "column": 12, - "document": "manifest", - "end": 2791, - "line": 41, - "start": 2769 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources", - "span": { - "column": 12, - "document": "manifest", - "end": 1405, - "line": 27, - "start": 1327 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/0", - "span": { - "column": 13, - "document": "manifest", - "end": 1363, - "line": 27, - "start": 1328 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/0/kind", - "span": { - "column": 13, - "document": "manifest", - "end": 1363, - "line": 27, - "start": 1328 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/0/name", - "span": { - "column": 27, - "document": "manifest", - "end": 1348, - "line": 27, - "start": 1342 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/0/path", - "span": { - "column": 41, - "document": "manifest", - "end": 1362, - "line": 27, - "start": 1356 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/0/requirement", - "span": { - "column": 13, - "document": "manifest", - "end": 1363, - "line": 27, - "start": 1328 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/0/subpath", - "span": { - "column": 13, - "document": "manifest", - "end": 1363, - "line": 27, - "start": 1328 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/1", - "span": { - "column": 50, - "document": "manifest", - "end": 1404, - "line": 27, - "start": 1365 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/1/kind", - "span": { - "column": 50, - "document": "manifest", - "end": 1404, - "line": 27, - "start": 1365 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/1/name", - "span": { - "column": 64, - "document": "manifest", - "end": 1387, - "line": 27, - "start": 1379 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/1/path", - "span": { - "column": 80, - "document": "manifest", - "end": 1403, - "line": 27, - "start": 1395 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/1/requirement", - "span": { - "column": 50, - "document": "manifest", - "end": 1404, - "line": 27, - "start": 1365 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/1/subpath", - "span": { - "column": 50, - "document": "manifest", - "end": 1404, - "line": 27, - "start": 1365 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses", - "span": { - "column": 9, - "document": "manifest", - "end": 2869, - "line": 42, - "start": 2802 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 178, - "line": 6, - "start": 170 - } - ], - "pointer": "/uses/0", - "span": { - "column": 10, - "document": "manifest", - "end": 2808, - "line": 42, - "start": 2803 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 178, - "line": 6, - "start": 170 - } - ], - "pointer": "/uses/0/condition", - "span": { - "column": 10, - "document": "manifest", - "end": 2808, - "line": 42, - "start": 2803 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 178, - "line": 6, - "start": 170 - } - ], - "pointer": "/uses/0/kind", - "span": { - "column": 10, - "document": "manifest", - "end": 2808, - "line": 42, - "start": 2803 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 178, - "line": 6, - "start": 170 - } - ], - "pointer": "/uses/0/name", - "span": { - "column": 10, - "document": "manifest", - "end": 2808, - "line": 42, - "start": 2803 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "shared constant or assembled value; replace its definition explicitly" - }, - "origins": [ - { - "column": 29, - "document": "manifest", - "end": 178, - "line": 6, - "start": 170 - } - ], - "pointer": "/uses/0/source", - "span": { - "column": 10, - "document": "manifest", - "end": 2808, - "line": 42, - "start": 2803 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses/1", - "span": { - "column": 17, - "document": "manifest", - "end": 2868, - "line": 42, - "start": 2810 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses/1/condition", - "span": { - "column": 51, - "document": "manifest", - "end": 2867, - "line": 42, - "start": 2844 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses/1/condition/agents", - "span": { - "column": 65, - "document": "manifest", - "end": 2866, - "line": 42, - "start": 2858 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses/1/condition/agents/0", - "span": { - "column": 66, - "document": "manifest", - "end": 2865, - "line": 42, - "start": 2859 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses/1/condition/platforms", - "span": { - "column": 51, - "document": "manifest", - "end": 2867, - "line": 42, - "start": 2844 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses/1/condition/scopes", - "span": { - "column": 51, - "document": "manifest", - "end": 2867, - "line": 42, - "start": 2844 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/uses/1/kind", - "span": { - "column": 17, - "document": "manifest", - "end": 2868, - "line": 42, - "start": 2810 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses/1/name", - "span": { - "column": 30, - "document": "manifest", - "end": 2831, - "line": 42, - "start": 2823 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses/1/source", - "span": { - "column": 17, - "document": "manifest", - "end": 2868, - "line": 42, - "start": 2810 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/watch", - "span": { - "column": 14, - "document": "manifest", - "end": 2871, - "line": 25, - "start": 1285 - } - } - ], - "schemaVersion": 1, - "sourceDigest": "sha256:1532a48a6cf3953edc7e28a77b761ac216863bc521775beed798cb3a8cacbe76" -} diff --git a/Tests/AgentsManifestTests/Fixtures/LiteralCoverage.swift.txt b/Tests/AgentsManifestTests/Fixtures/LiteralCoverage.swift.txt deleted file mode 100644 index cceecf7..0000000 --- a/Tests/AgentsManifestTests/Fixtures/LiteralCoverage.swift.txt +++ /dev/null @@ -1,43 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let text: PromptContent = "Review invariants." -let section: SectionReference = "guide" -let local: GroupReference = "review" -let selection: SkillSelection = ["review", "testing"] -let configuration: ConfigurationValue = [ - "string": "value", "integer": -1, "boolean": true, "null": nil, - "array": [1, "two", false, nil], "object": ["enabled": true], "decimal": .decimal("1.25") -] -let environment: [String: RuntimeValue] = ["LEVEL": "info", "TOKEN": .secret("token")] -let emptySelection: SkillSelection = [] -let emptyObject: ConfigurationValue = [:] -let emptyArray: ConfigurationValue = [] -let emptyTools: Component = .subagent(name: "empty-tools", description: "No tools", prompt: "Read", tools: []) -let invocation: ExecutableInvocation = .executable("server", environment: environment, workingDirectory: .path("tools", source: "vendor")) -let runtime: RuntimeValue = .literal("literal") -let scalar: ConfigurationValue = .string("x") -let integer: ConfigurationValue = .integer(-9223372036854775808) -let boolean: ConfigurationValue = .boolean(false) -let null: ConfigurationValue = .null -let array: ConfigurationValue = .array([scalar, integer, boolean, null]) -let object: ConfigurationValue = .object(["array": array]) -let agents = Agents( - exports: ["review"], - sources: [.source(name: "team", path: "team"), .source(name: "vendor", path: "vendor")], - components: [ - .mcpServer(name: "tools", transport: .stdio("server", environment: environment)), - .mcpServer(name: "sse", transport: .sse(url: "https://example.org/events")), - .command(name: "review", description: "Review", prompt: text), - .instructions(sections: [section]), - .skills(source: "team", select: selection, overrides: [.skill(name: "review", mode: .copy, agents: [.codex])]), - .lspServer(name: "swift", run: invocation, languages: [".swift": "swift"], initializationOptions: ["config": configuration]), - .permissions(name: "policy", rules: [.allow(.read, "Sources/**"), .ask(.write, "**"), .deny(.execute, "rm *"), .deny(.tool("fetch"), "*")]), - .plugin(name: "tools", path: "plugins/tools", source: "vendor", select: [.skills, .instructions, .mcpServer, .hook, .subagent, .command, .lspServer, .permissions, .ignore, .plugin], exclude: [.skill(name: "a"), .instruction(name: "a"), .mcpServer(name: "a"), .hook(name: "a"), .subagent(name: "a"), .command(name: "a"), .lspServer(name: "a"), .permissions(name: "a"), .ignore(name: "a"), .plugin(name: "a")]), - .hook(name: "native", event: .native("Event"), run: invocation, agents: [.codex]), - .ignore(name: "context", patterns: [], purpose: .context, agents: [], condition: .when(scopes: [.project, .user], platforms: [.macOS, .linux])), - emptyTools - ], - groups: [.group(name: "review")], - uses: [local, .group(name: "review", condition: .when(agents: [.codex]))] -) diff --git a/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json b/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json deleted file mode 100644 index d68b7e4..0000000 --- a/Tests/AgentsManifestTests/Fixtures/ParserBaseline.json +++ /dev/null @@ -1,144 +0,0 @@ -{ - "fixtures": { - "ConsumerExample.swift.txt": { - "syntaxDepth": 31, - "syntaxNodes": 1707, - "syntaxReservation": 2980, - "tokens": 741 - }, - "CoreExample.swift.txt": { - "syntaxDepth": 26, - "syntaxNodes": 199, - "syntaxReservation": 344, - "tokens": 82 - }, - "DumpSymbolic.swift.txt": { - "syntaxDepth": 29, - "syntaxNodes": 747, - "syntaxReservation": 1268, - "tokens": 313 - }, - "ExportedGroup.swift.txt": { - "syntaxDepth": 29, - "syntaxNodes": 210, - "syntaxReservation": 388, - "tokens": 93 - }, - "InstructionRecipients.swift.txt": { - "syntaxDepth": 23, - "syntaxNodes": 88, - "syntaxReservation": 152, - "tokens": 34 - }, - "LiteralCoverage.swift.txt": { - "syntaxDepth": 29, - "syntaxNodes": 1805, - "syntaxReservation": 2932, - "tokens": 729 - }, - "PrintedEmpty.swift.txt": { - "syntaxDepth": 10, - "syntaxNodes": 29, - "syntaxReservation": 48, - "tokens": 8 - }, - "PrintedEscapes.swift.txt": { - "syntaxDepth": 29, - "syntaxNodes": 192, - "syntaxReservation": 424, - "tokens": 75 - }, - "PrintedExplicitEmpty.swift.txt": { - "syntaxDepth": 18, - "syntaxNodes": 62, - "syntaxReservation": 120, - "tokens": 26 - }, - "PrintedFields.swift.txt": { - "syntaxDepth": 32, - "syntaxNodes": 748, - "syntaxReservation": 1304, - "tokens": 322 - }, - "PrintedRanges.swift.txt": { - "syntaxDepth": 23, - "syntaxNodes": 474, - "syntaxReservation": 752, - "tokens": 184 - }, - "PrintedWidth.swift.txt": { - "syntaxDepth": 23, - "syntaxNodes": 209, - "syntaxReservation": 348, - "tokens": 83 - }, - "ProducerExample.swift.txt": { - "syntaxDepth": 29, - "syntaxNodes": 210, - "syntaxReservation": 388, - "tokens": 93 - }, - "RecipientConditions.swift.txt": { - "syntaxDepth": 25, - "syntaxNodes": 217, - "syntaxReservation": 404, - "tokens": 97 - }, - "RequirementValues.swift.txt": { - "syntaxDepth": 26, - "syntaxNodes": 823, - "syntaxReservation": 1232, - "tokens": 304 - }, - "RequirementsExample.swift.txt": { - "syntaxDepth": 29, - "syntaxNodes": 1251, - "syntaxReservation": 2028, - "tokens": 503 - }, - "SectionConcatenation.swift.txt": { - "syntaxDepth": 31, - "syntaxNodes": 1707, - "syntaxReservation": 2980, - "tokens": 741 - }, - "SharedRules.swift.txt": { - "syntaxDepth": 26, - "syntaxNodes": 199, - "syntaxReservation": 344, - "tokens": 82 - }, - "SketchExample.swift.txt": { - "syntaxDepth": 25, - "syntaxNodes": 217, - "syntaxReservation": 404, - "tokens": 97 - }, - "SkillsExample.swift.txt": { - "syntaxDepth": 23, - "syntaxNodes": 88, - "syntaxReservation": 152, - "tokens": 34 - }, - "TeamConfiguration.swift.txt": { - "syntaxDepth": 29, - "syntaxNodes": 961, - "syntaxReservation": 1672, - "tokens": 414 - }, - "VersionCollections.swift.txt": { - "syntaxDepth": 14, - "syntaxNodes": 143, - "syntaxReservation": 208, - "tokens": 48 - }, - "VocabularyDepthExample.swift.txt": { - "syntaxDepth": 43, - "syntaxNodes": 155, - "syntaxReservation": 288, - "tokens": 68 - } - }, - "swiftSyntax": "604.0.0", - "toolchain": "Apple Swift 6.4 (swiftlang-6.4.0.34.1), arm64 macOS 27" -} diff --git a/Tests/AgentsManifestTests/Fixtures/PrintedEmpty.dump.json b/Tests/AgentsManifestTests/Fixtures/PrintedEmpty.dump.json deleted file mode 100644 index b55ad0e..0000000 --- a/Tests/AgentsManifestTests/Fixtures/PrintedEmpty.dump.json +++ /dev/null @@ -1,138 +0,0 @@ -{ - "declaration": { - "components": [], - "defaultAgents": null, - "exports": [], - "groups": [], - "sources": [], - "uses": [], - "watch": [] - }, - "diagnostics": [], - "kind": "manifest", - "languageVersion": "1.0", - "locations": [ - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "", - "span": { - "column": 14, - "document": "manifest", - "end": 76, - "line": 4, - "start": 68 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components", - "span": { - "column": 14, - "document": "manifest", - "end": 76, - "line": 4, - "start": 68 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/defaultAgents", - "span": { - "column": 14, - "document": "manifest", - "end": 76, - "line": 4, - "start": 68 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/exports", - "span": { - "column": 14, - "document": "manifest", - "end": 76, - "line": 4, - "start": 68 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups", - "span": { - "column": 14, - "document": "manifest", - "end": 76, - "line": 4, - "start": 68 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources", - "span": { - "column": 14, - "document": "manifest", - "end": 76, - "line": 4, - "start": 68 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses", - "span": { - "column": 14, - "document": "manifest", - "end": 76, - "line": 4, - "start": 68 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/watch", - "span": { - "column": 14, - "document": "manifest", - "end": 76, - "line": 4, - "start": 68 - } - } - ], - "schemaVersion": 1, - "sourceDigest": "sha256:65bce43a6e2a03e2cc8f774f710c7011b02d7d08a5be1bd49035100854cfa3ac" -} diff --git a/Tests/AgentsManifestTests/Fixtures/PrintedEmpty.swift.txt b/Tests/AgentsManifestTests/Fixtures/PrintedEmpty.swift.txt deleted file mode 100644 index 8162099..0000000 --- a/Tests/AgentsManifestTests/Fixtures/PrintedEmpty.swift.txt +++ /dev/null @@ -1,4 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents() diff --git a/Tests/AgentsManifestTests/Fixtures/PrintedEscapes.swift.txt b/Tests/AgentsManifestTests/Fixtures/PrintedEscapes.swift.txt deleted file mode 100644 index b008e9e..0000000 --- a/Tests/AgentsManifestTests/Fixtures/PrintedEscapes.swift.txt +++ /dev/null @@ -1,27 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - defaultAgents: [], - sources: [ - .source( - name: "é/别名~\"\\\n\r\t\u{1}\u{7f}\u{85}", - url: "https://example.org/escape.git" - ), - ], - components: [ - .skills( - source: "é/别名~\"\\\n\r\t\u{1}\u{7f}\u{85}", - select: ["selected"] - ), - .instructions( - chatGPT: [ - .prompt( - name: "\"\\\n\r\t\u{1}\u{7f}\u{85} é 😀", - sections: ["own"], - append: "notes/内容.md" - ), - ] - ), - ] -) diff --git a/Tests/AgentsManifestTests/Fixtures/PrintedExplicitEmpty.swift.txt b/Tests/AgentsManifestTests/Fixtures/PrintedExplicitEmpty.swift.txt deleted file mode 100644 index a221151..0000000 --- a/Tests/AgentsManifestTests/Fixtures/PrintedExplicitEmpty.swift.txt +++ /dev/null @@ -1,11 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - defaultAgents: [], - components: [ - .instructions( - agents: [] - ), - ] -) diff --git a/Tests/AgentsManifestTests/Fixtures/PrintedFields.dump.json b/Tests/AgentsManifestTests/Fixtures/PrintedFields.dump.json deleted file mode 100644 index 96281c0..0000000 --- a/Tests/AgentsManifestTests/Fixtures/PrintedFields.dump.json +++ /dev/null @@ -1,2293 +0,0 @@ -{ - "declaration": { - "components": [ - { - "agents": null, - "condition": null, - "exclude": [], - "kind": "skills", - "mode": "edit", - "native": {}, - "overrides": [], - "select": "all", - "source": "empty" - }, - { - "agents": [], - "condition": null, - "exclude": [ - "b" - ], - "kind": "skills", - "mode": "copy", - "native": {}, - "overrides": [ - { - "agents": [ - "codex" - ], - "mode": "link", - "name": "a" - }, - { - "agents": [], - "mode": null, - "name": "b" - } - ], - "select": [ - "a", - "b" - ], - "source": "git" - }, - { - "agents": null, - "condition": null, - "exclude": [], - "kind": "skills", - "mode": null, - "native": {}, - "overrides": [], - "select": [], - "source": "index" - }, - { - "agents": null, - "condition": null, - "exclude": [], - "kind": "skills", - "mode": null, - "native": {}, - "overrides": [ - { - "agents": null, - "mode": "copy", - "name": "future" - } - ], - "select": "all", - "source": "local" - }, - { - "agents": [ - "codex", - "gemini-cli" - ], - "chatGPT": [ - { - "append": null, - "condition": null, - "name": "", - "sections": [] - }, - { - "append": "notes/周报.md", - "condition": null, - "name": "周报", - "sections": [ - { - "condition": null, - "name": "rule", - "source": "git" - }, - { - "condition": null, - "name": "own", - "source": null - } - ] - } - ], - "condition": null, - "kind": "instructions", - "native": {}, - "sections": [ - { - "condition": null, - "name": "own", - "source": null - }, - { - "condition": null, - "name": "rule", - "source": "git" - }, - { - "condition": null, - "name": "own", - "source": null - }, - { - "condition": null, - "name": "nested/rule", - "source": "local" - } - ] - } - ], - "defaultAgents": [ - "claude-code", - "codex", - "opencode" - ], - "exports": [], - "groups": [], - "sources": [ - { - "kind": "local", - "name": "empty", - "path": "./live", - "requirement": null, - "subpath": null - }, - { - "kind": "git", - "name": "git", - "requirement": { - "branch": "main" - }, - "subpath": "skills", - "url": "https://intranet/team.git" - }, - { - "index": "https://example.org/.well-known/skills/index.json", - "kind": "index", - "name": "index", - "requirement": null, - "subpath": "bundle" - }, - { - "kind": "local", - "name": "local", - "path": "./drafts", - "requirement": { - "revision": "abc123" - }, - "subpath": null - } - ], - "uses": [], - "watch": [ - "git", - "index", - "local" - ] - }, - "diagnostics": [], - "kind": "manifest", - "languageVersion": "1.0", - "locations": [ - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "", - "span": { - "column": 14, - "document": "manifest", - "end": 1619, - "line": 4, - "start": 68 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components", - "span": { - "column": 15, - "document": "manifest", - "end": 1581, - "line": 21, - "start": 525 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0", - "span": { - "column": 5, - "document": "manifest", - "end": 568, - "line": 22, - "start": 531 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 568, - "line": 22, - "start": 531 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 568, - "line": 22, - "start": 531 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/exclude", - "span": { - "column": 5, - "document": "manifest", - "end": 568, - "line": 22, - "start": 531 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/0/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 568, - "line": 22, - "start": 531 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/mode", - "span": { - "column": 36, - "document": "manifest", - "end": 567, - "line": 22, - "start": 562 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/native", - "span": { - "column": 5, - "document": "manifest", - "end": 568, - "line": 22, - "start": 531 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/overrides", - "span": { - "column": 5, - "document": "manifest", - "end": 568, - "line": 22, - "start": 531 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/select", - "span": { - "column": 5, - "document": "manifest", - "end": 568, - "line": 22, - "start": 531 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/0/source", - "span": { - "column": 21, - "document": "manifest", - "end": 554, - "line": 22, - "start": 547 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1", - "span": { - "column": 5, - "document": "manifest", - "end": 888, - "line": 23, - "start": 574 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/agents", - "span": { - "column": 15, - "document": "manifest", - "end": 882, - "line": 39, - "start": 880 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 888, - "line": 23, - "start": 574 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/exclude", - "span": { - "column": 16, - "document": "manifest", - "end": 650, - "line": 26, - "start": 645 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/exclude/0", - "span": { - "column": 17, - "document": "manifest", - "end": 649, - "line": 26, - "start": 646 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/1/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 888, - "line": 23, - "start": 574 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/mode", - "span": { - "column": 13, - "document": "manifest", - "end": 669, - "line": 27, - "start": 664 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/native", - "span": { - "column": 5, - "document": "manifest", - "end": 888, - "line": 23, - "start": 574 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides", - "span": { - "column": 18, - "document": "manifest", - "end": 864, - "line": 28, - "start": 688 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/0", - "span": { - "column": 9, - "document": "manifest", - "end": 786, - "line": 29, - "start": 698 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/0/agents", - "span": { - "column": 19, - "document": "manifest", - "end": 776, - "line": 32, - "start": 768 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/0/agents/0", - "span": { - "column": 20, - "document": "manifest", - "end": 775, - "line": 32, - "start": 769 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/0/mode", - "span": { - "column": 17, - "document": "manifest", - "end": 748, - "line": 31, - "start": 743 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/0/name", - "span": { - "column": 17, - "document": "manifest", - "end": 725, - "line": 30, - "start": 722 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/1", - "span": { - "column": 9, - "document": "manifest", - "end": 855, - "line": 34, - "start": 796 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/1/agents", - "span": { - "column": 19, - "document": "manifest", - "end": 845, - "line": 36, - "start": 843 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/1/mode", - "span": { - "column": 9, - "document": "manifest", - "end": 855, - "line": 34, - "start": 796 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/overrides/1/name", - "span": { - "column": 17, - "document": "manifest", - "end": 823, - "line": 35, - "start": 820 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/select", - "span": { - "column": 15, - "document": "manifest", - "end": 628, - "line": 25, - "start": 618 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/select/0", - "span": { - "column": 16, - "document": "manifest", - "end": 622, - "line": 25, - "start": 619 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/select/1", - "span": { - "column": 21, - "document": "manifest", - "end": 627, - "line": 25, - "start": 624 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/1/source", - "span": { - "column": 15, - "document": "manifest", - "end": 602, - "line": 24, - "start": 597 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2", - "span": { - "column": 5, - "document": "manifest", - "end": 948, - "line": 41, - "start": 894 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 948, - "line": 41, - "start": 894 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 948, - "line": 41, - "start": 894 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/exclude", - "span": { - "column": 5, - "document": "manifest", - "end": 948, - "line": 41, - "start": 894 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/2/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 948, - "line": 41, - "start": 894 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/mode", - "span": { - "column": 5, - "document": "manifest", - "end": 948, - "line": 41, - "start": 894 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/native", - "span": { - "column": 5, - "document": "manifest", - "end": 948, - "line": 41, - "start": 894 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/overrides", - "span": { - "column": 5, - "document": "manifest", - "end": 948, - "line": 41, - "start": 894 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/select", - "span": { - "column": 15, - "document": "manifest", - "end": 942, - "line": 43, - "start": 940 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/2/source", - "span": { - "column": 15, - "document": "manifest", - "end": 924, - "line": 42, - "start": 917 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3", - "span": { - "column": 5, - "document": "manifest", - "end": 1063, - "line": 45, - "start": 954 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/agents", - "span": { - "column": 5, - "document": "manifest", - "end": 1063, - "line": 45, - "start": 954 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 1063, - "line": 45, - "start": 954 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/exclude", - "span": { - "column": 5, - "document": "manifest", - "end": 1063, - "line": 45, - "start": 954 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/3/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 1063, - "line": 45, - "start": 954 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/mode", - "span": { - "column": 5, - "document": "manifest", - "end": 1063, - "line": 45, - "start": 954 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/native", - "span": { - "column": 5, - "document": "manifest", - "end": 1063, - "line": 45, - "start": 954 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/overrides", - "span": { - "column": 18, - "document": "manifest", - "end": 1057, - "line": 47, - "start": 1003 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/overrides/0", - "span": { - "column": 9, - "document": "manifest", - "end": 1048, - "line": 48, - "start": 1013 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/overrides/0/agents", - "span": { - "column": 9, - "document": "manifest", - "end": 1048, - "line": 48, - "start": 1013 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/overrides/0/mode", - "span": { - "column": 38, - "document": "manifest", - "end": 1047, - "line": 48, - "start": 1042 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/overrides/0/name", - "span": { - "column": 22, - "document": "manifest", - "end": 1034, - "line": 48, - "start": 1026 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/select", - "span": { - "column": 5, - "document": "manifest", - "end": 1063, - "line": 45, - "start": 954 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/3/source", - "span": { - "column": 15, - "document": "manifest", - "end": 984, - "line": 46, - "start": 977 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4", - "span": { - "column": 5, - "document": "manifest", - "end": 1576, - "line": 51, - "start": 1069 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/agents", - "span": { - "column": 15, - "document": "manifest", - "end": 1570, - "line": 72, - "start": 1550 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/agents/0", - "span": { - "column": 16, - "document": "manifest", - "end": 1557, - "line": 72, - "start": 1551 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/agents/1", - "span": { - "column": 24, - "document": "manifest", - "end": 1569, - "line": 72, - "start": 1559 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/chatGPT", - "span": { - "column": 16, - "document": "manifest", - "end": 1534, - "line": 58, - "start": 1259 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/chatGPT/0", - "span": { - "column": 9, - "document": "manifest", - "end": 1330, - "line": 59, - "start": 1269 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/chatGPT/0/append", - "span": { - "column": 9, - "document": "manifest", - "end": 1330, - "line": 59, - "start": 1269 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/chatGPT/0/condition", - "span": { - "column": 9, - "document": "manifest", - "end": 1330, - "line": 59, - "start": 1269 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/chatGPT/0/name", - "span": { - "column": 17, - "document": "manifest", - "end": 1296, - "line": 60, - "start": 1294 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/chatGPT/0/sections", - "span": { - "column": 21, - "document": "manifest", - "end": 1320, - "line": 61, - "start": 1318 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/chatGPT/1", - "span": { - "column": 9, - "document": "manifest", - "end": 1525, - "line": 63, - "start": 1340 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/chatGPT/1/append", - "span": { - "column": 19, - "document": "manifest", - "end": 1515, - "line": 69, - "start": 1498 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/chatGPT/1/condition", - "span": { - "column": 9, - "document": "manifest", - "end": 1525, - "line": 63, - "start": 1340 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/chatGPT/1/name", - "span": { - "column": 17, - "document": "manifest", - "end": 1373, - "line": 64, - "start": 1365 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/chatGPT/1/sections", - "span": { - "column": 21, - "document": "manifest", - "end": 1478, - "line": 65, - "start": 1395 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/chatGPT/1/sections/0", - "span": { - "column": 13, - "document": "manifest", - "end": 1446, - "line": 66, - "start": 1409 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/chatGPT/1/sections/0/condition", - "span": { - "column": 13, - "document": "manifest", - "end": 1446, - "line": 66, - "start": 1409 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/chatGPT/1/sections/0/name", - "span": { - "column": 28, - "document": "manifest", - "end": 1430, - "line": 66, - "start": 1424 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/chatGPT/1/sections/0/source", - "span": { - "column": 44, - "document": "manifest", - "end": 1445, - "line": 66, - "start": 1440 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/chatGPT/1/sections/1", - "span": { - "column": 13, - "document": "manifest", - "end": 1465, - "line": 67, - "start": 1460 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/4/chatGPT/1/sections/1/condition", - "span": { - "column": 13, - "document": "manifest", - "end": 1465, - "line": 67, - "start": 1460 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/4/chatGPT/1/sections/1/name", - "span": { - "column": 13, - "document": "manifest", - "end": 1465, - "line": 67, - "start": 1460 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/4/chatGPT/1/sections/1/source", - "span": { - "column": 13, - "document": "manifest", - "end": 1465, - "line": 67, - "start": 1460 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/condition", - "span": { - "column": 5, - "document": "manifest", - "end": 1576, - "line": 51, - "start": 1069 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/4/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 1576, - "line": 51, - "start": 1069 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/native", - "span": { - "column": 5, - "document": "manifest", - "end": 1576, - "line": 51, - "start": 1069 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/sections", - "span": { - "column": 17, - "document": "manifest", - "end": 1242, - "line": 52, - "start": 1100 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/sections/0", - "span": { - "column": 9, - "document": "manifest", - "end": 1115, - "line": 53, - "start": 1110 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/4/sections/0/condition", - "span": { - "column": 9, - "document": "manifest", - "end": 1115, - "line": 53, - "start": 1110 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/4/sections/0/name", - "span": { - "column": 9, - "document": "manifest", - "end": 1115, - "line": 53, - "start": 1110 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/4/sections/0/source", - "span": { - "column": 9, - "document": "manifest", - "end": 1115, - "line": 53, - "start": 1110 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/sections/1", - "span": { - "column": 9, - "document": "manifest", - "end": 1162, - "line": 54, - "start": 1125 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/sections/1/condition", - "span": { - "column": 9, - "document": "manifest", - "end": 1162, - "line": 54, - "start": 1125 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/sections/1/name", - "span": { - "column": 24, - "document": "manifest", - "end": 1146, - "line": 54, - "start": 1140 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/sections/1/source", - "span": { - "column": 40, - "document": "manifest", - "end": 1161, - "line": 54, - "start": 1156 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/sections/2", - "span": { - "column": 9, - "document": "manifest", - "end": 1177, - "line": 55, - "start": 1172 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/4/sections/2/condition", - "span": { - "column": 9, - "document": "manifest", - "end": 1177, - "line": 55, - "start": 1172 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/4/sections/2/name", - "span": { - "column": 9, - "document": "manifest", - "end": 1177, - "line": 55, - "start": 1172 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/components/4/sections/2/source", - "span": { - "column": 9, - "document": "manifest", - "end": 1177, - "line": 55, - "start": 1172 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/sections/3", - "span": { - "column": 9, - "document": "manifest", - "end": 1233, - "line": 56, - "start": 1187 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/sections/3/condition", - "span": { - "column": 9, - "document": "manifest", - "end": 1233, - "line": 56, - "start": 1187 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/sections/3/name", - "span": { - "column": 24, - "document": "manifest", - "end": 1215, - "line": 56, - "start": 1202 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/components/4/sections/3/source", - "span": { - "column": 47, - "document": "manifest", - "end": 1232, - "line": 56, - "start": 1225 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/defaultAgents", - "span": { - "column": 18, - "document": "manifest", - "end": 125, - "line": 5, - "start": 93 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/defaultAgents/0", - "span": { - "column": 19, - "document": "manifest", - "end": 105, - "line": 5, - "start": 94 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/defaultAgents/1", - "span": { - "column": 32, - "document": "manifest", - "end": 113, - "line": 5, - "start": 107 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/defaultAgents/2", - "span": { - "column": 40, - "document": "manifest", - "end": 124, - "line": 5, - "start": 115 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/exports", - "span": { - "column": 14, - "document": "manifest", - "end": 1619, - "line": 4, - "start": 68 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/groups", - "span": { - "column": 14, - "document": "manifest", - "end": 1619, - "line": 4, - "start": 68 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources", - "span": { - "column": 12, - "document": "manifest", - "end": 509, - "line": 6, - "start": 138 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/0", - "span": { - "column": 5, - "document": "manifest", - "end": 182, - "line": 7, - "start": 144 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/0/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 182, - "line": 7, - "start": 144 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/0/name", - "span": { - "column": 19, - "document": "manifest", - "end": 165, - "line": 7, - "start": 158 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/0/path", - "span": { - "column": 34, - "document": "manifest", - "end": 181, - "line": 7, - "start": 173 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/0/requirement", - "span": { - "column": 5, - "document": "manifest", - "end": 182, - "line": 7, - "start": 144 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/0/subpath", - "span": { - "column": 5, - "document": "manifest", - "end": 182, - "line": 7, - "start": 144 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/1", - "span": { - "column": 5, - "document": "manifest", - "end": 307, - "line": 8, - "start": 188 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/1/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 307, - "line": 8, - "start": 188 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/1/name", - "span": { - "column": 13, - "document": "manifest", - "end": 214, - "line": 9, - "start": 209 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/1/requirement", - "span": { - "column": 15, - "document": "manifest", - "end": 276, - "line": 11, - "start": 270 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/1/requirement/branch", - "span": { - "column": 15, - "document": "manifest", - "end": 276, - "line": 11, - "start": 270 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/1/subpath", - "span": { - "column": 16, - "document": "manifest", - "end": 301, - "line": 12, - "start": 293 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/1/url", - "span": { - "column": 12, - "document": "manifest", - "end": 254, - "line": 10, - "start": 227 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/2", - "span": { - "column": 5, - "document": "manifest", - "end": 438, - "line": 14, - "start": 313 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/2/index", - "span": { - "column": 14, - "document": "manifest", - "end": 407, - "line": 16, - "start": 356 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/2/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 438, - "line": 14, - "start": 313 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/2/name", - "span": { - "column": 13, - "document": "manifest", - "end": 341, - "line": 15, - "start": 334 - } - }, - { - "defaulted": true, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/2/requirement", - "span": { - "column": 5, - "document": "manifest", - "end": 438, - "line": 14, - "start": 313 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/2/subpath", - "span": { - "column": 16, - "document": "manifest", - "end": 432, - "line": 17, - "start": 424 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/3", - "span": { - "column": 5, - "document": "manifest", - "end": 504, - "line": 19, - "start": 444 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/3/kind", - "span": { - "column": 5, - "document": "manifest", - "end": 504, - "line": 19, - "start": 444 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/3/name", - "span": { - "column": 19, - "document": "manifest", - "end": 465, - "line": 19, - "start": 458 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/3/path", - "span": { - "column": 34, - "document": "manifest", - "end": 483, - "line": 19, - "start": 473 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/3/requirement", - "span": { - "column": 56, - "document": "manifest", - "end": 503, - "line": 19, - "start": 495 - } - }, - { - "defaulted": false, - "editability": { - "kind": "readOnly", - "reason": "normalized field; replace its containing construction" - }, - "origins": [], - "pointer": "/sources/3/requirement/revision", - "span": { - "column": 56, - "document": "manifest", - "end": 503, - "line": 19, - "start": 495 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/sources/3/subpath", - "span": { - "column": 5, - "document": "manifest", - "end": 504, - "line": 19, - "start": 444 - } - }, - { - "defaulted": true, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/uses", - "span": { - "column": 14, - "document": "manifest", - "end": 1619, - "line": 4, - "start": 68 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/watch", - "span": { - "column": 10, - "document": "manifest", - "end": 1617, - "line": 75, - "start": 1592 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/watch/0", - "span": { - "column": 11, - "document": "manifest", - "end": 1598, - "line": 75, - "start": 1593 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/watch/1", - "span": { - "column": 18, - "document": "manifest", - "end": 1607, - "line": 75, - "start": 1600 - } - }, - { - "defaulted": false, - "editability": { - "kind": "direct" - }, - "origins": [], - "pointer": "/watch/2", - "span": { - "column": 27, - "document": "manifest", - "end": 1616, - "line": 75, - "start": 1609 - } - } - ], - "schemaVersion": 1, - "sourceDigest": "sha256:2b0afd8fd9775033934edb314622cbc706cf2e8c139d07c9f52e8bddb37d3e03" -} diff --git a/Tests/AgentsManifestTests/Fixtures/PrintedFields.swift.txt b/Tests/AgentsManifestTests/Fixtures/PrintedFields.swift.txt deleted file mode 100644 index aed9e70..0000000 --- a/Tests/AgentsManifestTests/Fixtures/PrintedFields.swift.txt +++ /dev/null @@ -1,76 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - defaultAgents: [.claudeCode, .codex, .openCode], - sources: [ - .source(name: "empty", path: "./live"), - .source( - name: "git", - url: "https://intranet/team.git", - branch: "main", - subpath: "skills" - ), - .source( - name: "index", - index: "https://example.org/.well-known/skills/index.json", - subpath: "bundle" - ), - .source(name: "local", path: "./drafts", revision: "abc123"), - ], - components: [ - .skills(source: "empty", mode: .edit), - .skills( - source: "git", - select: ["a", "b"], - exclude: ["b"], - mode: .copy, - overrides: [ - .skill( - name: "a", - mode: .link, - agents: [.codex] - ), - .skill( - name: "b", - agents: [] - ), - ], - agents: [] - ), - .skills( - source: "index", - select: [] - ), - .skills( - source: "local", - overrides: [ - .skill(name: "future", mode: .copy), - ] - ), - .instructions( - sections: [ - "own", - .section(name: "rule", source: "git"), - "own", - .section(name: "nested/rule", source: "local"), - ], - chatGPT: [ - .prompt( - name: "", - sections: [] - ), - .prompt( - name: "周报", - sections: [ - .section(name: "rule", source: "git"), - "own", - ], - append: "notes/周报.md" - ), - ], - agents: [.codex, .geminiCLI] - ), - ], - watch: ["git", "index", "local"] -) diff --git a/Tests/AgentsManifestTests/Fixtures/PrintedRanges.swift.txt b/Tests/AgentsManifestTests/Fixtures/PrintedRanges.swift.txt deleted file mode 100644 index b4757f4..0000000 --- a/Tests/AgentsManifestTests/Fixtures/PrintedRanges.swift.txt +++ /dev/null @@ -1,43 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - sources: [ - .source(name: "a", url: "https://Example.org/a.git", exact: "1.2.3+build"), - .source(name: "b", path: "./b", from: "1.2.0"), - .source( - name: "c", - path: "./c", - .upToNextMinor(from: "1.2.0-beta+build") - ), - .source(name: "d", path: "./d", from: "1.2.0"), - .source( - name: "e", - path: "./e", - .upToNextMinor(from: "1.2.0+lower") - ), - .source( - name: "f", - path: "./f", - "1.2.0"..<"1.8.0-beta+bound" - ), - .source( - name: "g", - path: "./g", - .upToNextMinor(from: "9223372036854775807.1.0") - ), - .source( - name: "h", - url: "ssh://User@INTRANET:2222/team/h.git", - revision: "abc123" - ), - .source( - name: "i", - path: "./i", - .upToNextMinor( - from: "1.2.0-alphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalphaalpha" - ) - ), - .source(name: "j", url: "https://intranet/team@variant"), - ] -) diff --git a/Tests/AgentsManifestTests/Fixtures/PrintedWidth.swift.txt b/Tests/AgentsManifestTests/Fixtures/PrintedWidth.swift.txt deleted file mode 100644 index a5752f0..0000000 --- a/Tests/AgentsManifestTests/Fixtures/PrintedWidth.swift.txt +++ /dev/null @@ -1,24 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - sources: [ - .source(name: "s", path: "./s"), - .source(name: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", path: "p"), - .source( - name: "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy", - path: "p2" - ), - ], - components: [ - .skills( - source: "s", - select: ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbb"], - exclude: [ - "ccccccccccccccccccccccccccccccccc", - "dddddddddddddddddddddddd", - ], - mode: .link - ), - ] -) diff --git a/Tests/AgentsManifestTests/Fixtures/ProducerExample.swift.txt b/Tests/AgentsManifestTests/Fixtures/ProducerExample.swift.txt deleted file mode 100644 index 91bbf6a..0000000 --- a/Tests/AgentsManifestTests/Fixtures/ProducerExample.swift.txt +++ /dev/null @@ -1,16 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - exports: ["review"], - groups: [ - .group( - name: "review", - components: [ - .instructions(sections: ["review-principles"], agents: [.claudeCode, .codex]), - .skills(source: ".", select: ["review"], mode: .copy, agents: [.claudeCode, .codex]), - ], - condition: .when(scopes: [.project]) - ), - ] -) diff --git a/Tests/AgentsManifestTests/Fixtures/RecipientConditions.swift.txt b/Tests/AgentsManifestTests/Fixtures/RecipientConditions.swift.txt deleted file mode 100644 index dd35e54..0000000 --- a/Tests/AgentsManifestTests/Fixtures/RecipientConditions.swift.txt +++ /dev/null @@ -1,16 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - defaultAgents: [.cursor], - sources: [.source(name: "team", path: "./team")], - components: [ - .ignore( - name: "build-products", patterns: [".build/"], purpose: .indexing, - condition: .when(scopes: [.project]) - ), - ], - uses: [ - .group(name: "review", source: "team", condition: .when(agents: [.codex])), - ] -) diff --git a/Tests/AgentsManifestTests/Fixtures/RequirementValues.swift.txt b/Tests/AgentsManifestTests/Fixtures/RequirementValues.swift.txt deleted file mode 100644 index 98a5199..0000000 --- a/Tests/AgentsManifestTests/Fixtures/RequirementValues.swift.txt +++ /dev/null @@ -1,24 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let majorFrom: Source = .source(name: "rules", url: "https://example.org/rules.git", from: "1.2.0") -let majorHelper: Source = .source(name: "rules", url: "https://example.org/rules.git", .upToNextMajor(from: "1.2.0")) -let majorRange: Source = .source(name: "rules", url: "https://example.org/rules.git", "1.2.0"..<"2.0.0") -let minorHelper: Source = .source(name: "rules", url: "https://example.org/rules.git", .upToNextMinor(from: "1.2.0")) -let minorRange: Source = .source(name: "rules", url: "https://example.org/rules.git", "1.2.0"..<"1.3.0") -let prereleaseFrom: Source = .source(name: "rules", url: "https://example.org/rules.git", from: "1.2.3-beta.1+build.7") -let prereleaseHelper: Source = .source(name: "rules", url: "https://example.org/rules.git", .upToNextMajor(from: "1.2.3-beta.1+build.7")) -let prereleaseRange: Source = .source(name: "rules", url: "https://example.org/rules.git", "1.2.3-beta.1+build.7"..<"2.0.0") -let prereleaseMinor: Source = .source(name: "rules", url: "https://example.org/rules.git", .upToNextMinor(from: "1.2.3-beta.1+build.7")) -let prereleaseMinorRange: Source = .source(name: "rules", url: "https://example.org/rules.git", "1.2.3-beta.1+build.7"..<"1.3.0") -let localLiteral: GroupReference = "review" -let localFactory: GroupReference = .group(name: "review") -let agents = Agents( - exports: ["review"], - sources: [majorFrom], - components: [ - .plugin(name: "tools", path: "tools", source: "rules", exclude: [.hook(name: "format")]), - ], - groups: [.group(name: "review")], - uses: [localLiteral] -) diff --git a/Tests/AgentsManifestTests/Fixtures/RequirementsExample.swift.txt b/Tests/AgentsManifestTests/Fixtures/RequirementsExample.swift.txt deleted file mode 100644 index eee30dd..0000000 --- a/Tests/AgentsManifestTests/Fixtures/RequirementsExample.swift.txt +++ /dev/null @@ -1,46 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let minimum: Version = "1.2.0" -let review: ComponentGroup = .group( - name: "review", - components: [ - .skills(source: ".", overrides: [.skill(name: "review", mode: .copy)]), - .instructions( - sections: [.section(name: "guide", source: ".")], - chatGPT: [.prompt(name: "weekly", sections: ["guide"])] - ), - .command( - name: "review", description: "Review a change", prompt: .file("review.md", source: "."), - parameters: [.parameter(name: "change", description: "Change identifier", defaultValue: "HEAD")] - ), - .hook( - name: "format", event: .afterTool, - run: .executable("swift", workingDirectory: .path("Sources", source: ".")) - ), - ] -) -let agents = Agents( - exports: ["review"], - sources: [ - .source(name: "major", url: "https://example.org/major.git", from: minimum), - .source(name: "exact", url: "https://example.org/exact.git", exact: "1.2.0"), - .source(name: "branch", url: "https://example.org/branch.git", branch: "main"), - .source(name: "revision", url: "https://example.org/revision.git", revision: "abc123"), - .source(name: "range", url: "https://example.org/range.git", "1.2.0"..<"2.0.0"), - .source(name: "minor", url: "https://example.org/minor.git", .upToNextMinor(from: "1.2.0")), - .source(name: "explicit-major", url: "https://example.org/explicit.git", .upToNextMajor(from: minimum)), - .source(name: "local-major", path: "./major", from: "1.2.0"), - .source(name: "local-exact", path: "./exact", exact: "1.2.0"), - .source(name: "local-branch", path: "./branch", branch: "main"), - .source(name: "local-revision", path: "./revision", revision: "abc123"), - .source(name: "local-range", path: "./range", "1.2.0" ..< "2.0.0", subpath: "tools"), - .source(name: "local-minor", path: "./minor", .upToNextMinor(from: "1.2.0")), - .source(name: "local-explicit-major", path: "./explicit", .upToNextMajor(from: "1.2.0")), - .source(name: "unversioned", url: "https://example.org/unversioned.git"), - .source(name: "local", path: "./local"), - .source(name: "catalog", index: "https://example.org/index.json", subpath: "tools"), - ], - groups: [review, .group(name: "quality", uses: ["review"])], - uses: ["quality", .group(name: "review", source: "major")] -) diff --git a/Tests/AgentsManifestTests/Fixtures/SectionConcatenation.swift.txt b/Tests/AgentsManifestTests/Fixtures/SectionConcatenation.swift.txt deleted file mode 100644 index d31bf3b..0000000 --- a/Tests/AgentsManifestTests/Fixtures/SectionConcatenation.swift.txt +++ /dev/null @@ -1,97 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let base: [SectionReference] = ["guide"] -let sections = base + [.section(name: "engineering", source: "rules")] -let reviewer: Component = .subagent( - name: "reviewer", - description: "Review correctness and tests.", - prompt: "Check invariants and explain concrete failures.", - agents: [.claudeCode], - condition: .when(platforms: [.macOS]), - native: ["claude-code/subagent@1": ["memory": "project"]] -) - -let agents = Agents( - sources: [ - .source(name: "team", path: "./team"), - .source(name: "drafts", path: "./draft-skills"), - .source(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), - .source(name: "catalog", index: "https://example.org/skills/index.json"), - .source(name: "vendor", url: "https://example.org/vendor/tools.git", exact: "2.1.0"), - ], - components: [ - .skills( - source: "rules", exclude: ["experimental"], mode: .copy, - overrides: [.skill(name: "testing", mode: .link, agents: [.codex])] - ), - .skills( - source: "drafts", select: ["draft"], mode: .edit, - condition: .when(agents: [.claudeCode], scopes: [.project]) - ), - .instructions( - sections: sections, - chatGPT: [.prompt(name: "weekly", sections: base, append: "notes/weekly.md")] - ), - .mcpServer( - name: "workspace", - transport: .stdio( - "workspace-tools", arguments: ["serve"], - environment: ["TOKEN": .secret("workspace-token"), "LOG_LEVEL": "info"] - ), - agents: [.claudeCode] - ), - .mcpServer( - name: "reference", - transport: .streamableHTTP( - url: "https://example.org/mcp", headers: ["Authorization": .environment("MCP_AUTH")] - ), - agents: [.openCode] - ), - .hook( - name: "format", event: .afterTool, - run: .executable( - "swift", arguments: ["format", "--in-place", "Sources"], - workingDirectory: .path("tools", source: "rules") - ), - timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) - ), - .command( - name: "review/change", description: "Review a selected change.", - prompt: "Review ${input:change} and cite evidence.", - parameters: [.parameter(name: "change", description: "The change to review.")], - agents: [.claudeCode] - ), - .lspServer( - name: "swift", run: .executable("sourcekit-lsp"), - languages: [".swift": "swift"], - initializationOptions: ["backgroundIndexing": true], - agents: [.claudeCode], condition: .when(platforms: [.macOS]) - ), - .permissions( - name: "private-files", - rules: [.deny(.read, "secrets/**")], - agents: [.claudeCode], condition: .when(scopes: [.project]) - ), - .ignore( - name: "build-products", patterns: [".build/", "DerivedData/"], purpose: .indexing, - agents: [.cursor], condition: .when(scopes: [.project]) - ), - .plugin( - name: "vendor-tools", path: "plugins/tools", source: "vendor", mode: .native, - agents: [.claudeCode], condition: .when(scopes: [.user]) - ), - .plugin( - name: "shared-tools", path: "plugins/shared", source: "vendor", - exclude: [.hook(name: "format")], condition: .when(scopes: [.project]) - ), - ], - groups: [ - .group( - name: "review-tools", components: [reviewer], - uses: [.group(name: "review", source: "team", condition: .when(agents: [.codex]))] - ), - ], - uses: ["review-tools"], - watch: ["rules", "catalog"] -) diff --git a/Tests/AgentsManifestTests/Fixtures/SharedRules.swift.txt b/Tests/AgentsManifestTests/Fixtures/SharedRules.swift.txt deleted file mode 100644 index 44f9882..0000000 --- a/Tests/AgentsManifestTests/Fixtures/SharedRules.swift.txt +++ /dev/null @@ -1,23 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - sources: [ - .source( - name: "agents-tools", - url: "https://github.com/agents-tools/.github", - branch: "master", - subpath: ".agent" - ), - ], - components: [ - .instructions( - sections: [ - "guide", - .section(name: "shared/swift-package-route", source: "agents-tools"), - .section(name: "shared/swift-package-tests", source: "agents-tools"), - ], - agents: [.claudeCode, .codex] - ), - ] -) diff --git a/Tests/AgentsManifestTests/Fixtures/SketchExample.swift.txt b/Tests/AgentsManifestTests/Fixtures/SketchExample.swift.txt deleted file mode 100644 index dd35e54..0000000 --- a/Tests/AgentsManifestTests/Fixtures/SketchExample.swift.txt +++ /dev/null @@ -1,16 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - defaultAgents: [.cursor], - sources: [.source(name: "team", path: "./team")], - components: [ - .ignore( - name: "build-products", patterns: [".build/"], purpose: .indexing, - condition: .when(scopes: [.project]) - ), - ], - uses: [ - .group(name: "review", source: "team", condition: .when(agents: [.codex])), - ] -) diff --git a/Tests/AgentsManifestTests/Fixtures/SkillsExample.swift.txt b/Tests/AgentsManifestTests/Fixtures/SkillsExample.swift.txt deleted file mode 100644 index a8fb88d..0000000 --- a/Tests/AgentsManifestTests/Fixtures/SkillsExample.swift.txt +++ /dev/null @@ -1,11 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - components: [ - .instructions( - sections: ["guide", "code-review-rules"], - agents: [.claudeCode, .codex] - ), - ] -) diff --git a/Tests/AgentsManifestTests/Fixtures/TeamConfiguration.swift.txt b/Tests/AgentsManifestTests/Fixtures/TeamConfiguration.swift.txt deleted file mode 100644 index efa409a..0000000 --- a/Tests/AgentsManifestTests/Fixtures/TeamConfiguration.swift.txt +++ /dev/null @@ -1,81 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -// A team repository's .agent/Agents.swift. -// Everything here is a declaration: agents reads it, never runs it. - -let reviewer: Component = .subagent( - name: "reviewer", - description: "Review correctness and tests.", - prompt: "Check invariants and explain concrete failures.", - agents: [.claudeCode] -) - -let agents = Agents( - // Components without their own `agents:` go to these. - defaultAgents: [.claudeCode, .codex], - - sources: [ - .source(name: "org", url: "https://github.com/acme/.github", branch: "main", subpath: ".agent"), - .source(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), - .source(name: "drafts", path: "./draft-skills"), - ], - - components: [ - // AGENTS.md / CLAUDE.md, assembled from sections. - .instructions( - sections: [ - "guide", - .section(name: "shared/swift-package-route", source: "org"), - ] - ), - - // Every skill from `rules` except one; Codex gets `testing` as a link. - .skills( - source: "rules", exclude: ["experimental"], mode: .copy, - overrides: [.skill(name: "testing", mode: .link, agents: [.codex])] - ), - - // Work-in-progress skills, only for Claude Code in this project. - .skills( - source: "drafts", select: ["draft"], mode: .edit, - condition: .when(agents: [.claudeCode], scopes: [.project]) - ), - - .mcpServer( - name: "workspace", - transport: .stdio( - "workspace-tools", arguments: ["serve"], - environment: ["TOKEN": .secret("workspace-token"), "LOG_LEVEL": "info"] - ) - ), - - .hook( - name: "format", event: .afterTool, - run: .executable("swift", arguments: ["format", "--in-place", "Sources"]), - timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) - ), - - .lspServer( - name: "swift", run: .executable("sourcekit-lsp"), - languages: [".swift": "swift"], - agents: [.claudeCode], condition: .when(platforms: [.macOS]) - ), - - .permissions( - name: "private-files", - rules: [.deny(.read, "secrets/**")], - condition: .when(scopes: [.project]) - ), - - .ignore( - name: "build-products", patterns: [".build/", "DerivedData/"], purpose: .indexing, - agents: [.cursor] - ), - - reviewer, - ], - - // Re-check these sources for updates. - watch: ["rules"] -) diff --git a/Tests/AgentsManifestTests/Fixtures/VersionCollections.swift.txt b/Tests/AgentsManifestTests/Fixtures/VersionCollections.swift.txt deleted file mode 100644 index cd9dc64..0000000 --- a/Tests/AgentsManifestTests/Fixtures/VersionCollections.swift.txt +++ /dev/null @@ -1,8 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let versions: [Version] = ["1.2.3"] -let namedVersions: [String: Version] = ["stable": "1.2.3"] -let version: Version = "1.2.3" -let referencedVersions: [Version] = [version] -let agents = Agents() diff --git a/Tests/AgentsManifestTests/Fixtures/VocabularyDepthExample.swift.txt b/Tests/AgentsManifestTests/Fixtures/VocabularyDepthExample.swift.txt deleted file mode 100644 index b6b6f35..0000000 --- a/Tests/AgentsManifestTests/Fixtures/VocabularyDepthExample.swift.txt +++ /dev/null @@ -1,22 +0,0 @@ -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - groups: [ - .group( - name: "review", - components: [ - .instructions( - chatGPT: [ - .prompt( - name: "review", - sections: [ - .section(name: "guide", condition: .when(agents: [.codex])), - ] - ), - ] - ), - ] - ), - ] -) diff --git a/Tests/AgentsManifestTests/FrontEndTests.swift b/Tests/AgentsManifestTests/FrontEndTests.swift index b4f0c07..b5457ef 100644 --- a/Tests/AgentsManifestTests/FrontEndTests.swift +++ b/Tests/AgentsManifestTests/FrontEndTests.swift @@ -1,219 +1,67 @@ import AgentsCore -import AgentsDescription import Foundation import Testing @testable import AgentsManifest -let manifestHeader = "// agents-tools-version: 1.0\nimport AgentsDescription\n\n" - +let manifestHeader = "" func document(_ body: String) throws -> DeclarationDocument { - try DeclarationDocument( - bytes: Array((manifestHeader + body).utf8), identity: DocumentIdentity("manifest")) -} - -func manifestFixture(_ name: String) throws -> [UInt8] { - Array(try Data(contentsOf: Bundle.module.resourceURL!.appendingPathComponent("Fixtures/" + name))) + try DeclarationDocument(bytes: Array(body.utf8), identity: DocumentIdentity("manifest")) } -@Suite("Manifest front end") +@Suite("YAML frontend") struct FrontEndTests { - @Test func completeExamplesCompileAndAgreeUnderValueEquality() throws { - let baselineURL = Bundle.module.resourceURL!.appendingPathComponent( - "Fixtures/ParserBaseline.json") - let baseline = - try JSONSerialization.jsonObject(with: Data(contentsOf: baselineURL)) as! [String: Any] - let baselineFixtures = baseline["fixtures"] as! [String: [String: Int]] - let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent() - .deletingLastPathComponent().deletingLastPathComponent() - let resolved = - try JSONSerialization.jsonObject( - with: Data(contentsOf: root.appendingPathComponent("Package.resolved"))) as! [String: Any] - let pins = resolved["pins"] as! [[String: Any]] - let syntaxPin = pins.first { $0["identity"] as? String == "swift-syntax" }! - #expect( - (syntaxPin["state"] as! [String: String])["version"] == baseline["swiftSyntax"] as? String) - let fixtureDirectory = Bundle.module.resourceURL!.appendingPathComponent("Fixtures") - let sourceNames = try FileManager.default.contentsOfDirectory(atPath: fixtureDirectory.path) - .filter { $0.hasSuffix(".swift.txt") }.sorted() - #expect(compiledFixtures().map(\.name).sorted() == sourceNames) - #expect(baselineFixtures.keys.sorted() == sourceNames) - for fixture in compiledFixtures() { - let name = fixture.name - let url = Bundle.module.resourceURL!.appendingPathComponent("Fixtures/" + name) - let doc = try DeclarationDocument( - bytes: Array(Data(contentsOf: url)), identity: DocumentIdentity("manifest")) - #expect(fixture.agents == Agents(value: doc.evaluation.root.value), "\(name)") - #expect(fixture.constants.keys.sorted() == doc.evaluation.constants.keys.sorted()) - for (constant, compiled) in fixture.constants { - #expect(compiled == doc.evaluation.constants[constant]?.value, "\(name): \(constant)") - } - #expect(doc.metrics.parserCalls == 1) - #expect(doc.metrics.syntaxNodes <= doc.metrics.syntaxReservation) - #expect(doc.metrics.syntaxDepth <= 128) - #expect(!doc.sourceMap.entries.isEmpty) - if let expected = baselineFixtures[name] { - #expect(doc.metrics.tokens == expected["tokens"]) - #expect(doc.metrics.syntaxReservation == expected["syntaxReservation"]) - #expect(doc.metrics.syntaxNodes == expected["syntaxNodes"]) - #expect(doc.metrics.syntaxDepth == expected["syntaxDepth"]) - } else { - Issue.record("fixture is missing from parser baseline: \(name)") - } - } + @Test(arguments: ["yes", "on", "2026-11-15"]) + func coreStringsRemainStrings(_ text: String) throws { + let doc = try document( + "version: 1\ncomponents: [{kind: subagent, name: a, description: d, prompt: \(text)}]\n") + #expect(doc.declaration.components[0]["prompt"]?.record?["value"] == .string(text)) } - - @Test func closedLiteralTyping() throws { - let bodies = [ - ("let text = \"x\"\nlet value: SectionReference = text", "manifest.type"), - ("let text = \"x\"\nlet value: PromptContent = text", "manifest.type"), - ("let text = \"x\"\nlet value: RuntimeValue = text", "manifest.type"), - ("let text = \"1.2.0\"\nlet value: Version = text", "manifest.type"), - ("let text = \"review\"\nlet value: GroupReference = text", "manifest.type"), - ("let names = [\"x\"]\nlet value: SkillSelection = names", "manifest.type"), - ("let text = \"x\"\nlet value: ConfigurationValue = text", "manifest.type"), - ("let value = .copy", "manifest.type"), - ("let value = []", "manifest.type"), - ("let value = [:]", "manifest.type"), - ("let value = nil", "manifest.type"), - ("let value = \"a\" + \"b\"", "manifest.operator"), - ("let value: SkillSelection = [\"a\"] + [\"b\"]", "manifest.operator"), - ("let value: ConfigurationValue = [1] + [2]", "manifest.operator"), - ("let value = Version(\"1.2.0\")", "manifest.call"), - ("let value = String(stringLiteral: \"x\")", "manifest.call"), - ("let value = future\nlet future = 1", "manifest.reference"), - ] - for (body, code) in bodies { - expectManifestFailure(code) { try document(body + "\nlet agents = Agents()") } - } + @Test(arguments: ["&a []", "*a", "!!str x", "!!float 1", "{x: 1}"]) + func unsupportedOrdinaryValuesAreRejected(_ text: String) { + #expect(throws: ManifestFailure.self) { try document("version: 1\nwatch: \(text)\n") } } - - @Test func domainValidationIsOfflineAndIncludesUnusedValues() throws { - let bad = [ - ( - "let bad: Condition = .when(agents: [.codex, .codex])\nlet agents = Agents()", - "manifest.domain" - ), - ("let agents = Agents(sources: [.source(name: \".\", path: \"a\")])", "manifest.domain"), - ( - "let agents = Agents(sources: [.source(name: \"a\", url: \"https://EXAMPLE.org/r.git\"), .source(name: \"b\", url: \"https://example.org/r/\")])", - "manifest.domain" - ), - ( - "let agents = Agents(components: [.hook(name: \"h\", event: .native(\"x\"), run: .executable(\"tool\"))])", - "manifest.domain" - ), - ( - "let agents = Agents(components: [.hook(name: \"h\", event: .beforeTool, run: .executable(\"tool\"), timeoutSeconds: 0)])", - "manifest.domain" - ), - ( - "let agents = Agents(components: [.subagent(name: \"../bad\", description: \"x\", prompt: \"x\")])", - "manifest.domain" - ), - ( - "let agents = Agents(components: [.mcpServer(name: \"x\", transport: .sse(url: \"https://user:pw@example.org/mcp\"))])", - "manifest.domain" - ), - ( - "let agents = Agents(components: [.command(name: \"x\", description: \"x\", prompt: \"${input:missing}\")])", - "manifest.domain" - ), - ( - "let value: ConfigurationValue = .decimal(\"1e99999\")\nlet agents = Agents()", - "manifest.domain" - ), - ("let value: Resource = .path(\"../escape\")\nlet agents = Agents()", "manifest.domain"), - ( - "let value: PermissionRule = .allow(.read, \"/private/**\")\nlet agents = Agents()", - "manifest.domain" - ), - ( - "let value: PermissionRule = .deny(.write, \"../**\")\nlet agents = Agents()", - "manifest.domain" - ), - ( - "let agents = Agents(groups: [.group(name: \"a\", uses: [\"b\"]), .group(name: \"b\", uses: [\"a\"])])", - "manifest.group.cycle" - ), - ( - "let agents = Agents(groups: [.group(name: \"unused\", uses: [\"missing\"])])", - "manifest.group.missing" - ), - ] - for (input, code) in bad { - expectManifestFailure(code) { try document(input) } - } - let doc = try document( - "let agents = Agents(sources: [.source(name: \"r\", url: \"intranet/team\")])") - #expect(doc.diagnostics.first?.code == "manifest.domain") - #expect(doc.diagnostics.first?.severity == .warning) - #expect( - String(decoding: doc.diagnostics.first!.fixIt!.replacement, as: UTF8.self) - == "\"https://intranet/team\"") - _ = try document( - "let root: Resource = .path(\"\")\nlet notes: Resource = .path(\"~notes\")\nlet rule: PermissionRule = .allow(.read, \"src/**\")\nlet agents = Agents(components: [.mcpServer(name: \"s\", transport: .streamableHTTP(url: \"HTTPS://example.org/mcp\"))])" - ) + @Test(arguments: ["\u{85}", "\u{2028}", "\u{2029}"]) + func rawSeparatorsAreRejectedBeforeParsing(_ separator: String) { + expectManifestFailure("manifest.character") { try document("# \(separator)\nversion: 1\n") } } - - @Test func duplicateKeysUseDecodedSwiftStringEqualityAndLocatedRelatedSpans() throws { - for key in ["\\u{61}", "a"] { - do { - _ = try document( - "let value: [String: Int] = [\"a\": 1, \"\(key)\": 2]\nlet agents = Agents()") - Issue.record("duplicate accepted") - } catch let error as ManifestFailure { - #expect(error.diagnostics[0].code == "manifest.dictionary.duplicateKey") - #expect(error.diagnostics[0].related.count == 1) - #expect(error.diagnostics[0].span.start > error.diagnostics[0].related[0].start) - } - } - expectManifestFailure("manifest.dictionary.duplicateKey") { - try document( - "let value: ConfigurationValue = [\"é\": 1, \"e\\u{301}\": 2]\nlet agents = Agents()") - } + @Test func escapedSeparatorsAndDecimalPayloadsRoundTrip() throws { + let body = #""" + version: 1 + components: + - kind: lspServer + name: test + run: {executable: unused} + languages: {'.swift': swift} + initializationOptions: + text: "\u0085\u2028\u2029" + decimal: !!float "1E+003" + integerLike: !!float "1" + negativeZero: !!float "-0" + '<<': {ordinary: true} + """# + let doc = try document(body) + let typed = try ManifestProjection.declaration(of: doc, environment: projectionEnvironment) + let bytes = try #require(try planned(Declaration(), typed, in: nil)) + #expect(try projected(String(decoding: bytes, as: UTF8.self)).components == typed.components) + let dumped = try ManifestDump(document: doc) + #expect(dumped.schemaVersion == 2 && dumped.format == "yaml" && dumped.manifestVersion == 1) + #expect(String(decoding: try dumped.encodedJSON(), as: UTF8.self).contains("1E+003")) } - - @Test func defaultsOrderConditionsAndProvenanceRemainSymbolic() throws { - let doc = try document( - "let sections: [SectionReference] = [\"guide\", \"guide\"]\nlet agents = Agents(defaultAgents: [], components: [.instructions(sections: sections, condition: .when(agents: []))], groups: [.group(name: \"inert\")])" - ) - #expect(doc.declaration.defaultAgents == []) - #expect(doc.declaration.components[0]["agents"] == .null) - #expect(doc.declaration.components[0]["sections"]?.elements?.count == 2) - #expect(doc.declaration.groups.count == 1) - #expect(doc.sourceMap.locations(at: "/components/0/agents").first?.defaulted == true) - #expect(doc.sourceMap.locations(at: "/components/0/sections/0").first?.origins.isEmpty == false) + @Test func sourceMapUsesOrderedSemanticPointers() throws { + let body = + "version: 1\nsources: {b: {path: b}, a: {path: a}}\ngroups: {unused: {components: [{kind: ignore, name: i, patterns: []}]}}\n" + let doc = try document(body) + let name = try #require(doc.sourceMap.locations(at: "/sources/0/name").first) + #expect(String(decoding: doc.bytes[name.span.start..] = [:] - let protocolKinds: [String: LiteralKind] = [ - "ExpressibleByStringLiteral": .string, "ExpressibleByIntegerLiteral": .integer, - "ExpressibleByBooleanLiteral": .boolean, "ExpressibleByNilLiteral": .nilLiteral, - "ExpressibleByArrayLiteral": .array, "ExpressibleByDictionaryLiteral": .dictionary, - ] - func typeSpelling(_ raw: String) -> String { - var value = raw - for (alias, type) in aliases { - value = value.replacingOccurrences(of: alias, with: type) - } - return value.replacingOccurrences(of: "Range", with: "VersionRange") - .filter { !$0.isWhitespace } - } - func signature( - _ owner: String, _ member: String, _ parameters: [(String, String, String?)], callable: Bool - ) -> String { - owner + "." + member + "(" - + parameters.map { - $0.0 + ":" + typeSpelling($0.1) + "=" + ($0.2?.filter { !$0.isWhitespace } ?? "required") - }.joined(separator: ",") + ")" + (callable ? " call" : " member") - } - for block in blocks { - let tree = Parser.parse(source: block) - let source = SourceText(Array(block.utf8), identity: DocumentIdentity("interface")) - _ = try SyntaxValidation.guardTree(Syntax(tree), source: source) - var pending: [(Syntax, String)] = [(Syntax(tree), "")] - while let (node, owner) = pending.popLast() { - var name = owner - let inheritance: InheritanceClauseSyntax? - if let declaration = node.as(StructDeclSyntax.self) { - name = declaration.name.text - namedTypes.insert(name) - inheritance = declaration.inheritanceClause - } else if let declaration = node.as(EnumDeclSyntax.self) { - name = declaration.name.text - namedTypes.insert(name) - inheritance = declaration.inheritanceClause - } else { - inheritance = nil - } - for inherited in inheritance?.inheritedTypes ?? [] { - if let kind = protocolKinds[inherited.type.trimmedDescription] { - literalTypes[name, default: []].insert(kind) - } - } - if let declaration = node.as(ExtensionDeclSyntax.self), - declaration.extendedType.trimmedDescription == "Range" - { - name = "VersionRange" - } else if let declaration = node.as(TypeAliasDeclSyntax.self) { - namedTypes.insert(declaration.name.text) - } else if let method = node.as(FunctionDeclSyntax.self), name != "Version" { - let parameters = method.signature.parameterClause.parameters.map { - ( - $0.firstName.text, $0.type.trimmedDescription, - $0.defaultValue?.value.trimmedDescription - ) - } - signatures.append(signature(name, method.name.text, parameters, callable: true)) - } else if let initializer = node.as(InitializerDeclSyntax.self), name == "Agents" { - let parameters = initializer.signature.parameterClause.parameters.map { - ( - $0.firstName.text, $0.type.trimmedDescription, - $0.defaultValue?.value.trimmedDescription - ) - } - signatures.append(signature(name, "Agents", parameters, callable: true)) - } else if let declaration = node.as(EnumCaseDeclSyntax.self) { - for element in declaration.elements { - let parameters = (element.parameterClause?.parameters ?? []).map { - ( - $0.firstName?.text ?? "_", $0.type.trimmedDescription, - $0.defaultValue?.value.trimmedDescription - ) - } - signatures.append( - signature(name, element.name.text, parameters, callable: !parameters.isEmpty)) - } - } else if let declaration = node.as(VariableDeclSyntax.self), - declaration.modifiers.contains(where: { $0.name.text == "static" }) - { - for binding in declaration.bindings { - let member = try #require( - binding.pattern.as(IdentifierPatternSyntax.self)?.identifier.text) - signatures.append(signature(name, member, [], callable: false)) - } - } - for child in node.children(viewMode: .sourceAccurate) { pending.append((child, name)) } - } - } - func registeredType(_ type: ConstructionType) -> String { - switch type { - case .untyped: return "untyped" - case .named(let name): return name - case .array(let element): return "[" + registeredType(element) + "]" - case .dictionary(let element): return "[String:" + registeredType(element) + "]" - case .optional(let element): return registeredType(element) + "?" - } - } - let registered = Vocabulary.signatures.map { value in - signature( - value.type, value.member, - value.parameters.map { - ($0.label, registeredType($0.type), $0.defaultValue.map { CanonicalPrinter().render($0) }) - }, callable: value.callable) - } - #expect(namedTypes == Vocabulary.typeNames) - #expect(literalTypes == Vocabulary.literalTypes) - #expect(signatures.sorted() == registered.sorted()) - #expect(Set(Vocabulary.scalarValues["Agent"]!.values) == Set(AgentID.allCases.map(\.rawValue))) - } - - @Test func sourceSignaturesDefineLocationAndRequirementSlots() throws { - let locations: Set = ["url", "path", "index"] - #expect(SourceRequirements.locations == locations) - #expect(SourceRequirements.locationsWithRequirements == ["url", "path"]) - #expect(SourceRequirements.labels == ["from", "exact", "branch", "revision"]) - for signature in Vocabulary.signatures where signature.type == "Source" { - try #require(signature.parameters.count >= 2) - #expect(signature.parameters[0].label == "name") - #expect(signature.parameters[0].name == "name") - #expect(signature.parameters[0].defaultValue == nil) - #expect(locations.contains(signature.parameters[1].label)) - #expect(signature.parameters[1].defaultValue == nil) - } - for location in locations { - let text = - manifestHeader + "let agents = Agents(sources: [.source(name: \"r\", " - + location + ": \"example.org/r\", from: \"1.2.3\")])" - if SourceRequirements.locationsWithRequirements.contains(location) { - _ = try Recognizer( - source: SourceText(Array(text.utf8), identity: DocumentIdentity("manifest")) - ) - .recognize() - } else { - do { - _ = try DeclarationDocument( - bytes: Array(text.utf8), identity: DocumentIdentity("manifest")) - Issue.record("unsupported source requirement was accepted") - } catch let failure as ManifestFailure { - #expect(failure.diagnostics[0].code == "manifest.syntax") - #expect(failure.metrics.parserCalls == 0) - } - } - } - } - - @Test(arguments: [ - "Documentation/Reference/Manifest.md", "Documentation/Proposals/AgentsManifest.md", - ]) - func everySwiftBlockPassesTheRealParser(_ document: String) throws { - let contract = try String(contentsOf: root.appendingPathComponent(document), encoding: .utf8) - let directory = try temporaryManifestDirectory() - defer { try? FileManager.default.removeItem(at: directory) } - for (index, tail) in contract.components(separatedBy: "```swift\n").dropFirst().enumerated() { - let block = tail.components(separatedBy: "```")[0] - let file = directory.appendingPathComponent( - "block\(index)." + (block.hasPrefix("public ") ? "swiftinterface" : "swift")) - try Data(block.utf8).write(to: file) - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/env") - process.arguments = ["swiftc", "-frontend", "-parse", file.path] - let errors = Pipe() - process.standardError = errors - try process.run() - let errorData = errors.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - #expect( - process.terminationReason == .exit && process.terminationStatus == 0, - "block \(index): \(String(decoding: errorData, as: UTF8.self))") - } - } -} diff --git a/Tests/AgentsManifestTests/LanguageVersionTests.swift b/Tests/AgentsManifestTests/LanguageVersionTests.swift deleted file mode 100644 index 56a0a64..0000000 --- a/Tests/AgentsManifestTests/LanguageVersionTests.swift +++ /dev/null @@ -1,65 +0,0 @@ -import AgentsCore -import Testing - -@testable import AgentsManifest - -@Suite("Manifest language version") -struct LanguageVersionTests { - @Test func directiveDiagnosticsAreLexicalAndDistinct() throws { - for (text, code) in [ - ("import AgentsDescription\nlet agents = Agents()", "manifest.version.missing"), - ( - "// agents-tools-version: 01.0\nimport AgentsDescription\nlet agents = Agents()", - "manifest.version.invalid" - ), - ( - "// agents-tools-version: 1.0 \nimport AgentsDescription\nlet agents = Agents()", - "manifest.version.invalid" - ), - ( - "// agents-tools-version: 2.0\nimport AgentsDescription\nlet agents = Agents()", - "manifest.version.unsupported" - ), - ( - manifestHeader + "// agents-tools-version: 1.0\nlet agents = Agents()", - "manifest.version.duplicate" - ), - ] { - do { - _ = try DeclarationDocument(bytes: Array(text.utf8), identity: DocumentIdentity("manifest")) - Issue.record("directive accepted") - } catch let failure as ManifestFailure { - #expect(failure.diagnostics[0].code == code) - #expect(failure.metrics.parserCalls == 0) - } - } - _ = try document("let text = \"// agents-tools-version: 1.0\"\nlet agents = Agents()") - } - - @Test func versionDirectiveRejectsBareCRBeforeTheParser() throws { - let directive = "// agents-tools-version: 1.0" - for suffix in ["\r", "\rimport AgentsDescription\nlet agents = Agents()"] { - do { - _ = try DeclarationDocument( - bytes: Array((directive + suffix).utf8), identity: DocumentIdentity("manifest")) - Issue.record("bare CR directive accepted") - } catch let failure as ManifestFailure { - #expect(failure.diagnostics[0].code == "manifest.version.invalid") - #expect(failure.metrics.parserCalls == 0) - #expect(failure.diagnostics[0].span.start == directive.utf8.count) - #expect(failure.diagnostics[0].span.line == 1) - #expect(failure.diagnostics[0].span.column == directive.utf8.count + 1) - } - } - for newline in ["\n", "\r\n"] { - _ = try DeclarationDocument( - bytes: Array( - (directive + newline + "import AgentsDescription" + newline + "let agents = Agents()") - .utf8), identity: DocumentIdentity("manifest")) - } - // EOF terminates the directive; the remaining grammar still requires an import. - expectManifestFailure("manifest.syntax") { - try DeclarationDocument(bytes: Array(directive.utf8), identity: DocumentIdentity("manifest")) - } - } -} diff --git a/Tests/AgentsManifestTests/LiteralConversionTests.swift b/Tests/AgentsManifestTests/LiteralConversionTests.swift deleted file mode 100644 index e72f78d..0000000 --- a/Tests/AgentsManifestTests/LiteralConversionTests.swift +++ /dev/null @@ -1,42 +0,0 @@ -import AgentsCore -import AgentsDescription -import Testing - -@testable import AgentsManifest - -@Suite("Manifest literal conversion") -struct LiteralConversionTests { - @Test func valueLiteralExamplesMatchTheRealCompiler() throws { - let values: [(String, ConfigurationValue)] = [ - ("nil", nil), ("true", true), ("-9_223_372_036_854_775_808", .integer(Int.min)), - ("[1, true, nil, \"x\"]", [1, true, nil, "x"]), - ("[\"x\": [\"y\": .decimal(\"1.25\")]]", ["x": ["y": .decimal("1.25")]]), - ("\"\\0\\t\\n\\r\\\"\\'\\\\\\u{1F600}\"", "\0\t\n\r\"'\\😀"), - ("\"\"\"\n first\n\n last\n \"\"\"", "first\n\nlast"), - ] - for (expression, compiled) in values { - let doc = try document( - "let value: ConfigurationValue = " + expression + "\nlet agents = Agents()") - #expect(doc.evaluation.constants["value"]!.value == compiled.constructionValue) - } - } - - @Test func editorLiteralConversionsMatchCompiledConfigurationValues() throws { - let values: [(StaticValue, ConfigurationValue)] = [ - (.null, nil), (.boolean(true), true), (.integer(Int.min), .integer(Int.min)), - (.string("\0\u{1F} \u{7F}😀"), "\0\u{1F} \u{7F}😀"), - (.string("first\n\nlast"), "first\n\nlast"), - (.array([.integer(1), .boolean(true), .null, .string("x")]), [1, true, nil, "x"]), - ( - .dictionary(["x": .dictionary(["y": .configuration(.decimal("1.25"))])]), - ["x": ["y": .decimal("1.25")]] - ), - ] - for (literal, compiled) in values { - let doc = try document("let value: ConfigurationValue = 0\nlet agents = Agents()") - let changed = try edited( - doc, [.replaceConstant(doc.constant(named: "value")!, with: literal, acceptingUses: [])]) - #expect(changed.evaluation.constants["value"]?.value == compiled.constructionValue) - } - } -} diff --git a/Tests/AgentsManifestTests/PrintingTests.swift b/Tests/AgentsManifestTests/PrintingTests.swift deleted file mode 100644 index 5921700..0000000 --- a/Tests/AgentsManifestTests/PrintingTests.swift +++ /dev/null @@ -1,166 +0,0 @@ -import AgentsCore -import Foundation -import Testing - -@testable import AgentsManifest - -private func local(_ location: String, _ requirement: SourceRequirement? = nil) -> SourceDeclaration -{ - SourceDeclaration(kind: .local, location: location, requirement: requirement) -} - -private let escapedAlias = "é/别名~\"\\\n\r\t\u{1}\u{7f}\u{85}" - -/// Declarations whose canonical documents are the `Printed*` goldens. -let printedDeclarations: [(String, Declaration)] = [ - ("PrintedEmpty", Declaration()), - ( - "PrintedExplicitEmpty", - Declaration(agents: [], instructions: InstructionsDeclaration(agents: [])) - ), - ( - "PrintedEscapes", - Declaration( - agents: [], - sources: [escapedAlias: SourceDeclaration(kind: .git, location: "example.org/escape.git")], - skills: [escapedAlias: SkillDeclaration(select: .names(["selected"]))], - instructions: InstructionsDeclaration(chatgpt: [ - "\"\\\n\r\t\u{1}\u{7f}\u{85} e\u{301} 😀": PromptDeclaration( - sections: ["own"], append: "notes/内容.md") - ])) - ), - ( - "PrintedRanges", - Declaration(sources: [ - "a": SourceDeclaration( - kind: .git, location: "https://Example.org/a.git", requirement: .exact("1.2.3+build")), - "b": local("./b", .upToNextMajor(from: "1.2.0")), - "c": local("./c", .upToNextMinor(from: "1.2.0-beta+build")), - "d": local("./d", .range(from: "1.2.0", to: "2.0.0")), - "e": local("./e", .upToNextMinor(from: "1.2.0+lower")), - "f": local("./f", .range(from: "1.2.0", to: "1.8.0-beta+bound")), - "g": local("./g", .upToNextMinor(from: "9223372036854775807.1.0")), - "h": SourceDeclaration( - kind: .git, location: "ssh://User@INTRANET:2222/team/h.git", - requirement: .revision("abc123")), - "i": local("./i", .upToNextMinor(from: "1.2.0-" + String(repeating: "alpha", count: 20))), - "j": SourceDeclaration(kind: .git, location: "intranet/team@variant"), - ]) - ), - ( - "PrintedWidth", - Declaration( - sources: [ - "s": local("./s"), String(repeating: "x", count: 47): local("p"), - String(repeating: "y", count: 48): local("p2"), - ], - skills: [ - "s": SkillDeclaration( - select: .names([String(repeating: "a", count: 33), String(repeating: "b", count: 24)]), - exclude: [String(repeating: "c", count: 33), String(repeating: "d", count: 24)], - mode: .link) - ]) - ), - ( - "PrintedFields", - Declaration( - agents: [.claudeCode, .codex, .opencode], - sources: [ - "empty": local("./live"), - "git": SourceDeclaration( - kind: .git, location: "intranet/team.git", requirement: .branch("main"), path: "skills"), - "index": SourceDeclaration( - kind: .wellKnown, location: "https://example.org/.well-known/skills/index.json", - path: "bundle"), - "local": local("./drafts", .revision("abc123")), - ], - skills: [ - "empty": SkillDeclaration(select: .all, mode: .edit), - "git": SkillDeclaration( - select: .names(["a", "b"]), exclude: ["b"], agents: [], mode: .copy, - overrides: [ - "a": SkillOverride(agents: [.codex], mode: .link), "b": SkillOverride(agents: []), - ]), - "index": SkillDeclaration(select: .names([])), - "local": SkillDeclaration(select: .all, overrides: ["future": SkillOverride(mode: .copy)]), - ], - instructions: InstructionsDeclaration( - agents: [.codex, .geminiCLI], sections: ["own", "git:rule", "own", "local:nested/rule"], - chatgpt: [ - "": PromptDeclaration(sections: []), - "周报": PromptDeclaration(sections: ["git:rule", "own"], append: "notes/周报.md"), - ]), - watch: ["git", "index", "local"]) - ), -] - -@Suite("Canonical manifest printing") -struct PrintingTests { - @Test(arguments: printedDeclarations) - func newDocumentsMatchTheirGoldensDeterministically(_ name: String, _ declaration: Declaration) - throws - { - let golden = try manifestFixture(name + ".swift.txt") - let printed = try CanonicalPrinter().manifest( - DeclarationConstruction.root(declaration).constructionValue) - #expect(printed == golden) - #expect( - try CanonicalPrinter().manifest(DeclarationConstruction.root(declaration).constructionValue) - == printed) - let created = try planned(Declaration(), declaration, in: nil) - let empty = ManifestProjection.equivalent( - declaration, Declaration(), environment: projectionEnvironment) - #expect(created == (empty ? nil : golden)) - #expect(try planned(Declaration(), declaration, in: nil) == created) - #expect(golden.last == 10 && !golden.contains(13)) - #expect(!golden.starts(with: [0xEF, 0xBB, 0xBF])) - let text = String(decoding: golden, as: UTF8.self) - for line in text.split(separator: "\n") where !line.contains("alphaalpha") { - #expect(line.utf8.count <= 80, "\(name): \(line)") - } - let document = try DeclarationDocument(bytes: golden, identity: DocumentIdentity("manifest")) - let projection = try ManifestProjection.declaration( - of: document, environment: projectionEnvironment) - #expect( - ManifestProjection.equivalent(projection, declaration, environment: projectionEnvironment)) - } - - @Test func firstEditsOfAnEmptyManifestUseTheCanonicalLayout() throws { - let empty = manifestHeader + "let agents = Agents()\n" - var added = Declaration() - added.sources["skills"] = SourceDeclaration(kind: .git, location: "github.com/team/skills") - try added.setSkills(["skills": SkillDeclaration(select: .all)]) - let bytes = try #require(try planned(Declaration(), added, in: empty)) - #expect( - String(decoding: bytes, as: UTF8.self) == manifestHeader + """ - let agents = Agents( - sources: [ - .source(name: "skills", url: "https://github.com/team/skills"), - ], - components: [ - .skills(source: "skills"), - ] - ) - - """) - #expect( - bytes - == (try CanonicalPrinter().manifest(DeclarationConstruction.root(added).constructionValue))) - for (name, declaration) in printedDeclarations where name != "PrintedEmpty" { - let edited = try #require(try planned(Declaration(), declaration, in: empty)) - #expect(edited == (try manifestFixture(name + ".swift.txt")), "\(name)") - } - } - - @Test func emptyArgumentListsSkipDefaultsAndRejectCommentOnlyInteriors() throws { - let doc = try document("let agents = Agents()") - let source = try doc.preparing(operations: [ - .setArgument(doc.node(at: "")!, field: "watch", value: .array([])) - ]) - #expect(source.bytes == doc.bytes) - let commented = try document("let agents = Agents(/* empty */)") - expectManifestFailure("manifest.edit.readOnly") { - try commented.preparing([.setWatch(["s"])]) - } - } -} diff --git a/Tests/AgentsManifestTests/ProjectionTests.swift b/Tests/AgentsManifestTests/ProjectionTests.swift index fa0806e..094e2e1 100644 --- a/Tests/AgentsManifestTests/ProjectionTests.swift +++ b/Tests/AgentsManifestTests/ProjectionTests.swift @@ -7,158 +7,57 @@ import Testing let projectionEnvironment = RuntimeEnvironment( projectDirectory: URL(fileURLWithPath: "/work/project", isDirectory: true), homeDirectory: URL(fileURLWithPath: "/work/home", isDirectory: true), environment: [:]) - func projected(_ body: String) throws -> Declaration { try ManifestProjection.declaration(of: document(body), environment: projectionEnvironment) } @Suite("Manifest projection") struct ProjectionTests { - @Test func compilerBackedFixturesProjectAndConstructWithoutLoss() throws { - for fixture in compiledFixtures() { - let doc = try DeclarationDocument( - bytes: manifestFixture(fixture.name), identity: DocumentIdentity(fixture.name)) - let declaration = try ManifestProjection.declaration( - of: doc, environment: projectionEnvironment) - let construction = try DeclarationConstruction.root(declaration).constructionValue - #expect(Lowering.declaration(construction) == doc.declaration, "\(fixture.name)") - #expect( - Lowering.declaration(fixture.agents.constructionValue) == doc.declaration, "\(fixture.name)" - ) - let printed = try CanonicalPrinter().manifest(construction) - let roundtrip = try DeclarationDocument( - bytes: printed, identity: DocumentIdentity(fixture.name)) - #expect(roundtrip.declaration == doc.declaration, "\(fixture.name)") - } - } - @Test func absentValuesStayDistinctFromExplicitEmptyValues() throws { - #expect(try projected("let agents = Agents()") == Declaration()) + #expect(try projected("version: 1\n") == Declaration()) let explicit = try projected( - "let agents = Agents(defaultAgents: [], components: [.instructions(agents: [])], watch: [])") + "version: 1\ndefaultAgents: []\ncomponents: [{kind: instructions, agents: []}]\nwatch: []\n") #expect(explicit.agents == []) #expect((try explicit.instructions) == InstructionsDeclaration(agents: [])) #expect(explicit.watch == nil) - let inherited = try projected("let agents = Agents(components: [.instructions()])") + let inherited = try projected("version: 1\ncomponents: [{kind: instructions}]\n") #expect(inherited.agents == nil) #expect((try inherited.instructions) == InstructionsDeclaration()) #expect((try inherited.instructions)?.agents == nil) } - @Test(arguments: [ - "groups: [.group(name: \"g\")], uses: [\"g\"]", - "components: [.skills(source: \"s\", condition: .when(agents: [.codex]))]", - "components: [.skills(source: \"s\", native: [\"claude-code/skill@1\": [\"x\": 1]])]", - "components: [.instructions(condition: .when(scopes: [.user]))]", - "components: [.instructions(sections: [.section(name: \"g\", condition: .when())])]", - "components: [.instructions(chatGPT: [.prompt(name: \"p\", sections: [], condition: .when(platforms: [.linux]))])]", - "components: [.instructions(chatGPT: [.prompt(name: \"p\", sections: [.section(name: \"g\", condition: .when())])])]", - "components: [.ignore(name: \"i\", patterns: [])]", - "components: [.skills(source: \"s\"), .skills(source: \"s\", select: [\"a\"])]", - "components: [.instructions(), .instructions(sections: [\"g\"])]", - "components: [.skills(source: \".\")]", + "groups: {g: {}}\nuses: [{group: g}]", + "components: [{kind: skills, source: s, condition: {agents: [codex]}}]", + "components: [{kind: skills, source: s, native: {'claude-code/skill@1': {x: 1}}}]", + "components: [{kind: instructions, condition: {scopes: [user]}}]", + "components: [{kind: instructions, sections: [{name: g, condition: {}}]}]", + "components: [{kind: instructions, chatgpt: {p: {sections: [], condition: {platforms: [linux]}}}}]", + "components: [{kind: instructions, chatgpt: {p: {sections: [{name: g, condition: {}}]}}}]", + "components: [{kind: ignore, name: i, patterns: []}]", + "components: [{kind: skills, source: s}, {kind: skills, source: s, select: [a]}]", + "components: [{kind: instructions}, {kind: instructions, sections: [{name: g}]}]", + "components: [{kind: skills, source: '.'}]", ]) func completeStructuresRemainSymbolic(_ fields: String) throws { - let body = #"let agents = Agents(sources: [.source(name: "s", path: "s")], "# + fields + ")" - let doc = try document(body) + let doc = try document("version: 1\nsources: {s: {path: s}}\n" + fields + "\n") let declaration = try ManifestProjection.declaration( of: doc, environment: projectionEnvironment) - #expect( - Lowering.declaration(try DeclarationConstruction.root(declaration).constructionValue) - == doc.declaration) + #expect(YAMLConstruction.root(declaration) == doc.declaration) } - @Test func unusedGroupsAndExportsArePreserved() throws { let declaration = try projected( - """ - let agents = Agents( - exports: ["review"], - sources: [.source(name: "s", path: "s")], - groups: [ - .group( - name: "review", - components: [ - .skills(source: "s", condition: .when(agents: [.codex])), - .ignore(name: "i", patterns: ["x"]), - ], - uses: ["nested"] - ), - .group(name: "nested", components: [.instructions(sections: ["g"])]), - ] - ) - """) + "version: 1\nexports: [review]\nsources: {s: {path: s}}\ngroups: {review: {components: [{kind: skills, source: s, condition: {agents: [codex]}}, {kind: ignore, name: i, patterns: [x]}], uses: [{group: nested}]}, nested: {components: [{kind: instructions, sections: [{name: g}]}]}}\n" + ) #expect(declaration.exports == ["review"]) #expect(declaration.groups.map(\.name) == ["review", "nested"]) #expect(declaration.groups[0].components.count == 2) #expect(declaration.groups[0].uses == [GroupUseDeclaration(name: "nested")]) } - @Test func environmentDependentValidationFollowsProjection() throws { let doc = try document( - "let agents = Agents(sources: [.source(name: \"a\", path: \"~/rules\"), .source(name: \"b\", path: \"/work/home/rules\")])" - ) + "version: 1\nsources: {a: {path: '~/rules'}, b: {path: /work/home/rules}}\n") #expect(throws: CoreError.self) { try ManifestProjection.declaration(of: doc, environment: projectionEnvironment) } - let other = RuntimeEnvironment( - projectDirectory: URL(fileURLWithPath: "/work/project", isDirectory: true), - homeDirectory: URL(fileURLWithPath: "/elsewhere", isDirectory: true), environment: [:]) - #expect(try ManifestProjection.declaration(of: doc, environment: other).sources.count == 2) - } - - @Test func semanticEqualityIgnoresSpellingButKeepsInheritanceAndSectionOrder() throws { - func equal(_ lhs: Declaration, _ rhs: Declaration) -> Bool { - ManifestProjection.equivalent(lhs, rhs, environment: projectionEnvironment) - } - func sources(_ source: SourceDeclaration) -> Declaration { Declaration(sources: ["s": source]) } - #expect( - equal( - sources(SourceDeclaration(kind: .git, location: "github.com/a/b")), - sources(SourceDeclaration(kind: .git, location: "https://GitHub.com/a/b.git/")))) - #expect( - equal( - sources(SourceDeclaration(kind: .local, location: "./rules", path: "./skills/")), - sources(SourceDeclaration(kind: .local, location: "/work/project/rules", path: "skills")))) - #expect( - equal( - sources( - SourceDeclaration( - kind: .git, location: "https://e.org/r", requirement: .range(from: "1.2.0", to: "2.0.0") - )), - sources( - SourceDeclaration( - kind: .git, location: "https://e.org/r", requirement: .upToNextMajor(from: "v1.2.0"))))) - #expect( - !equal( - sources( - SourceDeclaration(kind: .git, location: "https://e.org/r", requirement: .exact("1.0.0"))), - sources( - SourceDeclaration(kind: .git, location: "https://e.org/r", requirement: .exact("1.0.0+b")) - ))) - #expect( - !equal( - sources(SourceDeclaration(kind: .local, location: "a")), - sources(SourceDeclaration(kind: .local, location: "a", path: "x")))) - #expect(equal(Declaration(agents: [.codex, .cursor]), Declaration(agents: [.cursor, .codex]))) - #expect(!equal(Declaration(agents: []), Declaration())) - #expect(equal(Declaration(skills: [:], watch: []), Declaration())) - let base = Declaration(sources: ["s": SourceDeclaration(kind: .local, location: "s")]) - var left = base - var right = base - try left.setSkills([ - "s": SkillDeclaration(select: .names(["a", "b"]), exclude: [], overrides: [:]) - ]) - try right.setSkills(["s": SkillDeclaration(select: .names(["b", "a"]))]) - #expect(equal(left, right)) - try right.updateSkills { $0?["s"]?.agents = [] } - #expect(!equal(left, right)) - try left.setInstructions(InstructionsDeclaration(sections: ["a", "b"], chatgpt: [:])) - right = left - try right.updateInstructions { $0?.chatgpt = nil } - #expect(equal(left, right)) - try right.updateInstructions { $0?.sections = ["b", "a"] } - #expect(!equal(left, right)) - try right.setInstructions(nil) - #expect(!equal(left, right)) } } diff --git a/Tests/AgentsManifestTests/ResourceTests.swift b/Tests/AgentsManifestTests/ResourceTests.swift index 65af9f7..056dc18 100644 --- a/Tests/AgentsManifestTests/ResourceTests.swift +++ b/Tests/AgentsManifestTests/ResourceTests.swift @@ -1,150 +1,52 @@ import AgentsCore -import AgentsDescription import Foundation -import ManifestTestSupport import Testing @testable import AgentsManifest -@Suite("Manifest resources") +@Suite("YAML parser resources") struct ResourceTests { - @Test func everyConstantChargesItsFullExpandedCostBeforeUseOrMapping() throws { - let directory = try temporaryManifestDirectory() - defer { try? FileManager.default.removeItem(at: directory) } - var body = "let v0: ConfigurationValue = 1\n" - for index in 1...24 { - body += "let v\(index): ConfigurationValue = .array([v\(index - 1), v\(index - 1)])\n" - } - let report = try probe( - "unused-exponential-reuse", Array((manifestHeader + body + "let agents = Agents()").utf8), - semantics: true, in: directory) - #expect(report.report.stage == .evaluation) - #expect(report.report.status == "manifest.limit") - var aliases = "let seed: ConfigurationValue = 0\n" - var tail = "seed" - for level in 0..<50 { - let container = "c\(level)" - aliases += "let \(container): ConfigurationValue = .array([\(tail)])\n" - tail = container - for index in 0..<40 { - let name = "a\(level)_\(index)" - aliases += "let \(name) = \(tail)\n" - tail = name - } - } - let aliasReport = try probe( - "aliases-across-container-depth", - Array((manifestHeader + aliases + "let agents = Agents()").utf8), - semantics: true, in: directory) - #expect(aliasReport.report.status == "manifest.limit") - var flatAliases = "" - for chain in 0..<100 { - var previous = "c\(chain)" - flatAliases += "let \(previous) = 0\n" - for index in 0..<60 { - let name = "a\(chain)_\(index)" - flatAliases += "let \(name) = \(previous)\n" - previous = name - } - } - let domainReport = try probe( - "domain-reference-work", - Array((manifestHeader + flatAliases + "let agents = Agents()").utf8), - semantics: true, in: directory) - #expect(domainReport.report.stage == .domain) - #expect(domainReport.report.status == "manifest.limit") - var deep = "let v0: ConfigurationValue = 0\n" - for index in 1...65 { deep += "let v\(index): ConfigurationValue = .array([v\(index - 1)])\n" } - expectManifestFailure("manifest.limit") { try document(deep + "let agents = Agents()") } - expectManifestFailure("manifest.limit") { - try document( - "let values: [Int] = [" + Array(repeating: "0", count: 10_001).joined(separator: ",") - + "]\nlet agents = Agents()") - } + @Test func parserStageWorkCancelsBeforeTheCSTGate() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + "yaml-budget-" + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } } + let bytes = Array( + ("[" + Array(repeating: "x", count: 200_000).joined(separator: ",") + "]").utf8) + let result = try probe("wide-flow", bytes, semantics: true, in: directory) + #expect(result.report.status == "manifest.limit") + #expect(result.report.stage == .parser) + #expect(result.report.metrics.parserCallbacks == YAMLParser.callbackLimit + 1) + #expect(result.report.metrics.syntaxNodes == 0) } - - @Test func nestedCollectionsReuseTypedReferencedDescendants() throws { - let base = Array(repeating: "[0]", count: 5_000).joined(separator: ",") - var body = "let base: [[Int]] = [" + base + "]\n" - for index in 0..<4 { - body += "let nested\(index) = [[[[[[base]]]]]]\n" - } - let doc = try document(body + "let agents = Agents()") - let original = try #require(doc.evaluation.constants["base"]) - guard case .array(let originalElements) = original.value else { - Issue.record("base is not an array") - return - } - #expect(doc.evaluation.steps < ManifestLimits.Evaluation.steps) - for index in 0..<4 { - var descendant = try #require(doc.evaluation.constants["nested\(index)"]).value - for _ in 0..<6 { - guard case .array(let layer) = descendant, layer.count == 1 else { - Issue.record("missing collection layer") - return - } - descendant = layer[0] - } - guard case .array(let elements) = descendant else { - Issue.record("missing referenced array") - return - } - // Reusing the array storage keeps all 5,000 typed descendants out of conversion work. - originalElements.withUnsafeBufferPointer { original in - elements.withUnsafeBufferPointer { reused in - #expect(reused.baseAddress == original.baseAddress) - } - } + @Test func validScalarAtTheInputLimitIsAdmitted() throws { + let prefix = "version: 1\ncomponents: [{kind: subagent, name: a, description: d, prompt: '" + let suffix = "'}]\n" + let bytes = Array( + (prefix + + String( + repeating: "x", count: ManifestLimits.Input.bytes - prefix.utf8.count - suffix.utf8.count) + + suffix).utf8) + let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) + #expect(document.bytes.count == ManifestLimits.Input.bytes) + #expect(document.declaration.components.count == 1) + } + @Test func wideAndDeepShapesFailWithAnEnforcedBudget() { + for text in [ + "[" + Array(repeating: "x", count: 200_000).joined(separator: ",") + "]", + String(repeating: "[", count: 256) + "x" + String(repeating: "]", count: 256), + ] { + expectManifestFailure("manifest.limit") { try document(text) } } } - - @Test func mapOriginsAndComparisonHaveIndependentBudgets() throws { - let base = - "let sections: [SectionReference] = [" - + Array(repeating: "\"guide\"", count: 100).joined(separator: ",") + "]\n" - let components = Array(repeating: ".instructions(sections: sections)", count: 40).joined( - separator: ",") - let doc = try document(base + "let agents = Agents(components: [" + components + "])") - #expect(doc.sourceMap.entries.count > 10_000) - #expect(doc.sourceMap.entries.count <= 100_000) - #expect(doc.sourceMap.entries.reduce(0) { $0 + $1.origins.count } <= 1_000_000) - let unchanged = try doc.preparing([.setWatch([])]) - #expect(unchanged.patches.isEmpty) + @Test func inputAndContainerLimitsRemainIndependent() { expectManifestFailure("manifest.limit") { - try doc.preparing(Array(repeating: .setWatch([]), count: 101)) + try document(String(repeating: "x", count: ManifestLimits.Input.bytes + 1)) } - let tiny = try document("let agents = Agents()") expectManifestFailure("manifest.limit") { - try tiny.preparing([.setWatch(Array(repeating: "x", count: 10_001))]) + try document( + "version: 1\nwatch: [" + Array(repeating: "x", count: 10_001).joined(separator: ",") + "]\n" + ) } } - - @Test func memoryReportsDeriveGrowthFromStoredHighWaterMarks() throws { - let report = ProbeReport( - status: "manifest.limit", operation: .editing, metrics: FrontEndMetrics(), - peakMemoryBytes: 2_048, preparationBaselinePeakBytes: 1_024) - let data = try JSONEncoder().encode(report) - let fields = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) - #expect(fields["preparationPeakGrowthBytes"] == nil) - let decoded = try JSONDecoder().decode(ProbeReport.self, from: data) - #expect(decoded.preparationBaselinePeakBytes == 1_024) - #expect(decoded.preparationPeakGrowthBytes == 1_024) - } - - @Test func oversizedExplicitInsertionIsRejectedBeforeRendering() throws { - let directory = try temporaryManifestDirectory() - defer { try? FileManager.default.removeItem(at: directory) } - let result = try probe( - "oversized-direct-insert", - Array((manifestHeader + "let agents = Agents(components: [])").utf8), - extraArguments: ["--edit-oversized"], in: directory) - #expect(result.report.status == "manifest.limit") - #expect(result.report.operation == .editing) - #expect(result.report.preparationBaselinePeakBytes != nil) - // Compare RSS high-water marks after constructing the component, including earlier peaks. - // Allow 8 MiB of growth for allocator/runtime variation, below one 20 MB render buffer. - #expect(try #require(result.report.preparationPeakGrowthBytes) < 8 * 1_024 * 1_024) - try recordProbeResults([result], name: "oversized-insert-run") - } - } diff --git a/Tests/AgentsManifestTests/SemanticVersionTests.swift b/Tests/AgentsManifestTests/SemanticVersionTests.swift deleted file mode 100644 index 149d232..0000000 --- a/Tests/AgentsManifestTests/SemanticVersionTests.swift +++ /dev/null @@ -1,94 +0,0 @@ -import AgentsDescription -import Foundation -import Testing - -@testable import AgentsCore -@testable import AgentsManifest - -@Suite("Manifest semantic versions") -struct SemanticVersionTests { - @Test func descriptionValidationAndOrderingMatchCore() { - let versions = [ - "0.0.0", "v1.2.3", " V1.2.3+build ", "1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-alpha.beta", - "1.0.0-beta.2", "1.0.0-beta.11", "1.0.0-rc.1", "1.0.0", "1.0.0+build", - "\(Int.max).\(Int.max).\(Int.max)", "1.0.0-9999999999999999999999999999999", "", "1.0", - "01.0.0", "1.01.0", "1.0.01", "1.0.0-01", "1.0.0-", "1.0.0+", "1.0.0+a+b", "1.0.0-😀", - ] - for raw in versions { - let value = Version(stringLiteral: raw) - let oracle = SemanticVersion(raw) - #expect(value.valid == (oracle != nil), "\(raw)") - if let oracle { #expect(value.normalized == oracle.description) } - for other in versions { - if let a = oracle, let b = SemanticVersion(other) { - #expect((value < Version(stringLiteral: other)) == (a < b)) - #expect((value == Version(stringLiteral: other)) == (a == b)) - } - } - } - } - - @Test func rangeIRUsesPrecedenceAndExactIRKeepsMetadata() throws { - #expect( - DeclarationValue.requirement(.range(from: "1.2.0+left", to: "1.8.0+right")) - == .requirement(.range(from: "1.2.0", to: "1.8.0"))) - #expect( - DeclarationValue.requirement(.upToNextMajor(from: "1.2.0")) - == .requirement(.range(from: "1.2.0", to: "2.0.0+build"))) - #expect(DeclarationValue.requirement(.exact("1.2.0+build")) != .requirement(.exact("1.2.0"))) - let doc = try document( - "let agents = Agents(sources: [.source(name: \"s\", path: \"s\", \"1.2.0+lower\"..<\"1.8.0+upper\")])" - ) - let change = try doc.preparing([.upsertSource(.source(name: "s", path: "s", "1.2.0"..<"1.8.0"))] - ) - #expect(change.bytes == doc.bytes) - #expect(change.patches.isEmpty) - } - @Test func checkedSuccessorsCanonicalizeRangesAndKeepExactMetadata() throws { - let doc = try document( - """ - let agents = Agents(sources: [ - .source(name: "major", path: "major", " v1.2.0+lower "..<"2.0.0+upper"), - .source(name: "minor", path: "minor", "1.2.0"..<"1.3.0+meta"), - .source(name: "exact", path: "exact", exact: "V1.2.0+meta") - ]) - """) - #expect( - doc.declaration.sources[0]["requirement"] == .requirement(.upToNextMajor(from: "1.2.0+lower")) - ) - #expect( - doc.declaration.sources[1]["requirement"] == .requirement(.upToNextMinor(from: "1.2.0"))) - #expect(doc.declaration.sources[2]["requirement"] == .requirement(.exact("1.2.0+meta"))) - _ = try document( - "let agents = Agents(sources: [.source(name: \"s\", path: \"s\", \"\(Int.max).0.0\"..<\"\(Int.max).1.0\")])" - ) - for requirement in [ - "from: \"\(Int.max).0.0\"", ".upToNextMinor(from: \"1.\(Int.max).0\")", - "\"2.0.0\"..<\"1.0.0\"", "exact: \"1.0\"", - ] { - expectManifestFailure("manifest.domain") { - try document( - "let agents = Agents(sources: [.source(name: \"s\", path: \"s\", \(requirement))])") - } - } - } - - @Test func rangeValuesAndLiteralGroupReferencesAreEqual() throws { - let fixtures = compiledFixtures().first { $0.name == "RequirementValues.swift.txt" }! - let url = Bundle.module.resourceURL!.appendingPathComponent("Fixtures/" + fixtures.name) - let doc = try DeclarationDocument( - bytes: Array(Data(contentsOf: url)), identity: DocumentIdentity("manifest")) - let constants = doc.evaluation.constants - for pair in [ - ("majorFrom", "majorHelper"), ("majorFrom", "majorRange"), ("minorHelper", "minorRange"), - ("prereleaseFrom", "prereleaseHelper"), ("prereleaseFrom", "prereleaseRange"), - ("prereleaseMinor", "prereleaseMinorRange"), ("localLiteral", "localFactory"), - ] { - #expect(constants[pair.0]!.value == constants[pair.1]!.value, "\(pair)") - #expect( - Lowering.lower(constants[pair.0]!.value) == Lowering.lower(constants[pair.1]!.value), - "\(pair)") - } - } - -} diff --git a/Tests/AgentsManifestTests/SourceMapTests.swift b/Tests/AgentsManifestTests/SourceMapTests.swift deleted file mode 100644 index b6f8083..0000000 --- a/Tests/AgentsManifestTests/SourceMapTests.swift +++ /dev/null @@ -1,45 +0,0 @@ -import AgentsCore -import Foundation -import Testing - -@testable import AgentsManifest - -@Suite("Manifest source maps") -struct SourceMapTests { - @Test func normalizedRequirementParentsKeepTheCompleteReferenceOriginChain() throws { - let doc = try document( - """ - let minimum: Version = "1.2.0" - let alias: Version = minimum - let agents = Agents(sources: [.source(name: "s", path: "s", from: alias)]) - """) - for pointer in ["/sources/0/requirement", "/sources/0/requirement/from"] { - let location = try #require(doc.sourceMap.locations(at: pointer).first) - #expect( - String(decoding: doc.bytes[location.span.start.. ProbeResult { - let input = directory.appendingPathComponent("input.swift") + let input = directory.appendingPathComponent("input.yaml") let output = directory.appendingPathComponent("output.json") let errors = directory.appendingPathComponent("stderr.txt") try Data(bytes).write(to: input) @@ -81,7 +82,7 @@ func probe( let report = try JSONDecoder().decode(ProbeReport.self, from: Data(contentsOf: output)) #expect(report.configuration == probeConfiguration, "\(name): child build configuration") // A loose runaway-process guard, not a platform-specific memory promise. 512 MiB - // leaves room for the Swift runtime, Debug SwiftSyntax and bounded source/IR copies; + // leaves room for the Swift runtime, the YAML parsers and bounded source/IR copies; // it is well above the contract's 2 MiB input, 16 MiB values and 32 MiB encoding caps. #expect( report.peakMemoryBytes < 512 * 1_024 * 1_024, "\(name): peak memory \(report.peakMemoryBytes)") @@ -91,7 +92,7 @@ func probe( #expect(report.operation == .frontEnd) #expect(report.stage == .teardown) #expect(report.metrics.parserCalls == 1) - #expect(report.metrics.syntaxNodes <= report.metrics.syntaxReservation) + #expect(report.metrics.syntaxNodes <= ManifestLimits.Syntax.nodes) } return ProbeResult( name: name, configuration: probeConfiguration, watchdogSeconds: probeWatchdogSeconds, diff --git a/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift b/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift index 85337ff..b1766f5 100644 --- a/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift @@ -7,7 +7,7 @@ import Testing @testable import AgentsCore -/// Skill and watch writes through the scope's `Agents.swift` declaration document. +/// Skill and watch writes through the scope's `agents.yaml` declaration document. @Suite("Skill declaration documents") struct ManifestLifecycleTests { @Test func freshAddCreatesTheCanonicalDeclarationInTheLockJournal() throws { @@ -28,28 +28,15 @@ struct ManifestLifecycleTests { entries.value = journal.entries }) #expect( - entries.value.map(\.path) == ["codex/demo", "state/Agents.swift", "state/agents.resolved"]) + entries.value.map(\.path) == ["codex/demo", "state/agents.yaml", "state/agents.resolved"]) #expect(entries.value.allSatisfy { $0.preimage == nil }) #expect( String(decoding: try Data(contentsOf: store.declarationURL), as: UTF8.self) == """ - // agents-tools-version: 1.0 - import AgentsDescription - - let agents = Agents( - sources: [ - .source( - name: "fixture", - path: "\(fixture.repo.path)" - ), - ], - components: [ - .skills( - source: "fixture", - mode: .copy, - agents: [.codex] - ), - ] - ) + version: 1 + sources: + "fixture": {"path": "\(fixture.repo.path)"} + components: + - {"kind": "skills", "source": "fixture", "select": "all", "exclude": [], "mode": "copy", "overrides": {}, "agents": ["codex"], "native": {}} """) #expect(try store.loadResolved().skills["demo"]?.installs == ["codex": .copy]) @@ -62,27 +49,18 @@ struct ManifestLifecycleTests { try fixture.commit() let store = fixture.store() let header = """ - // agents-tools-version: 1.0 - import AgentsDescription + # Team skills, reviewed weekly. + version: 1 + sources: + # The fixture repository. + fixture: {path: "\(fixture.repo.path)"} - // Team skills, reviewed weekly. - let agents = Agents( - sources: [ - // The fixture repository. - .source(name: "fixture", path: "\(fixture.repo.path)"), - ], """ try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) try Data( - (header + """ - - components: [ - // Everything the fixture publishes. - .skills(source: "fixture", agents: [.codex]), - ] - ) - - """).utf8 + (header + + "components:\n # Everything the fixture publishes.\n - {kind: skills, source: fixture, agents: [codex]}\n") + .utf8 ).write(to: store.declarationURL) _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) #expect(try store.loadResolved().skills.keys.sorted() == ["demo", "other"]) @@ -92,7 +70,7 @@ struct ManifestLifecycleTests { func expectUntouched() throws { let current = try text() #expect(current.hasPrefix(header)) - #expect(current.contains(" // Everything the fixture publishes.\n")) + #expect(current.contains(" # Everything the fixture publishes.\n")) } try SkillOperations.remove(skillNames: ["demo"], environment: fixture.environment) @@ -113,14 +91,14 @@ struct ManifestLifecycleTests { #expect(try store.loadDeclaration().watch == ["fixture"]) try watch.remove("fixture", environment: fixture.environment) try expectUntouched() - // Only the component's arguments and the root's watch argument were edited. + // Only the component fields and the watch field were edited. let final = try text() #expect( final.hasPrefix( header - + "\n components: [\n // Everything the fixture publishes.\n .skills(\n source: " + + "components:\n # Everything the fixture publishes.\n - {kind: skills, source: fixture, agents: [codex]" )) - #expect(final.hasSuffix("),\n ],\n watch: []\n)\n")) + #expect(final.hasSuffix("\"watch\": []\n")) let declaration = try store.loadDeclaration() #expect(declaration.watch == nil) #expect((try declaration.skills)?["fixture"]?.select == .all) @@ -158,7 +136,7 @@ struct ManifestLifecycleTests { try SkillOperations.updateInstalled( environment: fixture.environment, apply: true, beforeApply: { _ in - edited = try Data(contentsOf: store.declarationURL) + Data("// Reviewed.\n".utf8) + edited = try Data(contentsOf: store.declarationURL) + Data("# Reviewed.\n".utf8) try edited.write(to: store.declarationURL) }) } throws: { error in @@ -170,9 +148,8 @@ struct ManifestLifecycleTests { #expect(try fixture.body(fixture.target("demo")) == target) } - /// A selection held in a constant has no direct source range, so the add stops before - /// retaining content or touching targets. - @Test func readOnlySelectionStopsAnAddBeforeRetention() throws { + /// Unsupported shared aliases stop before retaining content or touching targets. + @Test func unsupportedSelectionStopsAnAddBeforeRetention() throws { let fixture = try SkillFixture() try fixture.skill("demo", body: "A") try fixture.skill("other", body: "B") @@ -181,18 +158,11 @@ struct ManifestLifecycleTests { let store = fixture.store() let declaration = Data( """ - // agents-tools-version: 1.0 - import AgentsDescription - - let picked: SkillSelection = ["demo"] - let agents = Agents( - sources: [.source(name: "fixture", path: "\(fixture.repo.path)")], - components: [.skills(source: "fixture", select: picked, mode: .copy, agents: [.codex])] - ) - + version: 1 + sources: {"fixture": {"path": "\(fixture.repo.path)"}} + components: [{"kind": "skills", "source": "fixture", "select": &picked [demo], "mode": "copy", "agents": ["codex"]}] """.utf8) try declaration.write(to: store.declarationURL) - _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) let before = try snapshot(fixture.environment.projectDirectory) #expect { try SkillOperations.add( @@ -200,7 +170,7 @@ struct ManifestLifecycleTests { source: "fixture", agents: [.codex], skillNames: ["other"], mode: .copy, environment: fixture.environment)) } throws: { error in - (error as? ManifestFailure)?.diagnostics.first?.code == "manifest.edit.readOnly" + (error as? ManifestFailure)?.diagnostics.first?.code == "manifest.unsupported" } #expect(try snapshot(fixture.environment.projectDirectory) == before) #expect(try Data(contentsOf: store.declarationURL) == declaration) @@ -216,17 +186,9 @@ struct ManifestLifecycleTests { try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) let declaration = Data( """ - // agents-tools-version: 1.0 - import AgentsDescription - - let agents = Agents( - sources: [.source(name: "fixture", path: "\(fixture.repo.path)")], - components: [ - .skills(source: "fixture"), - .mcpServer(name: "tools", transport: .stdio("server")), - ] - ) - + version: 1 + sources: {"fixture": {"path": "\(fixture.repo.path)"}} + components: [{"kind": "skills", "source": "fixture"}, {"kind": "mcpServer", "name": "tools", "transport": {"kind": "stdio", "executable": "server"}}] """.utf8) try declaration.write(to: store.declarationURL) let before = try snapshot(fixture.root) diff --git a/Tests/ComponentsTests/ImpactTests.swift b/Tests/ComponentsTests/ImpactTests.swift index 8e1797a..a9c1c1b 100644 --- a/Tests/ComponentsTests/ImpactTests.swift +++ b/Tests/ComponentsTests/ImpactTests.swift @@ -9,12 +9,9 @@ struct ImpactTests { let fixture = try LinkFixture() let graph = try fixture.link( """ - let agents = Agents(defaultAgents: [.claudeCode, .codex], components: [ - .hook(name: "format", event: .afterTool, run: .executable("never-run")), - .hook(name: "format", event: .afterTool, run: .executable("never-run")), - .hook(name: "format", event: .afterTool, run: .executable("different"), condition: .when(agents: [])), - .mcpServer(name: "empty", transport: .stdio("never-run"), agents: []), - .mcpServer(name: "linux", transport: .stdio("never-run"), condition: .when(platforms: [.linux]))]) + version: 1 + defaultAgents: ["claude-code", "codex"] + components: [{"kind": "hook", "name": "format", "event": "afterTool", "run": {"executable": "never-run"}}, {"kind": "hook", "name": "format", "event": "afterTool", "run": {"executable": "never-run"}}, {"kind": "hook", "name": "format", "event": "afterTool", "run": {"executable": "different"}, "condition": {"agents": []}}, {"kind": "mcpServer", "name": "empty", "transport": {"kind": "stdio", "executable": "never-run"}, "agents": []}, {"kind": "mcpServer", "name": "linux", "transport": {"kind": "stdio", "executable": "never-run"}, "condition": {"platforms": ["linux"]}}] """) #expect(graph.components.count == 4) #expect(graph.components[0].origins.count == 2) @@ -22,9 +19,8 @@ struct ImpactTests { #expect(throws: LinkError.self) { try fixture.link( """ - let agents = Agents(components: [ - .hook(name: "format", event: .afterTool, run: .executable("one")), - .hook(name: "format", event: .afterTool, run: .executable("two"))]) + version: 1 + components: [{"kind": "hook", "name": "format", "event": "afterTool", "run": {"executable": "one"}}, {"kind": "hook", "name": "format", "event": "afterTool", "run": {"executable": "two"}}] """) } } @@ -37,9 +33,9 @@ struct ImpactTests { try fixture.instruction("rules", at: repository, own: false) let firstPin = try fixture.commit(repository, tag: "1.0.0") let expression = """ - let agents = Agents(sources: [.source(name: "s", path: "\(repository.path)")], components: [ - .skills(source: "s", select: ["review"]), - .instructions(sections: [.section(name: "rules", source: "s")])]) + version: 1 + sources: {"s": {"path": "\(repository.path)"}} + components: [{"kind": "skills", "source": "s", "select": ["review"]}, {"kind": "instructions", "sections": [{"name": "rules", "source": "s"}]}] """ let before = try fixture.link(expression) let sectionKey = try #require(before.components.last?.key) @@ -66,14 +62,15 @@ struct ImpactTests { try fixture.skill("review", at: repository) try fixture.manifest( """ - let agents = Agents(exports: ["skills", "mcp"], groups: [ - .group(name: "skills", components: [.skills(source: ".", select: ["review"])]), - .group(name: "mcp", components: [.mcpServer(name: "server", transport: .stdio("never-run"))])]) + version: 1 + exports: ["skills", "mcp"] + groups: {"skills": {"components": [{"kind": "skills", "source": ".", "select": ["review"]}]}, "mcp": {"components": [{"kind": "mcpServer", "name": "server", "transport": {"kind": "stdio", "executable": "never-run"}}]}} """, at: repository) let firstPin = try fixture.commit(repository, tag: "1.0.0") let expression = """ - let agents = Agents(sources: [.source(name: "s", path: "\(repository.path)")], uses: [ - .group(name: "skills", source: "s"), .group(name: "mcp", source: "s")]) + version: 1 + sources: {"s": {"path": "\(repository.path)"}} + uses: [{"source": "s", "group": "skills"}, {"source": "s", "group": "mcp"}] """ let before = try fixture.link(expression) try fixture.write("change", to: "unrelated.txt", base: repository) @@ -95,7 +92,8 @@ struct ImpactTests { restrictions: "agents: []\nscopes: [\"project\"]\nplatforms: [\"macos\"]\n") let graph = try fixture.link( """ - let agents = Agents(components: [.instructions(sections: ["rules"], chatGPT: [.prompt(name: "p", sections: ["rules"])])]) + version: 1 + components: [{"kind": "instructions", "sections": [{"name": "rules"}], "chatgpt": {"p": {"sections": [{"name": "rules"}]}}}] """) #expect(graph.components[0].recipients.isEmpty) #expect(!graph.components[0].chatGPT) @@ -109,15 +107,15 @@ extension ImpactTests { let fixture = try LinkFixture() let body = permissions - ? ".permissions(name: \"shared\", rules: [.allow(.read, \"Sources/**\")]" - : ".hook(name: \"shared\", event: .afterTool, run: .executable(\"never-run\")" + ? "{kind: permissions, name: shared, rules: [{effect: allow, operation: read, pattern: \"Sources/**\"}]" + : "{kind: hook, name: shared, event: afterTool, run: {executable: never-run}" func graph(_ conditions: [String]) throws -> LinkedComponents { - let components = conditions.map { body + ", condition: \($0))" }.joined(separator: ",") - return try fixture.link("let agents = Agents(components: [\(components)])") + let components = conditions.map { body + ", condition: \($0)}" }.joined(separator: ",") + return try fixture.link("version: 1\ncomponents: [\(components)]\n") } let clauses = [ - ".when(agents: [.codex], scopes: [.project], platforms: [.macOS])", - ".when(agents: [.claudeCode], scopes: [.project], platforms: [.macOS, .linux])", + "{\"agents\": [\"codex\"], \"scopes\": [\"project\"], \"platforms\": [\"macos\"]}", + "{\"agents\": [\"claude-code\"], \"scopes\": [\"project\"], \"platforms\": [\"macos\", \"linux\"]}", ] let before = try graph(clauses) let after = try graph(clauses.reversed()) @@ -131,20 +129,20 @@ extension ImpactTests { let changed = try graph([ clauses[0], - ".when(agents: [.claudeCode], scopes: [.project], platforms: [.macOS])", + "{\"agents\": [\"claude-code\"], \"scopes\": [\"project\"], \"platforms\": [\"macos\"]}", ]) #expect(changed.components[0].recipients == component.recipients) #expect(changed.protectedChanges(from: before, allowing: [.skills]) == [component.key]) let paired = try graph([ - ".when(agents: [.codex], scopes: [.project], platforms: [.macOS])", - ".when(agents: [.claudeCode], scopes: [.project], platforms: [.linux])", - ".when(agents: [.codex, .claudeCode], scopes: [.project], platforms: [.macOS])", + "{\"agents\": [\"codex\"], \"scopes\": [\"project\"], \"platforms\": [\"macos\"]}", + "{\"agents\": [\"claude-code\"], \"scopes\": [\"project\"], \"platforms\": [\"linux\"]}", + "{\"agents\": [\"codex\", \"claude-code\"], \"scopes\": [\"project\"], \"platforms\": [\"macos\"]}", ]) let swapped = try graph([ - ".when(agents: [.codex], scopes: [.project], platforms: [.linux])", - ".when(agents: [.claudeCode], scopes: [.project], platforms: [.macOS])", - ".when(agents: [.codex, .claudeCode], scopes: [.project], platforms: [.macOS])", + "{\"agents\": [\"codex\"], \"scopes\": [\"project\"], \"platforms\": [\"linux\"]}", + "{\"agents\": [\"claude-code\"], \"scopes\": [\"project\"], \"platforms\": [\"macos\"]}", + "{\"agents\": [\"codex\", \"claude-code\"], \"scopes\": [\"project\"], \"platforms\": [\"macos\"]}", ]) #expect(swapped.components[0].recipients == paired.components[0].recipients) #expect(swapped.protectedChanges(from: paired, allowing: [.skills]) == [component.key]) @@ -156,9 +154,9 @@ extension ImpactTests { func declaration(_ payload: String, _ agent: String) -> String { let body = permissions - ? ".permissions(name: \"shared\", rules: [.allow(.read, \"\(payload)/**\")]" - : ".hook(name: \"shared\", event: .afterTool, run: .executable(\"\(payload)\")" - return body + ", condition: .when(agents: [.\(agent)]))" + ? "{kind: permissions, name: shared, rules: [{effect: allow, operation: read, pattern: \"\(payload)/**\"}]" + : "{kind: hook, name: shared, event: afterTool, run: {executable: \"\(payload)\"}" + return body + ", condition: {agents: [\(agent == "claudeCode" ? "claude-code" : agent)]}}" } let a = declaration("a", "codex") let b = declaration("b", "claudeCode") @@ -166,7 +164,7 @@ extension ImpactTests { for declarations in [[a, b, c], [b, a, c], [a, c, b]] { do { _ = try fixture.link( - "let agents = Agents(components: [\(declarations.joined(separator: ","))])") + "version: 1\ncomponents: [\(declarations.joined(separator: ","))]\n") Issue.record("expected overlapping different payloads to conflict") } catch LinkError.conflict(let key, let origins) { #expect(key.kind == (permissions ? .permissions : .hook)) @@ -182,12 +180,12 @@ extension ImpactTests { func expression(_ sections: String) -> String { let component = chatGPT - ? ".instructions(chatGPT: [.prompt(name: \"review\", sections: [\(sections)])])" - : ".instructions(sections: [\(sections)], agents: [.codex])" - return "let agents = Agents(components: [\(component)])" + ? "{\"kind\": \"instructions\", \"chatgpt\": {\"review\": {\"sections\": [\(sections)]}}}" + : "{\"kind\": \"instructions\", \"sections\": [\(sections)], \"agents\": [\"codex\"]}" + return "version: 1\ncomponents: [\(component)]\n" } - let before = try fixture.link(expression("\"a\", \"b\"")) - let after = try fixture.link(expression("\"b\", \"a\"")) + let before = try fixture.link(expression("{name: a}, {name: b}")) + let after = try fixture.link(expression("{name: b}, {name: a}")) #expect(after.protectedChanges(from: before, allowing: [.skills]).map(\.name) == ["a", "b"]) #expect(after.protectedChanges(from: before, allowing: [.instructions]).isEmpty) } @@ -197,17 +195,17 @@ extension ImpactTests { try fixture.skill("review", at: fixture.project) for name in ["a", "b"] { try fixture.instruction(name, at: fixture.project) } let declarations = [ - ".instructions(sections: [\"a\"], agents: [.codex])", - ".instructions(sections: [\"b\"], agents: [.claudeCode])", - ".instructions(chatGPT: [.prompt(name: \"first\", sections: [\"a\"])])", - ".instructions(chatGPT: [.prompt(name: \"second\", sections: [\"b\"])])", - ".mcpServer(name: \"one\", transport: .stdio(\"never-run\"))", - ".mcpServer(name: \"two\", transport: .stdio(\"never-run\"))", + "{\"kind\": \"instructions\", \"sections\": [{\"name\": \"a\"}], \"agents\": [\"codex\"]}", + "{\"kind\": \"instructions\", \"sections\": [{\"name\": \"b\"}], \"agents\": [\"claude-code\"]}", + "{\"kind\": \"instructions\", \"chatgpt\": {\"first\": {\"sections\": [{\"name\": \"a\"}]}}}", + "{\"kind\": \"instructions\", \"chatgpt\": {\"second\": {\"sections\": [{\"name\": \"b\"}]}}}", + "{\"kind\": \"mcpServer\", \"name\": \"one\", \"transport\": {\"kind\": \"stdio\", \"executable\": \"never-run\"}}", + "{\"kind\": \"mcpServer\", \"name\": \"two\", \"transport\": {\"kind\": \"stdio\", \"executable\": \"never-run\"}}", ] let before = try fixture.link( - "let agents = Agents(components: [\(declarations.joined(separator: ","))])") + "version: 1\ncomponents: [\(declarations.joined(separator: ","))]\n") let after = try fixture.link( - "let agents = Agents(components: [.skills(source: \".\", select: [\"review\"], mode: .edit), \(declarations.reversed().joined(separator: ","))])" + "version: 1\ncomponents: [{\"kind\": \"skills\", \"source\": \".\", \"select\": [\"review\"], \"mode\": \"edit\"}, \(declarations.reversed().joined(separator: ","))]\n" ) #expect(after.protectedChanges(from: before, allowing: [.skills]).isEmpty) } @@ -216,9 +214,8 @@ extension ImpactTests { let fixture = try LinkFixture() let graph = try fixture.link( """ - let agents = Agents(components: [ - .hook(name: "format", event: .afterTool, run: .executable("never-run"), condition: .when(agents: [.codex])), - .hook(name: "format", event: .afterTool, run: .executable("never-run"), condition: .when(agents: [.claudeCode]))]) + version: 1 + components: [{"kind": "hook", "name": "format", "event": "afterTool", "run": {"executable": "never-run"}, "condition": {"agents": ["codex"]}}, {"kind": "hook", "name": "format", "event": "afterTool", "run": {"executable": "never-run"}, "condition": {"agents": ["claude-code"]}}] """) #expect(graph.components.count == 1) #expect(graph.components[0].recipients == [.codex, .claudeCode]) @@ -234,7 +231,7 @@ extension ImpactTests { let source = fixture.root.appendingPathComponent("source") try fixture.write("Review", to: "review.md", base: source) func expression(_ alias: String) -> String { - "let agents = Agents(sources: [.source(name: \"\(alias)\", path: \"\(source.path)\")], components: [.command(name: \"review\", description: \"Review\", prompt: .file(\"review.md\", source: \"\(alias)\"))])" + "version: 1\nsources: {\"\(alias)\": {\"path\": \"\(source.path)\"}}\ncomponents: [{\"kind\": \"command\", \"name\": \"review\", \"description\": \"Review\", \"prompt\": {\"file\": {\"path\": \"review.md\", \"source\": \"\(alias)\"}}}]\n" } let before = try fixture.link(expression("old")) let after = try fixture.link(expression("renamed")) diff --git a/Tests/ComponentsTests/LedgerReplayTests.swift b/Tests/ComponentsTests/LedgerReplayTests.swift index 35991aa..f549f27 100644 --- a/Tests/ComponentsTests/LedgerReplayTests.swift +++ b/Tests/ComponentsTests/LedgerReplayTests.swift @@ -21,11 +21,8 @@ struct LedgerReplayTests { atPath: project.appendingPathComponent("vendor/alias").path, withDestinationPath: "data") try fixture.manifest( """ - let agents = Agents(components: [ - .mcpServer(name: "server", transport: .stdio("./bin/server")), - .command(name: "task", description: "Task", prompt: .file("prompts/task.md")), - .plugin(name: "vendor", path: "vendor", source: ".") - ]) + version: 1 + components: [{"kind": "mcpServer", "name": "server", "transport": {"kind": "stdio", "executable": "./bin/server"}}, {"kind": "command", "name": "task", "description": "Task", "prompt": {"file": {"path": "prompts/task.md"}}}, {"kind": "plugin", "name": "vendor", "path": "vendor", "source": "."}] """, at: project) try run("ledger-freeze", root: project) let ledger = try fixture.store.loadLedger(limits: .standard) @@ -36,7 +33,7 @@ struct LedgerReplayTests { try FileManager.default.createDirectory( at: cold.appendingPathComponent(".agent"), withIntermediateDirectories: true) try FileManager.default.copyItem( - at: fixture.store.declarationURL, to: cold.appendingPathComponent(".agent/Agents.swift")) + at: fixture.store.declarationURL, to: cold.appendingPathComponent(".agent/agents.yaml")) try locked.write(to: cold.appendingPathComponent(".agent/agents.resolved")) try FileManager.default.removeItem(at: project) try run("ledger-replay", root: cold) @@ -62,7 +59,7 @@ struct LedgerReplayTests { let fixture = try LinkFixture() try fixture.write("before", to: "prompt.md", base: fixture.project) let document = try fixture.document( - "let agents = Agents(components: [.command(name: \"task\", description: \"Task\", prompt: .file(\"prompt.md\"))])" + "version: 1\ncomponents: [{\"kind\": \"command\", \"name\": \"task\", \"description\": \"Task\", \"prompt\": {\"file\": {\"path\": \"prompt.md\"}}}]\n" ) try ComponentLinker.withLinkedComponents( document: document, store: fixture.store, platform: .macOS @@ -188,7 +185,7 @@ struct LedgerResourceClosureTests { atPath: fixture.project.appendingPathComponent("vendor/reference").path, withDestinationPath: "../shared/text") let document = try fixture.document( - "let agents = Agents(components: [.plugin(name: \"vendor\", path: \"vendor\", source: \".\")])" + "version: 1\ncomponents: [{\"kind\": \"plugin\", \"name\": \"vendor\", \"path\": \"vendor\", \"source\": \".\"}]\n" ) var ledger = try ComponentLinker.withLinkedComponents( document: document, store: fixture.store, platform: .macOS @@ -247,15 +244,16 @@ struct LedgerExactGitTests { try fixture.write("original", to: "prompt.md", base: producer) try fixture.manifest( """ - let agents = Agents(exports: ["task"], groups: [ - .group(name: "task", components: [.command(name: "task", description: "Task", prompt: .file("prompt.md"))]) - ]) + version: 1 + exports: ["task"] + groups: {"task": {"components": [{"kind": "command", "name": "task", "description": "Task", "prompt": {"file": {"path": "prompt.md"}}}]}} """, at: producer) let original = try fixture.commit(producer) let document = try fixture.document( """ - let agents = Agents(sources: [.source(name: "producer", path: "../producer", branch: "main")], - uses: [.group(name: "task", source: "producer")]) + version: 1 + sources: {"producer": {"path": "../producer", "requirement": {"branch": "main"}}} + uses: [{"source": "producer", "group": "task"}] """) var ledger = try ComponentLinker.withLinkedComponents( document: document, store: fixture.store, platform: .macOS @@ -271,7 +269,7 @@ struct LedgerExactGitTests { #expect(ledger.groups.first?.manifestHash.hasPrefix("sha256:") == true) #expect(ledger.sources.values.contains { $0.revision == original }) try fixture.write("changed", to: "prompt.md", base: producer) - try fixture.write("invalid producer manifest", to: ".agent/Agents.swift", base: producer) + try fixture.write("invalid producer manifest", to: ".agent/agents.yaml", base: producer) _ = try fixture.commit(producer) let resource = try #require(ledger.resources.keys.first) #if os(macOS) diff --git a/Tests/ComponentsTests/LinkBudgetTests.swift b/Tests/ComponentsTests/LinkBudgetTests.swift index 3adaad2..87ecfd3 100644 --- a/Tests/ComponentsTests/LinkBudgetTests.swift +++ b/Tests/ComponentsTests/LinkBudgetTests.swift @@ -12,15 +12,16 @@ struct LinkBudgetTests { let prompt = String(repeating: "p", count: 100_000) try fixture.manifest( """ - let agents = Agents(exports: ["g"], groups: [.group(name: "g", components: [ - .command(name: "review", description: "Review", prompt: "\(prompt)")])]) + version: 1 + exports: ["g"] + groups: {"g": {"components": [{"kind": "command", "name": "review", "description": "Review", "prompt": "\(prompt)"}]}} """, at: producer) try fixture.commit(producer) func expression(_ count: Int) -> String { - let uses = Array(repeating: ".group(name: \"g\", source: \"p\")", count: count) + let uses = Array(repeating: "{group: g, source: p}", count: count) .joined(separator: ",") return - "let agents = Agents(sources: [.source(name: \"p\", path: \"\(producer.path)\")], uses: [\(uses)])" + "version: 1\nsources: {\"p\": {\"path\": \"\(producer.path)\"}}\nuses: [\(uses)]\n" } #expect(try fixture.link(expression(100)).components.count == 100) do { @@ -35,10 +36,10 @@ struct LinkBudgetTests { let fixture = try LinkFixture() try fixture.instruction("rules", at: fixture.project) func expression(overflow: Bool) -> String { - let sections = Array(repeating: "\"rules\"", count: 10_000).joined(separator: ",") - let extra = overflow ? ", .instructions(sections: [\"rules\"])" : "" - return - "let agents = Agents(components: [.instructions(sections: [\(sections)])\(extra)])" + let sections = Array(repeating: "name: rules", count: 10_000).joined(separator: ",") + let extra = overflow ? ", {kind: instructions, sections: [{name: rules}]}" : "" + return "version: 1\ncomponents: [{kind: instructions, sections: [\(sections)]}\(extra)]\n" + } #expect(try fixture.link(expression(overflow: false)).components.count == 10_000) do { @@ -53,10 +54,10 @@ struct LinkBudgetTests { let fixture = try LinkFixture() let producer = fixture.root.appendingPathComponent("producer") try fixture.write( - String(repeating: " ", count: 2_097_153), to: ".agent/Agents.swift", base: producer) + String(repeating: " ", count: 2_097_153), to: ".agent/agents.yaml", base: producer) do { _ = try fixture.link( - "let agents = Agents(sources: [.source(name: \"p\", path: \"\(producer.path)\")], uses: [.group(name: \"g\", source: \"p\")])" + "version: 1\nsources: {\"p\": {\"path\": \"\(producer.path)\"}}\nuses: [{\"source\": \"p\", \"group\": \"g\"}]\n" ) Issue.record("expected input limit") } catch LinkError.budget(let name) { #expect(name == "manifest input bytes") } @@ -71,14 +72,16 @@ extension LinkBudgetTests { for index in 0..<257 { let source = fixture.root.appendingPathComponent("live\(index)") try fixture.skill("s\(index)", at: source) - sources.append(".source(name: \"s\(index)\", path: \"\(source.path)\")") - selections.append(".skills(source: \"s\(index)\", select: [\"s\(index)\"], mode: .edit)") + sources.append("\"s\(index)\": {\"path\": \"\(source.path)\"}") + selections.append( + "{\"kind\": \"skills\", \"source\": \"s\(index)\", \"select\": [\"s\(index)\"], \"mode\": \"edit\"}" + ) } func expression(_ count: Int, repeated: Bool = false) -> String { let selected = Array(selections.prefix(count)) let components = repeated ? selected + selected : selected return - "let agents = Agents(sources: [\(sources.prefix(count).joined(separator: ","))], components: [\(components.joined(separator: ","))])" + "version: 1\nsources: {\(sources.prefix(count).joined(separator: ","))}\ncomponents: [\(components.joined(separator: ","))]\n" } #expect(try fixture.link(expression(256)).sourceSnapshots.count == 256) #expect(try fixture.link(expression(256, repeated: true)).components.count == 512) @@ -95,12 +98,12 @@ extension LinkBudgetTests { for index in 0..<257 { let producer = fixture.root.appendingPathComponent("p\(index)") try fixture.manifest( - "let agents = Agents(exports: [\"g\"], groups: [.group(name: \"g\")])", at: producer) - sources.append(".source(name: \"p\(index)\", path: \"\(producer.path)\")") - uses.append(".group(name: \"g\", source: \"p\(index)\")") + "version: 1\nexports: [\"g\"]\ngroups: {\"g\": {}}\n", at: producer) + sources.append("\"p\(index)\": {\"path\": \"\(producer.path)\"}") + uses.append("{group: g, source: p\(index)}") } func expression(_ count: Int) -> String { - "let agents = Agents(sources: [\(sources.prefix(count).joined(separator: ","))], uses: [\(uses.prefix(count).joined(separator: ","))])" + "version: 1\nsources: {\(sources.prefix(count).joined(separator: ","))}\nuses: [\(uses.prefix(count).joined(separator: ","))]\n" } #expect(try fixture.link(expression(256)).references.count == 256) do { @@ -117,16 +120,16 @@ extension LinkBudgetTests { let producer = fixture.root.appendingPathComponent("producer\(index)") try fixture.skill("s\(index)", at: producer) try fixture.manifest( - "let agents = Agents(exports: [\"g\"], groups: [.group(name: \"g\", components: [.skills(source: \".\", select: [\"s\(index)\"], mode: .edit)])])", + "version: 1\nexports: [\"g\"]\ngroups: {\"g\": {\"components\": [{\"kind\": \"skills\", \"source\": \".\", \"select\": [\"s\(index)\"], \"mode\": \"edit\"}]}}\n", at: producer) - sources.append(".source(name: \"p\(index)\", path: \"\(producer.path)\")") - uses.append(".group(name: \"g\", source: \"p\(index)\")") + sources.append("\"p\(index)\": {\"path\": \"\(producer.path)\"}") + uses.append("{group: g, source: p\(index)}") } func expression(_ count: Int, repeated: Bool = false) -> String { let selected = Array(uses.prefix(count)) let references = repeated ? selected + selected : selected return - "let agents = Agents(sources: [\(sources.prefix(count).joined(separator: ","))], uses: [\(references.joined(separator: ","))])" + "version: 1\nsources: {\(sources.prefix(count).joined(separator: ","))}\nuses: [\(references.joined(separator: ","))]\n" } #expect(try fixture.link(expression(128)).sourceSnapshots.count == 256) #expect(try fixture.link(expression(128, repeated: true)).components.count == 256) @@ -144,13 +147,13 @@ extension LinkBudgetTests { for index in 0.. String { - "let agents = Agents(sources: [\(sources.prefix(count).joined(separator: ","))], uses: [\(uses.prefix(count).joined(separator: ","))])" + "version: 1\nsources: {\(sources.prefix(count).joined(separator: ","))}\nuses: [\(uses.prefix(count).joined(separator: ","))]\n" } #expect(try fixture.link(expression(8)).references.count == 8) do { @@ -192,12 +195,12 @@ extension LinkBudgetTests { let fixture = try LinkFixture() let groups = (0..<40).map { index in index == 39 - ? ".group(name: \"g39\")" - : ".group(name: \"g\(index)\", uses: [\"g\(index + 1)\"])" + ? "\"g39\": {}" + : "\"g\(index)\": {\"uses\": [{\"group\": \"g\(index + 1)\"}]}" }.joined(separator: ",") - let uses = Array(repeating: "\"g0\"", count: 1500).joined(separator: ",") + let uses = Array(repeating: "{group: g0}", count: 1500).joined(separator: ",") do { - _ = try fixture.link("let agents = Agents(groups: [\(groups)], uses: [\(uses)])") + _ = try fixture.link("version: 1\ngroups: {\(groups)}\nuses: [\(uses)]\n") Issue.record("expected total-work bound for repeated provenance") } catch LinkError.budget(let name) { #expect(name == "resolution/evaluation steps") } } diff --git a/Tests/ComponentsTests/LinkFixture.swift b/Tests/ComponentsTests/LinkFixture.swift index 56895b6..ce46e04 100644 --- a/Tests/ComponentsTests/LinkFixture.swift +++ b/Tests/ComponentsTests/LinkFixture.swift @@ -34,16 +34,16 @@ final class LinkFixture { } func manifest(_ expression: String, at directory: URL) throws { - try write(Self.text(expression), to: ".agent/Agents.swift", base: directory) + try write(Self.text(expression), to: ".agent/agents.yaml", base: directory) } static func text(_ expression: String) -> String { - "// agents-tools-version: 1.0\nimport AgentsDescription\n" + expression + "\n" + expression + "\n" } func document(_ expression: String) throws -> DeclarationDocument { try DeclarationDocument( - bytes: Array(Self.text(expression).utf8), identity: DocumentIdentity("consumer/Agents.swift")) + bytes: Array(Self.text(expression).utf8), identity: DocumentIdentity("consumer/agents.yaml")) } func link( diff --git a/Tests/ComponentsTests/LinkingAcceptanceTests.swift b/Tests/ComponentsTests/LinkingAcceptanceTests.swift index 28a7842..5140aa7 100644 --- a/Tests/ComponentsTests/LinkingAcceptanceTests.swift +++ b/Tests/ComponentsTests/LinkingAcceptanceTests.swift @@ -14,54 +14,36 @@ struct LinkingAcceptanceTests { let repository = try fixture.gitRepository("a") try fixture.write( - repository, ".agent/Agents.swift", + repository, ".agent/agents.yaml", manifest( """ - exports: ["server"], - groups: [ - .group(name: "server", components: [ - .mcpServer( - name: "server", transport: .stdio("server-v1"), agents: [.codex]) - ]) - ] + exports: ["server"] + groups: {"server": {"components": [{"kind": "mcpServer", "name": "server", "transport": {"kind": "stdio", "executable": "server-v1"}, "agents": ["codex"]}]}} """)) let older = try fixture.commit(repository, tag: "1.0.0") try fixture.write( - repository, ".agent/Agents.swift", + repository, ".agent/agents.yaml", manifest( """ - exports: ["server"], - groups: [ - .group(name: "server", components: [ - .mcpServer( - name: "server", transport: .stdio("server-v2"), agents: [.codex]) - ]) - ] + exports: ["server"] + groups: {"server": {"components": [{"kind": "mcpServer", "name": "server", "transport": {"kind": "stdio", "executable": "server-v2"}, "agents": ["codex"]}]}} """)) _ = try fixture.commit(repository, tag: "2.0.0") let bridge = fixture.root.appendingPathComponent("bridge", isDirectory: true) try fixture.write( - bridge, ".agent/Agents.swift", + bridge, ".agent/agents.yaml", manifest( """ - exports: ["bridge"], - sources: [.source(name: "a", path: "../a", exact: "1.0.0")], - groups: [ - .group(name: "bridge", uses: [.group(name: "server", source: "a")]) - ] + exports: ["bridge"] + sources: {"a": {"path": "../a", "requirement": {"exact": "1.0.0"}}} + groups: {"bridge": {"uses": [{"source": "a", "group": "server"}]}} """)) let document = try fixture.document( manifest( """ - sources: [ - .source(name: "a", path: "../a", from: "1.0.0"), - .source(name: "bridge", path: "../bridge"), - ], - uses: [ - .group(name: "server", source: "a"), - .group(name: "bridge", source: "bridge"), - ] + sources: {"a": {"path": "../a", "requirement": {"from": "1.0.0"}}, "bridge": {"path": "../bridge"}} + uses: [{"source": "a", "group": "server"}, {"source": "bridge", "group": "bridge"}] """)) let graph = try fixture.link(document) @@ -88,38 +70,20 @@ struct LinkingAcceptanceTests { let producer = fixture.root.appendingPathComponent("producer", isDirectory: true) try fixture.write( - producer, ".agent/Agents.swift", + producer, ".agent/agents.yaml", manifest( """ - defaultAgents: [.claudeCode, .codex], - exports: ["left", "right"], - components: [ - .mcpServer(name: "root-only", transport: .stdio("root-only")) - ], - groups: [ - .group( - name: "leaf", - components: [ - .mcpServer(name: "leaf-server", transport: .stdio("leaf")), - .mcpServer( - name: "empty-server", transport: .stdio("empty"), - condition: .when(agents: [])), - ], - condition: .when(agents: [.codex], scopes: [.project])), - .group(name: "left", uses: ["leaf"]), - .group(name: "right", uses: ["leaf"]), - ] + defaultAgents: ["claude-code", "codex"] + exports: ["left", "right"] + components: [{"kind": "mcpServer", "name": "root-only", "transport": {"kind": "stdio", "executable": "root-only"}}] + groups: {"leaf": {"components": [{"kind": "mcpServer", "name": "leaf-server", "transport": {"kind": "stdio", "executable": "leaf"}}, {"kind": "mcpServer", "name": "empty-server", "transport": {"kind": "stdio", "executable": "empty"}, "condition": {"agents": []}}], "condition": {"agents": ["codex"], "scopes": ["project"]}}, "left": {"uses": [{"group": "leaf"}]}, "right": {"uses": [{"group": "leaf"}]}} """)) let document = try fixture.document( manifest( """ - defaultAgents: [.cursor], - sources: [.source(name: "producer", path: "../producer")], - uses: [ - .group(name: "left", source: "producer"), - .group(name: "right", source: "producer"), - .group(name: "left", source: "producer"), - ] + defaultAgents: ["cursor"] + sources: {"producer": {"path": "../producer"}} + uses: [{"source": "producer", "group": "left"}, {"source": "producer", "group": "right"}, {"source": "producer", "group": "left"}] """)) let graph = try fixture.link(document) @@ -147,7 +111,7 @@ struct LinkingAcceptanceTests { return } #expect(key == leaf.key) - #expect(provenance.relativePath.hasSuffix(".agent/Agents.swift")) + #expect(provenance.relativePath.hasSuffix(".agent/agents.yaml")) #expect(!provenance.referenceChain.isEmpty) } } @@ -160,15 +124,10 @@ struct LinkingAcceptanceTests { let repository = try fixture.gitRepository("shared") let producer = manifest( """ - exports: ["server", "empty"], - groups: [ - .group(name: "server", components: [ - .mcpServer(name: "shared-server", transport: .stdio("shared"), agents: [.codex]) - ]), - .group(name: "empty"), - ] + exports: ["server", "empty"] + groups: {"server": {"components": [{"kind": "mcpServer", "name": "shared-server", "transport": {"kind": "stdio", "executable": "shared"}, "agents": ["codex"]}]}, "empty": {}} """) - try fixture.write(repository, ".agent/Agents.swift", producer) + try fixture.write(repository, ".agent/agents.yaml", producer) let older = try fixture.commit(repository, tag: "1.0.0") try fixture.write(repository, "revision-marker", "second snapshot\n") let newer = try fixture.commit(repository, tag: "2.0.0") @@ -180,17 +139,14 @@ struct LinkingAcceptanceTests { func root(version: String, includeSkill: Bool, includeEmpty: Bool) -> String { let component = includeSkill - ? #".skills(source: "drafts", select: ["draft"], mode: .edit, agents: [.codex])"# + ? "{\"kind\": \"skills\", \"source\": \"drafts\", \"select\": [\"draft\"], \"mode\": \"edit\", \"agents\": [\"codex\"]}" : "" - let extra = includeEmpty ? #", .group(name: "empty", source: "shared")"# : "" + let extra = includeEmpty ? #", {group: empty, source: shared}"# : "" return manifest( """ - sources: [ - .source(name: "shared", path: "../shared", exact: "\(version)"), - .source(name: "drafts", path: "../skills"), - ], - components: [\(component)], - uses: [.group(name: "server", source: "shared")\(extra)] + sources: {shared: {path: ../shared, requirement: {exact: "\(version)"}}, drafts: {path: ../skills}} + components: [\(component)] + uses: [{group: server, source: shared}\(extra)] """) } @@ -241,15 +197,8 @@ struct LinkingAcceptanceTests { } } -private func manifest(_ arguments: String) -> String { - """ - // agents-tools-version: 1.0 - import AgentsDescription - - let agents = Agents( - \(arguments) - ) - """ +private func manifest(_ fields: String) -> String { + "version: 1\n" + fields + "\n" } private struct LinkingFixture { @@ -279,7 +228,7 @@ private struct LinkingFixture { func document(_ text: String) throws -> DeclarationDocument { try DeclarationDocument( - bytes: Array(text.utf8), identity: DocumentIdentity("consumer/.agent/Agents.swift")) + bytes: Array(text.utf8), identity: DocumentIdentity("consumer/.agent/agents.yaml")) } func link(_ document: DeclarationDocument) throws -> LinkedComponents { diff --git a/Tests/ComponentsTests/LinkingReviewRegressionTests.swift b/Tests/ComponentsTests/LinkingReviewRegressionTests.swift index 89ca0e6..1ade3db 100644 --- a/Tests/ComponentsTests/LinkingReviewRegressionTests.swift +++ b/Tests/ComponentsTests/LinkingReviewRegressionTests.swift @@ -11,29 +11,25 @@ struct LinkingReviewRegressionTests { for kind in ["hook", "permissions"] { func component(_ payload: String, _ agent: String) -> String { + let recipient = agent == "claudeCode" ? "claude-code" : agent if kind == "hook" { - return """ - .hook( - name: "shared", event: .afterTool, run: .executable("\(payload)"), - agents: [.\(agent)]) - """ + return + "{kind: hook, name: shared, event: afterTool, run: {executable: \"\(payload)\"}, agents: [\(recipient)]}" } let rule = payload == "a" ? "allow" : "deny" - return """ - .permissions( - name: "shared", rules: [.\(rule)(.read, "files/**")], - agents: [.\(agent)]) - """ + return + "{kind: permissions, name: shared, rules: [{effect: \(rule), operation: read, pattern: files/**}], agents: [\(recipient)]}" + } let aCodex = component("a", "codex") let bClaude = component("b", "claudeCode") let aClaude = component("a", "claudeCode") let disjoint = try fixture.link( - "let agents = Agents(components: [\(aCodex), \(bClaude)])") + "version: 1\ncomponents: [\(aCodex), \(bClaude)]\n") #expect(disjoint.components.count == 2) let identical = try fixture.link( - "let agents = Agents(components: [\(aCodex), \(aClaude)])") + "version: 1\ncomponents: [\(aCodex), \(aClaude)]\n") let merged = try #require(identical.components.first) #expect(identical.components.count == 1) #expect(merged.recipients == [.codex, .claudeCode]) @@ -45,7 +41,7 @@ struct LinkingReviewRegressionTests { ] { do { _ = try fixture.link( - "let agents = Agents(components: [\(components.joined(separator: ", "))])") + "version: 1\ncomponents: [\(components.joined(separator: ", "))]\n") Issue.record("Expected conflicting \(kind) payloads to be rejected") } catch let error as LinkError { guard case .conflict(let key, _) = error else { @@ -70,27 +66,26 @@ struct LinkingReviewRegressionTests { func declaration(_ sections: String, extra: Bool = false) -> String { let instruction = prompt - ? #".instructions(chatGPT: [.prompt(name: "review", sections: ["# + sections + "])])" - : ".instructions(sections: [\(sections)], agents: [.codex])" + ? "{kind: instructions, chatgpt: {review: {sections: [\(sections)]}}}" + : "{kind: instructions, sections: [\(sections)], agents: [codex]}" let skill = extra - ? #".skills(source: "drafts", select: ["draft"], mode: .edit, agents: [.codex]),"# - : "" - let uses = extra ? #"uses: ["empty"],"# : "" + ? "{kind: skills, source: drafts, select: [draft], mode: edit, agents: [codex]}," : "" + let uses = extra ? "uses: [{group: empty}]" : "" return """ - let agents = Agents( - sources: [.source(name: "drafts", path: "../drafts")], - components: [\(skill) \(instruction)], - groups: [.group(name: "empty")], - \(uses) - watch: [] - ) + version: 1 + sources: {drafts: {path: ../drafts}} + components: [\(skill) \(instruction)] + groups: {empty: {}} + \(uses) + watch: [] """ + } - let before = try fixture.link(declaration(#""a", "b""#)) - let after = try fixture.link(declaration(#""b", "a""#)) - let unrelated = try fixture.link(declaration(#""a", "b""#, extra: true)) + let before = try fixture.link(declaration(#"{name: a}, {name: b}"#)) + let after = try fixture.link(declaration(#"{name: b}, {name: a}"#)) + let unrelated = try fixture.link(declaration(#"{name: a}, {name: b}"#, extra: true)) let beforeSections = before.components.filter { $0.key.kind == .instructions && $0.chatGPT == prompt } @@ -114,19 +109,18 @@ struct LinkingReviewRegressionTests { func declaration(distinct count: Int, repetitions: Int = 1) -> String { let sources = (0.. LinkedComponents { try ComponentLinker.withLinkedComponents( @@ -62,7 +58,7 @@ struct LinkingTests { #expect(graph.references[4].snapshot.source == "local:" + homeDependency.path) let command = try #require(graph.components.first { $0.key.name == "review" }) #expect(command.snapshot.revision == producerPin) - #expect(command.origins[0].provenance.relativePath == "published/.agent/Agents.swift") + #expect(command.origins[0].provenance.relativePath == "published/.agent/agents.yaml") let resource = try #require(command.resources.first) let file = try session.resource(snapshot: resource.snapshot, path: resource.path) #expect(try String(contentsOf: file, encoding: .utf8) == "pinned prompt") @@ -79,20 +75,18 @@ struct LinkingTests { try fixture.instruction("section", at: producer) try fixture.manifest( """ - let agents = Agents(defaultAgents: [.claudeCode], exports: ["bundle"], - components: [.mcpServer(name: "not-imported", transport: .stdio("never-run"))], - groups: [ - .group(name: "leaf", components: [.instructions(sections: ["section"])]), - .group(name: "left", uses: ["leaf"]), - .group(name: "right", uses: ["leaf"]), - .group(name: "bundle", components: [.mcpServer(name: "first", transport: .stdio("never-run"))], uses: ["left", "right"]) - ]) + version: 1 + defaultAgents: ["claude-code"] + exports: ["bundle"] + components: [{"kind": "mcpServer", "name": "not-imported", "transport": {"kind": "stdio", "executable": "never-run"}}] + groups: {"leaf": {"components": [{"kind": "instructions", "sections": [{"name": "section"}]}]}, "left": {"uses": [{"group": "leaf"}]}, "right": {"uses": [{"group": "leaf"}]}, "bundle": {"components": [{"kind": "mcpServer", "name": "first", "transport": {"kind": "stdio", "executable": "never-run"}}], "uses": [{"group": "left"}, {"group": "right"}]}} """, at: producer) let expression = """ - let agents = Agents(defaultAgents: [.codex], - sources: [.source(name: "p", path: "\(producer.path)")], - components: [.mcpServer(name: "root", transport: .stdio("never-run"))], - uses: [.group(name: "bundle", source: "p"), .group(name: "bundle", source: "p")]) + version: 1 + defaultAgents: ["codex"] + sources: {"p": {"path": "\(producer.path)"}} + components: [{"kind": "mcpServer", "name": "root", "transport": {"kind": "stdio", "executable": "never-run"}}] + uses: [{"source": "p", "group": "bundle"}, {"source": "p", "group": "bundle"}] """ let graph = try fixture.link(expression) #expect( @@ -115,18 +109,20 @@ struct LinkingTests { let producer = fixture.root.appendingPathComponent("producer") try fixture.manifest( """ - let agents = Agents(exports: ["loop"], sources: [.source(name: "self", path: ".")], - groups: [.group(name: "loop", uses: [.group(name: "loop", source: "self")])]) + version: 1 + exports: ["loop"] + sources: {"self": {"path": "."}} + groups: {"loop": {"uses": [{"source": "self", "group": "loop"}]}} """, at: producer) #expect(throws: LinkError.self) { try fixture.link( - "let agents = Agents(sources: [.source(name: \"p\", path: \"\(producer.path)\")], uses: [.group(name: \"loop\", source: \"p\")])" + "version: 1\nsources: {\"p\": {\"path\": \"\(producer.path)\"}}\nuses: [{\"source\": \"p\", \"group\": \"loop\"}]\n" ) } - try fixture.manifest("let agents = Agents(groups: [.group(name: \"private\")])", at: producer) + try fixture.manifest("version: 1\ngroups: {\"private\": {}}\n", at: producer) #expect(throws: LinkError.self) { try fixture.link( - "let agents = Agents(sources: [.source(name: \"p\", path: \"\(producer.path)\")], uses: [.group(name: \"private\", source: \"p\")])" + "version: 1\nsources: {\"p\": {\"path\": \"\(producer.path)\"}}\nuses: [{\"source\": \"p\", \"group\": \"private\"}]\n" ) } } @@ -136,11 +132,11 @@ struct LinkingTests { let dependency = fixture.root.appendingPathComponent("dependency") try fixture.initialize(dependency) try fixture.manifest( - "let agents = Agents(exports: [\"d\"], groups: [.group(name: \"d\", components: [.mcpServer(name: \"dep-one\", transport: .stdio(\"never-run\"))])])", + "version: 1\nexports: [\"d\"]\ngroups: {\"d\": {\"components\": [{\"kind\": \"mcpServer\", \"name\": \"dep-one\", \"transport\": {\"kind\": \"stdio\", \"executable\": \"never-run\"}}]}}\n", at: dependency) let depOne = try fixture.commit(dependency, tag: "1.0.0") try fixture.manifest( - "let agents = Agents(exports: [\"d\"], groups: [.group(name: \"d\", components: [.mcpServer(name: \"dep-two\", transport: .stdio(\"never-run\"))])])", + "version: 1\nexports: [\"d\"]\ngroups: {\"d\": {\"components\": [{\"kind\": \"mcpServer\", \"name\": \"dep-two\", \"transport\": {\"kind\": \"stdio\", \"executable\": \"never-run\"}}]}}\n", at: dependency) try fixture.commit(dependency, tag: "2.0.0") let producer = fixture.root.appendingPathComponent("producer") @@ -149,8 +145,10 @@ struct LinkingTests { func writeProducer(_ version: String) throws { try fixture.manifest( """ - let agents = Agents(exports: ["p"], sources: [.source(name: "d", url: "\(url)", exact: "\(version)")], - groups: [.group(name: "p", uses: [.group(name: "d", source: "d")])]) + version: 1 + exports: ["p"] + sources: {"d": {"url": "\(url)", "requirement": {"exact": "\(version)"}}} + groups: {"p": {"uses": [{"source": "d", "group": "d"}]}} """, at: producer) } try writeProducer("1.0.0") @@ -159,10 +157,9 @@ struct LinkingTests { try fixture.commit(producer, tag: "1.1.0") let graph = try fixture.link( """ - let agents = Agents(sources: [ - .source(name: "p", path: "\(producer.path)", from: "1.0.0"), - .source(name: "d", url: "\(url)", exact: "1.0.0")], - uses: [.group(name: "p", source: "p"), .group(name: "d", source: "d")]) + version: 1 + sources: {"p": {"path": "\(producer.path)", "requirement": {"from": "1.0.0"}}, "d": {"url": "\(url)", "requirement": {"exact": "1.0.0"}}} + uses: [{"source": "p", "group": "p"}, {"source": "d", "group": "d"}] """) #expect(graph.components.map(\.key.name) == ["dep-one", "dep-one"]) #expect(graph.selections["local:" + producer.path]?.revision == lower) @@ -178,9 +175,10 @@ struct LinkingTests { restrictions: "agents: [claude-code]\nscopes: [project]\nplatforms: [macos]\n") let graph = try fixture.link( """ - let agents = Agents(defaultAgents: [.codex], sources: [.source(name: "s", path: "\(source.path)")], - components: [.skills(source: "s", select: ["review"], mode: .edit, - overrides: [.skill(name: "review", agents: [.claudeCode, .codex])])]) + version: 1 + defaultAgents: ["codex"] + sources: {"s": {"path": "\(source.path)"}} + components: [{"kind": "skills", "source": "s", "select": ["review"], "mode": "edit", "overrides": {"review": {"agents": ["claude-code", "codex"]}}}] """) let component = try #require(graph.components.first) #expect(component.recipients == [.claudeCode]) @@ -192,7 +190,7 @@ struct LinkingTests { try fixture.skill("review", at: source, restrictions: "agents: wrong\n") #expect(throws: (any Error).self) { try fixture.link( - "let agents = Agents(sources: [.source(name: \"s\", path: \"\(source.path)\")], components: [.skills(source: \"s\")])" + "version: 1\nsources: {\"s\": {\"path\": \"\(source.path)\"}}\ncomponents: [{\"kind\": \"skills\", \"source\": \"s\"}]\n" ) } } @@ -205,18 +203,23 @@ extension LinkingTests { try fixture.initialize(dependency) try fixture.write("old", to: "prompt.md", base: dependency) try fixture.manifest( - "let agents = Agents(exports: [\"d\"], groups: [.group(name: \"d\")])", at: dependency) + "version: 1\nexports: [\"d\"]\ngroups: {\"d\": {}}\n", at: dependency) let first = try fixture.commit(dependency, tag: "1.0.0") try fixture.write("new", to: "prompt.md", base: dependency) try fixture.commit(dependency, tag: "1.1.0") let producer = fixture.root.appendingPathComponent("producer") try fixture.manifest( """ - let agents = Agents(exports: ["tools"], sources: [.source(name: "r", url: "file://localhost\(dependency.path)", from: "1.0.0")], groups: [.group(name: "tools", components: [.command(name: "review", description: "Review", prompt: .file("prompt.md", source: "r"))])]) + version: 1 + exports: ["tools"] + sources: {"r": {"url": "file://localhost\(dependency.path)", "requirement": {"from": "1.0.0"}}} + groups: {"tools": {"components": [{"kind": "command", "name": "review", "description": "Review", "prompt": {"file": {"path": "prompt.md", "source": "r"}}}]}} """, at: producer) let graph = try fixture.link( """ - let agents = Agents(sources: [.source(name: "p", path: "\(producer.path)"), .source(name: "d", url: "file://localhost\(dependency.path)", exact: "1.0.0")], uses: [.group(name: "tools", source: "p"), .group(name: "d", source: "d")]) + version: 1 + sources: {"p": {"path": "\(producer.path)"}, "d": {"url": "file://localhost\(dependency.path)", "requirement": {"exact": "1.0.0"}}} + uses: [{"source": "p", "group": "tools"}, {"source": "d", "group": "d"}] """) #expect(graph.components.first?.resources.first?.snapshot.revision == first) #expect(graph.constraints.filter { $0.source.hasPrefix("localhost/") }.count == 2) diff --git a/Tests/ComponentsTests/SnapshotTests.swift b/Tests/ComponentsTests/SnapshotTests.swift index 3545574..cb1641e 100644 --- a/Tests/ComponentsTests/SnapshotTests.swift +++ b/Tests/ComponentsTests/SnapshotTests.swift @@ -74,13 +74,17 @@ struct SnapshotTests { try fixture.skill("one", at: repository) try fixture.manifest( """ - let agents = Agents(exports: ["tools"], groups: [.group(name: "tools", components: [.skills(source: ".", mode: .edit)])]) + version: 1 + exports: ["tools"] + groups: {"tools": {"components": [{"kind": "skills", "source": ".", "mode": "edit"}]}} """, at: repository) try fixture.commit(repository) do { _ = try fixture.link( """ - let agents = Agents(sources: [.source(name: "p", url: "file://localhost\(repository.path)")], uses: [.group(name: "tools", source: "p")]) + version: 1 + sources: {"p": {"url": "file://localhost\(repository.path)"}} + uses: [{"source": "p", "group": "tools"}] """) Issue.record("expected immutable edit rejection") } catch LinkError.invalid(_, let positions) { @@ -94,7 +98,9 @@ struct SnapshotTests { #expect(throws: (any Error).self) { try fixture.link( """ - let agents = Agents(sources: [.source(name: "p", url: "file://localhost\(repository.path)")], uses: [.group(name: "tools", source: "p")]) + version: 1 + sources: {"p": {"url": "file://localhost\(repository.path)"}} + uses: [{"source": "p", "group": "tools"}] """) } } @@ -104,19 +110,20 @@ struct SnapshotTests { let repository = fixture.root.appendingPathComponent("remote") try fixture.initialize(repository) try fixture.manifest( - "let agents = Agents(exports: [\"leaf\"], groups: [.group(name: \"leaf\", components: [.mcpServer(name: \"leaf\", transport: .stdio(\"never-run\"))])])", + "version: 1\nexports: [\"leaf\"]\ngroups: {\"leaf\": {\"components\": [{\"kind\": \"mcpServer\", \"name\": \"leaf\", \"transport\": {\"kind\": \"stdio\", \"executable\": \"never-run\"}}]}}\n", at: repository.appendingPathComponent("child")) func producer(path: String, requirement: String = "") throws { try fixture.manifest( """ - let agents = Agents(exports: ["g"], sources: [ - .source(name: "child", path: "\(path)"\(requirement))], groups: [ - .group(name: "g", uses: [.group(name: "leaf", source: "child")])]) + version: 1 + exports: [g] + sources: {child: {path: "\(path)"\(requirement)}} + groups: {g: {uses: [{group: leaf, source: child}]}} """, at: repository) try fixture.commit(repository) } let expression = - "let agents = Agents(sources: [.source(name: \"p\", url: \"file://localhost\(repository.path)\")], uses: [.group(name: \"g\", source: \"p\")])" + "version: 1\nsources: {\"p\": {\"url\": \"file://localhost\(repository.path)\"}}\nuses: [{\"source\": \"p\", \"group\": \"g\"}]\n" try producer(path: "child") let graph = try fixture.link(expression) #expect(graph.components.first?.key.name == "leaf") @@ -126,7 +133,7 @@ struct SnapshotTests { try producer(path: path) #expect(throws: (any Error).self) { try fixture.link(expression) } } - try producer(path: "child", requirement: ", exact: \"1.0.0\"") + try producer(path: "child", requirement: ", requirement: {exact: \"1.0.0\"}") #expect(throws: LinkError.self) { try fixture.link(expression) } try FileManager.default.createSymbolicLink( at: repository.appendingPathComponent("escape"), withDestinationURL: fixture.project) @@ -166,7 +173,7 @@ extension SnapshotTests { for name in ["a", "b"] { let directory = repository.appendingPathComponent(name) try fixture.manifest( - "let agents = Agents(exports: [\"tools\"], groups: [.group(name: \"tools\", components: [.mcpServer(name: \"\(name)\", transport: .stdio(\"never-run\"))])])", + "version: 1\nexports: [\"tools\"]\ngroups: {\"tools\": {\"components\": [{\"kind\": \"mcpServer\", \"name\": \"\(name)\", \"transport\": {\"kind\": \"stdio\", \"executable\": \"never-run\"}}]}}\n", at: directory) } let commit = try fixture.commit(repository) @@ -175,12 +182,15 @@ extension SnapshotTests { let producer = fixture.root.appendingPathComponent("producer-" + name) try fixture.manifest( """ - let agents = Agents(exports: ["tools"], sources: [.source(name: "s", url: "file://localhost\(repository.path)", subpath: "\(name)")], groups: [.group(name: "tools", uses: [.group(name: "tools", source: "s")])]) + version: 1 + exports: ["tools"] + sources: {"s": {"url": "file://localhost\(repository.path)", "subpath": "\(name)"}} + groups: {"tools": {"uses": [{"source": "s", "group": "tools"}]}} """, at: producer) - sources.append(".source(name: \"\(name)\", path: \"\(producer.path)\")") + sources.append("\"\(name)\": {\"path\": \"\(producer.path)\"}") } let graph = try fixture.link( - "let agents = Agents(sources: [\(sources.joined(separator: ","))], uses: [.group(name: \"tools\", source: \"a\"), .group(name: \"tools\", source: \"b\")])" + "version: 1\nsources: {\(sources.joined(separator: ","))}\nuses: [{\"source\": \"a\", \"group\": \"tools\"}, {\"source\": \"b\", \"group\": \"tools\"}]\n" ) #expect(graph.components.map(\.key.name) == ["a", "b"]) #expect(graph.components.map(\.key.root) == ["a", "b"]) @@ -258,11 +268,13 @@ extension SnapshotTests { try fixture.write("Prompt bytes", to: "prompts/review.md", base: repository) try fixture.manifest( """ - let agents = Agents(exports: ["tools"], groups: [.group(name: "tools", components: [.command(name: "review", description: "Review", prompt: .file("prompts/review.md"))])]) + version: 1 + exports: ["tools"] + groups: {"tools": {"components": [{"kind": "command", "name": "review", "description": "Review", "prompt": {"file": {"path": "prompts/review.md"}}}]}} """, at: repository) let pin = try fixture.commit(repository, tag: "1.0.0") let document = try fixture.document( - "let agents = Agents(sources: [.source(name: \"p\", path: \"\(repository.path)\")], uses: [.group(name: \"tools\", source: \"p\")])" + "version: 1\nsources: {\"p\": {\"path\": \"\(repository.path)\"}}\nuses: [{\"source\": \"p\", \"group\": \"tools\"}]\n" ) var borrowed: URL? let graph = try ComponentLinker.withLinkedComponents( @@ -292,11 +304,12 @@ extension SnapshotTests { try fixture.skill("one", at: fixture.project) let pin = try fixture.commit(fixture.project) try fixture.skill("two", at: fixture.project) - let linked = try fixture.link("let agents = Agents(components: [.skills(source: \".\")])") + let linked = try fixture.link( + "version: 1\ncomponents: [{\"kind\": \"skills\", \"source\": \".\"}]\n") #expect(linked.components.map(\.key.name) == ["one"]) #expect(linked.components[0].pin?.revision == pin) let edited = try fixture.link( - "let agents = Agents(components: [.skills(source: \".\", mode: .edit)])") + "version: 1\ncomponents: [{\"kind\": \"skills\", \"source\": \".\", \"mode\": \"edit\"}]\n") #expect(edited.components.map(\.key.name) == ["one", "two"]) for component in edited.components { guard case .skill(let skill, .edit, _) = component.payload else { diff --git a/Tests/ComponentsTests/UserScopeTests.swift b/Tests/ComponentsTests/UserScopeTests.swift index 5c20837..fa573a5 100644 --- a/Tests/ComponentsTests/UserScopeTests.swift +++ b/Tests/ComponentsTests/UserScopeTests.swift @@ -18,10 +18,9 @@ struct UserScopeTests { } let document = try fixture.document( """ - let agents = Agents(defaultAgents: [.codex], components: [ - .command(name: "review", description: "Review", prompt: .file("prompt.md")), - .hook(name: "run", event: .afterTool, run: .executable("tools/run")), - .skills(source: ".", mode: .edit)]) + version: 1 + defaultAgents: ["codex"] + components: [{"kind": "command", "name": "review", "description": "Review", "prompt": {"file": {"path": "prompt.md"}}}, {"kind": "hook", "name": "run", "event": "afterTool", "run": {"executable": "tools/run"}}, {"kind": "skills", "source": ".", "mode": "edit"}] """) func link() throws -> LinkedComponents { try ComponentLinker.withLinkedComponents(document: document, store: store, platform: .macOS) { @@ -31,7 +30,7 @@ struct UserScopeTests { #expect(component.recipients == [.codex]) let provenance = try #require(component.origins.first?.provenance) #expect(provenance.sourceIdentity == "local:" + store.directory.path) - #expect(provenance.relativePath == "Agents.swift") + #expect(provenance.relativePath == "agents.yaml") } for component in graph.components.prefix(2) { let resource = try #require(component.resources.first) @@ -69,9 +68,9 @@ struct UserScopeTests { } let document = try fixture.document( """ - let agents = Agents(sources: [.source(name: "rules", path: "rules")], components: [ - .instructions(sections: [.section(name: "rules", source: "rules")], - chatGPT: [.prompt(name: "p", sections: [.section(name: "rules", source: "rules")], append: "append.md")])]) + version: 1 + sources: {"rules": {"path": "rules"}} + components: [{"kind": "instructions", "sections": [{"name": "rules", "source": "rules"}], "chatgpt": {"p": {"sections": [{"name": "rules", "source": "rules"}], "append": "append.md"}}}] """) try ComponentLinker.withLinkedComponents(document: document, store: store, platform: .macOS) { graph, session in @@ -84,7 +83,7 @@ struct UserScopeTests { #expect(append.snapshot.source == "local:" + fixture.home.path) #expect(append.path == "append.md") #expect(graph.components[1].origins[0].dependencies.contains(append.snapshot)) - #expect(graph.components[1].origins[0].provenance.relativePath == "Agents.swift") + #expect(graph.components[1].origins[0].provenance.relativePath == "agents.yaml") } } @@ -94,14 +93,14 @@ struct UserScopeTests { for directory in [fixture.project, fixture.home, store.directory] { try fixture.instruction("rules", at: directory) } - for section in ["\"rules\"", ".section(name: \"rules\", source: \".\")"] { + for section in ["{name: rules}", "{\"name\": \"rules\", \"source\": \".\"}"] { for selection in [ - ".instructions(sections: [\(section)])", - ".instructions(chatGPT: [.prompt(name: \"p\", sections: [\(section)])])", + "{\"kind\": \"instructions\", \"sections\": [\(section)]}", + "{\"kind\": \"instructions\", \"chatgpt\": {\"p\": {\"sections\": [\(section)]}}}", ] { do { _ = try ComponentLinker.withLinkedComponents( - document: fixture.document("let agents = Agents(components: [\(selection)])"), + document: fixture.document("version: 1\ncomponents: [\(selection)]\n"), store: store, platform: .macOS ) { _, _ in Issue.record("expected named-source requirement") } } catch LinkError.invalid(let message, let spans) { @@ -118,14 +117,15 @@ struct UserScopeTests { try fixture.write("home append", to: "append.md", base: fixture.home) try fixture.manifest( """ - let agents = Agents(defaultAgents: [.claudeCode], exports: ["g"], groups: [ - .group(name: "g", components: [.instructions(sections: ["producer"], - chatGPT: [.prompt(name: "p", sections: ["producer"], append: "append.md")])])]) + version: 1 + defaultAgents: ["claude-code"] + exports: ["g"] + groups: {"g": {"components": [{"kind": "instructions", "sections": [{"name": "producer"}], "chatgpt": {"p": {"sections": [{"name": "producer"}], "append": "append.md"}}}]}} """, at: producer) let pin = try fixture.commit(producer) try ComponentLinker.withLinkedComponents( document: fixture.document( - "let agents = Agents(sources: [.source(name: \"p\", path: \"producer\")], uses: [.group(name: \"g\", source: \"p\")])" + "version: 1\nsources: {\"p\": {\"path\": \"producer\"}}\nuses: [{\"source\": \"p\", \"group\": \"g\"}]\n" ), store: store, platform: .macOS ) { graph, session in let component = try #require(graph.components.first) @@ -133,7 +133,7 @@ struct UserScopeTests { #expect(component.snapshot.revision == pin) #expect(component.recipients == [.claudeCode]) #expect(component.origins[0].provenance.sourceIdentity == "local:" + producer.path) - #expect(component.origins[0].provenance.relativePath == ".agent/Agents.swift") + #expect(component.origins[0].provenance.relativePath == ".agent/agents.yaml") #expect(!component.origins[0].consumerEditable) let prompt = try #require(graph.components.last) #expect(prompt.chatGPT) diff --git a/Tests/ManifestTestProcess/main.swift b/Tests/ManifestTestProcess/main.swift index af3f0fa..db697dc 100644 --- a/Tests/ManifestTestProcess/main.swift +++ b/Tests/ManifestTestProcess/main.swift @@ -1,5 +1,4 @@ import AgentsCore -import AgentsDescription import AgentsManifest import Foundation import ManifestTestSupport @@ -73,7 +72,7 @@ if CommandLine.arguments.contains("--edit-oversized") { var preparationBaselinePeakBytes: UInt64? do { let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) - let component = Component.ignore( + let component = ComponentDeclaration.ignore( name: "large", patterns: [String(repeating: "x", count: 20_000_000)]) preparationBaselinePeakBytes = peakMemory() _ = try document.preparing([.insertComponent(component, into: .root, at: .first)]) diff --git a/Tests/StateTestProcess/LedgerProbe.swift b/Tests/StateTestProcess/LedgerProbe.swift index c92219c..28e46f4 100644 --- a/Tests/StateTestProcess/LedgerProbe.swift +++ b/Tests/StateTestProcess/LedgerProbe.swift @@ -40,7 +40,7 @@ func ledgerProbe(_ action: String, store: StateStore) throws { if action == "ledger-freeze" { let document = try DeclarationDocument( bytes: Array(Data(contentsOf: store.declarationURL)), - identity: DocumentIdentity("probe/Agents.swift")) + identity: DocumentIdentity("probe/agents.yaml")) let ledger = try ComponentLinker.withLinkedComponents( document: document, store: store, platform: { diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 7c7f984..454913a 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -326,7 +326,7 @@ if arguments[2].hasPrefix("ledger-") { InstructionLocations.file(for: .geminiCLI, scope: scope, environment: store.environment)!, with: .data(Data("New instructions\n".utf8))) try transaction.replace( - store.declarationURL, with: .data(manifestText("defaultAgents: [.cursor]"))) + store.declarationURL, with: .data(manifestText("defaultAgents: [\"cursor\"]\n"))) try transaction.replace(store.resolvedURL, with: .data(StateStore.encode(ResolvedState()))) try transaction.commit() } else if arguments[2] == "watch-crash" { @@ -367,7 +367,7 @@ if arguments[2].hasPrefix("ledger-") { ) .appendingPathComponent("target"), with: .copy(root.appendingPathComponent("new"))) try transaction.replace( - store.declarationURL, with: .data(manifestText("defaultAgents: [.codex]"))) + store.declarationURL, with: .data(manifestText("defaultAgents: [\"codex\"]\n"))) try transaction.replace( store.resolvedURL, with: .data( diff --git a/Tests/StateTestSupport/ManifestText.swift b/Tests/StateTestSupport/ManifestText.swift index bd9eae3..53a7564 100644 --- a/Tests/StateTestSupport/ManifestText.swift +++ b/Tests/StateTestSupport/ManifestText.swift @@ -1,9 +1,6 @@ import Foundation -/// A language 1.0 declaration document whose root `Agents(...)` call receives `arguments` -/// verbatim, for fixtures that need declaration bytes without the declaration model. -package func manifestText(_ arguments: String = "") -> Data { - let call = arguments.isEmpty ? "Agents()" : "Agents(\n \(arguments)\n)" - let header = "// agents-tools-version: 1.0\nimport AgentsDescription\n\n" - return Data((header + "let agents = \(call)\n").utf8) +/// YAML fields for transaction fixtures that need bytes without the declaration model. +package func manifestText(_ fields: String = "") -> Data { + Data(("version: 1\n" + fields + (fields.hasSuffix("\n") || fields.isEmpty ? "" : "\n")).utf8) } From eb6526a30b700d272cf23f97d36797287a4d23f6 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:42:48 +0800 Subject: [PATCH 044/171] test: align YAML acceptance fixtures with the contract --- .../IndependentYAMLAcceptanceTests.swift | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/Tests/AgentsManifestTests/IndependentYAMLAcceptanceTests.swift b/Tests/AgentsManifestTests/IndependentYAMLAcceptanceTests.swift index bc2ab2f..7def43d 100644 --- a/Tests/AgentsManifestTests/IndependentYAMLAcceptanceTests.swift +++ b/Tests/AgentsManifestTests/IndependentYAMLAcceptanceTests.swift @@ -209,7 +209,7 @@ struct IndependentYAMLAcceptanceTests { condition: {agents: []} transport: kind: stdio - executable: /does-not-exist/marker-program + executable: nonexistent-marker-program environment: {TOKEN: {secret: token}} groups: unused: @@ -241,7 +241,7 @@ struct IndependentYAMLAcceptanceTests { transport == .stdio( ExecutableDeclaration( - executable: "/does-not-exist/marker-program", environment: ["TOKEN": .secret("token")])) + executable: "nonexistent-marker-program", environment: ["TOKEN": .secret("token")])) ) #expect( declaration.groups[0].components == [ @@ -287,7 +287,12 @@ struct IndependentYAMLAcceptanceTests { " prompt: |- # prompt header\n Keep this block.\n", "\n# Tail stays.", ]) - #expect(output == input.replacingOccurrences(of: "patterns: [old]", with: "patterns: [new]")) + let scalar = try #require(input.range(of: "old")) + let prefix = String(input[..= prefix.utf8.count + suffix.utf8.count) } @Test func flowFieldEditRetainsNeighboringComments() throws { @@ -305,7 +310,12 @@ struct IndependentYAMLAcceptanceTests { "# Heading\nversion: 1\n", "{kind: ignore, name: second, patterns: [keep]} ] # components", "\n# Footer", ]) - #expect(output == input.replacingOccurrences(of: "patterns: [old]", with: "patterns: [new]")) + let scalar = try #require(input.range(of: "old")) + let prefix = String(input[..= prefix.utf8.count + suffix.utf8.count) } @Test func insertingIntoEmptyComponentsKeepsSurroundingSections() throws { From decfa8db99906cb1607e82d06d623facefb3cd1e Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:44:10 +0800 Subject: [PATCH 045/171] feat: verify private filesystem access before writing --- Sources/AgentsCore/FileAccess.swift | 240 +++++++++++++++++++ Sources/CPlatform/CPlatform.c | 177 ++++++++++++++ Sources/CPlatform/include/CPlatform.h | 22 ++ Tests/AgentsCoreTests/FileAccessTests.swift | 246 ++++++++++++++++++++ 4 files changed, 685 insertions(+) create mode 100644 Sources/AgentsCore/FileAccess.swift create mode 100644 Tests/AgentsCoreTests/FileAccessTests.swift diff --git a/Sources/AgentsCore/FileAccess.swift b/Sources/AgentsCore/FileAccess.swift new file mode 100644 index 0000000..11183f7 --- /dev/null +++ b/Sources/AgentsCore/FileAccess.swift @@ -0,0 +1,240 @@ +import CPlatform +import Foundation + +/// Access metadata is separate from content generations. ACL bytes contain ordered +/// numeric identities and inheritance, never resolved account names or payload bytes. +struct FileAccessEvidence: Codable, Equatable, Sendable { + enum ACLFormat: String, Codable, Sendable { + case darwinExternal + case linuxPOSIX + } + + let identity: FileObjectIdentity + let owner: UInt32 + let group: UInt32 + let mode: mode_t + let aclFormat: ACLFormat + let acl: Data + let defaultACL: Data + + static func capture(descriptor: Int32) throws -> Self { + try read(descriptor: descriptor).evidence + } + + func validate(descriptor: Int32) throws { + guard try Self.capture(descriptor: descriptor) == self else { + throw CoreError.invalidState("filesystem access changed during preparation") + } + } + + /// Requires a live owner-readable/writable object with no effective access for + /// other identities. Root and same-UID adversaries are outside this boundary. + @discardableResult + static func requirePrivate(descriptor: Int32) throws -> Self { + let current = try read(descriptor: descriptor) + guard current.evidence.owner == geteuid(), current.evidence.mode & 0o7000 == 0, + current.assessment == 0, + current.evidence.identity.isDirectory || current.links == 1 + else { + throw CoreError.invalidState("private filesystem access cannot be established") + } + return current.evidence + } + + /// Traversable ordinary ancestors are allowed. Sticky directories protect an + /// already-owned child, but ACL deletion/control grants are never excused by sticky. + @discardableResult + static func requireNonReplaceableDirectory( + descriptor: Int32, protectingOwner childOwner: UInt32 + ) throws -> Self { + let current = try read(descriptor: descriptor) + let evidence = current.evidence + let trustedOwner = evidence.owner == geteuid() || evidence.owner == 0 + let stickyProtection = + evidence.mode & 0o1000 != 0 && (childOwner == geteuid() || childOwner == 0) + guard evidence.identity.isDirectory, trustedOwner, + current.assessment & UInt32(PLATFORM_ACCESS_EXTERNAL_CONTROL) == 0, + current.assessment & UInt32(PLATFORM_ACCESS_EXTERNAL_WRITE) == 0 || stickyProtection, + platform_access(descriptor, ".", X_OK) == 0 + else { + throw CoreError.invalidState("filesystem ancestry permits replacement or is unprovable") + } + return evidence + } + + private static func read(descriptor: Int32) throws -> ( + evidence: Self, assessment: UInt32, links: UInt64 + ) { + var value = platform_file_access() + guard platform_read_file_access(descriptor, &value) == 0 else { + throw CoreError.invalidState("cannot capture descriptor access evidence: \(errno)") + } + defer { platform_dispose_file_access(&value) } + #if os(macOS) + let format = ACLFormat.darwinExternal + #else + let format = ACLFormat.linuxPOSIX + #endif + let evidence = Self( + identity: FileObjectIdentity(value.info), owner: value.info.st_uid, + group: value.info.st_gid, mode: value.info.st_mode & 0o7777, aclFormat: format, + acl: value.acl.map { Data(bytes: $0, count: value.acl_size) } ?? Data(), + defaultACL: value.default_acl.map { Data(bytes: $0, count: value.default_acl_size) } ?? Data() + ) + return (evidence, value.assessment, UInt64(value.info.st_nlink)) + } +} + +extension DirectoryHandle { + func accessEvidence() throws -> FileAccessEvidence { + try FileAccessEvidence.capture(descriptor: descriptor) + } + + /// The entry and ACL are read through the same no-follow descriptor. Comparing + /// this result on every pinned ancestor detects replacement as well as access drift. + func accessEvidence(_ name: String) throws -> FileAccessEvidence? { + try requireAccessComponent(name) + guard let before = try info(name) else { return nil } + let file = openat(descriptor, name, O_RDONLY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC) + guard file >= 0 else { + throw CoreError.invalidState("cannot open entry for access evidence") + } + defer { close(file) } + let result = try FileAccessEvidence.capture(descriptor: file) + guard result.identity == FileObjectIdentity(before), + let after = try info(name), Self.sameGeneration(before, after) + else { throw CoreError.invalidState("entry changed while capturing access evidence") } + return result + } + + /// Returns an empty verified inode. No producer receives a writable payload + /// path before verification; inherited ACLs are retained and evaluated as found. + func createPrivateFile(_ name: String) throws -> PrivateFileHandle { + try requireAccessComponent(name) + let parentEvidence = try privateCreationParent() + let file = openat(descriptor, name, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) + guard file >= 0 else { throw CoreError.invalidState("cannot create private file: \(errno)") } + var retained = false + defer { if !retained { close(file) } } + var created = stat() + guard fstat(file, &created) == 0 else { + throw CoreError.invalidState("cannot identify created private file") + } + do { + let evidence = try FileAccessEvidence.requirePrivate(descriptor: file) + try parentEvidence.validate(descriptor: descriptor) + guard try accessEvidence(name) == evidence else { + throw CoreError.invalidState("private file changed during creation") + } + let result = PrivateFileHandle( + descriptor: file, parent: self, name: name, evidence: evidence, + parentEvidence: parentEvidence) + retained = true + return result + } catch { + try? removeEmptyPrivateCreation( + name, identity: FileObjectIdentity(created), directory: false, + parentEvidence: parentEvidence) + throw error + } + } + + func createPrivateDirectory(_ name: String) throws -> DirectoryHandle { + try requireAccessComponent(name) + let parentEvidence = try privateCreationParent() + guard mkdirat(descriptor, name, 0o700) == 0 else { + throw CoreError.invalidState("cannot create private directory: \(errno)") + } + guard let created = try info(name) else { + throw CoreError.invalidState("private directory disappeared during creation") + } + do { + let directory = try child(name, matching: created) + let evidence = try FileAccessEvidence.requirePrivate(descriptor: directory.descriptor) + try parentEvidence.validate(descriptor: descriptor) + guard try accessEvidence(name) == evidence else { + throw CoreError.invalidState("private directory changed during creation") + } + try directory.sync() + try sync() + return directory + } catch { + try? removeEmptyPrivateCreation( + name, identity: FileObjectIdentity(created), directory: true, parentEvidence: parentEvidence + ) + throw error + } + } + + private func privateCreationParent() throws -> FileAccessEvidence { + let evidence = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: descriptor, protectingOwner: geteuid()) + guard platform_access(descriptor, ".", W_OK | X_OK) == 0 else { + throw CoreError.invalidState("private creation requires writable directory access") + } + return evidence + } + + private func removeEmptyPrivateCreation( + _ name: String, identity: FileObjectIdentity, directory: Bool, + parentEvidence: FileAccessEvidence + ) throws { + // If the namespace lost its protection, retain the empty object for its owner + // rather than risking an unlink of an external replacement. + try parentEvidence.validate(descriptor: descriptor) + guard try info(name).map(FileObjectIdentity.init) == identity else { return } + // A failed creation has never received bytes. rmdir also refuses unexpected children. + guard unlinkat(descriptor, name, directory ? AT_REMOVEDIR : 0) == 0 else { return } + try sync() + } +} + +/// The parent remains pinned until the last write. Publication, full path ancestry, +/// durable journal ownership and eventual disposal remain the transaction's duties. +final class PrivateFileHandle { + let descriptor: Int32 + let evidence: FileAccessEvidence + private let parent: DirectoryHandle + private let name: String + private let parentEvidence: FileAccessEvidence + + fileprivate init( + descriptor: Int32, parent: DirectoryHandle, name: String, evidence: FileAccessEvidence, + parentEvidence: FileAccessEvidence + ) { + self.descriptor = descriptor + self.parent = parent + self.name = name + self.evidence = evidence + self.parentEvidence = parentEvidence + } + + deinit { close(descriptor) } + + func write(_ data: Data) throws { + try parentEvidence.validate(descriptor: parent.descriptor) + guard try FileAccessEvidence.requirePrivate(descriptor: descriptor) == evidence, + try parent.accessEvidence(name) == evidence + else { throw CoreError.invalidState("private file access changed before writing") } + try data.withUnsafeBytes { bytes in + var offset = 0 + while offset < bytes.count { + let count = CPlatform.write( + descriptor, bytes.baseAddress!.advanced(by: offset), bytes.count - offset) + if count < 0 && errno == EINTR { continue } + guard count > 0 else { throw CoreError.invalidState("cannot write private file") } + offset += count + } + } + guard platform_sync(descriptor) == 0 else { + throw CoreError.invalidState("cannot synchronize private file") + } + try parent.sync() + } +} + +private func requireAccessComponent(_ name: String) throws { + guard !name.isEmpty, name != ".", name != "..", !name.contains("/"), !name.contains("\0") else { + throw CoreError.invalidState("access operation requires one path component") + } +} diff --git a/Sources/CPlatform/CPlatform.c b/Sources/CPlatform/CPlatform.c index c221734..aa34e56 100644 --- a/Sources/CPlatform/CPlatform.c +++ b/Sources/CPlatform/CPlatform.c @@ -2,6 +2,7 @@ #include "CPlatform.h" #include +#include #include #include @@ -232,6 +233,182 @@ int platform_copy_link_metadata(int sourceDirectory, const char *source, #endif } +void platform_dispose_file_access(struct platform_file_access *value) { + free(value->acl); + free(value->default_acl); + memset(value, 0, sizeof(*value)); +} + +static unsigned int access_permissions(unsigned int permissions) { + return ((permissions & 4) ? PLATFORM_ACCESS_EXTERNAL_READ : 0) | + ((permissions & 2) ? PLATFORM_ACCESS_EXTERNAL_WRITE : 0) | + ((permissions & 1) ? PLATFORM_ACCESS_EXTERNAL_SEARCH : 0); +} + +#if defined(__APPLE__) +static int read_access_acl(int descriptor, struct platform_file_access *value) { + acl_t acl = acl_get_fd_np(descriptor, ACL_TYPE_EXTENDED); + // Darwin reports ENOENT for an absent extended ACL even on a valid open fd. + // fstat brackets this read; unsupported/denied ACL queries still fail closed. + if (!acl) return errno == ENOENT ? 0 : -1; + int result = -1; + ssize_t size = acl_size(acl); + if (size < 0) goto done; + // acl_copy_ext uses the portable external representation, including ordered + // qualifiers, permissions and inheritance flags, without resolving UUIDs. + value->acl = calloc(size ? (size_t)size : 1, 1); + if (!value->acl) { errno = ENOMEM; goto done; } + ssize_t count = acl_copy_ext(value->acl, acl, size); + if (count < 0) goto done; + value->acl_size = (size_t)count; + acl_entry_t entry; + int status = acl_get_entry(acl, ACL_FIRST_ENTRY, &entry); + while (status == 0) { + acl_tag_t tag; + acl_flagset_t flags; + acl_permset_mask_t permissions; + if (acl_get_tag_type(entry, &tag) < 0 || acl_get_flagset_np(entry, &flags) < 0 || + acl_get_permset_mask_np(entry, &permissions) < 0) goto done; + if (tag != ACL_EXTENDED_ALLOW && tag != ACL_EXTENDED_DENY) { errno = ENOTSUP; goto done; } + const acl_permset_mask_t known = ACL_READ_DATA | ACL_WRITE_DATA | ACL_EXECUTE | + ACL_DELETE | ACL_APPEND_DATA | ACL_DELETE_CHILD | ACL_READ_ATTRIBUTES | + ACL_WRITE_ATTRIBUTES | ACL_READ_EXTATTRIBUTES | ACL_WRITE_EXTATTRIBUTES | + ACL_READ_SECURITY | ACL_WRITE_SECURITY | ACL_CHANGE_OWNER | ACL_SYNCHRONIZE; + if (permissions & ~known) { errno = ENOTSUP; goto done; } + int inheritOnly = acl_get_flag_np(flags, ACL_ENTRY_ONLY_INHERIT); + if (inheritOnly < 0) goto done; + if (!inheritOnly) { + const acl_permset_mask_t read = ACL_READ_DATA; + const acl_permset_mask_t write = ACL_WRITE_DATA | ACL_APPEND_DATA; + const acl_permset_mask_t control = ACL_DELETE | ACL_DELETE_CHILD | + ACL_WRITE_SECURITY | ACL_CHANGE_OWNER | ACL_WRITE_ATTRIBUTES | ACL_WRITE_EXTATTRIBUTES; + const acl_permset_mask_t required = read | write | control | + (S_ISDIR(value->info.st_mode) ? ACL_SEARCH : 0); + // Without identity-directory resolution a deny may apply to the owner. + // Reject that unprovable layout; do not reorder ACEs or guess membership. + if (tag == ACL_EXTENDED_DENY && (permissions & required)) { + value->assessment |= PLATFORM_ACCESS_OWNER_DENIED; + } + if (tag == ACL_EXTENDED_ALLOW) { + if (permissions & read) value->assessment |= PLATFORM_ACCESS_EXTERNAL_READ; + if (permissions & write) value->assessment |= PLATFORM_ACCESS_EXTERNAL_WRITE; + if (permissions & ACL_SEARCH) value->assessment |= PLATFORM_ACCESS_EXTERNAL_SEARCH; + if (permissions & control) value->assessment |= PLATFORM_ACCESS_EXTERNAL_CONTROL; + } + } + status = acl_get_entry(acl, ACL_NEXT_ENTRY, &entry); + } + // Darwin returns -1/EINVAL at the end of iteration, unlike the POSIX API. + if (errno != EINVAL) goto done; + result = 0; +done:; + int error = errno; + acl_free(acl); + errno = error; + return result; +} +#else +static int read_acl_xattr(int descriptor, const char *name, void **bytes, size_t *length) { + ssize_t size = fgetxattr(descriptor, name, NULL, 0); + if (size < 0) return errno == ENODATA ? 0 : -1; + *bytes = malloc(size ? (size_t)size : 1); + if (!*bytes) { errno = ENOMEM; return -1; } + ssize_t count = fgetxattr(descriptor, name, *bytes, (size_t)size); + if (count < 0) return -1; + if (count != size) { errno = EAGAIN; return -1; } + *length = (size_t)count; + return 0; +} + +static unsigned int acl_u16(const unsigned char *p) { + return (unsigned int)p[0] | ((unsigned int)p[1] << 8); +} + +static uint32_t acl_u32(const unsigned char *p) { + return (uint32_t)acl_u16(p) | ((uint32_t)acl_u16(p + 2) << 16); +} + +// The kernel validates installed ACLs. Validate the representation as well so an +// unrecognized format never becomes an empty/permissive guessed assessment. +static int posix_acl_permissions(const void *bytes, size_t size, uid_t owner, + unsigned int *ownerPermissions, unsigned int *external) { + const unsigned char *p = bytes; + if (size < 4 || (size - 4) % 8 != 0 || acl_u32(p) != 2) { errno = ENOTSUP; return -1; } + unsigned int seen = 0, group = 0, named = 0, other = 0, mask = 7; + bool hasNamed = false; + for (size_t offset = 4; offset < size; offset += 8) { + unsigned int tag = acl_u16(p + offset), permissions = acl_u16(p + offset + 2); + uint32_t identifier = acl_u32(p + offset + 4); + if (permissions > 7) { errno = ENOTSUP; return -1; } + if (tag == 2 || tag == 8) { + if (identifier == UINT32_MAX) { errno = ENOTSUP; return -1; } + hasNamed = true; + // The owning user's class always wins over a named entry for that uid. + if (tag == 8 || identifier != owner) named |= permissions; + continue; + } + if (identifier != UINT32_MAX || (seen & tag)) { errno = ENOTSUP; return -1; } + seen |= tag; + switch (tag) { + case 1: *ownerPermissions = permissions; break; + case 4: group = permissions; break; + case 16: mask = permissions; break; + case 32: other = permissions; break; + default: errno = ENOTSUP; return -1; + } + } + if ((seen & 37) != 37 || (hasNamed && !(seen & 16))) { errno = ENOTSUP; return -1; } + *external = ((group | named) & mask) | other; + return 0; +} + +static int read_access_acl(int descriptor, struct platform_file_access *value) { + if (read_acl_xattr(descriptor, "system.posix_acl_access", &value->acl, &value->acl_size) < 0) return -1; + unsigned int owner = (value->info.st_mode >> 6) & 7; + unsigned int external = (value->info.st_mode & 7) | ((value->info.st_mode >> 3) & 7); + if (value->acl && posix_acl_permissions(value->acl, value->acl_size, value->info.st_uid, + &owner, &external) < 0) return -1; + value->assessment = access_permissions(external); + unsigned int required = S_ISDIR(value->info.st_mode) ? 7 : 6; + if ((owner & required) != required) value->assessment |= PLATFORM_ACCESS_OWNER_DENIED; + if (S_ISDIR(value->info.st_mode)) { + if (read_acl_xattr(descriptor, "system.posix_acl_default", &value->default_acl, + &value->default_acl_size) < 0) return -1; + if (value->default_acl) { + unsigned int ignoredOwner, ignoredExternal; + if (posix_acl_permissions(value->default_acl, value->default_acl_size, value->info.st_uid, + &ignoredOwner, &ignoredExternal) < 0) return -1; + } + } + return 0; +} +#endif + +int platform_read_file_access(int descriptor, struct platform_file_access *result) { + memset(result, 0, sizeof(*result)); + if (fstat(descriptor, &result->info) < 0) return -1; + if (!S_ISREG(result->info.st_mode) && !S_ISDIR(result->info.st_mode)) { + errno = EINVAL; + return -1; + } + unsigned int owner = (result->info.st_mode >> 6) & 7; + unsigned int required = S_ISDIR(result->info.st_mode) ? 7 : 6; + result->assessment = access_permissions((result->info.st_mode & 7) | ((result->info.st_mode >> 3) & 7)); + if ((owner & required) != required) result->assessment |= PLATFORM_ACCESS_OWNER_DENIED; + if (read_access_acl(descriptor, result) < 0) goto failed; + struct stat after; + if (fstat(descriptor, &after) < 0) goto failed; + if (!platform_same_generation(&result->info, &after) || + result->info.st_uid != after.st_uid || result->info.st_gid != after.st_gid || + result->info.st_nlink != after.st_nlink) { errno = EAGAIN; goto failed; } + return 0; +failed:; + int error = errno; + platform_dispose_file_access(result); + errno = error; + return -1; +} + int platform_spawn(pid_t *pid, const char *executable, char *const argv[], char *const environment[], const char *directory, int lock, bool inheritInput, int output, int error) { diff --git a/Sources/CPlatform/include/CPlatform.h b/Sources/CPlatform/include/CPlatform.h index 436a04c..a09f267 100644 --- a/Sources/CPlatform/include/CPlatform.h +++ b/Sources/CPlatform/include/CPlatform.h @@ -34,6 +34,28 @@ int platform_copy_metadata(int source, int destination, mode_t mode); int platform_copy_link_metadata(int sourceDirectory, const char *source, int destinationDirectory, const char *destination); +// ACL bytes are descriptor-derived, ordered, and platform-specific: Darwin's +// external ACL representation or Linux's POSIX ACL xattr format. No names or +// directory-service lookups participate in capture or evaluation. +enum { + PLATFORM_ACCESS_OWNER_DENIED = 1, + PLATFORM_ACCESS_EXTERNAL_READ = 2, + PLATFORM_ACCESS_EXTERNAL_WRITE = 4, + PLATFORM_ACCESS_EXTERNAL_SEARCH = 8, + PLATFORM_ACCESS_EXTERNAL_CONTROL = 16 +}; +struct platform_file_access { + struct stat info; + void *acl; + size_t acl_size; + void *default_acl; + size_t default_acl_size; + unsigned int assessment; +}; +// Failure never changes the object. Success owns allocations released by dispose. +int platform_read_file_access(int descriptor, struct platform_file_access *result); +void platform_dispose_file_access(struct platform_file_access *value); + // Returns a POSIX error number, as posix_spawn does. The caller owns all fds. // In the child only stdin, stdout, stderr and the specified lock survive exec. int platform_spawn(pid_t *pid, const char *executable, char *const argv[], diff --git a/Tests/AgentsCoreTests/FileAccessTests.swift b/Tests/AgentsCoreTests/FileAccessTests.swift new file mode 100644 index 0000000..ca765e9 --- /dev/null +++ b/Tests/AgentsCoreTests/FileAccessTests.swift @@ -0,0 +1,246 @@ +import CPlatform +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Descriptor access and private creation") +struct FileAccessTests { + @Test func verifiesEmptyPrivateObjectsBeforeFirstPayloadWrite() throws { + let fixture = try AccessFixture() + let directory = try fixture.handle.createPrivateDirectory("private") + let file = try directory.createPrivateFile("payload") + var info = stat() + try #require(fstat(file.descriptor, &info) == 0) + #expect(info.st_size == 0) + #expect(info.st_mode & 0o7777 == 0o600) + #expect(info.st_uid == geteuid()) + #expect(file.evidence.group == info.st_gid) + #expect(try FileAccessEvidence.requirePrivate(descriptor: directory.descriptor).mode == 0o700) + let encoded = try JSONEncoder().encode(file.evidence) + #expect(try JSONDecoder().decode(FileAccessEvidence.self, from: encoded) == file.evidence) + let bytes = Data("private payload".utf8) + try file.write(bytes) + #expect(try directory.read("payload") == bytes) + #expect(try directory.accessEvidence("payload") == file.evidence) + } + + @Test(arguments: ["mode", "acl", "parent", "replacement"]) + func refusesChangedAccessBeforeAnyPayload(_ change: String) throws { + let fixture = try AccessFixture() + let file = try fixture.handle.createPrivateFile("payload") + switch change { + case "mode": try #require(fchmod(file.descriptor, 0o644) == 0) + case "acl": try grantRead(fixture.root.appendingPathComponent("payload")) + case "parent": try #require(fchmod(fixture.handle.descriptor, 0o777) == 0) + default: + try #require( + renameat(fixture.handle.descriptor, "payload", fixture.handle.descriptor, "old") == 0) + try fixture.handle.write("payload", data: Data("unrelated".utf8)) + } + #expect(throws: CoreError.self) { try file.write(Data("private payload".utf8)) } + var info = stat() + try #require(fstat(file.descriptor, &info) == 0) + #expect(info.st_size == 0) + if change == "replacement" { + #expect(try fixture.handle.read("payload") == Data("unrelated".utf8)) + } + } + + @Test func accessEvidenceDetectsACLChangesWithoutModeChanges() throws { + let fixture = try AccessFixture() + let file = try fixture.handle.createPrivateFile("payload") + let before = try FileAccessEvidence.capture(descriptor: file.descriptor) + #if os(macOS) + try addACL("everyone allow readsecurity", at: fixture.root.appendingPathComponent("payload")) + #else + try installPOSIXACL( + descriptor: file.descriptor, owner: 6, named: 4, mask: 0, defaultACL: false) + #endif + let after = try FileAccessEvidence.capture(descriptor: file.descriptor) + #expect(before.mode == after.mode) + #expect(before.identity == after.identity) + #expect(before.acl != after.acl) + #expect(throws: CoreError.self) { try before.validate(descriptor: file.descriptor) } + #expect(try FileAccessEvidence.requirePrivate(descriptor: file.descriptor) == after) + } + + @Test func effectiveACLGrantsAndOwnerDenialsAreEvaluated() throws { + let fixture = try AccessFixture() + let file = try fixture.handle.createPrivateFile("payload") + let url = fixture.root.appendingPathComponent("payload") + try grantRead(url) + #expect(throws: CoreError.self) { + try FileAccessEvidence.requirePrivate(descriptor: file.descriptor) + } + #if os(macOS) + var info = stat() + try #require(fstat(file.descriptor, &info) == 0) + #expect(info.st_mode & 0o777 == 0o600) + try addACL("everyone deny read", at: url) + #else + // A named read grant with a zero mask is not effective access. + try installPOSIXACL( + descriptor: file.descriptor, owner: 6, named: 4, mask: 0, defaultACL: false) + _ = try FileAccessEvidence.requirePrivate(descriptor: file.descriptor) + // Mask bits alone grant nothing when every masked entry is empty. + try installPOSIXACL( + descriptor: file.descriptor, owner: 6, named: 0, mask: 4, defaultACL: false) + _ = try FileAccessEvidence.requirePrivate(descriptor: file.descriptor) + try installPOSIXACL( + descriptor: file.descriptor, owner: 0, named: 4, mask: 0, defaultACL: false) + #endif + #expect(throws: CoreError.self) { + try FileAccessEvidence.requirePrivate(descriptor: file.descriptor) + } + // Exercise the actual kernel's current-owner open denial, not just ACL bytes. + try #require(geteuid() != 0) + let denied = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) + let code = errno + if denied >= 0 { close(denied) } + #expect(denied == -1 && (code == EACCES || code == EPERM)) + } + + @Test func inheritanceIsCheckedOnTheCreatedInode() throws { + let fixture = try AccessFixture() + #if os(macOS) + try addACL("everyone allow read,file_inherit,only_inherit", at: fixture.root) + // Inherit-only grants do not grant access to this directory itself. + _ = try FileAccessEvidence.requirePrivate(descriptor: fixture.handle.descriptor) + #expect(throws: CoreError.self) { try fixture.handle.createPrivateFile("payload") } + #expect(try fixture.handle.info("payload") == nil) + #else + try installPOSIXACL( + descriptor: fixture.handle.descriptor, owner: 7, named: 4, mask: 4, defaultACL: true) + let before = try fixture.handle.accessEvidence() + #expect(!before.defaultACL.isEmpty) + let file = try fixture.handle.createPrivateFile("payload") + #expect(!file.evidence.acl.isEmpty) + _ = try FileAccessEvidence.requirePrivate(descriptor: file.descriptor) + try file.write(Data("private payload".utf8)) + // The create mode masks named access; an owner-denying default is still fatal. + try installPOSIXACL( + descriptor: fixture.handle.descriptor, owner: 0, named: 4, mask: 4, defaultACL: true) + #expect(throws: CoreError.self) { try fixture.handle.createPrivateFile("denied") } + #expect(try fixture.handle.info("denied") == nil) + #expect(throws: CoreError.self) { try before.validate(descriptor: fixture.handle.descriptor) } + #endif + } + + @Test func inheritedOwnerDenialDoesNotWriteOrRepairPolicy() throws { + let fixture = try AccessFixture() + try setRestrictiveInheritedDirectoryACL(fixture.root) + let before = try fixture.handle.accessEvidence() + #expect(throws: CoreError.self) { try fixture.handle.createPrivateDirectory("denied") } + #expect(try fixture.handle.info("denied") == nil) + #expect(try fixture.handle.accessEvidence() == before) + try setRestrictiveInheritedFileACL(fixture.root) + let filePolicy = try fixture.handle.accessEvidence() + #expect(throws: CoreError.self) { try fixture.handle.createPrivateFile("denied-file") } + // Some kernels create the empty inode before refusing the creating open. + // Without a returned descriptor, disposal belongs to the caller's recorded intent. + #expect(try fixture.handle.info("denied-file").map { $0.st_size == 0 } ?? true) + #expect(try fixture.handle.accessEvidence() == filePolicy) + } + + @Test func traversableAncestorsAndStickyOwnershipHaveDistinctReplacementRules() throws { + let fixture = try AccessFixture() + try #require(fchmod(fixture.handle.descriptor, 0o755) == 0) + _ = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: fixture.handle.descriptor, protectingOwner: geteuid()) + let file = try fixture.handle.createPrivateFile("payload") + try file.write(Data("private payload".utf8)) + try #require(fchmod(fixture.handle.descriptor, 0o777) == 0) + #expect(throws: CoreError.self) { + try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: fixture.handle.descriptor, protectingOwner: geteuid()) + } + try #require(fchmod(fixture.handle.descriptor, 0o1777) == 0) + _ = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: fixture.handle.descriptor, protectingOwner: geteuid()) + #expect(throws: CoreError.self) { + try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: fixture.handle.descriptor, protectingOwner: geteuid() + 1) + } + } + + @Test func namespaceEvidenceDetectsAncestorExchangeAndRefusesSymlinks() throws { + let fixture = try AccessFixture() + let ancestor = try fixture.handle.createPrivateDirectory("ancestor") + let before = try #require(try fixture.handle.accessEvidence("ancestor")) + try #require( + renameat(fixture.handle.descriptor, "ancestor", fixture.handle.descriptor, "old") == 0) + _ = try fixture.handle.createPrivateDirectory("ancestor") + #expect(try fixture.handle.accessEvidence("ancestor") != before) + // The old descriptor remains valid; callers must compare every namespace edge. + try before.validate(descriptor: ancestor.descriptor) + try fixture.handle.link("link", destination: "ancestor") + #expect(throws: CoreError.self) { try fixture.handle.accessEvidence("link") } + #expect(throws: CoreError.self) { try fixture.handle.createPrivateFile("link") } + #expect(throws: CoreError.self) { try fixture.handle.createPrivateFile("../escape") } + #expect(throws: CoreError.self) { try fixture.handle.createPrivateDirectory("nested/path") } + #expect(try fixture.handle.child("ancestor").names().isEmpty) + } +} + +private final class AccessFixture { + let root: URL + let handle: DirectoryHandle + + init() throws { + root = try temporaryDirectory() + do { + try #require(chmod(root.path, 0o700) == 0) + handle = try DirectoryHandle(at: root) + } catch { + removeTemporaryDirectory(root) + throw error + } + } + + deinit { + #if os(macOS) + do { try ProcessRunner.run("/bin/chmod", arguments: ["-RN", root.path]) } catch { + Issue.record(error) + } + #endif + chmod(root.path, 0o700) + removeTemporaryDirectory(root) + } +} + +private func grantRead(_ url: URL) throws { + #if os(macOS) + try addACL("everyone allow read", at: url) + #else + let file = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) + try #require(file >= 0) + defer { close(file) } + try installPOSIXACL(descriptor: file, owner: 6, named: 4, mask: 4, defaultACL: false) + #endif +} + +#if os(macOS) + private func addACL(_ entry: String, at url: URL) throws { + try ProcessRunner.run("/bin/chmod", arguments: ["+a", entry, url.path]) + } +#else + private func installPOSIXACL( + descriptor: Int32, owner: UInt16, named: UInt16, mask: UInt16, defaultACL: Bool + ) throws { + var bytes = Data([2, 0, 0, 0]) + let foreignOwner: UInt32 = geteuid() == 65_534 ? 65_533 : 65_534 + for (tag, permissions, identifier): (UInt16, UInt16, UInt32) in [ + (1, owner, .max), (2, named, foreignOwner), (4, 0, .max), + (16, mask, .max), (32, 0, .max), + ] { + for field in [UInt32(tag) | (UInt32(permissions) << 16), identifier] { + var value = field.littleEndian + withUnsafeBytes(of: &value) { bytes.append(contentsOf: $0) } + } + } + let name = defaultACL ? "system.posix_acl_default" : "system.posix_acl_access" + try #require( + bytes.withUnsafeBytes { fsetxattr(descriptor, name, $0.baseAddress, $0.count, 0) } == 0) + } +#endif From abeb960d7a405275d9e03fdbd37f7c38eb89d1af Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:49:55 +0800 Subject: [PATCH 046/171] fix(manifest): enforce compiled schema constraints --- Documentation/Reference/Manifest.md | 6 +- Documentation/Reference/ManifestSchema.md | 100 ++++---- Scripts/generate-manifest-schema.py | 237 ++++++++++++++---- Scripts/test_manifest_schema.py | 59 +++++ Sources/AgentsManifest/ManifestSchema.swift | 193 ++++++++------ Sources/AgentsManifest/YAMLValidation.swift | 67 +++-- Tests/AgentsManifestTests/FrontEndTests.swift | 32 +++ 7 files changed, 486 insertions(+), 208 deletions(-) create mode 100644 Scripts/test_manifest_schema.py diff --git a/Documentation/Reference/Manifest.md b/Documentation/Reference/Manifest.md index 3dea96f..7f1a05e 100644 --- a/Documentation/Reference/Manifest.md +++ b/Documentation/Reference/Manifest.md @@ -24,7 +24,11 @@ exports: [checks] The distributed [JSON schema](../../Sources/AgentsManifest/Resources/agents.schema.json) is the field-shape owner. [Generated field help](ManifestSchema.md) lists every -supported shape. Unknown fixed fields, decoded duplicate keys and invalid scalar +supported shape and its schema-owned collection bounds. The finite compiler +rejects unsupported validation keywords, values and combinations; its generated +rules enforce the accepted constraints. Parser and decoded-value safety budgets +apply independently of these field constraints. +Unknown fixed fields, decoded duplicate keys and invalid scalar kinds are errors. Domain validation also checks unused groups and inactive components. References remain symbolic until linking; declaration reads never resolve sources, access resources or execute component programs. diff --git a/Documentation/Reference/ManifestSchema.md b/Documentation/Reference/ManifestSchema.md index 000451d..56d421a 100644 --- a/Documentation/Reference/ManifestSchema.md +++ b/Documentation/Reference/ManifestSchema.md @@ -7,13 +7,13 @@ Generated from `Sources/AgentsManifest/Resources/agents.schema.json`. | Field | Required | Shape | | --- | --- | --- | | `version` | yes | `1` | -| `defaultAgents` | | sequence of agent | -| `sources` | | name → source | -| `components` | | sequence of component | -| `groups` | | name → group | -| `uses` | | sequence of use | -| `exports` | | sequence of string | -| `watch` | | sequence of string | +| `defaultAgents` | | sequence of agent (at most 10000 items) | +| `sources` | | name → source (at most 10000 properties) | +| `components` | | sequence of component (at most 10000 items) | +| `groups` | | name → group (at most 10000 properties) | +| `uses` | | sequence of use (at most 10000 items) | +| `exports` | | sequence of string (at most 10000 items) | +| `watch` | | sequence of string (at most 10000 items) | ## agent @@ -23,9 +23,9 @@ Generated from `Sources/AgentsManifest/Resources/agents.schema.json`. | Field | Required | Shape | | --- | --- | --- | -| `agents` | | sequence of agent | -| `scopes` | | sequence of `project` / `user` | -| `platforms` | | sequence of `macos` / `linux` | +| `agents` | | sequence of agent (at most 10000 items) | +| `scopes` | | sequence of `project` / `user` (at most 10000 items) | +| `platforms` | | sequence of `macos` / `linux` (at most 10000 items) | ## resource @@ -55,8 +55,8 @@ one of: string, mapping | Field | Required | Shape | | --- | --- | --- | | `executable` | yes | string | -| `arguments` | | sequence of string | -| `environment` | | name → binding | +| `arguments` | | sequence of string (at most 10000 items) | +| `environment` | | name → binding (at most 10000 properties) | | `workingDirectory` | | resource | ## transport @@ -91,7 +91,7 @@ one of: `read` / `write` / `execute`, mapping | Field | Required | Shape | | --- | --- | --- | -| `sections` | | sequence of section | +| `sections` | | sequence of section (at most 10000 items) | | `append` | | string | | `condition` | | condition | @@ -99,7 +99,7 @@ one of: `read` / `write` / `execute`, mapping | Field | Required | Shape | | --- | --- | --- | -| `agents` | | sequence of agent | +| `agents` | | sequence of agent (at most 10000 items) | | `mode` | | `link` / `copy` / `edit` | ## requirement @@ -122,34 +122,34 @@ one of: mapping, mapping, mapping | Field | Required | Shape | | --- | --- | --- | | `kind` | yes | `skills` | -| `agents` | | sequence of agent | +| `agents` | | sequence of agent (at most 10000 items) | | `condition` | | condition | -| `native` | | name → name → NativeValue | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | | `source` | yes | string | -| `select` | | one of: `all`, sequence of string | -| `exclude` | | sequence of string | +| `select` | | one of: `all`, sequence of string (at most 10000 items) | +| `exclude` | | sequence of string (at most 10000 items) | | `mode` | | `link` / `copy` / `edit` | -| `overrides` | | name → override | +| `overrides` | | name → override (at most 10000 properties) | ## component_instructions | Field | Required | Shape | | --- | --- | --- | | `kind` | yes | `instructions` | -| `agents` | | sequence of agent | +| `agents` | | sequence of agent (at most 10000 items) | | `condition` | | condition | -| `native` | | name → name → NativeValue | -| `sections` | | sequence of section | -| `chatgpt` | | name → promptDeclaration | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | +| `sections` | | sequence of section (at most 10000 items) | +| `chatgpt` | | name → promptDeclaration (at most 10000 properties) | ## component_mcpServer | Field | Required | Shape | | --- | --- | --- | | `kind` | yes | `mcpServer` | -| `agents` | | sequence of agent | +| `agents` | | sequence of agent (at most 10000 items) | | `condition` | | condition | -| `native` | | name → name → NativeValue | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | | `name` | yes | string | | `transport` | yes | transport | @@ -158,76 +158,76 @@ one of: mapping, mapping, mapping | Field | Required | Shape | | --- | --- | --- | | `kind` | yes | `hook` | -| `agents` | | sequence of agent | +| `agents` | | sequence of agent (at most 10000 items) | | `condition` | | condition | -| `native` | | name → name → NativeValue | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | | `name` | yes | string | | `event` | yes | event | | `run` | yes | run | | `matcher` | | string | -| `timeoutSeconds` | | integer | +| `timeoutSeconds` | | integer ≥ 1 | ## component_subagent | Field | Required | Shape | | --- | --- | --- | | `kind` | yes | `subagent` | -| `agents` | | sequence of agent | +| `agents` | | sequence of agent (at most 10000 items) | | `condition` | | condition | -| `native` | | name → name → NativeValue | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | | `name` | yes | string | | `description` | yes | string | | `prompt` | yes | prompt | | `model` | | string | -| `tools` | | sequence of string | +| `tools` | | sequence of string (at most 10000 items) | ## component_command | Field | Required | Shape | | --- | --- | --- | | `kind` | yes | `command` | -| `agents` | | sequence of agent | +| `agents` | | sequence of agent (at most 10000 items) | | `condition` | | condition | -| `native` | | name → name → NativeValue | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | | `name` | yes | string | | `description` | yes | string | | `prompt` | yes | prompt | -| `parameters` | | sequence of parameter | +| `parameters` | | sequence of parameter (at most 10000 items) | ## component_lspServer | Field | Required | Shape | | --- | --- | --- | | `kind` | yes | `lspServer` | -| `agents` | | sequence of agent | +| `agents` | | sequence of agent (at most 10000 items) | | `condition` | | condition | -| `native` | | name → name → NativeValue | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | | `name` | yes | string | | `run` | yes | run | -| `languages` | yes | name → string | -| `initializationOptions` | | name → NativeValue | +| `languages` | yes | name → string (at most 10000 properties) | +| `initializationOptions` | | name → NativeValue (at most 10000 properties) | ## component_permissions | Field | Required | Shape | | --- | --- | --- | | `kind` | yes | `permissions` | -| `agents` | | sequence of agent | +| `agents` | | sequence of agent (at most 10000 items) | | `condition` | | condition | -| `native` | | name → name → NativeValue | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | | `name` | yes | string | -| `rules` | yes | sequence of rule | +| `rules` | yes | sequence of rule (at most 10000 items) | ## component_ignore | Field | Required | Shape | | --- | --- | --- | | `kind` | yes | `ignore` | -| `agents` | | sequence of agent | +| `agents` | | sequence of agent (at most 10000 items) | | `condition` | | condition | -| `native` | | name → name → NativeValue | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | | `name` | yes | string | -| `patterns` | yes | sequence of string | +| `patterns` | yes | sequence of string (at most 10000 items) | | `purpose` | | `context` / `indexing` | ## component_plugin @@ -235,15 +235,15 @@ one of: mapping, mapping, mapping | Field | Required | Shape | | --- | --- | --- | | `kind` | yes | `plugin` | -| `agents` | | sequence of agent | +| `agents` | | sequence of agent (at most 10000 items) | | `condition` | | condition | -| `native` | | name → name → NativeValue | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | | `name` | yes | string | | `source` | yes | string | | `path` | yes | string | | `mode` | | `native` / `components` | -| `select` | | sequence of `skills` / `instructions` / `mcpServer` / `hook` / `subagent` / `command` / `lspServer` / `permissions` / `ignore` / `plugin` | -| `exclude` | | sequence of componentReference | +| `select` | | sequence of `skills` / `instructions` / `mcpServer` / `hook` / `subagent` / `command` / `lspServer` / `permissions` / `ignore` / `plugin` (at most 10000 items) | +| `exclude` | | sequence of componentReference (at most 10000 items) | ## component @@ -261,6 +261,6 @@ one of: component_skills, component_instructions, component_mcpServer, component | Field | Required | Shape | | --- | --- | --- | -| `components` | | sequence of component | -| `uses` | | sequence of use | +| `components` | | sequence of component (at most 10000 items) | +| `uses` | | sequence of use (at most 10000 items) | | `condition` | | condition | diff --git a/Scripts/generate-manifest-schema.py b/Scripts/generate-manifest-schema.py index 440b903..384733c 100644 --- a/Scripts/generate-manifest-schema.py +++ b/Scripts/generate-manifest-schema.py @@ -1,53 +1,190 @@ #!/usr/bin/env python3 """Compile the finite field shapes used by the shipped manifest schema.""" -import argparse,json,subprocess +import argparse +import json +import subprocess from pathlib import Path -root=Path(__file__).resolve().parent.parent -source=root/'Sources/AgentsManifest/Resources/agents.schema.json' -schema=json.loads(source.read_text()) -allowed={'$schema','$id','$defs','$ref','title','description','examples','type','properties','required','additionalProperties','items','enum','const','oneOf','minimum','maxItems','maxProperties','x-agents-scalar-kind','x-agents-native-value'} -def q(s):return json.dumps(s,ensure_ascii=False) -def emit(v): - unknown=set(v)-allowed - if unknown:raise ValueError('unsupported schema keywords: '+str(unknown)) - if '$ref' in v:return '.named('+q(v['$ref'].removeprefix('#/$defs/'))+')' - if v.get('x-agents-native-value'):return '.native' - if 'oneOf' in v:return '.oneOf(['+', '.join(emit(x) for x in v['oneOf'])+'])' - if 'const' in v:return '.constant('+q(str(v['const']))+')' if isinstance(v['const'],str) else '.version' - if 'enum' in v:return '.enumeration(['+', '.join(q(x) for x in v['enum'])+'])' - kind=v['type'] - if kind=='string':return '.string' - if kind=='integer':return '.integer(minimum: '+str(v.get('minimum',-9223372036854775808))+')' - if kind=='array':return '.array('+emit(v['items'])+')' - if kind=='object': - if isinstance(v['additionalProperties'],dict):return '.dictionary('+emit(v['additionalProperties'])+')' - props=', '.join(q(k)+': '+emit(x) for k,x in v.get('properties',{}).items()) - return '.object(['+props+'], required: ['+', '.join(q(x) for x in v.get('required',[]))+'])' - raise ValueError('unsupported field shape '+kind) -text='// Generated by Scripts/generate-manifest-schema.py.\n\nenum ManifestSchema {\n static let root: YAMLRule = '+emit(schema)+'\n static let definitions: [String: YAMLRule] = [\n' -text+=''.join(' '+q(k)+': '+emit(v)+',\n' for k,v in schema['$defs'].items())+' ]\n}\n' -text=subprocess.run(['xcrun','swift-format','format','--configuration',str(root/'.swift-format')],input=text,text=True,capture_output=True,check=True).stdout -path=root/'Sources/AgentsManifest/ManifestSchema.swift' -def describe(v): - if '$ref' in v:return v['$ref'].removeprefix('#/$defs/') - if v.get('x-agents-native-value'):return 'NativeValue' - if 'const' in v:return '`'+str(v['const'])+'`' - if 'enum' in v:return ' / '.join('`'+str(x)+'`' for x in v['enum']) - if 'oneOf' in v:return 'one of: '+', '.join(describe(x) for x in v['oneOf']) - if v.get('type')=='array':return 'sequence of '+describe(v['items']) - if v.get('type')=='object':return 'name → '+describe(v['additionalProperties']) if isinstance(v.get('additionalProperties'),dict) else 'mapping' - return v.get('type','value') -help='# Manifest Field Shapes\n\nGenerated from `Sources/AgentsManifest/Resources/agents.schema.json`.\n' -for name,definition in [('Declaration',schema)]+list(schema['$defs'].items()): - help+='\n## '+name+'\n\n' - if 'properties' in definition: - help+='| Field | Required | Shape |\n| --- | --- | --- |\n' - for key,value in definition['properties'].items():help+='| `'+key+'` | '+('yes' if key in definition.get('required',[]) else '')+' | '+describe(value)+' |\n' - else:help+=describe(definition)+'\n' -help_path=root/'Documentation/Reference/ManifestSchema.md' -p=argparse.ArgumentParser();p.add_argument('--check',action='store_true');args=p.parse_args() -if args.check: - if not path.exists() or path.read_text()!=text or not help_path.exists() or help_path.read_text()!=help:raise SystemExit('generated manifest schema/help is stale') -else: - path.write_text(text) - help_path.write_text(help) + +ROOT = Path(__file__).resolve().parent.parent +ANNOTATIONS = {'title', 'description', 'examples'} +INTEGER_MIN = -(2 ** 63) +INTEGER_MAX = 2 ** 63 - 1 + + +def q(value): + escapes = {'"': '\\"', '\\': '\\\\', '\n': '\\n', '\r': '\\r', '\t': '\\t'} + return '"' + ''.join(escapes.get(c, '\\u{' + format(ord(c), 'x') + '}' if ord(c) < 32 else c) + for c in value) + '"' + + +def integer(value, name, minimum=INTEGER_MIN): + if type(value) is not int or not minimum <= value <= INTEGER_MAX: + raise ValueError(f'{name} must be an integer in {minimum}...{INTEGER_MAX}') + return str(value) + + +def emit(value, definitions, *, root=False): + if not isinstance(value, dict): + raise ValueError('field shapes must be schema objects') + + def allow(keys): + accepted = set(keys) | ANNOTATIONS + if root: + accepted |= {'$schema', '$id', '$defs'} + unsupported = set(value) - accepted + if unsupported: + raise ValueError('unsupported schema keywords or combination: ' + ', '.join(sorted(unsupported))) + + for key in ('title', 'description', '$schema', '$id'): + if key in value and not isinstance(value[key], str): + raise ValueError(key + ' must be a string') + if 'examples' in value and not isinstance(value['examples'], list): + raise ValueError('examples must be an array') + if '$ref' in value: + allow({'$ref'}) + ref = value['$ref'] + if not isinstance(ref, str) or not ref.startswith('#/$defs/') or ref[8:] not in definitions: + raise ValueError('expected a reference to a bundled definition') + return '.named(' + q(ref[8:]) + ')' + if 'x-agents-native-value' in value: + allow({'x-agents-native-value'}) + if value['x-agents-native-value'] is not True: + raise ValueError('x-agents-native-value must be true') + return '.native' + if 'oneOf' in value: + allow({'oneOf'}) + choices = value['oneOf'] + if not isinstance(choices, list) or not choices: + raise ValueError('oneOf must contain field shapes') + return '.oneOf([' + ', '.join(emit(x, definitions) for x in choices) + '])' + if 'const' in value: + allow({'const', 'type', 'x-agents-scalar-kind'}) + literal = value['const'] + if isinstance(literal, str) and value.get('type', 'string') == 'string': + if 'x-agents-scalar-kind' in value: + raise ValueError('scalar-kind is supported only on integers') + return '.constant(' + q(literal) + ')' + if type(literal) is int and value.get('type') == 'integer': + if value.get('x-agents-scalar-kind', 'integer') != 'integer': + raise ValueError('unsupported scalar-kind') + return '.integerConstant(' + integer(literal, 'const') + ')' + raise ValueError('const supports strings and typed integers') + if 'enum' in value: + allow({'enum', 'type'}) + choices = value['enum'] + if (value.get('type', 'string') != 'string' or not isinstance(choices, list) + or not choices or any(not isinstance(x, str) for x in choices) + or len(set(choices)) != len(choices)): + raise ValueError('enum must contain unique strings') + return '.enumeration([' + ', '.join(q(x) for x in choices) + '])' + kind = value.get('type') + if kind == 'string': + allow({'type'}) + return '.string' + if kind == 'integer': + allow({'type', 'minimum', 'x-agents-scalar-kind'}) + if value.get('x-agents-scalar-kind', 'integer') != 'integer': + raise ValueError('unsupported scalar-kind') + return '.integer(minimum: ' + integer(value.get('minimum', INTEGER_MIN), 'minimum') + ')' + if kind == 'array': + allow({'type', 'items', 'maxItems'}) + if 'items' not in value: + raise ValueError('arrays require an item shape') + maximum = integer(value['maxItems'], 'maxItems', 0) if 'maxItems' in value else 'nil' + return '.array(' + emit(value['items'], definitions) + ', maximum: ' + maximum + ')' + if kind == 'object': + allow({'type', 'properties', 'required', 'additionalProperties', 'maxProperties'}) + maximum = integer(value['maxProperties'], 'maxProperties', 0) if 'maxProperties' in value else 'nil' + additional = value.get('additionalProperties') + if isinstance(additional, dict): + if 'properties' in value or 'required' in value: + raise ValueError('dictionary shapes cannot also declare fixed fields or required keys') + return '.dictionary(' + emit(additional, definitions) + ', maximum: ' + maximum + ')' + if additional is not False: + raise ValueError('objects require false or a field shape for additionalProperties') + properties = value.get('properties', {}) + required = value.get('required', []) + if not isinstance(properties, dict) or any(not isinstance(x, str) for x in properties): + raise ValueError('properties must map field names to shapes') + if (not isinstance(required, list) or any(not isinstance(x, str) for x in required) + or len(set(required)) != len(required) or not set(required) <= set(properties)): + raise ValueError('required must contain unique declared field names') + fields = ', '.join(q(k) + ': ' + emit(v, definitions) for k, v in properties.items()) + return ('.object([' + (fields or ':') + '], required: [' + ', '.join(q(x) for x in required) + + '], maximum: ' + maximum + ')') + raise ValueError('unsupported field shape: ' + str(kind)) + + +def describe(value): + if '$ref' in value: + return value['$ref'].removeprefix('#/$defs/') + if 'x-agents-native-value' in value: + return 'NativeValue' + if 'const' in value: + return '`' + str(value['const']) + '`' + if 'enum' in value: + return ' / '.join('`' + str(x) + '`' for x in value['enum']) + if 'oneOf' in value: + return 'one of: ' + ', '.join(describe(x) for x in value['oneOf']) + kind = value['type'] + if kind == 'array': + shape = 'sequence of ' + describe(value['items']) + return shape + (f" (at most {value['maxItems']} items)" if 'maxItems' in value else '') + if kind == 'object': + shape = ('name → ' + describe(value['additionalProperties']) + if isinstance(value['additionalProperties'], dict) else 'mapping') + return shape + (f" (at most {value['maxProperties']} properties)" if 'maxProperties' in value else '') + if kind == 'integer' and 'minimum' in value: + return 'integer ≥ ' + str(value['minimum']) + return kind + + +def compile_schema(schema): + if not isinstance(schema, dict) or not isinstance(schema.get('$defs'), dict): + raise ValueError('the bundled schema requires named definitions') + if schema.get('$schema', 'https://json-schema.org/draft/2020-12/schema') != 'https://json-schema.org/draft/2020-12/schema': + raise ValueError('the bundled schema uses the 2020-12 dialect') + definitions = schema['$defs'] + if any(not isinstance(name, str) or not name or '/' in name or '~' in name for name in definitions): + raise ValueError('definition names must be nonempty, unescaped pointer segments') + text = ('// Generated by Scripts/generate-manifest-schema.py.\n\nenum ManifestSchema {\n' + + ' static let root: YAMLRule = ' + emit(schema, definitions, root=True) + + '\n static let definitions: [String: YAMLRule] = [\n') + text += ''.join(' ' + q(k) + ': ' + emit(v, definitions) + ',\n' for k, v in definitions.items()) + text += ' ]\n}\n' + help_text = ('# Manifest Field Shapes\n\n' + 'Generated from `Sources/AgentsManifest/Resources/agents.schema.json`.\n') + for name, definition in [('Declaration', schema)] + list(definitions.items()): + help_text += '\n## ' + name + '\n\n' + if 'properties' in definition: + if 'maxProperties' in definition: + help_text += describe(definition) + '\n\n' + help_text += '| Field | Required | Shape |\n| --- | --- | --- |\n' + for key, value in definition['properties'].items(): + help_text += ('| `' + key + '` | ' + ('yes' if key in definition.get('required', []) else '') + + ' | ' + describe(value) + ' |\n') + else: + help_text += describe(definition) + '\n' + return text, help_text + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--check', action='store_true') + args = parser.parse_args() + schema = json.loads((ROOT / 'Sources/AgentsManifest/Resources/agents.schema.json').read_text()) + text, help_text = compile_schema(schema) + text = subprocess.run(['xcrun', 'swift-format', 'format', '--configuration', str(ROOT / '.swift-format')], + input=text, text=True, capture_output=True, check=True).stdout + outputs = {ROOT / 'Sources/AgentsManifest/ManifestSchema.swift': text, + ROOT / 'Documentation/Reference/ManifestSchema.md': help_text} + for path, contents in outputs.items(): + if args.check: + if not path.exists() or path.read_text() != contents: + raise SystemExit('generated manifest schema/help is stale: ' + str(path)) + else: + path.write_text(contents) + + +if __name__ == '__main__': + main() diff --git a/Scripts/test_manifest_schema.py b/Scripts/test_manifest_schema.py new file mode 100644 index 0000000..82c7a3b --- /dev/null +++ b/Scripts/test_manifest_schema.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Guard the bundled schema compiler's accepted validation semantics.""" +import importlib.util +import unittest +from pathlib import Path + +spec = importlib.util.spec_from_file_location('manifest_schema', Path(__file__).with_name('generate-manifest-schema.py')) +compiler = importlib.util.module_from_spec(spec) +spec.loader.exec_module(compiler) + + +class SchemaCompilerTests(unittest.TestCase): + def test_schema_values_drive_runtime_constraints_and_help(self): + schema = { + 'type': 'object', 'additionalProperties': False, '$defs': {}, + 'properties': { + 'version': {'type': 'integer', 'const': 2}, + 'items': {'type': 'array', 'items': {'type': 'string'}, 'maxItems': 3}, + 'names': {'type': 'object', 'additionalProperties': {'type': 'string'}, 'maxProperties': 4}, + 'record': {'type': 'object', 'additionalProperties': False, 'maxProperties': 0}, + 'count': {'type': 'integer', 'minimum': 5}, + }, + } + swift, help_text = compiler.compile_schema(schema) + for expected in ['.integerConstant(2)', '.array(.string, maximum: 3)', + '.dictionary(.string, maximum: 4)', '.object([:], required: [], maximum: 0)', + '.integer(minimum: 5)']: + self.assertIn(expected, swift) + for expected in ['`2`', 'at most 3 items', 'at most 4 properties', 'at most 0 properties', 'integer ≥ 5']: + self.assertIn(expected, help_text) + + def test_validation_siblings_are_not_discarded(self): + for shape in [{'$ref': '#/$defs/string'}, {'oneOf': [{'type': 'string'}]}, + {'x-agents-native-value': True}, {'const': 'a'}, {'enum': ['a']}]: + with self.subTest(shape=shape), self.assertRaises(ValueError): + compiler.emit({**shape, 'maxItems': 1}, {'string': {'type': 'string'}}) + for shape in [{'type': 'string', 'minimum': 1}, {'type': 'array', 'items': {'type': 'string'}, 'maxProperties': 1}, + {'type': 'object', 'additionalProperties': {'type': 'string'}, 'properties': {}}]: + with self.subTest(shape=shape), self.assertRaises(ValueError): + compiler.emit(shape, {}) + + def test_unsupported_values_are_rejected(self): + for shape in [{'const': True}, {'const': 2.5}, {'type': 'integer', 'const': 2 ** 63}, + {'const': 'a', 'type': 'integer'}, {'enum': [1]}, {'enum': []}, + {'type': 'object', 'additionalProperties': True}, {'type': 'object'}, + {'x-agents-native-value': False}, {'oneOf': []}, {'$ref': 'external'}, + {'$ref': '#/$defs/missing'}, {'type': 'integer', 'x-agents-scalar-kind': 'float'}, + {'type': 'object', 'additionalProperties': False, 'required': ['absent']}]: + with self.subTest(shape=shape), self.assertRaises(ValueError): + compiler.emit(shape, {}) + for maximum in [-1, True, 1.5, 2 ** 63]: + for shape in [{'type': 'array', 'items': {'type': 'string'}, 'maxItems': maximum}, + {'type': 'object', 'additionalProperties': False, 'maxProperties': maximum}]: + with self.subTest(shape=shape), self.assertRaises(ValueError): + compiler.emit(shape, {}) + + +if __name__ == '__main__': + unittest.main() diff --git a/Sources/AgentsManifest/ManifestSchema.swift b/Sources/AgentsManifest/ManifestSchema.swift index fda91cc..99e2cec 100644 --- a/Sources/AgentsManifest/ManifestSchema.swift +++ b/Sources/AgentsManifest/ManifestSchema.swift @@ -3,79 +3,94 @@ enum ManifestSchema { static let root: YAMLRule = .object( [ - "version": .version, "defaultAgents": .array(.named("agent")), - "sources": .dictionary(.named("source")), "components": .array(.named("component")), - "groups": .dictionary(.named("group")), "uses": .array(.named("use")), - "exports": .array(.string), "watch": .array(.string), - ], required: ["version"]) + "version": .integerConstant(1), "defaultAgents": .array(.named("agent"), maximum: 10000), + "sources": .dictionary(.named("source"), maximum: 10000), + "components": .array(.named("component"), maximum: 10000), + "groups": .dictionary(.named("group"), maximum: 10000), + "uses": .array(.named("use"), maximum: 10000), "exports": .array(.string, maximum: 10000), + "watch": .array(.string, maximum: 10000), + ], required: ["version"], maximum: nil) static let definitions: [String: YAMLRule] = [ "agent": .enumeration(["codex", "claude-code", "cursor", "gemini-cli", "opencode"]), "condition": .object( [ - "agents": .array(.named("agent")), "scopes": .array(.enumeration(["project", "user"])), - "platforms": .array(.enumeration(["macos", "linux"])), - ], required: []), - "resource": .object(["path": .string, "source": .string], required: ["path"]), + "agents": .array(.named("agent"), maximum: 10000), + "scopes": .array(.enumeration(["project", "user"]), maximum: 10000), + "platforms": .array(.enumeration(["macos", "linux"]), maximum: 10000), + ], required: [], maximum: nil), + "resource": .object(["path": .string, "source": .string], required: ["path"], maximum: nil), "section": .object( - ["name": .string, "source": .string, "condition": .named("condition")], required: ["name"]), + ["name": .string, "source": .string, "condition": .named("condition")], required: ["name"], + maximum: nil), "binding": .oneOf([ - .string, .object(["env": .string], required: ["env"]), - .object(["secret": .string], required: ["secret"]), + .string, .object(["env": .string], required: ["env"], maximum: nil), + .object(["secret": .string], required: ["secret"], maximum: nil), + ]), + "prompt": .oneOf([ + .string, .object(["file": .named("resource")], required: ["file"], maximum: nil), ]), - "prompt": .oneOf([.string, .object(["file": .named("resource")], required: ["file"])]), "run": .object( [ - "executable": .string, "arguments": .array(.string), - "environment": .dictionary(.named("binding")), "workingDirectory": .named("resource"), - ], required: ["executable"]), + "executable": .string, "arguments": .array(.string, maximum: 10000), + "environment": .dictionary(.named("binding"), maximum: 10000), + "workingDirectory": .named("resource"), + ], required: ["executable"], maximum: nil), "transport": .oneOf([ .object( [ - "kind": .constant("stdio"), "executable": .string, "arguments": .array(.string), - "environment": .dictionary(.named("binding")), "workingDirectory": .named("resource"), - ], required: ["kind", "executable"]), + "kind": .constant("stdio"), "executable": .string, + "arguments": .array(.string, maximum: 10000), + "environment": .dictionary(.named("binding"), maximum: 10000), + "workingDirectory": .named("resource"), + ], required: ["kind", "executable"], maximum: nil), .object( [ "kind": .enumeration(["streamableHTTP", "sse"]), "url": .string, - "headers": .dictionary(.named("binding")), - ], required: ["kind", "url"]), + "headers": .dictionary(.named("binding"), maximum: 10000), + ], required: ["kind", "url"], maximum: nil), ]), "event": .oneOf([ .enumeration(["beforeTool", "afterTool", "sessionStart", "sessionEnd"]), - .object(["native": .string], required: ["native"]), + .object(["native": .string], required: ["native"], maximum: nil), ]), "operation": .oneOf([ - .enumeration(["read", "write", "execute"]), .object(["tool": .string], required: ["tool"]), + .enumeration(["read", "write", "execute"]), + .object(["tool": .string], required: ["tool"], maximum: nil), ]), "rule": .object( [ "effect": .enumeration(["allow", "ask", "deny"]), "operation": .named("operation"), "pattern": .string, - ], required: ["effect", "operation", "pattern"]), + ], required: ["effect", "operation", "pattern"], maximum: nil), "parameter": .object( ["name": .string, "description": .string, "defaultValue": .string], - required: ["name", "description"]), + required: ["name", "description"], maximum: nil), "promptDeclaration": .object( - ["sections": .array(.named("section")), "append": .string, "condition": .named("condition")], - required: []), + [ + "sections": .array(.named("section"), maximum: 10000), "append": .string, + "condition": .named("condition"), + ], required: [], maximum: nil), "override": .object( - ["agents": .array(.named("agent")), "mode": .enumeration(["link", "copy", "edit"])], - required: []), + [ + "agents": .array(.named("agent"), maximum: 10000), + "mode": .enumeration(["link", "copy", "edit"]), + ], required: [], maximum: nil), "requirement": .oneOf([ - .object(["branch": .string], required: ["branch"]), - .object(["revision": .string], required: ["revision"]), - .object(["exact": .string], required: ["exact"]), - .object(["from": .string], required: ["from"]), - .object(["upToNextMinor": .string], required: ["upToNextMinor"]), - .object(["from": .string, "to": .string], required: ["from", "to"]), + .object(["branch": .string], required: ["branch"], maximum: nil), + .object(["revision": .string], required: ["revision"], maximum: nil), + .object(["exact": .string], required: ["exact"], maximum: nil), + .object(["from": .string], required: ["from"], maximum: nil), + .object(["upToNextMinor": .string], required: ["upToNextMinor"], maximum: nil), + .object(["from": .string, "to": .string], required: ["from", "to"], maximum: nil), ]), "source": .oneOf([ .object( ["url": .string, "subpath": .string, "requirement": .named("requirement")], - required: ["url"]), + required: ["url"], maximum: nil), .object( ["path": .string, "subpath": .string, "requirement": .named("requirement")], - required: ["path"]), .object(["index": .string, "subpath": .string], required: ["index"]), + required: ["path"], maximum: nil), + .object(["index": .string, "subpath": .string], required: ["index"], maximum: nil), ]), "componentReference": .object( [ @@ -83,80 +98,91 @@ enum ManifestSchema { "skill", "instruction", "mcpServer", "hook", "subagent", "command", "lspServer", "permissions", "ignore", "plugin", ]), "name": .string, - ], required: ["kind", "name"]), + ], required: ["kind", "name"], maximum: nil), "component_skills": .object( [ - "kind": .constant("skills"), "agents": .array(.named("agent")), - "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), - "source": .string, "select": .oneOf([.constant("all"), .array(.string)]), - "exclude": .array(.string), "mode": .enumeration(["link", "copy", "edit"]), - "overrides": .dictionary(.named("override")), - ], required: ["kind", "source"]), + "kind": .constant("skills"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), + "source": .string, "select": .oneOf([.constant("all"), .array(.string, maximum: 10000)]), + "exclude": .array(.string, maximum: 10000), "mode": .enumeration(["link", "copy", "edit"]), + "overrides": .dictionary(.named("override"), maximum: 10000), + ], required: ["kind", "source"], maximum: nil), "component_instructions": .object( [ - "kind": .constant("instructions"), "agents": .array(.named("agent")), - "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), - "sections": .array(.named("section")), "chatgpt": .dictionary(.named("promptDeclaration")), - ], required: ["kind"]), + "kind": .constant("instructions"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), + "sections": .array(.named("section"), maximum: 10000), + "chatgpt": .dictionary(.named("promptDeclaration"), maximum: 10000), + ], required: ["kind"], maximum: nil), "component_mcpServer": .object( [ - "kind": .constant("mcpServer"), "agents": .array(.named("agent")), - "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), + "kind": .constant("mcpServer"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), "name": .string, "transport": .named("transport"), - ], required: ["kind", "name", "transport"]), + ], required: ["kind", "name", "transport"], maximum: nil), "component_hook": .object( [ - "kind": .constant("hook"), "agents": .array(.named("agent")), - "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), + "kind": .constant("hook"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), "name": .string, "event": .named("event"), "run": .named("run"), "matcher": .string, "timeoutSeconds": .integer(minimum: 1), - ], required: ["kind", "name", "event", "run"]), + ], required: ["kind", "name", "event", "run"], maximum: nil), "component_subagent": .object( [ - "kind": .constant("subagent"), "agents": .array(.named("agent")), - "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), + "kind": .constant("subagent"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), "name": .string, "description": .string, "prompt": .named("prompt"), "model": .string, - "tools": .array(.string), - ], required: ["kind", "name", "description", "prompt"]), + "tools": .array(.string, maximum: 10000), + ], required: ["kind", "name", "description", "prompt"], maximum: nil), "component_command": .object( [ - "kind": .constant("command"), "agents": .array(.named("agent")), - "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), + "kind": .constant("command"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), "name": .string, "description": .string, "prompt": .named("prompt"), - "parameters": .array(.named("parameter")), - ], required: ["kind", "name", "description", "prompt"]), + "parameters": .array(.named("parameter"), maximum: 10000), + ], required: ["kind", "name", "description", "prompt"], maximum: nil), "component_lspServer": .object( [ - "kind": .constant("lspServer"), "agents": .array(.named("agent")), - "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), - "name": .string, "run": .named("run"), "languages": .dictionary(.string), - "initializationOptions": .dictionary(.native), - ], required: ["kind", "name", "run", "languages"]), + "kind": .constant("lspServer"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), + "name": .string, "run": .named("run"), "languages": .dictionary(.string, maximum: 10000), + "initializationOptions": .dictionary(.native, maximum: 10000), + ], required: ["kind", "name", "run", "languages"], maximum: nil), "component_permissions": .object( [ - "kind": .constant("permissions"), "agents": .array(.named("agent")), - "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), - "name": .string, "rules": .array(.named("rule")), - ], required: ["kind", "name", "rules"]), + "kind": .constant("permissions"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), + "name": .string, "rules": .array(.named("rule"), maximum: 10000), + ], required: ["kind", "name", "rules"], maximum: nil), "component_ignore": .object( [ - "kind": .constant("ignore"), "agents": .array(.named("agent")), - "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), - "name": .string, "patterns": .array(.string), + "kind": .constant("ignore"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), + "name": .string, "patterns": .array(.string, maximum: 10000), "purpose": .enumeration(["context", "indexing"]), - ], required: ["kind", "name", "patterns"]), + ], required: ["kind", "name", "patterns"], maximum: nil), "component_plugin": .object( [ - "kind": .constant("plugin"), "agents": .array(.named("agent")), - "condition": .named("condition"), "native": .dictionary(.dictionary(.native)), + "kind": .constant("plugin"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), "name": .string, "source": .string, "path": .string, "mode": .enumeration(["native", "components"]), "select": .array( .enumeration([ "skills", "instructions", "mcpServer", "hook", "subagent", "command", "lspServer", "permissions", "ignore", "plugin", - ])), "exclude": .array(.named("componentReference")), - ], required: ["kind", "name", "source", "path"]), + ]), maximum: 10000), "exclude": .array(.named("componentReference"), maximum: 10000), + ], required: ["kind", "name", "source", "path"], maximum: nil), "component": .oneOf([ .named("component_skills"), .named("component_instructions"), .named("component_mcpServer"), .named("component_hook"), .named("component_subagent"), .named("component_command"), @@ -164,11 +190,12 @@ enum ManifestSchema { .named("component_plugin"), ]), "use": .object( - ["group": .string, "source": .string, "condition": .named("condition")], required: ["group"]), + ["group": .string, "source": .string, "condition": .named("condition")], required: ["group"], + maximum: nil), "group": .object( [ - "components": .array(.named("component")), "uses": .array(.named("use")), - "condition": .named("condition"), - ], required: []), + "components": .array(.named("component"), maximum: 10000), + "uses": .array(.named("use"), maximum: 10000), "condition": .named("condition"), + ], required: [], maximum: nil), ] } diff --git a/Sources/AgentsManifest/YAMLValidation.swift b/Sources/AgentsManifest/YAMLValidation.swift index ea73920..5e7778d 100644 --- a/Sources/AgentsManifest/YAMLValidation.swift +++ b/Sources/AgentsManifest/YAMLValidation.swift @@ -2,14 +2,15 @@ import AgentsCore /// The finite constraints compiled from the bundled declaration schema. No caller supplies rules. indirect enum YAMLRule: Sendable { - case string, native, version + case string, native case integer(minimum: Int) + case integerConstant(Int) case constant(String) case enumeration([String]) case named(String) - case array(YAMLRule) - case dictionary(YAMLRule) - case object([String: YAMLRule], required: [String]) + case array(YAMLRule, maximum: Int?) + case dictionary(YAMLRule, maximum: Int?) + case object([String: YAMLRule], required: [String], maximum: Int?) case oneOf([YAMLRule]) } @@ -60,7 +61,7 @@ final class YAMLValidation { } } - private func check(_ node: YAMLNode, _ rule: YAMLRule) throws { + func check(_ node: YAMLNode, _ rule: YAMLRule) throws { try spend(node) func fail(_ message: String) -> ManifestFailure { source.failure("manifest.schema", message, node.range.lowerBound, end: node.range.upperBound) @@ -80,24 +81,32 @@ final class YAMLValidation { guard try values.contains(string()) else { throw fail("expected one of \(values.joined(separator: ", "))") } - case .integer, .version: + case .integer, .integerConstant: guard case .scalar(let text, let quoted, let tag) = node.data, !quoted, !tag, YAMLScalar.classify(text) == .integer, let integer = YAMLScalar.integer(text) else { throw fail("expected a representable plain integer") } switch rule { - case .version: guard integer == 1 else { throw fail("unsupported manifest version") } + case .integerConstant(let expected): + guard integer == expected else { throw fail("expected integer \(expected)") } case .integer(let minimum): guard integer >= minimum else { throw fail("integer is below its minimum") } default: break } - case .array(let item): + case .array(let item, let maximum): guard let items = node.items else { throw fail("expected a sequence") } + if let maximum, items.count > maximum { throw fail("sequence exceeds maxItems: \(maximum)") } for node in items { try check(node, item) } - case .dictionary(let value): + case .dictionary(let value, let maximum): guard let pairs = node.pairs else { throw fail("expected a mapping") } + if let maximum, pairs.count > maximum { + throw fail("mapping exceeds maxProperties: \(maximum)") + } for pair in pairs { try check(pair.value, value) } - case .object(let fields, let required): + case .object(let fields, let required, let maximum): guard let pairs = node.pairs else { throw fail("expected a mapping") } + if let maximum, pairs.count > maximum { + throw fail("mapping exceeds maxProperties: \(maximum)") + } let present = Set(pairs.map { $0.key.text! }) for name in required where !present.contains(name) { throw fail("missing field: \(name)") } for pair in pairs { @@ -109,9 +118,11 @@ final class YAMLValidation { try check(pair.value, rule) } case .oneOf(let choices): - // Component and transport records have a literal discriminator in the generated schema. - // Select that branch before traversing descendants, rather than rescanning whole subtrees. + // Disjoint literal discriminators permit one traversal of component/transport subtrees. + // Other unions must count all matching branches to enforce oneOf. if let kind = node.pairs?.first(where: { $0.key.text == "kind" })?.value.text { + var discriminated: [String: YAMLRule] = [:] + var disjoint = true for candidate in choices { let resolved: YAMLRule if case .named(let name) = candidate { @@ -119,19 +130,27 @@ final class YAMLValidation { } else { resolved = candidate } - if case .object(let fields, _) = resolved, - let discriminator = fields["kind"] - { - switch discriminator { - case .constant(let value) where value == kind: - try check(node, candidate) - return - case .enumeration(let values) where values.contains(kind): - try check(node, candidate) - return - default: continue - } + guard case .object(let fields, let required, _) = resolved, + required.contains("kind"), let discriminator = fields["kind"] + else { + disjoint = false + break } + let values: [String] + switch discriminator { + case .constant(let value): values = [value] + case .enumeration(let options): values = options + default: + disjoint = false + values = [] + } + for value in values { + if discriminated.updateValue(candidate, forKey: value) != nil { disjoint = false } + } + } + if disjoint, let candidate = discriminated[kind] { + try check(node, candidate) + return } } var matches = 0 diff --git a/Tests/AgentsManifestTests/FrontEndTests.swift b/Tests/AgentsManifestTests/FrontEndTests.swift index b5457ef..ebb3fed 100644 --- a/Tests/AgentsManifestTests/FrontEndTests.swift +++ b/Tests/AgentsManifestTests/FrontEndTests.swift @@ -64,4 +64,36 @@ struct FrontEndTests { #expect(throws: ManifestFailure.self) { try document(body) } } } + + @Test func schemaBoundsAreIndependentOfParserSafetyLimits() throws { + for (rule, accepted, rejected) in [ + (YAMLRule.array(.string, maximum: 1), "[a]", "[a, b]"), + (.dictionary(.string, maximum: 1), "{a: x}", "{a: x, b: y}"), + (.object(["a": .string], required: [], maximum: 0), "{}", "{a: x}"), + (.integerConstant(2), "2", "1"), + ] { + try validate(accepted, against: rule) + expectManifestFailure("manifest.schema") { try validate(rejected, against: rule) } + } + for text in ["2.0", "'2'", "9223372036854775808"] { + expectManifestFailure("manifest.schema") { try validate(text, against: .integerConstant(2)) } + } + } + + @Test func oneOfRejectsOverlappingDiscriminatorsAndUnconstrainedBranches() throws { + let record = YAMLRule.object(["kind": .constant("a")], required: ["kind"], maximum: nil) + let optional = YAMLRule.object(["kind": .constant("a")], required: [], maximum: nil) + for choices in [[record, record], [record, optional]] { + expectManifestFailure("manifest.schema") { + try validate("{kind: a}", against: .oneOf(choices)) + } + } + try validate("{kind: a}", against: .oneOf([record, .string])) + } + + private func validate(_ text: String, against rule: YAMLRule) throws { + let source = SourceText(Array(text.utf8), identity: DocumentIdentity("schema-test")) + let node = try YAMLParser.parse(source).root + try YAMLValidation(source: source).check(node, rule) + } } From f3bcb87e3e6ffa1be936a13c0c3e37644b804860 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 04:30:38 +0800 Subject: [PATCH 047/171] fix(manifest): preserve valid YAML editing and diagnostics --- Sources/AgentsManifest/IRTree.swift | 3 +- Sources/AgentsManifest/SourceText.swift | 18 ++ Sources/AgentsManifest/YAMLParser.swift | 68 +++++++- Sources/AgentsManifest/YAMLPatches.swift | 74 +++++++-- Sources/AgentsManifest/YAMLProjection.swift | 1 + .../TargetLifecycleTests.swift | 19 +-- Tests/AgentsManifestTests/EditPlanTests.swift | 154 ++++++++++++++++++ Tests/AgentsManifestTests/FrontEndTests.swift | 39 +++++ 8 files changed, 345 insertions(+), 31 deletions(-) diff --git a/Sources/AgentsManifest/IRTree.swift b/Sources/AgentsManifest/IRTree.swift index e2d8d1e..6e7dd71 100644 --- a/Sources/AgentsManifest/IRTree.swift +++ b/Sources/AgentsManifest/IRTree.swift @@ -27,7 +27,8 @@ enum IRTree { groups: records("groups"), uses: records("uses"), watch: strings("watch")) } static func segments(_ pointer: String) -> [String] { - pointer.split(separator: "/", omittingEmptySubsequences: true).map { + guard !pointer.isEmpty else { return [] } + return pointer.dropFirst().split(separator: "/", omittingEmptySubsequences: false).map { pointerUnescape(String($0)) } } diff --git a/Sources/AgentsManifest/SourceText.swift b/Sources/AgentsManifest/SourceText.swift index c1d085e..7462d68 100644 --- a/Sources/AgentsManifest/SourceText.swift +++ b/Sources/AgentsManifest/SourceText.swift @@ -42,6 +42,24 @@ struct SourceText: Sendable { ManifestDiagnostic(code: code, message: message, span: span(offset..<(end ?? offset)))) } + /// Decoder columns count Unicode scalars, excluding a stream-initial UTF-8 BOM. + /// Source spans retain the original bytes and count CRLF as one line break. + func decoderOffset(line: Int, scalarColumn: Int) -> Int { + guard line > 0, scalarColumn > 0 else { return 0 } + guard line <= lines.count else { return bytes.count } + var offset = lines[line - 1] + if line == 1, bytes.starts(with: [0xEF, 0xBB, 0xBF]) { offset = 3 } + var column = 1 + while offset < bytes.count, bytes[offset] != 10, bytes[offset] != 13, + column < scalarColumn + { + offset += 1 + while offset < bytes.count, bytes[offset] & 0xC0 == 0x80 { offset += 1 } + column += 1 + } + return offset + } + func spelling(_ range: Range) -> String { String(decoding: bytes[range], as: UTF8.self) } diff --git a/Sources/AgentsManifest/YAMLParser.swift b/Sources/AgentsManifest/YAMLParser.swift index 6cc9757..84cfcd0 100644 --- a/Sources/AgentsManifest/YAMLParser.swift +++ b/Sources/AgentsManifest/YAMLParser.swift @@ -82,7 +82,7 @@ enum YAMLParser { guard let text = String(bytes: source.bytes, encoding: .utf8) else { throw source.failure("manifest.encoding", "expected UTF-8", 0) } - var offset = 0 + var offset = source.bytes.count - text.utf8.count for scalar in text.unicodeScalars { let value = scalar.value if value == 0 || value == 0x85 || value == 0x2028 || value == 0x2029 @@ -204,7 +204,9 @@ enum YAMLParser { throw source.failure("manifest.schema", "expected a declaration mapping", 0) } decoded = value - } catch let failure as ManifestFailure { throw failure } catch { + } catch let failure as ManifestFailure { throw failure } catch let error as Yams.YamlError { + throw decodingFailure(error, source: source, text: text) + } catch { throw source.failure("manifest.syntax", "YAML decoding failed: \(error)", 0) } let value = try pair(root, decoded, source: source) @@ -218,6 +220,37 @@ enum YAMLParser { } } + private static func decodingFailure(_ error: Yams.YamlError, source: SourceText, text: String) + -> ManifestFailure + { + switch error { + case .scanner(_, let problem, let mark, _), .parser(_, let problem, let mark, _), + .composer(_, let problem, let mark, _): + return source.failure( + "manifest.syntax", "YAML decoding failed: \(problem)", + source.decoderOffset(line: mark.line, scalarColumn: mark.column)) + case .duplicatedKeysInMapping(let duplicates, let context): + // Yams supplies one key's mark, not the positions of every conflicting occurrence. + return source.failure( + "manifest.key.duplicate", + "duplicate decoded mapping key(s): \(duplicates.joined(separator: ", "))", + source.decoderOffset(line: context.mark.line, scalarColumn: context.mark.column)) + case .reader(let problem, let offset, _, _): + let index = offset.flatMap { offset in + offset >= 0 ? text.index(text.startIndex, offsetBy: offset, limitedBy: text.endIndex) : nil + } + // UTF-8 String decoding consumes a leading BOM; reader offsets index that decoded string. + let byteOffset = + index.map { + source.bytes.count - text.utf8.count + + text.utf8.distance(from: text.utf8.startIndex, to: $0) + } ?? 0 + return source.failure("manifest.syntax", "YAML decoding failed: \(problem)", byteOffset) + default: + return source.failure("manifest.syntax", "YAML decoding failed: \(error)", 0) + } + } + private static func seconds(_ duration: Duration) -> Double { let parts = duration.components return Double(parts.seconds) + Double(parts.attoseconds) / 1e18 @@ -267,9 +300,9 @@ enum YAMLParser { for (syntaxPair, semanticPair) in zip(syntaxPairs, mapping) { let key = field(syntaxPair, "key") let value = field(syntaxPair, "value") - guard !ts_node_is_null(key), !ts_node_is_null(value) else { + guard !ts_node_is_null(key) else { throw source.failure( - "manifest.schema", "mapping entries require explicit keys and values", + "manifest.schema", "mapping entries require explicit keys", Int(ts_node_start_byte(syntaxPair))) } let keyNode = try pair(key, semanticPair.key, source: source) @@ -284,7 +317,12 @@ enum YAMLParser { "manifest.key.duplicate", "duplicate decoded mapping key: \(name)", keyNode.range.lowerBound) } - let node = try pair(value, semanticPair.value, source: source) + let node: YAMLNode + if ts_node_is_null(value) { + node = try emptyScalar(syntaxPair, semanticPair.value, source: source) + } else { + node = try pair(value, semanticPair.value, source: source) + } pairs.append( ( keyNode, @@ -305,6 +343,9 @@ enum YAMLParser { data: .sequence(try zip(children, sequence).map { try pair($0, $1, source: source) }), range: range, entryRange: range, flow: kind == "flow_sequence") } + if kind == "block_sequence_item", content.isEmpty { + return try emptyScalar(syntax, semantic, source: source) + } if let scalar = semantic.scalar, ["plain_scalar", "single_quote_scalar", "double_quote_scalar", "block_scalar"].contains(kind) { @@ -316,6 +357,23 @@ enum YAMLParser { "manifest.parser.mismatch", "YAML parsers disagree on structure", range.lowerBound) } + private static func emptyScalar(_ syntax: TSNode, _ semantic: Yams.Node, source: SourceText) + throws -> YAMLNode + { + guard semantic.scalar?.string == "", + let delimiter = (0.. TSNode { name.withCString { ts_node_child_by_field_name(node, $0, UInt32(name.utf8.count)) } } diff --git a/Sources/AgentsManifest/YAMLPatches.swift b/Sources/AgentsManifest/YAMLPatches.swift index 66c332b..60c2dec 100644 --- a/Sources/AgentsManifest/YAMLPatches.swift +++ b/Sources/AgentsManifest/YAMLPatches.swift @@ -102,7 +102,7 @@ struct YAMLPatches { } let node = document.locations[pointer]! if value == nil || value == .null { - guard let container = document.locations[parent], + guard let container = mapping(at: parent), let pair = container.pairs?.first(where: { $0.key.text == yamlKey(key, parent: parent) }) else { throw readOnly(pointer, "value has no removable mapping entry") @@ -168,13 +168,18 @@ struct YAMLPatches { { rendered += newline } + if node.range.isEmpty, node.range.lowerBound > 0, + [UInt8(ascii: ":"), UInt8(ascii: "-")].contains(bytes[node.range.lowerBound - 1]) + { + rendered = " " + rendered + } return [SourcePatch(range: node.range, replacement: Array(rendered.utf8))] } private func addField(_ parent: String, _ key: String, _ value: DeclarationValue) throws -> [SourcePatch] { - guard let container = document.locations[parent] else { + guard let container = mapping(at: parent) else { throw readOnly(parent, "missing owning mapping") } if document.defaulted.contains(parent) { @@ -194,19 +199,15 @@ struct YAMLPatches { replacement: Array(("{" + source.spelling(container.range) + ", " + text + "}").utf8)) ] } - let end = container.range.upperBound - 1 - return [ - SourcePatch(range: end.. 0 && bytes[end - 1] != 10 ? newline : "" return [ - SourcePatch(range: end.. YAMLNode? { + guard let node = document.locations[pointer] else { return nil } + if IRTree.value(IRTree.root(document.declaration), at: pointer)?.record?.kind == "file" { + return node.pairs?.first(where: { $0.key.text == "file" })?.value + } + return node + } + + private func blockEntry(_ text: String, at offset: Int) -> [UInt8] { + let prefix = offset > 0 && bytes[offset - 1] != 10 ? newline : "" + let suffix = offset == bytes.count && bytes.last != 10 ? "" : newline + return Array((prefix + text + suffix).utf8) + } + + private func appendFlow(_ text: String, to container: YAMLNode) -> [SourcePatch] { + let last = container.items?.last ?? container.pairs?.last?.value + let start = last?.entryRange.upperBound ?? container.range.lowerBound + 1 + let end = container.range.upperBound - 1 + if start == end { + return [ + SourcePatch(range: end..= start && comment.lowerBound < end { + if bytes[cursor.. [SourcePatch] { guard let container = document.locations[pointer] else { diff --git a/Sources/AgentsManifest/YAMLProjection.swift b/Sources/AgentsManifest/YAMLProjection.swift index 9bd0af8..9d71c13 100644 --- a/Sources/AgentsManifest/YAMLProjection.swift +++ b/Sources/AgentsManifest/YAMLProjection.swift @@ -277,6 +277,7 @@ final class YAMLProjection { return .record(DeclarationRecord(kind: "literal", fields: ["value": .string(text)])) } let resource = try record(fields(node)["file"]!, at: pointer, role: "resource") + try mark(node, pointer) try mark(node.pairs!.first!.key, pointer + "/kind") return .record(DeclarationRecord(kind: "file", fields: resource.fields)) } diff --git a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift index caa60f2..0f00d9e 100644 --- a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift @@ -65,22 +65,19 @@ struct TargetLifecycleTests { try fixture.addOwn(names: ["guide"], agents: [.codex]) let declarationFile = fixture.store().declarationURL let lockFile = fixture.store().resolvedURL - #expect( - String(decoding: try Data(contentsOf: declarationFile), as: UTF8.self) == """ - version: 1 - components: [{"kind": "instructions", "sections": [{"name": "guide"}], "agents": ["codex"]}] - """) - let lockText = String(decoding: try Data(contentsOf: lockFile), as: UTF8.self) - #expect(lockText.contains("\"chatgpt\": {}") && lockText.contains("\"skills\": {}")) - #expect(!lockText.contains(" : ")) - // The same intent in another layout, with a comment, is not rewritten. let declaration = Data( """ + # Project-owned layout. version: 1 - components: [{"kind": "instructions", "sections": [{"name": "guide"}], "agents": ["codex"]}] + components: + - kind: instructions # Keep this guidance. + sections: + - {name: guide} + agents: [codex] """.utf8) try declaration.write(to: declarationFile) - let existingLockBytes = try StateStore.encode(fixture.store().loadResolved()) + var existingLockBytes = try Data(contentsOf: lockFile) + existingLockBytes.append(Data("\n \n".utf8)) try existingLockBytes.write(to: lockFile) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) #expect(try Data(contentsOf: declarationFile) == declaration) diff --git a/Tests/AgentsManifestTests/EditPlanTests.swift b/Tests/AgentsManifestTests/EditPlanTests.swift index 728b2dc..c7719be 100644 --- a/Tests/AgentsManifestTests/EditPlanTests.swift +++ b/Tests/AgentsManifestTests/EditPlanTests.swift @@ -159,3 +159,157 @@ extension EditPlanTests { .declaration == change.expectedDeclaration) } } + +extension EditPlanTests { + @Test func promptKindChangesOwnTheWrapperAndRetainResourceLocations() throws { + var text = + "version: 1\nsources: {s: {path: ./s}}\ncomponents: [{kind: subagent, name: a, description: d, prompt: {file: {path: p.md}}, model: keep}] # tail\n" + let original = try document(text) + let prompt = try #require(original.sourceMap.locations(at: "/components/0/prompt").first?.span) + let path = try #require( + original.sourceMap.locations(at: "/components/0/prompt/path").first?.span) + #expect( + String(decoding: original.bytes[prompt.start.. Date: Mon, 16 Nov 2026 04:49:54 +0800 Subject: [PATCH 048/171] fix: preserve implicit null separators in YAML edits --- Sources/AgentsManifest/YAMLPatches.swift | 7 ++- Tests/AgentsManifestTests/EditPlanTests.swift | 55 ++++++++++++++----- 2 files changed, 47 insertions(+), 15 deletions(-) diff --git a/Sources/AgentsManifest/YAMLPatches.swift b/Sources/AgentsManifest/YAMLPatches.swift index 60c2dec..3b40177 100644 --- a/Sources/AgentsManifest/YAMLPatches.swift +++ b/Sources/AgentsManifest/YAMLPatches.swift @@ -281,9 +281,12 @@ struct YAMLPatches { let last = container.items?.last ?? container.pairs?.last?.value let start = last?.entryRange.upperBound ?? container.range.lowerBound + 1 let end = container.range.upperBound - 1 + // An implicit value ends at its colon; a plain key still needs whitespace before the comma. + let separator = last?.range.isEmpty == true ? " ," : "," if start == end { return [ - SourcePatch(range: end.. Date: Mon, 16 Nov 2026 05:06:21 +0800 Subject: [PATCH 049/171] feat(core): preserve private materializations through state transactions --- Documentation/Architecture/State.md | 88 +++- Sources/AgentsCore/FileAccess.swift | 81 ++- Sources/AgentsCore/FileTransaction.swift | 129 ++++- .../AgentsCore/PrivateMaterialization.swift | 216 ++++++++ Sources/AgentsCore/StateStore.swift | 2 +- Sources/AgentsCore/TransactionDisposal.swift | 23 + Sources/AgentsCore/TransactionEvidence.swift | 58 +++ Sources/AgentsCore/TransactionJournal.swift | 4 +- .../AgentsCore/TransactionPublication.swift | 76 ++- Sources/AgentsCore/TransactionRecovery.swift | 5 + Sources/AgentsCore/TransactionSession.swift | 30 +- Sources/AgentsCore/UpdatePreconditions.swift | 31 +- .../PrivateMaterializationTests.swift | 486 ++++++++++++++++++ .../PrivateMaterializationProbe.swift | 31 ++ Tests/StateTestProcess/main.swift | 2 + 15 files changed, 1230 insertions(+), 32 deletions(-) create mode 100644 Sources/AgentsCore/PrivateMaterialization.swift create mode 100644 Tests/AgentsCoreTests/PrivateMaterializationTests.swift create mode 100644 Tests/StateTestProcess/PrivateMaterializationProbe.swift diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index 89083ab..380d439 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -315,7 +315,7 @@ the denial. Existing user content and metadata are preserved. ### Journal records -Journal format version 1 is independent of the manifest language, lock and watch +Journal format version 2 is independent of the manifest language, lock and watch versions. The root records its version, transaction UUID, scope identity, registered root identities, transaction phase, operations, private containers and disposal @@ -497,6 +497,92 @@ described below; the latter two require `import AgentsManifest`. returns the complete `DeclarationDocument`, or `nil` for a scope without state. Both can also throw the declaration's `ManifestFailure`. +### Private runtime materialization + +Package callers obtain a `MaterializationTarget` from `StateStore` and prepare it +with `preparePrivateMaterialization`. Core admits only its registered file paths; +source-authoring and arbitrary external paths are refused. Current registrations +cover existing instruction-file destinations. Native settings, provider routes +and cross-scope destinations require verified adapter registrations before use. + +Callers retain the existing scope read/writer lock and pending-recovery checks +around preparation. Preparation captures the target's physical identity, UID/GID, mode and ordered +ACL evidence, together with every existing physical ancestor. It does not call a +binding provider or renderer. A permissive existing file requires the caller's +explicit `changingAccess` intent, as does an existing owner-only mode that differs +from the intended 0600 (for example, owner execute). The prepared `accessChange` exposes its before +access and intended owner-only mode for the caller's report. This is part of the +prepared mutation, without a separate approval record. Missing ancestors may be +created by the transaction; their final identities and access are sealed before +staging. Existing ancestry, ACL, ownership or permission drift invalidates the +preparation. The prepared `accessFingerprint()` is a non-secret segment for the +complete displayed candidate fingerprint: it covers registered target, intended +owner, access/ancestry evidence, effective permission-change intent and local +receipt generation, and excludes binding values and materialized content digests. +It does not replace the enclosing candidate fingerprint or apply-handle lifecycle. + +`FileTransaction.replacePrivate` queues a cold renderer and explicitly injected +`RuntimeBindingProvider` using the store's runtime environment. Binding names are +data, never commands supplied by a source. The same scope lock and sole journal +cover ordinary targets, private targets, declaration/lock updates and the local +receipt. Ordinary requests preserve their existing metadata behavior. A private +replacement uses its own independently sealed access rather than copying the +live target's metadata. Core verifies its private construction directory and an +empty owner-readable/writable file before resolving bindings or writing payload +bytes. It rechecks access before writing and publication. Arbitrary path-based +prepared producers are not a private materialization interface. Provider and +renderer failures have fixed diagnostics; returned values have no encoding and +redacted diagnostic/reflection representations. + +The private `materializations.json` file in the scope directory stores only +registered target coordinates, materialization generation, registered-root +identity, materialized digest and access evidence. It contains no binding values, +source closure or declaration model. It is updated in the same transaction as +the target. A later ordinary replacement or deletion still classifies its old +materialized preimage as sensitive, then removes that target's receipt record +when the new ordinary generation commits. Direct caller writes to the receipt +are refused. Corrupt, permissive or stale receipts stop mutation rather than +silently downgrading a known sensitive object. `materializationReceipt(for:)` +returns only the local generation and access metadata. A caller that knows from +its prior symbolic deployment that an existing target was materialized must set +`requiringReceiptForExistingTarget`; a missing receipt then stops preparation. +`expecting:` also binds a known local receipt generation. These expectations stay +local; host materialization data does not enter the portable declaration or +ledger. A freshly observed absent target has no sensitive preimage and can be +restored or removed while its stale receipt record is reconciled atomically. + +Journal entries require preimage/replacement security classifications and the +necessary sealed access/ancestry evidence. Private container identity and access +are durable before payload construction. Missing security fields or older +journal versions require recovery with the writing version; there is no implicit +ordinary default or migration. Recovery consumes physical evidence only and +never invokes binding providers or renderers. Before restoring a sensitive +preimage, it verifies the destination ancestry, private container and preimage +access again, including after the restoration checkpoint. Unsafe or stale +access retains the journal and available private objects as a conflict. +Ordinary preimages keep their recorded metadata on rollback, including when a +private replacement had an explicit permission-change intent. Disposal validates +sensitive evidence before erasing retained objects. + +Linux assessment applies POSIX ACL masks to named and owning-group entries; +default ACLs are captured and inherited access is checked on the actual created +inode. macOS assessment preserves ACE order/inheritance, ignores inherit-only +ACEs for the current inode, and refuses active content/control grants or relevant +denials whose principal membership cannot be proved without directory-service +lookups. Unprovable layouts fail without repairing host permissions. Traversable +ordinary ancestors are allowed when trusted ownership and effective replacement +protection hold; sticky protection is bound to the child owner. Root and same-UID +adversaries are outside this boundary. Snapshot capture may retry a transient +stat/ACL generation race; retries never refresh prepared or sealed evidence. + +No cross-scope native route is registered by these primitives. Verified F routes +must supply their physical root/relative target derivation, native scope and +version, shared resource identity, owned region, actual readers/precedence, +private/reference alternatives and collision evidence before the corresponding +shared footprint, lock ordering and durable reservation can be integrated. These +local operations retain the ordinary scope writer lock and do not acquire a +global user lock. + ### Read-only access Non-applying skill and instruction operations, listings, previews, watch status diff --git a/Sources/AgentsCore/FileAccess.swift b/Sources/AgentsCore/FileAccess.swift index 11183f7..cc31a25 100644 --- a/Sources/AgentsCore/FileAccess.swift +++ b/Sources/AgentsCore/FileAccess.swift @@ -3,16 +3,16 @@ import Foundation /// Access metadata is separate from content generations. ACL bytes contain ordered /// numeric identities and inheritance, never resolved account names or payload bytes. -struct FileAccessEvidence: Codable, Equatable, Sendable { +package struct FileAccessEvidence: Codable, Equatable, Sendable { enum ACLFormat: String, Codable, Sendable { case darwinExternal case linuxPOSIX } let identity: FileObjectIdentity - let owner: UInt32 - let group: UInt32 - let mode: mode_t + package let owner: UInt32 + package let group: UInt32 + package let mode: mode_t let aclFormat: ACLFormat let acl: Data let defaultACL: Data @@ -66,7 +66,17 @@ struct FileAccessEvidence: Codable, Equatable, Sendable { evidence: Self, assessment: UInt32, links: UInt64 ) { var value = platform_file_access() - guard platform_read_file_access(descriptor, &value) == 0 else { + // Concurrent directory-entry activity can move stat's generation during an + // ACL query. Retry only capture; sealed/prepared evidence is never refreshed. + var captured = false + for attempt in 0..<3 { + if platform_read_file_access(descriptor, &value) == 0 { + captured = true + break + } + if errno != EAGAIN || attempt == 2 { break } + } + guard captured else { throw CoreError.invalidState("cannot capture descriptor access evidence: \(errno)") } defer { platform_dispose_file_access(&value) } @@ -238,3 +248,64 @@ private func requireAccessComponent(_ name: String) throws { throw CoreError.invalidState("access operation requires one path component") } } + +/// Ordered physical ancestry, derived from a registered target rather than journal paths. +/// A prefix can describe a not-yet-created parent during preparation only. +struct DirectoryAccessEvidence: Codable, Equatable { + let directories: [FileAccessEvidence] + + static func capture(at url: URL) throws -> Self { + var descriptor = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC) + guard descriptor >= 0 else { throw CoreError.unsafePath("cannot open access ancestry") } + defer { close(descriptor) } + var evidence = [try FileAccessEvidence.capture(descriptor: descriptor)] + for (index, name) in url.standardizedFileURL.pathComponents.dropFirst().enumerated() { + let alias = index == 0 && platform_system_alias(name) + let next = openat( + descriptor, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC | (alias ? 0 : O_NOFOLLOW)) + if next < 0 { + guard errno == ENOENT else { throw CoreError.unsafePath("cannot open access ancestry") } + break + } + do { + let child = try FileAccessEvidence.capture(descriptor: next) + _ = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: descriptor, protectingOwner: child.owner) + evidence.append(child) + } catch { + close(next) + throw error + } + close(descriptor) + descriptor = next + } + _ = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: descriptor, protectingOwner: geteuid()) + return Self(directories: evidence) + } + + func validate(at url: URL, allowingCreation: Bool = false) throws { + let current = try Self.capture(at: url) + guard + allowingCreation + ? current.directories.starts(with: directories) : current == self + else { throw CoreError.invalidState("filesystem access ancestry changed during preparation") } + } +} + +extension DirectoryHandle { + @discardableResult + func requirePrivateAccess(_ name: String, matching expected: FileAccessEvidence? = nil) throws + -> FileAccessEvidence + { + try requireAccessComponent(name) + let file = openat(descriptor, name, O_RDONLY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC) + guard file >= 0 else { throw CoreError.invalidState("cannot open private object") } + defer { close(file) } + let evidence = try FileAccessEvidence.requirePrivate(descriptor: file) + guard expected == nil || expected == evidence, + try info(name).map(FileObjectIdentity.init) == evidence.identity + else { throw CoreError.invalidState("private object access changed") } + return evidence + } +} diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index ab45cb8..6e0418d 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -1,3 +1,4 @@ +import CPlatform import Foundation /// The scope's sole durable undo journal owns private construction containers, @@ -24,14 +25,20 @@ package final class FileTransaction { private struct Request { let path: String let evidence: TargetPrecondition - /// Absent for a deletion. + /// Ordinary input. Private installs produce bytes only after verified creation. let source: Source? let expectation: Expectation + let security: TransactionSecurity + let privateData: (() throws -> Data)? + var installs: Bool { source != nil || security.replacement == .privateMaterialization } } private let store: StateStore private let checkpoint: (String) throws -> Void private let outcome: TransactionOutcome private var requests: [Request] = [] + private var receiptState: + (records: MaterializationReceipts, evidence: TargetPrecondition, access: FileAccessEvidence?)? + private var receiptIndex: Int? private var unchanged: [any PreparedEvidence] = [] private var targetPaths: Set { Set(requests.map { $0.evidence.url.path }) } @@ -50,7 +57,7 @@ package final class FileTransaction { executableFlags: [String: Bool]? = nil, expecting: TargetPrecondition? = nil ) throws { if let expectedHash { try StateValidation.digest(expectedHash) } - let (path, evidence) = try request(destination, expecting: expecting) + let (path, evidence, security) = try request(destination, expecting: expecting) var expectation = Expectation(hash: expectedHash, executableFlags: executableFlags) switch source { case .copy(let url): @@ -61,12 +68,75 @@ package final class FileTransaction { case .data, .prepared: break } requests.append( - Request(path: path, evidence: evidence, source: source, expectation: expectation)) + Request( + path: path, evidence: evidence, source: source, expectation: expectation, + security: security, privateData: nil)) } package func delete(_ destination: URL, expecting: TargetPrecondition? = nil) throws { - let (path, evidence) = try request(destination, expecting: expecting) - requests.append(Request(path: path, evidence: evidence, source: nil, expectation: .init())) + let (path, evidence, security) = try request(destination, expecting: expecting) + requests.append( + Request( + path: path, evidence: evidence, source: nil, expectation: .init(), security: security, + privateData: nil)) + } + + /// Values are resolved only inside commit, after private staging has been verified. + package func replacePrivate( + _ prepared: PreparedPrivateMaterialization, bindings: Set = [], + provider: any RuntimeBindingProvider, + render: @escaping (RuntimeBindingValues) throws -> Data + ) throws { + guard prepared.target.scope == store.directory, prepared.owner == geteuid(), + bindings.allSatisfy({ !$0.isEmpty && !$0.contains("\0") }) + else { throw CoreError.invalidState("invalid private materialization inputs") } + try prepared.receiptEvidence.validate() + let (path, evidence, previous) = try request(prepared.target.url, expecting: prepared.evidence) + guard path == prepared.target.path else { + throw CoreError.invalidState("materialization registration changed") + } + try prepared.ancestry.validate(at: evidence.physicalURL.deletingLastPathComponent()) + var security = previous + security.replacement = .privateMaterialization + security.permissionChange = prepared.accessChange != nil + security.preimageAccess = prepared.beforeAccess + security.ancestry = prepared.ancestry + let environment = store.environment + requests.append( + Request( + path: path, evidence: evidence, source: nil, expectation: .init(), + security: security, + privateData: { + do { + var values: [String: Data] = [:] + for name in bindings.sorted() { + values[name] = try provider.value(for: name, environment: environment) + } + return try render(RuntimeBindingValues(values)) + } catch { + throw CoreError.invalidState( + "private materialization could not resolve or render its bindings") + } + })) + } + + private func queueReceipt() throws { + guard receiptIndex == nil, let receiptState, + requests.contains(where: { + $0.security.isPrivate || receiptState.records.targets[$0.path] != nil + }) + else { return } + let target = store.materializationReceiptURL + var security = TransactionSecurity() + security.preimage = receiptState.access == nil ? .ordinary : .privateMaterialization + security.replacement = .privateMaterialization + security.preimageAccess = receiptState.access + security.ancestry = try DirectoryAccessEvidence.capture(at: target.deletingLastPathComponent()) + receiptIndex = requests.count + requests.append( + Request( + path: "state/" + MaterializationReceipts.fileName, evidence: receiptState.evidence, + source: nil, expectation: .init(), security: security, privateData: nil)) } /// Prepared inputs that this journal does not replace must still match at commit entry, @@ -80,9 +150,13 @@ package final class FileTransaction { } private func request(_ destination: URL, expecting: TargetPrecondition?) throws -> ( - path: String, evidence: TargetPrecondition + path: String, evidence: TargetPrecondition, security: TransactionSecurity ) { let path = try TransactionPaths(store: store).path(for: destination) + guard path != "state/" + MaterializationReceipts.fileName else { + throw CoreError.unsafePath("materialization receipts are transaction-owned") + } + if receiptState == nil { receiptState = try store.materializationReceipts() } guard !requests.contains(where: { $0.path == path }) else { throw CoreError.invalidState("duplicate transaction destination") } @@ -90,7 +164,25 @@ package final class FileTransaction { guard evidence.url.path == destination.standardizedFileURL.path else { throw CoreError.invalidState("precondition belongs to another target") } - return (path, evidence) + var security = TransactionSecurity() + if let record = receiptState?.records.targets[path] { + let paths = TransactionPaths(store: store) + let key = try paths.components(path).root + guard try paths.root(key).identity == record.rootIdentity else { + throw CoreError.invalidState("materialization receipt root changed") + } + // A known absence has no sensitive preimage; its receipt is reconciled in this journal. + guard evidence.snapshot != nil else { return (path, evidence, security) } + guard evidence.snapshot?.digest == record.digest, + evidence.snapshot?.identity == record.access.identity + else { throw CoreError.invalidState("materialized preimage differs from its receipt") } + let parent = try DirectoryHandle(at: evidence.physicalURL.deletingLastPathComponent()) + _ = try parent.requirePrivateAccess(destination.lastPathComponent, matching: record.access) + security.preimage = .privateMaterialization + security.preimageAccess = record.access + security.ancestry = try DirectoryAccessEvidence.capture(at: parent.url) + } + return (path, evidence, security) } static func copyExpectation( @@ -119,6 +211,8 @@ package final class FileTransaction { else { throw CoreError.invalidState("transaction recovery is required") } + try queueReceipt() + try receiptState?.evidence.validate() try validateUnchanged() for request in requests { try request.evidence.validate() } try validateOverlap() @@ -136,7 +230,16 @@ package final class FileTransaction { try SourceCache(store: store, checkpoint: checkpoint).beginWatchReferenceUpdate() } for (index, request) in requests.enumerated() { - try session.stage(index, source: request.source, expectation: request.expectation) + if index == receiptIndex { + try session.stage(index, source: request.source, expectation: request.expectation) { + try StateStore.encode( + session.materializationReceipts(previous: self.receiptState!.records)) + } + } else { + try session.stage( + index, source: request.source, expectation: request.expectation, + privateData: request.privateData) + } } try session.emit(.preconditions) try validateUnchanged() @@ -210,10 +313,16 @@ package final class FileTransaction { containers.append( .init(entry: index, name: TransactionJournal.containerName(id: id, index: container))) } + var security = request.security + if let ancestry = security.ancestry { + try ancestry.validate(at: parents[index].url, allowingCreation: true) + security.ancestry = try DirectoryAccessEvidence.capture(at: parents[index].url) + } entries.append( .init( - path: request.path, action: request.source == nil ? .delete : .install, - preimage: request.evidence.snapshot, parentIdentity: identity, container: container)) + path: request.path, action: request.installs ? .install : .delete, + preimage: request.evidence.snapshot, parentIdentity: identity, container: container, + security: security)) } let journal = TransactionJournal( id: id, scope: try directory.identity, diff --git a/Sources/AgentsCore/PrivateMaterialization.swift b/Sources/AgentsCore/PrivateMaterialization.swift new file mode 100644 index 0000000..4c09e2e --- /dev/null +++ b/Sources/AgentsCore/PrivateMaterialization.swift @@ -0,0 +1,216 @@ +import CPlatform +import Foundation + +/// Runtime data supplied by the application. Source declarations never supply commands. +package protocol RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data +} + +/// Ephemeral values have no encoding or diagnostic representation. +package struct RuntimeBindingValues: CustomStringConvertible, CustomDebugStringConvertible, + CustomReflectable +{ + package var description: String { "" } + package var debugDescription: String { description } + package var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } + private let values: [String: Data] + + init(_ values: [String: Data]) { self.values = values } + + package func value(for binding: String) throws -> Data { + guard let value = values[binding] else { + throw CoreError.invalidState("required runtime binding is unavailable") + } + return value + } +} + +/// A physical file admitted by Core's existing, scope-owned path registrations. +package struct MaterializationTarget { + package let url: URL + package let path: String + let scope: URL +} + +/// The before-access and intended owner-only replacement are available for a prepared report. +package struct PrivateAccessChange { + package let before: FileAccessEvidence + package let owner: UInt32 + package let mode: UInt32 +} + +/// A local receipt view has no payload digest or serializable binding data. +package struct MaterializationReceipt { + package let generation: UUID + package let access: FileAccessEvidence +} + +package struct PreparedPrivateMaterialization { + package let owner: UInt32 + package let receiptGeneration: UUID? + package let accessChange: PrivateAccessChange? + package let target: MaterializationTarget + let evidence: TargetPrecondition + let receiptEvidence: TargetPrecondition + var ancestry: DirectoryAccessEvidence { evidence.access!.ancestry } + var beforeAccess: FileAccessEvidence? { evidence.access?.target } + + /// A non-secret access segment for the enclosing candidate's displayed fingerprint. + package func accessFingerprint() throws -> String { + let input = PrivateAccessFingerprint( + target: target.path, owner: owner, before: beforeAccess, ancestry: ancestry, + permissionChange: accessChange != nil, receiptGeneration: receiptGeneration) + return "sha256:" + FileHash.sha256Hex(data: try StateStore.encode(input)) + } +} + +private struct PrivateAccessFingerprint: Encodable { + let version = 1 + let target: String + let owner: UInt32 + let before: FileAccessEvidence? + let ancestry: DirectoryAccessEvidence + let permissionChange: Bool + let receiptGeneration: UUID? +} + +extension StateStore { + /// Native routes must extend the owning static registration after route verification. + /// This seam cannot authorize arbitrary external roots or source-authoring files. + package func materializationTarget(at url: URL) throws -> MaterializationTarget { + let paths = TransactionPaths(store: self) + let path = try paths.path(for: url) + let root = try paths.components(path).root + guard root.hasPrefix("instructions-"), root != "instructions-authoring" else { + throw CoreError.unsafePath("private materialization requires a registered file target") + } + return MaterializationTarget(url: url.standardizedFileURL, path: path, scope: directory) + } + + /// Inspects the last local generation under the caller's scope lock, without exposing bytes. + package func materializationReceipt(for target: MaterializationTarget) throws + -> MaterializationReceipt? + { + guard target.scope == directory, + try TransactionPaths(store: self).path(for: target.url) == target.path + else { throw CoreError.invalidState("materialization target belongs to another scope") } + guard let record = try materializationReceipts().records.targets[target.path] else { + return nil + } + _ = try preparePrivateMaterialization(target, expecting: record.generation) + return MaterializationReceipt(generation: record.generation, access: record.access) + } + + /// Under the caller's scope lock, preparation never calls a provider or renderer. + package func preparePrivateMaterialization( + _ target: MaterializationTarget, changingAccess: Bool = false, + requiringReceiptForExistingTarget: Bool = false, expecting generation: UUID? = nil + ) throws -> PreparedPrivateMaterialization { + guard target.scope == directory, + try TransactionPaths(store: self).path(for: target.url) == target.path + else { throw CoreError.invalidState("materialization target belongs to another scope") } + let receipt = try materializationReceipts() + let record = receipt.records.targets[target.path] + if let generation, record?.generation != generation { + throw CoreError.invalidState("materialization receipt generation changed or is missing") + } + let evidence = try TargetPrecondition(target.url).capturingAccess() + guard !requiringReceiptForExistingTarget || evidence.snapshot == nil || record != nil else { + throw CoreError.invalidState("known materialized target is missing its private receipt") + } + guard evidence.snapshot == nil || evidence.snapshot?.isRegular == true else { + throw CoreError.unsafePath("private materialization requires a regular file") + } + let parentURL = evidence.physicalURL.deletingLastPathComponent() + let ancestry = try DirectoryAccessEvidence.capture(at: parentURL) + var beforeAccess: FileAccessEvidence? + var change: PrivateAccessChange? + if evidence.snapshot != nil { + let parent = try DirectoryHandle(at: parentURL) + beforeAccess = try parent.accessEvidence(target.url.lastPathComponent) + var changesAccess = beforeAccess?.mode != 0o600 + do { _ = try parent.requirePrivateAccess(target.url.lastPathComponent) } catch { + changesAccess = true + } + if changesAccess { + guard changingAccess, let beforeAccess else { + throw CoreError.invalidState("private materialization requires an explicit access change") + } + change = PrivateAccessChange(before: beforeAccess, owner: UInt32(geteuid()), mode: 0o600) + } + } + if let record = receipt.records.targets[target.path] { + let paths = TransactionPaths(store: self) + let key = try paths.components(target.path).root + guard try paths.root(key).identity == record.rootIdentity else { + throw CoreError.invalidState("materialization receipt root changed") + } + if evidence.snapshot != nil { + guard evidence.snapshot?.digest == record.digest, beforeAccess == record.access else { + throw CoreError.invalidState("materialized preimage differs from its receipt") + } + _ = try DirectoryHandle(at: parentURL).requirePrivateAccess( + target.url.lastPathComponent, matching: record.access) + } + } + try evidence.validate() + try ancestry.validate(at: parentURL) + return PreparedPrivateMaterialization( + owner: UInt32(geteuid()), receiptGeneration: record?.generation, accessChange: change, + target: target, + evidence: evidence, receiptEvidence: receipt.evidence) + } +} + +/// Only materialization generations and local physical evidence belong here. +struct MaterializationReceipts: Codable { + static let fileName = "materializations.json" + var version = 1 + var targets: [String: Record] = [:] + + struct Record: Codable { + let generation: UUID + let rootIdentity: String + let digest: String + let access: FileAccessEvidence + } + + func validate(store: StateStore) throws { + guard version == 1 else { throw CoreError.invalidState("unsupported materialization receipt") } + for (path, record) in targets { + let paths = TransactionPaths(store: store) + let parts = try paths.components(path) + guard parts.root.hasPrefix("instructions-"), parts.root != "instructions-authoring", + record.access.identity.kind == S_IFREG, + !record.rootIdentity.isEmpty + else { throw CoreError.invalidState("invalid materialization receipt target") } + try StateValidation.digest("sha256:" + record.digest) + } + } +} + +extension StateStore { + var materializationReceiptURL: URL { + directory.appendingPathComponent(MaterializationReceipts.fileName) + } + + func materializationReceipts() throws -> ( + records: MaterializationReceipts, evidence: TargetPrecondition, access: FileAccessEvidence? + ) { + let evidence = try TargetPrecondition(materializationReceiptURL) + guard evidence.snapshot != nil else { return (.init(), evidence, nil) } + guard let directory = try openDirectoryIfPresent() else { + throw CoreError.invalidState("materialization receipt directory is missing") + } + let evidenceWithAccess = try evidence.capturingAccess() + let access = try directory.requirePrivateAccess(MaterializationReceipts.fileName) + do { + let records = try Self.decode( + directory.read(MaterializationReceipts.fileName), as: MaterializationReceipts.self) + try records.validate(store: self) + try evidence.validate() + _ = try directory.requirePrivateAccess(MaterializationReceipts.fileName, matching: access) + return (records, evidenceWithAccess, access) + } catch { throw CoreError.invalidState("invalid private materialization receipt") } + } +} diff --git a/Sources/AgentsCore/StateStore.swift b/Sources/AgentsCore/StateStore.swift index c89bd2b..fa3d18d 100644 --- a/Sources/AgentsCore/StateStore.swift +++ b/Sources/AgentsCore/StateStore.swift @@ -25,7 +25,7 @@ public struct StateStore: Sendable { package static let watchFileName = "agents.watch" /// The scope files a state transaction may replace. package static let stateFileNames: Set = [ - declarationFileName, resolvedFileName, watchFileName, + declarationFileName, resolvedFileName, watchFileName, MaterializationReceipts.fileName, ] /// The declaration's bytes, or nil when the scope has no declaration and no lock or watch diff --git a/Sources/AgentsCore/TransactionDisposal.swift b/Sources/AgentsCore/TransactionDisposal.swift index 81cce55..e5b5ccc 100644 --- a/Sources/AgentsCore/TransactionDisposal.swift +++ b/Sources/AgentsCore/TransactionDisposal.swift @@ -99,6 +99,9 @@ extension TransactionSession { func verifyTarget(_ index: Int) throws { let entry = journal.entries[index] try requireParent(index) + if case .object(let expected) = TransactionLayout.expected(entry)[0].target { + try entry.security.validateObject(expected, named: entry.name, in: parents[index]) + } // Terminal phases have a single distribution; disposal may have removed its slots. guard try TransactionLayout.expected(entry)[0].target.matches(entry.name, from: parents[index]) else { @@ -128,6 +131,25 @@ extension TransactionSession { guard FileObjectIdentity(actual) == identity else { throw conflict(record.entry, "private container identity changed") } + if journal.entries.contains(where: { $0.container == index && $0.security.isPrivate }) { + let handle = try container(index) + for (entryIndex, entry) in journal.entries.enumerated() where entry.container == index { + for slot in TransactionSlot.objectSlots { + let name = slot.name(entryIndex) + guard let info = try handle.info(name) else { continue } + if let expected = [entry.preimage, entry.staged].compactMap({ $0 }).first(where: { + $0.identity == FileObjectIdentity(info) + }) { + try entry.security.validateObject(expected, named: name, in: handle) + } else if entry.progress == .queued + && entry.security.replacement == .privateMaterialization + && slot == TransactionSlot.staging(for: entry) + { + _ = try handle.requirePrivateAccess(name) + } + } + } + } if let expected = record.disposal { let current = try FileSnapshot.read(record.name, from: parent) let matches = @@ -142,6 +164,7 @@ extension TransactionSession { let parent = parents[record.entry] try requireScope() try requireParent(record.entry) + try validateContainerForDisposal(index) if let identity = record.identity { try parent.remove(record.name, expecting: record.disposal, identity: identity) { point in try emit( diff --git a/Sources/AgentsCore/TransactionEvidence.swift b/Sources/AgentsCore/TransactionEvidence.swift index d1653cb..1a976ab 100644 --- a/Sources/AgentsCore/TransactionEvidence.swift +++ b/Sources/AgentsCore/TransactionEvidence.swift @@ -185,3 +185,61 @@ struct FileSnapshot: Codable, Equatable, Sendable { return remaining.allSatisfy { name, value in children[name]?.containsRemaining(value) == true } } } + +/// Required journal classification. Optional metadata is required by validation whenever +/// its corresponding object exists in a security-bearing operation. +struct TransactionSecurity: Codable { + enum Classification: String, Codable { case ordinary, privateMaterialization } + var preimage: Classification = .ordinary + var replacement: Classification = .ordinary + var permissionChange = false + var ancestry: DirectoryAccessEvidence? + var preimageAccess: FileAccessEvidence? + var stagedAccess: FileAccessEvidence? + + var isPrivate: Bool { + preimage == .privateMaterialization || replacement == .privateMaterialization + } + + func validate(entry: TransactionJournal.Entry) throws { + guard !isPrivate || ancestry != nil, + !permissionChange || (replacement == .privateMaterialization && entry.preimage != nil), + !isPrivate || (entry.preimage == nil) == (preimageAccess == nil), + replacement != .privateMaterialization || (entry.staged == nil) == (stagedAccess == nil), + !isPrivate || entry.preimage == nil || entry.preimage?.isRegular == true, + preimage != .privateMaterialization || entry.preimage?.isRegular == true, + replacement != .privateMaterialization || entry.staged == nil + || entry.staged?.isRegular == true, + replacement != .privateMaterialization || entry.action == .install + else { throw CoreError.invalidState("missing or contradictory transaction security evidence") } + for (snapshot, access) in [(entry.preimage, preimageAccess), (entry.staged, stagedAccess)] { + if let access { + guard access.identity == snapshot?.identity, access.mode == snapshot?.mode else { + throw CoreError.invalidState("transaction access evidence belongs to another object") + } + } + } + } + + func validateObject(_ snapshot: FileSnapshot, named name: String, in parent: DirectoryHandle) + throws + { + let access: FileAccessEvidence? + let classification: Classification + if snapshot.identity == preimageAccess?.identity { + access = preimageAccess + classification = preimage + } else if snapshot.identity == stagedAccess?.identity { + access = stagedAccess + classification = replacement + } else { + return + } + guard let access else { return } + if classification == .privateMaterialization { + _ = try parent.requirePrivateAccess(name, matching: access) + } else if try parent.accessEvidence(name) != access { + throw CoreError.invalidState("transaction object access changed") + } + } +} diff --git a/Sources/AgentsCore/TransactionJournal.swift b/Sources/AgentsCore/TransactionJournal.swift index dec9c4f..1b98a94 100644 --- a/Sources/AgentsCore/TransactionJournal.swift +++ b/Sources/AgentsCore/TransactionJournal.swift @@ -2,7 +2,7 @@ import Foundation /// The version is independent of declaration, resolved and watch formats. struct TransactionJournal: Codable { - static let currentVersion = 1 + static let currentVersion = 2 static let fileName = "transaction.json" /// The next journal generation before it replaces `fileName`. static let incompleteFileName = "transaction.new" @@ -54,6 +54,7 @@ struct TransactionJournal: Codable { var staged: FileSnapshot? var progress: Progress = .queued var conflict: Conflict? + var security = TransactionSecurity() var name: String { String(path.split(separator: "/").last!) } } @@ -67,6 +68,7 @@ struct TransactionJournal: Codable { /// entries are admitted only after `disposing` is durable; private unfinished construction /// needs no tree evidence. var disposal: FileSnapshot? + var access: FileAccessEvidence? } static func containerName(id: UUID, index: Int) -> String { ".agents-\(id.uuidString)-\(index)" } diff --git a/Sources/AgentsCore/TransactionPublication.swift b/Sources/AgentsCore/TransactionPublication.swift index d951c59..89cd47d 100644 --- a/Sources/AgentsCore/TransactionPublication.swift +++ b/Sources/AgentsCore/TransactionPublication.swift @@ -5,7 +5,12 @@ extension TransactionSession { func createContainers() throws { for index in journal.containers.indices { let parent = parents[journal.containers[index].entry] - let created = try parent.makeDirectory(journal.containerName(index)) + let needsPrivate = journal.entries.contains { $0.container == index && $0.security.isPrivate } + let created = + try needsPrivate + ? parent.createPrivateDirectory(journal.containerName(index)) + : parent.makeDirectory(journal.containerName(index)) + if needsPrivate { journal.containers[index].access = try created.accessEvidence() } let identity = try created.objectIdentity try emit(.containerCreated(index)) guard try parent.info(journal.containerName(index)).map(FileObjectIdentity.init) == identity @@ -35,7 +40,8 @@ extension TransactionSession { } func stage( - _ index: Int, source: FileTransaction.Source?, expectation: FileTransaction.Expectation + _ index: Int, source: FileTransaction.Source?, expectation: FileTransaction.Expectation, + privateData: (() throws -> Data)? = nil ) throws { let entry = journal.entries[index] let parent = parents[index] @@ -44,10 +50,10 @@ extension TransactionSession { try emit(.stage(index, .preimageSynced)) let staging = TransactionSlot.staging(for: entry) var staged: FileSnapshot? - if let source { + if source != nil || entry.security.replacement == .privateMaterialization { let sealed = try construct( source, expectation: expectation, named: staging.name(index), index: index, - container: container, parent: parent) + container: container, parent: parent, privateData: privateData) try emit(.stage(index, .constructed)) let capture = try FileSnapshot.capture(staging.name(index), from: container) try verify(source, sealed, capture: capture) @@ -55,10 +61,14 @@ extension TransactionSession { throw conflict(index, "missing constructed object") } staged = snapshot + if entry.security.replacement == .privateMaterialization { + journal.entries[index].security.stagedAccess = try container.requirePrivateAccess( + staging.name(index)) + } } else { try emit(.stage(index, .constructed)) } - for slot in TransactionSlot.objectSlots where source == nil || slot != staging { + for slot in TransactionSlot.objectSlots where entry.action == .delete || slot != staging { guard try container.info(slot.name(index)) == nil else { throw CoreError.invalidState("unexpected private recovery slot before sealing") } @@ -70,11 +80,30 @@ extension TransactionSession { /// Returns the expectation the sealed staging must meet. private func construct( - _ source: FileTransaction.Source, expectation: FileTransaction.Expectation, - named name: String, index: Int, container: DirectoryHandle, parent: DirectoryHandle + _ source: FileTransaction.Source?, expectation: FileTransaction.Expectation, + named name: String, index: Int, container: DirectoryHandle, parent: DirectoryHandle, + privateData: (() throws -> Data)? ) throws -> FileTransaction.Expectation { let entry = journal.entries[index] var expectation = expectation + if entry.security.replacement == .privateMaterialization { + guard let privateData else { + throw conflict(index, "missing private materialization producer") + } + let file = try container.createPrivateFile(name) + try emit(.stage(index, .writeCreated)) + try requirePreimage(index) + _ = try container.requirePrivateAccess(name, matching: file.evidence) + // The callback is never given a path or unverified descriptor. + let data = try privateData() + try requireParent(index) + try file.write(data) + expectation.hash = "sha256:" + FileHash.sha256Hex(data: data) + expectation.kind = S_IFREG + expectation.mode = file.evidence.mode + return expectation + } + guard let source else { throw conflict(index, "missing ordinary construction input") } switch source { case .data(let data): let original = entry.preimage?.isRegular == true ? entry.preimage : nil @@ -118,14 +147,14 @@ extension TransactionSession { } private func verify( - _ source: FileTransaction.Source, _ expectation: FileTransaction.Expectation, + _ source: FileTransaction.Source?, _ expectation: FileTransaction.Expectation, capture: FileSnapshot.Capture ) throws { let snapshot = capture.snapshot if let kind = expectation.kind, snapshot?.identity.kind != kind { throw CoreError.invalidState("staged content type mismatch") } - if case .data = source, snapshot?.isRegular != true { + if case .data? = source, snapshot?.isRegular != true { throw CoreError.invalidState("staged content type mismatch") } if let mode = expectation.mode, snapshot?.mode != mode { @@ -133,16 +162,16 @@ extension TransactionSession { } var linked: URL? switch source { - case .data(let data): + case .data(let data)?: guard snapshot?.digest == FileHash.sha256Hex(data: data) else { throw CoreError.invalidState("staged content bytes mismatch") } - case .link(let url): + case .link(let url)?: guard snapshot?.isSymbolicLink == true, let destination = expectation.linkDestination, snapshot?.digest == FileHash.sha256Hex(data: Data(destination.utf8)) else { throw CoreError.invalidState("staged symbolic link destination mismatch") } linked = url - case .copy, .prepared: break + case .copy?, .prepared?, nil: break } if let expected = expectation.hash { let actual = try linked.map(FileHash.folderHash) ?? capture.contentHash @@ -175,6 +204,7 @@ extension TransactionSession { try advance(index, to: .publishing) try requirePreimage(index) try emit(.publication(index, .validated)) + if entry.security.isPrivate { try requirePreimage(index) } try grantDirectoryPermissions(index, layout: layout, purpose: .publicationGrant) if entry.action == .install { let exchange = entry.preimage != nil @@ -201,6 +231,10 @@ extension TransactionSession { func requirePreimage(_ index: Int) throws { try requireParent(index) + let entry = journal.entries[index] + if let preimage = entry.preimage { + try entry.security.validateObject(preimage, named: entry.name, in: parents[index]) + } guard try FileSnapshot.read(journal.entries[index].name, from: parents[index]) == journal.entries[index].preimage @@ -209,6 +243,24 @@ extension TransactionSession { } } + func materializationReceipts(previous: MaterializationReceipts) throws -> MaterializationReceipts + { + var records = previous + for entry in journal.entries where entry.path != "state/" + MaterializationReceipts.fileName { + if entry.security.replacement == .privateMaterialization { + guard let snapshot = entry.staged, let access = entry.security.stagedAccess, + let root = entry.path.split(separator: "/").first, + let identity = journal.roots[String(root)] + else { throw CoreError.invalidState("materialization is missing sealed receipt evidence") } + records.targets[entry.path] = .init( + generation: journal.id, rootIdentity: identity, digest: snapshot.digest, access: access) + } else { + records.targets.removeValue(forKey: entry.path) + } + } + return records + } + /// A copied subtree keeps relative links that stay inside it, dangling ones included. private static func validateCopy(_ source: URL) throws { guard let root = PathSafety.realPath(source.path), diff --git a/Sources/AgentsCore/TransactionRecovery.swift b/Sources/AgentsCore/TransactionRecovery.swift index 048015b..971c585 100644 --- a/Sources/AgentsCore/TransactionRecovery.swift +++ b/Sources/AgentsCore/TransactionRecovery.swift @@ -209,6 +209,11 @@ extension TransactionSession { let parent = parents[index] let container = try self.container(entry.container) try emit(.restoration(index, .validated)) + try requireParent(index) + if let preimage = entry.preimage { + let slot: TransactionSlot = entry.action == .install ? .exchanged : .deleted + try entry.security.validateObject(preimage, named: slot.name(index), in: container) + } if entry.preimage != nil { if entry.action == .install { try container.move( diff --git a/Sources/AgentsCore/TransactionSession.swift b/Sources/AgentsCore/TransactionSession.swift index 67278a2..5c8104f 100644 --- a/Sources/AgentsCore/TransactionSession.swift +++ b/Sources/AgentsCore/TransactionSession.swift @@ -79,6 +79,7 @@ final class TransactionSession { } func requireParent(_ index: Int) throws { + try journal.entries[index].security.ancestry?.validate(at: parents[index].url) guard try DirectoryHandle(at: parents[index].url).identity == journal.entries[index].parentIdentity else { @@ -117,6 +118,13 @@ final class TransactionSession { guard try handle.objectIdentity == expected else { throw conflict(record.entry, "private container changed while opening") } + if journal.entries.contains(where: { $0.container == index && $0.security.isPrivate }) { + guard let access = record.access else { + throw conflict(record.entry, "missing private container access") + } + _ = try FileAccessEvidence.requirePrivate(descriptor: handle.descriptor) + try access.validate(descriptor: handle.descriptor) + } return handle } @@ -130,6 +138,7 @@ final class TransactionSession { var targets: [URL] = [] for (index, entry) in journal.entries.enumerated() { try requireParent(index) + try entry.security.validate(entry: entry) let target = parents[index].url.appendingPathComponent(entry.name) guard !targets.contains(where: { @@ -171,6 +180,11 @@ final class TransactionSession { throw CoreError.invalidState("sealed operation is missing private container identity") } } + let needsPrivate = journal.entries.contains { $0.container == index && $0.security.isPrivate } + guard !needsPrivate || record.identity == nil || record.access?.identity == record.identity + else { + throw CoreError.invalidState("private container is missing access evidence") + } try record.disposal?.validate() if let disposal = record.disposal { guard disposal.identity == record.identity else { @@ -214,11 +228,17 @@ final class TransactionSession { let entry = journal.entries[index] try requireParent(index) let layouts = TransactionLayout.expected(entry) - if entry.progress == .queued { return layouts[0] } + if entry.progress == .queued { + if entry.security.preimage == .privateMaterialization, let original = entry.preimage { + try entry.security.validateObject(original, named: entry.name, in: parents[index]) + } + return layouts[0] + } let container = try self.container(entry.container) var objects: [TransactionSlot: FileSnapshot] = [:] for slot in TransactionSlot.objectSlots { if let value = try FileSnapshot.read(slot.name(index), from: container) { + try entry.security.validateObject(value, named: slot.name(index), in: container) objects[slot] = value } } @@ -230,6 +250,14 @@ final class TransactionSession { return expected.matches(actual, permittingDirectoryWrite: permitsWrite) }) else { continue } + if layout.kind == .prepared, let original = entry.preimage { + try entry.security.validateObject(original, named: entry.name, in: parents[index]) + } + if case .object(let expected) = layout.target, + try parents[index].info(entry.name).map(FileObjectIdentity.init) == expected.identity + { + try entry.security.validateObject(expected, named: entry.name, in: parents[index]) + } if try layout.target.matches( entry.name, from: parents[index], permittingDirectoryWrite: permitsWrite) { diff --git a/Sources/AgentsCore/UpdatePreconditions.swift b/Sources/AgentsCore/UpdatePreconditions.swift index 2388318..587cdb7 100644 --- a/Sources/AgentsCore/UpdatePreconditions.swift +++ b/Sources/AgentsCore/UpdatePreconditions.swift @@ -89,6 +89,7 @@ package struct TargetPrecondition { package let url: URL let snapshot: FileSnapshot? private let identity: PathIdentity + private(set) var access: TargetAccessPrecondition? var physicalURL: URL { url.deletingLastPathComponent().resolvingSymlinksInPath().appendingPathComponent( @@ -120,16 +121,44 @@ package struct TargetPrecondition { return (capture.bytes, Self(url: url, snapshot: capture.snapshot, identity: identity)) } + func capturingAccess() throws -> Self { + var result = self + result.access = try TargetAccessPrecondition.capture(at: physicalURL) + try result.validate() + return result + } + package func sameGeneration(as other: Self) -> Bool { - url.path == other.url.path && snapshot == other.snapshot + url.path == other.url.path && snapshot == other.snapshot && access == other.access } func validateIdentity() throws { try identity.validate() } package func validate() throws { try validateIdentity() + try access?.validate(at: physicalURL) guard try FileSnapshot.read(at: url) == snapshot else { throw CoreError.invalidState("target changed during preparation: \(url.path)") } } } + +struct TargetAccessPrecondition: Equatable { + let ancestry: DirectoryAccessEvidence + let target: FileAccessEvidence? + + static func capture(at url: URL) throws -> Self { + let parentURL = url.deletingLastPathComponent() + let ancestry = try DirectoryAccessEvidence.capture(at: parentURL) + let complete = ancestry.directories.count == parentURL.standardizedFileURL.pathComponents.count + let target = + try complete ? DirectoryHandle(at: parentURL).accessEvidence(url.lastPathComponent) : nil + return Self(ancestry: ancestry, target: target) + } + + func validate(at url: URL) throws { + guard try Self.capture(at: url) == self else { + throw CoreError.invalidState("target or ancestry access changed during preparation") + } + } +} diff --git a/Tests/AgentsCoreTests/PrivateMaterializationTests.swift b/Tests/AgentsCoreTests/PrivateMaterializationTests.swift new file mode 100644 index 0000000..524ce8e --- /dev/null +++ b/Tests/AgentsCoreTests/PrivateMaterializationTests.swift @@ -0,0 +1,486 @@ +import CPlatform +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite("Private materialization transactions") +struct PrivateMaterializationTests { + @Test func preparationIsSymbolicAndAccessChangesAreExplicit() throws { + let fixture = try TransactionFixture() + let target = try fixture.store.materializationTarget( + at: fixture.root.appendingPathComponent("AGENTS.md")) + let provider = TestBindings("secret-sentinel") + try #require(chmod(target.url.path, 0o644) == 0) + let before = try FileSnapshot.read(at: target.url) + #expect(throws: CoreError.self) { try fixture.store.preparePrivateMaterialization(target) } + let prepared = try fixture.store.preparePrivateMaterialization(target, changingAccess: true) + #expect(prepared.accessChange?.before.mode == 0o644) + #expect(prepared.accessChange?.mode == 0o600) + #expect(provider.calls == 0) + #expect(try FileSnapshot.read(at: target.url) == before) + #expect(!FileManager.default.fileExists(atPath: fixture.store.materializationReceiptURL.path)) + #expect(throws: CoreError.self) { + try fixture.store.materializationTarget( + at: fixture.root.appendingPathComponent("outside.json")) + } + #expect(throws: CoreError.self) { + try fixture.store.materializationTarget(at: fixture.store.resolvedURL) + } + } + + @Test(arguments: [false, true]) + func ownerExecuteChangesAreExplicitAndRollbackRestoresTheirMode(_ rollback: Bool) throws { + let fixture = try TransactionFixture() + let target = fixture.root.appendingPathComponent("AGENTS.md") + try #require(chmod(target.path, 0o700) == 0) + try fixture.store.withLock { + let registered = try fixture.store.materializationTarget(at: target) + #expect(throws: CoreError.self) { + try fixture.store.preparePrivateMaterialization(registered) + } + let prepared = try fixture.store.preparePrivateMaterialization( + registered, changingAccess: true) + #expect(prepared.accessChange?.before.mode == 0o700) + #expect(prepared.accessChange?.mode == 0o600) + let transaction = FileTransaction(store: fixture.store) { point in + if rollback && point == "entry.0.applied" { + throw CoreError.invalidState("interrupt owner mode change") + } + } + try transaction.replacePrivate(prepared, provider: TestBindings("unused")) { _ in + Data("private-after".utf8) + } + if rollback { + #expect(throws: CoreError.self) { try transaction.commit() } + } else { + try transaction.commit() + } + } + #expect( + try DirectoryHandle(at: fixture.root).accessEvidence("AGENTS.md")?.mode + == (rollback ? 0o700 : 0o600)) + #expect( + try Data(contentsOf: target) == Data((rollback ? "old instructions" : "private-after").utf8)) + } + + @Test func privateStagingPrecedesProviderAndReceiptCommitsWithTheTarget() throws { + let fixture = try TransactionFixture() + let provider = TestBindings("secret-sentinel") + var observed = false + try fixture.store.withLock { + let target = try fixture.store.materializationTarget( + at: fixture.root.appendingPathComponent("AGENTS.md")) + let prepared = try fixture.store.preparePrivateMaterialization(target, changingAccess: true) + let transaction = FileTransaction(store: fixture.store) { point in + if point == "stage.0.writeCreated" { + let journal = try readMaterializationJournal(fixture) + let container = try DirectoryHandle(at: fixture.root).child(journal.containerName(0)) + let name = TransactionSlot.exchanged.name(0) + let info = try #require(try container.info(name)) + #expect(info.st_size == 0) + _ = try container.requirePrivateAccess(name) + #expect(provider.calls == 0) + observed = true + } + } + try transaction.replacePrivate(prepared, bindings: ["value"], provider: provider) { + #expect(!String(reflecting: $0).contains("secret-sentinel")) + return try $0.value(for: "value") + } + #expect(provider.calls == 0) + try transaction.commit() + } + #expect(observed && provider.calls == 1) + let record = try #require( + try fixture.store.materializationReceipts().records.targets["instructions-project/AGENTS.md"]) + #expect( + try Data(contentsOf: fixture.root.appendingPathComponent("AGENTS.md")) + == Data("secret-sentinel".utf8)) + let parent = try DirectoryHandle(at: fixture.root) + _ = try parent.requirePrivateAccess("AGENTS.md", matching: record.access) + _ = try DirectoryHandle(at: fixture.store.directory).requirePrivateAccess( + MaterializationReceipts.fileName) + let receipt = try Data(contentsOf: fixture.store.materializationReceiptURL) + #expect(!String(decoding: receipt, as: UTF8.self).contains("secret-sentinel")) + #expect(try !TransactionJournal.isPresent(in: DirectoryHandle(at: fixture.store.directory))) + } + + @Test(arguments: ["target-mode", "target-acl", "ancestor", "provider", "renderer"]) + func staleAccessAndValueFailuresPublishNothingAndNeverExposeValues(_ kind: String) throws { + let fixture = try TransactionFixture() + let provider = TestBindings("secret-error-sentinel") + let targetURL = fixture.root.appendingPathComponent("AGENTS.md") + try #require(chmod(targetURL.path, 0o644) == 0) + var errorText = "" + try fixture.store.withLock { + let target = try fixture.store.materializationTarget(at: targetURL) + let prepared = try fixture.store.preparePrivateMaterialization(target, changingAccess: true) + let transaction = FileTransaction(store: fixture.store) + try transaction.replacePrivate(prepared, bindings: ["value"], provider: provider) { values in + if kind == "renderer" { throw CoreError.invalidState("secret-error-sentinel") } + return try values.value(for: "value") + } + switch kind { + case "target-mode": try #require(chmod(targetURL.path, 0o640) == 0) + case "target-acl": try setFixtureMetadata(targetURL, mode: 0o644, value: Data()) + case "ancestor": try #require(chmod(fixture.root.path, 0o775) == 0) + case "provider": provider.fails = true + default: break + } + do { + try transaction.commit() + Issue.record("expected private materialization refusal") + } catch { errorText = String(describing: error) } + #expect(!errorText.contains("secret-error-sentinel")) + } + #expect(!errorText.isEmpty) + #expect(try Data(contentsOf: targetURL) == Data("old instructions".utf8)) + #expect(!FileManager.default.fileExists(atPath: fixture.store.materializationReceiptURL.path)) + #expect(provider.calls == (["provider", "renderer"].contains(kind) ? 1 : 0)) + } + + @Test func ordinaryReplacementAndDeletionRetainSensitivePreimageClassification() throws { + let fixture = try TransactionFixture() + try installPrivate("private-before", in: fixture) + let target = fixture.root.appendingPathComponent("AGENTS.md") + for deleting in [false, true] { + if deleting { try installPrivate("private-again", in: fixture) } + var inspected = false + try fixture.store.withLock { + let transaction = FileTransaction(store: fixture.store) { point in + if point == "entry.0.ready" { + let journal = try readMaterializationJournal(fixture) + #expect(journal.entries[0].security.preimage == .privateMaterialization) + #expect(journal.entries.count == 2) + inspected = true + } + } + if deleting { + try transaction.delete(target) + } else { + try transaction.replace(target, with: .data(Data("ordinary".utf8))) + } + try transaction.commit() + } + #expect(inspected) + #expect(try fixture.store.materializationReceipts().records.targets.isEmpty) + if !deleting { + #expect(try Data(contentsOf: target) == Data("ordinary".utf8)) + #expect(try DirectoryHandle(at: fixture.root).accessEvidence("AGENTS.md")?.mode == 0o600) + } else { + #expect(!FileManager.default.fileExists(atPath: target.path)) + } + } + } + + @Test(arguments: [ + "containers.identified", "stage.0.writeCreated", "stage.0.constructed", "entry.0.ready", + "publish.0.exchanged", "entry.0.applied", "entry.1.applied", "journal.committed", + "disposal.intent", "disposal.0.removed", + ]) + func killedMaterializationRecoversWithoutCallingProvider(_ point: String) throws { + let fixture = try TransactionFixture() + try installPrivate("private-before", in: fixture) + let beforeReceipt = try Data(contentsOf: fixture.store.materializationReceiptURL) + let child = try stateTestProcess(root: fixture.root, arguments: ["private-install", point]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let called = fixture.root.appendingPathComponent("provider-called") + if FileManager.default.fileExists(atPath: called.path) { + try FileManager.default.removeItem(at: called) + } else { + #expect(["containers.identified", "stage.0.writeCreated"].contains(point)) + } + let recovery = try stateTestProcess( + root: fixture.root, arguments: ["private-recover", "never"]) + defer { terminateProcess(recovery) } + try ProcessWait.exit(recovery, root: fixture.root) + #expect(recovery.terminationStatus == 0) + #expect( + !FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("provider-called").path)) + let committed = point == "journal.committed" || point.hasPrefix("disposal.") + #expect( + try Data(contentsOf: fixture.root.appendingPathComponent("AGENTS.md")) + == Data((committed ? "private-after" : "private-before").utf8)) + if !committed { + #expect(try Data(contentsOf: fixture.store.materializationReceiptURL) == beforeReceipt) + } + _ = try fixture.store.materializationReceipts() + #expect(try !TransactionJournal.isPresent(in: DirectoryHandle(at: fixture.store.directory))) + } + + @Test func aNewPrivateTargetRollsBackWithoutLeavingAReceipt() throws { + let fixture = try TransactionFixture() + let target = fixture.root.appendingPathComponent("GEMINI.md") + try fixture.store.withLock { + let prepared = try fixture.store.preparePrivateMaterialization( + fixture.store.materializationTarget(at: target)) + #expect(prepared.accessChange == nil) + let transaction = FileTransaction(store: fixture.store) { point in + if point == "entry.0.applied" { + throw CoreError.invalidState("interrupt new private target") + } + } + try transaction.replacePrivate(prepared, provider: TestBindings("unused")) { _ in + Data("private-new".utf8) + } + #expect(throws: CoreError.self) { try transaction.commit() } + } + #expect(!FileManager.default.fileExists(atPath: target.path)) + #expect(!FileManager.default.fileExists(atPath: fixture.store.materializationReceiptURL.path)) + #expect(try !TransactionJournal.isPresent(in: DirectoryHandle(at: fixture.store.directory))) + } + + @Test func changedStagingAccessStopsBeforeResolvingBindings() throws { + let fixture = try TransactionFixture() + let provider = TestBindings("must-not-be-read") + #expect(throws: CoreError.self) { + try fixture.store.withLock { + let prepared = try fixture.store.preparePrivateMaterialization( + fixture.store.materializationTarget(at: fixture.root.appendingPathComponent("AGENTS.md")), + changingAccess: true) + let transaction = FileTransaction(store: fixture.store) { point in + if point == "stage.0.writeCreated" { + let journal = try readMaterializationJournal(fixture) + let file = fixture.root.appendingPathComponent(journal.containerName(0)) + .appendingPathComponent("entry.0.exchanged") + try #require(chmod(file.path, 0o644) == 0) + } + } + try transaction.replacePrivate(prepared, bindings: ["value"], provider: provider) { + try $0.value(for: "value") + } + try transaction.commit() + } + } + #expect(provider.calls == 0) + #expect( + try Data(contentsOf: fixture.root.appendingPathComponent("AGENTS.md")) + == Data("old instructions".utf8)) + } + + @Test(arguments: [ + "restore.1.exchanged", "restore.0.exchanged", "journal.rolledBack", "disposal.0.removed", + ]) + func recoveryCanBeKilledAndRepeatedWithoutResolvingBindings(_ point: String) throws { + let fixture = try TransactionFixture() + try installPrivate("private-before", in: fixture) + let originalReceipt = try Data(contentsOf: fixture.store.materializationReceiptURL) + let child = try stateTestProcess( + root: fixture.root, arguments: ["private-install", "entry.1.applied"]) + defer { terminateProcess(child) } + let marker = fixture.root.appendingPathComponent("ready") + try ProcessWait.marker(marker, child: child, root: fixture.root) + terminateProcess(child) + try FileManager.default.removeItem(at: marker) + try FileManager.default.removeItem(at: fixture.root.appendingPathComponent("provider-called")) + let first = try stateTestProcess(root: fixture.root, arguments: ["private-recover", point]) + defer { terminateProcess(first) } + try ProcessWait.marker(marker, child: first, root: fixture.root) + terminateProcess(first) + let second = try stateTestProcess(root: fixture.root, arguments: ["private-recover", "never"]) + defer { terminateProcess(second) } + try ProcessWait.exit(second, root: fixture.root) + #expect(second.terminationStatus == 0) + #expect( + try Data(contentsOf: fixture.root.appendingPathComponent("AGENTS.md")) + == Data("private-before".utf8)) + #expect(try Data(contentsOf: fixture.store.materializationReceiptURL) == originalReceipt) + #expect( + !FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("provider-called").path)) + #expect(try !TransactionJournal.isPresent(in: DirectoryHandle(at: fixture.store.directory))) + } + + @Test(arguments: ["target", "backup", "ancestor", "restore-race"]) + func unsafeSensitiveRecoveryRetainsJournalAndPrivateEvidence(_ change: String) throws { + let fixture = try TransactionFixture() + try installPrivate("private-before", in: fixture) + let child = try stateTestProcess( + root: fixture.root, arguments: ["private-install", "entry.0.applied"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let journal = try readMaterializationJournal(fixture) + let backup = fixture.root.appendingPathComponent(journal.containerName(0)) + .appendingPathComponent("entry.0.exchanged") + if change == "target" { + try #require(chmod(fixture.root.appendingPathComponent("AGENTS.md").path, 0o644) == 0) + } + if change == "backup" { try #require(chmod(backup.path, 0o644) == 0) } + if change == "ancestor" { try #require(chmod(fixture.root.path, 0o775) == 0) } + #expect(throws: (any Error).self) { + try fixture.store.withLock( + checkpoint: { point in + if change == "restore-race" && point == "restore.0.validated" { + try #require(chmod(backup.path, 0o644) == 0) + } + }, {}) + } + #expect( + FileManager.default.fileExists( + atPath: fixture.store.directory.appendingPathComponent(TransactionJournal.fileName).path)) + #expect(try Data(contentsOf: backup) == Data("private-before".utf8)) + #expect( + try Data(contentsOf: fixture.root.appendingPathComponent("AGENTS.md")) + == Data("private-after".utf8)) + } + + @Test func receiptInspectionAndExpectedGenerationsDoNotExposeValues() throws { + let fixture = try TransactionFixture() + try installPrivate("receipt-secret-sentinel", in: fixture) + let target = try fixture.store.materializationTarget( + at: fixture.root.appendingPathComponent("AGENTS.md")) + let first = try #require(try fixture.store.materializationReceipt(for: target)) + let prepared = try fixture.store.preparePrivateMaterialization( + target, expecting: first.generation) + let same = try fixture.store.preparePrivateMaterialization(target, expecting: first.generation) + #expect(try prepared.accessFingerprint() == same.accessFingerprint()) + #expect(!String(reflecting: first).contains("receipt-secret-sentinel")) + try installPrivate("rotated-private-value", in: fixture) + #expect(throws: CoreError.self) { + try fixture.store.preparePrivateMaterialization(target, expecting: first.generation) + } + let second = try #require(try fixture.store.materializationReceipt(for: target)) + #expect(second.generation != first.generation) + try FileManager.default.removeItem(at: fixture.store.materializationReceiptURL) + #expect(throws: CoreError.self) { + try fixture.store.preparePrivateMaterialization( + target, requiringReceiptForExistingTarget: true) + } + } + + @Test func receiptWritesAreReservedAcrossLogicalAndPhysicalRootAliases() throws { + let fixture = try TransactionFixture() + try installPrivate("private-before", in: fixture) + let before = try Data(contentsOf: fixture.store.materializationReceiptURL) + let alias = fixture.root.appendingPathComponent("project-alias") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: fixture.root) + let aliased = StateStore( + scope: .project, environment: RuntimeEnvironment(projectDirectory: alias)) + let transaction = FileTransaction(store: aliased) + #expect(throws: CoreError.self) { + try transaction.replace( + fixture.store.materializationReceiptURL.resolvingSymlinksInPath(), with: .data(Data())) + } + #expect(try Data(contentsOf: fixture.store.materializationReceiptURL) == before) + } + + @Test func anAbsentRecordedTargetCanBeRestoredAndItsReceiptCanBeRemoved() throws { + let fixture = try TransactionFixture() + try installPrivate("private-before", in: fixture) + let target = fixture.root.appendingPathComponent("AGENTS.md") + try FileManager.default.removeItem(at: target) + try fixture.store.withLock { + let prepared = try fixture.store.preparePrivateMaterialization( + fixture.store.materializationTarget(at: target), requiringReceiptForExistingTarget: true) + let transaction = FileTransaction(store: fixture.store) + try transaction.replacePrivate( + prepared, bindings: ["value"], provider: TestBindings("restored-private") + ) { try $0.value(for: "value") } + try transaction.commit() + } + #expect(try Data(contentsOf: target) == Data("restored-private".utf8)) + try FileManager.default.removeItem(at: target) + try fixture.store.withLock { + let transaction = FileTransaction(store: fixture.store) + try transaction.delete(target) + try transaction.commit() + } + #expect(try fixture.store.materializationReceipts().records.targets.isEmpty) + } + + @Test func lastPublicationCheckCannotCopyChangedTargetAccessOntoSecretBytes() throws { + let fixture = try TransactionFixture() + let target = fixture.root.appendingPathComponent("AGENTS.md") + try #require(chmod(target.path, 0o644) == 0) + #expect(throws: CoreError.self) { + try fixture.store.withLock { + let prepared = try fixture.store.preparePrivateMaterialization( + fixture.store.materializationTarget(at: target), changingAccess: true) + let transaction = FileTransaction(store: fixture.store) { point in + if point == "publish.0.validated" { try #require(chmod(target.path, 0o640) == 0) } + } + try transaction.replacePrivate( + prepared, bindings: ["value"], provider: TestBindings("unpublished-secret") + ) { try $0.value(for: "value") } + try transaction.commit() + } + } + #expect(try Data(contentsOf: target) == Data("old instructions".utf8)) + let journal = try readMaterializationJournal(fixture) + let container = try DirectoryHandle(at: fixture.root).child(journal.containerName(0)) + _ = try container.requirePrivateAccess("entry.0.exchanged") + #expect(try container.read("entry.0.exchanged") == Data("unpublished-secret".utf8)) + } + + @Test(arguments: ["security", "preimageAccess", "ancestry", "version"]) + func missingSecurityEvidenceCannotRecoverOrMutateObjects(_ field: String) throws { + let fixture = try TransactionFixture() + try installPrivate("private-before", in: fixture) + let child = try stateTestProcess( + root: fixture.root, arguments: ["private-install", "entry.0.applied"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let path = fixture.store.directory.appendingPathComponent(TransactionJournal.fileName) + var value = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: path)) as? [String: Any]) + if field == "version" { + value["version"] = 1 + } else { + var entries = try #require(value["entries"] as? [[String: Any]]) + if field == "security" { + entries[0].removeValue(forKey: field) + } else { + var security = try #require(entries[0]["security"] as? [String: Any]) + security.removeValue(forKey: field) + entries[0]["security"] = security + } + value["entries"] = entries + } + try JSONSerialization.data(withJSONObject: value).write(to: path) + let before = try FileSnapshot.read(at: fixture.root) + #expect(throws: (any Error).self) { try fixture.store.withLock {} } + #expect(try FileSnapshot.read(at: fixture.root) == before) + } +} + +private final class TestBindings: RuntimeBindingProvider { + let value: String + var calls = 0 + var fails = false + init(_ value: String) { self.value = value } + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + calls += 1 + if fails { throw CoreError.invalidState(value) } + return Data(value.utf8) + } +} + +private func installPrivate(_ value: String, in fixture: TransactionFixture) throws { + try fixture.store.withLock { + let target = try fixture.store.materializationTarget( + at: fixture.root.appendingPathComponent("AGENTS.md")) + let prepared = try fixture.store.preparePrivateMaterialization(target, changingAccess: true) + let transaction = FileTransaction(store: fixture.store) + try transaction.replacePrivate(prepared, bindings: ["value"], provider: TestBindings(value)) { + try $0.value(for: "value") + } + try transaction.commit() + } +} + +private func readMaterializationJournal(_ fixture: TransactionFixture) throws -> TransactionJournal +{ + try StateStore.decode( + Data(contentsOf: fixture.store.directory.appendingPathComponent(TransactionJournal.fileName)), + as: TransactionJournal.self) +} diff --git a/Tests/StateTestProcess/PrivateMaterializationProbe.swift b/Tests/StateTestProcess/PrivateMaterializationProbe.swift new file mode 100644 index 0000000..6752d57 --- /dev/null +++ b/Tests/StateTestProcess/PrivateMaterializationProbe.swift @@ -0,0 +1,31 @@ +import AgentsCore +import Foundation + +func privateMaterializationProbe( + _ command: String, store: StateStore, checkpoint: @escaping (String) throws -> Void +) throws { + let root = store.environment.projectDirectory + if command == "private-recover" { + do { try store.withLock(checkpoint: checkpoint, {}) } catch CoreError.transactionRecovered {} + return + } + try store.withLock { + let target = try store.materializationTarget(at: root.appendingPathComponent("AGENTS.md")) + let prepared = try store.preparePrivateMaterialization(target, changingAccess: true) + let transaction = FileTransaction(store: store, checkpoint: checkpoint) + try transaction.replacePrivate( + prepared, bindings: ["value"], provider: ProbeBindings(root: root) + ) { + try $0.value(for: "value") + } + try transaction.commit() + } +} + +private struct ProbeBindings: RuntimeBindingProvider { + let root: URL + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + try Data().write(to: root.appendingPathComponent("provider-called")) + return Data("private-after".utf8) + } +} diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 454913a..72a544b 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -53,6 +53,8 @@ func signalContention() throws { } if arguments[2].hasPrefix("ledger-") { try ledgerProbe(arguments[2], store: store) +} else if arguments[2].hasPrefix("private-") { + try privateMaterializationProbe(arguments[2], store: store, checkpoint: { try stop($0) }) } else if arguments[2] == "git-environment" { let before = ProcessInfo.processInfo.environment let cache = SourceCache(store: store) From 50c9c62fcbee9cd32ded1679d54c3539ea207b67 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 06:07:19 +0800 Subject: [PATCH 050/171] docs: archive superseded manifest proposal --- Documentation/{Proposals => Archive}/AgentsManifest.md | 0 Documentation/Archive/README.md | 3 ++- Documentation/Decisions/ConfigurationApplication.md | 2 +- Documentation/Proposals/README.md | 4 ---- 4 files changed, 3 insertions(+), 6 deletions(-) rename Documentation/{Proposals => Archive}/AgentsManifest.md (100%) diff --git a/Documentation/Proposals/AgentsManifest.md b/Documentation/Archive/AgentsManifest.md similarity index 100% rename from Documentation/Proposals/AgentsManifest.md rename to Documentation/Archive/AgentsManifest.md diff --git a/Documentation/Archive/README.md b/Documentation/Archive/README.md index dca5aa5..06aa6bd 100644 --- a/Documentation/Archive/README.md +++ b/Documentation/Archive/README.md @@ -3,7 +3,8 @@ This directory holds retired or superseded material that remains useful for historical reference. -There is no archived material yet. +- [Agents Manifest Contract](AgentsManifest.md) — original frontend and + component-management design proposal. ## Placement diff --git a/Documentation/Decisions/ConfigurationApplication.md b/Documentation/Decisions/ConfigurationApplication.md index 58502a5..46a39e9 100644 --- a/Documentation/Decisions/ConfigurationApplication.md +++ b/Documentation/Decisions/ConfigurationApplication.md @@ -50,4 +50,4 @@ or enabled the component. - [Agent Components and Adapters](AgentComponents.md) - [Swift Manifest](SwiftManifest.md) -- [Agents Manifest Contract](../Proposals/AgentsManifest.md) +- [Agents Manifest Contract](../Archive/AgentsManifest.md) diff --git a/Documentation/Proposals/README.md b/Documentation/Proposals/README.md index f20bf14..f6896fa 100644 --- a/Documentation/Proposals/README.md +++ b/Documentation/Proposals/README.md @@ -4,10 +4,6 @@ This directory holds design-in-progress documents and unresolved alternatives. ## Active Proposals -- [Agents Manifest Contract](AgentsManifest.md) — owner: showxu; historical - frontend design superseded by [YAML Manifest](../Decisions/YAMLManifest.md). - Remaining component-management work follows its current architecture owners. - - `AgentInstructions.md`: skills and instructions as two kinds of one model, the declaration and lock formats, the command tree, the rules for writing instruction files, and watch as a subscription. From 24e91486dacb5ef77fee2fe9eb6740ee52b7a1a7 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 06:24:27 +0800 Subject: [PATCH 051/171] feat(core): edit owned native configuration regions --- Documentation/Architecture/NativeDocuments.md | 98 + Documentation/Architecture/Package.md | 14 + Documentation/Architecture/README.md | 5 +- Package.swift | 16 + Sources/NativeDocuments/JSONParser.swift | 190 + Sources/NativeDocuments/Model.swift | 204 + Sources/NativeDocuments/NativeDocument.swift | 499 ++ Sources/NativeDocuments/PatchBuilder.swift | 509 ++ Sources/NativeDocuments/Semantics.swift | 188 + Sources/NativeDocuments/TOMLIndex.swift | 278 + Sources/TOMLSemantics/DateTime.swift | 424 + Sources/TOMLSemantics/LICENSE | 9 + Sources/TOMLSemantics/PATCHES.md | 39 + Sources/TOMLSemantics/Parsing/Constants.swift | 109 + .../TOMLSemantics/Parsing/Parser+Finish.swift | 24 + Sources/TOMLSemantics/Parsing/Parser.swift | 2679 +++++++ .../TOMLSemantics/Parsing/TOMLDocument.swift | 186 + Sources/TOMLSemantics/Parsing/Token.swift | 27 + Sources/TOMLSemantics/SemanticBudget.swift | 93 + Sources/TOMLSemantics/SemanticDocument.swift | 174 + Sources/TOMLSemantics/TOMLError.swift | 147 + Sources/TOMLSemantics/TOMLKey.swift | 33 + Sources/TOMLSemantics/provenance.json | 48 + Sources/TOMLSemantics/upstream.patch | 6975 +++++++++++++++++ Sources/TreeSitterTOML/LICENSE | 21 + Sources/TreeSitterTOML/include/toml.h | 16 + Sources/TreeSitterTOML/parser.c | 4739 +++++++++++ Sources/TreeSitterTOML/provenance.json | 26 + Sources/TreeSitterTOML/scanner.c | 82 + Sources/TreeSitterTOML/tree_sitter/parser.h | 266 + .../NativeDocumentTests.swift | 571 ++ .../NativeDocumentsTests/SemanticTests.swift | 70 + 32 files changed, 18758 insertions(+), 1 deletion(-) create mode 100644 Documentation/Architecture/NativeDocuments.md create mode 100644 Sources/NativeDocuments/JSONParser.swift create mode 100644 Sources/NativeDocuments/Model.swift create mode 100644 Sources/NativeDocuments/NativeDocument.swift create mode 100644 Sources/NativeDocuments/PatchBuilder.swift create mode 100644 Sources/NativeDocuments/Semantics.swift create mode 100644 Sources/NativeDocuments/TOMLIndex.swift create mode 100644 Sources/TOMLSemantics/DateTime.swift create mode 100644 Sources/TOMLSemantics/LICENSE create mode 100644 Sources/TOMLSemantics/PATCHES.md create mode 100644 Sources/TOMLSemantics/Parsing/Constants.swift create mode 100644 Sources/TOMLSemantics/Parsing/Parser+Finish.swift create mode 100644 Sources/TOMLSemantics/Parsing/Parser.swift create mode 100644 Sources/TOMLSemantics/Parsing/TOMLDocument.swift create mode 100644 Sources/TOMLSemantics/Parsing/Token.swift create mode 100644 Sources/TOMLSemantics/SemanticBudget.swift create mode 100644 Sources/TOMLSemantics/SemanticDocument.swift create mode 100644 Sources/TOMLSemantics/TOMLError.swift create mode 100644 Sources/TOMLSemantics/TOMLKey.swift create mode 100644 Sources/TOMLSemantics/provenance.json create mode 100644 Sources/TOMLSemantics/upstream.patch create mode 100644 Sources/TreeSitterTOML/LICENSE create mode 100644 Sources/TreeSitterTOML/include/toml.h create mode 100644 Sources/TreeSitterTOML/parser.c create mode 100644 Sources/TreeSitterTOML/provenance.json create mode 100644 Sources/TreeSitterTOML/scanner.c create mode 100644 Sources/TreeSitterTOML/tree_sitter/parser.h create mode 100644 Tests/NativeDocumentsTests/NativeDocumentTests.swift create mode 100644 Tests/NativeDocumentsTests/SemanticTests.swift diff --git a/Documentation/Architecture/NativeDocuments.md b/Documentation/Architecture/NativeDocuments.md new file mode 100644 index 0000000..487b991 --- /dev/null +++ b/Documentation/Architecture/NativeDocuments.md @@ -0,0 +1,98 @@ +# Native Documents + +`NativeDocuments` is a package-only byte inspection and regional editing layer. +It receives `Data`, a fixed JSON/JSONC/TOML format, an operation budget and typed +region intents. Adapters own client dialects and ownership decisions. Filesystem +access, routes, secrets, locks, freshness, transactions and publication stay with +their existing owners. + +## Inspection and evidence + +`NativeDocument` preserves the supplied bytes. Regions consist of exact decoded +keys and array occurrence evidence. Key and string identity uses decoded UTF-8 +sequences. Canonically equivalent Unicode strings remain distinct native values. +Objects retain ordered entries; projecting a region that Core dictionaries cannot +represent returns no Core value. TOML date/time and non-finite numbers likewise +remain native atoms, retaining their lexemes. + +`read` returns an optional package-only observation with a Core value when +representable, native kind, raw numeric lexeme, explicit projection failure, +ephemeral byte ranges, exact structural fingerprint +and array occurrence evidence. Observations and prepared bytes can contain +materialized secrets; they are neither preview records nor serialized ledger +models. Diagnostics use fixed codes and byte ranges, without source excerpts. + +A put requires an absent expectation or matching owned observation. Removal +requires matching owned evidence. Empty object-container removal requires explicit +caller-supplied creation evidence and fails if comments must remain. An existing +unmanaged region is never adopted by matching a desired value. Missing object +ancestors can be created; the preparation reports created container regions. + +Stable array IDs are exact string fields and must be unique. Without an ID, +observations retain a structural fingerprint, ordinal and neighboring evidence. +Duplicate content is rejected when it cannot be uniquely identified; an ordinal +alone does not authorize a match. Individual occurrence edits preserve other +array entries and their order. An absent terminal occurrence with a stable ID can +append an exactly matching object. Owned array-of-table sets diff their entries +and append complete new occurrences; removing the final occurrence retains an +explicit empty array. New child tables bind only where their native scope can be +proved. + +## Parsers and edits + +JSON has one root and preserves raw numeric lexemes. JSONC comments and trailing +commas are independent fixed-dialect capabilities. The scanner validates string +escapes/surrogates and decoded duplicate keys. A leading UTF-8 BOM is preserved. + +TOML uses the fixed grammar in `TreeSitterTOML` with the existing formal runtime +dependency for locations. `TOMLSemantics` contains the licensed parser/validator +subset from pinned TOMLDecoder, with exact key identity, lexical scalar +classification, complete lazy validation, actual EOF checks and cooperative +resource admission. Each target records upstream file hashes and patch details. +The semantic parser remains the validity owner when the older CST grammar +cannot locate legal TOML syntax; such documents can be inspected and return +`syntaxNotLocated` for edits. No error recovery tree is used for editing. + +The TOML index resolves quoted/dotted keys, inline tables and array-of-table +headers in source order. Child table headers bind to the latest array table. +Scalar updates replace only the value span. Object updates diff members; +removal uses individual owned entries and headers across table blocks. Inline +punctuation is located independently of comments. Structural edits with ambiguous +trivia or scope are refused. New members use their containing table block or a +precise new table declaration, preserving subsequent table scope. + +Every preparation checks overlap and ownership, builds the complete expected +native tree, constructs nonoverlapping patches, copies every unselected byte +segment unchanged and reparses the complete candidate. Only a candidate equal to +the expected tree is returned. No-op intent returns the original bytes, including +escape spelling, newline style, comments and key order. Multiple internal drafts +are private; failure returns no partially prepared result. + +JSON integer/decimal declarations can encode the same numeric token. TOML +integer-looking decimal declarations append `e0` to retain native float kind. +Encoding and comparison preserve exact decimal text without a Double round trip. +Core projection removes TOML digit separators and a leading plus while retaining +the original numeric token separately in the observation. +Declarations and ledger identity remain with their owners, independently of +native byte no-ops. + +## Budget and cancellation + +`NativeDocumentBudget` is one serial operation-scoped mutable reference supplied +by the caller. Input admission, semantic construction, node/depth checks, decoded +storage, scans/key comparisons, reads, fingerprints, rendering, patches, drafts +and reparses consume that reference. No stage resets it. Limits are explicit +caller inputs rather than copies of YAML or ledger policy. + +Before entering the C parser, the entire input must fit the caller's maximum +uninterrupted-byte envelope. This covers strings, keys, skipped comments and +whitespace alike. The fixed grammar also reserves a conservative logical node +envelope of four nodes per input byte plus the document root before CST entry; +traversal and progress callbacks consume additional work. The progress callback +checks the same cancellation source and budget between parser work intervals. +All parser/tree handles are synchronously released on every exit. + +These are conservative logical admission units and cooperative cancellation, +not exact heap/RSS quotas or hard real-time deadlines. A caller requiring a +smaller uninterrupted interval must supply a smaller envelope. There is no +background timeout task or filesystem provider in this layer. diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 25e554d..2505c18 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -15,6 +15,9 @@ AgentsSkills → AgentsCore, AgentsManifest, Yams AgentsInstructions → AgentsCore, AgentsManifest, Markdown Components → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions AgentsUpdates → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions +NativeDocuments → AgentsCore, TOMLSemantics, TreeSitterTOML, TreeSitter +TOMLSemantics → Foundation +TreeSitterTOML → (vendored C grammar) AgentsCore → CPlatform, Crypto ``` @@ -22,6 +25,17 @@ AgentsCore → CPlatform, Crypto parser/scanner and headers, with upstream license and per-file provenance. The runtime is a normal SwiftPM dependency. Consumers never receive parser types. +## NativeDocuments + +`NativeDocuments` inspects provided JSON, JSONC and TOML bytes and prepares +ownership-checked regional changes. It preserves no-op bytes, unmanaged content, +comments and exact native semantics, and reparses each complete candidate. +`TOMLSemantics` owns bounded standard TOML validation; `TreeSitterTOML` supplies +pinned concrete locations through the existing Tree-sitter runtime dependency. +These targets are package-only, with no library product or filesystem provider. +See [native documents](NativeDocuments.md) for typed regions, observations, +creation evidence, read-only syntax and cumulative operation budgets. + ## AgentsManifest The frontend reads `.agent/agents.yaml` or the user scope’s `agents.yaml` and diff --git a/Documentation/Architecture/README.md b/Documentation/Architecture/README.md index 5d66cda..27a4af1 100644 --- a/Documentation/Architecture/README.md +++ b/Documentation/Architecture/README.md @@ -13,7 +13,9 @@ text transformations. It depends on `AgentsCore` for sources and state, `AgentsManifest` for the declaration, and `swift-markdown` for CommonMark structure. `Components` links exact source exports through package readers above those modules. `AgentsUpdates` composes the existing skill and instruction lifecycle. Tests -follow those module boundaries. +follow those module boundaries. `NativeDocuments` supplies package-only native +JSON/JSONC/TOML inspection and ownership-checked byte edits, backed by the +internal TOML semantic validator and pinned CST grammar. ## Belongs Here @@ -32,6 +34,7 @@ follow those module boundaries. ## Current Files - `Package.md`: library products, module boundaries, and public workflows +- `NativeDocuments.md`: native byte inspection, ownership evidence and regional edits - `State.md`: declaration, resolved state, source cache and installation invariants - `Instructions.md`: instruction discovery, targets, lifecycle, prompts and diagnostics - `Watch.md`: subscription operations, upstream comparisons and seen-state retention diff --git a/Package.swift b/Package.swift index 3128a5b..b0f6fd2 100644 --- a/Package.swift +++ b/Package.swift @@ -22,6 +22,22 @@ let package = Package( .package(url: "https://github.com/tree-sitter/tree-sitter", exact: "0.25.10"), ], targets: [ + .target( + name: "TOMLSemantics", + exclude: ["LICENSE", "provenance.json", "PATCHES.md", "upstream.patch"]), + .target( + name: "TreeSitterTOML", exclude: ["LICENSE", "provenance.json"], + sources: ["parser.c", "scanner.c"], publicHeadersPath: "include", + cSettings: [.headerSearchPath(".")]), + .target( + name: "NativeDocuments", + dependencies: [ + "AgentsCore", "TOMLSemantics", "TreeSitterTOML", + .product(name: "TreeSitter", package: "tree-sitter"), + ]), + .testTarget( + name: "NativeDocumentsTests", + dependencies: ["NativeDocuments", "TOMLSemantics", "AgentsCore"]), .target(name: "CPlatform"), .target( name: "TreeSitterYAML", exclude: ["LICENSE", "provenance.json"], diff --git a/Sources/NativeDocuments/JSONParser.swift b/Sources/NativeDocuments/JSONParser.swift new file mode 100644 index 0000000..18f6908 --- /dev/null +++ b/Sources/NativeDocuments/JSONParser.swift @@ -0,0 +1,190 @@ +import Foundation + +struct JSONParser { + let bytes: [UInt8] + let format: NativeDocumentFormat + let budget: NativeDocumentBudget + var i: Int = 0 + var comments: [Range] = [] + var allowsComments: Bool { if case .jsonc = format { true } else { false } } + var trailing: Bool { if case .jsonc(let allowed) = format { allowed } else { false } } + + mutating func parse() throws -> Node { + if bytes.starts(with: [0xef, 0xbb, 0xbf]) { i = 3 } + try trivia() + let node = try value(depth: 0) + try trivia() + guard i == bytes.count else { throw invalid() } + return node + } + func invalid() -> NativeDocumentError { + .invalidDocument(code: "jsonSyntax", range: i.. (String, Range) { + let start = i + guard i < bytes.count, bytes[i] == 34 else { throw invalid() } + i += 1 + while i < bytes.count { + try budget.step() + let ch = bytes[i] + i += 1 + if ch == 34 { + try budget.allocate(i - start, stage: "decoded string") + let data = Data(bytes[start.. Node { + try budget.node(depth: depth) + try trivia() + guard i < bytes.count else { throw invalid() } + let start = i + switch bytes[i] { + case 123, 91: + let object = bytes[i] == 123 + let close: UInt8 = object ? 125 : 93 + let node = Node(object ? .object : .array) + node.inline = true + i += 1 + try trivia() + if i < bytes.count && bytes[i] == close { + i += 1 + node.range = start..? + if object { + let parsedKey = try string() + key = parsedKey.0 + keyRange = parsedKey.1 + guard try node.member(key, budget: budget) == nil else { + throw NativeDocumentError.invalidDocument(code: "duplicateKey", range: entryStart..? + if i < bytes.count && bytes[i] == 44 { + comma = i..= 49 && bytes[i] <= 57 else { throw invalid() } + try digits() + } + var decimal = false + if i < bytes.count && bytes[i] == 46 { + decimal = true + i += 1 + try requiredDigits() + } + if i < bytes.count && [69, 101].contains(bytes[i]) { + decimal = true + i += 1 + if i < bytes.count && [43, 45].contains(bytes[i]) { i += 1 } + try requiredDigits() + } + try budget.allocate(i - start, stage: "numeric lexeme") + let raw = String(decoding: bytes[start..= 48 && bytes[i] <= 57 { + try budget.step() + i += 1 + } + } + mutating func requiredDigits() throws { + let start = i + try digits() + guard i > start else { throw invalid() } + } +} diff --git a/Sources/NativeDocuments/Model.swift b/Sources/NativeDocuments/Model.swift new file mode 100644 index 0000000..edc5c7b --- /dev/null +++ b/Sources/NativeDocuments/Model.swift @@ -0,0 +1,204 @@ +import AgentsCore +import Foundation +import TOMLSemantics + +package enum NativeDocumentFormat: Equatable { + case json + case jsonc(trailingCommas: Bool) + case toml +} + +package enum NativeDocumentError: Error, CustomStringConvertible { + package var description: String { + switch self { + case .invalidDocument(let code, _): "Invalid native document (\(code))." + case .ownershipMismatch: "Native region ownership does not match." + case .unsupportedEdit(let reason, _, _): "Unsupported native edit (\(reason))." + case .unrepresentableValue: "Value is not representable in the native format." + case .budgetExceeded(let stage): "Native document budget exceeded (\(stage))." + case .cancelled: "Native document operation cancelled." + } + } + case invalidDocument(code: String, range: Range?) + case ownershipMismatch(NativeRegion) + case unsupportedEdit(NativeUnsupportedEdit, NativeRegion, [Range]) + case unrepresentableValue(NativeDocumentFormat, NativeRegion, String) + case budgetExceeded(String) + case cancelled +} + +package enum NativeUnsupportedEdit { + case syntaxNotLocated, ambiguousOccurrence, ambiguousTrivia, wouldRewriteUnownedStructure, + overlappingEdits +} + +package struct NativeRegion: Equatable { + package let steps: [NativePathStep] + package init(_ steps: [NativePathStep]) { self.steps = steps } + package init(keys: [String]) { steps = keys.map(NativePathStep.key) } + package static func == (lhs: Self, rhs: Self) -> Bool { lhs.steps == rhs.steps } +} + +package enum NativePathStep: Equatable { + case key(String) + case occurrence(NativeOccurrenceEvidence) + package static func == (a: Self, b: Self) -> Bool { + switch (a, b) { + case (.key(let x), .key(let y)): return x.utf8.elementsEqual(y.utf8) + case (.occurrence(let x), .occurrence(let y)): return x == y + default: return false + } + } +} + +package struct NativeOccurrenceEvidence: Equatable { + package let idKey: String? + package let id: String? + let snapshot: Data? + let ordinal: Int? + let previous: Data? + let next: Data? + package init(idKey: String, id: String) { + self.idKey = idKey + self.id = id + snapshot = nil + ordinal = nil + previous = nil + next = nil + } + init(snapshot: Data, ordinal: Int, previous: Data?, next: Data?) { + idKey = nil + id = nil + self.snapshot = snapshot + self.ordinal = ordinal + self.previous = previous + self.next = next + } + package static func == (a: Self, b: Self) -> Bool { + func same(_ x: String?, _ y: String?) -> Bool { + switch (x, y) { + case (.some(let x), .some(let y)): x.utf8.elementsEqual(y.utf8) + case (.none, .none): true + default: false + } + } + return same(a.idKey, b.idKey) && same(a.id, b.id) && a.snapshot == b.snapshot + && a.ordinal == b.ordinal && a.previous == b.previous && a.next == b.next + } +} + +package enum NativeProjectionFailure { + case canonicalKeyCollision + case nativeType(String) +} + +package struct NativeObservation { + package let region: NativeRegion + package let value: NativeValue? + package let nativeKind: String + package let numericLexeme: String? + package let projectionFailure: NativeProjectionFailure? + package let valueRange: Range? + package let entryRanges: [Range] + package let occurrences: [NativeOccurrenceEvidence] + let fingerprint: Data +} + +package enum NativeExpectedRegion { + case absent + case owned(NativeObservation) + /// The caller supplies creation evidence; only an empty, trivia-free container can be removed. + case createdContainer(NativeObservation) +} + +package enum NativeRegionEdit { + case put(region: NativeRegion, expected: NativeExpectedRegion, value: NativeValue) + case remove(region: NativeRegion, expected: NativeExpectedRegion) + var region: NativeRegion { + switch self { + case .put(let r, _, _), .remove(let r, _): r + } + } + var expected: NativeExpectedRegion { + switch self { + case .put(_, let e, _), .remove(_, let e): e + } + } +} + +package struct PreparedNativeChange { + package let bytes: Data + package let changedRegions: [NativeRegion] + package let observations: [NativeObservation] + package let createdContainers: [NativeRegion] +} + +struct Member { + var key: String + var node: Node + var entry: Range? + var comma: Range? + var keyRange: Range? = nil +} + +final class Node { + enum Kind: String { case object, array, string, integer, decimal, boolean, null, atom } + var kind: Kind + var text: String + var raw: String + var atomType: String? + var range: Range? + var entry: Range? + var members: [Member] = [] + var elements: [Node] = [] + var headers: [Range] = [] + var insertion: Int? + var inline = false + var aot = false + var syntaxLocated = false + var commas: [Range] = [] + init(_ kind: Kind, text: String = "", raw: String = "", range: Range? = nil) { + self.kind = kind + self.text = text + self.raw = raw + self.range = range + } + func member(_ key: String, budget: NativeDocumentBudget) throws -> Int? { + for i in members.indices { + try budget.step() + if try budget.equal(members[i].key, key) { return i } + } + return nil + } + func copy(_ budget: NativeDocumentBudget, depth: Int = 0) throws -> Node { + try budget.node(depth: depth) + let result = Node(kind, text: text, raw: raw, range: range) + result.entry = entry + result.atomType = atomType + result.headers = headers + result.insertion = insertion + result.inline = inline + result.aot = aot + result.syntaxLocated = syntaxLocated + result.commas = commas + for member in members { + try budget.allocate(1, stage: "expected member") + result.members.append( + Member( + key: member.key, node: try member.node.copy(budget, depth: depth + 1), + entry: member.entry, comma: member.comma, keyRange: member.keyRange)) + } + for element in elements { result.elements.append(try element.copy(budget, depth: depth + 1)) } + return result + } +} + +func translated(_ body: () throws -> T) throws -> T { + do { return try body() } catch SemanticBudget.Failure.exceeded(let stage) { + throw NativeDocumentError.budgetExceeded(stage) + } catch SemanticBudget.Failure.cancelled { throw NativeDocumentError.cancelled } catch let error + as NativeDocumentError + { throw error } catch { + throw NativeDocumentError.invalidDocument(code: "invalidSyntaxOrValue", range: nil) + } +} diff --git a/Sources/NativeDocuments/NativeDocument.swift b/Sources/NativeDocuments/NativeDocument.swift new file mode 100644 index 0000000..dc4f479 --- /dev/null +++ b/Sources/NativeDocuments/NativeDocument.swift @@ -0,0 +1,499 @@ +import AgentsCore +import Foundation +import TOMLSemantics + +package typealias NativeDocumentBudget = SemanticBudget + +package struct NativeDocument { + package let bytes: Data + package let format: NativeDocumentFormat + let budget: NativeDocumentBudget + let root: Node + let source: [UInt8] + let comments: [Range] + let located: Bool + + package init(bytes: Data, format: NativeDocumentFormat, budget: NativeDocumentBudget) throws { + self = try translated { + try budget.allocate(bytes.count, stage: "input bytes") + // Admission and cooperative work precede copies, decoder and parser construction. + for _ in bytes { try budget.step() } + try budget.allocate(bytes.count, stage: "UTF8 validation") + guard String(data: bytes, encoding: .utf8) != nil else { + throw NativeDocumentError.invalidDocument(code: "utf8", range: nil) + } + let source = Array(bytes) + let root: Node + let comments: [Range] + let located: Bool + if format == .toml { + var parser = TOMLIndex(bytes: source, budget: budget) + root = try parser.parse() + comments = parser.comments + located = parser.located + } else { + var parser = JSONParser(bytes: source, format: format, budget: budget) + root = try parser.parse() + comments = parser.comments + located = true + } + return Self( + bytes: bytes, format: format, budget: budget, root: root, source: source, + comments: comments, located: located) + } + } + + private init( + bytes: Data, format: NativeDocumentFormat, budget: NativeDocumentBudget, root: Node, + source: [UInt8], comments: [Range], located: Bool + ) { + self.bytes = bytes + self.format = format + self.budget = budget + self.root = root + self.source = source + self.comments = comments + self.located = located + } + + package func read(_ region: NativeRegion) throws -> NativeObservation? { + try translated { + guard let node = try resolve(region, on: root) else { return nil } + return try observation(node, region: region) + } + } + + package func prepare(_ edits: [NativeRegionEdit]) throws -> PreparedNativeChange { + try translated { + try budget.check() + var addresses: [[AddressStep]] = [] + for edit in edits { + guard !edit.region.steps.isEmpty else { + throw NativeDocumentError.unsupportedEdit(.wouldRewriteUnownedStructure, edit.region, []) + } + let address = try address(edit.region) + for previous in addresses { + try budget.step(address.reduce(0) { $0 + $1.work } + previous.reduce(0) { $0 + $1.work }) + if address.starts(with: previous) || previous.starts(with: address) { + throw NativeDocumentError.unsupportedEdit(.overlappingEdits, edit.region, []) + } + } + let existing = try resolve(edit.region, on: root) + switch edit.expected { + case .absent: + guard existing == nil else { throw NativeDocumentError.ownershipMismatch(edit.region) } + case .owned(let observation), .createdContainer(let observation): + try budget.step(observation.fingerprint.count) + guard let existing, try sameRegion(observation.region, edit.region), + try existing.fingerprint(budget) == observation.fingerprint + else { throw NativeDocumentError.ownershipMismatch(edit.region) } + } + addresses.append(address) + } + if !edits.isEmpty && !located { + throw NativeDocumentError.unsupportedEdit(.syntaxNotLocated, edits[0].region, []) + } + var current = self + var changed: [NativeRegion] = [] + var created: [NativeRegion] = [] + var observed: [Int] = [] + var removed: [([AddressStep], Int)] = [] + for (editIndex, edit) in edits.enumerated() { + let effective = try current.region(edit.region, at: addresses[editIndex], removed: removed) + let old = try current.resolve(effective, on: current.root) + let desired: Node? + switch edit { + case .put(_, _, let value): + let text = try NativeRenderer(format: format, budget: budget, region: edit.region).render( + value) + if format == .toml { + let parsed = try NativeDocument( + bytes: Data(("value = " + text).utf8), format: .toml, budget: budget) + desired = parsed.root.members.first?.node + } else { + let parsed = try NativeDocument(bytes: Data(text.utf8), format: .json, budget: budget) + desired = parsed.root + } + case .remove: + desired = nil + } + if let old, let desired, try old.equal(to: desired, budget: budget) { + observed.append(editIndex) + continue + } + guard old != nil || desired != nil else { + throw NativeDocumentError.ownershipMismatch(edit.region) + } + if let old, desired == nil, old.kind == .object && old.members.isEmpty { + guard case .createdContainer = edit.expected else { + throw NativeDocumentError.ownershipMismatch(edit.region) + } + guard try !current.hasComments(old) else { + throw NativeDocumentError.unsupportedEdit(.ambiguousTrivia, edit.region, old.headers) + } + } + try current.createdObjects(old: old, new: desired, path: effective.steps, into: &created) + let expected = try current.root.copy(budget) + try current.change( + expected, steps: effective.steps[...], desired: desired, region: effective, + created: &created) + var editor = PatchBuilder(document: current, region: effective) + if let old, let desired { + try editor.diff(old, desired: desired, path: effective.steps) + } else if let old { + try editor.remove(old, path: effective.steps) + } else if let desired { + try editor.insert( + path: effective.steps, value: desired, root: current.root) + } + let candidate = try editor.apply() + let checked: NativeDocument + do { + checked = try NativeDocument(bytes: candidate, format: format, budget: budget) + } catch NativeDocumentError.invalidDocument { + throw NativeDocumentError.unsupportedEdit( + .wouldRewriteUnownedStructure, edit.region, editor.patches.map(\.range)) + } + guard try checked.root.equal(to: expected, budget: budget) else { + throw NativeDocumentError.unsupportedEdit( + .wouldRewriteUnownedStructure, edit.region, editor.patches.map(\.range)) + } + if desired != nil { + observed.append(editIndex) + } else if case .element(let ordinal) = addresses[editIndex].last { + removed.append((Array(addresses[editIndex].dropLast()), ordinal)) + } + current = checked + changed.append(edit.region) + } + var observations: [NativeObservation] = [] + for index in observed { + let region = try current.region(edits[index].region, at: addresses[index], removed: removed) + if let node = try current.resolve(region, on: current.root) { + observations.append(try current.observation(node, region: region)) + } + } + return PreparedNativeChange( + bytes: current.bytes, changedRegions: changed, observations: observations, + createdContainers: created) + } + } + + private func sameRegion(_ a: NativeRegion, _ b: NativeRegion) throws -> Bool { + guard a.steps.count == b.steps.count else { return false } + for (a, b) in zip(a.steps, b.steps) { + switch (a, b) { + case (.key(let a), .key(let b)): if try !budget.equal(a, b) { return false } + case (.occurrence(let a), .occurrence(let b)): + let aSize = + (a.idKey?.utf8.count ?? 0) + (a.id?.utf8.count ?? 0) + (a.snapshot?.count ?? 0) + + (a.previous?.count ?? 0) + (a.next?.count ?? 0) + let bSize = + (b.idKey?.utf8.count ?? 0) + (b.id?.utf8.count ?? 0) + (b.snapshot?.count ?? 0) + + (b.previous?.count ?? 0) + (b.next?.count ?? 0) + try budget.step(aSize + bSize + 1) + if a != b { return false } + default: return false + } + } + return true + } + + private enum AddressStep: Equatable { + case key(Data) + case element(Int) + case append(Data, Data) + var work: Int { + switch self { + case .key(let bytes): bytes.count + case .element: 1 + case .append(let key, let id): key.count + id.count + 1 + } + } + } + + private func address(_ region: NativeRegion) throws -> [AddressStep] { + try budget.enter(region.steps.count) + var node: Node? = root + var result: [AddressStep] = [] + for step in region.steps { + try budget.step() + switch step { + case .key(let key): + try budget.allocate(key.utf8.count + 1, stage: "region address") + result.append(.key(Data(key.utf8))) + if let current = node, let i = try current.member(key, budget: budget) { + node = current.members[i].node + } else { + node = nil + } + case .occurrence(let evidence): + guard let current = node else { throw NativeDocumentError.ownershipMismatch(region) } + do { + let i = try occurrence(evidence, in: current, region: region) + result.append(.element(i)) + node = current.elements[i] + } catch NativeDocumentError.ownershipMismatch { + guard current.kind == .array, let key = evidence.idKey, let id = evidence.id, + result.count == region.steps.count - 1 + else { throw NativeDocumentError.ownershipMismatch(region) } + try budget.allocate(key.utf8.count + id.utf8.count + 1, stage: "new occurrence address") + result.append(.append(Data(key.utf8), Data(id.utf8))) + node = nil + } + } + } + return result + } + + /// Addresses refer to the original snapshot. Only removals can shift other owned occurrences. + private func region( + _ original: NativeRegion, at address: [AddressStep], removed: [([AddressStep], Int)] + ) throws -> NativeRegion { + var node: Node? = root + var steps: [NativePathStep] = [] + for (index, step) in original.steps.enumerated() { + try budget.step() + switch step { + case .key(let key): + steps.append(step) + if let current = node, let i = try current.member(key, budget: budget) { + node = current.members[i].node + } else { + node = nil + } + case .occurrence(let evidence): + if case .append = address[index] { + steps.append(step) + node = nil + continue + } + guard let current = node, case .element(let ordinal) = address[index] else { + throw NativeDocumentError.ownershipMismatch(original) + } + let prefix = Array(address.prefix(index)) + var shift = 0 + for (parent, deleted) in removed { + try budget.step(prefix.reduce(0) { $0 + $1.work } + parent.reduce(0) { $0 + $1.work }) + if parent == prefix && deleted < ordinal { shift += 1 } + } + let i = ordinal - shift + guard i >= 0 && i < current.elements.count else { + throw NativeDocumentError.ownershipMismatch(original) + } + let element = current.elements[i] + let next: NativeOccurrenceEvidence + if let key = evidence.idKey, let m = try element.member(key, budget: budget), + element.members[m].node.kind == .string + { + next = .init(idKey: key, id: element.members[m].node.text) + } else { + next = .init( + snapshot: try element.fingerprint(budget), ordinal: i, + previous: i > 0 ? try current.elements[i - 1].fingerprint(budget) : nil, + next: i + 1 < current.elements.count + ? try current.elements[i + 1].fingerprint(budget) : nil) + } + // Newly ambiguous evidence cannot become a later ownership capability. + guard try occurrence(next, in: current, region: original) == i else { + throw NativeDocumentError.unsupportedEdit(.ambiguousOccurrence, original, []) + } + steps.append(.occurrence(next)) + node = element + } + } + return NativeRegion(steps) + } + + func hasComments(_ node: Node) throws -> Bool { + for comment in comments { + try budget.step() + if let range = node.range, range.overlaps(comment) { return true } + for header in node.headers { + try budget.step() + if comment.lowerBound >= header.lowerBound + && comment.lowerBound < (node.insertion ?? header.upperBound) + { + return true + } + } + } + return false + } + + func occurrence(_ evidence: NativeOccurrenceEvidence, in node: Node, region: NativeRegion) throws + -> Int + { + guard node.kind == .array else { throw NativeDocumentError.ownershipMismatch(region) } + var matches: [Int] = [] + for (i, element) in node.elements.enumerated() { + try budget.step() + if let key = evidence.idKey, let id = evidence.id, + let m = try element.member(key, budget: budget), element.members[m].node.kind == .string + { + if try budget.equal(element.members[m].node.text, id) { matches.append(i) } + } else if let snapshot = evidence.snapshot { + try budget.step(snapshot.count) + if try element.fingerprint(budget) == snapshot { matches.append(i) } + } + } + if evidence.idKey == nil && matches.count > 1 { + var contextual: [Int] = [] + func same(_ a: Data?, _ b: Data?) throws -> Bool { + switch (a, b) { + case (.some(let a), .some(let b)): + try budget.step(a.count + b.count) + return a == b + case (.none, .none): return true + default: return false + } + } + for i in matches { + let previous = i > 0 ? try node.elements[i - 1].fingerprint(budget) : nil + let next = i + 1 < node.elements.count ? try node.elements[i + 1].fingerprint(budget) : nil + if try same(previous, evidence.previous) && same(next, evidence.next) { + contextual.append(i) + } + } + matches = contextual + } + guard !matches.isEmpty else { throw NativeDocumentError.ownershipMismatch(region) } + guard matches.count == 1, let match = matches.first else { + throw NativeDocumentError.unsupportedEdit(.ambiguousOccurrence, region, []) + } + return match + } + + func resolve(_ region: NativeRegion, on root: Node) throws -> Node? { + var node = root + for step in region.steps { + try budget.step() + switch step { + case .key(let key): + guard node.kind == .object, let i = try node.member(key, budget: budget) else { return nil } + node = node.members[i].node + case .occurrence(let evidence): + do { + node = node.elements[try occurrence(evidence, in: node, region: region)] + } catch NativeDocumentError.ownershipMismatch { return nil } + } + } + return node + } + + private func entryRanges(_ node: Node) throws -> [Range] { + try budget.step() + if let entry = node.entry { + try budget.allocate(1, stage: "observation ranges") + return [entry] + } + try budget.allocate(node.headers.count, stage: "observation ranges") + var ranges = node.headers + for member in node.members { + let children = try entryRanges(member.node) + try budget.allocate(children.count, stage: "observation ranges") + ranges += children + } + for element in node.elements { + let children = try entryRanges(element) + try budget.allocate(children.count, stage: "observation ranges") + ranges += children + } + return ranges + } + + private func observation(_ node: Node, region: NativeRegion) throws -> NativeObservation { + var occurrences: [NativeOccurrenceEvidence] = [] + if node.kind == .array { + var prints: [Data] = [] + for e in node.elements { prints.append(try e.fingerprint(budget)) } + for i in prints.indices { + occurrences.append( + .init( + snapshot: prints[i], ordinal: i, previous: i > 0 ? prints[i - 1] : nil, + next: i + 1 < prints.count ? prints[i + 1] : nil)) + } + } + return NativeObservation( + region: region, value: try node.project(budget), + nativeKind: node.atomType ?? node.kind.rawValue, + numericLexeme: node.kind == .integer || node.kind == .decimal ? node.raw : nil, + projectionFailure: try node.projectionFailure(budget), + valueRange: node.range, entryRanges: try entryRanges(node), + occurrences: occurrences, fingerprint: try node.fingerprint(budget)) + } + + private func createdObjects( + old: Node?, new: Node?, path: [NativePathStep], into result: inout [NativeRegion] + ) throws { + guard let new, new.kind == .object else { return } + try budget.step() + if old?.kind != .object { + try budget.allocate(path.count + 1, stage: "created container evidence") + result.append(NativeRegion(path)) + } + for member in new.members { + let previous = try old?.member(member.key, budget: budget).map { old!.members[$0].node } + try budget.allocate(path.count + 1, stage: "created container path") + try createdObjects( + old: previous, new: member.node, path: path + [.key(member.key)], into: &result) + } + } + + private func change( + _ node: Node, steps: ArraySlice, desired: Node?, region: NativeRegion, + created: inout [NativeRegion], offset: Int = 0 + ) throws { + try budget.enter(offset) + guard let step = steps.first else { throw NativeDocumentError.ownershipMismatch(region) } + let tail = steps.dropFirst() + switch step { + case .key(let key): + guard node.kind == .object else { throw NativeDocumentError.ownershipMismatch(region) } + let m = try node.member(key, budget: budget) + if tail.isEmpty { + if let m { + if let desired { node.members[m].node = desired } else { node.members.remove(at: m) } + } else if let desired { + node.members.append(Member(key: key, node: desired)) + } + } else { + let child: Node + if let m { + child = node.members[m].node + } else { + guard desired != nil else { throw NativeDocumentError.ownershipMismatch(region) } + try budget.node(depth: offset) + child = Node(.object) + node.members.append(Member(key: key, node: child)) + created.append(NativeRegion(Array(region.steps.prefix(offset + 1)))) + } + try change( + child, steps: tail, desired: desired, region: region, created: &created, + offset: offset + 1) + } + case .occurrence(let evidence): + let i: Int + do { i = try occurrence(evidence, in: node, region: region) } catch NativeDocumentError + .ownershipMismatch + { + guard node.kind == .array, tail.isEmpty, let desired, desired.kind == .object, + let key = evidence.idKey, let id = evidence.id, + let field = try desired.member(key, budget: budget), + desired.members[field].node.kind == .string, + try budget.equal(desired.members[field].node.text, id) + else { throw NativeDocumentError.ownershipMismatch(region) } + try budget.allocate(1, stage: "new occurrence") + node.elements.append(desired) + return + } + if tail.isEmpty { + if let desired { node.elements[i] = desired } else { node.elements.remove(at: i) } + } else { + try change( + node.elements[i], steps: tail, desired: desired, region: region, created: &created, + offset: offset + 1) + } + } + } +} diff --git a/Sources/NativeDocuments/PatchBuilder.swift b/Sources/NativeDocuments/PatchBuilder.swift new file mode 100644 index 0000000..4aa122a --- /dev/null +++ b/Sources/NativeDocuments/PatchBuilder.swift @@ -0,0 +1,509 @@ +import Foundation + +struct BytePatch { + let range: Range + let bytes: [UInt8] +} + +struct PatchBuilder { + let document: NativeDocument + let region: NativeRegion + var patches: [BytePatch] = [] + var budget: NativeDocumentBudget { document.budget } + var toml: Bool { document.format == .toml } + var newline: String { + get throws { + var lf = false + var crlf = false + for i in document.source.indices where document.source[i] == 10 { + try budget.step() + if i > 0 && document.source[i - 1] == 13 { crlf = true } else { lf = true } + } + if lf && crlf { throw NativeDocumentError.unsupportedEdit(.ambiguousTrivia, region, []) } + return crlf ? "\r\n" : "\n" + } + } + mutating func patch(_ range: Range, _ text: String = "") throws { + try budget.allocate(text.utf8.count + 1, stage: "patch") + try budget.step(text.utf8.count) + patches.append(BytePatch(range: range, bytes: Array(text.utf8))) + } + func encoded(_ node: Node) throws -> String { + let renderer = NativeRenderer(format: document.format, budget: budget, region: region) + try budget.step() + switch node.kind { + case .string: return try renderer.string(node.text) + case .integer, .decimal, .boolean, .null: return node.raw.isEmpty ? node.text : node.raw + case .array: + var values: [String] = [] + for e in node.elements { values.append(try encoded(e)) } + return try nativeJoin(values, prefix: "[", suffix: "]", separator: ", ", budget: budget) + case .object: + var values: [String] = [] + for m in node.members { + values.append(try renderer.string(m.key) + (toml ? " = " : ": ") + encoded(m.node)) + } + return try nativeJoin(values, prefix: "{", suffix: "}", separator: ", ", budget: budget) + case .atom: + throw NativeDocumentError.unrepresentableValue(document.format, region, "nativeAtom") + } + } + mutating func diff(_ old: Node, desired: Node, path: [NativePathStep]) throws { + if try old.equal(to: desired, budget: budget) { return } + if old.kind == .object && desired.kind == .object { + var retained: [Int] = [] + var added: [Member] = [] + for (i, m) in old.members.enumerated() { + if let next = try desired.member(m.key, budget: budget) { + retained.append(i) + try diff(m.node, desired: desired.members[next].node, path: path + [.key(m.key)]) + } else { + try eraseMember(m, parent: old) + } + } + if old.inline && retained.count != old.members.count { + let keepCommas = Set(retained.dropLast().compactMap { old.members[$0].comma?.lowerBound }) + for m in old.members { + if let comma = m.comma, !keepCommas.contains(comma.lowerBound) { try patch(comma) } + } + } + for m in desired.members where try old.member(m.key, budget: budget) == nil { + added.append(m) + } + if !added.isEmpty { + try insertMembers( + added, in: old, path: path, remaining: retained.count, + survivors: retained.map { old.members[$0] }) + } + return + } + if old.kind == .array && desired.kind == .array && old.aot { + if desired.elements.contains(where: { $0.kind != .object }) { + for element in old.elements { try eraseTable(element) } + try arrayAssignment(path: path, rendered: encoded(desired)) + return + } + let common = min(old.elements.count, desired.elements.count) + for i in 0.. common { + try budget.allocate(desired.elements.count - common, stage: "AoT append") + try appendTables(Array(desired.elements.dropFirst(common)), path: path) + } + return + } + guard let range = old.range else { + throw NativeDocumentError.unsupportedEdit(.wouldRewriteUnownedStructure, region, old.headers) + } + if try document.hasComments(old) { + throw NativeDocumentError.unsupportedEdit(.ambiguousTrivia, region, [range]) + } + try patch(range, encoded(desired)) + } + mutating func eraseMember(_ member: Member, parent: Node) throws { + if let entry = member.entry { + if try document.comments.contains(where: { + try budget.step() + return entry.overlaps($0) + }) { + throw NativeDocumentError.unsupportedEdit(.ambiguousTrivia, region, [entry]) + } + try patch(entry) + } else if toml && !parent.inline { + try eraseTable(member.node) + } else { + throw NativeDocumentError.unsupportedEdit(.syntaxNotLocated, region, []) + } + } + mutating func eraseTable(_ node: Node) throws { + for header in node.headers { try patch(header) } + for m in node.members { + if let entry = m.entry { + if try document.comments.contains(where: { + try budget.step() + return entry.overlaps($0) + }) { + throw NativeDocumentError.unsupportedEdit(.ambiguousTrivia, region, [entry]) + } + try patch(entry) + } else { + try eraseTable(m.node) + } + } + if node.aot { for e in node.elements { try eraseTable(e) } } + } + mutating func remove(_ node: Node, path: [NativePathStep]) throws { + let parentPath = NativeRegion(Array(path.dropLast())) + guard let parent = try document.resolve(parentPath, on: document.root), let last = path.last + else { throw NativeDocumentError.ownershipMismatch(region) } + switch last { + case .key(let key): + guard let i = try parent.member(key, budget: budget) else { + throw NativeDocumentError.ownershipMismatch(region) + } + try eraseMember(parent.members[i], parent: parent) + if parent.inline { + if let comma = parent.members[i].comma { + try patch(comma) + } else if i > 0, let comma = parent.members[i - 1].comma { + try patch(comma) + } + } + case .occurrence(let evidence): + let i = try document.occurrence(evidence, in: parent, region: region) + if parent.aot { + try eraseTable(node) + if parent.elements.count == 1 { try arrayAssignment(path: Array(path.dropLast())) } + } else { + guard let range = node.range else { + throw NativeDocumentError.unsupportedEdit(.syntaxNotLocated, region, []) + } + if try document.hasComments(node) { + throw NativeDocumentError.unsupportedEdit(.ambiguousTrivia, region, [range]) + } + try patch(range) + if i < parent.commas.count { + try patch(parent.commas[i]) + } else if i > 0 && i - 1 < parent.commas.count { + try patch(parent.commas[i - 1]) + } + } + } + } + mutating func insert(path: [NativePathStep], value: Node, root: Node) throws { + var parent = root + var existing: [NativePathStep] = [] + for (i, step) in path.enumerated() { + switch step { + case .occurrence(let evidence): + do { + parent = parent.elements[try document.occurrence(evidence, in: parent, region: region)] + existing.append(step) + } catch NativeDocumentError.ownershipMismatch { + guard i == path.count - 1 else { throw NativeDocumentError.ownershipMismatch(region) } + if parent.aot { + try appendTables([value], path: existing) + } else { + try appendValues([value], in: parent) + } + return + } + case .key(let key): + if let m = try parent.member(key, budget: budget) { + parent = parent.members[m].node + existing.append(step) + continue + } + let remainder = Array(path.dropFirst(i + 1)) + var new = value + for step in remainder.reversed() { + guard case .key(let key) = step else { + throw NativeDocumentError.unsupportedEdit(.ambiguousOccurrence, region, []) + } + try budget.node(depth: remainder.count) + let container = Node(.object) + container.members = [Member(key: key, node: new)] + new = container + } + try insertMembers( + [Member(key: key, node: new)], in: parent, path: existing, remaining: parent.members.count + ) + return + } + } + throw NativeDocumentError.ownershipMismatch(region) + } + private mutating func arrayAssignment(path: [NativePathStep], rendered: String = "[]") throws { + guard case .key(let key) = path.last, + let parent = try document.resolve(NativeRegion(Array(path.dropLast())), on: document.root) + else { throw NativeDocumentError.unsupportedEdit(.wouldRewriteUnownedStructure, region, []) } + let renderer = NativeRenderer(format: document.format, budget: budget, region: region) + let nl = try newline + let at: Int + let assignmentKey: String + if let insertion = parent.insertion { + at = insertion + assignmentKey = try renderer.string(key) + } else { + at = document.root.insertion ?? 0 + var keys: [String] = [] + for step in path { + guard case .key(let key) = step else { + throw NativeDocumentError.unsupportedEdit(.wouldRewriteUnownedStructure, region, []) + } + keys.append(try renderer.string(key)) + } + assignmentKey = keys.joined(separator: ".") + } + try patch( + at.. 0 && document.source[at - 1] != 10 ? nl : "") + assignmentKey + " = " + rendered + nl) + } + + private mutating func appendTables(_ values: [Node], path: [NativePathStep]) throws { + let renderer = NativeRenderer(format: document.format, budget: budget, region: region) + var keys: [String] = [] + var current = document.root + for step in path { + switch step { + case .key(let key): + keys.append(try renderer.string(key)) + if let i = try current.member(key, budget: budget) { current = current.members[i].node } + case .occurrence(let evidence): + let i = try document.occurrence(evidence, in: current, region: region) + guard i == current.elements.count - 1 else { + throw NativeDocumentError.unsupportedEdit(.wouldRewriteUnownedStructure, region, []) + } + current = current.elements[i] + } + } + let nl = try newline + var blocks: [String] = [] + for value in values { + guard value.kind == .object else { + throw NativeDocumentError.unrepresentableValue(document.format, region, "arrayTableElement") + } + var pairs: [String] = [] + for member in value.members { + pairs.append(try renderer.string(member.key) + " = " + encoded(member.node)) + } + blocks.append( + try nativeJoin( + pairs, prefix: "[[" + keys.joined(separator: ".") + "]]" + nl, suffix: "", separator: nl, + budget: budget)) + } + let at = document.source.count + try patch( + at.. 0 && document.source[at - 1] != 10 ? nl : "") + + (try nativeJoin(blocks, prefix: "", suffix: nl, separator: nl, budget: budget))) + } + + private mutating func appendValues(_ values: [Node], in array: Node) throws { + guard array.kind == .array, let range = array.range else { + throw NativeDocumentError.unsupportedEdit(.syntaxNotLocated, region, []) + } + let at = range.upperBound - 1 + var pieces: [String] = [] + for value in values { pieces.append(try encoded(value)) } + let comma = !array.elements.isEmpty && array.commas.count < array.elements.count + if document.source[range].contains(10), let closeIndent = try indentation(at: at) { + let nl = try newline + var indent = closeIndent + " " + if let first = array.elements.first?.range, let local = try indentation(at: first.lowerBound) + { + indent = local + } + if comma, let end = array.elements.last?.range?.upperBound { try patch(end.. range.lowerBound + 1 && [9, 32].contains(document.source[insertion - 1]) { + try budget.step() + insertion -= 1 + } + let separator = array.elements.count > 1 ? " " : "" + try patch( + insertion.. String { + let fallback = toml ? " = " : ": " + guard let first = parent.members.first(where: { $0.keyRange != nil }), let key = first.keyRange, + let value = first.node.range + else { return fallback } + let gap = document.source[key.upperBound.. String? { + var start = position + while start > 0 && document.source[start - 1] != 10 { + try budget.step() + start -= 1 + } + let prefix = document.source[start.. lower + && (document.source[insertion - 1] == 9 || document.source[insertion - 1] == 32) + { + try budget.step() + insertion -= 1 + } + let text = try nativeJoin( + pieces, prefix: (remaining > 0 && !hasComma ? "," : "") + separator, suffix: "", + separator: "," + separator, budget: budget) + try patch(insertion.. 0 && document.source[at - 1] != 10 ? nl : "" + try patch(at.. 0 && document.source[at - 1] != 10 ? nl : "" + var blocks: [String] = [] + var rootPairs: [String] = [] + for m in members { + let full = keys + [try renderer.string(m.key)] + if m.node.kind == .object { + var pairs: [String] = [] + for child in m.node.members { + pairs.append(try renderer.string(child.key) + " = " + encoded(child.node)) + } + blocks.append("[" + full.joined(separator: ".") + "]" + nl + pairs.joined(separator: nl)) + } else { + // A dotted assignment belongs in the root block, before the first header. + rootPairs.append(full.joined(separator: ".") + " = " + (try encoded(m.node))) + } + } + if !rootPairs.isEmpty { + let rootAt = document.root.insertion ?? 0 + try patch( + rootAt.. Data { + // Coalesce repeated deletions but reject any other overlap before allocating a result. + try budget.allocate(patches.count, stage: "patch order") + var ordered = try patches.sorted { + try budget.step() + if $0.range.lowerBound == $1.range.lowerBound { return $0.range.isEmpty && !$1.range.isEmpty } + return $0.range.lowerBound < $1.range.lowerBound + } + var merged: [BytePatch] = [] + for p in ordered { + try budget.step() + if let last = merged.last, p.range.lowerBound < last.range.upperBound || p.range == last.range + { + guard p.bytes.isEmpty && last.bytes.isEmpty else { + throw NativeDocumentError.unsupportedEdit( + .overlappingEdits, region, [p.range, last.range]) + } + merged.removeLast() + merged.append( + BytePatch( + range: last.range.lowerBound.. Bool { + try budget.step() + guard kind == other.kind else { return false } + if kind == .object { + guard members.count == other.members.count else { return false } + for member in members { + guard let i = try other.member(member.key, budget: budget), + try member.node.equal(to: other.members[i].node, budget: budget) + else { return false } + } + return true + } + if kind == .array { + guard elements.count == other.elements.count else { return false } + for (a, b) in zip(elements, other.elements) { + if try !a.equal(to: b, budget: budget) { return false } + } + return true + } + return try budget.equal(text, other.text) + } + + func fingerprint(_ budget: NativeDocumentBudget) throws -> Data { + var data = Data() + func append(_ text: String) throws { + try budget.allocate(text.utf8.count + 24, stage: "observation") + try budget.step(text.utf8.count) + data.append(contentsOf: "\(text.utf8.count):".utf8) + data.append(contentsOf: text.utf8) + } + try append(kind.rawValue) + if kind == .object { + try append(String(members.count)) + var sorted: [Member] = [] + for m in members { + var index = 0 + while index < sorted.count { + try budget.step(m.key.utf8.count + sorted[index].key.utf8.count) + if m.key.utf8.lexicographicallyPrecedes(sorted[index].key.utf8) { break } + index += 1 + } + try budget.allocate(1, stage: "observation members") + sorted.insert(m, at: index) + } + for m in sorted { + try append(m.key) + let child = try m.node.fingerprint(budget) + try budget.allocate(child.count, stage: "observation subtree") + data.append(child) + } + } else if kind == .array { + try append(String(elements.count)) + for e in elements { + let child = try e.fingerprint(budget) + try budget.allocate(child.count, stage: "observation subtree") + data.append(child) + } + } else { + try append(text) + } + return data + } + + func projectionFailure(_ budget: NativeDocumentBudget) throws -> NativeProjectionFailure? { + try budget.step() + if kind == .atom { return .nativeType(atomType ?? "nativeAtom") } + if kind == .object { + var keys: Set = [] + for member in members { + try budget.allocate(member.key.utf8.count, stage: "projection key") + try budget.step(member.key.utf8.count) + if !keys.insert(member.key).inserted { return .canonicalKeyCollision } + if let failure = try member.node.projectionFailure(budget) { return failure } + } + } + for element in elements { + if let failure = try element.projectionFailure(budget) { return failure } + } + return nil + } + + func project(_ budget: NativeDocumentBudget) throws -> NativeValue? { + try budget.step() + switch kind { + case .object: + var result: [String: NativeValue] = [:] + for m in members { + try budget.allocate(m.key.utf8.count + 1, stage: "projection") + // Core dictionaries use canonical equivalence; refuse this projection rather than collapse keys. + guard result[m.key] == nil, let value = try m.node.project(budget) else { return nil } + result[m.key] = value + } + return .object(result) + case .array: + var values: [NativeValue] = [] + for e in elements { + guard let v = try e.project(budget) else { return nil } + values.append(v) + } + return .array(values) + case .string: return .string(text) + case .integer: return Int(text).map(NativeValue.integer) ?? .decimal(raw) + case .decimal: return .decimal(text) + case .boolean: return .boolean(text == "true") + case .null: return .null + case .atom: return nil + } + } +} + +struct NativeRenderer { + let format: NativeDocumentFormat + let budget: NativeDocumentBudget + let region: NativeRegion + var toml: Bool { format == .toml } + func string(_ value: String) throws -> String { + guard value.utf8.count <= (Int.max - 2) / 6 else { + throw NativeDocumentError.budgetExceeded("string encoding") + } + try budget.allocate(value.utf8.count * 6 + 2, stage: "string encoding") + try budget.step(value.utf8.count) + let encoder = JSONEncoder() + encoder.outputFormatting = [.withoutEscapingSlashes] + let bytes = try encoder.encode(value) + try budget.allocate(bytes.count, stage: "encoded string") + return String(decoding: bytes, as: UTF8.self) + } + func render(_ value: NativeValue, depth: Int = 0) throws -> String { + try budget.node(depth: depth) + switch value { + case .string(let value): return try string(value) + case .integer(let value): return String(value) + case .decimal(let raw): + try budget.allocate(raw.utf8.count, stage: "decimal input") + var parser = JSONParser(bytes: Array(raw.utf8), format: .json, budget: budget) + let node: Node + do { node = try parser.parse() } catch let failure as TOMLSemantics.SemanticBudget.Failure { + throw failure + } catch { throw NativeDocumentError.unrepresentableValue(format, region, "decimal") } + guard node.kind == .integer || node.kind == .decimal, node.range == 0.. String { + try budget.allocate(prefix.utf8.count + suffix.utf8.count, stage: "rendered container") + for part in parts { + try budget.step(part.utf8.count) + try budget.allocate(part.utf8.count + separator.utf8.count, stage: "rendered container") + } + return prefix + parts.joined(separator: separator) + suffix +} diff --git a/Sources/NativeDocuments/TOMLIndex.swift b/Sources/NativeDocuments/TOMLIndex.swift new file mode 100644 index 0000000..5613bdb --- /dev/null +++ b/Sources/NativeDocuments/TOMLIndex.swift @@ -0,0 +1,278 @@ +import Foundation +import TOMLSemantics +import TreeSitter +import TreeSitterTOML + +private struct ParseInput { + let bytes: UnsafePointer + let count: Int + let budget: NativeDocumentBudget + var failure: (any Error)? +} + +struct TOMLIndex { + let bytes: [UInt8] + let budget: NativeDocumentBudget + var comments: [Range] = [] + var located = true + var offset: Int { bytes.starts(with: [0xef, 0xbb, 0xbf]) ? 3 : 0 } + + mutating func parse() throws -> Node { + try budget.allocate(bytes.count, stage: "TOML string") + guard let source = String(bytes: bytes.dropFirst(offset), encoding: .utf8) else { + throw NativeDocumentError.invalidDocument(code: "utf8", range: nil) + } + let semantics = try SemanticDocument(source: source, budget: budget) + let root = try convert(semantics.root, depth: 0) + root.syntaxLocated = true + // The admitted whole envelope includes long comments and whitespace absent from semantic tokens. + try budget.admitCST(bytes: bytes.count) + guard bytes.count <= Int(UInt32.max), let parser = ts_parser_new() else { + throw NativeDocumentError.budgetExceeded("CST input") + } + defer { ts_parser_delete(parser) } + guard ts_parser_set_language(parser, tree_sitter_toml()) else { + throw NativeDocumentError.invalidDocument(code: "parserABI", range: nil) + } + var failure: (any Error)? + let tree = bytes.withUnsafeBytes { raw -> OpaquePointer? in + var empty: CChar = 0 + return withUnsafePointer(to: &empty) { emptyPointer in + var state = ParseInput( + bytes: raw.baseAddress?.assumingMemoryBound(to: CChar.self).advanced(by: offset) + ?? emptyPointer, count: bytes.count - offset, budget: budget) + return withUnsafeMutablePointer(to: &state) { pointer in + let input = TSInput( + payload: UnsafeMutableRawPointer(pointer), + read: { payload, index, _, count in + let state = payload!.assumingMemoryBound(to: ParseInput.self).pointee + let offset = min(Int(index), state.count) + count!.pointee = UInt32(state.count - offset) + return state.bytes.advanced(by: offset) + }, encoding: TSInputEncodingUTF8, decode: nil) + let options = TSParseOptions( + payload: UnsafeMutableRawPointer(pointer), + progress_callback: { progress in + let state = progress!.pointee.payload!.assumingMemoryBound(to: ParseInput.self) + do { + try state.pointee.budget.step() + return false + } catch { + state.pointee.failure = error + return true + } + }) + let tree = ts_parser_parse_with_options(parser, nil, input, options) + failure = pointer.pointee.failure + return tree + } + } + } + if let failure { + if let tree { ts_tree_delete(tree) } + throw failure + } + guard let tree else { + throw NativeDocumentError.invalidDocument(code: "parserFailure", range: nil) + } + defer { ts_tree_delete(tree) } + try budget.check() + let syntax = ts_tree_root_node(tree) + if ts_node_has_error(syntax) { + located = false + return root + } + let top = try children(syntax) + root.insertion = + top.first(where: { type($0) == "table" || type($0) == "table_array_element" }).map { + span($0).lowerBound + } ?? bytes.count + var active = root + for child in top { + try budget.step() + switch type(child) { + case "comment": comments.append(span(child)) + case "pair": try pair(child, in: root) + case "table", "table_array_element": + let parts = try children(child) + guard let key = parts.first(where: { type($0) != "comment" }) else { + located = false + continue + } + let keys = try keyParts(key) + let isArray = type(child) == "table_array_element" + active = try table(root, keys: keys, aot: isArray) + let start = span(child).lowerBound + var end = span(key).upperBound + while end < bytes.count && bytes[end] != 93 { + try budget.step() + end += 1 + } + guard end < bytes.count else { + located = false + continue + } + end += isArray ? 2 : 1 + active.syntaxLocated = true + active.headers.append(start.. Node { + try budget.node(depth: depth) + switch value { + case .object(let entries): + let n = Node(.object) + for e in entries { + n.members.append(Member(key: e.key, node: try convert(e.value, depth: depth + 1))) + } + return n + case .array(let elements): + let n = Node(.array) + for e in elements { n.elements.append(try convert(e, depth: depth + 1)) } + return n + case .scalar(let kind, let decoded, let raw, let range): + let k: Node.Kind + switch kind { + case .string: k = .string + case .boolean: k = .boolean + case .integer: k = .integer + case .float: + k = ["inf", "+inf", "-inf", "nan", "+nan", "-nan"].contains(raw) ? .atom : .decimal + case .dateTime: k = .atom + } + let node = Node( + k, text: k == .atom ? raw : decoded, raw: raw, + range: (range.lowerBound + offset)..<(range.upperBound + offset) + ) + if k == .atom { node.atomType = kind == .dateTime ? "dateTime" : "nonFiniteFloat" } + return node + } + } + func span(_ node: TSNode) -> Range { + (Int(ts_node_start_byte(node)) + offset)..<(Int(ts_node_end_byte(node)) + offset) + } + func type(_ node: TSNode) -> String { String(cString: ts_node_type(node)) } + func children(_ node: TSNode) throws -> [TSNode] { + var result: [TSNode] = [] + for i in 0.. [String] { + try budget.step() + if type(node) == "dotted_key" { + var keys: [String] = [] + for c in try children(node) { keys += try keyParts(c) } + return keys + } + try budget.allocate(span(node).count, stage: "CST key copy") + return [try SemanticDocument.decodeKey(Array(bytes[span(node)]), budget: budget)] + } + func table(_ root: Node, keys: [String], aot: Bool) throws -> Node { + var current = root + for (i, key) in keys.enumerated() { + guard let m = try current.member(key, budget: budget) else { + throw NativeDocumentError.invalidDocument(code: "syntaxSemanticMismatch", range: nil) + } + current = current.members[m].node + if current.kind == .array { + if i == keys.count - 1 && aot { + current.aot = true + guard let next = current.elements.first(where: { $0.headers.isEmpty }) else { + throw NativeDocumentError.invalidDocument(code: "arrayTableIndex", range: nil) + } + current = next + } else { + guard let latest = current.elements.last(where: { !$0.headers.isEmpty }) else { + throw NativeDocumentError.invalidDocument(code: "arrayTableScope", range: nil) + } + current = latest + } + } + } + return current + } + mutating func pair(_ syntax: TSNode, in parent: Node) throws { + let nodes = try children(syntax).filter { type($0) != "comment" } + guard nodes.count >= 2 else { + located = false + return + } + let keys = try keyParts(nodes[0]) + var current = parent + for key in keys.dropLast() { + guard let m = try current.member(key, budget: budget) else { + located = false + return + } + current = current.members[m].node + } + guard let key = keys.last, let m = try current.member(key, budget: budget) else { + located = false + return + } + let value = nodes[1] + current.members[m].entry = span(nodes[0]).lowerBound.. Important: Offset date-time in TOML is defined by RFC 3339, +/// > which interprets the date with proleptic Gregorian calendar. +/// > This is different from Foundation's usage of the Gregorian calendar, +/// > which follows the Julian calendar up to 1582-10-04, +/// > then transitions to the Gregorian calendar after that. +/// > This means for ancient dates, +/// > ``OffsetDateTime`` may disagree with `Foundation.Date` on how much time has passed since a reference date. +/// > For modern dates, there's no difference between the two. +public struct OffsetDateTime: Equatable, Hashable, Sendable, Codable, CustomStringConvertible { + /// The date component of the offset date-time. + public var date: LocalDate + /// The time component of the offset date-time. + public var time: LocalTime + /// The offset from UTC in minutes, valid range is [-1440, 1440]. + public var offset: Int16 + /// Details about the formatting of the date-time string. + /// For example, whether the 'T' connecting the date and time is lowercase or uppercase. + /// Or whether 00:00 offset is represented as 'Z' or '+00:00'. + public var features: Features + + /// Create a new offset date-time from it's members. + /// + /// This initializer does not validate the components. + /// Use ``isValid`` to check if the offset date-time is valid. + /// + /// - Parameters: + /// - date: The date component of the offset date-time. + /// - time: The time component of the offset date-time. + /// - offset: The offset from UTC in minutes, valid range is [-1440, 1440]. + /// - features: Details about the formatting of the date-time string. + public init(date: LocalDate, time: LocalTime, offset: Int16, features: Features) { + self.date = date + self.time = time + self.offset = offset + self.features = features + } + + /// Create a new offset date-time from it's members. + /// + /// This initializer validates the components. + /// A invalid component causes a error to be thrown. + /// + /// - Parameters: + /// - date: The date component of the offset date-time. + /// - time: The time component of the offset date-time. + /// - offset: The offset from UTC in minutes, valid range is [-1440, 1440]. + /// - features: Details about the formatting of the date-time string. + public init(validatingDate date: LocalDate, time: LocalTime, offset: Int16, features: Features) + throws + { + self.init(date: date, time: time, offset: offset, features: features) + guard date.isValid else { + throw TOMLError(.invalidDateTimeComponents("Invalid local date: \(date)")) + } + guard time.isValid else { + throw TOMLError(.invalidDateTimeComponents("Invalid local time: \(time)")) + } + guard offsetIsValid else { + throw TOMLError(.invalidDateTimeComponents("Invalid offset: \(offset)")) + } + guard featuresAreValid else { + throw TOMLError(.invalidDateTimeComponents("Invalid features: \(features)")) + } + } + + /// Check if the offset date-time is valid. + public var isValid: Bool { + guard date.isValid, time.isValid, offsetIsValid else { + return false + } + + return featuresAreValid + } + + private var offsetIsValid: Bool { + offset >= -1440 && offset <= 1440 + } + + private var featuresAreValid: Bool { + if features.contains(.lowercaseZ) || features.contains(.uppercaseZ) { + return offset == 0 + } + + return true + } + + /// Number of seconds since 2001-01-01T00:00:00Z according to the proleptic Gregorian calendar. + /// + /// > Important: This is similar to `Foundation.Date.timeIntervalSinceReferenceDate`. + /// But for ancient dates, this result may disagree with `Foundation.Date` on how much time has passed. + /// this is because Foundation's Gregorian calendar follows the Julian calendar up to 1582-10-04, + /// then the Gregorian calendar after that. According to the TOML specification, + /// an offset date-time should follow the proleptic Gregorian calendar, + /// which extends the Gregorian calendar backwards to year 1. + public var timeIntervalSince2001: Double { + timeIntervalSince1970 - 978_307_200 + } + + /// Number of seconds since 1970-01-01T00:00:00Z according to the proleptic Gregorian calendar. + /// + /// > Important: This is similar to `Foundation.Date.timeIntervalSinceReferenceDate`. + /// But for ancient dates, this result may disagree with `Foundation.Date` on how much time has passed. + /// this is because Foundation's Gregorian calendar follows the Julian calendar up to 1582-10-04, + /// then the Gregorian calendar after that. According to the TOML specification, + /// an offset date-time should follow the proleptic Gregorian calendar, + /// which extends the Gregorian calendar backwards to year 1. + public var timeIntervalSince1970: Double { + let year = Int64(date.year) + let month = Int64(date.month) + let day = Int64(date.day) + let hour = Int64(time.hour) + let minute = Int64(time.minute) + let second = Int64(time.second) + let nanosecond = Int64(time.nanosecond) + let offsetInSeconds = Int64(offset) * 60 + + var y = year + if month <= 2 { y -= 1 } + + let era = (y >= 0 ? y : y - 399) / 400 + let yoe = y - era * 400 + let doy = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + day - 1 + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy + let epochOffset = Int64(719_468) + let dayCounts = era * 146_097 + doe - epochOffset + let secondOfDay = hour * 3600 + minute * 60 + second + let totalSeconds = dayCounts * 86400 + secondOfDay - offsetInSeconds + + return Double(totalSeconds) + Double(nanosecond) / 1_000_000_000 + } + + /// The string representation of the offset date-time. + /// + /// If a value has precision up to 1 nanosecond, + /// and it does not require superfluous trailing zeros in its fraction seconds, + /// this value can be recreated exactly. + public var description: String { + let dateString = date.description + let timeString = time.description + let separator = + if features.contains(.lowercaseT) { + "t" + } else if features.contains(.uppercaseT) { + "T" + } else { + " " + } + + if features.contains(.lowercaseZ) { + return "\(dateString)\(separator)\(timeString)z" + } else if features.contains(.uppercaseZ) { + return "\(dateString)\(separator)\(timeString)Z" + } else { + let sign = offset >= 0 ? "+" : "-" + let absOffset = abs(offset) + let hours = absOffset / 60 + let minutes = absOffset % 60 + let hoursStr = hours < 10 ? "0\(hours)" : "\(hours)" + let minutesStr = minutes < 10 ? "0\(minutes)" : "\(minutes)" + return "\(dateString)\(separator)\(timeString)\(sign)\(hoursStr):\(minutesStr)" + } + } + + /// Presentation details for string representation of the offset date-time. + /// + /// A parser can preserve features of a offset date-time string with this type. + /// If neither lowercase nor uppercase 'T' is present, the date-time seprator is a space, which is allowed by TOML. + public struct Features: OptionSet, Hashable, Sendable, Codable { + /// The raw value of the features. + public let rawValue: UInt8 + + /// Create a new features from it's raw value. + public init(rawValue: UInt8) { + self.rawValue = rawValue + } + + /// Indicates the date-time seprator is a lowercase 't'. + public static let lowercaseT = Features(rawValue: 1 << 1) + + /// Indicates the date-time seprator is a uppercase 'T'. + public static let uppercaseT = Features(rawValue: 1 << 2) + + /// Indicates the offset is represented as a lowercase 'z'. + /// This should not be present if the offset is non-zero, + /// or if it's +00:00. + public static let lowercaseZ = Features(rawValue: 1 << 3) + + /// Indicates the offset is represented as a uppercase 'Z'. + /// This should not be present if the offset is non-zero, + /// or if it's +00:00. + public static let uppercaseZ = Features(rawValue: 1 << 4) + } +} + +/// A local date-time as defined by TOML. +/// +/// ``LocalDateTime`` stores fractional seconds to the nanosecond precision. +public struct LocalDateTime: Equatable, Hashable, Sendable, Codable, CustomStringConvertible { + /// The date component of the local date-time. + public var date: LocalDate + /// The time component of the local date-time. + public var time: LocalTime + + /// Create a new local date-time from it's members. + /// + /// This initializer does not validate the components. + /// Use ``isValid`` to check if the local date-time is valid. + /// - Parameters: + /// - date: The date component of the local date-time. + /// - time: The time component of the local date-time. + public init(date: LocalDate, time: LocalTime) { + self.date = date + self.time = time + } + + /// Create a new local date-time from it's members. + /// + /// This initializer validates the components. + /// A invalid component causes a error to be thrown. + /// + /// - Parameters: + /// - date: The date component of the local date-time. + /// - time: The time component of the local date-time. + public init(validatingDate date: LocalDate, time: LocalTime) throws { + self.init(date: date, time: time) + guard date.isValid else { + throw TOMLError(.invalidDateTimeComponents("Invalid local date: \(date)")) + } + guard time.isValid else { + throw TOMLError(.invalidDateTimeComponents("Invalid local time: \(time)")) + } + } + + /// Check if the local date-time is valid. + public var isValid: Bool { + date.isValid && time.isValid + } + + /// The string representation of the local date-time. + public var description: String { + "\(date.description)T\(time.description)" + } +} + +/// A local time as defined by TOML. +/// +/// ``LocalTime`` stores fractional seconds to the nanosecond precision. +public struct LocalTime: Equatable, Hashable, Sendable, Codable, CustomStringConvertible { + /// The hour component of the local time. + public var hour: UInt8 + /// The minute component of the local time. + public var minute: UInt8 + /// The second component of the local time. + public var second: UInt8 + /// The fractional second component of the local time in nanoseconds. + public var nanosecond: UInt32 + + /// Create a new local time from it's members. + /// + /// This initializer validates the components. + /// A invalid component causes a error to be thrown. + /// + /// - Parameters: + /// - hour: The hour component of the local time. + /// - minute: The minute component of the local time. + /// - second: The second component of the local time. + /// - nanosecond: The fractional second component of the local time in nanoseconds. + public init(validatingHour hour: UInt8, minute: UInt8, second: UInt8, nanosecond: UInt32 = 0) + throws + { + self.init(hour: hour, minute: minute, second: second, nanosecond: nanosecond) + guard isValid else { + throw TOMLError( + .invalidDateTimeComponents( + "Invalid local time components: \(hour):\(minute):\(second).\(nanosecond)")) + } + } + + /// Create a new local time from it's members. + /// + /// This initializer does not validate the components. + /// Use ``isValid`` to check if the local time is valid. + /// + /// - Parameters: + /// - hour: The hour component of the local time. + /// - minute: The minute component of the local time. + /// - second: The second component of the local time. + /// - nanosecond: The fractional second component of the local time in nanoseconds. + public init(hour: UInt8, minute: UInt8, second: UInt8, nanosecond: UInt32 = 0) { + self.hour = hour + self.minute = minute + self.second = second + self.nanosecond = nanosecond + } + + /// Check if the local time is valid. + public var isValid: Bool { + hour < 24 && minute < 60 && second < 60 && nanosecond < 1_000_000_000 + } + + /// The string representation of the local time. + public var description: String { + let hourStr = hour < 10 ? "0\(hour)" : "\(hour)" + let minuteStr = minute < 10 ? "0\(minute)" : "\(minute)" + let secondStr = second < 10 ? "0\(second)" : "\(second)" + + if nanosecond == 0 { + return "\(hourStr):\(minuteStr):\(secondStr)" + } else { + let nanosecondStr = String(nanosecond).padded(to: 9, with: "0") + let trimmedFractional = nanosecondStr.trimmingSuffix("0") + let finalFractional = trimmedFractional.isEmpty ? "0" : trimmedFractional + return "\(hourStr):\(minuteStr):\(secondStr).\(finalFractional)" + } + } +} + +/// A local date as defined by TOML. +/// +/// ``LocalDate`` stores the year, month, and day components of a date. +public struct LocalDate: Equatable, Hashable, Sendable, Codable, CustomStringConvertible { + /// The year component of the local date. + /// Valid range is [1, 9999]. + public var year: UInt16 + + /// The month component of the local date. + /// Valid range is [1, 12]. + public var month: UInt8 + + /// The day component of the local date. + /// Valid range is depends on the month and year. + public var day: UInt8 + + /// Create a new local date from it's members. + /// + /// This initializer validates the components. + /// A invalid component causes a error to be thrown. + /// + /// - Parameters: + /// - year: The year component of the local date. + /// - month: The month component of the local date. + /// - day: The day component of the local date. + public init(validatingYear year: UInt16, month: UInt8, day: UInt8) throws { + self.init(year: year, month: month, day: day) + guard isValid else { + throw TOMLError( + .invalidDateTimeComponents("Invalid local date components: \(year)-\(month)-\(day)")) + } + } + + /// Create a new local date from it's members. + /// + /// This initializer does not validate the components. + /// Use ``isValid`` to check if the local date is valid. + /// + /// - Parameters: + /// - year: The year component of the local date. + /// - month: The month component of the local date. + /// - day: The day component of the local date. + public init(year: UInt16, month: UInt8, day: UInt8) { + self.year = year + self.month = month + self.day = day + } + + /// Check if the local date is valid. + public var isValid: Bool { + guard month >= 1, month <= 12 else { return false } + guard day >= 1 else { return false } + + let daysInMonth: UInt8 + switch month { + case 1, 3, 5, 7, 8, 10, 12: + daysInMonth = 31 + case 4, 6, 9, 11: + daysInMonth = 30 + case 2: + let isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) + daysInMonth = isLeapYear ? 29 : 28 + default: + return false + } + + return day <= daysInMonth + } + + /// The string representation of the local date. + public var description: String { + let yearStr = String(year).padded(to: 4, with: "0") + let monthStr = month < 10 ? "0\(month)" : "\(month)" + let dayStr = day < 10 ? "0\(day)" : "\(day)" + return "\(yearStr)-\(monthStr)-\(dayStr)" + } +} + +extension String { + fileprivate func padded(to length: Int, with character: Character) -> String { + if count >= length { + return self + } + return String(repeating: character, count: length - count) + self + } + + fileprivate func trimmingSuffix(_ suffix: Character) -> String { + var result = self + while result.last == suffix { + result.removeLast() + } + return result + } +} diff --git a/Sources/TOMLSemantics/LICENSE b/Sources/TOMLSemantics/LICENSE new file mode 100644 index 0000000..a30b4e4 --- /dev/null +++ b/Sources/TOMLSemantics/LICENSE @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2019 TOMLDecoder contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Sources/TOMLSemantics/PATCHES.md b/Sources/TOMLSemantics/PATCHES.md new file mode 100644 index 0000000..31332e5 --- /dev/null +++ b/Sources/TOMLSemantics/PATCHES.md @@ -0,0 +1,39 @@ +# TOML semantic source subset + +Source: TOMLDecoder 0.4.5, revision +`a2bbd2796fe3064e107de18cb56031052c4fa899`, MIT. `provenance.json` +records each copied file's original path and SHA256. `upstream.patch` records +the complete zero-context differences for those exact hashed files, including +repository formatting. +`SemanticBudget.swift` and `SemanticDocument.swift` are package-owned seams. + +The subset contains the parser, token/model/constants, scalar/date validators, +key context and errors. General Decodable containers, public table/array +accessors, Dictionary/Any conversion, executables, tests, documentation, +benchmarks and build plugins are not included. + +Local changes are limited to: + +- Per-operation budget/cancellation propagation through construction, capacity + reservation, recursive descent, token/trivia scans, key comparisons, lazy + scalar decoding and ordered traversal. Original typed throws become ordinary + throwing calls so budget and cancellation errors propagate without casts. +- Exact decoded UTF-8 key comparison, including sampled-hash collisions. Unused + key-transform and String-key Dictionary/Any access paths are removed. Keyed + model types do not synthesize String equality. +- Stable entry source positions for ordered typed traversal. Scalar syntax is + classified before invoking its standard validator. Overflowing integers do + not retry as floating point. Raw numeric lexemes and native atoms remain + separate from Core projection; finite decimal projection removes only TOML + separators and a leading plus, with no floating-point formatting. +- Actual EOF guards after fractional-time scanning and before the month/day + delimiter. No source terminator, sentinel or synthetic newline is appended. +- Required string helper budget propagation and quoted-key validation through + the same standard validators. Decoder-specific date initializers and unused + Foundation date conversion extensions are omitted with the decoder product. +- Repository Swift formatting. + +NativeDocuments owns the JSON syntax, source index, ownership expectations, +patches and full-candidate comparison. This target has no library product and +performs no I/O. Standard-validator failures are translated into safe document +codes by NativeDocuments; upstream error descriptions are never preview text. diff --git a/Sources/TOMLSemantics/Parsing/Constants.swift b/Sources/TOMLSemantics/Parsing/Constants.swift new file mode 100644 index 0000000..34a168c --- /dev/null +++ b/Sources/TOMLSemantics/Parsing/Constants.swift @@ -0,0 +1,109 @@ +enum CodeUnits { + static let escape: UTF8.CodeUnit = 27 + static let equal: UTF8.CodeUnit = 61 + static let comma: UTF8.CodeUnit = 44 + static let lbrace: UTF8.CodeUnit = 123 + static let rbrace: UTF8.CodeUnit = 125 + static let lbracket: UTF8.CodeUnit = 91 + static let rbracket: UTF8.CodeUnit = 93 + static let pound: UTF8.CodeUnit = 35 + static let backslash: UTF8.CodeUnit = 92 + static let backspace: UTF8.CodeUnit = 8 + static let cr: UTF8.CodeUnit = 13 + static let colon: UTF8.CodeUnit = 58 + static let dot: UTF8.CodeUnit = 46 + static let doubleQuote: UTF8.CodeUnit = 34 + static let formfeed: UTF8.CodeUnit = 12 + static let lf: UTF8.CodeUnit = 10 + static let minus: UTF8.CodeUnit = 45 + static let plus: UTF8.CodeUnit = 43 + static let singleQuote: UTF8.CodeUnit = 39 + static let space: UTF8.CodeUnit = 32 + static let tab: UTF8.CodeUnit = 9 + static let underscore: UTF8.CodeUnit = 95 + + static let number0: UTF8.CodeUnit = 48 + static let number1: UTF8.CodeUnit = 49 + static let number7: UTF8.CodeUnit = 55 + static let number9: UTF8.CodeUnit = 57 + + static let lowerA: UTF8.CodeUnit = 97 + static let lowerB: UTF8.CodeUnit = 98 + static let lowerI: UTF8.CodeUnit = 105 + static let lowerE: UTF8.CodeUnit = 101 + static let lowerF: UTF8.CodeUnit = 102 + static let lowerL: UTF8.CodeUnit = 108 + static let lowerS: UTF8.CodeUnit = 115 + static let lowerN: UTF8.CodeUnit = 110 + static let lowerO: UTF8.CodeUnit = 111 + static let lowerR: UTF8.CodeUnit = 114 + static let lowerT: UTF8.CodeUnit = 116 + static let lowerU: UTF8.CodeUnit = 117 + static let lowerX: UTF8.CodeUnit = 120 + static let lowerZ: UTF8.CodeUnit = 122 + static let upperA: UTF8.CodeUnit = 65 + static let upperE: UTF8.CodeUnit = 69 + static let upperF: UTF8.CodeUnit = 70 + static let upperT: UTF8.CodeUnit = 84 + static let upperU: UTF8.CodeUnit = 85 + static let upperZ: UTF8.CodeUnit = 90 + + nonisolated(unsafe) static let isBareKeyChar: UnsafePointer = { + let ptr = UnsafeMutablePointer.allocate(capacity: 256) + ptr.initialize(repeating: false, count: 256) + for i in 0..<256 { + let ch = UTF8.CodeUnit(i) + if (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerZ) + || (ch >= CodeUnits.upperA && ch <= CodeUnits.upperZ) + || (ch >= CodeUnits.number0 && ch <= CodeUnits.number9) || ch == CodeUnits.underscore + || ch == CodeUnits.minus + { + ptr[i] = true + } + } + return UnsafePointer(ptr) + }() + + nonisolated(unsafe) static let isValueChar: UnsafePointer = { + let ptr = UnsafeMutablePointer.allocate(capacity: 256) + ptr.initialize(repeating: false, count: 256) + for i in 0..<256 { + let ch = UTF8.CodeUnit(i) + if (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerZ) + || (ch >= CodeUnits.upperA && ch <= CodeUnits.upperZ) + || (ch >= CodeUnits.number0 && ch <= CodeUnits.number9) || ch == CodeUnits.underscore + || ch == CodeUnits.minus || ch == CodeUnits.plus || ch == CodeUnits.dot + { + ptr[i] = true + } + } + return UnsafePointer(ptr) + }() + + nonisolated(unsafe) static let isBasicStringBodyChar: UnsafePointer = { + let ptr = UnsafeMutablePointer.allocate(capacity: 256) + ptr.initialize(repeating: true, count: 256) + ptr[Int(CodeUnits.backslash)] = false + ptr[Int(CodeUnits.doubleQuote)] = false + ptr[Int(CodeUnits.lf)] = false + return UnsafePointer(ptr) + }() + + static let null: UTF8.CodeUnit = 0x00 + static let unitSeparator: UTF8.CodeUnit = 0x1F + static let delete: UTF8.CodeUnit = 0x7F +} + +extension UTF8.CodeUnit { + @_transparent + var isDecimalDigit: Bool { + CodeUnits.number0 <= self && self <= CodeUnits.number9 + } + + @_transparent + var isHexDigit: Bool { + isDecimalDigit + || CodeUnits.lowerA <= self && self <= CodeUnits.lowerF + || CodeUnits.upperA <= self && self <= CodeUnits.upperF + } +} diff --git a/Sources/TOMLSemantics/Parsing/Parser+Finish.swift b/Sources/TOMLSemantics/Parsing/Parser+Finish.swift new file mode 100644 index 0000000..eafd32d --- /dev/null +++ b/Sources/TOMLSemantics/Parsing/Parser+Finish.swift @@ -0,0 +1,24 @@ +extension Parser { + consuming func finish(source: String) -> TOMLDocument { + var tables: [InternalTOMLTable] = [] + var arrays: [InternalTOMLArray] = [] + var keyTables: [KeyTablePair] = [] + var keyArrays: [KeyArrayPair] = [] + var keyValues: [KeyValuePair] = [] + + swap(&tables, &self.tables) + swap(&arrays, &self.arrays) + swap(&keyTables, &self.keyTables) + swap(&keyArrays, &self.keyArrays) + swap(&keyValues, &self.keyValues) + + return TOMLDocument( + source: source, + tables: tables, + arrays: arrays, + keyTables: keyTables, + keyArrays: keyArrays, + keyValues: keyValues + ) + } +} diff --git a/Sources/TOMLSemantics/Parsing/Parser.swift b/Sources/TOMLSemantics/Parsing/Parser.swift new file mode 100644 index 0000000..8368cb7 --- /dev/null +++ b/Sources/TOMLSemantics/Parsing/Parser.swift @@ -0,0 +1,2679 @@ +struct Parser: ~Copyable { + let budget: SemanticBudget + var depth = 0 + var token = Token.empty + var cursor = 0 + var currentLineNumber = 1 + var currentTable = 0 + var currentTableIsKeyed = false + var tablePath: [(key: String, keyHash: Int)] = [] + var tables: [InternalTOMLTable] = [] + var arrays: [InternalTOMLArray] = [] + var keyTables: [KeyTablePair] = [] + var keyArrays: [KeyArrayPair] = [] + var keyValues: [KeyValuePair] = [] + + mutating func parse(bytes: UnsafeBufferPointer) throws { + try budget.node(depth: 0) + tables.append(InternalTOMLTable()) + let estimatedKeyValues = max(32, bytes.count / 48) + let estimatedNodes = max(8, estimatedKeyValues / 8) + try budget.allocate(max(8, estimatedNodes), stage: "semantic storage") + tables.reserveCapacity(max(8, estimatedNodes)) + try budget.allocate(estimatedNodes, stage: "semantic storage") + arrays.reserveCapacity(estimatedNodes) + try budget.allocate(estimatedNodes, stage: "semantic storage") + keyTables.reserveCapacity(estimatedNodes) + try budget.allocate(estimatedNodes, stage: "semantic storage") + keyArrays.reserveCapacity(estimatedNodes) + try budget.allocate(estimatedKeyValues, stage: "semantic storage") + keyValues.reserveCapacity(estimatedKeyValues) + try budget.allocate(8, stage: "semantic storage") + tablePath.reserveCapacity(8) + + while token.kind != .eof { + try budget.step() + switch token.kind { + case .newline: + try nextToken(bytes: bytes, isDotSpecial: true) + case .string, .bareKey: + try parseKeyValue(bytes: bytes, tableIndex: currentTable, isKeyed: currentTableIsKeyed) + if token.kind != .newline, token.kind != .eof { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "extra chars after value")) + } + if token.kind == .newline { + try eatToken(bytes: bytes, kind: .newline, isDotSpecial: true) + } + case .lbracket: + try parseSelect(bytes: bytes) + default: + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) + } + } + } + + mutating func nextToken(bytes: UnsafeBufferPointer, isDotSpecial: Bool) throws { + let lineNumber = currentLineNumber + var position = cursor + + @inline(__always) + func emitToken(kind: Token.Kind, start: Int, end: Int, newlines: Int = 0) throws { + try budget.node(depth: depth) + token = Token(budget: budget, kind: kind, lineNumber: lineNumber, text: start..= CodeUnits.null && commentChar <= CodeUnits.backspace) + || (commentChar >= CodeUnits.lf && commentChar <= CodeUnits.unitSeparator) + || commentChar == CodeUnits.delete + { + if commentChar == CodeUnits.cr { + let nextPosition = position + 1 + if nextPosition < count, bytes[nextPosition] == CodeUnits.lf { + // Allow CRLF sequence + } else { + throw TOMLError( + .syntax( + lineNumber: lineNumber, + message: "control characters are not allowed in comments" + ) + ) + } + } else { + throw TOMLError( + .syntax( + lineNumber: lineNumber, + message: "control characters are not allowed in comments" + ) + ) + } + } + position += 1 + } + continue + case CodeUnits.space, CodeUnits.tab: + // ignore white spaces + position += 1 + while position < count { + try budget.step() + let ws = bytes[position] + if ws != CodeUnits.space, ws != CodeUnits.tab { + break + } + position += 1 + } + continue + case CodeUnits.dot where isDotSpecial: + try emitToken(kind: .dot, start: position, end: position + 1) + return + case CodeUnits.comma: + try emitToken(kind: .comma, start: position, end: position + 1) + return + case CodeUnits.equal: + try emitToken(kind: .equal, start: position, end: position + 1) + return + case CodeUnits.lbrace: + try emitToken(kind: .lbrace, start: position, end: position + 1) + return + case CodeUnits.rbrace: + try emitToken(kind: .rbrace, start: position, end: position + 1) + return + case CodeUnits.lbracket: + try emitToken(kind: .lbracket, start: position, end: position + 1) + return + case CodeUnits.rbracket: + try emitToken(kind: .rbracket, start: position, end: position + 1) + return + case CodeUnits.lf: + try emitToken(kind: .newline, start: position, end: position + 1, newlines: 1) + return + case CodeUnits.cr: + // Check if this is part of a CRLF sequence + let nextPosition = position + 1 + if nextPosition < count, bytes[nextPosition] == CodeUnits.lf { + // This is CRLF, treat as newline + try emitToken(kind: .newline, start: position, end: nextPosition + 1, newlines: 1) + return + } + // Bare CR is invalid + throw TOMLError( + .syntax( + lineNumber: lineNumber, + message: "bare carriage return is not allowed" + ) + ) + default: + break + } + + func scanString(range: Range, lineNumber: Int) throws { + let start = range.lowerBound + let end = range.upperBound + let head = bytes[start] + if (head >= CodeUnits.lowerA && head <= CodeUnits.lowerZ) + || (head >= CodeUnits.upperA && head <= CodeUnits.upperZ) || head == CodeUnits.underscore + { + let isBareKeyChar = CodeUnits.isBareKeyChar + var index = start + 1 + while index < end { + try budget.step() + let ch = bytes[index] + if isBareKeyChar[Int(ch)] { + index += 1 + continue + } + break + } + try emitToken(kind: .bareKey, start: start, end: index) + return + } + + if head == CodeUnits.singleQuote { + if start + 3 <= end, + bytes[start + 1] == CodeUnits.singleQuote, + bytes[start + 2] == CodeUnits.singleQuote + { + var i = start + 3 + var newlinesInToken = 0 + + while i < end { + try budget.step() + if bytes[i] == CodeUnits.lf { + newlinesInToken += 1 + } + if i + 3 <= end, + bytes[i] == CodeUnits.singleQuote, + bytes[i + 1] == CodeUnits.singleQuote, + bytes[i + 2] == CodeUnits.singleQuote + { + if i + 3 >= end || bytes[i + 3] != CodeUnits.singleQuote { + break + } + } + i += 1 + } + + guard i < end else { + throw TOMLError( + .syntax(lineNumber: lineNumber, message: "unterminated triple-s-quote") + ) + } + + try emitToken(kind: .string, start: start, end: i + 3, newlines: newlinesInToken) + return + } + + var i = start + 1 + while i < end { + try budget.step() + let ch = bytes[i] + if ch == CodeUnits.singleQuote || ch == CodeUnits.lf { + break + } + i += 1 + } + + if i >= end || bytes[i] != CodeUnits.singleQuote { + throw TOMLError( + .syntax(lineNumber: lineNumber, message: "unterminated s-quote") + ) + } + + try emitToken(kind: .string, start: start, end: i + 1) + return + } + + if head == CodeUnits.doubleQuote { + if start + 3 < end, + bytes[start + 1] == CodeUnits.doubleQuote, + bytes[start + 2] == CodeUnits.doubleQuote + { + var i = start + 3 + var newlinesInToken = 0 + + while i < end { + try budget.step() + if bytes[i] == CodeUnits.lf { + newlinesInToken += 1 + } + if i + 3 <= end, + bytes[i] == CodeUnits.doubleQuote, + bytes[i + 1] == CodeUnits.doubleQuote, + bytes[i + 2] == CodeUnits.doubleQuote + { + if i + 3 >= end || bytes[i + 3] != CodeUnits.doubleQuote { + if bytes[i - 1] == CodeUnits.backslash { + i += 1 + continue + } + break + } + } + i += 1 + } + + guard i < end else { + throw TOMLError( + .syntax(lineNumber: lineNumber, message: "unterminated triple-d-quote") + ) + } + + try emitToken(kind: .string, start: start, end: i + 3, newlines: newlinesInToken) + return + } + + var i = start + 1 + let isBasicStringBodyChar = CodeUnits.isBasicStringBodyChar + let baseAddress = bytes.baseAddress! + while i + 8 <= end { + try budget.step() + let chunk = UnsafeRawPointer(baseAddress.advanced(by: i)).loadUnaligned( + as: UInt64.self + ) + if chunkContainsDoubleQuotedStopByte(chunk) { + break + } + i += 8 + } + + while i < end { + try budget.step() + let ch = bytes[i] + if isBasicStringBodyChar[Int(ch)] { + i += 1 + continue + } + if ch == CodeUnits.backslash { + i += 1 + if i < end { + i += 1 + continue + } + break + } + + break + } + + if i >= end || bytes[i] != CodeUnits.doubleQuote { + throw TOMLError( + .syntax(lineNumber: lineNumber, message: "unterminated quote") + ) + } + + try emitToken(kind: .string, start: start, end: i + 1) + return + } + + if !isDotSpecial { + var index = start + var dateEnder: Int? + // Fast path: Dates must produce YYYY-MM-DD, so checks for the dash + if start + 4 < end && bytes[start + 4] == CodeUnits.minus { + dateEnder = scanDate(bytes: bytes, range: range)?.3 + } + + if let dateEnder, dateEnder < end, + bytes[dateEnder] == CodeUnits.upperT || bytes[dateEnder] == CodeUnits.lowerT + || bytes[dateEnder] == CodeUnits.space + { + let timeStarter = dateEnder + 1 + if let timeEnder = scanTime( + bytes: bytes, range: timeStarter.. start { + if index < end { + if bytes[index] == CodeUnits.dot { + index += 1 + while index < end, bytes[index] >= CodeUnits.number0, + bytes[index] <= CodeUnits.number9 + { + try budget.step() + index += 1 + } + } + if index < end, bytes[index] == CodeUnits.upperZ || bytes[index] == CodeUnits.lowerZ { + index += 1 + } else if let timzoneEnder = scanTimezoneOffset( + bytes: bytes, range: index.. start, bytes[index - 1] == CodeUnits.space { + try budget.step() + index -= 1 + } + // tokenize + try emitToken(kind: .string, start: start, end: index) + return + } + } + + if isDotSpecial { + let isBareKeyChar = CodeUnits.isBareKeyChar + var index = start + while index < end, isBareKeyChar[Int(bytes[index])] { + try budget.step() + index += 1 + } + if index >= end || bytes[index] != CodeUnits.plus { + try emitToken(kind: .bareKey, start: start, end: index) + return + } + + index += 1 + while index < end { + try budget.step() + let ch = bytes[index] + if isBareKeyChar[Int(ch)] || ch == CodeUnits.plus { + index += 1 + continue + } + break + } + try emitToken(kind: .string, start: start, end: index) + } else { + let isValueChar = CodeUnits.isValueChar + var index = start + while index < end { + try budget.step() + let ch = bytes[index] + if isValueChar[Int(ch)] { + index += 1 + continue + } + break + } + try emitToken(kind: .string, start: start, end: index) + } + } + + try scanString(range: position.., kind: Token.Kind, isDotSpecial: Bool) + throws + { + if token.kind != kind { + throw TOMLError(.internalError(lineNumber: token.lineNumber)) + } + try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) + } + + mutating func createKeyValue( + bytes: UnsafeBufferPointer, + token: Token, + value: Token, + inTable tableIndex: Int, + isKeyed: Bool + ) throws { + let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token) + if try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) != nil { + throw TOMLError(.badKey(lineNumber: token.lineNumber)) + } + let index = keyValues.count + try budget.node(depth: depth) + keyValues.append( + KeyValuePair(key: key, keyHash: keyHash, sourcePosition: token.text.lowerBound, value: value)) + + if isKeyed { + if keyTables[tableIndex].table.keyValues.isEmpty { + try budget.allocate(8, stage: "semantic storage") + keyTables[tableIndex].table.keyValues.reserveCapacity(8) + } + try budget.node(depth: depth) + keyTables[tableIndex].table.keyValues.append(index) + keyTables[tableIndex].table.recordKeyHash(keyHash) + } else { + if tables[tableIndex].keyValues.isEmpty { + try budget.allocate(8, stage: "semantic storage") + tables[tableIndex].keyValues.reserveCapacity(8) + } + try budget.node(depth: depth) + tables[tableIndex].keyValues.append(index) + tables[tableIndex].recordKeyHash(keyHash) + } + } + + mutating func createKeyTable( + bytes: UnsafeBufferPointer, token: Token, inTable tableIndex: Int, isKeyed: Bool, + implicit: Bool = false + ) throws -> Int { + let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token) + return try createKeyTable( + normalizedKey: key, + keyHash: keyHash, + lineNumber: token.lineNumber, + inTable: tableIndex, + isKeyed: isKeyed, + implicit: implicit + ) + } + + mutating func createKeyTable( + normalizedKey key: String, keyHash: Int, lineNumber: Int, inTable tableIndex: Int, + isKeyed: Bool, implicit: Bool = false + ) throws -> Int { + // Check if parent table is readOnly (inline table) + if isKeyed ? keyTables[tableIndex].table.readOnly : tables[tableIndex].readOnly { + throw TOMLError(.syntax(lineNumber: lineNumber, message: "cannot add to inline table")) + } + + switch try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) { + case .table(let existingTableIndex): + if keyTables[existingTableIndex].table.implicit { + if keyTables[existingTableIndex].table.definedByDottedKey { + throw TOMLError(.keyExists(lineNumber: lineNumber)) + } + keyTables[existingTableIndex].table.implicit = false + return existingTableIndex + } + throw TOMLError(.keyExists(lineNumber: lineNumber)) + case .keyValue, .array: + throw TOMLError(.keyExists(lineNumber: lineNumber)) + case nil: + break + } + let index = keyTables.count + var newTable = InternalTOMLTable() + newTable.implicit = implicit + newTable.definedByDottedKey = implicit + try budget.node(depth: depth) + keyTables.append( + KeyTablePair( + key: key, keyHash: keyHash, sourcePosition: token.text.lowerBound, table: newTable)) + + if isKeyed { + if keyTables[tableIndex].table.tables.isEmpty { + try budget.allocate(8, stage: "semantic storage") + keyTables[tableIndex].table.tables.reserveCapacity(8) + } + try budget.node(depth: depth) + keyTables[tableIndex].table.tables.append(index) + keyTables[tableIndex].table.recordKeyHash(keyHash) + } else { + if tables[tableIndex].tables.isEmpty { + try budget.allocate(8, stage: "semantic storage") + tables[tableIndex].tables.reserveCapacity(8) + } + try budget.node(depth: depth) + tables[tableIndex].tables.append(index) + tables[tableIndex].recordKeyHash(keyHash) + } + return index + } + + mutating func createKeyArray( + bytes: UnsafeBufferPointer, token: Token, inTable tableIndex: Int, isKeyed: Bool, + kind: InternalTOMLArray.Kind? = nil + ) throws -> Int { + let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token) + return try createKeyArray( + normalizedKey: key, + keyHash: keyHash, + lineNumber: token.lineNumber, + inTable: tableIndex, + isKeyed: isKeyed, + kind: kind + ) + } + + mutating func createKeyArray( + normalizedKey key: String, keyHash: Int, lineNumber: Int, inTable tableIndex: Int, + isKeyed: Bool, kind: InternalTOMLArray.Kind? = nil + ) throws -> Int { + if try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) != nil { + throw TOMLError(.keyExists(lineNumber: lineNumber)) + } + + let index = keyArrays.count + var array = InternalTOMLArray(kind: kind) + if kind == .table { + try budget.allocate(8, stage: "semantic storage") + array.elements.reserveCapacity(8) + } + try budget.node(depth: depth) + keyArrays.append( + KeyArrayPair(key: key, keyHash: keyHash, sourcePosition: token.text.lowerBound, array: array)) + if isKeyed { + if keyTables[tableIndex].table.arrays.isEmpty { + try budget.allocate(8, stage: "semantic storage") + keyTables[tableIndex].table.arrays.reserveCapacity(8) + } + try budget.node(depth: depth) + keyTables[tableIndex].table.arrays.append(index) + keyTables[tableIndex].table.recordKeyHash(keyHash) + } else { + if tables[tableIndex].arrays.isEmpty { + try budget.allocate(8, stage: "semantic storage") + tables[tableIndex].arrays.reserveCapacity(8) + } + try budget.node(depth: depth) + tables[tableIndex].arrays.append(index) + tables[tableIndex].recordKeyHash(keyHash) + } + return index + } + + @inline(__always) + mutating func skipNewlines(bytes: UnsafeBufferPointer, isDotSpecial: Bool) throws { + if token.kind != .newline { + return + } + + let count = bytes.count + var position = cursor + var lineNumber = currentLineNumber + + while position < count { + try budget.step() + let ch = bytes[position] + if ch == CodeUnits.space || ch == CodeUnits.tab { + // 8x unrolling for space/tab skipping + while position + 8 <= count { + try budget.step() + let c0 = bytes[position] + let c1 = bytes[position + 1] + let c2 = bytes[position + 2] + let c3 = bytes[position + 3] + let c4 = bytes[position + 4] + let c5 = bytes[position + 5] + let c6 = bytes[position + 6] + let c7 = bytes[position + 7] + + if c0 == CodeUnits.space || c0 == CodeUnits.tab, + c1 == CodeUnits.space || c1 == CodeUnits.tab, + c2 == CodeUnits.space || c2 == CodeUnits.tab, + c3 == CodeUnits.space || c3 == CodeUnits.tab, + c4 == CodeUnits.space || c4 == CodeUnits.tab, + c5 == CodeUnits.space || c5 == CodeUnits.tab, + c6 == CodeUnits.space || c6 == CodeUnits.tab, + c7 == CodeUnits.space || c7 == CodeUnits.tab + { + position += 8 + } else { + break + } + } + + while position < count { + try budget.step() + let ws = bytes[position] + if ws != CodeUnits.space, ws != CodeUnits.tab { + break + } + position += 1 + } + continue + } + switch ch { + case CodeUnits.lf: + lineNumber += 1 + position += 1 + case CodeUnits.cr: + if position + 1 < count, bytes[position + 1] == CodeUnits.lf { + lineNumber += 1 + position += 2 + } else { + // Bare CR, let nextToken handle error + cursor = position + currentLineNumber = lineNumber + try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) + return + } + case CodeUnits.pound: + // Comment + position += 1 + while position < count { + try budget.step() + let c = bytes[position] + if c == CodeUnits.lf { + break // Leave LF for next iteration to handle line number + } + if (c >= CodeUnits.null && c <= CodeUnits.backspace) + || (c >= CodeUnits.lf && c <= CodeUnits.unitSeparator) || c == CodeUnits.delete + { + if c == CodeUnits.cr { + if position + 1 < count, bytes[position + 1] == CodeUnits.lf { + // CRLF ends comment + break + } + } + // Let nextToken throw the error + cursor = position + currentLineNumber = lineNumber + try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) + return + } + position += 1 + } + default: + // Found something else, stop skipping + cursor = position + currentLineNumber = lineNumber + try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) + return + } + } + + // If we hit EOF or loop finishes + cursor = position + currentLineNumber = lineNumber + try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) + } + + mutating func parseKeyedInlineTable(bytes: UnsafeBufferPointer, tableIndex: Int) throws { + try budget.enter(depth + 1) + depth += 1 + defer { depth -= 1 } + try eatToken(bytes: bytes, kind: .lbrace, isDotSpecial: true) + + while true { + try budget.step() + try skipNewlines(bytes: bytes, isDotSpecial: false) + + if token.kind == .rbrace { + break + } + + if token.kind != .string, token.kind != .bareKey { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expect a string")) + } + + try parseKeyValue(bytes: bytes, tableIndex: tableIndex, isKeyed: true) + + try skipNewlines(bytes: bytes, isDotSpecial: false) + + if token.kind == .comma { + try eatToken(bytes: bytes, kind: .comma, isDotSpecial: true) + continue + } + break + } + + try eatToken(bytes: bytes, kind: .rbrace, isDotSpecial: true) + + keyTables[tableIndex].table.readOnly = true + } + + mutating func parseInlineTable(bytes: UnsafeBufferPointer, tableIndex: Int) throws { + try budget.enter(depth + 1) + depth += 1 + defer { depth -= 1 } + try eatToken(bytes: bytes, kind: .lbrace, isDotSpecial: true) + + while true { + try budget.step() + try skipNewlines(bytes: bytes, isDotSpecial: false) + + if token.kind == .rbrace { + break + } + + if token.kind != .string, token.kind != .bareKey { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expect a string")) + } + + try parseKeyValue(bytes: bytes, tableIndex: tableIndex, isKeyed: false) + + try skipNewlines(bytes: bytes, isDotSpecial: false) + + if token.kind == .comma { + try eatToken(bytes: bytes, kind: .comma, isDotSpecial: true) + continue + } + break + } + + try eatToken(bytes: bytes, kind: .rbrace, isDotSpecial: true) + + tables[tableIndex].readOnly = true + } + + mutating func parseKeyedArray(bytes: UnsafeBufferPointer, arrayIndex: Int) throws { + try budget.enter(depth + 1) + depth += 1 + defer { depth -= 1 } + try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: false) + + while true { + try budget.step() + try skipNewlines(bytes: bytes, isDotSpecial: false) + + if token.kind == .rbracket { + break + } + if keyArrays[arrayIndex].array.elements.isEmpty { + try budget.allocate(8, stage: "semantic storage") + keyArrays[arrayIndex].array.elements.reserveCapacity(8) + } + + switch token.kind { + case .string, .bareKey: + if keyArrays[arrayIndex].array.kind == nil { + keyArrays[arrayIndex].array.kind = .value + } else if keyArrays[arrayIndex].array.kind != .value { + keyArrays[arrayIndex].array.kind = .mixed + } + + try budget.node(depth: depth) + keyArrays[arrayIndex].array.elements.append(.leaf(token)) + + try nextToken(bytes: bytes, isDotSpecial: true) + + case .lbracket: // Nested array + if keyArrays[arrayIndex].array.kind == nil { + keyArrays[arrayIndex].array.kind = .array + } else if keyArrays[arrayIndex].array.kind != .array { + keyArrays[arrayIndex].array.kind = .mixed + } + + let newArrayIndex = arrays.count + try budget.node(depth: depth) + arrays.append(InternalTOMLArray()) + try budget.node(depth: depth) + keyArrays[arrayIndex].array.elements.append( + .array(lineNumber: token.lineNumber, newArrayIndex)) + + try parseArray(bytes: bytes, arrayIndex: newArrayIndex) + + case .lbrace: // Nested table + if keyArrays[arrayIndex].array.kind == nil { + keyArrays[arrayIndex].array.kind = .table + } else if keyArrays[arrayIndex].array.kind != .table { + keyArrays[arrayIndex].array.kind = .mixed + } + + let newTableIndex = tables.count + try budget.node(depth: depth) + tables.append(InternalTOMLTable()) + try budget.node(depth: depth) + keyArrays[arrayIndex].array.elements.append( + .table(lineNumber: token.lineNumber, newTableIndex)) + + try parseInlineTable(bytes: bytes, tableIndex: newTableIndex) + + default: + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) + } + + try skipNewlines(bytes: bytes, isDotSpecial: false) + + if token.kind == .comma { + try eatToken(bytes: bytes, kind: .comma, isDotSpecial: false) + continue + } + break + } + + try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) + } + + mutating func parseArray(bytes: UnsafeBufferPointer, arrayIndex: Int) throws { + try budget.enter(depth + 1) + depth += 1 + defer { depth -= 1 } + try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: false) + + while true { + try budget.step() + try skipNewlines(bytes: bytes, isDotSpecial: false) + + if token.kind == .rbracket { + break + } + if arrays[arrayIndex].elements.isEmpty { + try budget.allocate(8, stage: "semantic storage") + arrays[arrayIndex].elements.reserveCapacity(8) + } + + switch token.kind { + case .string, .bareKey: + if arrays[arrayIndex].kind == nil { + arrays[arrayIndex].kind = .value + } else if arrays[arrayIndex].kind != .value { + arrays[arrayIndex].kind = .mixed + } + + try budget.node(depth: depth) + arrays[arrayIndex].elements.append(.leaf(token)) + + try nextToken(bytes: bytes, isDotSpecial: true) + + case .lbracket: // Nested array + if arrays[arrayIndex].kind == nil { + arrays[arrayIndex].kind = .array + } else if arrays[arrayIndex].kind != .array { + arrays[arrayIndex].kind = .mixed + } + + let newArrayIndex = arrays.count + try budget.node(depth: depth) + arrays.append(InternalTOMLArray()) + try budget.node(depth: depth) + arrays[arrayIndex].elements.append(.array(lineNumber: token.lineNumber, newArrayIndex)) + + try parseArray(bytes: bytes, arrayIndex: newArrayIndex) + + case .lbrace: // Nested table + if arrays[arrayIndex].kind == nil { + arrays[arrayIndex].kind = .table + } else if arrays[arrayIndex].kind != .table { + arrays[arrayIndex].kind = .mixed + } + + let newTableIndex = tables.count + try budget.node(depth: depth) + tables.append(InternalTOMLTable()) + try budget.node(depth: depth) + arrays[arrayIndex].elements.append(.table(lineNumber: token.lineNumber, newTableIndex)) + + try parseInlineTable(bytes: bytes, tableIndex: newTableIndex) + + default: + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) + } + + try skipNewlines(bytes: bytes, isDotSpecial: false) + + if token.kind == .comma { + try eatToken(bytes: bytes, kind: .comma, isDotSpecial: false) + continue + } + break + } + + try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) + } + + mutating func parseKeyValue(bytes: UnsafeBufferPointer, tableIndex: Int, isKeyed: Bool) + throws + { + if isKeyed ? keyTables[tableIndex].table.readOnly : tables[tableIndex].readOnly { + throw TOMLError( + .syntax( + lineNumber: token.lineNumber, message: "cannot insert new entry into existing table")) + } + + let key = token + try nextToken(bytes: bytes, isDotSpecial: true) + + if token.kind == .dot { + let (subTableKey, subTableHash) = try normalizeKeyAndHash( + bytes: bytes, + token: key + ) + let subTableIndex: Int + + if let existingTableIndex = try lookupTable( + in: tableIndex, keyed: isKeyed, key: subTableKey, keyHash: subTableHash) + { + // Check if the existing table is explicitly defined (not implicit) + if !keyTables[existingTableIndex].table.implicit { + throw TOMLError( + .syntax( + lineNumber: token.lineNumber, + message: "cannot add to explicitly defined table using dotted keys")) + } + subTableIndex = existingTableIndex + } else { + subTableIndex = try createKeyTable( + normalizedKey: subTableKey, + keyHash: subTableHash, + lineNumber: key.lineNumber, + inTable: tableIndex, + isKeyed: isKeyed, + implicit: true + ) + } + + try nextToken(bytes: bytes, isDotSpecial: true) + try parseKeyValue(bytes: bytes, tableIndex: subTableIndex, isKeyed: true) + return + } + + if token.kind != .equal { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "missing =")) + } + + try nextToken(bytes: bytes, isDotSpecial: false) + + if token.kind == .string || token.kind == .bareKey { + try createKeyValue( + bytes: bytes, token: key, value: token, inTable: tableIndex, isKeyed: isKeyed) + try nextToken(bytes: bytes, isDotSpecial: false) + return + } + + if token.kind == .lbracket { + let index = try createKeyArray( + bytes: bytes, token: key, inTable: tableIndex, isKeyed: isKeyed) + try parseKeyedArray(bytes: bytes, arrayIndex: index) + return + } + + if token.kind == .lbrace { + let index = try createKeyTable( + bytes: bytes, token: key, inTable: tableIndex, isKeyed: isKeyed) + try parseKeyedInlineTable(bytes: bytes, tableIndex: index) + return + } + + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) + } + + mutating func fillTablePath(bytes: UnsafeBufferPointer, clearPath: Bool = true) throws -> ( + key: String, + keyHash: Int, + token: Token + ) { + let lineNumber = token.lineNumber + if clearPath { + tablePath.removeAll(keepingCapacity: true) + } + + while true { + try budget.step() + if token.kind != .string, token.kind != .bareKey { + throw TOMLError(.syntax(lineNumber: lineNumber, message: "invalid or missing key")) + } + + let currentToken = token + let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token) + try nextToken(bytes: bytes, isDotSpecial: true) + + if token.kind == .rbracket { + return (key: key, keyHash: keyHash, token: currentToken) + } + + try budget.node(depth: depth) + tablePath.append((key: key, keyHash: keyHash)) + + if token.kind != .dot { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) + } + + try nextToken(bytes: bytes, isDotSpecial: true) + } + } + + mutating func parseSelect(bytes: UnsafeBufferPointer) throws { + assert(token.kind == .lbracket) + let nextIndex = token.text.lowerBound + 1 + let llb = nextIndex < bytes.count && bytes[nextIndex] == CodeUnits.lbracket + if llb { + cursor = nextIndex + 1 + try nextToken(bytes: bytes, isDotSpecial: true) + } else { + try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: true) + } + + if token.kind != .string, token.kind != .bareKey { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid or missing key")) + } + + let firstToken = token + let firstIsBare = firstToken.kind == .bareKey + let firstKey: String? + let firstKeyHash: Int + if firstIsBare { + firstKey = nil + firstKeyHash = fastKeyHash(bytes: bytes, range: firstToken.text) + } else { + let normalized = try normalizeKeyAndHash( + bytes: bytes, + token: firstToken + ) + firstKey = normalized.key + firstKeyHash = normalized.keyHash + } + try nextToken(bytes: bytes, isDotSpecial: true) + + if token.kind == .rbracket { + currentTable = 0 + currentTableIsKeyed = false + if !llb { + let key = try firstKey ?? makeString(budget: budget, bytes: bytes, range: firstToken.text) + currentTable = try createKeyTable( + normalizedKey: key, + keyHash: firstKeyHash, + lineNumber: firstToken.lineNumber, + inTable: currentTable, + isKeyed: currentTableIsKeyed + ) + currentTableIsKeyed = true + } else { + let arrayIndex: Int + if firstIsBare { + if let existingArrayIndex = try lookupArray( + in: currentTable, + keyed: currentTableIsKeyed, + bytes: bytes, + token: firstToken, + keyHash: firstKeyHash + ) { + arrayIndex = existingArrayIndex + } else { + let key = try makeString(budget: budget, bytes: bytes, range: firstToken.text) + arrayIndex = try createKeyArray( + normalizedKey: key, + keyHash: firstKeyHash, + lineNumber: firstToken.lineNumber, + inTable: currentTable, + isKeyed: currentTableIsKeyed, + kind: .table + ) + } + } else { + let key = firstKey! + if let existingArrayIndex = try lookupArray( + in: currentTable, + keyed: currentTableIsKeyed, + key: key, + keyHash: firstKeyHash + ) { + arrayIndex = existingArrayIndex + } else { + arrayIndex = try createKeyArray( + normalizedKey: key, + keyHash: firstKeyHash, + lineNumber: firstToken.lineNumber, + inTable: currentTable, + isKeyed: currentTableIsKeyed, + kind: .table + ) + } + } + if keyArrays[arrayIndex].array.kind != .table { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "array mismatch")) + } + + let newTableIndex = tables.count + try budget.node(depth: depth) + tables.append(InternalTOMLTable()) + try budget.node(depth: depth) + keyArrays[arrayIndex].array.elements.append( + .table(lineNumber: token.lineNumber, newTableIndex)) + currentTable = newTableIndex + currentTableIsKeyed = false + } + } else { + if token.kind != .dot { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) + } + + let firstPathKey = + try firstKey ?? makeString(budget: budget, bytes: bytes, range: firstToken.text) + var pathTableIndex = 0 + var pathTableIsKeyed = false + try advanceTablePathSegment( + tableIndex: &pathTableIndex, + isKeyed: &pathTableIsKeyed, + key: firstPathKey, + keyHash: firstKeyHash + ) + + try nextToken(bytes: bytes, isDotSpecial: true) + if token.kind != .string, token.kind != .bareKey { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid or missing key")) + } + + let secondToken = token + let (secondKey, secondKeyHash) = try normalizeKeyAndHash( + bytes: bytes, + token: secondToken + ) + try nextToken(bytes: bytes, isDotSpecial: true) + + let key: String + let keyHash: Int + let keyToken: Token + + if token.kind == .rbracket { + currentTable = pathTableIndex + currentTableIsKeyed = pathTableIsKeyed + key = secondKey + keyHash = secondKeyHash + keyToken = secondToken + } else { + tablePath.removeAll(keepingCapacity: true) + try budget.node(depth: depth) + tablePath.append((key: secondKey, keyHash: secondKeyHash)) + if token.kind != .dot { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) + } + try nextToken(bytes: bytes, isDotSpecial: true) + + let terminal = try fillTablePath(bytes: bytes, clearPath: false) + key = terminal.key + keyHash = terminal.keyHash + keyToken = terminal.token + try walkTablePath(startTable: pathTableIndex, startKeyed: pathTableIsKeyed) + } + + if !llb { + currentTable = try createKeyTable( + normalizedKey: key, + keyHash: keyHash, + lineNumber: keyToken.lineNumber, + inTable: currentTable, + isKeyed: currentTableIsKeyed + ) + currentTableIsKeyed = true + } else { + let arrayIndex: Int = + if let existingArrayIndex = try lookupArray( + in: currentTable, + keyed: currentTableIsKeyed, + key: key, + keyHash: keyHash + ) { + existingArrayIndex + } else { + try createKeyArray( + normalizedKey: key, + keyHash: keyHash, + lineNumber: keyToken.lineNumber, + inTable: currentTable, + isKeyed: currentTableIsKeyed, + kind: .table + ) + } + if keyArrays[arrayIndex].array.kind != .table { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "array mismatch")) + } + + let newTableIndex = tables.count + try budget.node(depth: depth) + tables.append(InternalTOMLTable()) + try budget.node(depth: depth) + keyArrays[arrayIndex].array.elements.append( + .table(lineNumber: token.lineNumber, newTableIndex)) + currentTable = newTableIndex + currentTableIsKeyed = false + } + } + + if token.kind != .rbracket { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expects ]")) + } + + if llb { + guard cursor < bytes.count, bytes[cursor] == CodeUnits.rbracket else { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expects ]]")) + } + cursor += 1 + try nextToken(bytes: bytes, isDotSpecial: true) + } else { + try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) + } + + if token.kind != .newline, token.kind != .eof { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "extra chars after ] or ]]")) + } + } +} + +extension Token { + func unpackBool(bytes: UnsafeBufferPointer, context: TOMLKey) throws -> Bool { + try budget.allocate(text.count, stage: "scalar decode") + try budget.step(text.count) + if text.count == 4, + bytes[text.lowerBound] == CodeUnits.lowerT, + bytes[text.lowerBound + 1] == CodeUnits.lowerR, + bytes[text.lowerBound + 2] == CodeUnits.lowerU, + bytes[text.lowerBound + 3] == CodeUnits.lowerE + { + return true + } else if text.count == 5, + bytes[text.lowerBound] == CodeUnits.lowerF, + bytes[text.lowerBound + 1] == CodeUnits.lowerA, + bytes[text.lowerBound + 2] == CodeUnits.lowerL, + bytes[text.lowerBound + 3] == CodeUnits.lowerS, + bytes[text.lowerBound + 4] == CodeUnits.lowerE + { + return false + } + + throw TOMLError(.invalidBool(context: context, lineNumber: lineNumber)) + } + + func unpackFloat(bytes: UnsafeBufferPointer, context: TOMLKey) throws -> Double { + try budget.allocate(text.count, stage: "scalar decode") + try budget.step(text.count) + var resultCodeUnits: [UTF8.CodeUnit] = [] + var index = text.lowerBound + if bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus { + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(bytes[index]) + index += 1 + } + guard index < text.upperBound else { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, reason: "expected digit, nan or inf after sign") + ) + } + + if !bytes[index].isDecimalDigit { + let nameEnd = index + 3 + guard nameEnd == text.upperBound, + (bytes[index] == CodeUnits.lowerN && bytes[index + 1] == CodeUnits.lowerA + && bytes[index + 2] == CodeUnits.lowerN) + || (bytes[index] == CodeUnits.lowerI && bytes[index + 1] == CodeUnits.lowerN + && bytes[index + 2] == CodeUnits.lowerF) + else { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, + reason: "Expected nan or inf, found \(bytes[index])")) + } + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(bytes[index]) + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(bytes[index + 1]) + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(bytes[index + 2]) + } else { + let nextIndex = index + 1 + if bytes[index] == CodeUnits.number0, + nextIndex < text.upperBound, + case let next = bytes[nextIndex], + next != CodeUnits.dot, next != CodeUnits.lowerE, next != CodeUnits.upperE + { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, + reason: "Float begins with 0 must be followed by a '.', 'e' or 'E'")) + } + + while index < text.upperBound { + try budget.step() + let ch = bytes[index] + index += 1 + + if ch == CodeUnits.underscore { + guard + let last = resultCodeUnits.last, + last.isDecimalDigit + else { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, reason: "'_' must be preceded by a digit") + ) + } + + guard + index < text.upperBound, + case let next = bytes[index], + next.isDecimalDigit + else { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, reason: "'_' must be follewed by a digit") + ) + } + + continue + } else if ch == CodeUnits.dot { + if resultCodeUnits.isEmpty { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, + reason: "First digit of floats cannot be '.'")) + } + + if !resultCodeUnits.last!.isDecimalDigit { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, + reason: "'.' must be preceded by a decimal digit")) + } + + guard index < text.upperBound, bytes[index].isDecimalDigit else { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, reason: "A digit must follow '.'")) + } + + } else if ch == CodeUnits.upperE || ch == CodeUnits.lowerE { + } else if !ch.isDecimalDigit, ch != CodeUnits.plus, ch != CodeUnits.minus { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, reason: "invalid character for float")) + } + + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(ch) + } + } + + guard let double = Double(String(decoding: resultCodeUnits, as: UTF8.self)) else { + throw TOMLError( + .invalidFloat(context: context, lineNumber: lineNumber, reason: "not a float")) + } + + return double + } + + func unpackString(bytes: UnsafeBufferPointer, context: TOMLKey) throws -> String { + try budget.allocate(text.count, stage: "scalar decode") + try budget.step(text.count) + var multiline = false + + if bytes.count == 0 { + throw TOMLError( + .invalidString(context: context, lineNumber: lineNumber, reason: "missing closing quote")) + } + + let quoteChar = bytes[text.lowerBound] + if quoteChar != CodeUnits.doubleQuote, quoteChar != CodeUnits.singleQuote { + throw TOMLError(.typeMismatch(context: context, lineNumber: lineNumber, expected: "string")) + } + var index = text.lowerBound + var endIndex = text.upperBound + + if endIndex - index >= 3 && bytes[index] == CodeUnits.doubleQuote + && bytes[index + 1] == CodeUnits.doubleQuote && bytes[index + 2] == CodeUnits.doubleQuote + || endIndex - index >= 3 && bytes[index] == CodeUnits.singleQuote + && bytes[index + 1] == CodeUnits.singleQuote && bytes[index + 2] == CodeUnits.singleQuote + { + multiline = true + index += 3 + endIndex -= 3 + + if index < endIndex, bytes[index] == CodeUnits.lf { + index += 1 + } else if endIndex - index >= 2, bytes[index] == CodeUnits.cr, + bytes[index + 1] == CodeUnits.lf + { + index += 2 + } + } else { + index = index + 1 + endIndex = endIndex - 1 + guard endIndex >= 0, bytes[endIndex] == quoteChar else { + throw TOMLError( + .invalidString(context: context, lineNumber: lineNumber, reason: "missing closing quote")) + } + } + + if quoteChar == CodeUnits.singleQuote { + return try literalString( + budget: budget, bytes: bytes, range: index.., context: TOMLKey) throws -> Int64 { + try budget.allocate(text.count, stage: "scalar decode") + try budget.step(text.count) + @_transparent + func isValidDigit(_ codeUnit: UTF8.CodeUnit, base: Int) -> Bool { + switch base { + case 10: + codeUnit.isDecimalDigit + case 16: + codeUnit.isHexDigit + case 2: + codeUnit == CodeUnits.number0 || codeUnit == CodeUnits.number1 + case 8: + CodeUnits.number0 <= codeUnit && codeUnit <= CodeUnits.number7 + default: + false + } + } + + var resultCodeUnits: [UTF8.CodeUnit] = [] + var index = text.lowerBound + var base = 10 + var hasSign = false + if bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus { + hasSign = true + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(bytes[index]) + index = text.index(after: index) + } + guard index < text.upperBound else { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, reason: "expected digit after sign")) + } + + if bytes[index] == CodeUnits.underscore { + throw TOMLError( + .invalidInteger(context: context, lineNumber: lineNumber, reason: "cannot start with a '_'") + ) + } + + if bytes[index] == CodeUnits.number0 { + let nextIndex = index + 1 + if nextIndex < text.upperBound { + if bytes[nextIndex] == CodeUnits.lowerX { + if hasSign { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, + reason: "hexadecimal integers cannot have explicit signs")) + } + base = 16 + index += 2 + } else if bytes[nextIndex] == CodeUnits.lowerO { + if hasSign { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, + reason: "octal integers cannot have explicit signs")) + } + base = 8 + index += 2 + } else if bytes[nextIndex] == CodeUnits.lowerB { + if hasSign { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, + reason: "binary integers cannot have explicit signs")) + } + base = 2 + index += 2 + } else if bytes[nextIndex].isDecimalDigit || bytes[nextIndex] == CodeUnits.underscore { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, + reason: "decimal integers cannot have leading zeros")) + } + } + // Single zero is allowed to continue to the main loop + } + guard index < text.upperBound else { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, reason: "expected digit after base prefix")) + } + + while index < text.upperBound { + try budget.step() + let ch = bytes[index] + index += 1 + + if ch == CodeUnits.underscore { + guard + let last = resultCodeUnits.last, + isValidDigit(last, base: base) + else { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, + reason: "cannot use '_' adjacent to a non-digit")) + } + + if index >= text.endIndex { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, reason: "cannot end with a '_'")) + } + + let next = bytes[index] + if next == CodeUnits.underscore { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, reason: "cannot contain consecutive '_'")) + } + guard isValidDigit(next, base: base) else { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, + reason: "cannot use '_' adjacent to a non-digit")) + } + continue + } + + guard isValidDigit(ch, base: base) else { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, reason: "invalid digit for base \(base)")) + } + + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(ch) + } + + let s = String(decoding: resultCodeUnits, as: UTF8.self) + guard let i = Int64(s, radix: base) else { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, + reason: "\(s) is a invalid integer of base \(base)")) + } + return i + } + + func unpackDateTime(bytes: UnsafeBufferPointer, context: TOMLKey) throws + -> DateTimeComponents + { + try budget.allocate(text.count, stage: "scalar decode") + try budget.step(text.count) + var mustParseTime = false + var date: (year: Int, month: Int, day: Int)? + var time: (hour: Int, minute: Int, second: Int)? + + var index = text.lowerBound + if let (year, month, day, _) = scanDate(bytes: bytes, range: text) { + // Validate date components + if month < 1 || month > 12 { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, reason: "month must be between 01 and 12")) + } + if day < 1 { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, reason: "day must be between 01 and 31")) + } + + // Validate days per month and leap years + let isLeapYear = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) + let maxDaysInMonth: Int = + switch month { + case 2: + isLeapYear ? 29 : 28 + case 4, 6, 9, 11: + 30 + default: + 31 + } + + if day > maxDaysInMonth { + if month == 2, !isLeapYear { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, + reason: "February only has 28 days in non-leap years")) + } else if month == 2, isLeapYear { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, + reason: "February only has 29 days in leap years")) + } else { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, + reason: "day \(day) is invalid for month \(month)")) + } + } + + date = (year, month, day) + index += 10 + } + + var features: OffsetDateTime.Features = [] + var nanoseconds: UInt32? + if index < text.upperBound { + if date != nil { + let isSeparatorLowerT = bytes[index] == CodeUnits.lowerT + let isSeparatorUpperT = bytes[index] == CodeUnits.upperT + guard isSeparatorLowerT || isSeparatorUpperT || bytes[index] == CodeUnits.space else { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, + reason: "expected 'T' or 't' or space to separate date and time")) + } + if isSeparatorLowerT { + features.insert(.lowercaseT) + } else if isSeparatorUpperT { + features.insert(.uppercaseT) + } + mustParseTime = true + index += 1 + } else { + // For standalone time values, don't advance index + mustParseTime = true + } + if let (hour, minute, second, newIndex) = scanTime( + bytes: bytes, range: index.. 23 { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, reason: "hour must be between 00 and 23")) + } + if minute > 59 { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, reason: "minute must be between 00 and 59")) + } + if second > 59 { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, reason: "second must be between 00 and 59")) + } + + time = (hour, minute, second) + + index = newIndex + if index < text.upperBound, bytes[index] == CodeUnits.dot { + index += 1 + let beforeNanoIndex = index + nanoseconds = try parseNanoSeconds( + budget: budget, bytes: bytes, range: index.. 24 { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, + reason: "timezone offset hour must be between 00 and 24")) + } + if offsetMinute > 59 { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, + reason: "timezone offset minute must be between 00 and 59")) + } + + let offsetInMinutes = offsetHour * 60 + offsetMinute + timeOffset = Int16(offsetIsNegative ? -offsetInMinutes : offsetInMinutes) + index += consumedLength + } catch let parseError { + if let tomlError = parseError as? TOMLError { + switch tomlError.reason { + case .invalidDateTime(_, let reason): + throw TOMLError( + .invalidDateTime3(context: context, lineNumber: lineNumber, reason: reason)) + default: + throw tomlError + } + } else { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, reason: "timezone parsing error")) + } + } + } + } + + if index < text.upperBound { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, reason: "extra character after date time")) + } + + return DateTimeComponents( + date: date.map { + LocalDate(year: .init($0.year), month: .init($0.month), day: .init($0.day)) + }, + time: time.map { + LocalTime( + hour: .init($0.hour), minute: .init($0.minute), second: .init($0.second), + nanosecond: nanoseconds ?? 0) + }, + offset: timeOffset, + features: features + ) + } + +} + +func parseTimezoneOffset(bytes: UnsafeBufferPointer, range: Range, lineNumber: Int) + throws -> (hour: Int, minute: Int, consumedLength: Int) +{ + guard range.count >= 2 else { + throw TOMLError( + .invalidDateTime( + lineNumber: lineNumber, reason: "timezone offset must have at least 2 digits for hour")) + } + + var index = range.lowerBound + + // Parse hour digits (exactly 2 required) + guard + index < range.upperBound, + bytes[index].isDecimalDigit, + case let firstHourDigit = bytes[index], + case let nextIndex = index + 1, + nextIndex < range.upperBound, + bytes[nextIndex].isDecimalDigit, + case let secondHourDigit = bytes[nextIndex] + else { + throw TOMLError( + .invalidDateTime( + lineNumber: lineNumber, reason: "timezone offset hour must be exactly 2 digits")) + } + + let offsetHour = + Int(firstHourDigit - CodeUnits.number0) * 10 + Int(secondHourDigit - CodeUnits.number0) + index += 2 + var consumedLength = 2 + + // Parse required minute digits (timezone offset must include minutes) + guard index < range.upperBound, bytes[index] == CodeUnits.colon else { + throw TOMLError( + .invalidDateTime( + lineNumber: lineNumber, reason: "timezone offset must include minutes (format: ±HH:MM)")) + } + + index += 1 + consumedLength += 1 + + guard + index < range.upperBound, + bytes[index].isDecimalDigit, + case let firstMinuteDigit = bytes[index], + case let nextMinuteIndex = index + 1, + nextMinuteIndex < range.upperBound, + bytes[nextMinuteIndex].isDecimalDigit, + case let secondMinuteDigit = bytes[nextMinuteIndex] + else { + throw TOMLError( + .invalidDateTime( + lineNumber: lineNumber, reason: "timezone offset minute must be exactly 2 digits")) + } + + let offsetMinute = + Int(firstMinuteDigit - CodeUnits.number0) * 10 + Int(secondMinuteDigit - CodeUnits.number0) + consumedLength += 2 + + return (offsetHour, offsetMinute, consumedLength) +} + +func literalString( + budget: SemanticBudget, bytes: UnsafeBufferPointer, range: Range, multiline: Bool +) throws -> String { + var resultCodeUnits: [UTF8.CodeUnit] = [] + var consecutiveQuotes = 0 + + for index in range { + try budget.step() + let codeUnit = bytes[index] + if codeUnit >= CodeUnits.null && codeUnit <= CodeUnits.backspace + || codeUnit >= CodeUnits.lf && codeUnit <= CodeUnits.unitSeparator + || codeUnit == CodeUnits.delete + { + if multiline, codeUnit == CodeUnits.lf { + // Allow LF in multiline literal strings + } else if multiline, codeUnit == CodeUnits.cr { + // Only allow CR if followed by LF (CRLF sequence) + let nextIndex = index + 1 + if nextIndex < range.upperBound, bytes[nextIndex] == CodeUnits.lf { + // Allow CRLF sequence - will be processed as separate characters + } else { + throw TOMLError(.invalidCharacter(codeUnit)) + } + } else { + throw TOMLError(.invalidCharacter(codeUnit)) + } + } + + if multiline, codeUnit == CodeUnits.singleQuote { + consecutiveQuotes += 1 + if consecutiveQuotes > 2 { + throw TOMLError( + .syntax( + lineNumber: 0, + message: + "literal multiline strings cannot contain more than 2 consecutive single quotes")) + } + } else { + consecutiveQuotes = 0 + } + + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(codeUnit) + } + return String(decoding: resultCodeUnits, as: UTF8.self) +} + +func basicString( + budget: SemanticBudget, bytes: UnsafeBufferPointer, range: Range, multiline: Bool +) throws -> String { + let startIndex = range.lowerBound + let endIndex = range.upperBound + var resultCodeUnits: [UTF8.CodeUnit] = [] + try budget.allocate(range.count, stage: "decoded string capacity") + resultCodeUnits.reserveCapacity(range.count) + var consecutiveQuotes = 0 + var index = startIndex + while true { + try budget.step() + if index >= endIndex { + break + } + + var ch = bytes[index] + index += 1 + if ch != CodeUnits.backslash { + if ch >= CodeUnits.null && ch <= CodeUnits.backspace + || ch >= CodeUnits.lf && ch <= CodeUnits.unitSeparator || ch == CodeUnits.delete + { + if multiline, ch == CodeUnits.lf { + // Allow LF in multiline basic strings + } else if multiline, ch == CodeUnits.cr { + // Only allow CR if followed by LF (CRLF sequence) + if index < endIndex, bytes[index] == CodeUnits.lf { + // Allow CRLF sequence - will be processed as separate characters + } else { + throw TOMLError(.invalidCharacter(ch)) + } + } else { + throw TOMLError(.invalidCharacter(ch)) + } + } + + if multiline, ch == CodeUnits.doubleQuote { + consecutiveQuotes += 1 + if consecutiveQuotes > 2 { + throw TOMLError( + .syntax( + lineNumber: 0, + message: + "basic multiline strings cannot contain more than 2 consecutive double quotes" + ) + ) + } + } else { + consecutiveQuotes = 0 + } + + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(ch) + continue + } + + if index >= endIndex { + throw TOMLError(.invalidCharacter(CodeUnits.backslash)) + } + + func indexAfterSkippingCharacters(start: Int, endIndex: Int, characters: [UTF8.CodeUnit]) + throws -> Int + { + var index = start + while index < endIndex { + try budget.step() + if characters.contains(bytes[index]) { + index += 1 + } else { + break + } + } + return index + } + + if multiline { + let afterWhitespace = try indexAfterSkippingCharacters( + start: index, endIndex: endIndex, + characters: [CodeUnits.space, CodeUnits.tab, CodeUnits.cr] + ) + if afterWhitespace < endIndex, bytes[afterWhitespace] == CodeUnits.lf { + index = try indexAfterSkippingCharacters( + start: index, endIndex: endIndex, + characters: [CodeUnits.space, CodeUnits.tab, CodeUnits.cr, CodeUnits.lf] + ) + continue + } + } + + ch = bytes[index] + index += 1 + + if ch == CodeUnits.lowerU || ch == CodeUnits.upperU || ch == CodeUnits.lowerX { + let hexCount = + switch ch { + case CodeUnits.lowerU: 4 + case CodeUnits.upperU: 8 + case CodeUnits.lowerX: 2 + default: fatalError("Unsupported CodeUnit: \(ch)") + } + var ucs: UInt32 = 0 + for _ in 0..= endIndex { + throw TOMLError(.expectedHexCharacters(ch, hexCount)) + } + ch = bytes[index] + index += 1 + let v: Int32 = + ch.isDecimalDigit + ? Int32(ch - CodeUnits.number0) + : (ch >= CodeUnits.upperA && ch <= CodeUnits.upperF) + ? Int32(ch - CodeUnits.upperA + 10) + : (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerF) + ? Int32(ch - CodeUnits.lowerA + 10) + : -1 + if v == -1 { + throw TOMLError(.invalidHexCharacters(ch)) + } + ucs = ucs * 16 + UInt32(v) + } + guard let scalar = Unicode.Scalar(ucs) else { + throw TOMLError(.illegalUCSCode(ucs)) + } + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(contentsOf: scalar.utf8) + continue + } else if ch == CodeUnits.lowerB { + ch = CodeUnits.backspace + } else if ch == CodeUnits.lowerT { + ch = CodeUnits.tab + } else if ch == CodeUnits.lowerF { + ch = CodeUnits.formfeed + } else if ch == CodeUnits.lowerR { + ch = CodeUnits.cr + } else if ch == CodeUnits.lowerN { + ch = CodeUnits.lf + } else if ch == CodeUnits.lowerE { + ch = CodeUnits.escape + } else if ch != CodeUnits.doubleQuote, ch != CodeUnits.backslash { + throw TOMLError(.illegalEscapeCharacter(ch)) + } + + consecutiveQuotes = 0 // Reset count after escape sequence + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(ch) + } + return String(decoding: resultCodeUnits, as: UTF8.self) +} + +func scanDate(bytes: UnsafeBufferPointer, range: Range) -> (Int, Int, Int, Int)? { + guard let year = scanDigits(bytes: bytes, range: range, n: 4) else { + return nil + } + + var index = range.lowerBound + index += 4 + + guard index < range.upperBound, bytes[index] == CodeUnits.minus else { + return nil + } + + index += 1 + guard let month = scanDigits(bytes: bytes, range: index.., range: Range, n: Int) -> Int? { + var result = 0 + var n = n + var index = range.lowerBound + while n > 0, index < range.upperBound, bytes[index].isDecimalDigit { + result = 10 * result + Int(bytes[index]) - Int(CodeUnits.number0) + index += 1 + n -= 1 + } + return n != 0 ? nil : result +} + +func scanTime(bytes: UnsafeBufferPointer, range: Range) -> (Int, Int, Int, Int)? { + guard let hour = scanDigits(bytes: bytes, range: range, n: 2) else { + return nil + } + + var index = range.lowerBound + + index += 2 + guard index < range.upperBound, bytes[index] == CodeUnits.colon else { + return nil + } + + index += 1 + guard let minute = scanDigits(bytes: bytes, range: index.., range: Range, + updatedIndex: inout Int +) throws -> UInt32 { + var unit: Double = 100_000_000 + var result: Double = 0 + var index = range.lowerBound + while index < range.upperBound, bytes[index].isDecimalDigit { + try budget.step() + result += Double(bytes[index] - CodeUnits.number0) * unit + index += 1 + unit /= 10 + } + updatedIndex = index + return UInt32(result) +} + +func scanTimezoneOffset(bytes: UnsafeBufferPointer, range: Range) -> Int? { + var index = range.lowerBound + guard index < range.upperBound, bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus + else { + return nil + } + + index += 1 + guard scanDigits(bytes: bytes, range: index.. Bool { + let ones: UInt64 = 0x0101_0101_0101_0101 + let highBits: UInt64 = 0x8080_8080_8080_8080 + + @inline(__always) + func hasByte(_ bytePattern: UInt64) -> Bool { + let xor = chunk ^ bytePattern + return ((xor &- ones) & ~xor & highBits) != 0 + } + + return hasByte(0x2222_2222_2222_2222) + || hasByte(0x5C5C_5C5C_5C5C_5C5C) + || hasByte(0x0A0A_0A0A_0A0A_0A0A) +} + +func normalizeKeyAndHash(bytes: UnsafeBufferPointer, token: Token) throws -> ( + key: String, keyHash: Int +) { + let budget = token.budget! + try budget.allocate(token.text.count, stage: "decoded key") + var start = token.text.lowerBound + var end = token.text.upperBound + if token.kind == .bareKey { + let str = try makeString(budget: budget, bytes: bytes, range: start..= CodeUnits.number0 && byte <= CodeUnits.number9 // 0-9 + || byte >= CodeUnits.upperA && byte <= CodeUnits.upperZ // A-Z + || byte >= CodeUnits.lowerA && byte <= CodeUnits.lowerZ // a-z + || byte == CodeUnits.underscore // _ + || byte == CodeUnits.minus // - + { + continue + } + throw TOMLError(.badKey(lineNumber: token.lineNumber)) + } + + let key = try makeString(budget: budget, bytes: bytes, range: start.., range: Range) -> Int { + let count = range.upperBound - range.lowerBound + if count == 0 { + return 0 + } + let start = bytes.baseAddress!.advanced(by: range.lowerBound) + if count <= 8 { + return Int(truncatingIfNeeded: packedKeyHash(UnsafeBufferPointer(start: start, count: count))) + } + return Int(truncatingIfNeeded: sampledKeyHash(start: start, count: count)) +} + +@inline(__always) +func fastKeyHash(_ key: String) -> Int { + if let hash = key.utf8.withContiguousStorageIfAvailable({ buffer -> UInt64 in + if buffer.count <= 8 { + return packedKeyHash(buffer) + } + if let start = buffer.baseAddress { + return sampledKeyHash(start: start, count: buffer.count) + } + return 0 + }) { + return Int(truncatingIfNeeded: hash) + } + + let offsetBasis: UInt64 = 14_695_981_039_346_656_037 + let prime: UInt64 = 1_099_511_628_211 + var hash = offsetBasis + var packed: UInt64 = 0 + var count = 0 + for byte in key.utf8 { + if count < 8 { + packed |= UInt64(byte) << (UInt64(count) * 8) + } + hash ^= UInt64(byte) + hash &*= prime + count += 1 + } + return Int(truncatingIfNeeded: count <= 8 ? packed : hash) +} + +@inline(__always) +private func sampledKeyHash(start: UnsafePointer, count: Int) -> UInt64 { + let prefix = packedKeyHash(UnsafeBufferPointer(start: start, count: 8)) + let suffix = packedKeyHash(UnsafeBufferPointer(start: start.advanced(by: count - 8), count: 8)) + let rotatedSuffix = (suffix << 1) | (suffix >> 63) + return prefix ^ rotatedSuffix ^ (UInt64(truncatingIfNeeded: count) &* 0x9E37_79B1_85EB_CA87) +} + +@inline(__always) +private func packedKeyHash(_ buffer: UnsafeBufferPointer) -> UInt64 { + var packed: UInt64 = 0 + switch buffer.count { + case 8: + packed |= UInt64(buffer[7]) << 56 + fallthrough + case 7: + packed |= UInt64(buffer[6]) << 48 + fallthrough + case 6: + packed |= UInt64(buffer[5]) << 40 + fallthrough + case 5: + packed |= UInt64(buffer[4]) << 32 + fallthrough + case 4: + packed |= UInt64(buffer[3]) << 24 + fallthrough + case 3: + packed |= UInt64(buffer[2]) << 16 + fallthrough + case 2: + packed |= UInt64(buffer[1]) << 8 + fallthrough + case 1: + packed |= UInt64(buffer[0]) + default: + break + } + return packed +} + +@inline(__always) +private func makeString( + budget: SemanticBudget, bytes: UnsafeBufferPointer, range: Range +) throws -> String { + try budget.allocate(range.count, stage: "decoded key copy") + try budget.step(range.count) + let count = range.upperBound - range.lowerBound + if count == 0 { + return "" + } + let start = bytes.baseAddress!.advanced(by: range.lowerBound) + return String(decoding: UnsafeBufferPointer(start: start, count: count), as: UTF8.self) +} + +extension Parser { + @inline(__always) + func matchKeyValue(in indices: borrowing [Int], key: borrowing String, keyHash: Int) throws + -> Int? + { + if indices.isEmpty { + return nil + } + return try keyValues.withUnsafeBufferPointer { keyValueBuffer -> Int? in + guard let keyValueBase = keyValueBuffer.baseAddress else { + return nil + } + let indexCount = indices.count + var i = 0 + while i < indexCount { + try budget.step() + let keyValueIndex = indices[i] + let keyValuePair = keyValueBase.advanced(by: keyValueIndex).pointee + if keyValuePair.keyHash == keyHash, try budget.equal(keyValuePair.key, key) { + return keyValueIndex + } + i += 1 + } + return nil + } + } + + @inline(__always) + func matchKeyArray(in indices: borrowing [Int], key: borrowing String, keyHash: Int) throws + -> Int? + { + if indices.isEmpty { + return nil + } + return try keyArrays.withUnsafeBufferPointer { keyArrayBuffer -> Int? in + guard let keyArrayBase = keyArrayBuffer.baseAddress else { + return nil + } + let indexCount = indices.count + var i = 0 + while i < indexCount { + try budget.step() + let keyArrayIndex = indices[i] + let keyArrayPair = keyArrayBase.advanced(by: keyArrayIndex).pointee + if keyArrayPair.keyHash == keyHash, try budget.equal(keyArrayPair.key, key) { + return keyArrayIndex + } + i += 1 + } + return nil + } + } + + @inline(__always) + func keyMatchesToken(bytes: UnsafeBufferPointer, token: Token, key: borrowing String) + throws -> Bool + { + let range = token.text + let count = range.upperBound - range.lowerBound + + if let matches = try key.utf8.withContiguousStorageIfAvailable({ keyBuffer -> Bool in + if keyBuffer.count != count { + return false + } + + var keyIndex = 0 + var byteIndex = range.lowerBound + while keyIndex < count { + try budget.step() + if keyBuffer[keyIndex] != bytes[byteIndex] { + return false + } + keyIndex += 1 + byteIndex += 1 + } + return true + }) { + return matches + } + + var index = range.lowerBound + for byte in key.utf8 { + try budget.step() + if index >= range.upperBound || bytes[index] != byte { + return false + } + index += 1 + } + return index == range.upperBound + } + + @inline(__always) + func matchKeyArray( + in indices: borrowing [Int], + bytes: UnsafeBufferPointer, + token: Token, + keyHash: Int + ) throws -> Int? { + if indices.isEmpty { + return nil + } + return try keyArrays.withUnsafeBufferPointer { keyArrayBuffer -> Int? in + guard let keyArrayBase = keyArrayBuffer.baseAddress else { + return nil + } + let indexCount = indices.count + var i = 0 + while i < indexCount { + try budget.step() + let keyArrayIndex = indices[i] + let keyArrayPair = keyArrayBase.advanced(by: keyArrayIndex).pointee + if keyArrayPair.keyHash == keyHash, + try keyMatchesToken(bytes: bytes, token: token, key: keyArrayPair.key) + { + return keyArrayIndex + } + i += 1 + } + return nil + } + } + + @inline(__always) + func matchKeyTable(in indices: borrowing [Int], key: borrowing String, keyHash: Int) throws + -> Int? + { + if indices.isEmpty { + return nil + } + return try keyTables.withUnsafeBufferPointer { keyTableBuffer -> Int? in + guard let keyTableBase = keyTableBuffer.baseAddress else { + return nil + } + let indexCount = indices.count + var i = 0 + while i < indexCount { + try budget.step() + let keyTableIndex = indices[i] + let keyTablePair = keyTableBase.advanced(by: keyTableIndex).pointee + if keyTablePair.keyHash == keyHash, try budget.equal(keyTablePair.key, key) { + return keyTableIndex + } + i += 1 + } + return nil + } + } + + @inline(__always) + func tableValue( + tableIndex: Int, + keyed: Bool, + key: borrowing String, + keyHash: Int + ) throws -> InternalTOMLTable.Value? { + if keyed { + if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { + return nil + } + } else if !tables[tableIndex].mightContainKeyHash(keyHash) { + return nil + } + + if keyed { + if let keyValueIndex = try matchKeyValue( + in: keyTables[tableIndex].table.keyValues, key: key, keyHash: keyHash) + { + return .keyValue(keyValueIndex) + } + + if let keyArrayIndex = try matchKeyArray( + in: keyTables[tableIndex].table.arrays, key: key, keyHash: keyHash) + { + return .array(keyArrayIndex) + } + + if let keyTableIndex = try matchKeyTable( + in: keyTables[tableIndex].table.tables, key: key, keyHash: keyHash) + { + return .table(keyTableIndex) + } + return nil + } + + if let keyValueIndex = try matchKeyValue( + in: tables[tableIndex].keyValues, key: key, keyHash: keyHash) + { + return .keyValue(keyValueIndex) + } + + if let keyArrayIndex = try matchKeyArray( + in: tables[tableIndex].arrays, key: key, keyHash: keyHash) + { + return .array(keyArrayIndex) + } + + if let keyTableIndex = try matchKeyTable( + in: tables[tableIndex].tables, key: key, keyHash: keyHash) + { + return .table(keyTableIndex) + } + + return nil + } + + @inline(__always) + func lookupTable(in tableIndex: Int, keyed: Bool, key: borrowing String, keyHash: Int) throws + -> Int? + { + if keyed { + if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { + return nil + } + return try matchKeyTable(in: keyTables[tableIndex].table.tables, key: key, keyHash: keyHash) + } + if !tables[tableIndex].mightContainKeyHash(keyHash) { + return nil + } + return try matchKeyTable(in: tables[tableIndex].tables, key: key, keyHash: keyHash) + } + + @inline(__always) + func lookupArray(in tableIndex: Int, keyed: Bool, key: borrowing String, keyHash: Int) throws + -> Int? + { + if keyed { + if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { + return nil + } + return try matchKeyArray(in: keyTables[tableIndex].table.arrays, key: key, keyHash: keyHash) + } + if !tables[tableIndex].mightContainKeyHash(keyHash) { + return nil + } + return try matchKeyArray(in: tables[tableIndex].arrays, key: key, keyHash: keyHash) + } + + @inline(__always) + func lookupArray( + in tableIndex: Int, + keyed: Bool, + bytes: UnsafeBufferPointer, + token: Token, + keyHash: Int + ) throws -> Int? { + if keyed { + if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { + return nil + } + return try matchKeyArray( + in: keyTables[tableIndex].table.arrays, + bytes: bytes, + token: token, + keyHash: keyHash + ) + } + if !tables[tableIndex].mightContainKeyHash(keyHash) { + return nil + } + return try matchKeyArray( + in: tables[tableIndex].arrays, + bytes: bytes, + token: token, + keyHash: keyHash + ) + } + + mutating func advanceTablePathSegment( + tableIndex: inout Int, + isKeyed: inout Bool, + key: String, + keyHash: Int + ) throws { + switch try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) { + case .table(let index): + tableIndex = index + isKeyed = true + case .array(let arrayIndex): + let array = keyArrays[arrayIndex].array + guard case .table = array.kind else { + throw TOMLError( + .syntax(lineNumber: token.lineNumber, message: "array element is not a table")) + } + + if array.elements.isEmpty { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "empty array")) + } + + guard case .table(_, let index) = array.elements.last else { + throw TOMLError( + .syntax(lineNumber: token.lineNumber, message: "array element is not a table")) + } + + tableIndex = index + isKeyed = false + case .keyValue: + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "key-value already exists")) + default: + let newTableAddress = keyTables.count + var newTable = InternalTOMLTable() + newTable.implicit = true + newTable.definedByDottedKey = false + try budget.node(depth: depth) + keyTables.append( + KeyTablePair( + key: key, keyHash: keyHash, sourcePosition: token.text.lowerBound, table: newTable)) + + if isKeyed { + if keyTables[tableIndex].table.tables.isEmpty { + try budget.allocate(8, stage: "semantic storage") + keyTables[tableIndex].table.tables.reserveCapacity(8) + } + try budget.node(depth: depth) + keyTables[tableIndex].table.tables.append(newTableAddress) + keyTables[tableIndex].table.recordKeyHash(keyHash) + } else { + if tables[tableIndex].tables.isEmpty { + try budget.allocate(8, stage: "semantic storage") + tables[tableIndex].tables.reserveCapacity(8) + } + try budget.node(depth: depth) + tables[tableIndex].tables.append(newTableAddress) + tables[tableIndex].recordKeyHash(keyHash) + } + tableIndex = newTableAddress + isKeyed = true + } + } + + mutating func walkTablePath(startTable: Int = 0, startKeyed: Bool = false) throws { + var tableIndex = startTable + var isKeyed = startKeyed + for (key, keyHash) in tablePath { + try budget.step() + try advanceTablePathSegment( + tableIndex: &tableIndex, + isKeyed: &isKeyed, + key: key, + keyHash: keyHash + ) + } + currentTable = tableIndex + currentTableIsKeyed = isKeyed + } +} diff --git a/Sources/TOMLSemantics/Parsing/TOMLDocument.swift b/Sources/TOMLSemantics/Parsing/TOMLDocument.swift new file mode 100644 index 0000000..54c07f7 --- /dev/null +++ b/Sources/TOMLSemantics/Parsing/TOMLDocument.swift @@ -0,0 +1,186 @@ +import Foundation + +struct TOMLDocument { + let tables: [InternalTOMLTable] + let arrays: [InternalTOMLArray] + let keyTables: [KeyTablePair] + let keyArrays: [KeyArrayPair] + let keyValues: [KeyValuePair] + + let source: String + + init( + source: String, + tables: [InternalTOMLTable], + arrays: [InternalTOMLArray], + keyTables: [KeyTablePair], + keyArrays: [KeyArrayPair], + keyValues: [KeyValuePair] + ) { + self.source = source + self.tables = tables + self.arrays = arrays + self.keyTables = keyTables + self.keyArrays = keyArrays + self.keyValues = keyValues + } + +} + +struct InternalTOMLArray: Equatable { + var kind: Kind? + var elements: [Element] + + init(kind: Kind? = nil, elements: [Element] = []) { + self.kind = kind + self.elements = elements + } + + enum Element: Equatable { + case leaf(Token) + case array(lineNumber: Int, Int) + case table(lineNumber: Int, Int) + + var lineNumber: Int { + switch self { + case .leaf(let token): + token.lineNumber + case .array(let lineNumber, _): + lineNumber + case .table(let lineNumber, _): + lineNumber + } + } + + static func == (lhs: Element, rhs: Element) -> Bool { + switch (lhs, rhs) { + case (.leaf(let lhsToken), .leaf(let rhsToken)): + lhsToken == rhsToken + case (.array(let lhsLineNumber, let lhsIndex), .array(let rhsLineNumber, let rhsIndex)): + lhsLineNumber == rhsLineNumber && lhsIndex == rhsIndex + case (.table(let lhsLineNumber, let lhsIndex), .table(let rhsLineNumber, let rhsIndex)): + lhsLineNumber == rhsLineNumber && lhsIndex == rhsIndex + default: + false + } + } + } + + enum Kind: UInt8 { + case value + case array + case table + case mixed + } +} + +struct KeyTablePair { + let key: String + let keyHash: Int + let sourcePosition: Int + var table: InternalTOMLTable +} + +struct KeyArrayPair { + let key: String + let keyHash: Int + let sourcePosition: Int + var array: InternalTOMLArray +} + +struct KeyValuePair { + let key: String + let keyHash: Int + let sourcePosition: Int + var value: Token +} + +struct InternalTOMLTable: Equatable { + var implicit: Bool = false + var readOnly: Bool = false + var definedByDottedKey: Bool = false + var keyHashBloom: UInt64 = 0 + var keyValues: [Int] = [] + var arrays: [Int] = [] + var tables: [Int] = [] + + @inline(__always) + mutating func recordKeyHash(_ keyHash: Int) { + keyHashBloom |= keyHashBloomMask(keyHash) + } + + @inline(__always) + func mightContainKeyHash(_ keyHash: Int) -> Bool { + let mask = keyHashBloomMask(keyHash) + return (keyHashBloom & mask) == mask + } + + enum Value { + case keyValue(Int) + case array(Int) + case table(Int) + } +} + +@inline(__always) +private func keyHashBloomMask(_ keyHash: Int) -> UInt64 { + let raw = UInt(bitPattern: keyHash) + let bit0 = UInt64(1) << UInt64(raw & 63) + let bit1 = UInt64(1) << UInt64((raw >> 6) & 63) + return bit0 | bit1 +} + +struct DateTimeComponents: Equatable { + let date: LocalDate? + let time: LocalTime? + let offset: Int16? + let features: OffsetDateTime.Features + + @inline(__always) + func localDate(exactMatch: Bool = true) -> LocalDate? { + switch (date, time, offset) { + case (.some(let date), .none, .none): + date + case (.some(let date), _, _) where !exactMatch: + date + default: + nil + } + } + + @inline(__always) + func localTime(exactMatch: Bool = true) -> LocalTime? { + switch (date, time, offset) { + case (.none, .some(let time), .none): + time + case (_, .some(let time), _) where !exactMatch: + time + default: + nil + } + } + + @inline(__always) + func localDateTime(exactMatch: Bool = true) -> LocalDateTime? { + switch (date, time, offset) { + case (.some(let date), .some(let time), .none): + LocalDateTime(date: date, time: time) + case (.some(let date), .some(let time), .some) where !exactMatch: + LocalDateTime(date: date, time: time) + default: + nil + } + } +} + +extension TOMLDocument { + @inline(__always) + func table(at index: Int, keyed: Bool) -> InternalTOMLTable { + keyed ? keyTables[index].table : tables[index] + } + + @inline(__always) + func array(at index: Int, keyed: Bool) -> InternalTOMLArray { + keyed ? keyArrays[index].array : arrays[index] + } +} diff --git a/Sources/TOMLSemantics/Parsing/Token.swift b/Sources/TOMLSemantics/Parsing/Token.swift new file mode 100644 index 0000000..a73f890 --- /dev/null +++ b/Sources/TOMLSemantics/Parsing/Token.swift @@ -0,0 +1,27 @@ +struct Token: Equatable { + enum Kind: UInt8 { + case dot + case comma + case equal + case lbrace + case rbrace + case newline + case lbracket + case rbracket + case string + case bareKey + case eof + } + + var budget: SemanticBudget! = nil + + let kind: Kind + let lineNumber: Int + let text: Range + + static func == (lhs: Token, rhs: Token) -> Bool { + lhs.kind == rhs.kind && lhs.lineNumber == rhs.lineNumber && lhs.text == rhs.text + } + + static var empty: Token { Token(kind: .newline, lineNumber: 1, text: 0..<0) } +} diff --git a/Sources/TOMLSemantics/SemanticBudget.swift b/Sources/TOMLSemantics/SemanticBudget.swift new file mode 100644 index 0000000..b48e8b3 --- /dev/null +++ b/Sources/TOMLSemantics/SemanticBudget.swift @@ -0,0 +1,93 @@ +import Foundation + +/// One serial operation's cumulative admission. Units bound logical storage/work, not RSS. +package final class SemanticBudget { + package struct Limits { + package var storage: Int + package var work: Int + package var nodes: Int + package var depth: Int + package var uninterruptedBytes: Int + + package init(storage: Int, work: Int, nodes: Int, depth: Int, uninterruptedBytes: Int) { + self.storage = storage + self.work = work + self.nodes = nodes + self.depth = depth + self.uninterruptedBytes = uninterruptedBytes + } + } + + package enum Failure: Error { + case exceeded(String) + case cancelled + } + private var storage: Int + private var work: Int + private var nodes: Int + package let limits: Limits + private let cancellation: () -> Bool + + package init(limits: Limits, cancellation: @escaping () -> Bool = { false }) { + self.limits = limits + self.storage = limits.storage + self.work = limits.work + self.nodes = limits.nodes + self.cancellation = cancellation + } + + package func check() throws { + if cancellation() || Task.isCancelled { throw Failure.cancelled } + } + + package func step(_ amount: Int = 1) throws { + try check() + guard amount >= 0, amount <= work else { throw Failure.exceeded("work") } + work -= amount + } + + package func allocate(_ amount: Int, stage: String) throws { + try check() + guard amount >= 0, amount <= storage else { throw Failure.exceeded(stage) } + storage -= amount + } + + package func enter(_ depth: Int) throws { + try check() + guard depth <= limits.depth else { throw Failure.exceeded("depth") } + } + + package func node(depth: Int) throws { + try enter(depth) + guard nodes > 0 else { throw Failure.exceeded("nodes") } + nodes -= 1 + try allocate(1, stage: "node") + } + + package func equal(_ a: String, _ b: String) throws -> Bool { + guard a.utf8.count == b.utf8.count else { + try step() + return false + } + for (x, y) in zip(a.utf8, b.utf8) { + try step() + if x != y { return false } + } + return true + } + + /// The whole admitted envelope bounds every CST lexical run, including skipped trivia. + package func admitCST(bytes: Int) throws { + try check() + guard bytes <= limits.uninterruptedBytes else { + throw Failure.exceeded("CST uninterrupted input") + } + try step(bytes) + guard bytes <= (Int.max - 1) / 4 else { throw Failure.exceeded("CST nodes") } + let admittedNodes = bytes * 4 + 1 + guard admittedNodes <= nodes else { throw Failure.exceeded("CST nodes") } + nodes -= admittedNodes + try allocate(admittedNodes, stage: "CST nodes") + try allocate(bytes, stage: "CST input") + } +} diff --git a/Sources/TOMLSemantics/SemanticDocument.swift b/Sources/TOMLSemantics/SemanticDocument.swift new file mode 100644 index 0000000..eb46946 --- /dev/null +++ b/Sources/TOMLSemantics/SemanticDocument.swift @@ -0,0 +1,174 @@ +import Foundation + +package enum SemanticScalarKind: String { case string, boolean, integer, float, dateTime } + +package struct SemanticEntry { + package let key: String + package let value: SemanticValue + package init(key: String, value: SemanticValue) { + self.key = key + self.value = value + } +} + +package indirect enum SemanticValue { + case object([SemanticEntry]) + case array([SemanticValue]) + case scalar(kind: SemanticScalarKind, decoded: String, raw: String, range: Range) +} + +package struct SemanticDocument { + package let root: SemanticValue + + package init(source: String, budget: SemanticBudget) throws { + try budget.allocate(source.utf8.count, stage: "semantic input") + var parser = Parser(budget: budget) + try source.utf8.withContiguousStorageIfAvailable { try parser.parse(bytes: $0) } + .unwrapStorage() + let document = parser.finish(source: source) + root = try Self.table(document.tables[0], document: document, budget: budget, depth: 0) + } + + private static func table( + _ table: InternalTOMLTable, document: TOMLDocument, budget: SemanticBudget, depth: Int + ) throws -> SemanticValue { + try budget.node(depth: depth) + var entries: [(Int, SemanticEntry)] = [] + for i in table.keyValues { + try budget.step() + let pair = document.keyValues[i] + try budget.allocate(1, stage: "ordered entry") + entries.append( + ( + pair.sourcePosition, + SemanticEntry( + key: pair.key, value: try scalar(pair.value, source: document.source, budget: budget)) + )) + } + for i in table.arrays { + try budget.step() + let pair = document.keyArrays[i] + try budget.allocate(1, stage: "ordered entry") + entries.append( + ( + pair.sourcePosition, + SemanticEntry( + key: pair.key, + value: try array(pair.array, document: document, budget: budget, depth: depth + 1)) + )) + } + for i in table.tables { + try budget.step() + let pair = document.keyTables[i] + try budget.allocate(1, stage: "ordered entry") + entries.append( + ( + pair.sourcePosition, + SemanticEntry( + key: pair.key, + value: try Self.table(pair.table, document: document, budget: budget, depth: depth + 1)) + )) + } + try budget.allocate(entries.count, stage: "ordered entries") + let ordered = try entries.sorted { + try budget.step() + return $0.0 < $1.0 + } + return .object(ordered.map(\.1)) + } + + private static func array( + _ array: InternalTOMLArray, document: TOMLDocument, budget: SemanticBudget, depth: Int + ) throws -> SemanticValue { + try budget.node(depth: depth) + var values: [SemanticValue] = [] + for element in array.elements { + try budget.step() + try budget.allocate(1, stage: "ordered element") + switch element { + case .leaf(let token): + values.append(try scalar(token, source: document.source, budget: budget)) + case .array(_, let i): + values.append( + try Self.array(document.arrays[i], document: document, budget: budget, depth: depth + 1)) + case .table(_, let i): + values.append( + try table(document.tables[i], document: document, budget: budget, depth: depth + 1)) + } + } + return .array(values) + } + + private static func scalar(_ token: Token, source: String, budget: SemanticBudget) throws + -> SemanticValue + { + try budget.node(depth: 0) + try budget.allocate(token.text.count, stage: "scalar lexeme") + return try source.utf8.withContiguousStorageIfAvailable { bytes in + try budget.step(token.text.count) + let raw = String(decoding: bytes[token.text], as: UTF8.self) + let kind: SemanticScalarKind + let decoded: String + let first = bytes[token.text.lowerBound] + var dot = false + var exponent = false + var colon = false + for byte in bytes[token.text] { + try budget.step() + dot = dot || byte == 46 + exponent = exponent || byte == 101 || byte == 69 + colon = colon || byte == 58 + } + if first == 34 || first == 39 { + kind = .string + decoded = try token.unpackString(bytes: bytes, context: .super) + } else if first == 116 || first == 102 { + kind = .boolean + decoded = try token.unpackBool(bytes: bytes, context: .super) ? "true" : "false" + } else if colon || (token.text.count > 4 && bytes[token.text.lowerBound + 4] == 45) { + kind = .dateTime + _ = try token.unpackDateTime(bytes: bytes, context: .super) + decoded = raw + } else { + // Base-prefixed integers can contain e/E hex digits. Classification precedes validation. + let numeric = (first == 43 || first == 45) ? String(raw.dropFirst()) : raw + if !numeric.hasPrefix("0x") && !numeric.hasPrefix("0o") && !numeric.hasPrefix("0b") + && (dot || exponent || numeric == "inf" || numeric == "nan") + { + kind = .float + _ = try token.unpackFloat(bytes: bytes, context: .super) + try budget.allocate(token.text.count, stage: "decimal projection") + var projection: [UInt8] = [] + for (i, byte) in bytes[token.text].enumerated() { + try budget.step() + if byte != 95 && !(i == 0 && byte == 43) { projection.append(byte) } + } + decoded = String(decoding: projection, as: UTF8.self) + } else { + kind = .integer + decoded = String(try token.unpackInteger(bytes: bytes, context: .super)) + } + } + return .scalar(kind: kind, decoded: decoded, raw: raw, range: token.text) + }.unwrapStorage() + } + + package static func decodeKey(_ bytes: [UInt8], budget: SemanticBudget) throws -> String { + try budget.allocate(bytes.count, stage: "key input") + if bytes.first == 34 || bytes.first == 39 { + return try bytes.withUnsafeBufferPointer { + let token = Token(budget: budget, kind: .string, lineNumber: 1, text: 0.. Wrapped { + guard let self else { throw TOMLError(.invalidUTF8) } + return self + } +} diff --git a/Sources/TOMLSemantics/TOMLError.swift b/Sources/TOMLSemantics/TOMLError.swift new file mode 100644 index 0000000..c54c7f3 --- /dev/null +++ b/Sources/TOMLSemantics/TOMLError.swift @@ -0,0 +1,147 @@ +/// An error originated from parsing the TOML document. +/// +/// This error provides details for invalid values, +/// or formatting issues in the TOML document. +/// It comes from the parsing phase. +/// Read to learn more. +public struct TOMLError: Error { + let reason: Reason + + init(_ reason: Reason) { + self.reason = reason + } + + enum Reason { + case arrayOutOfBound(index: Int, bound: Int) + case badKey(lineNumber: Int) + case expectedHexCharacters(UTF8.CodeUnit, Int) + case illegalEscapeCharacter(UTF8.CodeUnit) + case illegalUCSCode(UInt32) + case internalError(lineNumber: Int) + case invalidBool(context: TOMLKey, lineNumber: Int) + case invalidCharacter(UTF8.CodeUnit) + case invalidDateTime(lineNumber: Int?, reason: String) + case invalidDateTime3(context: TOMLKey, lineNumber: Int, reason: String) + case invalidDateTimeComponents(String) + case invalidFloat(context: TOMLKey, lineNumber: Int, reason: String) + case invalidHexCharacters(UTF8.CodeUnit) + case invalidInteger(context: TOMLKey, lineNumber: Int, reason: String) + case invalidNumber(reason: String) + case invalidString(context: TOMLKey, lineNumber: Int, reason: String) + case invalidUTF8 + case invalidValueInTable(context: TOMLKey, lineNumber: Int) + case keyExists(lineNumber: Int) + case keyNotFoundInTable(key: String, expected: String) + case notReallyCodable + case syntax(lineNumber: Int, message: String) + case typeMismatch(context: TOMLKey, lineNumber: Int, expected: String) + case typeMismatchInArray(lineNumber: Int, index: Int, expected: String) + case typeMismatchInTable(key: String, expected: String) + } +} + +extension TOMLError: CustomStringConvertible { + public var description: String { + switch reason { + case .arrayOutOfBound(let index, let bound): + "Array index \(index) is out of bounds (0..<\(bound))." + case .badKey(let lineNumber): + "(Line \(lineNumber)) Ill-formed key." + case .expectedHexCharacters(let codeUnit, let hexCount): + "Expected \(hexCount) hexadecimal characters after '\(String(UnicodeScalar(codeUnit))).'." + case .illegalEscapeCharacter(let codeUnit): + "Illegal escape character '\(String(UnicodeScalar(codeUnit)))'." + case .illegalUCSCode(let ucs): + "Illegal UCS code '\(ucs)'." + case .internalError(let lineNumber): + "(Line \(lineNumber)) Internal error." + case .invalidBool(let context, let lineNumber): + switch context { + case .string(let key): + "(Line \(lineNumber)) Invalid boolean value for key '\(key)'." + case .int(let index): + "(Line \(lineNumber)) Invalid boolean value for index \(index)." + case .super: + "(Line \(lineNumber)) Invalid boolean value for 'super'." + } + case .invalidCharacter(let codeUnit): + "Invalid character '\(String(UnicodeScalar(codeUnit)))'." + case .invalidDateTime(let lineNumber, let reason): + "\(lineNumber.map { "(Line \($0)) " } ?? "")Invalid date-time: \(reason)." + case .invalidDateTime3(let context, let lineNumber, let reason): + switch context { + case .string(let key): + "(Line \(lineNumber)) Invalid date-time value for key '\(key)': \(reason)." + case .int(let index): + "(Line \(lineNumber)) Invalid date-time value for index \(index)': \(reason)." + case .super: + "(Line \(lineNumber)) Invalid date-time value for 'super': \(reason)." + } + case .invalidDateTimeComponents(let components): + "Invalid date-time components: \(components)." + case .invalidFloat(let context, let lineNumber, let reason): + switch context { + case .string(let key): + "(Line \(lineNumber)) Invalid float value for key '\(key)': \(reason)." + case .int(let index): + "(Line \(lineNumber)) Invalid float value for index \(index)': \(reason)." + case .super: + "(Line \(lineNumber)) Invalid float value for 'super': \(reason)." + } + case .invalidHexCharacters(let codeUnit): + "Invalid hexadecimal characters '\(String(UnicodeScalar(codeUnit)))'." + case .invalidInteger(let context, let lineNumber, let reason): + switch context { + case .string(let key): + "(Line \(lineNumber)) Invalid integer value for key '\(key)': \(reason)." + case .int(let index): + "(Line \(lineNumber)) Invalid integer value for index \(index)': \(reason)." + case .super: + "(Line \(lineNumber)) Invalid integer value for 'super': \(reason)." + } + case .invalidNumber(let reason): + "Invalid number: \(reason)." + case .invalidString(let context, let lineNumber, let reason): + switch context { + case .string(let key): + "(Line \(lineNumber)) Invalid string value for key '\(key)': \(reason)." + case .int(let index): + "(Line \(lineNumber)) Invalid string value for index \(index)': \(reason)." + case .super: + "(Line \(lineNumber)) Invalid string value for 'super': \(reason)." + } + case .invalidUTF8: + "The given data was not valid UTF8." + case .invalidValueInTable(let context, let lineNumber): + switch context { + case .string(let key): + "(Line \(lineNumber)) Invalid value in table for key '\(key)'." + case .int(let index): + "(Line \(lineNumber)) Invalid value in table for index \(index)." + case .super: + "(Line \(lineNumber)) Invalid value in table for 'super'." + } + case .keyExists(let lineNumber): + "(Line \(lineNumber)) Key already exists." + case .keyNotFoundInTable(let key, let expected): + "Key '\(key)' not found in table while looking for \(expected)." + case .notReallyCodable: + "This type is not generally codable. Use TOMLDecoder to decode it as part of a larger Codable." + case .syntax(let lineNumber, let message): + "(Line \(lineNumber)) Syntax error: \(message)." + case .typeMismatch(let context, let lineNumber, let expected): + switch context { + case .string(let key): + "(Line \(lineNumber)) Type mismatch at table key '\(key)': expected \(expected)." + case .int(let index): + "(Line \(lineNumber)) Type mismatch at array index \(index): expected \(expected)." + case .super: + "(Line \(lineNumber)) Type mismatch at 'super': expected \(expected)." + } + case .typeMismatchInArray(let lineNumber, let index, let expected): + "(Line \(lineNumber)) Type mismatch at array index \(index): expected \(expected)." + case .typeMismatchInTable(let key, let expected): + "Type mismatch at table key '\(key)': expected \(expected)." + } + } +} diff --git a/Sources/TOMLSemantics/TOMLKey.swift b/Sources/TOMLSemantics/TOMLKey.swift new file mode 100644 index 0000000..d358984 --- /dev/null +++ b/Sources/TOMLSemantics/TOMLKey.swift @@ -0,0 +1,33 @@ +enum TOMLKey: CodingKey { + case string(String) + case int(Int) + case `super` + + init(stringValue: String) { + self = .string(stringValue) + } + + init(intValue: Int) { + self = .int(intValue) + } + + var stringValue: String { + switch self { + case .string(let string): + string + case .int(let int): + "Index \(int)" + case .super: + "super" + } + } + + var intValue: Int? { + switch self { + case .int(let int): + int + default: + nil + } + } +} diff --git a/Sources/TOMLSemantics/provenance.json b/Sources/TOMLSemantics/provenance.json new file mode 100644 index 0000000..8611de3 --- /dev/null +++ b/Sources/TOMLSemantics/provenance.json @@ -0,0 +1,48 @@ +{ + "upstream": "https://github.com/dduan/TOMLDecoder.git", + "revision": "a2bbd2796fe3064e107de18cb56031052c4fa899", + "files": { + "Parsing/Parser.swift": { + "source": "Sources/TOMLDecoder/Parsing/Parser.swift", + "sha256": "262c1a417325008fc2cefb0ce449bb6bb5189310ff154322bf1ff3a5cf837da5" + }, + "Parsing/Parser+Finish.swift": { + "source": "Sources/TOMLDecoder/Parsing/Parser+Finish.swift", + "sha256": "8e1ce8317624b9f2b9544399e09dfd4df944400bfe0c8a24e6577d4241f04f36" + }, + "Parsing/Token.swift": { + "source": "Sources/TOMLDecoder/Parsing/Token.swift", + "sha256": "f78a3e37ab5991195f3b82e092aae2d12f69c137f88447ce15ee49b8da7b0385" + }, + "Parsing/TOMLDocument.swift": { + "source": "Sources/TOMLDecoder/Parsing/TOMLDocument.swift", + "sha256": "9b92cc3127bcdba696fa51e3983da8d9fd25c16b9ae5aea0cd87569a058bf57d" + }, + "Parsing/Constants.swift": { + "source": "Sources/TOMLDecoder/Parsing/Constants.swift", + "sha256": "47adaa2e74ae68094fbd3d0da44fd0db28846b60a587e98cb95ce3f112485612" + }, + "DateTime.swift": { + "source": "Sources/TOMLDecoder/DateTime.swift", + "sha256": "c22cc93a4ea0ce8b7dac5c00c916ab24974b5df23d1c2645ca96ac61ebdeb6aa" + }, + "TOMLKey.swift": { + "source": "Sources/TOMLDecoder/TOMLKey.swift", + "sha256": "ccf76e6622ab7e585fb7e0fb2e812c48c42b96d5761a9970866f3d8bf90b4f1e" + }, + "TOMLError.swift": { + "source": "Sources/TOMLDecoder/TOMLError.swift", + "sha256": "b7f18d5a666d4e64fa9c12c0de73a0a53a506262be093e99d7f50b52156c6417" + }, + "LICENSE": { + "source": "LICENSE.md", + "sha256": "ee59f20a0a5550b0b071a0d9edb31c29629ce4bad2d8f5d0467ee7d574b541cf" + } + }, + "patches": { + "description": "PATCHES.md", + "diff": "upstream.patch", + "sha256": "985f698f5bd81b42c08c478cfe8bfc93dcd9e05afd409caaa4400fffb42cd16c", + "context_lines": 0 + } +} diff --git a/Sources/TOMLSemantics/upstream.patch b/Sources/TOMLSemantics/upstream.patch new file mode 100644 index 0000000..b139941 --- /dev/null +++ b/Sources/TOMLSemantics/upstream.patch @@ -0,0 +1,6975 @@ +--- Sources/TOMLDecoder/Parsing/Parser.swift ++++ Sources/TOMLSemantics/Parsing/Parser.swift +@@ -2,31 +2,202 @@ +- var token = Token.empty +- var cursor = 0 +- var currentLineNumber = 1 +- var currentTable = 0 +- var currentTableIsKeyed = false +- var tablePath: [(key: String, keyHash: Int)] = [] +- var tables: [InternalTOMLTable] = [InternalTOMLTable()] +- var arrays: [InternalTOMLArray] = [] +- var keyTables: [KeyTablePair] = [] +- var keyArrays: [KeyArrayPair] = [] +- var keyValues: [KeyValuePair] = [] +- var keyTransform: (@Sendable (String) -> String)? +- +- mutating func parse(bytes: UnsafeBufferPointer) throws(TOMLError) { +- let estimatedKeyValues = max(32, bytes.count / 48) +- let estimatedNodes = max(8, estimatedKeyValues / 8) +- tables.reserveCapacity(max(8, estimatedNodes)) +- arrays.reserveCapacity(estimatedNodes) +- keyTables.reserveCapacity(estimatedNodes) +- keyArrays.reserveCapacity(estimatedNodes) +- keyValues.reserveCapacity(estimatedKeyValues) +- tablePath.reserveCapacity(8) +- +- while token.kind != .eof { +- switch token.kind { +- case .newline: +- try nextToken(bytes: bytes, isDotSpecial: true) +- case .string, .bareKey: +- try parseKeyValue(bytes: bytes, tableIndex: currentTable, isKeyed: currentTableIsKeyed) +- if token.kind != .newline, token.kind != .eof { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "extra chars after value")) ++ let budget: SemanticBudget ++ var depth = 0 ++ var token = Token.empty ++ var cursor = 0 ++ var currentLineNumber = 1 ++ var currentTable = 0 ++ var currentTableIsKeyed = false ++ var tablePath: [(key: String, keyHash: Int)] = [] ++ var tables: [InternalTOMLTable] = [] ++ var arrays: [InternalTOMLArray] = [] ++ var keyTables: [KeyTablePair] = [] ++ var keyArrays: [KeyArrayPair] = [] ++ var keyValues: [KeyValuePair] = [] ++ ++ mutating func parse(bytes: UnsafeBufferPointer) throws { ++ try budget.node(depth: 0) ++ tables.append(InternalTOMLTable()) ++ let estimatedKeyValues = max(32, bytes.count / 48) ++ let estimatedNodes = max(8, estimatedKeyValues / 8) ++ try budget.allocate(max(8, estimatedNodes), stage: "semantic storage") ++ tables.reserveCapacity(max(8, estimatedNodes)) ++ try budget.allocate(estimatedNodes, stage: "semantic storage") ++ arrays.reserveCapacity(estimatedNodes) ++ try budget.allocate(estimatedNodes, stage: "semantic storage") ++ keyTables.reserveCapacity(estimatedNodes) ++ try budget.allocate(estimatedNodes, stage: "semantic storage") ++ keyArrays.reserveCapacity(estimatedNodes) ++ try budget.allocate(estimatedKeyValues, stage: "semantic storage") ++ keyValues.reserveCapacity(estimatedKeyValues) ++ try budget.allocate(8, stage: "semantic storage") ++ tablePath.reserveCapacity(8) ++ ++ while token.kind != .eof { ++ try budget.step() ++ switch token.kind { ++ case .newline: ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ case .string, .bareKey: ++ try parseKeyValue(bytes: bytes, tableIndex: currentTable, isKeyed: currentTableIsKeyed) ++ if token.kind != .newline, token.kind != .eof { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "extra chars after value")) ++ } ++ if token.kind == .newline { ++ try eatToken(bytes: bytes, kind: .newline, isDotSpecial: true) ++ } ++ case .lbracket: ++ try parseSelect(bytes: bytes) ++ default: ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) ++ } ++ } ++ } ++ ++ mutating func nextToken(bytes: UnsafeBufferPointer, isDotSpecial: Bool) throws { ++ let lineNumber = currentLineNumber ++ var position = cursor ++ ++ @inline(__always) ++ func emitToken(kind: Token.Kind, start: Int, end: Int, newlines: Int = 0) throws { ++ try budget.node(depth: depth) ++ token = Token(budget: budget, kind: kind, lineNumber: lineNumber, text: start..= CodeUnits.null && commentChar <= CodeUnits.backspace) ++ || (commentChar >= CodeUnits.lf && commentChar <= CodeUnits.unitSeparator) ++ || commentChar == CodeUnits.delete ++ { ++ if commentChar == CodeUnits.cr { ++ let nextPosition = position + 1 ++ if nextPosition < count, bytes[nextPosition] == CodeUnits.lf { ++ // Allow CRLF sequence ++ } else { ++ throw TOMLError( ++ .syntax( ++ lineNumber: lineNumber, ++ message: "control characters are not allowed in comments" ++ ) ++ ) ++ } ++ } else { ++ throw TOMLError( ++ .syntax( ++ lineNumber: lineNumber, ++ message: "control characters are not allowed in comments" ++ ) ++ ) ++ } ++ } ++ position += 1 ++ } ++ continue ++ case CodeUnits.space, CodeUnits.tab: ++ // ignore white spaces ++ position += 1 ++ while position < count { ++ try budget.step() ++ let ws = bytes[position] ++ if ws != CodeUnits.space, ws != CodeUnits.tab { ++ break ++ } ++ position += 1 ++ } ++ continue ++ case CodeUnits.dot where isDotSpecial: ++ try emitToken(kind: .dot, start: position, end: position + 1) ++ return ++ case CodeUnits.comma: ++ try emitToken(kind: .comma, start: position, end: position + 1) ++ return ++ case CodeUnits.equal: ++ try emitToken(kind: .equal, start: position, end: position + 1) ++ return ++ case CodeUnits.lbrace: ++ try emitToken(kind: .lbrace, start: position, end: position + 1) ++ return ++ case CodeUnits.rbrace: ++ try emitToken(kind: .rbrace, start: position, end: position + 1) ++ return ++ case CodeUnits.lbracket: ++ try emitToken(kind: .lbracket, start: position, end: position + 1) ++ return ++ case CodeUnits.rbracket: ++ try emitToken(kind: .rbracket, start: position, end: position + 1) ++ return ++ case CodeUnits.lf: ++ try emitToken(kind: .newline, start: position, end: position + 1, newlines: 1) ++ return ++ case CodeUnits.cr: ++ // Check if this is part of a CRLF sequence ++ let nextPosition = position + 1 ++ if nextPosition < count, bytes[nextPosition] == CodeUnits.lf { ++ // This is CRLF, treat as newline ++ try emitToken(kind: .newline, start: position, end: nextPosition + 1, newlines: 1) ++ return ++ } ++ // Bare CR is invalid ++ throw TOMLError( ++ .syntax( ++ lineNumber: lineNumber, ++ message: "bare carriage return is not allowed" ++ ) ++ ) ++ default: ++ break ++ } ++ ++ func scanString(range: Range, lineNumber: Int) throws { ++ let start = range.lowerBound ++ let end = range.upperBound ++ let head = bytes[start] ++ if (head >= CodeUnits.lowerA && head <= CodeUnits.lowerZ) ++ || (head >= CodeUnits.upperA && head <= CodeUnits.upperZ) || head == CodeUnits.underscore ++ { ++ let isBareKeyChar = CodeUnits.isBareKeyChar ++ var index = start + 1 ++ while index < end { ++ try budget.step() ++ let ch = bytes[index] ++ if isBareKeyChar[Int(ch)] { ++ index += 1 ++ continue ++ } ++ break ++ } ++ try emitToken(kind: .bareKey, start: start, end: index) ++ return ++ } ++ ++ if head == CodeUnits.singleQuote { ++ if start + 3 <= end, ++ bytes[start + 1] == CodeUnits.singleQuote, ++ bytes[start + 2] == CodeUnits.singleQuote ++ { ++ var i = start + 3 ++ var newlinesInToken = 0 ++ ++ while i < end { ++ try budget.step() ++ if bytes[i] == CodeUnits.lf { ++ newlinesInToken += 1 ++ } ++ if i + 3 <= end, ++ bytes[i] == CodeUnits.singleQuote, ++ bytes[i + 1] == CodeUnits.singleQuote, ++ bytes[i + 2] == CodeUnits.singleQuote ++ { ++ if i + 3 >= end || bytes[i + 3] != CodeUnits.singleQuote { ++ break +@@ -34,2 +205,58 @@ +- if token.kind == .newline { +- try eatToken(bytes: bytes, kind: .newline, isDotSpecial: true) ++ } ++ i += 1 ++ } ++ ++ guard i < end else { ++ throw TOMLError( ++ .syntax(lineNumber: lineNumber, message: "unterminated triple-s-quote") ++ ) ++ } ++ ++ try emitToken(kind: .string, start: start, end: i + 3, newlines: newlinesInToken) ++ return ++ } ++ ++ var i = start + 1 ++ while i < end { ++ try budget.step() ++ let ch = bytes[i] ++ if ch == CodeUnits.singleQuote || ch == CodeUnits.lf { ++ break ++ } ++ i += 1 ++ } ++ ++ if i >= end || bytes[i] != CodeUnits.singleQuote { ++ throw TOMLError( ++ .syntax(lineNumber: lineNumber, message: "unterminated s-quote") ++ ) ++ } ++ ++ try emitToken(kind: .string, start: start, end: i + 1) ++ return ++ } ++ ++ if head == CodeUnits.doubleQuote { ++ if start + 3 < end, ++ bytes[start + 1] == CodeUnits.doubleQuote, ++ bytes[start + 2] == CodeUnits.doubleQuote ++ { ++ var i = start + 3 ++ var newlinesInToken = 0 ++ ++ while i < end { ++ try budget.step() ++ if bytes[i] == CodeUnits.lf { ++ newlinesInToken += 1 ++ } ++ if i + 3 <= end, ++ bytes[i] == CodeUnits.doubleQuote, ++ bytes[i + 1] == CodeUnits.doubleQuote, ++ bytes[i + 2] == CodeUnits.doubleQuote ++ { ++ if i + 3 >= end || bytes[i + 3] != CodeUnits.doubleQuote { ++ if bytes[i - 1] == CodeUnits.backslash { ++ i += 1 ++ continue ++ } ++ break +@@ -37,4 +264,2 @@ +- case .lbracket: +- try parseSelect(bytes: bytes) +- default: +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) ++ } ++ i += 1 +@@ -42,15 +267,362 @@ +- } +- } +- +- mutating func nextToken(bytes: UnsafeBufferPointer, isDotSpecial: Bool) throws(TOMLError) { +- let lineNumber = currentLineNumber +- var position = cursor +- +- @inline(__always) +- func emitToken(kind: Token.Kind, start: Int, end: Int, newlines: Int = 0) { +- token = Token(kind: kind, lineNumber: lineNumber, text: start ..< end) +- cursor = end +- currentLineNumber = lineNumber + newlines +- } +- +- let count = bytes.count ++ ++ guard i < end else { ++ throw TOMLError( ++ .syntax(lineNumber: lineNumber, message: "unterminated triple-d-quote") ++ ) ++ } ++ ++ try emitToken(kind: .string, start: start, end: i + 3, newlines: newlinesInToken) ++ return ++ } ++ ++ var i = start + 1 ++ let isBasicStringBodyChar = CodeUnits.isBasicStringBodyChar ++ let baseAddress = bytes.baseAddress! ++ while i + 8 <= end { ++ try budget.step() ++ let chunk = UnsafeRawPointer(baseAddress.advanced(by: i)).loadUnaligned( ++ as: UInt64.self ++ ) ++ if chunkContainsDoubleQuotedStopByte(chunk) { ++ break ++ } ++ i += 8 ++ } ++ ++ while i < end { ++ try budget.step() ++ let ch = bytes[i] ++ if isBasicStringBodyChar[Int(ch)] { ++ i += 1 ++ continue ++ } ++ if ch == CodeUnits.backslash { ++ i += 1 ++ if i < end { ++ i += 1 ++ continue ++ } ++ break ++ } ++ ++ break ++ } ++ ++ if i >= end || bytes[i] != CodeUnits.doubleQuote { ++ throw TOMLError( ++ .syntax(lineNumber: lineNumber, message: "unterminated quote") ++ ) ++ } ++ ++ try emitToken(kind: .string, start: start, end: i + 1) ++ return ++ } ++ ++ if !isDotSpecial { ++ var index = start ++ var dateEnder: Int? ++ // Fast path: Dates must produce YYYY-MM-DD, so checks for the dash ++ if start + 4 < end && bytes[start + 4] == CodeUnits.minus { ++ dateEnder = scanDate(bytes: bytes, range: range)?.3 ++ } ++ ++ if let dateEnder, dateEnder < end, ++ bytes[dateEnder] == CodeUnits.upperT || bytes[dateEnder] == CodeUnits.lowerT ++ || bytes[dateEnder] == CodeUnits.space ++ { ++ let timeStarter = dateEnder + 1 ++ if let timeEnder = scanTime( ++ bytes: bytes, range: timeStarter.. start { ++ if index < end { ++ if bytes[index] == CodeUnits.dot { ++ index += 1 ++ while index < end, bytes[index] >= CodeUnits.number0, ++ bytes[index] <= CodeUnits.number9 ++ { ++ try budget.step() ++ index += 1 ++ } ++ } ++ if index < end, bytes[index] == CodeUnits.upperZ || bytes[index] == CodeUnits.lowerZ { ++ index += 1 ++ } else if let timzoneEnder = scanTimezoneOffset( ++ bytes: bytes, range: index.. start, bytes[index - 1] == CodeUnits.space { ++ try budget.step() ++ index -= 1 ++ } ++ // tokenize ++ try emitToken(kind: .string, start: start, end: index) ++ return ++ } ++ } ++ ++ if isDotSpecial { ++ let isBareKeyChar = CodeUnits.isBareKeyChar ++ var index = start ++ while index < end, isBareKeyChar[Int(bytes[index])] { ++ try budget.step() ++ index += 1 ++ } ++ if index >= end || bytes[index] != CodeUnits.plus { ++ try emitToken(kind: .bareKey, start: start, end: index) ++ return ++ } ++ ++ index += 1 ++ while index < end { ++ try budget.step() ++ let ch = bytes[index] ++ if isBareKeyChar[Int(ch)] || ch == CodeUnits.plus { ++ index += 1 ++ continue ++ } ++ break ++ } ++ try emitToken(kind: .string, start: start, end: index) ++ } else { ++ let isValueChar = CodeUnits.isValueChar ++ var index = start ++ while index < end { ++ try budget.step() ++ let ch = bytes[index] ++ if isValueChar[Int(ch)] { ++ index += 1 ++ continue ++ } ++ break ++ } ++ try emitToken(kind: .string, start: start, end: index) ++ } ++ } ++ ++ try scanString(range: position.., kind: Token.Kind, isDotSpecial: Bool) ++ throws ++ { ++ if token.kind != kind { ++ throw TOMLError(.internalError(lineNumber: token.lineNumber)) ++ } ++ try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) ++ } ++ ++ mutating func createKeyValue( ++ bytes: UnsafeBufferPointer, ++ token: Token, ++ value: Token, ++ inTable tableIndex: Int, ++ isKeyed: Bool ++ ) throws { ++ let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token) ++ if try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) != nil { ++ throw TOMLError(.badKey(lineNumber: token.lineNumber)) ++ } ++ let index = keyValues.count ++ try budget.node(depth: depth) ++ keyValues.append( ++ KeyValuePair(key: key, keyHash: keyHash, sourcePosition: token.text.lowerBound, value: value)) ++ ++ if isKeyed { ++ if keyTables[tableIndex].table.keyValues.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ keyTables[tableIndex].table.keyValues.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ keyTables[tableIndex].table.keyValues.append(index) ++ keyTables[tableIndex].table.recordKeyHash(keyHash) ++ } else { ++ if tables[tableIndex].keyValues.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ tables[tableIndex].keyValues.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ tables[tableIndex].keyValues.append(index) ++ tables[tableIndex].recordKeyHash(keyHash) ++ } ++ } ++ ++ mutating func createKeyTable( ++ bytes: UnsafeBufferPointer, token: Token, inTable tableIndex: Int, isKeyed: Bool, ++ implicit: Bool = false ++ ) throws -> Int { ++ let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token) ++ return try createKeyTable( ++ normalizedKey: key, ++ keyHash: keyHash, ++ lineNumber: token.lineNumber, ++ inTable: tableIndex, ++ isKeyed: isKeyed, ++ implicit: implicit ++ ) ++ } ++ ++ mutating func createKeyTable( ++ normalizedKey key: String, keyHash: Int, lineNumber: Int, inTable tableIndex: Int, ++ isKeyed: Bool, implicit: Bool = false ++ ) throws -> Int { ++ // Check if parent table is readOnly (inline table) ++ if isKeyed ? keyTables[tableIndex].table.readOnly : tables[tableIndex].readOnly { ++ throw TOMLError(.syntax(lineNumber: lineNumber, message: "cannot add to inline table")) ++ } ++ ++ switch try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) { ++ case .table(let existingTableIndex): ++ if keyTables[existingTableIndex].table.implicit { ++ if keyTables[existingTableIndex].table.definedByDottedKey { ++ throw TOMLError(.keyExists(lineNumber: lineNumber)) ++ } ++ keyTables[existingTableIndex].table.implicit = false ++ return existingTableIndex ++ } ++ throw TOMLError(.keyExists(lineNumber: lineNumber)) ++ case .keyValue, .array: ++ throw TOMLError(.keyExists(lineNumber: lineNumber)) ++ case nil: ++ break ++ } ++ let index = keyTables.count ++ var newTable = InternalTOMLTable() ++ newTable.implicit = implicit ++ newTable.definedByDottedKey = implicit ++ try budget.node(depth: depth) ++ keyTables.append( ++ KeyTablePair( ++ key: key, keyHash: keyHash, sourcePosition: token.text.lowerBound, table: newTable)) ++ ++ if isKeyed { ++ if keyTables[tableIndex].table.tables.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ keyTables[tableIndex].table.tables.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ keyTables[tableIndex].table.tables.append(index) ++ keyTables[tableIndex].table.recordKeyHash(keyHash) ++ } else { ++ if tables[tableIndex].tables.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ tables[tableIndex].tables.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ tables[tableIndex].tables.append(index) ++ tables[tableIndex].recordKeyHash(keyHash) ++ } ++ return index ++ } ++ ++ mutating func createKeyArray( ++ bytes: UnsafeBufferPointer, token: Token, inTable tableIndex: Int, isKeyed: Bool, ++ kind: InternalTOMLArray.Kind? = nil ++ ) throws -> Int { ++ let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token) ++ return try createKeyArray( ++ normalizedKey: key, ++ keyHash: keyHash, ++ lineNumber: token.lineNumber, ++ inTable: tableIndex, ++ isKeyed: isKeyed, ++ kind: kind ++ ) ++ } ++ ++ mutating func createKeyArray( ++ normalizedKey key: String, keyHash: Int, lineNumber: Int, inTable tableIndex: Int, ++ isKeyed: Bool, kind: InternalTOMLArray.Kind? = nil ++ ) throws -> Int { ++ if try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) != nil { ++ throw TOMLError(.keyExists(lineNumber: lineNumber)) ++ } ++ ++ let index = keyArrays.count ++ var array = InternalTOMLArray(kind: kind) ++ if kind == .table { ++ try budget.allocate(8, stage: "semantic storage") ++ array.elements.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ keyArrays.append( ++ KeyArrayPair(key: key, keyHash: keyHash, sourcePosition: token.text.lowerBound, array: array)) ++ if isKeyed { ++ if keyTables[tableIndex].table.arrays.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ keyTables[tableIndex].table.arrays.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ keyTables[tableIndex].table.arrays.append(index) ++ keyTables[tableIndex].table.recordKeyHash(keyHash) ++ } else { ++ if tables[tableIndex].arrays.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ tables[tableIndex].arrays.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ tables[tableIndex].arrays.append(index) ++ tables[tableIndex].recordKeyHash(keyHash) ++ } ++ return index ++ } ++ ++ @inline(__always) ++ mutating func skipNewlines(bytes: UnsafeBufferPointer, isDotSpecial: Bool) throws { ++ if token.kind != .newline { ++ return ++ } ++ ++ let count = bytes.count ++ var position = cursor ++ var lineNumber = currentLineNumber ++ ++ while position < count { ++ try budget.step() ++ let ch = bytes[position] ++ if ch == CodeUnits.space || ch == CodeUnits.tab { ++ // 8x unrolling for space/tab skipping ++ while position + 8 <= count { ++ try budget.step() ++ let c0 = bytes[position] ++ let c1 = bytes[position + 1] ++ let c2 = bytes[position + 2] ++ let c3 = bytes[position + 3] ++ let c4 = bytes[position + 4] ++ let c5 = bytes[position + 5] ++ let c6 = bytes[position + 6] ++ let c7 = bytes[position + 7] ++ ++ if c0 == CodeUnits.space || c0 == CodeUnits.tab, ++ c1 == CodeUnits.space || c1 == CodeUnits.tab, ++ c2 == CodeUnits.space || c2 == CodeUnits.tab, ++ c3 == CodeUnits.space || c3 == CodeUnits.tab, ++ c4 == CodeUnits.space || c4 == CodeUnits.tab, ++ c5 == CodeUnits.space || c5 == CodeUnits.tab, ++ c6 == CodeUnits.space || c6 == CodeUnits.tab, ++ c7 == CodeUnits.space || c7 == CodeUnits.tab ++ { ++ position += 8 ++ } else { ++ break ++ } ++ } ++ +@@ -58,87 +630,39 @@ +- let ch = bytes[position] +- switch ch { +- case CodeUnits.pound: +- // skip comment, stop just before the \n. +- position += 1 +- while position < count, bytes[position] != CodeUnits.lf { +- let commentChar = bytes[position] +- // Validate comment characters - control characters are not allowed except CR when followed by LF (CRLF) +- if (commentChar >= CodeUnits.null && commentChar <= CodeUnits.backspace) +- || (commentChar >= CodeUnits.lf && commentChar <= CodeUnits.unitSeparator) +- || commentChar == CodeUnits.delete +- { +- if commentChar == CodeUnits.cr { +- let nextPosition = position + 1 +- if nextPosition < count, bytes[nextPosition] == CodeUnits.lf { +- // Allow CRLF sequence +- } else { +- throw TOMLError( +- .syntax( +- lineNumber: lineNumber, +- message: "control characters are not allowed in comments" +- ) +- ) +- } +- } else { +- throw TOMLError( +- .syntax( +- lineNumber: lineNumber, +- message: "control characters are not allowed in comments" +- ) +- ) +- } +- } +- position += 1 +- } +- continue +- case CodeUnits.space, CodeUnits.tab: +- // ignore white spaces +- position += 1 +- while position < count { +- let ws = bytes[position] +- if ws != CodeUnits.space, ws != CodeUnits.tab { +- break +- } +- position += 1 +- } +- continue +- case CodeUnits.dot where isDotSpecial: +- emitToken(kind: .dot, start: position, end: position + 1) +- return +- case CodeUnits.comma: +- emitToken(kind: .comma, start: position, end: position + 1) +- return +- case CodeUnits.equal: +- emitToken(kind: .equal, start: position, end: position + 1) +- return +- case CodeUnits.lbrace: +- emitToken(kind: .lbrace, start: position, end: position + 1) +- return +- case CodeUnits.rbrace: +- emitToken(kind: .rbrace, start: position, end: position + 1) +- return +- case CodeUnits.lbracket: +- emitToken(kind: .lbracket, start: position, end: position + 1) +- return +- case CodeUnits.rbracket: +- emitToken(kind: .rbracket, start: position, end: position + 1) +- return +- case CodeUnits.lf: +- emitToken(kind: .newline, start: position, end: position + 1, newlines: 1) +- return +- case CodeUnits.cr: +- // Check if this is part of a CRLF sequence +- let nextPosition = position + 1 +- if nextPosition < count, bytes[nextPosition] == CodeUnits.lf { +- // This is CRLF, treat as newline +- emitToken(kind: .newline, start: position, end: nextPosition + 1, newlines: 1) +- return +- } +- // Bare CR is invalid +- throw TOMLError( +- .syntax( +- lineNumber: lineNumber, +- message: "bare carriage return is not allowed" +- ) +- ) +- default: ++ try budget.step() ++ let ws = bytes[position] ++ if ws != CodeUnits.space, ws != CodeUnits.tab { ++ break ++ } ++ position += 1 ++ } ++ continue ++ } ++ switch ch { ++ case CodeUnits.lf: ++ lineNumber += 1 ++ position += 1 ++ case CodeUnits.cr: ++ if position + 1 < count, bytes[position + 1] == CodeUnits.lf { ++ lineNumber += 1 ++ position += 2 ++ } else { ++ // Bare CR, let nextToken handle error ++ cursor = position ++ currentLineNumber = lineNumber ++ try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) ++ return ++ } ++ case CodeUnits.pound: ++ // Comment ++ position += 1 ++ while position < count { ++ try budget.step() ++ let c = bytes[position] ++ if c == CodeUnits.lf { ++ break // Leave LF for next iteration to handle line number ++ } ++ if (c >= CodeUnits.null && c <= CodeUnits.backspace) ++ || (c >= CodeUnits.lf && c <= CodeUnits.unitSeparator) || c == CodeUnits.delete ++ { ++ if c == CodeUnits.cr { ++ if position + 1 < count, bytes[position + 1] == CodeUnits.lf { ++ // CRLF ends comment +@@ -145,0 +670 @@ ++ } +@@ -147,247 +672,4 @@ +- +- func scanString(range: Range, lineNumber: Int) throws(TOMLError) { +- let start = range.lowerBound +- let end = range.upperBound +- let head = bytes[start] +- if (head >= CodeUnits.lowerA && head <= CodeUnits.lowerZ) || +- (head >= CodeUnits.upperA && head <= CodeUnits.upperZ) || +- head == CodeUnits.underscore +- { +- let isBareKeyChar = CodeUnits.isBareKeyChar +- var index = start + 1 +- while index < end { +- let ch = bytes[index] +- if isBareKeyChar[Int(ch)] { +- index += 1 +- continue +- } +- break +- } +- emitToken(kind: .bareKey, start: start, end: index) +- return +- } +- +- if head == CodeUnits.singleQuote { +- if start + 3 <= end, +- bytes[start + 1] == CodeUnits.singleQuote, +- bytes[start + 2] == CodeUnits.singleQuote +- { +- var i = start + 3 +- var newlinesInToken = 0 +- +- while i < end { +- if bytes[i] == CodeUnits.lf { +- newlinesInToken += 1 +- } +- if i + 3 <= end, +- bytes[i] == CodeUnits.singleQuote, +- bytes[i + 1] == CodeUnits.singleQuote, +- bytes[i + 2] == CodeUnits.singleQuote +- { +- if i + 3 >= end || bytes[i + 3] != CodeUnits.singleQuote { +- break +- } +- } +- i += 1 +- } +- +- guard i < end else { +- throw TOMLError( +- .syntax(lineNumber: lineNumber, message: "unterminated triple-s-quote") +- ) +- } +- +- emitToken(kind: .string, start: start, end: i + 3, newlines: newlinesInToken) +- return +- } +- +- var i = start + 1 +- while i < end { +- let ch = bytes[i] +- if ch == CodeUnits.singleQuote || ch == CodeUnits.lf { +- break +- } +- i += 1 +- } +- +- if i >= end || bytes[i] != CodeUnits.singleQuote { +- throw TOMLError( +- .syntax(lineNumber: lineNumber, message: "unterminated s-quote") +- ) +- } +- +- emitToken(kind: .string, start: start, end: i + 1) +- return +- } +- +- if head == CodeUnits.doubleQuote { +- if start + 3 < end, +- bytes[start + 1] == CodeUnits.doubleQuote, +- bytes[start + 2] == CodeUnits.doubleQuote +- { +- var i = start + 3 +- var newlinesInToken = 0 +- +- while i < end { +- if bytes[i] == CodeUnits.lf { +- newlinesInToken += 1 +- } +- if i + 3 <= end, +- bytes[i] == CodeUnits.doubleQuote, +- bytes[i + 1] == CodeUnits.doubleQuote, +- bytes[i + 2] == CodeUnits.doubleQuote +- { +- if i + 3 >= end || bytes[i + 3] != CodeUnits.doubleQuote { +- if bytes[i - 1] == CodeUnits.backslash { +- i += 1 +- continue +- } +- break +- } +- } +- i += 1 +- } +- +- guard i < end else { +- throw TOMLError( +- .syntax(lineNumber: lineNumber, message: "unterminated triple-d-quote") +- ) +- } +- +- emitToken(kind: .string, start: start, end: i + 3, newlines: newlinesInToken) +- return +- } +- +- var i = start + 1 +- let isBasicStringBodyChar = CodeUnits.isBasicStringBodyChar +- let baseAddress = bytes.baseAddress! +- while i + 8 <= end { +- let chunk = UnsafeRawPointer(baseAddress.advanced(by: i)).loadUnaligned( +- as: UInt64.self +- ) +- if chunkContainsDoubleQuotedStopByte(chunk) { +- break +- } +- i += 8 +- } +- +- while i < end { +- let ch = bytes[i] +- if isBasicStringBodyChar[Int(ch)] { +- i += 1 +- continue +- } +- if ch == CodeUnits.backslash { +- i += 1 +- if i < end { +- i += 1 +- continue +- } +- break +- } +- +- break +- } +- +- if i >= end || bytes[i] != CodeUnits.doubleQuote { +- throw TOMLError( +- .syntax(lineNumber: lineNumber, message: "unterminated quote") +- ) +- } +- +- emitToken(kind: .string, start: start, end: i + 1) +- return +- } +- +- if !isDotSpecial { +- var index = start +- var dateEnder: Int? +- // Fast path: Dates must produce YYYY-MM-DD, so checks for the dash +- if start + 4 < end && bytes[start + 4] == CodeUnits.minus { +- dateEnder = scanDate(bytes: bytes, range: range)?.3 +- } +- +- if let dateEnder, dateEnder < end, +- bytes[dateEnder] == CodeUnits.upperT || bytes[dateEnder] == CodeUnits.lowerT +- || bytes[dateEnder] == CodeUnits.space +- { +- let timeStarter = dateEnder + 1 +- if let timeEnder = scanTime( +- bytes: bytes, range: timeStarter ..< end +- )?.3 { +- index = timeEnder +- } +- } else if let dateEnder { +- index = dateEnder +- } else if start + 2 < end, bytes[start + 2] == CodeUnits.colon, +- let timeEnder = scanTime( +- bytes: bytes, range: start ..< end +- )?.3 +- { +- index = timeEnder +- } +- if index > start { +- if index < end { +- if bytes[index] == CodeUnits.dot { +- index += 1 +- while index < end, bytes[index] >= CodeUnits.number0, +- bytes[index] <= CodeUnits.number9 +- { +- index += 1 +- } +- } +- if bytes[index] == CodeUnits.upperZ || bytes[index] == CodeUnits.lowerZ { +- index += 1 +- } else if let timzoneEnder = scanTimezoneOffset( +- bytes: bytes, range: index ..< end +- ) { +- index = timzoneEnder +- } +- } +- // squeeze out any spaces at end of string +- while index > start, bytes[index - 1] == CodeUnits.space { +- index -= 1 +- } +- // tokenize +- emitToken(kind: .string, start: start, end: index) +- return +- } +- } +- +- if isDotSpecial { +- let isBareKeyChar = CodeUnits.isBareKeyChar +- var index = start +- while index < end, isBareKeyChar[Int(bytes[index])] { +- index += 1 +- } +- if index >= end || bytes[index] != CodeUnits.plus { +- emitToken(kind: .bareKey, start: start, end: index) +- return +- } +- +- index += 1 +- while index < end { +- let ch = bytes[index] +- if isBareKeyChar[Int(ch)] || ch == CodeUnits.plus { +- index += 1 +- continue +- } +- break +- } +- emitToken(kind: .string, start: start, end: index) +- } else { +- let isValueChar = CodeUnits.isValueChar +- var index = start +- while index < end { +- let ch = bytes[index] +- if isValueChar[Int(ch)] { +- index += 1 +- continue +- } +- break +- } +- emitToken(kind: .string, start: start, end: index) +- } +- } +- +- try scanString(range: position ..< count, lineNumber: lineNumber) ++ // Let nextToken throw the error ++ cursor = position ++ currentLineNumber = lineNumber ++ try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) +@@ -395,236 +677,5 @@ +- } +- +- emitToken(kind: .eof, start: position, end: count) +- } +- +- mutating func eatToken(bytes: UnsafeBufferPointer, kind: Token.Kind, isDotSpecial: Bool) +- throws(TOMLError) +- { +- if token.kind != kind { +- throw TOMLError(.internalError(lineNumber: token.lineNumber)) +- } +- try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) +- } +- +- mutating func createKeyValue( +- bytes: UnsafeBufferPointer, +- token: Token, +- value: Token, +- inTable tableIndex: Int, +- isKeyed: Bool +- ) throws(TOMLError) { +- let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token, keyTransform: keyTransform) +- if tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) != nil { +- throw TOMLError(.badKey(lineNumber: token.lineNumber)) +- } +- let index = keyValues.count +- keyValues.append(KeyValuePair(key: key, keyHash: keyHash, value: value)) +- +- if isKeyed { +- if keyTables[tableIndex].table.keyValues.isEmpty { +- keyTables[tableIndex].table.keyValues.reserveCapacity(8) +- } +- keyTables[tableIndex].table.keyValues.append(index) +- keyTables[tableIndex].table.recordKeyHash(keyHash) +- } else { +- if tables[tableIndex].keyValues.isEmpty { +- tables[tableIndex].keyValues.reserveCapacity(8) +- } +- tables[tableIndex].keyValues.append(index) +- tables[tableIndex].recordKeyHash(keyHash) +- } +- } +- +- mutating func createKeyTable(bytes: UnsafeBufferPointer, token: Token, inTable tableIndex: Int, isKeyed: Bool, implicit: Bool = false) throws(TOMLError) -> Int { +- let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token, keyTransform: keyTransform) +- return try createKeyTable( +- normalizedKey: key, +- keyHash: keyHash, +- lineNumber: token.lineNumber, +- inTable: tableIndex, +- isKeyed: isKeyed, +- implicit: implicit +- ) +- } +- +- mutating func createKeyTable(normalizedKey key: String, keyHash: Int, lineNumber: Int, inTable tableIndex: Int, isKeyed: Bool, implicit: Bool = false) throws(TOMLError) -> Int { +- // Check if parent table is readOnly (inline table) +- if isKeyed ? keyTables[tableIndex].table.readOnly : tables[tableIndex].readOnly { +- throw TOMLError(.syntax(lineNumber: lineNumber, message: "cannot add to inline table")) +- } +- +- switch tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) { +- case let .table(existingTableIndex): +- if keyTables[existingTableIndex].table.implicit { +- if keyTables[existingTableIndex].table.definedByDottedKey { +- throw TOMLError(.keyExists(lineNumber: lineNumber)) +- } +- keyTables[existingTableIndex].table.implicit = false +- return existingTableIndex +- } +- throw TOMLError(.keyExists(lineNumber: lineNumber)) +- case .keyValue, .array: +- throw TOMLError(.keyExists(lineNumber: lineNumber)) +- case nil: +- break +- } +- let index = keyTables.count +- var newTable = InternalTOMLTable() +- newTable.implicit = implicit +- newTable.definedByDottedKey = implicit +- keyTables.append(KeyTablePair(key: key, keyHash: keyHash, table: newTable)) +- +- if isKeyed { +- if keyTables[tableIndex].table.tables.isEmpty { +- keyTables[tableIndex].table.tables.reserveCapacity(8) +- } +- keyTables[tableIndex].table.tables.append(index) +- keyTables[tableIndex].table.recordKeyHash(keyHash) +- } else { +- if tables[tableIndex].tables.isEmpty { +- tables[tableIndex].tables.reserveCapacity(8) +- } +- tables[tableIndex].tables.append(index) +- tables[tableIndex].recordKeyHash(keyHash) +- } +- return index +- } +- +- mutating func createKeyArray(bytes: UnsafeBufferPointer, token: Token, inTable tableIndex: Int, isKeyed: Bool, kind: InternalTOMLArray.Kind? = nil) throws(TOMLError) -> Int { +- let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token, keyTransform: keyTransform) +- return try createKeyArray( +- normalizedKey: key, +- keyHash: keyHash, +- lineNumber: token.lineNumber, +- inTable: tableIndex, +- isKeyed: isKeyed, +- kind: kind +- ) +- } +- +- mutating func createKeyArray(normalizedKey key: String, keyHash: Int, lineNumber: Int, inTable tableIndex: Int, isKeyed: Bool, kind: InternalTOMLArray.Kind? = nil) throws(TOMLError) -> Int { +- if tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) != nil { +- throw TOMLError(.keyExists(lineNumber: lineNumber)) +- } +- +- let index = keyArrays.count +- var array = InternalTOMLArray(kind: kind) +- if kind == .table { +- array.elements.reserveCapacity(8) +- } +- keyArrays.append(KeyArrayPair(key: key, keyHash: keyHash, array: array)) +- if isKeyed { +- if keyTables[tableIndex].table.arrays.isEmpty { +- keyTables[tableIndex].table.arrays.reserveCapacity(8) +- } +- keyTables[tableIndex].table.arrays.append(index) +- keyTables[tableIndex].table.recordKeyHash(keyHash) +- } else { +- if tables[tableIndex].arrays.isEmpty { +- tables[tableIndex].arrays.reserveCapacity(8) +- } +- tables[tableIndex].arrays.append(index) +- tables[tableIndex].recordKeyHash(keyHash) +- } +- return index +- } +- +- @inline(__always) +- mutating func skipNewlines(bytes: UnsafeBufferPointer, isDotSpecial: Bool) throws(TOMLError) { +- if token.kind != .newline { +- return +- } +- +- let count = bytes.count +- var position = cursor +- var lineNumber = currentLineNumber +- +- while position < count { +- let ch = bytes[position] +- if ch == CodeUnits.space || ch == CodeUnits.tab { +- // 8x unrolling for space/tab skipping +- while position + 8 <= count { +- let c0 = bytes[position] +- let c1 = bytes[position + 1] +- let c2 = bytes[position + 2] +- let c3 = bytes[position + 3] +- let c4 = bytes[position + 4] +- let c5 = bytes[position + 5] +- let c6 = bytes[position + 6] +- let c7 = bytes[position + 7] +- +- if c0 == CodeUnits.space || c0 == CodeUnits.tab, +- c1 == CodeUnits.space || c1 == CodeUnits.tab, +- c2 == CodeUnits.space || c2 == CodeUnits.tab, +- c3 == CodeUnits.space || c3 == CodeUnits.tab, +- c4 == CodeUnits.space || c4 == CodeUnits.tab, +- c5 == CodeUnits.space || c5 == CodeUnits.tab, +- c6 == CodeUnits.space || c6 == CodeUnits.tab, +- c7 == CodeUnits.space || c7 == CodeUnits.tab +- { +- position += 8 +- } else { +- break +- } +- } +- +- while position < count { +- let ws = bytes[position] +- if ws != CodeUnits.space, ws != CodeUnits.tab { +- break +- } +- position += 1 +- } +- continue +- } +- switch ch { +- case CodeUnits.lf: +- lineNumber += 1 +- position += 1 +- case CodeUnits.cr: +- if position + 1 < count, bytes[position + 1] == CodeUnits.lf { +- lineNumber += 1 +- position += 2 +- } else { +- // Bare CR, let nextToken handle error +- cursor = position +- currentLineNumber = lineNumber +- try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) +- return +- } +- case CodeUnits.pound: +- // Comment +- position += 1 +- while position < count { +- let c = bytes[position] +- if c == CodeUnits.lf { +- break // Leave LF for next iteration to handle line number +- } +- if (c >= CodeUnits.null && c <= CodeUnits.backspace) || +- (c >= CodeUnits.lf && c <= CodeUnits.unitSeparator) || +- c == CodeUnits.delete +- { +- if c == CodeUnits.cr { +- if position + 1 < count, bytes[position + 1] == CodeUnits.lf { +- // CRLF ends comment +- break +- } +- } +- // Let nextToken throw the error +- cursor = position +- currentLineNumber = lineNumber +- try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) +- return +- } +- position += 1 +- } +- default: +- // Found something else, stop skipping +- cursor = position +- currentLineNumber = lineNumber +- try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) +- return +- } +- } +- +- // If we hit EOF or loop finishes ++ } ++ position += 1 ++ } ++ default: ++ // Found something else, stop skipping +@@ -634,10 +685,1078 @@ +- } +- +- mutating func parseKeyedInlineTable(bytes: UnsafeBufferPointer, tableIndex: Int) throws(TOMLError) { +- try eatToken(bytes: bytes, kind: .lbrace, isDotSpecial: true) +- +- while true { +- try skipNewlines(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .rbrace { +- break ++ return ++ } ++ } ++ ++ // If we hit EOF or loop finishes ++ cursor = position ++ currentLineNumber = lineNumber ++ try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) ++ } ++ ++ mutating func parseKeyedInlineTable(bytes: UnsafeBufferPointer, tableIndex: Int) throws { ++ try budget.enter(depth + 1) ++ depth += 1 ++ defer { depth -= 1 } ++ try eatToken(bytes: bytes, kind: .lbrace, isDotSpecial: true) ++ ++ while true { ++ try budget.step() ++ try skipNewlines(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .rbrace { ++ break ++ } ++ ++ if token.kind != .string, token.kind != .bareKey { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expect a string")) ++ } ++ ++ try parseKeyValue(bytes: bytes, tableIndex: tableIndex, isKeyed: true) ++ ++ try skipNewlines(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .comma { ++ try eatToken(bytes: bytes, kind: .comma, isDotSpecial: true) ++ continue ++ } ++ break ++ } ++ ++ try eatToken(bytes: bytes, kind: .rbrace, isDotSpecial: true) ++ ++ keyTables[tableIndex].table.readOnly = true ++ } ++ ++ mutating func parseInlineTable(bytes: UnsafeBufferPointer, tableIndex: Int) throws { ++ try budget.enter(depth + 1) ++ depth += 1 ++ defer { depth -= 1 } ++ try eatToken(bytes: bytes, kind: .lbrace, isDotSpecial: true) ++ ++ while true { ++ try budget.step() ++ try skipNewlines(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .rbrace { ++ break ++ } ++ ++ if token.kind != .string, token.kind != .bareKey { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expect a string")) ++ } ++ ++ try parseKeyValue(bytes: bytes, tableIndex: tableIndex, isKeyed: false) ++ ++ try skipNewlines(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .comma { ++ try eatToken(bytes: bytes, kind: .comma, isDotSpecial: true) ++ continue ++ } ++ break ++ } ++ ++ try eatToken(bytes: bytes, kind: .rbrace, isDotSpecial: true) ++ ++ tables[tableIndex].readOnly = true ++ } ++ ++ mutating func parseKeyedArray(bytes: UnsafeBufferPointer, arrayIndex: Int) throws { ++ try budget.enter(depth + 1) ++ depth += 1 ++ defer { depth -= 1 } ++ try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: false) ++ ++ while true { ++ try budget.step() ++ try skipNewlines(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .rbracket { ++ break ++ } ++ if keyArrays[arrayIndex].array.elements.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ keyArrays[arrayIndex].array.elements.reserveCapacity(8) ++ } ++ ++ switch token.kind { ++ case .string, .bareKey: ++ if keyArrays[arrayIndex].array.kind == nil { ++ keyArrays[arrayIndex].array.kind = .value ++ } else if keyArrays[arrayIndex].array.kind != .value { ++ keyArrays[arrayIndex].array.kind = .mixed ++ } ++ ++ try budget.node(depth: depth) ++ keyArrays[arrayIndex].array.elements.append(.leaf(token)) ++ ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ ++ case .lbracket: // Nested array ++ if keyArrays[arrayIndex].array.kind == nil { ++ keyArrays[arrayIndex].array.kind = .array ++ } else if keyArrays[arrayIndex].array.kind != .array { ++ keyArrays[arrayIndex].array.kind = .mixed ++ } ++ ++ let newArrayIndex = arrays.count ++ try budget.node(depth: depth) ++ arrays.append(InternalTOMLArray()) ++ try budget.node(depth: depth) ++ keyArrays[arrayIndex].array.elements.append( ++ .array(lineNumber: token.lineNumber, newArrayIndex)) ++ ++ try parseArray(bytes: bytes, arrayIndex: newArrayIndex) ++ ++ case .lbrace: // Nested table ++ if keyArrays[arrayIndex].array.kind == nil { ++ keyArrays[arrayIndex].array.kind = .table ++ } else if keyArrays[arrayIndex].array.kind != .table { ++ keyArrays[arrayIndex].array.kind = .mixed ++ } ++ ++ let newTableIndex = tables.count ++ try budget.node(depth: depth) ++ tables.append(InternalTOMLTable()) ++ try budget.node(depth: depth) ++ keyArrays[arrayIndex].array.elements.append( ++ .table(lineNumber: token.lineNumber, newTableIndex)) ++ ++ try parseInlineTable(bytes: bytes, tableIndex: newTableIndex) ++ ++ default: ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) ++ } ++ ++ try skipNewlines(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .comma { ++ try eatToken(bytes: bytes, kind: .comma, isDotSpecial: false) ++ continue ++ } ++ break ++ } ++ ++ try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) ++ } ++ ++ mutating func parseArray(bytes: UnsafeBufferPointer, arrayIndex: Int) throws { ++ try budget.enter(depth + 1) ++ depth += 1 ++ defer { depth -= 1 } ++ try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: false) ++ ++ while true { ++ try budget.step() ++ try skipNewlines(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .rbracket { ++ break ++ } ++ if arrays[arrayIndex].elements.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ arrays[arrayIndex].elements.reserveCapacity(8) ++ } ++ ++ switch token.kind { ++ case .string, .bareKey: ++ if arrays[arrayIndex].kind == nil { ++ arrays[arrayIndex].kind = .value ++ } else if arrays[arrayIndex].kind != .value { ++ arrays[arrayIndex].kind = .mixed ++ } ++ ++ try budget.node(depth: depth) ++ arrays[arrayIndex].elements.append(.leaf(token)) ++ ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ ++ case .lbracket: // Nested array ++ if arrays[arrayIndex].kind == nil { ++ arrays[arrayIndex].kind = .array ++ } else if arrays[arrayIndex].kind != .array { ++ arrays[arrayIndex].kind = .mixed ++ } ++ ++ let newArrayIndex = arrays.count ++ try budget.node(depth: depth) ++ arrays.append(InternalTOMLArray()) ++ try budget.node(depth: depth) ++ arrays[arrayIndex].elements.append(.array(lineNumber: token.lineNumber, newArrayIndex)) ++ ++ try parseArray(bytes: bytes, arrayIndex: newArrayIndex) ++ ++ case .lbrace: // Nested table ++ if arrays[arrayIndex].kind == nil { ++ arrays[arrayIndex].kind = .table ++ } else if arrays[arrayIndex].kind != .table { ++ arrays[arrayIndex].kind = .mixed ++ } ++ ++ let newTableIndex = tables.count ++ try budget.node(depth: depth) ++ tables.append(InternalTOMLTable()) ++ try budget.node(depth: depth) ++ arrays[arrayIndex].elements.append(.table(lineNumber: token.lineNumber, newTableIndex)) ++ ++ try parseInlineTable(bytes: bytes, tableIndex: newTableIndex) ++ ++ default: ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) ++ } ++ ++ try skipNewlines(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .comma { ++ try eatToken(bytes: bytes, kind: .comma, isDotSpecial: false) ++ continue ++ } ++ break ++ } ++ ++ try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) ++ } ++ ++ mutating func parseKeyValue(bytes: UnsafeBufferPointer, tableIndex: Int, isKeyed: Bool) ++ throws ++ { ++ if isKeyed ? keyTables[tableIndex].table.readOnly : tables[tableIndex].readOnly { ++ throw TOMLError( ++ .syntax( ++ lineNumber: token.lineNumber, message: "cannot insert new entry into existing table")) ++ } ++ ++ let key = token ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ ++ if token.kind == .dot { ++ let (subTableKey, subTableHash) = try normalizeKeyAndHash( ++ bytes: bytes, ++ token: key ++ ) ++ let subTableIndex: Int ++ ++ if let existingTableIndex = try lookupTable( ++ in: tableIndex, keyed: isKeyed, key: subTableKey, keyHash: subTableHash) ++ { ++ // Check if the existing table is explicitly defined (not implicit) ++ if !keyTables[existingTableIndex].table.implicit { ++ throw TOMLError( ++ .syntax( ++ lineNumber: token.lineNumber, ++ message: "cannot add to explicitly defined table using dotted keys")) ++ } ++ subTableIndex = existingTableIndex ++ } else { ++ subTableIndex = try createKeyTable( ++ normalizedKey: subTableKey, ++ keyHash: subTableHash, ++ lineNumber: key.lineNumber, ++ inTable: tableIndex, ++ isKeyed: isKeyed, ++ implicit: true ++ ) ++ } ++ ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ try parseKeyValue(bytes: bytes, tableIndex: subTableIndex, isKeyed: true) ++ return ++ } ++ ++ if token.kind != .equal { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "missing =")) ++ } ++ ++ try nextToken(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .string || token.kind == .bareKey { ++ try createKeyValue( ++ bytes: bytes, token: key, value: token, inTable: tableIndex, isKeyed: isKeyed) ++ try nextToken(bytes: bytes, isDotSpecial: false) ++ return ++ } ++ ++ if token.kind == .lbracket { ++ let index = try createKeyArray( ++ bytes: bytes, token: key, inTable: tableIndex, isKeyed: isKeyed) ++ try parseKeyedArray(bytes: bytes, arrayIndex: index) ++ return ++ } ++ ++ if token.kind == .lbrace { ++ let index = try createKeyTable( ++ bytes: bytes, token: key, inTable: tableIndex, isKeyed: isKeyed) ++ try parseKeyedInlineTable(bytes: bytes, tableIndex: index) ++ return ++ } ++ ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) ++ } ++ ++ mutating func fillTablePath(bytes: UnsafeBufferPointer, clearPath: Bool = true) throws -> ( ++ key: String, ++ keyHash: Int, ++ token: Token ++ ) { ++ let lineNumber = token.lineNumber ++ if clearPath { ++ tablePath.removeAll(keepingCapacity: true) ++ } ++ ++ while true { ++ try budget.step() ++ if token.kind != .string, token.kind != .bareKey { ++ throw TOMLError(.syntax(lineNumber: lineNumber, message: "invalid or missing key")) ++ } ++ ++ let currentToken = token ++ let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token) ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ ++ if token.kind == .rbracket { ++ return (key: key, keyHash: keyHash, token: currentToken) ++ } ++ ++ try budget.node(depth: depth) ++ tablePath.append((key: key, keyHash: keyHash)) ++ ++ if token.kind != .dot { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) ++ } ++ ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ } ++ } ++ ++ mutating func parseSelect(bytes: UnsafeBufferPointer) throws { ++ assert(token.kind == .lbracket) ++ let nextIndex = token.text.lowerBound + 1 ++ let llb = nextIndex < bytes.count && bytes[nextIndex] == CodeUnits.lbracket ++ if llb { ++ cursor = nextIndex + 1 ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ } else { ++ try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: true) ++ } ++ ++ if token.kind != .string, token.kind != .bareKey { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid or missing key")) ++ } ++ ++ let firstToken = token ++ let firstIsBare = firstToken.kind == .bareKey ++ let firstKey: String? ++ let firstKeyHash: Int ++ if firstIsBare { ++ firstKey = nil ++ firstKeyHash = fastKeyHash(bytes: bytes, range: firstToken.text) ++ } else { ++ let normalized = try normalizeKeyAndHash( ++ bytes: bytes, ++ token: firstToken ++ ) ++ firstKey = normalized.key ++ firstKeyHash = normalized.keyHash ++ } ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ ++ if token.kind == .rbracket { ++ currentTable = 0 ++ currentTableIsKeyed = false ++ if !llb { ++ let key = try firstKey ?? makeString(budget: budget, bytes: bytes, range: firstToken.text) ++ currentTable = try createKeyTable( ++ normalizedKey: key, ++ keyHash: firstKeyHash, ++ lineNumber: firstToken.lineNumber, ++ inTable: currentTable, ++ isKeyed: currentTableIsKeyed ++ ) ++ currentTableIsKeyed = true ++ } else { ++ let arrayIndex: Int ++ if firstIsBare { ++ if let existingArrayIndex = try lookupArray( ++ in: currentTable, ++ keyed: currentTableIsKeyed, ++ bytes: bytes, ++ token: firstToken, ++ keyHash: firstKeyHash ++ ) { ++ arrayIndex = existingArrayIndex ++ } else { ++ let key = try makeString(budget: budget, bytes: bytes, range: firstToken.text) ++ arrayIndex = try createKeyArray( ++ normalizedKey: key, ++ keyHash: firstKeyHash, ++ lineNumber: firstToken.lineNumber, ++ inTable: currentTable, ++ isKeyed: currentTableIsKeyed, ++ kind: .table ++ ) ++ } ++ } else { ++ let key = firstKey! ++ if let existingArrayIndex = try lookupArray( ++ in: currentTable, ++ keyed: currentTableIsKeyed, ++ key: key, ++ keyHash: firstKeyHash ++ ) { ++ arrayIndex = existingArrayIndex ++ } else { ++ arrayIndex = try createKeyArray( ++ normalizedKey: key, ++ keyHash: firstKeyHash, ++ lineNumber: firstToken.lineNumber, ++ inTable: currentTable, ++ isKeyed: currentTableIsKeyed, ++ kind: .table ++ ) ++ } ++ } ++ if keyArrays[arrayIndex].array.kind != .table { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "array mismatch")) ++ } ++ ++ let newTableIndex = tables.count ++ try budget.node(depth: depth) ++ tables.append(InternalTOMLTable()) ++ try budget.node(depth: depth) ++ keyArrays[arrayIndex].array.elements.append( ++ .table(lineNumber: token.lineNumber, newTableIndex)) ++ currentTable = newTableIndex ++ currentTableIsKeyed = false ++ } ++ } else { ++ if token.kind != .dot { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) ++ } ++ ++ let firstPathKey = ++ try firstKey ?? makeString(budget: budget, bytes: bytes, range: firstToken.text) ++ var pathTableIndex = 0 ++ var pathTableIsKeyed = false ++ try advanceTablePathSegment( ++ tableIndex: &pathTableIndex, ++ isKeyed: &pathTableIsKeyed, ++ key: firstPathKey, ++ keyHash: firstKeyHash ++ ) ++ ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ if token.kind != .string, token.kind != .bareKey { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid or missing key")) ++ } ++ ++ let secondToken = token ++ let (secondKey, secondKeyHash) = try normalizeKeyAndHash( ++ bytes: bytes, ++ token: secondToken ++ ) ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ ++ let key: String ++ let keyHash: Int ++ let keyToken: Token ++ ++ if token.kind == .rbracket { ++ currentTable = pathTableIndex ++ currentTableIsKeyed = pathTableIsKeyed ++ key = secondKey ++ keyHash = secondKeyHash ++ keyToken = secondToken ++ } else { ++ tablePath.removeAll(keepingCapacity: true) ++ try budget.node(depth: depth) ++ tablePath.append((key: secondKey, keyHash: secondKeyHash)) ++ if token.kind != .dot { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) ++ } ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ ++ let terminal = try fillTablePath(bytes: bytes, clearPath: false) ++ key = terminal.key ++ keyHash = terminal.keyHash ++ keyToken = terminal.token ++ try walkTablePath(startTable: pathTableIndex, startKeyed: pathTableIsKeyed) ++ } ++ ++ if !llb { ++ currentTable = try createKeyTable( ++ normalizedKey: key, ++ keyHash: keyHash, ++ lineNumber: keyToken.lineNumber, ++ inTable: currentTable, ++ isKeyed: currentTableIsKeyed ++ ) ++ currentTableIsKeyed = true ++ } else { ++ let arrayIndex: Int = ++ if let existingArrayIndex = try lookupArray( ++ in: currentTable, ++ keyed: currentTableIsKeyed, ++ key: key, ++ keyHash: keyHash ++ ) { ++ existingArrayIndex ++ } else { ++ try createKeyArray( ++ normalizedKey: key, ++ keyHash: keyHash, ++ lineNumber: keyToken.lineNumber, ++ inTable: currentTable, ++ isKeyed: currentTableIsKeyed, ++ kind: .table ++ ) ++ } ++ if keyArrays[arrayIndex].array.kind != .table { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "array mismatch")) ++ } ++ ++ let newTableIndex = tables.count ++ try budget.node(depth: depth) ++ tables.append(InternalTOMLTable()) ++ try budget.node(depth: depth) ++ keyArrays[arrayIndex].array.elements.append( ++ .table(lineNumber: token.lineNumber, newTableIndex)) ++ currentTable = newTableIndex ++ currentTableIsKeyed = false ++ } ++ } ++ ++ if token.kind != .rbracket { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expects ]")) ++ } ++ ++ if llb { ++ guard cursor < bytes.count, bytes[cursor] == CodeUnits.rbracket else { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expects ]]")) ++ } ++ cursor += 1 ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ } else { ++ try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) ++ } ++ ++ if token.kind != .newline, token.kind != .eof { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "extra chars after ] or ]]")) ++ } ++ } ++} ++ ++extension Token { ++ func unpackBool(bytes: UnsafeBufferPointer, context: TOMLKey) throws -> Bool { ++ try budget.allocate(text.count, stage: "scalar decode") ++ try budget.step(text.count) ++ if text.count == 4, ++ bytes[text.lowerBound] == CodeUnits.lowerT, ++ bytes[text.lowerBound + 1] == CodeUnits.lowerR, ++ bytes[text.lowerBound + 2] == CodeUnits.lowerU, ++ bytes[text.lowerBound + 3] == CodeUnits.lowerE ++ { ++ return true ++ } else if text.count == 5, ++ bytes[text.lowerBound] == CodeUnits.lowerF, ++ bytes[text.lowerBound + 1] == CodeUnits.lowerA, ++ bytes[text.lowerBound + 2] == CodeUnits.lowerL, ++ bytes[text.lowerBound + 3] == CodeUnits.lowerS, ++ bytes[text.lowerBound + 4] == CodeUnits.lowerE ++ { ++ return false ++ } ++ ++ throw TOMLError(.invalidBool(context: context, lineNumber: lineNumber)) ++ } ++ ++ func unpackFloat(bytes: UnsafeBufferPointer, context: TOMLKey) throws -> Double { ++ try budget.allocate(text.count, stage: "scalar decode") ++ try budget.step(text.count) ++ var resultCodeUnits: [UTF8.CodeUnit] = [] ++ var index = text.lowerBound ++ if bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus { ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(bytes[index]) ++ index += 1 ++ } ++ guard index < text.upperBound else { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, reason: "expected digit, nan or inf after sign") ++ ) ++ } ++ ++ if !bytes[index].isDecimalDigit { ++ let nameEnd = index + 3 ++ guard nameEnd == text.upperBound, ++ (bytes[index] == CodeUnits.lowerN && bytes[index + 1] == CodeUnits.lowerA ++ && bytes[index + 2] == CodeUnits.lowerN) ++ || (bytes[index] == CodeUnits.lowerI && bytes[index + 1] == CodeUnits.lowerN ++ && bytes[index + 2] == CodeUnits.lowerF) ++ else { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, ++ reason: "Expected nan or inf, found \(bytes[index])")) ++ } ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(bytes[index]) ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(bytes[index + 1]) ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(bytes[index + 2]) ++ } else { ++ let nextIndex = index + 1 ++ if bytes[index] == CodeUnits.number0, ++ nextIndex < text.upperBound, ++ case let next = bytes[nextIndex], ++ next != CodeUnits.dot, next != CodeUnits.lowerE, next != CodeUnits.upperE ++ { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, ++ reason: "Float begins with 0 must be followed by a '.', 'e' or 'E'")) ++ } ++ ++ while index < text.upperBound { ++ try budget.step() ++ let ch = bytes[index] ++ index += 1 ++ ++ if ch == CodeUnits.underscore { ++ guard ++ let last = resultCodeUnits.last, ++ last.isDecimalDigit ++ else { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, reason: "'_' must be preceded by a digit") ++ ) ++ } ++ ++ guard ++ index < text.upperBound, ++ case let next = bytes[index], ++ next.isDecimalDigit ++ else { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, reason: "'_' must be follewed by a digit") ++ ) ++ } ++ ++ continue ++ } else if ch == CodeUnits.dot { ++ if resultCodeUnits.isEmpty { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, ++ reason: "First digit of floats cannot be '.'")) ++ } ++ ++ if !resultCodeUnits.last!.isDecimalDigit { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, ++ reason: "'.' must be preceded by a decimal digit")) ++ } ++ ++ guard index < text.upperBound, bytes[index].isDecimalDigit else { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, reason: "A digit must follow '.'")) ++ } ++ ++ } else if ch == CodeUnits.upperE || ch == CodeUnits.lowerE { ++ } else if !ch.isDecimalDigit, ch != CodeUnits.plus, ch != CodeUnits.minus { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, reason: "invalid character for float")) ++ } ++ ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(ch) ++ } ++ } ++ ++ guard let double = Double(String(decoding: resultCodeUnits, as: UTF8.self)) else { ++ throw TOMLError( ++ .invalidFloat(context: context, lineNumber: lineNumber, reason: "not a float")) ++ } ++ ++ return double ++ } ++ ++ func unpackString(bytes: UnsafeBufferPointer, context: TOMLKey) throws -> String { ++ try budget.allocate(text.count, stage: "scalar decode") ++ try budget.step(text.count) ++ var multiline = false ++ ++ if bytes.count == 0 { ++ throw TOMLError( ++ .invalidString(context: context, lineNumber: lineNumber, reason: "missing closing quote")) ++ } ++ ++ let quoteChar = bytes[text.lowerBound] ++ if quoteChar != CodeUnits.doubleQuote, quoteChar != CodeUnits.singleQuote { ++ throw TOMLError(.typeMismatch(context: context, lineNumber: lineNumber, expected: "string")) ++ } ++ var index = text.lowerBound ++ var endIndex = text.upperBound ++ ++ if endIndex - index >= 3 && bytes[index] == CodeUnits.doubleQuote ++ && bytes[index + 1] == CodeUnits.doubleQuote && bytes[index + 2] == CodeUnits.doubleQuote ++ || endIndex - index >= 3 && bytes[index] == CodeUnits.singleQuote ++ && bytes[index + 1] == CodeUnits.singleQuote && bytes[index + 2] == CodeUnits.singleQuote ++ { ++ multiline = true ++ index += 3 ++ endIndex -= 3 ++ ++ if index < endIndex, bytes[index] == CodeUnits.lf { ++ index += 1 ++ } else if endIndex - index >= 2, bytes[index] == CodeUnits.cr, ++ bytes[index + 1] == CodeUnits.lf ++ { ++ index += 2 ++ } ++ } else { ++ index = index + 1 ++ endIndex = endIndex - 1 ++ guard endIndex >= 0, bytes[endIndex] == quoteChar else { ++ throw TOMLError( ++ .invalidString(context: context, lineNumber: lineNumber, reason: "missing closing quote")) ++ } ++ } ++ ++ if quoteChar == CodeUnits.singleQuote { ++ return try literalString( ++ budget: budget, bytes: bytes, range: index.., context: TOMLKey) throws -> Int64 { ++ try budget.allocate(text.count, stage: "scalar decode") ++ try budget.step(text.count) ++ @_transparent ++ func isValidDigit(_ codeUnit: UTF8.CodeUnit, base: Int) -> Bool { ++ switch base { ++ case 10: ++ codeUnit.isDecimalDigit ++ case 16: ++ codeUnit.isHexDigit ++ case 2: ++ codeUnit == CodeUnits.number0 || codeUnit == CodeUnits.number1 ++ case 8: ++ CodeUnits.number0 <= codeUnit && codeUnit <= CodeUnits.number7 ++ default: ++ false ++ } ++ } ++ ++ var resultCodeUnits: [UTF8.CodeUnit] = [] ++ var index = text.lowerBound ++ var base = 10 ++ var hasSign = false ++ if bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus { ++ hasSign = true ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(bytes[index]) ++ index = text.index(after: index) ++ } ++ guard index < text.upperBound else { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, reason: "expected digit after sign")) ++ } ++ ++ if bytes[index] == CodeUnits.underscore { ++ throw TOMLError( ++ .invalidInteger(context: context, lineNumber: lineNumber, reason: "cannot start with a '_'") ++ ) ++ } ++ ++ if bytes[index] == CodeUnits.number0 { ++ let nextIndex = index + 1 ++ if nextIndex < text.upperBound { ++ if bytes[nextIndex] == CodeUnits.lowerX { ++ if hasSign { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, ++ reason: "hexadecimal integers cannot have explicit signs")) ++ } ++ base = 16 ++ index += 2 ++ } else if bytes[nextIndex] == CodeUnits.lowerO { ++ if hasSign { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, ++ reason: "octal integers cannot have explicit signs")) ++ } ++ base = 8 ++ index += 2 ++ } else if bytes[nextIndex] == CodeUnits.lowerB { ++ if hasSign { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, ++ reason: "binary integers cannot have explicit signs")) ++ } ++ base = 2 ++ index += 2 ++ } else if bytes[nextIndex].isDecimalDigit || bytes[nextIndex] == CodeUnits.underscore { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, ++ reason: "decimal integers cannot have leading zeros")) ++ } ++ } ++ // Single zero is allowed to continue to the main loop ++ } ++ guard index < text.upperBound else { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, reason: "expected digit after base prefix")) ++ } ++ ++ while index < text.upperBound { ++ try budget.step() ++ let ch = bytes[index] ++ index += 1 ++ ++ if ch == CodeUnits.underscore { ++ guard ++ let last = resultCodeUnits.last, ++ isValidDigit(last, base: base) ++ else { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, ++ reason: "cannot use '_' adjacent to a non-digit")) ++ } ++ ++ if index >= text.endIndex { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, reason: "cannot end with a '_'")) ++ } ++ ++ let next = bytes[index] ++ if next == CodeUnits.underscore { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, reason: "cannot contain consecutive '_'")) ++ } ++ guard isValidDigit(next, base: base) else { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, ++ reason: "cannot use '_' adjacent to a non-digit")) ++ } ++ continue ++ } ++ ++ guard isValidDigit(ch, base: base) else { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, reason: "invalid digit for base \(base)")) ++ } ++ ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(ch) ++ } ++ ++ let s = String(decoding: resultCodeUnits, as: UTF8.self) ++ guard let i = Int64(s, radix: base) else { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, ++ reason: "\(s) is a invalid integer of base \(base)")) ++ } ++ return i ++ } ++ ++ func unpackDateTime(bytes: UnsafeBufferPointer, context: TOMLKey) throws ++ -> DateTimeComponents ++ { ++ try budget.allocate(text.count, stage: "scalar decode") ++ try budget.step(text.count) ++ var mustParseTime = false ++ var date: (year: Int, month: Int, day: Int)? ++ var time: (hour: Int, minute: Int, second: Int)? ++ ++ var index = text.lowerBound ++ if let (year, month, day, _) = scanDate(bytes: bytes, range: text) { ++ // Validate date components ++ if month < 1 || month > 12 { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, reason: "month must be between 01 and 12")) ++ } ++ if day < 1 { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, reason: "day must be between 01 and 31")) ++ } ++ ++ // Validate days per month and leap years ++ let isLeapYear = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) ++ let maxDaysInMonth: Int = ++ switch month { ++ case 2: ++ isLeapYear ? 29 : 28 ++ case 4, 6, 9, 11: ++ 30 ++ default: ++ 31 ++ } ++ ++ if day > maxDaysInMonth { ++ if month == 2, !isLeapYear { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, ++ reason: "February only has 28 days in non-leap years")) ++ } else if month == 2, isLeapYear { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, ++ reason: "February only has 29 days in leap years")) ++ } else { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, ++ reason: "day \(day) is invalid for month \(month)")) ++ } ++ } ++ ++ date = (year, month, day) ++ index += 10 ++ } ++ ++ var features: OffsetDateTime.Features = [] ++ var nanoseconds: UInt32? ++ if index < text.upperBound { ++ if date != nil { ++ let isSeparatorLowerT = bytes[index] == CodeUnits.lowerT ++ let isSeparatorUpperT = bytes[index] == CodeUnits.upperT ++ guard isSeparatorLowerT || isSeparatorUpperT || bytes[index] == CodeUnits.space else { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, ++ reason: "expected 'T' or 't' or space to separate date and time")) ++ } ++ if isSeparatorLowerT { ++ features.insert(.lowercaseT) ++ } else if isSeparatorUpperT { ++ features.insert(.uppercaseT) ++ } ++ mustParseTime = true ++ index += 1 ++ } else { ++ // For standalone time values, don't advance index ++ mustParseTime = true ++ } ++ if let (hour, minute, second, newIndex) = scanTime( ++ bytes: bytes, range: index.. 23 { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, reason: "hour must be between 00 and 23")) ++ } ++ if minute > 59 { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, reason: "minute must be between 00 and 59")) ++ } ++ if second > 59 { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, reason: "second must be between 00 and 59")) ++ } ++ ++ time = (hour, minute, second) ++ ++ index = newIndex ++ if index < text.upperBound, bytes[index] == CodeUnits.dot { ++ index += 1 ++ let beforeNanoIndex = index ++ nanoseconds = try parseNanoSeconds( ++ budget: budget, bytes: bytes, range: index.. 24 { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, ++ reason: "timezone offset hour must be between 00 and 24")) ++ } ++ if offsetMinute > 59 { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, ++ reason: "timezone offset minute must be between 00 and 59")) ++ } ++ ++ let offsetInMinutes = offsetHour * 60 + offsetMinute ++ timeOffset = Int16(offsetIsNegative ? -offsetInMinutes : offsetInMinutes) ++ index += consumedLength ++ } catch let parseError { ++ if let tomlError = parseError as? TOMLError { ++ switch tomlError.reason { ++ case .invalidDateTime(_, let reason): ++ throw TOMLError( ++ .invalidDateTime3(context: context, lineNumber: lineNumber, reason: reason)) ++ default: ++ throw tomlError +@@ -645,198 +1764,184 @@ +- +- if token.kind != .string, token.kind != .bareKey { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expect a string")) +- } +- +- try parseKeyValue(bytes: bytes, tableIndex: tableIndex, isKeyed: true) +- +- try skipNewlines(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .comma { +- try eatToken(bytes: bytes, kind: .comma, isDotSpecial: true) +- continue +- } +- break +- } +- +- try eatToken(bytes: bytes, kind: .rbrace, isDotSpecial: true) +- +- keyTables[tableIndex].table.readOnly = true +- } +- +- mutating func parseInlineTable(bytes: UnsafeBufferPointer, tableIndex: Int) throws(TOMLError) { +- try eatToken(bytes: bytes, kind: .lbrace, isDotSpecial: true) +- +- while true { +- try skipNewlines(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .rbrace { +- break +- } +- +- if token.kind != .string, token.kind != .bareKey { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expect a string")) +- } +- +- try parseKeyValue(bytes: bytes, tableIndex: tableIndex, isKeyed: false) +- +- try skipNewlines(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .comma { +- try eatToken(bytes: bytes, kind: .comma, isDotSpecial: true) +- continue +- } +- break +- } +- +- try eatToken(bytes: bytes, kind: .rbrace, isDotSpecial: true) +- +- tables[tableIndex].readOnly = true +- } +- +- mutating func parseKeyedArray(bytes: UnsafeBufferPointer, arrayIndex: Int) throws(TOMLError) { +- try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: false) +- +- while true { +- try skipNewlines(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .rbracket { +- break +- } +- if keyArrays[arrayIndex].array.elements.isEmpty { +- keyArrays[arrayIndex].array.elements.reserveCapacity(8) +- } +- +- switch token.kind { +- case .string, .bareKey: +- if keyArrays[arrayIndex].array.kind == nil { +- keyArrays[arrayIndex].array.kind = .value +- } else if keyArrays[arrayIndex].array.kind != .value { +- keyArrays[arrayIndex].array.kind = .mixed +- } +- +- keyArrays[arrayIndex].array.elements.append(.leaf(token)) +- +- try nextToken(bytes: bytes, isDotSpecial: true) +- +- case .lbracket: // Nested array +- if keyArrays[arrayIndex].array.kind == nil { +- keyArrays[arrayIndex].array.kind = .array +- } else if keyArrays[arrayIndex].array.kind != .array { +- keyArrays[arrayIndex].array.kind = .mixed +- } +- +- let newArrayIndex = arrays.count +- arrays.append(InternalTOMLArray()) +- keyArrays[arrayIndex].array.elements.append(.array(lineNumber: token.lineNumber, newArrayIndex)) +- +- try parseArray(bytes: bytes, arrayIndex: newArrayIndex) +- +- case .lbrace: // Nested table +- if keyArrays[arrayIndex].array.kind == nil { +- keyArrays[arrayIndex].array.kind = .table +- } else if keyArrays[arrayIndex].array.kind != .table { +- keyArrays[arrayIndex].array.kind = .mixed +- } +- +- let newTableIndex = tables.count +- tables.append(InternalTOMLTable()) +- keyArrays[arrayIndex].array.elements.append(.table(lineNumber: token.lineNumber, newTableIndex)) +- +- try parseInlineTable(bytes: bytes, tableIndex: newTableIndex) +- +- default: +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) +- } +- +- try skipNewlines(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .comma { +- try eatToken(bytes: bytes, kind: .comma, isDotSpecial: false) +- continue +- } +- break +- } +- +- try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) +- } +- +- mutating func parseArray(bytes: UnsafeBufferPointer, arrayIndex: Int) throws(TOMLError) { +- try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: false) +- +- while true { +- try skipNewlines(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .rbracket { +- break +- } +- if arrays[arrayIndex].elements.isEmpty { +- arrays[arrayIndex].elements.reserveCapacity(8) +- } +- +- switch token.kind { +- case .string, .bareKey: +- if arrays[arrayIndex].kind == nil { +- arrays[arrayIndex].kind = .value +- } else if arrays[arrayIndex].kind != .value { +- arrays[arrayIndex].kind = .mixed +- } +- +- arrays[arrayIndex].elements.append(.leaf(token)) +- +- try nextToken(bytes: bytes, isDotSpecial: true) +- +- case .lbracket: // Nested array +- if arrays[arrayIndex].kind == nil { +- arrays[arrayIndex].kind = .array +- } else if arrays[arrayIndex].kind != .array { +- arrays[arrayIndex].kind = .mixed +- } +- +- let newArrayIndex = arrays.count +- arrays.append(InternalTOMLArray()) +- arrays[arrayIndex].elements.append(.array(lineNumber: token.lineNumber, newArrayIndex)) +- +- try parseArray(bytes: bytes, arrayIndex: newArrayIndex) +- +- case .lbrace: // Nested table +- if arrays[arrayIndex].kind == nil { +- arrays[arrayIndex].kind = .table +- } else if arrays[arrayIndex].kind != .table { +- arrays[arrayIndex].kind = .mixed +- } +- +- let newTableIndex = tables.count +- tables.append(InternalTOMLTable()) +- arrays[arrayIndex].elements.append(.table(lineNumber: token.lineNumber, newTableIndex)) +- +- try parseInlineTable(bytes: bytes, tableIndex: newTableIndex) +- +- default: +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) +- } +- +- try skipNewlines(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .comma { +- try eatToken(bytes: bytes, kind: .comma, isDotSpecial: false) +- continue +- } +- break +- } +- +- try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) +- } +- +- mutating func parseKeyValue(bytes: UnsafeBufferPointer, tableIndex: Int, isKeyed: Bool) throws(TOMLError) { +- if isKeyed ? keyTables[tableIndex].table.readOnly : tables[tableIndex].readOnly { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "cannot insert new entry into existing table")) +- } +- +- let key = token +- try nextToken(bytes: bytes, isDotSpecial: true) +- +- if token.kind == .dot { +- let (subTableKey, subTableHash) = try normalizeKeyAndHash( +- bytes: bytes, +- token: key, +- keyTransform: keyTransform ++ } else { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, reason: "timezone parsing error")) ++ } ++ } ++ } ++ } ++ ++ if index < text.upperBound { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, reason: "extra character after date time")) ++ } ++ ++ return DateTimeComponents( ++ date: date.map { ++ LocalDate(year: .init($0.year), month: .init($0.month), day: .init($0.day)) ++ }, ++ time: time.map { ++ LocalTime( ++ hour: .init($0.hour), minute: .init($0.minute), second: .init($0.second), ++ nanosecond: nanoseconds ?? 0) ++ }, ++ offset: timeOffset, ++ features: features ++ ) ++ } ++ ++} ++ ++func parseTimezoneOffset(bytes: UnsafeBufferPointer, range: Range, lineNumber: Int) ++ throws -> (hour: Int, minute: Int, consumedLength: Int) ++{ ++ guard range.count >= 2 else { ++ throw TOMLError( ++ .invalidDateTime( ++ lineNumber: lineNumber, reason: "timezone offset must have at least 2 digits for hour")) ++ } ++ ++ var index = range.lowerBound ++ ++ // Parse hour digits (exactly 2 required) ++ guard ++ index < range.upperBound, ++ bytes[index].isDecimalDigit, ++ case let firstHourDigit = bytes[index], ++ case let nextIndex = index + 1, ++ nextIndex < range.upperBound, ++ bytes[nextIndex].isDecimalDigit, ++ case let secondHourDigit = bytes[nextIndex] ++ else { ++ throw TOMLError( ++ .invalidDateTime( ++ lineNumber: lineNumber, reason: "timezone offset hour must be exactly 2 digits")) ++ } ++ ++ let offsetHour = ++ Int(firstHourDigit - CodeUnits.number0) * 10 + Int(secondHourDigit - CodeUnits.number0) ++ index += 2 ++ var consumedLength = 2 ++ ++ // Parse required minute digits (timezone offset must include minutes) ++ guard index < range.upperBound, bytes[index] == CodeUnits.colon else { ++ throw TOMLError( ++ .invalidDateTime( ++ lineNumber: lineNumber, reason: "timezone offset must include minutes (format: ±HH:MM)")) ++ } ++ ++ index += 1 ++ consumedLength += 1 ++ ++ guard ++ index < range.upperBound, ++ bytes[index].isDecimalDigit, ++ case let firstMinuteDigit = bytes[index], ++ case let nextMinuteIndex = index + 1, ++ nextMinuteIndex < range.upperBound, ++ bytes[nextMinuteIndex].isDecimalDigit, ++ case let secondMinuteDigit = bytes[nextMinuteIndex] ++ else { ++ throw TOMLError( ++ .invalidDateTime( ++ lineNumber: lineNumber, reason: "timezone offset minute must be exactly 2 digits")) ++ } ++ ++ let offsetMinute = ++ Int(firstMinuteDigit - CodeUnits.number0) * 10 + Int(secondMinuteDigit - CodeUnits.number0) ++ consumedLength += 2 ++ ++ return (offsetHour, offsetMinute, consumedLength) ++} ++ ++func literalString( ++ budget: SemanticBudget, bytes: UnsafeBufferPointer, range: Range, multiline: Bool ++) throws -> String { ++ var resultCodeUnits: [UTF8.CodeUnit] = [] ++ var consecutiveQuotes = 0 ++ ++ for index in range { ++ try budget.step() ++ let codeUnit = bytes[index] ++ if codeUnit >= CodeUnits.null && codeUnit <= CodeUnits.backspace ++ || codeUnit >= CodeUnits.lf && codeUnit <= CodeUnits.unitSeparator ++ || codeUnit == CodeUnits.delete ++ { ++ if multiline, codeUnit == CodeUnits.lf { ++ // Allow LF in multiline literal strings ++ } else if multiline, codeUnit == CodeUnits.cr { ++ // Only allow CR if followed by LF (CRLF sequence) ++ let nextIndex = index + 1 ++ if nextIndex < range.upperBound, bytes[nextIndex] == CodeUnits.lf { ++ // Allow CRLF sequence - will be processed as separate characters ++ } else { ++ throw TOMLError(.invalidCharacter(codeUnit)) ++ } ++ } else { ++ throw TOMLError(.invalidCharacter(codeUnit)) ++ } ++ } ++ ++ if multiline, codeUnit == CodeUnits.singleQuote { ++ consecutiveQuotes += 1 ++ if consecutiveQuotes > 2 { ++ throw TOMLError( ++ .syntax( ++ lineNumber: 0, ++ message: ++ "literal multiline strings cannot contain more than 2 consecutive single quotes")) ++ } ++ } else { ++ consecutiveQuotes = 0 ++ } ++ ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(codeUnit) ++ } ++ return String(decoding: resultCodeUnits, as: UTF8.self) ++} ++ ++func basicString( ++ budget: SemanticBudget, bytes: UnsafeBufferPointer, range: Range, multiline: Bool ++) throws -> String { ++ let startIndex = range.lowerBound ++ let endIndex = range.upperBound ++ var resultCodeUnits: [UTF8.CodeUnit] = [] ++ try budget.allocate(range.count, stage: "decoded string capacity") ++ resultCodeUnits.reserveCapacity(range.count) ++ var consecutiveQuotes = 0 ++ var index = startIndex ++ while true { ++ try budget.step() ++ if index >= endIndex { ++ break ++ } ++ ++ var ch = bytes[index] ++ index += 1 ++ if ch != CodeUnits.backslash { ++ if ch >= CodeUnits.null && ch <= CodeUnits.backspace ++ || ch >= CodeUnits.lf && ch <= CodeUnits.unitSeparator || ch == CodeUnits.delete ++ { ++ if multiline, ch == CodeUnits.lf { ++ // Allow LF in multiline basic strings ++ } else if multiline, ch == CodeUnits.cr { ++ // Only allow CR if followed by LF (CRLF sequence) ++ if index < endIndex, bytes[index] == CodeUnits.lf { ++ // Allow CRLF sequence - will be processed as separate characters ++ } else { ++ throw TOMLError(.invalidCharacter(ch)) ++ } ++ } else { ++ throw TOMLError(.invalidCharacter(ch)) ++ } ++ } ++ ++ if multiline, ch == CodeUnits.doubleQuote { ++ consecutiveQuotes += 1 ++ if consecutiveQuotes > 2 { ++ throw TOMLError( ++ .syntax( ++ lineNumber: 0, ++ message: ++ "basic multiline strings cannot contain more than 2 consecutive double quotes" +@@ -844,91 +1949,23 @@ +- let subTableIndex: Int +- +- if let existingTableIndex = lookupTable(in: tableIndex, keyed: isKeyed, key: subTableKey, keyHash: subTableHash) { +- // Check if the existing table is explicitly defined (not implicit) +- if !keyTables[existingTableIndex].table.implicit { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "cannot add to explicitly defined table using dotted keys")) +- } +- subTableIndex = existingTableIndex +- } else { +- subTableIndex = try createKeyTable( +- normalizedKey: subTableKey, +- keyHash: subTableHash, +- lineNumber: key.lineNumber, +- inTable: tableIndex, +- isKeyed: isKeyed, +- implicit: true +- ) +- } +- +- try nextToken(bytes: bytes, isDotSpecial: true) +- try parseKeyValue(bytes: bytes, tableIndex: subTableIndex, isKeyed: true) +- return +- } +- +- if token.kind != .equal { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "missing =")) +- } +- +- try nextToken(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .string || token.kind == .bareKey { +- try createKeyValue(bytes: bytes, token: key, value: token, inTable: tableIndex, isKeyed: isKeyed) +- try nextToken(bytes: bytes, isDotSpecial: false) +- return +- } +- +- if token.kind == .lbracket { +- let index = try createKeyArray(bytes: bytes, token: key, inTable: tableIndex, isKeyed: isKeyed) +- try parseKeyedArray(bytes: bytes, arrayIndex: index) +- return +- } +- +- if token.kind == .lbrace { +- let index = try createKeyTable(bytes: bytes, token: key, inTable: tableIndex, isKeyed: isKeyed) +- try parseKeyedInlineTable(bytes: bytes, tableIndex: index) +- return +- } +- +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) +- } +- +- mutating func fillTablePath(bytes: UnsafeBufferPointer, clearPath: Bool = true) throws(TOMLError) -> ( +- key: String, +- keyHash: Int, +- token: Token +- ) { +- let lineNumber = token.lineNumber +- if clearPath { +- tablePath.removeAll(keepingCapacity: true) +- } +- +- while true { +- if token.kind != .string, token.kind != .bareKey { +- throw TOMLError(.syntax(lineNumber: lineNumber, message: "invalid or missing key")) +- } +- +- let currentToken = token +- let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token, keyTransform: keyTransform) +- try nextToken(bytes: bytes, isDotSpecial: true) +- +- if token.kind == .rbracket { +- return (key: key, keyHash: keyHash, token: currentToken) +- } +- +- tablePath.append((key: key, keyHash: keyHash)) +- +- if token.kind != .dot { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) +- } +- +- try nextToken(bytes: bytes, isDotSpecial: true) +- } +- } +- +- mutating func parseSelect(bytes: UnsafeBufferPointer) throws(TOMLError) { +- assert(token.kind == .lbracket) +- let nextIndex = token.text.lowerBound + 1 +- let llb = nextIndex < bytes.count && bytes[nextIndex] == CodeUnits.lbracket +- if llb { +- cursor = nextIndex + 1 +- try nextToken(bytes: bytes, isDotSpecial: true) ++ ) ++ } ++ } else { ++ consecutiveQuotes = 0 ++ } ++ ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(ch) ++ continue ++ } ++ ++ if index >= endIndex { ++ throw TOMLError(.invalidCharacter(CodeUnits.backslash)) ++ } ++ ++ func indexAfterSkippingCharacters(start: Int, endIndex: Int, characters: [UTF8.CodeUnit]) ++ throws -> Int ++ { ++ var index = start ++ while index < endIndex { ++ try budget.step() ++ if characters.contains(bytes[index]) { ++ index += 1 +@@ -936,614 +1973,15 @@ +- try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: true) +- } +- +- if token.kind != .string, token.kind != .bareKey { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid or missing key")) +- } +- +- let firstToken = token +- let firstIsBareNoTransform = keyTransform == nil && firstToken.kind == .bareKey +- let firstKey: String? +- let firstKeyHash: Int +- if firstIsBareNoTransform { +- firstKey = nil +- firstKeyHash = fastKeyHash(bytes: bytes, range: firstToken.text) +- } else { +- let normalized = try normalizeKeyAndHash( +- bytes: bytes, +- token: firstToken, +- keyTransform: keyTransform +- ) +- firstKey = normalized.key +- firstKeyHash = normalized.keyHash +- } +- try nextToken(bytes: bytes, isDotSpecial: true) +- +- if token.kind == .rbracket { +- currentTable = 0 +- currentTableIsKeyed = false +- if !llb { +- let key = firstKey ?? makeString(bytes: bytes, range: firstToken.text) +- currentTable = try createKeyTable( +- normalizedKey: key, +- keyHash: firstKeyHash, +- lineNumber: firstToken.lineNumber, +- inTable: currentTable, +- isKeyed: currentTableIsKeyed +- ) +- currentTableIsKeyed = true +- } else { +- let arrayIndex: Int +- if firstIsBareNoTransform { +- if let existingArrayIndex = lookupArray( +- in: currentTable, +- keyed: currentTableIsKeyed, +- bytes: bytes, +- token: firstToken, +- keyHash: firstKeyHash +- ) { +- arrayIndex = existingArrayIndex +- } else { +- let key = makeString(bytes: bytes, range: firstToken.text) +- arrayIndex = try createKeyArray( +- normalizedKey: key, +- keyHash: firstKeyHash, +- lineNumber: firstToken.lineNumber, +- inTable: currentTable, +- isKeyed: currentTableIsKeyed, +- kind: .table +- ) +- } +- } else { +- let key = firstKey! +- if let existingArrayIndex = lookupArray( +- in: currentTable, +- keyed: currentTableIsKeyed, +- key: key, +- keyHash: firstKeyHash +- ) { +- arrayIndex = existingArrayIndex +- } else { +- arrayIndex = try createKeyArray( +- normalizedKey: key, +- keyHash: firstKeyHash, +- lineNumber: firstToken.lineNumber, +- inTable: currentTable, +- isKeyed: currentTableIsKeyed, +- kind: .table +- ) +- } +- } +- if keyArrays[arrayIndex].array.kind != .table { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "array mismatch")) +- } +- +- let newTableIndex = tables.count +- tables.append(InternalTOMLTable()) +- keyArrays[arrayIndex].array.elements.append(.table(lineNumber: token.lineNumber, newTableIndex)) +- currentTable = newTableIndex +- currentTableIsKeyed = false +- } +- } else { +- if token.kind != .dot { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) +- } +- +- let firstPathKey = firstKey ?? makeString(bytes: bytes, range: firstToken.text) +- var pathTableIndex = 0 +- var pathTableIsKeyed = false +- try advanceTablePathSegment( +- tableIndex: &pathTableIndex, +- isKeyed: &pathTableIsKeyed, +- key: firstPathKey, +- keyHash: firstKeyHash +- ) +- +- try nextToken(bytes: bytes, isDotSpecial: true) +- if token.kind != .string, token.kind != .bareKey { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid or missing key")) +- } +- +- let secondToken = token +- let (secondKey, secondKeyHash) = try normalizeKeyAndHash( +- bytes: bytes, +- token: secondToken, +- keyTransform: keyTransform +- ) +- try nextToken(bytes: bytes, isDotSpecial: true) +- +- let key: String +- let keyHash: Int +- let keyToken: Token +- +- if token.kind == .rbracket { +- currentTable = pathTableIndex +- currentTableIsKeyed = pathTableIsKeyed +- key = secondKey +- keyHash = secondKeyHash +- keyToken = secondToken +- } else { +- tablePath.removeAll(keepingCapacity: true) +- tablePath.append((key: secondKey, keyHash: secondKeyHash)) +- if token.kind != .dot { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) +- } +- try nextToken(bytes: bytes, isDotSpecial: true) +- +- let terminal = try fillTablePath(bytes: bytes, clearPath: false) +- key = terminal.key +- keyHash = terminal.keyHash +- keyToken = terminal.token +- try walkTablePath(startTable: pathTableIndex, startKeyed: pathTableIsKeyed) +- } +- +- if !llb { +- currentTable = try createKeyTable( +- normalizedKey: key, +- keyHash: keyHash, +- lineNumber: keyToken.lineNumber, +- inTable: currentTable, +- isKeyed: currentTableIsKeyed +- ) +- currentTableIsKeyed = true +- } else { +- let arrayIndex: Int = if let existingArrayIndex = lookupArray( +- in: currentTable, +- keyed: currentTableIsKeyed, +- key: key, +- keyHash: keyHash +- ) { +- existingArrayIndex +- } else { +- try createKeyArray( +- normalizedKey: key, +- keyHash: keyHash, +- lineNumber: keyToken.lineNumber, +- inTable: currentTable, +- isKeyed: currentTableIsKeyed, +- kind: .table +- ) +- } +- if keyArrays[arrayIndex].array.kind != .table { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "array mismatch")) +- } +- +- let newTableIndex = tables.count +- tables.append(InternalTOMLTable()) +- keyArrays[arrayIndex].array.elements.append(.table(lineNumber: token.lineNumber, newTableIndex)) +- currentTable = newTableIndex +- currentTableIsKeyed = false +- } +- } +- +- if token.kind != .rbracket { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expects ]")) +- } +- +- if llb { +- guard cursor < bytes.count, bytes[cursor] == CodeUnits.rbracket else { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expects ]]")) +- } +- cursor += 1 +- try nextToken(bytes: bytes, isDotSpecial: true) +- } else { +- try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) +- } +- +- if token.kind != .newline, token.kind != .eof { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "extra chars after ] or ]]")) +- } +- } +-} +- +-extension Token { +- func unpackBool(bytes: UnsafeBufferPointer, context: TOMLKey) throws(TOMLError) -> Bool { +- if text.count == 4, +- bytes[text.lowerBound] == CodeUnits.lowerT, +- bytes[text.lowerBound + 1] == CodeUnits.lowerR, +- bytes[text.lowerBound + 2] == CodeUnits.lowerU, +- bytes[text.lowerBound + 3] == CodeUnits.lowerE +- { +- return true +- } else if text.count == 5, +- bytes[text.lowerBound] == CodeUnits.lowerF, +- bytes[text.lowerBound + 1] == CodeUnits.lowerA, +- bytes[text.lowerBound + 2] == CodeUnits.lowerL, +- bytes[text.lowerBound + 3] == CodeUnits.lowerS, +- bytes[text.lowerBound + 4] == CodeUnits.lowerE +- { +- return false +- } +- +- throw TOMLError(.invalidBool(context: context, lineNumber: lineNumber)) +- } +- +- func unpackFloat(bytes: UnsafeBufferPointer, context: TOMLKey) throws(TOMLError) -> Double { +- var resultCodeUnits: [UTF8.CodeUnit] = [] +- var index = text.lowerBound +- if bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus { +- resultCodeUnits.append(bytes[index]) +- index += 1 +- } +- guard index < text.upperBound else { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "expected digit, nan or inf after sign")) +- } +- +- if !bytes[index].isDecimalDigit { +- let nameEnd = index + 3 +- guard nameEnd == text.upperBound, +- ( +- bytes[index] == CodeUnits.lowerN && +- bytes[index + 1] == CodeUnits.lowerA && +- bytes[index + 2] == CodeUnits.lowerN +- ) || +- ( +- bytes[index] == CodeUnits.lowerI && +- bytes[index + 1] == CodeUnits.lowerN && +- bytes[index + 2] == CodeUnits.lowerF +- ) +- else { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "Expected nan or inf, found \(bytes[index])")) +- } +- resultCodeUnits.append(bytes[index]) +- resultCodeUnits.append(bytes[index + 1]) +- resultCodeUnits.append(bytes[index + 2]) +- } else { +- let nextIndex = index + 1 +- if bytes[index] == CodeUnits.number0, +- nextIndex < text.upperBound, +- case let next = bytes[nextIndex], +- next != CodeUnits.dot, next != CodeUnits.lowerE, next != CodeUnits.upperE +- { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "Float begins with 0 must be followed by a '.', 'e' or 'E'")) +- } +- +- while index < text.upperBound { +- let ch = bytes[index] +- index += 1 +- +- if ch == CodeUnits.underscore { +- guard +- let last = resultCodeUnits.last, +- last.isDecimalDigit +- else { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "'_' must be preceded by a digit")) +- } +- +- guard +- index < text.upperBound, +- case let next = bytes[index], +- next.isDecimalDigit +- else { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "'_' must be follewed by a digit")) +- } +- +- continue +- } else if ch == CodeUnits.dot { +- if resultCodeUnits.isEmpty { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "First digit of floats cannot be '.'")) +- } +- +- if !resultCodeUnits.last!.isDecimalDigit { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "'.' must be preceded by a decimal digit")) +- } +- +- guard index < text.upperBound, bytes[index].isDecimalDigit else { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "A digit must follow '.'")) +- } +- +- } else if ch == CodeUnits.upperE || ch == CodeUnits.lowerE { +- } else if !ch.isDecimalDigit, ch != CodeUnits.plus, ch != CodeUnits.minus { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "invalid character for float")) +- } +- +- resultCodeUnits.append(ch) +- } +- } +- +- guard let double = Double(String(decoding: resultCodeUnits, as: UTF8.self)) else { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "not a float")) +- } +- +- return double +- } +- +- func unpackString(bytes: UnsafeBufferPointer, context: TOMLKey) throws(TOMLError) -> String { +- var multiline = false +- +- if bytes.count == 0 { +- throw TOMLError(.invalidString(context: context, lineNumber: lineNumber, reason: "missing closing quote")) +- } +- +- let quoteChar = bytes[text.lowerBound] +- if quoteChar != CodeUnits.doubleQuote, quoteChar != CodeUnits.singleQuote { +- throw TOMLError(.typeMismatch(context: context, lineNumber: lineNumber, expected: "string")) +- } +- var index = text.lowerBound +- var endIndex = text.upperBound +- +- if endIndex - index >= 3 && bytes[index] == CodeUnits.doubleQuote && bytes[index + 1] == CodeUnits.doubleQuote && bytes[index + 2] == CodeUnits.doubleQuote || +- endIndex - index >= 3 && bytes[index] == CodeUnits.singleQuote && bytes[index + 1] == CodeUnits.singleQuote && bytes[index + 2] == CodeUnits.singleQuote +- { +- multiline = true +- index += 3 +- endIndex -= 3 +- +- if index < endIndex, bytes[index] == CodeUnits.lf { +- index += 1 +- } else if endIndex - index >= 2, bytes[index] == CodeUnits.cr, bytes[index + 1] == CodeUnits.lf { +- index += 2 +- } +- } else { +- index = index + 1 +- endIndex = endIndex - 1 +- guard endIndex >= 0, bytes[endIndex] == quoteChar else { +- throw TOMLError(.invalidString(context: context, lineNumber: lineNumber, reason: "missing closing quote")) +- } +- } +- +- if quoteChar == CodeUnits.singleQuote { +- return try literalString(bytes: bytes, range: index ..< endIndex, multiline: multiline) +- } else { +- return try basicString(bytes: bytes, range: index ..< endIndex, multiline: multiline) +- } +- } +- +- func unpackInteger(bytes: UnsafeBufferPointer, context: TOMLKey) throws(TOMLError) -> Int64 { +- @_transparent +- func isValidDigit(_ codeUnit: UTF8.CodeUnit, base: Int) -> Bool { +- switch base { +- case 10: +- codeUnit.isDecimalDigit +- case 16: +- codeUnit.isHexDigit +- case 2: +- codeUnit == CodeUnits.number0 || codeUnit == CodeUnits.number1 +- case 8: +- CodeUnits.number0 <= codeUnit && codeUnit <= CodeUnits.number7 +- default: +- false +- } +- } +- +- var resultCodeUnits: [UTF8.CodeUnit] = [] +- var index = text.lowerBound +- var base = 10 +- var hasSign = false +- if bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus { +- hasSign = true +- resultCodeUnits.append(bytes[index]) +- index = text.index(after: index) +- } +- guard index < text.upperBound else { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "expected digit after sign")) +- } +- +- if bytes[index] == CodeUnits.underscore { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "cannot start with a '_'")) +- } +- +- if bytes[index] == CodeUnits.number0 { +- let nextIndex = index + 1 +- if nextIndex < text.upperBound { +- if bytes[nextIndex] == CodeUnits.lowerX { +- if hasSign { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "hexadecimal integers cannot have explicit signs")) +- } +- base = 16 +- index += 2 +- } else if bytes[nextIndex] == CodeUnits.lowerO { +- if hasSign { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "octal integers cannot have explicit signs")) +- } +- base = 8 +- index += 2 +- } else if bytes[nextIndex] == CodeUnits.lowerB { +- if hasSign { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "binary integers cannot have explicit signs")) +- } +- base = 2 +- index += 2 +- } else if bytes[nextIndex].isDecimalDigit || bytes[nextIndex] == CodeUnits.underscore { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "decimal integers cannot have leading zeros")) +- } +- } +- // Single zero is allowed to continue to the main loop +- } +- guard index < text.upperBound else { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "expected digit after base prefix")) +- } +- +- while index < text.upperBound { +- let ch = bytes[index] +- index += 1 +- +- if ch == CodeUnits.underscore { +- guard +- let last = resultCodeUnits.last, +- isValidDigit(last, base: base) +- else { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "cannot use '_' adjacent to a non-digit")) +- } +- +- if index >= text.endIndex { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "cannot end with a '_'")) +- } +- +- let next = bytes[index] +- if next == CodeUnits.underscore { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "cannot contain consecutive '_'")) +- } +- guard isValidDigit(next, base: base) else { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "cannot use '_' adjacent to a non-digit")) +- } +- continue +- } +- +- guard isValidDigit(ch, base: base) else { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "invalid digit for base \(base)")) +- } +- +- resultCodeUnits.append(ch) +- } +- +- let s = String(decoding: resultCodeUnits, as: UTF8.self) +- guard let i = Int64(s, radix: base) else { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "\(s) is a invalid integer of base \(base)")) +- } +- return i +- } +- +- func unpackDateTime(bytes: UnsafeBufferPointer, context: TOMLKey) throws(TOMLError) -> DateTimeComponents { +- var mustParseTime = false +- var date: (year: Int, month: Int, day: Int)? +- var time: (hour: Int, minute: Int, second: Int)? +- +- var index = text.lowerBound +- if let (year, month, day, _) = scanDate(bytes: bytes, range: text) { +- // Validate date components +- if month < 1 || month > 12 { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "month must be between 01 and 12")) +- } +- if day < 1 { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "day must be between 01 and 31")) +- } +- +- // Validate days per month and leap years +- let isLeapYear = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) +- let maxDaysInMonth: Int = switch month { +- case 2: +- isLeapYear ? 29 : 28 +- case 4, 6, 9, 11: +- 30 +- default: +- 31 +- } +- +- if day > maxDaysInMonth { +- if month == 2, !isLeapYear { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "February only has 28 days in non-leap years")) +- } else if month == 2, isLeapYear { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "February only has 29 days in leap years")) +- } else { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "day \(day) is invalid for month \(month)")) +- } +- } +- +- date = (year, month, day) +- index += 10 +- } +- +- var features: OffsetDateTime.Features = [] +- var nanoseconds: UInt32? +- if index < text.upperBound { +- if date != nil { +- let isSeparatorLowerT = bytes[index] == CodeUnits.lowerT +- let isSeparatorUpperT = bytes[index] == CodeUnits.upperT +- guard isSeparatorLowerT || isSeparatorUpperT || bytes[index] == CodeUnits.space else { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "expected 'T' or 't' or space to separate date and time")) +- } +- if isSeparatorLowerT { +- features.insert(.lowercaseT) +- } else if isSeparatorUpperT { +- features.insert(.uppercaseT) +- } +- mustParseTime = true +- index += 1 +- } else { +- // For standalone time values, don't advance index +- mustParseTime = true +- } +- if let (hour, minute, second, newIndex) = scanTime(bytes: bytes, range: index ..< text.upperBound) { +- // Validate time components +- if hour > 23 { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "hour must be between 00 and 23")) +- } +- if minute > 59 { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "minute must be between 00 and 59")) +- } +- if second > 59 { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "second must be between 00 and 59")) +- } +- +- time = (hour, minute, second) +- +- index = newIndex +- if index < text.upperBound, bytes[index] == CodeUnits.dot { +- index += 1 +- let beforeNanoIndex = index +- nanoseconds = parseNanoSeconds(bytes: bytes, range: index ..< text.upperBound, updatedIndex: &index) +- // Must have at least one digit after decimal point +- if index == beforeNanoIndex { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "decimal point must be followed by digits")) +- } +- } +- } +- } +- +- if mustParseTime, time == nil { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "expected valid time")) +- } +- +- var timeOffset: Int16? +- if index < text.upperBound { +- if bytes[index] == CodeUnits.lowerZ { +- features.insert(.lowercaseZ) +- index += 1 +- timeOffset = 0 +- } else if bytes[index] == CodeUnits.upperZ { +- features.insert(.uppercaseZ) +- index += 1 +- timeOffset = 0 +- } else if bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus { +- let offsetIsNegative = bytes[index] == CodeUnits.minus +- index += 1 +- +- // Scan ahead to find the end of the timezone offset +- var endIndex = index +- while endIndex < text.upperBound { +- let ch = bytes[endIndex] +- if ch.isDecimalDigit || ch == CodeUnits.colon { +- endIndex += 1 +- } else { +- break +- } +- } +- +- do { +- let (offsetHour, offsetMinute, consumedLength) = try parseTimezoneOffset(bytes: bytes, range: index ..< endIndex, lineNumber: lineNumber) +- +- // Validate timezone offset ranges +- if offsetHour > 24 { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "timezone offset hour must be between 00 and 24")) +- } +- if offsetMinute > 59 { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "timezone offset minute must be between 00 and 59")) +- } +- +- let offsetInMinutes = offsetHour * 60 + offsetMinute +- timeOffset = Int16(offsetIsNegative ? -offsetInMinutes : offsetInMinutes) +- index += consumedLength +- } catch let parseError { +- if let tomlError = parseError as? TOMLError { +- switch tomlError.reason { +- case let .invalidDateTime(_, reason): +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: reason)) +- default: +- throw tomlError +- } +- } else { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "timezone parsing error")) +- } +- } +- } +- } +- +- if index < text.upperBound { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "extra character after date time")) +- } +- +- return DateTimeComponents( +- date: date.map { LocalDate(year: .init($0.year), month: .init($0.month), day: .init($0.day)) }, +- time: time.map { LocalTime(hour: .init($0.hour), minute: .init($0.minute), second: .init($0.second), nanosecond: nanoseconds ?? 0) }, +- offset: timeOffset, +- features: features ++ break ++ } ++ } ++ return index ++ } ++ ++ if multiline { ++ let afterWhitespace = try indexAfterSkippingCharacters( ++ start: index, endIndex: endIndex, ++ characters: [CodeUnits.space, CodeUnits.tab, CodeUnits.cr] ++ ) ++ if afterWhitespace < endIndex, bytes[afterWhitespace] == CodeUnits.lf { ++ index = try indexAfterSkippingCharacters( ++ start: index, endIndex: endIndex, ++ characters: [CodeUnits.space, CodeUnits.tab, CodeUnits.cr, CodeUnits.lf] +@@ -1551,69 +1989,5 @@ +- } +- +- func unpackAnyValue(bytes: UnsafeBufferPointer, context: TOMLKey) throws(TOMLError) -> Any { +- let firstChar = text.count > 0 ? bytes[text.lowerBound] : nil +- if firstChar == CodeUnits.singleQuote || firstChar == CodeUnits.doubleQuote { +- return try unpackString(bytes: bytes, context: context) +- } +- +- if let boolValue = try? unpackBool(bytes: bytes, context: context) { +- return boolValue +- } +- +- if let intValue = try? unpackInteger(bytes: bytes, context: context) { +- return intValue +- } +- +- if let floatValue = try? unpackFloat(bytes: bytes, context: context) { +- return floatValue +- } +- +- guard firstChar?.isDecimalDigit == true else { +- throw TOMLError(.invalidValueInTable(context: context, lineNumber: lineNumber)) +- } +- +- let datetime = try unpackDateTime(bytes: bytes, context: context) +- switch (datetime.date, datetime.time, datetime.offset) { +- case let (.some(date), .some(time), .some(offset)): +- return OffsetDateTime(date: date, time: time, offset: offset, features: datetime.features) +- case let (.some(date), .some(time), .none): +- return LocalDateTime(date: date, time: time) +- case let (.some(date), .none, .none): +- return date +- case let (.none, .some(time), .none): +- return time +- default: +- throw TOMLError(.invalidValueInTable(context: context, lineNumber: lineNumber)) +- } +- } +-} +- +-func parseTimezoneOffset(bytes: UnsafeBufferPointer, range: Range, lineNumber: Int) throws(TOMLError) -> (hour: Int, minute: Int, consumedLength: Int) { +- guard range.count >= 2 else { +- throw TOMLError(.invalidDateTime(lineNumber: lineNumber, reason: "timezone offset must have at least 2 digits for hour")) +- } +- +- var index = range.lowerBound +- +- // Parse hour digits (exactly 2 required) +- guard +- index < range.upperBound, +- bytes[index].isDecimalDigit, +- case let firstHourDigit = bytes[index], +- case let nextIndex = index + 1, +- nextIndex < range.upperBound, +- bytes[nextIndex].isDecimalDigit, +- case let secondHourDigit = bytes[nextIndex] +- else { +- throw TOMLError(.invalidDateTime(lineNumber: lineNumber, reason: "timezone offset hour must be exactly 2 digits")) +- } +- +- let offsetHour = Int(firstHourDigit - CodeUnits.number0) * 10 + Int(secondHourDigit - CodeUnits.number0) +- index += 2 +- var consumedLength = 2 +- +- // Parse required minute digits (timezone offset must include minutes) +- guard index < range.upperBound, bytes[index] == CodeUnits.colon else { +- throw TOMLError(.invalidDateTime(lineNumber: lineNumber, reason: "timezone offset must include minutes (format: ±HH:MM)")) +- } +- ++ continue ++ } ++ } ++ ++ ch = bytes[index] +@@ -1621,64 +1995,12 @@ +- consumedLength += 1 +- +- guard +- index < range.upperBound, +- bytes[index].isDecimalDigit, +- case let firstMinuteDigit = bytes[index], +- case let nextMinuteIndex = index + 1, +- nextMinuteIndex < range.upperBound, +- bytes[nextMinuteIndex].isDecimalDigit, +- case let secondMinuteDigit = bytes[nextMinuteIndex] +- else { +- throw TOMLError(.invalidDateTime(lineNumber: lineNumber, reason: "timezone offset minute must be exactly 2 digits")) +- } +- +- let offsetMinute = Int(firstMinuteDigit - CodeUnits.number0) * 10 + Int(secondMinuteDigit - CodeUnits.number0) +- consumedLength += 2 +- +- return (offsetHour, offsetMinute, consumedLength) +-} +- +-func literalString(bytes: UnsafeBufferPointer, range: Range, multiline: Bool) throws(TOMLError) -> String { +- var resultCodeUnits: [UTF8.CodeUnit] = [] +- var consecutiveQuotes = 0 +- +- for index in range { +- let codeUnit = bytes[index] +- if codeUnit >= CodeUnits.null && codeUnit <= CodeUnits.backspace || codeUnit >= CodeUnits.lf && codeUnit <= CodeUnits.unitSeparator || codeUnit == CodeUnits.delete { +- if multiline, codeUnit == CodeUnits.lf { +- // Allow LF in multiline literal strings +- } else if multiline, codeUnit == CodeUnits.cr { +- // Only allow CR if followed by LF (CRLF sequence) +- let nextIndex = index + 1 +- if nextIndex < range.upperBound, bytes[nextIndex] == CodeUnits.lf { +- // Allow CRLF sequence - will be processed as separate characters +- } else { +- throw TOMLError(.invalidCharacter(codeUnit)) +- } +- } else { +- throw TOMLError(.invalidCharacter(codeUnit)) +- } +- } +- +- if multiline, codeUnit == CodeUnits.singleQuote { +- consecutiveQuotes += 1 +- if consecutiveQuotes > 2 { +- throw TOMLError(.syntax(lineNumber: 0, message: "literal multiline strings cannot contain more than 2 consecutive single quotes")) +- } +- } else { +- consecutiveQuotes = 0 +- } +- +- resultCodeUnits.append(codeUnit) +- } +- return String(decoding: resultCodeUnits, as: UTF8.self) +-} +- +-func basicString(bytes: UnsafeBufferPointer, range: Range, multiline: Bool) throws(TOMLError) -> String { +- let startIndex = range.lowerBound +- let endIndex = range.upperBound +- var resultCodeUnits: [UTF8.CodeUnit] = [] +- resultCodeUnits.reserveCapacity(range.count) +- var consecutiveQuotes = 0 +- var index = startIndex +- while true { ++ ++ if ch == CodeUnits.lowerU || ch == CodeUnits.upperU || ch == CodeUnits.lowerX { ++ let hexCount = ++ switch ch { ++ case CodeUnits.lowerU: 4 ++ case CodeUnits.upperU: 8 ++ case CodeUnits.lowerX: 2 ++ default: fatalError("Unsupported CodeUnit: \(ch)") ++ } ++ var ucs: UInt32 = 0 ++ for _ in 0..= CodeUnits.null && ch <= CodeUnits.backspace +- || ch >= CodeUnits.lf && ch <= CodeUnits.unitSeparator || ch == CodeUnits.delete +- { +- if multiline, ch == CodeUnits.lf { +- // Allow LF in multiline basic strings +- } else if multiline, ch == CodeUnits.cr { +- // Only allow CR if followed by LF (CRLF sequence) +- if index < endIndex, bytes[index] == CodeUnits.lf { +- // Allow CRLF sequence - will be processed as separate characters +- } else { +- throw TOMLError(.invalidCharacter(ch)) +- } +- } else { +- throw TOMLError(.invalidCharacter(ch)) +- } +- } +- +- if multiline, ch == CodeUnits.doubleQuote { +- consecutiveQuotes += 1 +- if consecutiveQuotes > 2 { +- throw TOMLError( +- .syntax( +- lineNumber: 0, +- message: +- "basic multiline strings cannot contain more than 2 consecutive double quotes" +- ) +- ) +- } +- } else { +- consecutiveQuotes = 0 +- } +- +- resultCodeUnits.append(ch) +- continue +- } +- +- if index >= endIndex { +- throw TOMLError(.invalidCharacter(CodeUnits.backslash)) +- } +- +- func indexAfterSkippingCharacters(start: Int, endIndex: Int, characters: [UTF8.CodeUnit]) +- -> Int +- { +- var index = start +- while index < endIndex { +- if characters.contains(bytes[index]) { +- index += 1 +- } else { +- break +- } +- } +- return index +- } +- +- if multiline { +- let afterWhitespace = indexAfterSkippingCharacters( +- start: index, endIndex: endIndex, +- characters: [CodeUnits.space, CodeUnits.tab, CodeUnits.cr] +- ) +- if afterWhitespace < endIndex, bytes[afterWhitespace] == CodeUnits.lf { +- index = indexAfterSkippingCharacters( +- start: index, endIndex: endIndex, +- characters: [CodeUnits.space, CodeUnits.tab, CodeUnits.cr, CodeUnits.lf] +- ) +- continue +- } +- } +- ++ throw TOMLError(.expectedHexCharacters(ch, hexCount)) ++ } +@@ -1762,53 +2012,40 @@ +- +- if ch == CodeUnits.lowerU || ch == CodeUnits.upperU || ch == CodeUnits.lowerX { +- let hexCount = switch ch { +- case CodeUnits.lowerU: 4 +- case CodeUnits.upperU: 8 +- case CodeUnits.lowerX: 2 +- default: fatalError("Unsupported CodeUnit: \(ch)") +- } +- var ucs: UInt32 = 0 +- for _ in 0 ..< hexCount { +- if index >= endIndex { +- throw TOMLError(.expectedHexCharacters(ch, hexCount)) +- } +- ch = bytes[index] +- index += 1 +- let v: Int32 = +- ch.isDecimalDigit +- ? Int32(ch - CodeUnits.number0) +- : (ch >= CodeUnits.upperA && ch <= CodeUnits.upperF) +- ? Int32(ch - CodeUnits.upperA + 10) +- : (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerF) +- ? Int32(ch - CodeUnits.lowerA + 10) +- : -1 +- if v == -1 { +- throw TOMLError(.invalidHexCharacters(ch)) +- } +- ucs = ucs * 16 + UInt32(v) +- } +- guard let scalar = Unicode.Scalar(ucs) else { +- throw TOMLError(.illegalUCSCode(ucs)) +- } +- resultCodeUnits.append(contentsOf: scalar.utf8) +- continue +- } else if ch == CodeUnits.lowerB { +- ch = CodeUnits.backspace +- } else if ch == CodeUnits.lowerT { +- ch = CodeUnits.tab +- } else if ch == CodeUnits.lowerF { +- ch = CodeUnits.formfeed +- } else if ch == CodeUnits.lowerR { +- ch = CodeUnits.cr +- } else if ch == CodeUnits.lowerN { +- ch = CodeUnits.lf +- } else if ch == CodeUnits.lowerE { +- ch = CodeUnits.escape +- } else if ch != CodeUnits.doubleQuote, ch != CodeUnits.backslash { +- throw TOMLError(.illegalEscapeCharacter(ch)) +- } +- +- consecutiveQuotes = 0 // Reset count after escape sequence +- resultCodeUnits.append(ch) +- } +- return String(decoding: resultCodeUnits, as: UTF8.self) ++ let v: Int32 = ++ ch.isDecimalDigit ++ ? Int32(ch - CodeUnits.number0) ++ : (ch >= CodeUnits.upperA && ch <= CodeUnits.upperF) ++ ? Int32(ch - CodeUnits.upperA + 10) ++ : (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerF) ++ ? Int32(ch - CodeUnits.lowerA + 10) ++ : -1 ++ if v == -1 { ++ throw TOMLError(.invalidHexCharacters(ch)) ++ } ++ ucs = ucs * 16 + UInt32(v) ++ } ++ guard let scalar = Unicode.Scalar(ucs) else { ++ throw TOMLError(.illegalUCSCode(ucs)) ++ } ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(contentsOf: scalar.utf8) ++ continue ++ } else if ch == CodeUnits.lowerB { ++ ch = CodeUnits.backspace ++ } else if ch == CodeUnits.lowerT { ++ ch = CodeUnits.tab ++ } else if ch == CodeUnits.lowerF { ++ ch = CodeUnits.formfeed ++ } else if ch == CodeUnits.lowerR { ++ ch = CodeUnits.cr ++ } else if ch == CodeUnits.lowerN { ++ ch = CodeUnits.lf ++ } else if ch == CodeUnits.lowerE { ++ ch = CodeUnits.escape ++ } else if ch != CodeUnits.doubleQuote, ch != CodeUnits.backslash { ++ throw TOMLError(.illegalEscapeCharacter(ch)) ++ } ++ ++ consecutiveQuotes = 0 // Reset count after escape sequence ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(ch) ++ } ++ return String(decoding: resultCodeUnits, as: UTF8.self) +@@ -1818,11 +2055,36 @@ +- guard let year = scanDigits(bytes: bytes, range: range, n: 4) else { +- return nil +- } +- +- var index = range.lowerBound +- index += 4 +- +- guard index < range.upperBound, bytes[index] == CodeUnits.minus else { +- return nil +- } +- ++ guard let year = scanDigits(bytes: bytes, range: range, n: 4) else { ++ return nil ++ } ++ ++ var index = range.lowerBound ++ index += 4 ++ ++ guard index < range.upperBound, bytes[index] == CodeUnits.minus else { ++ return nil ++ } ++ ++ index += 1 ++ guard let month = scanDigits(bytes: bytes, range: index.., range: Range, n: Int) -> Int? { ++ var result = 0 ++ var n = n ++ var index = range.lowerBound ++ while n > 0, index < range.upperBound, bytes[index].isDecimalDigit { ++ result = 10 * result + Int(bytes[index]) - Int(CodeUnits.number0) +@@ -1830,9 +2092,47 @@ +- guard let month = scanDigits(bytes: bytes, range: index ..< range.upperBound, n: 2) else { +- return nil +- } +- +- index += 2 +- guard bytes[index] == CodeUnits.minus else { +- return nil +- } +- ++ n -= 1 ++ } ++ return n != 0 ? nil : result ++} ++ ++func scanTime(bytes: UnsafeBufferPointer, range: Range) -> (Int, Int, Int, Int)? { ++ guard let hour = scanDigits(bytes: bytes, range: range, n: 2) else { ++ return nil ++ } ++ ++ var index = range.lowerBound ++ ++ index += 2 ++ guard index < range.upperBound, bytes[index] == CodeUnits.colon else { ++ return nil ++ } ++ ++ index += 1 ++ guard let minute = scanDigits(bytes: bytes, range: index.., range: Range, ++ updatedIndex: inout Int ++) throws -> UInt32 { ++ var unit: Double = 100_000_000 ++ var result: Double = 0 ++ var index = range.lowerBound ++ while index < range.upperBound, bytes[index].isDecimalDigit { ++ try budget.step() ++ result += Double(bytes[index] - CodeUnits.number0) * unit +@@ -1840,6 +2140,4 @@ +- guard let day = scanDigits(bytes: bytes, range: index ..< range.upperBound, n: 2) else { +- return nil +- } +- +- index += 2 +- return (year, month, day, index) ++ unit /= 10 ++ } ++ updatedIndex = index ++ return UInt32(result) +@@ -1848,56 +2145,0 @@ +-func scanDigits(bytes: UnsafeBufferPointer, range: Range, n: Int) -> Int? { +- var result = 0 +- var n = n +- var index = range.lowerBound +- while n > 0, index < range.upperBound, bytes[index].isDecimalDigit { +- result = 10 * result + Int(bytes[index]) - Int(CodeUnits.number0) +- index += 1 +- n -= 1 +- } +- return n != 0 ? nil : result +-} +- +-func scanTime(bytes: UnsafeBufferPointer, range: Range) -> (Int, Int, Int, Int)? { +- guard let hour = scanDigits(bytes: bytes, range: range, n: 2) else { +- return nil +- } +- +- var index = range.lowerBound +- +- index += 2 +- guard index < range.upperBound, bytes[index] == CodeUnits.colon else { +- return nil +- } +- +- index += 1 +- guard let minute = scanDigits(bytes: bytes, range: index ..< range.upperBound, n: 2) else { +- return nil +- } +- +- index += 2 +- guard index < range.upperBound, bytes[index] == CodeUnits.colon else { +- return (hour, minute, 0, index) // Seconds are optional since 1.1.0. When omitted, :00 seconds is assumed +- } +- +- index += 1 +- guard let second = scanDigits(bytes: bytes, range: index ..< range.upperBound, n: 2) else { +- return nil +- } +- +- index += 2 +- return (hour, minute, second, index) +-} +- +-func parseNanoSeconds(bytes: UnsafeBufferPointer, range: Range, updatedIndex: inout Int) -> UInt32 { +- var unit: Double = 100_000_000 +- var result: Double = 0 +- var index = range.lowerBound +- while index < range.upperBound, bytes[index].isDecimalDigit { +- result += Double(bytes[index] - CodeUnits.number0) * unit +- index += 1 +- unit /= 10 +- } +- updatedIndex = index +- return UInt32(result) +-} +- +@@ -1905,21 +2147,22 @@ +- var index = range.lowerBound +- guard index < range.upperBound, bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus else { +- return nil +- } +- +- index += 1 +- guard let _ = scanDigits(bytes: bytes, range: index ..< range.upperBound, n: 2) else { +- return nil +- } +- +- index += 2 +- guard index < range.upperBound, bytes[index] == CodeUnits.colon else { +- return nil +- } +- +- index += 1 +- guard let _ = scanDigits(bytes: bytes, range: index ..< range.upperBound, n: 2) else { +- return nil +- } +- index += 2 +- return index ++ var index = range.lowerBound ++ guard index < range.upperBound, bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus ++ else { ++ return nil ++ } ++ ++ index += 1 ++ guard scanDigits(bytes: bytes, range: index.. Bool { +- let xor = chunk ^ bytePattern +- return ((xor &- ones) & ~xor & highBits) != 0 +- } +- +- return hasByte(0x2222_2222_2222_2222) +- || hasByte(0x5C5C_5C5C_5C5C_5C5C) +- || hasByte(0x0A0A_0A0A_0A0A_0A0A) ++ let ones: UInt64 = 0x0101_0101_0101_0101 ++ let highBits: UInt64 = 0x8080_8080_8080_8080 ++ ++ @inline(__always) ++ func hasByte(_ bytePattern: UInt64) -> Bool { ++ let xor = chunk ^ bytePattern ++ return ((xor &- ones) & ~xor & highBits) != 0 ++ } ++ ++ return hasByte(0x2222_2222_2222_2222) ++ || hasByte(0x5C5C_5C5C_5C5C_5C5C) ++ || hasByte(0x0A0A_0A0A_0A0A_0A0A) +@@ -1944,52 +2187,48 @@ +-func normalizeKeyAndHash(bytes: UnsafeBufferPointer, token: Token, keyTransform: (@Sendable (String) -> String)?) throws(TOMLError) -> (key: String, keyHash: Int) { +- var start = token.text.lowerBound +- var end = token.text.upperBound +- if token.kind == .bareKey { +- var str = makeString(bytes: bytes, range: start ..< end) +- if let keyTransform { +- str = keyTransform(str) +- return (str, fastKeyHash(str)) +- } +- return (str, fastKeyHash(bytes: bytes, range: start ..< end)) +- } +- +- let ch = bytes[start] +- var result = "" +- if ch == CodeUnits.doubleQuote || ch == CodeUnits.singleQuote { +- if bytes[start + 1] == ch, bytes[start + 2] == ch { +- // Keys cannot be multiline +- throw TOMLError(.badKey(lineNumber: token.lineNumber)) +- } else { +- start = start + 1 +- end = end - 1 +- } +- +- if ch == CodeUnits.singleQuote { +- result = makeString(bytes: bytes, range: start ..< end) +- return (result, fastKeyHash(bytes: bytes, range: start ..< end)) +- } else { +- result = try basicString(bytes: bytes, range: start ..< end, multiline: false) +- return (result, fastKeyHash(result)) +- } +- } +- +- for i in start ..< end { +- let byte = bytes[i] +- if byte >= CodeUnits.number0 && byte <= CodeUnits.number9 || // 0-9 +- byte >= CodeUnits.upperA && byte <= CodeUnits.upperZ || // A-Z +- byte >= CodeUnits.lowerA && byte <= CodeUnits.lowerZ || // a-z +- byte == CodeUnits.underscore || // _ +- byte == CodeUnits.minus // - +- { +- continue +- } +- throw TOMLError(.badKey(lineNumber: token.lineNumber)) +- } +- +- if let keyTransform { +- let key = keyTransform(makeString(bytes: bytes, range: start ..< end)) +- return (key, fastKeyHash(key)) +- } +- +- let key = makeString(bytes: bytes, range: start ..< end) +- return (key, fastKeyHash(bytes: bytes, range: start ..< end)) ++func normalizeKeyAndHash(bytes: UnsafeBufferPointer, token: Token) throws -> ( ++ key: String, keyHash: Int ++) { ++ let budget = token.budget! ++ try budget.allocate(token.text.count, stage: "decoded key") ++ var start = token.text.lowerBound ++ var end = token.text.upperBound ++ if token.kind == .bareKey { ++ let str = try makeString(budget: budget, bytes: bytes, range: start..= CodeUnits.number0 && byte <= CodeUnits.number9 // 0-9 ++ || byte >= CodeUnits.upperA && byte <= CodeUnits.upperZ // A-Z ++ || byte >= CodeUnits.lowerA && byte <= CodeUnits.lowerZ // a-z ++ || byte == CodeUnits.underscore // _ ++ || byte == CodeUnits.minus // - ++ { ++ continue ++ } ++ throw TOMLError(.badKey(lineNumber: token.lineNumber)) ++ } ++ ++ let key = try makeString(budget: budget, bytes: bytes, range: start.. UInt64 in +- if buffer.count <= 8 { +- return packedKeyHash(buffer) +- } +- if let start = buffer.baseAddress { +- return sampledKeyHash(start: start, count: buffer.count) +- } +- return 0 +- }) { +- return Int(truncatingIfNeeded: hash) +- } +- +- let offsetBasis: UInt64 = 14_695_981_039_346_656_037 +- let prime: UInt64 = 1_099_511_628_211 +- var hash = offsetBasis +- var packed: UInt64 = 0 +- var count = 0 +- for byte in key.utf8 { +- if count < 8 { +- packed |= UInt64(byte) << (UInt64(count) * 8) +- } +- hash ^= UInt64(byte) +- hash &*= prime +- count += 1 +- } +- return Int(truncatingIfNeeded: count <= 8 ? packed : hash) ++ if let hash = key.utf8.withContiguousStorageIfAvailable({ buffer -> UInt64 in ++ if buffer.count <= 8 { ++ return packedKeyHash(buffer) ++ } ++ if let start = buffer.baseAddress { ++ return sampledKeyHash(start: start, count: buffer.count) ++ } ++ return 0 ++ }) { ++ return Int(truncatingIfNeeded: hash) ++ } ++ ++ let offsetBasis: UInt64 = 14_695_981_039_346_656_037 ++ let prime: UInt64 = 1_099_511_628_211 ++ var hash = offsetBasis ++ var packed: UInt64 = 0 ++ var count = 0 ++ for byte in key.utf8 { ++ if count < 8 { ++ packed |= UInt64(byte) << (UInt64(count) * 8) ++ } ++ hash ^= UInt64(byte) ++ hash &*= prime ++ count += 1 ++ } ++ return Int(truncatingIfNeeded: count <= 8 ? packed : hash) +@@ -2043,4 +2282,4 @@ +- let prefix = packedKeyHash(UnsafeBufferPointer(start: start, count: 8)) +- let suffix = packedKeyHash(UnsafeBufferPointer(start: start.advanced(by: count - 8), count: 8)) +- let rotatedSuffix = (suffix << 1) | (suffix >> 63) +- return prefix ^ rotatedSuffix ^ (UInt64(truncatingIfNeeded: count) &* 0x9E37_79B1_85EB_CA87) ++ let prefix = packedKeyHash(UnsafeBufferPointer(start: start, count: 8)) ++ let suffix = packedKeyHash(UnsafeBufferPointer(start: start.advanced(by: count - 8), count: 8)) ++ let rotatedSuffix = (suffix << 1) | (suffix >> 63) ++ return prefix ^ rotatedSuffix ^ (UInt64(truncatingIfNeeded: count) &* 0x9E37_79B1_85EB_CA87) +@@ -2051,25 +2290,342 @@ +- var packed: UInt64 = 0 +- switch buffer.count { +- case 8: +- packed |= UInt64(buffer[7]) << 56 +- fallthrough +- case 7: +- packed |= UInt64(buffer[6]) << 48 +- fallthrough +- case 6: +- packed |= UInt64(buffer[5]) << 40 +- fallthrough +- case 5: +- packed |= UInt64(buffer[4]) << 32 +- fallthrough +- case 4: +- packed |= UInt64(buffer[3]) << 24 +- fallthrough +- case 3: +- packed |= UInt64(buffer[2]) << 16 +- fallthrough +- case 2: +- packed |= UInt64(buffer[1]) << 8 +- fallthrough +- case 1: +- packed |= UInt64(buffer[0]) ++ var packed: UInt64 = 0 ++ switch buffer.count { ++ case 8: ++ packed |= UInt64(buffer[7]) << 56 ++ fallthrough ++ case 7: ++ packed |= UInt64(buffer[6]) << 48 ++ fallthrough ++ case 6: ++ packed |= UInt64(buffer[5]) << 40 ++ fallthrough ++ case 5: ++ packed |= UInt64(buffer[4]) << 32 ++ fallthrough ++ case 4: ++ packed |= UInt64(buffer[3]) << 24 ++ fallthrough ++ case 3: ++ packed |= UInt64(buffer[2]) << 16 ++ fallthrough ++ case 2: ++ packed |= UInt64(buffer[1]) << 8 ++ fallthrough ++ case 1: ++ packed |= UInt64(buffer[0]) ++ default: ++ break ++ } ++ return packed ++} ++ ++@inline(__always) ++private func makeString( ++ budget: SemanticBudget, bytes: UnsafeBufferPointer, range: Range ++) throws -> String { ++ try budget.allocate(range.count, stage: "decoded key copy") ++ try budget.step(range.count) ++ let count = range.upperBound - range.lowerBound ++ if count == 0 { ++ return "" ++ } ++ let start = bytes.baseAddress!.advanced(by: range.lowerBound) ++ return String(decoding: UnsafeBufferPointer(start: start, count: count), as: UTF8.self) ++} ++ ++extension Parser { ++ @inline(__always) ++ func matchKeyValue(in indices: borrowing [Int], key: borrowing String, keyHash: Int) throws ++ -> Int? ++ { ++ if indices.isEmpty { ++ return nil ++ } ++ return try keyValues.withUnsafeBufferPointer { keyValueBuffer -> Int? in ++ guard let keyValueBase = keyValueBuffer.baseAddress else { ++ return nil ++ } ++ let indexCount = indices.count ++ var i = 0 ++ while i < indexCount { ++ try budget.step() ++ let keyValueIndex = indices[i] ++ let keyValuePair = keyValueBase.advanced(by: keyValueIndex).pointee ++ if keyValuePair.keyHash == keyHash, try budget.equal(keyValuePair.key, key) { ++ return keyValueIndex ++ } ++ i += 1 ++ } ++ return nil ++ } ++ } ++ ++ @inline(__always) ++ func matchKeyArray(in indices: borrowing [Int], key: borrowing String, keyHash: Int) throws ++ -> Int? ++ { ++ if indices.isEmpty { ++ return nil ++ } ++ return try keyArrays.withUnsafeBufferPointer { keyArrayBuffer -> Int? in ++ guard let keyArrayBase = keyArrayBuffer.baseAddress else { ++ return nil ++ } ++ let indexCount = indices.count ++ var i = 0 ++ while i < indexCount { ++ try budget.step() ++ let keyArrayIndex = indices[i] ++ let keyArrayPair = keyArrayBase.advanced(by: keyArrayIndex).pointee ++ if keyArrayPair.keyHash == keyHash, try budget.equal(keyArrayPair.key, key) { ++ return keyArrayIndex ++ } ++ i += 1 ++ } ++ return nil ++ } ++ } ++ ++ @inline(__always) ++ func keyMatchesToken(bytes: UnsafeBufferPointer, token: Token, key: borrowing String) ++ throws -> Bool ++ { ++ let range = token.text ++ let count = range.upperBound - range.lowerBound ++ ++ if let matches = try key.utf8.withContiguousStorageIfAvailable({ keyBuffer -> Bool in ++ if keyBuffer.count != count { ++ return false ++ } ++ ++ var keyIndex = 0 ++ var byteIndex = range.lowerBound ++ while keyIndex < count { ++ try budget.step() ++ if keyBuffer[keyIndex] != bytes[byteIndex] { ++ return false ++ } ++ keyIndex += 1 ++ byteIndex += 1 ++ } ++ return true ++ }) { ++ return matches ++ } ++ ++ var index = range.lowerBound ++ for byte in key.utf8 { ++ try budget.step() ++ if index >= range.upperBound || bytes[index] != byte { ++ return false ++ } ++ index += 1 ++ } ++ return index == range.upperBound ++ } ++ ++ @inline(__always) ++ func matchKeyArray( ++ in indices: borrowing [Int], ++ bytes: UnsafeBufferPointer, ++ token: Token, ++ keyHash: Int ++ ) throws -> Int? { ++ if indices.isEmpty { ++ return nil ++ } ++ return try keyArrays.withUnsafeBufferPointer { keyArrayBuffer -> Int? in ++ guard let keyArrayBase = keyArrayBuffer.baseAddress else { ++ return nil ++ } ++ let indexCount = indices.count ++ var i = 0 ++ while i < indexCount { ++ try budget.step() ++ let keyArrayIndex = indices[i] ++ let keyArrayPair = keyArrayBase.advanced(by: keyArrayIndex).pointee ++ if keyArrayPair.keyHash == keyHash, ++ try keyMatchesToken(bytes: bytes, token: token, key: keyArrayPair.key) ++ { ++ return keyArrayIndex ++ } ++ i += 1 ++ } ++ return nil ++ } ++ } ++ ++ @inline(__always) ++ func matchKeyTable(in indices: borrowing [Int], key: borrowing String, keyHash: Int) throws ++ -> Int? ++ { ++ if indices.isEmpty { ++ return nil ++ } ++ return try keyTables.withUnsafeBufferPointer { keyTableBuffer -> Int? in ++ guard let keyTableBase = keyTableBuffer.baseAddress else { ++ return nil ++ } ++ let indexCount = indices.count ++ var i = 0 ++ while i < indexCount { ++ try budget.step() ++ let keyTableIndex = indices[i] ++ let keyTablePair = keyTableBase.advanced(by: keyTableIndex).pointee ++ if keyTablePair.keyHash == keyHash, try budget.equal(keyTablePair.key, key) { ++ return keyTableIndex ++ } ++ i += 1 ++ } ++ return nil ++ } ++ } ++ ++ @inline(__always) ++ func tableValue( ++ tableIndex: Int, ++ keyed: Bool, ++ key: borrowing String, ++ keyHash: Int ++ ) throws -> InternalTOMLTable.Value? { ++ if keyed { ++ if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { ++ return nil ++ } ++ } else if !tables[tableIndex].mightContainKeyHash(keyHash) { ++ return nil ++ } ++ ++ if keyed { ++ if let keyValueIndex = try matchKeyValue( ++ in: keyTables[tableIndex].table.keyValues, key: key, keyHash: keyHash) ++ { ++ return .keyValue(keyValueIndex) ++ } ++ ++ if let keyArrayIndex = try matchKeyArray( ++ in: keyTables[tableIndex].table.arrays, key: key, keyHash: keyHash) ++ { ++ return .array(keyArrayIndex) ++ } ++ ++ if let keyTableIndex = try matchKeyTable( ++ in: keyTables[tableIndex].table.tables, key: key, keyHash: keyHash) ++ { ++ return .table(keyTableIndex) ++ } ++ return nil ++ } ++ ++ if let keyValueIndex = try matchKeyValue( ++ in: tables[tableIndex].keyValues, key: key, keyHash: keyHash) ++ { ++ return .keyValue(keyValueIndex) ++ } ++ ++ if let keyArrayIndex = try matchKeyArray( ++ in: tables[tableIndex].arrays, key: key, keyHash: keyHash) ++ { ++ return .array(keyArrayIndex) ++ } ++ ++ if let keyTableIndex = try matchKeyTable( ++ in: tables[tableIndex].tables, key: key, keyHash: keyHash) ++ { ++ return .table(keyTableIndex) ++ } ++ ++ return nil ++ } ++ ++ @inline(__always) ++ func lookupTable(in tableIndex: Int, keyed: Bool, key: borrowing String, keyHash: Int) throws ++ -> Int? ++ { ++ if keyed { ++ if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { ++ return nil ++ } ++ return try matchKeyTable(in: keyTables[tableIndex].table.tables, key: key, keyHash: keyHash) ++ } ++ if !tables[tableIndex].mightContainKeyHash(keyHash) { ++ return nil ++ } ++ return try matchKeyTable(in: tables[tableIndex].tables, key: key, keyHash: keyHash) ++ } ++ ++ @inline(__always) ++ func lookupArray(in tableIndex: Int, keyed: Bool, key: borrowing String, keyHash: Int) throws ++ -> Int? ++ { ++ if keyed { ++ if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { ++ return nil ++ } ++ return try matchKeyArray(in: keyTables[tableIndex].table.arrays, key: key, keyHash: keyHash) ++ } ++ if !tables[tableIndex].mightContainKeyHash(keyHash) { ++ return nil ++ } ++ return try matchKeyArray(in: tables[tableIndex].arrays, key: key, keyHash: keyHash) ++ } ++ ++ @inline(__always) ++ func lookupArray( ++ in tableIndex: Int, ++ keyed: Bool, ++ bytes: UnsafeBufferPointer, ++ token: Token, ++ keyHash: Int ++ ) throws -> Int? { ++ if keyed { ++ if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { ++ return nil ++ } ++ return try matchKeyArray( ++ in: keyTables[tableIndex].table.arrays, ++ bytes: bytes, ++ token: token, ++ keyHash: keyHash ++ ) ++ } ++ if !tables[tableIndex].mightContainKeyHash(keyHash) { ++ return nil ++ } ++ return try matchKeyArray( ++ in: tables[tableIndex].arrays, ++ bytes: bytes, ++ token: token, ++ keyHash: keyHash ++ ) ++ } ++ ++ mutating func advanceTablePathSegment( ++ tableIndex: inout Int, ++ isKeyed: inout Bool, ++ key: String, ++ keyHash: Int ++ ) throws { ++ switch try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) { ++ case .table(let index): ++ tableIndex = index ++ isKeyed = true ++ case .array(let arrayIndex): ++ let array = keyArrays[arrayIndex].array ++ guard case .table = array.kind else { ++ throw TOMLError( ++ .syntax(lineNumber: token.lineNumber, message: "array element is not a table")) ++ } ++ ++ if array.elements.isEmpty { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "empty array")) ++ } ++ ++ guard case .table(_, let index) = array.elements.last else { ++ throw TOMLError( ++ .syntax(lineNumber: token.lineNumber, message: "array element is not a table")) ++ } ++ ++ tableIndex = index ++ isKeyed = false ++ case .keyValue: ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "key-value already exists")) +@@ -2077,3 +2633,46 @@ +- break +- } +- return packed ++ let newTableAddress = keyTables.count ++ var newTable = InternalTOMLTable() ++ newTable.implicit = true ++ newTable.definedByDottedKey = false ++ try budget.node(depth: depth) ++ keyTables.append( ++ KeyTablePair( ++ key: key, keyHash: keyHash, sourcePosition: token.text.lowerBound, table: newTable)) ++ ++ if isKeyed { ++ if keyTables[tableIndex].table.tables.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ keyTables[tableIndex].table.tables.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ keyTables[tableIndex].table.tables.append(newTableAddress) ++ keyTables[tableIndex].table.recordKeyHash(keyHash) ++ } else { ++ if tables[tableIndex].tables.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ tables[tableIndex].tables.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ tables[tableIndex].tables.append(newTableAddress) ++ tables[tableIndex].recordKeyHash(keyHash) ++ } ++ tableIndex = newTableAddress ++ isKeyed = true ++ } ++ } ++ ++ mutating func walkTablePath(startTable: Int = 0, startKeyed: Bool = false) throws { ++ var tableIndex = startTable ++ var isKeyed = startKeyed ++ for (key, keyHash) in tablePath { ++ try budget.step() ++ try advanceTablePathSegment( ++ tableIndex: &tableIndex, ++ isKeyed: &isKeyed, ++ key: key, ++ keyHash: keyHash ++ ) ++ } ++ currentTable = tableIndex ++ currentTableIsKeyed = isKeyed ++ } +@@ -2081,316 +2679,0 @@ +- +-@inline(__always) +-private func makeString(bytes: UnsafeBufferPointer, range: Range) -> String { +- let count = range.upperBound - range.lowerBound +- if count == 0 { +- return "" +- } +- let start = bytes.baseAddress!.advanced(by: range.lowerBound) +- return String(decoding: UnsafeBufferPointer(start: start, count: count), as: UTF8.self) +-} +- +-extension Parser { +- @inline(__always) +- func matchKeyValue(in indices: borrowing [Int], key: borrowing String, keyHash: Int) -> Int? { +- if indices.isEmpty { +- return nil +- } +- return keyValues.withUnsafeBufferPointer { keyValueBuffer -> Int? in +- guard let keyValueBase = keyValueBuffer.baseAddress else { +- return nil +- } +- let indexCount = indices.count +- var i = 0 +- while i < indexCount { +- let keyValueIndex = indices[i] +- let keyValuePair = keyValueBase.advanced(by: keyValueIndex).pointee +- if keyValuePair.keyHash == keyHash, keyValuePair.key == key { +- return keyValueIndex +- } +- i += 1 +- } +- return nil +- } +- } +- +- @inline(__always) +- func matchKeyArray(in indices: borrowing [Int], key: borrowing String, keyHash: Int) -> Int? { +- if indices.isEmpty { +- return nil +- } +- return keyArrays.withUnsafeBufferPointer { keyArrayBuffer -> Int? in +- guard let keyArrayBase = keyArrayBuffer.baseAddress else { +- return nil +- } +- let indexCount = indices.count +- var i = 0 +- while i < indexCount { +- let keyArrayIndex = indices[i] +- let keyArrayPair = keyArrayBase.advanced(by: keyArrayIndex).pointee +- if keyArrayPair.keyHash == keyHash, keyArrayPair.key == key { +- return keyArrayIndex +- } +- i += 1 +- } +- return nil +- } +- } +- +- @inline(__always) +- func keyMatchesToken(bytes: UnsafeBufferPointer, token: Token, key: borrowing String) -> Bool { +- let range = token.text +- let count = range.upperBound - range.lowerBound +- +- if let matches = key.utf8.withContiguousStorageIfAvailable({ keyBuffer -> Bool in +- if keyBuffer.count != count { +- return false +- } +- +- var keyIndex = 0 +- var byteIndex = range.lowerBound +- while keyIndex < count { +- if keyBuffer[keyIndex] != bytes[byteIndex] { +- return false +- } +- keyIndex += 1 +- byteIndex += 1 +- } +- return true +- }) { +- return matches +- } +- +- var index = range.lowerBound +- for byte in key.utf8 { +- if index >= range.upperBound || bytes[index] != byte { +- return false +- } +- index += 1 +- } +- return index == range.upperBound +- } +- +- @inline(__always) +- func matchKeyArray( +- in indices: borrowing [Int], +- bytes: UnsafeBufferPointer, +- token: Token, +- keyHash: Int +- ) -> Int? { +- if indices.isEmpty { +- return nil +- } +- return keyArrays.withUnsafeBufferPointer { keyArrayBuffer -> Int? in +- guard let keyArrayBase = keyArrayBuffer.baseAddress else { +- return nil +- } +- let indexCount = indices.count +- var i = 0 +- while i < indexCount { +- let keyArrayIndex = indices[i] +- let keyArrayPair = keyArrayBase.advanced(by: keyArrayIndex).pointee +- if keyArrayPair.keyHash == keyHash, +- keyMatchesToken(bytes: bytes, token: token, key: keyArrayPair.key) +- { +- return keyArrayIndex +- } +- i += 1 +- } +- return nil +- } +- } +- +- @inline(__always) +- func matchKeyTable(in indices: borrowing [Int], key: borrowing String, keyHash: Int) -> Int? { +- if indices.isEmpty { +- return nil +- } +- return keyTables.withUnsafeBufferPointer { keyTableBuffer -> Int? in +- guard let keyTableBase = keyTableBuffer.baseAddress else { +- return nil +- } +- let indexCount = indices.count +- var i = 0 +- while i < indexCount { +- let keyTableIndex = indices[i] +- let keyTablePair = keyTableBase.advanced(by: keyTableIndex).pointee +- if keyTablePair.keyHash == keyHash, keyTablePair.key == key { +- return keyTableIndex +- } +- i += 1 +- } +- return nil +- } +- } +- +- @inline(__always) +- func tableValue( +- tableIndex: Int, +- keyed: Bool, +- key: borrowing String, +- keyHash: Int +- ) -> InternalTOMLTable.Value? { +- if keyed { +- if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { +- return nil +- } +- } else if !tables[tableIndex].mightContainKeyHash(keyHash) { +- return nil +- } +- +- if keyed { +- if let keyValueIndex = matchKeyValue(in: keyTables[tableIndex].table.keyValues, key: key, keyHash: keyHash) { +- return .keyValue(keyValueIndex) +- } +- +- if let keyArrayIndex = matchKeyArray(in: keyTables[tableIndex].table.arrays, key: key, keyHash: keyHash) { +- return .array(keyArrayIndex) +- } +- +- if let keyTableIndex = matchKeyTable(in: keyTables[tableIndex].table.tables, key: key, keyHash: keyHash) { +- return .table(keyTableIndex) +- } +- return nil +- } +- +- if let keyValueIndex = matchKeyValue(in: tables[tableIndex].keyValues, key: key, keyHash: keyHash) { +- return .keyValue(keyValueIndex) +- } +- +- if let keyArrayIndex = matchKeyArray(in: tables[tableIndex].arrays, key: key, keyHash: keyHash) { +- return .array(keyArrayIndex) +- } +- +- if let keyTableIndex = matchKeyTable(in: tables[tableIndex].tables, key: key, keyHash: keyHash) { +- return .table(keyTableIndex) +- } +- +- return nil +- } +- +- @inline(__always) +- func lookupTable(in tableIndex: Int, keyed: Bool, key: borrowing String, keyHash: Int) -> Int? { +- if keyed { +- if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { +- return nil +- } +- return matchKeyTable(in: keyTables[tableIndex].table.tables, key: key, keyHash: keyHash) +- } +- if !tables[tableIndex].mightContainKeyHash(keyHash) { +- return nil +- } +- return matchKeyTable(in: tables[tableIndex].tables, key: key, keyHash: keyHash) +- } +- +- @inline(__always) +- func lookupArray(in tableIndex: Int, keyed: Bool, key: borrowing String, keyHash: Int) -> Int? { +- if keyed { +- if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { +- return nil +- } +- return matchKeyArray(in: keyTables[tableIndex].table.arrays, key: key, keyHash: keyHash) +- } +- if !tables[tableIndex].mightContainKeyHash(keyHash) { +- return nil +- } +- return matchKeyArray(in: tables[tableIndex].arrays, key: key, keyHash: keyHash) +- } +- +- @inline(__always) +- func lookupArray( +- in tableIndex: Int, +- keyed: Bool, +- bytes: UnsafeBufferPointer, +- token: Token, +- keyHash: Int +- ) -> Int? { +- if keyed { +- if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { +- return nil +- } +- return matchKeyArray( +- in: keyTables[tableIndex].table.arrays, +- bytes: bytes, +- token: token, +- keyHash: keyHash +- ) +- } +- if !tables[tableIndex].mightContainKeyHash(keyHash) { +- return nil +- } +- return matchKeyArray( +- in: tables[tableIndex].arrays, +- bytes: bytes, +- token: token, +- keyHash: keyHash +- ) +- } +- +- mutating func advanceTablePathSegment( +- tableIndex: inout Int, +- isKeyed: inout Bool, +- key: String, +- keyHash: Int +- ) throws(TOMLError) { +- switch tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) { +- case let .table(index): +- tableIndex = index +- isKeyed = true +- case let .array(arrayIndex): +- let array = keyArrays[arrayIndex].array +- guard case .table = array.kind else { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "array element is not a table")) +- } +- +- if array.elements.isEmpty { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "empty array")) +- } +- +- guard case let .table(_, index) = array.elements.last else { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "array element is not a table")) +- } +- +- tableIndex = index +- isKeyed = false +- case .keyValue: +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "key-value already exists")) +- default: +- let newTableAddress = keyTables.count +- var newTable = InternalTOMLTable() +- newTable.implicit = true +- newTable.definedByDottedKey = false +- keyTables.append(KeyTablePair(key: key, keyHash: keyHash, table: newTable)) +- +- if isKeyed { +- if keyTables[tableIndex].table.tables.isEmpty { +- keyTables[tableIndex].table.tables.reserveCapacity(8) +- } +- keyTables[tableIndex].table.tables.append(newTableAddress) +- keyTables[tableIndex].table.recordKeyHash(keyHash) +- } else { +- if tables[tableIndex].tables.isEmpty { +- tables[tableIndex].tables.reserveCapacity(8) +- } +- tables[tableIndex].tables.append(newTableAddress) +- tables[tableIndex].recordKeyHash(keyHash) +- } +- tableIndex = newTableAddress +- isKeyed = true +- } +- } +- +- mutating func walkTablePath(startTable: Int = 0, startKeyed: Bool = false) throws(TOMLError) { +- var tableIndex = startTable +- var isKeyed = startKeyed +- for (key, keyHash) in tablePath { +- try advanceTablePathSegment( +- tableIndex: &tableIndex, +- isKeyed: &isKeyed, +- key: key, +- keyHash: keyHash +- ) +- } +- currentTable = tableIndex +- currentTableIsKeyed = isKeyed +- } +-} +--- Sources/TOMLDecoder/Parsing/Parser+Finish.swift ++++ Sources/TOMLSemantics/Parsing/Parser+Finish.swift +@@ -2,6 +2,6 @@ +- consuming func finish(source: String) -> TOMLDocument { +- var tables: [InternalTOMLTable] = [] +- var arrays: [InternalTOMLArray] = [] +- var keyTables: [KeyTablePair] = [] +- var keyArrays: [KeyArrayPair] = [] +- var keyValues: [KeyValuePair] = [] ++ consuming func finish(source: String) -> TOMLDocument { ++ var tables: [InternalTOMLTable] = [] ++ var arrays: [InternalTOMLArray] = [] ++ var keyTables: [KeyTablePair] = [] ++ var keyArrays: [KeyArrayPair] = [] ++ var keyValues: [KeyValuePair] = [] +@@ -9,5 +9,5 @@ +- swap(&tables, &self.tables) +- swap(&arrays, &self.arrays) +- swap(&keyTables, &self.keyTables) +- swap(&keyArrays, &self.keyArrays) +- swap(&keyValues, &self.keyValues) ++ swap(&tables, &self.tables) ++ swap(&arrays, &self.arrays) ++ swap(&keyTables, &self.keyTables) ++ swap(&keyArrays, &self.keyArrays) ++ swap(&keyValues, &self.keyValues) +@@ -15,9 +15,9 @@ +- return TOMLDocument( +- source: source, +- tables: tables, +- arrays: arrays, +- keyTables: keyTables, +- keyArrays: keyArrays, +- keyValues: keyValues +- ) +- } ++ return TOMLDocument( ++ source: source, ++ tables: tables, ++ arrays: arrays, ++ keyTables: keyTables, ++ keyArrays: keyArrays, ++ keyValues: keyValues ++ ) ++ } +--- Sources/TOMLDecoder/Parsing/Token.swift ++++ Sources/TOMLSemantics/Parsing/Token.swift +@@ -2,13 +2,13 @@ +- enum Kind: UInt8 { +- case dot +- case comma +- case equal +- case lbrace +- case rbrace +- case newline +- case lbracket +- case rbracket +- case string +- case bareKey +- case eof +- } ++ enum Kind: UInt8 { ++ case dot ++ case comma ++ case equal ++ case lbrace ++ case rbrace ++ case newline ++ case lbracket ++ case rbracket ++ case string ++ case bareKey ++ case eof ++ } +@@ -16,3 +16 @@ +- let kind: Kind +- let lineNumber: Int +- let text: Range ++ var budget: SemanticBudget! = nil +@@ -20 +18,9 @@ +- static let empty = Token(kind: .newline, lineNumber: 1, text: 0 ..< 0) ++ let kind: Kind ++ let lineNumber: Int ++ let text: Range ++ ++ static func == (lhs: Token, rhs: Token) -> Bool { ++ lhs.kind == rhs.kind && lhs.lineNumber == rhs.lineNumber && lhs.text == rhs.text ++ } ++ ++ static var empty: Token { Token(kind: .newline, lineNumber: 1, text: 0..<0) } +@@ -22,89 +27,0 @@ +- +-extension Token { +- func unpackBool(source: String, context: TOMLKey) throws(TOMLError) -> Bool { +- do { +- return try (source.utf8.withContiguousStorageIfAvailable { try unpackBool(bytes: $0, context: context) })! +- } catch { +- throw error as! TOMLError +- } +- } +- +- func unpackFloat(source: String, context: TOMLKey) throws(TOMLError) -> Double { +- do { +- return try (source.utf8.withContiguousStorageIfAvailable { try unpackFloat(bytes: $0, context: context) })! +- } catch { +- throw error as! TOMLError +- } +- } +- +- func unpackString(source: String, context: TOMLKey) throws(TOMLError) -> String { +- do { +- return try (source.utf8.withContiguousStorageIfAvailable { try unpackString(bytes: $0, context: context) })! +- } catch { +- throw error as! TOMLError +- } +- } +- +- func unpackInteger(source: String, context: TOMLKey) throws(TOMLError) -> Int64 { +- do { +- return try (source.utf8.withContiguousStorageIfAvailable { try unpackInteger(bytes: $0, context: context) })! +- } catch { +- throw error as! TOMLError +- } +- } +- +- func unpackDateTime(source: String, context: TOMLKey) throws(TOMLError) -> DateTimeComponents { +- do { +- return try (source.utf8.withContiguousStorageIfAvailable { try unpackDateTime(bytes: $0, context: context) })! +- } catch { +- throw error as! TOMLError +- } +- } +- +- func unpackOffsetDateTime(source: String, context: TOMLKey) throws(TOMLError) -> OffsetDateTime { +- let datetime: DateTimeComponents +- do { +- datetime = try (source.utf8.withContiguousStorageIfAvailable { try unpackDateTime(bytes: $0, context: context) })! +- } catch { +- throw error as! TOMLError +- } +- switch (datetime.date, datetime.time, datetime.offset) { +- case let (.some(date), .some(time), .some(offset)): +- return OffsetDateTime(date: date, time: time, offset: offset, features: datetime.features) +- default: +- throw TOMLError(.typeMismatch(context: context, lineNumber: lineNumber, expected: "offset date-time")) +- } +- } +- +- func unpackLocalDateTime(source: String, context: TOMLKey, exactMatch: Bool = true) throws(TOMLError) -> LocalDateTime { +- let components = try unpackDateTime(source: source, context: context) +- guard let localDateTime = components.localDateTime(exactMatch: exactMatch) else { +- throw TOMLError(.typeMismatch(context: context, lineNumber: lineNumber, expected: "local date-time")) +- } +- return localDateTime +- } +- +- func unpackLocalDate(source: String, context: TOMLKey, exactMatch: Bool = true) throws(TOMLError) -> LocalDate { +- let components = try unpackDateTime(source: source, context: context) +- guard let localDate = components.localDate(exactMatch: exactMatch) else { +- throw TOMLError(.typeMismatch(context: context, lineNumber: lineNumber, expected: "local date")) +- } +- return localDate +- } +- +- func unpackLocalTime(source: String, context: TOMLKey, exactMatch: Bool = true) throws(TOMLError) -> LocalTime { +- let components = try unpackDateTime(source: source, context: context) +- guard let localTime = components.localTime(exactMatch: exactMatch) else { +- throw TOMLError(.typeMismatch(context: context, lineNumber: lineNumber, expected: "local time")) +- } +- return localTime +- } +- +- func unpackAnyValue(source: String, context: TOMLKey) throws(TOMLError) -> Any { +- do { +- return try (source.utf8.withContiguousStorageIfAvailable { try unpackAnyValue(bytes: $0, context: context) })! +- } catch { +- throw error as! TOMLError +- } +- } +-} +--- Sources/TOMLDecoder/Parsing/TOMLDocument.swift ++++ Sources/TOMLSemantics/Parsing/TOMLDocument.swift +@@ -3,6 +3,6 @@ +-struct TOMLDocument: Equatable, @unchecked Sendable { +- let tables: [InternalTOMLTable] +- let arrays: [InternalTOMLArray] +- let keyTables: [KeyTablePair] +- let keyArrays: [KeyArrayPair] +- let keyValues: [KeyValuePair] ++struct TOMLDocument { ++ let tables: [InternalTOMLTable] ++ let arrays: [InternalTOMLArray] ++ let keyTables: [KeyTablePair] ++ let keyArrays: [KeyArrayPair] ++ let keyValues: [KeyValuePair] +@@ -10 +10 @@ +- let source: String ++ let source: String +@@ -12,14 +12,41 @@ +- init( +- source: String, +- tables: [InternalTOMLTable], +- arrays: [InternalTOMLArray], +- keyTables: [KeyTablePair], +- keyArrays: [KeyArrayPair], +- keyValues: [KeyValuePair] +- ) { +- self.source = source +- self.tables = tables +- self.arrays = arrays +- self.keyTables = keyTables +- self.keyArrays = keyArrays +- self.keyValues = keyValues ++ init( ++ source: String, ++ tables: [InternalTOMLTable], ++ arrays: [InternalTOMLArray], ++ keyTables: [KeyTablePair], ++ keyArrays: [KeyArrayPair], ++ keyValues: [KeyValuePair] ++ ) { ++ self.source = source ++ self.tables = tables ++ self.arrays = arrays ++ self.keyTables = keyTables ++ self.keyArrays = keyArrays ++ self.keyValues = keyValues ++ } ++ ++} ++ ++struct InternalTOMLArray: Equatable { ++ var kind: Kind? ++ var elements: [Element] ++ ++ init(kind: Kind? = nil, elements: [Element] = []) { ++ self.kind = kind ++ self.elements = elements ++ } ++ ++ enum Element: Equatable { ++ case leaf(Token) ++ case array(lineNumber: Int, Int) ++ case table(lineNumber: Int, Int) ++ ++ var lineNumber: Int { ++ switch self { ++ case .leaf(let token): ++ token.lineNumber ++ case .array(let lineNumber, _): ++ lineNumber ++ case .table(let lineNumber, _): ++ lineNumber ++ } +@@ -28,3 +55,13 @@ +- init(source: String, keyTransform: (@Sendable (String) -> String)?) throws(TOMLError) { +- var hasContinousStorage = false +- var parser = Parser(keyTransform: keyTransform) ++ static func == (lhs: Element, rhs: Element) -> Bool { ++ switch (lhs, rhs) { ++ case (.leaf(let lhsToken), .leaf(let rhsToken)): ++ lhsToken == rhsToken ++ case (.array(let lhsLineNumber, let lhsIndex), .array(let rhsLineNumber, let rhsIndex)): ++ lhsLineNumber == rhsLineNumber && lhsIndex == rhsIndex ++ case (.table(let lhsLineNumber, let lhsIndex), .table(let rhsLineNumber, let rhsIndex)): ++ lhsLineNumber == rhsLineNumber && lhsIndex == rhsIndex ++ default: ++ false ++ } ++ } ++ } +@@ -32,20 +69,6 @@ +- do { +- try source.utf8.withContiguousStorageIfAvailable { +- hasContinousStorage = true +- try parser.parse(bytes: $0) +- } +- } catch { +- throw error as! TOMLError +- } +- +- if !hasContinousStorage { +- var source = source +- do { +- try source.withUTF8 { try parser.parse(bytes: $0) } +- } catch { +- throw error as! TOMLError +- } +- } +- +- self = parser.finish(source: source) +- } ++ enum Kind: UInt8 { ++ case value ++ case array ++ case table ++ case mixed ++ } +@@ -54,45 +77,5 @@ +-struct InternalTOMLArray: Equatable, Sendable { +- var kind: Kind? +- var elements: [Element] +- +- init(kind: Kind? = nil, elements: [Element] = []) { +- self.kind = kind +- self.elements = elements +- } +- +- enum Element: Equatable { +- case leaf(Token) +- case array(lineNumber: Int, Int) +- case table(lineNumber: Int, Int) +- +- var lineNumber: Int { +- switch self { +- case let .leaf(token): +- token.lineNumber +- case let .array(lineNumber, _): +- lineNumber +- case let .table(lineNumber, _): +- lineNumber +- } +- } +- +- static func == (lhs: Element, rhs: Element) -> Bool { +- switch (lhs, rhs) { +- case let (.leaf(lhsToken), .leaf(rhsToken)): +- lhsToken == rhsToken +- case let (.array(lhsLineNumber, lhsIndex), .array(rhsLineNumber, rhsIndex)): +- lhsLineNumber == rhsLineNumber && lhsIndex == rhsIndex +- case let (.table(lhsLineNumber, lhsIndex), .table(rhsLineNumber, rhsIndex)): +- lhsLineNumber == rhsLineNumber && lhsIndex == rhsIndex +- default: +- false +- } +- } +- } +- +- enum Kind: UInt8 { +- case value +- case array +- case table +- case mixed +- } ++struct KeyTablePair { ++ let key: String ++ let keyHash: Int ++ let sourcePosition: Int ++ var table: InternalTOMLTable +@@ -101,4 +84,5 @@ +-struct KeyTablePair: Equatable { +- let key: String +- let keyHash: Int +- var table: InternalTOMLTable ++struct KeyArrayPair { ++ let key: String ++ let keyHash: Int ++ let sourcePosition: Int ++ var array: InternalTOMLArray +@@ -107,4 +91,5 @@ +-struct KeyArrayPair: Equatable { +- let key: String +- let keyHash: Int +- var array: InternalTOMLArray ++struct KeyValuePair { ++ let key: String ++ let keyHash: Int ++ let sourcePosition: Int ++ var value: Token +@@ -113,5 +98,8 @@ +-struct KeyValuePair: Equatable { +- let key: String +- let keyHash: Int +- var value: Token +-} ++struct InternalTOMLTable: Equatable { ++ var implicit: Bool = false ++ var readOnly: Bool = false ++ var definedByDottedKey: Bool = false ++ var keyHashBloom: UInt64 = 0 ++ var keyValues: [Int] = [] ++ var arrays: [Int] = [] ++ var tables: [Int] = [] +@@ -119,8 +107,4 @@ +-struct InternalTOMLTable: Equatable, Sendable { +- var implicit: Bool = false +- var readOnly: Bool = false +- var definedByDottedKey: Bool = false +- var keyHashBloom: UInt64 = 0 +- var keyValues: [Int] = [] +- var arrays: [Int] = [] +- var tables: [Int] = [] ++ @inline(__always) ++ mutating func recordKeyHash(_ keyHash: Int) { ++ keyHashBloom |= keyHashBloomMask(keyHash) ++ } +@@ -128,4 +112,5 @@ +- @inline(__always) +- mutating func recordKeyHash(_ keyHash: Int) { +- keyHashBloom |= keyHashBloomMask(keyHash) +- } ++ @inline(__always) ++ func mightContainKeyHash(_ keyHash: Int) -> Bool { ++ let mask = keyHashBloomMask(keyHash) ++ return (keyHashBloom & mask) == mask ++ } +@@ -133,48 +118,5 @@ +- @inline(__always) +- func mightContainKeyHash(_ keyHash: Int) -> Bool { +- let mask = keyHashBloomMask(keyHash) +- return (keyHashBloom & mask) == mask +- } +- +- func allKeys(_ document: TOMLDocument) -> [String] { +- var keys = [String]() +- for kv in keyValues { +- keys.append(document.keyValues[kv].key) +- } +- for arr in arrays { +- keys.append(document.keyArrays[arr].key) +- } +- for table in tables { +- keys.append(document.keyTables[table].key) +- } +- return keys +- } +- +- func contains(source: TOMLDocument, key: String) -> Bool { +- let keyHash = fastKeyHash(key) +- for kv in keyValues { +- let pair = source.keyValues[kv] +- if pair.keyHash == keyHash, pair.key == key { +- return true +- } +- } +- for arr in arrays { +- let arrayPair = source.keyArrays[arr] +- if arrayPair.keyHash == keyHash, arrayPair.key == key { +- return true +- } +- } +- for table in tables { +- let tablePair = source.keyTables[table] +- if tablePair.keyHash == keyHash, tablePair.key == key { +- return true +- } +- } +- return false +- } +- +- enum Value { +- case keyValue(Int) +- case array(Int) +- case table(Int) +- } ++ enum Value { ++ case keyValue(Int) ++ case array(Int) ++ case table(Int) ++ } +@@ -185,4 +127,4 @@ +- let raw = UInt(bitPattern: keyHash) +- let bit0 = UInt64(1) << UInt64(raw & 63) +- let bit1 = UInt64(1) << UInt64((raw >> 6) & 63) +- return bit0 | bit1 ++ let raw = UInt(bitPattern: keyHash) ++ let bit0 = UInt64(1) << UInt64(raw & 63) ++ let bit1 = UInt64(1) << UInt64((raw >> 6) & 63) ++ return bit0 | bit1 +@@ -192,4 +134,4 @@ +- let date: LocalDate? +- let time: LocalTime? +- let offset: Int16? +- let features: OffsetDateTime.Features ++ let date: LocalDate? ++ let time: LocalTime? ++ let offset: Int16? ++ let features: OffsetDateTime.Features +@@ -197,10 +139,9 @@ +- @inline(__always) +- func localDate(exactMatch: Bool = true) -> LocalDate? { +- switch (date, time, offset) { +- case let (.some(date), .none, .none): +- date +- case let (.some(date), _, _) where !exactMatch: +- date +- default: +- nil +- } ++ @inline(__always) ++ func localDate(exactMatch: Bool = true) -> LocalDate? { ++ switch (date, time, offset) { ++ case (.some(let date), .none, .none): ++ date ++ case (.some(let date), _, _) where !exactMatch: ++ date ++ default: ++ nil +@@ -207,0 +149 @@ ++ } +@@ -209,10 +151,9 @@ +- @inline(__always) +- func localTime(exactMatch: Bool = true) -> LocalTime? { +- switch (date, time, offset) { +- case let (.none, .some(time), .none): +- time +- case let (_, .some(time), _) where !exactMatch: +- time +- default: +- nil +- } ++ @inline(__always) ++ func localTime(exactMatch: Bool = true) -> LocalTime? { ++ switch (date, time, offset) { ++ case (.none, .some(let time), .none): ++ time ++ case (_, .some(let time), _) where !exactMatch: ++ time ++ default: ++ nil +@@ -219,0 +161 @@ ++ } +@@ -221,10 +163,9 @@ +- @inline(__always) +- func localDateTime(exactMatch: Bool = true) -> LocalDateTime? { +- switch (date, time, offset) { +- case let (.some(date), .some(time), .none): +- LocalDateTime(date: date, time: time) +- case let (.some(date), .some(time), .some) where !exactMatch: +- LocalDateTime(date: date, time: time) +- default: +- nil +- } ++ @inline(__always) ++ func localDateTime(exactMatch: Bool = true) -> LocalDateTime? { ++ switch (date, time, offset) { ++ case (.some(let date), .some(let time), .none): ++ LocalDateTime(date: date, time: time) ++ case (.some(let date), .some(let time), .some) where !exactMatch: ++ LocalDateTime(date: date, time: time) ++ default: ++ nil +@@ -232,41 +173 @@ +-} +- +-extension InternalTOMLTable { +- func dictionary(source: TOMLDocument) throws(TOMLError) -> [String: Any] { +- var result = [String: Any]() +- for tableIndex in tables { +- let tablePair = source.keyTables[tableIndex] +- result[tablePair.key] = try tablePair.table.dictionary(source: source) +- } +- +- for arrayIndex in arrays { +- let arrayPair = source.keyArrays[arrayIndex] +- result[arrayPair.key] = try arrayPair.array.array(source: source) +- } +- +- for kvIndex in keyValues { +- let pair = source.keyValues[kvIndex] +- result[pair.key] = try pair.value.unpackAnyValue(source: source.source, context: .string(pair.key)) +- } +- +- return result +- } +-} +- +-extension InternalTOMLArray { +- func array(source: TOMLDocument) throws(TOMLError) -> [Any] { +- var result = [Any]() +- +- for (index, element) in zip(0..., elements) { +- switch element { +- case let .array(_, arrayIndex): +- try result.append(source.arrays[arrayIndex].array(source: source)) +- case let .table(_, tableIndex): +- try result.append(source.tables[tableIndex].dictionary(source: source)) +- case let .leaf(token): +- try result.append(token.unpackAnyValue(source: source.source, context: .int(index))) +- } +- } +- +- return result +- } ++ } +@@ -276,4 +177,4 @@ +- @inline(__always) +- func table(at index: Int, keyed: Bool) -> InternalTOMLTable { +- keyed ? keyTables[index].table : tables[index] +- } ++ @inline(__always) ++ func table(at index: Int, keyed: Bool) -> InternalTOMLTable { ++ keyed ? keyTables[index].table : tables[index] ++ } +@@ -281,4 +182,4 @@ +- @inline(__always) +- func array(at index: Int, keyed: Bool) -> InternalTOMLArray { +- keyed ? keyArrays[index].array : arrays[index] +- } ++ @inline(__always) ++ func array(at index: Int, keyed: Bool) -> InternalTOMLArray { ++ keyed ? keyArrays[index].array : arrays[index] ++ } +--- Sources/TOMLDecoder/Parsing/Constants.swift ++++ Sources/TOMLSemantics/Parsing/Constants.swift +@@ -2,22 +2,22 @@ +- static let escape: UTF8.CodeUnit = 27 +- static let equal: UTF8.CodeUnit = 61 +- static let comma: UTF8.CodeUnit = 44 +- static let lbrace: UTF8.CodeUnit = 123 +- static let rbrace: UTF8.CodeUnit = 125 +- static let lbracket: UTF8.CodeUnit = 91 +- static let rbracket: UTF8.CodeUnit = 93 +- static let pound: UTF8.CodeUnit = 35 +- static let backslash: UTF8.CodeUnit = 92 +- static let backspace: UTF8.CodeUnit = 8 +- static let cr: UTF8.CodeUnit = 13 +- static let colon: UTF8.CodeUnit = 58 +- static let dot: UTF8.CodeUnit = 46 +- static let doubleQuote: UTF8.CodeUnit = 34 +- static let formfeed: UTF8.CodeUnit = 12 +- static let lf: UTF8.CodeUnit = 10 +- static let minus: UTF8.CodeUnit = 45 +- static let plus: UTF8.CodeUnit = 43 +- static let singleQuote: UTF8.CodeUnit = 39 +- static let space: UTF8.CodeUnit = 32 +- static let tab: UTF8.CodeUnit = 9 +- static let underscore: UTF8.CodeUnit = 95 ++ static let escape: UTF8.CodeUnit = 27 ++ static let equal: UTF8.CodeUnit = 61 ++ static let comma: UTF8.CodeUnit = 44 ++ static let lbrace: UTF8.CodeUnit = 123 ++ static let rbrace: UTF8.CodeUnit = 125 ++ static let lbracket: UTF8.CodeUnit = 91 ++ static let rbracket: UTF8.CodeUnit = 93 ++ static let pound: UTF8.CodeUnit = 35 ++ static let backslash: UTF8.CodeUnit = 92 ++ static let backspace: UTF8.CodeUnit = 8 ++ static let cr: UTF8.CodeUnit = 13 ++ static let colon: UTF8.CodeUnit = 58 ++ static let dot: UTF8.CodeUnit = 46 ++ static let doubleQuote: UTF8.CodeUnit = 34 ++ static let formfeed: UTF8.CodeUnit = 12 ++ static let lf: UTF8.CodeUnit = 10 ++ static let minus: UTF8.CodeUnit = 45 ++ static let plus: UTF8.CodeUnit = 43 ++ static let singleQuote: UTF8.CodeUnit = 39 ++ static let space: UTF8.CodeUnit = 32 ++ static let tab: UTF8.CodeUnit = 9 ++ static let underscore: UTF8.CodeUnit = 95 +@@ -25,4 +25,4 @@ +- static let number0: UTF8.CodeUnit = 48 +- static let number1: UTF8.CodeUnit = 49 +- static let number7: UTF8.CodeUnit = 55 +- static let number9: UTF8.CodeUnit = 57 ++ static let number0: UTF8.CodeUnit = 48 ++ static let number1: UTF8.CodeUnit = 49 ++ static let number7: UTF8.CodeUnit = 55 ++ static let number9: UTF8.CodeUnit = 57 +@@ -30,20 +30,20 @@ +- static let lowerA: UTF8.CodeUnit = 97 +- static let lowerB: UTF8.CodeUnit = 98 +- static let lowerI: UTF8.CodeUnit = 105 +- static let lowerE: UTF8.CodeUnit = 101 +- static let lowerF: UTF8.CodeUnit = 102 +- static let lowerL: UTF8.CodeUnit = 108 +- static let lowerS: UTF8.CodeUnit = 115 +- static let lowerN: UTF8.CodeUnit = 110 +- static let lowerO: UTF8.CodeUnit = 111 +- static let lowerR: UTF8.CodeUnit = 114 +- static let lowerT: UTF8.CodeUnit = 116 +- static let lowerU: UTF8.CodeUnit = 117 +- static let lowerX: UTF8.CodeUnit = 120 +- static let lowerZ: UTF8.CodeUnit = 122 +- static let upperA: UTF8.CodeUnit = 65 +- static let upperE: UTF8.CodeUnit = 69 +- static let upperF: UTF8.CodeUnit = 70 +- static let upperT: UTF8.CodeUnit = 84 +- static let upperU: UTF8.CodeUnit = 85 +- static let upperZ: UTF8.CodeUnit = 90 ++ static let lowerA: UTF8.CodeUnit = 97 ++ static let lowerB: UTF8.CodeUnit = 98 ++ static let lowerI: UTF8.CodeUnit = 105 ++ static let lowerE: UTF8.CodeUnit = 101 ++ static let lowerF: UTF8.CodeUnit = 102 ++ static let lowerL: UTF8.CodeUnit = 108 ++ static let lowerS: UTF8.CodeUnit = 115 ++ static let lowerN: UTF8.CodeUnit = 110 ++ static let lowerO: UTF8.CodeUnit = 111 ++ static let lowerR: UTF8.CodeUnit = 114 ++ static let lowerT: UTF8.CodeUnit = 116 ++ static let lowerU: UTF8.CodeUnit = 117 ++ static let lowerX: UTF8.CodeUnit = 120 ++ static let lowerZ: UTF8.CodeUnit = 122 ++ static let upperA: UTF8.CodeUnit = 65 ++ static let upperE: UTF8.CodeUnit = 69 ++ static let upperF: UTF8.CodeUnit = 70 ++ static let upperT: UTF8.CodeUnit = 84 ++ static let upperU: UTF8.CodeUnit = 85 ++ static let upperZ: UTF8.CodeUnit = 90 +@@ -51,16 +51,15 @@ +- nonisolated(unsafe) static let isBareKeyChar: UnsafePointer = { +- let ptr = UnsafeMutablePointer.allocate(capacity: 256) +- ptr.initialize(repeating: false, count: 256) +- for i in 0 ..< 256 { +- let ch = UTF8.CodeUnit(i) +- if (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerZ) || +- (ch >= CodeUnits.upperA && ch <= CodeUnits.upperZ) || +- (ch >= CodeUnits.number0 && ch <= CodeUnits.number9) || +- ch == CodeUnits.underscore || +- ch == CodeUnits.minus +- { +- ptr[i] = true +- } +- } +- return UnsafePointer(ptr) +- }() ++ nonisolated(unsafe) static let isBareKeyChar: UnsafePointer = { ++ let ptr = UnsafeMutablePointer.allocate(capacity: 256) ++ ptr.initialize(repeating: false, count: 256) ++ for i in 0..<256 { ++ let ch = UTF8.CodeUnit(i) ++ if (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerZ) ++ || (ch >= CodeUnits.upperA && ch <= CodeUnits.upperZ) ++ || (ch >= CodeUnits.number0 && ch <= CodeUnits.number9) || ch == CodeUnits.underscore ++ || ch == CodeUnits.minus ++ { ++ ptr[i] = true ++ } ++ } ++ return UnsafePointer(ptr) ++ }() +@@ -68,18 +67,15 @@ +- nonisolated(unsafe) static let isValueChar: UnsafePointer = { +- let ptr = UnsafeMutablePointer.allocate(capacity: 256) +- ptr.initialize(repeating: false, count: 256) +- for i in 0 ..< 256 { +- let ch = UTF8.CodeUnit(i) +- if (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerZ) || +- (ch >= CodeUnits.upperA && ch <= CodeUnits.upperZ) || +- (ch >= CodeUnits.number0 && ch <= CodeUnits.number9) || +- ch == CodeUnits.underscore || +- ch == CodeUnits.minus || +- ch == CodeUnits.plus || +- ch == CodeUnits.dot +- { +- ptr[i] = true +- } +- } +- return UnsafePointer(ptr) +- }() ++ nonisolated(unsafe) static let isValueChar: UnsafePointer = { ++ let ptr = UnsafeMutablePointer.allocate(capacity: 256) ++ ptr.initialize(repeating: false, count: 256) ++ for i in 0..<256 { ++ let ch = UTF8.CodeUnit(i) ++ if (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerZ) ++ || (ch >= CodeUnits.upperA && ch <= CodeUnits.upperZ) ++ || (ch >= CodeUnits.number0 && ch <= CodeUnits.number9) || ch == CodeUnits.underscore ++ || ch == CodeUnits.minus || ch == CodeUnits.plus || ch == CodeUnits.dot ++ { ++ ptr[i] = true ++ } ++ } ++ return UnsafePointer(ptr) ++ }() +@@ -87,8 +83,8 @@ +- nonisolated(unsafe) static let isBasicStringBodyChar: UnsafePointer = { +- let ptr = UnsafeMutablePointer.allocate(capacity: 256) +- ptr.initialize(repeating: true, count: 256) +- ptr[Int(CodeUnits.backslash)] = false +- ptr[Int(CodeUnits.doubleQuote)] = false +- ptr[Int(CodeUnits.lf)] = false +- return UnsafePointer(ptr) +- }() ++ nonisolated(unsafe) static let isBasicStringBodyChar: UnsafePointer = { ++ let ptr = UnsafeMutablePointer.allocate(capacity: 256) ++ ptr.initialize(repeating: true, count: 256) ++ ptr[Int(CodeUnits.backslash)] = false ++ ptr[Int(CodeUnits.doubleQuote)] = false ++ ptr[Int(CodeUnits.lf)] = false ++ return UnsafePointer(ptr) ++ }() +@@ -96,3 +92,3 @@ +- static let null: UTF8.CodeUnit = 0x00 +- static let unitSeparator: UTF8.CodeUnit = 0x1F +- static let delete: UTF8.CodeUnit = 0x7F ++ static let null: UTF8.CodeUnit = 0x00 ++ static let unitSeparator: UTF8.CodeUnit = 0x1F ++ static let delete: UTF8.CodeUnit = 0x7F +@@ -102,4 +98,4 @@ +- @_transparent +- var isDecimalDigit: Bool { +- CodeUnits.number0 <= self && self <= CodeUnits.number9 +- } ++ @_transparent ++ var isDecimalDigit: Bool { ++ CodeUnits.number0 <= self && self <= CodeUnits.number9 ++ } +@@ -107,6 +103,6 @@ +- @_transparent +- var isHexDigit: Bool { +- isDecimalDigit +- || CodeUnits.lowerA <= self && self <= CodeUnits.lowerF +- || CodeUnits.upperA <= self && self <= CodeUnits.upperF +- } ++ @_transparent ++ var isHexDigit: Bool { ++ isDecimalDigit ++ || CodeUnits.lowerA <= self && self <= CodeUnits.lowerF ++ || CodeUnits.upperA <= self && self <= CodeUnits.upperF ++ } +--- Sources/TOMLDecoder/DateTime.swift ++++ Sources/TOMLSemantics/DateTime.swift +@@ -23,188 +23,183 @@ +- /// The date component of the offset date-time. +- public var date: LocalDate +- /// The time component of the offset date-time. +- public var time: LocalTime +- /// The offset from UTC in minutes, valid range is [-1440, 1440]. +- public var offset: Int16 +- /// Details about the formatting of the date-time string. +- /// For example, whether the 'T' connecting the date and time is lowercase or uppercase. +- /// Or whether 00:00 offset is represented as 'Z' or '+00:00'. +- public var features: Features +- +- /// Create a new offset date-time from it's members. +- /// +- /// This initializer does not validate the components. +- /// Use ``isValid`` to check if the offset date-time is valid. +- /// +- /// - Parameters: +- /// - date: The date component of the offset date-time. +- /// - time: The time component of the offset date-time. +- /// - offset: The offset from UTC in minutes, valid range is [-1440, 1440]. +- /// - features: Details about the formatting of the date-time string. +- public init(date: LocalDate, time: LocalTime, offset: Int16, features: Features) { +- self.date = date +- self.time = time +- self.offset = offset +- self.features = features +- } +- +- public init(from decoder: any Decoder) throws { +- if let decoder = decoder as? _TOMLDecoder { +- self = try decoder.decode(OffsetDateTime.self) +- } else { +- try self.init(from: decoder) +- } +- } +- +- /// Create a new offset date-time from it's members. +- /// +- /// This initializer validates the components. +- /// A invalid component causes a error to be thrown. +- /// +- /// - Parameters: +- /// - date: The date component of the offset date-time. +- /// - time: The time component of the offset date-time. +- /// - offset: The offset from UTC in minutes, valid range is [-1440, 1440]. +- /// - features: Details about the formatting of the date-time string. +- public init(validatingDate date: LocalDate, time: LocalTime, offset: Int16, features: Features) throws(TOMLError) { +- self.init(date: date, time: time, offset: offset, features: features) +- guard date.isValid else { +- throw TOMLError(.invalidDateTimeComponents("Invalid local date: \(date)")) +- } +- guard time.isValid else { +- throw TOMLError(.invalidDateTimeComponents("Invalid local time: \(time)")) +- } +- guard offsetIsValid else { +- throw TOMLError(.invalidDateTimeComponents("Invalid offset: \(offset)")) +- } +- guard featuresAreValid else { +- throw TOMLError(.invalidDateTimeComponents("Invalid features: \(features)")) +- } +- } +- +- /// Check if the offset date-time is valid. +- public var isValid: Bool { +- guard date.isValid, time.isValid, offsetIsValid else { +- return false +- } +- +- return featuresAreValid +- } +- +- private var offsetIsValid: Bool { +- offset >= -1440 && offset <= 1440 +- } +- +- private var featuresAreValid: Bool { +- if features.contains(.lowercaseZ) || features.contains(.uppercaseZ) { +- return offset == 0 +- } +- +- return true +- } +- +- /// Number of seconds since 2001-01-01T00:00:00Z according to the proleptic Gregorian calendar. +- /// +- /// > Important: This is similar to `Foundation.Date.timeIntervalSinceReferenceDate`. +- /// But for ancient dates, this result may disagree with `Foundation.Date` on how much time has passed. +- /// this is because Foundation's Gregorian calendar follows the Julian calendar up to 1582-10-04, +- /// then the Gregorian calendar after that. According to the TOML specification, +- /// an offset date-time should follow the proleptic Gregorian calendar, +- /// which extends the Gregorian calendar backwards to year 1. +- public var timeIntervalSince2001: Double { +- timeIntervalSince1970 - 978_307_200 +- } +- +- /// Number of seconds since 1970-01-01T00:00:00Z according to the proleptic Gregorian calendar. +- /// +- /// > Important: This is similar to `Foundation.Date.timeIntervalSinceReferenceDate`. +- /// But for ancient dates, this result may disagree with `Foundation.Date` on how much time has passed. +- /// this is because Foundation's Gregorian calendar follows the Julian calendar up to 1582-10-04, +- /// then the Gregorian calendar after that. According to the TOML specification, +- /// an offset date-time should follow the proleptic Gregorian calendar, +- /// which extends the Gregorian calendar backwards to year 1. +- public var timeIntervalSince1970: Double { +- let year = Int64(date.year) +- let month = Int64(date.month) +- let day = Int64(date.day) +- let hour = Int64(time.hour) +- let minute = Int64(time.minute) +- let second = Int64(time.second) +- let nanosecond = Int64(time.nanosecond) +- let offsetInSeconds = Int64(offset) * 60 +- +- var y = year +- if month <= 2 { y -= 1 } +- +- let era = (y >= 0 ? y : y - 399) / 400 +- let yoe = y - era * 400 +- let doy = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + day - 1 +- let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy +- let epochOffset = Int64(719_468) +- let dayCounts = era * 146_097 + doe - epochOffset +- let secondOfDay = hour * 3600 + minute * 60 + second +- let totalSeconds = dayCounts * 86400 + secondOfDay - offsetInSeconds +- +- return Double(totalSeconds) + Double(nanosecond) / 1_000_000_000 +- } +- +- /// The string representation of the offset date-time. +- /// +- /// If a value has precision up to 1 nanosecond, +- /// and it does not require superfluous trailing zeros in its fraction seconds, +- /// this value can be recreated exactly. +- public var description: String { +- let dateString = date.description +- let timeString = time.description +- let separator = if features.contains(.lowercaseT) { +- "t" +- } else if features.contains(.uppercaseT) { +- "T" +- } else { +- " " +- } +- +- if features.contains(.lowercaseZ) { +- return "\(dateString)\(separator)\(timeString)z" +- } else if features.contains(.uppercaseZ) { +- return "\(dateString)\(separator)\(timeString)Z" +- } else { +- let sign = offset >= 0 ? "+" : "-" +- let absOffset = abs(offset) +- let hours = absOffset / 60 +- let minutes = absOffset % 60 +- let hoursStr = hours < 10 ? "0\(hours)" : "\(hours)" +- let minutesStr = minutes < 10 ? "0\(minutes)" : "\(minutes)" +- return "\(dateString)\(separator)\(timeString)\(sign)\(hoursStr):\(minutesStr)" +- } +- } +- +- /// Presentation details for string representation of the offset date-time. +- /// +- /// A parser can preserve features of a offset date-time string with this type. +- /// If neither lowercase nor uppercase 'T' is present, the date-time seprator is a space, which is allowed by TOML. +- public struct Features: OptionSet, Hashable, Sendable, Codable { +- /// The raw value of the features. +- public let rawValue: UInt8 +- +- /// Create a new features from it's raw value. +- public init(rawValue: UInt8) { +- self.rawValue = rawValue +- } +- +- /// Indicates the date-time seprator is a lowercase 't'. +- public static let lowercaseT = Features(rawValue: 1 << 1) +- +- /// Indicates the date-time seprator is a uppercase 'T'. +- public static let uppercaseT = Features(rawValue: 1 << 2) +- +- /// Indicates the offset is represented as a lowercase 'z'. +- /// This should not be present if the offset is non-zero, +- /// or if it's +00:00. +- public static let lowercaseZ = Features(rawValue: 1 << 3) +- +- /// Indicates the offset is represented as a uppercase 'Z'. +- /// This should not be present if the offset is non-zero, +- /// or if it's +00:00. +- public static let uppercaseZ = Features(rawValue: 1 << 4) +- } ++ /// The date component of the offset date-time. ++ public var date: LocalDate ++ /// The time component of the offset date-time. ++ public var time: LocalTime ++ /// The offset from UTC in minutes, valid range is [-1440, 1440]. ++ public var offset: Int16 ++ /// Details about the formatting of the date-time string. ++ /// For example, whether the 'T' connecting the date and time is lowercase or uppercase. ++ /// Or whether 00:00 offset is represented as 'Z' or '+00:00'. ++ public var features: Features ++ ++ /// Create a new offset date-time from it's members. ++ /// ++ /// This initializer does not validate the components. ++ /// Use ``isValid`` to check if the offset date-time is valid. ++ /// ++ /// - Parameters: ++ /// - date: The date component of the offset date-time. ++ /// - time: The time component of the offset date-time. ++ /// - offset: The offset from UTC in minutes, valid range is [-1440, 1440]. ++ /// - features: Details about the formatting of the date-time string. ++ public init(date: LocalDate, time: LocalTime, offset: Int16, features: Features) { ++ self.date = date ++ self.time = time ++ self.offset = offset ++ self.features = features ++ } ++ ++ /// Create a new offset date-time from it's members. ++ /// ++ /// This initializer validates the components. ++ /// A invalid component causes a error to be thrown. ++ /// ++ /// - Parameters: ++ /// - date: The date component of the offset date-time. ++ /// - time: The time component of the offset date-time. ++ /// - offset: The offset from UTC in minutes, valid range is [-1440, 1440]. ++ /// - features: Details about the formatting of the date-time string. ++ public init(validatingDate date: LocalDate, time: LocalTime, offset: Int16, features: Features) ++ throws ++ { ++ self.init(date: date, time: time, offset: offset, features: features) ++ guard date.isValid else { ++ throw TOMLError(.invalidDateTimeComponents("Invalid local date: \(date)")) ++ } ++ guard time.isValid else { ++ throw TOMLError(.invalidDateTimeComponents("Invalid local time: \(time)")) ++ } ++ guard offsetIsValid else { ++ throw TOMLError(.invalidDateTimeComponents("Invalid offset: \(offset)")) ++ } ++ guard featuresAreValid else { ++ throw TOMLError(.invalidDateTimeComponents("Invalid features: \(features)")) ++ } ++ } ++ ++ /// Check if the offset date-time is valid. ++ public var isValid: Bool { ++ guard date.isValid, time.isValid, offsetIsValid else { ++ return false ++ } ++ ++ return featuresAreValid ++ } ++ ++ private var offsetIsValid: Bool { ++ offset >= -1440 && offset <= 1440 ++ } ++ ++ private var featuresAreValid: Bool { ++ if features.contains(.lowercaseZ) || features.contains(.uppercaseZ) { ++ return offset == 0 ++ } ++ ++ return true ++ } ++ ++ /// Number of seconds since 2001-01-01T00:00:00Z according to the proleptic Gregorian calendar. ++ /// ++ /// > Important: This is similar to `Foundation.Date.timeIntervalSinceReferenceDate`. ++ /// But for ancient dates, this result may disagree with `Foundation.Date` on how much time has passed. ++ /// this is because Foundation's Gregorian calendar follows the Julian calendar up to 1582-10-04, ++ /// then the Gregorian calendar after that. According to the TOML specification, ++ /// an offset date-time should follow the proleptic Gregorian calendar, ++ /// which extends the Gregorian calendar backwards to year 1. ++ public var timeIntervalSince2001: Double { ++ timeIntervalSince1970 - 978_307_200 ++ } ++ ++ /// Number of seconds since 1970-01-01T00:00:00Z according to the proleptic Gregorian calendar. ++ /// ++ /// > Important: This is similar to `Foundation.Date.timeIntervalSinceReferenceDate`. ++ /// But for ancient dates, this result may disagree with `Foundation.Date` on how much time has passed. ++ /// this is because Foundation's Gregorian calendar follows the Julian calendar up to 1582-10-04, ++ /// then the Gregorian calendar after that. According to the TOML specification, ++ /// an offset date-time should follow the proleptic Gregorian calendar, ++ /// which extends the Gregorian calendar backwards to year 1. ++ public var timeIntervalSince1970: Double { ++ let year = Int64(date.year) ++ let month = Int64(date.month) ++ let day = Int64(date.day) ++ let hour = Int64(time.hour) ++ let minute = Int64(time.minute) ++ let second = Int64(time.second) ++ let nanosecond = Int64(time.nanosecond) ++ let offsetInSeconds = Int64(offset) * 60 ++ ++ var y = year ++ if month <= 2 { y -= 1 } ++ ++ let era = (y >= 0 ? y : y - 399) / 400 ++ let yoe = y - era * 400 ++ let doy = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + day - 1 ++ let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy ++ let epochOffset = Int64(719_468) ++ let dayCounts = era * 146_097 + doe - epochOffset ++ let secondOfDay = hour * 3600 + minute * 60 + second ++ let totalSeconds = dayCounts * 86400 + secondOfDay - offsetInSeconds ++ ++ return Double(totalSeconds) + Double(nanosecond) / 1_000_000_000 ++ } ++ ++ /// The string representation of the offset date-time. ++ /// ++ /// If a value has precision up to 1 nanosecond, ++ /// and it does not require superfluous trailing zeros in its fraction seconds, ++ /// this value can be recreated exactly. ++ public var description: String { ++ let dateString = date.description ++ let timeString = time.description ++ let separator = ++ if features.contains(.lowercaseT) { ++ "t" ++ } else if features.contains(.uppercaseT) { ++ "T" ++ } else { ++ " " ++ } ++ ++ if features.contains(.lowercaseZ) { ++ return "\(dateString)\(separator)\(timeString)z" ++ } else if features.contains(.uppercaseZ) { ++ return "\(dateString)\(separator)\(timeString)Z" ++ } else { ++ let sign = offset >= 0 ? "+" : "-" ++ let absOffset = abs(offset) ++ let hours = absOffset / 60 ++ let minutes = absOffset % 60 ++ let hoursStr = hours < 10 ? "0\(hours)" : "\(hours)" ++ let minutesStr = minutes < 10 ? "0\(minutes)" : "\(minutes)" ++ return "\(dateString)\(separator)\(timeString)\(sign)\(hoursStr):\(minutesStr)" ++ } ++ } ++ ++ /// Presentation details for string representation of the offset date-time. ++ /// ++ /// A parser can preserve features of a offset date-time string with this type. ++ /// If neither lowercase nor uppercase 'T' is present, the date-time seprator is a space, which is allowed by TOML. ++ public struct Features: OptionSet, Hashable, Sendable, Codable { ++ /// The raw value of the features. ++ public let rawValue: UInt8 ++ ++ /// Create a new features from it's raw value. ++ public init(rawValue: UInt8) { ++ self.rawValue = rawValue ++ } ++ ++ /// Indicates the date-time seprator is a lowercase 't'. ++ public static let lowercaseT = Features(rawValue: 1 << 1) ++ ++ /// Indicates the date-time seprator is a uppercase 'T'. ++ public static let uppercaseT = Features(rawValue: 1 << 2) ++ ++ /// Indicates the offset is represented as a lowercase 'z'. ++ /// This should not be present if the offset is non-zero, ++ /// or if it's +00:00. ++ public static let lowercaseZ = Features(rawValue: 1 << 3) ++ ++ /// Indicates the offset is represented as a uppercase 'Z'. ++ /// This should not be present if the offset is non-zero, ++ /// or if it's +00:00. ++ public static let uppercaseZ = Features(rawValue: 1 << 4) ++ } +@@ -217,52 +212,44 @@ +- /// The date component of the local date-time. +- public var date: LocalDate +- /// The time component of the local date-time. +- public var time: LocalTime +- +- /// Create a new local date-time from it's members. +- /// +- /// This initializer does not validate the components. +- /// Use ``isValid`` to check if the local date-time is valid. +- /// - Parameters: +- /// - date: The date component of the local date-time. +- /// - time: The time component of the local date-time. +- public init(date: LocalDate, time: LocalTime) { +- self.date = date +- self.time = time +- } +- +- public init(from decoder: any Decoder) throws { +- if let decoder = decoder as? _TOMLDecoder { +- self = try decoder.decode(LocalDateTime.self) +- } else { +- try self.init(from: decoder) +- } +- } +- +- /// Create a new local date-time from it's members. +- /// +- /// This initializer validates the components. +- /// A invalid component causes a error to be thrown. +- /// +- /// - Parameters: +- /// - date: The date component of the local date-time. +- /// - time: The time component of the local date-time. +- public init(validatingDate date: LocalDate, time: LocalTime) throws(TOMLError) { +- self.init(date: date, time: time) +- guard date.isValid else { +- throw TOMLError(.invalidDateTimeComponents("Invalid local date: \(date)")) +- } +- guard time.isValid else { +- throw TOMLError(.invalidDateTimeComponents("Invalid local time: \(time)")) +- } +- } +- +- /// Check if the local date-time is valid. +- public var isValid: Bool { +- date.isValid && time.isValid +- } +- +- /// The string representation of the local date-time. +- public var description: String { +- "\(date.description)T\(time.description)" +- } ++ /// The date component of the local date-time. ++ public var date: LocalDate ++ /// The time component of the local date-time. ++ public var time: LocalTime ++ ++ /// Create a new local date-time from it's members. ++ /// ++ /// This initializer does not validate the components. ++ /// Use ``isValid`` to check if the local date-time is valid. ++ /// - Parameters: ++ /// - date: The date component of the local date-time. ++ /// - time: The time component of the local date-time. ++ public init(date: LocalDate, time: LocalTime) { ++ self.date = date ++ self.time = time ++ } ++ ++ /// Create a new local date-time from it's members. ++ /// ++ /// This initializer validates the components. ++ /// A invalid component causes a error to be thrown. ++ /// ++ /// - Parameters: ++ /// - date: The date component of the local date-time. ++ /// - time: The time component of the local date-time. ++ public init(validatingDate date: LocalDate, time: LocalTime) throws { ++ self.init(date: date, time: time) ++ guard date.isValid else { ++ throw TOMLError(.invalidDateTimeComponents("Invalid local date: \(date)")) ++ } ++ guard time.isValid else { ++ throw TOMLError(.invalidDateTimeComponents("Invalid local time: \(time)")) ++ } ++ } ++ ++ /// Check if the local date-time is valid. ++ public var isValid: Bool { ++ date.isValid && time.isValid ++ } ++ ++ /// The string representation of the local date-time. ++ public var description: String { ++ "\(date.description)T\(time.description)" ++ } +@@ -275,63 +262,67 @@ +- /// The hour component of the local time. +- public var hour: UInt8 +- /// The minute component of the local time. +- public var minute: UInt8 +- /// The second component of the local time. +- public var second: UInt8 +- /// The fractional second component of the local time in nanoseconds. +- public var nanosecond: UInt32 +- +- /// Create a new local time from it's members. +- /// +- /// This initializer validates the components. +- /// A invalid component causes a error to be thrown. +- /// +- /// - Parameters: +- /// - hour: The hour component of the local time. +- /// - minute: The minute component of the local time. +- /// - second: The second component of the local time. +- /// - nanosecond: The fractional second component of the local time in nanoseconds. +- public init(validatingHour hour: UInt8, minute: UInt8, second: UInt8, nanosecond: UInt32 = 0) throws(TOMLError) { +- self.init(hour: hour, minute: minute, second: second, nanosecond: nanosecond) +- guard isValid else { +- throw TOMLError(.invalidDateTimeComponents("Invalid local time components: \(hour):\(minute):\(second).\(nanosecond)")) +- } +- } +- +- /// Create a new local time from it's members. +- /// +- /// This initializer does not validate the components. +- /// Use ``isValid`` to check if the local time is valid. +- /// +- /// - Parameters: +- /// - hour: The hour component of the local time. +- /// - minute: The minute component of the local time. +- /// - second: The second component of the local time. +- /// - nanosecond: The fractional second component of the local time in nanoseconds. +- public init(hour: UInt8, minute: UInt8, second: UInt8, nanosecond: UInt32 = 0) { +- self.hour = hour +- self.minute = minute +- self.second = second +- self.nanosecond = nanosecond +- } +- +- /// Check if the local time is valid. +- public var isValid: Bool { +- hour < 24 && minute < 60 && second < 60 && nanosecond < 1_000_000_000 +- } +- +- /// The string representation of the local time. +- public var description: String { +- let hourStr = hour < 10 ? "0\(hour)" : "\(hour)" +- let minuteStr = minute < 10 ? "0\(minute)" : "\(minute)" +- let secondStr = second < 10 ? "0\(second)" : "\(second)" +- +- if nanosecond == 0 { +- return "\(hourStr):\(minuteStr):\(secondStr)" +- } else { +- let nanosecondStr = String(nanosecond).padded(to: 9, with: "0") +- let trimmedFractional = nanosecondStr.trimmingSuffix("0") +- let finalFractional = trimmedFractional.isEmpty ? "0" : trimmedFractional +- return "\(hourStr):\(minuteStr):\(secondStr).\(finalFractional)" +- } +- } ++ /// The hour component of the local time. ++ public var hour: UInt8 ++ /// The minute component of the local time. ++ public var minute: UInt8 ++ /// The second component of the local time. ++ public var second: UInt8 ++ /// The fractional second component of the local time in nanoseconds. ++ public var nanosecond: UInt32 ++ ++ /// Create a new local time from it's members. ++ /// ++ /// This initializer validates the components. ++ /// A invalid component causes a error to be thrown. ++ /// ++ /// - Parameters: ++ /// - hour: The hour component of the local time. ++ /// - minute: The minute component of the local time. ++ /// - second: The second component of the local time. ++ /// - nanosecond: The fractional second component of the local time in nanoseconds. ++ public init(validatingHour hour: UInt8, minute: UInt8, second: UInt8, nanosecond: UInt32 = 0) ++ throws ++ { ++ self.init(hour: hour, minute: minute, second: second, nanosecond: nanosecond) ++ guard isValid else { ++ throw TOMLError( ++ .invalidDateTimeComponents( ++ "Invalid local time components: \(hour):\(minute):\(second).\(nanosecond)")) ++ } ++ } ++ ++ /// Create a new local time from it's members. ++ /// ++ /// This initializer does not validate the components. ++ /// Use ``isValid`` to check if the local time is valid. ++ /// ++ /// - Parameters: ++ /// - hour: The hour component of the local time. ++ /// - minute: The minute component of the local time. ++ /// - second: The second component of the local time. ++ /// - nanosecond: The fractional second component of the local time in nanoseconds. ++ public init(hour: UInt8, minute: UInt8, second: UInt8, nanosecond: UInt32 = 0) { ++ self.hour = hour ++ self.minute = minute ++ self.second = second ++ self.nanosecond = nanosecond ++ } ++ ++ /// Check if the local time is valid. ++ public var isValid: Bool { ++ hour < 24 && minute < 60 && second < 60 && nanosecond < 1_000_000_000 ++ } ++ ++ /// The string representation of the local time. ++ public var description: String { ++ let hourStr = hour < 10 ? "0\(hour)" : "\(hour)" ++ let minuteStr = minute < 10 ? "0\(minute)" : "\(minute)" ++ let secondStr = second < 10 ? "0\(second)" : "\(second)" ++ ++ if nanosecond == 0 { ++ return "\(hourStr):\(minuteStr):\(secondStr)" ++ } else { ++ let nanosecondStr = String(nanosecond).padded(to: 9, with: "0") ++ let trimmedFractional = nanosecondStr.trimmingSuffix("0") ++ let finalFractional = trimmedFractional.isEmpty ? "0" : trimmedFractional ++ return "\(hourStr):\(minuteStr):\(secondStr).\(finalFractional)" ++ } ++ } +@@ -344,71 +335,72 @@ +- /// The year component of the local date. +- /// Valid range is [1, 9999]. +- public var year: UInt16 +- +- /// The month component of the local date. +- /// Valid range is [1, 12]. +- public var month: UInt8 +- +- /// The day component of the local date. +- /// Valid range is depends on the month and year. +- public var day: UInt8 +- +- /// Create a new local date from it's members. +- /// +- /// This initializer validates the components. +- /// A invalid component causes a error to be thrown. +- /// +- /// - Parameters: +- /// - year: The year component of the local date. +- /// - month: The month component of the local date. +- /// - day: The day component of the local date. +- public init(validatingYear year: UInt16, month: UInt8, day: UInt8) throws(TOMLError) { +- self.init(year: year, month: month, day: day) +- guard isValid else { +- throw TOMLError(.invalidDateTimeComponents("Invalid local date components: \(year)-\(month)-\(day)")) +- } +- } +- +- /// Create a new local date from it's members. +- /// +- /// This initializer does not validate the components. +- /// Use ``isValid`` to check if the local date is valid. +- /// +- /// - Parameters: +- /// - year: The year component of the local date. +- /// - month: The month component of the local date. +- /// - day: The day component of the local date. +- public init(year: UInt16, month: UInt8, day: UInt8) { +- self.year = year +- self.month = month +- self.day = day +- } +- +- /// Check if the local date is valid. +- public var isValid: Bool { +- guard month >= 1, month <= 12 else { return false } +- guard day >= 1 else { return false } +- +- let daysInMonth: UInt8 +- switch month { +- case 1, 3, 5, 7, 8, 10, 12: +- daysInMonth = 31 +- case 4, 6, 9, 11: +- daysInMonth = 30 +- case 2: +- let isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) +- daysInMonth = isLeapYear ? 29 : 28 +- default: +- return false +- } +- +- return day <= daysInMonth +- } +- +- /// The string representation of the local date. +- public var description: String { +- let yearStr = String(year).padded(to: 4, with: "0") +- let monthStr = month < 10 ? "0\(month)" : "\(month)" +- let dayStr = day < 10 ? "0\(day)" : "\(day)" +- return "\(yearStr)-\(monthStr)-\(dayStr)" +- } ++ /// The year component of the local date. ++ /// Valid range is [1, 9999]. ++ public var year: UInt16 ++ ++ /// The month component of the local date. ++ /// Valid range is [1, 12]. ++ public var month: UInt8 ++ ++ /// The day component of the local date. ++ /// Valid range is depends on the month and year. ++ public var day: UInt8 ++ ++ /// Create a new local date from it's members. ++ /// ++ /// This initializer validates the components. ++ /// A invalid component causes a error to be thrown. ++ /// ++ /// - Parameters: ++ /// - year: The year component of the local date. ++ /// - month: The month component of the local date. ++ /// - day: The day component of the local date. ++ public init(validatingYear year: UInt16, month: UInt8, day: UInt8) throws { ++ self.init(year: year, month: month, day: day) ++ guard isValid else { ++ throw TOMLError( ++ .invalidDateTimeComponents("Invalid local date components: \(year)-\(month)-\(day)")) ++ } ++ } ++ ++ /// Create a new local date from it's members. ++ /// ++ /// This initializer does not validate the components. ++ /// Use ``isValid`` to check if the local date is valid. ++ /// ++ /// - Parameters: ++ /// - year: The year component of the local date. ++ /// - month: The month component of the local date. ++ /// - day: The day component of the local date. ++ public init(year: UInt16, month: UInt8, day: UInt8) { ++ self.year = year ++ self.month = month ++ self.day = day ++ } ++ ++ /// Check if the local date is valid. ++ public var isValid: Bool { ++ guard month >= 1, month <= 12 else { return false } ++ guard day >= 1 else { return false } ++ ++ let daysInMonth: UInt8 ++ switch month { ++ case 1, 3, 5, 7, 8, 10, 12: ++ daysInMonth = 31 ++ case 4, 6, 9, 11: ++ daysInMonth = 30 ++ case 2: ++ let isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ++ daysInMonth = isLeapYear ? 29 : 28 ++ default: ++ return false ++ } ++ ++ return day <= daysInMonth ++ } ++ ++ /// The string representation of the local date. ++ public var description: String { ++ let yearStr = String(year).padded(to: 4, with: "0") ++ let monthStr = month < 10 ? "0\(month)" : "\(month)" ++ let dayStr = day < 10 ? "0\(day)" : "\(day)" ++ return "\(yearStr)-\(monthStr)-\(dayStr)" ++ } +@@ -418,14 +410,14 @@ +- fileprivate func padded(to length: Int, with character: Character) -> String { +- if count >= length { +- return self +- } +- return String(repeating: character, count: length - count) + self +- } +- +- fileprivate func trimmingSuffix(_ suffix: Character) -> String { +- var result = self +- while result.last == suffix { +- result.removeLast() +- } +- return result +- } ++ fileprivate func padded(to length: Int, with character: Character) -> String { ++ if count >= length { ++ return self ++ } ++ return String(repeating: character, count: length - count) + self ++ } ++ ++ fileprivate func trimmingSuffix(_ suffix: Character) -> String { ++ var result = self ++ while result.last == suffix { ++ result.removeLast() ++ } ++ return result ++ } +@@ -433,49 +424,0 @@ +- +-#if canImport(Foundation) +-public import Foundation +- +-extension DateComponents { +- /// Create a new `Foundation.DateComponents` from an offset date-time. +- /// Only the literal components of a offset date-time will be in the components. +- /// the calendar component, for example, is not set. +- /// +- /// - Parameter offsetDateTime: The offset date-time to convert. +- public init(offsetDateTime: OffsetDateTime) { +- self.init( +- timeZone: TimeZone(secondsFromGMT: Int(offsetDateTime.offset) * 60), +- year: Int(offsetDateTime.date.year), +- month: Int(offsetDateTime.date.month), +- day: Int(offsetDateTime.date.day), +- hour: Int(offsetDateTime.time.hour), +- minute: Int(offsetDateTime.time.minute), +- second: Int(offsetDateTime.time.second), +- nanosecond: Int(offsetDateTime.time.nanosecond) +- ) +- } +-} +- +-extension Date { +- /// Create a new `Foundation.Date` from an offset date-time. +- /// +- /// - Parameter offsetDateTime: The offset date-time to convert. +- /// - Parameter calendar: The calendar based on which the date is constructed. +- /// Defaults to the Gregorian calendar. +- /// Note that Foundation's Gregorian calendar is NOT proleptic. +- /// It follows the Julian calendar up to 1582-10-04, +- /// then the Gregorian calendar after that. +- /// According to the TOML specification, +- /// an offset date-time should follow the proleptic Gregorian calendar, +- /// which extends the Gregorian calendar backwards to year 1. +- /// Therefore, +- /// for ancient dates, +- /// the resulting `Date`'s `.timeIntervalSince1970` or `.timeIntervalSinceReferenceDate` may have a different value as defined in the TOML specification, +- /// which follows RFC 3339. +- /// To get the proleptic Gregorian time interval, +- /// use ``OffsetDateTime/timeIntervalSince2001`` or ``OffsetDateTime/timeIntervalSince1970``. +- public init(offsetDateTime: OffsetDateTime, calendar: Calendar = Calendar(identifier: .gregorian)) { +- var components = DateComponents(offsetDateTime: offsetDateTime) +- components.calendar = calendar +- self = components.date! +- } +-} +-#endif +--- Sources/TOMLDecoder/TOMLKey.swift ++++ Sources/TOMLSemantics/TOMLKey.swift +@@ -2,3 +2,3 @@ +- case string(String) +- case int(Int) +- case `super` ++ case string(String) ++ case int(Int) ++ case `super` +@@ -6,2 +6,16 @@ +- init(stringValue: String) { +- self = .string(stringValue) ++ init(stringValue: String) { ++ self = .string(stringValue) ++ } ++ ++ init(intValue: Int) { ++ self = .int(intValue) ++ } ++ ++ var stringValue: String { ++ switch self { ++ case .string(let string): ++ string ++ case .int(let int): ++ "Index \(int)" ++ case .super: ++ "super" +@@ -8,0 +23 @@ ++ } +@@ -10,2 +25,6 @@ +- init(intValue: Int) { +- self = .int(intValue) ++ var intValue: Int? { ++ switch self { ++ case .int(let int): ++ int ++ default: ++ nil +@@ -13,20 +32 @@ +- +- var stringValue: String { +- switch self { +- case let .string(string): +- string +- case let .int(int): +- "Index \(int)" +- case .super: +- "super" +- } +- } +- +- var intValue: Int? { +- switch self { +- case let .int(int): +- int +- default: +- nil +- } +- } ++ } +--- Sources/TOMLDecoder/TOMLError.swift ++++ Sources/TOMLSemantics/TOMLError.swift +@@ -8 +8 @@ +- let reason: Reason ++ let reason: Reason +@@ -10,3 +10,3 @@ +- init(_ reason: Reason) { +- self.reason = reason +- } ++ init(_ reason: Reason) { ++ self.reason = reason ++ } +@@ -14,27 +14,27 @@ +- enum Reason { +- case arrayOutOfBound(index: Int, bound: Int) +- case badKey(lineNumber: Int) +- case expectedHexCharacters(UTF8.CodeUnit, Int) +- case illegalEscapeCharacter(UTF8.CodeUnit) +- case illegalUCSCode(UInt32) +- case internalError(lineNumber: Int) +- case invalidBool(context: TOMLKey, lineNumber: Int) +- case invalidCharacter(UTF8.CodeUnit) +- case invalidDateTime(lineNumber: Int?, reason: String) +- case invalidDateTime3(context: TOMLKey, lineNumber: Int, reason: String) +- case invalidDateTimeComponents(String) +- case invalidFloat(context: TOMLKey, lineNumber: Int, reason: String) +- case invalidHexCharacters(UTF8.CodeUnit) +- case invalidInteger(context: TOMLKey, lineNumber: Int, reason: String) +- case invalidNumber(reason: String) +- case invalidString(context: TOMLKey, lineNumber: Int, reason: String) +- case invalidUTF8 +- case invalidValueInTable(context: TOMLKey, lineNumber: Int) +- case keyExists(lineNumber: Int) +- case keyNotFoundInTable(key: String, expected: String) +- case notReallyCodable +- case syntax(lineNumber: Int, message: String) +- case typeMismatch(context: TOMLKey, lineNumber: Int, expected: String) +- case typeMismatchInArray(lineNumber: Int, index: Int, expected: String) +- case typeMismatchInTable(key: String, expected: String) +- } ++ enum Reason { ++ case arrayOutOfBound(index: Int, bound: Int) ++ case badKey(lineNumber: Int) ++ case expectedHexCharacters(UTF8.CodeUnit, Int) ++ case illegalEscapeCharacter(UTF8.CodeUnit) ++ case illegalUCSCode(UInt32) ++ case internalError(lineNumber: Int) ++ case invalidBool(context: TOMLKey, lineNumber: Int) ++ case invalidCharacter(UTF8.CodeUnit) ++ case invalidDateTime(lineNumber: Int?, reason: String) ++ case invalidDateTime3(context: TOMLKey, lineNumber: Int, reason: String) ++ case invalidDateTimeComponents(String) ++ case invalidFloat(context: TOMLKey, lineNumber: Int, reason: String) ++ case invalidHexCharacters(UTF8.CodeUnit) ++ case invalidInteger(context: TOMLKey, lineNumber: Int, reason: String) ++ case invalidNumber(reason: String) ++ case invalidString(context: TOMLKey, lineNumber: Int, reason: String) ++ case invalidUTF8 ++ case invalidValueInTable(context: TOMLKey, lineNumber: Int) ++ case keyExists(lineNumber: Int) ++ case keyNotFoundInTable(key: String, expected: String) ++ case notReallyCodable ++ case syntax(lineNumber: Int, message: String) ++ case typeMismatch(context: TOMLKey, lineNumber: Int, expected: String) ++ case typeMismatchInArray(lineNumber: Int, index: Int, expected: String) ++ case typeMismatchInTable(key: String, expected: String) ++ } +@@ -44,102 +44,101 @@ +- public var description: String { +- switch reason { +- case let .arrayOutOfBound(index, bound): +- "Array index \(index) is out of bounds (0..<\(bound))." +- case let .badKey(lineNumber): +- "(Line \(lineNumber)) Ill-formed key." +- case let .expectedHexCharacters(codeUnit, hexCount): +- "Expected \(hexCount) hexadecimal characters after '\(String(UnicodeScalar(codeUnit))).'." +- case let .illegalEscapeCharacter(codeUnit): +- "Illegal escape character '\(String(UnicodeScalar(codeUnit)))'." +- case let .illegalUCSCode(ucs): +- "Illegal UCS code '\(ucs)'." +- case let .internalError(lineNumber): +- "(Line \(lineNumber)) Internal error." +- case let .invalidBool(context, lineNumber): +- switch context { +- case let .string(key): +- "(Line \(lineNumber)) Invalid boolean value for key '\(key)'." +- case let .int(index): +- "(Line \(lineNumber)) Invalid boolean value for index \(index)." +- case .super: +- "(Line \(lineNumber)) Invalid boolean value for 'super'." +- } +- case let .invalidCharacter(codeUnit): +- "Invalid character '\(String(UnicodeScalar(codeUnit)))'." +- case let .invalidDateTime(lineNumber, reason): +- "\(lineNumber.map { "(Line \($0)) " } ?? "")Invalid date-time: \(reason)." +- case let .invalidDateTime3(context, lineNumber, reason): +- switch context { +- case let .string(key): +- "(Line \(lineNumber)) Invalid date-time value for key '\(key)': \(reason)." +- case let .int(index): +- "(Line \(lineNumber)) Invalid date-time value for index \(index)': \(reason)." +- case .super: +- "(Line \(lineNumber)) Invalid date-time value for 'super': \(reason)." +- } +- case let .invalidDateTimeComponents(components): +- "Invalid date-time components: \(components)." +- case let .invalidFloat(context, lineNumber, reason): +- switch context { +- case let .string(key): +- "(Line \(lineNumber)) Invalid float value for key '\(key)': \(reason)." +- case let .int(index): +- "(Line \(lineNumber)) Invalid float value for index \(index)': \(reason)." +- case .super: +- "(Line \(lineNumber)) Invalid float value for 'super': \(reason)." +- } +- case let .invalidHexCharacters(codeUnit): +- "Invalid hexadecimal characters '\(String(UnicodeScalar(codeUnit)))'." +- case let .invalidInteger(context, lineNumber, reason): +- switch context { +- case let .string(key): +- "(Line \(lineNumber)) Invalid integer value for key '\(key)': \(reason)." +- case let .int(index): +- "(Line \(lineNumber)) Invalid integer value for index \(index)': \(reason)." +- case .super: +- "(Line \(lineNumber)) Invalid integer value for 'super': \(reason)." +- } +- case let .invalidNumber(reason): +- "Invalid number: \(reason)." +- case let .invalidString(context, lineNumber, reason): +- switch context { +- case let .string(key): +- "(Line \(lineNumber)) Invalid string value for key '\(key)': \(reason)." +- case let .int(index): +- "(Line \(lineNumber)) Invalid string value for index \(index)': \(reason)." +- case .super: +- "(Line \(lineNumber)) Invalid string value for 'super': \(reason)." +- } +- case .invalidUTF8: +- "The given data was not valid UTF8." +- case let .invalidValueInTable(context, lineNumber): +- switch context { +- case let .string(key): +- "(Line \(lineNumber)) Invalid value in table for key '\(key)'." +- case let .int(index): +- "(Line \(lineNumber)) Invalid value in table for index \(index)." +- case .super: +- "(Line \(lineNumber)) Invalid value in table for 'super'." +- } +- case let .keyExists(lineNumber): +- "(Line \(lineNumber)) Key already exists." +- case let .keyNotFoundInTable(key, expected): +- "Key '\(key)' not found in table while looking for \(expected)." +- case .notReallyCodable: +- "This type is not generally codable. Use TOMLDecoder to decode it as part of a larger Codable." +- case let .syntax(lineNumber, message): +- "(Line \(lineNumber)) Syntax error: \(message)." +- case let .typeMismatch(context, lineNumber, expected): +- switch context { +- case let .string(key): +- "(Line \(lineNumber)) Type mismatch at table key '\(key)': expected \(expected)." +- case let .int(index): +- "(Line \(lineNumber)) Type mismatch at array index \(index): expected \(expected)." +- case .super: +- "(Line \(lineNumber)) Type mismatch at 'super': expected \(expected)." +- } +- case let .typeMismatchInArray(lineNumber, index, expected): +- "(Line \(lineNumber)) Type mismatch at array index \(index): expected \(expected)." +- case let .typeMismatchInTable(key, expected): +- "Type mismatch at table key '\(key)': expected \(expected)." +- } ++ public var description: String { ++ switch reason { ++ case .arrayOutOfBound(let index, let bound): ++ "Array index \(index) is out of bounds (0..<\(bound))." ++ case .badKey(let lineNumber): ++ "(Line \(lineNumber)) Ill-formed key." ++ case .expectedHexCharacters(let codeUnit, let hexCount): ++ "Expected \(hexCount) hexadecimal characters after '\(String(UnicodeScalar(codeUnit))).'." ++ case .illegalEscapeCharacter(let codeUnit): ++ "Illegal escape character '\(String(UnicodeScalar(codeUnit)))'." ++ case .illegalUCSCode(let ucs): ++ "Illegal UCS code '\(ucs)'." ++ case .internalError(let lineNumber): ++ "(Line \(lineNumber)) Internal error." ++ case .invalidBool(let context, let lineNumber): ++ switch context { ++ case .string(let key): ++ "(Line \(lineNumber)) Invalid boolean value for key '\(key)'." ++ case .int(let index): ++ "(Line \(lineNumber)) Invalid boolean value for index \(index)." ++ case .super: ++ "(Line \(lineNumber)) Invalid boolean value for 'super'." ++ } ++ case .invalidCharacter(let codeUnit): ++ "Invalid character '\(String(UnicodeScalar(codeUnit)))'." ++ case .invalidDateTime(let lineNumber, let reason): ++ "\(lineNumber.map { "(Line \($0)) " } ?? "")Invalid date-time: \(reason)." ++ case .invalidDateTime3(let context, let lineNumber, let reason): ++ switch context { ++ case .string(let key): ++ "(Line \(lineNumber)) Invalid date-time value for key '\(key)': \(reason)." ++ case .int(let index): ++ "(Line \(lineNumber)) Invalid date-time value for index \(index)': \(reason)." ++ case .super: ++ "(Line \(lineNumber)) Invalid date-time value for 'super': \(reason)." ++ } ++ case .invalidDateTimeComponents(let components): ++ "Invalid date-time components: \(components)." ++ case .invalidFloat(let context, let lineNumber, let reason): ++ switch context { ++ case .string(let key): ++ "(Line \(lineNumber)) Invalid float value for key '\(key)': \(reason)." ++ case .int(let index): ++ "(Line \(lineNumber)) Invalid float value for index \(index)': \(reason)." ++ case .super: ++ "(Line \(lineNumber)) Invalid float value for 'super': \(reason)." ++ } ++ case .invalidHexCharacters(let codeUnit): ++ "Invalid hexadecimal characters '\(String(UnicodeScalar(codeUnit)))'." ++ case .invalidInteger(let context, let lineNumber, let reason): ++ switch context { ++ case .string(let key): ++ "(Line \(lineNumber)) Invalid integer value for key '\(key)': \(reason)." ++ case .int(let index): ++ "(Line \(lineNumber)) Invalid integer value for index \(index)': \(reason)." ++ case .super: ++ "(Line \(lineNumber)) Invalid integer value for 'super': \(reason)." ++ } ++ case .invalidNumber(let reason): ++ "Invalid number: \(reason)." ++ case .invalidString(let context, let lineNumber, let reason): ++ switch context { ++ case .string(let key): ++ "(Line \(lineNumber)) Invalid string value for key '\(key)': \(reason)." ++ case .int(let index): ++ "(Line \(lineNumber)) Invalid string value for index \(index)': \(reason)." ++ case .super: ++ "(Line \(lineNumber)) Invalid string value for 'super': \(reason)." ++ } ++ case .invalidUTF8: ++ "The given data was not valid UTF8." ++ case .invalidValueInTable(let context, let lineNumber): ++ switch context { ++ case .string(let key): ++ "(Line \(lineNumber)) Invalid value in table for key '\(key)'." ++ case .int(let index): ++ "(Line \(lineNumber)) Invalid value in table for index \(index)." ++ case .super: ++ "(Line \(lineNumber)) Invalid value in table for 'super'." ++ } ++ case .keyExists(let lineNumber): ++ "(Line \(lineNumber)) Key already exists." ++ case .keyNotFoundInTable(let key, let expected): ++ "Key '\(key)' not found in table while looking for \(expected)." ++ case .notReallyCodable: ++ "This type is not generally codable. Use TOMLDecoder to decode it as part of a larger Codable." ++ case .syntax(let lineNumber, let message): ++ "(Line \(lineNumber)) Syntax error: \(message)." ++ case .typeMismatch(let context, let lineNumber, let expected): ++ switch context { ++ case .string(let key): ++ "(Line \(lineNumber)) Type mismatch at table key '\(key)': expected \(expected)." ++ case .int(let index): ++ "(Line \(lineNumber)) Type mismatch at array index \(index): expected \(expected)." ++ case .super: ++ "(Line \(lineNumber)) Type mismatch at 'super': expected \(expected)." ++ } ++ case .typeMismatchInArray(let lineNumber, let index, let expected): ++ "(Line \(lineNumber)) Type mismatch at array index \(index): expected \(expected)." ++ case .typeMismatchInTable(let key, let expected): ++ "Type mismatch at table key '\(key)': expected \(expected)." +@@ -146,0 +146 @@ ++ } diff --git a/Sources/TreeSitterTOML/LICENSE b/Sources/TreeSitterTOML/LICENSE new file mode 100644 index 0000000..7bf071b --- /dev/null +++ b/Sources/TreeSitterTOML/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Ika (https://github.com/ikatyang) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Sources/TreeSitterTOML/include/toml.h b/Sources/TreeSitterTOML/include/toml.h new file mode 100644 index 0000000..85a2e7c --- /dev/null +++ b/Sources/TreeSitterTOML/include/toml.h @@ -0,0 +1,16 @@ +#ifndef TREE_SITTER_TOML_H_ +#define TREE_SITTER_TOML_H_ + +typedef struct TSLanguage TSLanguage; + +#ifdef __cplusplus +extern "C" { +#endif + +const TSLanguage *tree_sitter_toml(void); + +#ifdef __cplusplus +} +#endif + +#endif // TREE_SITTER_TOML_H_ diff --git a/Sources/TreeSitterTOML/parser.c b/Sources/TreeSitterTOML/parser.c new file mode 100644 index 0000000..1cfc62b --- /dev/null +++ b/Sources/TreeSitterTOML/parser.c @@ -0,0 +1,4739 @@ +#include "tree_sitter/parser.h" + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#endif + +#define LANGUAGE_VERSION 14 +#define STATE_COUNT 152 +#define LARGE_STATE_COUNT 2 +#define SYMBOL_COUNT 66 +#define ALIAS_COUNT 0 +#define TOKEN_COUNT 40 +#define EXTERNAL_TOKEN_COUNT 5 +#define FIELD_COUNT 0 +#define MAX_ALIAS_SEQUENCE_LENGTH 8 +#define PRODUCTION_ID_COUNT 2 + +enum ts_symbol_identifiers { + aux_sym_document_token1 = 1, + sym_comment = 2, + anon_sym_LBRACK = 3, + anon_sym_RBRACK = 4, + anon_sym_LBRACK_LBRACK = 5, + anon_sym_RBRACK_RBRACK = 6, + anon_sym_EQ = 7, + anon_sym_DOT = 8, + sym_bare_key = 9, + anon_sym_DQUOTE = 10, + aux_sym__basic_string_token1 = 11, + anon_sym_DQUOTE2 = 12, + anon_sym_DQUOTE_DQUOTE_DQUOTE = 13, + aux_sym__multiline_basic_string_token1 = 14, + sym_escape_sequence = 15, + sym__escape_line_ending = 16, + anon_sym_SQUOTE = 17, + aux_sym__literal_string_token1 = 18, + anon_sym_SQUOTE2 = 19, + anon_sym_SQUOTE_SQUOTE_SQUOTE = 20, + aux_sym_integer_token1 = 21, + aux_sym_integer_token2 = 22, + aux_sym_integer_token3 = 23, + aux_sym_integer_token4 = 24, + aux_sym_float_token1 = 25, + aux_sym_float_token2 = 26, + sym_boolean = 27, + sym_offset_date_time = 28, + sym_local_date_time = 29, + sym_local_date = 30, + sym_local_time = 31, + anon_sym_COMMA = 32, + anon_sym_LBRACE = 33, + anon_sym_RBRACE = 34, + sym__line_ending_or_eof = 35, + sym__multiline_basic_string_content = 36, + sym__multiline_basic_string_end = 37, + sym__multiline_literal_string_content = 38, + sym__multiline_literal_string_end = 39, + sym_document = 40, + sym_table = 41, + sym_table_array_element = 42, + sym_pair = 43, + sym__inline_pair = 44, + sym__key = 45, + sym_dotted_key = 46, + sym_quoted_key = 47, + sym__inline_value = 48, + sym_string = 49, + sym__basic_string = 50, + sym__multiline_basic_string = 51, + sym__literal_string = 52, + sym__multiline_literal_string = 53, + sym_integer = 54, + sym_float = 55, + sym_array = 56, + sym_inline_table = 57, + aux_sym_document_repeat1 = 58, + aux_sym_document_repeat2 = 59, + aux_sym__basic_string_repeat1 = 60, + aux_sym__multiline_basic_string_repeat1 = 61, + aux_sym__multiline_literal_string_repeat1 = 62, + aux_sym_array_repeat1 = 63, + aux_sym_array_repeat2 = 64, + aux_sym_inline_table_repeat1 = 65, +}; + +static const char * const ts_symbol_names[] = { + [ts_builtin_sym_end] = "end", + [aux_sym_document_token1] = "document_token1", + [sym_comment] = "comment", + [anon_sym_LBRACK] = "[", + [anon_sym_RBRACK] = "]", + [anon_sym_LBRACK_LBRACK] = "[[", + [anon_sym_RBRACK_RBRACK] = "]]", + [anon_sym_EQ] = "=", + [anon_sym_DOT] = ".", + [sym_bare_key] = "bare_key", + [anon_sym_DQUOTE] = "\"", + [aux_sym__basic_string_token1] = "_basic_string_token1", + [anon_sym_DQUOTE2] = "\"", + [anon_sym_DQUOTE_DQUOTE_DQUOTE] = "\"\"\"", + [aux_sym__multiline_basic_string_token1] = "_multiline_basic_string_token1", + [sym_escape_sequence] = "escape_sequence", + [sym__escape_line_ending] = "escape_sequence", + [anon_sym_SQUOTE] = "'", + [aux_sym__literal_string_token1] = "_literal_string_token1", + [anon_sym_SQUOTE2] = "'", + [anon_sym_SQUOTE_SQUOTE_SQUOTE] = "'''", + [aux_sym_integer_token1] = "integer_token1", + [aux_sym_integer_token2] = "integer_token2", + [aux_sym_integer_token3] = "integer_token3", + [aux_sym_integer_token4] = "integer_token4", + [aux_sym_float_token1] = "float_token1", + [aux_sym_float_token2] = "float_token2", + [sym_boolean] = "boolean", + [sym_offset_date_time] = "offset_date_time", + [sym_local_date_time] = "local_date_time", + [sym_local_date] = "local_date", + [sym_local_time] = "local_time", + [anon_sym_COMMA] = ",", + [anon_sym_LBRACE] = "{", + [anon_sym_RBRACE] = "}", + [sym__line_ending_or_eof] = "_line_ending_or_eof", + [sym__multiline_basic_string_content] = "_multiline_basic_string_content", + [sym__multiline_basic_string_end] = "_multiline_basic_string_end", + [sym__multiline_literal_string_content] = "_multiline_literal_string_content", + [sym__multiline_literal_string_end] = "_multiline_literal_string_end", + [sym_document] = "document", + [sym_table] = "table", + [sym_table_array_element] = "table_array_element", + [sym_pair] = "pair", + [sym__inline_pair] = "_inline_pair", + [sym__key] = "_key", + [sym_dotted_key] = "dotted_key", + [sym_quoted_key] = "quoted_key", + [sym__inline_value] = "_inline_value", + [sym_string] = "string", + [sym__basic_string] = "_basic_string", + [sym__multiline_basic_string] = "_multiline_basic_string", + [sym__literal_string] = "_literal_string", + [sym__multiline_literal_string] = "_multiline_literal_string", + [sym_integer] = "integer", + [sym_float] = "float", + [sym_array] = "array", + [sym_inline_table] = "inline_table", + [aux_sym_document_repeat1] = "document_repeat1", + [aux_sym_document_repeat2] = "document_repeat2", + [aux_sym__basic_string_repeat1] = "_basic_string_repeat1", + [aux_sym__multiline_basic_string_repeat1] = "_multiline_basic_string_repeat1", + [aux_sym__multiline_literal_string_repeat1] = "_multiline_literal_string_repeat1", + [aux_sym_array_repeat1] = "array_repeat1", + [aux_sym_array_repeat2] = "array_repeat2", + [aux_sym_inline_table_repeat1] = "inline_table_repeat1", +}; + +static const TSSymbol ts_symbol_map[] = { + [ts_builtin_sym_end] = ts_builtin_sym_end, + [aux_sym_document_token1] = aux_sym_document_token1, + [sym_comment] = sym_comment, + [anon_sym_LBRACK] = anon_sym_LBRACK, + [anon_sym_RBRACK] = anon_sym_RBRACK, + [anon_sym_LBRACK_LBRACK] = anon_sym_LBRACK_LBRACK, + [anon_sym_RBRACK_RBRACK] = anon_sym_RBRACK_RBRACK, + [anon_sym_EQ] = anon_sym_EQ, + [anon_sym_DOT] = anon_sym_DOT, + [sym_bare_key] = sym_bare_key, + [anon_sym_DQUOTE] = anon_sym_DQUOTE, + [aux_sym__basic_string_token1] = aux_sym__basic_string_token1, + [anon_sym_DQUOTE2] = anon_sym_DQUOTE, + [anon_sym_DQUOTE_DQUOTE_DQUOTE] = anon_sym_DQUOTE_DQUOTE_DQUOTE, + [aux_sym__multiline_basic_string_token1] = aux_sym__multiline_basic_string_token1, + [sym_escape_sequence] = sym_escape_sequence, + [sym__escape_line_ending] = sym_escape_sequence, + [anon_sym_SQUOTE] = anon_sym_SQUOTE, + [aux_sym__literal_string_token1] = aux_sym__literal_string_token1, + [anon_sym_SQUOTE2] = anon_sym_SQUOTE, + [anon_sym_SQUOTE_SQUOTE_SQUOTE] = anon_sym_SQUOTE_SQUOTE_SQUOTE, + [aux_sym_integer_token1] = aux_sym_integer_token1, + [aux_sym_integer_token2] = aux_sym_integer_token2, + [aux_sym_integer_token3] = aux_sym_integer_token3, + [aux_sym_integer_token4] = aux_sym_integer_token4, + [aux_sym_float_token1] = aux_sym_float_token1, + [aux_sym_float_token2] = aux_sym_float_token2, + [sym_boolean] = sym_boolean, + [sym_offset_date_time] = sym_offset_date_time, + [sym_local_date_time] = sym_local_date_time, + [sym_local_date] = sym_local_date, + [sym_local_time] = sym_local_time, + [anon_sym_COMMA] = anon_sym_COMMA, + [anon_sym_LBRACE] = anon_sym_LBRACE, + [anon_sym_RBRACE] = anon_sym_RBRACE, + [sym__line_ending_or_eof] = sym__line_ending_or_eof, + [sym__multiline_basic_string_content] = sym__multiline_basic_string_content, + [sym__multiline_basic_string_end] = sym__multiline_basic_string_end, + [sym__multiline_literal_string_content] = sym__multiline_literal_string_content, + [sym__multiline_literal_string_end] = sym__multiline_literal_string_end, + [sym_document] = sym_document, + [sym_table] = sym_table, + [sym_table_array_element] = sym_table_array_element, + [sym_pair] = sym_pair, + [sym__inline_pair] = sym__inline_pair, + [sym__key] = sym__key, + [sym_dotted_key] = sym_dotted_key, + [sym_quoted_key] = sym_quoted_key, + [sym__inline_value] = sym__inline_value, + [sym_string] = sym_string, + [sym__basic_string] = sym__basic_string, + [sym__multiline_basic_string] = sym__multiline_basic_string, + [sym__literal_string] = sym__literal_string, + [sym__multiline_literal_string] = sym__multiline_literal_string, + [sym_integer] = sym_integer, + [sym_float] = sym_float, + [sym_array] = sym_array, + [sym_inline_table] = sym_inline_table, + [aux_sym_document_repeat1] = aux_sym_document_repeat1, + [aux_sym_document_repeat2] = aux_sym_document_repeat2, + [aux_sym__basic_string_repeat1] = aux_sym__basic_string_repeat1, + [aux_sym__multiline_basic_string_repeat1] = aux_sym__multiline_basic_string_repeat1, + [aux_sym__multiline_literal_string_repeat1] = aux_sym__multiline_literal_string_repeat1, + [aux_sym_array_repeat1] = aux_sym_array_repeat1, + [aux_sym_array_repeat2] = aux_sym_array_repeat2, + [aux_sym_inline_table_repeat1] = aux_sym_inline_table_repeat1, +}; + +static const TSSymbolMetadata ts_symbol_metadata[] = { + [ts_builtin_sym_end] = { + .visible = false, + .named = true, + }, + [aux_sym_document_token1] = { + .visible = false, + .named = false, + }, + [sym_comment] = { + .visible = true, + .named = true, + }, + [anon_sym_LBRACK] = { + .visible = true, + .named = false, + }, + [anon_sym_RBRACK] = { + .visible = true, + .named = false, + }, + [anon_sym_LBRACK_LBRACK] = { + .visible = true, + .named = false, + }, + [anon_sym_RBRACK_RBRACK] = { + .visible = true, + .named = false, + }, + [anon_sym_EQ] = { + .visible = true, + .named = false, + }, + [anon_sym_DOT] = { + .visible = true, + .named = false, + }, + [sym_bare_key] = { + .visible = true, + .named = true, + }, + [anon_sym_DQUOTE] = { + .visible = true, + .named = false, + }, + [aux_sym__basic_string_token1] = { + .visible = false, + .named = false, + }, + [anon_sym_DQUOTE2] = { + .visible = true, + .named = false, + }, + [anon_sym_DQUOTE_DQUOTE_DQUOTE] = { + .visible = true, + .named = false, + }, + [aux_sym__multiline_basic_string_token1] = { + .visible = false, + .named = false, + }, + [sym_escape_sequence] = { + .visible = true, + .named = true, + }, + [sym__escape_line_ending] = { + .visible = true, + .named = true, + }, + [anon_sym_SQUOTE] = { + .visible = true, + .named = false, + }, + [aux_sym__literal_string_token1] = { + .visible = false, + .named = false, + }, + [anon_sym_SQUOTE2] = { + .visible = true, + .named = false, + }, + [anon_sym_SQUOTE_SQUOTE_SQUOTE] = { + .visible = true, + .named = false, + }, + [aux_sym_integer_token1] = { + .visible = false, + .named = false, + }, + [aux_sym_integer_token2] = { + .visible = false, + .named = false, + }, + [aux_sym_integer_token3] = { + .visible = false, + .named = false, + }, + [aux_sym_integer_token4] = { + .visible = false, + .named = false, + }, + [aux_sym_float_token1] = { + .visible = false, + .named = false, + }, + [aux_sym_float_token2] = { + .visible = false, + .named = false, + }, + [sym_boolean] = { + .visible = true, + .named = true, + }, + [sym_offset_date_time] = { + .visible = true, + .named = true, + }, + [sym_local_date_time] = { + .visible = true, + .named = true, + }, + [sym_local_date] = { + .visible = true, + .named = true, + }, + [sym_local_time] = { + .visible = true, + .named = true, + }, + [anon_sym_COMMA] = { + .visible = true, + .named = false, + }, + [anon_sym_LBRACE] = { + .visible = true, + .named = false, + }, + [anon_sym_RBRACE] = { + .visible = true, + .named = false, + }, + [sym__line_ending_or_eof] = { + .visible = false, + .named = true, + }, + [sym__multiline_basic_string_content] = { + .visible = false, + .named = true, + }, + [sym__multiline_basic_string_end] = { + .visible = false, + .named = true, + }, + [sym__multiline_literal_string_content] = { + .visible = false, + .named = true, + }, + [sym__multiline_literal_string_end] = { + .visible = false, + .named = true, + }, + [sym_document] = { + .visible = true, + .named = true, + }, + [sym_table] = { + .visible = true, + .named = true, + }, + [sym_table_array_element] = { + .visible = true, + .named = true, + }, + [sym_pair] = { + .visible = true, + .named = true, + }, + [sym__inline_pair] = { + .visible = false, + .named = true, + }, + [sym__key] = { + .visible = false, + .named = true, + }, + [sym_dotted_key] = { + .visible = true, + .named = true, + }, + [sym_quoted_key] = { + .visible = true, + .named = true, + }, + [sym__inline_value] = { + .visible = false, + .named = true, + }, + [sym_string] = { + .visible = true, + .named = true, + }, + [sym__basic_string] = { + .visible = false, + .named = true, + }, + [sym__multiline_basic_string] = { + .visible = false, + .named = true, + }, + [sym__literal_string] = { + .visible = false, + .named = true, + }, + [sym__multiline_literal_string] = { + .visible = false, + .named = true, + }, + [sym_integer] = { + .visible = true, + .named = true, + }, + [sym_float] = { + .visible = true, + .named = true, + }, + [sym_array] = { + .visible = true, + .named = true, + }, + [sym_inline_table] = { + .visible = true, + .named = true, + }, + [aux_sym_document_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym_document_repeat2] = { + .visible = false, + .named = false, + }, + [aux_sym__basic_string_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__multiline_basic_string_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__multiline_literal_string_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym_array_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym_array_repeat2] = { + .visible = false, + .named = false, + }, + [aux_sym_inline_table_repeat1] = { + .visible = false, + .named = false, + }, +}; + +static const TSSymbol ts_alias_sequences[PRODUCTION_ID_COUNT][MAX_ALIAS_SEQUENCE_LENGTH] = { + [0] = {0}, + [1] = { + [1] = sym_pair, + }, +}; + +static const uint16_t ts_non_terminal_alias_map[] = { + sym__inline_pair, 2, + sym__inline_pair, + sym_pair, + 0, +}; + +static const TSStateId ts_primary_state_ids[STATE_COUNT] = { + [0] = 0, + [1] = 1, + [2] = 2, + [3] = 3, + [4] = 4, + [5] = 5, + [6] = 6, + [7] = 2, + [8] = 8, + [9] = 9, + [10] = 10, + [11] = 9, + [12] = 12, + [13] = 13, + [14] = 5, + [15] = 3, + [16] = 8, + [17] = 6, + [18] = 4, + [19] = 10, + [20] = 12, + [21] = 13, + [22] = 22, + [23] = 23, + [24] = 24, + [25] = 24, + [26] = 26, + [27] = 27, + [28] = 28, + [29] = 29, + [30] = 30, + [31] = 31, + [32] = 32, + [33] = 33, + [34] = 33, + [35] = 35, + [36] = 36, + [37] = 37, + [38] = 38, + [39] = 39, + [40] = 40, + [41] = 41, + [42] = 40, + [43] = 43, + [44] = 41, + [45] = 43, + [46] = 46, + [47] = 47, + [48] = 48, + [49] = 49, + [50] = 50, + [51] = 51, + [52] = 52, + [53] = 53, + [54] = 54, + [55] = 55, + [56] = 56, + [57] = 57, + [58] = 58, + [59] = 57, + [60] = 58, + [61] = 61, + [62] = 61, + [63] = 54, + [64] = 56, + [65] = 53, + [66] = 66, + [67] = 67, + [68] = 68, + [69] = 69, + [70] = 70, + [71] = 71, + [72] = 72, + [73] = 73, + [74] = 74, + [75] = 75, + [76] = 76, + [77] = 77, + [78] = 78, + [79] = 79, + [80] = 80, + [81] = 81, + [82] = 82, + [83] = 83, + [84] = 84, + [85] = 85, + [86] = 86, + [87] = 87, + [88] = 88, + [89] = 67, + [90] = 88, + [91] = 67, + [92] = 92, + [93] = 88, + [94] = 94, + [95] = 95, + [96] = 96, + [97] = 97, + [98] = 94, + [99] = 99, + [100] = 97, + [101] = 99, + [102] = 102, + [103] = 102, + [104] = 104, + [105] = 104, + [106] = 106, + [107] = 107, + [108] = 108, + [109] = 109, + [110] = 47, + [111] = 48, + [112] = 51, + [113] = 52, + [114] = 114, + [115] = 115, + [116] = 114, + [117] = 117, + [118] = 107, + [119] = 109, + [120] = 120, + [121] = 114, + [122] = 96, + [123] = 78, + [124] = 48, + [125] = 125, + [126] = 79, + [127] = 127, + [128] = 75, + [129] = 71, + [130] = 81, + [131] = 51, + [132] = 76, + [133] = 84, + [134] = 85, + [135] = 82, + [136] = 72, + [137] = 77, + [138] = 115, + [139] = 73, + [140] = 86, + [141] = 141, + [142] = 142, + [143] = 83, + [144] = 47, + [145] = 145, + [146] = 141, + [147] = 87, + [148] = 52, + [149] = 74, + [150] = 141, + [151] = 80, +}; + +static bool ts_lex(TSLexer *lexer, TSStateId state) { + START_LEXER(); + eof = lexer->eof(lexer); + switch (state) { + case 0: + if (eof) ADVANCE(77); + ADVANCE_MAP( + '\n', 129, + '\r', 1, + '"', 127, + '#', 79, + '\'', 137, + '+', 15, + ',', 161, + '-', 95, + '.', 86, + '0', 92, + '1', 90, + '2', 89, + '=', 85, + '[', 81, + '\\', 5, + ']', 82, + 'f', 102, + 'i', 108, + 'n', 103, + 't', 109, + '{', 162, + '}', 163, + ); + if (lookahead == '\t' || + lookahead == ' ') SKIP(75); + if (('3' <= lookahead && lookahead <= '9')) ADVANCE(91); + if (('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 1: + if (lookahead == '\n') ADVANCE(129); + END_STATE(); + case 2: + if (lookahead == '\n') ADVANCE(129); + if (lookahead == '\r') ADVANCE(1); + if (lookahead == '"') ADVANCE(126); + if (lookahead == '#') ADVANCE(125); + if (lookahead == '\\') ADVANCE(5); + if (lookahead == '\t' || + lookahead == ' ') ADVANCE(124); + if (lookahead > ' ' && + lookahead != 0x7f) ADVANCE(125); + END_STATE(); + case 3: + if (lookahead == '\n') ADVANCE(129); + if (lookahead == '\r') ADVANCE(1); + if (lookahead == '#') ADVANCE(135); + if (lookahead == '\'') ADVANCE(136); + if (lookahead == '\t' || + lookahead == ' ') ADVANCE(134); + if (lookahead > ' ' && + lookahead != 0x7f) ADVANCE(135); + END_STATE(); + case 4: + if (lookahead == '\n') ADVANCE(131); + END_STATE(); + case 5: + ADVANCE_MAP( + '\n', 131, + '\r', 4, + 'U', 74, + 'u', 70, + '"', 130, + '\\', 130, + 'b', 130, + 'f', 130, + 'n', 130, + 'r', 130, + 't', 130, + ); + END_STATE(); + case 6: + if (lookahead == '\n') ADVANCE(78); + END_STATE(); + case 7: + ADVANCE_MAP( + '\n', 78, + '\r', 6, + '"', 123, + '#', 79, + '\'', 133, + ',', 161, + '0', 144, + '1', 142, + '2', 141, + '[', 80, + ']', 82, + 'f', 30, + 'i', 35, + 'n', 31, + 't', 37, + '{', 162, + ); + if (lookahead == '\t' || + lookahead == ' ') SKIP(7); + if (('+' <= lookahead && lookahead <= '-')) ADVANCE(17); + if (('3' <= lookahead && lookahead <= '9')) ADVANCE(143); + END_STATE(); + case 8: + if (lookahead == '"') ADVANCE(128); + END_STATE(); + case 9: + if (lookahead == '#') ADVANCE(79); + if (lookahead == '\'') ADVANCE(136); + if (lookahead == '.') ADVANCE(86); + if (lookahead == ']') ADVANCE(29); + if (lookahead == '\t' || + lookahead == ' ') SKIP(10); + END_STATE(); + case 10: + if (lookahead == '#') ADVANCE(79); + if (lookahead == '.') ADVANCE(86); + if (lookahead == ']') ADVANCE(29); + if (lookahead == '\t' || + lookahead == ' ') SKIP(10); + END_STATE(); + case 11: + if (lookahead == '\'') ADVANCE(138); + END_STATE(); + case 12: + if (lookahead == '-') ADVANCE(18); + if (lookahead == ':') ADVANCE(46); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(13); + END_STATE(); + case 13: + if (lookahead == '-') ADVANCE(18); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(13); + END_STATE(); + case 14: + if (lookahead == '-') ADVANCE(20); + END_STATE(); + case 15: + if (lookahead == '0') ADVANCE(139); + if (lookahead == 'i') ADVANCE(35); + if (lookahead == 'n') ADVANCE(31); + if (('1' <= lookahead && lookahead <= '9')) ADVANCE(147); + END_STATE(); + case 16: + if (lookahead == '0') ADVANCE(159); + END_STATE(); + case 17: + if (lookahead == '0') ADVANCE(146); + if (lookahead == 'i') ADVANCE(35); + if (lookahead == 'n') ADVANCE(31); + if (('1' <= lookahead && lookahead <= '9')) ADVANCE(145); + END_STATE(); + case 18: + if (lookahead == '0') ADVANCE(50); + if (lookahead == '1') ADVANCE(43); + END_STATE(); + case 19: + if (lookahead == '0') ADVANCE(156); + END_STATE(); + case 20: + if (lookahead == '0') ADVANCE(51); + if (lookahead == '3') ADVANCE(42); + if (lookahead == '1' || + lookahead == '2') ADVANCE(59); + END_STATE(); + case 21: + if (lookahead == '2') ADVANCE(44); + if (lookahead == '0' || + lookahead == '1') ADVANCE(63); + END_STATE(); + case 22: + if (lookahead == '2') ADVANCE(45); + if (lookahead == '0' || + lookahead == '1') ADVANCE(64); + END_STATE(); + case 23: + if (lookahead == '6') ADVANCE(16); + if (('0' <= lookahead && lookahead <= '5')) ADVANCE(54); + END_STATE(); + case 24: + if (lookahead == '6') ADVANCE(19); + if (('0' <= lookahead && lookahead <= '5')) ADVANCE(60); + END_STATE(); + case 25: + if (lookahead == ':') ADVANCE(23); + END_STATE(); + case 26: + if (lookahead == ':') ADVANCE(47); + END_STATE(); + case 27: + if (lookahead == ':') ADVANCE(24); + END_STATE(); + case 28: + if (lookahead == ':') ADVANCE(48); + END_STATE(); + case 29: + if (lookahead == ']') ADVANCE(84); + END_STATE(); + case 30: + if (lookahead == 'a') ADVANCE(34); + END_STATE(); + case 31: + if (lookahead == 'a') ADVANCE(36); + END_STATE(); + case 32: + if (lookahead == 'e') ADVANCE(154); + END_STATE(); + case 33: + if (lookahead == 'f') ADVANCE(153); + END_STATE(); + case 34: + if (lookahead == 'l') ADVANCE(38); + END_STATE(); + case 35: + if (lookahead == 'n') ADVANCE(33); + END_STATE(); + case 36: + if (lookahead == 'n') ADVANCE(153); + END_STATE(); + case 37: + if (lookahead == 'r') ADVANCE(39); + END_STATE(); + case 38: + if (lookahead == 's') ADVANCE(32); + END_STATE(); + case 39: + if (lookahead == 'u') ADVANCE(32); + END_STATE(); + case 40: + if (lookahead == '+' || + lookahead == '-') ADVANCE(58); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(152); + END_STATE(); + case 41: + if (lookahead == '0' || + lookahead == '1') ADVANCE(150); + END_STATE(); + case 42: + if (lookahead == '0' || + lookahead == '1') ADVANCE(158); + END_STATE(); + case 43: + if (('0' <= lookahead && lookahead <= '2')) ADVANCE(14); + END_STATE(); + case 44: + if (('0' <= lookahead && lookahead <= '3')) ADVANCE(28); + END_STATE(); + case 45: + if (('0' <= lookahead && lookahead <= '3')) ADVANCE(26); + END_STATE(); + case 46: + if (('0' <= lookahead && lookahead <= '5')) ADVANCE(53); + END_STATE(); + case 47: + if (('0' <= lookahead && lookahead <= '5')) ADVANCE(61); + END_STATE(); + case 48: + if (('0' <= lookahead && lookahead <= '5')) ADVANCE(65); + END_STATE(); + case 49: + if (('0' <= lookahead && lookahead <= '7')) ADVANCE(149); + END_STATE(); + case 50: + if (('1' <= lookahead && lookahead <= '9')) ADVANCE(14); + END_STATE(); + case 51: + if (('1' <= lookahead && lookahead <= '9')) ADVANCE(158); + END_STATE(); + case 52: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(147); + END_STATE(); + case 53: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(25); + END_STATE(); + case 54: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(159); + END_STATE(); + case 55: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(160); + END_STATE(); + case 56: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(145); + END_STATE(); + case 57: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(151); + END_STATE(); + case 58: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(152); + END_STATE(); + case 59: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(158); + END_STATE(); + case 60: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(156); + END_STATE(); + case 61: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(155); + END_STATE(); + case 62: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(157); + END_STATE(); + case 63: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(28); + END_STATE(); + case 64: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(26); + END_STATE(); + case 65: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(27); + END_STATE(); + case 66: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(130); + END_STATE(); + case 67: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(148); + END_STATE(); + case 68: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(66); + END_STATE(); + case 69: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(68); + END_STATE(); + case 70: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(69); + END_STATE(); + case 71: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(70); + END_STATE(); + case 72: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(71); + END_STATE(); + case 73: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(72); + END_STATE(); + case 74: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(73); + END_STATE(); + case 75: + if (eof) ADVANCE(77); + ADVANCE_MAP( + '\n', 78, + '\r', 6, + '"', 123, + '#', 79, + '\'', 133, + '+', 15, + ',', 161, + '-', 95, + '.', 86, + '0', 92, + '1', 90, + '2', 89, + '=', 85, + '[', 81, + ']', 82, + 'f', 102, + 'i', 108, + 'n', 103, + 't', 109, + '{', 162, + '}', 163, + ); + if (lookahead == '\t' || + lookahead == ' ') SKIP(75); + if (('3' <= lookahead && lookahead <= '9')) ADVANCE(91); + if (('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 76: + if (eof) ADVANCE(77); + ADVANCE_MAP( + '\n', 78, + '\r', 6, + '"', 122, + '#', 79, + '\'', 132, + ',', 161, + '.', 86, + '=', 85, + '[', 81, + ']', 82, + '}', 163, + ); + if (lookahead == '\t' || + lookahead == ' ') SKIP(76); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 77: + ACCEPT_TOKEN(ts_builtin_sym_end); + END_STATE(); + case 78: + ACCEPT_TOKEN(aux_sym_document_token1); + END_STATE(); + case 79: + ACCEPT_TOKEN(sym_comment); + if (lookahead > 0x08 && + (lookahead < '\n' || 0x1f < lookahead) && + lookahead != 0x7f) ADVANCE(79); + END_STATE(); + case 80: + ACCEPT_TOKEN(anon_sym_LBRACK); + END_STATE(); + case 81: + ACCEPT_TOKEN(anon_sym_LBRACK); + if (lookahead == '[') ADVANCE(83); + END_STATE(); + case 82: + ACCEPT_TOKEN(anon_sym_RBRACK); + END_STATE(); + case 83: + ACCEPT_TOKEN(anon_sym_LBRACK_LBRACK); + END_STATE(); + case 84: + ACCEPT_TOKEN(anon_sym_RBRACK_RBRACK); + END_STATE(); + case 85: + ACCEPT_TOKEN(anon_sym_EQ); + END_STATE(); + case 86: + ACCEPT_TOKEN(anon_sym_DOT); + END_STATE(); + case 87: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-') ADVANCE(96); + if (lookahead == ':') ADVANCE(46); + if (lookahead == '_') ADVANCE(119); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(91); + if (('A' <= lookahead && lookahead <= 'Z') || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 88: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-') ADVANCE(96); + if (lookahead == ':') ADVANCE(46); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(93); + if (('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 89: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-') ADVANCE(96); + if (lookahead == '_') ADVANCE(119); + if (('0' <= lookahead && lookahead <= '3')) ADVANCE(87); + if (('4' <= lookahead && lookahead <= '9')) ADVANCE(91); + if (('A' <= lookahead && lookahead <= 'Z') || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 90: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-') ADVANCE(96); + if (lookahead == '_') ADVANCE(119); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(87); + if (('A' <= lookahead && lookahead <= 'Z') || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 91: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-') ADVANCE(96); + if (lookahead == '_') ADVANCE(119); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(91); + if (('A' <= lookahead && lookahead <= 'Z') || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 92: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-') ADVANCE(96); + if (lookahead == 'b') ADVANCE(113); + if (lookahead == 'o') ADVANCE(115); + if (lookahead == 'x') ADVANCE(120); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(88); + if (('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 93: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-') ADVANCE(96); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(93); + if (('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 94: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-') ADVANCE(97); + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 95: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '0') ADVANCE(121); + if (lookahead == 'i') ADVANCE(108); + if (lookahead == 'n') ADVANCE(103); + if (('1' <= lookahead && lookahead <= '9')) ADVANCE(101); + if (lookahead == '-' || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 96: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '0') ADVANCE(117); + if (lookahead == '1') ADVANCE(114); + if (lookahead == '-' || + ('2' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 97: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '0') ADVANCE(116); + if (lookahead == '3') ADVANCE(112); + if (lookahead == '1' || + lookahead == '2') ADVANCE(118); + if (lookahead == '-' || + ('4' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 98: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '_') ADVANCE(113); + if (lookahead == '0' || + lookahead == '1') ADVANCE(98); + if (lookahead == '-' || + ('2' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 99: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '_') ADVANCE(115); + if (('0' <= lookahead && lookahead <= '7')) ADVANCE(99); + if (lookahead == '-' || + lookahead == '8' || + lookahead == '9' || + ('A' <= lookahead && lookahead <= 'Z') || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 100: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '_') ADVANCE(120); + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(100); + if (lookahead == '-' || + ('G' <= lookahead && lookahead <= 'Z') || + ('g' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 101: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '_') ADVANCE(119); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(101); + if (lookahead == '-' || + ('A' <= lookahead && lookahead <= 'Z') || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 102: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'a') ADVANCE(106); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('b' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 103: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'a') ADVANCE(107); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('b' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 104: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'e') ADVANCE(121); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 105: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'f') ADVANCE(121); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 106: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'l') ADVANCE(110); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 107: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'n') ADVANCE(121); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 108: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'n') ADVANCE(105); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 109: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'r') ADVANCE(111); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 110: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 's') ADVANCE(104); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 111: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'u') ADVANCE(104); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 112: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '0' || + lookahead == '1') ADVANCE(121); + if (lookahead == '-' || + ('2' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 113: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '0' || + lookahead == '1') ADVANCE(98); + if (lookahead == '-' || + ('2' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 114: + ACCEPT_TOKEN(sym_bare_key); + if (('0' <= lookahead && lookahead <= '2')) ADVANCE(94); + if (lookahead == '-' || + ('3' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 115: + ACCEPT_TOKEN(sym_bare_key); + if (('0' <= lookahead && lookahead <= '7')) ADVANCE(99); + if (lookahead == '-' || + lookahead == '8' || + lookahead == '9' || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 116: + ACCEPT_TOKEN(sym_bare_key); + if (('1' <= lookahead && lookahead <= '9')) ADVANCE(121); + if (lookahead == '-' || + lookahead == '0' || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 117: + ACCEPT_TOKEN(sym_bare_key); + if (('1' <= lookahead && lookahead <= '9')) ADVANCE(94); + if (lookahead == '-' || + lookahead == '0' || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 118: + ACCEPT_TOKEN(sym_bare_key); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(121); + if (lookahead == '-' || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 119: + ACCEPT_TOKEN(sym_bare_key); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(101); + if (lookahead == '-' || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 120: + ACCEPT_TOKEN(sym_bare_key); + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(100); + if (lookahead == '-' || + ('G' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('g' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 121: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 122: + ACCEPT_TOKEN(anon_sym_DQUOTE); + END_STATE(); + case 123: + ACCEPT_TOKEN(anon_sym_DQUOTE); + if (lookahead == '"') ADVANCE(8); + END_STATE(); + case 124: + ACCEPT_TOKEN(aux_sym__basic_string_token1); + if (lookahead == '#') ADVANCE(125); + if (lookahead == '\t' || + lookahead == ' ') ADVANCE(124); + if (lookahead > ' ' && + lookahead != '"' && + lookahead != '#' && + lookahead != '\\' && + lookahead != 0x7f) ADVANCE(125); + END_STATE(); + case 125: + ACCEPT_TOKEN(aux_sym__basic_string_token1); + if (lookahead > 0x08 && + (lookahead < '\n' || 0x1f < lookahead) && + lookahead != '"' && + lookahead != '\\' && + lookahead != 0x7f) ADVANCE(125); + END_STATE(); + case 126: + ACCEPT_TOKEN(anon_sym_DQUOTE2); + END_STATE(); + case 127: + ACCEPT_TOKEN(anon_sym_DQUOTE2); + if (lookahead == '"') ADVANCE(8); + END_STATE(); + case 128: + ACCEPT_TOKEN(anon_sym_DQUOTE_DQUOTE_DQUOTE); + END_STATE(); + case 129: + ACCEPT_TOKEN(aux_sym__multiline_basic_string_token1); + END_STATE(); + case 130: + ACCEPT_TOKEN(sym_escape_sequence); + END_STATE(); + case 131: + ACCEPT_TOKEN(sym__escape_line_ending); + END_STATE(); + case 132: + ACCEPT_TOKEN(anon_sym_SQUOTE); + END_STATE(); + case 133: + ACCEPT_TOKEN(anon_sym_SQUOTE); + if (lookahead == '\'') ADVANCE(11); + END_STATE(); + case 134: + ACCEPT_TOKEN(aux_sym__literal_string_token1); + if (lookahead == '#') ADVANCE(135); + if (lookahead == '\t' || + lookahead == ' ') ADVANCE(134); + if (lookahead > ' ' && + lookahead != '\'' && + lookahead != 0x7f) ADVANCE(135); + END_STATE(); + case 135: + ACCEPT_TOKEN(aux_sym__literal_string_token1); + if (lookahead > 0x08 && + (lookahead < '\n' || 0x1f < lookahead) && + lookahead != '\'' && + lookahead != 0x7f) ADVANCE(135); + END_STATE(); + case 136: + ACCEPT_TOKEN(anon_sym_SQUOTE2); + END_STATE(); + case 137: + ACCEPT_TOKEN(anon_sym_SQUOTE2); + if (lookahead == '\'') ADVANCE(11); + END_STATE(); + case 138: + ACCEPT_TOKEN(anon_sym_SQUOTE_SQUOTE_SQUOTE); + END_STATE(); + case 139: + ACCEPT_TOKEN(aux_sym_integer_token1); + END_STATE(); + case 140: + ACCEPT_TOKEN(aux_sym_integer_token1); + if (lookahead == '-') ADVANCE(18); + if (lookahead == '.') ADVANCE(57); + if (lookahead == ':') ADVANCE(46); + if (lookahead == '_') ADVANCE(56); + if (lookahead == 'E' || + lookahead == 'e') ADVANCE(40); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(143); + END_STATE(); + case 141: + ACCEPT_TOKEN(aux_sym_integer_token1); + if (lookahead == '-') ADVANCE(18); + if (lookahead == '.') ADVANCE(57); + if (lookahead == '_') ADVANCE(56); + if (lookahead == 'E' || + lookahead == 'e') ADVANCE(40); + if (('0' <= lookahead && lookahead <= '3')) ADVANCE(140); + if (('4' <= lookahead && lookahead <= '9')) ADVANCE(143); + END_STATE(); + case 142: + ACCEPT_TOKEN(aux_sym_integer_token1); + if (lookahead == '-') ADVANCE(18); + if (lookahead == '.') ADVANCE(57); + if (lookahead == '_') ADVANCE(56); + if (lookahead == 'E' || + lookahead == 'e') ADVANCE(40); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(140); + END_STATE(); + case 143: + ACCEPT_TOKEN(aux_sym_integer_token1); + if (lookahead == '-') ADVANCE(18); + if (lookahead == '.') ADVANCE(57); + if (lookahead == '_') ADVANCE(56); + if (lookahead == 'E' || + lookahead == 'e') ADVANCE(40); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(143); + END_STATE(); + case 144: + ACCEPT_TOKEN(aux_sym_integer_token1); + if (lookahead == '-') ADVANCE(18); + if (lookahead == '.') ADVANCE(57); + if (lookahead == 'b') ADVANCE(41); + if (lookahead == 'o') ADVANCE(49); + if (lookahead == 'x') ADVANCE(67); + if (lookahead == 'E' || + lookahead == 'e') ADVANCE(40); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(12); + END_STATE(); + case 145: + ACCEPT_TOKEN(aux_sym_integer_token1); + if (lookahead == '.') ADVANCE(57); + if (lookahead == '_') ADVANCE(56); + if (lookahead == 'E' || + lookahead == 'e') ADVANCE(40); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(145); + END_STATE(); + case 146: + ACCEPT_TOKEN(aux_sym_integer_token1); + if (lookahead == '.') ADVANCE(57); + if (lookahead == 'E' || + lookahead == 'e') ADVANCE(40); + END_STATE(); + case 147: + ACCEPT_TOKEN(aux_sym_integer_token1); + if (lookahead == '_') ADVANCE(52); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(147); + END_STATE(); + case 148: + ACCEPT_TOKEN(aux_sym_integer_token2); + if (lookahead == '_') ADVANCE(67); + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(148); + END_STATE(); + case 149: + ACCEPT_TOKEN(aux_sym_integer_token3); + if (lookahead == '_') ADVANCE(49); + if (('0' <= lookahead && lookahead <= '7')) ADVANCE(149); + END_STATE(); + case 150: + ACCEPT_TOKEN(aux_sym_integer_token4); + if (lookahead == '_') ADVANCE(41); + if (lookahead == '0' || + lookahead == '1') ADVANCE(150); + END_STATE(); + case 151: + ACCEPT_TOKEN(aux_sym_float_token1); + if (lookahead == '_') ADVANCE(57); + if (lookahead == 'E' || + lookahead == 'e') ADVANCE(40); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(151); + END_STATE(); + case 152: + ACCEPT_TOKEN(aux_sym_float_token1); + if (lookahead == '_') ADVANCE(58); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(152); + END_STATE(); + case 153: + ACCEPT_TOKEN(aux_sym_float_token2); + END_STATE(); + case 154: + ACCEPT_TOKEN(sym_boolean); + END_STATE(); + case 155: + ACCEPT_TOKEN(sym_offset_date_time); + END_STATE(); + case 156: + ACCEPT_TOKEN(sym_local_date_time); + if (lookahead == '.') ADVANCE(62); + if (lookahead == '+' || + lookahead == '-') ADVANCE(22); + if (lookahead == 'Z' || + lookahead == 'z') ADVANCE(155); + END_STATE(); + case 157: + ACCEPT_TOKEN(sym_local_date_time); + if (lookahead == '+' || + lookahead == '-') ADVANCE(22); + if (lookahead == 'Z' || + lookahead == 'z') ADVANCE(155); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(157); + END_STATE(); + case 158: + ACCEPT_TOKEN(sym_local_date); + if (lookahead == ' ' || + lookahead == 'T' || + lookahead == 't') ADVANCE(21); + END_STATE(); + case 159: + ACCEPT_TOKEN(sym_local_time); + if (lookahead == '.') ADVANCE(55); + END_STATE(); + case 160: + ACCEPT_TOKEN(sym_local_time); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(160); + END_STATE(); + case 161: + ACCEPT_TOKEN(anon_sym_COMMA); + END_STATE(); + case 162: + ACCEPT_TOKEN(anon_sym_LBRACE); + END_STATE(); + case 163: + ACCEPT_TOKEN(anon_sym_RBRACE); + END_STATE(); + default: + return false; + } +} + +static const TSLexMode ts_lex_modes[STATE_COUNT] = { + [0] = {.lex_state = 0, .external_lex_state = 1}, + [1] = {.lex_state = 76}, + [2] = {.lex_state = 7}, + [3] = {.lex_state = 7}, + [4] = {.lex_state = 7}, + [5] = {.lex_state = 7}, + [6] = {.lex_state = 7}, + [7] = {.lex_state = 7}, + [8] = {.lex_state = 7}, + [9] = {.lex_state = 7}, + [10] = {.lex_state = 7}, + [11] = {.lex_state = 7}, + [12] = {.lex_state = 7}, + [13] = {.lex_state = 7}, + [14] = {.lex_state = 7}, + [15] = {.lex_state = 7}, + [16] = {.lex_state = 7}, + [17] = {.lex_state = 7}, + [18] = {.lex_state = 7}, + [19] = {.lex_state = 7}, + [20] = {.lex_state = 7}, + [21] = {.lex_state = 7}, + [22] = {.lex_state = 7}, + [23] = {.lex_state = 7}, + [24] = {.lex_state = 7}, + [25] = {.lex_state = 7}, + [26] = {.lex_state = 7}, + [27] = {.lex_state = 76}, + [28] = {.lex_state = 76}, + [29] = {.lex_state = 76}, + [30] = {.lex_state = 76}, + [31] = {.lex_state = 76}, + [32] = {.lex_state = 76}, + [33] = {.lex_state = 76}, + [34] = {.lex_state = 76}, + [35] = {.lex_state = 76}, + [36] = {.lex_state = 76}, + [37] = {.lex_state = 76}, + [38] = {.lex_state = 76}, + [39] = {.lex_state = 2, .external_lex_state = 2}, + [40] = {.lex_state = 76}, + [41] = {.lex_state = 2, .external_lex_state = 2}, + [42] = {.lex_state = 76}, + [43] = {.lex_state = 2, .external_lex_state = 2}, + [44] = {.lex_state = 2, .external_lex_state = 2}, + [45] = {.lex_state = 2, .external_lex_state = 2}, + [46] = {.lex_state = 0}, + [47] = {.lex_state = 76}, + [48] = {.lex_state = 76}, + [49] = {.lex_state = 0}, + [50] = {.lex_state = 0}, + [51] = {.lex_state = 76}, + [52] = {.lex_state = 76}, + [53] = {.lex_state = 76}, + [54] = {.lex_state = 76}, + [55] = {.lex_state = 3, .external_lex_state = 3}, + [56] = {.lex_state = 76}, + [57] = {.lex_state = 3, .external_lex_state = 3}, + [58] = {.lex_state = 76}, + [59] = {.lex_state = 3, .external_lex_state = 3}, + [60] = {.lex_state = 76}, + [61] = {.lex_state = 3, .external_lex_state = 3}, + [62] = {.lex_state = 3, .external_lex_state = 3}, + [63] = {.lex_state = 76}, + [64] = {.lex_state = 76}, + [65] = {.lex_state = 76}, + [66] = {.lex_state = 2}, + [67] = {.lex_state = 2}, + [68] = {.lex_state = 76}, + [69] = {.lex_state = 76}, + [70] = {.lex_state = 76}, + [71] = {.lex_state = 76}, + [72] = {.lex_state = 76}, + [73] = {.lex_state = 76}, + [74] = {.lex_state = 76}, + [75] = {.lex_state = 76}, + [76] = {.lex_state = 76}, + [77] = {.lex_state = 76}, + [78] = {.lex_state = 76}, + [79] = {.lex_state = 76}, + [80] = {.lex_state = 76}, + [81] = {.lex_state = 76}, + [82] = {.lex_state = 76}, + [83] = {.lex_state = 76}, + [84] = {.lex_state = 76}, + [85] = {.lex_state = 76}, + [86] = {.lex_state = 76}, + [87] = {.lex_state = 76}, + [88] = {.lex_state = 2}, + [89] = {.lex_state = 2}, + [90] = {.lex_state = 2}, + [91] = {.lex_state = 2}, + [92] = {.lex_state = 76}, + [93] = {.lex_state = 2}, + [94] = {.lex_state = 0}, + [95] = {.lex_state = 0}, + [96] = {.lex_state = 0}, + [97] = {.lex_state = 0}, + [98] = {.lex_state = 0}, + [99] = {.lex_state = 0}, + [100] = {.lex_state = 0}, + [101] = {.lex_state = 0}, + [102] = {.lex_state = 0}, + [103] = {.lex_state = 0}, + [104] = {.lex_state = 0}, + [105] = {.lex_state = 0}, + [106] = {.lex_state = 0}, + [107] = {.lex_state = 0}, + [108] = {.lex_state = 0}, + [109] = {.lex_state = 0}, + [110] = {.lex_state = 9}, + [111] = {.lex_state = 9}, + [112] = {.lex_state = 9}, + [113] = {.lex_state = 9}, + [114] = {.lex_state = 3}, + [115] = {.lex_state = 0}, + [116] = {.lex_state = 3}, + [117] = {.lex_state = 0}, + [118] = {.lex_state = 9}, + [119] = {.lex_state = 0}, + [120] = {.lex_state = 9}, + [121] = {.lex_state = 3}, + [122] = {.lex_state = 9}, + [123] = {.lex_state = 0, .external_lex_state = 4}, + [124] = {.lex_state = 0, .external_lex_state = 4}, + [125] = {.lex_state = 0}, + [126] = {.lex_state = 0, .external_lex_state = 4}, + [127] = {.lex_state = 0, .external_lex_state = 4}, + [128] = {.lex_state = 0, .external_lex_state = 4}, + [129] = {.lex_state = 0, .external_lex_state = 4}, + [130] = {.lex_state = 0, .external_lex_state = 4}, + [131] = {.lex_state = 0, .external_lex_state = 4}, + [132] = {.lex_state = 0, .external_lex_state = 4}, + [133] = {.lex_state = 0, .external_lex_state = 4}, + [134] = {.lex_state = 0, .external_lex_state = 4}, + [135] = {.lex_state = 0, .external_lex_state = 4}, + [136] = {.lex_state = 0, .external_lex_state = 4}, + [137] = {.lex_state = 0, .external_lex_state = 4}, + [138] = {.lex_state = 0, .external_lex_state = 4}, + [139] = {.lex_state = 0, .external_lex_state = 4}, + [140] = {.lex_state = 0, .external_lex_state = 4}, + [141] = {.lex_state = 9}, + [142] = {.lex_state = 0, .external_lex_state = 4}, + [143] = {.lex_state = 0, .external_lex_state = 4}, + [144] = {.lex_state = 0, .external_lex_state = 4}, + [145] = {.lex_state = 0, .external_lex_state = 4}, + [146] = {.lex_state = 9}, + [147] = {.lex_state = 0, .external_lex_state = 4}, + [148] = {.lex_state = 0, .external_lex_state = 4}, + [149] = {.lex_state = 0, .external_lex_state = 4}, + [150] = {.lex_state = 9}, + [151] = {.lex_state = 0, .external_lex_state = 4}, +}; + +static const uint16_t ts_parse_table[LARGE_STATE_COUNT][SYMBOL_COUNT] = { + [0] = { + [ts_builtin_sym_end] = ACTIONS(1), + [aux_sym_document_token1] = ACTIONS(1), + [sym_comment] = ACTIONS(3), + [anon_sym_LBRACK] = ACTIONS(1), + [anon_sym_RBRACK] = ACTIONS(1), + [anon_sym_LBRACK_LBRACK] = ACTIONS(1), + [anon_sym_EQ] = ACTIONS(1), + [anon_sym_DOT] = ACTIONS(1), + [sym_bare_key] = ACTIONS(1), + [anon_sym_DQUOTE] = ACTIONS(1), + [anon_sym_DQUOTE2] = ACTIONS(1), + [anon_sym_DQUOTE_DQUOTE_DQUOTE] = ACTIONS(1), + [aux_sym__multiline_basic_string_token1] = ACTIONS(1), + [sym_escape_sequence] = ACTIONS(1), + [sym__escape_line_ending] = ACTIONS(1), + [anon_sym_SQUOTE] = ACTIONS(1), + [anon_sym_SQUOTE2] = ACTIONS(1), + [anon_sym_SQUOTE_SQUOTE_SQUOTE] = ACTIONS(1), + [aux_sym_integer_token1] = ACTIONS(1), + [aux_sym_integer_token2] = ACTIONS(1), + [aux_sym_integer_token3] = ACTIONS(1), + [aux_sym_integer_token4] = ACTIONS(1), + [aux_sym_float_token2] = ACTIONS(1), + [sym_boolean] = ACTIONS(1), + [sym_local_date] = ACTIONS(1), + [sym_local_time] = ACTIONS(1), + [anon_sym_COMMA] = ACTIONS(1), + [anon_sym_LBRACE] = ACTIONS(1), + [anon_sym_RBRACE] = ACTIONS(1), + [sym__line_ending_or_eof] = ACTIONS(1), + [sym__multiline_basic_string_content] = ACTIONS(1), + [sym__multiline_basic_string_end] = ACTIONS(1), + [sym__multiline_literal_string_content] = ACTIONS(1), + [sym__multiline_literal_string_end] = ACTIONS(1), + }, + [1] = { + [sym_document] = STATE(125), + [sym_table] = STATE(46), + [sym_table_array_element] = STATE(46), + [sym_pair] = STATE(27), + [sym__inline_pair] = STATE(127), + [sym__key] = STATE(119), + [sym_dotted_key] = STATE(119), + [sym_quoted_key] = STATE(119), + [sym__basic_string] = STATE(96), + [sym__literal_string] = STATE(96), + [aux_sym_document_repeat1] = STATE(27), + [aux_sym_document_repeat2] = STATE(46), + [ts_builtin_sym_end] = ACTIONS(5), + [aux_sym_document_token1] = ACTIONS(7), + [sym_comment] = ACTIONS(3), + [anon_sym_LBRACK] = ACTIONS(9), + [anon_sym_LBRACK_LBRACK] = ACTIONS(11), + [sym_bare_key] = ACTIONS(13), + [anon_sym_DQUOTE] = ACTIONS(15), + [anon_sym_SQUOTE] = ACTIONS(17), + }, +}; + +static const uint16_t ts_small_parse_table[] = { + [0] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(23), 1, + anon_sym_RBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(41), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(39), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(63), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [66] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(45), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [132] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(51), 1, + aux_sym_document_token1, + ACTIONS(53), 1, + anon_sym_RBRACK, + STATE(6), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [198] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(59), 1, + aux_sym_document_token1, + ACTIONS(61), 1, + anon_sym_RBRACK, + STATE(7), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(65), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(63), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(58), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [264] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(67), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [330] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(69), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(73), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(71), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(54), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [396] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(67), 1, + anon_sym_RBRACK, + ACTIONS(75), 1, + aux_sym_document_token1, + STATE(9), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [462] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(77), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [528] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(77), 1, + anon_sym_RBRACK, + ACTIONS(79), 1, + aux_sym_document_token1, + STATE(12), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [594] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(81), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [660] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(83), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [726] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(83), 1, + anon_sym_RBRACK, + ACTIONS(85), 1, + aux_sym_document_token1, + STATE(15), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [792] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(87), 1, + aux_sym_document_token1, + ACTIONS(89), 1, + anon_sym_RBRACK, + STATE(2), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(93), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(91), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(60), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [858] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(95), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [924] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(97), 1, + aux_sym_document_token1, + ACTIONS(99), 1, + anon_sym_RBRACK, + STATE(11), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [990] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(99), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1056] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(101), 1, + aux_sym_document_token1, + ACTIONS(103), 1, + anon_sym_RBRACK, + STATE(17), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1122] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(81), 1, + anon_sym_RBRACK, + ACTIONS(105), 1, + aux_sym_document_token1, + STATE(20), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1188] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(107), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1254] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(107), 1, + anon_sym_RBRACK, + ACTIONS(109), 1, + aux_sym_document_token1, + STATE(3), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1320] = 16, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(111), 1, + aux_sym_document_token1, + STATE(23), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1383] = 16, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1446] = 14, + ACTIONS(3), 1, + sym_comment, + ACTIONS(113), 1, + anon_sym_LBRACK, + ACTIONS(115), 1, + anon_sym_DQUOTE, + ACTIONS(117), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(119), 1, + anon_sym_SQUOTE, + ACTIONS(121), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(123), 1, + aux_sym_integer_token1, + ACTIONS(133), 1, + anon_sym_LBRACE, + ACTIONS(127), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(131), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(125), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(129), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(139), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(138), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1503] = 14, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(137), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(135), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(115), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1560] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(139), 1, + aux_sym_document_token1, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(144), 5, + anon_sym_DQUOTE, + anon_sym_SQUOTE, + aux_sym_integer_token1, + sym_local_date_time, + sym_local_date, + ACTIONS(142), 14, + anon_sym_LBRACK, + anon_sym_RBRACK, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + aux_sym_float_token1, + aux_sym_float_token2, + sym_boolean, + sym_offset_date_time, + sym_local_time, + anon_sym_COMMA, + anon_sym_LBRACE, + [1593] = 13, + ACTIONS(3), 1, + sym_comment, + ACTIONS(9), 1, + anon_sym_LBRACK, + ACTIONS(11), 1, + anon_sym_LBRACK_LBRACK, + ACTIONS(13), 1, + sym_bare_key, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(146), 1, + ts_builtin_sym_end, + ACTIONS(148), 1, + aux_sym_document_token1, + STATE(127), 1, + sym__inline_pair, + STATE(29), 2, + sym_pair, + aux_sym_document_repeat1, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(49), 3, + sym_table, + sym_table_array_element, + aux_sym_document_repeat2, + STATE(119), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1639] = 11, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym_bare_key, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(152), 1, + aux_sym_document_token1, + ACTIONS(154), 1, + anon_sym_LBRACK, + STATE(127), 1, + sym__inline_pair, + ACTIONS(150), 2, + ts_builtin_sym_end, + anon_sym_LBRACK_LBRACK, + STATE(31), 2, + sym_pair, + aux_sym_document_repeat1, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(119), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1678] = 11, + ACTIONS(3), 1, + sym_comment, + ACTIONS(158), 1, + aux_sym_document_token1, + ACTIONS(161), 1, + anon_sym_LBRACK, + ACTIONS(163), 1, + sym_bare_key, + ACTIONS(166), 1, + anon_sym_DQUOTE, + ACTIONS(169), 1, + anon_sym_SQUOTE, + STATE(127), 1, + sym__inline_pair, + ACTIONS(156), 2, + ts_builtin_sym_end, + anon_sym_LBRACK_LBRACK, + STATE(29), 2, + sym_pair, + aux_sym_document_repeat1, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(119), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1717] = 11, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym_bare_key, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(148), 1, + aux_sym_document_token1, + ACTIONS(174), 1, + anon_sym_LBRACK, + STATE(127), 1, + sym__inline_pair, + ACTIONS(172), 2, + ts_builtin_sym_end, + anon_sym_LBRACK_LBRACK, + STATE(29), 2, + sym_pair, + aux_sym_document_repeat1, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(119), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1756] = 11, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym_bare_key, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(148), 1, + aux_sym_document_token1, + ACTIONS(178), 1, + anon_sym_LBRACK, + STATE(127), 1, + sym__inline_pair, + ACTIONS(176), 2, + ts_builtin_sym_end, + anon_sym_LBRACK_LBRACK, + STATE(29), 2, + sym_pair, + aux_sym_document_repeat1, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(119), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1795] = 11, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym_bare_key, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(182), 1, + aux_sym_document_token1, + ACTIONS(184), 1, + anon_sym_LBRACK, + STATE(127), 1, + sym__inline_pair, + ACTIONS(180), 2, + ts_builtin_sym_end, + anon_sym_LBRACK_LBRACK, + STATE(30), 2, + sym_pair, + aux_sym_document_repeat1, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(119), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1834] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(186), 1, + sym_bare_key, + ACTIONS(188), 1, + anon_sym_RBRACE, + STATE(94), 1, + sym__inline_pair, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(109), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1862] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(186), 1, + sym_bare_key, + ACTIONS(190), 1, + anon_sym_RBRACE, + STATE(98), 1, + sym__inline_pair, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(109), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1890] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(186), 1, + sym_bare_key, + STATE(108), 1, + sym__inline_pair, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(109), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1915] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(192), 1, + sym_bare_key, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(117), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1937] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(194), 1, + sym_bare_key, + ACTIONS(196), 1, + anon_sym_DQUOTE, + ACTIONS(198), 1, + anon_sym_SQUOTE, + STATE(122), 2, + sym__basic_string, + sym__literal_string, + STATE(120), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1959] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(202), 1, + anon_sym_LBRACK, + ACTIONS(200), 6, + ts_builtin_sym_end, + aux_sym_document_token1, + anon_sym_LBRACK_LBRACK, + sym_bare_key, + anon_sym_DQUOTE, + anon_sym_SQUOTE, + [1974] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(209), 1, + sym__multiline_basic_string_end, + STATE(39), 1, + aux_sym__multiline_basic_string_repeat1, + ACTIONS(206), 5, + sym__multiline_basic_string_content, + aux_sym__basic_string_token1, + aux_sym__multiline_basic_string_token1, + sym_escape_sequence, + sym__escape_line_ending, + [1991] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(196), 1, + anon_sym_DQUOTE, + ACTIONS(198), 1, + anon_sym_SQUOTE, + ACTIONS(211), 1, + sym_bare_key, + STATE(118), 2, + sym__key, + sym_quoted_key, + STATE(122), 2, + sym__basic_string, + sym__literal_string, + [2012] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(215), 1, + sym__multiline_basic_string_end, + STATE(43), 1, + aux_sym__multiline_basic_string_repeat1, + ACTIONS(213), 5, + sym__multiline_basic_string_content, + aux_sym__basic_string_token1, + aux_sym__multiline_basic_string_token1, + sym_escape_sequence, + sym__escape_line_ending, + [2029] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(217), 1, + sym_bare_key, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(107), 2, + sym__key, + sym_quoted_key, + [2050] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(221), 1, + sym__multiline_basic_string_end, + STATE(39), 1, + aux_sym__multiline_basic_string_repeat1, + ACTIONS(219), 5, + sym__multiline_basic_string_content, + aux_sym__basic_string_token1, + aux_sym__multiline_basic_string_token1, + sym_escape_sequence, + sym__escape_line_ending, + [2067] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(225), 1, + sym__multiline_basic_string_end, + STATE(45), 1, + aux_sym__multiline_basic_string_repeat1, + ACTIONS(223), 5, + sym__multiline_basic_string_content, + aux_sym__basic_string_token1, + aux_sym__multiline_basic_string_token1, + sym_escape_sequence, + sym__escape_line_ending, + [2084] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(227), 1, + sym__multiline_basic_string_end, + STATE(39), 1, + aux_sym__multiline_basic_string_repeat1, + ACTIONS(219), 5, + sym__multiline_basic_string_content, + aux_sym__basic_string_token1, + aux_sym__multiline_basic_string_token1, + sym_escape_sequence, + sym__escape_line_ending, + [2101] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(9), 1, + anon_sym_LBRACK, + ACTIONS(11), 1, + anon_sym_LBRACK_LBRACK, + ACTIONS(146), 1, + ts_builtin_sym_end, + STATE(50), 3, + sym_table, + sym_table_array_element, + aux_sym_document_repeat2, + [2119] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(229), 6, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_EQ, + anon_sym_DOT, + anon_sym_COMMA, + anon_sym_RBRACE, + [2131] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(231), 6, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_EQ, + anon_sym_DOT, + anon_sym_COMMA, + anon_sym_RBRACE, + [2143] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(9), 1, + anon_sym_LBRACK, + ACTIONS(11), 1, + anon_sym_LBRACK_LBRACK, + ACTIONS(233), 1, + ts_builtin_sym_end, + STATE(50), 3, + sym_table, + sym_table_array_element, + aux_sym_document_repeat2, + [2161] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(235), 1, + ts_builtin_sym_end, + ACTIONS(237), 1, + anon_sym_LBRACK, + ACTIONS(240), 1, + anon_sym_LBRACK_LBRACK, + STATE(50), 3, + sym_table, + sym_table_array_element, + aux_sym_document_repeat2, + [2179] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(243), 6, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_EQ, + anon_sym_DOT, + anon_sym_COMMA, + anon_sym_RBRACE, + [2191] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(245), 6, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_EQ, + anon_sym_DOT, + anon_sym_COMMA, + anon_sym_RBRACE, + [2203] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(103), 1, + anon_sym_RBRACK, + ACTIONS(247), 1, + anon_sym_COMMA, + STATE(26), 1, + aux_sym_array_repeat1, + STATE(103), 1, + aux_sym_array_repeat2, + [2222] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(53), 1, + anon_sym_RBRACK, + ACTIONS(249), 1, + aux_sym_document_token1, + ACTIONS(251), 1, + anon_sym_COMMA, + STATE(56), 1, + aux_sym_array_repeat1, + STATE(102), 1, + aux_sym_array_repeat2, + [2241] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(256), 1, + sym__multiline_literal_string_end, + STATE(55), 1, + aux_sym__multiline_literal_string_repeat1, + ACTIONS(253), 3, + sym__multiline_literal_string_content, + aux_sym__multiline_basic_string_token1, + aux_sym__literal_string_token1, + [2256] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(67), 1, + anon_sym_RBRACK, + ACTIONS(258), 1, + anon_sym_COMMA, + STATE(26), 1, + aux_sym_array_repeat1, + STATE(104), 1, + aux_sym_array_repeat2, + [2275] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(262), 1, + sym__multiline_literal_string_end, + STATE(62), 1, + aux_sym__multiline_literal_string_repeat1, + ACTIONS(260), 3, + sym__multiline_literal_string_content, + aux_sym__multiline_basic_string_token1, + aux_sym__literal_string_token1, + [2290] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + anon_sym_RBRACK, + ACTIONS(264), 1, + aux_sym_document_token1, + ACTIONS(266), 1, + anon_sym_COMMA, + STATE(65), 1, + aux_sym_array_repeat1, + STATE(97), 1, + aux_sym_array_repeat2, + [2309] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(270), 1, + sym__multiline_literal_string_end, + STATE(61), 1, + aux_sym__multiline_literal_string_repeat1, + ACTIONS(268), 3, + sym__multiline_literal_string_content, + aux_sym__multiline_basic_string_token1, + aux_sym__literal_string_token1, + [2324] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(23), 1, + anon_sym_RBRACK, + ACTIONS(272), 1, + aux_sym_document_token1, + ACTIONS(274), 1, + anon_sym_COMMA, + STATE(53), 1, + aux_sym_array_repeat1, + STATE(100), 1, + aux_sym_array_repeat2, + [2343] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(278), 1, + sym__multiline_literal_string_end, + STATE(55), 1, + aux_sym__multiline_literal_string_repeat1, + ACTIONS(276), 3, + sym__multiline_literal_string_content, + aux_sym__multiline_basic_string_token1, + aux_sym__literal_string_token1, + [2358] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(280), 1, + sym__multiline_literal_string_end, + STATE(55), 1, + aux_sym__multiline_literal_string_repeat1, + ACTIONS(276), 3, + sym__multiline_literal_string_content, + aux_sym__multiline_basic_string_token1, + aux_sym__literal_string_token1, + [2373] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(103), 1, + anon_sym_RBRACK, + ACTIONS(247), 1, + anon_sym_COMMA, + ACTIONS(282), 1, + aux_sym_document_token1, + STATE(64), 1, + aux_sym_array_repeat1, + STATE(103), 1, + aux_sym_array_repeat2, + [2392] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(99), 1, + anon_sym_RBRACK, + ACTIONS(284), 1, + anon_sym_COMMA, + STATE(26), 1, + aux_sym_array_repeat1, + STATE(105), 1, + aux_sym_array_repeat2, + [2411] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(53), 1, + anon_sym_RBRACK, + ACTIONS(251), 1, + anon_sym_COMMA, + STATE(26), 1, + aux_sym_array_repeat1, + STATE(102), 1, + aux_sym_array_repeat2, + [2430] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(289), 1, + anon_sym_DQUOTE2, + STATE(66), 1, + aux_sym__basic_string_repeat1, + ACTIONS(286), 2, + aux_sym__basic_string_token1, + sym_escape_sequence, + [2444] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(293), 1, + anon_sym_DQUOTE2, + STATE(66), 1, + aux_sym__basic_string_repeat1, + ACTIONS(291), 2, + aux_sym__basic_string_token1, + sym_escape_sequence, + [2458] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(295), 2, + anon_sym_RBRACK, + anon_sym_COMMA, + [2472] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(297), 1, + aux_sym_document_token1, + STATE(70), 1, + aux_sym_array_repeat1, + ACTIONS(295), 2, + anon_sym_RBRACK, + anon_sym_COMMA, + [2486] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(299), 2, + anon_sym_RBRACK, + anon_sym_COMMA, + [2500] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(301), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2510] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(303), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2520] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(305), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2530] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(307), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2540] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(309), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2550] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(311), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2560] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(313), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2570] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(315), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2580] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(317), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2590] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(319), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2600] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(321), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2610] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(323), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2620] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(325), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2630] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(327), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2640] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(329), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2650] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(331), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2660] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(333), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2670] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(337), 1, + anon_sym_DQUOTE2, + STATE(89), 1, + aux_sym__basic_string_repeat1, + ACTIONS(335), 2, + aux_sym__basic_string_token1, + sym_escape_sequence, + [2684] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(339), 1, + anon_sym_DQUOTE2, + STATE(66), 1, + aux_sym__basic_string_repeat1, + ACTIONS(291), 2, + aux_sym__basic_string_token1, + sym_escape_sequence, + [2698] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(343), 1, + anon_sym_DQUOTE2, + STATE(91), 1, + aux_sym__basic_string_repeat1, + ACTIONS(341), 2, + aux_sym__basic_string_token1, + sym_escape_sequence, + [2712] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(345), 1, + anon_sym_DQUOTE2, + STATE(66), 1, + aux_sym__basic_string_repeat1, + ACTIONS(291), 2, + aux_sym__basic_string_token1, + sym_escape_sequence, + [2726] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(347), 1, + aux_sym_document_token1, + STATE(68), 1, + aux_sym_array_repeat1, + ACTIONS(349), 2, + anon_sym_RBRACK, + anon_sym_COMMA, + [2740] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(353), 1, + anon_sym_DQUOTE2, + STATE(67), 1, + aux_sym__basic_string_repeat1, + ACTIONS(351), 2, + aux_sym__basic_string_token1, + sym_escape_sequence, + [2754] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(355), 1, + anon_sym_COMMA, + ACTIONS(357), 1, + anon_sym_RBRACE, + STATE(99), 1, + aux_sym_inline_table_repeat1, + [2767] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(349), 1, + anon_sym_RBRACK, + ACTIONS(359), 1, + anon_sym_COMMA, + STATE(95), 1, + aux_sym_array_repeat2, + [2780] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(362), 3, + anon_sym_RBRACK, + anon_sym_EQ, + anon_sym_DOT, + [2789] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(53), 1, + anon_sym_RBRACK, + ACTIONS(251), 1, + anon_sym_COMMA, + STATE(95), 1, + aux_sym_array_repeat2, + [2802] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(355), 1, + anon_sym_COMMA, + ACTIONS(364), 1, + anon_sym_RBRACE, + STATE(101), 1, + aux_sym_inline_table_repeat1, + [2815] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(355), 1, + anon_sym_COMMA, + ACTIONS(366), 1, + anon_sym_RBRACE, + STATE(106), 1, + aux_sym_inline_table_repeat1, + [2828] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(103), 1, + anon_sym_RBRACK, + ACTIONS(247), 1, + anon_sym_COMMA, + STATE(95), 1, + aux_sym_array_repeat2, + [2841] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(355), 1, + anon_sym_COMMA, + ACTIONS(368), 1, + anon_sym_RBRACE, + STATE(106), 1, + aux_sym_inline_table_repeat1, + [2854] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(67), 1, + anon_sym_RBRACK, + ACTIONS(258), 1, + anon_sym_COMMA, + STATE(95), 1, + aux_sym_array_repeat2, + [2867] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(99), 1, + anon_sym_RBRACK, + ACTIONS(284), 1, + anon_sym_COMMA, + STATE(95), 1, + aux_sym_array_repeat2, + [2880] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(77), 1, + anon_sym_RBRACK, + ACTIONS(370), 1, + anon_sym_COMMA, + STATE(95), 1, + aux_sym_array_repeat2, + [2893] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(81), 1, + anon_sym_RBRACK, + ACTIONS(372), 1, + anon_sym_COMMA, + STATE(95), 1, + aux_sym_array_repeat2, + [2906] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(374), 1, + anon_sym_COMMA, + ACTIONS(377), 1, + anon_sym_RBRACE, + STATE(106), 1, + aux_sym_inline_table_repeat1, + [2919] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(379), 3, + anon_sym_RBRACK, + anon_sym_EQ, + anon_sym_DOT, + [2928] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(381), 2, + anon_sym_COMMA, + anon_sym_RBRACE, + [2936] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(383), 1, + anon_sym_EQ, + ACTIONS(385), 1, + anon_sym_DOT, + [2946] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(229), 2, + anon_sym_RBRACK_RBRACK, + anon_sym_DOT, + [2954] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(231), 2, + anon_sym_RBRACK_RBRACK, + anon_sym_DOT, + [2962] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(243), 2, + anon_sym_RBRACK_RBRACK, + anon_sym_DOT, + [2970] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(245), 2, + anon_sym_RBRACK_RBRACK, + anon_sym_DOT, + [2978] = 3, + ACTIONS(204), 1, + sym_comment, + ACTIONS(387), 1, + aux_sym__literal_string_token1, + ACTIONS(389), 1, + anon_sym_SQUOTE2, + [2988] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(391), 2, + anon_sym_COMMA, + anon_sym_RBRACE, + [2996] = 3, + ACTIONS(204), 1, + sym_comment, + ACTIONS(393), 1, + aux_sym__literal_string_token1, + ACTIONS(395), 1, + anon_sym_SQUOTE2, + [3006] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(385), 1, + anon_sym_DOT, + ACTIONS(397), 1, + anon_sym_RBRACK, + [3016] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(379), 2, + anon_sym_RBRACK_RBRACK, + anon_sym_DOT, + [3024] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(385), 1, + anon_sym_DOT, + ACTIONS(399), 1, + anon_sym_EQ, + [3034] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(401), 1, + anon_sym_RBRACK_RBRACK, + ACTIONS(403), 1, + anon_sym_DOT, + [3044] = 3, + ACTIONS(204), 1, + sym_comment, + ACTIONS(405), 1, + aux_sym__literal_string_token1, + ACTIONS(407), 1, + anon_sym_SQUOTE2, + [3054] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(362), 2, + anon_sym_RBRACK_RBRACK, + anon_sym_DOT, + [3062] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(315), 1, + sym__line_ending_or_eof, + [3069] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(231), 1, + sym__line_ending_or_eof, + [3076] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(409), 1, + ts_builtin_sym_end, + [3083] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(317), 1, + sym__line_ending_or_eof, + [3090] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(411), 1, + sym__line_ending_or_eof, + [3097] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(309), 1, + sym__line_ending_or_eof, + [3104] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(301), 1, + sym__line_ending_or_eof, + [3111] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(321), 1, + sym__line_ending_or_eof, + [3118] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(243), 1, + sym__line_ending_or_eof, + [3125] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(311), 1, + sym__line_ending_or_eof, + [3132] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(327), 1, + sym__line_ending_or_eof, + [3139] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(329), 1, + sym__line_ending_or_eof, + [3146] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(323), 1, + sym__line_ending_or_eof, + [3153] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(303), 1, + sym__line_ending_or_eof, + [3160] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(313), 1, + sym__line_ending_or_eof, + [3167] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(391), 1, + sym__line_ending_or_eof, + [3174] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(305), 1, + sym__line_ending_or_eof, + [3181] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(331), 1, + sym__line_ending_or_eof, + [3188] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(413), 1, + anon_sym_SQUOTE2, + [3195] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(415), 1, + sym__line_ending_or_eof, + [3202] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(325), 1, + sym__line_ending_or_eof, + [3209] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(229), 1, + sym__line_ending_or_eof, + [3216] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(417), 1, + sym__line_ending_or_eof, + [3223] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(419), 1, + anon_sym_SQUOTE2, + [3230] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(333), 1, + sym__line_ending_or_eof, + [3237] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(245), 1, + sym__line_ending_or_eof, + [3244] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(307), 1, + sym__line_ending_or_eof, + [3251] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(421), 1, + anon_sym_SQUOTE2, + [3258] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(319), 1, + sym__line_ending_or_eof, +}; + +static const uint32_t ts_small_parse_table_map[] = { + [SMALL_STATE(2)] = 0, + [SMALL_STATE(3)] = 66, + [SMALL_STATE(4)] = 132, + [SMALL_STATE(5)] = 198, + [SMALL_STATE(6)] = 264, + [SMALL_STATE(7)] = 330, + [SMALL_STATE(8)] = 396, + [SMALL_STATE(9)] = 462, + [SMALL_STATE(10)] = 528, + [SMALL_STATE(11)] = 594, + [SMALL_STATE(12)] = 660, + [SMALL_STATE(13)] = 726, + [SMALL_STATE(14)] = 792, + [SMALL_STATE(15)] = 858, + [SMALL_STATE(16)] = 924, + [SMALL_STATE(17)] = 990, + [SMALL_STATE(18)] = 1056, + [SMALL_STATE(19)] = 1122, + [SMALL_STATE(20)] = 1188, + [SMALL_STATE(21)] = 1254, + [SMALL_STATE(22)] = 1320, + [SMALL_STATE(23)] = 1383, + [SMALL_STATE(24)] = 1446, + [SMALL_STATE(25)] = 1503, + [SMALL_STATE(26)] = 1560, + [SMALL_STATE(27)] = 1593, + [SMALL_STATE(28)] = 1639, + [SMALL_STATE(29)] = 1678, + [SMALL_STATE(30)] = 1717, + [SMALL_STATE(31)] = 1756, + [SMALL_STATE(32)] = 1795, + [SMALL_STATE(33)] = 1834, + [SMALL_STATE(34)] = 1862, + [SMALL_STATE(35)] = 1890, + [SMALL_STATE(36)] = 1915, + [SMALL_STATE(37)] = 1937, + [SMALL_STATE(38)] = 1959, + [SMALL_STATE(39)] = 1974, + [SMALL_STATE(40)] = 1991, + [SMALL_STATE(41)] = 2012, + [SMALL_STATE(42)] = 2029, + [SMALL_STATE(43)] = 2050, + [SMALL_STATE(44)] = 2067, + [SMALL_STATE(45)] = 2084, + [SMALL_STATE(46)] = 2101, + [SMALL_STATE(47)] = 2119, + [SMALL_STATE(48)] = 2131, + [SMALL_STATE(49)] = 2143, + [SMALL_STATE(50)] = 2161, + [SMALL_STATE(51)] = 2179, + [SMALL_STATE(52)] = 2191, + [SMALL_STATE(53)] = 2203, + [SMALL_STATE(54)] = 2222, + [SMALL_STATE(55)] = 2241, + [SMALL_STATE(56)] = 2256, + [SMALL_STATE(57)] = 2275, + [SMALL_STATE(58)] = 2290, + [SMALL_STATE(59)] = 2309, + [SMALL_STATE(60)] = 2324, + [SMALL_STATE(61)] = 2343, + [SMALL_STATE(62)] = 2358, + [SMALL_STATE(63)] = 2373, + [SMALL_STATE(64)] = 2392, + [SMALL_STATE(65)] = 2411, + [SMALL_STATE(66)] = 2430, + [SMALL_STATE(67)] = 2444, + [SMALL_STATE(68)] = 2458, + [SMALL_STATE(69)] = 2472, + [SMALL_STATE(70)] = 2486, + [SMALL_STATE(71)] = 2500, + [SMALL_STATE(72)] = 2510, + [SMALL_STATE(73)] = 2520, + [SMALL_STATE(74)] = 2530, + [SMALL_STATE(75)] = 2540, + [SMALL_STATE(76)] = 2550, + [SMALL_STATE(77)] = 2560, + [SMALL_STATE(78)] = 2570, + [SMALL_STATE(79)] = 2580, + [SMALL_STATE(80)] = 2590, + [SMALL_STATE(81)] = 2600, + [SMALL_STATE(82)] = 2610, + [SMALL_STATE(83)] = 2620, + [SMALL_STATE(84)] = 2630, + [SMALL_STATE(85)] = 2640, + [SMALL_STATE(86)] = 2650, + [SMALL_STATE(87)] = 2660, + [SMALL_STATE(88)] = 2670, + [SMALL_STATE(89)] = 2684, + [SMALL_STATE(90)] = 2698, + [SMALL_STATE(91)] = 2712, + [SMALL_STATE(92)] = 2726, + [SMALL_STATE(93)] = 2740, + [SMALL_STATE(94)] = 2754, + [SMALL_STATE(95)] = 2767, + [SMALL_STATE(96)] = 2780, + [SMALL_STATE(97)] = 2789, + [SMALL_STATE(98)] = 2802, + [SMALL_STATE(99)] = 2815, + [SMALL_STATE(100)] = 2828, + [SMALL_STATE(101)] = 2841, + [SMALL_STATE(102)] = 2854, + [SMALL_STATE(103)] = 2867, + [SMALL_STATE(104)] = 2880, + [SMALL_STATE(105)] = 2893, + [SMALL_STATE(106)] = 2906, + [SMALL_STATE(107)] = 2919, + [SMALL_STATE(108)] = 2928, + [SMALL_STATE(109)] = 2936, + [SMALL_STATE(110)] = 2946, + [SMALL_STATE(111)] = 2954, + [SMALL_STATE(112)] = 2962, + [SMALL_STATE(113)] = 2970, + [SMALL_STATE(114)] = 2978, + [SMALL_STATE(115)] = 2988, + [SMALL_STATE(116)] = 2996, + [SMALL_STATE(117)] = 3006, + [SMALL_STATE(118)] = 3016, + [SMALL_STATE(119)] = 3024, + [SMALL_STATE(120)] = 3034, + [SMALL_STATE(121)] = 3044, + [SMALL_STATE(122)] = 3054, + [SMALL_STATE(123)] = 3062, + [SMALL_STATE(124)] = 3069, + [SMALL_STATE(125)] = 3076, + [SMALL_STATE(126)] = 3083, + [SMALL_STATE(127)] = 3090, + [SMALL_STATE(128)] = 3097, + [SMALL_STATE(129)] = 3104, + [SMALL_STATE(130)] = 3111, + [SMALL_STATE(131)] = 3118, + [SMALL_STATE(132)] = 3125, + [SMALL_STATE(133)] = 3132, + [SMALL_STATE(134)] = 3139, + [SMALL_STATE(135)] = 3146, + [SMALL_STATE(136)] = 3153, + [SMALL_STATE(137)] = 3160, + [SMALL_STATE(138)] = 3167, + [SMALL_STATE(139)] = 3174, + [SMALL_STATE(140)] = 3181, + [SMALL_STATE(141)] = 3188, + [SMALL_STATE(142)] = 3195, + [SMALL_STATE(143)] = 3202, + [SMALL_STATE(144)] = 3209, + [SMALL_STATE(145)] = 3216, + [SMALL_STATE(146)] = 3223, + [SMALL_STATE(147)] = 3230, + [SMALL_STATE(148)] = 3237, + [SMALL_STATE(149)] = 3244, + [SMALL_STATE(150)] = 3251, + [SMALL_STATE(151)] = 3258, +}; + +static const TSParseActionEntry ts_parse_actions[] = { + [0] = {.entry = {.count = 0, .reusable = false}}, + [1] = {.entry = {.count = 1, .reusable = false}}, RECOVER(), + [3] = {.entry = {.count = 1, .reusable = true}}, SHIFT_EXTRA(), + [5] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_document, 0, 0, 0), + [7] = {.entry = {.count = 1, .reusable = true}}, SHIFT(27), + [9] = {.entry = {.count = 1, .reusable = false}}, SHIFT(36), + [11] = {.entry = {.count = 1, .reusable = true}}, SHIFT(37), + [13] = {.entry = {.count = 1, .reusable = true}}, SHIFT(119), + [15] = {.entry = {.count = 1, .reusable = true}}, SHIFT(90), + [17] = {.entry = {.count = 1, .reusable = true}}, SHIFT(116), + [19] = {.entry = {.count = 1, .reusable = true}}, SHIFT(26), + [21] = {.entry = {.count = 1, .reusable = true}}, SHIFT(14), + [23] = {.entry = {.count = 1, .reusable = true}}, SHIFT(78), + [25] = {.entry = {.count = 1, .reusable = false}}, SHIFT(90), + [27] = {.entry = {.count = 1, .reusable = true}}, SHIFT(41), + [29] = {.entry = {.count = 1, .reusable = false}}, SHIFT(116), + [31] = {.entry = {.count = 1, .reusable = true}}, SHIFT(59), + [33] = {.entry = {.count = 1, .reusable = false}}, SHIFT(71), + [35] = {.entry = {.count = 1, .reusable = true}}, SHIFT(71), + [37] = {.entry = {.count = 1, .reusable = true}}, SHIFT(72), + [39] = {.entry = {.count = 1, .reusable = true}}, SHIFT(63), + [41] = {.entry = {.count = 1, .reusable = false}}, SHIFT(63), + [43] = {.entry = {.count = 1, .reusable = true}}, SHIFT(34), + [45] = {.entry = {.count = 1, .reusable = true}}, SHIFT(87), + [47] = {.entry = {.count = 1, .reusable = true}}, SHIFT(69), + [49] = {.entry = {.count = 1, .reusable = false}}, SHIFT(69), + [51] = {.entry = {.count = 1, .reusable = true}}, SHIFT(6), + [53] = {.entry = {.count = 1, .reusable = true}}, SHIFT(135), + [55] = {.entry = {.count = 1, .reusable = true}}, SHIFT(92), + [57] = {.entry = {.count = 1, .reusable = false}}, SHIFT(92), + [59] = {.entry = {.count = 1, .reusable = true}}, SHIFT(7), + [61] = {.entry = {.count = 1, .reusable = true}}, SHIFT(149), + [63] = {.entry = {.count = 1, .reusable = true}}, SHIFT(58), + [65] = {.entry = {.count = 1, .reusable = false}}, SHIFT(58), + [67] = {.entry = {.count = 1, .reusable = true}}, SHIFT(133), + [69] = {.entry = {.count = 1, .reusable = true}}, SHIFT(123), + [71] = {.entry = {.count = 1, .reusable = true}}, SHIFT(54), + [73] = {.entry = {.count = 1, .reusable = false}}, SHIFT(54), + [75] = {.entry = {.count = 1, .reusable = true}}, SHIFT(9), + [77] = {.entry = {.count = 1, .reusable = true}}, SHIFT(134), + [79] = {.entry = {.count = 1, .reusable = true}}, SHIFT(12), + [81] = {.entry = {.count = 1, .reusable = true}}, SHIFT(85), + [83] = {.entry = {.count = 1, .reusable = true}}, SHIFT(140), + [85] = {.entry = {.count = 1, .reusable = true}}, SHIFT(15), + [87] = {.entry = {.count = 1, .reusable = true}}, SHIFT(2), + [89] = {.entry = {.count = 1, .reusable = true}}, SHIFT(74), + [91] = {.entry = {.count = 1, .reusable = true}}, SHIFT(60), + [93] = {.entry = {.count = 1, .reusable = false}}, SHIFT(60), + [95] = {.entry = {.count = 1, .reusable = true}}, SHIFT(147), + [97] = {.entry = {.count = 1, .reusable = true}}, SHIFT(11), + [99] = {.entry = {.count = 1, .reusable = true}}, SHIFT(84), + [101] = {.entry = {.count = 1, .reusable = true}}, SHIFT(17), + [103] = {.entry = {.count = 1, .reusable = true}}, SHIFT(82), + [105] = {.entry = {.count = 1, .reusable = true}}, SHIFT(20), + [107] = {.entry = {.count = 1, .reusable = true}}, SHIFT(86), + [109] = {.entry = {.count = 1, .reusable = true}}, SHIFT(3), + [111] = {.entry = {.count = 1, .reusable = true}}, SHIFT(23), + [113] = {.entry = {.count = 1, .reusable = true}}, SHIFT(5), + [115] = {.entry = {.count = 1, .reusable = false}}, SHIFT(93), + [117] = {.entry = {.count = 1, .reusable = true}}, SHIFT(44), + [119] = {.entry = {.count = 1, .reusable = false}}, SHIFT(121), + [121] = {.entry = {.count = 1, .reusable = true}}, SHIFT(57), + [123] = {.entry = {.count = 1, .reusable = false}}, SHIFT(129), + [125] = {.entry = {.count = 1, .reusable = true}}, SHIFT(129), + [127] = {.entry = {.count = 1, .reusable = true}}, SHIFT(136), + [129] = {.entry = {.count = 1, .reusable = true}}, SHIFT(138), + [131] = {.entry = {.count = 1, .reusable = false}}, SHIFT(138), + [133] = {.entry = {.count = 1, .reusable = true}}, SHIFT(33), + [135] = {.entry = {.count = 1, .reusable = true}}, SHIFT(115), + [137] = {.entry = {.count = 1, .reusable = false}}, SHIFT(115), + [139] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_array_repeat1, 2, 0, 0), SHIFT_REPEAT(26), + [142] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_array_repeat1, 2, 0, 0), + [144] = {.entry = {.count = 1, .reusable = false}}, REDUCE(aux_sym_array_repeat1, 2, 0, 0), + [146] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_document, 1, 0, 0), + [148] = {.entry = {.count = 1, .reusable = true}}, SHIFT(29), + [150] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_table, 4, 0, 0), + [152] = {.entry = {.count = 1, .reusable = true}}, SHIFT(31), + [154] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_table, 4, 0, 0), + [156] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_document_repeat1, 2, 0, 0), + [158] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_document_repeat1, 2, 0, 0), SHIFT_REPEAT(29), + [161] = {.entry = {.count = 1, .reusable = false}}, REDUCE(aux_sym_document_repeat1, 2, 0, 0), + [163] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_document_repeat1, 2, 0, 0), SHIFT_REPEAT(119), + [166] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_document_repeat1, 2, 0, 0), SHIFT_REPEAT(90), + [169] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_document_repeat1, 2, 0, 0), SHIFT_REPEAT(116), + [172] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_table_array_element, 5, 0, 0), + [174] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_table_array_element, 5, 0, 0), + [176] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_table, 5, 0, 0), + [178] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_table, 5, 0, 0), + [180] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_table_array_element, 4, 0, 0), + [182] = {.entry = {.count = 1, .reusable = true}}, SHIFT(30), + [184] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_table_array_element, 4, 0, 0), + [186] = {.entry = {.count = 1, .reusable = true}}, SHIFT(109), + [188] = {.entry = {.count = 1, .reusable = true}}, SHIFT(137), + [190] = {.entry = {.count = 1, .reusable = true}}, SHIFT(77), + [192] = {.entry = {.count = 1, .reusable = true}}, SHIFT(117), + [194] = {.entry = {.count = 1, .reusable = true}}, SHIFT(120), + [196] = {.entry = {.count = 1, .reusable = true}}, SHIFT(88), + [198] = {.entry = {.count = 1, .reusable = true}}, SHIFT(114), + [200] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_pair, 2, 0, 0), + [202] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_pair, 2, 0, 0), + [204] = {.entry = {.count = 1, .reusable = false}}, SHIFT_EXTRA(), + [206] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__multiline_basic_string_repeat1, 2, 0, 0), SHIFT_REPEAT(39), + [209] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__multiline_basic_string_repeat1, 2, 0, 0), + [211] = {.entry = {.count = 1, .reusable = true}}, SHIFT(118), + [213] = {.entry = {.count = 1, .reusable = true}}, SHIFT(43), + [215] = {.entry = {.count = 1, .reusable = true}}, SHIFT(75), + [217] = {.entry = {.count = 1, .reusable = true}}, SHIFT(107), + [219] = {.entry = {.count = 1, .reusable = true}}, SHIFT(39), + [221] = {.entry = {.count = 1, .reusable = true}}, SHIFT(79), + [223] = {.entry = {.count = 1, .reusable = true}}, SHIFT(45), + [225] = {.entry = {.count = 1, .reusable = true}}, SHIFT(128), + [227] = {.entry = {.count = 1, .reusable = true}}, SHIFT(126), + [229] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__basic_string, 2, 0, 0), + [231] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__literal_string, 2, 0, 0), + [233] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_document, 2, 0, 0), + [235] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_document_repeat2, 2, 0, 0), + [237] = {.entry = {.count = 2, .reusable = false}}, REDUCE(aux_sym_document_repeat2, 2, 0, 0), SHIFT_REPEAT(36), + [240] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_document_repeat2, 2, 0, 0), SHIFT_REPEAT(37), + [243] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__basic_string, 3, 0, 0), + [245] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__literal_string, 3, 0, 0), + [247] = {.entry = {.count = 1, .reusable = true}}, SHIFT(16), + [249] = {.entry = {.count = 1, .reusable = true}}, SHIFT(56), + [251] = {.entry = {.count = 1, .reusable = true}}, SHIFT(8), + [253] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__multiline_literal_string_repeat1, 2, 0, 0), SHIFT_REPEAT(55), + [256] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__multiline_literal_string_repeat1, 2, 0, 0), + [258] = {.entry = {.count = 1, .reusable = true}}, SHIFT(10), + [260] = {.entry = {.count = 1, .reusable = true}}, SHIFT(62), + [262] = {.entry = {.count = 1, .reusable = true}}, SHIFT(132), + [264] = {.entry = {.count = 1, .reusable = true}}, SHIFT(65), + [266] = {.entry = {.count = 1, .reusable = true}}, SHIFT(4), + [268] = {.entry = {.count = 1, .reusable = true}}, SHIFT(61), + [270] = {.entry = {.count = 1, .reusable = true}}, SHIFT(76), + [272] = {.entry = {.count = 1, .reusable = true}}, SHIFT(53), + [274] = {.entry = {.count = 1, .reusable = true}}, SHIFT(18), + [276] = {.entry = {.count = 1, .reusable = true}}, SHIFT(55), + [278] = {.entry = {.count = 1, .reusable = true}}, SHIFT(80), + [280] = {.entry = {.count = 1, .reusable = true}}, SHIFT(151), + [282] = {.entry = {.count = 1, .reusable = true}}, SHIFT(64), + [284] = {.entry = {.count = 1, .reusable = true}}, SHIFT(19), + [286] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__basic_string_repeat1, 2, 0, 0), SHIFT_REPEAT(66), + [289] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__basic_string_repeat1, 2, 0, 0), + [291] = {.entry = {.count = 1, .reusable = true}}, SHIFT(66), + [293] = {.entry = {.count = 1, .reusable = true}}, SHIFT(131), + [295] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_array_repeat2, 3, 0, 0), + [297] = {.entry = {.count = 1, .reusable = true}}, SHIFT(70), + [299] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_array_repeat2, 4, 0, 0), + [301] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_integer, 1, 0, 0), + [303] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_float, 1, 0, 0), + [305] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_string, 1, 0, 0), + [307] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_array, 2, 0, 0), + [309] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__multiline_basic_string, 2, 0, 0), + [311] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__multiline_literal_string, 2, 0, 0), + [313] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_inline_table, 2, 0, 0), + [315] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_array, 3, 0, 0), + [317] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__multiline_basic_string, 3, 0, 0), + [319] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__multiline_literal_string, 3, 0, 0), + [321] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_inline_table, 3, 0, 1), + [323] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_array, 4, 0, 0), + [325] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_inline_table, 4, 0, 1), + [327] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_array, 5, 0, 0), + [329] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_array, 6, 0, 0), + [331] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_array, 7, 0, 0), + [333] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_array, 8, 0, 0), + [335] = {.entry = {.count = 1, .reusable = true}}, SHIFT(89), + [337] = {.entry = {.count = 1, .reusable = true}}, SHIFT(110), + [339] = {.entry = {.count = 1, .reusable = true}}, SHIFT(112), + [341] = {.entry = {.count = 1, .reusable = true}}, SHIFT(91), + [343] = {.entry = {.count = 1, .reusable = true}}, SHIFT(47), + [345] = {.entry = {.count = 1, .reusable = true}}, SHIFT(51), + [347] = {.entry = {.count = 1, .reusable = true}}, SHIFT(68), + [349] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_array_repeat2, 2, 0, 0), + [351] = {.entry = {.count = 1, .reusable = true}}, SHIFT(67), + [353] = {.entry = {.count = 1, .reusable = true}}, SHIFT(144), + [355] = {.entry = {.count = 1, .reusable = true}}, SHIFT(35), + [357] = {.entry = {.count = 1, .reusable = true}}, SHIFT(130), + [359] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_array_repeat2, 2, 0, 0), SHIFT_REPEAT(22), + [362] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_quoted_key, 1, 0, 0), + [364] = {.entry = {.count = 1, .reusable = true}}, SHIFT(81), + [366] = {.entry = {.count = 1, .reusable = true}}, SHIFT(143), + [368] = {.entry = {.count = 1, .reusable = true}}, SHIFT(83), + [370] = {.entry = {.count = 1, .reusable = true}}, SHIFT(13), + [372] = {.entry = {.count = 1, .reusable = true}}, SHIFT(21), + [374] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_inline_table_repeat1, 2, 0, 0), SHIFT_REPEAT(35), + [377] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_inline_table_repeat1, 2, 0, 0), + [379] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_dotted_key, 3, 0, 0), + [381] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_inline_table_repeat1, 2, 0, 1), + [383] = {.entry = {.count = 1, .reusable = true}}, SHIFT(25), + [385] = {.entry = {.count = 1, .reusable = true}}, SHIFT(42), + [387] = {.entry = {.count = 1, .reusable = true}}, SHIFT(141), + [389] = {.entry = {.count = 1, .reusable = true}}, SHIFT(111), + [391] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__inline_pair, 3, 0, 0), + [393] = {.entry = {.count = 1, .reusable = true}}, SHIFT(146), + [395] = {.entry = {.count = 1, .reusable = true}}, SHIFT(48), + [397] = {.entry = {.count = 1, .reusable = true}}, SHIFT(142), + [399] = {.entry = {.count = 1, .reusable = true}}, SHIFT(24), + [401] = {.entry = {.count = 1, .reusable = true}}, SHIFT(145), + [403] = {.entry = {.count = 1, .reusable = true}}, SHIFT(40), + [405] = {.entry = {.count = 1, .reusable = true}}, SHIFT(150), + [407] = {.entry = {.count = 1, .reusable = true}}, SHIFT(124), + [409] = {.entry = {.count = 1, .reusable = true}}, ACCEPT_INPUT(), + [411] = {.entry = {.count = 1, .reusable = true}}, SHIFT(38), + [413] = {.entry = {.count = 1, .reusable = true}}, SHIFT(113), + [415] = {.entry = {.count = 1, .reusable = true}}, SHIFT(28), + [417] = {.entry = {.count = 1, .reusable = true}}, SHIFT(32), + [419] = {.entry = {.count = 1, .reusable = true}}, SHIFT(52), + [421] = {.entry = {.count = 1, .reusable = true}}, SHIFT(148), +}; + +enum ts_external_scanner_symbol_identifiers { + ts_external_token__line_ending_or_eof = 0, + ts_external_token__multiline_basic_string_content = 1, + ts_external_token__multiline_basic_string_end = 2, + ts_external_token__multiline_literal_string_content = 3, + ts_external_token__multiline_literal_string_end = 4, +}; + +static const TSSymbol ts_external_scanner_symbol_map[EXTERNAL_TOKEN_COUNT] = { + [ts_external_token__line_ending_or_eof] = sym__line_ending_or_eof, + [ts_external_token__multiline_basic_string_content] = sym__multiline_basic_string_content, + [ts_external_token__multiline_basic_string_end] = sym__multiline_basic_string_end, + [ts_external_token__multiline_literal_string_content] = sym__multiline_literal_string_content, + [ts_external_token__multiline_literal_string_end] = sym__multiline_literal_string_end, +}; + +static const bool ts_external_scanner_states[5][EXTERNAL_TOKEN_COUNT] = { + [1] = { + [ts_external_token__line_ending_or_eof] = true, + [ts_external_token__multiline_basic_string_content] = true, + [ts_external_token__multiline_basic_string_end] = true, + [ts_external_token__multiline_literal_string_content] = true, + [ts_external_token__multiline_literal_string_end] = true, + }, + [2] = { + [ts_external_token__multiline_basic_string_content] = true, + [ts_external_token__multiline_basic_string_end] = true, + }, + [3] = { + [ts_external_token__multiline_literal_string_content] = true, + [ts_external_token__multiline_literal_string_end] = true, + }, + [4] = { + [ts_external_token__line_ending_or_eof] = true, + }, +}; + +#ifdef __cplusplus +extern "C" { +#endif +void *tree_sitter_toml_external_scanner_create(void); +void tree_sitter_toml_external_scanner_destroy(void *); +bool tree_sitter_toml_external_scanner_scan(void *, TSLexer *, const bool *); +unsigned tree_sitter_toml_external_scanner_serialize(void *, char *); +void tree_sitter_toml_external_scanner_deserialize(void *, const char *, unsigned); + +#ifdef TREE_SITTER_HIDE_SYMBOLS +#define TS_PUBLIC +#elif defined(_WIN32) +#define TS_PUBLIC __declspec(dllexport) +#else +#define TS_PUBLIC __attribute__((visibility("default"))) +#endif + +TS_PUBLIC const TSLanguage *tree_sitter_toml(void) { + static const TSLanguage language = { + .version = LANGUAGE_VERSION, + .symbol_count = SYMBOL_COUNT, + .alias_count = ALIAS_COUNT, + .token_count = TOKEN_COUNT, + .external_token_count = EXTERNAL_TOKEN_COUNT, + .state_count = STATE_COUNT, + .large_state_count = LARGE_STATE_COUNT, + .production_id_count = PRODUCTION_ID_COUNT, + .field_count = FIELD_COUNT, + .max_alias_sequence_length = MAX_ALIAS_SEQUENCE_LENGTH, + .parse_table = &ts_parse_table[0][0], + .small_parse_table = ts_small_parse_table, + .small_parse_table_map = ts_small_parse_table_map, + .parse_actions = ts_parse_actions, + .symbol_names = ts_symbol_names, + .symbol_metadata = ts_symbol_metadata, + .public_symbol_map = ts_symbol_map, + .alias_map = ts_non_terminal_alias_map, + .alias_sequences = &ts_alias_sequences[0][0], + .lex_modes = ts_lex_modes, + .lex_fn = ts_lex, + .external_scanner = { + &ts_external_scanner_states[0][0], + ts_external_scanner_symbol_map, + tree_sitter_toml_external_scanner_create, + tree_sitter_toml_external_scanner_destroy, + tree_sitter_toml_external_scanner_scan, + tree_sitter_toml_external_scanner_serialize, + tree_sitter_toml_external_scanner_deserialize, + }, + .primary_state_ids = ts_primary_state_ids, + }; + return &language; +} +#ifdef __cplusplus +} +#endif diff --git a/Sources/TreeSitterTOML/provenance.json b/Sources/TreeSitterTOML/provenance.json new file mode 100644 index 0000000..128ca3e --- /dev/null +++ b/Sources/TreeSitterTOML/provenance.json @@ -0,0 +1,26 @@ +{ + "upstream": "https://github.com/tree-sitter-grammars/tree-sitter-toml.git", + "revision": "64b56832c2cffe41758f28e05c756a3a98d16f41", + "files": { + "parser.c": { + "source": "src/parser.c", + "sha256": "1991a2608e6f0214e563fe5f762e8df72954dc69a3dd9a1e22ea8a870e4052c3" + }, + "scanner.c": { + "source": "src/scanner.c", + "sha256": "b25ff3b5034f40046e9a041d1e9110aa46d081706bbd1b748b480701aa6f5bde" + }, + "tree_sitter/parser.h": { + "source": "src/tree_sitter/parser.h", + "sha256": "a1f6ef161fbaf48a0e10fca90ef5290a062462b307b3898aa562993853b9f80a" + }, + "include/toml.h": { + "source": "bindings/swift/TreeSitterTOML/toml.h", + "sha256": "5ad880da451bae8855bd376f9ac267ff10cc44c5fbbdf6ea67cd08ffcc087757" + }, + "LICENSE": { + "source": "LICENSE", + "sha256": "b727eee929bee836e8102cecf749a795b199f291b58c885bcd81cae727ac5a46" + } + } +} diff --git a/Sources/TreeSitterTOML/scanner.c b/Sources/TreeSitterTOML/scanner.c new file mode 100644 index 0000000..7fa3c23 --- /dev/null +++ b/Sources/TreeSitterTOML/scanner.c @@ -0,0 +1,82 @@ +#include "tree_sitter/parser.h" + +typedef enum { + LINE_ENDING_OR_EOF, + MULTILINE_BASIC_STRING_CONTENT, + MULTILINE_BASIC_STRING_END, + MULTILINE_LITERAL_STRING_CONTENT, + MULTILINE_LITERAL_STRING_END, +} TokenType; + +void *tree_sitter_toml_external_scanner_create() { return NULL; } + +void tree_sitter_toml_external_scanner_destroy(void *payload) {} + +unsigned tree_sitter_toml_external_scanner_serialize(void *payload, char *buffer) { return 0; } + +void tree_sitter_toml_external_scanner_deserialize(void *payload, const char *buffer, unsigned length) {} + +bool tree_sitter_toml_external_scanner_scan_multiline_string_end(TSLexer *lexer, const bool *valid_symbols, + int32_t delimiter, TokenType content_symbol, + TokenType end_symbol) { + if (!valid_symbols[end_symbol] || lexer->lookahead != delimiter) { + return false; + } + + lexer->advance(lexer, false); + lexer->mark_end(lexer); + + if (lexer->lookahead != delimiter) { + lexer->result_symbol = content_symbol; + return true; + } + + lexer->advance(lexer, false); + + if (lexer->lookahead != delimiter) { + lexer->mark_end(lexer); + lexer->result_symbol = content_symbol; + return true; + } + + lexer->advance(lexer, false); + + if (lexer->lookahead != delimiter) { + lexer->mark_end(lexer); + lexer->result_symbol = end_symbol; + return true; + } + + lexer->result_symbol = content_symbol; + return true; +} + +bool tree_sitter_toml_external_scanner_scan(void *payload, TSLexer *lexer, const bool *valid_symbols) { + if (tree_sitter_toml_external_scanner_scan_multiline_string_end( + lexer, valid_symbols, '"', MULTILINE_BASIC_STRING_CONTENT, MULTILINE_BASIC_STRING_END) || + tree_sitter_toml_external_scanner_scan_multiline_string_end( + lexer, valid_symbols, '\'', MULTILINE_LITERAL_STRING_CONTENT, MULTILINE_LITERAL_STRING_END)) { + return true; + } + + if (valid_symbols[LINE_ENDING_OR_EOF]) { + lexer->result_symbol = LINE_ENDING_OR_EOF; + + while (lexer->lookahead == ' ' || lexer->lookahead == '\t') { + lexer->advance(lexer, true); + } + + if (lexer->lookahead == 0 || lexer->lookahead == '\n') { + return true; + } + + if (lexer->lookahead == '\r') { + lexer->advance(lexer, true); + if (lexer->lookahead == '\n') { + return true; + } + } + } + + return false; +} diff --git a/Sources/TreeSitterTOML/tree_sitter/parser.h b/Sources/TreeSitterTOML/tree_sitter/parser.h new file mode 100644 index 0000000..799f599 --- /dev/null +++ b/Sources/TreeSitterTOML/tree_sitter/parser.h @@ -0,0 +1,266 @@ +#ifndef TREE_SITTER_PARSER_H_ +#define TREE_SITTER_PARSER_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +#define ts_builtin_sym_error ((TSSymbol)-1) +#define ts_builtin_sym_end 0 +#define TREE_SITTER_SERIALIZATION_BUFFER_SIZE 1024 + +#ifndef TREE_SITTER_API_H_ +typedef uint16_t TSStateId; +typedef uint16_t TSSymbol; +typedef uint16_t TSFieldId; +typedef struct TSLanguage TSLanguage; +#endif + +typedef struct { + TSFieldId field_id; + uint8_t child_index; + bool inherited; +} TSFieldMapEntry; + +typedef struct { + uint16_t index; + uint16_t length; +} TSFieldMapSlice; + +typedef struct { + bool visible; + bool named; + bool supertype; +} TSSymbolMetadata; + +typedef struct TSLexer TSLexer; + +struct TSLexer { + int32_t lookahead; + TSSymbol result_symbol; + void (*advance)(TSLexer *, bool); + void (*mark_end)(TSLexer *); + uint32_t (*get_column)(TSLexer *); + bool (*is_at_included_range_start)(const TSLexer *); + bool (*eof)(const TSLexer *); + void (*log)(const TSLexer *, const char *, ...); +}; + +typedef enum { + TSParseActionTypeShift, + TSParseActionTypeReduce, + TSParseActionTypeAccept, + TSParseActionTypeRecover, +} TSParseActionType; + +typedef union { + struct { + uint8_t type; + TSStateId state; + bool extra; + bool repetition; + } shift; + struct { + uint8_t type; + uint8_t child_count; + TSSymbol symbol; + int16_t dynamic_precedence; + uint16_t production_id; + } reduce; + uint8_t type; +} TSParseAction; + +typedef struct { + uint16_t lex_state; + uint16_t external_lex_state; +} TSLexMode; + +typedef union { + TSParseAction action; + struct { + uint8_t count; + bool reusable; + } entry; +} TSParseActionEntry; + +typedef struct { + int32_t start; + int32_t end; +} TSCharacterRange; + +struct TSLanguage { + uint32_t version; + uint32_t symbol_count; + uint32_t alias_count; + uint32_t token_count; + uint32_t external_token_count; + uint32_t state_count; + uint32_t large_state_count; + uint32_t production_id_count; + uint32_t field_count; + uint16_t max_alias_sequence_length; + const uint16_t *parse_table; + const uint16_t *small_parse_table; + const uint32_t *small_parse_table_map; + const TSParseActionEntry *parse_actions; + const char * const *symbol_names; + const char * const *field_names; + const TSFieldMapSlice *field_map_slices; + const TSFieldMapEntry *field_map_entries; + const TSSymbolMetadata *symbol_metadata; + const TSSymbol *public_symbol_map; + const uint16_t *alias_map; + const TSSymbol *alias_sequences; + const TSLexMode *lex_modes; + bool (*lex_fn)(TSLexer *, TSStateId); + bool (*keyword_lex_fn)(TSLexer *, TSStateId); + TSSymbol keyword_capture_token; + struct { + const bool *states; + const TSSymbol *symbol_map; + void *(*create)(void); + void (*destroy)(void *); + bool (*scan)(void *, TSLexer *, const bool *symbol_whitelist); + unsigned (*serialize)(void *, char *); + void (*deserialize)(void *, const char *, unsigned); + } external_scanner; + const TSStateId *primary_state_ids; +}; + +static inline bool set_contains(TSCharacterRange *ranges, uint32_t len, int32_t lookahead) { + uint32_t index = 0; + uint32_t size = len - index; + while (size > 1) { + uint32_t half_size = size / 2; + uint32_t mid_index = index + half_size; + TSCharacterRange *range = &ranges[mid_index]; + if (lookahead >= range->start && lookahead <= range->end) { + return true; + } else if (lookahead > range->end) { + index = mid_index; + } + size -= half_size; + } + TSCharacterRange *range = &ranges[index]; + return (lookahead >= range->start && lookahead <= range->end); +} + +/* + * Lexer Macros + */ + +#ifdef _MSC_VER +#define UNUSED __pragma(warning(suppress : 4101)) +#else +#define UNUSED __attribute__((unused)) +#endif + +#define START_LEXER() \ + bool result = false; \ + bool skip = false; \ + UNUSED \ + bool eof = false; \ + int32_t lookahead; \ + goto start; \ + next_state: \ + lexer->advance(lexer, skip); \ + start: \ + skip = false; \ + lookahead = lexer->lookahead; + +#define ADVANCE(state_value) \ + { \ + state = state_value; \ + goto next_state; \ + } + +#define ADVANCE_MAP(...) \ + { \ + static const uint16_t map[] = { __VA_ARGS__ }; \ + for (uint32_t i = 0; i < sizeof(map) / sizeof(map[0]); i += 2) { \ + if (map[i] == lookahead) { \ + state = map[i + 1]; \ + goto next_state; \ + } \ + } \ + } + +#define SKIP(state_value) \ + { \ + skip = true; \ + state = state_value; \ + goto next_state; \ + } + +#define ACCEPT_TOKEN(symbol_value) \ + result = true; \ + lexer->result_symbol = symbol_value; \ + lexer->mark_end(lexer); + +#define END_STATE() return result; + +/* + * Parse Table Macros + */ + +#define SMALL_STATE(id) ((id) - LARGE_STATE_COUNT) + +#define STATE(id) id + +#define ACTIONS(id) id + +#define SHIFT(state_value) \ + {{ \ + .shift = { \ + .type = TSParseActionTypeShift, \ + .state = (state_value) \ + } \ + }} + +#define SHIFT_REPEAT(state_value) \ + {{ \ + .shift = { \ + .type = TSParseActionTypeShift, \ + .state = (state_value), \ + .repetition = true \ + } \ + }} + +#define SHIFT_EXTRA() \ + {{ \ + .shift = { \ + .type = TSParseActionTypeShift, \ + .extra = true \ + } \ + }} + +#define REDUCE(symbol_name, children, precedence, prod_id) \ + {{ \ + .reduce = { \ + .type = TSParseActionTypeReduce, \ + .symbol = symbol_name, \ + .child_count = children, \ + .dynamic_precedence = precedence, \ + .production_id = prod_id \ + }, \ + }} + +#define RECOVER() \ + {{ \ + .type = TSParseActionTypeRecover \ + }} + +#define ACCEPT_INPUT() \ + {{ \ + .type = TSParseActionTypeAccept \ + }} + +#ifdef __cplusplus +} +#endif + +#endif // TREE_SITTER_PARSER_H_ diff --git a/Tests/NativeDocumentsTests/NativeDocumentTests.swift b/Tests/NativeDocumentsTests/NativeDocumentTests.swift new file mode 100644 index 0000000..6f70220 --- /dev/null +++ b/Tests/NativeDocumentsTests/NativeDocumentTests.swift @@ -0,0 +1,571 @@ +import AgentsCore +import Foundation +import NativeDocuments +import Testing + +func document( + _ text: String, _ format: NativeDocumentFormat = .toml, budget: NativeDocumentBudget? = nil +) throws -> NativeDocument { + try NativeDocument(bytes: Data(text.utf8), format: format, budget: budget ?? generousBudget()) +} +func keyRegion(_ keys: String...) -> NativeRegion { NativeRegion(keys: keys) } +func owned(_ doc: NativeDocument, _ region: NativeRegion) throws -> NativeExpectedRegion { + .owned(try #require(try doc.read(region))) +} +func text(_ change: PreparedNativeChange) -> String { + String(decoding: change.bytes, as: UTF8.self) +} + +@Test func jsoncRegionalOwnershipAndBytes() throws { + let source = """ + { + // client-owned , [ ] \" sentinel + "accountSentinel": "keep", + "projects": { + "/work/a.b": { + "hasTrustDialogAccepted": false, + "mcpServers": {"db": {"command": "old", "args": []}} + }, + "/work/b": {"mcpServers": {"other": {"command": "keep"}}} + }, + "mcpServers": {"user": {"command": "keep"}} + } + """ + let doc = try document(source, .jsonc(trailingCommas: true)) + let command = keyRegion("projects", "/work/a.b", "mcpServers", "db", "command") + let commandObservation = try #require(try doc.read(command)) + #expect( + commandObservation.entryRanges.contains { + String(decoding: Array(source.utf8)[$0], as: UTF8.self) == "\"command\": \"old\"" + }) + let updated = try doc.prepare([ + .put(region: command, expected: owned(doc, command), value: .string("new")) + ]) + #expect(text(updated) == source.replacingOccurrences(of: "\"old\"", with: "\"new\"")) + let db = keyRegion("projects", "/work/a.b", "mcpServers", "db") + let removed = try doc.prepare([.remove(region: db, expected: owned(doc, db))]) + #expect(text(removed).contains("\"mcpServers\": {}")) + #expect(text(removed).contains("// client-owned , [ ] \" sentinel")) + #expect(text(removed).contains("\"hasTrustDialogAccepted\": false")) + #expect(text(removed).contains("\"user\": {\"command\": \"keep\"}")) + #expect(throws: NativeDocumentError.self) { + try doc.prepare([.put(region: command, expected: .absent, value: .string("old"))]) + } + #expect(try doc.prepare([]).bytes == Data(source.utf8)) + let crlf = "\u{feff}" + source.replacingOccurrences(of: "\n", with: "\r\n") + let crDoc = try document(crlf, .jsonc(trailingCommas: false)) + #expect( + try crDoc.prepare([ + .put(region: command, expected: owned(crDoc, command), value: .string("old")) + ]).bytes == Data(crlf.utf8)) +} + +@Test func jsonSyntaxExactIdentityAndNumbers() throws { + for source in [ + #"{"db":1,"\u0064b":2}"#, "{}{}", "[1,]", "{/*comment*/}", "{a:1}", "[01]", "[1.]", "[NaN]", + #"["\uD800"]"#, + ] { + #expect(throws: NativeDocumentError.self) { try document(source, .json) } + } + let source = #"{"é":1,"e\u0301":2,"value":"\u00e9","decimal":12345678901234567890.00100}"# + let doc = try document(source, .json) + #expect(try doc.read(keyRegion("é"))?.value == .integer(1)) + #expect(try doc.read(keyRegion("e\u{301}"))?.value == .integer(2)) + #expect(try doc.read(NativeRegion(keys: []))?.value == nil) + let r = keyRegion("value") + #expect( + try doc.prepare([.put(region: r, expected: owned(doc, r), value: .string("é"))]).bytes + == Data(source.utf8)) + let change = try doc.prepare([ + .put(region: r, expected: owned(doc, r), value: .string("e\u{301}")) + ]) + #expect(change.bytes != Data(source.utf8)) + #expect(text(change).contains("12345678901234567890.00100")) + for format: NativeDocumentFormat in [.json, .toml] { + for decimal in ["1", "1.00", "1E+2", "-0", "123456789012345678901234567890"] { + let doc = try document(format == .json ? "{}" : "", format) + let c = try doc.prepare([ + .put(region: keyRegion("n"), expected: .absent, value: .decimal(decimal)) + ]) + let result = try NativeDocument(bytes: c.bytes, format: format, budget: generousBudget()) + #expect(try result.read(keyRegion("n")) != nil) + #expect(text(c).contains(decimal)) + } + } +} + +let t1 = #""" + title = "keep" + stamp = 1979-05-27T07:32:00Z + + [mcp_servers."db.prod"] # keep table note + command = "old" # keep field note + args = ["a", "b"] + description = """first + second # literal content + """ + + [mcp_servers."db.prod".env] + TOKEN = "${REFERENCE}" + [mcp_servers.other] + command = "keep" + """# + +@Test func tomlQuotedNestedAndNativeAtoms() throws { + let doc = try document(t1) + let command = keyRegion("mcp_servers", "db.prod", "command") + #expect( + text( + try doc.prepare([.put(region: command, expected: owned(doc, command), value: .string("new"))]) + ) == t1.replacingOccurrences(of: "\"old\"", with: "\"new\"")) + #expect(try doc.read(keyRegion("stamp"))?.value == nil) + let token = keyRegion("mcp_servers", "db.prod", "env", "TOKEN") + let newKey = keyRegion("mcp_servers", "db.prod", "env", "NEW") + let added = try doc.prepare([.put(region: newKey, expected: .absent, value: .string("added"))]) + #expect(text(added).contains("TOKEN = \"${REFERENCE}\"")) + #expect(text(added).contains("\"NEW\" = \"added\"\n[mcp_servers.other]")) + #expect( + text(try doc.prepare([.remove(region: token, expected: owned(doc, token))])).contains( + "[mcp_servers.other]")) + let server = keyRegion("mcp_servers", "db.prod") + let serverObservation = try #require(try doc.read(server)) + #expect( + serverObservation.entryRanges.contains { + String(decoding: Array(t1.utf8)[$0], as: UTF8.self) == "TOKEN = \"${REFERENCE}\"" + }) + let removed = text(try doc.prepare([.remove(region: server, expected: owned(doc, server))])) + #expect(removed.contains("# keep table note")) + #expect(removed.contains("# keep field note")) + #expect(removed.contains("stamp = 1979-05-27T07:32:00Z")) + #expect(!removed.contains("TOKEN =")) + #expect(removed.contains("[mcp_servers.other]\ncommand = \"keep\"")) + #expect(throws: NativeDocumentError.self) { + try doc.prepare([.put(region: command, expected: owned(doc, command), value: .null)]) + } + #expect( + try doc.prepare([.put(region: command, expected: owned(doc, command), value: .string("old"))]) + .bytes == Data(t1.utf8)) +} + +@Test func tomlDottedInlineAndScope() throws { + let source = #""" + mcp_servers."db.prod".command = "tool" + mcp_servers."db.prod".env = { "A.B" = "old", C = "keep" } + """# + let doc = try document(source) + let r = keyRegion("mcp_servers", "db.prod", "env", "A.B") + #expect( + text(try doc.prepare([.put(region: r, expected: owned(doc, r), value: .string("new"))])) + == source.replacingOccurrences(of: "\"old\"", with: "\"new\"")) + let added = try doc.prepare([ + .put( + region: keyRegion("mcp_servers", "db.prod", "env", "D"), expected: .absent, + value: .boolean(true)) + ]) + #expect(text(added).contains("C = \"keep\"")) + let deleted = try doc.prepare([.remove(region: r, expected: owned(doc, r))]) + #expect(text(deleted).contains("C = \"keep\"")) + let sibling = try doc.prepare([ + .put( + region: keyRegion("mcp_servers", "new"), expected: .absent, + value: .object(["command": .string("new")])) + ]) + #expect( + try NativeDocument(bytes: sibling.bytes, format: .toml, budget: generousBudget()).read( + keyRegion("mcp_servers", "new", "command"))?.value == .string("new")) + #expect(throws: NativeDocumentError.self) { + try document(source + "\n[mcp_servers.\"db.prod\"]\na=1") + } +} + +@Test func tomlArrayTablesLatestChildAndRemoval() throws { + let source = """ + [[checks]] + id = "first" + [checks.env] + MODE = "a" + [[checks]] + id = "second" + [checks.env] + MODE = "b" + """ + let doc = try document(source) + let second = NativeRegion([ + .key("checks"), .occurrence(.init(idKey: "id", id: "second")), .key("env"), .key("MODE"), + ]) + #expect(try doc.read(second)?.value == .string("b")) + let changed = try doc.prepare([ + .put(region: second, expected: owned(doc, second), value: .string("new")) + ]) + #expect(text(changed) == source.replacingOccurrences(of: "\"b\"", with: "\"new\"")) + let first = NativeRegion([.key("checks"), .occurrence(.init(idKey: "id", id: "first"))]) + let removed = try doc.prepare([.remove(region: first, expected: owned(doc, first))]) + #expect(!text(removed).contains("MODE = \"a\"")) + #expect(text(removed).contains("id = \"second\"\n[checks.env]\nMODE = \"b\"")) + let duplicates = try document(String(repeating: "[[checks]]\nid=\"same\"\n", count: 5)) + let occurrences = try #require(try duplicates.read(keyRegion("checks"))).occurrences + #expect(throws: NativeDocumentError.self) { + try duplicates.read(NativeRegion([.key("checks"), .occurrence(occurrences[2])])) + } + +} + +@Test func readOnlyBudgetsAndSafeErrors() throws { + let source = "x = {\na = 1,\n}" + let doc = try document(source) + #expect(try doc.read(keyRegion("x", "a"))?.value == .integer(1)) + #expect(throws: NativeDocumentError.self) { + try doc.prepare([ + .put( + region: keyRegion("x", "a"), expected: owned(doc, keyRegion("x", "a")), value: .integer(2)) + ]) + } + for source in [ + "x=\"" + String(repeating: "a", count: 2000) + "\"", "#" + String(repeating: "a", count: 2000), + "x=1\n" + String(repeating: " ", count: 2000), + ] { + let budget = NativeDocumentBudget( + limits: .init( + storage: 100_000, work: 100_000, nodes: 1000, depth: 20, uninterruptedBytes: 100)) + #expect(throws: NativeDocumentError.self) { try document(source, budget: budget) } + } + let budget = NativeDocumentBudget( + limits: .init(storage: 100_000, work: 300, nodes: 1000, depth: 20, uninterruptedBytes: 1000)) + let bounded = try document("x=1", budget: budget) + var exhausted = false + for _ in 0..<30 { + do { + _ = try bounded.prepare([ + .put(region: keyRegion("x"), expected: owned(bounded, keyRegion("x")), value: .integer(2)) + ]) + } catch NativeDocumentError.budgetExceeded { + exhausted = true + break + } + } + #expect(exhausted) + do { _ = try document("secret=\"PRIVATE_SENTINEL\"\nbad=1979-05") } catch { + #expect(!String(describing: error).contains("PRIVATE_SENTINEL")) + } +} + +@Test func structuralObjectsTriviaAndContainerEvidence() throws { + let source = "{\"a\": 1, /* sibling */ \"b\": 2, \"c\": 3}" + let doc = try document(source, .jsonc(trailingCommas: true)) + let object = keyRegion("owned") + let parent = try document( + "{\"owned\": " + source + ", \"keep\": true}", .jsonc(trailingCommas: true)) + let result = try parent.prepare([ + .put( + region: object, expected: owned(parent, object), + value: .object(["a": .integer(1), "new": .string("yes")])) + ]) + #expect(text(result).contains("/* sibling */")) + #expect(text(result).contains("\"keep\": true")) + #expect( + try doc.prepare([.remove(region: keyRegion("b"), expected: owned(doc, keyRegion("b")))]).bytes + != doc.bytes) + let empty = try document("{\"owned\":{}}", .json) + let observed = try #require(try empty.read(object)) + #expect(throws: NativeDocumentError.self) { + try empty.prepare([.remove(region: object, expected: .owned(observed))]) + } + #expect( + text(try empty.prepare([.remove(region: object, expected: .createdContainer(observed))])) + == "{}") + let commented = try document("{\"owned\":{/* preserve */}}", .jsonc(trailingCommas: true)) + let commentEvidence = try #require(try commented.read(object)) + #expect(throws: NativeDocumentError.self) { + try commented.prepare([.remove(region: object, expected: .createdContainer(commentEvidence))]) + } + let created = try empty.prepare([ + .put(region: keyRegion("new", "child"), expected: .absent, value: .object([:])) + ]) + #expect(created.createdContainers.contains(keyRegion("new"))) + #expect(created.createdContainers.contains(keyRegion("new", "child"))) + let invalid = try document("{\"a\": /* ambiguous */ 1}", .jsonc(trailingCommas: true)) + #expect(throws: NativeDocumentError.self) { + try invalid.prepare([.remove(region: keyRegion("a"), expected: owned(invalid, keyRegion("a")))]) + } + let trailing = try document("{\"a\":1,}", .jsonc(trailingCommas: true)) + _ = try trailing.prepare([.put(region: keyRegion("b"), expected: .absent, value: .integer(2))]) +} + +@Test func tomlUnicodeBOMAndInlinePunctuation() throws { + let source = "\u{feff}\"é\"=1\r\n\"e\u{301}\"=2\r\nx=\"\\u00e9\"\r\nstamp=nan\r\n" + let doc = try document(source) + #expect(try doc.read(keyRegion("é"))?.value == .integer(1)) + #expect(try doc.read(keyRegion("e\u{301}"))?.value == .integer(2)) + let x = keyRegion("x") + #expect( + try doc.prepare([.put(region: x, expected: owned(doc, x), value: .string("é"))]).bytes + == Data(source.utf8)) + let changed = try doc.prepare([ + .put(region: x, expected: owned(doc, x), value: .string("e\u{301}")) + ]) + #expect(text(changed) == source.replacingOccurrences(of: "\\u00e9", with: "e\u{301}")) + let inline = try document("x={ a=\"first\", b=[], c=\"last\" }") + let b = keyRegion("x", "b") + #expect( + text(try inline.prepare([.remove(region: b, expected: owned(inline, b))])).contains( + "c=\"last\"")) + let r = keyRegion("a") + let before = try document("a=\"old\"") + let after = try document("a=\"new\"") + #expect(throws: NativeDocumentError.self) { + try after.prepare([.put(region: r, expected: owned(before, r), value: .string("replace"))]) + } +} + +@Test func exactEvidenceAndMultiEditFailure() throws { + let region = keyRegion("owned") + let original = try document(#"{"owned":{"a":{},"b":"x"}}"#, .json) + let changed = try document(#"{"owned":{"a":{"b":"x"}}}"#, .json) + #expect(throws: NativeDocumentError.self) { + try changed.prepare([ + .put(region: region, expected: owned(original, region), value: .object([:])) + ]) + } + let valid = try document(#"{"a":1,"b":2}"#, .json) + let before = valid.bytes + #expect(throws: NativeDocumentError.self) { + try valid.prepare([ + .put(region: keyRegion("a"), expected: owned(valid, keyRegion("a")), value: .integer(3)), + .put(region: keyRegion("b"), expected: .absent, value: .integer(4)), + ]) + } + #expect(valid.bytes == before) + let source = "[owned]\nargs=[\n# keep array note\n\"a\"\n]\n" + let table = try document(source) + #expect(throws: NativeDocumentError.self) { + try table.prepare([ + .remove(region: keyRegion("owned"), expected: owned(table, keyRegion("owned"))) + ]) + } +} + +@Test func occurrenceIdentityEvidenceAndAliasOverlap() throws { + let source = "[[checks]]\nid=\"é\"\nx=1\n[[checks]]\nid=\"e\u{301}\"\nx=2" + let doc = try document(source) + let array = try #require(try doc.read(keyRegion("checks"))) + let second = NativeRegion([ + .key("checks"), .occurrence(.init(idKey: "id", id: "e\u{301}")), .key("x"), + ]) + #expect(try doc.read(second)?.value == .integer(2)) + let same = NativeRegion([.key("checks"), .occurrence(array.occurrences[1]), .key("x")]) + #expect(throws: NativeDocumentError.self) { + try doc.prepare([ + .put(region: second, expected: owned(doc, second), value: .integer(3)), + .put(region: same, expected: owned(doc, same), value: .integer(4)), + ]) + } + let id = NativeRegion([.key("checks"), .occurrence(.init(idKey: "id", id: "é")), .key("id")]) + let renamed = try doc.prepare([ + .put(region: id, expected: owned(doc, id), value: .string("renamed")) + ]) + #expect(renamed.observations.first?.value == .string("renamed")) + #expect( + renamed.observations.first?.region + == NativeRegion([.key("checks"), .occurrence(.init(idKey: "id", id: "renamed")), .key("id")])) + let duplicates = try document("[[checks]]\nx=1\n[[checks]]\nx=2\n[[checks]]\nx=1") + let evidence = try #require(try duplicates.read(keyRegion("checks"))).occurrences[2] + #expect( + try duplicates.read(NativeRegion([.key("checks"), .occurrence(evidence), .key("x")]))?.value + == .integer(1)) +} + +@Test func arrayDraftsPreserveOriginalOwnershipAddresses() throws { + let doc = try document( + "[[checks]]\nid=\"first\"\nx=1\n[[checks]]\nid=\"second\"\nx=2\n[[checks]]\nid=\"third\"\nx=3") + func occurrence(_ id: String, _ key: String? = nil) -> NativeRegion { + var steps: [NativePathStep] = [.key("checks"), .occurrence(.init(idKey: "id", id: id))] + if let key { steps.append(.key(key)) } + return NativeRegion(steps) + } + let renamed = try doc.prepare([ + .put( + region: occurrence("second", "id"), expected: owned(doc, occurrence("second", "id")), + value: .string("renamed")), + .put( + region: occurrence("second", "x"), expected: owned(doc, occurrence("second", "x")), + value: .integer(22)), + ]) + #expect(renamed.observations.count == 2) + #expect(renamed.observations.last?.value == .integer(22)) + let removed = try doc.prepare([ + .remove(region: occurrence("first"), expected: owned(doc, occurrence("first"))), + .remove(region: occurrence("second"), expected: owned(doc, occurrence("second"))), + ]) + #expect(text(removed).contains("id=\"third\"")) + #expect(!text(removed).contains("id=\"second\"")) +} + +@Test func exactTOMLDecimalProjectionAndTrueEOF() throws { + let doc = try document("n=+1_000.00\nx=12:13:14.1") + let region = keyRegion("n") + let observation = try #require(try doc.read(region)) + #expect(observation.value == .decimal("1000.00")) + #expect(observation.numericLexeme == "+1_000.00") + #expect( + try doc.prepare([ + .put(region: region, expected: .owned(observation), value: .decimal("1000.00")) + ]).bytes == doc.bytes) + #expect(try doc.prepare([]).bytes == doc.bytes) + #expect(throws: NativeDocumentError.self) { + try doc.prepare([.put(region: region, expected: .owned(observation), value: .decimal("1_000"))]) + } +} + +@Test func nativeCanonicalTableCollisionAndReadOnlyReasons() throws { + let a = "prefixabcdefgh-a\u{301}\u{327}-zyxwvuts" + let b = "prefixabcdefgh-a\u{327}\u{301}-zyxwvuts" + let source = "title=\"old\"\n[\"\(a)\"]\nx=1\n[\"\(b)\"]\nx=2" + let doc = try document(source) + #expect(try doc.read(keyRegion(a, "x"))?.value == .integer(1)) + #expect(try doc.read(keyRegion(b, "x"))?.value == .integer(2)) + #expect( + text( + try doc.prepare([ + .put( + region: keyRegion("title"), expected: owned(doc, keyRegion("title")), + value: .string("new")) + ])) == source.replacingOccurrences(of: "\"old\"", with: "\"new\"")) + for source in ["x={\na=1,\n}", #"x="\x41""#, #"x="\e""#, "x=12:13"] { + let doc = try document(source) + #expect(try doc.read(keyRegion("x")) != nil) + do { + _ = try doc.prepare([ + .put(region: keyRegion("x"), expected: owned(doc, keyRegion("x")), value: .string("new")) + ]) + Issue.record("read-only syntax was edited") + } catch NativeDocumentError.unsupportedEdit(.syntaxNotLocated, _, _) {} + } +} + +@Test func cancellationAndReadOnlyAdmissionAreNotSyntaxFallbacks() throws { + var checks = 0 + let cancelled = NativeDocumentBudget( + limits: .init( + storage: 1_000_000, work: 1_000_000, nodes: 10_000, depth: 30, uninterruptedBytes: 100_000), + cancellation: { + checks += 1 + return checks > 100 + }) + do { + _ = try document("#" + String(repeating: "x", count: 10_000), budget: cancelled) + Issue.record("cancellation was ignored") + } catch NativeDocumentError.cancelled {} + let wide = "x={\n" + (0..<1000).map { "k\($0)=1," }.joined(separator: "\n") + "\n}" + let bounded = NativeDocumentBudget( + limits: .init( + storage: 1_000_000, work: 20_000, nodes: 100_000, depth: 30, uninterruptedBytes: 100_000)) + do { + _ = try document(wide, budget: bounded) + Issue.record("read-only semantics escaped the work budget") + } catch NativeDocumentError.budgetExceeded {} + for source in [ + "#" + String(repeating: "x", count: 2000), "x=1\n" + String(repeating: " ", count: 2000), + "x=\"" + String(repeating: "x", count: 2000) + "\"", + ] { + let budget = NativeDocumentBudget( + limits: .init( + storage: 1_000_000, work: 1_000_000, nodes: 100_000, depth: 30, uninterruptedBytes: 100)) + do { + _ = try document(source, budget: budget) + Issue.record("CST envelope was not enforced") + } catch NativeDocumentError.budgetExceeded(let stage) { + #expect(stage == "CST uninterrupted input") + } + } +} + +@Test func regionalInsertionUsesLocalWhitespace() throws { + let pretty = "{\n \"owned\": {\n \"a\":1 // keep field note\n },\n \"keep\": true\n}" + let doc = try document(pretty, .jsonc(trailingCommas: false)) + let result = try doc.prepare([ + .put(region: keyRegion("owned", "b"), expected: .absent, value: .integer(2)) + ]) + #expect( + text(result) + == pretty.replacingOccurrences(of: "\"a\":1", with: "\"a\":1,").replacingOccurrences( + of: " },", with: " \"b\":2\n },")) + let compact = try document("{\"a\":1}", .json) + #expect( + text(try compact.prepare([.put(region: keyRegion("b"), expected: .absent, value: .integer(2))])) + == "{\"a\":1,\"b\":2}") + let inline = try document("x={ a = 1, b = 2 }") + #expect( + text( + try inline.prepare([.put(region: keyRegion("x", "c"), expected: .absent, value: .integer(3))]) + ) == "x={ a = 1, b = 2, \"c\" = 3 }") +} + +@Test func absentOccurrenceAppendAndOwnedArrayTables() throws { + let source = "[[checks]]\nid=\"first\"\n[checks.env]\nMODE=\"a\"\n[other]\nvalue=\"keep\"" + let doc = try document(source) + let second = NativeRegion([.key("checks"), .occurrence(.init(idKey: "id", id: "second"))]) + #expect(try doc.read(second) == nil) + let appended = try doc.prepare([ + .put( + region: second, expected: .absent, + value: .object(["id": .string("second"), "env": .object(["MODE": .string("b")])])) + ]) + #expect(text(appended).hasPrefix(source)) + let parsed = try NativeDocument(bytes: appended.bytes, format: .toml, budget: generousBudget()) + #expect( + try parsed.read(NativeRegion(second.steps + [.key("env"), .key("MODE")]))?.value == .string("b") + ) + #expect(try parsed.read(keyRegion("other", "value"))?.value == .string("keep")) + #expect(throws: NativeDocumentError.self) { + try doc.prepare([ + .put(region: second, expected: .absent, value: .object(["id": .string("wrong")])) + ]) + } + let array = keyRegion("checks") + let replaced = try doc.prepare([ + .put( + region: array, expected: owned(doc, array), + value: .array([ + .object(["id": .string("renamed"), "env": .object(["MODE": .string("new")])]), + .object(["id": .string("second")]), + ])) + ]) + #expect(text(replaced).contains("value=\"keep\"")) + #expect( + try NativeDocument(bytes: replaced.bytes, format: .toml, budget: generousBudget()).read( + NativeRegion([ + .key("checks"), .occurrence(.init(idKey: "id", id: "renamed")), .key("env"), .key("MODE"), + ]))?.value == .string("new")) + let json = try document("{\"checks\":[{\"id\":\"first\"}],\"keep\":true}", .json) + let jsonAppend = try json.prepare([ + .put(region: second, expected: .absent, value: .object(["id": .string("second")])) + ]) + #expect( + try NativeDocument(bytes: jsonAppend.bytes, format: .json, budget: generousBudget()).read( + second)?.value == .object(["id": .string("second")])) +} + +@Test func finalArrayOccurrenceRetainsItsContainer() throws { + let doc = try document( + "[[checks]] # keep table note\nid=\"last\"\n[checks.env]\nMODE=\"a\"\n[other]\nx=1") + let occurrence = NativeRegion([.key("checks"), .occurrence(.init(idKey: "id", id: "last"))]) + let removed = try doc.prepare([.remove(region: occurrence, expected: owned(doc, occurrence))]) + let result = try NativeDocument(bytes: removed.bytes, format: .toml, budget: generousBudget()) + #expect(try result.read(keyRegion("checks"))?.value == .array([])) + #expect(text(removed).contains("# keep table note")) + #expect(text(removed).contains("[other]\nx=1")) + let mixed = try doc.prepare([ + .put( + region: keyRegion("checks"), expected: owned(doc, keyRegion("checks")), + value: .array([.integer(1), .string("two")])) + ]) + #expect( + try NativeDocument(bytes: mixed.bytes, format: .toml, budget: generousBudget()).read( + keyRegion("checks"))?.value == .array([.integer(1), .string("two")])) + let emptySet = try doc.prepare([ + .put(region: keyRegion("checks"), expected: owned(doc, keyRegion("checks")), value: .array([])) + ]) + #expect( + try NativeDocument(bytes: emptySet.bytes, format: .toml, budget: generousBudget()).read( + keyRegion("checks"))?.value == .array([])) +} diff --git a/Tests/NativeDocumentsTests/SemanticTests.swift b/Tests/NativeDocumentsTests/SemanticTests.swift new file mode 100644 index 0000000..067d0c5 --- /dev/null +++ b/Tests/NativeDocumentsTests/SemanticTests.swift @@ -0,0 +1,70 @@ +import Foundation +import Testing + +@testable import TOMLSemantics + +func generousBudget() -> SemanticBudget { + SemanticBudget( + limits: .init( + storage: 20_000_000, work: 20_000_000, nodes: 100_000, depth: 128, + uninterruptedBytes: 1_000_000)) +} + +@Test func exactKeysAndLazyValidation() throws { + let a = "prefixabcdefgh-a\u{301}\u{327}-zyxwvuts" + let b = "prefixabcdefgh-a\u{327}\u{301}-zyxwvuts" + let doc = try SemanticDocument( + source: "\"é\"=1\n\"e\u{301}\"=2\n\"\(a)\"=3\n\"\(b)\"=4", budget: generousBudget()) + guard case .object(let pairs) = doc.root else { + Issue.record("root") + return + } + #expect(pairs.count == 4) + #expect(pairs[0].key.utf8.elementsEqual("é".utf8)) + #expect(pairs[1].key.utf8.elementsEqual("e\u{301}".utf8)) + #expect(throws: (any Error).self) { + try SemanticDocument(source: "a=1\n\"\\u0061\"=2", budget: generousBudget()) + } + for source in [ + "deep=[{bad=2023-02-30}]", #"deep=[{bad="\q"}]"#, "x=9223372036854775808", "x=1979-05", + "x=12:13:", + ] { + #expect(throws: (any Error).self) { + try SemanticDocument(source: source, budget: generousBudget()) + } + } + for source in ["x=12:13:14.1", "x=12:13", "x={\na=1,\n}", "x=[0xFE,1.0,true,1979-05-27,\"yes\"]"] + { + _ = try SemanticDocument(source: source, budget: generousBudget()) + } +} + +@Test func semanticBudgetAndCancellation() throws { + let tiny = SemanticBudget( + limits: .init(storage: 2, work: 100, nodes: 10, depth: 3, uninterruptedBytes: 10)) + #expect(throws: SemanticBudget.Failure.self) { try SemanticDocument(source: "x=1", budget: tiny) } + let cancelled = SemanticBudget( + limits: .init(storage: 1000, work: 1000, nodes: 100, depth: 10, uninterruptedBytes: 1000), + cancellation: { true }) + #expect(throws: SemanticBudget.Failure.self) { + try SemanticDocument(source: "x=1", budget: cancelled) + } + var cancellationChecks = 0 + let scanning = SemanticBudget( + limits: .init( + storage: 100_000, work: 100_000, nodes: 10_000, depth: 10, uninterruptedBytes: 100_000), + cancellation: { + cancellationChecks += 1 + return cancellationChecks > 100 + }) + do { + _ = try SemanticDocument(source: "#" + String(repeating: "x", count: 5000), budget: scanning) + Issue.record("semantic comment scanning ignored cancellation") + } catch SemanticBudget.Failure.cancelled {} + let depth = SemanticBudget( + limits: .init( + storage: 100_000, work: 100_000, nodes: 1000, depth: 3, uninterruptedBytes: 100_000)) + #expect(throws: SemanticBudget.Failure.self) { + try SemanticDocument(source: "x={\na={\nb={\nc={\nd=1\n}\n}\n}\n}", budget: depth) + } +} From 87bbb4cafae814812f0358f0034a83509e2d799f Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 06:46:57 +0800 Subject: [PATCH 052/171] test(core): cover native configuration edit contracts --- .../NativeDocumentTests.swift | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) diff --git a/Tests/NativeDocumentsTests/NativeDocumentTests.swift b/Tests/NativeDocumentsTests/NativeDocumentTests.swift index 6f70220..229b6f3 100644 --- a/Tests/NativeDocumentsTests/NativeDocumentTests.swift +++ b/Tests/NativeDocumentsTests/NativeDocumentTests.swift @@ -569,3 +569,106 @@ let t1 = #""" try NativeDocument(bytes: emptySet.bytes, format: .toml, budget: generousBudget()).read( keyRegion("checks"))?.value == .array([])) } + +@Test func completeJSONCObjectIntentPreservesUnselectedBytes() throws { + let source = + "{\n \"owned\": {\"a\": 1, /* keep */ \"b\": 2, \"c\": 3},\n \"outside\": { \"sentinel\": true }\n}" + let doc = try document(source, .jsonc(trailingCommas: false)) + let region = keyRegion("owned") + let change = try doc.prepare([ + .put( + region: region, expected: owned(doc, region), + value: .object(["a": .integer(1), "b": .integer(20), "new": .string("yes")])) + ]) + let result = try NativeDocument( + bytes: change.bytes, format: .jsonc(trailingCommas: false), budget: generousBudget()) + #expect( + try result.read(region)?.value + == .object([ + "a": .integer(1), "b": .integer(20), "new": .string("yes"), + ])) + #expect(try result.read(keyRegion("owned", "c")) == nil) + #expect(text(change).contains("/* keep */")) + #expect(text(change).hasSuffix(",\n \"outside\": { \"sentinel\": true }\n}")) +} + +@Test func occurrenceEvidenceAcrossExternalChanges() throws { + let original = try document(#"{"items":[{"x":0},{"x":1},{"x":2}]}"#, .json) + let evidence = try #require(try original.read(keyRegion("items"))).occurrences[1] + let selected = NativeRegion([.key("items"), .occurrence(evidence), .key("x")]) + let observation = try #require(try original.read(selected)) + #expect(observation.value == .integer(1)) + let changed = try document(#"{"items":[{"x":0},{"x":1},{"x":2},{"x":0},{"x":1},{"x":2}]}"#, .json) + do { + _ = try changed.prepare([ + .put(region: selected, expected: .owned(observation), value: .integer(9)) + ]) + Issue.record("ambiguous occurrence was edited") + } catch NativeDocumentError.unsupportedEdit(.ambiguousOccurrence, _, _) {} + + let first = try document(#"{"items":[{"id":"a","x":1},{"id":"b","x":2}]}"#, .json) + let stable = NativeRegion([.key("items"), .occurrence(.init(idKey: "id", id: "b")), .key("x")]) + let prior = try #require(try first.read(stable)) + let inserted = try document( + #"{"items":[{"id":"new","x":0},{"id":"a","x":1},{"id":"b","x":2}]}"#, .json) + let result = try inserted.prepare([ + .put(region: stable, expected: .owned(prior), value: .integer(7)) + ]) + #expect(text(result) == #"{"items":[{"id":"new","x":0},{"id":"a","x":1},{"id":"b","x":7}]}"#) +} + +@Test func sharedBudgetAcrossDocumentsAndDrafts() throws { + func budget(_ work: Int) -> NativeDocumentBudget { + NativeDocumentBudget( + limits: .init( + storage: 1_000_000, work: work, nodes: 10_000, depth: 30, uninterruptedBytes: 10_000)) + } + func consume(_ budget: NativeDocumentBudget) throws { + let doc = try document(#"{"data":[1,2,3,4,5,6,7,8]}"#, .json, budget: budget) + _ = try doc.read(keyRegion("data")) + } + func setup(_ budget: NativeDocumentBudget) throws -> (NativeDocument, [NativeRegionEdit]) { + let doc = try document(#"{"a":1,"b":2}"#, .json, budget: budget) + let edits: [NativeRegionEdit] = try [ + .put(region: keyRegion("a"), expected: owned(doc, keyRegion("a")), value: .integer(3)), + .put(region: keyRegion("b"), expected: owned(doc, keyRegion("b")), value: .integer(4)), + ] + return (doc, edits) + } + var demonstrated = false + for limit in stride(from: 100, through: 5000, by: 50) { + do { + try consume(budget(limit)) + let (doc, edits) = try setup(budget(limit)) + _ = try doc.prepare(edits) + } catch NativeDocumentError.budgetExceeded { continue } + let shared = budget(limit) + try consume(shared) + let doc: NativeDocument + let edits: [NativeRegionEdit] + do { + (doc, edits) = try setup(shared) + } catch NativeDocumentError.budgetExceeded { continue } + do { + _ = try doc.prepare(edits) + } catch NativeDocumentError.budgetExceeded { + demonstrated = true + break + } + } + #expect(demonstrated) +} + +@Test func publicErrorsDistinguishInvalidDocumentsAndOwnership() throws { + for source in ["deep=[{bad=2023-02-30}]", #"deep=[{bad="\q"}]"#, "x=9223372036854775808"] { + do { + _ = try document(source) + Issue.record("invalid document was accepted") + } catch NativeDocumentError.invalidDocument {} + } + let doc = try document(#"{"a":1}"#, .json) + do { + _ = try doc.prepare([.put(region: keyRegion("a"), expected: .absent, value: .integer(1))]) + Issue.record("unowned value was adopted") + } catch NativeDocumentError.ownershipMismatch {} +} From c48f1fb0eb991ea984b688721ee336a03a7c3bc0 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:24:12 +0800 Subject: [PATCH 053/171] feat(core): coordinate shared configuration transactions --- Documentation/Architecture/State.md | 107 ++- Sources/AgentsCore/FileLock.swift | 43 + Sources/AgentsCore/FileTransaction.swift | 111 ++- .../AgentsCore/NativeTargetCoordination.swift | 492 +++++++++++ .../AgentsCore/PrivateMaterialization.swift | 76 +- Sources/AgentsCore/StateInspection.swift | 14 + Sources/AgentsCore/StateStore.swift | 24 +- .../AgentsCore/TransactionCheckpoint.swift | 4 +- Sources/AgentsCore/TransactionDisposal.swift | 4 + Sources/AgentsCore/TransactionJournal.swift | 46 +- Sources/AgentsCore/TransactionPaths.swift | 35 + .../AgentsCore/TransactionPublication.swift | 17 +- Sources/AgentsCore/TransactionRecovery.swift | 115 ++- Sources/AgentsCore/TransactionSession.swift | 32 +- .../PrivateMaterializationTests.swift | 66 +- Tests/AgentsCoreTests/SharedTargetTests.swift | 822 ++++++++++++++++++ .../StateTransactionTests.swift | 4 +- .../WatchDurabilityTests.swift | 4 +- .../CombinedUpdateTests.swift | 16 +- .../PrivateMaterializationProbe.swift | 54 ++ Tests/StateTestProcess/main.swift | 8 +- 21 files changed, 1976 insertions(+), 118 deletions(-) create mode 100644 Sources/AgentsCore/NativeTargetCoordination.swift create mode 100644 Tests/AgentsCoreTests/SharedTargetTests.swift diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index 380d439..f2128bf 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -315,16 +315,17 @@ the denial. Existing user content and metadata are preserved. ### Journal records -Journal format version 2 is independent of the manifest language, lock and watch +Journal format version 3 is independent of the manifest language, lock and watch versions. The root records its version, transaction UUID, scope identity, registered root -identities, transaction phase, operations, private containers and disposal -intent. A journal without this version, or with another version, is retained +identities, transaction phase, operations, private containers, disposal +intent, shared physical footprint, reservation readiness and terminal finalization. A journal without this version, or with another version, is retained unchanged. Recovery reports that it was written by another version and must be recovered with the version that wrote it; it does not guess a compatible replay. Paths are relative to named roots: scope state, registered agent installation -directories and registered instruction destinations. The journal binds the state +directories, registered instruction destinations and closed native routes. +Shared metadata destinations are derived by Core and cannot be requested as ordinary targets. The journal binds the state directory, each root and every destination parent to its physical location and identity. Registry boundaries resolve configured containers; descendants open without following links. Symlinked journals or descendants, overlapping targets, @@ -335,8 +336,9 @@ Each operation records its path, install/delete action, expected preimage or absence, parent identity, private container, sealed staged object, progress and any conflict reason and retained locations. Object evidence contains device, inode, type, SHA-256 digest, permission bits and executable status. Directory -evidence includes child identities and digests. Data replacements inherit the -existing regular file's metadata. Undo restores the original object and its +evidence includes child identities and digests. Ordinary data replacements inherit the +existing regular file's metadata. Known sensitive files use private construction +for replacements, including ordinary byte edits. Undo restores the original object and its metadata. Each used target parent has one private container with a UUID-derived name and @@ -431,7 +433,7 @@ ownership denials are reported rather than bypassed. ### Recovery outcomes Every mutating state operation first checks for an abandoned journal under the -scope lock, validates watch state and finishes pending reference cleanup before +scope lock, after taking any journal/request shared physical locks, validates watch state and finishes pending reference cleanup before proceeding. Recovery never reads the declaration: journal and watch-reference recovery complete even when `agents.yaml` does not parse, and orphaned mirror locations come from watch state and the lock, then from the mirror's origin. @@ -477,6 +479,15 @@ verified container identity. Links are never followed during deletion. Owner access may be granted to directories being disposed of without changing installed or restored metadata. Absent entries still receive a parent barrier. +After every container disposal barrier, the terminal journal durably records +`finalized = true`, retaining its `committed` or `rolledBack` phase. Only then +may it remove its reservations, sync their parents and remove the scope journal. +Recovery and diagnosis dispatch finalized records before constructing data roots +or parents: they validate scope and required coordination metadata only. Recovery +removes only that journal's metadata; diagnosis reports the terminal result and +pending cleanup without writes. A later writer's target, receipt and reservation +are left untouched, even when old data parents no longer exist. + Conflicts retain `transaction.json`, the available target objects and private containers holding user data in their slots. Each conflicting entry records the reason and scope-relative recovery locations. Doctor lists those reasons and @@ -502,11 +513,14 @@ scope without state. Both can also throw the declaration's `ManifestFailure`. Package callers obtain a `MaterializationTarget` from `StateStore` and prepare it with `preparePrivateMaterialization`. Core admits only its registered file paths; source-authoring and arbitrary external paths are refused. Current registrations -cover existing instruction-file destinations. Native settings, provider routes -and cross-scope destinations require verified adapter registrations before use. - -Callers retain the existing scope read/writer lock and pending-recovery checks -around preparation. Preparation captures the target's physical identity, UID/GID, mode and ordered +cover existing instruction-file destinations and the verified Claude MCP project, +local and user physical routes. `nativeTarget(for:)` accepts a closed +`NativeTargetRoute`; it grants no arbitrary external destination or regional +ownership. Native adapters still own regional editing and capability validation. + +Callers pass the complete `footprint: Set` to the existing +`withLock` or `withReadLock` boundary and retain that context around preparation. +Pending journal footprints are independently included before taking the scope lock. Preparation captures the target's physical identity, UID/GID, mode and ordered ACL evidence, together with every existing physical ancestor. It does not call a binding provider or renderer. A permissive existing file requires the caller's explicit `changingAccess` intent, as does an existing owner-only mode that differs @@ -525,7 +539,7 @@ It does not replace the enclosing candidate fingerprint or apply-handle lifecycl `RuntimeBindingProvider` using the store's runtime environment. Binding names are data, never commands supplied by a source. The same scope lock and sole journal cover ordinary targets, private targets, declaration/lock updates and the local -receipt. Ordinary requests preserve their existing metadata behavior. A private +receipt. Ordinary non-sensitive requests preserve their metadata behavior. A private replacement uses its own independently sealed access rather than copying the live target's metadata. Core verifies its private construction directory and an empty owner-readable/writable file before resolving bindings or writing payload @@ -538,9 +552,12 @@ The private `materializations.json` file in the scope directory stores only registered target coordinates, materialization generation, registered-root identity, materialized digest and access evidence. It contains no binding values, source closure or declaration model. It is updated in the same transaction as -the target. A later ordinary replacement or deletion still classifies its old -materialized preimage as sensitive, then removes that target's receipt record -when the new ordinary generation commits. Direct caller writes to the receipt +the target. A later ordinary byte replacement keeps both preimage and replacement +sensitive, constructs the replacement privately before its first byte and updates +the receipt from the sealed generation without invoking a provider. Region deletion +retains whole-file sensitivity while a file remains; whole-file deletion removes +the record in the same journal. Copy, link and arbitrary prepared producers cannot +replace a known sensitive file. Direct caller writes to the receipt are refused. Corrupt, permissive or stale receipts stop mutation rather than silently downgrading a known sensitive object. `materializationReceipt(for:)` returns only the local generation and access metadata. A caller that knows from @@ -575,13 +592,57 @@ protection hold; sticky protection is bound to the child owner. Root and same-UI adversaries are outside this boundary. Snapshot capture may retry a transient stat/ACL generation race; retries never refresh prepared or sealed evidence. -No cross-scope native route is registered by these primitives. Verified F routes -must supply their physical root/relative target derivation, native scope and -version, shared resource identity, owned region, actual readers/precedence, -private/reference alternatives and collision evidence before the corresponding -shared footprint, lock ordering and durable reservation can be integrated. These -local operations retain the ordinary scope writer lock and do not acquire a -global user lock. +### Shared physical native targets + +Claude project MCP uses project `.mcp.json` and remains scope-local. Claude local +and user MCP use the same `.claude.json`: a nonempty supplied `CLAUDE_CONFIG_DIR` +selects its parent, otherwise the supplied HOME does. Overrides must be absolute +filesystem directories; ambiguous relative roots are refused. This global configuration +root is distinct from the ordinary Claude skills/settings directory. + +The opened parent's device, inode and kind plus the registered basename define +the coordination identity and total lock order. Pathname authorization and +freshness remain separate. HOME, route and path aliases do not split a physical +resource; replacing the file does not change its coordination identity. Private +metadata under that parent lives in `.agents-native//`, containing +a persistent `lock`, authoritative private `receipt` and transient `reservation`. +The receipt records one physical file's generation, digest, root identity and +access evidence. Shared files have no second authoritative scope receipt. +Metadata, lock, receipt and reservation access are verified through opened +nofollow descriptors. A conflicting or unprovable domain stops publication. + +Admission takes the union of requested routes and a bounded read of the pending +scope journal, deduplicates and locks shared resources in physical order, then +locks the scope. It rereads scope and footprint before any preparation callback. +An expanded footprint releases all locks and re-admits before callback delivery. +The thread-confined context spans preparation, apply, synchronous failure recovery +and disposal. Nested scope acquisition or upgrades are refused. Skill, +instruction, combined update and watch mutations use this same boundary even +when only a pending journal requires shared coordination. Unrelated read-only +scope data does not acquire an absent shared footprint. + +The sole scope journal durably records reservation intents before creating any +reservation slot. A journal-UUID-derived private temporary file is written and +synced, then published with no-replace rename and a parent barrier. All +reservations become durable before readiness and any target publication. A +half-written temporary slot is recognized by its exact durable intent and +verified private file metadata; cleanup does not decode partial bytes. Before +readiness, reservation-only recovery has no constructed data objects and disposes +only its intent-owned metadata. Unknown slots and malformed final reservations +are retained. Another scope reports the owner locator and journal UUID; it never +runs cross-project recovery or steals by PID, time or missing owner journal. +Ready non-finalized journals require their reservations to remain present. + +The kernel locks last through finalization and metadata cleanup. A finalized +owner may encounter a newer reservation and leaves it untouched. Read-only paths +use existing locks and create no coordination directories, lock files, receipts +or reservations. They diagnose pending recovery without replay. External native +clients do not participate in these locks: preimage, digest, identity and access +changes cause freshness conflicts rather than overwriting client siblings. + +E supplies the complete new/old deployment footprint and redacted composition; +F supplies exact owned-region edits and route semantics. These Core registrations +do not claim native parser, adapter or real-client acceptance. ### Read-only access diff --git a/Sources/AgentsCore/FileLock.swift b/Sources/AgentsCore/FileLock.swift index 35af712..8d09fac 100644 --- a/Sources/AgentsCore/FileLock.swift +++ b/Sources/AgentsCore/FileLock.swift @@ -68,6 +68,49 @@ package enum FileLock { return try withDescriptor(descriptor, at: url, checkpoint: { _ in }, body) } + static func withCoordinationDescriptor( + at url: URL, writable: Bool, checkpoint: (String) throws -> Void = { _ in }, + _ body: (Int32) throws -> T + ) throws -> T { + let parent = try DirectoryHandle(at: url.deletingLastPathComponent()) + let descriptor = openat( + parent.descriptor, url.lastPathComponent, + (writable ? O_RDWR : O_RDONLY) | O_NOFOLLOW | O_CLOEXEC) + if descriptor < 0, !writable, errno == ENOENT { + let result = Result { try body(-1) } + if try parent.info(url.lastPathComponent) != nil { throw CoordinationReadmission.required } + return try result.get() + } + guard descriptor >= 0 else { + throw CoreError.invalidState("cannot open shared coordination lock") + } + defer { close(descriptor) } + let evidence = try FileAccessEvidence.requirePrivate(descriptor: descriptor) + guard evidence.identity.kind == S_IFREG else { + throw CoreError.invalidState("shared coordination lock is not a regular file") + } + let mode = writable ? LOCK_EX : LOCK_SH + while platform_flock(descriptor, mode | LOCK_NB) != 0 { + if errno == EINTR { continue } + guard errno == EWOULDBLOCK else { + throw CoreError.invalidState("cannot acquire shared coordination lock") + } + try checkpoint("contended") + while platform_flock(descriptor, mode) != 0 { + if errno != EINTR { + throw CoreError.invalidState("cannot acquire shared coordination lock") + } + } + break + } + guard try parent.info(url.lastPathComponent).map(FileObjectIdentity.init) == evidence.identity + else { + throw CoreError.invalidState("shared coordination lock changed") + } + try evidence.validate(descriptor: descriptor) + return try body(descriptor) + } + private static func withDescriptor( _ descriptor: Int32, at url: URL, checkpoint: (String) throws -> Void, _ body: (Int32) throws -> T diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 6e0418d..7b5e0be 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -36,9 +36,8 @@ package final class FileTransaction { private let checkpoint: (String) throws -> Void private let outcome: TransactionOutcome private var requests: [Request] = [] - private var receiptState: - (records: MaterializationReceipts, evidence: TargetPrecondition, access: FileAccessEvidence?)? - private var receiptIndex: Int? + private var receiptStates: [String: MaterializationReceiptState] = [:] + private var receiptIndices: [Int: MaterializationReceiptState] = [:] private var unchanged: [any PreparedEvidence] = [] private var targetPaths: Set { Set(requests.map { $0.evidence.url.path }) } @@ -57,7 +56,8 @@ package final class FileTransaction { executableFlags: [String: Bool]? = nil, expecting: TargetPrecondition? = nil ) throws { if let expectedHash { try StateValidation.digest(expectedHash) } - let (path, evidence, security) = try request(destination, expecting: expecting) + let (path, evidence, previous) = try request(destination, expecting: expecting) + var security = previous var expectation = Expectation(hash: expectedHash, executableFlags: executableFlags) switch source { case .copy(let url): @@ -67,10 +67,21 @@ package final class FileTransaction { url, parent: destination.deletingLastPathComponent(), store: store) case .data, .prepared: break } - requests.append( - Request( - path: path, evidence: evidence, source: source, expectation: expectation, - security: security, privateData: nil)) + if security.preimage == .privateMaterialization { + guard case .data(let data) = source else { + throw CoreError.invalidState("sensitive replacement requires private byte construction") + } + security.replacement = .privateMaterialization + requests.append( + Request( + path: path, evidence: evidence, source: nil, expectation: expectation, + security: security, privateData: { data })) + } else { + requests.append( + Request( + path: path, evidence: evidence, source: source, expectation: expectation, + security: security, privateData: nil)) + } } package func delete(_ destination: URL, expecting: TargetPrecondition? = nil) throws { @@ -87,7 +98,7 @@ package final class FileTransaction { provider: any RuntimeBindingProvider, render: @escaping (RuntimeBindingValues) throws -> Data ) throws { - guard prepared.target.scope == store.directory, prepared.owner == geteuid(), + guard prepared.target.scope.path == store.directory.path, prepared.owner == geteuid(), bindings.allSatisfy({ !$0.isEmpty && !$0.contains("\0") }) else { throw CoreError.invalidState("invalid private materialization inputs") } try prepared.receiptEvidence.validate() @@ -121,22 +132,27 @@ package final class FileTransaction { } private func queueReceipt() throws { - guard receiptIndex == nil, let receiptState, - requests.contains(where: { - $0.security.isPrivate || receiptState.records.targets[$0.path] != nil - }) - else { return } - let target = store.materializationReceiptURL - var security = TransactionSecurity() - security.preimage = receiptState.access == nil ? .ordinary : .privateMaterialization - security.replacement = .privateMaterialization - security.preimageAccess = receiptState.access - security.ancestry = try DirectoryAccessEvidence.capture(at: target.deletingLastPathComponent()) - receiptIndex = requests.count - requests.append( - Request( - path: "state/" + MaterializationReceipts.fileName, evidence: receiptState.evidence, - source: nil, expectation: .init(), security: security, privateData: nil)) + let originals = requests + for state in receiptStates.values.sorted(by: { $0.path < $1.path }) { + let shared = state.path.hasPrefix(NativeTargetRoute.metadataRoot + "/") + let affected = originals.filter { + $0.path.hasPrefix(NativeTargetRoute.globalRoot + "/") == shared + && ($0.security.isPrivate || state.records.targets[$0.path] != nil) + } + guard !affected.isEmpty else { continue } + var security = TransactionSecurity() + security.preimage = state.access == nil ? .ordinary : .privateMaterialization + let deletesShared = shared && affected.allSatisfy { !$0.installs } + security.replacement = deletesShared ? .ordinary : .privateMaterialization + security.preimageAccess = state.access + security.ancestry = try DirectoryAccessEvidence.capture( + at: state.url.deletingLastPathComponent()) + if !deletesShared { receiptIndices[requests.count] = state } + requests.append( + Request( + path: state.path, evidence: state.evidence, source: nil, + expectation: .init(), security: security, privateData: nil)) + } } /// Prepared inputs that this journal does not replace must still match at commit entry, @@ -156,7 +172,14 @@ package final class FileTransaction { guard path != "state/" + MaterializationReceipts.fileName else { throw CoreError.unsafePath("materialization receipts are transaction-owned") } - if receiptState == nil { receiptState = try store.materializationReceipts() } + if path.hasPrefix(NativeTargetRoute.globalRoot + "/") { + guard TransactionLockContext.current(store)?.writable == true else { + throw CoreError.invalidState("shared writes require the held writer footprint") + } + } + let receipt = try store.materializationReceipts(for: path) + if receiptStates[receipt.path] == nil { receiptStates[receipt.path] = receipt } + let receiptState = receiptStates[receipt.path]! guard !requests.contains(where: { $0.path == path }) else { throw CoreError.invalidState("duplicate transaction destination") } @@ -165,10 +188,10 @@ package final class FileTransaction { throw CoreError.invalidState("precondition belongs to another target") } var security = TransactionSecurity() - if let record = receiptState?.records.targets[path] { + if let record = receiptState.records.targets[path] { let paths = TransactionPaths(store: store) let key = try paths.components(path).root - guard try paths.root(key).identity == record.rootIdentity else { + guard try store.materializationRootIdentity(key) == record.rootIdentity else { throw CoreError.invalidState("materialization receipt root changed") } // A known absence has no sensitive preimage; its receipt is reconciled in this journal. @@ -206,13 +229,28 @@ package final class FileTransaction { package func commit() throws { guard !requests.isEmpty else { return } + let shared = requests.filter { $0.path.hasPrefix(NativeTargetRoute.globalRoot + "/") } + if !shared.isEmpty { + guard let context = TransactionLockContext.current(store), context.writable else { + throw CoreError.invalidState("shared commit requires its held writer footprint") + } + try context.requireWriterScope() + let resource = try context.resource() + for request in shared { + let parent = try DirectoryHandle( + at: request.evidence.physicalURL.deletingLastPathComponent()) + guard try parent.objectIdentity == resource.identity.parent else { + throw CoreError.invalidState("shared commit physical registration changed") + } + } + } guard let directory = try store.openDirectoryIfPresent(), try !TransactionJournal.isPresent(in: directory) else { throw CoreError.invalidState("transaction recovery is required") } try queueReceipt() - try receiptState?.evidence.validate() + for state in receiptStates.values { try state.evidence.validate() } try validateUnchanged() for request in requests { try request.evidence.validate() } try validateOverlap() @@ -221,6 +259,7 @@ package final class FileTransaction { do { try session.persist(.created) try session.emit(.phase(.preparing)) + try session.createReservations(owner: store.directory.path) try session.createContainers() try session.checkCapabilities() // Capability probing may only touch missing ancestry, journal and private containers. @@ -230,10 +269,12 @@ package final class FileTransaction { try SourceCache(store: store, checkpoint: checkpoint).beginWatchReferenceUpdate() } for (index, request) in requests.enumerated() { - if index == receiptIndex { + if let state = receiptIndices[index] { try session.stage(index, source: request.source, expectation: request.expectation) { try StateStore.encode( - session.materializationReceipts(previous: self.receiptState!.records)) + session.materializationReceipts( + previous: state.records, + shared: state.path.hasPrefix(NativeTargetRoute.metadataRoot + "/"))) } } else { try session.stage( @@ -324,12 +365,16 @@ package final class FileTransaction { preimage: request.evidence.snapshot, parentIdentity: identity, container: container, security: security)) } + let shared = + roots[NativeTargetRoute.globalRoot] != nil || roots[NativeTargetRoute.metadataRoot] != nil + let resources = shared ? [try TransactionLockContext.current(store).requiredResource()] : [] let journal = TransactionJournal( id: id, scope: try directory.identity, - roots: try roots.mapValues { try $0.identity }, entries: entries, containers: containers) + roots: try roots.mapValues { try $0.identity }, entries: entries, containers: containers, + footprint: resources.map(\.identity)) let session = TransactionSession( journal: journal, directory: directory, parents: parents, - checkpoint: checkpoint) + checkpoint: checkpoint, resources: resources) try session.validateRecords(store: store) return session } diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift new file mode 100644 index 0000000..714d8db --- /dev/null +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -0,0 +1,492 @@ +import CPlatform +import Foundation + +/// Closed physical routes; regional ownership and rendering belong to the native adapter. +package enum NativeTargetRoute: String, Codable, Sendable { + case claudeMCPProject = "claude.mcp.project" + case claudeMCPLocal = "claude.mcp.local" + case claudeMCPUser = "claude.mcp.user" + + var shared: Bool { self != .claudeMCPProject } + static let projectRoot = "native-claude-project" + static let globalRoot = "native-claude-global" + static let metadataRoot = "native-claude-metadata" + + static func globalLogicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + if let override = environment.environment["CLAUDE_CONFIG_DIR"], !override.isEmpty { + guard override.hasPrefix("/"), !override.contains("\0") else { + throw CoreError.unsafePath("registered Claude config root must be an absolute directory") + } + return URL(fileURLWithPath: override).standardizedFileURL + } + guard environment.homeDirectory.isFileURL, !environment.homeDirectory.path.contains("\0") else { + throw CoreError.unsafePath("registered Claude HOME must be a filesystem directory") + } + return environment.homeDirectory.standardizedFileURL + } + + static func globalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + try globalLogicalDirectory(environment).resolvingSymlinksInPath() + } +} + +/// Pathname authorization is checked separately. Neither route nor caller participates here. +struct SharedResourceIdentity: Codable, Equatable, Comparable { + let parent: FileObjectIdentity + let basename: String + + var orderingKey: String { + "\(parent.device):\(parent.inode):\(parent.kind):\(basename.utf8.count):\(basename)" + } + var directoryName: String { FileHash.sha256Hex(data: Data(orderingKey.utf8)) } + static func < (lhs: Self, rhs: Self) -> Bool { lhs.orderingKey < rhs.orderingKey } + + func validate() throws { + guard parent.isDirectory, basename == ".claude.json" else { + throw CoreError.invalidState("unregistered shared transaction resource") + } + } +} + +struct SharedReservation: Codable, Equatable { + let version: Int + let resource: SharedResourceIdentity + let scope: String + let owner: String + let journal: UUID +} + +/// An opened, verified physical coordination domain. Its lock inode is never removed. +final class SharedResource { + static let metadataName = ".agents-native" + let identity: SharedResourceIdentity + let parent: DirectoryHandle + let metadata: DirectoryHandle? + let ancestry: DirectoryAccessEvidence + let metadataAccess: FileAccessEvidence? + let metadataAncestry: DirectoryAccessEvidence? + let authorizedRoot: URL + private var lockDescriptor: Int32? + private var lockAccess: FileAccessEvidence? + + init(store: StateStore, create: Bool) throws { + authorizedRoot = try NativeTargetRoute.globalLogicalDirectory(store.environment) + let url = authorizedRoot.resolvingSymlinksInPath() + parent = try DirectoryHandle(at: url, create: create) + ancestry = try DirectoryAccessEvidence.capture(at: url) + identity = SharedResourceIdentity(parent: try parent.objectIdentity, basename: ".claude.json") + func child(_ parent: DirectoryHandle, _ name: String) throws -> DirectoryHandle? { + if try parent.info(name) == nil { + guard create else { return nil } + return try parent.createPrivateDirectory(name) + } + let result = try parent.child(name) + _ = try FileAccessEvidence.requirePrivate(descriptor: result.descriptor) + return result + } + if let base = try child(parent, Self.metadataName) { + metadata = try child(base, identity.directoryName) + } else { + metadata = nil + } + metadataAccess = try metadata?.accessEvidence() + metadataAncestry = try metadata.map { try DirectoryAccessEvidence.capture(at: $0.url) } + } + + func bindLock(_ descriptor: Int32) throws { + guard descriptor >= 0 else { return } + lockDescriptor = descriptor + lockAccess = try FileAccessEvidence.requirePrivate(descriptor: descriptor) + try validate() + } + + func validate() throws { + if let descriptor = lockDescriptor, let access = lockAccess { + guard let metadata, + try metadata.info("lock").map(FileObjectIdentity.init) == access.identity + else { + throw CoreError.invalidState("held shared coordination lock identity changed") + } + try access.validate(descriptor: descriptor) + } + try ancestry.validate(at: parent.url) + guard + try DirectoryHandle(at: authorizedRoot.resolvingSymlinksInPath()).objectIdentity + == identity.parent, + try DirectoryHandle(at: parent.url).objectIdentity == identity.parent + else { + throw CoreError.invalidState("shared target parent identity changed") + } + if let metadata { + try metadataAncestry?.validate(at: metadata.url) + let current = try DirectoryHandle(at: metadata.url) + guard try current.objectIdentity == metadata.objectIdentity else { + throw CoreError.invalidState("shared coordination directory changed") + } + _ = try FileAccessEvidence.requirePrivate(descriptor: current.descriptor) + try metadataAccess?.validate(descriptor: current.descriptor) + } + } + + func reservation() throws -> SharedReservation? { + try validate() + guard let metadata, try metadata.info("reservation") != nil else { return nil } + let access = try metadata.requirePrivateAccess("reservation") + let value: SharedReservation + do { + value = try StateStore.decode( + metadata.read("reservation", maximumBytes: 16_384), as: SharedReservation.self) + } catch { throw CoreError.invalidState("invalid shared reservation; owner action required") } + guard value.version == 1, value.resource == identity, !value.scope.isEmpty, + !value.owner.isEmpty + else { throw CoreError.invalidState("invalid shared reservation ownership") } + _ = try metadata.requirePrivateAccess("reservation", matching: access) + return value + } + + static func temporaryName(_ journal: UUID) -> String { "reservation-\(journal.uuidString).new" } + + func inspect(journal: TransactionJournal?, scope: String) throws { + try validate() + guard let metadata else { return } + let own = journal.map { Self.temporaryName($0.id) } + for name in try metadata.names() where name.hasPrefix("reservation-") { + guard name == own, journal?.footprint.contains(identity) == true else { + throw CoreError.invalidState( + "pending shared reservation construction; owner action required") + } + // A durable intent owns the exact slot even when its bytes are incomplete. + _ = try metadata.requirePrivateAccess(name) + } + if let reservation = try reservation() { + guard reservation.scope == scope, reservation.journal == journal?.id, + journal?.footprint.contains(identity) == true + else { + throw CoreError.recoveryPending( + "Shared target requires recovery by \(reservation.owner), journal \(reservation.journal.uuidString)" + ) + } + } else if journal?.reservationsReady == true, journal?.finalized == false, + journal?.footprint.contains(identity) == true + { + throw CoreError.invalidState("ready shared transaction is missing its reservation") + } + } + + func reserve(_ journal: TransactionJournal, owner: String, checkpoint: (String) throws -> Void) + throws + { + guard let metadata, journal.footprint.contains(identity), !journal.reservationsReady else { + throw CoreError.invalidState("missing durable shared reservation intent") + } + try inspect(journal: journal, scope: journal.scope) + guard try reservation() == nil else { return } + let name = Self.temporaryName(journal.id) + guard try metadata.info(name) == nil else { + throw CoreError.invalidState("unfinished shared reservation needs recovery") + } + let file = try metadata.createPrivateFile(name) + try checkpoint("reservation.created") + let record = SharedReservation( + version: 1, resource: identity, scope: journal.scope, owner: owner, journal: journal.id) + let bytes = try StateStore.encode(record) + let middle = bytes.count / 2 + try file.write(bytes.prefix(middle)) + try checkpoint("reservation.halfWritten") + try file.write(bytes.suffix(from: middle)) + try checkpoint("reservation.written") + try metadata.move(name, to: metadata, named: "reservation", mode: .exclusive) { + try checkpoint("reservation.published") + } + try checkpoint("reservation.synced") + } + + func validateFinalized(_ journal: TransactionJournal) throws { + try validate() + guard let metadata else { throw CoreError.invalidState("shared metadata is missing") } + let name = Self.temporaryName(journal.id) + if try metadata.info(name) != nil { _ = try metadata.requirePrivateAccess(name) } + if let record = try reservation(), record.journal == journal.id, + record.scope != journal.scope + { + throw CoreError.invalidState("finalized reservation owner changed") + } + } + + /// Finalized journals may encounter a newer owner's final reservation. Never remove it. + func release(_ journal: TransactionJournal, checkpoint: (String) throws -> Void) throws { + try validate() + guard let metadata else { throw CoreError.invalidState("shared metadata is missing") } + let name = Self.temporaryName(journal.id) + if try metadata.info(name) != nil { + let access = try metadata.requirePrivateAccess(name) + try metadata.remove(name, identity: access.identity) + } + if let record = try reservation(), record.journal == journal.id { + guard record.scope == journal.scope, record.resource == identity else { + throw CoreError.invalidState("shared reservation owner changed") + } + let access = try metadata.requirePrivateAccess("reservation") + try metadata.remove("reservation", identity: access.identity) + try checkpoint("reservation.removed") + } else if !journal.finalized, journal.reservationsReady { + throw CoreError.invalidState("ready shared transaction lost its reservation") + } + try metadata.sync() + } +} + +/// Synchronous, thread-confined admission. There is no lock acquisition inside a transaction. +final class TransactionLockContext { + private static let threadKey = "agents.core.transaction-lock-context" + let scopeURL: URL + let resources: [SharedResource] + let writable: Bool + let requestedShared: Bool + private var scopeDirectory: DirectoryHandle? + private var scopeDescriptor: Int32? + private var scopeLockIdentity: FileObjectIdentity? + + init(store: StateStore, resources: [SharedResource], writable: Bool, requestedShared: Bool) { + scopeURL = store.directory.standardizedFileURL + self.resources = resources + self.writable = writable + self.requestedShared = requestedShared + } + + static var isHeld: Bool { Thread.current.threadDictionary[threadKey] != nil } + + static func current(_ store: StateStore) -> TransactionLockContext? { + let context = Thread.current.threadDictionary[threadKey] as? TransactionLockContext + return context?.scopeURL.path == store.directory.standardizedFileURL.path ? context : nil + } + + func run(_ body: () throws -> T) throws -> T { + guard Thread.current.threadDictionary[Self.threadKey] == nil else { + throw CoreError.invalidState("nested scope operations cannot acquire transaction locks") + } + Thread.current.threadDictionary[Self.threadKey] = self + defer { Thread.current.threadDictionary.removeObject(forKey: Self.threadKey) } + return try body() + } + + static func validateHeldScope(_ identity: String) throws { + guard let context = Thread.current.threadDictionary[threadKey] as? TransactionLockContext else { + return + } + try context.validateScope() + if let directory = context.scopeDirectory, try directory.identity != identity { + throw CoreError.invalidState("transaction belongs to another held scope") + } + } + + func bindScope(_ directory: DirectoryHandle, descriptor: Int32) throws { + var info = stat() + guard fstat(descriptor, &info) == 0, + try directory.info(".agents.lock").map(FileObjectIdentity.init) == FileObjectIdentity(info) + else { throw CoreError.invalidState("scope lock changed during admission") } + scopeDirectory = directory + scopeDescriptor = descriptor + scopeLockIdentity = FileObjectIdentity(info) + try validateScope() + } + + func validateScope() throws { + guard let directory = scopeDirectory else { return } + var info = stat() + guard let descriptor = scopeDescriptor, let identity = scopeLockIdentity, + fstat(descriptor, &info) == 0, FileObjectIdentity(info) == identity, + try DirectoryHandle(at: directory.url).identity == directory.identity, + try directory.info(".agents.lock").map(FileObjectIdentity.init) == identity + else { throw CoreError.invalidState("held transaction scope or lock identity changed") } + } + + func requireWriterScope() throws { + guard writable, scopeDirectory != nil else { + throw CoreError.invalidState("shared commit requires a held scope writer descriptor") + } + try validateScope() + } + + func resource(_ identity: SharedResourceIdentity? = nil) throws -> SharedResource { + try validateScope() + guard let resource = resources.first(where: { identity == nil || $0.identity == identity }) + else { + throw CoreError.invalidState("shared target is outside the held request footprint") + } + try resource.validate() + return resource + } + + func validate(_ journal: TransactionJournal, scope: DirectoryHandle) throws { + try journal.validateCoordination() + try validateScope() + guard try scope.identity == journal.scope else { + throw CoreError.invalidState("transaction scope identity changed") + } + for identity in journal.footprint { + let resource = try resource(identity) + if !journal.finalized { try resource.inspect(journal: journal, scope: journal.scope) } + } + } +} + +extension StateStore { + package func nativeTarget(for route: NativeTargetRoute) throws -> MaterializationTarget { + guard environment.projectDirectory.isFileURL, !environment.projectDirectory.path.contains("\0") + else { + throw CoreError.unsafePath("registered project root must be a filesystem directory") + } + guard route.shared || scope == .project else { + throw CoreError.unsafePath("project native targets require their project scope") + } + let root = route.shared ? NativeTargetRoute.globalRoot : NativeTargetRoute.projectRoot + let parent: URL + if route.shared, let resource = TransactionLockContext.current(self)?.resources.first { + try resource.validate() + parent = resource.parent.url + } else { + parent = + route.shared + ? try NativeTargetRoute.globalDirectory(environment) + : environment.projectDirectory.resolvingSymlinksInPath() + } + let name = route.shared ? ".claude.json" : ".mcp.json" + return MaterializationTarget( + url: parent.appendingPathComponent(name), path: root + "/" + name, scope: directory) + } + + /// Acquire the union before the scope lock. Re-admission never replays a delivered callback. + func withCoordination( + routes: Set, writable: Bool, + checkpoint: (String) throws -> Void = { _ in }, _ body: () throws -> T + ) throws -> T { + if TransactionLockContext.isHeld { + throw CoreError.invalidState("nested scope lock acquisition") + } + while true { + let before = try pendingCoordinationJournal(diagnosing: !writable) + let needsShared = routes.contains(where: \.shared) || before?.footprint.isEmpty == false + var resources: [SharedResource] = [] + if needsShared { + let pendingShared = before?.footprint.isEmpty == false + let resource: SharedResource + do { resource = try SharedResource(store: self, create: writable && !pendingShared) } catch + { + if pendingShared { + throw CoreError.invalidState( + "shared recovery requires the original registered runtime context and verifiable coordination metadata" + ) + } + throw error + } + if pendingShared { + guard let metadata = resource.metadata, try metadata.info("lock") != nil else { + throw CoreError.invalidState("shared recovery coordination metadata is missing") + } + } + for identity in before?.footprint ?? [] { + try identity.validate() + guard identity == resource.identity else { + throw CoreError.invalidState("shared recovery requires the original runtime context") + } + } + resources = [resource] + } + let context = TransactionLockContext( + store: self, resources: resources.sorted { $0.identity < $1.identity }, writable: writable, + requestedShared: routes.contains(where: \.shared)) + func locked(_ index: Int) throws -> T? { + if index < context.resources.count { + let resource = context.resources[index] + guard let metadata = resource.metadata else { + // No metadata means no prior registered writer. Recheck after the unlocked read. + let result = Result { try locked(index + 1) } + let after = try SharedResource(store: self, create: false) + guard after.metadata == nil else { return nil } + return try result.get() + } + let url = metadata.url.appendingPathComponent("lock") + if writable { + if try metadata.info("lock") == nil { + _ = try metadata.createPrivateFile("lock") + } + _ = try metadata.requirePrivateAccess("lock") + } + return try FileLock.withCoordinationDescriptor( + at: url, writable: writable, + checkpoint: { try checkpoint("shared.\(index).lock." + $0) }, + { descriptor in + try resource.bindLock(descriptor) + try resource.validate() + return try locked(index + 1) + }) + } + return try context.run { try body() } + } + // The scope-lock body checks that the preflight footprint still covers the journal. + do { + if let result = try locked(0) { return result } + } catch CoordinationReadmission.required { continue } + } + } + + func pendingCoordinationJournal(diagnosing: Bool = false) throws -> TransactionJournal? { + guard let directory = try openDirectoryIfPresent() else { return nil } + let primary = try directory.info(TransactionJournal.fileName) != nil + let name = primary ? TransactionJournal.fileName : TransactionJournal.incompleteFileName + guard try directory.info(name) != nil else { return nil } + do { + guard let info = try directory.info(name), let limit = Int(exactly: info.st_size), limit >= 0 + else { + throw CoreError.invalidState("cannot bound pending journal generation") + } + let bytes = try directory.read(name, matching: info, maximumBytes: limit) + if !primary, (try? JSONSerialization.jsonObject(with: bytes)) == nil { return nil } + let journal = try FileTransaction.readJournal(bytes) + try journal.validateCoordination() + return journal + } catch { + // A corrupt journal admits no data callback. The read boundary still takes the + // scope lock and routes to its pending-recovery diagnostic without writes. + if diagnosing { return nil } + throw error + } + } + + func verifyCoordinationAdmission() throws { + guard let context = TransactionLockContext.current(self) else { + throw CoreError.invalidState("missing held scope coordination context") + } + let journal = try pendingCoordinationJournal(diagnosing: !context.writable) + let held = context.resources.map(\.identity) + if let journal, !journal.footprint.allSatisfy(held.contains) { + throw CoordinationReadmission.required + } + if !context.requestedShared, journal?.footprint.isEmpty != false, !held.isEmpty { + throw CoordinationReadmission.required + } + let directory = try openDirectoryIfPresent() + if let journal, context.writable { + guard let directory else { throw CoreError.invalidState("missing transaction scope") } + try context.validate(journal, scope: directory) + } + for resource in context.resources { + if journal?.finalized != true && (context.writable || journal == nil) { + try resource.inspect(journal: journal, scope: directory?.identity ?? "") + } + } + } + +} + +enum CoordinationReadmission: Error { case required } + +extension Optional where Wrapped == TransactionLockContext { + func requiredResource(_ identity: SharedResourceIdentity? = nil) throws -> SharedResource { + guard let context = self else { + throw CoreError.invalidState("shared target requires a held request footprint") + } + return try context.resource(identity) + } +} diff --git a/Sources/AgentsCore/PrivateMaterialization.swift b/Sources/AgentsCore/PrivateMaterialization.swift index 4c09e2e..b8fb1a5 100644 --- a/Sources/AgentsCore/PrivateMaterialization.swift +++ b/Sources/AgentsCore/PrivateMaterialization.swift @@ -91,10 +91,11 @@ extension StateStore { package func materializationReceipt(for target: MaterializationTarget) throws -> MaterializationReceipt? { - guard target.scope == directory, + guard target.scope.path == directory.path, try TransactionPaths(store: self).path(for: target.url) == target.path else { throw CoreError.invalidState("materialization target belongs to another scope") } - guard let record = try materializationReceipts().records.targets[target.path] else { + guard let record = try materializationReceipts(for: target.path).records.targets[target.path] + else { return nil } _ = try preparePrivateMaterialization(target, expecting: record.generation) @@ -106,10 +107,10 @@ extension StateStore { _ target: MaterializationTarget, changingAccess: Bool = false, requiringReceiptForExistingTarget: Bool = false, expecting generation: UUID? = nil ) throws -> PreparedPrivateMaterialization { - guard target.scope == directory, + guard target.scope.path == directory.path, try TransactionPaths(store: self).path(for: target.url) == target.path else { throw CoreError.invalidState("materialization target belongs to another scope") } - let receipt = try materializationReceipts() + let receipt = try materializationReceipts(for: target.path) let record = receipt.records.targets[target.path] if let generation, record?.generation != generation { throw CoreError.invalidState("materialization receipt generation changed or is missing") @@ -142,7 +143,7 @@ extension StateStore { if let record = receipt.records.targets[target.path] { let paths = TransactionPaths(store: self) let key = try paths.components(target.path).root - guard try paths.root(key).identity == record.rootIdentity else { + guard try materializationRootIdentity(key) == record.rootIdentity else { throw CoreError.invalidState("materialization receipt root changed") } if evidence.snapshot != nil { @@ -180,7 +181,13 @@ struct MaterializationReceipts: Codable { for (path, record) in targets { let paths = TransactionPaths(store: store) let parts = try paths.components(path) - guard parts.root.hasPrefix("instructions-"), parts.root != "instructions-authoring", + guard + (parts.root.hasPrefix("instructions-") && parts.root != "instructions-authoring") + || [NativeTargetRoute.projectRoot, NativeTargetRoute.globalRoot].contains(parts.root) + else { + throw CoreError.invalidState("invalid materialization receipt target") + } + guard record.access.identity.kind == S_IFREG, !record.rootIdentity.isEmpty else { throw CoreError.invalidState("invalid materialization receipt target") } @@ -194,23 +201,58 @@ extension StateStore { directory.appendingPathComponent(MaterializationReceipts.fileName) } - func materializationReceipts() throws -> ( - records: MaterializationReceipts, evidence: TargetPrecondition, access: FileAccessEvidence? - ) { - let evidence = try TargetPrecondition(materializationReceiptURL) - guard evidence.snapshot != nil else { return (.init(), evidence, nil) } - guard let directory = try openDirectoryIfPresent() else { - throw CoreError.invalidState("materialization receipt directory is missing") + func materializationRootIdentity(_ root: String) throws -> String { + if root == NativeTargetRoute.globalRoot { + return try TransactionLockContext.current(self).requiredResource().identity.orderingKey + } + return try TransactionPaths(store: self).root(root).identity + } + + func materializationReceipts(for path: String = "") throws -> MaterializationReceiptState { + let shared = path.hasPrefix(NativeTargetRoute.globalRoot + "/") + let resource = shared ? try TransactionLockContext.current(self).requiredResource() : nil + let url: URL + let receiptPath: String + if let resource { + let metadataURL = resource.parent.url.appendingPathComponent(SharedResource.metadataName) + .appendingPathComponent(resource.identity.directoryName) + url = (resource.metadata?.url ?? metadataURL).appendingPathComponent("receipt") + receiptPath = NativeTargetRoute.metadataRoot + "/receipt" + } else { + url = materializationReceiptURL + receiptPath = "state/" + MaterializationReceipts.fileName + } + let evidence = try TargetPrecondition(url) + guard evidence.snapshot != nil else { + return .init(path: receiptPath, url: url, records: .init(), evidence: evidence, access: nil) } + let directory = try DirectoryHandle(at: url.deletingLastPathComponent()) let evidenceWithAccess = try evidence.capturingAccess() - let access = try directory.requirePrivateAccess(MaterializationReceipts.fileName) + let access = try directory.requirePrivateAccess(url.lastPathComponent) do { let records = try Self.decode( - directory.read(MaterializationReceipts.fileName), as: MaterializationReceipts.self) + directory.read(url.lastPathComponent), as: MaterializationReceipts.self) try records.validate(store: self) + if shared, Set(records.targets.keys) != [NativeTargetRoute.globalRoot + "/.claude.json"] { + throw CoreError.invalidState("shared receipt must identify its physical file") + } + for (key, record) in records.targets { + guard shared == key.hasPrefix(NativeTargetRoute.globalRoot + "/"), + !shared || record.rootIdentity == resource?.identity.orderingKey + else { throw CoreError.invalidState("receipt belongs to another physical resource") } + } try evidence.validate() - _ = try directory.requirePrivateAccess(MaterializationReceipts.fileName, matching: access) - return (records, evidenceWithAccess, access) + _ = try directory.requirePrivateAccess(url.lastPathComponent, matching: access) + return .init( + path: receiptPath, url: url, records: records, evidence: evidenceWithAccess, access: access) } catch { throw CoreError.invalidState("invalid private materialization receipt") } } } + +struct MaterializationReceiptState { + let path: String + let url: URL + let records: MaterializationReceipts + let evidence: TargetPrecondition + let access: FileAccessEvidence? +} diff --git a/Sources/AgentsCore/StateInspection.swift b/Sources/AgentsCore/StateInspection.swift index 3d07a9f..ff22e70 100644 --- a/Sources/AgentsCore/StateInspection.swift +++ b/Sources/AgentsCore/StateInspection.swift @@ -7,6 +7,16 @@ extension StateStore { /// by default it throws `CoreError.recoveryPending`. /// The body may be retried when a first writer creates the scope lock. package func withReadLock( + onPendingRecovery: (() throws -> T)? = nil, + footprint: Set = [], + _ body: () throws -> T + ) throws -> T { + try withCoordination(routes: footprint, writable: false) { + try withScopeReadLock(onPendingRecovery: onPendingRecovery, body) + } + } + + private func withScopeReadLock( onPendingRecovery: (() throws -> T)? = nil, _ body: () throws -> T ) throws -> T { @@ -28,6 +38,10 @@ extension StateStore { } } defer { if descriptor >= 0 { platform_flock(descriptor, LOCK_UN) } } + if descriptor >= 0, let directory { + try TransactionLockContext.current(self)?.bindScope(directory, descriptor: descriptor) + } + try verifyCoordinationAdmission() let pending = try hasPendingRecovery(in: directory) let result = Result { guard pending else { return try body() } diff --git a/Sources/AgentsCore/StateStore.swift b/Sources/AgentsCore/StateStore.swift index fa3d18d..ca27dfd 100644 --- a/Sources/AgentsCore/StateStore.swift +++ b/Sources/AgentsCore/StateStore.swift @@ -82,11 +82,25 @@ public struct StateStore: Sendable { } package func withLock( + createIfMissing: Bool = true, checkpoint: @escaping (String) throws -> Void = { _ in }, + outcome: TransactionOutcome? = nil, footprint: Set = [], + _ body: () throws -> T + ) throws -> T { + try withCoordination(routes: footprint, writable: true, checkpoint: checkpoint) { + try withScopeLock( + createIfMissing: createIfMissing, checkpoint: checkpoint, outcome: outcome, body) + } + } + + private func withScopeLock( createIfMissing: Bool = true, checkpoint: @escaping (String) throws -> Void = { _ in }, outcome: TransactionOutcome? = nil, _ body: () throws -> T ) throws -> T { if try openDirectoryIfPresent() == nil, !createIfMissing { + guard TransactionLockContext.current(self)?.resources.isEmpty != false else { + throw CoreError.invalidState("shared mutation requires a scope journal directory") + } return try body() } // Without a scope lock, journal or ref-cleanup marker, invalid or orphaned state stops the @@ -101,7 +115,15 @@ public struct StateStore: Sendable { let base = scope == .project ? environment.projectDirectory : environment.homeDirectory let physicalDirectory = base.resolvingSymlinksInPath().appendingPathComponent( directory.lastPathComponent) - return try FileLock.withLock(at: physicalDirectory.appendingPathComponent(".agents.lock")) { + return try FileLock.withDescriptor(at: physicalDirectory.appendingPathComponent(".agents.lock")) + { descriptor in + guard let context = TransactionLockContext.current(self), + let scopeDirectory = try openDirectoryIfPresent() + else { + throw CoreError.invalidState("missing scope lock admission") + } + try context.bindScope(scopeDirectory, descriptor: descriptor) + try verifyCoordinationAdmission() let recovered = try FileTransaction.recover( store: self, outcome: outcome, checkpoint: checkpoint) _ = try readWatch() diff --git a/Sources/AgentsCore/TransactionCheckpoint.swift b/Sources/AgentsCore/TransactionCheckpoint.swift index 72b23e3..1e51234 100644 --- a/Sources/AgentsCore/TransactionCheckpoint.swift +++ b/Sources/AgentsCore/TransactionCheckpoint.swift @@ -6,7 +6,7 @@ enum TransactionCheckpoint { enum Change { case created, containers case entry(Int, TransactionJournal.Progress) - case terminal, disposing + case terminal, disposing, reservationsReady, finalized case conflict(Int, TransactionJournal.Progress) var name: String { switch self { @@ -15,6 +15,8 @@ enum TransactionCheckpoint { case .entry(let index, let progress): "entry.\(index).\(progress.rawValue)" case .terminal: "terminal" case .disposing: "disposing" + case .reservationsReady: "reservationsReady" + case .finalized: "finalized" case .conflict(let index, let progress): "entry.\(index).\(progress.rawValue).conflict" } } diff --git a/Sources/AgentsCore/TransactionDisposal.swift b/Sources/AgentsCore/TransactionDisposal.swift index e5b5ccc..82808f0 100644 --- a/Sources/AgentsCore/TransactionDisposal.swift +++ b/Sources/AgentsCore/TransactionDisposal.swift @@ -88,6 +88,10 @@ extension TransactionSession { } for index in journal.containers.indices { try disposeContainer(index) } try requireScope() + journal.finalized = true + try persist(.finalized) + try checkpoint("journal.finalized") + try releaseReservations() try directory.removeFiles( [TransactionJournal.incompleteFileName, TransactionJournal.fileName] ) { name in diff --git a/Sources/AgentsCore/TransactionJournal.swift b/Sources/AgentsCore/TransactionJournal.swift index 1b98a94..a71d633 100644 --- a/Sources/AgentsCore/TransactionJournal.swift +++ b/Sources/AgentsCore/TransactionJournal.swift @@ -2,7 +2,7 @@ import Foundation /// The version is independent of declaration, resolved and watch formats. struct TransactionJournal: Codable { - static let currentVersion = 2 + static let currentVersion = 3 static let fileName = "transaction.json" /// The next journal generation before it replaces `fileName`. static let incompleteFileName = "transaction.new" @@ -15,6 +15,38 @@ struct TransactionJournal: Codable { var containers: [Container] /// Only this durable intent permits absent or partially removed disposal objects. var disposing = false + /// Durable intents exist before any reservation slot is created. + var footprint: [SharedResourceIdentity] = [] + var reservationsReady = false + /// Disposal is synced; terminal phase retains the committed/rolledBack result. + var finalized = false + + func validateCoordination() throws { + // The closed routes currently share exactly one possible physical file per runtime. + guard footprint.count <= 1 else { + throw CoreError.invalidState("unregistered shared transaction footprint") + } + for identity in footprint { try identity.validate() } + guard !finalized || (disposing && (phase == .committed || phase == .rolledBack)), + footprint.isEmpty || reservationsReady || phase == .preparing || phase == .rolledBack + else { throw CoreError.invalidState("invalid transaction coordination evidence") } + if finalized { + let terminalProgress: Set = + phase == .committed + ? [.applied] : [.queued, .ready, .restored, .cancelled] + guard entries.allSatisfy({ terminalProgress.contains($0.progress) }) else { + throw CoreError.invalidState("finalized transaction contradicts its terminal outcome") + } + } + if !finalized { + let sharedRoots = + roots.keys.contains(NativeTargetRoute.globalRoot) + || roots.keys.contains(NativeTargetRoute.metadataRoot) + guard sharedRoots == !footprint.isEmpty else { + throw CoreError.invalidState("journal roots contradict shared footprint") + } + } + } enum Phase: String, Codable { case preparing, applying, committed, rolledBack } enum Action: String, Codable { case install, delete } @@ -89,9 +121,17 @@ struct TransactionJournal: Codable { try directory.info(fileName) != nil || directory.info(incompleteFileName) != nil } - /// Without an identified container or sealed operation, the journal owns no object. + var isReservationOnly: Bool { + !footprint.isEmpty && !reservationsReady && !finalized && phase == .preparing + && containers.allSatisfy { $0.identity == nil } + && entries.allSatisfy { $0.progress == .queued } + } + + /// Only journals without reservation intents, identified containers or sealed operations + /// can be discarded without examining owned metadata. var isUnstarted: Bool { - phase == .preparing && containers.allSatisfy { $0.identity == nil } + footprint.isEmpty && !reservationsReady && !finalized && phase == .preparing + && containers.allSatisfy { $0.identity == nil } && entries.allSatisfy { $0.progress == .queued } } } diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index ebff758..7d5a055 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -29,6 +29,19 @@ struct TransactionPaths { } } } + let nativeRoutes: [NativeTargetRoute] = + store.scope == .project + ? [.claudeMCPProject, .claudeMCPLocal] : [.claudeMCPUser] + for route in nativeRoutes { + guard destination.lastPathComponent == (route.shared ? ".claude.json" : ".mcp.json") else { + continue + } + let target = try store.nativeTarget(for: route) + if target.url == destination.standardizedFileURL { + if route.shared { _ = try TransactionLockContext.current(store).requiredResource() } + return target.path + } + } for agent in AgentID.allCases { let logical = AgentRegistry.installSkillsDirectory( for: agent, scope: store.scope, environment: store.environment) @@ -64,6 +77,16 @@ struct TransactionPaths { store.scope == .project ? store.environment.projectDirectory : store.environment.homeDirectory url = base.resolvingSymlinksInPath().appendingPathComponent(store.directory.lastPathComponent) + } else if key == NativeTargetRoute.projectRoot, store.scope == .project { + url = store.environment.projectDirectory.resolvingSymlinksInPath() + } else if key == NativeTargetRoute.globalRoot { + url = try TransactionLockContext.current(store).requiredResource().parent.url + } else if key == NativeTargetRoute.metadataRoot { + guard let metadata = try TransactionLockContext.current(store).requiredResource().metadata + else { + throw CoreError.invalidState("shared metadata directory is missing") + } + url = metadata.url } else if key == "instructions-project" || key == "instructions-authoring", store.scope == .project { @@ -111,6 +134,18 @@ struct TransactionPaths { guard stateFile || cache else { throw CoreError.unsafePath("unmanaged state transaction path") } + } else if key == NativeTargetRoute.projectRoot { + guard store.scope == .project, descendants == [".mcp.json"] else { + throw CoreError.unsafePath("unregistered project native target") + } + } else if key == NativeTargetRoute.globalRoot { + guard descendants == [".claude.json"] else { + throw CoreError.unsafePath("unregistered shared native target") + } + } else if key == NativeTargetRoute.metadataRoot { + guard descendants == ["receipt"] else { + throw CoreError.unsafePath("unregistered shared transaction metadata") + } } else if key == "instructions-project", store.scope == .project { guard InstructionLocations.isProjectTarget(descendants.joined(separator: "/")) else { throw CoreError.unsafePath("unmanaged project instruction path") diff --git a/Sources/AgentsCore/TransactionPublication.swift b/Sources/AgentsCore/TransactionPublication.swift index 89cd47d..9828419 100644 --- a/Sources/AgentsCore/TransactionPublication.swift +++ b/Sources/AgentsCore/TransactionPublication.swift @@ -192,6 +192,9 @@ extension TransactionSession { } func publish(_ index: Int) throws { + guard journal.footprint.isEmpty || journal.reservationsReady else { + throw CoreError.invalidState("shared reservations are not ready") + } let entry = journal.entries[index] let parent = parents[index] let container = try self.container(entry.container) @@ -243,17 +246,25 @@ extension TransactionSession { } } - func materializationReceipts(previous: MaterializationReceipts) throws -> MaterializationReceipts + func materializationReceipts(previous: MaterializationReceipts, shared: Bool = false) throws + -> MaterializationReceipts { + var records = previous - for entry in journal.entries where entry.path != "state/" + MaterializationReceipts.fileName { + for entry in journal.entries + where entry.path != "state/" + MaterializationReceipts.fileName + && !entry.path.hasPrefix(NativeTargetRoute.metadataRoot + "/") + && entry.path.hasPrefix(NativeTargetRoute.globalRoot + "/") == shared + { if entry.security.replacement == .privateMaterialization { guard let snapshot = entry.staged, let access = entry.security.stagedAccess, let root = entry.path.split(separator: "/").first, let identity = journal.roots[String(root)] else { throw CoreError.invalidState("materialization is missing sealed receipt evidence") } records.targets[entry.path] = .init( - generation: journal.id, rootIdentity: identity, digest: snapshot.digest, access: access) + generation: journal.id, + rootIdentity: shared ? resources[0].identity.orderingKey : identity, + digest: snapshot.digest, access: access) } else { records.targets.removeValue(forKey: entry.path) } diff --git a/Sources/AgentsCore/TransactionRecovery.swift b/Sources/AgentsCore/TransactionRecovery.swift index 971c585..d41c6c7 100644 --- a/Sources/AgentsCore/TransactionRecovery.swift +++ b/Sources/AgentsCore/TransactionRecovery.swift @@ -19,6 +19,26 @@ extension FileTransaction { let incomplete = TransactionJournal.incompleteFileName guard try directory.info(primary) != nil else { guard try directory.info(incomplete) != nil else { return false } + let bytes = try directory.read(incomplete) + if (try? JSONSerialization.jsonObject(with: bytes)) != nil { + let journal = try readJournal(bytes) + if journal.finalized { + try validateRecoveryCoordination(journal, store: store, directory: directory) + try directory.syncFile(incomplete) + try cleanupFinalized(journal, store: store, directory: directory, checkpoint: checkpoint) + if outcome?.journalID == journal.id { + outcome?.disposition = journal.phase == .committed ? .committed : .unchanged + } + return true + } + if journal.isReservationOnly { + try validateRecoveryCoordination(journal, store: store, directory: directory) + try finalizeReservationConstruction( + journal, store: store, directory: directory, checkpoint: checkpoint) + if outcome?.journalID == journal.id { outcome?.disposition = .unchanged } + return true + } + } // An unstarted journal owns no object, so it is discarded without a journal barrier. try requireUnstartedIncompleteJournal(in: directory) try directory.remove(incomplete) @@ -28,6 +48,21 @@ extension FileTransaction { do { let journal = try readJournal(directory.read(primary)) recoveredID = journal.id + try validateRecoveryCoordination(journal, store: store, directory: directory) + if journal.isReservationOnly { + try finalizeReservationConstruction( + journal, store: store, directory: directory, checkpoint: checkpoint) + if outcome?.journalID == journal.id { outcome?.disposition = .unchanged } + return true + } + if journal.finalized { + try directory.syncFile(primary) + try cleanupFinalized(journal, store: store, directory: directory, checkpoint: checkpoint) + if outcome?.journalID == journal.id { + outcome?.disposition = journal.phase == .committed ? .committed : .unchanged + } + return true + } let session = try recoverySession( journal, store: store, directory: directory, checkpoint: checkpoint) // Validate the incomplete next generation before any recovery mutation. @@ -65,11 +100,32 @@ extension FileTransaction { } if try directory.info(TransactionJournal.fileName) == nil { if try directory.info(TransactionJournal.incompleteFileName) != nil { + let bytes = try directory.read(TransactionJournal.incompleteFileName) + if (try? JSONSerialization.jsonObject(with: bytes)) != nil { + let journal = try readJournal(bytes) + if journal.finalized { + try validateRecoveryCoordination(journal, store: store, directory: directory) + return .init( + requiresOwner: false, + message: "Transaction metadata cleanup is pending (\(journal.phase.rawValue)).") + } + if journal.isReservationOnly { + try validateRecoveryCoordination(journal, store: store, directory: directory) + return .init( + requiresOwner: false, message: TransactionRecoveryDiagnostic.pendingMessage) + } + } try requireUnstartedIncompleteJournal(in: directory) } return .init(requiresOwner: false, message: TransactionRecoveryDiagnostic.pendingMessage) } let journal = try readJournal(directory.read(TransactionJournal.fileName)) + try validateRecoveryCoordination(journal, store: store, directory: directory) + if journal.finalized { + return .init( + requiresOwner: false, + message: "Transaction metadata cleanup is pending (\(journal.phase.rawValue)).") + } retained += journal.entries.compactMap(journal.containerLocation(of:)) let session = try recoverySession( journal, store: store, directory: directory, checkpoint: { _ in }) @@ -104,7 +160,7 @@ extension FileTransaction { } } - private static func readJournal(_ bytes: Data) throws -> TransactionJournal { + static func readJournal(_ bytes: Data) throws -> TransactionJournal { try JSONKeys.validate(bytes) let value = try JSONSerialization.jsonObject(with: bytes) as? [String: Any] guard value?["version"] as? Int == TransactionJournal.currentVersion else { @@ -117,6 +173,58 @@ extension FileTransaction { } } + private static func finalizeReservationConstruction( + _ journal: TransactionJournal, store: StateStore, directory: DirectoryHandle, + checkpoint: @escaping (String) throws -> Void + ) throws { + // Reservation construction precedes every container and publication. No data object + // belongs to this journal yet; a later writer may already have advanced the target. + var terminal = journal + terminal.phase = .rolledBack + terminal.disposing = true + terminal.finalized = true + let session = TransactionSession( + journal: terminal, directory: directory, parents: [], checkpoint: checkpoint) + try session.persist(.finalized) + try checkpoint("journal.finalized") + try cleanupFinalized(terminal, store: store, directory: directory, checkpoint: checkpoint) + } + + private static func validateRecoveryCoordination( + _ journal: TransactionJournal, store: StateStore, directory: DirectoryHandle + ) throws { + try journal.validateCoordination() + guard try directory.identity == journal.scope else { + throw CoreError.invalidState("transaction scope identity changed") + } + if !journal.footprint.isEmpty { + guard let context = TransactionLockContext.current(store) else { + throw CoreError.invalidState("shared recovery requires its held coordination footprint") + } + try context.validate(journal, scope: directory) + if journal.finalized { + for identity in journal.footprint { + try context.resource(identity).validateFinalized(journal) + } + } + } + } + + private static func cleanupFinalized( + _ journal: TransactionJournal, store: StateStore, directory: DirectoryHandle, + checkpoint: (String) throws -> Void + ) throws { + for (index, identity) in journal.footprint.enumerated() { + let resource = try TransactionLockContext.current(store).requiredResource(identity) + try resource.release(journal) { try checkpoint("shared.\(index)." + $0) } + } + try directory.removeFiles([TransactionJournal.incompleteFileName, TransactionJournal.fileName]) + { name in + if name == TransactionJournal.fileName { try checkpoint("journal.unlinked") } + } + try checkpoint("journal.removed") + } + private static func recoverySession( _ journal: TransactionJournal, store: StateStore, directory: DirectoryHandle, checkpoint: @escaping (String) throws -> Void @@ -132,7 +240,10 @@ extension FileTransaction { } let parents = try journal.entries.map { try paths.parent(for: $0.path, roots: roots) } let session = TransactionSession( - journal: journal, directory: directory, parents: parents, checkpoint: checkpoint) + journal: journal, directory: directory, parents: parents, checkpoint: checkpoint, + resources: try journal.footprint.map { identity in + try TransactionLockContext.current(store).requiredResource(identity) + }) try session.validateRecords(store: store) return session } diff --git a/Sources/AgentsCore/TransactionSession.swift b/Sources/AgentsCore/TransactionSession.swift index 5c8104f..83e48af 100644 --- a/Sources/AgentsCore/TransactionSession.swift +++ b/Sources/AgentsCore/TransactionSession.swift @@ -6,18 +6,20 @@ final class TransactionSession { let directory: DirectoryHandle let parents: [DirectoryHandle] let checkpoint: (String) throws -> Void + let resources: [SharedResource] /// Devices whose atomic renames passed a probe during this session only; `st_dev` values /// can be reused by another filesystem after an unmount. var capableDevices: Set = [] init( journal: TransactionJournal, directory: DirectoryHandle, parents: [DirectoryHandle], - checkpoint: @escaping (String) throws -> Void + checkpoint: @escaping (String) throws -> Void, resources: [SharedResource] = [] ) { self.journal = journal self.directory = directory self.parents = parents self.checkpoint = checkpoint + self.resources = resources } func emit(_ point: TransactionCheckpoint) throws { try checkpoint(point.name) } @@ -73,12 +75,15 @@ final class TransactionSession { } func requireScope() throws { + try TransactionLockContext.validateHeldScope(journal.scope) + for resource in resources { try resource.validate() } guard try DirectoryHandle(at: directory.url).identity == journal.scope else { throw CoreError.invalidState("transaction scope identity changed") } } func requireParent(_ index: Int) throws { + if !resources.isEmpty { try requireScope() } try journal.entries[index].security.ancestry?.validate(at: parents[index].url) guard try DirectoryHandle(at: parents[index].url).identity == journal.entries[index].parentIdentity @@ -130,6 +135,13 @@ final class TransactionSession { func validateRecords(store: StateStore) throws { try requireScope() + try journal.validateCoordination() + if !journal.footprint.isEmpty { + guard let context = TransactionLockContext.current(store) else { + throw CoreError.invalidState("shared transaction is outside its held writer context") + } + try context.validate(journal, scope: directory) + } let paths = TransactionPaths(store: store) let keys = try Set(journal.entries.map { try paths.components($0.path).root }) guard keys == Set(journal.roots.keys), !journal.entries.isEmpty else { @@ -271,3 +283,21 @@ final class TransactionSession { + (expected.isEmpty ? "none" : expected.joined(separator: ", "))) } } + +extension TransactionSession { + func createReservations(owner: String) throws { + guard !journal.footprint.isEmpty else { return } + for (index, resource) in resources.enumerated() { + try resource.reserve(journal, owner: owner) { try checkpoint("shared.\(index)." + $0) } + } + journal.reservationsReady = true + try persist(.reservationsReady) + try checkpoint("shared.ready") + } + + func releaseReservations() throws { + for (index, resource) in resources.enumerated() { + try resource.release(journal) { try checkpoint("shared.\(index)." + $0) } + } + } +} diff --git a/Tests/AgentsCoreTests/PrivateMaterializationTests.swift b/Tests/AgentsCoreTests/PrivateMaterializationTests.swift index 524ce8e..291505a 100644 --- a/Tests/AgentsCoreTests/PrivateMaterializationTests.swift +++ b/Tests/AgentsCoreTests/PrivateMaterializationTests.swift @@ -141,38 +141,48 @@ struct PrivateMaterializationTests { #expect(provider.calls == (["provider", "renderer"].contains(kind) ? 1 : 0)) } - @Test func ordinaryReplacementAndDeletionRetainSensitivePreimageClassification() throws { + @Test func ordinaryRegionEditsKeepSensitiveSiblingsAndPrivateReceipt() throws { let fixture = try TransactionFixture() - try installPrivate("private-before", in: fixture) - let target = fixture.root.appendingPathComponent("AGENTS.md") - for deleting in [false, true] { - if deleting { try installPrivate("private-again", in: fixture) } - var inspected = false - try fixture.store.withLock { - let transaction = FileTransaction(store: fixture.store) { point in - if point == "entry.0.ready" { - let journal = try readMaterializationJournal(fixture) - #expect(journal.entries[0].security.preimage == .privateMaterialization) - #expect(journal.entries.count == 2) - inspected = true - } - } - if deleting { - try transaction.delete(target) - } else { - try transaction.replace(target, with: .data(Data("ordinary".utf8))) + try installPrivate("secret sibling; region before", in: fixture) + let target = try fixture.store.materializationTarget( + at: fixture.root.appendingPathComponent("AGENTS.md")) + let before = try fixture.store.preparePrivateMaterialization(target) + var inspected = false + try fixture.store.withLock { + let transaction = FileTransaction(store: fixture.store) { point in + if point == "stage.0.writeCreated" { + let journal = try readMaterializationJournal(fixture) + let container = target.url.deletingLastPathComponent().appendingPathComponent( + journal.containers[0].name) + let handle = try DirectoryHandle(at: container) + let access = try handle.requirePrivateAccess("entry.0.exchanged") + #expect(access.mode == 0o600) + #expect(try handle.read("entry.0.exchanged").isEmpty) + inspected = true } - try transaction.commit() - } - #expect(inspected) - #expect(try fixture.store.materializationReceipts().records.targets.isEmpty) - if !deleting { - #expect(try Data(contentsOf: target) == Data("ordinary".utf8)) - #expect(try DirectoryHandle(at: fixture.root).accessEvidence("AGENTS.md")?.mode == 0o600) - } else { - #expect(!FileManager.default.fileExists(atPath: target.path)) } + try transaction.replace(target.url, with: .data(Data("secret sibling; region after".utf8))) + try transaction.commit() + } + #expect(inspected) + #expect(try Data(contentsOf: target.url) == Data("secret sibling; region after".utf8)) + let after = try fixture.store.preparePrivateMaterialization( + target, requiringReceiptForExistingTarget: true) + #expect(after.receiptGeneration != before.receiptGeneration) + #expect(throws: CoreError.self) { try before.evidence.validate() } + } + + @Test func wholeFileDeletionRemovesSensitiveReceipt() throws { + let fixture = try TransactionFixture() + try installPrivate("private-before", in: fixture) + let target = fixture.root.appendingPathComponent("AGENTS.md") + try fixture.store.withLock { + let transaction = FileTransaction(store: fixture.store) + try transaction.delete(target) + try transaction.commit() } + #expect(try fixture.store.materializationReceipts().records.targets.isEmpty) + #expect(!FileManager.default.fileExists(atPath: target.path)) } @Test(arguments: [ diff --git a/Tests/AgentsCoreTests/SharedTargetTests.swift b/Tests/AgentsCoreTests/SharedTargetTests.swift new file mode 100644 index 0000000..e6d1a85 --- /dev/null +++ b/Tests/AgentsCoreTests/SharedTargetTests.swift @@ -0,0 +1,822 @@ +import CPlatform +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite("Shared native physical targets") +struct SharedTargetTests { + @Test func localAndUserWritersKeepOnePrivateGenerationAcrossScopesAndAliases() throws { + let fixture = try SharedFixture() + let provider = SharedBindings() + var stale: PreparedPrivateMaterialization? + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.a.nativeTarget(for: .claudeMCPLocal) + let prepared = try fixture.a.preparePrivateMaterialization(target) + let transaction = FileTransaction(store: fixture.a) + try transaction.replacePrivate(prepared, bindings: ["secret"], provider: provider) { + try $0.value(for: "secret") + } + try transaction.commit() + stale = try fixture.a.preparePrivateMaterialization(target) + } + let first = try #require(stale) + let key = try fixture.identity(fixture.a) + var generations = [first.receiptGeneration] + for (store, route, bytes) in [ + (fixture.b, NativeTargetRoute.claudeMCPLocal, "secret sibling; B region"), + (fixture.user, NativeTargetRoute.claudeMCPUser, "secret sibling; B region; user region"), + (fixture.a, NativeTargetRoute.claudeMCPLocal, "secret sibling; user region"), + ] { + var privateBeforeWrite = false + try store.withLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + let before = try store.preparePrivateMaterialization( + target, requiringReceiptForExistingTarget: true) + #expect(before.receiptGeneration == generations.last!) + let transaction = FileTransaction(store: store) { point in + if point == "stage.0.writeCreated" { + let journal = try fixture.journal(store) + let container = target.url.deletingLastPathComponent().appendingPathComponent( + journal.containers[0].name) + let directory = try DirectoryHandle(at: container) + _ = try directory.requirePrivateAccess("entry.0.exchanged") + #expect(try directory.read("entry.0.exchanged").isEmpty) + privateBeforeWrite = true + } + } + try transaction.replace(target.url, with: .data(Data(bytes.utf8))) + try transaction.commit() + let after = try store.preparePrivateMaterialization( + target, requiringReceiptForExistingTarget: true) + #expect(after.receiptGeneration != before.receiptGeneration) + generations.append(after.receiptGeneration) + #expect(try Data(contentsOf: target.url) == Data(bytes.utf8)) + #expect(try TransactionLockContext.current(store).requiredResource().identity == key) + } + #expect(privateBeforeWrite) + #expect(try store.materializationReceipts().records.targets.isEmpty) + } + #expect(provider.calls == 1) + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + #expect(throws: CoreError.self) { try first.evidence.validate() } + #expect(throws: CoreError.self) { + try fixture.a.preparePrivateMaterialization( + first.target, expecting: first.receiptGeneration) + } + } + } + + @Test func registeredProjectRouteIsLocalAndSharedRequestsRequireAdmission() throws { + let fixture = try SharedFixture() + let target = try fixture.a.nativeTarget(for: .claudeMCPLocal) + try fixture.a.withLock { + let transaction = FileTransaction(store: fixture.a) + #expect(throws: CoreError.self) { try transaction.replace(target.url, with: .data(Data())) } + } + #expect( + !FileManager.default.fileExists( + atPath: fixture.config.appendingPathComponent(SharedResource.metadataName).path)) + try fixture.a.withLock(footprint: [.claudeMCPProject]) { + #expect(TransactionLockContext.current(fixture.a)?.resources.isEmpty == true) + let project = try fixture.a.nativeTarget(for: .claudeMCPProject) + let transaction = FileTransaction(store: fixture.a) + try transaction.replace(project.url, with: .data(Data("project only".utf8))) + #expect(throws: CoreError.self) { + try transaction.replace( + fixture.config.appendingPathComponent("other.json"), with: .data(Data())) + } + try transaction.commit() + } + #expect( + !FileManager.default.fileExists( + atPath: fixture.config.appendingPathComponent(SharedResource.metadataName).path)) + } + + @Test func externalSiblingOrAccessChangesCannotRefreshSharedReceipts() throws { + let fixture = try SharedFixture() + try fixture.install() + let before = try Data(contentsOf: fixture.receiptURL()) + try Data("external trust change".utf8).write(to: fixture.target) + #expect(throws: CoreError.self) { + try fixture.b.withLock(footprint: [.claudeMCPLocal]) { + let transaction = FileTransaction(store: fixture.b) + try transaction.replace(fixture.target, with: .data(Data("replacement".utf8))) + } + } + #expect(try Data(contentsOf: fixture.receiptURL()) == before) + #expect(try Data(contentsOf: fixture.target) == Data("external trust change".utf8)) + } + + @Test(arguments: [ + "journal.preparing.created.written", "journal.preparing.created.renamed", + "shared.0.reservation.created", + "shared.0.reservation.halfWritten", "shared.0.reservation.written", + "shared.0.reservation.published", "shared.0.reservation.synced", "shared.ready", + "stage.0.writeCreated", "publish.0.exchanged", "entry.0.applied", "entry.2.applied", + "journal.committed", "disposal.0.removed", "journal.finalized", + "shared.0.reservation.removed", "journal.unlinked", + ]) + func sharedCrashWindowsRecoverOneGeneration(_ point: String) throws { + let fixture = try SharedFixture() + try fixture.install() + let old = try Data(contentsOf: fixture.target) + let oldReceipt = try Data(contentsOf: fixture.receiptURL()) + let child = try stateTestProcess(root: fixture.root, arguments: ["shared-edit", point]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let observed = + point == "journal.preparing.created.written" + ? fixture.a.directory.appendingPathComponent("transaction.new") + : fixture.root.appendingPathComponent("last-journal") + let journal = try StateStore.decode( + Data(contentsOf: observed), + as: TransactionJournal.self) + let committed = journal.phase == .committed + if point != "shared.0.reservation.removed" && point != "journal.unlinked" + && point != "journal.preparing.created.renamed" + && point != "journal.preparing.created.written" + { + #expect(throws: CoreError.self) { + try fixture.b.withLock(footprint: [.claudeMCPLocal]) {} + } + } + do { try fixture.a.withLock {} } catch CoreError.transactionRecovered {} + #expect( + try Data(contentsOf: fixture.target) + == (committed ? Data("secret sibling; edited region".utf8) : old)) + if !committed { #expect(try Data(contentsOf: fixture.receiptURL()) == oldReceipt) } + try fixture.b.withLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.b.nativeTarget(for: .claudeMCPLocal) + #expect(try fixture.b.materializationReceipt(for: target) != nil) + } + #expect( + !FileManager.default.fileExists( + atPath: fixture.a.directory.appendingPathComponent("transaction.json").path)) + #expect( + try DirectoryHandle(at: fixture.receiptURL().deletingLastPathComponent()).names().sorted() + == ["lock", "receipt"]) + } + + @Test(arguments: [false, true]) + func finalizedCleanupAndDiagnosisNeverReconstructOldData(_ rolledBack: Bool) throws { + let fixture = try SharedFixture() + try fixture.install() + let command = rolledBack ? "entry.0.applied" : "shared.0.reservation.removed" + let child = try stateTestProcess(root: fixture.root, arguments: ["shared-edit", command]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + if rolledBack { + try FileManager.default.removeItem(at: fixture.root.appendingPathComponent("ready")) + let recovery = try stateTestProcess( + root: fixture.root, arguments: ["shared-recover", "shared.0.reservation.removed"]) + defer { terminateProcess(recovery) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: recovery, root: fixture.root) + terminateProcess(recovery) + } + let journal = try fixture.journal(fixture.a) + #expect(journal.finalized) + #expect(journal.phase == (rolledBack ? .rolledBack : .committed)) + try fixture.b.withLock(footprint: [.claudeMCPLocal]) { + let transaction = FileTransaction(store: fixture.b) + try transaction.replace( + fixture.target, with: .data(Data("secret sibling; later B generation".utf8))) + try transaction.commit() + } + try FileManager.default.removeItem(at: fixture.root.appendingPathComponent("old-data")) + let target = try FileSnapshot.read(at: fixture.target) + let receipt = try Data(contentsOf: fixture.receiptURL()) + let journalBytes = try Data( + contentsOf: fixture.a.directory.appendingPathComponent("transaction.json")) + try fixture.a.withReadLock( + onPendingRecovery: { + let diagnostic = FileTransaction.recoveryDiagnostic(store: fixture.a) + #expect(!diagnostic.requiresOwner) + #expect(diagnostic.message.contains(rolledBack ? "rolledBack" : "committed")) + }, { _ = Issue.record("finalized journal must remain pending for inspection") }) + #expect( + try Data(contentsOf: fixture.a.directory.appendingPathComponent("transaction.json")) + == journalBytes) + let outcome = TransactionOutcome() + outcome.journalID = journal.id + do { try fixture.a.withLock(outcome: outcome) {} } catch CoreError.transactionRecovered {} + #expect(outcome.disposition == (rolledBack ? .unchanged : .committed)) + #expect(try FileSnapshot.read(at: fixture.target) == target) + #expect(try Data(contentsOf: fixture.receiptURL()) == receipt) + #expect( + !FileManager.default.fileExists(atPath: fixture.root.appendingPathComponent("old-data").path)) + } + @Test func aliasedCallersWaitOnTheSamePhysicalLockBeforeScopeEntry() throws { + let fixture = try SharedFixture() + let holder = try stateTestProcess( + root: fixture.root, arguments: ["shared-lock", "shared.locked"]) + defer { terminateProcess(holder) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: holder, root: fixture.root) + let other = fixture.b.environment.projectDirectory + let waiter = try stateTestProcess( + root: other, + arguments: [ + "shared-lock", "shared.0.lock.contended", "--shared-config", + fixture.root.appendingPathComponent("config-alias").path, + ]) + defer { terminateProcess(waiter) } + try ProcessWait.marker(other.appendingPathComponent("ready"), child: waiter, root: other) + #expect(!FileManager.default.fileExists(atPath: fixture.b.directory.path)) + terminateProcess(waiter) + terminateProcess(holder) + try fixture.b.withLock(footprint: [.claudeMCPLocal, .claudeMCPUser]) { + let local = try fixture.b.nativeTarget(for: .claudeMCPLocal) + let user = try fixture.b.nativeTarget(for: .claudeMCPUser) + #expect(local.path == user.path) + #expect(local.url == user.url) + } + } + + @Test(arguments: ["shared-skill-recover", "shared-watch-recover", "shared-instruction-recover"]) + func ordinaryMutationEntrypointsRecoverPendingSharedFootprints(_ command: String) throws { + let fixture = try SharedFixture() + try fixture.install() + let old = try Data(contentsOf: fixture.target) + let oldReceipt = try Data(contentsOf: fixture.receiptURL()) + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "entry.0.applied"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let before = try FileSnapshot.read(at: fixture.config) + #expect(throws: CoreError.self) { try fixture.a.loadResolved() } + #expect(try FileSnapshot.read(at: fixture.config) == before) + let recovery = try stateTestProcess(root: fixture.root, arguments: [command, "never"]) + defer { terminateProcess(recovery) } + try ProcessWait.exit(recovery, root: fixture.root) + #expect(recovery.terminationStatus == 0) + #expect(try Data(contentsOf: fixture.target) == old) + #expect(try Data(contentsOf: fixture.receiptURL()) == oldReceipt) + } + + @Test(arguments: [false, true]) + func wholeFileDeletionAndReceiptDeletionRecoverTogether(_ committed: Bool) throws { + let fixture = try SharedFixture() + try fixture.install() + let old = try Data(contentsOf: fixture.target) + let receiptURL = try fixture.receiptURL() + let oldReceipt = try Data(contentsOf: receiptURL) + let child = try stateTestProcess( + root: fixture.root, + arguments: ["shared-delete", committed ? "journal.committed" : "entry.0.applied"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + do { try fixture.a.withLock {} } catch CoreError.transactionRecovered {} + if committed { + #expect(!FileManager.default.fileExists(atPath: fixture.target.path)) + #expect(!FileManager.default.fileExists(atPath: receiptURL.path)) + } else { + #expect(try Data(contentsOf: fixture.target) == old) + #expect(try Data(contentsOf: receiptURL) == oldReceipt) + } + } + + @Test func finalizedOwnerCannotDeleteAnotherJournalsReservation() throws { + let fixture = try SharedFixture() + try fixture.install() + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "shared.0.reservation.removed"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let other = fixture.b.environment.projectDirectory + let b = try stateTestProcess( + root: other, + arguments: ["shared-edit", "shared.ready", "--shared-config", fixture.config.path]) + defer { terminateProcess(b) } + try ProcessWait.marker(other.appendingPathComponent("ready"), child: b, root: other) + terminateProcess(b) + let reservationURL = try fixture.receiptURL().deletingLastPathComponent() + .appendingPathComponent("reservation") + let reservation = try Data(contentsOf: reservationURL) + let target = try FileSnapshot.read(at: fixture.target) + try FileManager.default.removeItem(at: fixture.root.appendingPathComponent("old-data")) + try fixture.a.withReadLock( + onPendingRecovery: { + #expect(!FileTransaction.recoveryDiagnostic(store: fixture.a).requiresOwner) + }, { _ = Issue.record("expected metadata cleanup diagnostic") }) + do { try fixture.a.withLock {} } catch CoreError.transactionRecovered {} + #expect(try Data(contentsOf: reservationURL) == reservation) + #expect(try FileSnapshot.read(at: fixture.target) == target) + do { try fixture.b.withLock {} } catch CoreError.transactionRecovered {} + } + + @Test func synchronousFailureRecoversWithinTheOriginalFootprint() throws { + let fixture = try SharedFixture() + try fixture.install() + let before = try Data(contentsOf: fixture.target) + let receipt = try Data(contentsOf: fixture.receiptURL()) + var callbacks = 0 + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + callbacks += 1 + let transaction = FileTransaction(store: fixture.a) { point in + if point == "publish.0.exchanged" { throw CoreError.invalidState("injected failure") } + } + try transaction.replace(fixture.target, with: .data(Data("secret sibling; change".utf8))) + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(try TransactionLockContext.current(fixture.a).requiredResource().reservation() == nil) + let unsupported = FileTransaction(store: fixture.a) + var producers = 0 + #expect(throws: CoreError.self) { + try unsupported.replace( + fixture.target, + with: .prepared { url in + producers += 1 + return url + }) + } + #expect(producers == 0) + #expect(throws: CoreError.self) { + try fixture.b.withLock(footprint: [.claudeMCPUser]) { callbacks += 1 } + } + } + #expect(callbacks == 1) + #expect(try Data(contentsOf: fixture.target) == before) + #expect(try Data(contentsOf: fixture.receiptURL()) == receipt) + } + + @Test(arguments: [ + "collision", "symlink", "unknown-slot", "malformed-reservation", "missing-ready-reservation", + "unsafe-partial", + ]) + func unsafeCoordinationMetadataIsRetainedAndRefused(_ shape: String) throws { + let fixture = try SharedFixture() + if shape == "collision" || shape == "symlink" { + let url = fixture.config.appendingPathComponent(SharedResource.metadataName) + if shape == "collision" { + try Data().write(to: url) + } else { + try FileManager.default.createSymbolicLink( + at: url, withDestinationURL: fixture.b.environment.projectDirectory) + } + } else { + try fixture.install() + let metadata = try DirectoryHandle(at: fixture.receiptURL().deletingLastPathComponent()) + if shape == "missing-ready-reservation" || shape == "unsafe-partial" { + let child = try stateTestProcess( + root: fixture.root, + arguments: [ + "shared-edit", + shape == "unsafe-partial" ? "shared.0.reservation.halfWritten" : "shared.ready", + ]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + if shape == "unsafe-partial" { + let journal = try fixture.journal(fixture.a) + let slot = metadata.url.appendingPathComponent(SharedResource.temporaryName(journal.id)) + try #require(chmod(slot.path, 0o644) == 0) + } else { + try metadata.remove("reservation") + } + } else { + let name = shape == "unknown-slot" ? "reservation-unknown.new" : "reservation" + let file = try metadata.createPrivateFile(name) + try file.write(Data("incomplete".utf8)) + } + } + let before = try FileSnapshot.read(at: fixture.config) + var callbacks = 0 + #expect(throws: CoreError.self) { + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { callbacks += 1 } + } + #expect(callbacks == 0) + #expect(try FileSnapshot.read(at: fixture.config) == before) + } + + @Test func intentBeforeReservationCannotUndoALaterWritersGeneration() throws { + let fixture = try SharedFixture() + try fixture.install() + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "journal.preparing.created.renamed"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + try fixture.b.withLock(footprint: [.claudeMCPLocal]) { + let transaction = FileTransaction(store: fixture.b) + try transaction.replace( + fixture.target, with: .data(Data("secret sibling; later region".utf8))) + try transaction.commit() + } + let before = try FileSnapshot.read(at: fixture.target) + let receipt = try Data(contentsOf: fixture.receiptURL()) + do { try fixture.a.withLock {} } catch CoreError.transactionRecovered {} + #expect(try FileSnapshot.read(at: fixture.target) == before) + #expect(try Data(contentsOf: fixture.receiptURL()) == receipt) + } + + @Test(arguments: [ + "journal.rolledBack.finalized.written", "journal.rolledBack.finalized.renamed", + "journal.finalized", + ]) + func interruptedRecoveryOfALoneReservationIntentIsRepeatable(_ point: String) throws { + let fixture = try SharedFixture() + try fixture.install() + let before = try Data(contentsOf: fixture.target) + let receipt = try Data(contentsOf: fixture.receiptURL()) + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "journal.preparing.created.written"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + try FileManager.default.removeItem(at: fixture.root.appendingPathComponent("ready")) + let recovery = try stateTestProcess(root: fixture.root, arguments: ["shared-recover", point]) + defer { terminateProcess(recovery) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: recovery, root: fixture.root) + terminateProcess(recovery) + try fixture.a.withReadLock( + onPendingRecovery: { + #expect(!FileTransaction.recoveryDiagnostic(store: fixture.a).requiresOwner) + }, { _ = Issue.record("expected pending cleanup") }) + do { try fixture.a.withLock {} } catch CoreError.transactionRecovered {} + #expect(try Data(contentsOf: fixture.target) == before) + #expect(try Data(contentsOf: fixture.receiptURL()) == receipt) + } + + @Test func authorizationAliasChangesInvalidateTheHeldPhysicalTarget() throws { + let fixture = try SharedFixture() + try fixture.install() + let before = try FileSnapshot.read(at: fixture.target) + let receipt = try Data(contentsOf: fixture.receiptURL()) + let other = fixture.root.appendingPathComponent("other-config") + try FileManager.default.createDirectory(at: other, withIntermediateDirectories: true) + try fixture.b.withLock(footprint: [.claudeMCPLocal]) { + let alias = fixture.root.appendingPathComponent("config-alias") + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: other) + #expect(throws: CoreError.self) { try fixture.b.nativeTarget(for: .claudeMCPLocal) } + let transaction = FileTransaction(store: fixture.b) + #expect(throws: CoreError.self) { + try transaction.replace(other.appendingPathComponent(".claude.json"), with: .data(Data())) + } + } + #expect(try FileSnapshot.read(at: fixture.target) == before) + #expect(try Data(contentsOf: fixture.receiptURL()) == receipt) + #expect(try FileManager.default.contentsOfDirectory(atPath: other.path).isEmpty) + } + + @Test(arguments: ["footprint", "reservationsReady", "finalized", "metadata-target"]) + func missingCoordinationEvidenceAndForgedMetadataTargetsCannotReplay(_ field: String) throws { + let fixture = try SharedFixture() + try fixture.install() + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "shared.ready"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let url = fixture.a.directory.appendingPathComponent("transaction.json") + var value = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) + if field == "metadata-target" { + var entries = try #require(value["entries"] as? [[String: Any]]) + let index = try #require( + entries.firstIndex { + ($0["path"] as? String)?.hasPrefix(NativeTargetRoute.metadataRoot) == true + }) + entries[index]["path"] = NativeTargetRoute.metadataRoot + "/lock" + value["entries"] = entries + } else { + value.removeValue(forKey: field) + } + let bytes = try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys]) + try bytes.write(to: url) + let target = try FileSnapshot.read(at: fixture.target) + let metadata = try FileSnapshot.read(at: fixture.receiptURL().deletingLastPathComponent()) + try fixture.a.withReadLock( + onPendingRecovery: { + #expect(FileTransaction.recoveryDiagnostic(store: fixture.a).requiresOwner) + }, { _ = Issue.record("invalid evidence must block inspection") }) + #expect(throws: CoreError.self) { try fixture.a.withLock {} } + #expect(try Data(contentsOf: url) == bytes) + #expect(try FileSnapshot.read(at: fixture.target) == target) + #expect(try FileSnapshot.read(at: fixture.receiptURL().deletingLastPathComponent()) == metadata) + } + + @Test func aForeignReservationReportsItsOwnerWithoutOpeningTheOwnerScope() throws { + let fixture = try SharedFixture() + try fixture.install() + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "shared.ready"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let journal = try fixture.journal(fixture.a) + var message = "" + do { try fixture.b.withLock(footprint: [.claudeMCPLocal]) {} } catch CoreError.recoveryPending( + let value) + { message = value } + #expect(message.contains(fixture.a.directory.path)) + #expect(message.contains(journal.id.uuidString)) + #expect(!message.contains("secret sibling")) + #expect(try fixture.journal(fixture.a).id == journal.id) + } + + @Test(arguments: [false, true], [false, true]) + func readOnlyAdmissionRechecksSuccessfulAndFailedUnlockedSharedReads( + _ metadataExists: Bool, _ throwFirst: Bool + ) throws { + let fixture = try SharedFixture() + if metadataExists { _ = try SharedResource(store: fixture.a, create: true) } + let writer = fixture.a + var attempts = 0 + let result = try fixture.b.withReadLock(footprint: [.claudeMCPLocal]) { + attempts += 1 + let target = try fixture.b.nativeTarget(for: .claudeMCPLocal) + let receipt = try fixture.b.materializationReceipt(for: target) + if attempts == 1 { + #expect(receipt == nil) + let finished = DispatchSemaphore(value: 0) + Thread.detachNewThread { + defer { finished.signal() } + do { + try writer.withLock(footprint: [.claudeMCPLocal]) { + let target = try writer.nativeTarget(for: .claudeMCPLocal) + let transaction = FileTransaction(store: writer) + try transaction.replacePrivate( + try writer.preparePrivateMaterialization(target), provider: SharedBindings() + ) { _ in + Data("secret sibling; concurrently installed".utf8) + } + try transaction.commit() + } + } catch { Issue.record(error) } + } + try #require(finished.wait(timeout: .now() + 10) == .success) + if throwFirst { throw CoreError.invalidState("discarded unlocked inspection") } + } + return receipt != nil + } + #expect(attempts == 2) + #expect(result) + } + + @Test func aSharedTransactionCannotEscapeItsHeldContext() throws { + let fixture = try SharedFixture() + try fixture.install() + let before = try FileSnapshot.read(at: fixture.target) + let provider = SharedBindings() + var escaped: FileTransaction? + let missingRoot = AgentRegistry.installSkillsDirectory( + for: .claudeCode, scope: .project, environment: fixture.a.environment) + #expect(!FileManager.default.fileExists(atPath: missingRoot.path)) + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.a.nativeTarget(for: .claudeMCPLocal) + let transaction = FileTransaction(store: fixture.a) + try transaction.replace(missingRoot.appendingPathComponent("escaped"), with: .data(Data())) + try transaction.replacePrivate( + try fixture.a.preparePrivateMaterialization(target), bindings: ["secret"], + provider: provider + ) { try $0.value(for: "secret") } + escaped = transaction + } + #expect(throws: CoreError.self) { try escaped?.commit() } + #expect(provider.calls == 0) + #expect(!FileManager.default.fileExists(atPath: missingRoot.path)) + #expect(try FileSnapshot.read(at: fixture.target) == before) + #expect( + !FileManager.default.fileExists( + atPath: fixture.a.directory.appendingPathComponent("transaction.json").path)) + } + + @Test func recoveryCannotCreateANewCoordinationDomainFromAChangedRuntime() throws { + let fixture = try SharedFixture() + try fixture.install() + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "shared.ready"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let wrong = fixture.root.appendingPathComponent("missing-config") + var environment = fixture.a.environment + environment.environment["CLAUDE_CONFIG_DIR"] = wrong.path + let relocated = StateStore(scope: .project, environment: environment) + let journal = try Data( + contentsOf: fixture.a.directory.appendingPathComponent("transaction.json")) + let target = try FileSnapshot.read(at: fixture.target) + #expect { try relocated.withLock {} } throws: { error in + guard case CoreError.invalidState(let message) = error else { return false } + return message.contains("original registered runtime context") + } + #expect(!FileManager.default.fileExists(atPath: wrong.path)) + #expect( + try Data(contentsOf: fixture.a.directory.appendingPathComponent("transaction.json")) + == journal) + #expect(try FileSnapshot.read(at: fixture.target) == target) + } + + @Test func finalizedCleanupRequiresAConsistentTerminalOutcome() throws { + let fixture = try SharedFixture() + try fixture.install() + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "shared.0.reservation.removed"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + var journal = try fixture.journal(fixture.a) + journal.entries[0].progress = .publishing + let bytes = try StateStore.encode(journal) + let url = fixture.a.directory.appendingPathComponent("transaction.json") + try bytes.write(to: url) + let target = try FileSnapshot.read(at: fixture.target) + try fixture.a.withReadLock( + onPendingRecovery: { + #expect(FileTransaction.recoveryDiagnostic(store: fixture.a).requiresOwner) + }, { _ = Issue.record("inconsistent terminal outcome must block inspection") }) + #expect(throws: CoreError.self) { try fixture.a.withLock {} } + #expect(try Data(contentsOf: url) == bytes) + #expect(try FileSnapshot.read(at: fixture.target) == target) + } + + @Test(arguments: ["scope", "lock", "coordination-lock"]) + func replacementOfTheHeldScopeOrLockStopsBeforeBindings(_ shape: String) throws { + let fixture = try SharedFixture() + try fixture.install() + let before = try FileSnapshot.read(at: fixture.target) + let provider = SharedBindings() + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.a.nativeTarget(for: .claudeMCPLocal) + let transaction = FileTransaction(store: fixture.a) + try transaction.replacePrivate( + try fixture.a.preparePrivateMaterialization(target), bindings: ["secret"], + provider: provider + ) { + try $0.value(for: "secret") + } + let original: URL + if shape == "scope" { + original = fixture.a.directory + } else if shape == "lock" { + original = fixture.a.directory.appendingPathComponent(".agents.lock") + } else { + original = try TransactionLockContext.current(fixture.a).requiredResource().metadata!.url + .appendingPathComponent("lock") + } + let retained = fixture.root.appendingPathComponent("retained-scope-lock") + try FileManager.default.moveItem(at: original, to: retained) + defer { + try? FileManager.default.removeItem(at: original) + try? FileManager.default.moveItem(at: retained, to: original) + } + if shape == "scope" { + try FileManager.default.createDirectory(at: original, withIntermediateDirectories: false) + } else { + try Data().write(to: original) + try #require(chmod(original.path, 0o600) == 0) + } + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(provider.calls == 0) + } + #expect(try FileSnapshot.read(at: fixture.target) == before) + } + + @Test func aSharedLockReplacedDuringStagingStopsBeforeTheProvider() throws { + let fixture = try SharedFixture() + try fixture.install() + let before = try FileSnapshot.read(at: fixture.target) + let provider = SharedBindings() + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.a.nativeTarget(for: .claudeMCPLocal) + let metadata = try #require( + TransactionLockContext.current(fixture.a).requiredResource().metadata) + let lock = metadata.url.appendingPathComponent("lock") + let retained = fixture.root.appendingPathComponent("retained-coordination-lock") + var replaced = false + let transaction = FileTransaction(store: fixture.a) { point in + if point == "stage.0.writeCreated" { + try FileManager.default.moveItem(at: lock, to: retained) + try Data().write(to: lock) + try #require(chmod(lock.path, 0o600) == 0) + replaced = true + } + } + try transaction.replacePrivate( + try fixture.a.preparePrivateMaterialization(target), bindings: ["secret"], + provider: provider + ) { + try $0.value(for: "secret") + } + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(replaced && provider.calls == 0) + try FileManager.default.removeItem(at: lock) + try FileManager.default.moveItem(at: retained, to: lock) + #expect(try FileTransaction.recover(store: fixture.a)) + } + #expect(try FileSnapshot.read(at: fixture.target) == before) + } + + @Test func readOnlyFootprintsCreateNoMetadataOrScopeLock() throws { + let fixture = try SharedFixture() + let before = try FileSnapshot.read(at: fixture.config) + try fixture.b.withReadLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.b.nativeTarget(for: .claudeMCPLocal) + #expect(try fixture.b.materializationReceipt(for: target) == nil) + } + #expect(try FileSnapshot.read(at: fixture.config) == before) + #expect(!FileManager.default.fileExists(atPath: fixture.b.directory.path)) + } + +} + +private final class SharedBindings: RuntimeBindingProvider { + var calls = 0 + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + calls += 1 + return Data("secret sibling; initial region".utf8) + } +} + +private final class SharedFixture { + let base: TransactionFixture + var root: URL { base.root } + let a: StateStore + let b: StateStore + let user: StateStore + let config: URL + var target: URL { config.appendingPathComponent(".claude.json") } + + init() throws { + base = try TransactionFixture() + config = base.root.appendingPathComponent("configured-claude") + let other = base.root.appendingPathComponent("B") + let home = base.root.appendingPathComponent("other-home") + for url in [config, other, home, base.root.appendingPathComponent("old-data")] { + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + } + try Data("ordinary before".utf8).write( + to: base.root.appendingPathComponent("old-data/AGENTS.md")) + let alias = base.root.appendingPathComponent("config-alias") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: config) + a = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: base.root, + homeDirectory: base.root.appendingPathComponent("home"), + environment: ["CLAUDE_CONFIG_DIR": config.path])) + b = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: other, + homeDirectory: home, environment: ["CLAUDE_CONFIG_DIR": alias.path])) + user = StateStore( + scope: .user, + environment: RuntimeEnvironment( + projectDirectory: other, + homeDirectory: config, environment: [:])) + } + + func install() throws { + try a.withLock(footprint: [.claudeMCPLocal]) { + let target = try a.nativeTarget(for: .claudeMCPLocal) + let transaction = FileTransaction(store: a) + try transaction.replacePrivate( + try a.preparePrivateMaterialization(target), provider: SharedBindings() + ) { _ in + Data("secret sibling; initial region".utf8) + } + try transaction.commit() + } + } + + func identity(_ store: StateStore) throws -> SharedResourceIdentity { + try store.withReadLock(footprint: [.claudeMCPUser]) { + try TransactionLockContext.current(store).requiredResource().identity + } + } + + func receiptURL() throws -> URL { + let identity = try SharedResource(store: a, create: false).identity + return config.appendingPathComponent(SharedResource.metadataName).appendingPathComponent( + identity.directoryName + ).appendingPathComponent("receipt") + } + + func journal(_ store: StateStore) throws -> TransactionJournal { + try StateStore.decode( + Data(contentsOf: store.directory.appendingPathComponent("transaction.json")), + as: TransactionJournal.self) + } +} diff --git a/Tests/AgentsCoreTests/StateTransactionTests.swift b/Tests/AgentsCoreTests/StateTransactionTests.swift index 78b59ed..e680dc3 100644 --- a/Tests/AgentsCoreTests/StateTransactionTests.swift +++ b/Tests/AgentsCoreTests/StateTransactionTests.swift @@ -450,9 +450,7 @@ extension StateTransactionTests { let originalHash = try FileSnapshot.read(at: fixture.root) let copyHash = try FileSnapshot.read(at: copy) let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: copy)) - #expect(throws: CoreError.invalidState("transaction root identity changed")) { - try store.withLock {} - } + #expect(throws: CoreError.self) { try store.withLock {} } #expect(try FileSnapshot.read(at: fixture.root) == originalHash) #expect(try FileSnapshot.read(at: copy) == copyHash) } diff --git a/Tests/AgentsCoreTests/WatchDurabilityTests.swift b/Tests/AgentsCoreTests/WatchDurabilityTests.swift index 7eff557..f2239ea 100644 --- a/Tests/AgentsCoreTests/WatchDurabilityTests.swift +++ b/Tests/AgentsCoreTests/WatchDurabilityTests.swift @@ -240,7 +240,9 @@ final class WatchGitFixture { defer { terminateProcess(child) } let marker = root.appendingPathComponent("ready") try ProcessWait.marker(marker, child: child, root: root) - #expect(try String(contentsOf: marker, encoding: .utf8) == step) + try ProcessWait.stopped(child, root: root) + let observed = try String(contentsOf: marker, encoding: .utf8) + #expect(observed == step) terminateProcess(child) try FileManager.default.removeItem(at: marker) } diff --git a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift index c1217d8..83e8269 100644 --- a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift +++ b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift @@ -221,7 +221,21 @@ struct CombinedUpdateTests { guard step == "plan.skills" else { return } attempts += 1 if attempts == 1 { - try fixture.declare() + let store = fixture.store + let source = fixture.repo.path + let finished = DispatchSemaphore(value: 0) + Thread.detachNewThread { + defer { finished.signal() } + do { + try store.save( + declaration: Declaration( + sources: ["fixture": SourceDeclaration(kind: .local, location: source)], + skills: ["fixture": SkillDeclaration(select: .all, agents: [.codex], mode: .copy)] + ), + resolved: ResolvedState()) + } catch { Issue.record(error) } + } + try #require(finished.wait(timeout: .now() + 10) == .success) if throwFirst { throw CoreError.invalidState("discarded read") } } }) diff --git a/Tests/StateTestProcess/PrivateMaterializationProbe.swift b/Tests/StateTestProcess/PrivateMaterializationProbe.swift index 6752d57..139b0d3 100644 --- a/Tests/StateTestProcess/PrivateMaterializationProbe.swift +++ b/Tests/StateTestProcess/PrivateMaterializationProbe.swift @@ -1,4 +1,6 @@ import AgentsCore +import AgentsInstructions +import AgentsSkills import Foundation func privateMaterializationProbe( @@ -29,3 +31,55 @@ private struct ProbeBindings: RuntimeBindingProvider { return Data("private-after".utf8) } } + +func sharedMaterializationProbe( + _ command: String, store: StateStore, checkpoint: @escaping (String) throws -> Void +) throws { + if command == "shared-skill-recover" { + do { + _ = try SkillOperations.remove(skillNames: ["absent"], environment: store.environment) + } catch CoreError.transactionRecovered {} + return + } + if command == "shared-watch-recover" { + do { + _ = try SkillOperations.watchOperations().remove("absent", environment: store.environment) + } catch CoreError.transactionRecovered {} + return + } + if command == "shared-instruction-recover" { + do { + _ = try InstructionOperations.remove(names: ["absent"], environment: store.environment) + } catch CoreError.transactionRecovered {} + return + } + if command == "shared-recover" { + do { try store.withLock(checkpoint: checkpoint, {}) } catch CoreError.transactionRecovered {} + return + } + try store.withLock(checkpoint: checkpoint, footprint: [.claudeMCPLocal]) { + if command == "shared-lock" { + try checkpoint("shared.locked") + return + } + let target = try store.nativeTarget(for: .claudeMCPLocal) + let transaction = FileTransaction(store: store, checkpoint: checkpoint) + if command == "shared-delete" { + try transaction.delete(target.url) + } else if command == "shared-install" { + let prepared = try store.preparePrivateMaterialization(target, changingAccess: true) + try transaction.replacePrivate( + prepared, bindings: ["value"], + provider: ProbeBindings(root: store.environment.projectDirectory) + ) { + try $0.value(for: "value") + } + } else { + try transaction.replace(target.url, with: .data(Data("secret sibling; edited region".utf8))) + } + try transaction.replace( + store.environment.projectDirectory.appendingPathComponent("old-data/AGENTS.md"), + with: .data(Data("ordinary after".utf8))) + try transaction.commit() + } +} diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 72a544b..4a4d695 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -13,12 +13,16 @@ let root = URL(fileURLWithPath: arguments[1]) let scopeIndex = arguments.firstIndex(of: "--scope") let scope: InstallScope = scopeIndex.flatMap { InstallScope(rawValue: arguments[$0 + 1]) } ?? .project +let sharedConfigIndex = arguments.firstIndex(of: "--shared-config") +let sharedConfig = + sharedConfigIndex.map { arguments[$0 + 1] } + ?? root.appendingPathComponent("configured-claude").path let store = StateStore( scope: scope, environment: RuntimeEnvironment( projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), - environment: ["CLAUDE_CONFIG_DIR": root.appendingPathComponent("configured-claude").path])) + environment: ["CLAUDE_CONFIG_DIR": sharedConfig])) let checkpointState = Mutex( (requested: arguments.count > 3 ? arguments[3] : "", seen: Set())) let traceURL = root.appendingPathComponent( @@ -53,6 +57,8 @@ func signalContention() throws { } if arguments[2].hasPrefix("ledger-") { try ledgerProbe(arguments[2], store: store) +} else if arguments[2].hasPrefix("shared-") { + try sharedMaterializationProbe(arguments[2], store: store, checkpoint: { try stop($0) }) } else if arguments[2].hasPrefix("private-") { try privateMaterializationProbe(arguments[2], store: store, checkpoint: { try stop($0) }) } else if arguments[2] == "git-environment" { From f661b2b49b85da7e5732610c350f5efe6f337b32 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:35:20 +0800 Subject: [PATCH 054/171] fix(core): preserve native configuration ownership and syntax --- Sources/NativeDocuments/Model.swift | 25 ++++ Sources/NativeDocuments/NativeDocument.swift | 5 + Sources/NativeDocuments/PatchBuilder.swift | 78 ++++++++-- Sources/NativeDocuments/Semantics.swift | 14 ++ Sources/NativeDocuments/TOMLIndex.swift | 13 +- Sources/TOMLSemantics/PATCHES.md | 12 +- Sources/TOMLSemantics/Parsing/Parser.swift | 27 +++- .../TOMLSemantics/Parsing/TOMLDocument.swift | 1 + Sources/TOMLSemantics/SemanticDocument.swift | 9 +- Sources/TOMLSemantics/provenance.json | 2 +- Sources/TOMLSemantics/upstream.patch | 136 ++++++++++-------- .../NativeDocumentTests.swift | 68 +++++++++ .../NativeDocumentsTests/SemanticTests.swift | 74 ++++++++++ 13 files changed, 383 insertions(+), 81 deletions(-) diff --git a/Sources/NativeDocuments/Model.swift b/Sources/NativeDocuments/Model.swift index edc5c7b..ca26a63 100644 --- a/Sources/NativeDocuments/Model.swift +++ b/Sources/NativeDocuments/Model.swift @@ -154,6 +154,9 @@ final class Node { var headers: [Range] = [] var insertion: Int? var inline = false + // Dotted descendants own entries inside these braces, not a separately extensible table. + weak var enclosingInline: Node? + var inlineKeyPath: [String] = [] var aot = false var syntaxLocated = false var commas: [Range] = [] @@ -170,6 +173,28 @@ final class Node { } return nil } + func inlineEntries(_ budget: NativeDocumentBudget) throws -> [(parent: Node, index: Int)] { + var result: [(parent: Node, index: Int)] = [] + func collect(_ node: Node, depth: Int) throws { + try budget.enter(depth) + for i in node.members.indices { + try budget.step() + if node.members[i].entry != nil { + try budget.allocate(1, stage: "inline entries") + result.append((node, i)) + } else { + try collect(node.members[i].node, depth: depth + 1) + } + } + } + try collect(self, depth: 0) + try budget.allocate(result.count, stage: "inline entry order") + return try result.sorted { + try budget.step() + return $0.parent.members[$0.index].entry!.lowerBound + < $1.parent.members[$1.index].entry!.lowerBound + } + } func copy(_ budget: NativeDocumentBudget, depth: Int = 0) throws -> Node { try budget.node(depth: depth) let result = Node(kind, text: text, raw: raw, range: range) diff --git a/Sources/NativeDocuments/NativeDocument.swift b/Sources/NativeDocuments/NativeDocument.swift index dc4f479..fdfe971 100644 --- a/Sources/NativeDocuments/NativeDocument.swift +++ b/Sources/NativeDocuments/NativeDocument.swift @@ -124,6 +124,11 @@ package struct NativeDocument { guard old != nil || desired != nil else { throw NativeDocumentError.ownershipMismatch(edit.region) } + if desired == nil, case .createdContainer = edit.expected { + guard let old, old.kind == .object, old.members.isEmpty else { + throw NativeDocumentError.ownershipMismatch(edit.region) + } + } if let old, desired == nil, old.kind == .object && old.members.isEmpty { guard case .createdContainer = edit.expected else { throw NativeDocumentError.ownershipMismatch(edit.region) diff --git a/Sources/NativeDocuments/PatchBuilder.swift b/Sources/NativeDocuments/PatchBuilder.swift index 4aa122a..01a369e 100644 --- a/Sources/NativeDocuments/PatchBuilder.swift +++ b/Sources/NativeDocuments/PatchBuilder.swift @@ -61,7 +61,9 @@ struct PatchBuilder { try eraseMember(m, parent: old) } } - if old.inline && retained.count != old.members.count { + if toml, let container = old.inline ? old : old.enclosingInline { + try pruneInlineCommas(in: container) + } else if old.inline && retained.count != old.members.count { let keepCommas = Set(retained.dropLast().compactMap { old.members[$0].comma?.lowerBound }) for m in old.members { if let comma = m.comma, !keepCommas.contains(comma.lowerBound) { try patch(comma) } @@ -143,7 +145,9 @@ struct PatchBuilder { throw NativeDocumentError.ownershipMismatch(region) } try eraseMember(parent.members[i], parent: parent) - if parent.inline { + if toml, let container = parent.inline ? parent : parent.enclosingInline { + try pruneInlineCommas(in: container) + } else if parent.inline { if let comma = parent.members[i].comma { try patch(comma) } else if i > 0, let comma = parent.members[i - 1].comma { @@ -171,6 +175,36 @@ struct PatchBuilder { } } } + private func entryRemoved(_ member: Member) throws -> Bool { + guard let entry = member.entry else { return false } + return try patches.contains { + try budget.step() + return $0.bytes.isEmpty && $0.range.lowerBound <= entry.lowerBound + && $0.range.upperBound >= entry.upperBound + } + } + private func survivingInlineMembers(in container: Node) throws -> [Member] { + var surviving: [Member] = [] + for entry in try container.inlineEntries(budget) { + let member = entry.parent.members[entry.index] + if try !entryRemoved(member) { + try budget.allocate(1, stage: "inline survivors") + surviving.append(member) + } + } + return surviving + } + private mutating func pruneInlineCommas(in container: Node) throws { + let surviving = try survivingInlineMembers(in: container) + for entry in try container.inlineEntries(budget) { + let member = entry.parent.members[entry.index] + if let comma = member.comma, + try entryRemoved(member) || member.entry == surviving.last?.entry + { + try patch(comma) + } + } + } mutating func insert(path: [NativePathStep], value: Node, root: Node) throws { var parent = root var existing: [NativePathStep] = [] @@ -318,9 +352,13 @@ struct PatchBuilder { private func assignment(in parent: Node) throws -> String { let fallback = toml ? " = " : ": " - guard let first = parent.members.first(where: { $0.keyRange != nil }), let key = first.keyRange, - let value = first.node.range - else { return fallback } + let first: Member? + if toml && parent.inline { + first = try parent.inlineEntries(budget).first.map { $0.parent.members[$0.index] } + } else { + first = parent.members.first(where: { $0.keyRange != nil }) + } + guard let first, let key = first.keyRange, let value = first.node.range else { return fallback } let gap = document.source[key.upperBound.. String { diff --git a/Sources/NativeDocuments/TOMLIndex.swift b/Sources/NativeDocuments/TOMLIndex.swift index 5613bdb..2bb2f46 100644 --- a/Sources/NativeDocuments/TOMLIndex.swift +++ b/Sources/NativeDocuments/TOMLIndex.swift @@ -211,12 +211,20 @@ struct TOMLIndex { } let keys = try keyParts(nodes[0]) var current = parent + let enclosingInline = parent.inline ? parent : parent.enclosingInline + var inlineKeyPath = parent.inline ? [] : parent.inlineKeyPath for key in keys.dropLast() { guard let m = try current.member(key, budget: budget) else { located = false return } current = current.members[m].node + if let enclosingInline { + try budget.allocate(key.utf8.count + inlineKeyPath.count + 1, stage: "inline key path") + inlineKeyPath.append(key) + current.enclosingInline = enclosingInline + current.inlineKeyPath = inlineKeyPath + } } guard let key = keys.last, let m = try current.member(key, budget: budget) else { located = false @@ -251,8 +259,9 @@ struct TOMLIndex { try budget.step() return ($0.entry?.lowerBound ?? 0) < ($1.entry?.lowerBound ?? 0) } - for i in node.members.indices where i < node.commas.count { - node.members[i].comma = node.commas[i] + let entries = try node.inlineEntries(budget) + for (i, entry) in entries.enumerated() where i < node.commas.count { + entry.parent.members[entry.index].comma = node.commas[i] } } else if node.kind == .array { let all = try children(syntax) diff --git a/Sources/TOMLSemantics/PATCHES.md b/Sources/TOMLSemantics/PATCHES.md index 31332e5..7992b38 100644 --- a/Sources/TOMLSemantics/PATCHES.md +++ b/Sources/TOMLSemantics/PATCHES.md @@ -18,19 +18,27 @@ Local changes are limited to: reservation, recursive descent, token/trivia scans, key comparisons, lazy scalar decoding and ordered traversal. Original typed throws become ordinary throwing calls so budget and cancellation errors propagate without casts. + Dotted-key descent admits depth before recursion, cumulatively with enclosing + inline tables and arrays. - Exact decoded UTF-8 key comparison, including sampled-hash collisions. Unused key-transform and String-key Dictionary/Any access paths are removed. Keyed model types do not synthesize String equality. - Stable entry source positions for ordered typed traversal. Scalar syntax is classified before invoking its standard validator. Overflowing integers do not retry as floating point. Raw numeric lexemes and native atoms remain - separate from Core projection; finite decimal projection removes only TOML + separate from Core projection. Date/time atoms require one of the four valid + date/time/offset combinations. Finite decimal projection removes only TOML separators and a leading plus, with no floating-point formatting. - Actual EOF guards after fractional-time scanning and before the month/day - delimiter. No source terminator, sentinel or synthetic newline is appended. + delimiter. Multiline basic-string closing delimiters use backslash parity + with cooperative scan checks. No source terminator, sentinel or synthetic + newline is appended. - Required string helper budget propagation and quoted-key validation through the same standard validators. Decoder-specific date initializers and unused Foundation date conversion extensions are omitted with the decoder product. +- Inline-table closure is enforced while traversing ancestors. Static arrays + containing inline tables retain a distinct kind from declared arrays of + tables, so headers cannot extend them. - Repository Swift formatting. NativeDocuments owns the JSON syntax, source index, ownership expectations, diff --git a/Sources/TOMLSemantics/Parsing/Parser.swift b/Sources/TOMLSemantics/Parsing/Parser.swift index 8368cb7..462a042 100644 --- a/Sources/TOMLSemantics/Parsing/Parser.swift +++ b/Sources/TOMLSemantics/Parsing/Parser.swift @@ -255,7 +255,14 @@ struct Parser: ~Copyable { bytes[i + 2] == CodeUnits.doubleQuote { if i + 3 >= end || bytes[i + 3] != CodeUnits.doubleQuote { - if bytes[i - 1] == CodeUnits.backslash { + var backslashStart = i + while backslashStart > start + 3 + && bytes[backslashStart - 1] == CodeUnits.backslash + { + try budget.step() + backslashStart -= 1 + } + if (i - backslashStart) % 2 != 0 { i += 1 continue } @@ -809,8 +816,8 @@ struct Parser: ~Copyable { case .lbrace: // Nested table if keyArrays[arrayIndex].array.kind == nil { - keyArrays[arrayIndex].array.kind = .table - } else if keyArrays[arrayIndex].array.kind != .table { + keyArrays[arrayIndex].array.kind = .inlineTable + } else if keyArrays[arrayIndex].array.kind != .inlineTable { keyArrays[arrayIndex].array.kind = .mixed } @@ -887,8 +894,8 @@ struct Parser: ~Copyable { case .lbrace: // Nested table if arrays[arrayIndex].kind == nil { - arrays[arrayIndex].kind = .table - } else if arrays[arrayIndex].kind != .table { + arrays[arrayIndex].kind = .inlineTable + } else if arrays[arrayIndex].kind != .inlineTable { arrays[arrayIndex].kind = .mixed } @@ -929,6 +936,9 @@ struct Parser: ~Copyable { try nextToken(bytes: bytes, isDotSpecial: true) if token.kind == .dot { + try budget.enter(depth + 1) + depth += 1 + defer { depth -= 1 } let (subTableKey, subTableHash) = try normalizeKeyAndHash( bytes: bytes, token: key @@ -2605,8 +2615,15 @@ extension Parser { key: String, keyHash: Int ) throws { + if isKeyed ? keyTables[tableIndex].table.readOnly : tables[tableIndex].readOnly { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "cannot add to inline table")) + } switch try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) { case .table(let index): + guard !keyTables[index].table.readOnly else { + throw TOMLError( + .syntax(lineNumber: token.lineNumber, message: "cannot add to inline table")) + } tableIndex = index isKeyed = true case .array(let arrayIndex): diff --git a/Sources/TOMLSemantics/Parsing/TOMLDocument.swift b/Sources/TOMLSemantics/Parsing/TOMLDocument.swift index 54c07f7..142dc61 100644 --- a/Sources/TOMLSemantics/Parsing/TOMLDocument.swift +++ b/Sources/TOMLSemantics/Parsing/TOMLDocument.swift @@ -70,6 +70,7 @@ struct InternalTOMLArray: Equatable { case value case array case table + case inlineTable case mixed } } diff --git a/Sources/TOMLSemantics/SemanticDocument.swift b/Sources/TOMLSemantics/SemanticDocument.swift index eb46946..6586a1c 100644 --- a/Sources/TOMLSemantics/SemanticDocument.swift +++ b/Sources/TOMLSemantics/SemanticDocument.swift @@ -127,7 +127,14 @@ package struct SemanticDocument { decoded = try token.unpackBool(bytes: bytes, context: .super) ? "true" : "false" } else if colon || (token.text.count > 4 && bytes[token.text.lowerBound + 4] == 45) { kind = .dateTime - _ = try token.unpackDateTime(bytes: bytes, context: .super) + let components = try token.unpackDateTime(bytes: bytes, context: .super) + switch (components.date, components.time, components.offset) { + case (.some, .some, .some), (.some, .some, .none), (.some, .none, .none), + (.none, .some, .none): + break + default: + throw TOMLError(.invalidValueInTable(context: .super, lineNumber: token.lineNumber)) + } decoded = raw } else { // Base-prefixed integers can contain e/E hex digits. Classification precedes validation. diff --git a/Sources/TOMLSemantics/provenance.json b/Sources/TOMLSemantics/provenance.json index 8611de3..de272da 100644 --- a/Sources/TOMLSemantics/provenance.json +++ b/Sources/TOMLSemantics/provenance.json @@ -42,7 +42,7 @@ "patches": { "description": "PATCHES.md", "diff": "upstream.patch", - "sha256": "985f698f5bd81b42c08c478cfe8bfc93dcd9e05afd409caaa4400fffb42cd16c", + "sha256": "b7522712c6d4879493b89f84596452a6e2b2a2b2cc3cac7fa4a13ca1bdc6c986", "context_lines": 0 } } diff --git a/Sources/TOMLSemantics/upstream.patch b/Sources/TOMLSemantics/upstream.patch index b139941..4cf520b 100644 --- a/Sources/TOMLSemantics/upstream.patch +++ b/Sources/TOMLSemantics/upstream.patch @@ -1,5 +1,5 @@ --- Sources/TOMLDecoder/Parsing/Parser.swift -+++ Sources/TOMLSemantics/Parsing/Parser.swift ++++ Sources/TOMLDecoder/Parsing/Parser.swift @@ -2,31 +2,202 @@ - var token = Token.empty - var cursor = 0 @@ -234,7 +234,7 @@ + { + if i + 3 >= end || bytes[i + 3] != CodeUnits.singleQuote { + break -@@ -34,2 +205,58 @@ +@@ -34,2 +205,65 @@ - if token.kind == .newline { - try eatToken(bytes: bytes, kind: .newline, isDotSpecial: true) + } @@ -290,19 +290,26 @@ + bytes[i + 2] == CodeUnits.doubleQuote + { + if i + 3 >= end || bytes[i + 3] != CodeUnits.doubleQuote { -+ if bytes[i - 1] == CodeUnits.backslash { ++ var backslashStart = i ++ while backslashStart > start + 3 ++ && bytes[backslashStart - 1] == CodeUnits.backslash ++ { ++ try budget.step() ++ backslashStart -= 1 ++ } ++ if (i - backslashStart) % 2 != 0 { + i += 1 + continue + } + break -@@ -37,4 +264,2 @@ +@@ -37,4 +271,2 @@ - case .lbracket: - try parseSelect(bytes: bytes) - default: - throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) + } + i += 1 -@@ -42,15 +267,362 @@ +@@ -42,15 +274,362 @@ - } - } - @@ -680,7 +687,7 @@ + } + } + -@@ -58,87 +630,39 @@ +@@ -58,87 +637,39 @@ - let ch = bytes[position] - switch ch { - case CodeUnits.pound: @@ -807,9 +814,9 @@ + if c == CodeUnits.cr { + if position + 1 < count, bytes[position + 1] == CodeUnits.lf { + // CRLF ends comment -@@ -145,0 +670 @@ +@@ -145,0 +677 @@ + } -@@ -147,247 +672,4 @@ +@@ -147,247 +679,4 @@ - - func scanString(range: Range, lineNumber: Int) throws(TOMLError) { - let start = range.lowerBound @@ -1061,7 +1068,7 @@ + cursor = position + currentLineNumber = lineNumber + try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) -@@ -395,236 +677,5 @@ +@@ -395,236 +684,5 @@ - } - - emitToken(kind: .eof, start: position, end: count) @@ -1303,7 +1310,7 @@ + } + default: + // Found something else, stop skipping -@@ -634,10 +685,1078 @@ +@@ -634,10 +692,1081 @@ - } - - mutating func parseKeyedInlineTable(bytes: UnsafeBufferPointer, tableIndex: Int) throws(TOMLError) { @@ -1441,8 +1448,8 @@ + + case .lbrace: // Nested table + if keyArrays[arrayIndex].array.kind == nil { -+ keyArrays[arrayIndex].array.kind = .table -+ } else if keyArrays[arrayIndex].array.kind != .table { ++ keyArrays[arrayIndex].array.kind = .inlineTable ++ } else if keyArrays[arrayIndex].array.kind != .inlineTable { + keyArrays[arrayIndex].array.kind = .mixed + } + @@ -1519,8 +1526,8 @@ + + case .lbrace: // Nested table + if arrays[arrayIndex].kind == nil { -+ arrays[arrayIndex].kind = .table -+ } else if arrays[arrayIndex].kind != .table { ++ arrays[arrayIndex].kind = .inlineTable ++ } else if arrays[arrayIndex].kind != .inlineTable { + arrays[arrayIndex].kind = .mixed + } + @@ -1561,6 +1568,9 @@ + try nextToken(bytes: bytes, isDotSpecial: true) + + if token.kind == .dot { ++ try budget.enter(depth + 1) ++ depth += 1 ++ defer { depth -= 1 } + let (subTableKey, subTableHash) = try normalizeKeyAndHash( + bytes: bytes, + token: key @@ -2392,7 +2402,7 @@ + .invalidDateTime3(context: context, lineNumber: lineNumber, reason: reason)) + default: + throw tomlError -@@ -645,198 +1764,184 @@ +@@ -645,198 +1774,184 @@ - - if token.kind != .string, token.kind != .bareKey { - throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expect a string")) @@ -2775,7 +2785,7 @@ + lineNumber: 0, + message: + "basic multiline strings cannot contain more than 2 consecutive double quotes" -@@ -844,91 +1949,23 @@ +@@ -844,91 +1959,23 @@ - let subTableIndex: Int - - if let existingTableIndex = lookupTable(in: tableIndex, keyed: isKeyed, key: subTableKey, keyHash: subTableHash) { @@ -2890,7 +2900,7 @@ + try budget.step() + if characters.contains(bytes[index]) { + index += 1 -@@ -936,614 +1973,15 @@ +@@ -936,614 +1983,15 @@ - try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: true) - } - @@ -3520,7 +3530,7 @@ + index = try indexAfterSkippingCharacters( + start: index, endIndex: endIndex, + characters: [CodeUnits.space, CodeUnits.tab, CodeUnits.cr, CodeUnits.lf] -@@ -1551,69 +1989,5 @@ +@@ -1551,69 +1999,5 @@ - } - - func unpackAnyValue(bytes: UnsafeBufferPointer, context: TOMLKey) throws(TOMLError) -> Any { @@ -3595,7 +3605,7 @@ + } + + ch = bytes[index] -@@ -1621,64 +1995,12 @@ +@@ -1621,64 +2005,12 @@ - consumedLength += 1 - - guard @@ -3672,7 +3682,7 @@ + var ucs: UInt32 = 0 + for _ in 0.. 0, index < range.upperBound, bytes[index].isDecimalDigit { + result = 10 * result + Int(bytes[index]) - Int(CodeUnits.number0) -@@ -1830,9 +2092,47 @@ +@@ -1830,9 +2102,47 @@ - guard let month = scanDigits(bytes: bytes, range: index ..< range.upperBound, n: 2) else { - return nil - } @@ -3948,7 +3958,7 @@ + while index < range.upperBound, bytes[index].isDecimalDigit { + try budget.step() + result += Double(bytes[index] - CodeUnits.number0) * unit -@@ -1840,6 +2140,4 @@ +@@ -1840,6 +2150,4 @@ - guard let day = scanDigits(bytes: bytes, range: index ..< range.upperBound, n: 2) else { - return nil - } @@ -3959,7 +3969,7 @@ + } + updatedIndex = index + return UInt32(result) -@@ -1848,56 +2145,0 @@ +@@ -1848,56 +2155,0 @@ -func scanDigits(bytes: UnsafeBufferPointer, range: Range, n: Int) -> Int? { - var result = 0 - var n = n @@ -4016,7 +4026,7 @@ - return UInt32(result) -} - -@@ -1905,21 +2147,22 @@ +@@ -1905,21 +2157,22 @@ - var index = range.lowerBound - guard index < range.upperBound, bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus else { - return nil @@ -4060,7 +4070,7 @@ + } + index += 2 + return index -@@ -1930,12 +2173,12 @@ +@@ -1930,12 +2183,12 @@ - let ones: UInt64 = 0x0101_0101_0101_0101 - let highBits: UInt64 = 0x8080_8080_8080_8080 - @@ -4085,7 +4095,7 @@ + return hasByte(0x2222_2222_2222_2222) + || hasByte(0x5C5C_5C5C_5C5C_5C5C) + || hasByte(0x0A0A_0A0A_0A0A_0A0A) -@@ -1944,52 +2187,48 @@ +@@ -1944,52 +2197,48 @@ -func normalizeKeyAndHash(bytes: UnsafeBufferPointer, token: Token, keyTransform: (@Sendable (String) -> String)?) throws(TOMLError) -> (key: String, keyHash: Int) { - var start = token.text.lowerBound - var end = token.text.upperBound @@ -4186,7 +4196,7 @@ + + let key = try makeString(budget: budget, bytes: bytes, range: start.. UInt64 in - if buffer.count <= 8 { - return packedKeyHash(buffer) @@ -4258,7 +4268,7 @@ + count += 1 + } + return Int(truncatingIfNeeded: count <= 8 ? packed : hash) -@@ -2043,4 +2282,4 @@ +@@ -2043,4 +2292,4 @@ - let prefix = packedKeyHash(UnsafeBufferPointer(start: start, count: 8)) - let suffix = packedKeyHash(UnsafeBufferPointer(start: start.advanced(by: count - 8), count: 8)) - let rotatedSuffix = (suffix << 1) | (suffix >> 63) @@ -4267,7 +4277,7 @@ + let suffix = packedKeyHash(UnsafeBufferPointer(start: start.advanced(by: count - 8), count: 8)) + let rotatedSuffix = (suffix << 1) | (suffix >> 63) + return prefix ^ rotatedSuffix ^ (UInt64(truncatingIfNeeded: count) &* 0x9E37_79B1_85EB_CA87) -@@ -2051,25 +2290,342 @@ +@@ -2051,25 +2300,349 @@ - var packed: UInt64 = 0 - switch buffer.count { - case 8: @@ -4611,8 +4621,15 @@ + key: String, + keyHash: Int + ) throws { ++ if isKeyed ? keyTables[tableIndex].table.readOnly : tables[tableIndex].readOnly { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "cannot add to inline table")) ++ } + switch try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) { + case .table(let index): ++ guard !keyTables[index].table.readOnly else { ++ throw TOMLError( ++ .syntax(lineNumber: token.lineNumber, message: "cannot add to inline table")) ++ } + tableIndex = index + isKeyed = true + case .array(let arrayIndex): @@ -4635,7 +4652,7 @@ + isKeyed = false + case .keyValue: + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "key-value already exists")) -@@ -2077,3 +2633,46 @@ +@@ -2077,3 +2650,46 @@ - break - } - return packed @@ -4685,7 +4702,7 @@ + currentTable = tableIndex + currentTableIsKeyed = isKeyed + } -@@ -2081,316 +2679,0 @@ +@@ -2081,316 +2696,0 @@ - -@inline(__always) -private func makeString(bytes: UnsafeBufferPointer, range: Range) -> String { @@ -5003,7 +5020,7 @@ - } -} --- Sources/TOMLDecoder/Parsing/Parser+Finish.swift -+++ Sources/TOMLSemantics/Parsing/Parser+Finish.swift ++++ Sources/TOMLDecoder/Parsing/Parser+Finish.swift @@ -2,6 +2,6 @@ - consuming func finish(source: String) -> TOMLDocument { - var tables: [InternalTOMLTable] = [] @@ -5048,7 +5065,7 @@ + ) + } --- Sources/TOMLDecoder/Parsing/Token.swift -+++ Sources/TOMLSemantics/Parsing/Token.swift ++++ Sources/TOMLDecoder/Parsing/Token.swift @@ -2,13 +2,13 @@ - enum Kind: UInt8 { - case dot @@ -5183,7 +5200,7 @@ - } -} --- Sources/TOMLDecoder/Parsing/TOMLDocument.swift -+++ Sources/TOMLSemantics/Parsing/TOMLDocument.swift ++++ Sources/TOMLDecoder/Parsing/TOMLDocument.swift @@ -3,6 +3,6 @@ -struct TOMLDocument: Equatable, @unchecked Sendable { - let tables: [InternalTOMLTable] @@ -5273,7 +5290,7 @@ + } + } + } -@@ -32,20 +69,6 @@ +@@ -32,20 +69,7 @@ - do { - try source.utf8.withContiguousStorageIfAvailable { - hasContinousStorage = true @@ -5298,9 +5315,10 @@ + case value + case array + case table ++ case inlineTable + case mixed + } -@@ -54,45 +77,5 @@ +@@ -54,45 +78,5 @@ -struct InternalTOMLArray: Equatable, Sendable { - var kind: Kind? - var elements: [Element] @@ -5351,7 +5369,7 @@ + let keyHash: Int + let sourcePosition: Int + var table: InternalTOMLTable -@@ -101,4 +84,5 @@ +@@ -101,4 +85,5 @@ -struct KeyTablePair: Equatable { - let key: String - let keyHash: Int @@ -5361,7 +5379,7 @@ + let keyHash: Int + let sourcePosition: Int + var array: InternalTOMLArray -@@ -107,4 +91,5 @@ +@@ -107,4 +92,5 @@ -struct KeyArrayPair: Equatable { - let key: String - let keyHash: Int @@ -5371,7 +5389,7 @@ + let keyHash: Int + let sourcePosition: Int + var value: Token -@@ -113,5 +98,8 @@ +@@ -113,5 +99,8 @@ -struct KeyValuePair: Equatable { - let key: String - let keyHash: Int @@ -5385,7 +5403,7 @@ + var keyValues: [Int] = [] + var arrays: [Int] = [] + var tables: [Int] = [] -@@ -119,8 +107,4 @@ +@@ -119,8 +108,4 @@ -struct InternalTOMLTable: Equatable, Sendable { - var implicit: Bool = false - var readOnly: Bool = false @@ -5398,7 +5416,7 @@ + mutating func recordKeyHash(_ keyHash: Int) { + keyHashBloom |= keyHashBloomMask(keyHash) + } -@@ -128,4 +112,5 @@ +@@ -128,4 +113,5 @@ - @inline(__always) - mutating func recordKeyHash(_ keyHash: Int) { - keyHashBloom |= keyHashBloomMask(keyHash) @@ -5408,7 +5426,7 @@ + let mask = keyHashBloomMask(keyHash) + return (keyHashBloom & mask) == mask + } -@@ -133,48 +118,5 @@ +@@ -133,48 +119,5 @@ - @inline(__always) - func mightContainKeyHash(_ keyHash: Int) -> Bool { - let mask = keyHashBloomMask(keyHash) @@ -5462,7 +5480,7 @@ + case array(Int) + case table(Int) + } -@@ -185,4 +127,4 @@ +@@ -185,4 +128,4 @@ - let raw = UInt(bitPattern: keyHash) - let bit0 = UInt64(1) << UInt64(raw & 63) - let bit1 = UInt64(1) << UInt64((raw >> 6) & 63) @@ -5471,7 +5489,7 @@ + let bit0 = UInt64(1) << UInt64(raw & 63) + let bit1 = UInt64(1) << UInt64((raw >> 6) & 63) + return bit0 | bit1 -@@ -192,4 +134,4 @@ +@@ -192,4 +135,4 @@ - let date: LocalDate? - let time: LocalTime? - let offset: Int16? @@ -5480,7 +5498,7 @@ + let time: LocalTime? + let offset: Int16? + let features: OffsetDateTime.Features -@@ -197,10 +139,9 @@ +@@ -197,10 +140,9 @@ - @inline(__always) - func localDate(exactMatch: Bool = true) -> LocalDate? { - switch (date, time, offset) { @@ -5500,9 +5518,9 @@ + date + default: + nil -@@ -207,0 +149 @@ +@@ -207,0 +150 @@ + } -@@ -209,10 +151,9 @@ +@@ -209,10 +152,9 @@ - @inline(__always) - func localTime(exactMatch: Bool = true) -> LocalTime? { - switch (date, time, offset) { @@ -5522,9 +5540,9 @@ + time + default: + nil -@@ -219,0 +161 @@ +@@ -219,0 +162 @@ + } -@@ -221,10 +163,9 @@ +@@ -221,10 +164,9 @@ - @inline(__always) - func localDateTime(exactMatch: Bool = true) -> LocalDateTime? { - switch (date, time, offset) { @@ -5544,7 +5562,7 @@ + LocalDateTime(date: date, time: time) + default: + nil -@@ -232,41 +173 @@ +@@ -232,41 +174 @@ -} - -extension InternalTOMLTable { @@ -5587,7 +5605,7 @@ - return result - } + } -@@ -276,4 +177,4 @@ +@@ -276,4 +178,4 @@ - @inline(__always) - func table(at index: Int, keyed: Bool) -> InternalTOMLTable { - keyed ? keyTables[index].table : tables[index] @@ -5596,7 +5614,7 @@ + func table(at index: Int, keyed: Bool) -> InternalTOMLTable { + keyed ? keyTables[index].table : tables[index] + } -@@ -281,4 +182,4 @@ +@@ -281,4 +183,4 @@ - @inline(__always) - func array(at index: Int, keyed: Bool) -> InternalTOMLArray { - keyed ? keyArrays[index].array : arrays[index] @@ -5606,7 +5624,7 @@ + keyed ? keyArrays[index].array : arrays[index] + } --- Sources/TOMLDecoder/Parsing/Constants.swift -+++ Sources/TOMLSemantics/Parsing/Constants.swift ++++ Sources/TOMLDecoder/Parsing/Constants.swift @@ -2,22 +2,22 @@ - static let escape: UTF8.CodeUnit = 27 - static let equal: UTF8.CodeUnit = 61 @@ -5815,7 +5833,7 @@ + || CodeUnits.upperA <= self && self <= CodeUnits.upperF + } --- Sources/TOMLDecoder/DateTime.swift -+++ Sources/TOMLSemantics/DateTime.swift ++++ Sources/TOMLDecoder/DateTime.swift @@ -23,188 +23,183 @@ - /// The date component of the offset date-time. - public var date: LocalDate @@ -6640,7 +6658,7 @@ -} -#endif --- Sources/TOMLDecoder/TOMLKey.swift -+++ Sources/TOMLSemantics/TOMLKey.swift ++++ Sources/TOMLDecoder/TOMLKey.swift @@ -2,3 +2,3 @@ - case string(String) - case int(Int) @@ -6701,7 +6719,7 @@ - } + } --- Sources/TOMLDecoder/TOMLError.swift -+++ Sources/TOMLSemantics/TOMLError.swift ++++ Sources/TOMLDecoder/TOMLError.swift @@ -8 +8 @@ - let reason: Reason + let reason: Reason diff --git a/Tests/NativeDocumentsTests/NativeDocumentTests.swift b/Tests/NativeDocumentsTests/NativeDocumentTests.swift index 229b6f3..9efa9e1 100644 --- a/Tests/NativeDocumentsTests/NativeDocumentTests.swift +++ b/Tests/NativeDocumentsTests/NativeDocumentTests.swift @@ -265,6 +265,17 @@ let t1 = #""" #expect( try doc.prepare([.remove(region: keyRegion("b"), expected: owned(doc, keyRegion("b")))]).bytes != doc.bytes) + let populated = try document(#"{"owned":{"client":true}}"#, .json) + let populatedEvidence = try #require(try populated.read(object)) + do { + _ = try populated.prepare([ + .remove(region: object, expected: .createdContainer(populatedEvidence)) + ]) + Issue.record("creation evidence removed later children") + } catch NativeDocumentError.ownershipMismatch {} + #expect( + text(try populated.prepare([.remove(region: object, expected: .owned(populatedEvidence))])) + == "{}") let empty = try document("{\"owned\":{}}", .json) let observed = try #require(try empty.read(object)) #expect(throws: NativeDocumentError.self) { @@ -672,3 +683,60 @@ let t1 = #""" Issue.record("unowned value was adopted") } catch NativeDocumentError.ownershipMismatch {} } + +@Test(arguments: [false, true]) +func dottedInlineInsertionStaysWithinBraces(_ ownedParent: Bool) throws { + let source = "# keep\nx = { a.b = 1, z = 2 } # outside\n" + let doc = try document(source) + let region = keyRegion("x", "a", "c") + let edit: NativeRegionEdit + if ownedParent { + let parent = keyRegion("x", "a") + edit = .put( + region: parent, expected: try owned(doc, parent), + value: .object([ + "b": .integer(1), "c": .object(["d": .integer(2)]), + ])) + } else { + edit = .put(region: region, expected: .absent, value: .object(["d": .integer(2)])) + } + let change = try doc.prepare([edit]) + #expect(text(change) == "# keep\nx = { a.b = 1, z = 2, \"a\".\"c\" = {\"d\" = 2} } # outside\n") + let added = try NativeDocument(bytes: change.bytes, format: .toml, budget: generousBudget()) + #expect(try added.read(region)?.value == .object(["d": .integer(2)])) + let child = keyRegion("x", "a", "c", "d") + let update = try added.prepare([ + .put(region: child, expected: owned(added, child), value: .integer(3)) + ]) + #expect(text(update) == text(change).replacingOccurrences(of: "= 2}", with: "= 3}")) + let remove = try added.prepare([.remove(region: region, expected: owned(added, region))]) + #expect( + try NativeDocument(bytes: remove.bytes, format: .toml, budget: generousBudget()).read( + keyRegion("x"))?.value == .object(["a": .object(["b": .integer(1)]), "z": .integer(2)])) + #expect(text(remove).contains("a.b = 1, z = 2")) + #expect(text(remove).hasSuffix(" # outside\n")) +} + +@Test(arguments: invalidTOMLExtensionsAndTimes) +func invalidTOMLCannotBecomeReadOnly(_ source: String) throws { + do { + _ = try document(source) + Issue.record("invalid TOML admitted as a document") + } catch NativeDocumentError.invalidDocument {} +} + +@Test func tomlDELStringsAndKeysRoundTrip() throws { + let source = #"x="\u007F""# + let doc = try document(source) + let x = keyRegion("x") + #expect( + try doc.prepare([.put(region: x, expected: owned(doc, x), value: .string("\u{7f}"))]).bytes + == doc.bytes) + let key = "key\u{7f}" + let change = try doc.prepare([ + .put(region: keyRegion(key), expected: .absent, value: .string("value\u{7f}")) + ]) + #expect(!change.bytes.contains(127)) + let result = try NativeDocument(bytes: change.bytes, format: .toml, budget: generousBudget()) + #expect(try result.read(keyRegion(key))?.value == .string("value\u{7f}")) +} diff --git a/Tests/NativeDocumentsTests/SemanticTests.swift b/Tests/NativeDocumentsTests/SemanticTests.swift index 067d0c5..4b7e19a 100644 --- a/Tests/NativeDocumentsTests/SemanticTests.swift +++ b/Tests/NativeDocumentsTests/SemanticTests.swift @@ -1,4 +1,5 @@ import Foundation +import NativeDocuments import Testing @testable import TOMLSemantics @@ -68,3 +69,76 @@ func generousBudget() -> SemanticBudget { try SemanticDocument(source: "x={\na={\nb={\nc={\nd=1\n}\n}\n}\n}", budget: depth) } } + +let invalidTOMLExtensionsAndTimes = [ + "x={a.b=1,z=2}\n[x.a.c]\nd=2", + "x={a.b=1,z=2}\nx.a.c=2", + "x={a.b=1}\n[[x.a.c]]", + "a=[{}]\n[[a]]", + "x.a=[{}]\n[[x.a]]", + "a=[{id=1}]\n[[a]]", + "x=12:13:14Z", + "x=12:13:14+01:00", +] + +@Test(arguments: invalidTOMLExtensionsAndTimes) +func semanticRejectsClosedInlineStaticArrayAndInvalidTime(_ source: String) throws { + #expect(throws: TOMLError.self) { + try SemanticDocument(source: source, budget: generousBudget()) + } +} + +@Test(arguments: ["", "x={", "x={a={"]) +func dottedDescentAdmitsDepthBeforeParsing(_ prefix: String) throws { + let source = + prefix + String(repeating: "a.", count: 256) + "leaf=1" + + String(repeating: "}", count: prefix.filter { $0 == "{" }.count) + let budget = SemanticBudget( + limits: .init( + storage: 20_000_000, work: 20_000_000, nodes: 100_000, depth: 3, uninterruptedBytes: 1_000_000 + )) + var parser = Parser(budget: budget) + do { + try Array(source.utf8).withUnsafeBufferPointer { try parser.parse(bytes: $0) } + Issue.record("dotted descent bypassed caller depth before semantic traversal") + } catch SemanticBudget.Failure.exceeded(let stage) { + #expect(stage == "depth") + } +} + +@Test(arguments: [2, 4, 3]) +func multilineEOFBackslashParity(_ backslashes: Int) throws { + let source = + "x = " + String(repeating: "\"", count: 3) + String(repeating: "\\", count: backslashes) + + String(repeating: "\"", count: backslashes.isMultiple(of: 2) ? 3 : 4) + let doc = try SemanticDocument(source: source, budget: generousBudget()) + guard case .object(let entries) = doc.root, + case .scalar(kind: .string, let decoded, _, _) = entries[0].value + else { + Issue.record("missing decoded multiline value") + return + } + let expected = + String(repeating: "\\", count: backslashes / 2) + (backslashes.isMultiple(of: 2) ? "" : "\"") + #expect(decoded.utf8.elementsEqual(expected.utf8)) + let native = try document(source) + let region = keyRegion("x") + #expect(try native.read(region)?.value == .string(expected)) + #expect( + try native.prepare([ + .put(region: region, expected: owned(native, region), value: .string(expected)) + ]).bytes == native.bytes) +} + +@Test(arguments: ["1979-05-27", "12:13:14.1", "1979-05-27T07:32:00", "1979-05-27T07:32:00Z"]) +func dateTimeComponentKindsRetainLexemes(_ raw: String) throws { + let doc = try SemanticDocument(source: "x=" + raw, budget: generousBudget()) + guard case .object(let entries) = doc.root, + case .scalar(kind: .dateTime, let decoded, let lexeme, _) = entries[0].value + else { + Issue.record("missing native date/time atom") + return + } + #expect(decoded == raw) + #expect(lexeme == raw) +} From 4b2b44682a36e327ac2688e70fc76ad8374712d5 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:47:06 +0800 Subject: [PATCH 055/171] fix(core): limit container creation evidence to pruning --- Sources/NativeDocuments/Model.swift | 2 +- Sources/NativeDocuments/NativeDocument.swift | 10 ++++----- .../NativeDocumentTests.swift | 21 +++++++++++++++++++ 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/Sources/NativeDocuments/Model.swift b/Sources/NativeDocuments/Model.swift index ca26a63..24f4128 100644 --- a/Sources/NativeDocuments/Model.swift +++ b/Sources/NativeDocuments/Model.swift @@ -107,7 +107,7 @@ package struct NativeObservation { package enum NativeExpectedRegion { case absent case owned(NativeObservation) - /// The caller supplies creation evidence; only an empty, trivia-free container can be removed. + /// Creation evidence authorizes only empty, comment-safe pruning, never a put. case createdContainer(NativeObservation) } diff --git a/Sources/NativeDocuments/NativeDocument.swift b/Sources/NativeDocuments/NativeDocument.swift index fdfe971..c6d6ced 100644 --- a/Sources/NativeDocuments/NativeDocument.swift +++ b/Sources/NativeDocuments/NativeDocument.swift @@ -79,6 +79,11 @@ package struct NativeDocument { } } let existing = try resolve(edit.region, on: root) + if case .createdContainer = edit.expected { + guard case .remove = edit, let existing, existing.kind == .object, + existing.members.isEmpty + else { throw NativeDocumentError.ownershipMismatch(edit.region) } + } switch edit.expected { case .absent: guard existing == nil else { throw NativeDocumentError.ownershipMismatch(edit.region) } @@ -124,11 +129,6 @@ package struct NativeDocument { guard old != nil || desired != nil else { throw NativeDocumentError.ownershipMismatch(edit.region) } - if desired == nil, case .createdContainer = edit.expected { - guard let old, old.kind == .object, old.members.isEmpty else { - throw NativeDocumentError.ownershipMismatch(edit.region) - } - } if let old, desired == nil, old.kind == .object && old.members.isEmpty { guard case .createdContainer = edit.expected else { throw NativeDocumentError.ownershipMismatch(edit.region) diff --git a/Tests/NativeDocumentsTests/NativeDocumentTests.swift b/Tests/NativeDocumentsTests/NativeDocumentTests.swift index 9efa9e1..e10700d 100644 --- a/Tests/NativeDocumentsTests/NativeDocumentTests.swift +++ b/Tests/NativeDocumentsTests/NativeDocumentTests.swift @@ -276,8 +276,29 @@ let t1 = #""" #expect( text(try populated.prepare([.remove(region: object, expected: .owned(populatedEvidence))])) == "{}") + for value: NativeValue in [ + .object([:]), .string("replacement"), .object(["client": .boolean(true)]), + ] { + do { + _ = try populated.prepare([ + .put(region: object, expected: .createdContainer(populatedEvidence), value: value) + ]) + Issue.record("creation-only evidence authorized a put") + } catch NativeDocumentError.ownershipMismatch {} + } + #expect( + text( + try populated.prepare([ + .put(region: object, expected: .owned(populatedEvidence), value: .object([:])) + ])) == #"{"owned":{}}"#) let empty = try document("{\"owned\":{}}", .json) let observed = try #require(try empty.read(object)) + do { + _ = try empty.prepare([ + .put(region: object, expected: .createdContainer(observed), value: .object([:])) + ]) + Issue.record("creation-only evidence authorized an empty-container no-op put") + } catch NativeDocumentError.ownershipMismatch {} #expect(throws: NativeDocumentError.self) { try empty.prepare([.remove(region: object, expected: .owned(observed))]) } From 190d9b2c8443b873cf9d27069281aa4a402393fa Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:58:25 +0800 Subject: [PATCH 056/171] test(core): exercise concurrent readers with independent writers --- .../StateInspectionTests.swift | 19 ++++++- .../TransactionCostTests.swift | 57 ------------------- .../ReadOnlyInspectionTests.swift | 14 ++++- 3 files changed, 30 insertions(+), 60 deletions(-) diff --git a/Tests/AgentsCoreTests/StateInspectionTests.swift b/Tests/AgentsCoreTests/StateInspectionTests.swift index fef4417..12804c5 100644 --- a/Tests/AgentsCoreTests/StateInspectionTests.swift +++ b/Tests/AgentsCoreTests/StateInspectionTests.swift @@ -1,5 +1,6 @@ import AgentsManifest import Foundation +import Synchronization import Testing @testable import AgentsCore @@ -22,10 +23,24 @@ struct StateInspectionTests { let result = try store.withReadLock( onPendingRecovery: { diagnostics += 1 + let finished = DispatchSemaphore(value: 0) + let writer = Mutex<(recovery: Result, save: Result)?>(nil) + Thread.detachNewThread { + let recovery = Result { + try store.save(declaration: Declaration(agents: [.cursor]), resolved: ResolvedState()) + } + let save = Result { + try store.save(declaration: Declaration(agents: [.cursor]), resolved: ResolvedState()) + } + writer.withLock { $0 = (recovery, save) } + finished.signal() + } + finished.wait() + let outcome = try #require(writer.withLock { $0 }) #expect(throws: CoreError.transactionRecovered(store.directory.path)) { - try store.save(declaration: Declaration(agents: [.cursor]), resolved: ResolvedState()) + try outcome.recovery.get() } - try store.save(declaration: Declaration(agents: [.cursor]), resolved: ResolvedState()) + try outcome.save.get() if callbackThrows { throw CoreError.invalidState("pending inspection") } return "pending" }, diff --git a/Tests/AgentsCoreTests/TransactionCostTests.swift b/Tests/AgentsCoreTests/TransactionCostTests.swift index e256862..5b34375 100644 --- a/Tests/AgentsCoreTests/TransactionCostTests.swift +++ b/Tests/AgentsCoreTests/TransactionCostTests.swift @@ -7,41 +7,6 @@ import Testing @Suite("Transaction I/O cost") struct TransactionCostTests { - /// Every commit probes its device once; existing ancestry costs one barrier per component. - @Test func twoSmallFiles() throws { - let root = try temporaryDirectory() - defer { removeTemporaryDirectory(root) } - let store = StateStore( - scope: .project, - environment: RuntimeEnvironment(projectDirectory: root, homeDirectory: root, environment: [:]) - ) - try store.save(declaration: Declaration(), resolved: ResolvedState()) - let targets = ["AGENTS.md", "GEMINI.md"].map { root.appendingPathComponent($0) } - for target in targets { try Data("before".utf8).write(to: target) } - let ancestry = root.resolvingSymlinksInPath().pathComponents.count - 1 - for _ in 0..<2 { - let count = TransactionIOCount() - try store.withLock { - let transaction = FileTransaction(store: store) { step in - if TransactionCheckpoint.isJournalPublished(step) { count.persist() } - if step == TransactionCheckpoint.probe(0, .verified).name { count.probe() } - } - for target in targets { - try transaction.replace(target, with: .data(Data("after".utf8))) - } - try DirectoryHandle.$synchronizationObserver.withValue( - DirectoryHandle.SynchronizationObserver(didSynchronize: { count.sync() }) - ) { - try transaction.commit() - } - } - #expect(count.persists == 10) - #expect(count.probes == 1) - #expect(count.barriers - ancestry == 38) - for target in targets { #expect(try Data(contentsOf: target) == Data("after".utf8)) } - } - } - @Test func containersOnOneDeviceShareOneProbe() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } @@ -64,25 +29,3 @@ struct TransactionCostTests { #expect(!steps.contains(TransactionCheckpoint.probe(1, .firstCreated).name)) } } - -private final class TransactionIOCount: @unchecked Sendable { - private let lock = NSLock() - private(set) var persists = 0 - private(set) var barriers = 0 - private(set) var probes = 0 - func persist() { - lock.lock() - defer { lock.unlock() } - persists += 1 - } - func probe() { - lock.lock() - defer { lock.unlock() } - probes += 1 - } - func sync() { - lock.lock() - defer { lock.unlock() } - barriers += 1 - } -} diff --git a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift index bd1f17e..e2ad5cc 100644 --- a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift +++ b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift @@ -4,6 +4,7 @@ import AgentsSkills import CPlatform import Foundation import StateTestSupport +import Synchronization import Testing @testable import AgentsCore @@ -29,7 +30,18 @@ struct ReadOnlyInspectionTests { let skills = try store.readResolved().skills if reads == 1 { try #require(skills.isEmpty) - _ = try fixture.add(mode: .copy) + let options = AddOptions( + source: fixture.repo.path, alias: "fixture", agents: [.codex], mode: .copy, all: true, + environment: fixture.environment) + let finished = DispatchSemaphore(value: 0) + let writer = Mutex?>(nil) + Thread.detachNewThread { + let outcome = Result { _ = try SkillOperations.add(options) } + writer.withLock { $0 = outcome } + finished.signal() + } + finished.wait() + try #require(writer.withLock { $0 }).get() if bodyThrows { throw CoreError.invalidState("inconsistent inspection") } } else { let descriptor = open(lock.path, O_RDONLY | O_CLOEXEC) From d39a7e3ab61af3fcf95eed71b65886e7329f0791 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:18:24 +0800 Subject: [PATCH 057/171] fix(core): compose edits within TOML inline tables --- Sources/NativeDocuments/PatchBuilder.swift | 164 +++++++++++------- .../NativeDocumentTests.swift | 92 +++++++--- 2 files changed, 165 insertions(+), 91 deletions(-) diff --git a/Sources/NativeDocuments/PatchBuilder.swift b/Sources/NativeDocuments/PatchBuilder.swift index 01a369e..1e6a05c 100644 --- a/Sources/NativeDocuments/PatchBuilder.swift +++ b/Sources/NativeDocuments/PatchBuilder.swift @@ -6,9 +6,14 @@ struct BytePatch { } struct PatchBuilder { + struct InlineChange { + let container: Node + var additions: [String] + } let document: NativeDocument let region: NativeRegion var patches: [BytePatch] = [] + var inlineChanges: [InlineChange] = [] var budget: NativeDocumentBudget { document.budget } var toml: Bool { document.format == .toml } var newline: String { @@ -62,7 +67,7 @@ struct PatchBuilder { } } if toml, let container = old.inline ? old : old.enclosingInline { - try pruneInlineCommas(in: container) + try recordInlineChange(in: container) } else if old.inline && retained.count != old.members.count { let keepCommas = Set(retained.dropLast().compactMap { old.members[$0].comma?.lowerBound }) for m in old.members { @@ -112,7 +117,7 @@ struct PatchBuilder { throw NativeDocumentError.unsupportedEdit(.ambiguousTrivia, region, [entry]) } try patch(entry) - } else if toml && !parent.inline { + } else if toml && (!parent.inline || member.node.enclosingInline === parent) { try eraseTable(member.node) } else { throw NativeDocumentError.unsupportedEdit(.syntaxNotLocated, region, []) @@ -146,7 +151,7 @@ struct PatchBuilder { } try eraseMember(parent.members[i], parent: parent) if toml, let container = parent.inline ? parent : parent.enclosingInline { - try pruneInlineCommas(in: container) + try recordInlineChange(in: container) } else if parent.inline { if let comma = parent.members[i].comma { try patch(comma) @@ -194,6 +199,21 @@ struct PatchBuilder { } return surviving } + private mutating func recordInlineChange(in container: Node, additions: [String] = []) throws { + guard let range = container.range else { + throw NativeDocumentError.unsupportedEdit(.syntaxNotLocated, region, []) + } + for i in inlineChanges.indices { + try budget.step() + if inlineChanges[i].container.range == range { + try budget.allocate(additions.count, stage: "inline additions") + inlineChanges[i].additions.append(contentsOf: additions) + return + } + } + try budget.allocate(additions.count + 1, stage: "inline changes") + inlineChanges.append(InlineChange(container: container, additions: additions)) + } private mutating func pruneInlineCommas(in container: Node) throws { let surviving = try survivingInlineMembers(in: container) for entry in try container.inlineEntries(budget) { @@ -382,6 +402,68 @@ struct PatchBuilder { return String(decoding: prefix, as: UTF8.self) } + private mutating func insertInlinePieces( + _ pieces: [String], in parent: Node, surviving: [Member], remaining: Int + ) throws { + guard let at = parent.insertion else { + throw NativeDocumentError.unsupportedEdit(.syntaxNotLocated, region, []) + } + let first = + toml + ? try parent.inlineEntries(budget).first.map { $0.parent.members[$0.index] } + : parent.members.first + let multiline = parent.range.map { document.source[$0].contains(10) } ?? false + let last = surviving.last + let commaRemoved = + try last?.comma.map { comma in + try patches.contains { + try budget.step() + return $0.range == comma && $0.bytes.isEmpty + } + } ?? false + let hasComma = last?.comma != nil && !commaRemoved + if multiline, let closeIndent = try indentation(at: at) { + let nl = try newline + var indent = closeIndent + " " + if let entry = first?.entry, + let local = try indentation(at: entry.lowerBound) + { + indent = local + } + if let last, !hasComma, let entry = last.entry { + try patch(entry.upperBound.. lower + && (document.source[insertion - 1] == 9 || document.source[insertion - 1] == 32) + { + try budget.step() + insertion -= 1 + } + let text = try nativeJoin( + pieces, prefix: (remaining > 0 && !hasComma ? "," : "") + separator, suffix: "", + separator: "," + separator, budget: budget) + try patch(insertion.. lower - && (document.source[insertion - 1] == 9 || document.source[insertion - 1] == 32) - { - try budget.step() - insertion -= 1 - } - let text = try nativeJoin( - pieces, prefix: (remaining > 0 && !hasComma ? "," : "") + separator, suffix: "", - separator: "," + separator, budget: budget) - try patch(insertion.. Data { + mutating func apply() throws -> Data { + // Resolve each physical inline delta after all recursive entry removals are known. + for change in inlineChanges { + try pruneInlineCommas(in: change.container) + if !change.additions.isEmpty { + let surviving = try survivingInlineMembers(in: change.container) + try insertInlinePieces( + change.additions, in: change.container, surviving: surviving, remaining: surviving.count) + } + } // Coalesce repeated deletions but reject any other overlap before allocating a result. try budget.allocate(patches.count, stage: "patch order") var ordered = try patches.sorted { diff --git a/Tests/NativeDocumentsTests/NativeDocumentTests.swift b/Tests/NativeDocumentsTests/NativeDocumentTests.swift index e10700d..a35c146 100644 --- a/Tests/NativeDocumentsTests/NativeDocumentTests.swift +++ b/Tests/NativeDocumentsTests/NativeDocumentTests.swift @@ -705,37 +705,75 @@ let t1 = #""" } catch NativeDocumentError.ownershipMismatch {} } -@Test(arguments: [false, true]) -func dottedInlineInsertionStaysWithinBraces(_ ownedParent: Bool) throws { +@Test func dottedInlineInsertionStaysWithinBraces() throws { let source = "# keep\nx = { a.b = 1, z = 2 } # outside\n" let doc = try document(source) let region = keyRegion("x", "a", "c") - let edit: NativeRegionEdit - if ownedParent { - let parent = keyRegion("x", "a") - edit = .put( - region: parent, expected: try owned(doc, parent), - value: .object([ - "b": .integer(1), "c": .object(["d": .integer(2)]), - ])) - } else { - edit = .put(region: region, expected: .absent, value: .object(["d": .integer(2)])) - } - let change = try doc.prepare([edit]) - #expect(text(change) == "# keep\nx = { a.b = 1, z = 2, \"a\".\"c\" = {\"d\" = 2} } # outside\n") - let added = try NativeDocument(bytes: change.bytes, format: .toml, budget: generousBudget()) - #expect(try added.read(region)?.value == .object(["d": .integer(2)])) - let child = keyRegion("x", "a", "c", "d") - let update = try added.prepare([ - .put(region: child, expected: owned(added, child), value: .integer(3)) + for ownedParent in [false, true] { + let edit: NativeRegionEdit + if ownedParent { + let parent = keyRegion("x", "a") + edit = .put( + region: parent, expected: try owned(doc, parent), + value: .object([ + "b": .integer(1), "c": .object(["d": .integer(2)]), + ])) + } else { + edit = .put(region: region, expected: .absent, value: .object(["d": .integer(2)])) + } + let change = try doc.prepare([edit]) + #expect(text(change) == "# keep\nx = { a.b = 1, z = 2, \"a\".\"c\" = {\"d\" = 2} } # outside\n") + let added = try NativeDocument(bytes: change.bytes, format: .toml, budget: generousBudget()) + #expect(try added.read(region)?.value == .object(["d": .integer(2)])) + let child = keyRegion("x", "a", "c", "d") + let update = try added.prepare([ + .put(region: child, expected: owned(added, child), value: .integer(3)) + ]) + #expect(text(update) == text(change).replacingOccurrences(of: "= 2}", with: "= 3}")) + let remove = try added.prepare([.remove(region: region, expected: owned(added, region))]) + #expect( + try NativeDocument(bytes: remove.bytes, format: .toml, budget: generousBudget()).read( + keyRegion("x"))?.value == .object(["a": .object(["b": .integer(1)]), "z": .integer(2)])) + #expect(text(remove).contains("a.b = 1, z = 2")) + #expect(text(remove).hasSuffix(" # outside\n")) + } + let whole = keyRegion("x") + let desired: NativeValue = .object([ + "a": .object(["b": .integer(1), "c": .integer(3)]), "z": .integer(2), "extra": .integer(4), ]) - #expect(text(update) == text(change).replacingOccurrences(of: "= 2}", with: "= 3}")) - let remove = try added.prepare([.remove(region: region, expected: owned(added, region))]) - #expect( - try NativeDocument(bytes: remove.bytes, format: .toml, budget: generousBudget()).read( - keyRegion("x"))?.value == .object(["a": .object(["b": .integer(1)]), "z": .integer(2)])) - #expect(text(remove).contains("a.b = 1, z = 2")) - #expect(text(remove).hasSuffix(" # outside\n")) + let additions = NativeRegionEdit.put( + region: whole, expected: try owned(doc, whole), value: desired) + do { + let change = try doc.prepare([additions]) + #expect( + text(change) == "# keep\nx = { a.b = 1, z = 2, \"a\".\"c\" = 3, \"extra\" = 4 } # outside\n") + let checked = try NativeDocument(bytes: change.bytes, format: .toml, budget: generousBudget()) + #expect(try checked.read(whole)?.value == desired) + #expect(try doc.prepare([additions]).bytes == change.bytes) + } catch { + Issue.record(error) + } + do { + _ = try doc.prepare([ + additions, .put(region: region, expected: .absent, value: .integer(3)), + ]) + Issue.record("overlapping owned and child intents were accepted") + } catch NativeDocumentError.unsupportedEdit(.overlappingEdits, _, _) {} + let implicit = keyRegion("x", "a") + let removals: [NativeRegionEdit] = try [ + .remove(region: implicit, expected: owned(doc, implicit)), + .put(region: whole, expected: owned(doc, whole), value: .object(["z": .integer(2)])), + ] + for edit in removals { + do { + let change = try doc.prepare([edit]) + #expect(text(change) == source.replacingOccurrences(of: "a.b = 1,", with: "")) + let checked = try NativeDocument(bytes: change.bytes, format: .toml, budget: generousBudget()) + #expect(try checked.read(whole)?.value == .object(["z": .integer(2)])) + } catch { + Issue.record(error) + } + } } @Test(arguments: invalidTOMLExtensionsAndTimes) From d8a0d8ba6567719b5f632596f056208143d4e5f3 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:51:48 +0800 Subject: [PATCH 058/171] test(core): cover shared target races and orphan reservations --- Tests/AgentsCoreTests/SharedTargetTests.swift | 111 ++++++++++++++++++ 1 file changed, 111 insertions(+) diff --git a/Tests/AgentsCoreTests/SharedTargetTests.swift b/Tests/AgentsCoreTests/SharedTargetTests.swift index e6d1a85..bd3f4a2 100644 --- a/Tests/AgentsCoreTests/SharedTargetTests.swift +++ b/Tests/AgentsCoreTests/SharedTargetTests.swift @@ -109,6 +109,36 @@ struct SharedTargetTests { #expect(try Data(contentsOf: fixture.target) == Data("external trust change".utf8)) } + @Test(arguments: ["target", "ancestor"]) + func sharedPreparedWriteRejectsChangedAccess(_ changed: String) throws { + let fixture = try SharedFixture() + try fixture.install() + let targetBytes = try Data(contentsOf: fixture.target) + let receiptURL = try fixture.receiptURL() + let receipt = try Data(contentsOf: receiptURL) + let changedURL = changed == "target" ? fixture.target : fixture.config + var original = stat() + try #require(stat(changedURL.path, &original) == 0) + defer { _ = chmod(changedURL.path, original.st_mode & 0o7777) } + try fixture.b.withLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.b.nativeTarget(for: .claudeMCPLocal) + let prepared = try fixture.b.preparePrivateMaterialization( + target, requiringReceiptForExistingTarget: true) + let transaction = FileTransaction(store: fixture.b) + try transaction.replace( + target.url, with: .data(Data("secret sibling; changed region".utf8)), + expecting: prepared.evidence) + let externalMode: mode_t = changed == "target" ? 0o644 : 0o777 + try #require(chmod(changedURL.path, externalMode) == 0) + #expect(throws: CoreError.self) { try transaction.commit() } + var actual = stat() + try #require(stat(changedURL.path, &actual) == 0) + #expect(actual.st_mode & 0o7777 == externalMode) + #expect(try Data(contentsOf: fixture.target) == targetBytes) + #expect(try Data(contentsOf: receiptURL) == receipt) + } + } + @Test(arguments: [ "journal.preparing.created.written", "journal.preparing.created.renamed", "shared.0.reservation.created", @@ -239,6 +269,56 @@ struct SharedTargetTests { } } + @Test(arguments: [false, true]) + func aliasedWritersSerializeAcrossReplacementAndBothMakeProgress(_ reverse: Bool) throws { + let fixture = try SharedFixture() + try fixture.install() + let other = fixture.b.environment.projectDirectory + try FileManager.default.createDirectory( + at: other.appendingPathComponent("old-data"), withIntermediateDirectories: true) + try Data("ordinary before".utf8).write(to: other.appendingPathComponent("old-data/AGENTS.md")) + let firstRoot = reverse ? other : fixture.root + let secondRoot = reverse ? fixture.root : other + let firstConfig = reverse ? fixture.root.appendingPathComponent("config-alias") : fixture.config + let secondConfig = + reverse ? fixture.config : fixture.root.appendingPathComponent("config-alias") + let holder = try stateTestProcess( + root: firstRoot, + arguments: ["shared-edit", "publish.0.exchanged", "--shared-config", firstConfig.path]) + defer { terminateProcess(holder) } + try ProcessWait.marker( + firstRoot.appendingPathComponent("ready"), child: holder, root: firstRoot) + try ProcessWait.stopped(holder, root: firstRoot) + let published = try Data(contentsOf: fixture.target) + #expect(published == Data("secret sibling; edited region".utf8)) + let waiter = try stateTestProcess( + root: secondRoot, + arguments: ["shared-edit", "shared.0.lock.contended", "--shared-config", secondConfig.path]) + defer { terminateProcess(waiter) } + try ProcessWait.marker( + secondRoot.appendingPathComponent("ready"), child: waiter, root: secondRoot) + try ProcessWait.stopped(waiter, root: secondRoot) + #expect(try Data(contentsOf: fixture.target) == published) + try #require(kill(holder.processIdentifier, SIGCONT) == 0) + try ProcessWait.exit(holder, root: firstRoot) + #expect(holder.terminationStatus == 0) + let firstGeneration = try fixture.a.withReadLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.a.nativeTarget(for: .claudeMCPLocal) + let receipt = try fixture.a.materializationReceipt(for: target) + return try #require(receipt).generation + } + try #require(kill(waiter.processIdentifier, SIGCONT) == 0) + try ProcessWait.exit(waiter, root: secondRoot) + #expect(waiter.terminationStatus == 0) + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.a.nativeTarget(for: .claudeMCPLocal) + let after = try fixture.a.preparePrivateMaterialization( + target, requiringReceiptForExistingTarget: true) + #expect(after.receiptGeneration != firstGeneration) + #expect(try Data(contentsOf: target.url) == published) + } + } + @Test(arguments: ["shared-skill-recover", "shared-watch-recover", "shared-instruction-recover"]) func ordinaryMutationEntrypointsRecoverPendingSharedFootprints(_ command: String) throws { let fixture = try SharedFixture() @@ -533,6 +613,37 @@ struct SharedTargetTests { #expect(try fixture.journal(fixture.a).id == journal.id) } + @Test func orphanedForeignReservationRemainsPending() throws { + let fixture = try SharedFixture() + try fixture.install() + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "shared.ready"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let journal = try fixture.journal(fixture.a) + let journalURL = fixture.a.directory.appendingPathComponent("transaction.json") + let reservationURL = try fixture.receiptURL().deletingLastPathComponent() + .appendingPathComponent("reservation") + let reservation = try Data(contentsOf: reservationURL) + let target = try FileSnapshot.read(at: fixture.target) + try FileManager.default.removeItem(at: journalURL) + var calls = 0 + var message = "" + do { + try fixture.b.withLock(footprint: [.claudeMCPLocal]) { calls += 1 } + } catch CoreError.recoveryPending(let value) { + message = value + } + #expect(message.contains(fixture.a.directory.path)) + #expect(message.contains(journal.id.uuidString)) + #expect(calls == 0) + #expect(try Data(contentsOf: reservationURL) == reservation) + #expect(try FileSnapshot.read(at: fixture.target) == target) + #expect(!FileManager.default.fileExists(atPath: journalURL.path)) + } + @Test(arguments: [false, true], [false, true]) func readOnlyAdmissionRechecksSuccessfulAndFailedUnlockedSharedReads( _ metadataExists: Bool, _ throwFirst: Bool From e2283312ce6123a0a55000eb8da40b978e0785a9 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:57:55 +0800 Subject: [PATCH 059/171] test(core): expose scope lock contention through checkpoints --- Sources/AgentsCore/StateStore.swift | 64 +++++++++++++++-------------- 1 file changed, 33 insertions(+), 31 deletions(-) diff --git a/Sources/AgentsCore/StateStore.swift b/Sources/AgentsCore/StateStore.swift index ca27dfd..4d3f04f 100644 --- a/Sources/AgentsCore/StateStore.swift +++ b/Sources/AgentsCore/StateStore.swift @@ -115,40 +115,42 @@ public struct StateStore: Sendable { let base = scope == .project ? environment.projectDirectory : environment.homeDirectory let physicalDirectory = base.resolvingSymlinksInPath().appendingPathComponent( directory.lastPathComponent) - return try FileLock.withDescriptor(at: physicalDirectory.appendingPathComponent(".agents.lock")) - { descriptor in - guard let context = TransactionLockContext.current(self), - let scopeDirectory = try openDirectoryIfPresent() - else { - throw CoreError.invalidState("missing scope lock admission") - } - try context.bindScope(scopeDirectory, descriptor: descriptor) - try verifyCoordinationAdmission() - let recovered = try FileTransaction.recover( - store: self, outcome: outcome, checkpoint: checkpoint) - _ = try readWatch() - let cache = SourceCache(store: self, checkpoint: checkpoint) - let referencesRecovered = try cache.recoverWatchReferences() - if recovered || referencesRecovered { - throw CoreError.transactionRecovered(directory.path) - } - let result: T - do { - result = try body() - } catch { - // A handled failure can finish rollback now. A killed process leaves the marker - // for the next access, which must recover the journal before releasing any ref. + return try FileLock.withDescriptor( + at: physicalDirectory.appendingPathComponent(".agents.lock"), + checkpoint: { try checkpoint("scope." + $0) }, + { descriptor in + guard let context = TransactionLockContext.current(self), + let scopeDirectory = try openDirectoryIfPresent() + else { + throw CoreError.invalidState("missing scope lock admission") + } + try context.bindScope(scopeDirectory, descriptor: descriptor) + try verifyCoordinationAdmission() + let recovered = try FileTransaction.recover( + store: self, outcome: outcome, checkpoint: checkpoint) + _ = try readWatch() + let cache = SourceCache(store: self, checkpoint: checkpoint) + let referencesRecovered = try cache.recoverWatchReferences() + if recovered || referencesRecovered { + throw CoreError.transactionRecovered(directory.path) + } + let result: T do { - _ = try FileTransaction.recover(store: self, outcome: outcome) - _ = try SourceCache(store: self).recoverWatchReferences() + result = try body() } catch { - outcome?.disposition = .recoveryRequired + // A handled failure can finish rollback now. A killed process leaves the marker + // for the next access, which must recover the journal before releasing any ref. + do { + _ = try FileTransaction.recover(store: self, outcome: outcome) + _ = try SourceCache(store: self).recoverWatchReferences() + } catch { + outcome?.disposition = .recoveryRequired + } + throw error } - throw error - } - _ = try cache.recoverWatchReferences() - return result - } + _ = try cache.recoverWatchReferences() + return result + }) } /// Only the supplied scope root may resolve through links; state and cache ancestry may not. From 5c0d12b6c7b52ff33fbc9d894461a29334e364dc Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:06:37 +0800 Subject: [PATCH 060/171] test(core): verify pending journal footprint readmission --- Tests/AgentsCoreTests/SharedTargetTests.swift | 87 +++++++++++++++++++ .../PrivateMaterializationProbe.swift | 24 +++++ Tests/StateTestProcess/main.swift | 7 +- 3 files changed, 117 insertions(+), 1 deletion(-) diff --git a/Tests/AgentsCoreTests/SharedTargetTests.swift b/Tests/AgentsCoreTests/SharedTargetTests.swift index bd3f4a2..d301c0f 100644 --- a/Tests/AgentsCoreTests/SharedTargetTests.swift +++ b/Tests/AgentsCoreTests/SharedTargetTests.swift @@ -319,6 +319,93 @@ struct SharedTargetTests { } } + @Test func pendingFootprintReadmitsBeforeCallbackOrProvider() throws { + let fixture = try SharedFixture() + try fixture.install() + let original = try Data(contentsOf: fixture.target) + let receipt = try Data(contentsOf: fixture.receiptURL()) + let marker = fixture.root.appendingPathComponent("ready") + let nextStop = fixture.root.appendingPathComponent("stop-at") + let journal = fixture.a.directory.appendingPathComponent("transaction.json") + let holder = try stateTestProcess( + root: fixture.root, arguments: ["shared-readmission-writer", "shared.beforeJournal"]) + defer { terminateProcess(holder) } + try ProcessWait.marker(marker, child: holder, root: fixture.root) + try ProcessWait.stopped(holder, root: fixture.root) + #expect(!FileManager.default.fileExists(atPath: journal.path)) + try FileManager.default.removeItem(at: marker) + let waiter = try stateTestProcess( + root: fixture.root, arguments: ["shared-admission-wait", "scope-contention"]) + defer { terminateProcess(waiter) } + try ProcessWait.marker(marker, child: waiter, root: fixture.root) + try ProcessWait.stopped(waiter, root: fixture.root) + let contention = try String(contentsOf: marker, encoding: .utf8) + #expect(contention.hasPrefix("scope.lock.") && contention.hasSuffix(".contended")) + #expect(!FileManager.default.fileExists(atPath: journal.path)) + try FileManager.default.removeItem(at: marker) + try Data("entry.0.applied".utf8).write(to: nextStop) + try #require(kill(holder.processIdentifier, SIGCONT) == 0) + try ProcessWait.marker(marker, child: holder, root: fixture.root) + try ProcessWait.stopped(holder, root: fixture.root) + #expect(FileManager.default.fileExists(atPath: journal.path)) + #expect(try Data(contentsOf: fixture.target) != original) + terminateProcess(holder) + + let other = fixture.b.environment.projectDirectory + let lock = try fixture.receiptURL().deletingLastPathComponent().appendingPathComponent("lock") + let blocker = try stateTestProcess( + root: other, arguments: ["shared-hold-lock", "shared.rawLocked", "--lock-path", lock.path]) + defer { terminateProcess(blocker) } + try ProcessWait.marker(other.appendingPathComponent("ready"), child: blocker, root: other) + try ProcessWait.stopped(blocker, root: other) + try FileManager.default.removeItem(at: marker) + try Data("shared.0.lock.contended".utf8).write(to: nextStop) + try #require(kill(waiter.processIdentifier, SIGCONT) == 0) + try ProcessWait.marker(marker, child: waiter, root: fixture.root) + try ProcessWait.stopped(waiter, root: fixture.root) + #expect(try String(contentsOf: marker, encoding: .utf8) == "shared.0.lock.contended") + #expect(FileManager.default.fileExists(atPath: journal.path)) + #expect( + !FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("admission-body").path)) + #expect( + !FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("provider-called").path)) + try #require(kill(blocker.processIdentifier, SIGCONT) == 0) + try ProcessWait.exit(blocker, root: other) + #expect(blocker.terminationStatus == 0) + try #require(kill(waiter.processIdentifier, SIGCONT) == 0) + try ProcessWait.exit(waiter, root: fixture.root) + #expect(waiter.terminationStatus == 0) + #expect( + FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("admission-recovered").path)) + #expect( + !FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("admission-body").path)) + #expect( + !FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("provider-called").path)) + #expect(!FileManager.default.fileExists(atPath: journal.path)) + #expect(try Data(contentsOf: fixture.target) == original) + #expect(try Data(contentsOf: fixture.receiptURL()) == receipt) + + let provider = SharedBindings() + var callbacks = 0 + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + callbacks += 1 + let target = try fixture.a.nativeTarget(for: .claudeMCPLocal) + let prepared = try fixture.a.preparePrivateMaterialization( + target, requiringReceiptForExistingTarget: true) + let transaction = FileTransaction(store: fixture.a) + try transaction.replacePrivate(prepared, bindings: ["secret"], provider: provider) { + try $0.value(for: "secret") + } + try transaction.commit() + } + #expect(callbacks == 1 && provider.calls == 1) + } + @Test(arguments: ["shared-skill-recover", "shared-watch-recover", "shared-instruction-recover"]) func ordinaryMutationEntrypointsRecoverPendingSharedFootprints(_ command: String) throws { let fixture = try SharedFixture() diff --git a/Tests/StateTestProcess/PrivateMaterializationProbe.swift b/Tests/StateTestProcess/PrivateMaterializationProbe.swift index 139b0d3..f7194b0 100644 --- a/Tests/StateTestProcess/PrivateMaterializationProbe.swift +++ b/Tests/StateTestProcess/PrivateMaterializationProbe.swift @@ -35,6 +35,29 @@ private struct ProbeBindings: RuntimeBindingProvider { func sharedMaterializationProbe( _ command: String, store: StateStore, checkpoint: @escaping (String) throws -> Void ) throws { + if command == "shared-admission-wait" { + do { + try store.withLock(checkpoint: checkpoint) { + try Data().write( + to: store.environment.projectDirectory.appendingPathComponent("admission-body")) + _ = try ProbeBindings(root: store.environment.projectDirectory).value( + for: "value", environment: store.environment) + } + } catch CoreError.transactionRecovered { + try Data().write( + to: store.environment.projectDirectory.appendingPathComponent("admission-recovered")) + } + return + } + if command == "shared-hold-lock" { + guard let index = CommandLine.arguments.firstIndex(of: "--lock-path"), + CommandLine.arguments.indices.contains(index + 1) + else { throw CoreError.invalidState("missing test lock path") } + try FileLock.withLock(at: URL(fileURLWithPath: CommandLine.arguments[index + 1])) { + try checkpoint("shared.rawLocked") + } + return + } if command == "shared-skill-recover" { do { _ = try SkillOperations.remove(skillNames: ["absent"], environment: store.environment) @@ -62,6 +85,7 @@ func sharedMaterializationProbe( try checkpoint("shared.locked") return } + if command == "shared-readmission-writer" { try checkpoint("shared.beforeJournal") } let target = try store.nativeTarget(for: .claudeMCPLocal) let transaction = FileTransaction(store: store, checkpoint: checkpoint) if command == "shared-delete" { diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 4a4d695..88a54a6 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -33,7 +33,12 @@ let trace = try FileHandle(forWritingTo: traceURL) /// point ambiguous, so the recorder fails the run. Each command runs one recorded operation. func stop(_ point: String, marker: String = "ready") throws { let (repeated, shouldStop) = checkpointState.withLock { state in - (!state.seen.insert(point).inserted, point == state.requested) + ( + !state.seen.insert(point).inserted, + point == state.requested + || (state.requested == "scope-contention" && point.hasPrefix("scope.") + && FileLock.isContentionCheckpoint(point)) + ) } try trace.write(contentsOf: Data((point + "\n").utf8)) if repeated { fatalError("repeated checkpoint: \(point)") } From a20ccd7399a779779d9c97a54a5f84d95a74dd1b Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:20:47 +0800 Subject: [PATCH 061/171] feat(components): render pinned native MCP configurations --- Documentation/Architecture/Package.md | 2 +- Package.swift | 4 +- .../Components/Adapters/ClaudeAdapter.swift | 25 + .../Components/Adapters/CodexAdapter.swift | 67 ++ .../Components/Adapters/CursorAdapter.swift | 22 + .../Components/Adapters/GeminiAdapter.swift | 27 + .../Components/Adapters/OpenCodeAdapter.swift | 36 ++ Sources/Components/CapabilityRegistry.swift | 140 ++++ Sources/Components/LedgerReplay.swift | 2 +- Sources/Components/MCPLayoutV1.swift | 186 ++++++ Sources/Components/MCPLowering.swift | 401 ++++++++++++ Tests/ComponentsTests/NativeMCPTests.swift | 606 ++++++++++++++++++ 12 files changed, 1515 insertions(+), 3 deletions(-) create mode 100644 Sources/Components/Adapters/ClaudeAdapter.swift create mode 100644 Sources/Components/Adapters/CodexAdapter.swift create mode 100644 Sources/Components/Adapters/CursorAdapter.swift create mode 100644 Sources/Components/Adapters/GeminiAdapter.swift create mode 100644 Sources/Components/Adapters/OpenCodeAdapter.swift create mode 100644 Sources/Components/CapabilityRegistry.swift create mode 100644 Sources/Components/MCPLayoutV1.swift create mode 100644 Sources/Components/MCPLowering.swift create mode 100644 Tests/ComponentsTests/NativeMCPTests.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 2505c18..4db7929 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -13,7 +13,7 @@ terminal/UI presentation and executable distribution. AgentsManifest → AgentsCore, TreeSitterYAML, TreeSitter, Yams AgentsSkills → AgentsCore, AgentsManifest, Yams AgentsInstructions → AgentsCore, AgentsManifest, Markdown -Components → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions +Components → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, NativeDocuments AgentsUpdates → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions NativeDocuments → AgentsCore, TOMLSemantics, TreeSitterTOML, TreeSitter TOMLSemantics → Foundation diff --git a/Package.swift b/Package.swift index b0f6fd2..abc8b5c 100644 --- a/Package.swift +++ b/Package.swift @@ -67,7 +67,9 @@ let package = Package( ]), .target( name: "Components", - dependencies: ["AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions"]), + dependencies: [ + "AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions", "NativeDocuments", + ]), .testTarget( name: "ComponentsTests", dependencies: [ diff --git a/Sources/Components/Adapters/ClaudeAdapter.swift b/Sources/Components/Adapters/ClaudeAdapter.swift new file mode 100644 index 0000000..3c5be31 --- /dev/null +++ b/Sources/Components/Adapters/ClaudeAdapter.swift @@ -0,0 +1,25 @@ +import AgentsCore + +/// Claude's local audience is a project even though Core routes it to the shared global file. +enum ClaudeAdapter { + static func mcp(_ input: MCPInput) throws -> MCPEntry { + var entry = MCPEntry(input) + switch input.transport { + case .stdio(let run): + try input.rejectWorkingDirectory(run) + entry.fields["type"] = .init("stdio") + try entry.command(run) + try entry.bindings(run.environment, field: "env", reference: .claude) + case .streamableHTTP(let url, let headers): + entry.fields["type"] = .init("http") + try entry.url(url) + try entry.bindings(headers, field: "headers", reference: .claude) + case .sse(let url, let headers): + entry.fields["type"] = .init("sse") + try entry.url(url) + try entry.bindings(headers, field: "headers", reference: .claude) + } + try entry.nativeFields([:]) + return entry + } +} diff --git a/Sources/Components/Adapters/CodexAdapter.swift b/Sources/Components/Adapters/CodexAdapter.swift new file mode 100644 index 0000000..db3e4f2 --- /dev/null +++ b/Sources/Components/Adapters/CodexAdapter.swift @@ -0,0 +1,67 @@ +import AgentsCore + +/// Codex env_vars forwards the same variable name; it is not an environment rename operation. +enum CodexAdapter { + static func mcp(_ input: MCPInput) throws -> MCPEntry { + var entry = MCPEntry(input) + switch input.transport { + case .stdio(let run): + try entry.command(run) + try entry.workingDirectory(run) + var forwarded: [LedgerValue] = [] + var environment: [String: LedgerValue] = [:] + for (key, binding) in run.environment.sorted(by: { $0.key < $1.key }) { + if case .environment(let source) = binding, source == key { + try input.environmentName(source, field: ["transport", "environment", key]) + entry.placements.append( + .init( + path: [.key("env_vars"), .index(forwarded.count)], binding: binding, reference: true)) + forwarded.append(.init(source)) + } else { + environment[key] = try entry.binding( + binding, path: [.key("env"), .key(key)], reference: nil) + } + } + if !environment.isEmpty { entry.fields["env"] = .init(object: environment) } + if !forwarded.isEmpty { entry.fields["env_vars"] = .init(array: forwarded) } + case .streamableHTTP(let url, let headers): + try entry.url(url) + var literal: [String: LedgerValue] = [:] + var references: [String: LedgerValue] = [:] + for (key, binding) in headers.sorted(by: { $0.key < $1.key }) { + if case .environment(let name) = binding { + try input.environmentName(name, field: ["transport", "headers", key]) + references[key] = .init(name) + entry.placements.append( + .init(path: [.key("env_http_headers"), .key(key)], binding: binding, reference: true)) + } else { + literal[key] = try entry.binding( + binding, path: [.key("http_headers"), .key(key)], reference: nil) + } + } + if !literal.isEmpty { entry.fields["http_headers"] = .init(object: literal) } + if !references.isEmpty { entry.fields["env_http_headers"] = .init(object: references) } + case .sse: + throw input.issue( + ["transport", "kind"], .unsupported, + "the pinned Codex transport enum has no legacy SSE variant") + } + var rules: [String: MCPNativeField] = [ + "enabled": .boolean, "required": .boolean, + "startup_timeout_sec": .nonnegativeNumber, "tool_timeout_sec": .nonnegativeNumber, + ] + if case .streamableHTTP = input.transport { rules["bearer_token_env_var"] = .environmentName } + try entry.nativeFields(rules) + if input.native["bearer_token_env_var"] != nil { + let hasAuthorization = ["http_headers", "env_http_headers"].contains { field in + entry.fields[field]?.object?.keys.contains { $0.lowercased() == "authorization" } == true + } + guard !hasAuthorization else { + throw input.issue( + ["native", "bearer_token_env_var"], .invalid, + "bearer token and explicit Authorization header overlap") + } + } + return entry + } +} diff --git a/Sources/Components/Adapters/CursorAdapter.swift b/Sources/Components/Adapters/CursorAdapter.swift new file mode 100644 index 0000000..a48c5df --- /dev/null +++ b/Sources/Components/Adapters/CursorAdapter.swift @@ -0,0 +1,22 @@ +import AgentsCore + +/// The documented MCP shape is shared by IDE/CLI; surface acceptance remains separate. +enum CursorAdapter { + static func mcp(_ input: MCPInput) throws -> MCPEntry { + var entry = MCPEntry(input) + switch input.transport { + case .stdio(let run): + try input.rejectWorkingDirectory(run) + entry.fields["type"] = .init("stdio") + try entry.command(run) + // Captured documentation establishes interpolation fields but not its exact token grammar. + try entry.bindings(run.environment, field: "env", reference: nil) + case .streamableHTTP, .sse: + throw input.issue( + ["transport", "kind"], .unverified, + "captured Cursor documentation does not fix an explicit remote transport selector") + } + try entry.nativeFields([:]) + return entry + } +} diff --git a/Sources/Components/Adapters/GeminiAdapter.swift b/Sources/Components/Adapters/GeminiAdapter.swift new file mode 100644 index 0000000..4f7be98 --- /dev/null +++ b/Sources/Components/Adapters/GeminiAdapter.swift @@ -0,0 +1,27 @@ +import AgentsCore + +/// Explicit type with url fixes transport; httpUrl is a deprecated Streamable HTTP field. +enum GeminiAdapter { + static func mcp(_ input: MCPInput) throws -> MCPEntry { + var entry = MCPEntry(input) + switch input.transport { + case .stdio(let run): + try entry.command(run) + try entry.workingDirectory(run) + try entry.bindings(run.environment, field: "env", reference: .gemini) + case .streamableHTTP(let url, let headers): + entry.fields["type"] = .init("http") + try entry.url(url) + try entry.bindings(headers, field: "headers", reference: .gemini) + case .sse(let url, let headers): + entry.fields["type"] = .init("sse") + try entry.url(url) + try entry.bindings(headers, field: "headers", reference: .gemini) + } + try entry.nativeFields([ + "timeout": .positiveNumber, "description": .string, + "includeTools": .strings, "excludeTools": .strings, + ]) + return entry + } +} diff --git a/Sources/Components/Adapters/OpenCodeAdapter.swift b/Sources/Components/Adapters/OpenCodeAdapter.swift new file mode 100644 index 0000000..b6039ce --- /dev/null +++ b/Sources/Components/Adapters/OpenCodeAdapter.swift @@ -0,0 +1,36 @@ +import AgentsCore + +/// OpenCode 2 remote is Streamable HTTP. protocol selects MCP negotiation, not transport. +enum OpenCodeAdapter { + static func mcp(_ input: MCPInput) throws -> MCPEntry { + try input.literal(input.name, field: ["name"]) + var entry = MCPEntry(input) + switch input.transport { + case .stdio(let run): + entry.fields["type"] = .init("local") + try entry.command(run, argv: true) + try entry.workingDirectory(run) + try entry.bindings(run.environment, field: "environment", reference: .openCode) + case .streamableHTTP(let url, let headers): + entry.fields["type"] = .init("remote") + try entry.url(url) + try entry.bindings(headers, field: "headers", reference: .openCode) + case .sse: + throw input.issue( + ["transport", "kind"], .unsupported, + "the pinned remote client constructs StreamableHTTPClientTransport only") + } + var rules: [String: MCPNativeField] = [ + "disabled": .boolean, "codemode": .boolean, "pool": .boolean, + "protocol": .oneOf(["legacy", "auto", "2026-07-28"]), + "timeout": .positiveIntegerObject(["startup", "catalog", "execution"]), + ] + if case .streamableHTTP = input.transport { rules["oauth"] = .falseOnly } + try entry.nativeFields(rules) + if case .streamableHTTP = input.transport, entry.fields["codemode"] == nil { + // The native default rewrites the endpoint with a codemode query parameter. + entry.fields["codemode"] = .init(boolean: false) + } + return entry + } +} diff --git a/Sources/Components/CapabilityRegistry.swift b/Sources/Components/CapabilityRegistry.swift new file mode 100644 index 0000000..bd8f379 --- /dev/null +++ b/Sources/Components/CapabilityRegistry.swift @@ -0,0 +1,140 @@ +import AgentsCore +import NativeDocuments + +/// Surfaces with independently evidenced loading contracts. Marketing names do not select one. +package enum NativeClientSurface: String, CaseIterable, Sendable { + case claudeCode, codexCLI, geminiCLI, openCodeCLI, cursorEditor, cursorCLI, cursorCloud + + package var agent: AgentID { + switch self { + case .claudeCode: .claudeCode + case .codexCLI: .codex + case .geminiCLI: .geminiCLI + case .openCodeCLI: .opencode + case .cursorEditor, .cursorCLI, .cursorCloud: .cursor + } + } +} + +package enum NativeMCPScope: String, CaseIterable, Sendable { case project, local, user } + +package struct NativeMCPRequest: Equatable, Sendable { + package let surface: NativeClientSurface + package let scope: NativeMCPScope + + package init(surface: NativeClientSurface, scope: NativeMCPScope) { + self.surface = surface + self.scope = scope + } +} + +/// Schema evidence is separate from runtime acceptance of a particular deployed candidate. +package struct NativeSchemaEvidence: Equatable, Sendable { + package let revision: String + package let sources: [String] +} + +package struct NativeMCPDescriptor { + package let request: NativeMCPRequest + package let format: String + package let documentFormat: NativeDocumentFormat + package let evidence: NativeSchemaEvidence + package var knownReaders: Set { [request.surface.agent] } + + /// Core supplies the native canonical project key; it is not a machine path saved in layout. + package func region(server: String, nativeProjectKey: String? = nil) throws -> NativeRegion { + var keys: [String] + switch request.surface { + case .codexCLI: keys = ["mcp_servers"] + case .openCodeCLI: keys = ["mcp", "servers"] + case .claudeCode where request.scope == .local: + guard let nativeProjectKey, nativeProjectKey.hasPrefix("/"), !nativeProjectKey.contains("\0") + else { + throw NativeAdapterIssue( + request: request, component: server, field: ["region", "nativeProjectKey"], + reason: .integrationRequired, detail: "Core must supply the native canonical project key") + } + keys = ["projects", nativeProjectKey, "mcpServers"] + default: keys = ["mcpServers"] + } + return NativeRegion(keys: keys + [server]) + } + +} + +package struct NativeAdapterIssue: Error, Equatable, CustomStringConvertible { + package enum Reason: String, Sendable { + case invalid, unsupported, unverified, integrationRequired + } + package let request: NativeMCPRequest + package let component: String + package let field: [String] + package let reason: Reason + package let detail: String + + package var description: String { + "\(request.surface.rawValue)/mcpServer/\(component)/\(request.scope.rawValue) " + + "\(field.joined(separator: ".")): \(reason.rawValue) (\(detail))." + } +} + +package enum CapabilityRegistry { + package static func mcp( + _ request: NativeMCPRequest, component: String + ) throws -> NativeMCPDescriptor { + func issue(_ field: String, _ detail: String) -> NativeAdapterIssue { + .init( + request: request, component: component, field: [field], reason: .unverified, detail: detail) + } + if request.surface == .cursorCloud { + throw issue("surface", "Cloud MCP configuration loading needs separate evidence") + } + if request.scope == .local && request.surface != .claudeCode { + throw issue("scope", "a separate local MCP scope is not established by this schema evidence") + } + let name: String + let document: NativeDocumentFormat + let evidence: NativeSchemaEvidence + switch request.surface { + case .claudeCode: + name = "claude" + document = .json + evidence = .init( + revision: "installed:2.1.309", + sources: ["claude-mcp-routes.json", "https://code.claude.com/docs/en/mcp"]) + case .codexCLI: + name = "codex" + document = .toml + evidence = .init( + revision: "092d3acd6bec3e3a14bdc7e7a2810ab628ab759d", + sources: ["codex-rs/config/src/config_toml.rs", "codex-rs/config/src/mcp_types.rs"]) + case .geminiCLI: + name = "gemini" + document = .jsonc(trailingCommas: false) + evidence = .init( + revision: "5a5c7180ff3f0a02511f54b54db7f228d4982a30", + sources: [ + "packages/core/src/config/config.ts", "packages/cli/src/config/settings.ts", + "packages/cli/src/utils/envVarResolver.ts", + ]) + case .openCodeCLI: + name = "opencode" + document = .jsonc(trailingCommas: true) + evidence = .init( + revision: "fedc6f208aa2bd54c1019227214568083f6380ad", + sources: [ + "packages/schema/src/mcp.ts", "packages/schema/src/config/mcp.ts", + "packages/core/src/mcp/client.ts", "packages/core/src/config/variable.ts", + ]) + case .cursorEditor, .cursorCLI, .cursorCloud: + name = "cursor" + document = .json + evidence = .init( + revision: "sha256:f5e70852d7122b56fd3136b3659dfc1d430ab363f763431f617839fdea8df7d4", + sources: ["https://cursor.com/docs/mcp", "https://cursor.com/docs/cli/using"]) + } + return .init( + request: request, format: "agents/\(name)-mcp@1", documentFormat: document, + evidence: evidence) + } +} diff --git a/Sources/Components/LedgerReplay.swift b/Sources/Components/LedgerReplay.swift index f8f1a9d..ab79806 100644 --- a/Sources/Components/LedgerReplay.swift +++ b/Sources/Components/LedgerReplay.swift @@ -76,7 +76,7 @@ package enum LedgerReplay { "agents/instructions@1": { try instructions($0, $1, $2, outputBytes: outputBytes) }, "agents/claude-import@1": { try forwarding($0, $1, $2, outputBytes: outputBytes) }, "agents/chatgpt@1": { try chatGPT($0, $1, $2, outputBytes: outputBytes) }, - ] + ].merging(MCPLayoutV1.renderers) { existing, _ in existing } } package static func withReplay( diff --git a/Sources/Components/MCPLayoutV1.swift b/Sources/Components/MCPLayoutV1.swift new file mode 100644 index 0000000..0731128 --- /dev/null +++ b/Sources/Components/MCPLayoutV1.swift @@ -0,0 +1,186 @@ +import AgentsCore +import Foundation + +/// Version 1 stores regional intentions, references and exact resource identities. Its renderer +/// does not choose a route, expand a binding or turn temporary replay trees into native paths. +/// The owned-values artifact is the complete region-intention envelope, so its digest also pins +/// targeting and binding placement. E decodes it to a contribution before native preparation. +package enum MCPLayoutV1 { + static var renderers: [String: LedgerRenderer] { + [ + "agents/claude-mcp@1": render, + "agents/codex-mcp@1": render, + "agents/gemini-mcp@1": render, + "agents/opencode-mcp@1": render, + "agents/cursor-mcp@1": render, + ] + } + + package static func contribution( + _ lowering: LockedLowering, ledger: ResolvedLedger + ) throws -> NativeMCPContribution { + func invalid() -> CoreError { .invalidState("invalid version 1 MCP layout") } + try lowering.layout.validate() + guard let layout = lowering.layout.object, + Set(layout.keys) == [ + "artifact", "surface", "scope", "component", "name", "value", "occurrences", + "recipients", "knownReaders", "bindings", "resourcePlacements", + ], + let surfaceText = string(layout["surface"]), + let surface = NativeClientSurface(rawValue: surfaceText), + let scopeText = string(layout["scope"]), let scope = NativeMCPScope(rawValue: scopeText), + let name = string(layout["name"]), !name.isEmpty, + let component = string(layout["component"]), lowering.inputs == [component], + let record = ledger.components[component], record.name == name, record.kind == "mcpServer", + record.recipients.contains(surface.agent), lowering.resources == record.resources, + let value = layout["value"], value.kind == .object, + let artifact = string(layout["artifact"]), !artifact.isEmpty, + layout["occurrences"]?.kind == .array, let occurrenceValues = layout["occurrences"]?.array, + layout["bindings"]?.kind == .array, let bindingValues = layout["bindings"]?.array, + layout["resourcePlacements"]?.kind == .array, + let resourceValues = layout["resourcePlacements"]?.array + else { throw invalid() } + let descriptor = try CapabilityRegistry.mcp( + .init(surface: surface, scope: scope), component: name) + guard lowering.format == descriptor.format, + layout["recipients"] == LedgerPayload.strings([surface.agent.rawValue]), + layout["knownReaders"] + == LedgerPayload.strings(descriptor.knownReaders.map(\.rawValue).sorted()) + else { throw invalid() } + let occurrences = try occurrenceValues.map { value in + guard value.kind == .integer, let id = value.integer else { throw invalid() } + return id + } + guard !occurrences.isEmpty, + Set(occurrences).count == occurrences.count, + occurrences + == ledger.occurrences.filter({ + $0.component == component && occurrences.contains($0.id) + }).map(\.id) + else { throw invalid() } + let bindings: [MCPBindingPlacement] = try bindingValues.map { item in + guard let fields = item.object, Set(fields.keys) == ["path", "binding", "reference"], + let encoded = fields["binding"], let name = encoded.text, + fields["reference"]?.kind == .boolean, let reference = fields["reference"]?.boolean + else { throw invalid() } + let binding: RuntimeBinding + switch encoded.kind { + case .environment: binding = .environment(name) + case .secret where !reference: binding = .secret(name) + default: throw invalid() + } + let steps = try steps(fields["path"]) + let slot = try at(steps, in: value) + if reference { + guard MCPReferenceSyntax.isName(name) + else { + throw invalid() + } + let expected: LedgerValue + switch surface { + case .claudeCode: expected = .init(MCPReferenceSyntax.claude.render(name)) + case .geminiCLI: expected = .init(MCPReferenceSyntax.gemini.render(name)) + case .openCodeCLI: expected = .init(MCPReferenceSyntax.openCode.render(name)) + case .codexCLI: expected = .init(name) + case .cursorEditor, .cursorCLI, .cursorCloud: throw invalid() + } + guard slot == expected else { throw invalid() } + } else { + guard slot == encoded else { throw invalid() } + } + return .init(path: steps, binding: binding, reference: reference) + } + let resourcePlacements: [MCPResourcePlacement] = try resourceValues.map { item in + guard let fields = item.object, Set(fields.keys) == ["path", "resource"], + let resource = string(fields["resource"]), lowering.resources.contains(resource) + else { throw invalid() } + let steps = try steps(fields["path"]) + guard try at(steps, in: value) == .init(object: ["resource": .init(resource)]) else { + throw invalid() + } + return .init(path: steps, resource: resource) + } + var paths: [[MCPValueStep]] = [] + for path in bindings.map(\.path) + resourcePlacements.map(\.path) { + guard !paths.contains(where: { $0.starts(with: path) || path.starts(with: $0) }) else { + throw invalid() + } + paths.append(path) + } + return .init( + descriptor: descriptor, component: component, name: name, occurrences: occurrences, + recipients: [surface.agent], bindings: bindings, resourcePlacements: resourcePlacements, + value: value, resources: lowering.resources) + } + + static func path(_ path: [MCPValueStep]) -> LedgerValue { + .init( + array: path.map { step in + switch step { + case .key(let key): .init(object: ["key": .init(key)]) + case .index(let index): .init(object: ["index": .init(integer: index)]) + } + }) + } + + static func binding(_ binding: RuntimeBinding) -> LedgerValue { + switch binding { + case .literal(let value): .init(value, kind: .literal) + case .environment(let name): .init(name, kind: .environment) + case .secret(let name): .init(name, kind: .secret) + } + } + + private static func string(_ value: LedgerValue?) -> String? { + value?.kind == .string ? value?.text : nil + } + + private static func steps(_ value: LedgerValue?) throws -> [MCPValueStep] { + guard value?.kind == .array, let array = value?.array, !array.isEmpty else { + throw CoreError.invalidState("invalid MCP slot path") + } + return try array.map { item in + guard let object = item.object, object.count == 1 else { + throw CoreError.invalidState("invalid MCP slot step") + } + if let key = string(object["key"]) { return .key(key) } + if let index = object["index"], index.kind == .integer, let i = index.integer, i >= 0 { + return .index(i) + } + throw CoreError.invalidState("invalid MCP slot step") + } + } + + private static func at(_ path: [MCPValueStep], in root: LedgerValue) throws -> LedgerValue { + var value = root + for step in path { + switch step { + case .key(let key): + guard let next = value.object?[key] else { + throw CoreError.invalidState("missing MCP slot") + } + value = next + case .index(let index): + guard let array = value.array, array.indices.contains(index) else { + throw CoreError.invalidState("missing MCP slot") + } + value = array[index] + } + } + return value + } + + private static func render( + _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL] + ) throws -> [ReplayedArtifact] { + _ = try contribution(lowering, ledger: ledger) + guard lowering.resources.allSatisfy({ resources[$0] != nil }) else { + throw CoreError.invalidState("missing frozen MCP resource") + } + return [ + .init( + name: lowering.layout.object!["artifact"]!.text!, kind: .ownedValues, + values: lowering.layout) + ] + } +} diff --git a/Sources/Components/MCPLowering.swift b/Sources/Components/MCPLowering.swift new file mode 100644 index 0000000..8d46f0f --- /dev/null +++ b/Sources/Components/MCPLowering.swift @@ -0,0 +1,401 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// Slots are relative to one server value, never to an arbitrary physical document. +package enum MCPValueStep: Equatable, Sendable { + case key(String) + case index(Int) +} + +package struct MCPBindingPlacement: Equatable, Sendable { + package let path: [MCPValueStep] + package let binding: RuntimeBinding + /// A reference needs the downstream client's environment, not the applying process's value. + package let reference: Bool +} + +package struct MCPResourcePlacement: Equatable, Sendable { + package let path: [MCPValueStep] + package let resource: String +} + +/// One logical contribution. E combines physical documents and establishes regional ownership. +package struct NativeMCPContribution { + package let descriptor: NativeMCPDescriptor + package let component: String + package let name: String + package let occurrences: [Int] + /// Intended readers of this region. The complete producer targeting stays on its ledger owner. + package let recipients: [AgentID] + package let bindings: [MCPBindingPlacement] + package let resourcePlacements: [MCPResourcePlacement] + package let value: LedgerValue + package let resources: [String] + + /// Produces reference-safe native values. Literal binding and final resource placement are + /// deliberately deferred to E's staged render using Core's sole provider/publication policy. + package func referenceValue() throws -> NativeValue { + if let binding = bindings.first(where: { !$0.reference }) { + throw issue(binding.path.fields, "staged binding through Core is required") + } + if let resource = resourcePlacements.first { + throw issue(resource.path.fields, "E must place this frozen resource before staged rendering") + } + return try nativeValue(value) + } + + package func lowering( + id: String, artifact: String, platform: DeclarationPlatform, deployments: [String] = [] + ) -> LockedLowering { + .init( + id: id, format: descriptor.format, inputs: [component], resources: resources, + deployments: deployments, + layout: .init(object: [ + "artifact": .init(artifact), "surface": .init(descriptor.request.surface.rawValue), + "scope": .init(descriptor.request.scope.rawValue), + "component": .init(component), "name": .init(name), "value": value, + "occurrences": .init(array: occurrences.map { .init(integer: $0) }), + "recipients": LedgerPayload.strings(recipients.map(\.rawValue)), + "knownReaders": LedgerPayload.strings( + descriptor.knownReaders.map(\.rawValue).sorted()), + "bindings": .init( + array: bindings.map { placement in + .init(object: [ + "path": MCPLayoutV1.path(placement.path), + "binding": MCPLayoutV1.binding(placement.binding), + "reference": .init(boolean: placement.reference), + ]) + }), + "resourcePlacements": .init( + array: resourcePlacements.map { placement in + .init(object: [ + "path": MCPLayoutV1.path(placement.path), "resource": .init(placement.resource), + ]) + }), + ]), platform: platform.rawValue, artifacts: []) + } + + private func issue(_ field: [String], _ detail: String) -> NativeAdapterIssue { + .init( + request: descriptor.request, component: name, field: field, + reason: .integrationRequired, detail: detail) + } + + private func nativeValue(_ value: LedgerValue) throws -> NativeValue { + switch value.kind { + case .string, .literal: return .string(value.text!) + case .integer: return .integer(value.integer!) + case .decimal: return .decimal(value.text!) + case .boolean: return .boolean(value.boolean!) + case .null: return .null + case .array: return .array(try value.array!.map(nativeValue)) + case .object: return .object(try value.object!.mapValues(nativeValue)) + case .environment, .secret: + throw issue(["value"], "staged binding through Core is required") + } + } +} + +package enum NativeMCPLowering { + /// The frozen occurrence graph connects the linked identity to its exact durable component. + /// Call once per requested recipient; this method never aggregates equal native values. + package static func lower( + _ linked: LinkedComponent, frozen ledger: ResolvedLedger, request: NativeMCPRequest + ) throws -> NativeMCPContribution { + let descriptor = try CapabilityRegistry.mcp(request, component: linked.key.name) + func invalid(_ detail: String) -> NativeAdapterIssue { + .init( + request: request, component: linked.key.name, field: ["component"], reason: .invalid, + detail: detail) + } + guard linked.recipients.contains(request.surface.agent), + case .declaration(let declaration) = linked.payload, + case .mcpServer(let name, let transport, _, _, let native) = declaration + else { throw invalid("the linked component does not target this MCP recipient") } + let ids = Set(linked.origins.map(\.occurrence)) + let occurrences = ledger.occurrences.filter { ids.contains($0.id) } + let owners = Set(occurrences.map(\.component)) + guard !ids.isEmpty, occurrences.count == ids.count, owners.count == 1, + let id = owners.first, let record = ledger.components[id], + record.kind == DeclaredComponentKind.mcpServer.rawValue, record.name == name, + record.root == linked.key.root, record.group == linked.key.group, + record.payload == (try LedgerPayload.component(declaration)), + record.conditions == linked.conditions.map(LedgerCondition.init), + Set(record.recipients) == linked.recipients, + record.resources.count == linked.resources.count + else { throw invalid("linked component and frozen occurrence graph do not match") } + for (origin, frozen) in zip(linked.origins, occurrences) { + let audience: InstallScope = request.scope == .user ? .user : .project + guard origin.occurrence == frozen.id, origin.reference == frozen.reference, + origin.condition.scopes?.contains(audience) ?? true, + origin.condition.agents?.contains(request.surface.agent) ?? true, + origin.provenance.relativePath == frozen.manifestPath, + origin.recipients.contains(request.surface.agent), + Set(origin.recipients) == Set(frozen.recipients), + origin.consumerEditable == frozen.consumerEditable + else { throw invalid("linked origin and frozen occurrence do not match") } + } + for (resource, frozen) in zip(linked.resources, record.resources) { + guard let item = ledger.resources[frozen], item.path == resource.path, + item.hash == resource.hash + else { throw invalid("linked resource and frozen evidence do not match") } + } + let input = MCPInput( + descriptor: descriptor, name: name, transport: transport, + native: native[request.surface.agent.rawValue] ?? [:], resources: record.resources) + let entry: MCPEntry + switch request.surface { + case .claudeCode: entry = try ClaudeAdapter.mcp(input) + case .codexCLI: entry = try CodexAdapter.mcp(input) + case .geminiCLI: entry = try GeminiAdapter.mcp(input) + case .openCodeCLI: entry = try OpenCodeAdapter.mcp(input) + case .cursorEditor, .cursorCLI, .cursorCloud: entry = try CursorAdapter.mcp(input) + } + return .init( + descriptor: descriptor, component: id, name: name, occurrences: occurrences.map(\.id), + recipients: [request.surface.agent], bindings: entry.placements, + resourcePlacements: entry.resourcePlacements, value: .init(object: entry.fields), + resources: record.resources) + } +} + +struct MCPInput { + let descriptor: NativeMCPDescriptor + let name: String + let transport: MCPTransportDeclaration + let native: [String: NativeValue] + let resources: [String] + + func issue(_ field: [String], _ reason: NativeAdapterIssue.Reason, _ detail: String) + -> NativeAdapterIssue + { + .init( + request: descriptor.request, component: name, field: field, reason: reason, detail: detail) + } + + func rejectWorkingDirectory(_ run: ExecutableDeclaration) throws { + guard run.workingDirectory == nil else { + throw issue( + ["transport", "workingDirectory"], .unverified, + "this client contract does not establish an MCP working-directory field") + } + } + + func environmentName(_ name: String, field: [String]) throws { + guard MCPReferenceSyntax.isName(name) + else { throw issue(field, .invalid, "native environment reference needs a variable name") } + } + + func literal(_ value: String, field: [String]) throws { + guard !value.contains("\0") else { throw issue(field, .invalid, "NUL is not a native string") } + let interpolates: Bool + switch descriptor.request.surface { + case .claudeCode: interpolates = value.contains("${") + case .geminiCLI: + interpolates = value.range(of: #"\$(?:\w|\{)"#, options: .regularExpression) != nil + case .openCodeCLI: interpolates = value.contains("{env:") || value.contains("{file:") + case .cursorEditor, .cursorCLI, .cursorCloud: interpolates = value.contains("${") + case .codexCLI: interpolates = false + } + guard !interpolates else { + throw issue( + field, .unverified, "literal preservation across native interpolation needs evidence") + } + } +} + +enum MCPReferenceSyntax { + case claude, gemini, openCode + static func isName(_ name: String) -> Bool { + let bytes = Array(name.utf8) + guard let first = bytes.first, + first == 95 || (65...90).contains(first) || (97...122).contains(first) + else { return false } + return bytes.allSatisfy { + $0 == 95 || (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) + } + } + + func render(_ name: String) -> String { + switch self { + case .claude, .gemini: "${" + name + "}" + case .openCode: "{env:" + name + "}" + } + } +} + +enum MCPNativeField { + case boolean, falseOnly, string, strings, positiveNumber, nonnegativeNumber, environmentName + case oneOf(Set) + case positiveIntegerObject(Set) + + func accepts(_ value: NativeValue) -> Bool { + switch (self, value) { + case (.boolean, .boolean): true + case (.falseOnly, .boolean(false)): true + case (.string, .string), (.environmentName, .string): true + case (.strings, .array(let array)): + array.allSatisfy { if case .string = $0 { true } else { false } } + case (.nonnegativeNumber, .integer(let number)): number >= 0 + case (.nonnegativeNumber, .decimal(let number)): + Double(number).map { $0.isFinite && $0 >= 0 } ?? false + case (.positiveNumber, .integer(let number)): number > 0 + case (.positiveNumber, .decimal(let number)): + Double(number).map { $0.isFinite && $0 > 0 } ?? false + case (.oneOf(let allowed), .string(let text)): allowed.contains(text) + case (.positiveIntegerObject(let allowed), .object(let object)): + object.allSatisfy { key, value in + allowed.contains(key) && { if case .integer(let i) = value { i > 0 } else { false } }() + } + default: false + } + } +} + +struct MCPEntry { + let input: MCPInput + var fields: [String: LedgerValue] = [:] + var placements: [MCPBindingPlacement] = [] + var resourcePlacements: [MCPResourcePlacement] = [] + init(_ input: MCPInput) { self.input = input } + + mutating func command(_ run: ExecutableDeclaration, argv: Bool = false) throws { + guard !run.executable.isEmpty else { + throw input.issue(["transport", "executable"], .invalid, "executable must not be empty") + } + let executable: LedgerValue + if run.executable.contains("/") { + guard let id = input.resources.first else { + throw input.issue( + ["transport", "executable"], .invalid, "missing frozen executable resource") + } + let path: [MCPValueStep] = argv ? [.key("command"), .index(0)] : [.key("command")] + executable = .init(object: ["resource": .init(id)]) + resourcePlacements.append(.init(path: path, resource: id)) + } else { + try input.literal(run.executable, field: ["transport", "executable"]) + executable = .init(run.executable) + } + for (index, argument) in run.arguments.enumerated() { + try input.literal(argument, field: ["transport", "arguments", String(index)]) + } + if argv { + fields["command"] = .init(array: [executable] + run.arguments.map { .init($0) }) + } else { + fields["command"] = executable + fields["args"] = LedgerPayload.strings(run.arguments) + } + } + + mutating func workingDirectory(_ run: ExecutableDeclaration) throws { + guard run.workingDirectory != nil else { return } + let index = run.executable.contains("/") ? 1 : 0 + guard index < input.resources.count else { + throw input.issue( + ["transport", "workingDirectory"], .invalid, "missing frozen directory resource") + } + let id = input.resources[index] + fields["cwd"] = .init(object: ["resource": .init(id)]) + resourcePlacements.append(.init(path: [.key("cwd")], resource: id)) + } + + mutating func url(_ url: String) throws { + guard let parsed = URL(string: url), ["http", "https"].contains(parsed.scheme), + parsed.host?.isEmpty == false, parsed.user == nil, parsed.password == nil + else { + throw input.issue(["transport", "url"], .invalid, "a credential-free HTTP URL is required") + } + try input.literal(url, field: ["transport", "url"]) + fields["url"] = .init(url) + } + + mutating func bindings( + _ bindings: [String: RuntimeBinding], field: String, reference: MCPReferenceSyntax? + ) throws { + if bindings.isEmpty { return } + var values: [String: LedgerValue] = [:] + for (key, value) in bindings.sorted(by: { $0.key < $1.key }) { + values[key] = try binding(value, path: [.key(field), .key(key)], reference: reference) + } + fields[field] = .init(object: values) + } + + mutating func binding( + _ binding: RuntimeBinding, path: [MCPValueStep], reference: MCPReferenceSyntax? + ) throws -> LedgerValue { + if input.descriptor.request.surface == .openCodeCLI, case .key(let key) = path.last { + try input.literal(key, field: path.fields + ["key"]) + } + switch binding { + case .literal(let text): + try input.literal(text, field: path.fields) + return .init(text) + case .environment(let name): + try input.environmentName(name, field: path.fields) + placements.append(.init(path: path, binding: binding, reference: reference != nil)) + return reference.map { .init($0.render(name)) } ?? .init(name, kind: .environment) + case .secret(let name): + placements.append(.init(path: path, binding: binding, reference: false)) + return .init(name, kind: .secret) + } + } + + mutating func nativeFields(_ rules: [String: MCPNativeField]) throws { + for (key, value) in input.native.sorted(by: { $0.key < $1.key }) { + let path = ["native", input.descriptor.request.surface.agent.rawValue, key] + guard fields[key] == nil else { + throw input.issue(path, .invalid, "native field overlaps the portable MCP mapping") + } + guard let rule = rules[key] else { + throw input.issue(path, .unverified, "no verified field mapping in this native schema") + } + guard rule.accepts(value) else { + throw input.issue(path, .invalid, "value is outside the verified native field profile") + } + if case .environmentName = rule, case .string(let name) = value { + try input.environmentName(name, field: path) + placements.append(.init(path: [.key(key)], binding: .environment(name), reference: true)) + } else { + try checkStrings(value, path: path) + } + fields[key] = ledgerValue(value) + } + } + + private func checkStrings(_ value: NativeValue, path: [String]) throws { + switch value { + case .string(let text): try input.literal(text, field: path) + case .array(let array): + for (i, value) in array.enumerated() { try checkStrings(value, path: path + [String(i)]) } + case .object(let object): + for (key, value) in object.sorted(by: { $0.key < $1.key }) { + try checkStrings(value, path: path + [key]) + } + default: break + } + } + + private func ledgerValue(_ value: NativeValue) -> LedgerValue { + switch value { + case .string(let text): .init(text) + case .integer(let number): .init(integer: number) + case .decimal(let number): .init(number, kind: .decimal) + case .boolean(let boolean): .init(boolean: boolean) + case .null: .init() + case .array(let array): .init(array: array.map(ledgerValue)) + case .object(let object): .init(object: object.mapValues(ledgerValue)) + } + } +} + +extension Array where Element == MCPValueStep { + var fields: [String] { + map { step in + switch step { + case .key(let key): key + case .index(let index): String(index) + } + } + } +} diff --git a/Tests/ComponentsTests/NativeMCPTests.swift b/Tests/ComponentsTests/NativeMCPTests.swift new file mode 100644 index 0000000..b76a7b1 --- /dev/null +++ b/Tests/ComponentsTests/NativeMCPTests.swift @@ -0,0 +1,606 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation +import NativeDocuments +import Testing + +@Suite("Native MCP mapping and replay") +struct NativeMCPTests { + @Test(arguments: NativeMCPScope.allCases) + func claudeRegionsPreserveClientAndOtherScopeState(_ scope: NativeMCPScope) throws { + try withMCP( + [server("db", transport: stdio(), agents: ["claude-code"])], + request: .init(surface: .claudeCode, scope: scope) + ) { contribution, _, _ in + let source = """ + { + "accountSentinel" : "keep-account", + "mcpServers": {"db": {"command":"old","args":[]}, "user-sibling" : {"command":"keep"}}, + "projects": { + "/work/a.b": {"hasTrustDialogAccepted":false,"mcpServers":{"db":{"command":"old","args":[]}}}, + "/work/other": {"allowedTools":[],"mcpServers":{"other":{"command":"keep"}}} + } + } + """ + let region = try contribution.descriptor.region( + server: contribution.name, nativeProjectKey: "/work/a.b") + let expectedKeys = + scope == .local + ? ["projects", "/work/a.b", "mcpServers", "db"] : ["mcpServers", "db"] + #expect(region == NativeRegion(keys: expectedKeys)) + #expect(contribution.descriptor.request.scope == scope) + #expect(contribution.descriptor.knownReaders == [.claudeCode]) + let doc = try document(source, contribution) + let fixtureOwnedEntry = try #require(try doc.read(region)) + let value = try contribution.referenceValue() + let changed = try doc.prepare([ + .put(region: region, expected: .owned(fixtureOwnedEntry), value: value) + ]) + let changedText = String(decoding: changed.bytes, as: UTF8.self) + #expect(changedText.contains(#""accountSentinel" : "keep-account""#)) + #expect(changedText.contains(#""user-sibling" : {"command":"keep"}"#)) + #expect(changedText.contains(#""hasTrustDialogAccepted":false"#)) + #expect( + changedText.contains( + #""/work/other": {"allowedTools":[],"mcpServers":{"other":{"command":"keep"}}}"#)) + let next = try document(changedText, contribution) + #expect(try next.read(region)?.value == value) + let owned = try #require(try next.read(region)) + #expect( + try next.prepare([.put(region: region, expected: .owned(owned), value: value)]).bytes + == changed.bytes) + #expect(throws: NativeDocumentError.self) { + try next.prepare([.put(region: region, expected: .absent, value: value)]) + } + let removed = try next.prepare([.remove(region: region, expected: .owned(owned))]) + let after = try NativeDocument(bytes: removed.bytes, format: .json, budget: budget()) + #expect(try after.read(region) == nil) + #expect( + String(decoding: removed.bytes, as: UTF8.self).contains( + #""accountSentinel" : "keep-account""#)) + if scope == .local { + #expect( + try after.read(.init(keys: ["projects", "/work/a.b", "hasTrustDialogAccepted"]))?.value + == .boolean(false)) + #expect(throws: NativeAdapterIssue.self) { + try contribution.descriptor.region(server: contribution.name) + } + } + } + } + + @Test(arguments: [false, true]) + func codexQuotedServerAndEnvironmentTOML(_ inline: Bool) throws { + let name = "db.api\"quoted" + let invocation = stdio(environment: ["NOTE": "new", "INHERITED": ["env": "INHERITED"]]) + try withMCP( + [server(name, transport: invocation, agents: ["codex"])], + request: .init(surface: .codexCLI, scope: .project) + ) { contribution, _, _ in + let source = + inline + ? """ + # native client sentinel + model = "keep-model" + mcp_servers.'db.api"quoted' = { command = "old", args = [], env = { NOTE = "before" }, env_vars = ["INHERITED"] } + [mcp_servers.sibling] + command = "keep-sibling" # preserve this comment + """ + : """ + # native client sentinel + model = "keep-model" + [mcp_servers.'db.api"quoted'] + command = "old" + args = [] + env_vars = ["INHERITED"] + [mcp_servers.'db.api"quoted'.env] + NOTE = "before" + [mcp_servers.sibling] + command = "keep-sibling" # preserve this comment + """ + let region = try contribution.descriptor.region(server: contribution.name) + #expect(region == NativeRegion(keys: ["mcp_servers", name])) + let doc = try document(source, contribution) + let knownOwned = try #require(try doc.read(region)) + let changed = try doc.prepare([ + .put(region: region, expected: .owned(knownOwned), value: contribution.referenceValue()) + ]) + #expect( + String(decoding: changed.bytes, as: UTF8.self) + == source.replacingOccurrences(of: "\"old\"", with: "\"fixture-server-never-run\"") + .replacingOccurrences(of: "\"before\"", with: "\"new\"")) + let next = try NativeDocument(bytes: changed.bytes, format: .toml, budget: budget()) + #expect(try next.read(region)?.value == contribution.referenceValue()) + #expect(contribution.bindings.map(\.path) == [[.key("env_vars"), .index(0)]]) + #expect(contribution.bindings.map(\.binding) == [.environment("INHERITED")]) + #expect(contribution.bindings.allSatisfy { $0.reference }) + } + } + + @Test(arguments: [false, true]) + func codexHeaderTablesAndNativeBearerReference(_ inline: Bool) throws { + let transport: [String: Any] = [ + "kind": "streamableHTTP", "url": "https://example.invalid/mcp", + "headers": ["X.Static": "new", "X-Token": ["env": "HTTP_TOKEN"]], + ] + try withMCP( + [ + server( + "api.v1", transport: transport, agents: ["codex"], + native: ["codex": ["bearer_token_env_var": "BEARER_TOKEN"]]) + ], + request: .init(surface: .codexCLI, scope: .user) + ) { contribution, _, _ in + let source = + inline + ? """ + # unmanaged prelude + model = "keep" + mcp_servers.'api.v1' = { url = "https://example.invalid/mcp", bearer_token_env_var = "BEARER_TOKEN", http_headers = { 'X.Static' = "old" }, env_http_headers = { X-Token = "HTTP_TOKEN" } } + [unmanaged] + value = "keep" # suffix + """ + : """ + # unmanaged prelude + model = "keep" + [mcp_servers.'api.v1'] + url = "https://example.invalid/mcp" + bearer_token_env_var = "BEARER_TOKEN" + [mcp_servers.'api.v1'.http_headers] + 'X.Static' = "old" + [mcp_servers.'api.v1'.env_http_headers] + X-Token = "HTTP_TOKEN" + [unmanaged] + value = "keep" # suffix + """ + let doc = try document(source, contribution) + let region = try contribution.descriptor.region(server: contribution.name) + let owned = try #require(try doc.read(region)) + let edited = try doc.prepare([ + .put(region: region, expected: .owned(owned), value: contribution.referenceValue()) + ]) + #expect( + String(decoding: edited.bytes, as: UTF8.self) + == source.replacingOccurrences(of: "\"old\"", with: "\"new\"")) + let fields = try #require(contribution.value.object) + #expect(fields["env_http_headers"] == .init(object: ["X-Token": .init("HTTP_TOKEN")])) + #expect(fields["bearer_token_env_var"] == .init("BEARER_TOKEN")) + #expect( + contribution.bindings.map(\.binding) == [ + .environment("HTTP_TOKEN"), .environment("BEARER_TOKEN"), + ]) + #expect(fields["type"] == nil) + } + } + + @Test(arguments: [ + NativeClientSurface.claudeCode, .codexCLI, .geminiCLI, .openCodeCLI, .cursorEditor, .cursorCLI, + ]) + func mapsRealStdioSchemasAndProductionReplay(_ surface: NativeClientSurface) throws { + let run = stdio(arguments: ["--name", "with spaces"], environment: ["NOTE": "literal"]) + try withMCP( + [server("typed", transport: run, agents: [surface.agent.rawValue])], + request: .init(surface: surface, scope: .project) + ) { contribution, ledger, fixture in + let fields = try #require(contribution.value.object) + let expected: LedgerValue + if surface == .openCodeCLI { + expected = .init(object: [ + "type": .init("local"), + "command": .init(array: [ + .init("fixture-server-never-run"), .init("--name"), .init("with spaces"), + ]), + "environment": .init(object: ["NOTE": .init("literal")]), + ]) + #expect( + try contribution.descriptor.region(server: contribution.name) + == NativeRegion(keys: ["mcp", "servers", "typed"])) + } else { + var expectedFields: [String: LedgerValue] = [ + "command": .init("fixture-server-never-run"), + "args": .init(array: [.init("--name"), .init("with spaces")]), + "env": .init(object: ["NOTE": .init("literal")]), + ] + if surface == .claudeCode || surface == .cursorEditor || surface == .cursorCLI { + expectedFields["type"] = .init("stdio") + } + expected = .init(object: expectedFields) + } + #expect(contribution.value == expected) + #expect(fields["enabled"] == nil) + var candidate = ledger + candidate.lowerings = [ + contribution.lowering(id: "mcp", artifact: "typed", platform: platform) + ] + candidate = try LedgerReplay.prepareLowerings( + candidate, store: fixture.store, roots: [:], limits: .standard) + try LedgerReplay.withReplay(candidate, store: fixture.store, roots: [:], limits: .standard) { + output in + #expect(output.count == 1) + #expect(output[0].kind == .ownedValues) + #expect(output[0].values?.object?["value"] == expected) + #expect(output[0].bytes == nil) + } + } + } + + @Test(arguments: [NativeClientSurface.claudeCode, .geminiCLI]) + func remoteTypesAndReferencesRemainDistinct(_ surface: NativeClientSurface) throws { + for (kind, nativeType) in [("streamableHTTP", "http"), ("sse", "sse")] { + let remote: [String: Any] = [ + "kind": kind, "url": "https://example.invalid/mcp", + "headers": ["X-Token": ["env": "REMOTE_TOKEN"]], + ] + try withMCP( + [server("remote", transport: remote, agents: [surface.agent.rawValue])], + request: .init(surface: surface, scope: .project) + ) { contribution, _, _ in + #expect( + contribution.value + == .init(object: [ + "type": .init(nativeType), "url": .init("https://example.invalid/mcp"), + "headers": .init(object: ["X-Token": .init("${REMOTE_TOKEN}")]), + ])) + #expect(contribution.bindings[0].binding == .environment("REMOTE_TOKEN")) + #expect(contribution.bindings[0].reference) + _ = try contribution.referenceValue() + } + } + } + + @Test func openCodeRemoteProtocolIsNotSSE() throws { + try withMCP( + [ + server( + "remote", + transport: [ + "kind": "streamableHTTP", "url": "https://example.invalid/mcp", + "headers": ["X-Token": ["env": "REMOTE_TOKEN"]], + ], agents: ["opencode"], + native: ["opencode": ["protocol": "legacy", "oauth": false]]) + ], + request: .init(surface: .openCodeCLI, scope: .project) + ) { contribution, _, _ in + #expect( + contribution.value + == .init(object: [ + "type": .init("remote"), "url": .init("https://example.invalid/mcp"), + "headers": .init(object: ["X-Token": .init("{env:REMOTE_TOKEN}")]), + "protocol": .init("legacy"), "codemode": .init(boolean: false), + "oauth": .init(boolean: false), + ])) + _ = try contribution.referenceValue() + } + } + + @Test func symbolicBindingsRemainReplayableWithoutMaterializedValues() throws { + try withMCP( + [ + server( + "private", + transport: stdio(environment: [ + "RENAMED": ["env": "ORIGINAL"], "TOKEN": ["secret": "credential/server"], + ]), agents: ["codex"]) + ], request: .init(surface: .codexCLI, scope: .project) + ) { contribution, ledger, fixture in + #expect( + contribution.value.object?["env"] + == .init(object: [ + "RENAMED": .init("ORIGINAL", kind: .environment), + "TOKEN": .init("credential/server", kind: .secret), + ])) + #expect(contribution.bindings.allSatisfy { !$0.reference }) + do { + _ = try contribution.referenceValue() + Issue.record("symbolic bindings were treated as native literal values") + } catch let issue as NativeAdapterIssue { + #expect(issue.reason == .integrationRequired) + #expect(issue.field == ["env", "RENAMED"]) + #expect(!issue.description.contains("credential/server")) + } + var candidate = ledger + candidate.lowerings = [ + contribution.lowering(id: "private", artifact: "private", platform: platform) + ] + candidate = try LedgerReplay.prepareLowerings( + candidate, store: fixture.store, roots: [:], limits: .standard) + let bytes = try ResolvedLedgerCodec.encode(candidate, limits: .standard) + let restored = try ResolvedLedgerCodec.decode(bytes, limits: .standard) + let replayed = try MCPLayoutV1.contribution(restored.lowerings[0], ledger: restored) + #expect(replayed.bindings == contribution.bindings) + #expect(replayed.value == contribution.value) + #expect(replayed.resourcePlacements.isEmpty) + try LedgerReplay.withReplay(restored, store: fixture.store, roots: [:], limits: .standard) { + #expect($0[0].values?.object?["value"] == contribution.value) + } + } + } + + @Test func coldReplayPinsLocalRouteAndRetainsIndependentAndRepeatedOwners() throws { + let fixture = try LinkFixture() + let item = server("same", transport: stdio(), agents: ["claude-code"]) + let declaration: [String: Any] = [ + "version": 1, "exports": ["one", "two"], + "groups": ["one": ["components": [item]], "two": ["components": [item]]], + "uses": [ + ["source": ".", "group": "one"], ["source": ".", "group": "two"], + ["source": ".", "group": "one"], + ], + ] + let (linked, frozen) = try freeze(declaration, fixture) + #expect(linked.count == 3) + #expect(frozen.components.count == 2) + let contributions = try linked.map { + try NativeMCPLowering.lower( + $0, frozen: frozen, request: .init(surface: .claudeCode, scope: .local)) + } + #expect(contributions[0].component != contributions[1].component) + #expect(contributions[0].component == contributions[2].component) + #expect(contributions.map(\.occurrences) == linked.map { $0.origins.map(\.occurrence) }) + var candidate = frozen + candidate.lowerings = contributions.enumerated().map { index, contribution in + contribution.lowering(id: "lower-\(index)", artifact: "entry-\(index)", platform: platform) + } + candidate = try LedgerReplay.prepareLowerings( + candidate, store: fixture.store, roots: [:], limits: .standard) + let encoded = try ResolvedLedgerCodec.encode(candidate, limits: .standard) + #expect(!String(decoding: encoded, as: UTF8.self).contains(fixture.project.path)) + try FileManager.default.removeItem(at: fixture.project) + let restored = try ResolvedLedgerCodec.decode(encoded, limits: .standard) + try LedgerReplay.withReplay(restored, store: fixture.store, roots: [:], limits: .standard) { + output in + #expect(output.map(\.name) == ["entry-0", "entry-1", "entry-2"]) + #expect( + output.map { $0.values?.object?["value"] } == contributions.map { Optional($0.value) }) + } + for (index, lowering) in restored.lowerings.enumerated() { + let replayed = try MCPLayoutV1.contribution(lowering, ledger: restored) + #expect(replayed.component == contributions[index].component) + #expect(replayed.occurrences == contributions[index].occurrences) + #expect(replayed.descriptor.request == .init(surface: .claudeCode, scope: .local)) + #expect( + try replayed.descriptor.region( + server: replayed.name, nativeProjectKey: "/relocated/project") + == NativeRegion(keys: ["projects", "/relocated/project", "mcpServers", "same"])) + } + var changed = restored + changed.lowerings[0].layout.object?["scope"] = .init("project") + #expect(throws: CoreError.self) { + try LedgerReplay.withReplay(changed, store: fixture.store, roots: [:], limits: .standard) { + _ in + } + } + changed = restored + changed.lowerings[0].format = "agents/claude-mcp@999" + #expect(throws: CoreError.self) { + try LedgerReplay.withReplay(changed, store: fixture.store, roots: [:], limits: .standard) { + _ in + } + } + } + + @Test func frozenExecutableAndDirectoryUseSymbolicPlacements() throws { + let fixture = try LinkFixture() + try fixture.write("#!/bin/sh\nexit 0\n", to: "bin/server", base: fixture.project) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: fixture.project.appendingPathComponent("bin/server").path) + try fixture.write("resource", to: "data/file", base: fixture.project) + var run = stdio() + run["executable"] = "./bin/server" + run["workingDirectory"] = ["path": "data"] + let (linked, frozen) = try freeze( + [ + "version": 1, "components": [server("frozen", transport: run, agents: ["codex"])], + ], fixture) + let contribution = try NativeMCPLowering.lower( + try #require(linked.first), frozen: frozen, + request: .init(surface: .codexCLI, scope: .project)) + #expect(contribution.resourcePlacements.map(\.path) == [[.key("command")], [.key("cwd")]]) + #expect(contribution.resourcePlacements.map(\.resource) == contribution.resources) + #expect(throws: NativeAdapterIssue.self) { try contribution.referenceValue() } + var candidate = frozen + candidate.lowerings = [ + contribution.lowering(id: "frozen", artifact: "frozen", platform: platform) + ] + candidate = try LedgerReplay.prepareLowerings( + candidate, store: fixture.store, roots: [:], limits: .standard) + let bytes = try ResolvedLedgerCodec.encode(candidate, limits: .standard) + #expect(!String(decoding: bytes, as: UTF8.self).contains(fixture.project.path)) + try FileManager.default.removeItem(at: fixture.project) + try LedgerReplay.withReplay( + ResolvedLedgerCodec.decode(bytes, limits: .standard), store: fixture.store, roots: [:], + limits: .standard + ) { output in + #expect(output[0].values?.object?["value"] == contribution.value) + #expect(output[0].tree == nil) + } + } + + @Test func unsupportedUnknownAndInvalidDiagnosticsAreExact() throws { + for surface in [NativeClientSurface.codexCLI, .openCodeCLI, .cursorEditor, .cursorCLI] { + do { + try withMCP( + [ + server( + "exact", transport: ["kind": "sse", "url": "https://example.invalid/sse"], + agents: [surface.agent.rawValue]) + ], request: .init(surface: surface, scope: .project) + ) { _, _, _ in Issue.record("unexpected mapping") } + Issue.record("transport restriction was lost") + } catch let issue as NativeAdapterIssue { + #expect(issue.request.surface == surface) + #expect(issue.request.scope == .project) + #expect(issue.component == "exact") + #expect(issue.field == ["transport", "kind"]) + #expect( + issue.reason + == (surface == .codexCLI || surface == .openCodeCLI ? .unsupported : .unverified)) + } + } + do { + try withMCP( + [ + server( + "exact", transport: stdio(), agents: ["codex"], + native: ["codex": ["futureField": "SENSITIVE_UNMANAGED_VALUE"]]) + ], request: .init(surface: .codexCLI, scope: .project) + ) { _, _, _ in Issue.record("unknown field accepted") } + Issue.record("unknown field was dropped") + } catch let issue as NativeAdapterIssue { + #expect(issue.reason == .unverified) + #expect(issue.field == ["native", "codex", "futureField"]) + #expect(!issue.description.contains("SENSITIVE_UNMANAGED_VALUE")) + } + do { + try withMCP( + [ + server( + "exact", transport: stdio(), agents: ["codex"], + native: ["codex": ["startup_timeout_sec": -1]]) + ], request: .init(surface: .codexCLI, scope: .project) + ) { _, _, _ in Issue.record("invalid timeout accepted") } + Issue.record("invalid timeout was dropped") + } catch let issue as NativeAdapterIssue { + #expect(issue.reason == .invalid) + #expect(issue.field == ["native", "codex", "startup_timeout_sec"]) + } + #expect(throws: NativeAdapterIssue.self) { + try CapabilityRegistry.mcp(.init(surface: .geminiCLI, scope: .local), component: "exact") + } + #expect(throws: NativeAdapterIssue.self) { + try CapabilityRegistry.mcp(.init(surface: .cursorCloud, scope: .project), component: "exact") + } + } + + @Test func recipientProjectionPreservesTheFrozenOwnerTargeting() throws { + let fixture = try LinkFixture() + let (linked, ledger) = try freeze( + [ + "version": 1, + "components": [server("shared", transport: stdio(), agents: ["claude-code", "codex"])], + ], fixture) + let component = try #require(linked.first) + for surface in [NativeClientSurface.claudeCode, .codexCLI] { + let contribution = try NativeMCPLowering.lower( + component, frozen: ledger, request: .init(surface: surface, scope: .project)) + #expect(contribution.recipients == [surface.agent]) + #expect(contribution.descriptor.knownReaders == [surface.agent]) + #expect(Set(ledger.components[contribution.component]!.recipients) == [.claudeCode, .codex]) + #expect(contribution.occurrences == component.origins.map(\.occurrence)) + } + } + + @Test func nativeInterpolationCannotChangeLiteralIdentity() throws { + for (surface, field, text) in [ + (NativeClientSurface.claudeCode, "env", "${CLIENT_TOKEN}"), + (.geminiCLI, "env", "$CLIENT_TOKEN"), + (.openCodeCLI, "environment", "{file:private.txt}"), + (.cursorCLI, "env", "${unknown:CLIENT_TOKEN}"), + ] { + do { + try withMCP( + [ + server( + "literal", transport: stdio(environment: ["TOKEN": text]), + agents: [surface.agent.rawValue]) + ], request: .init(surface: surface, scope: .project) + ) { _, _, _ in + Issue.record("native interpolation was accepted as a portable literal") + } + Issue.record("literal identity was lost") + } catch let issue as NativeAdapterIssue { + #expect(issue.reason == .unverified) + #expect(issue.field == [field, "TOKEN"]) + #expect(!issue.description.contains(text)) + } + } + } + + @Test func producerTargetingAndFrozenIdentityAreNotReinterpreted() throws { + let fixture = try LinkFixture() + var item = server("scoped", transport: stdio(), agents: ["claude-code"]) + item["condition"] = ["scopes": ["project"]] + let (linked, frozen) = try freeze(["version": 1, "components": [item]], fixture) + let component = try #require(linked.first) + #expect(throws: NativeAdapterIssue.self) { + try NativeMCPLowering.lower( + component, frozen: frozen, request: .init(surface: .codexCLI, scope: .project)) + } + #expect(throws: NativeAdapterIssue.self) { + try NativeMCPLowering.lower( + component, frozen: frozen, request: .init(surface: .claudeCode, scope: .user)) + } + var changed = frozen + changed.occurrences[0].consumerEditable = false + #expect(throws: NativeAdapterIssue.self) { + try NativeMCPLowering.lower( + component, frozen: changed, request: .init(surface: .claudeCode, scope: .project)) + } + } + + private var platform: DeclarationPlatform { + #if os(macOS) + .macOS + #else + .linux + #endif + } + + private func server( + _ name: String, transport: [String: Any], agents: [String], native: [String: Any] = [:] + ) -> [String: Any] { + ["kind": "mcpServer", "name": name, "transport": transport, "agents": agents, "native": native] + } + + private func stdio(arguments: [String] = [], environment: [String: Any] = [:]) -> [String: Any] { + [ + "kind": "stdio", "executable": "fixture-server-never-run", "arguments": arguments, + "environment": environment, + ] + } + + private func withMCP( + _ components: [[String: Any]], request: NativeMCPRequest, + _ body: (NativeMCPContribution, ResolvedLedger, LinkFixture) throws -> Void + ) throws { + let fixture = try LinkFixture() + let (linked, ledger) = try freeze(["version": 1, "components": components], fixture) + let contribution = try NativeMCPLowering.lower( + try #require(linked.first), frozen: ledger, request: request) + try body(contribution, ledger, fixture) + } + + private func freeze(_ declaration: [String: Any], _ fixture: LinkFixture) throws -> ( + [LinkedComponent], ResolvedLedger + ) { + let bytes = try JSONSerialization.data(withJSONObject: declaration, options: [.sortedKeys]) + let document = try DeclarationDocument( + bytes: Array(bytes), identity: DocumentIdentity("consumer/agents.yaml")) + return try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: platform + ) { linked, session in + let frozen = try LedgerFreeze.freeze( + linked, session: session, + locations: .init(sources: [ + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: ".") + ]), limits: .standard) + return (linked.components, frozen) + } + } + + private func budget() -> NativeDocumentBudget { + .init( + limits: .init( + storage: 32_000_000, work: 100_000_000, nodes: 100_000, depth: 128, + uninterruptedBytes: 1_000_000)) + } + + private func document(_ text: String, _ contribution: NativeMCPContribution) throws + -> NativeDocument + { + try NativeDocument( + bytes: Data(text.utf8), format: contribution.descriptor.documentFormat, budget: budget()) + } +} From 606123001028843acb8d03a8237cad4ab9d017a6 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:42:16 +0800 Subject: [PATCH 062/171] feat(components): add bounded MCP connection transports --- Documentation/Architecture/Package.md | 47 +- Package.resolved | 64 ++- Package.swift | 14 +- Sources/AgentsCore/OwnedDuplexProcess.swift | 227 ++++++++++ Sources/CPlatform/DuplexProcess.c | 139 ++++++ Sources/CPlatform/include/CPlatform.h | 2 + Sources/CPlatform/include/DuplexProcess.h | 16 + Sources/Components/MCPBoundedTransport.swift | 193 +++++++++ Sources/Components/MCPConnectionRunner.swift | 193 +++++++++ Sources/Components/MCPConnectionTypes.swift | 99 +++++ Sources/Components/MCPHTTPConnection.swift | 406 ++++++++++++++++++ Sources/Components/MCPMessageSink.swift | 217 ++++++++++ .../ComponentsTests/Fixtures/MCPHTTPServer.py | 89 ++++ .../ComponentsTests/MCPConnectionTests.swift | 343 +++++++++++++++ Tests/MCPTestProcess/main.swift | 140 ++++++ 15 files changed, 2183 insertions(+), 6 deletions(-) create mode 100644 Sources/AgentsCore/OwnedDuplexProcess.swift create mode 100644 Sources/CPlatform/DuplexProcess.c create mode 100644 Sources/CPlatform/include/DuplexProcess.h create mode 100644 Sources/Components/MCPBoundedTransport.swift create mode 100644 Sources/Components/MCPConnectionRunner.swift create mode 100644 Sources/Components/MCPConnectionTypes.swift create mode 100644 Sources/Components/MCPHTTPConnection.swift create mode 100644 Sources/Components/MCPMessageSink.swift create mode 100644 Tests/ComponentsTests/Fixtures/MCPHTTPServer.py create mode 100644 Tests/ComponentsTests/MCPConnectionTests.swift create mode 100644 Tests/MCPTestProcess/main.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 25e554d..5cb53df 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -13,7 +13,7 @@ terminal/UI presentation and executable distribution. AgentsManifest → AgentsCore, TreeSitterYAML, TreeSitter, Yams AgentsSkills → AgentsCore, AgentsManifest, Yams AgentsInstructions → AgentsCore, AgentsManifest, Markdown -Components → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions +Components → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, MCP AgentsUpdates → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions AgentsCore → CPlatform, Crypto ``` @@ -95,7 +95,9 @@ and the existing state, linking, lifecycle and recovery guarantees. domain planners during one update. `StatePrecondition`, `TargetPrecondition` and `PathIdentity` validate the rendered generation before application. `TransactionOutcome` follows its owning journal through commit and recovery. - `ProcessRunner` executes subprocesses. + `ProcessRunner` executes synchronous subprocesses. `OwnedDuplexProcess` is a + separate package-only, nonblocking pipe/process-group owner for bidirectional + connection tests. - `WatchOperations` owns source subscriptions, seen baselines, branch tracking and file comparisons. `WatchState` defines version 1 of `agents.watch`. Skill discovery and artifact loading are injected by `AgentsSkills` through @@ -141,6 +143,17 @@ inspecting arguments, exit codes, or diagnostic text. Non-Git process failures continue to use `CoreError.commandFailed`; process launch errors retain their underlying platform error. +`OwnedDuplexProcess` takes explicit argv, cwd, environment and PATH. Its CPlatform +spawn closes nonstandard child descriptors and creates a separate process group; +it never inherits transaction locks. The owner closes stdin, waits a finite grace, +signals TERM/KILL while the unreaped leader reserves its identity, and confirms +reap with nonblocking waits. It refuses auto-reaping SIGCHLD configurations and +reports ownership loss or unconfirmed cleanup. Darwin inspects only the reserved +group, under a finite byte bound, to distinguish a zombie-only group before +signalling. It does not operate on unrelated processes or promise ownership of +children that detach into another session/group. `ProcessRunner` owns synchronous +Git/one-shot execution; transaction publication owns filesystem state. + ## AgentsSkills `SkillOperations` is the public lifecycle surface: @@ -331,6 +344,36 @@ environment. Root user instructions require named sources, while imported producer groups retain their own sections. User prompt append content is read relative to the runtime home. +The package-only `MCPConnectionRunner` performs one explicit connection test on +already-bound ephemeral values. Only Components links the exact official MCP SDK; +SDK models do not enter public APIs. The SDK Client owns automatic initialization +and typed tools/list requests. A bounded receive admission gate validates the +negotiated version before initialized is sent, and discovery runs only when the +server declares tools. There are no business tool, resource, prompt, sampling or +elicitation handlers; SDK logging is no-op. + +The selected transport is stdio, Streamable HTTP, or legacy SSE. Stdio frames +nonblocking owned pipes and discards counted stderr. HTTP uses one ephemeral +Foundation/FoundationNetworking data-delegate session with incremental JSON/SSE +admission, owned session/version headers and bounded SSE resumption without POST +replay. Legacy SSE waits for its same-origin endpoint event before posting. No +cookie/cache/credential store or OAuth flow is used; redirects and legacy +endpoints cannot transfer headers to another origin or downgrade transport. + +A monotonic total deadline includes preparation and all requests; a request +budget cannot extend it. Input, frame, cumulative input/output, stderr, queued +payload, discovery pages/tools/text and redirect/resume bounds are finite and +validated before I/O. Overflow is a structured failure or incomplete discovery, +not a successful dropped message. Cancellation and every terminal path abort I/O, +disconnect Client and join the owned work. Finite process/URLSession cleanup +budgets are additional to the protocol deadline. Unconfirmed cleanup prevents +complete success. Internal outcomes contain bounded private text values for the +caller to redact; they have no automatic serialized representation. + +`MCPTestProcess` and the owned loopback HTTP fixture exercise real wire, process, +origin, deadline and resource-cleanup behavior in ComponentsTests. They do not +use external services or execute configured third-party clients. + ## AgentsUpdates `UpdateOperations.preview` plans all declared skills, instruction targets and diff --git a/Package.resolved b/Package.resolved index 15a738f..0438c2e 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,6 +1,15 @@ { - "originHash" : "ab09bed54f5aab76864fb60822b02f0a35a5f6a7d8c83569ee7317a964deef44", + "originHash" : "e52552c8d5747be8dcb02a8ace8ba7f8b39ac4605c24605c1811b3ccd827f09d", "pins" : [ + { + "identity" : "eventsource", + "kind" : "remoteSourceControl", + "location" : "https://github.com/mattt/eventsource.git", + "state" : { + "revision" : "bb4b61273b5a976bb571859c17f903ebc3439df1", + "version" : "1.6.0" + } + }, { "identity" : "swift-asn1", "kind" : "remoteSourceControl", @@ -10,6 +19,15 @@ "version" : "1.7.3" } }, + { + "identity" : "swift-atomics", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-atomics.git", + "state" : { + "revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34", + "version" : "1.3.1" + } + }, { "identity" : "swift-cmark", "kind" : "remoteSourceControl", @@ -19,6 +37,15 @@ "version" : "0.9.0" } }, + { + "identity" : "swift-collections", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-collections.git", + "state" : { + "revision" : "88754449ab766a739610b660e117762115fabc9c", + "version" : "1.7.6" + } + }, { "identity" : "swift-crypto", "kind" : "remoteSourceControl", @@ -28,6 +55,15 @@ "version" : "5.0.3" } }, + { + "identity" : "swift-log", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-log.git", + "state" : { + "revision" : "e3da04078777e6a1b72ce19981fbd6539b0847d8", + "version" : "1.17.0" + } + }, { "identity" : "swift-markdown", "kind" : "remoteSourceControl", @@ -37,6 +73,32 @@ "version" : "0.9.0" } }, + { + "identity" : "swift-nio", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-nio.git", + "state" : { + "revision" : "2f58d8ef84438d6517fc78bcea2f8527e3c72936", + "version" : "2.105.0" + } + }, + { + "identity" : "swift-sdk", + "kind" : "remoteSourceControl", + "location" : "https://github.com/modelcontextprotocol/swift-sdk.git", + "state" : { + "revision" : "a0ae212ebf6eab5f754c3129608bc5557637e605" + } + }, + { + "identity" : "swift-system", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-system.git", + "state" : { + "revision" : "640e5755b5826f4437eaeedd366fd776737db62c", + "version" : "1.9.0" + } + }, { "identity" : "tree-sitter", "kind" : "remoteSourceControl", diff --git a/Package.swift b/Package.swift index 3128a5b..744247d 100644 --- a/Package.swift +++ b/Package.swift @@ -16,6 +16,9 @@ let package = Package( .library(name: "AgentsUpdates", targets: ["AgentsUpdates"]), ], dependencies: [ + .package( + url: "https://github.com/modelcontextprotocol/swift-sdk.git", + revision: "a0ae212ebf6eab5f754c3129608bc5557637e605"), .package(url: "https://github.com/apple/swift-crypto.git", from: "5.0.0"), .package(url: "https://github.com/jpsim/Yams", exact: "6.2.2"), .package(url: "https://github.com/swiftlang/swift-markdown.git", from: "0.9.0"), @@ -51,13 +54,18 @@ let package = Package( ]), .target( name: "Components", - dependencies: ["AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions"]), + dependencies: [ + "AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions", + .product(name: "MCP", package: "swift-sdk"), + ]), .testTarget( name: "ComponentsTests", dependencies: [ "Components", "AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions", - "StateTestProcess", "StateTestSupport", - ]), + "StateTestProcess", "StateTestSupport", "MCPTestProcess", + ], resources: [.copy("Fixtures")]), + .executableTarget( + name: "MCPTestProcess", dependencies: ["CPlatform"], path: "Tests/MCPTestProcess"), .target(name: "StateTestSupport", path: "Tests/StateTestSupport"), .executableTarget( name: "StateTestProcess", diff --git a/Sources/AgentsCore/OwnedDuplexProcess.swift b/Sources/AgentsCore/OwnedDuplexProcess.swift new file mode 100644 index 0000000..e957917 --- /dev/null +++ b/Sources/AgentsCore/OwnedDuplexProcess.swift @@ -0,0 +1,227 @@ +import CPlatform +import Foundation + +package struct DuplexProcessConfiguration: Sendable { + package var executable: String + package var arguments: [String] + package var directory: URL + package var environment: [String: String] + + package init( + executable: String, arguments: [String], directory: URL, environment: [String: String] + ) { + self.executable = executable + self.arguments = arguments + self.directory = directory + self.environment = environment + } +} + +package enum DuplexProcessError: Error, Sendable { + case invalidInput + case launchFailed + case ioFailed +} + +package enum DuplexRead: Sendable { + case bytes(Data) + case wouldBlock + case end +} + +/// Owns the child's wait status exclusively until group cleanup and reap finish. +/// The unreaped leader reserves its PID/PGID; no group signal is sent after reap +/// or ECHILD. Every descriptor access is locked and every I/O syscall nonblocking. +package final class OwnedDuplexProcess: @unchecked Sendable { + private let lock = NSLock() + private var descriptors: [Int32] + private var owned = true + private var reaped = false + package let identifier: Int32 + package let resolvedExecutable: String + + package init(_ configuration: DuplexProcessConfiguration) throws { + func valid(_ value: String) -> Bool { !value.utf8.contains(0) } + guard valid(configuration.executable), !configuration.executable.isEmpty, + valid(configuration.directory.path), configuration.arguments.allSatisfy(valid), + configuration.environment.allSatisfy({ + !$0.key.isEmpty && !$0.key.contains("=") && valid($0.key) && valid($0.value) + }) + else { throw DuplexProcessError.invalidInput } + var isDirectory: ObjCBool = false + guard configuration.directory.isFileURL, + FileManager.default.fileExists( + atPath: configuration.directory.path, isDirectory: &isDirectory), + isDirectory.boolValue + else { throw DuplexProcessError.invalidInput } + let executable: String + if configuration.executable.contains("/") { + executable = + configuration.executable.hasPrefix("/") + ? configuration.executable + : configuration.directory.appendingPathComponent(configuration.executable).path + } else { + guard let path = configuration.environment["PATH"] else { + throw DuplexProcessError.invalidInput + } + guard configuration.executable.utf8.count <= Int(NAME_MAX) else { + throw DuplexProcessError.invalidInput + } + let candidates = path.split(separator: ":", omittingEmptySubsequences: false).lazy.map { + entry in + let path = String(entry) + let base = + path.hasPrefix("/") + ? URL(fileURLWithPath: path, isDirectory: true) + : configuration.directory.appendingPathComponent(path, isDirectory: true) + return base.appendingPathComponent(configuration.executable).standardizedFileURL.path + } + guard + let found = candidates.first(where: { + var directory: ObjCBool = false + return FileManager.default.fileExists(atPath: $0, isDirectory: &directory) + && !directory.boolValue && access($0, X_OK) == 0 + }) + else { + throw DuplexProcessError.launchFailed + } + executable = found + } + guard executable.utf8.count <= Int(PATH_MAX) else { throw DuplexProcessError.invalidInput } + resolvedExecutable = executable + let arguments = ([executable] + configuration.arguments).map { strdup($0) } + [nil] + let environment = + configuration.environment.sorted(by: { $0.key < $1.key }).map { + strdup($0.key + "=" + $0.value) + } + [nil] + defer { for pointer in arguments + environment { free(pointer) } } + var pid: pid_t = 0 + var fds: [Int32] = [-1, -1, -1] + let result = platform_duplex_spawn( + &pid, executable, arguments, environment, configuration.directory.path, &fds) + guard result == 0 else { throw DuplexProcessError.launchFailed } + identifier = pid + descriptors = fds + } + + package func readStandardOutput() throws -> DuplexRead { try read(1) } + package func readStandardError() throws -> DuplexRead { try read(2) } + + private func read(_ index: Int) throws -> DuplexRead { + try lock.withLock { + let fd = descriptors[index] + guard fd >= 0 else { return .end } + var bytes = [UInt8](repeating: 0, count: 4096) + let count = bytes.withUnsafeMutableBytes { buffer in + CPlatform.read(fd, buffer.baseAddress, buffer.count) + } + if count > 0 { return .bytes(Data(bytes.prefix(count))) } + if count == 0 { + close(fd) + descriptors[index] = -1 + return .end + } + if errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR { return .wouldBlock } + throw DuplexProcessError.ioFailed + } + } + + package func write(_ bytes: Data, offset: Int) throws -> Int { + try lock.withLock { + guard offset >= 0 && offset <= bytes.count else { throw DuplexProcessError.invalidInput } + if offset == bytes.count { return 0 } + guard descriptors[0] >= 0 else { throw DuplexProcessError.ioFailed } + let count = bytes.withUnsafeBytes { buffer in + platform_duplex_write( + descriptors[0], buffer.baseAddress!.advanced(by: offset), bytes.count - offset) + } + if count >= 0 { return count } + if errno == EAGAIN || errno == EWOULDBLOCK { return 0 } + throw DuplexProcessError.ioFailed + } + } + + package func closeInput() { + lock.withLock { + if descriptors[0] >= 0 { + close(descriptors[0]) + descriptors[0] = -1 + } + } + } + + package func closeOutput() { + lock.withLock { + for index in 1...2 where descriptors[index] >= 0 { + close(descriptors[index]) + descriptors[index] = -1 + } + } + } + + private func signalGroup(_ signal: Int32) -> Bool { + lock.withLock { + guard owned && !reaped else { return false } + var exited = false + guard platform_duplex_observe(identifier, &exited) == 0 else { + owned = false + return false + } + return platform_duplex_signal(identifier, signal) == 0 + } + } + + private func reapIfExited() -> Bool { + lock.withLock { + if reaped { return true } + guard owned else { return false } + var exited = false + guard platform_duplex_observe(identifier, &exited) == 0 else { + owned = false + return false + } + guard exited else { return false } + var status: Int32 = 0 + let result = waitpid(identifier, &status, WNOHANG) + if result == identifier { + reaped = true + owned = false + return true + } + if result < 0 && errno != EINTR { owned = false } + return false + } + } + + /// Cleanup has its own finite grace/TERM/KILL budgets in addition to the + /// protocol deadline. The leader is not reaped until group signals finish, + /// including descendants that closed their inherited pipes. False means the + /// kernel did not confirm cleanup; callers must not report complete success. + package func finish(grace: Duration, terminate: Duration, killWait: Duration) async -> Bool { + closeInput() + try? await Task.sleep(for: grace) + let term = signalGroup(SIGTERM) + try? await Task.sleep(for: terminate) + let killed = signalGroup(SIGKILL) + closeOutput() + let deadline = ContinuousClock.now + killWait + repeat { + if reapIfExited() { return term && killed } + try? await Task.sleep(for: .milliseconds(2)) + } while ContinuousClock.now < deadline + return false + } + + deinit { + // Exceptional abandoned ownership must never turn into an unbounded wait. + for fd in descriptors where fd >= 0 { close(fd) } + if owned && !reaped { + var exited = false + if platform_duplex_observe(identifier, &exited) == 0 { + _ = platform_duplex_signal(identifier, SIGKILL) + var status: Int32 = 0 + _ = waitpid(identifier, &status, WNOHANG) + } + } + } +} diff --git a/Sources/CPlatform/DuplexProcess.c b/Sources/CPlatform/DuplexProcess.c new file mode 100644 index 0000000..2c0a95b --- /dev/null +++ b/Sources/CPlatform/DuplexProcess.c @@ -0,0 +1,139 @@ +#define _GNU_SOURCE 1 +#include "CPlatform.h" +#include +#include +#if defined(__APPLE__) +#include +#include +#endif + +int platform_duplex_spawn(pid_t *pid, const char *executable, char *const argv[], + char *const environment[], const char *directory, + int descriptors[3]) { + struct sigaction childAction; + if (sigaction(SIGCHLD, NULL, &childAction) < 0) return errno; + if (childAction.sa_handler == SIG_IGN || (childAction.sa_flags & SA_NOCLDWAIT)) return EINVAL; + int pipes[6] = {-1,-1,-1,-1,-1,-1}; + int result = 0; + for (int i = 0; i < 6; i += 2) { +#if defined(__APPLE__) + if (pipe(&pipes[i]) < 0) { result = errno; goto cleanup; } + for (int j = i; j < i + 2; j++) { + if (fcntl(pipes[j], F_SETFD, FD_CLOEXEC) < 0) { result = errno; goto cleanup; } + } +#else + if (pipe2(&pipes[i], O_CLOEXEC) < 0) { result = errno; goto cleanup; } +#endif + for (int j = i; j < i + 2; j++) { + if (pipes[j] < 3) { + int replacement = fcntl(pipes[j], F_DUPFD_CLOEXEC, 3); + if (replacement < 0) { result = errno; goto cleanup; } + close(pipes[j]); pipes[j] = replacement; + } + } + } + posix_spawn_file_actions_t actions; + posix_spawnattr_t attributes; + result = posix_spawn_file_actions_init(&actions); + if (result) goto cleanup; + result = posix_spawnattr_init(&attributes); + if (result) { posix_spawn_file_actions_destroy(&actions); goto cleanup; } +#define CHECK(call) do { result = (call); if (result) goto destroy; } while (0) + short flags = POSIX_SPAWN_SETPGROUP | POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF; +#if defined(__APPLE__) + flags |= POSIX_SPAWN_CLOEXEC_DEFAULT; +#endif + sigset_t mask, defaults; + sigemptyset(&mask); sigemptyset(&defaults); + sigaddset(&defaults, SIGPIPE); sigaddset(&defaults, SIGTERM); + sigaddset(&defaults, SIGINT); sigaddset(&defaults, SIGHUP); + CHECK(posix_spawnattr_setflags(&attributes, flags)); + CHECK(posix_spawnattr_setpgroup(&attributes, 0)); + CHECK(posix_spawnattr_setsigmask(&attributes, &mask)); + CHECK(posix_spawnattr_setsigdefault(&attributes, &defaults)); +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + CHECK(posix_spawn_file_actions_addchdir_np(&actions, directory)); +#pragma clang diagnostic pop + CHECK(posix_spawn_file_actions_adddup2(&actions, pipes[0], 0)); + CHECK(posix_spawn_file_actions_adddup2(&actions, pipes[3], 1)); + CHECK(posix_spawn_file_actions_adddup2(&actions, pipes[5], 2)); +#if !defined(__APPLE__) + CHECK(posix_spawn_file_actions_addclosefrom_np(&actions, 3)); +#endif + // Parent ends are nonblocking; child standard streams retain ordinary blocking I/O. + for (int i = 0; i < 3; i++) { + int fd = pipes[(int[]){1,2,4}[i]]; + if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) { result = errno; goto destroy; } + } + result = posix_spawn(pid, executable, &actions, &attributes, argv, environment); + if (!result) { + descriptors[0] = pipes[1]; pipes[1] = -1; + descriptors[1] = pipes[2]; pipes[2] = -1; + descriptors[2] = pipes[4]; pipes[4] = -1; + } +destroy: + posix_spawnattr_destroy(&attributes); + posix_spawn_file_actions_destroy(&actions); +#undef CHECK +cleanup: + for (int i = 0; i < 6; i++) if (pipes[i] >= 0) close(pipes[i]); + return result; +} + +int platform_duplex_observe(pid_t pid, bool *exited) { + siginfo_t info; + memset(&info, 0, sizeof(info)); + int result; + do { result = waitid(P_PID, (id_t)pid, &info, WEXITED | WNOHANG | WNOWAIT); } + while (result < 0 && errno == EINTR); + if (result < 0) return errno; + *exited = info.si_pid == pid; + return 0; +} + +ssize_t platform_duplex_write(int descriptor, const void *bytes, size_t count) { + sigset_t blocked, previous, pending; + sigemptyset(&blocked); sigaddset(&blocked, SIGPIPE); + int result = pthread_sigmask(SIG_BLOCK, &blocked, &previous); + if (result) { errno = result; return -1; } + sigpending(&pending); + bool wasPending = sigismember(&pending, SIGPIPE) == 1; + ssize_t written; + do { written = write(descriptor, bytes, count); } while (written < 0 && errno == EINTR); + int error = errno; + if (written < 0 && error == EPIPE && !wasPending && sigismember(&previous, SIGPIPE) != 1) { + sigpending(&pending); + if (sigismember(&pending, SIGPIPE) == 1) { int signal; sigwait(&blocked, &signal); } + } + pthread_sigmask(SIG_SETMASK, &previous, NULL); + errno = error; + return written; +} + +int platform_duplex_signal(pid_t pid, int signal) { +#if defined(__APPLE__) + // Zombie-only groups need no signal. Inspect only this reserved group; + // an all-zombie group cannot fork. + int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PGRP, pid}; + size_t size = 0; + if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0) return errno; + if (size > 1024 * 1024) return EOVERFLOW; // Bounded cleanup inspection bytes. + if (size == 0) return 0; + struct kinfo_proc *members = malloc(size); + if (!members) return ENOMEM; + int result = sysctl(mib, 4, members, &size, NULL, 0); + int error = errno; + bool live = false; + if (result == 0) { + for (size_t i = 0; i < size / sizeof(*members); i++) { + if (members[i].kp_proc.p_stat != SZOMB) { live = true; break; } + } + } + free(members); + if (result < 0) return error; + if (!live) return 0; +#endif + if (kill(-pid, signal) == 0 || errno == ESRCH) return 0; + return errno; +} diff --git a/Sources/CPlatform/include/CPlatform.h b/Sources/CPlatform/include/CPlatform.h index 436a04c..f675e30 100644 --- a/Sources/CPlatform/include/CPlatform.h +++ b/Sources/CPlatform/include/CPlatform.h @@ -1,6 +1,8 @@ #ifndef CORE_CPLATFORM_H #define CORE_CPLATFORM_H +#include "DuplexProcess.h" + #include #include #include diff --git a/Sources/CPlatform/include/DuplexProcess.h b/Sources/CPlatform/include/DuplexProcess.h new file mode 100644 index 0000000..4a17af5 --- /dev/null +++ b/Sources/CPlatform/include/DuplexProcess.h @@ -0,0 +1,16 @@ +#ifndef CORE_DUPLEX_PROCESS_H +#define CORE_DUPLEX_PROCESS_H +#include +#include +#include + +// Owns a new process group. Only descriptors 0...2 survive exec. +// Success transfers nonblocking parent stdin/stdout/stderr fds to the caller. +int platform_duplex_spawn(pid_t *pid, const char *executable, char *const argv[], + char *const environment[], const char *directory, + int descriptors[3]); +// Observe without reaping, reserving the leader's identity for group cleanup. +int platform_duplex_observe(pid_t pid, bool *exited); +int platform_duplex_signal(pid_t pid, int signal); +ssize_t platform_duplex_write(int descriptor, const void *bytes, size_t count); +#endif diff --git a/Sources/Components/MCPBoundedTransport.swift b/Sources/Components/MCPBoundedTransport.swift new file mode 100644 index 0000000..6a553ec --- /dev/null +++ b/Sources/Components/MCPBoundedTransport.swift @@ -0,0 +1,193 @@ +import AgentsCore +import Foundation +import Logging +import MCP + +/// Cancellation may arrive before connect installs its resource. Installation +/// observes the latched abort, so a late resource cannot escape cleanup. +private final class MCPAbortHandle: @unchecked Sendable { + private let lock = NSLock() + private var aborted = false + private var action: (@Sendable () -> Void)? + func install(_ action: @escaping @Sendable () -> Void) { + let run = lock.withLock { + self.action = action + return aborted + } + if run { action() } + } + func abort() { + let action = lock.withLock { + aborted = true + return self.action + } + action?() + } +} + +actor MCPBoundedTransport: Transport { + nonisolated let logger = Logger( + label: "MCPConnection", factory: { _ in SwiftLogNoOpLogHandler() }) + nonisolated let sink: MCPMessageSink + private nonisolated let abortHandle = MCPAbortHandle() + private let input: MCPConnectionInput + private var process: OwnedDuplexProcess? + private var executable: String? + private var http: MCPHTTPConnection? + private var pumpTask: Task? + private var started = false + private var clean = false + private var cleanupTask: Task? + private var line = Data() + private struct Write { + var bytes: Data + var offset: Int + var continuation: CheckedContinuation + } + private var writes: [Write] = [] + private var writeBytes = 0 + + init(_ input: MCPConnectionInput, limits: MCPConnectionLimits) { + self.input = input + sink = MCPMessageSink(limits) + } + + nonisolated func abort(_ issue: MCPConnectionIssue) { + sink.fail(issue) + abortHandle.abort() + } + + func connect() async throws { + guard !started else { throw MCPConnectionIssue.protocolError } + if let issue = sink.failure { throw issue } + started = true + switch input { + case .stdio(let configuration): + do { + let process = try OwnedDuplexProcess(configuration) + self.process = process + executable = process.resolvedExecutable + abortHandle.install { process.closeInput() } + } catch DuplexProcessError.invalidInput { + throw MCPConnectionIssue.invalidInput + } catch { throw MCPConnectionIssue.connectionFailed } + case .streamableHTTP(let url, let headers): + let http = MCPHTTPConnection(url: url, headers: headers, mode: .streamable, sink: sink) + self.http = http + abortHandle.install { http.abort() } + case .legacySSE(let url, let headers): + let http = MCPHTTPConnection(url: url, headers: headers, mode: .legacy, sink: sink) + self.http = http + abortHandle.install { http.abort() } + } + pumpTask = Task { await pump() } + try await http?.connect() + if let issue = sink.failure { throw issue } + } + + func receive() -> AsyncThrowingStream { sink.stream } + + func send(_ bytes: Data) async throws { + let header = try sink.prepare(bytes) + guard started else { throw MCPConnectionIssue.connectionClosed } + if let http { + try await http.send(bytes, header: header) + return + } + guard process != nil else { throw MCPConnectionIssue.connectionClosed } + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + guard bytes.count < sink.limits.queueBytes - writeBytes, + writes.count < sink.limits.queueMessages + else { + continuation.resume(throwing: MCPConnectionIssue.queueLimit) + abort(.queueLimit) + return + } + var frame = bytes + frame.append(10) + writeBytes += frame.count + writes.append(Write(bytes: frame, offset: 0, continuation: continuation)) + } + } + + private func pump() async { + do { + while sink.failure == nil && !Task.isCancelled { + if let process { + switch try process.readStandardOutput() { + case .bytes(let bytes): + try sink.receiveBytes(bytes.count) + for byte in bytes { + if byte == 10 { + if line.last == 13 { line.removeLast() } + if !line.isEmpty { try sink.admit(line) } + line.removeAll(keepingCapacity: true) + } else { + guard line.count < sink.limits.frameBytes else { + throw MCPConnectionIssue.messageLimit + } + line.append(byte) + } + } + case .end: throw MCPConnectionIssue.connectionClosed + case .wouldBlock: break + } + switch try process.readStandardError() { + case .bytes(let bytes): try sink.receiveBytes(bytes.count, standardError: true) + case .end, .wouldBlock: break + } + if !writes.isEmpty { + let written = try process.write(writes[0].bytes, offset: writes[0].offset) + writes[0].offset += written + if writes[0].offset == writes[0].bytes.count { + let completed = writes.removeFirst() + writeBytes -= completed.bytes.count + completed.continuation.resume() + } + } + } + http?.tick() + try await Task.sleep(for: .milliseconds(1)) + } + } catch { + abort(error as? MCPConnectionIssue ?? .connectionFailed) + } + for pending in writes { + pending.continuation.resume(throwing: sink.failure ?? MCPConnectionIssue.connectionClosed) + } + writes.removeAll() + writeBytes = 0 + line.removeAll() + } + + func disconnect() async { + if let cleanupTask { + clean = await cleanupTask.value + return + } + abort(.connectionClosed) + pumpTask?.cancel() + let pump = pumpTask + let process = process + let http = http + let limits = sink.limits + let task = Task { + await pump?.value + if let process { + return await process.finish( + grace: .seconds(limits.cleanupGrace), + terminate: .seconds(limits.cleanupTerminate), killWait: .seconds(limits.cleanupKillWait)) + } + if let http { return await http.finish() } + return true + } + cleanupTask = task + clean = await task.value + self.process = nil + self.http = nil + pumpTask = nil + } + + func cleanupComplete() -> Bool { clean } + func resolvedExecutable() -> String? { executable } +} diff --git a/Sources/Components/MCPConnectionRunner.swift b/Sources/Components/MCPConnectionRunner.swift new file mode 100644 index 0000000..c39c193 --- /dev/null +++ b/Sources/Components/MCPConnectionRunner.swift @@ -0,0 +1,193 @@ +import AgentsCore +import Foundation +import MCP + +private final class MCPDeadline: @unchecked Sendable { + private let lock = NSLock() + let total: ContinuousClock.Instant + private var request: ContinuousClock.Instant + init(_ limits: MCPConnectionLimits, started: ContinuousClock.Instant) { + total = started + .seconds(limits.totalTimeout) + request = min(total, .now + .seconds(limits.requestTimeout)) + } + func arm(_ seconds: TimeInterval) { + lock.withLock { request = min(total, .now + .seconds(seconds)) } + } + var expired: Bool { lock.withLock { ContinuousClock.now >= min(total, request) } } +} + +private actor MCPDiscoveryProgress { + var version: String? + var tools: [MCPDiscoveredTool] = [] + func handshake(_ version: String) { self.version = version } + func append(_ next: [MCPDiscoveredTool]) { tools.append(contentsOf: next) } + func outcome(_ status: MCPConnectionOutcome.Status) -> MCPConnectionOutcome { + MCPConnectionOutcome( + status: status, negotiatedVersion: version, tools: tools, cleanupComplete: false) + } +} + +package enum MCPConnectionRunner { + private enum Event: Sendable { + case completed(MCPConnectionOutcome.Status) + case failed(MCPConnectionIssue) + } + + package static func run( + _ input: MCPConnectionInput, client identity: MCPConnectionClient, + limits: MCPConnectionLimits = .init() + ) async -> MCPConnectionOutcome { + let started = ContinuousClock.now + do { + try limits.validate() + try validate(input, limits: limits) + guard !identity.name.isEmpty, !identity.version.isEmpty, + [identity.name, identity.version].allSatisfy({ + !$0.utf8.contains(0) && $0.utf8.count <= limits.textBytes + }) + else { throw MCPConnectionIssue.invalidInput } + try Task.checkCancellation() + } catch { + return MCPConnectionOutcome( + status: .failed(error is CancellationError ? .cancelled : .invalidInput), + negotiatedVersion: nil, tools: [], cleanupComplete: true) + } + let deadline = MCPDeadline(limits, started: started) + if deadline.expired { + return MCPConnectionOutcome( + status: .failed(.timeout), negotiatedVersion: nil, tools: [], cleanupComplete: true) + } + let transport = MCPBoundedTransport(input, limits: limits) + let client = Client( + name: identity.name, version: identity.version, capabilities: .init(), configuration: .strict) + let progress = MCPDiscoveryProgress() + return await withTaskCancellationHandler { + await withTaskGroup(of: Event.self) { group in + group.addTask { + do { + let initialized = try await client.connect(transport: transport) + guard initialized.protocolVersion == transport.sink.version else { + throw MCPConnectionIssue.protocolError + } + await progress.handshake(initialized.protocolVersion) + guard initialized.capabilities.tools != nil else { return .completed(.noTools) } + var cursor: String? + var seen = Set() + var toolCount = 0 + var pages = 0 + repeat { + guard pages < limits.pages else { throw MCPConnectionIssue.pageLimit } + deadline.arm(limits.requestTimeout) + let request = + cursor.map { ListTools.request(.init(cursor: $0)) } ?? ListTools.request(.init()) + let context = try await client.send(request) + let result = try await context.value + pages += 1 + guard result.tools.count <= limits.tools - toolCount else { + throw MCPConnectionIssue.toolLimit + } + var tools: [MCPDiscoveredTool] = [] + for tool in result.tools { + guard + [tool.name, tool.title ?? "", tool.description ?? ""].allSatisfy({ + $0.utf8.count <= limits.textBytes + }) + else { throw MCPConnectionIssue.textLimit } + tools.append( + MCPDiscoveredTool( + name: tool.name, title: tool.title, description: tool.description)) + } + toolCount += tools.count + await progress.append(tools) + cursor = result.nextCursor + if let cursor { + guard cursor.utf8.count <= limits.frameBytes else { + throw MCPConnectionIssue.messageLimit + } + guard seen.insert(cursor).inserted else { throw MCPConnectionIssue.cursorCycle } + } + } while cursor != nil + return .completed(.discovered) + } catch { + return .failed(error as? MCPConnectionIssue ?? .protocolError) + } + } + group.addTask { + while !Task.isCancelled { + if deadline.expired { + transport.abort(.timeout) + return .failed(.timeout) + } + do { try await Task.sleep(for: .milliseconds(2)) } catch { break } + } + return .failed(.cancelled) + } + group.addTask { + for await issue in transport.sink.failures { return .failed(issue) } + return .failed(.connectionClosed) + } + var event = await group.next() ?? .failed(.connectionClosed) + if case .failed(.connectionClosed) = event, transport.sink.responsesAdmitted { + // EOF must not interrupt SDK decoding of responses already admitted to + // its queue. The existing request/total timer still bounds this join. + event = await group.next() ?? event + } + let transportIssue = transport.sink.failure + // A separate cleanup task is deliberately joined and is not cancelled + // with the caller: cancelling sleep must not skip EOF/TERM/KILL budgets. + let cleanup = Task { + transport.abort(.connectionClosed) + await client.disconnect() + // The runner joins the transport it created; disconnect is idempotent. + await transport.disconnect() + return await transport.cleanupComplete() + } + let clean = await cleanup.value + group.cancelAll() + while await group.next() != nil {} + let status: MCPConnectionOutcome.Status + switch event { + case .completed(let value): status = value + case .failed(let failure): + let issue = transportIssue ?? failure + let state = await progress.outcome(.failed(issue)) + status = state.negotiatedVersion == nil ? .failed(issue) : .incomplete(issue) + } + var outcome = await progress.outcome(clean ? status : .failed(.cleanupFailed)) + outcome.cleanupComplete = clean + outcome.resolvedExecutable = await transport.resolvedExecutable() + return outcome + } + } onCancel: { + transport.abort(.cancelled) + } + } + + private static func validate(_ input: MCPConnectionInput, limits: MCPConnectionLimits) throws { + var remaining = limits.inputBytes + func admit(_ string: String) throws { + // Charge the terminator as well, bounding arrays of empty arguments. + guard string.utf8.count < remaining else { throw MCPConnectionIssue.invalidInput } + remaining -= string.utf8.count + 1 + } + switch input { + case .stdio(let configuration): + try admit(configuration.executable) + try admit(configuration.directory.path) + for argument in configuration.arguments { try admit(argument) } + for (key, value) in configuration.environment { + try admit(key) + try admit(value) + } + case .streamableHTTP(let url, let headers), .legacySSE(let url, let headers): + try admit(url.absoluteString) + for (key, value) in headers { + try admit(key) + try admit(value) + } + guard MCPHTTPConnection.validURL(url), MCPHTTPConnection.validHeaders(headers) else { + throw MCPConnectionIssue.invalidInput + } + } + } +} diff --git a/Sources/Components/MCPConnectionTypes.swift b/Sources/Components/MCPConnectionTypes.swift new file mode 100644 index 0000000..61229dd --- /dev/null +++ b/Sources/Components/MCPConnectionTypes.swift @@ -0,0 +1,99 @@ +import AgentsCore +import Foundation + +/// Already-bound values borrowed only for this run. No serialization or public API. +package enum MCPConnectionInput: Sendable { + case stdio(DuplexProcessConfiguration) + case streamableHTTP(URL, headers: [String: String]) + case legacySSE(URL, headers: [String: String]) +} + +package struct MCPConnectionClient: Sendable { + package var name: String + package var version: String + package init(name: String, version: String) { + self.name = name + self.version = version + } +} + +package struct MCPConnectionLimits: Sendable { + package var totalTimeout: TimeInterval = 15 + package var requestTimeout: TimeInterval = 5 + package var cleanupGrace: TimeInterval = 0.1 + package var cleanupTerminate: TimeInterval = 0.1 + package var cleanupKillWait: TimeInterval = 1 + // Bytes: at most four 256 KiB frames queued, with 4 MiB aggregate input. + package var inputBytes = 256 * 1024 + package var frameBytes = 256 * 1024 + package var receivedBytes = 4 * 1024 * 1024 + package var sentBytes = 256 * 1024 + package var stderrBytes = 64 * 1024 + package var queueBytes = 1024 * 1024 + package var queueMessages = 4 + package var pages = 16 + package var tools = 256 + package var textBytes = 4096 + package var redirects = 4 + package var resumes = 2 + + package init() {} + + func validate() throws { + let times = [totalTimeout, requestTimeout, cleanupGrace, cleanupTerminate, cleanupKillWait] + guard times.allSatisfy({ $0.isFinite && $0 > 0 && $0 < Double(Int64.max) / 1_000_000_000 }), + [ + inputBytes, frameBytes, receivedBytes, sentBytes, stderrBytes, queueBytes, queueMessages, + pages, tools, textBytes, redirects, resumes, + ].allSatisfy({ $0 > 0 }), + queueBytes >= frameBytes + else { throw MCPConnectionIssue.invalidInput } + } +} + +package enum MCPConnectionIssue: String, Error, Sendable { + case invalidInput + case connectionFailed + case connectionClosed + case protocolError + case unsupportedVersion + case authenticationRequired + case forbidden + case authorityChanged + case sessionExpired + case messageLimit + case receiveLimit + case sendLimit + case stderrLimit + case queueLimit + case pageLimit + case toolLimit + case textLimit + case redirectLimit + case resumeLimit + case cursorCycle + case timeout + case cancelled + case cleanupFailed +} + +package struct MCPDiscoveredTool: Sendable { + package var name: String + package var title: String? + package var description: String? +} + +/// Private result values must be redacted by the facade before presentation. +package struct MCPConnectionOutcome: Sendable { + package enum Status: Sendable, Equatable { + case discovered + case noTools + case incomplete(MCPConnectionIssue) + case failed(MCPConnectionIssue) + } + package var status: Status + package var negotiatedVersion: String? + package var tools: [MCPDiscoveredTool] + package var cleanupComplete: Bool + package var resolvedExecutable: String? = nil +} diff --git a/Sources/Components/MCPHTTPConnection.swift b/Sources/Components/MCPHTTPConnection.swift new file mode 100644 index 0000000..fa64a98 --- /dev/null +++ b/Sources/Components/MCPHTTPConnection.swift @@ -0,0 +1,406 @@ +import Foundation +import MCP + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +/// One ephemeral session per explicit connection test. All job and endpoint +/// state is protected by lock; delegate callbacks never create Swift Tasks. +final class MCPHTTPConnection: NSObject, URLSessionDataDelegate, @unchecked Sendable { + enum Mode { case streamable, legacy } + private final class Job { + var request: URLRequest + let expected: ID? + let events: Bool + let legacyPost: Bool + var continuation: CheckedContinuation? + var parser: MCPSSEParser + var body = Data() + var sse = false + var json = false + var responseSeen = false + var redirects = 0 + var resumes = 0 + var retryAt = ContinuousClock.now + init( + request: URLRequest, expected: ID?, events: Bool, legacyPost: Bool, + continuation: CheckedContinuation?, limit: Int + ) { + self.request = request + self.expected = expected + self.events = events + self.legacyPost = legacyPost + self.continuation = continuation + parser = MCPSSEParser(limit: limit) + } + func finish(_ error: MCPConnectionIssue? = nil) { + let pending = continuation + continuation = nil + if let error { pending?.resume(throwing: error) } else { pending?.resume() } + } + } + + private let lock = NSLock() + private let sink: MCPMessageSink + private let mode: Mode + private let url: URL + private let headers: [String: String] + private let limits: MCPConnectionLimits + private var session: URLSession! + private var sessionID: String? + private var endpoint: URL? + private var endpointWaiter: CheckedContinuation? + private var active: [Int: Job] = [:] + private var resumes: [Job] = [] + private var closed = false + private var invalidated = false + + init(url: URL, headers: [String: String], mode: Mode, sink: MCPMessageSink) { + self.url = url + self.headers = headers + self.mode = mode + self.sink = sink + limits = sink.limits + super.init() + let configuration = URLSessionConfiguration.ephemeral + configuration.httpCookieStorage = nil + configuration.urlCache = nil + configuration.urlCredentialStorage = nil + configuration.httpShouldSetCookies = false + configuration.connectionProxyDictionary = [:] + configuration.timeoutIntervalForRequest = limits.totalTimeout + configuration.timeoutIntervalForResource = limits.totalTimeout + configuration.httpMaximumConnectionsPerHost = limits.queueMessages + let queue = OperationQueue() + queue.maxConcurrentOperationCount = 1 + session = URLSession(configuration: configuration, delegate: self, delegateQueue: queue) + } + + static func validURL(_ url: URL) -> Bool { + ["http", "https"].contains(url.scheme?.lowercased() ?? "") && url.host != nil + && url.user == nil && url.password == nil && url.fragment == nil + } + + static func validHeaders(_ headers: [String: String]) -> Bool { + let reserved = [ + "host", "content-length", "transfer-encoding", "connection", "content-type", "accept", + "mcp-session-id", "mcp-protocol-version", "last-event-id", + ] + let punctuation = Set("!#$%&'*+-.^_`|~".utf8) + var names = Set() + return headers.allSatisfy { key, value in + !key.isEmpty && names.insert(key.lowercased()).inserted + && !reserved.contains(key.lowercased()) + && key.utf8.allSatisfy { + (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) + || punctuation.contains($0) + } + && value.utf8.allSatisfy { $0 == 9 || ($0 >= 32 && $0 != 127) } + } + } + + private static func sameOrigin(_ first: URL, _ second: URL) -> Bool { + func port(_ url: URL) -> Int { url.port ?? (url.scheme?.lowercased() == "https" ? 443 : 80) } + return validURL(second) && first.scheme?.lowercased() == second.scheme?.lowercased() + && first.host?.lowercased() == second.host?.lowercased() && port(first) == port(second) + } + + private func request(_ target: URL, method: String, body: Data? = nil) -> URLRequest { + var request = URLRequest(url: target) + request.httpMethod = method + request.httpBody = body + for (name, value) in headers { request.setValue(value, forHTTPHeaderField: name) } + request.setValue("application/json, text/event-stream", forHTTPHeaderField: "Accept") + if body != nil { request.setValue("application/json", forHTTPHeaderField: "Content-Type") } + if mode == .streamable { + request.setValue(sink.version ?? Version.latest, forHTTPHeaderField: "MCP-Protocol-Version") + if let sessionID { request.setValue(sessionID, forHTTPHeaderField: "Mcp-Session-Id") } + } + return request + } + + private func startLocked(_ job: Job) throws { + guard !closed else { throw MCPConnectionIssue.connectionClosed } + guard active.count + resumes.count < limits.queueMessages else { + throw MCPConnectionIssue.queueLimit + } + let task = session.dataTask(with: job.request) + active[task.taskIdentifier] = job + task.resume() + } + + func connect() async throws { + if mode == .streamable { return } + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + lock.withLock { + guard !closed else { + continuation.resume(throwing: MCPConnectionIssue.connectionClosed) + return + } + endpointWaiter = continuation + do { + try startLocked( + Job( + request: request(url, method: "GET"), expected: nil, + events: true, legacyPost: false, continuation: nil, limit: limits.frameBytes)) + } catch { + endpointWaiter = nil + continuation.resume(throwing: MCPConnectionIssue.connectionFailed) + sink.fail(.connectionFailed) + } + } + } + } + + func send(_ data: Data, header: MCPWireHeader) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + lock.withLock { + guard !closed else { + continuation.resume(throwing: MCPConnectionIssue.connectionClosed) + return + } + let target = mode == .legacy ? endpoint : url + guard let target else { + continuation.resume(throwing: MCPConnectionIssue.protocolError) + return + } + let job = Job( + request: request(target, method: "POST", body: data), + expected: header.method == nil ? nil : header.id, + events: false, legacyPost: mode == .legacy, + continuation: continuation, limit: limits.frameBytes) + do { try startLocked(job) } catch { + let issue = error as? MCPConnectionIssue ?? .connectionFailed + job.finish(issue) + sink.fail(issue) + } + } + } + } + + /// A single transport pump owns bounded resumption scheduling; delegate + /// callbacks queue at most queueMessages resumptions and never replay POST. + func tick() { + lock.withLock { + guard !closed else { return } + while let index = resumes.firstIndex(where: { $0.retryAt <= .now }) { + let job = resumes.remove(at: index) + do { try startLocked(job) } catch { + job.finish(.connectionFailed) + sink.fail(.connectionFailed) + } + } + } + } + + func abort() { + let session: URLSession? = lock.withLock { + guard !closed else { return nil } + closed = true + endpointWaiter?.resume(throwing: MCPConnectionIssue.connectionClosed) + endpointWaiter = nil + for job in resumes { job.finish(.connectionClosed) } + resumes.removeAll() + return self.session + } + session?.invalidateAndCancel() + } + + func finish() async -> Bool { + abort() + let deadline = ContinuousClock.now + .seconds(limits.cleanupKillWait) + repeat { + if lock.withLock({ invalidated && active.isEmpty && resumes.isEmpty }) { return true } + try? await Task.sleep(for: .milliseconds(2)) + } while ContinuousClock.now < deadline + return false + } + + func urlSession( + _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, + completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void + ) { + let allow = lock.withLock { () -> Bool in + guard !closed, let job = active[dataTask.taskIdentifier], + let response = response as? HTTPURLResponse + else { return false } + let issue: MCPConnectionIssue? + switch response.statusCode { + case 401: issue = .authenticationRequired + case 403: issue = .forbidden + case 404 where sessionID != nil: issue = .sessionExpired + case 200, 202, 204: issue = nil + default: issue = .connectionFailed + } + if let issue { + sink.fail(issue) + return false + } + if let value = response.value(forHTTPHeaderField: "Mcp-Session-Id"), mode == .streamable { + guard !value.isEmpty, value.utf8.count <= 1024, + value.utf8.allSatisfy({ $0 >= 33 && $0 <= 126 }), + sessionID == nil || sessionID == value + else { + sink.fail(.protocolError) + return false + } + sessionID = value + } + let type = response.value(forHTTPHeaderField: "Content-Type")?.split(separator: ";").first? + .trimmingCharacters(in: .whitespaces).lowercased() + job.sse = type == "text/event-stream" + job.json = type == "application/json" + if job.events || (job.expected != nil && !job.legacyPost) { + guard response.statusCode == 200, job.sse || (!job.events && job.json) else { + sink.fail(.protocolError) + return false + } + } + return true + } + completionHandler(allow ? .allow : .cancel) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive bytes: Data) { + lock.withLock { + guard !closed, let job = active[dataTask.taskIdentifier] else { return } + do { + try sink.receiveBytes(bytes.count) + if job.legacyPost { return } + if job.expected == nil && !job.events && !bytes.isEmpty { + throw MCPConnectionIssue.protocolError + } + if job.sse { + var parser = job.parser + try parser.feed(bytes) { event in + if mode == .legacy && job.events && event.name == "endpoint" { + guard endpoint == nil, let text = String(data: event.data, encoding: .utf8), + let candidate = URL(string: text, relativeTo: url)?.absoluteURL, + Self.sameOrigin(url, candidate) + else { throw MCPConnectionIssue.authorityChanged } + endpoint = candidate + endpointWaiter?.resume() + endpointWaiter = nil + } else if event.name.isEmpty || event.name == "message" { + try sink.admit(event.data) + if let expected = job.expected, + let header = try? JSONDecoder().decode(MCPWireHeader.self, from: event.data), + header.id == expected && header.method == nil + { + job.responseSeen = true + } + } + } + job.parser = parser + } else if job.json { + guard bytes.count <= limits.frameBytes - job.body.count else { + throw MCPConnectionIssue.messageLimit + } + job.body.append(bytes) + } else if !bytes.isEmpty { + throw MCPConnectionIssue.protocolError + } + } catch { + sink.fail(error as? MCPConnectionIssue ?? .protocolError) + dataTask.cancel() + } + } + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + lock.withLock { + guard let job = active.removeValue(forKey: task.taskIdentifier) else { return } + if closed || sink.failure != nil { + job.finish(sink.failure ?? .connectionClosed) + return + } + do { + if (error as? URLError)?.code == .timedOut { throw MCPConnectionIssue.timeout } + if job.json && job.expected != nil && !job.legacyPost { + if error != nil { throw MCPConnectionIssue.connectionFailed } + let header = try? JSONDecoder().decode(MCPWireHeader.self, from: job.body) + guard header?.id == job.expected, header?.method == nil else { + throw MCPConnectionIssue.protocolError + } + try sink.admit(job.body) + job.responseSeen = true + } + if job.events { throw MCPConnectionIssue.connectionClosed } + if job.sse && job.expected != nil && !job.responseSeen && mode == .streamable, + let id = job.parser.lastID, !id.isEmpty + { + guard job.resumes < limits.resumes else { throw MCPConnectionIssue.resumeLimit } + let delay = job.parser.retry ?? 0 + guard delay < limits.totalTimeout else { throw MCPConnectionIssue.timeout } + job.resumes += 1 + job.retryAt = .now + .seconds(delay) + job.request = request(url, method: "GET") + job.request.setValue(id, forHTTPHeaderField: "Last-Event-ID") + job.parser.restart() + resumes.append(job) + return + } + if error != nil { throw MCPConnectionIssue.connectionFailed } + if job.expected != nil && !job.legacyPost && !job.responseSeen { + throw MCPConnectionIssue.protocolError + } + job.finish() + } catch { + let issue = error as? MCPConnectionIssue ?? .connectionFailed + job.finish(issue) + sink.fail(issue) + } + } + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, + completionHandler: @escaping @Sendable (URLRequest?) -> Void + ) { + let next: URLRequest? = lock.withLock { + guard !closed, let job = active[task.taskIdentifier], let target = request.url, + Self.sameOrigin(url, target) + else { + sink.fail(.authorityChanged) + return nil + } + guard job.redirects < limits.redirects else { + sink.fail(.redirectLimit) + return nil + } + guard request.httpMethod == job.request.httpMethod else { + sink.fail(.protocolError) + return nil + } + job.redirects += 1 + job.request.url = target + return job.request + } + completionHandler(next) + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, + completionHandler: + @escaping @Sendable (URLSession.AuthChallengeDisposition, URLCredential?) -> Void + ) { + #if canImport(Security) + if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + completionHandler(.performDefaultHandling, nil) + return + } + #endif + sink.fail(.authenticationRequired) + completionHandler(.cancelAuthenticationChallenge, nil) + } + + func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + lock.withLock { + invalidated = true + for job in active.values { job.finish(.connectionClosed) } + active.removeAll() + } + } +} diff --git a/Sources/Components/MCPMessageSink.swift b/Sources/Components/MCPMessageSink.swift new file mode 100644 index 0000000..b2c949f --- /dev/null +++ b/Sources/Components/MCPMessageSink.swift @@ -0,0 +1,217 @@ +import Foundation +import MCP + +struct MCPWireHeader: Decodable { + var id: ID? + var method: String? +} + +/// The delegate and stdio pump share one locked admission boundary. Stream +/// capacity times frameBytes never exceeds queueBytes, even for a slow consumer. +final class MCPMessageSink: @unchecked Sendable { + let stream: AsyncThrowingStream + let failures: AsyncStream + private let continuation: AsyncThrowingStream.Continuation + private let failureContinuation: AsyncStream.Continuation + private let lock = NSLock() + let limits: MCPConnectionLimits + private var received = 0 + private var sent = 0 + private var stderr = 0 + private var issue: MCPConnectionIssue? + private var pendingResponses = Set() + private var initializeID: ID? + private var negotiated: String? + + init(_ limits: MCPConnectionLimits) { + self.limits = limits + (stream, continuation) = AsyncThrowingStream.makeStream( + bufferingPolicy: .bufferingOldest( + min(limits.queueMessages, limits.queueBytes / limits.frameBytes))) + (failures, failureContinuation) = AsyncStream.makeStream(bufferingPolicy: .bufferingOldest(1)) + } + + var failure: MCPConnectionIssue? { lock.withLock { issue } } + var version: String? { lock.withLock { negotiated } } + var responsesAdmitted: Bool { lock.withLock { pendingResponses.isEmpty } } + + func fail(_ error: MCPConnectionIssue) { + lock.withLock { finishLocked(error) } + } + + private func finishLocked(_ error: MCPConnectionIssue) { + guard issue == nil else { return } + issue = error + continuation.finish(throwing: error) + failureContinuation.yield(error) + failureContinuation.finish() + } + + func receiveBytes(_ count: Int, standardError: Bool = false) throws { + try lock.withLock { + if let issue { throw issue } + if standardError { + guard count <= limits.stderrBytes - stderr else { + finishLocked(.stderrLimit) + throw MCPConnectionIssue.stderrLimit + } + stderr += count + } else { + guard count <= limits.receivedBytes - received else { + finishLocked(.receiveLimit) + throw MCPConnectionIssue.receiveLimit + } + received += count + } + } + } + + /// Call before I/O. Initialize belongs to SDK Client, not the runner. + func prepare(_ data: Data) throws -> MCPWireHeader { + try lock.withLock { + if let issue { throw issue } + guard data.count <= limits.frameBytes else { throw MCPConnectionIssue.messageLimit } + guard data.count < limits.sentBytes - sent else { throw MCPConnectionIssue.sendLimit } + sent += data.count + 1 // Includes the stdio newline; conservatively shared by HTTP. + let header: MCPWireHeader + do { header = try JSONDecoder().decode(MCPWireHeader.self, from: data) } catch { + throw MCPConnectionIssue.protocolError + } + if header.method == Initialize.name { + guard initializeID == nil else { throw MCPConnectionIssue.protocolError } + guard let id = header.id else { throw MCPConnectionIssue.protocolError } + initializeID = id + } else if header.method == InitializedNotification.name { + guard negotiated != nil else { throw MCPConnectionIssue.unsupportedVersion } + } else if let method = header.method, method != ListTools.name { + throw MCPConnectionIssue.protocolError + } + if header.method != nil, let id = header.id { pendingResponses.insert(id) } + return header + } + } + + /// Raw bytes have already been counted, and the frame bound precedes SDK decode. + func admit(_ data: Data) throws { + try lock.withLock { + if let issue { throw issue } + guard data.count <= limits.frameBytes else { + finishLocked(.messageLimit) + throw MCPConnectionIssue.messageLimit + } + let header = try? JSONDecoder().decode(MCPWireHeader.self, from: data) + if negotiated == nil && header?.method == nil { + let response: Response + do { response = try JSONDecoder().decode(Response.self, from: data) } catch { + finishLocked(.protocolError) + throw MCPConnectionIssue.protocolError + } + guard response.id == initializeID else { + finishLocked(.protocolError) + throw MCPConnectionIssue.protocolError + } + if case .success(let result) = response.result { + guard Version.supported.contains(result.protocolVersion) else { + finishLocked(.unsupportedVersion) + throw MCPConnectionIssue.unsupportedVersion + } + negotiated = result.protocolVersion + } + } + switch continuation.yield(data) { + case .enqueued: + if header?.method == nil, let id = header?.id { pendingResponses.remove(id) } + case .dropped: + finishLocked(.queueLimit) + throw MCPConnectionIssue.queueLimit + case .terminated: + finishLocked(.connectionClosed) + throw MCPConnectionIssue.connectionClosed + @unknown default: + finishLocked(.connectionClosed) + throw MCPConnectionIssue.connectionClosed + } + } + } +} + +/// Incremental SSE line/event parser. All raw bytes, including comments, are +/// counted by its caller; neither an unterminated line nor event can grow freely. +struct MCPSSEParser { + struct Event { + var name: String + var data: Data + var id: String? + var retry: TimeInterval? + } + private var line = Data() + private var data = Data() + private var name = "" + private(set) var lastID: String? + private(set) var retry: TimeInterval? + private var afterCR = false + private var firstLine = true + let limit: Int + + mutating func restart() { + line.removeAll(keepingCapacity: true) + data.removeAll(keepingCapacity: true) + name = "" + afterCR = false + firstLine = true + } + + mutating func feed(_ bytes: Data, emit: (Event) throws -> Void) throws { + for byte in bytes { + if byte == 10 && afterCR { + afterCR = false + continue + } + afterCR = byte == 13 + if byte == 10 || byte == 13 { + try endLine(emit) + } else { + guard line.count < limit else { throw MCPConnectionIssue.messageLimit } + line.append(byte) + } + } + } + + private mutating func endLine(_ emit: (Event) throws -> Void) throws { + defer { + line.removeAll(keepingCapacity: true) + firstLine = false + } + if firstLine && line.starts(with: [0xEF, 0xBB, 0xBF]) { line.removeFirst(3) } + if line.isEmpty { + if !data.isEmpty { + data.removeLast() // SSE removes the final data-field newline. + try emit(Event(name: name, data: data, id: lastID, retry: retry)) + } + data.removeAll(keepingCapacity: true) + name = "" + return + } + if line.first == 58 { return } + let separator = line.firstIndex(of: 58) ?? line.endIndex + let field = String(decoding: line[..= 48 && $0 <= 57 }), + let milliseconds = UInt64(String(decoding: value, as: UTF8.self)) + { + retry = Double(milliseconds) / 1000 + } + default: break + } + } +} diff --git a/Tests/ComponentsTests/Fixtures/MCPHTTPServer.py b/Tests/ComponentsTests/Fixtures/MCPHTTPServer.py new file mode 100644 index 0000000..d7dee57 --- /dev/null +++ b/Tests/ComponentsTests/Fixtures/MCPHTTPServer.py @@ -0,0 +1,89 @@ +"""Owned loopback fixture. Synthetic MCP frames; no external service/client.""" +import http.server,json,os,queue,socket,sys,threading,time +from pathlib import Path +mode,root=sys.argv[1],Path(sys.argv[2]) +messages=queue.Queue(maxsize=32) +record_lock=threading.Lock() +last_initialize=None +resume_reply=None + +def record(value): + with record_lock: + with (root/'wire.jsonl').open('a') as f:f.write(json.dumps(value)+'\n') + +def result(message): + method=message.get('method') + if method=='initialize': + return {'protocolVersion':'2025-11-25','capabilities':{'tools':{}},'serverInfo':{'name':'http-fixture','version':'1'}} + cursor=message.get('params',{}).get('cursor') + value={'tools':[{'name':'first' if not cursor else 'second','inputSchema':{'type':'object'}}]} + if not cursor:value['nextCursor']='next' + return value + +class Handler(http.server.BaseHTTPRequestHandler): + protocol_version='HTTP/1.1' + def log_message(self,*args):pass + def log_request_data(self,method): + record({'http':self.command,'path':self.path,'method':method, + 'authorization':self.headers.get('Authorization') is not None, + 'session':self.headers.get('Mcp-Session-Id'),'version':self.headers.get('MCP-Protocol-Version'), + 'lastEventID':self.headers.get('Last-Event-ID')}) + def empty(self,status,headers={}): + self.send_response(status) + for key,value in headers.items():self.send_header(key,value) + self.send_header('Content-Length','0');self.end_headers() + def do_POST(self): + global resume_reply,last_initialize + body=self.rfile.read(int(self.headers.get('Content-Length','0'))) + message=json.loads(body) + self.log_request_data(message.get('method','response')) + if mode=='auth':self.empty(401,{'WWW-Authenticate':'Basic realm="fixture"'});return + if mode=='forbidden':self.empty(403);return + if mode=='redirect':self.empty(307,{'Location':'http://localhost:%d/leak'%self.server.server_port});return + if 'id' not in message:self.empty(202);return + reply=json.dumps({'jsonrpc':'2.0','id':message['id'],'result':result(message)}).encode() + if mode.startswith('legacy'): + messages.put(reply);self.empty(202);return + self.send_response(200) + self.send_header('Mcp-Session-Id','fixture-session') + if mode=='json': + self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(reply)));self.end_headers();self.wfile.write(reply);return + self.send_header('Content-Type','text/event-stream');self.send_header('Connection','close');self.end_headers() + try: + if mode=='pending-body': + while True:self.wfile.write(b'data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"fixture","progress":1}}\n\n');self.wfile.flush();time.sleep(.01) + elif mode=='event-flood': + self.wfile.write(b'data: '+b'x'*65536);self.wfile.flush() + elif mode=='comment-flood': + while True:self.wfile.write(b':'+b'x'*255+b'\n');self.wfile.flush() + elif mode=='resume' and message['method']=='initialize': + resume_reply=reply + self.wfile.write(b'id: first-event\nretry: 1\ndata: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"probe","progress":1}}\n\n') + self.wfile.flush() + else: + # Split a multiline data event inside its field name and use CRLF. + self.wfile.write(b'event: message\r\nid: response\r\nda');self.wfile.flush() + time.sleep(.005) + payload=b'\r\ndata: '.join(json.dumps(json.loads(reply),indent=1).encode().splitlines()) + self.wfile.write(b'ta: '+payload+b'\r\n\r\n');self.wfile.flush() + except (BrokenPipeError,ConnectionResetError):record({'peerClosed':True}) + self.close_connection=True + def do_GET(self): + self.log_request_data(None) + self.send_response(200);self.send_header('Content-Type','text/event-stream');self.send_header('Connection','close');self.end_headers() + try: + if mode=='resume': + self.wfile.write(b'event: message\ndata: '+resume_reply+b'\n\n');self.wfile.flush();self.close_connection=True;return + endpoint=('/messages' if mode!='legacy-cross' else 'http://localhost:%d/messages'%self.server.server_port).encode() + self.wfile.write(b'event: endpoint\ndata: '+endpoint+b'\n\n');self.wfile.flush() + while True: + try:reply=messages.get(timeout=.05);self.wfile.write(b'event: message\ndata: '+reply+b'\n\n') + except queue.Empty:self.wfile.write(b': heartbeat\n\n') + self.wfile.flush() + except (BrokenPipeError,ConnectionResetError):record({'peerClosed':True}) + self.close_connection=True + +server=http.server.ThreadingHTTPServer(('127.0.0.1',0),Handler) +server.daemon_threads=True +(root/'port').write_text(str(server.server_port)) +server.serve_forever() diff --git a/Tests/ComponentsTests/MCPConnectionTests.swift b/Tests/ComponentsTests/MCPConnectionTests.swift new file mode 100644 index 0000000..91c2940 --- /dev/null +++ b/Tests/ComponentsTests/MCPConnectionTests.swift @@ -0,0 +1,343 @@ +import AgentsCore +import CPlatform +import Foundation +import Testing + +@testable import Components + +private final class MCPTestBundle: NSObject {} + +private final class MCPFixture { + let root: URL + private var server: Process? + static var executable: URL { + var directory = Bundle(for: MCPTestBundle.self).bundleURL + for _ in 0..<8 { + let candidate = directory.appendingPathComponent("MCPTestProcess") + if FileManager.default.isExecutableFile(atPath: candidate.path) { return candidate } + directory.deleteLastPathComponent() + } + return directory.appendingPathComponent("MCPTestProcess") + } + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "mcp-io-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + var environment: [String: String] { + [ + "PATH": MCPFixture.executable.deletingLastPathComponent().path + ":/usr/bin:/bin", + "HOME": root.path, "FIXTURE_VALUE": "explicit-environment", + ] + } + func input(_ mode: String, extra: [String: String] = [:]) -> MCPConnectionInput { + .stdio(configuration(mode, extra: extra)) + } + func configuration(_ mode: String, extra: [String: String] = [:]) -> DuplexProcessConfiguration { + DuplexProcessConfiguration( + executable: "MCPTestProcess", arguments: [mode, root.path], directory: root, + environment: environment.merging(extra, uniquingKeysWith: { _, new in new })) + } + func text(_ name: String) -> String? { + try? String(contentsOf: root.appendingPathComponent(name), encoding: .utf8) + } + func records() -> [[String: Any]] { + (text("wire.jsonl") ?? "").split(separator: "\n").compactMap { + (try? JSONSerialization.jsonObject(with: Data($0.utf8))) as? [String: Any] + } + } + func methods() -> [String] { records().compactMap { $0["method"] as? String } } + func waitFor(_ predicate: () -> Bool) async -> Bool { + let deadline = ContinuousClock.now + .seconds(3) + while !predicate() { + if ContinuousClock.now >= deadline { return false } + try? await Task.sleep(for: .milliseconds(2)) + } + return true + } + func startHTTP(_ mode: String) async throws -> URL { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/env") + let file = Bundle.module.url( + forResource: "MCPHTTPServer", withExtension: "py", subdirectory: "Fixtures")! + process.arguments = ["python3", file.path, mode, root.path] + var environment = self.environment + // Python is an existing test tool, not a downloaded service/client. + environment["PATH"] = "/usr/bin:/bin:/opt/homebrew/bin" + process.environment = environment + process.standardOutput = FileHandle.nullDevice + process.standardError = FileHandle.nullDevice + try process.run() + server = process + guard await waitFor({ self.text("port") != nil }), let port = text("port") else { + throw MCPConnectionIssue.connectionFailed + } + return URL(string: "http://127.0.0.1:" + port + "/mcp")! + } + func stopHTTP() { + if let server, server.isRunning { + _ = kill(server.processIdentifier, SIGTERM) + let deadline = Date().addingTimeInterval(2) + while server.isRunning && Date() < deadline { usleep(1000) } + if server.isRunning { _ = kill(server.processIdentifier, SIGKILL) } + let killedDeadline = Date().addingTimeInterval(2) + while server.isRunning && Date() < killedDeadline { usleep(1000) } + if server.isRunning { Issue.record("Owned HTTP fixture did not terminate") } + } + server = nil + } + deinit { + stopHTTP() + try? FileManager.default.removeItem(at: root) + } +} + +private func runConnection(_ input: MCPConnectionInput, limits: MCPConnectionLimits = .init()) async + -> MCPConnectionOutcome +{ + await MCPConnectionRunner.run( + input, client: MCPConnectionClient(name: "fixture-client", version: "1"), limits: limits) +} + +@Suite(.serialized) struct MCPConnectionTests { + @Test func stdioDiscoversOnlyToolsAndInheritsExplicitValues() async throws { + let fixture = try MCPFixture() + let file = fixture.root.appendingPathComponent("lock") + let original = open(file.path, O_RDWR | O_CREAT, 0o600) + #expect(original >= 0) + let high = fcntl(original, F_DUPFD, 200) + defer { + close(original) + if high >= 0 { close(high) } + } + let result = await runConnection(fixture.input("normal", extra: ["FD_CHECK": String(high)])) + #expect(result.status == .discovered) + #expect(result.negotiatedVersion == "2025-11-25") + #expect(result.tools.map(\.name) == ["first", "second"]) + #expect(result.cleanupComplete) + #expect( + fixture.methods() == ["initialize", "notifications/initialized", "tools/list", "tools/list"]) + let startup = try #require(fixture.records().first) + let cwd = try #require(startup["cwd"] as? String) + let actual = try FileManager.default.attributesOfItem(atPath: cwd) + let expected = try FileManager.default.attributesOfItem(atPath: fixture.root.path) + #expect(actual[.systemNumber] as? NSNumber == expected[.systemNumber] as? NSNumber) + #expect(actual[.systemFileNumber] as? NSNumber == expected[.systemFileNumber] as? NSNumber) + #expect(startup["environment"] as? String == "explicit-environment") + #expect(startup["inheritedFD"] as? Bool == false) + let initialize = try #require( + fixture.records().first { $0["method"] as? String == "initialize" }) + #expect( + ((initialize["params"] as? [String: Any])?["capabilities"] as? [String: Any])?.isEmpty == true + ) + let pid = try #require(Int32(fixture.text("pid") ?? "")) + #expect(kill(pid, 0) == -1 && errno == ESRCH) + } + + @Test(arguments: ["wrong-version", "no-tools", "cursor-cycle", "stdout-flood", "stderr-flood"]) + func wireAndBudgetFailures(_ mode: String) async throws { + let fixture = try MCPFixture() + var limits = MCPConnectionLimits() + limits.frameBytes = 1024 + limits.stderrBytes = 1024 + let result = await runConnection(fixture.input(mode), limits: limits) + let expected: MCPConnectionOutcome.Status + switch mode { + case "wrong-version": expected = .failed(.unsupportedVersion) + case "no-tools": expected = .noTools + case "cursor-cycle": expected = .incomplete(.cursorCycle) + case "stdout-flood": expected = .failed(.messageLimit) + default: expected = .failed(.stderrLimit) + } + #expect(result.status == expected) + #expect(result.cleanupComplete) + if mode == "wrong-version" { #expect(fixture.methods() == ["initialize"]) } + if mode == "no-tools" { + #expect(fixture.methods() == ["initialize", "notifications/initialized"]) + } + } + + @Test(arguments: ["pending-initialize", "pending-tools"]) + func requestDeadlineActuallyReaps(_ mode: String) async throws { + let fixture = try MCPFixture() + var limits = MCPConnectionLimits() + limits.totalTimeout = 1 + limits.requestTimeout = 0.08 + let result = await runConnection(fixture.input(mode), limits: limits) + #expect( + result.status == (mode == "pending-initialize" ? .failed(.timeout) : .incomplete(.timeout))) + #expect(result.cleanupComplete) + let pid = try #require(Int32(fixture.text("pid") ?? "")) + #expect(kill(pid, 0) == -1) + } + + @Test func cancellationKillsStubbornChildAndLeavesSameNameProcess() async throws { + let fixture = try MCPFixture() + let unrelated = Process() + let other = try MCPFixture() + unrelated.executableURL = MCPFixture.executable + unrelated.arguments = ["ignore-input", other.root.path] + unrelated.environment = other.environment + try unrelated.run() + defer { + _ = kill(unrelated.processIdentifier, SIGKILL) + let deadline = Date().addingTimeInterval(2) + while unrelated.isRunning && Date() < deadline { usleep(1000) } + if unrelated.isRunning { Issue.record("Owned unrelated-process fixture did not terminate") } + } + #expect(await other.waitFor { other.text("holder-ready") != nil }) + let input = fixture.input("stubborn") + let task = Task { await runConnection(input) } + #expect(await fixture.waitFor { fixture.text("stubborn-ready") != nil }) + task.cancel() + let result = await task.value + #expect(result.status == .incomplete(.cancelled)) + #expect(result.cleanupComplete) + let pid = try #require(Int32(fixture.text("pid") ?? "")) + #expect(kill(pid, 0) == -1) + #expect(unrelated.isRunning) + } + + @Test func groupCleanupAfterLeaderEOFStopsDescendant() async throws { + let fixture = try MCPFixture() + let result = await runConnection(fixture.input("descendant")) + #expect(result.status == .discovered) + #expect(result.cleanupComplete) + let pid = try #require(Int32(fixture.text("pid") ?? "")) + #expect(kill(pid, 0) == -1) + guard let child = fixture.text("descendant-pid").flatMap({ Int32($0) }) else { + Issue.record("Missing owned descendant") + return + } + #if os(Linux) + let stat = try? String(contentsOfFile: "/proc/\(child)/stat", encoding: .utf8) + #expect(stat == nil || stat!.split(separator: ")").last!.hasPrefix(" Z")) + #else + #expect(await fixture.waitFor { kill(child, 0) == -1 }) + #endif + } + + @Test func blockedKernelPipeWriteIsNonblockingAndCleanupIsFinite() async throws { + let fixture = try MCPFixture() + let process = try OwnedDuplexProcess(fixture.configuration("ignore-input")) + #expect(await fixture.waitFor { fixture.text("holder-ready") != nil }) + let bytes = Data(repeating: 120, count: 256 * 1024) + var offset = 0 + while offset < bytes.count { + let count = try process.write(bytes, offset: offset) + if count == 0 { break } + offset += count + } + #expect(offset < bytes.count) + let cleaned = await process.finish( + grace: .milliseconds(5), terminate: .milliseconds(5), killWait: .seconds(1)) + #expect(cleaned) + #expect(kill(process.identifier, 0) == -1) + } + + @Test func finiteDiscoveryAndInputAdmission() async throws { + let fixture = try MCPFixture() + var limits = MCPConnectionLimits() + limits.pages = 1 + let result = await runConnection(fixture.input("normal"), limits: limits) + #expect(result.status == .incomplete(.pageLimit)) + #expect(result.tools.count == 1) + #expect(fixture.methods().filter { $0 == "tools/list" }.count == 1) + let originalWire = fixture.text("wire.jsonl") + limits.totalTimeout = .infinity + let invalid = await runConnection(fixture.input("normal"), limits: limits) + #expect(invalid.status == .failed(.invalidInput)) + #expect(invalid.cleanupComplete) + #expect(fixture.text("wire.jsonl") == originalWire) + } + + @Test(arguments: ["tool", "text", "send"]) + func discoveryAndOutputBudgets(_ mode: String) async throws { + let fixture = try MCPFixture() + var limits = MCPConnectionLimits() + if mode == "tool" { limits.tools = 1 } + if mode == "text" { limits.textBytes = 16 } + if mode == "send" { limits.sentBytes = 64 } + let input = fixture.input(mode == "text" ? "long-text" : "normal") + let result = await runConnection(input, limits: limits) + let expected: MCPConnectionOutcome.Status = + mode == "tool" + ? .incomplete(.toolLimit) + : mode == "text" ? .incomplete(.textLimit) : .failed(.sendLimit) + #expect(result.status == expected) + #expect(result.cleanupComplete) + if mode == "send" { #expect(fixture.methods().isEmpty) } + } + + @Test(arguments: ["eof-initialize", "eof-tools"]) + func stdioEOFJoinsPendingRequestsAndDrainsAcceptedResponse(_ mode: String) async throws { + let fixture = try MCPFixture() + var limits = MCPConnectionLimits() + limits.frameBytes = 1024 * 1024 + limits.tools = 1000 + let result = await runConnection(fixture.input(mode), limits: limits) + #expect(result.status == (mode == "eof-tools" ? .discovered : .failed(.connectionClosed))) + #expect(result.cleanupComplete) + if mode == "eof-tools" { #expect(result.tools.count == 1000) } + } + + @Test(arguments: ["json", "sse", "legacy", "resume"]) + func actualHTTPModesDiscoverAndCleanUp(_ mode: String) async throws { + let fixture = try MCPFixture() + let url = try await fixture.startHTTP(mode) + let input: MCPConnectionInput = + mode == "legacy" ? .legacySSE(url, headers: [:]) : .streamableHTTP(url, headers: [:]) + let result = await runConnection(input) + #expect(result.status == .discovered) + #expect(result.cleanupComplete) + #expect(result.tools.map(\.name) == ["first", "second"]) + fixture.stopHTTP() + #expect( + fixture.methods() == ["initialize", "notifications/initialized", "tools/list", "tools/list"]) + if mode != "legacy" { + let posts = fixture.records().filter { $0["http"] as? String == "POST" } + #expect( + posts.dropFirst().allSatisfy { + $0["session"] as? String == "fixture-session" && $0["version"] as? String == "2025-11-25" + }) + } + if mode == "resume" { + #expect( + fixture.records().contains { + $0["http"] as? String == "GET" && $0["lastEventID"] as? String == "first-event" + }) + } + } + + @Test(arguments: [ + "auth", "forbidden", "redirect", "legacy-cross", "event-flood", "comment-flood", "pending-body", + ]) + func httpAuthorityAndStreamBounds(_ mode: String) async throws { + let fixture = try MCPFixture() + let url = try await fixture.startHTTP(mode) + var limits = MCPConnectionLimits() + limits.frameBytes = 1024 + limits.receivedBytes = 8192 + if mode == "event-flood" { limits.receivedBytes = 128 * 1024 } + limits.totalTimeout = 0.12 + limits.requestTimeout = 1 + let headers = ["Authorization": "fixture-canary"] + let input: MCPConnectionInput = + mode.hasPrefix("legacy") + ? .legacySSE(url, headers: headers) : .streamableHTTP(url, headers: headers) + let result = await runConnection(input, limits: limits) + let expected: MCPConnectionIssue + switch mode { + case "auth": expected = .authenticationRequired + case "forbidden": expected = .forbidden + case "redirect", "legacy-cross": expected = .authorityChanged + case "event-flood": expected = .messageLimit + case "comment-flood": expected = .receiveLimit + default: expected = .timeout + } + #expect(result.status == .failed(expected)) + #expect(result.cleanupComplete) + fixture.stopHTTP() + #expect(fixture.records().filter { $0["http"] != nil }.count == 1) + } +} diff --git a/Tests/MCPTestProcess/main.swift b/Tests/MCPTestProcess/main.swift new file mode 100644 index 0000000..a6250f5 --- /dev/null +++ b/Tests/MCPTestProcess/main.swift @@ -0,0 +1,140 @@ +import CPlatform +import Foundation + +#if os(Linux) + import Glibc +#else + import Darwin +#endif + +let arguments = CommandLine.arguments +let scenario = arguments.count > 1 ? arguments[1] : "normal" +let root = URL(fileURLWithPath: arguments.count > 2 ? arguments[2] : "/tmp") +func record(_ value: [String: Any]) { + guard let data = try? JSONSerialization.data(withJSONObject: value) else { return } + let file = root.appendingPathComponent("wire.jsonl") + if !FileManager.default.fileExists(atPath: file.path) { + _ = FileManager.default.createFile(atPath: file.path, contents: nil) + } + if let handle = try? FileHandle(forWritingTo: file) { + handle.seekToEndOfFile() + handle.write(data) + handle.write(Data([10])) + try? handle.close() + } +} +func output(_ data: Data, fd: Int32 = 1) { + var offset = 0 + while offset < data.count { + let size = data.withUnsafeBytes { + platform_duplex_write(fd, $0.baseAddress!.advanced(by: offset), data.count - offset) + } + if size <= 0 { exit(0) } + offset += size + } +} +func response(_ id: Any, _ result: [String: Any]) { + if let bytes = try? JSONSerialization.data(withJSONObject: [ + "jsonrpc": "2.0", "id": id, "result": result, + ]) { + output(bytes + Data([10])) + } +} +try? String(getpid()).write( + to: root.appendingPathComponent(scenario == "holder" ? "holder-pid" : "pid"), atomically: true, + encoding: .utf8) +if scenario == "holder" || scenario == "ignore-input" { + _ = signal(SIGTERM, SIG_IGN) + try? "ready".write( + to: root.appendingPathComponent("holder-ready"), atomically: true, encoding: .utf8) + while true { _ = sleep(1) } +} +if scenario == "descendant" { + let argv = [arguments[0], "holder", root.path].map { strdup($0) } + [nil] + let environment = + ProcessInfo.processInfo.environment.map { strdup($0.key + "=" + $0.value) } + [nil] + var pid: pid_t = 0 + if posix_spawn(&pid, arguments[0], nil, nil, argv, environment) != 0 { exit(2) } + for pointer in argv + environment { free(pointer) } + try? String(pid).write( + to: root.appendingPathComponent("descendant-pid"), atomically: true, encoding: .utf8) + for _ in 0..<2000 { + if FileManager.default.fileExists(atPath: root.appendingPathComponent("holder-ready").path) { + break + } + usleep(1000) + } +} +let fd = Int32(ProcessInfo.processInfo.environment["FD_CHECK"] ?? "-1") ?? -1 +record([ + "startup": true, "cwd": FileManager.default.currentDirectoryPath, + "environment": ProcessInfo.processInfo.environment["FIXTURE_VALUE"] ?? "absent", + "inheritedFD": fd >= 0 && fcntl(fd, F_GETFD) >= 0, +]) +var line = Data() +while true { + var byte: UInt8 = 0 + let count = read(0, &byte, 1) + if count == 0 { exit(0) } + if count < 0 { + if errno == EINTR { continue } + exit(1) + } + if byte != 10 { + line.append(byte) + if line.count > 1_048_576 { exit(2) } + continue + } + defer { line.removeAll(keepingCapacity: true) } + guard let message = try? JSONSerialization.jsonObject(with: line) as? [String: Any], + let method = message["method"] as? String + else { continue } + record(["method": method, "params": message["params"] ?? [:]]) + guard let id = message["id"] else { continue } + if method == "initialize" { + if scenario == "eof-initialize" { exit(0) } + if scenario == "pending-initialize" { continue } + if scenario == "stdout-flood" { + output(Data(repeating: 120, count: 65536)) + continue + } + if scenario == "stderr-flood" { + output(Data(repeating: 120, count: 65536), fd: 2) + continue + } + let capabilities: [String: Any] = scenario == "no-tools" ? [:] : ["tools": [:]] + response( + id, + [ + "protocolVersion": scenario == "wrong-version" ? "2099-01-01" : "2025-11-25", + "capabilities": capabilities, "serverInfo": ["name": "local-fixture", "version": "1"], + ]) + } else if method == "tools/list" { + if scenario == "eof-tools" { + let tools: [[String: Any]] = (0..<1000).map { index in + [ + "name": "tool-" + String(index), "description": String(repeating: "x", count: 200), + "inputSchema": ["type": "object"], + ] + } + response(id, ["tools": tools]) + exit(0) + } + if scenario == "pending-tools" { continue } + if scenario == "stubborn" { + _ = signal(SIGTERM, SIG_IGN) + try? "ready".write( + to: root.appendingPathComponent("stubborn-ready"), atomically: true, encoding: .utf8) + while true { _ = sleep(1) } + } + let cursor = (message["params"] as? [String: Any])?["cursor"] as? String + let tool: [String: Any] = [ + "name": cursor == nil ? "first" : "second", + "description": scenario == "long-text" ? String(repeating: "x", count: 17) : "fixture", + "inputSchema": ["type": "object"], + ] + var result: [String: Any] = ["tools": [tool]] + if cursor == nil || scenario == "cursor-cycle" { result["nextCursor"] = "next" } + response(id, result) + } +} From cbc806bf6aff5e66cc1ac5c87a5eca707917c657 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:47:15 +0800 Subject: [PATCH 063/171] fix(core): reconcile private receipts and recovery diagnostics --- Sources/AgentsCore/FileTransaction.swift | 10 +++- .../AgentsCore/TransactionPublication.swift | 6 ++- Sources/AgentsCore/TransactionRecovery.swift | 3 ++ .../InstructionDoctor.swift | 14 +++--- .../PrivateMaterializationTests.swift | 27 ++++++++-- Tests/AgentsCoreTests/SharedTargetTests.swift | 50 +++++++++++++++++++ .../ReadOnlyInspectionTests.swift | 34 ++++++++++++- 7 files changed, 130 insertions(+), 14 deletions(-) diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 7b5e0be..46bad55 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -140,9 +140,17 @@ package final class FileTransaction { && ($0.security.isPrivate || state.records.targets[$0.path] != nil) } guard !affected.isEmpty else { continue } + var sensitiveTargets = Set(state.records.targets.keys) + for request in affected { + if request.security.replacement == .privateMaterialization { + sensitiveTargets.insert(request.path) + } else { + sensitiveTargets.remove(request.path) + } + } var security = TransactionSecurity() security.preimage = state.access == nil ? .ordinary : .privateMaterialization - let deletesShared = shared && affected.allSatisfy { !$0.installs } + let deletesShared = shared && sensitiveTargets.isEmpty security.replacement = deletesShared ? .ordinary : .privateMaterialization security.preimageAccess = state.access security.ancestry = try DirectoryAccessEvidence.capture( diff --git a/Sources/AgentsCore/TransactionPublication.swift b/Sources/AgentsCore/TransactionPublication.swift index 9828419..dcdaff2 100644 --- a/Sources/AgentsCore/TransactionPublication.swift +++ b/Sources/AgentsCore/TransactionPublication.swift @@ -97,8 +97,12 @@ extension TransactionSession { // The callback is never given a path or unverified descriptor. let data = try privateData() try requireParent(index) + let hash = "sha256:" + FileHash.sha256Hex(data: data) + if let expected = expectation.hash, expected != hash { + throw CoreError.invalidState("staged content digest mismatch") + } try file.write(data) - expectation.hash = "sha256:" + FileHash.sha256Hex(data: data) + expectation.hash = expectation.hash ?? hash expectation.kind = S_IFREG expectation.mode = file.evidence.mode return expectation diff --git a/Sources/AgentsCore/TransactionRecovery.swift b/Sources/AgentsCore/TransactionRecovery.swift index d41c6c7..c6ce4c8 100644 --- a/Sources/AgentsCore/TransactionRecovery.swift +++ b/Sources/AgentsCore/TransactionRecovery.swift @@ -126,6 +126,9 @@ extension FileTransaction { requiresOwner: false, message: "Transaction metadata cleanup is pending (\(journal.phase.rawValue)).") } + if journal.isReservationOnly { + return .init(requiresOwner: false, message: TransactionRecoveryDiagnostic.pendingMessage) + } retained += journal.entries.compactMap(journal.containerLocation(of:)) let session = try recoverySession( journal, store: store, directory: directory, checkpoint: { _ in }) diff --git a/Sources/AgentsInstructions/InstructionDoctor.swift b/Sources/AgentsInstructions/InstructionDoctor.swift index b08dfd7..9f8b4ca 100644 --- a/Sources/AgentsInstructions/InstructionDoctor.swift +++ b/Sources/AgentsInstructions/InstructionDoctor.swift @@ -19,13 +19,13 @@ extension InstructionOperations { message: recovery.message, path: store.directory) } - let otherSections: [LockedSection]? = try other.withReadLock( - onPendingRecovery: { nil }, - { - _ = try other.readDeploymentDeclaration() - return try other.readResolved().instructions.sections - }) - let otherDiagnostics = otherSections == nil ? [pendingRecovery(other)] : [] + let (otherSections, otherDiagnostics): ([LockedSection]?, [InstructionDiagnostic]) = + try other.withReadLock( + onPendingRecovery: { (nil, [pendingRecovery(other)]) }, + { + _ = try other.readDeploymentDeclaration() + return (try other.readResolved().instructions.sections, []) + }) let root = scope == .project ? environment.projectDirectory : environment.homeDirectory return try store.withReadLock( onPendingRecovery: { diff --git a/Tests/AgentsCoreTests/PrivateMaterializationTests.swift b/Tests/AgentsCoreTests/PrivateMaterializationTests.swift index 291505a..4a97197 100644 --- a/Tests/AgentsCoreTests/PrivateMaterializationTests.swift +++ b/Tests/AgentsCoreTests/PrivateMaterializationTests.swift @@ -141,12 +141,18 @@ struct PrivateMaterializationTests { #expect(provider.calls == (["provider", "renderer"].contains(kind) ? 1 : 0)) } - @Test func ordinaryRegionEditsKeepSensitiveSiblingsAndPrivateReceipt() throws { + @Test(arguments: [false, true]) + func ordinaryRegionEditsKeepSensitiveSiblingsAndPrivateReceipt(_ digestMatches: Bool) throws { let fixture = try TransactionFixture() try installPrivate("secret sibling; region before", in: fixture) let target = try fixture.store.materializationTarget( at: fixture.root.appendingPathComponent("AGENTS.md")) let before = try fixture.store.preparePrivateMaterialization(target) + let targetBefore = try FileSnapshot.read(at: target.url) + let receiptBefore = try Data(contentsOf: fixture.store.materializationReceiptURL) + let replacement = Data("secret sibling; region after".utf8) + let expectedHash = + "sha256:" + FileHash.sha256Hex(data: digestMatches ? replacement : Data("different".utf8)) var inspected = false try fixture.store.withLock { let transaction = FileTransaction(store: fixture.store) { point in @@ -161,10 +167,25 @@ struct PrivateMaterializationTests { inspected = true } } - try transaction.replace(target.url, with: .data(Data("secret sibling; region after".utf8))) - try transaction.commit() + try transaction.replace(target.url, with: .data(replacement), expectedHash: expectedHash) + if digestMatches { + try transaction.commit() + } else { + #expect(throws: CoreError.invalidState("staged content digest mismatch")) { + try transaction.commit() + } + } } #expect(inspected) + if !digestMatches { + #expect(try FileSnapshot.read(at: target.url) == targetBefore) + #expect(try Data(contentsOf: fixture.store.materializationReceiptURL) == receiptBefore) + #expect( + try fixture.store.preparePrivateMaterialization( + target, requiringReceiptForExistingTarget: true + ).receiptGeneration == before.receiptGeneration) + return + } #expect(try Data(contentsOf: target.url) == Data("secret sibling; region after".utf8)) let after = try fixture.store.preparePrivateMaterialization( target, requiringReceiptForExistingTarget: true) diff --git a/Tests/AgentsCoreTests/SharedTargetTests.swift b/Tests/AgentsCoreTests/SharedTargetTests.swift index d301c0f..21dfdba 100644 --- a/Tests/AgentsCoreTests/SharedTargetTests.swift +++ b/Tests/AgentsCoreTests/SharedTargetTests.swift @@ -109,6 +109,46 @@ struct SharedTargetTests { #expect(try Data(contentsOf: fixture.target) == Data("external trust change".utf8)) } + @Test(arguments: [false, true]) + func ordinaryRecreationOfAnAbsentTargetRemovesItsSensitiveReceipt(_ rollback: Bool) throws { + let fixture = try SharedFixture() + try fixture.install() + let receiptURL = try fixture.receiptURL() + let receipt = try Data(contentsOf: receiptURL) + try FileManager.default.removeItem(at: fixture.target) + try fixture.b.withLock(footprint: [.claudeMCPLocal]) { + let transaction = FileTransaction(store: fixture.b) { point in + if rollback, point == "entry.1.applied" { + throw CoreError.invalidState("injected receipt publication failure") + } + } + try transaction.replace(fixture.target, with: .data(Data("ordinary recreation".utf8))) + if rollback { + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(!FileManager.default.fileExists(atPath: fixture.target.path)) + #expect(try Data(contentsOf: receiptURL) == receipt) + let retry = FileTransaction(store: fixture.b) + try retry.replace(fixture.target, with: .data(Data("ordinary recreation".utf8))) + try retry.commit() + } else { + try transaction.commit() + } + } + #expect(!FileManager.default.fileExists(atPath: receiptURL.path)) + try fixture.user.withReadLock(footprint: [.claudeMCPUser]) { + let target = try fixture.user.nativeTarget(for: .claudeMCPUser) + #expect(try fixture.user.materializationReceipt(for: target) == nil) + #expect(try Data(contentsOf: target.url) == Data("ordinary recreation".utf8)) + } + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + let transaction = FileTransaction(store: fixture.a) + try transaction.replace(fixture.target, with: .data(Data("ordinary next edit".utf8))) + try transaction.commit() + } + #expect(try Data(contentsOf: fixture.target) == Data("ordinary next edit".utf8)) + #expect(!FileManager.default.fileExists(atPath: receiptURL.path)) + } + @Test(arguments: ["target", "ancestor"]) func sharedPreparedWriteRejectsChangedAccess(_ changed: String) throws { let fixture = try SharedFixture() @@ -585,6 +625,16 @@ struct SharedTargetTests { } let before = try FileSnapshot.read(at: fixture.target) let receipt = try Data(contentsOf: fixture.receiptURL()) + let scope = try FileSnapshot.read(at: fixture.a.directory) + let config = try FileSnapshot.read(at: fixture.config) + try fixture.a.withReadLock( + onPendingRecovery: { + let diagnostic = FileTransaction.recoveryDiagnostic(store: fixture.a) + #expect(!diagnostic.requiresOwner) + #expect(diagnostic.message == TransactionRecoveryDiagnostic.pendingMessage) + }, { _ = Issue.record("expected pending reservation intent") }) + #expect(try FileSnapshot.read(at: fixture.a.directory) == scope) + #expect(try FileSnapshot.read(at: fixture.config) == config) do { try fixture.a.withLock {} } catch CoreError.transactionRecovered {} #expect(try FileSnapshot.read(at: fixture.target) == before) #expect(try Data(contentsOf: fixture.receiptURL()) == receipt) diff --git a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift index e2ad5cc..22c9f2f 100644 --- a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift +++ b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift @@ -84,6 +84,33 @@ struct ReadOnlyInspectionTests { try inspectPendingTransaction(scope: .project, initialize: true) } + @Test func instructionDoctorsDiagnosePendingSharedRecoveryWithoutWriting() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let environment = RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: ["CLAUDE_CONFIG_DIR": root.appendingPathComponent("configured-claude").path]) + for directory in [environment.homeDirectory, root.appendingPathComponent("old-data")] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + try Data("ordinary before".utf8).write( + to: root.appendingPathComponent("old-data/AGENTS.md")) + let child = try interruptedTransaction( + root: root, scope: .project, command: "shared-install", checkpoint: "shared.ready") + defer { terminateProcess(child) } + try ProcessWait.marker(root.appendingPathComponent("ready"), child: child, root: root) + terminateProcess(child) + let before = try snapshot(root) + let pending = StateStore(scope: .project, environment: environment) + for scope in [InstallScope.project, .user] { + let report = try InstructionOperations.doctor(scope: scope, environment: environment) + #expect(report.diagnostics.map(\.kind) == [.pendingRecovery]) + #expect(report.diagnostics.first?.path == pending.directory) + #expect(report.diagnostics.first?.message == TransactionRecoveryDiagnostic.pendingMessage) + } + #expect(try snapshot(root) == before) + } + private func inspectPendingTransaction( scope: InstallScope, initialize: Bool ) throws { @@ -417,7 +444,10 @@ struct ReadOnlyInspectionTests { return result } - private func interruptedTransaction(root: URL, scope: InstallScope) throws -> Process { + private func interruptedTransaction( + root: URL, scope: InstallScope, command: String = "inspection-transaction", + checkpoint: String = TransactionCheckpoint.progress(4, .applied).name + ) throws -> Process { var directory = Bundle(for: InspectionTestBundle.self).bundleURL while !FileManager.default.isExecutableFile( atPath: directory.appendingPathComponent("StateTestProcess").path), directory.path != "/" @@ -427,7 +457,7 @@ struct ReadOnlyInspectionTests { let process = Process() process.executableURL = directory.appendingPathComponent("StateTestProcess") process.arguments = [ - root.path, "inspection-transaction", TransactionCheckpoint.progress(4, .applied).name, + root.path, command, checkpoint, "--scope", scope.rawValue, ] try process.run() From c256068ce40f17f03f05eb6e478ca683002de980 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:54:18 +0800 Subject: [PATCH 064/171] fix(components): preserve MCP binding and source identities --- .../Components/Adapters/CodexAdapter.swift | 2 +- .../Components/Adapters/OpenCodeAdapter.swift | 4 +- Sources/Components/LedgerFreeze.swift | 16 +- Sources/Components/MCPLayoutV1.swift | 3 +- Sources/Components/MCPLowering.swift | 26 ++- Tests/ComponentsTests/NativeMCPTests.swift | 174 ++++++++++++++++-- 6 files changed, 201 insertions(+), 24 deletions(-) diff --git a/Sources/Components/Adapters/CodexAdapter.swift b/Sources/Components/Adapters/CodexAdapter.swift index db3e4f2..bc054c9 100644 --- a/Sources/Components/Adapters/CodexAdapter.swift +++ b/Sources/Components/Adapters/CodexAdapter.swift @@ -48,7 +48,7 @@ enum CodexAdapter { } var rules: [String: MCPNativeField] = [ "enabled": .boolean, "required": .boolean, - "startup_timeout_sec": .nonnegativeNumber, "tool_timeout_sec": .nonnegativeNumber, + "startup_timeout_sec": .durationSeconds, "tool_timeout_sec": .durationSeconds, ] if case .streamableHTTP = input.transport { rules["bearer_token_env_var"] = .environmentName } try entry.nativeFields(rules) diff --git a/Sources/Components/Adapters/OpenCodeAdapter.swift b/Sources/Components/Adapters/OpenCodeAdapter.swift index b6039ce..37d7831 100644 --- a/Sources/Components/Adapters/OpenCodeAdapter.swift +++ b/Sources/Components/Adapters/OpenCodeAdapter.swift @@ -10,11 +10,11 @@ enum OpenCodeAdapter { entry.fields["type"] = .init("local") try entry.command(run, argv: true) try entry.workingDirectory(run) - try entry.bindings(run.environment, field: "environment", reference: .openCode) + try entry.bindings(run.environment, field: "environment", reference: nil) case .streamableHTTP(let url, let headers): entry.fields["type"] = .init("remote") try entry.url(url) - try entry.bindings(headers, field: "headers", reference: .openCode) + try entry.bindings(headers, field: "headers", reference: nil) case .sse: throw input.issue( ["transport", "kind"], .unsupported, diff --git a/Sources/Components/LedgerFreeze.swift b/Sources/Components/LedgerFreeze.swift index 4317a62..41d08b0 100644 --- a/Sources/Components/LedgerFreeze.swift +++ b/Sources/Components/LedgerFreeze.swift @@ -9,10 +9,24 @@ package struct LedgerFreezeLocations { } package enum LedgerFreeze { + /// Ephemeral B-to-C identities accompany the frozen ledger during native lowering. + /// They retain exact snapshots without persisting machine-local source coordinates. + package struct Result { + package var ledger: ResolvedLedger + package let sources: [SourceSnapshotID: String] + } + package static func freeze( _ linked: LinkedComponents, session: SourceResolutionSession, locations: LedgerFreezeLocations, limits: LedgerLimits ) throws -> ResolvedLedger { + try freezeWithSources(linked, session: session, locations: locations, limits: limits).ledger + } + + package static func freezeWithSources( + _ linked: LinkedComponents, session: SourceResolutionSession, + locations: LedgerFreezeLocations, limits: LedgerLimits + ) throws -> Result { var ledger = ResolvedLedger() let allSnapshots = linked.sourceSnapshots + linked.declaringSnapshots let evidence = Dictionary( @@ -161,6 +175,6 @@ package enum LedgerFreeze { children: (children[reference.occurrence] ?? []).sorted()) } try ledger.validate() - return ledger + return Result(ledger: ledger, sources: sources) } } diff --git a/Sources/Components/MCPLayoutV1.swift b/Sources/Components/MCPLayoutV1.swift index 0731128..ddb7636 100644 --- a/Sources/Components/MCPLayoutV1.swift +++ b/Sources/Components/MCPLayoutV1.swift @@ -80,9 +80,8 @@ package enum MCPLayoutV1 { switch surface { case .claudeCode: expected = .init(MCPReferenceSyntax.claude.render(name)) case .geminiCLI: expected = .init(MCPReferenceSyntax.gemini.render(name)) - case .openCodeCLI: expected = .init(MCPReferenceSyntax.openCode.render(name)) case .codexCLI: expected = .init(name) - case .cursorEditor, .cursorCLI, .cursorCloud: throw invalid() + case .openCodeCLI, .cursorEditor, .cursorCLI, .cursorCloud: throw invalid() } guard slot == expected else { throw invalid() } } else { diff --git a/Sources/Components/MCPLowering.swift b/Sources/Components/MCPLowering.swift index 8d46f0f..15b70ba 100644 --- a/Sources/Components/MCPLowering.swift +++ b/Sources/Components/MCPLowering.swift @@ -101,8 +101,10 @@ package enum NativeMCPLowering { /// The frozen occurrence graph connects the linked identity to its exact durable component. /// Call once per requested recipient; this method never aggregates equal native values. package static func lower( - _ linked: LinkedComponent, frozen ledger: ResolvedLedger, request: NativeMCPRequest + _ linked: LinkedComponent, frozen: LedgerFreeze.Result, request: NativeMCPRequest ) throws -> NativeMCPContribution { + let ledger = frozen.ledger + let sourceIDs = frozen.sources let descriptor = try CapabilityRegistry.mcp(request, component: linked.key.name) func invalid(_ detail: String) -> NativeAdapterIssue { .init( @@ -119,6 +121,9 @@ package enum NativeMCPLowering { guard !ids.isEmpty, occurrences.count == ids.count, owners.count == 1, let id = owners.first, let record = ledger.components[id], record.kind == DeclaredComponentKind.mcpServer.rawValue, record.name == name, + record.declaringSource == sourceIDs[linked.declaringSnapshot], + record.source == sourceIDs[linked.snapshot], linked.key.source == linked.snapshot.source, + record.revision == linked.pin?.revision, record.version == linked.pin?.version, record.root == linked.key.root, record.group == linked.key.group, record.payload == (try LedgerPayload.component(declaration)), record.conditions == linked.conditions.map(LedgerCondition.init), @@ -128,6 +133,11 @@ package enum NativeMCPLowering { for (origin, frozen) in zip(linked.origins, occurrences) { let audience: InstallScope = request.scope == .user ? .user : .project guard origin.occurrence == frozen.id, origin.reference == frozen.reference, + frozen.declaringSource == record.declaringSource, + origin.provenance.sourceIdentity == linked.declaringSnapshot.source, + origin.dependencies.compactMap({ sourceIDs[$0] }) == frozen.dependencies, + origin.dependencies.allSatisfy({ sourceIDs[$0] != nil }), + LedgerCondition(origin.condition) == frozen.condition, origin.condition.scopes?.contains(audience) ?? true, origin.condition.agents?.contains(request.surface.agent) ?? true, origin.provenance.relativePath == frozen.manifestPath, @@ -138,6 +148,7 @@ package enum NativeMCPLowering { } for (resource, frozen) in zip(linked.resources, record.resources) { guard let item = ledger.resources[frozen], item.path == resource.path, + item.source == sourceIDs[resource.snapshot], item.artifact == resource.artifact, item.hash == resource.hash else { throw invalid("linked resource and frozen evidence do not match") } } @@ -206,7 +217,7 @@ struct MCPInput { } enum MCPReferenceSyntax { - case claude, gemini, openCode + case claude, gemini static func isName(_ name: String) -> Bool { let bytes = Array(name.utf8) guard let first = bytes.first, @@ -220,13 +231,12 @@ enum MCPReferenceSyntax { func render(_ name: String) -> String { switch self { case .claude, .gemini: "${" + name + "}" - case .openCode: "{env:" + name + "}" } } } enum MCPNativeField { - case boolean, falseOnly, string, strings, positiveNumber, nonnegativeNumber, environmentName + case boolean, falseOnly, string, strings, positiveNumber, durationSeconds, environmentName case oneOf(Set) case positiveIntegerObject(Set) @@ -237,9 +247,11 @@ enum MCPNativeField { case (.string, .string), (.environmentName, .string): true case (.strings, .array(let array)): array.allSatisfy { if case .string = $0 { true } else { false } } - case (.nonnegativeNumber, .integer(let number)): number >= 0 - case (.nonnegativeNumber, .decimal(let number)): - Double(number).map { $0.isFinite && $0 >= 0 } ?? false + case (.durationSeconds, .integer(let number)): number >= 0 + case (.durationSeconds, .decimal(let number)): + // Rust Duration uses u64 seconds. The f64 immediately below 2^64 is 2048 seconds + // smaller, so fractional nanosecond rounding cannot overflow an accepted f64. + Double(number).map { $0 >= 0 && $0 < 0x1p64 } ?? false case (.positiveNumber, .integer(let number)): number > 0 case (.positiveNumber, .decimal(let number)): Double(number).map { $0.isFinite && $0 > 0 } ?? false diff --git a/Tests/ComponentsTests/NativeMCPTests.swift b/Tests/ComponentsTests/NativeMCPTests.swift index b76a7b1..07881db 100644 --- a/Tests/ComponentsTests/NativeMCPTests.swift +++ b/Tests/ComponentsTests/NativeMCPTests.swift @@ -1,10 +1,11 @@ import AgentsCore import AgentsManifest -import Components import Foundation import NativeDocuments import Testing +@testable import Components + @Suite("Native MCP mapping and replay") struct NativeMCPTests { @Test(arguments: NativeMCPScope.allCases) @@ -266,11 +267,161 @@ struct NativeMCPTests { contribution.value == .init(object: [ "type": .init("remote"), "url": .init("https://example.invalid/mcp"), - "headers": .init(object: ["X-Token": .init("{env:REMOTE_TOKEN}")]), + "headers": .init(object: ["X-Token": .init("REMOTE_TOKEN", kind: .environment)]), "protocol": .init("legacy"), "codemode": .init(boolean: false), "oauth": .init(boolean: false), ])) - _ = try contribution.referenceValue() + #expect(throws: NativeAdapterIssue.self) { try contribution.referenceValue() } + } + } + + @Test(arguments: [false, true]) + func openCodeEnvironmentValuesRequireStagedRendering(_ remote: Bool) throws { + let transport: [String: Any] = + remote + ? [ + "kind": "streamableHTTP", "url": "https://example.invalid/mcp", + "headers": ["X-Token": ["env": "EXACT_VALUE"]], + ] + : stdio(environment: ["TOKEN": ["env": "EXACT_VALUE"]]) + try withMCP( + [server("exact", transport: transport, agents: ["opencode"])], + request: .init(surface: .openCodeCLI, scope: .project) + ) { contribution, ledger, fixture in + let field = remote ? "headers" : "environment" + let key = remote ? "X-Token" : "TOKEN" + #expect( + contribution.value.object?[field]?.object?[key] == .init("EXACT_VALUE", kind: .environment)) + #expect(contribution.bindings.map(\.reference) == [false]) + #expect(throws: NativeAdapterIssue.self) { try contribution.referenceValue() } + var candidate = ledger + candidate.lowerings = [ + contribution.lowering(id: "exact", artifact: "exact", platform: platform) + ] + candidate = try LedgerReplay.prepareLowerings( + candidate, store: fixture.store, roots: [:], limits: .standard) + let restored = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(candidate, limits: .standard), limits: .standard) + let replayed = try MCPLayoutV1.contribution(restored.lowerings[0], ledger: restored) + #expect(replayed.bindings == contribution.bindings) + #expect(replayed.value == contribution.value) + #expect(throws: NativeAdapterIssue.self) { try replayed.referenceValue() } + var unsafeReference = restored.lowerings[0] + unsafeReference.layout.object?["bindings"]?.array?[0].object?["reference"] = .init( + boolean: true) + unsafeReference.layout.object?["value"]?.object?[field]?.object?[key] = .init( + "{env:EXACT_VALUE}") + #expect(throws: CoreError.self) { + try MCPLayoutV1.contribution(unsafeReference, ledger: restored) + } + } + } + + @Test(arguments: [false, true]) + func equalPayloadsCannotCrossFrozenSourceOwners(_ resource: Bool) throws { + let a = try LinkFixture() + let b = try LinkFixture() + var run = stdio() + if resource { + run["executable"] = "./server" + for fixture in [a, b] { + try fixture.write("same executable bytes", to: "server", base: fixture.project) + } + } + let declaration: [String: Any] = [ + "version": 1, "components": [server("same", transport: run, agents: ["codex"])], + ] + let (_, frozenA) = try freeze(declaration, a) + let (linkedB, _) = try freeze(declaration, b) + #expect(throws: NativeAdapterIssue.self) { + try NativeMCPLowering.lower( + try #require(linkedB.first), frozen: frozenA, + request: .init(surface: .codexCLI, scope: .project)) + } + } + + @Test func frozenSnapshotsAndResourceProvenanceRemainExact() throws { + let fixture = try LinkFixture() + let producer = fixture.root.appendingPathComponent("producer") + try fixture.initialize(producer) + try fixture.write("same bytes", to: "server", base: producer) + let producerDeclaration: [String: Any] = [ + "version": 1, "exports": ["tools"], + "groups": [ + "tools": [ + "components": [ + server( + "same", transport: ["kind": "stdio", "executable": "./server"], agents: ["codex"]) + ] + ] + ], + ] + try fixture.write( + String(decoding: JSONSerialization.data(withJSONObject: producerDeclaration), as: UTF8.self), + to: ".agent/agents.yaml", base: producer) + try fixture.commit(producer, tag: "1.0.0") + try fixture.write("unrelated revision", to: "README.md", base: producer) + try fixture.commit(producer, tag: "2.0.0") + func declaration(_ version: String) -> [String: Any] { + [ + "version": 1, + "sources": [ + "p": [ + "url": "file://localhost" + producer.path, + "requirement": ["exact": version], + ] + ], "uses": [["source": "p", "group": "tools"]], + ] + } + let (linkedA, frozenA) = try freeze(declaration("1.0.0"), fixture) + let (linkedB, frozenB) = try freeze(declaration("2.0.0"), fixture) + let a = try #require(linkedA.first) + let b = try #require(linkedB.first) + #expect(a.snapshot.source == b.snapshot.source) + #expect(a.snapshot.revision != b.snapshot.revision) + #expect(a.payload == b.payload) + #expect(a.resources.map(\.hash) == b.resources.map(\.hash)) + let request = NativeMCPRequest(surface: .codexCLI, scope: .project) + _ = try NativeMCPLowering.lower(a, frozen: frozenA, request: request) + _ = try NativeMCPLowering.lower(b, frozen: frozenB, request: request) + #expect(throws: NativeAdapterIssue.self) { + try NativeMCPLowering.lower(b, frozen: frozenA, request: request) + } + let mixedResources = LinkedComponent( + key: a.key, declaringSnapshot: a.declaringSnapshot, + snapshot: a.snapshot, pin: a.pin, payload: a.payload, conditions: a.conditions, + recipients: a.recipients, chatGPT: a.chatGPT, resources: b.resources, origins: a.origins) + #expect(throws: NativeAdapterIssue.self) { + try NativeMCPLowering.lower(mixedResources, frozen: frozenA, request: request) + } + } + + @Test(arguments: ["startup_timeout_sec", "tool_timeout_sec"]) + func codexTimeoutMatchesNativeDurationRange(_ field: String) throws { + for (value, accepted) in [ + ("0", true), ("-0.0", true), ("1e-100", true), + ("9223372036854775807", true), ("18446744073709549568.0", true), + ("18446744073709551615.0", false), ("18446744073709551616.0", false), ("1e100", false), + ] { + do { + try withMCP( + [ + server( + "exact", transport: stdio(), agents: ["codex"], + native: ["codex": [field: Double(value)!]]) + ], + request: .init(surface: .codexCLI, scope: .project) + ) { _, _, _ in + #expect(accepted) + } + } catch let issue as NativeAdapterIssue { + #expect(!accepted) + #expect(issue.reason == .invalid) + #expect(issue.request == .init(surface: .codexCLI, scope: .project)) + #expect(issue.component == "exact") + #expect(issue.field == ["native", "codex", field]) + #expect(!issue.description.contains(value)) + } } } @@ -330,7 +481,7 @@ struct NativeMCPTests { ] let (linked, frozen) = try freeze(declaration, fixture) #expect(linked.count == 3) - #expect(frozen.components.count == 2) + #expect(frozen.ledger.components.count == 2) let contributions = try linked.map { try NativeMCPLowering.lower( $0, frozen: frozen, request: .init(surface: .claudeCode, scope: .local)) @@ -338,7 +489,7 @@ struct NativeMCPTests { #expect(contributions[0].component != contributions[1].component) #expect(contributions[0].component == contributions[2].component) #expect(contributions.map(\.occurrences) == linked.map { $0.origins.map(\.occurrence) }) - var candidate = frozen + var candidate = frozen.ledger candidate.lowerings = contributions.enumerated().map { index, contribution in contribution.lowering(id: "lower-\(index)", artifact: "entry-\(index)", platform: platform) } @@ -400,7 +551,7 @@ struct NativeMCPTests { #expect(contribution.resourcePlacements.map(\.path) == [[.key("command")], [.key("cwd")]]) #expect(contribution.resourcePlacements.map(\.resource) == contribution.resources) #expect(throws: NativeAdapterIssue.self) { try contribution.referenceValue() } - var candidate = frozen + var candidate = frozen.ledger candidate.lowerings = [ contribution.lowering(id: "frozen", artifact: "frozen", platform: platform) ] @@ -487,7 +638,8 @@ struct NativeMCPTests { component, frozen: ledger, request: .init(surface: surface, scope: .project)) #expect(contribution.recipients == [surface.agent]) #expect(contribution.descriptor.knownReaders == [surface.agent]) - #expect(Set(ledger.components[contribution.component]!.recipients) == [.claudeCode, .codex]) + #expect( + Set(ledger.ledger.components[contribution.component]!.recipients) == [.claudeCode, .codex]) #expect(contribution.occurrences == component.origins.map(\.occurrence)) } } @@ -533,7 +685,7 @@ struct NativeMCPTests { component, frozen: frozen, request: .init(surface: .claudeCode, scope: .user)) } var changed = frozen - changed.occurrences[0].consumerEditable = false + changed.ledger.occurrences[0].consumerEditable = false #expect(throws: NativeAdapterIssue.self) { try NativeMCPLowering.lower( component, frozen: changed, request: .init(surface: .claudeCode, scope: .project)) @@ -569,11 +721,11 @@ struct NativeMCPTests { let (linked, ledger) = try freeze(["version": 1, "components": components], fixture) let contribution = try NativeMCPLowering.lower( try #require(linked.first), frozen: ledger, request: request) - try body(contribution, ledger, fixture) + try body(contribution, ledger.ledger, fixture) } private func freeze(_ declaration: [String: Any], _ fixture: LinkFixture) throws -> ( - [LinkedComponent], ResolvedLedger + [LinkedComponent], LedgerFreeze.Result ) { let bytes = try JSONSerialization.data(withJSONObject: declaration, options: [.sortedKeys]) let document = try DeclarationDocument( @@ -581,7 +733,7 @@ struct NativeMCPTests { return try ComponentLinker.withLinkedComponents( document: document, store: fixture.store, platform: platform ) { linked, session in - let frozen = try LedgerFreeze.freeze( + let frozen = try LedgerFreeze.freezeWithSources( linked, session: session, locations: .init(sources: [ "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: ".") From 19437c238807518e15bdb6ce386303ef3f940094 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:05:01 +0800 Subject: [PATCH 065/171] feat(manifest): expose annotated schema for editor integration --- Documentation/Reference/Manifest.md | 29 +- Documentation/Reference/ManifestSchema.md | 598 ++++++++++----- Scripts/generate-manifest-schema.py | 42 +- Scripts/test_manifest_schema.py | 27 + .../ManifestSchemaResource.swift | 14 + .../Resources/agents.schema.json | 712 ++++++++++++------ .../SchemaResourceTests.swift | 16 + 7 files changed, 1041 insertions(+), 397 deletions(-) create mode 100644 Sources/AgentsManifest/ManifestSchemaResource.swift create mode 100644 Tests/AgentsManifestTests/SchemaResourceTests.swift diff --git a/Documentation/Reference/Manifest.md b/Documentation/Reference/Manifest.md index 7f1a05e..5fe56ad 100644 --- a/Documentation/Reference/Manifest.md +++ b/Documentation/Reference/Manifest.md @@ -23,8 +23,8 @@ exports: [checks] ``` The distributed [JSON schema](../../Sources/AgentsManifest/Resources/agents.schema.json) -is the field-shape owner. [Generated field help](ManifestSchema.md) lists every -supported shape and its schema-owned collection bounds. The finite compiler +is the field-shape owner. [Generated field help](ManifestSchema.md) lists supported +shapes, field descriptions, examples and schema-owned collection bounds. The finite compiler rejects unsupported validation keywords, values and combinations; its generated rules enforce the accepted constraints. Parser and decoded-value safety budgets apply independently of these field constraints. @@ -36,6 +36,31 @@ resolve sources, access resources or execute component programs. Git requirements also apply to local Git repositories declared with `path`; their local source identity and declaring environment remain unchanged. +## Public Schema Resource + +Consumers importing `AgentsManifest` can obtain the bundled schema for offline +editor association or export: + +```swift +import AgentsManifest + +let bytes: [UInt8] = try ManifestSchemaResource.encodedJSON() +``` + +The API returns the exact resource bytes, including descriptions, examples and +`x-agents-*` scalar annotations. It reads no declaration or scope state and uses +no network. All schema references are bundled; the schema identifier is not a +download requirement. Executable distributions must include the Swift package's +resource bundle. A missing or unreadable schema file throws an I/O error; +consumers do not need a checkout or a build-directory path. + +The schema supplies completion, field help and structural validation. Core +diagnostics remain authoritative for YAML admission, scalar kinds, numeric +identity and domain relationships. General JSON Schema treats `1.0` as a +mathematical integer and cannot preserve decimal lexical identity. Saving a +manifest must preserve its YAML text rather than convert it through JSON numbers +or enable schema-driven format conversion. + ## Values and Ordering Sources, groups, components, uses, exports, prompt sections and named ChatGPT diff --git a/Documentation/Reference/ManifestSchema.md b/Documentation/Reference/ManifestSchema.md index 56d421a..403c11f 100644 --- a/Documentation/Reference/ManifestSchema.md +++ b/Documentation/Reference/ManifestSchema.md @@ -4,263 +4,523 @@ Generated from `Sources/AgentsManifest/Resources/agents.schema.json`. ## Declaration -| Field | Required | Shape | -| --- | --- | --- | -| `version` | yes | `1` | -| `defaultAgents` | | sequence of agent (at most 10000 items) | -| `sources` | | name → source (at most 10000 properties) | -| `components` | | sequence of component (at most 10000 items) | -| `groups` | | name → group (at most 10000 properties) | -| `uses` | | sequence of use (at most 10000 items) | -| `exports` | | sequence of string (at most 10000 items) | -| `watch` | | sequence of string (at most 10000 items) | +Version 1 declaration of symbolic sources, components and groups. Parsing validates supplied YAML without resolving sources, reading referenced resources or running programs. Unknown fixed fields and null optional fields are errors; omitted collections are empty unless a field says otherwise. Core diagnostics also enforce YAML scalar kinds, numeric identity and domain relationships that general JSON Schema cannot express. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `version` | yes | `1` | Required manifest version, written as the plain integer 1. Core rejects decimal spelling such as 1.0 even when a JSON Schema validator treats it as an integer. | +| `defaultAgents` | | sequence of agent (at most 10000 items) | Default recipients for components that omit agents. Omission defaults to codex and claude-code; an empty list selects no recipients. Component overrides and conditions further determine effective targets.
Examples: ["codex", "claude-code"], [] | +| `sources` | | name → source (at most 10000 properties) | Source aliases local to this declaration, retained in declaration order. References use these keys; aliases must be nonempty, must not be . or contain a colon, and must identify distinct normalized sources. Omission or an empty mapping declares none. | +| `components` | | sequence of component (at most 10000 items) | Direct component declarations, retained in order and checked even when their conditions select no targets. Omission or an empty sequence declares none. | +| `groups` | | name → group (at most 10000 properties) | Named reusable groups, retained in declaration order. Defining a group does not activate it; uses selects it and exports makes it available to importers. Unused groups are still validated. | +| `uses` | | sequence of use (at most 10000 items) | Group references expanded in declaration order. Omission or an empty sequence activates no groups. Local reference cycles are errors, including in inactive groups. | +| `exports` | | sequence of string (at most 10000 items) | Names of local groups available to importing declarations, retained in order. Every name must name a declared group and occur once. Omission or an empty sequence exports none. | +| `watch` | | sequence of string (at most 10000 items) | Source aliases subscribed independently of installations. Names must be unique and refer to a declared source or . for the current source. Omission and an empty sequence are equivalent; watch order has set-like semantics. | ## agent +Recipient identifier. Support for deploying an individual component is checked by its consuming operation; accepting the identifier does not imply every component is supported by that client. + `codex` / `claude-code` / `cursor` / `gemini-cli` / `opencode` ## condition -| Field | Required | Shape | -| --- | --- | --- | -| `agents` | | sequence of agent (at most 10000 items) | -| `scopes` | | sequence of `project` / `user` (at most 10000 items) | -| `platforms` | | sequence of `macos` / `linux` (at most 10000 items) | +Intersecting restrictions on recipients, scope and platform. Omitted dimensions impose no restriction; an explicit empty dimension matches nothing. Nested group, use, component and section conditions combine by intersection, without removing inactive intent from the declaration. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `agents` | | sequence of agent (at most 10000 items) | Only these recipients remain eligible. Omission leaves recipients unrestricted; an empty list matches none. Duplicate recipients are errors. | +| `scopes` | | sequence of `project` / `user` (at most 10000 items) | Only these installation scopes match. Omission allows either scope; an empty list matches neither. Duplicate scopes are errors. | +| `platforms` | | sequence of `macos` / `linux` (at most 10000 items) | Only these operating systems match. Omission allows either platform; an empty list matches neither. Duplicate platforms are errors. | ## resource -| Field | Required | Shape | -| --- | --- | --- | -| `path` | yes | string | -| `source` | | string | +A resource path with an optional source alias. It remains symbolic during declaration reads; linking resolves and confines it to the selected source root. + +Examples: {"path": "prompts/review.md", "source": "team"} + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `path` | yes | string | Required relative resource path within the selected source. Absolute paths, home expansion and parent traversal are not allowed. | +| `source` | | string | Alias declared in this document. Omission or . uses the current declaring source; imported declarations retain their own source context. | ## section -| Field | Required | Shape | -| --- | --- | --- | -| `name` | yes | string | -| `source` | | string | -| `condition` | | condition | +One instruction section reference. Section sequences retain their declared order and occurrences; the referenced content is read only by the consuming operation. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `name` | yes | string | Instruction name relative to its instruction container, without .md. Nested names use / separators. | +| `source` | | string | Source alias for this section. Omission or . selects the declaring source's own instructions; root user instructions require a named source when linking. | +| `condition` | | condition | Additional restrictions for this section, intersected with enclosing conditions. Omission imposes no additional restriction. | ## binding -one of: string, mapping, mapping +A literal string or a symbolic local environment/secret binding. Declaration reads preserve the binding without looking up values. Only the consuming operation resolves bindings; they are not source-provided literals. + +Examples: "literal text", {"env": "SERVICE_TOKEN"}, {"secret": "service-token"} + +### Alternative 1 + +Literal text, used exactly as supplied. Strings resembling binding syntax are not interpolated. + +string + +### Alternative 2 + +Symbolic local environment binding; no value is captured in the declaration. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `env` | yes | string | Name of an environment variable resolved locally by the consuming operation. | + +### Alternative 3 + +Symbolic local secret binding; no value is captured in the declaration. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `secret` | yes | string | Name of a secret resolved locally by the consuming operation's binding provider. | ## prompt -one of: string, mapping +Inline prompt text or a reference to a prompt file. Declaration reads do not read the file. Command input tokens use ${input:name}; $${input:name} escapes a literal token. + +### Alternative 1 + +Inline prompt body, including any literal newlines. + +string + +### Alternative 2 + +Prompt body read from a resource by the consuming operation. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `file` | yes | resource | Resource containing the prompt body, resolved in its declaring source context. | ## run -| Field | Required | Shape | -| --- | --- | --- | -| `executable` | yes | string | -| `arguments` | | sequence of string (at most 10000 items) | -| `environment` | | name → binding (at most 10000 properties) | -| `workingDirectory` | | resource | +A declared invocation, preserved as data until a consuming operation explicitly uses it. It does not contain a shell command line. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `executable` | yes | string | Required program name or relative executable path. A bare name is resolved by the consuming operation; paths containing / are source resources. Reading the declaration never starts the program. | +| `arguments` | | sequence of string (at most 10000 items) | Arguments in invocation order, passed as individual strings. Omission or an empty sequence supplies no arguments. | +| `environment` | | name → binding (at most 10000 properties) | Environment variable names mapped to literals or local bindings. Omission or an empty mapping supplies no declared entries; reading the declaration does not resolve bindings. | +| `workingDirectory` | | resource | Working directory resource, resolved by the consuming operation. Omission leaves the directory unspecified in the declaration. | ## transport -one of: mapping, mapping +MCP connection declaration: a local stdio invocation, Streamable HTTP or SSE. Parsing neither starts a server nor opens a connection. + +### Alternative 1 + +Local MCP server invocation over standard input/output. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `stdio` | Selects the local stdio transport. | +| `executable` | yes | string | Required program name or relative executable path. A bare name is resolved by the consuming operation; paths containing / are source resources. Reading the declaration never starts the program. | +| `arguments` | | sequence of string (at most 10000 items) | Arguments in invocation order, passed as individual strings. Omission or an empty sequence supplies no arguments. | +| `environment` | | name → binding (at most 10000 properties) | Environment variable names mapped to literals or local bindings. Omission or an empty mapping supplies no declared entries; reading the declaration does not resolve bindings. | +| `workingDirectory` | | resource | Working directory resource, resolved by the consuming operation. Omission leaves the directory unspecified in the declaration. | + +### Alternative 2 + +Remote MCP endpoint with optional literal or locally bound headers. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `streamableHTTP` / `sse` | Selects Streamable HTTP or SSE transport. | +| `url` | yes | string | Required HTTP or HTTPS endpoint with a host and no embedded credentials or fragment. | +| `headers` | | name → binding (at most 10000 properties) | HTTP header names mapped to literals or local bindings. Omission or an empty mapping supplies no declared headers. Values remain unresolved during declaration reads. | ## event -one of: `beforeTool` / `afterTool` / `sessionStart` / `sessionEnd`, mapping +Portable hook event or a client-native event name. A native event requires exactly one explicit component recipient. + +### Alternative 1 + +Portable event mapped by the target client adapter. + +`beforeTool` / `afterTool` / `sessionStart` / `sessionEnd` + +### Alternative 2 + +Client-specific hook event; support is checked by the consuming adapter. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `native` | yes | string | Event name in the selected client's vocabulary; the component must explicitly target exactly one agent. | ## operation -one of: `read` / `write` / `execute`, mapping +Portable permission operation or a named client tool operation. Interpretation belongs to the target client adapter. + +### Alternative 1 + +Portable file-read, file-write or program-execution operation. + +`read` / `write` / `execute` + +### Alternative 2 + +Named tool operation interpreted by the target client. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `tool` | yes | string | Tool identifier to which the rule applies. | ## rule -| Field | Required | Shape | -| --- | --- | --- | -| `effect` | yes | `allow` / `ask` / `deny` | -| `operation` | yes | operation | -| `pattern` | yes | string | +One permission rule. Rules retain declaration order; the target client determines enforcement semantics. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `effect` | yes | `allow` / `ask` / `deny` | Allow, ask for confirmation, or deny the matching operation in the target client. | +| `operation` | yes | operation | Portable operation or named client tool to match. | +| `pattern` | yes | string | Match pattern interpreted for the operation by the target adapter. Read and write patterns must be safe relative resource paths. | ## parameter -| Field | Required | Shape | -| --- | --- | --- | -| `name` | yes | string | -| `description` | yes | string | -| `defaultValue` | | string | +A named command input. Parameter names must be unique within the command; inline prompt tokens must refer to declared parameters. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `name` | yes | string | Input token name used in ${input:name}. It must be nonempty and contain no }, colon or NUL. | +| `description` | yes | string | User-facing explanation of the input requested by the command. | +| `defaultValue` | | string | Optional literal default input text. Omission leaves the default unspecified; an empty string is an explicit empty default. | ## promptDeclaration -| Field | Required | Shape | -| --- | --- | --- | -| `sections` | | sequence of section (at most 10000 items) | -| `append` | | string | -| `condition` | | condition | +A named ChatGPT prompt composed from ordered instruction sections and an optional append file. Names are the keys in chatgpt; omission of sections means an empty sequence. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `sections` | | sequence of section (at most 10000 items) | Instruction sections in rendering order, including repeated references. Omission or an empty sequence supplies none. | +| `append` | | string | Relative file appended to the prompt by the consuming operation. In project scope it uses the declaring source; in user scope it is relative to the user home directory. Omission appends no file. | +| `condition` | | condition | Additional scope/platform restrictions for this named prompt. Omission imposes no additional restriction. | ## override -| Field | Required | Shape | -| --- | --- | --- | -| `agents` | | sequence of agent (at most 10000 items) | -| `mode` | | `link` / `copy` / `edit` | +Per-skill recipient and installation-mode overrides. The mapping key is the skill name and must belong to an explicit selection when one is supplied. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `agents` | | sequence of agent (at most 10000 items) | Recipients for this skill instead of component/default recipients. Omission inherits; an empty list selects no recipients. Enclosing conditions still restrict the result. | +| `mode` | | `link` / `copy` / `edit` | Installation mode for this skill instead of the component mode. Omission inherits. edit requires a live local source without a requirement. | ## requirement -one of: mapping, mapping, mapping, mapping, mapping, mapping +One Git selection policy, also applicable to local Git repositories. Version requirements select semantic-version tags; a resolved lock records the exact revision. Reading the declaration never performs resolution. + +Examples: {"from": "1.2.0"}, {"from": "1.2.0", "to": "2.0.0"}, {"branch": "main"} + +### Alternative 1 + +Track the named Git branch. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `branch` | yes | string | Track the named Git branch. | + +### Alternative 2 + +Select the specified Git revision. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `revision` | yes | string | Select the specified Git revision. | + +### Alternative 3 + +Select exactly this semantic version tag. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `exact` | yes | string | Select exactly this semantic version tag. | + +### Alternative 4 + +Inclusive semantic-version lower bound, below the next major version. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `from` | yes | string | Inclusive semantic-version lower bound, below the next major version. | + +### Alternative 5 + +Inclusive semantic-version lower bound, below the next minor version. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `upToNextMinor` | yes | string | Inclusive semantic-version lower bound, below the next minor version. | + +### Alternative 6 + +Semantic-version interval with an inclusive lower bound and exclusive upper bound. The lower bound must be less than the upper bound. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `from` | yes | string | Inclusive semantic-version lower bound. | +| `to` | yes | string | Exclusive semantic-version upper bound, greater than from. | ## source -one of: mapping, mapping, mapping +Exactly one Git URL, local path or well-known skill index per alias. subpath narrows the discovery root. No source is accessed while reading the declaration. + +### Alternative 1 + +Git repository selected by a transport URL and optional requirement. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `url` | yes | string | Git transport URL. Complete URLs avoid canonicalization warnings; normalized repository identities must be distinct across aliases. | +| `subpath` | | string | Safe relative discovery path inside the source. Omission uses the source root; it cannot escape that root. | +| `requirement` | | requirement | Git selection policy. Omission leaves the source without an explicit requirement; resolution and exact locking belong to the consuming operation. | + +### Alternative 2 + +Local source interpreted using the directories of its declaring environment. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `path` | yes | string | Local path, relative to the declaring project directory unless absolute or home-relative. A requirement selects committed content from a local Git repository; edit mode requires no requirement. | +| `subpath` | | string | Safe relative discovery path inside the source. Omission uses the source root; it cannot escape that root. | +| `requirement` | | requirement | Git selection policy. Omission leaves the source without an explicit requirement; resolution and exact locking belong to the consuming operation. | + +### Alternative 3 + +Well-known skill index accessed only during source-consuming operations. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `index` | yes | string | HTTP or HTTPS well-known skill index URL, without embedded credentials or fragment. Git requirements do not apply to this source kind. | +| `subpath` | | string | Safe relative discovery path inside the source. Omission uses the source root; it cannot escape that root. | ## componentReference -| Field | Required | Shape | -| --- | --- | --- | -| `kind` | yes | `skill` / `instruction` / `mcpServer` / `hook` / `subagent` / `command` / `lspServer` / `permissions` / `ignore` / `plugin` | -| `name` | yes | string | +A typed member reference used to exclude one component from a plugin expansion. The singular skill and instruction kinds identify individual members. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `skill` / `instruction` / `mcpServer` / `hook` / `subagent` / `command` / `lspServer` / `permissions` / `ignore` / `plugin` | Kind of the individual plugin member to exclude. | +| `name` | yes | string | Relative member name within the plugin, paired with kind to identify the exclusion. Duplicate kind/name exclusions are errors. | ## component_skills -| Field | Required | Shape | -| --- | --- | --- | -| `kind` | yes | `skills` | -| `agents` | | sequence of agent (at most 10000 items) | -| `condition` | | condition | -| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | -| `source` | yes | string | -| `select` | | one of: `all`, sequence of string (at most 10000 items) | -| `exclude` | | sequence of string (at most 10000 items) | -| `mode` | | `link` / `copy` / `edit` | -| `overrides` | | name → override (at most 10000 properties) | +Select skills from a source and declare their recipients and installation modes. + +Examples: {"kind": "skills", "source": "team", "select": ["review"], "agents": ["codex"]} + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `skills` | Selects the skills component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `source` | yes | string | Required source alias, or . for the current declaring source. Source resolution occurs only in the consuming operation. | +| `select` | | one of: `all`, sequence of string (at most 10000 items) | all or omission selects all discovered skills; a name sequence selects those skills. An empty sequence selects none. Selection is combined with exclude and per-skill overrides. | +| `exclude` | | sequence of string (at most 10000 items) | Skill names removed from the selection. Omission or an empty sequence excludes none. | +| `mode` | | `link` / `copy` / `edit` | link shares cached content, copy creates an installed directory, and edit links live local content. Omission defaults to link. edit requires a local source without a requirement or pin. | +| `overrides` | | name → override (at most 10000 properties) | Skill names mapped to recipient/mode overrides. Omission or an empty mapping supplies none; omitted override fields inherit the component settings. | ## component_instructions -| Field | Required | Shape | -| --- | --- | --- | -| `kind` | yes | `instructions` | -| `agents` | | sequence of agent (at most 10000 items) | -| `condition` | | condition | -| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | -| `sections` | | sequence of section (at most 10000 items) | -| `chatgpt` | | name → promptDeclaration (at most 10000 properties) | +Compose instruction targets and named ChatGPT prompts from ordered section references. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `instructions` | Selects the instructions component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `sections` | | sequence of section (at most 10000 items) | Instruction sections in rendering order. Omission or an empty sequence supplies none; repeated references retain their occurrences. | +| `chatgpt` | | name → promptDeclaration (at most 10000 properties) | Named ChatGPT prompts retained in declaration order, separate from agent-targeted sections. Omission or an empty mapping declares none. | ## component_mcpServer -| Field | Required | Shape | -| --- | --- | --- | -| `kind` | yes | `mcpServer` | -| `agents` | | sequence of agent (at most 10000 items) | -| `condition` | | condition | -| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | -| `name` | yes | string | -| `transport` | yes | transport | +Declare a named MCP server connection without starting or contacting it. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `mcpServer` | Selects the mcpServer component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `name` | yes | string | Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed. | +| `transport` | yes | transport | Required MCP transport and its unresolved connection settings. | ## component_hook -| Field | Required | Shape | -| --- | --- | --- | -| `kind` | yes | `hook` | -| `agents` | | sequence of agent (at most 10000 items) | -| `condition` | | condition | -| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | -| `name` | yes | string | -| `event` | yes | event | -| `run` | yes | run | -| `matcher` | | string | -| `timeoutSeconds` | | integer ≥ 1 | +Declare a named event-triggered invocation without executing it. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `hook` | Selects the hook component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `name` | yes | string | Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed. | +| `event` | yes | event | Required portable or native hook event. Native events require exactly one explicit component recipient. | +| `run` | yes | run | Required invocation performed when the target client triggers this hook. Declaration reads never execute it. | +| `matcher` | | string | Optional target-client matcher text. Omission leaves matching unspecified; support and interpretation belong to the adapter. | +| `timeoutSeconds` | | integer ≥ 1 | Positive plain integer timeout in seconds. Omission leaves the timeout unspecified. Core rejects decimal spellings such as 1.0 and out-of-range integers. | ## component_subagent -| Field | Required | Shape | -| --- | --- | --- | -| `kind` | yes | `subagent` | -| `agents` | | sequence of agent (at most 10000 items) | -| `condition` | | condition | -| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | -| `name` | yes | string | -| `description` | yes | string | -| `prompt` | yes | prompt | -| `model` | | string | -| `tools` | | sequence of string (at most 10000 items) | +Declare a named subagent with a description and prompt body. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `subagent` | Selects the subagent component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `name` | yes | string | Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed. | +| `description` | yes | string | User-facing explanation of when to use this subagent. | +| `prompt` | yes | prompt | Required inline prompt or prompt-file reference. File contents are not read during declaration parsing. | +| `model` | | string | Optional target-client model identifier. Omission leaves model selection unspecified. | +| `tools` | | sequence of string (at most 10000 items) | Optional target-client tool names. Omission leaves the tool list unspecified; an empty sequence is an explicit empty list. | ## component_command -| Field | Required | Shape | -| --- | --- | --- | -| `kind` | yes | `command` | -| `agents` | | sequence of agent (at most 10000 items) | -| `condition` | | condition | -| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | -| `name` | yes | string | -| `description` | yes | string | -| `prompt` | yes | prompt | -| `parameters` | | sequence of parameter (at most 10000 items) | +Declare a named prompt command and its input parameters. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `command` | Selects the command component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `name` | yes | string | Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed. | +| `description` | yes | string | User-facing explanation of this prompt command. | +| `prompt` | yes | prompt | Required inline prompt or prompt-file reference. ${input:name} refers to a declared parameter; $${input:name} is literal text. | +| `parameters` | | sequence of parameter (at most 10000 items) | Inputs in declaration order. Omission or an empty sequence declares none. Names must be unique and inline prompt tokens must refer to these names. | ## component_lspServer -| Field | Required | Shape | -| --- | --- | --- | -| `kind` | yes | `lspServer` | -| `agents` | | sequence of agent (at most 10000 items) | -| `condition` | | condition | -| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | -| `name` | yes | string | -| `run` | yes | run | -| `languages` | yes | name → string (at most 10000 properties) | -| `initializationOptions` | | name → NativeValue (at most 10000 properties) | +Declare a named language server invocation and extension-to-language mapping. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `lspServer` | Selects the lspServer component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `name` | yes | string | Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed. | +| `run` | yes | run | Required language server invocation, retained as data until used by the consuming operation. | +| `languages` | yes | name → string (at most 10000 properties) | File extensions, including a leading dot, mapped to nonempty language identifiers. An empty mapping declares no extension associations.
Examples: {".swift": "swift"} | +| `initializationOptions` | | name → NativeValue (at most 10000 properties) | Native values passed as language server initialization options. Omission or an empty mapping supplies none. Values retain Core integer/decimal kind and exact decimal text; !!float "1.00" explicitly marks a decimal. Null and nested arrays/objects are data, not runtime bindings. | ## component_permissions -| Field | Required | Shape | -| --- | --- | --- | -| `kind` | yes | `permissions` | -| `agents` | | sequence of agent (at most 10000 items) | -| `condition` | | condition | -| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | -| `name` | yes | string | -| `rules` | yes | sequence of rule (at most 10000 items) | +Declare a named ordered collection of client permission rules. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `permissions` | Selects the permissions component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `name` | yes | string | Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed. | +| `rules` | yes | sequence of rule (at most 10000 items) | Permission rules in declaration order. An empty sequence declares no rules. Enforcement belongs to the target client. | ## component_ignore -| Field | Required | Shape | -| --- | --- | --- | -| `kind` | yes | `ignore` | -| `agents` | | sequence of agent (at most 10000 items) | -| `condition` | | condition | -| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | -| `name` | yes | string | -| `patterns` | yes | sequence of string (at most 10000 items) | -| `purpose` | | `context` / `indexing` | +Declare a named collection of context or indexing ignore patterns. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `ignore` | Selects the ignore component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `name` | yes | string | Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed. | +| `patterns` | yes | sequence of string (at most 10000 items) | Ignore patterns in declaration order, interpreted by the target client for the selected purpose. An empty sequence declares none. | +| `purpose` | | `context` / `indexing` | context excludes content from model context; indexing excludes it from indexing. Omission defaults to context; support is checked by the consuming adapter. | ## component_plugin -| Field | Required | Shape | -| --- | --- | --- | -| `kind` | yes | `plugin` | -| `agents` | | sequence of agent (at most 10000 items) | -| `condition` | | condition | -| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | -| `name` | yes | string | -| `source` | yes | string | -| `path` | yes | string | -| `mode` | | `native` / `components` | -| `select` | | sequence of `skills` / `instructions` / `mcpServer` / `hook` / `subagent` / `command` / `lspServer` / `permissions` / `ignore` / `plugin` (at most 10000 items) | -| `exclude` | | sequence of componentReference (at most 10000 items) | +Declare a plugin resource for native installation or component expansion. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `plugin` | Selects the plugin component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `name` | yes | string | Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed. | +| `source` | yes | string | Required source alias, or . for the declaring source, containing the plugin resource. | +| `path` | yes | string | Required safe relative plugin resource path within the selected source. | +| `mode` | | `native` / `components` | components (the default) expands plugin members. native installs the vendor plugin for exactly one explicit recipient and forbids select and nonempty exclude. | +| `select` | | sequence of `skills` / `instructions` / `mcpServer` / `hook` / `subagent` / `command` / `lspServer` / `permissions` / `ignore` / `plugin` (at most 10000 items) | Component kinds to include during components-mode expansion. Omission leaves kinds unrestricted; an empty sequence selects none. Duplicate kinds are errors. | +| `exclude` | | sequence of componentReference (at most 10000 items) | Typed individual members removed from components-mode expansion. Omission or an empty sequence excludes none. Each kind/name pair must be unique. | ## component -one of: component_skills, component_instructions, component_mcpServer, component_hook, component_subagent, component_command, component_lspServer, component_permissions, component_ignore, component_plugin +One component declaration, selected by its required kind. All fields are checked even when the component is inactive; target-client support is evaluated by the consuming operation. + +### Alternative 1 + +component_skills + +### Alternative 2 + +component_instructions + +### Alternative 3 + +component_mcpServer + +### Alternative 4 + +component_hook + +### Alternative 5 + +component_subagent + +### Alternative 6 + +component_command + +### Alternative 7 + +component_lspServer + +### Alternative 8 + +component_permissions + +### Alternative 9 + +component_ignore + +### Alternative 10 + +component_plugin ## use -| Field | Required | Shape | -| --- | --- | --- | -| `group` | yes | string | -| `source` | | string | -| `condition` | | condition | +Activate a local group or an exported group from a source. Uses retain order and occurrences; nested conditions intersect and source aliases remain local to their declaring document. + +Examples: {"group": "checks"}, {"group": "checks", "source": "team"} + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `group` | yes | string | Required group name. Without source it must name a local group; a named source must export the group before linking can use it. | +| `source` | | string | Alias of the producer exporting this group. Omission selects a local group; . addresses the current source. Remote source aliases are not rebound in the importing document. | +| `condition` | | condition | Additional restrictions for this expansion, intersected with group and enclosing conditions. Omission imposes no additional restriction. | ## group -| Field | Required | Shape | -| --- | --- | --- | -| `components` | | sequence of component (at most 10000 items) | -| `uses` | | sequence of use (at most 10000 items) | -| `condition` | | condition | +A reusable group of direct components and nested uses. Definition alone does not activate it. Local use cycles are rejected, and unused or inactive contents are still validated. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `components` | | sequence of component (at most 10000 items) | Direct components retained in declaration order. Omission or an empty sequence contributes none. | +| `uses` | | sequence of use (at most 10000 items) | Nested group uses expanded in declaration order. Omission or an empty sequence references none. | +| `condition` | | condition | Restrictions intersected with each importing use and nested component/section condition. Omission imposes no additional restriction. | diff --git a/Scripts/generate-manifest-schema.py b/Scripts/generate-manifest-schema.py index 384733c..cc2ef75 100644 --- a/Scripts/generate-manifest-schema.py +++ b/Scripts/generate-manifest-schema.py @@ -139,6 +139,38 @@ def describe(value): return kind +def table_text(text): + return text.replace('&', '&').replace('|', '|').replace('`', '`').replace('\n', '
') + + +def examples(value): + return ', '.join('' + table_text(json.dumps(example, ensure_ascii=False)).replace('<', '<') + .replace('>', '>') + '' for example in value.get('examples', [])) + + +def field_help(value, level=3): + text = value.get('description', '') + text = text + '\n\n' if text else '' + if value.get('examples'): + text += 'Examples: ' + examples(value) + '\n\n' + if 'properties' in value: + if 'maxProperties' in value: + text += describe(value) + '\n\n' + text += '| Field | Required | Shape | Description |\n| --- | --- | --- | --- |\n' + for key, field in value['properties'].items(): + details = table_text(field.get('description', '')) + if field.get('examples'): + details += ('
' if details else '') + 'Examples: ' + examples(field) + text += ('| `' + key + '` | ' + ('yes' if key in value.get('required', []) else '') + + ' | ' + describe(field) + ' | ' + details + ' |\n') + elif 'oneOf' not in value: + text += describe(value) + '\n' + for index, branch in enumerate(value.get('oneOf', []), 1): + text = text.rstrip('\n') + '\n\n' + '#' * level + ' Alternative ' + str(index) + '\n\n' + text += field_help(branch, level + 1) + return text + + def compile_schema(schema): if not isinstance(schema, dict) or not isinstance(schema.get('$defs'), dict): raise ValueError('the bundled schema requires named definitions') @@ -156,15 +188,7 @@ def compile_schema(schema): 'Generated from `Sources/AgentsManifest/Resources/agents.schema.json`.\n') for name, definition in [('Declaration', schema)] + list(definitions.items()): help_text += '\n## ' + name + '\n\n' - if 'properties' in definition: - if 'maxProperties' in definition: - help_text += describe(definition) + '\n\n' - help_text += '| Field | Required | Shape |\n| --- | --- | --- |\n' - for key, value in definition['properties'].items(): - help_text += ('| `' + key + '` | ' + ('yes' if key in definition.get('required', []) else '') - + ' | ' + describe(value) + ' |\n') - else: - help_text += describe(definition) + '\n' + help_text += field_help(definition) return text, help_text diff --git a/Scripts/test_manifest_schema.py b/Scripts/test_manifest_schema.py index 82c7a3b..78dc5b7 100644 --- a/Scripts/test_manifest_schema.py +++ b/Scripts/test_manifest_schema.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 """Guard the bundled schema compiler's accepted validation semantics.""" +import copy import importlib.util import unittest from pathlib import Path @@ -10,6 +11,32 @@ class SchemaCompilerTests(unittest.TestCase): + def test_annotations_reach_help_without_changing_runtime_rules(self): + schema = { + 'type': 'object', 'additionalProperties': False, '$defs': { + 'choice': {'oneOf': [ + {'type': 'object', 'additionalProperties': False, + 'properties': {'description': {'type': 'string'}}, 'required': ['description']}, + {'type': 'string'}, + ]}, + }, + 'properties': {'examples': {'$ref': '#/$defs/choice'}}, + } + annotated = copy.deepcopy(schema) + annotated['description'] = 'Declaration documentation.' + annotated['properties']['examples']['description'] = 'A field with a schema reference.' + branch = annotated['$defs']['choice']['oneOf'][0] + branch['description'] = 'Mapping alternative documentation.' + branch['properties']['description']['description'] = 'First line | `text`\nSecond line.' + branch['properties']['description']['examples'] = ['a | b', ''] + swift, help_text = compiler.compile_schema(annotated) + self.assertEqual(swift, compiler.compile_schema(schema)[0]) + for expected in ['Declaration documentation.', 'A field with a schema reference.', + 'Mapping alternative documentation.', 'First line | `text`
Second line.', + '"a | b"', '"<value>"', + '| `description` | yes | string |', '| `examples` | | choice |']: + self.assertIn(expected, help_text) + def test_schema_values_drive_runtime_constraints_and_help(self): schema = { 'type': 'object', 'additionalProperties': False, '$defs': {}, diff --git a/Sources/AgentsManifest/ManifestSchemaResource.swift b/Sources/AgentsManifest/ManifestSchemaResource.swift new file mode 100644 index 0000000..e122be7 --- /dev/null +++ b/Sources/AgentsManifest/ManifestSchemaResource.swift @@ -0,0 +1,14 @@ +import Foundation + +/// The bundled field schema shared by manifest validation, generated help and editor clients. +public enum ManifestSchemaResource { + /// Returns the resource's exact JSON bytes, including its scalar annotations, without reading + /// a declaration or accessing a scope or network. Consumers must distribute the package's + /// resource bundle with their executable. A missing or unreadable schema file throws an I/O error. + public static func encodedJSON() throws -> [UInt8] { + guard let url = Bundle.module.url(forResource: "agents.schema", withExtension: "json") else { + throw CocoaError(.fileReadNoSuchFile) + } + return try Array(Data(contentsOf: url)) + } +} diff --git a/Sources/AgentsManifest/Resources/agents.schema.json b/Sources/AgentsManifest/Resources/agents.schema.json index 48465a6..0d8b94b 100644 --- a/Sources/AgentsManifest/Resources/agents.schema.json +++ b/Sources/AgentsManifest/Resources/agents.schema.json @@ -4,56 +4,71 @@ "version": { "const": 1, "type": "integer", - "x-agents-scalar-kind": "integer" + "x-agents-scalar-kind": "integer", + "description": "Required manifest version, written as the plain integer 1. Core rejects decimal spelling such as 1.0 even when a JSON Schema validator treats it as an integer." }, "defaultAgents": { "type": "array", "items": { "$ref": "#/$defs/agent" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Default recipients for components that omit agents. Omission defaults to codex and claude-code; an empty list selects no recipients. Component overrides and conditions further determine effective targets.", + "examples": [ + [ + "codex", + "claude-code" + ], + [] + ] }, "sources": { "type": "object", "additionalProperties": { "$ref": "#/$defs/source" }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Source aliases local to this declaration, retained in declaration order. References use these keys; aliases must be nonempty, must not be . or contain a colon, and must identify distinct normalized sources. Omission or an empty mapping declares none." }, "components": { "type": "array", "items": { "$ref": "#/$defs/component" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Direct component declarations, retained in order and checked even when their conditions select no targets. Omission or an empty sequence declares none." }, "groups": { "type": "object", "additionalProperties": { "$ref": "#/$defs/group" }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Named reusable groups, retained in declaration order. Defining a group does not activate it; uses selects it and exports makes it available to importers. Unused groups are still validated." }, "uses": { "type": "array", "items": { "$ref": "#/$defs/use" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Group references expanded in declaration order. Omission or an empty sequence activates no groups. Local reference cycles are errors, including in inactive groups." }, "exports": { "type": "array", "items": { "type": "string" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Names of local groups available to importing declarations, retained in order. Every name must name a declared group and occur once. Omission or an empty sequence exports none." }, "watch": { "type": "array", "items": { "type": "string" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Source aliases subscribed independently of installations. Names must be unique and refer to a declared source or . for the current source. Omission and an empty sequence are equivalent; watch order has set-like semantics." } }, "required": [ @@ -63,7 +78,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://agents.tools/schemas/agents-1.json", "title": "Agents declaration", - "description": "Version 1 symbolic sources, components and groups. Parsing never resolves sources or runs programs.", + "description": "Version 1 declaration of symbolic sources, components and groups. Parsing validates supplied YAML without resolving sources, reading referenced resources or running programs. Unknown fixed fields and null optional fields are errors; omitted collections are empty unless a field says otherwise. Core diagnostics also enforce YAML scalar kinds, numeric identity and domain relationships that general JSON Schema cannot express.", "$defs": { "agent": { "type": "string", @@ -73,7 +88,8 @@ "cursor", "gemini-cli", "opencode" - ] + ], + "description": "Recipient identifier. Support for deploying an individual component is checked by its consuming operation; accepting the identifier does not imply every component is supported by that client." }, "condition": { "type": "object", @@ -83,7 +99,8 @@ "items": { "$ref": "#/$defs/agent" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Only these recipients remain eligible. Omission leaves recipients unrestricted; an empty list matches none. Duplicate recipients are errors." }, "scopes": { "type": "array", @@ -94,7 +111,8 @@ "user" ] }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Only these installation scopes match. Omission allows either scope; an empty list matches neither. Duplicate scopes are errors." }, "platforms": { "type": "array", @@ -105,123 +123,162 @@ "linux" ] }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Only these operating systems match. Omission allows either platform; an empty list matches neither. Duplicate platforms are errors." } }, "required": [], - "additionalProperties": false + "additionalProperties": false, + "description": "Intersecting restrictions on recipients, scope and platform. Omitted dimensions impose no restriction; an explicit empty dimension matches nothing. Nested group, use, component and section conditions combine by intersection, without removing inactive intent from the declaration." }, "resource": { "type": "object", "properties": { "path": { - "type": "string" + "type": "string", + "description": "Required relative resource path within the selected source. Absolute paths, home expansion and parent traversal are not allowed." }, "source": { - "type": "string" + "type": "string", + "description": "Alias declared in this document. Omission or . uses the current declaring source; imported declarations retain their own source context." } }, "required": [ "path" ], - "additionalProperties": false + "additionalProperties": false, + "description": "A resource path with an optional source alias. It remains symbolic during declaration reads; linking resolves and confines it to the selected source root.", + "examples": [ + { + "path": "prompts/review.md", + "source": "team" + } + ] }, "section": { "type": "object", "properties": { "name": { - "type": "string" + "type": "string", + "description": "Instruction name relative to its instruction container, without .md. Nested names use / separators." }, "source": { - "type": "string" + "type": "string", + "description": "Source alias for this section. Omission or . selects the declaring source's own instructions; root user instructions require a named source when linking." }, "condition": { - "$ref": "#/$defs/condition" + "$ref": "#/$defs/condition", + "description": "Additional restrictions for this section, intersected with enclosing conditions. Omission imposes no additional restriction." } }, "required": [ "name" ], - "additionalProperties": false + "additionalProperties": false, + "description": "One instruction section reference. Section sequences retain their declared order and occurrences; the referenced content is read only by the consuming operation." }, "binding": { "oneOf": [ { - "type": "string" + "type": "string", + "description": "Literal text, used exactly as supplied. Strings resembling binding syntax are not interpolated." }, { "type": "object", "properties": { "env": { - "type": "string" + "type": "string", + "description": "Name of an environment variable resolved locally by the consuming operation." } }, "required": [ "env" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Symbolic local environment binding; no value is captured in the declaration." }, { "type": "object", "properties": { "secret": { - "type": "string" + "type": "string", + "description": "Name of a secret resolved locally by the consuming operation's binding provider." } }, "required": [ "secret" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Symbolic local secret binding; no value is captured in the declaration." + } + ], + "description": "A literal string or a symbolic local environment/secret binding. Declaration reads preserve the binding without looking up values. Only the consuming operation resolves bindings; they are not source-provided literals.", + "examples": [ + "literal text", + { + "env": "SERVICE_TOKEN" + }, + { + "secret": "service-token" } ] }, "prompt": { "oneOf": [ { - "type": "string" + "type": "string", + "description": "Inline prompt body, including any literal newlines." }, { "type": "object", "properties": { "file": { - "$ref": "#/$defs/resource" + "$ref": "#/$defs/resource", + "description": "Resource containing the prompt body, resolved in its declaring source context." } }, "required": [ "file" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Prompt body read from a resource by the consuming operation." } - ] + ], + "description": "Inline prompt text or a reference to a prompt file. Declaration reads do not read the file. Command input tokens use ${input:name}; $${input:name} escapes a literal token." }, "run": { "type": "object", "properties": { "executable": { - "type": "string" + "type": "string", + "description": "Required program name or relative executable path. A bare name is resolved by the consuming operation; paths containing / are source resources. Reading the declaration never starts the program." }, "arguments": { "type": "array", "items": { "type": "string" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Arguments in invocation order, passed as individual strings. Omission or an empty sequence supplies no arguments." }, "environment": { "type": "object", "additionalProperties": { "$ref": "#/$defs/binding" }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Environment variable names mapped to literals or local bindings. Omission or an empty mapping supplies no declared entries; reading the declaration does not resolve bindings." }, "workingDirectory": { - "$ref": "#/$defs/resource" + "$ref": "#/$defs/resource", + "description": "Working directory resource, resolved by the consuming operation. Omission leaves the directory unspecified in the declaration." } }, "required": [ "executable" ], - "additionalProperties": false + "additionalProperties": false, + "description": "A declared invocation, preserved as data until a consuming operation explicitly uses it. It does not contain a shell command line." }, "transport": { "oneOf": [ @@ -229,34 +286,40 @@ "type": "object", "properties": { "kind": { - "const": "stdio" + "const": "stdio", + "description": "Selects the local stdio transport." }, "executable": { - "type": "string" + "type": "string", + "description": "Required program name or relative executable path. A bare name is resolved by the consuming operation; paths containing / are source resources. Reading the declaration never starts the program." }, "arguments": { "type": "array", "items": { "type": "string" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Arguments in invocation order, passed as individual strings. Omission or an empty sequence supplies no arguments." }, "environment": { "type": "object", "additionalProperties": { "$ref": "#/$defs/binding" }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Environment variable names mapped to literals or local bindings. Omission or an empty mapping supplies no declared entries; reading the declaration does not resolve bindings." }, "workingDirectory": { - "$ref": "#/$defs/resource" + "$ref": "#/$defs/resource", + "description": "Working directory resource, resolved by the consuming operation. Omission leaves the directory unspecified in the declaration." } }, "required": [ "kind", "executable" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Local MCP server invocation over standard input/output." }, { "type": "object", @@ -266,26 +329,31 @@ "enum": [ "streamableHTTP", "sse" - ] + ], + "description": "Selects Streamable HTTP or SSE transport." }, "url": { - "type": "string" + "type": "string", + "description": "Required HTTP or HTTPS endpoint with a host and no embedded credentials or fragment." }, "headers": { "type": "object", "additionalProperties": { "$ref": "#/$defs/binding" }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "HTTP header names mapped to literals or local bindings. Omission or an empty mapping supplies no declared headers. Values remain unresolved during declaration reads." } }, "required": [ "kind", "url" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Remote MCP endpoint with optional literal or locally bound headers." } - ] + ], + "description": "MCP connection declaration: a local stdio invocation, Streamable HTTP or SSE. Parsing neither starts a server nor opens a connection." }, "event": { "oneOf": [ @@ -296,21 +364,25 @@ "afterTool", "sessionStart", "sessionEnd" - ] + ], + "description": "Portable event mapped by the target client adapter." }, { "type": "object", "properties": { "native": { - "type": "string" + "type": "string", + "description": "Event name in the selected client's vocabulary; the component must explicitly target exactly one agent." } }, "required": [ "native" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Client-specific hook event; support is checked by the consuming adapter." } - ] + ], + "description": "Portable hook event or a client-native event name. A native event requires exactly one explicit component recipient." }, "operation": { "oneOf": [ @@ -320,21 +392,25 @@ "read", "write", "execute" - ] + ], + "description": "Portable file-read, file-write or program-execution operation." }, { "type": "object", "properties": { "tool": { - "type": "string" + "type": "string", + "description": "Tool identifier to which the rule applies." } }, "required": [ "tool" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Named tool operation interpreted by the target client." } - ] + ], + "description": "Portable permission operation or a named client tool operation. Interpretation belongs to the target client adapter." }, "rule": { "type": "object", @@ -345,13 +421,16 @@ "allow", "ask", "deny" - ] + ], + "description": "Allow, ask for confirmation, or deny the matching operation in the target client." }, "operation": { - "$ref": "#/$defs/operation" + "$ref": "#/$defs/operation", + "description": "Portable operation or named client tool to match." }, "pattern": { - "type": "string" + "type": "string", + "description": "Match pattern interpreted for the operation by the target adapter. Read and write patterns must be safe relative resource paths." } }, "required": [ @@ -359,26 +438,31 @@ "operation", "pattern" ], - "additionalProperties": false + "additionalProperties": false, + "description": "One permission rule. Rules retain declaration order; the target client determines enforcement semantics." }, "parameter": { "type": "object", "properties": { "name": { - "type": "string" + "type": "string", + "description": "Input token name used in ${input:name}. It must be nonempty and contain no }, colon or NUL." }, "description": { - "type": "string" + "type": "string", + "description": "User-facing explanation of the input requested by the command." }, "defaultValue": { - "type": "string" + "type": "string", + "description": "Optional literal default input text. Omission leaves the default unspecified; an empty string is an explicit empty default." } }, "required": [ "name", "description" ], - "additionalProperties": false + "additionalProperties": false, + "description": "A named command input. Parameter names must be unique within the command; inline prompt tokens must refer to declared parameters." }, "promptDeclaration": { "type": "object", @@ -388,17 +472,21 @@ "items": { "$ref": "#/$defs/section" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Instruction sections in rendering order, including repeated references. Omission or an empty sequence supplies none." }, "append": { - "type": "string" + "type": "string", + "description": "Relative file appended to the prompt by the consuming operation. In project scope it uses the declaring source; in user scope it is relative to the user home directory. Omission appends no file." }, "condition": { - "$ref": "#/$defs/condition" + "$ref": "#/$defs/condition", + "description": "Additional scope/platform restrictions for this named prompt. Omission imposes no additional restriction." } }, "required": [], - "additionalProperties": false + "additionalProperties": false, + "description": "A named ChatGPT prompt composed from ordered instruction sections and an optional append file. Names are the keys in chatgpt; omission of sections means an empty sequence." }, "override": { "type": "object", @@ -408,7 +496,8 @@ "items": { "$ref": "#/$defs/agent" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Recipients for this skill instead of component/default recipients. Omission inherits; an empty list selects no recipients. Enclosing conditions still restrict the result." }, "mode": { "type": "string", @@ -416,11 +505,13 @@ "link", "copy", "edit" - ] + ], + "description": "Installation mode for this skill instead of the component mode. Omission inherits. edit requires a live local source without a requirement." } }, "required": [], - "additionalProperties": false + "additionalProperties": false, + "description": "Per-skill recipient and installation-mode overrides. The mapping key is the skill name and must belong to an explicit selection when one is supplied." }, "requirement": { "oneOf": [ @@ -428,77 +519,103 @@ "type": "object", "properties": { "branch": { - "type": "string" + "type": "string", + "description": "Track the named Git branch." } }, "required": [ "branch" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Track the named Git branch." }, { "type": "object", "properties": { "revision": { - "type": "string" + "type": "string", + "description": "Select the specified Git revision." } }, "required": [ "revision" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Select the specified Git revision." }, { "type": "object", "properties": { "exact": { - "type": "string" + "type": "string", + "description": "Select exactly this semantic version tag." } }, "required": [ "exact" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Select exactly this semantic version tag." }, { "type": "object", "properties": { "from": { - "type": "string" + "type": "string", + "description": "Inclusive semantic-version lower bound, below the next major version." } }, "required": [ "from" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Inclusive semantic-version lower bound, below the next major version." }, { "type": "object", "properties": { "upToNextMinor": { - "type": "string" + "type": "string", + "description": "Inclusive semantic-version lower bound, below the next minor version." } }, "required": [ "upToNextMinor" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Inclusive semantic-version lower bound, below the next minor version." }, { "type": "object", "properties": { "from": { - "type": "string" + "type": "string", + "description": "Inclusive semantic-version lower bound." }, "to": { - "type": "string" + "type": "string", + "description": "Exclusive semantic-version upper bound, greater than from." } }, "required": [ "from", "to" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Semantic-version interval with an inclusive lower bound and exclusive upper bound. The lower bound must be less than the upper bound." + } + ], + "description": "One Git selection policy, also applicable to local Git repositories. Version requirements select semantic-version tags; a resolved lock records the exact revision. Reading the declaration never performs resolution.", + "examples": [ + { + "from": "1.2.0" + }, + { + "from": "1.2.0", + "to": "2.0.0" + }, + { + "branch": "main" } ] }, @@ -508,54 +625,66 @@ "type": "object", "properties": { "url": { - "type": "string" + "type": "string", + "description": "Git transport URL. Complete URLs avoid canonicalization warnings; normalized repository identities must be distinct across aliases." }, "subpath": { - "type": "string" + "type": "string", + "description": "Safe relative discovery path inside the source. Omission uses the source root; it cannot escape that root." }, "requirement": { - "$ref": "#/$defs/requirement" + "$ref": "#/$defs/requirement", + "description": "Git selection policy. Omission leaves the source without an explicit requirement; resolution and exact locking belong to the consuming operation." } }, "required": [ "url" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Git repository selected by a transport URL and optional requirement." }, { "type": "object", "properties": { "path": { - "type": "string" + "type": "string", + "description": "Local path, relative to the declaring project directory unless absolute or home-relative. A requirement selects committed content from a local Git repository; edit mode requires no requirement." }, "subpath": { - "type": "string" + "type": "string", + "description": "Safe relative discovery path inside the source. Omission uses the source root; it cannot escape that root." }, "requirement": { - "$ref": "#/$defs/requirement" + "$ref": "#/$defs/requirement", + "description": "Git selection policy. Omission leaves the source without an explicit requirement; resolution and exact locking belong to the consuming operation." } }, "required": [ "path" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Local source interpreted using the directories of its declaring environment." }, { "type": "object", "properties": { "index": { - "type": "string" + "type": "string", + "description": "HTTP or HTTPS well-known skill index URL, without embedded credentials or fragment. Git requirements do not apply to this source kind." }, "subpath": { - "type": "string" + "type": "string", + "description": "Safe relative discovery path inside the source. Omission uses the source root; it cannot escape that root." } }, "required": [ "index" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Well-known skill index accessed only during source-consuming operations." } - ] + ], + "description": "Exactly one Git URL, local path or well-known skill index per alias. subpath narrows the discovery root. No source is accessed while reading the declaration." }, "componentReference": { "type": "object", @@ -573,68 +702,82 @@ "permissions", "ignore", "plugin" - ] + ], + "description": "Kind of the individual plugin member to exclude." }, "name": { - "type": "string" + "type": "string", + "description": "Relative member name within the plugin, paired with kind to identify the exclusion. Duplicate kind/name exclusions are errors." } }, "required": [ "kind", "name" ], - "additionalProperties": false + "additionalProperties": false, + "description": "A typed member reference used to exclude one component from a plugin expansion. The singular skill and instruction kinds identify individual members." }, "component_skills": { "type": "object", "properties": { "kind": { - "const": "skills" + "const": "skills", + "description": "Selects the skills component shape." }, "agents": { "type": "array", "items": { "$ref": "#/$defs/agent" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." }, "condition": { - "$ref": "#/$defs/condition" + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." }, "native": { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { - "x-agents-native-value": true + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." }, "source": { - "type": "string" + "type": "string", + "description": "Required source alias, or . for the current declaring source. Source resolution occurs only in the consuming operation." }, "select": { "oneOf": [ { - "const": "all" + "const": "all", + "description": "Select all discovered skills, subject to exclusions." }, { "type": "array", "items": { "type": "string" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Select only these skill names; an empty sequence selects none." } - ] + ], + "description": "all or omission selects all discovered skills; a name sequence selects those skills. An empty sequence selects none. Selection is combined with exclude and per-skill overrides." }, "exclude": { "type": "array", "items": { "type": "string" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Skill names removed from the selection. Omission or an empty sequence excludes none." }, "mode": { "type": "string", @@ -642,101 +785,133 @@ "link", "copy", "edit" - ] + ], + "description": "link shares cached content, copy creates an installed directory, and edit links live local content. Omission defaults to link. edit requires a local source without a requirement or pin." }, "overrides": { "type": "object", "additionalProperties": { "$ref": "#/$defs/override" }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Skill names mapped to recipient/mode overrides. Omission or an empty mapping supplies none; omitted override fields inherit the component settings." } }, "required": [ "kind", "source" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Select skills from a source and declare their recipients and installation modes.", + "examples": [ + { + "kind": "skills", + "source": "team", + "select": [ + "review" + ], + "agents": [ + "codex" + ] + } + ] }, "component_instructions": { "type": "object", "properties": { "kind": { - "const": "instructions" + "const": "instructions", + "description": "Selects the instructions component shape." }, "agents": { "type": "array", "items": { "$ref": "#/$defs/agent" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." }, "condition": { - "$ref": "#/$defs/condition" + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." }, "native": { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { - "x-agents-native-value": true + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." }, "sections": { "type": "array", "items": { "$ref": "#/$defs/section" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Instruction sections in rendering order. Omission or an empty sequence supplies none; repeated references retain their occurrences." }, "chatgpt": { "type": "object", "additionalProperties": { "$ref": "#/$defs/promptDeclaration" }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Named ChatGPT prompts retained in declaration order, separate from agent-targeted sections. Omission or an empty mapping declares none." } }, "required": [ "kind" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Compose instruction targets and named ChatGPT prompts from ordered section references." }, "component_mcpServer": { "type": "object", "properties": { "kind": { - "const": "mcpServer" + "const": "mcpServer", + "description": "Selects the mcpServer component shape." }, "agents": { "type": "array", "items": { "$ref": "#/$defs/agent" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." }, "condition": { - "$ref": "#/$defs/condition" + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." }, "native": { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { - "x-agents-native-value": true + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." }, "name": { - "type": "string" + "type": "string", + "description": "Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed." }, "transport": { - "$ref": "#/$defs/transport" + "$ref": "#/$defs/transport", + "description": "Required MCP transport and its unresolved connection settings." } }, "required": [ @@ -744,51 +919,63 @@ "name", "transport" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Declare a named MCP server connection without starting or contacting it." }, "component_hook": { "type": "object", "properties": { "kind": { - "const": "hook" + "const": "hook", + "description": "Selects the hook component shape." }, "agents": { "type": "array", "items": { "$ref": "#/$defs/agent" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." }, "condition": { - "$ref": "#/$defs/condition" + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." }, "native": { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { - "x-agents-native-value": true + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." }, "name": { - "type": "string" + "type": "string", + "description": "Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed." }, "event": { - "$ref": "#/$defs/event" + "$ref": "#/$defs/event", + "description": "Required portable or native hook event. Native events require exactly one explicit component recipient." }, "run": { - "$ref": "#/$defs/run" + "$ref": "#/$defs/run", + "description": "Required invocation performed when the target client triggers this hook. Declaration reads never execute it." }, "matcher": { - "type": "string" + "type": "string", + "description": "Optional target-client matcher text. Omission leaves matching unspecified; support and interpretation belong to the adapter." }, "timeoutSeconds": { "type": "integer", "minimum": 1, - "x-agents-scalar-kind": "integer" + "x-agents-scalar-kind": "integer", + "description": "Positive plain integer timeout in seconds. Omission leaves the timeout unspecified. Core rejects decimal spellings such as 1.0 and out-of-range integers." } }, "required": [ @@ -797,53 +984,65 @@ "event", "run" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Declare a named event-triggered invocation without executing it." }, "component_subagent": { "type": "object", "properties": { "kind": { - "const": "subagent" + "const": "subagent", + "description": "Selects the subagent component shape." }, "agents": { "type": "array", "items": { "$ref": "#/$defs/agent" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." }, "condition": { - "$ref": "#/$defs/condition" + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." }, "native": { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { - "x-agents-native-value": true + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." }, "name": { - "type": "string" + "type": "string", + "description": "Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed." }, "description": { - "type": "string" + "type": "string", + "description": "User-facing explanation of when to use this subagent." }, "prompt": { - "$ref": "#/$defs/prompt" + "$ref": "#/$defs/prompt", + "description": "Required inline prompt or prompt-file reference. File contents are not read during declaration parsing." }, "model": { - "type": "string" + "type": "string", + "description": "Optional target-client model identifier. Omission leaves model selection unspecified." }, "tools": { "type": "array", "items": { "type": "string" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Optional target-client tool names. Omission leaves the tool list unspecified; an empty sequence is an explicit empty list." } }, "required": [ @@ -852,50 +1051,61 @@ "description", "prompt" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Declare a named subagent with a description and prompt body." }, "component_command": { "type": "object", "properties": { "kind": { - "const": "command" + "const": "command", + "description": "Selects the command component shape." }, "agents": { "type": "array", "items": { "$ref": "#/$defs/agent" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." }, "condition": { - "$ref": "#/$defs/condition" + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." }, "native": { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { - "x-agents-native-value": true + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." }, "name": { - "type": "string" + "type": "string", + "description": "Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed." }, "description": { - "type": "string" + "type": "string", + "description": "User-facing explanation of this prompt command." }, "prompt": { - "$ref": "#/$defs/prompt" + "$ref": "#/$defs/prompt", + "description": "Required inline prompt or prompt-file reference. ${input:name} refers to a declared parameter; $${input:name} is literal text." }, "parameters": { "type": "array", "items": { "$ref": "#/$defs/parameter" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Inputs in declaration order. Omission or an empty sequence declares none. Names must be unique and inline prompt tokens must refer to these names." } }, "required": [ @@ -904,54 +1114,71 @@ "description", "prompt" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Declare a named prompt command and its input parameters." }, "component_lspServer": { "type": "object", "properties": { "kind": { - "const": "lspServer" + "const": "lspServer", + "description": "Selects the lspServer component shape." }, "agents": { "type": "array", "items": { "$ref": "#/$defs/agent" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." }, "condition": { - "$ref": "#/$defs/condition" + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." }, "native": { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { - "x-agents-native-value": true + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." }, "name": { - "type": "string" + "type": "string", + "description": "Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed." }, "run": { - "$ref": "#/$defs/run" + "$ref": "#/$defs/run", + "description": "Required language server invocation, retained as data until used by the consuming operation." }, "languages": { "type": "object", "additionalProperties": { "type": "string" }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "File extensions, including a leading dot, mapped to nonempty language identifiers. An empty mapping declares no extension associations.", + "examples": [ + { + ".swift": "swift" + } + ] }, "initializationOptions": { "type": "object", "additionalProperties": { - "x-agents-native-value": true + "x-agents-native-value": true, + "description": "Arbitrary native data, including null, nested arrays/objects and decimals with exact lexical identity. Bindings are not evaluated here." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Native values passed as language server initialization options. Omission or an empty mapping supplies none. Values retain Core integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly marks a decimal. Null and nested arrays/objects are data, not runtime bindings." } }, "required": [ @@ -960,44 +1187,53 @@ "run", "languages" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Declare a named language server invocation and extension-to-language mapping." }, "component_permissions": { "type": "object", "properties": { "kind": { - "const": "permissions" + "const": "permissions", + "description": "Selects the permissions component shape." }, "agents": { "type": "array", "items": { "$ref": "#/$defs/agent" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." }, "condition": { - "$ref": "#/$defs/condition" + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." }, "native": { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { - "x-agents-native-value": true + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." }, "name": { - "type": "string" + "type": "string", + "description": "Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed." }, "rules": { "type": "array", "items": { "$ref": "#/$defs/rule" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Permission rules in declaration order. An empty sequence declares no rules. Enforcement belongs to the target client." } }, "required": [ @@ -1005,51 +1241,61 @@ "name", "rules" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Declare a named ordered collection of client permission rules." }, "component_ignore": { "type": "object", "properties": { "kind": { - "const": "ignore" + "const": "ignore", + "description": "Selects the ignore component shape." }, "agents": { "type": "array", "items": { "$ref": "#/$defs/agent" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." }, "condition": { - "$ref": "#/$defs/condition" + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." }, "native": { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { - "x-agents-native-value": true + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." }, "name": { - "type": "string" + "type": "string", + "description": "Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed." }, "patterns": { "type": "array", "items": { "type": "string" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Ignore patterns in declaration order, interpreted by the target client for the selected purpose. An empty sequence declares none." }, "purpose": { "type": "string", "enum": [ "context", "indexing" - ] + ], + "description": "context excludes content from model context; indexing excludes it from indexing. Omission defaults to context; support is checked by the consuming adapter." } }, "required": [ @@ -1057,50 +1303,61 @@ "name", "patterns" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Declare a named collection of context or indexing ignore patterns." }, "component_plugin": { "type": "object", "properties": { "kind": { - "const": "plugin" + "const": "plugin", + "description": "Selects the plugin component shape." }, "agents": { "type": "array", "items": { "$ref": "#/$defs/agent" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." }, "condition": { - "$ref": "#/$defs/condition" + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." }, "native": { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { - "x-agents-native-value": true + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." }, - "maxProperties": 10000 + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." }, "name": { - "type": "string" + "type": "string", + "description": "Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed." }, "source": { - "type": "string" + "type": "string", + "description": "Required source alias, or . for the declaring source, containing the plugin resource." }, "path": { - "type": "string" + "type": "string", + "description": "Required safe relative plugin resource path within the selected source." }, "mode": { "type": "string", "enum": [ "native", "components" - ] + ], + "description": "components (the default) expands plugin members. native installs the vendor plugin for exactly one explicit recipient and forbids select and nonempty exclude." }, "select": { "type": "array", @@ -1119,14 +1376,16 @@ "plugin" ] }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Component kinds to include during components-mode expansion. Omission leaves kinds unrestricted; an empty sequence selects none. Duplicate kinds are errors." }, "exclude": { "type": "array", "items": { "$ref": "#/$defs/componentReference" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Typed individual members removed from components-mode expansion. Omission or an empty sequence excludes none. Each kind/name pair must be unique." } }, "required": [ @@ -1135,7 +1394,8 @@ "source", "path" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Declare a plugin resource for native installation or component expansion." }, "component": { "oneOf": [ @@ -1169,25 +1429,39 @@ { "$ref": "#/$defs/component_plugin" } - ] + ], + "description": "One component declaration, selected by its required kind. All fields are checked even when the component is inactive; target-client support is evaluated by the consuming operation." }, "use": { "type": "object", "properties": { "group": { - "type": "string" + "type": "string", + "description": "Required group name. Without source it must name a local group; a named source must export the group before linking can use it." }, "source": { - "type": "string" + "type": "string", + "description": "Alias of the producer exporting this group. Omission selects a local group; . addresses the current source. Remote source aliases are not rebound in the importing document." }, "condition": { - "$ref": "#/$defs/condition" + "$ref": "#/$defs/condition", + "description": "Additional restrictions for this expansion, intersected with group and enclosing conditions. Omission imposes no additional restriction." } }, "required": [ "group" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Activate a local group or an exported group from a source. Uses retain order and occurrences; nested conditions intersect and source aliases remain local to their declaring document.", + "examples": [ + { + "group": "checks" + }, + { + "group": "checks", + "source": "team" + } + ] }, "group": { "type": "object", @@ -1197,21 +1471,25 @@ "items": { "$ref": "#/$defs/component" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Direct components retained in declaration order. Omission or an empty sequence contributes none." }, "uses": { "type": "array", "items": { "$ref": "#/$defs/use" }, - "maxItems": 10000 + "maxItems": 10000, + "description": "Nested group uses expanded in declaration order. Omission or an empty sequence references none." }, "condition": { - "$ref": "#/$defs/condition" + "$ref": "#/$defs/condition", + "description": "Restrictions intersected with each importing use and nested component/section condition. Omission imposes no additional restriction." } }, "required": [], - "additionalProperties": false + "additionalProperties": false, + "description": "A reusable group of direct components and nested uses. Definition alone does not activate it. Local use cycles are rejected, and unused or inactive contents are still validated." } } } diff --git a/Tests/AgentsManifestTests/SchemaResourceTests.swift b/Tests/AgentsManifestTests/SchemaResourceTests.swift new file mode 100644 index 0000000..6cc65b2 --- /dev/null +++ b/Tests/AgentsManifestTests/SchemaResourceTests.swift @@ -0,0 +1,16 @@ +import AgentsManifest +import Foundation +import Testing + +@Suite("Manifest schema resource") +struct SchemaResourceTests { + @Test func exportedBytesMatchTheCanonicalResource() throws { + let resource = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("Sources/AgentsManifest/Resources/agents.schema.json") + let expected = try Data(contentsOf: resource) + let exported = try ManifestSchemaResource.encodedJSON() + #expect(exported == Array(expected)) + _ = try JSONSerialization.jsonObject(with: Data(exported)) + } +} From e8e262f0bd3a527185eca72760d487499ab5f3c0 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:07:40 +0800 Subject: [PATCH 066/171] fix(components): confirm owned process groups stop before completion --- Sources/AgentsCore/OwnedDuplexProcess.swift | 16 +++- Sources/CPlatform/DuplexProcess.c | 78 ++++++++++++++++++- Sources/CPlatform/include/DuplexProcess.h | 2 + .../ComponentsTests/Fixtures/MCPHTTPServer.py | 4 +- .../ComponentsTests/MCPConnectionTests.swift | 7 +- Tests/MCPTestProcess/main.swift | 3 + 6 files changed, 100 insertions(+), 10 deletions(-) diff --git a/Sources/AgentsCore/OwnedDuplexProcess.swift b/Sources/AgentsCore/OwnedDuplexProcess.swift index e957917..3c0e9d3 100644 --- a/Sources/AgentsCore/OwnedDuplexProcess.swift +++ b/Sources/AgentsCore/OwnedDuplexProcess.swift @@ -171,7 +171,7 @@ package final class OwnedDuplexProcess: @unchecked Sendable { } } - private func reapIfExited() -> Bool { + private func reapIfExited(requireQuiescence: Bool = true) -> Bool { lock.withLock { if reaped { return true } guard owned else { return false } @@ -181,6 +181,12 @@ package final class OwnedDuplexProcess: @unchecked Sendable { return false } guard exited else { return false } + if requireQuiescence { + var quiescent = false + guard platform_duplex_group_quiescent(identifier, &quiescent) == 0, quiescent else { + return false + } + } var status: Int32 = 0 let result = waitpid(identifier, &status, WNOHANG) if result == identifier { @@ -194,8 +200,8 @@ package final class OwnedDuplexProcess: @unchecked Sendable { } /// Cleanup has its own finite grace/TERM/KILL budgets in addition to the - /// protocol deadline. The leader is not reaped until group signals finish, - /// including descendants that closed their inherited pipes. False means the + /// protocol deadline. Keep the leader's identity reserved until no live group + /// members remain or the cleanup deadline fails. False means the /// kernel did not confirm cleanup; callers must not report complete success. package func finish(grace: Duration, terminate: Duration, killWait: Duration) async -> Bool { closeInput() @@ -206,9 +212,11 @@ package final class OwnedDuplexProcess: @unchecked Sendable { closeOutput() let deadline = ContinuousClock.now + killWait repeat { - if reapIfExited() { return term && killed } + if reapIfExited() { return ContinuousClock.now <= deadline && term && killed } try? await Task.sleep(for: .milliseconds(2)) } while ContinuousClock.now < deadline + // No further group signals follow release of the reserved identity. + _ = reapIfExited(requireQuiescence: false) return false } diff --git a/Sources/CPlatform/DuplexProcess.c b/Sources/CPlatform/DuplexProcess.c index 2c0a95b..a9d6575 100644 --- a/Sources/CPlatform/DuplexProcess.c +++ b/Sources/CPlatform/DuplexProcess.c @@ -5,6 +5,10 @@ #if defined(__APPLE__) #include #include +#else +#include +#include +#include #endif int platform_duplex_spawn(pid_t *pid, const char *executable, char *const argv[], @@ -111,7 +115,8 @@ ssize_t platform_duplex_write(int descriptor, const void *bytes, size_t count) { return written; } -int platform_duplex_signal(pid_t pid, int signal) { +int platform_duplex_group_quiescent(pid_t pid, bool *quiescent) { + *quiescent = false; #if defined(__APPLE__) // Zombie-only groups need no signal. Inspect only this reserved group; // an all-zombie group cannot fork. @@ -119,7 +124,7 @@ int platform_duplex_signal(pid_t pid, int signal) { size_t size = 0; if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0) return errno; if (size > 1024 * 1024) return EOVERFLOW; // Bounded cleanup inspection bytes. - if (size == 0) return 0; + if (size == 0) { *quiescent = true; return 0; } struct kinfo_proc *members = malloc(size); if (!members) return ENOMEM; int result = sysctl(mib, 4, members, &size, NULL, 0); @@ -132,7 +137,74 @@ int platform_duplex_signal(pid_t pid, int signal) { } free(members); if (result < 0) return error; - if (!live) return 0; + *quiescent = !live; + return 0; +#else + // /proc is a runtime prerequisite. Bound both scan work and elapsed inspection; + // an unreadable or incomplete snapshot cannot establish group quiescence. + DIR *processes = opendir("/proc"); + if (!processes) return errno; + struct timespec start, now; + if (clock_gettime(CLOCK_MONOTONIC, &start) < 0) { + int error = errno; closedir(processes); return error; + } + int result = 0; + bool leaderSeen = false; + size_t entries = 0; + for (;;) { + if (++entries > 65536) { result = EOVERFLOW; break; } + if (clock_gettime(CLOCK_MONOTONIC, &now) < 0) { result = errno; break; } + if ((now.tv_sec - start.tv_sec) * 1000000000LL + now.tv_nsec - start.tv_nsec >= 20000000) { + result = EAGAIN; break; + } + errno = 0; + struct dirent *entry = readdir(processes); + if (!entry) { + result = errno; + if (!result && !leaderSeen) result = ESRCH; + if (!result) *quiescent = true; + break; + } + if (!entry->d_name[0] || strspn(entry->d_name, "0123456789") != strlen(entry->d_name)) continue; + char path[sizeof(entry->d_name) + 6]; + int length = snprintf(path, sizeof(path), "%s/stat", entry->d_name); + if (length < 0 || (size_t)length >= sizeof(path)) { result = EOVERFLOW; break; } + int fd = openat(dirfd(processes), path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + if (fd < 0) { + if (errno == ENOENT || errno == ESRCH) continue; + result = errno; break; + } + char stat[4096]; + ssize_t count = read(fd, stat, sizeof(stat) - 1); + int error = errno; + close(fd); + if (count < 0) { + if (error == ENOENT || error == ESRCH) continue; + result = error; break; + } + if (count == 0 || count == (ssize_t)sizeof(stat) - 1) { result = EOVERFLOW; break; } + stat[count] = 0; + // comm may contain spaces and ')'; the final ')' ends that field. + char *fields = strrchr(stat, ')'); + char state; + long parent, group; + if (!fields || sscanf(fields + 1, " %c %ld %ld", &state, &parent, &group) != 3) { + result = EINVAL; break; + } + if (group != pid) continue; + if (strtol(entry->d_name, NULL, 10) == pid) leaderSeen = true; + if (state != 'Z') break; + } + closedir(processes); + return result; +#endif +} + +int platform_duplex_signal(pid_t pid, int signal) { +#if defined(__APPLE__) + bool quiescent = false; + int result = platform_duplex_group_quiescent(pid, &quiescent); + if (result || quiescent) return result; #endif if (kill(-pid, signal) == 0 || errno == ESRCH) return 0; return errno; diff --git a/Sources/CPlatform/include/DuplexProcess.h b/Sources/CPlatform/include/DuplexProcess.h index 4a17af5..69017d4 100644 --- a/Sources/CPlatform/include/DuplexProcess.h +++ b/Sources/CPlatform/include/DuplexProcess.h @@ -11,6 +11,8 @@ int platform_duplex_spawn(pid_t *pid, const char *executable, char *const argv[] int descriptors[3]); // Observe without reaping, reserving the leader's identity for group cleanup. int platform_duplex_observe(pid_t pid, bool *exited); +// Requires the leader to remain owned and unreaped; failure leaves false. +int platform_duplex_group_quiescent(pid_t pid, bool *quiescent); int platform_duplex_signal(pid_t pid, int signal); ssize_t platform_duplex_write(int descriptor, const void *bytes, size_t count); #endif diff --git a/Tests/ComponentsTests/Fixtures/MCPHTTPServer.py b/Tests/ComponentsTests/Fixtures/MCPHTTPServer.py index d7dee57..8e90b68 100644 --- a/Tests/ComponentsTests/Fixtures/MCPHTTPServer.py +++ b/Tests/ComponentsTests/Fixtures/MCPHTTPServer.py @@ -85,5 +85,7 @@ def do_GET(self): server=http.server.ThreadingHTTPServer(('127.0.0.1',0),Handler) server.daemon_threads=True -(root/'port').write_text(str(server.server_port)) +endpoint='http://127.0.0.1:%d/mcp'%server.server_port +(root/'endpoint.pending').write_text(endpoint) +os.replace(root/'endpoint.pending',root/'endpoint') server.serve_forever() diff --git a/Tests/ComponentsTests/MCPConnectionTests.swift b/Tests/ComponentsTests/MCPConnectionTests.swift index 91c2940..12e51a7 100644 --- a/Tests/ComponentsTests/MCPConnectionTests.swift +++ b/Tests/ComponentsTests/MCPConnectionTests.swift @@ -69,10 +69,13 @@ private final class MCPFixture { process.standardError = FileHandle.nullDevice try process.run() server = process - guard await waitFor({ self.text("port") != nil }), let port = text("port") else { + guard await waitFor({ self.text("endpoint") != nil }), + let endpoint = text("endpoint"), let url = URL(string: endpoint), + url.host == "127.0.0.1", let port = url.port, (1...65535).contains(port) + else { throw MCPConnectionIssue.connectionFailed } - return URL(string: "http://127.0.0.1:" + port + "/mcp")! + return url } func stopHTTP() { if let server, server.isRunning { diff --git a/Tests/MCPTestProcess/main.swift b/Tests/MCPTestProcess/main.swift index a6250f5..4cfa409 100644 --- a/Tests/MCPTestProcess/main.swift +++ b/Tests/MCPTestProcess/main.swift @@ -58,12 +58,15 @@ if scenario == "descendant" { for pointer in argv + environment { free(pointer) } try? String(pid).write( to: root.appendingPathComponent("descendant-pid"), atomically: true, encoding: .utf8) + var descendantReady = false for _ in 0..<2000 { if FileManager.default.fileExists(atPath: root.appendingPathComponent("holder-ready").path) { + descendantReady = true break } usleep(1000) } + if !descendantReady || getpgid(pid) != getpgrp() { exit(2) } } let fd = Int32(ProcessInfo.processInfo.environment["FD_CHECK"] ?? "-1") ?? -1 record([ From 2bd6e341b1ace3be8724e0af4ab40d92abed3d25 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:23:57 +0800 Subject: [PATCH 067/171] docs(manifest): describe watch source aliases accurately --- Documentation/Reference/ManifestSchema.md | 2 +- Sources/AgentsManifest/Resources/agents.schema.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Documentation/Reference/ManifestSchema.md b/Documentation/Reference/ManifestSchema.md index 403c11f..68a8bbe 100644 --- a/Documentation/Reference/ManifestSchema.md +++ b/Documentation/Reference/ManifestSchema.md @@ -15,7 +15,7 @@ Version 1 declaration of symbolic sources, components and groups. Parsing valida | `groups` | | name → group (at most 10000 properties) | Named reusable groups, retained in declaration order. Defining a group does not activate it; uses selects it and exports makes it available to importers. Unused groups are still validated. | | `uses` | | sequence of use (at most 10000 items) | Group references expanded in declaration order. Omission or an empty sequence activates no groups. Local reference cycles are errors, including in inactive groups. | | `exports` | | sequence of string (at most 10000 items) | Names of local groups available to importing declarations, retained in order. Every name must name a declared group and occur once. Omission or an empty sequence exports none. | -| `watch` | | sequence of string (at most 10000 items) | Source aliases subscribed independently of installations. Names must be unique and refer to a declared source or . for the current source. Omission and an empty sequence are equivalent; watch order has set-like semantics. | +| `watch` | | sequence of string (at most 10000 items) | Source aliases subscribed independently of installations. Names must be unique and refer to declared source aliases. Omission and an empty sequence are equivalent; watch order has set-like semantics. | ## agent diff --git a/Sources/AgentsManifest/Resources/agents.schema.json b/Sources/AgentsManifest/Resources/agents.schema.json index 0d8b94b..3903bbd 100644 --- a/Sources/AgentsManifest/Resources/agents.schema.json +++ b/Sources/AgentsManifest/Resources/agents.schema.json @@ -68,7 +68,7 @@ "type": "string" }, "maxItems": 10000, - "description": "Source aliases subscribed independently of installations. Names must be unique and refer to a declared source or . for the current source. Omission and an empty sequence are equivalent; watch order has set-like semantics." + "description": "Source aliases subscribed independently of installations. Names must be unique and refer to declared source aliases. Omission and an empty sequence are equivalent; watch order has set-like semantics." } }, "required": [ From a3f829f9af4711a5cf2fb3e106fc3f4d0642e91f Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:40:29 +0800 Subject: [PATCH 068/171] test: cover MCP initialization with blocked input --- .../MCPConnectionAcceptanceTests.swift | 53 +++++++++++++++++++ Tests/MCPTestProcess/main.swift | 14 ++++- 2 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 Tests/ComponentsTests/MCPConnectionAcceptanceTests.swift diff --git a/Tests/ComponentsTests/MCPConnectionAcceptanceTests.swift b/Tests/ComponentsTests/MCPConnectionAcceptanceTests.swift new file mode 100644 index 0000000..11f5088 --- /dev/null +++ b/Tests/ComponentsTests/MCPConnectionAcceptanceTests.swift @@ -0,0 +1,53 @@ +import AgentsCore +import Foundation +import Testing + +@testable import Components + +private final class MCPAcceptanceBundle: NSObject {} + +@Suite(.serialized) struct MCPConnectionAcceptanceTests { + @Test func deadlineInterruptsBlockedInitializeWrite() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent( + "mcp-blocked-write-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + + var directory = Bundle(for: MCPAcceptanceBundle.self).bundleURL + var executable: URL? + for _ in 0..<8 { + let candidate = directory.appendingPathComponent("MCPTestProcess") + if FileManager.default.isExecutableFile(atPath: candidate.path) { + executable = candidate + break + } + directory.deleteLastPathComponent() + } + let program = try #require(executable) + let configuration = DuplexProcessConfiguration( + executable: program.path, arguments: ["blocked-input", root.path], directory: root, + environment: ["PATH": "/usr/bin:/bin", "HOME": root.path]) + var limits = MCPConnectionLimits() + limits.totalTimeout = 1 + limits.requestTimeout = 2 + limits.textBytes = 2_000_000 + limits.sentBytes = 4_000_000 + limits.frameBytes = 4_000_000 + limits.queueBytes = 4_000_000 + let started = ContinuousClock.now + let result = await MCPConnectionRunner.run( + .stdio(configuration), + client: MCPConnectionClient(name: String(repeating: "x", count: 2_000_000), version: "1"), + limits: limits) + #expect(result.status == .failed(.timeout)) + #expect(result.cleanupComplete) + #expect(started.duration(to: .now) < .seconds(4)) + let ready = root.appendingPathComponent("holder-ready") + #expect(FileManager.default.fileExists(atPath: ready.path)) + #expect( + FileManager.default.fileExists(atPath: root.appendingPathComponent("stdin-pending").path)) + let pidText = try String(contentsOf: root.appendingPathComponent("pid"), encoding: .utf8) + let pid = try #require(Int32(pidText)) + #expect(kill(pid, 0) == -1 && errno == ESRCH) + } +} diff --git a/Tests/MCPTestProcess/main.swift b/Tests/MCPTestProcess/main.swift index 4cfa409..d474d32 100644 --- a/Tests/MCPTestProcess/main.swift +++ b/Tests/MCPTestProcess/main.swift @@ -43,10 +43,22 @@ func response(_ id: Any, _ result: [String: Any]) { try? String(getpid()).write( to: root.appendingPathComponent(scenario == "holder" ? "holder-pid" : "pid"), atomically: true, encoding: .utf8) -if scenario == "holder" || scenario == "ignore-input" { +if scenario == "holder" || scenario == "ignore-input" || scenario == "blocked-input" { + if scenario == "blocked-input" { alarm(10) } _ = signal(SIGTERM, SIG_IGN) try? "ready".write( to: root.appendingPathComponent("holder-ready"), atomically: true, encoding: .utf8) + if scenario == "blocked-input" { + while true { + var descriptor = pollfd(fd: STDIN_FILENO, events: Int16(POLLIN), revents: 0) + if poll(&descriptor, 1, 100) > 0 && descriptor.revents & Int16(POLLIN) != 0 { + try? "ready".write( + to: root.appendingPathComponent("stdin-pending"), atomically: true, encoding: .utf8) + break + } + usleep(1000) + } + } while true { _ = sleep(1) } } if scenario == "descendant" { From fed584b72993133e83d7a9eb2f6ea9ad26610085 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:45:31 +0800 Subject: [PATCH 069/171] fix: preserve MCP cleanup and stream failure guarantees --- Sources/CPlatform/DuplexProcess.c | 164 +++++++++++++++--- Sources/Components/MCPConnectionRunner.swift | 5 +- Sources/Components/MCPMessageSink.swift | 18 +- .../ComponentsTests/Fixtures/MCPHTTPServer.py | 6 +- .../ComponentsTests/MCPConnectionTests.swift | 50 +++++- Tests/MCPTestProcess/main.swift | 48 ++++- 6 files changed, 258 insertions(+), 33 deletions(-) diff --git a/Sources/CPlatform/DuplexProcess.c b/Sources/CPlatform/DuplexProcess.c index a9d6575..869a302 100644 --- a/Sources/CPlatform/DuplexProcess.c +++ b/Sources/CPlatform/DuplexProcess.c @@ -9,6 +9,8 @@ #include #include #include +#include +#include #endif int platform_duplex_spawn(pid_t *pid, const char *executable, char *const argv[], @@ -115,6 +117,129 @@ ssize_t platform_duplex_write(int descriptor, const void *bytes, size_t count) { return written; } +#if !defined(__APPLE__) +static int duplex_proc_scan_budget(const struct timespec *start) { + struct timespec now; + if (clock_gettime(CLOCK_MONOTONIC, &now) < 0) return errno; + if ((now.tv_sec - start->tv_sec) * 1000000000LL + now.tv_nsec - start->tv_nsec >= 20000000) + return EAGAIN; + return 0; +} + +// Require a complete bounded kernel record; a short read is not an EOF proof. +static int duplex_proc_read_record(int fd, char *record, size_t capacity, + const struct timespec *start) { + size_t used = 0; + for (;;) { + int result = duplex_proc_scan_budget(start); + if (result) return result; + ssize_t count = read(fd, record + used, capacity - 1 - used); + if (count < 0) return errno; + if (count == 0) { + if (used == 0) return EINVAL; + record[used] = 0; + return 0; + } + used += (size_t)count; + if (used == capacity - 1) return EOVERFLOW; + } +} + +// mountinfo escapes whitespace in paths; its post-separator options are tokens. +static int duplex_proc_mount_options(char *line, unsigned long long mountID) { + char *end; + errno = 0; + unsigned long long identifier = strtoull(line, &end, 10); + if (errno || end == line || *end != ' ') return EINVAL; + if (identifier != mountID) return ENOENT; + char *separator = strstr(end, " - "); + char type[32], source[256], options[4096], extra; + if (!separator || sscanf(separator + 3, "%31s %255s %4095s %c", type, source, options, &extra) != 3) + return EINVAL; + if (strcmp(type, "proc") != 0) return ENOTSUP; + char *saved = NULL; + for (char *option = strtok_r(options, ",", &saved); option; option = strtok_r(NULL, ",", &saved)) { + if (strncmp(option, "hidepid", 7) == 0 && strcmp(option, "hidepid=0") != 0) return ENOTSUP; + } + return 0; +} + +static int duplex_proc_complete_view(int proc, const struct timespec *start) { + struct statfs filesystem; + if (fstatfs(proc, &filesystem) < 0) return errno; + if (filesystem.f_type != PROC_SUPER_MAGIC) return ENOTSUP; + // fdinfo identifies this open proc root, including bind mounts/overmounts. + char path[64], descriptorInfo[1024]; + int length = snprintf(path, sizeof(path), "self/fdinfo/%d", proc); + if (length < 0 || (size_t)length >= sizeof(path)) return EOVERFLOW; + int fd = openat(proc, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return errno; + int error = duplex_proc_read_record(fd, descriptorInfo, sizeof(descriptorInfo), start); + close(fd); + if (error) return error; + unsigned long long mountID = 0; + char *saved = NULL; + for (char *line = strtok_r(descriptorInfo, "\n", &saved); line; line = strtok_r(NULL, "\n", &saved)) { + if (strncmp(line, "mnt_id:", 7) == 0) { + char extra; + if (sscanf(line, "mnt_id: %llu %c", &mountID, &extra) != 1) return EINVAL; + break; + } + } + if (mountID == 0) return ENOTSUP; + fd = openat(proc, "self/mountinfo", O_RDONLY | O_CLOEXEC); + if (fd < 0) return errno; + char line[8192], chunk[4096]; + size_t used = 0, total = 0; + int result = ENOTSUP; + for (;;) { + result = duplex_proc_scan_budget(start); + if (result) break; + ssize_t count = read(fd, chunk, sizeof(chunk)); + if (count < 0) { result = errno; break; } + if (count == 0) { result = ENOTSUP; break; } + if ((size_t)count > 1024 * 1024 - total) { result = EOVERFLOW; break; } + total += (size_t)count; + for (ssize_t i = 0; i < count; i++) { + if (chunk[i] == '\n') { + line[used] = 0; + result = duplex_proc_mount_options(line, mountID); + if (result != ENOENT) goto complete; + used = 0; + } else { + if (used == sizeof(line) - 1) { result = EOVERFLOW; goto complete; } + line[used++] = chunk[i]; + } + } + } +complete: + close(fd); + return result; +} + +static int duplex_proc_state(char *stat, char *state, long *group, long *threads) { + // comm may contain spaces and ')'; the final ')' ends that field. + char *fields = strrchr(stat, ')'); + if (!fields) return EINVAL; + char *saved = NULL; + char *field = strtok_r(fields + 1, " \n", &saved); + for (int index = 0; index <= 17; index++, field = strtok_r(NULL, " \n", &saved)) { + if (!field) return EINVAL; + if (index == 0) { + if (strlen(field) != 1) return EINVAL; + *state = field[0]; + } else if (index == 2 || index == 17) { + char *end; + errno = 0; + long number = strtol(field, &end, 10); + if (errno || end == field || *end != 0 || (index == 17 ? number <= 0 : number < 0)) return EINVAL; + if (index == 2) *group = number; else *threads = number; + } + } + return 0; +} +#endif + int platform_duplex_group_quiescent(pid_t pid, bool *quiescent) { *quiescent = false; #if defined(__APPLE__) @@ -144,19 +269,18 @@ int platform_duplex_group_quiescent(pid_t pid, bool *quiescent) { // an unreadable or incomplete snapshot cannot establish group quiescence. DIR *processes = opendir("/proc"); if (!processes) return errno; - struct timespec start, now; + struct timespec start; if (clock_gettime(CLOCK_MONOTONIC, &start) < 0) { int error = errno; closedir(processes); return error; } - int result = 0; + int result = duplex_proc_complete_view(dirfd(processes), &start); + if (result) { closedir(processes); return result; } bool leaderSeen = false; size_t entries = 0; for (;;) { if (++entries > 65536) { result = EOVERFLOW; break; } - if (clock_gettime(CLOCK_MONOTONIC, &now) < 0) { result = errno; break; } - if ((now.tv_sec - start.tv_sec) * 1000000000LL + now.tv_nsec - start.tv_nsec >= 20000000) { - result = EAGAIN; break; - } + result = duplex_proc_scan_budget(&start); + if (result) break; errno = 0; struct dirent *entry = readdir(processes); if (!entry) { @@ -170,30 +294,20 @@ int platform_duplex_group_quiescent(pid_t pid, bool *quiescent) { int length = snprintf(path, sizeof(path), "%s/stat", entry->d_name); if (length < 0 || (size_t)length >= sizeof(path)) { result = EOVERFLOW; break; } int fd = openat(dirfd(processes), path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW); - if (fd < 0) { - if (errno == ENOENT || errno == ESRCH) continue; - result = errno; break; - } + if (fd < 0) { result = errno; break; } char stat[4096]; - ssize_t count = read(fd, stat, sizeof(stat) - 1); - int error = errno; + result = duplex_proc_read_record(fd, stat, sizeof(stat), &start); close(fd); - if (count < 0) { - if (error == ENOENT || error == ESRCH) continue; - result = error; break; - } - if (count == 0 || count == (ssize_t)sizeof(stat) - 1) { result = EOVERFLOW; break; } - stat[count] = 0; - // comm may contain spaces and ')'; the final ')' ends that field. - char *fields = strrchr(stat, ')'); + if (result) break; char state; - long parent, group; - if (!fields || sscanf(fields + 1, " %c %ld %ld", &state, &parent, &group) != 3) { - result = EINVAL; break; - } + long group, threads; + result = duplex_proc_state(stat, &state, &group, &threads); + if (result) break; if (group != pid) continue; if (strtol(entry->d_name, NULL, 10) == pid) leaderSeen = true; - if (state != 'Z') break; + // A zombie main thread can still have live workers after pthread_exit. + // num_threads includes the leader: exactly one zombie task proves no worker. + if (state != 'Z' || threads != 1) break; } closedir(processes); return result; diff --git a/Sources/Components/MCPConnectionRunner.swift b/Sources/Components/MCPConnectionRunner.swift index c39c193..469c70c 100644 --- a/Sources/Components/MCPConnectionRunner.swift +++ b/Sources/Components/MCPConnectionRunner.swift @@ -132,7 +132,10 @@ package enum MCPConnectionRunner { // its queue. The existing request/total timer still bounds this join. event = await group.next() ?? event } - let transportIssue = transport.sink.failure + let transportIssue = transport.sink.closeAdmission() + if let transportIssue, transportIssue != .connectionClosed { + event = .failed(transportIssue) + } // A separate cleanup task is deliberately joined and is not cancelled // with the caller: cancelling sleep must not skip EOF/TERM/KILL budgets. let cleanup = Task { diff --git a/Sources/Components/MCPMessageSink.swift b/Sources/Components/MCPMessageSink.swift index b2c949f..0b059c5 100644 --- a/Sources/Components/MCPMessageSink.swift +++ b/Sources/Components/MCPMessageSink.swift @@ -35,6 +35,16 @@ final class MCPMessageSink: @unchecked Sendable { var version: String? { lock.withLock { negotiated } } var responsesAdmitted: Bool { lock.withLock { pendingResponses.isEmpty } } + /// Seal admission and capture its preexisting failure in one locked step. + /// The runner's intentional close must not replace an already-latched limit. + func closeAdmission() -> MCPConnectionIssue? { + lock.withLock { + let terminal = issue + finishLocked(.connectionClosed) + return terminal + } + } + func fail(_ error: MCPConnectionIssue) { lock.withLock { finishLocked(error) } } @@ -147,6 +157,7 @@ struct MCPSSEParser { private var line = Data() private var data = Data() private var name = "" + private var eventID: String? private(set) var lastID: String? private(set) var retry: TimeInterval? private var afterCR = false @@ -157,6 +168,7 @@ struct MCPSSEParser { line.removeAll(keepingCapacity: true) data.removeAll(keepingCapacity: true) name = "" + eventID = nil afterCR = false firstLine = true } @@ -186,8 +198,10 @@ struct MCPSSEParser { if line.isEmpty { if !data.isEmpty { data.removeLast() // SSE removes the final data-field newline. - try emit(Event(name: name, data: data, id: lastID, retry: retry)) + try emit(Event(name: name, data: data, id: eventID ?? lastID, retry: retry)) } + if let eventID { lastID = eventID } + eventID = nil data.removeAll(keepingCapacity: true) name = "" return @@ -204,7 +218,7 @@ struct MCPSSEParser { data.append(10) case "event": name = String(decoding: value, as: UTF8.self) case "id": - if !value.contains(0) { lastID = String(decoding: value, as: UTF8.self) } + if !value.contains(0) { eventID = String(decoding: value, as: UTF8.self) } case "retry": if !value.isEmpty && value.allSatisfy({ $0 >= 48 && $0 <= 57 }), let milliseconds = UInt64(String(decoding: value, as: UTF8.self)) diff --git a/Tests/ComponentsTests/Fixtures/MCPHTTPServer.py b/Tests/ComponentsTests/Fixtures/MCPHTTPServer.py index 8e90b68..d3ac125 100644 --- a/Tests/ComponentsTests/Fixtures/MCPHTTPServer.py +++ b/Tests/ComponentsTests/Fixtures/MCPHTTPServer.py @@ -58,7 +58,8 @@ def do_POST(self): while True:self.wfile.write(b':'+b'x'*255+b'\n');self.wfile.flush() elif mode=='resume' and message['method']=='initialize': resume_reply=reply - self.wfile.write(b'id: first-event\nretry: 1\ndata: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"probe","progress":1}}\n\n') + self.wfile.write(b'id: 1\nretry: 1\ndata: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"probe","progress":1}}\n\n') + self.wfile.write(b'id: 2\ndata: {\"jsonrpc\":') self.wfile.flush() else: # Split a multiline data event inside its field name and use CRLF. @@ -70,10 +71,11 @@ def do_POST(self): self.close_connection=True def do_GET(self): self.log_request_data(None) + if mode=='resume' and self.headers.get('Last-Event-ID')!='1':self.empty(409);return self.send_response(200);self.send_header('Content-Type','text/event-stream');self.send_header('Connection','close');self.end_headers() try: if mode=='resume': - self.wfile.write(b'event: message\ndata: '+resume_reply+b'\n\n');self.wfile.flush();self.close_connection=True;return + self.wfile.write(b'event: message\nid: 2\ndata: '+resume_reply+b'\n\n');self.wfile.flush();self.close_connection=True;return endpoint=('/messages' if mode!='legacy-cross' else 'http://localhost:%d/messages'%self.server.server_port).encode() self.wfile.write(b'event: endpoint\ndata: '+endpoint+b'\n\n');self.wfile.flush() while True: diff --git a/Tests/ComponentsTests/MCPConnectionTests.swift b/Tests/ComponentsTests/MCPConnectionTests.swift index 12e51a7..5bd6aa0 100644 --- a/Tests/ComponentsTests/MCPConnectionTests.swift +++ b/Tests/ComponentsTests/MCPConnectionTests.swift @@ -220,6 +220,44 @@ private func runConnection(_ input: MCPConnectionInput, limits: MCPConnectionLim #endif } + #if os(Linux) + @Test func zombieDescendantLeaderDoesNotHideItsLiveWorker() async throws { + let fixture = try MCPFixture() + let process = try OwnedDuplexProcess(fixture.configuration("thread-descendant")) + func state(_ pid: Int32) -> (state: String, threads: Int)? { + guard let stat = try? String(contentsOfFile: "/proc/\(pid)/stat", encoding: .utf8), + let delimiter = stat.lastIndex(of: ")") + else { return nil } + let fields = stat[stat.index(after: delimiter)...].split(separator: " ") + guard fields.count > 17, let threads = Int(fields[17]) else { return nil } + return (String(fields[0]), threads) + } + let ready = await fixture.waitFor { + var exited = false + guard platform_duplex_observe(process.identifier, &exited) == 0, exited, + let child = fixture.text("descendant-pid").flatMap({ Int32($0) }), + let childState = state(child) + else { return false } + return childState.state == "Z" && childState.threads > 1 + } + #expect(ready) + var quiescent = true + let observation = platform_duplex_group_quiescent(process.identifier, &quiescent) + #expect(observation == 0) + #expect(!quiescent) + let cleaned = await process.finish( + grace: .milliseconds(5), terminate: .milliseconds(5), killWait: .seconds(1)) + #expect(cleaned) + #expect(kill(process.identifier, 0) == -1 && errno == ESRCH) + if let child = fixture.text("descendant-pid").flatMap({ Int32($0) }) { + let final = state(child) + #expect(final == nil || (final!.state == "Z" && final!.threads == 1)) + } else { + Issue.record("Missing owned multithreaded descendant") + } + } + #endif + @Test func blockedKernelPipeWriteIsNonblockingAndCleanupIsFinite() async throws { let fixture = try MCPFixture() let process = try OwnedDuplexProcess(fixture.configuration("ignore-input")) @@ -284,6 +322,16 @@ private func runConnection(_ input: MCPConnectionInput, limits: MCPConnectionLim if mode == "eof-tools" { #expect(result.tools.count == 1000) } } + @Test func finalToolsResponseCannotMaskSameBurstAdmissionFailure() async throws { + let fixture = try MCPFixture() + var limits = MCPConnectionLimits() + limits.frameBytes = 1024 + let result = await runConnection(fixture.input("final-response-limit"), limits: limits) + #expect(result.status == .incomplete(.messageLimit)) + #expect(result.cleanupComplete) + #expect(fixture.methods() == ["initialize", "notifications/initialized", "tools/list"]) + } + @Test(arguments: ["json", "sse", "legacy", "resume"]) func actualHTTPModesDiscoverAndCleanUp(_ mode: String) async throws { let fixture = try MCPFixture() @@ -307,7 +355,7 @@ private func runConnection(_ input: MCPConnectionInput, limits: MCPConnectionLim if mode == "resume" { #expect( fixture.records().contains { - $0["http"] as? String == "GET" && $0["lastEventID"] as? String == "first-event" + $0["http"] as? String == "GET" && $0["lastEventID"] as? String == "1" }) } } diff --git a/Tests/MCPTestProcess/main.swift b/Tests/MCPTestProcess/main.swift index d474d32..3b117b0 100644 --- a/Tests/MCPTestProcess/main.swift +++ b/Tests/MCPTestProcess/main.swift @@ -61,8 +61,35 @@ if scenario == "holder" || scenario == "ignore-input" || scenario == "blocked-in } while true { _ = sleep(1) } } -if scenario == "descendant" { - let argv = [arguments[0], "holder", root.path].map { strdup($0) } + [nil] +#if os(Linux) + if scenario == "thread-holder" { + alarm(10) + _ = signal(SIGTERM, SIG_IGN) + var worker: pthread_t = 0 + let context = UnsafeMutableRawPointer(strdup(root.path)) + let created = pthread_create( + &worker, nil, + { context in + guard let context else { return nil } + let path = String(cString: context.assumingMemoryBound(to: CChar.self)) + free(context) + try? "ready".write( + to: URL(fileURLWithPath: path).appendingPathComponent("holder-ready"), + atomically: true, encoding: .utf8) + while true { _ = sleep(1) } + }, context) + if created != 0 { + free(context) + exit(2) + } + pthread_exit(nil) + } +#endif +if scenario == "descendant" || scenario == "thread-descendant" { + let argv = + [arguments[0], scenario == "descendant" ? "holder" : "thread-holder", root.path].map { + strdup($0) + } + [nil] let environment = ProcessInfo.processInfo.environment.map { strdup($0.key + "=" + $0.value) } + [nil] var pid: pid_t = 0 @@ -79,6 +106,7 @@ if scenario == "descendant" { usleep(1000) } if !descendantReady || getpgid(pid) != getpgrp() { exit(2) } + if scenario == "thread-descendant" { exit(0) } } let fd = Int32(ProcessInfo.processInfo.environment["FD_CHECK"] ?? "-1") ?? -1 record([ @@ -125,6 +153,22 @@ while true { "capabilities": capabilities, "serverInfo": ["name": "local-fixture", "version": "1"], ]) } else if method == "tools/list" { + if scenario == "final-response-limit" { + let tools: [[String: Any]] = (0..<4).map { index in + [ + "name": "tool-" + String(index), "description": String(repeating: "x", count: 100), + "inputSchema": ["type": "object"], + ] + } + let response = try! JSONSerialization.data(withJSONObject: [ + "jsonrpc": "2.0", "id": id, "result": ["tools": tools], + ]) + precondition(response.count <= 1024) + let burst = response + Data([10]) + Data(repeating: 120, count: 1025) + precondition(burst.count < 4096) + output(burst) + continue + } if scenario == "eof-tools" { let tools: [[String: Any]] = (0..<1000).map { index in [ From 8e9fc1ecc4669090ad3dcc99ccc5d871e4de29e6 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:45:32 +0800 Subject: [PATCH 070/171] feat: coordinate registered native configuration targets --- Sources/AgentsCore/FileTransaction.swift | 39 +- .../AgentsCore/NativeTargetCoordination.swift | 218 +++++++--- .../AgentsCore/PrivateMaterialization.swift | 34 +- Sources/AgentsCore/TransactionJournal.swift | 18 +- Sources/AgentsCore/TransactionPaths.swift | 63 ++- .../AgentsCore/TransactionPublication.swift | 12 +- Sources/AgentsCore/TransactionRecovery.swift | 2 +- Sources/AgentsCore/TransactionSession.swift | 14 +- .../PrivateMaterializationTests.swift | 14 +- .../RegisteredNativeTargetTests.swift | 377 ++++++++++++++++++ Tests/AgentsCoreTests/SharedTargetTests.swift | 23 +- .../PrivateMaterializationProbe.swift | 39 +- Tests/StateTestProcess/main.swift | 7 +- 13 files changed, 735 insertions(+), 125 deletions(-) create mode 100644 Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 46bad55..ef039e2 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -134,9 +134,10 @@ package final class FileTransaction { private func queueReceipt() throws { let originals = requests for state in receiptStates.values.sorted(by: { $0.path < $1.path }) { - let shared = state.path.hasPrefix(NativeTargetRoute.metadataRoot + "/") + let receiptRoute = NativeTargetRoute.metadataRoute(state.path) + let shared = receiptRoute != nil let affected = originals.filter { - $0.path.hasPrefix(NativeTargetRoute.globalRoot + "/") == shared + NativeTargetRoute.sharedRoute($0.path)?.root == receiptRoute?.root && ($0.security.isPrivate || state.records.targets[$0.path] != nil) } guard !affected.isEmpty else { continue } @@ -180,7 +181,7 @@ package final class FileTransaction { guard path != "state/" + MaterializationReceipts.fileName else { throw CoreError.unsafePath("materialization receipts are transaction-owned") } - if path.hasPrefix(NativeTargetRoute.globalRoot + "/") { + if NativeTargetRoute.sharedRoute(path) != nil { guard TransactionLockContext.current(store)?.writable == true else { throw CoreError.invalidState("shared writes require the held writer footprint") } @@ -237,14 +238,14 @@ package final class FileTransaction { package func commit() throws { guard !requests.isEmpty else { return } - let shared = requests.filter { $0.path.hasPrefix(NativeTargetRoute.globalRoot + "/") } + let shared = requests.filter { NativeTargetRoute.sharedRoute($0.path) != nil } if !shared.isEmpty { guard let context = TransactionLockContext.current(store), context.writable else { throw CoreError.invalidState("shared commit requires its held writer footprint") } try context.requireWriterScope() - let resource = try context.resource() for request in shared { + let resource = try context.resource(for: NativeTargetRoute.sharedRoute(request.path)!) let parent = try DirectoryHandle( at: request.evidence.physicalURL.deletingLastPathComponent()) guard try parent.objectIdentity == resource.identity.parent else { @@ -282,7 +283,7 @@ package final class FileTransaction { try StateStore.encode( session.materializationReceipts( previous: state.records, - shared: state.path.hasPrefix(NativeTargetRoute.metadataRoot + "/"))) + targetRoot: NativeTargetRoute.metadataRoute(state.path)?.root)) } } else { try session.stage( @@ -346,7 +347,15 @@ package final class FileTransaction { try checkpoint(TransactionCheckpoint.parentAncestry(entry: index, step).name) } } - for request in requests { try request.evidence.validateIdentity() } + for (index, request) in requests.enumerated() { + try request.evidence.validateIdentity() + if NativeTargetRoute.targetRoute(request.path) != nil, + parents[index].url.standardizedFileURL.path + != request.evidence.physicalURL.deletingLastPathComponent().standardizedFileURL.path + { + throw CoreError.invalidState("registered native parent changed after preparation") + } + } let id = UUID() var containers: [TransactionJournal.Container] = [] var identities: [String: Int] = [:] @@ -373,16 +382,24 @@ package final class FileTransaction { preimage: request.evidence.snapshot, parentIdentity: identity, container: container, security: security)) } - let shared = - roots[NativeTargetRoute.globalRoot] != nil || roots[NativeTargetRoute.metadataRoot] != nil - let resources = shared ? [try TransactionLockContext.current(store).requiredResource()] : [] + let sharedRoutes = Set( + roots.keys.compactMap { key in + NativeTargetRoute.sharedRoute(key) ?? NativeTargetRoute.metadataRoute(key) + }) + let resources = try sharedRoutes.map { route in + guard let context = TransactionLockContext.current(store) else { + throw CoreError.invalidState("shared transaction requires its held footprint") + } + return try context.resource(for: route) + }.sorted { $0.identity < $1.identity } let journal = TransactionJournal( id: id, scope: try directory.identity, roots: try roots.mapValues { try $0.identity }, entries: entries, containers: containers, footprint: resources.map(\.identity)) let session = TransactionSession( journal: journal, directory: directory, parents: parents, - checkpoint: checkpoint, resources: resources) + checkpoint: checkpoint, resources: resources, + nativeRoots: try paths.nativeRootAuthorities(Set(journal.roots.keys))) try session.validateRecords(store: store) return session } diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index 714d8db..8cc41cc 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -2,29 +2,127 @@ import CPlatform import Foundation /// Closed physical routes; regional ownership and rendering belong to the native adapter. -package enum NativeTargetRoute: String, Codable, Sendable { +package enum NativeTargetRoute: String, Codable, Sendable, CaseIterable { case claudeMCPProject = "claude.mcp.project" case claudeMCPLocal = "claude.mcp.local" case claudeMCPUser = "claude.mcp.user" - - var shared: Bool { self != .claudeMCPProject } + case codexMCPProject = "codex.mcp.project" + case codexMCPUser = "codex.mcp.user" + case geminiMCPProject = "gemini.mcp.project" + case geminiMCPUser = "gemini.mcp.user" + case cursorMCPProject = "cursor.mcp.project" + case cursorMCPUser = "cursor.mcp.user" + case openCodeMCPProjectJSON = "opencode.mcp.project.json" + case openCodeMCPProjectJSONC = "opencode.mcp.project.jsonc" + case openCodeMCPUserJSON = "opencode.mcp.user.json" + case openCodeMCPUserJSONC = "opencode.mcp.user.jsonc" + + var shared: Bool { + switch self { + case .claudeMCPLocal, .claudeMCPUser, .codexMCPUser, .geminiMCPUser, .cursorMCPUser, + .openCodeMCPUserJSON, .openCodeMCPUserJSONC: + true + default: false + } + } static let projectRoot = "native-claude-project" static let globalRoot = "native-claude-global" static let metadataRoot = "native-claude-metadata" - static func globalLogicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { - if let override = environment.environment["CLAUDE_CONFIG_DIR"], !override.isEmpty { - guard override.hasPrefix("/"), !override.contains("\0") else { - throw CoreError.unsafePath("registered Claude config root must be an absolute directory") - } - return URL(fileURLWithPath: override).standardizedFileURL + var root: String { + switch self { + case .claudeMCPProject: Self.projectRoot + case .claudeMCPLocal, .claudeMCPUser: Self.globalRoot + default: + "native-" + + rawValue.replacingOccurrences(of: ".mcp.", with: "-") + .replacingOccurrences(of: ".", with: "-") } - guard environment.homeDirectory.isFileURL, !environment.homeDirectory.path.contains("\0") else { - throw CoreError.unsafePath("registered Claude HOME must be a filesystem directory") + } + var metadata: String { root == Self.globalRoot ? Self.metadataRoot : root + "-metadata" } + var basename: String { + switch self { + case .claudeMCPProject: ".mcp.json" + case .claudeMCPLocal, .claudeMCPUser: ".claude.json" + case .codexMCPProject, .codexMCPUser: "config.toml" + case .geminiMCPProject, .geminiMCPUser: "settings.json" + case .cursorMCPProject, .cursorMCPUser: "mcp.json" + case .openCodeMCPProjectJSON, .openCodeMCPUserJSON: "opencode.json" + case .openCodeMCPProjectJSONC, .openCodeMCPUserJSONC: "opencode.jsonc" } - return environment.homeDirectory.standardizedFileURL + } + static var sharedRoutes: [Self] { + [ + .claudeMCPLocal, .codexMCPUser, .geminiMCPUser, .cursorMCPUser, + .openCodeMCPUserJSON, .openCodeMCPUserJSONC, + ] + } + static func targetRoute(_ path: String) -> Self? { + let key = path.split(separator: "/").first.map(String.init) + return allCases.first { $0.root == key } + } + static func sharedRoute(_ path: String) -> Self? { + targetRoute(path).flatMap { $0.shared ? $0 : nil } + } + static func metadataRoute(_ path: String) -> Self? { + let key = path.split(separator: "/").first.map(String.init) + return sharedRoutes.first { $0.metadata == key } } + func logicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + func home() throws -> URL { try Self.absoluteDirectory(environment.homeDirectory) } + func override(_ key: String) throws -> URL? { + guard let value = environment.environment[key], !value.isEmpty else { return nil } + guard value.hasPrefix("/"), !value.contains("\0") else { + throw CoreError.unsafePath("registered " + key + " must be an absolute directory") + } + return URL(fileURLWithPath: value).standardizedFileURL + } + switch self { + case .claudeMCPProject: + return try Self.absoluteDirectory(environment.projectDirectory) + case .claudeMCPLocal, .claudeMCPUser: + return try override("CLAUDE_CONFIG_DIR") ?? home() + case .codexMCPProject: + return try Self.absoluteDirectory(environment.projectDirectory).appendingPathComponent( + ".codex") + case .codexMCPUser: + if let root = try override("CODEX_HOME") { + _ = try DirectoryHandle(at: root.resolvingSymlinksInPath()) + return root + } + return try home().appendingPathComponent(".codex") + case .geminiMCPProject: + return try Self.absoluteDirectory(environment.projectDirectory).appendingPathComponent( + ".gemini") + case .geminiMCPUser: + return try (override("GEMINI_CLI_HOME") ?? home()).appendingPathComponent(".gemini") + case .cursorMCPProject: + return try Self.absoluteDirectory(environment.projectDirectory).appendingPathComponent( + ".cursor") + case .cursorMCPUser: + return try home().appendingPathComponent(".cursor") + case .openCodeMCPProjectJSON, .openCodeMCPProjectJSONC: + return try Self.absoluteDirectory(environment.projectDirectory) + case .openCodeMCPUserJSON, .openCodeMCPUserJSONC: + if environment.environment["OPENCODE_CONFIG_DIR"] == "" { + throw CoreError.unsafePath( + "empty OPENCODE_CONFIG_DIR does not establish a registered absolute root") + } + return try override("OPENCODE_CONFIG_DIR") + ?? (override("XDG_CONFIG_HOME") ?? home().appendingPathComponent(".config")) + .appendingPathComponent("opencode") + } + } + private static func absoluteDirectory(_ url: URL) throws -> URL { + guard url.isFileURL, url.path.hasPrefix("/"), !url.path.contains("\0") else { + throw CoreError.unsafePath("registered native root must be an absolute filesystem directory") + } + return url.standardizedFileURL + } + static func globalLogicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + try Self.claudeMCPLocal.logicalDirectory(environment) + } static func globalDirectory(_ environment: RuntimeEnvironment) throws -> URL { try globalLogicalDirectory(environment).resolvingSymlinksInPath() } @@ -42,7 +140,9 @@ struct SharedResourceIdentity: Codable, Equatable, Comparable { static func < (lhs: Self, rhs: Self) -> Bool { lhs.orderingKey < rhs.orderingKey } func validate() throws { - guard parent.isDirectory, basename == ".claude.json" else { + guard parent.isDirectory, + NativeTargetRoute.sharedRoutes.contains(where: { $0.basename == basename }) + else { throw CoreError.invalidState("unregistered shared transaction resource") } } @@ -60,6 +160,7 @@ struct SharedReservation: Codable, Equatable { final class SharedResource { static let metadataName = ".agents-native" let identity: SharedResourceIdentity + let route: NativeTargetRoute let parent: DirectoryHandle let metadata: DirectoryHandle? let ancestry: DirectoryAccessEvidence @@ -69,12 +170,14 @@ final class SharedResource { private var lockDescriptor: Int32? private var lockAccess: FileAccessEvidence? - init(store: StateStore, create: Bool) throws { - authorizedRoot = try NativeTargetRoute.globalLogicalDirectory(store.environment) + init(store: StateStore, route: NativeTargetRoute = .claudeMCPLocal, create: Bool) throws { + guard route.shared else { throw CoreError.invalidState("project route has no shared resource") } + self.route = NativeTargetRoute.sharedRoutes.first { $0.root == route.root }! + authorizedRoot = try route.logicalDirectory(store.environment) let url = authorizedRoot.resolvingSymlinksInPath() parent = try DirectoryHandle(at: url, create: create) ancestry = try DirectoryAccessEvidence.capture(at: url) - identity = SharedResourceIdentity(parent: try parent.objectIdentity, basename: ".claude.json") + identity = SharedResourceIdentity(parent: try parent.objectIdentity, basename: route.basename) func child(_ parent: DirectoryHandle, _ name: String) throws -> DirectoryHandle? { if try parent.info(name) == nil { guard create else { return nil } @@ -310,7 +413,8 @@ final class TransactionLockContext { func resource(_ identity: SharedResourceIdentity? = nil) throws -> SharedResource { try validateScope() - guard let resource = resources.first(where: { identity == nil || $0.identity == identity }) + guard identity != nil || resources.count == 1, + let resource = resources.first(where: { identity == nil || $0.identity == identity }) else { throw CoreError.invalidState("shared target is outside the held request footprint") } @@ -318,6 +422,13 @@ final class TransactionLockContext { return resource } + func resource(for route: NativeTargetRoute) throws -> SharedResource { + guard let resource = resources.first(where: { $0.route.root == route.root }) else { + throw CoreError.invalidState("shared target is outside the held request footprint") + } + return try self.resource(resource.identity) + } + func validate(_ journal: TransactionJournal, scope: DirectoryHandle) throws { try journal.validateCoordination() try validateScope() @@ -333,27 +444,19 @@ final class TransactionLockContext { extension StateStore { package func nativeTarget(for route: NativeTargetRoute) throws -> MaterializationTarget { - guard environment.projectDirectory.isFileURL, !environment.projectDirectory.path.contains("\0") - else { - throw CoreError.unsafePath("registered project root must be a filesystem directory") - } guard route.shared || scope == .project else { throw CoreError.unsafePath("project native targets require their project scope") } - let root = route.shared ? NativeTargetRoute.globalRoot : NativeTargetRoute.projectRoot + let logical = try route.logicalDirectory(environment) let parent: URL - if route.shared, let resource = TransactionLockContext.current(self)?.resources.first { - try resource.validate() - parent = resource.parent.url + if route.shared, let context = TransactionLockContext.current(self) { + parent = try context.resource(for: route).parent.url } else { - parent = - route.shared - ? try NativeTargetRoute.globalDirectory(environment) - : environment.projectDirectory.resolvingSymlinksInPath() + parent = logical.resolvingSymlinksInPath() } - let name = route.shared ? ".claude.json" : ".mcp.json" return MaterializationTarget( - url: parent.appendingPathComponent(name), path: root + "/" + name, scope: directory) + url: parent.appendingPathComponent(route.basename), + path: route.root + "/" + route.basename, scope: directory) } /// Acquire the union before the scope lock. Re-admission never replays a delivered callback. @@ -366,32 +469,53 @@ extension StateStore { } while true { let before = try pendingCoordinationJournal(diagnosing: !writable) - let needsShared = routes.contains(where: \.shared) || before?.footprint.isEmpty == false var resources: [SharedResource] = [] - if needsShared { - let pendingShared = before?.footprint.isEmpty == false + let pending = before?.footprint ?? [] + var requested = Set( + routes.filter(\.shared).map { route in + NativeTargetRoute.sharedRoutes.first { $0.root == route.root }! + }) + for identity in pending { + try identity.validate() + guard + let route = NativeTargetRoute.sharedRoutes.first(where: { + $0.basename == identity.basename + }) + else { + throw CoreError.invalidState("unregistered shared recovery resource") + } + requested.insert(route) + } + // Validate every original recovery domain before creating any newly requested metadata. + let ordered = requested.sorted { left, right in + let leftPending = pending.contains { $0.basename == left.basename } + let rightPending = pending.contains { $0.basename == right.basename } + return leftPending == rightPending ? left.rawValue < right.rawValue : leftPending + } + for route in ordered { + let recovering = pending.contains { $0.basename == route.basename } let resource: SharedResource - do { resource = try SharedResource(store: self, create: writable && !pendingShared) } catch - { - if pendingShared { + do { + resource = try SharedResource(store: self, route: route, create: writable && !recovering) + } catch { + if recovering { throw CoreError.invalidState( "shared recovery requires the original registered runtime context and verifiable coordination metadata" ) } throw error } - if pendingShared { - guard let metadata = resource.metadata, try metadata.info("lock") != nil else { - throw CoreError.invalidState("shared recovery coordination metadata is missing") + if recovering { + guard pending.contains(resource.identity), let metadata = resource.metadata, + try metadata.info("lock") != nil + else { + throw CoreError.invalidState( + "shared recovery requires the original runtime context and coordination lock") } } - for identity in before?.footprint ?? [] { - try identity.validate() - guard identity == resource.identity else { - throw CoreError.invalidState("shared recovery requires the original runtime context") - } + if !resources.contains(where: { $0.identity == resource.identity }) { + resources.append(resource) } - resources = [resource] } let context = TransactionLockContext( store: self, resources: resources.sorted { $0.identity < $1.identity }, writable: writable, @@ -402,7 +526,7 @@ extension StateStore { guard let metadata = resource.metadata else { // No metadata means no prior registered writer. Recheck after the unlocked read. let result = Result { try locked(index + 1) } - let after = try SharedResource(store: self, create: false) + let after = try SharedResource(store: self, route: resource.route, create: false) guard after.metadata == nil else { return nil } return try result.get() } diff --git a/Sources/AgentsCore/PrivateMaterialization.swift b/Sources/AgentsCore/PrivateMaterialization.swift index b8fb1a5..0d2ad0e 100644 --- a/Sources/AgentsCore/PrivateMaterialization.swift +++ b/Sources/AgentsCore/PrivateMaterialization.swift @@ -2,7 +2,9 @@ import CPlatform import Foundation /// Runtime data supplied by the application. Source declarations never supply commands. -package protocol RuntimeBindingProvider { +/// Implementations must return bounded, noninteractive data synchronously. They must not +/// hide network requests, login flows or unbounded work inside value resolution. +public protocol RuntimeBindingProvider: Sendable { func value(for binding: String, environment: RuntimeEnvironment) throws -> Data } @@ -183,7 +185,7 @@ struct MaterializationReceipts: Codable { let parts = try paths.components(path) guard (parts.root.hasPrefix("instructions-") && parts.root != "instructions-authoring") - || [NativeTargetRoute.projectRoot, NativeTargetRoute.globalRoot].contains(parts.root) + || NativeTargetRoute.targetRoute(parts.root) != nil else { throw CoreError.invalidState("invalid materialization receipt target") } @@ -202,22 +204,34 @@ extension StateStore { } func materializationRootIdentity(_ root: String) throws -> String { - if root == NativeTargetRoute.globalRoot { - return try TransactionLockContext.current(self).requiredResource().identity.orderingKey + if let route = NativeTargetRoute.sharedRoute(root) { + guard let context = TransactionLockContext.current(self) else { + throw CoreError.invalidState("shared receipt requires its held footprint") + } + return try context.resource(for: route).identity.orderingKey } return try TransactionPaths(store: self).root(root).identity } func materializationReceipts(for path: String = "") throws -> MaterializationReceiptState { - let shared = path.hasPrefix(NativeTargetRoute.globalRoot + "/") - let resource = shared ? try TransactionLockContext.current(self).requiredResource() : nil + let route = NativeTargetRoute.sharedRoute(path) + let shared = route != nil + let resource: SharedResource? + if let route { + guard let context = TransactionLockContext.current(self) else { + throw CoreError.invalidState("shared receipt requires its held footprint") + } + resource = try context.resource(for: route) + } else { + resource = nil + } let url: URL let receiptPath: String if let resource { let metadataURL = resource.parent.url.appendingPathComponent(SharedResource.metadataName) .appendingPathComponent(resource.identity.directoryName) url = (resource.metadata?.url ?? metadataURL).appendingPathComponent("receipt") - receiptPath = NativeTargetRoute.metadataRoot + "/receipt" + receiptPath = resource.route.metadata + "/receipt" } else { url = materializationReceiptURL receiptPath = "state/" + MaterializationReceipts.fileName @@ -233,11 +247,13 @@ extension StateStore { let records = try Self.decode( directory.read(url.lastPathComponent), as: MaterializationReceipts.self) try records.validate(store: self) - if shared, Set(records.targets.keys) != [NativeTargetRoute.globalRoot + "/.claude.json"] { + if let resource, + Set(records.targets.keys) != [resource.route.root + "/" + resource.identity.basename] + { throw CoreError.invalidState("shared receipt must identify its physical file") } for (key, record) in records.targets { - guard shared == key.hasPrefix(NativeTargetRoute.globalRoot + "/"), + guard shared == (NativeTargetRoute.sharedRoute(key) != nil), !shared || record.rootIdentity == resource?.identity.orderingKey else { throw CoreError.invalidState("receipt belongs to another physical resource") } } diff --git a/Sources/AgentsCore/TransactionJournal.swift b/Sources/AgentsCore/TransactionJournal.swift index a71d633..61f9816 100644 --- a/Sources/AgentsCore/TransactionJournal.swift +++ b/Sources/AgentsCore/TransactionJournal.swift @@ -22,8 +22,9 @@ struct TransactionJournal: Codable { var finalized = false func validateCoordination() throws { - // The closed routes currently share exactly one possible physical file per runtime. - guard footprint.count <= 1 else { + guard footprint.count <= NativeTargetRoute.sharedRoutes.count, + zip(footprint, footprint.dropFirst()).allSatisfy({ $0 < $1 }) + else { throw CoreError.invalidState("unregistered shared transaction footprint") } for identity in footprint { try identity.validate() } @@ -39,10 +40,15 @@ struct TransactionJournal: Codable { } } if !finalized { - let sharedRoots = - roots.keys.contains(NativeTargetRoute.globalRoot) - || roots.keys.contains(NativeTargetRoute.metadataRoot) - guard sharedRoots == !footprint.isEmpty else { + let sharedRoots = Set( + roots.keys.compactMap { key in + (NativeTargetRoute.sharedRoute(key) ?? NativeTargetRoute.metadataRoute(key))?.root + }) + let footprintRoots = Set( + footprint.compactMap { identity in + NativeTargetRoute.sharedRoutes.first { $0.basename == identity.basename }?.root + }) + guard sharedRoots == footprintRoots, footprintRoots.count == footprint.count else { throw CoreError.invalidState("journal roots contradict shared footprint") } } diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index 7d5a055..a40278d 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -29,16 +29,20 @@ struct TransactionPaths { } } } - let nativeRoutes: [NativeTargetRoute] = - store.scope == .project - ? [.claudeMCPProject, .claudeMCPLocal] : [.claudeMCPUser] - for route in nativeRoutes { - guard destination.lastPathComponent == (route.shared ? ".claude.json" : ".mcp.json") else { - continue - } + let nativeRoutes = NativeTargetRoute.allCases.sorted { $0.shared && !$1.shared } + for route in nativeRoutes where route.shared || store.scope == .project { + guard destination.lastPathComponent == route.basename else { continue } + let registered = try route.logicalDirectory(store.environment).resolvingSymlinksInPath() + .appendingPathComponent(route.basename) + guard registered == destination.standardizedFileURL else { continue } let target = try store.nativeTarget(for: route) if target.url == destination.standardizedFileURL { - if route.shared { _ = try TransactionLockContext.current(store).requiredResource() } + if route.shared { + guard let context = TransactionLockContext.current(store) else { + throw CoreError.invalidState("shared target requires its held footprint") + } + _ = try context.resource(for: route) + } return target.path } } @@ -77,12 +81,21 @@ struct TransactionPaths { store.scope == .project ? store.environment.projectDirectory : store.environment.homeDirectory url = base.resolvingSymlinksInPath().appendingPathComponent(store.directory.lastPathComponent) - } else if key == NativeTargetRoute.projectRoot, store.scope == .project { - url = store.environment.projectDirectory.resolvingSymlinksInPath() - } else if key == NativeTargetRoute.globalRoot { - url = try TransactionLockContext.current(store).requiredResource().parent.url - } else if key == NativeTargetRoute.metadataRoot { - guard let metadata = try TransactionLockContext.current(store).requiredResource().metadata + } else if let route = NativeTargetRoute.targetRoute(key) { + guard route.shared || store.scope == .project else { + throw CoreError.unsafePath("project native targets require their project scope") + } + if route.shared { + guard let context = TransactionLockContext.current(store) else { + throw CoreError.invalidState("shared target requires its held footprint") + } + url = try context.resource(for: route).parent.url + } else { + url = try route.logicalDirectory(store.environment).resolvingSymlinksInPath() + } + } else if let route = NativeTargetRoute.metadataRoute(key) { + guard let context = TransactionLockContext.current(store), + let metadata = try context.resource(for: route).metadata else { throw CoreError.invalidState("shared metadata directory is missing") } @@ -108,6 +121,16 @@ struct TransactionPaths { return url } + func nativeRootAuthorities(_ keys: Set) throws -> [String: URL] { + var result: [String: URL] = [:] + for key in keys { + if let route = NativeTargetRoute.targetRoute(key), !route.shared { + result[key] = try route.logicalDirectory(store.environment) + } + } + return result + } + /// 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, @@ -134,15 +157,11 @@ struct TransactionPaths { guard stateFile || cache else { throw CoreError.unsafePath("unmanaged state transaction path") } - } else if key == NativeTargetRoute.projectRoot { - guard store.scope == .project, descendants == [".mcp.json"] else { - throw CoreError.unsafePath("unregistered project native target") - } - } else if key == NativeTargetRoute.globalRoot { - guard descendants == [".claude.json"] else { - throw CoreError.unsafePath("unregistered shared native target") + } else if let route = NativeTargetRoute.targetRoute(key) { + guard route.shared || store.scope == .project, descendants == [route.basename] else { + throw CoreError.unsafePath("unregistered native target") } - } else if key == NativeTargetRoute.metadataRoot { + } else if NativeTargetRoute.metadataRoute(key) != nil { guard descendants == ["receipt"] else { throw CoreError.unsafePath("unregistered shared transaction metadata") } diff --git a/Sources/AgentsCore/TransactionPublication.swift b/Sources/AgentsCore/TransactionPublication.swift index dcdaff2..85d3902 100644 --- a/Sources/AgentsCore/TransactionPublication.swift +++ b/Sources/AgentsCore/TransactionPublication.swift @@ -250,24 +250,28 @@ extension TransactionSession { } } - func materializationReceipts(previous: MaterializationReceipts, shared: Bool = false) throws + func materializationReceipts(previous: MaterializationReceipts, targetRoot: String? = nil) throws -> MaterializationReceipts { var records = previous for entry in journal.entries where entry.path != "state/" + MaterializationReceipts.fileName - && !entry.path.hasPrefix(NativeTargetRoute.metadataRoot + "/") - && entry.path.hasPrefix(NativeTargetRoute.globalRoot + "/") == shared + && NativeTargetRoute.metadataRoute(entry.path) == nil + && NativeTargetRoute.sharedRoute(entry.path)?.root == targetRoot { if entry.security.replacement == .privateMaterialization { guard let snapshot = entry.staged, let access = entry.security.stagedAccess, let root = entry.path.split(separator: "/").first, let identity = journal.roots[String(root)] else { throw CoreError.invalidState("materialization is missing sealed receipt evidence") } + let resource = resources.first { $0.route.root == String(root) } + if targetRoot != nil, resource == nil { + throw CoreError.invalidState("receipt resource is outside the transaction footprint") + } records.targets[entry.path] = .init( generation: journal.id, - rootIdentity: shared ? resources[0].identity.orderingKey : identity, + rootIdentity: resource?.identity.orderingKey ?? identity, digest: snapshot.digest, access: access) } else { records.targets.removeValue(forKey: entry.path) diff --git a/Sources/AgentsCore/TransactionRecovery.swift b/Sources/AgentsCore/TransactionRecovery.swift index c6ce4c8..8d2d6b8 100644 --- a/Sources/AgentsCore/TransactionRecovery.swift +++ b/Sources/AgentsCore/TransactionRecovery.swift @@ -246,7 +246,7 @@ extension FileTransaction { journal: journal, directory: directory, parents: parents, checkpoint: checkpoint, resources: try journal.footprint.map { identity in try TransactionLockContext.current(store).requiredResource(identity) - }) + }, nativeRoots: try paths.nativeRootAuthorities(Set(journal.roots.keys))) try session.validateRecords(store: store) return session } diff --git a/Sources/AgentsCore/TransactionSession.swift b/Sources/AgentsCore/TransactionSession.swift index 83e48af..4f94645 100644 --- a/Sources/AgentsCore/TransactionSession.swift +++ b/Sources/AgentsCore/TransactionSession.swift @@ -7,19 +7,23 @@ final class TransactionSession { let parents: [DirectoryHandle] let checkpoint: (String) throws -> Void let resources: [SharedResource] + /// Logical project-root authorization is checked separately from opened physical parents. + private let nativeRoots: [String: URL] /// Devices whose atomic renames passed a probe during this session only; `st_dev` values /// can be reused by another filesystem after an unmount. var capableDevices: Set = [] init( journal: TransactionJournal, directory: DirectoryHandle, parents: [DirectoryHandle], - checkpoint: @escaping (String) throws -> Void, resources: [SharedResource] = [] + checkpoint: @escaping (String) throws -> Void, resources: [SharedResource] = [], + nativeRoots: [String: URL] = [:] ) { self.journal = journal self.directory = directory self.parents = parents self.checkpoint = checkpoint self.resources = resources + self.nativeRoots = nativeRoots } func emit(_ point: TransactionCheckpoint) throws { try checkpoint(point.name) } @@ -84,6 +88,14 @@ final class TransactionSession { func requireParent(_ index: Int) throws { if !resources.isEmpty { try requireScope() } + if let route = NativeTargetRoute.targetRoute(journal.entries[index].path), !route.shared { + guard let logical = nativeRoots[route.root], + try DirectoryHandle(at: logical.resolvingSymlinksInPath()).identity + == journal.roots[route.root] + else { + throw conflict(index, "registered native root changed after preparation") + } + } try journal.entries[index].security.ancestry?.validate(at: parents[index].url) guard try DirectoryHandle(at: parents[index].url).identity == journal.entries[index].parentIdentity diff --git a/Tests/AgentsCoreTests/PrivateMaterializationTests.swift b/Tests/AgentsCoreTests/PrivateMaterializationTests.swift index 4a97197..7a8392a 100644 --- a/Tests/AgentsCoreTests/PrivateMaterializationTests.swift +++ b/Tests/AgentsCoreTests/PrivateMaterializationTests.swift @@ -1,6 +1,7 @@ import CPlatform import Foundation import StateTestSupport +import Synchronization import Testing @testable import AgentsCore @@ -486,11 +487,18 @@ struct PrivateMaterializationTests { private final class TestBindings: RuntimeBindingProvider { let value: String - var calls = 0 - var fails = false + private let state = Mutex((calls: 0, fails: false)) + var calls: Int { state.withLock { $0.calls } } + var fails: Bool { + get { state.withLock { $0.fails } } + set { state.withLock { $0.fails = newValue } } + } init(_ value: String) { self.value = value } func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { - calls += 1 + let fails = state.withLock { + $0.calls += 1 + return $0.fails + } if fails { throw CoreError.invalidState(value) } return Data(value.utf8) } diff --git a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift new file mode 100644 index 0000000..1ff9061 --- /dev/null +++ b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift @@ -0,0 +1,377 @@ +import CPlatform +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite("Registered native MCP files") +struct RegisteredNativeTargetTests { + @Test(arguments: NativeTargetRoute.allCases) + func registeredFilesPublishPrivatelyAndRetainTheirReceipt(_ route: NativeTargetRoute) throws { + let fixture = try NativeRouteFixture() + let expected: [NativeTargetRoute: String] = [ + .claudeMCPProject: ".mcp.json", .claudeMCPLocal: "configured/.claude.json", + .claudeMCPUser: "configured/.claude.json", .codexMCPProject: ".codex/config.toml", + .codexMCPUser: "configured/config.toml", .geminiMCPProject: ".gemini/settings.json", + .geminiMCPUser: "configured/.gemini/settings.json", .cursorMCPProject: ".cursor/mcp.json", + .cursorMCPUser: "home/.cursor/mcp.json", .openCodeMCPProjectJSON: "opencode.json", + .openCodeMCPProjectJSONC: "opencode.jsonc", .openCodeMCPUserJSON: "configured/opencode.json", + .openCodeMCPUserJSONC: "configured/opencode.jsonc", + ] + let store = fixture.store + var privateBeforeWrite = false + try store.withLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + #expect(target.url == fixture.root.appendingPathComponent(try #require(expected[route]))) + let transaction = FileTransaction(store: store) { point in + if point == "stage.0.writeCreated" { + let journal = try fixture.journal() + let container = try DirectoryHandle( + at: target.url.deletingLastPathComponent().appendingPathComponent( + journal.containers[0].name)) + _ = try container.requirePrivateAccess("entry.0.staged") + #expect(try container.read("entry.0.staged").isEmpty) + privateBeforeWrite = true + } + } + try transaction.replacePrivate( + try store.preparePrivateMaterialization(target), bindings: ["fixture"], + provider: NativeRouteBindings() + ) { try $0.value(for: "fixture") } + try transaction.commit() + let receipt = try #require(try store.materializationReceipt(for: target)) + let edit = FileTransaction(store: store) + try edit.replace(target.url, with: .data(Data("owned sibling; next region".utf8))) + try edit.commit() + #expect(try store.materializationReceipt(for: target)?.generation != receipt.generation) + #expect(try Data(contentsOf: target.url) == Data("owned sibling; next region".utf8)) + if !route.shared { #expect(TransactionLockContext.current(store)?.resources.isEmpty == true) } + } + #expect(privateBeforeWrite) + } + + @Test func explicitRootsAndFileVariantsDoNotGuessDiscoveryOrAuthorizeSiblings() throws { + let fixture = try NativeRouteFixture() + let environment = RuntimeEnvironment( + projectDirectory: fixture.root, homeDirectory: fixture.root.appendingPathComponent("home"), + environment: [ + "CURSOR_CONFIG_DIR": fixture.config.path, "XDG_CONFIG_HOME": fixture.config.path, + ]) + let store = StateStore(scope: .project, environment: environment) + #expect( + try store.nativeTarget(for: .codexMCPUser).url + == environment.homeDirectory.appendingPathComponent(".codex/config.toml")) + #expect( + try store.nativeTarget(for: .geminiMCPUser).url + == environment.homeDirectory.appendingPathComponent(".gemini/settings.json")) + #expect( + try store.nativeTarget(for: .cursorMCPUser).url + == environment.homeDirectory.appendingPathComponent(".cursor/mcp.json")) + #expect( + try store.nativeTarget(for: .openCodeMCPUserJSONC).url + == fixture.config.appendingPathComponent("opencode/opencode.jsonc")) + try FileManager.default.createDirectory( + at: fixture.config.appendingPathComponent("opencode"), withIntermediateDirectories: true) + let before = try FileSnapshot.read(at: fixture.root) + try store.withReadLock(footprint: [.openCodeMCPUserJSON, .openCodeMCPUserJSONC]) { + let json = try store.nativeTarget(for: .openCodeMCPUserJSON) + let jsonc = try store.nativeTarget(for: .openCodeMCPUserJSONC) + #expect(json.url.lastPathComponent == "opencode.json") + #expect(jsonc.url.lastPathComponent == "opencode.jsonc") + } + #expect(try FileSnapshot.read(at: fixture.root) == before) + for (key, route) in [ + ("CODEX_HOME", NativeTargetRoute.codexMCPUser), + ("GEMINI_CLI_HOME", .geminiMCPUser), ("OPENCODE_CONFIG_DIR", .openCodeMCPUserJSON), + ("XDG_CONFIG_HOME", .openCodeMCPUserJSON), + ] { + let invalid = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: fixture.root, homeDirectory: environment.homeDirectory, + environment: [key: "relative-root"])) + #expect(throws: CoreError.self) { try invalid.nativeTarget(for: route) } + } + let missing = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: fixture.root, homeDirectory: environment.homeDirectory, + environment: ["CODEX_HOME": fixture.root.appendingPathComponent("missing").path])) + #expect(throws: CoreError.self) { try missing.withLock(footprint: [.codexMCPUser]) {} } + #expect( + !FileManager.default.fileExists(atPath: fixture.root.appendingPathComponent("missing").path)) + try fixture.store.withLock(footprint: [.codexMCPUser]) { + let transaction = FileTransaction(store: fixture.store) + #expect(throws: CoreError.self) { + try transaction.replace( + fixture.config.appendingPathComponent("auth.json"), with: .data(Data())) + } + #expect(throws: CoreError.self) { + try transaction.replace( + fixture.config.appendingPathComponent("other.toml"), with: .data(Data())) + } + } + let user = StateStore(scope: .user, environment: fixture.store.environment) + #expect(throws: CoreError.self) { try user.nativeTarget(for: .codexMCPProject) } + } + + @Test(arguments: ["queued", "staged"]) + func projectRootAliasesCannotRedirectQueuedOrdinaryWrites(_ change: String) throws { + let fixture = try NativeRouteFixture() + let first = fixture.root.appendingPathComponent("first") + let second = fixture.root.appendingPathComponent("second") + for root in [first, second] { + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + let alias = fixture.root.appendingPathComponent(".codex") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: first) + func redirect() throws { + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: second) + } + #expect(throws: CoreError.self) { + try fixture.store.withLock(footprint: [.codexMCPProject]) { + let target = try fixture.store.nativeTarget(for: .codexMCPProject) + let transaction = FileTransaction(store: fixture.store) { point in + if change == "staged", point == "stage.0.writeCreated" { try redirect() } + } + try transaction.replace(target.url, with: .data(Data("owned region".utf8))) + if change == "queued" { try redirect() } + try transaction.commit() + } + } + let journal = fixture.store.directory.appendingPathComponent("transaction.json") + if change == "staged" { + #expect(FileManager.default.fileExists(atPath: journal.path)) + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: first) + #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { + try fixture.store.withLock {} + } + } + #expect(!FileManager.default.fileExists(atPath: journal.path)) + #expect( + !FileManager.default.fileExists(atPath: first.appendingPathComponent("config.toml").path)) + #expect( + !FileManager.default.fileExists(atPath: second.appendingPathComponent("config.toml").path)) + } + + @Test func projectAndUserFileCoincidenceRequiresTheSharedAdmission() throws { + let fixture = try NativeRouteFixture() + let root = fixture.root.appendingPathComponent(".codex") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: fixture.root, homeDirectory: fixture.root.appendingPathComponent("home"), + environment: ["CODEX_HOME": root.path])) + try store.withLock(footprint: [.codexMCPProject]) { + let target = try store.nativeTarget(for: .codexMCPProject) + let transaction = FileTransaction(store: store) + #expect(throws: CoreError.self) { + try transaction.replace(target.url, with: .data(Data("owned region".utf8))) + } + } + try store.withLock(footprint: [.codexMCPUser]) { + let target = try store.nativeTarget(for: .codexMCPUser) + let transaction = FileTransaction(store: store) + try transaction.replace(target.url, with: .data(Data("shared region".utf8))) + try transaction.commit() + } + #expect( + try Data(contentsOf: root.appendingPathComponent("config.toml")) == Data("shared region".utf8) + ) + } + + @Test func distinctFilesHaveIndependentReceiptsAcrossAliasedHomes() throws { + let fixture = try NativeRouteFixture() + let store = fixture.store + let routes = Set(NativeTargetRoute.sharedRoutes) + var receipts: [NativeTargetRoute: Data] = [:] + var identities: [NativeTargetRoute: SharedResourceIdentity] = [:] + try store.withLock(footprint: routes) { + let transaction = FileTransaction(store: store) + for route in NativeTargetRoute.sharedRoutes { + let target = try store.nativeTarget(for: route) + try transaction.replacePrivate( + try store.preparePrivateMaterialization(target), provider: NativeRouteBindings() + ) { _ in Data(route.rawValue.utf8) } + identities[route] = try TransactionLockContext.current(store).requiredResourceForRoute( + route + ).identity + } + try transaction.commit() + for route in NativeTargetRoute.sharedRoutes { + let target = try store.nativeTarget(for: route) + let receipt = try store.materializationReceipts(for: target.path) + #expect(Set(receipt.records.targets.keys) == [target.path]) + receipts[route] = try Data(contentsOf: receipt.url) + } + } + #expect(Set(identities.values.map(\.orderingKey)).count == NativeTargetRoute.sharedRoutes.count) + let alias = fixture.root.appendingPathComponent("alias") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: fixture.config) + let other = StateStore( + scope: .user, + environment: RuntimeEnvironment( + projectDirectory: fixture.root, + homeDirectory: fixture.root.appendingPathComponent("other-home"), + environment: [ + "CLAUDE_CONFIG_DIR": alias.path, "CODEX_HOME": alias.path, + "GEMINI_CLI_HOME": alias.path, "OPENCODE_CONFIG_DIR": alias.path, + ])) + let shared = Set([ + NativeTargetRoute.codexMCPUser, .geminiMCPUser, .openCodeMCPUserJSON, .openCodeMCPUserJSONC, + .claudeMCPLocal, + ]) + try other.withLock(footprint: shared) { + for route in shared { + #expect( + try TransactionLockContext.current(other).requiredResourceForRoute(route).identity + == identities[route]) + } + let target = try other.nativeTarget(for: .codexMCPUser) + let transaction = FileTransaction(store: other) + try transaction.replace(target.url, with: .data(Data("owned sibling; new codex region".utf8))) + try transaction.commit() + } + try store.withLock(footprint: routes) { + for route in NativeTargetRoute.sharedRoutes { + let target = try store.nativeTarget(for: route) + #expect(try store.materializationReceipt(for: target) != nil) + let receipt = try store.materializationReceipts(for: target.path) + if route != .codexMCPUser { #expect(try Data(contentsOf: receipt.url) == receipts[route]) } + } + let transaction = FileTransaction(store: store) + try transaction.delete(store.nativeTarget(for: .openCodeMCPUserJSON).url) + try transaction.commit() + #expect( + try store.materializationReceipt(for: store.nativeTarget(for: .openCodeMCPUserJSON)) == nil) + #expect( + try store.materializationReceipt(for: store.nativeTarget(for: .openCodeMCPUserJSONC)) != nil + ) + } + } + + @Test func aChangedPendingRuntimeCannotCreateAnUnrelatedRequestedDomain() throws { + let fixture = try NativeRouteFixture() + let child = try stateTestProcess( + root: fixture.root, + arguments: [ + "shared-install", "shared.ready", "--native-routes", + "codex.mcp.user,opencode.mcp.user.jsonc", "--shared-config", fixture.config.path, + ]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let before = try FileSnapshot.read(at: fixture.root) + let changed = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: fixture.root, homeDirectory: fixture.store.environment.homeDirectory, + environment: [ + "CODEX_HOME": fixture.config.path, + "OPENCODE_CONFIG_DIR": fixture.root.appendingPathComponent("wrong-root").path, + ])) + #expect(throws: CoreError.self) { + try changed.withLock(footprint: [.cursorMCPUser]) { + Issue.record("pending recovery must reject the changed runtime before callback") + } + } + #expect(try FileSnapshot.read(at: fixture.root) == before) + } + + @Test(arguments: [ + "shared.1.reservation.halfWritten", "shared.ready", "entry.0.applied", "journal.finalized", + ]) + func multiplePendingResourcesRecoverUnderTheirOriginalRuntime(_ point: String) throws { + let fixture = try NativeRouteFixture() + let child = try stateTestProcess( + root: fixture.root, + arguments: [ + "shared-install", point, "--native-routes", "codex.mcp.user,opencode.mcp.user.jsonc", + "--shared-config", fixture.config.path, + ]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let before = try FileSnapshot.read(at: fixture.root) + try fixture.store.withReadLock( + onPendingRecovery: { + let diagnostic = FileTransaction.recoveryDiagnostic(store: fixture.store) + #expect(!diagnostic.requiresOwner) + let context = try #require(TransactionLockContext.current(fixture.store)) + #expect( + Set(context.resources.map { $0.identity.basename }) == ["config.toml", "opencode.jsonc"]) + }, { _ = Issue.record("expected pending native resources") }) + #expect(try FileSnapshot.read(at: fixture.root) == before) + var entered = false + #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { + try fixture.store.withLock(footprint: [.cursorMCPUser]) { entered = true } + } + #expect(!entered) + try fixture.store.withLock(footprint: [.codexMCPUser, .openCodeMCPUserJSONC]) { + for route in [NativeTargetRoute.codexMCPUser, .openCodeMCPUserJSONC] { + let target = try fixture.store.nativeTarget(for: route) + let receipt = try fixture.store.materializationReceipt(for: target) + if point == "journal.finalized" { + #expect(receipt != nil) + } else { + #expect(!FileManager.default.fileExists(atPath: target.url.path)) + #expect(receipt == nil) + } + } + } + } +} + +private struct NativeRouteBindings: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + Data(binding.utf8) + } +} + +private final class NativeRouteFixture { + let root: URL + let config: URL + let store: StateStore + init() throws { + root = try temporaryDirectory() + config = root.appendingPathComponent("configured") + do { + try FileManager.default.createDirectory(at: config, withIntermediateDirectories: true) + try FileManager.default.createDirectory( + at: root.appendingPathComponent("home"), withIntermediateDirectories: true) + try FileManager.default.createDirectory( + at: root.appendingPathComponent("other-home"), withIntermediateDirectories: true) + try FileManager.default.createDirectory( + at: root.appendingPathComponent("old-data"), withIntermediateDirectories: true) + try Data("ordinary before".utf8).write(to: root.appendingPathComponent("old-data/AGENTS.md")) + store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: [ + "CLAUDE_CONFIG_DIR": config.path, "CODEX_HOME": config.path, + "GEMINI_CLI_HOME": config.path, "OPENCODE_CONFIG_DIR": config.path, + ])) + } catch { + removeTemporaryDirectory(root) + throw error + } + } + deinit { removeTemporaryDirectory(root) } + func journal() throws -> TransactionJournal { + try FileTransaction.readJournal( + Data(contentsOf: store.directory.appendingPathComponent("transaction.json"))) + } +} + +extension Optional where Wrapped == TransactionLockContext { + fileprivate func requiredResourceForRoute(_ route: NativeTargetRoute) throws -> SharedResource { + try #require(self).resource(for: route) + } +} diff --git a/Tests/AgentsCoreTests/SharedTargetTests.swift b/Tests/AgentsCoreTests/SharedTargetTests.swift index 21dfdba..afb4cf9 100644 --- a/Tests/AgentsCoreTests/SharedTargetTests.swift +++ b/Tests/AgentsCoreTests/SharedTargetTests.swift @@ -1,6 +1,7 @@ import CPlatform import Foundation import StateTestSupport +import Synchronization import Testing @testable import AgentsCore @@ -359,7 +360,8 @@ struct SharedTargetTests { } } - @Test func pendingFootprintReadmitsBeforeCallbackOrProvider() throws { + @Test(arguments: [false, true]) + func pendingFootprintReadmitsBeforeCallbackOrProvider(_ multipleResources: Bool) throws { let fixture = try SharedFixture() try fixture.install() let original = try Data(contentsOf: fixture.target) @@ -367,15 +369,16 @@ struct SharedTargetTests { let marker = fixture.root.appendingPathComponent("ready") let nextStop = fixture.root.appendingPathComponent("stop-at") let journal = fixture.a.directory.appendingPathComponent("transaction.json") + let extra = multipleResources ? ["--native-routes", "claude.mcp.local,codex.mcp.user"] : [] let holder = try stateTestProcess( - root: fixture.root, arguments: ["shared-readmission-writer", "shared.beforeJournal"]) + root: fixture.root, arguments: ["shared-readmission-writer", "shared.beforeJournal"] + extra) defer { terminateProcess(holder) } try ProcessWait.marker(marker, child: holder, root: fixture.root) try ProcessWait.stopped(holder, root: fixture.root) #expect(!FileManager.default.fileExists(atPath: journal.path)) try FileManager.default.removeItem(at: marker) let waiter = try stateTestProcess( - root: fixture.root, arguments: ["shared-admission-wait", "scope-contention"]) + root: fixture.root, arguments: ["shared-admission-wait", "scope-contention"] + extra) defer { terminateProcess(waiter) } try ProcessWait.marker(marker, child: waiter, root: fixture.root) try ProcessWait.stopped(waiter, root: fixture.root) @@ -399,11 +402,16 @@ struct SharedTargetTests { try ProcessWait.marker(other.appendingPathComponent("ready"), child: blocker, root: other) try ProcessWait.stopped(blocker, root: other) try FileManager.default.removeItem(at: marker) - try Data("shared.0.lock.contended".utf8).write(to: nextStop) + let pending = try fixture.journal(fixture.a) + let claude = try SharedResource(store: fixture.b, create: false).identity + let index = try #require(pending.footprint.firstIndex(of: claude)) + let sharedContention = "shared.\(index).lock.contended" + if multipleResources { #expect(pending.footprint.contains { $0.basename == "config.toml" }) } + try Data(sharedContention.utf8).write(to: nextStop) try #require(kill(waiter.processIdentifier, SIGCONT) == 0) try ProcessWait.marker(marker, child: waiter, root: fixture.root) try ProcessWait.stopped(waiter, root: fixture.root) - #expect(try String(contentsOf: marker, encoding: .utf8) == "shared.0.lock.contended") + #expect(try String(contentsOf: marker, encoding: .utf8) == sharedContention) #expect(FileManager.default.fileExists(atPath: journal.path)) #expect( !FileManager.default.fileExists( @@ -990,9 +998,10 @@ struct SharedTargetTests { } private final class SharedBindings: RuntimeBindingProvider { - var calls = 0 + private let count = Mutex(0) + var calls: Int { count.withLock { $0 } } func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { - calls += 1 + count.withLock { $0 += 1 } return Data("secret sibling; initial region".utf8) } } diff --git a/Tests/StateTestProcess/PrivateMaterializationProbe.swift b/Tests/StateTestProcess/PrivateMaterializationProbe.swift index f7194b0..5a72c72 100644 --- a/Tests/StateTestProcess/PrivateMaterializationProbe.swift +++ b/Tests/StateTestProcess/PrivateMaterializationProbe.swift @@ -80,26 +80,39 @@ func sharedMaterializationProbe( do { try store.withLock(checkpoint: checkpoint, {}) } catch CoreError.transactionRecovered {} return } - try store.withLock(checkpoint: checkpoint, footprint: [.claudeMCPLocal]) { + let routes: [NativeTargetRoute] + if let index = CommandLine.arguments.firstIndex(of: "--native-routes"), + CommandLine.arguments.indices.contains(index + 1) + { + routes = try CommandLine.arguments[index + 1].split(separator: ",").map { + guard let route = NativeTargetRoute(rawValue: String($0)) else { + throw CoreError.invalidState("invalid test native route") + } + return route + } + } else { + routes = [.claudeMCPLocal] + } + try store.withLock(checkpoint: checkpoint, footprint: Set(routes)) { if command == "shared-lock" { try checkpoint("shared.locked") return } if command == "shared-readmission-writer" { try checkpoint("shared.beforeJournal") } - let target = try store.nativeTarget(for: .claudeMCPLocal) let transaction = FileTransaction(store: store, checkpoint: checkpoint) - if command == "shared-delete" { - try transaction.delete(target.url) - } else if command == "shared-install" { - let prepared = try store.preparePrivateMaterialization(target, changingAccess: true) - try transaction.replacePrivate( - prepared, bindings: ["value"], - provider: ProbeBindings(root: store.environment.projectDirectory) - ) { - try $0.value(for: "value") + for route in routes { + let target = try store.nativeTarget(for: route) + if command == "shared-delete" { + try transaction.delete(target.url) + } else if command == "shared-install" { + let prepared = try store.preparePrivateMaterialization(target, changingAccess: true) + try transaction.replacePrivate( + prepared, bindings: ["value"], + provider: ProbeBindings(root: store.environment.projectDirectory) + ) { try $0.value(for: "value") } + } else { + try transaction.replace(target.url, with: .data(Data("secret sibling; edited region".utf8))) } - } else { - try transaction.replace(target.url, with: .data(Data("secret sibling; edited region".utf8))) } try transaction.replace( store.environment.projectDirectory.appendingPathComponent("old-data/AGENTS.md"), diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 88a54a6..b9f40ad 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -22,7 +22,12 @@ let store = StateStore( environment: RuntimeEnvironment( projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), - environment: ["CLAUDE_CONFIG_DIR": sharedConfig])) + environment: arguments.contains("--native-routes") + ? [ + "CLAUDE_CONFIG_DIR": sharedConfig, "CODEX_HOME": sharedConfig, + "OPENCODE_CONFIG_DIR": sharedConfig, "GEMINI_CLI_HOME": sharedConfig, + ] + : ["CLAUDE_CONFIG_DIR": sharedConfig])) let checkpointState = Mutex( (requested: arguments.count > 3 ? arguments[3] : "", seen: Set())) let traceURL = root.appendingPathComponent( From 8779b9c9ba8be1d0aaa9f0ae17bf6cc7e8fdcc2a Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:45:32 +0800 Subject: [PATCH 071/171] feat: lower native components and staged MCP values --- .../Components/Adapters/CodexComponents.swift | 45 ++ .../Adapters/CursorComponents.swift | 56 ++ .../Adapters/GeminiComponents.swift | 117 ++++ .../Adapters/OpenCodeComponents.swift | 74 +++ Sources/Components/CapabilityRegistry.swift | 119 ++++ Sources/Components/FrozenNativeIdentity.swift | 71 +++ Sources/Components/MCPLowering.swift | 79 +-- Sources/Components/MCPStagedValues.swift | 89 +++ .../Components/NativeComponentLayoutsV1.swift | 75 +++ .../Components/NativeComponentLowering.swift | 400 ++++++++++++ Sources/Components/NativeHookLayoutV1.swift | 103 +++ Sources/Components/NativeIgnoreLayoutV1.swift | 17 + Sources/Components/NativeLSPLayoutV1.swift | 36 ++ Sources/Components/NativePluginLayoutV1.swift | 116 ++++ Sources/Components/NativeProgramV1.swift | 201 ++++++ Sources/NativeDocuments/Model.swift | 14 +- .../NativeComponentTests.swift | 600 ++++++++++++++++++ Tests/ComponentsTests/NativeMCPTests.swift | 106 +++- 18 files changed, 2267 insertions(+), 51 deletions(-) create mode 100644 Sources/Components/Adapters/CodexComponents.swift create mode 100644 Sources/Components/Adapters/CursorComponents.swift create mode 100644 Sources/Components/Adapters/GeminiComponents.swift create mode 100644 Sources/Components/Adapters/OpenCodeComponents.swift create mode 100644 Sources/Components/FrozenNativeIdentity.swift create mode 100644 Sources/Components/MCPStagedValues.swift create mode 100644 Sources/Components/NativeComponentLayoutsV1.swift create mode 100644 Sources/Components/NativeComponentLowering.swift create mode 100644 Sources/Components/NativeHookLayoutV1.swift create mode 100644 Sources/Components/NativeIgnoreLayoutV1.swift create mode 100644 Sources/Components/NativeLSPLayoutV1.swift create mode 100644 Sources/Components/NativePluginLayoutV1.swift create mode 100644 Sources/Components/NativeProgramV1.swift create mode 100644 Tests/ComponentsTests/NativeComponentTests.swift diff --git a/Sources/Components/Adapters/CodexComponents.swift b/Sources/Components/Adapters/CodexComponents.swift new file mode 100644 index 0000000..363bbc7 --- /dev/null +++ b/Sources/Components/Adapters/CodexComponents.swift @@ -0,0 +1,45 @@ +import AgentsCore + +extension CodexAdapter { + static func components(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + switch input.record.kind { + case "subagent": + _ = try input.checkedNative([:]) + guard input.fields["tools"] == nil else { + throw input.issue( + ["tools"], .unsupported, "role overrides do not represent a portable tool allowlist") + } + let name = try input.relativeName() + let description = try input.text("description") + guard !NativeComponentText.isBlank(description, rust: true) else { + throw input.issue(["description"], .invalid, "native role description must not be blank") + } + guard NativeComponentText.isUntrimmed(description, rust: true) else { + throw input.issue(["description"], .unsupported, "native role descriptions are trimmed") + } + let prompt = try input.prompt() + guard !NativeComponentText.isBlank(prompt, rust: true) else { + throw input.issue(["prompt"], .invalid, "native role instructions must not be blank") + } + var lines = ["developer_instructions = " + (try input.quoted(prompt))] + if let model = input.fields["model"]?.text { + lines.append("model = " + (try input.quoted(model))) + } + lines.append("") + let file = input.envelope( + route: .codexAgent, path: name + ".toml", + selection: "file", value: .init(try input.joined(lines))) + let registration = input.envelope( + route: .codexConfig, keys: ["agents", name], + value: .init(object: [ + "description": .init(description), "config_file": .init("./agents/" + name + ".toml"), + ])) + return try input.emitted(lowering, .init(array: [file, registration])) + case "hook": return try NativeHookLayoutV1.render(lowering, input) + default: + throw input.issue(["kind"], .invalid, "component does not match this concrete native profile") + } + } +} diff --git a/Sources/Components/Adapters/CursorComponents.swift b/Sources/Components/Adapters/CursorComponents.swift new file mode 100644 index 0000000..d8177ad --- /dev/null +++ b/Sources/Components/Adapters/CursorComponents.swift @@ -0,0 +1,56 @@ +import AgentsCore + +extension CursorAdapter { + static func components(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + switch input.record.kind { + case "command": + _ = try input.checkedNative([:]) + try input.noParameters() + // The native file is a plain prompt; its schema has no description field. + guard try input.text("description").isEmpty else { + throw input.issue( + ["description"], .unsupported, "plain Markdown command files have no description field") + } + let name = try input.filename() + return try input.emitted( + lowering, + input.envelope( + route: .cursorCommand, + path: name + ".md", selection: "file", value: .init(try input.prompt()))) + case "subagent": + guard input.fields["tools"] == nil else { + throw input.issue( + ["tools"], .unverified, + "the documented subagent schema does not establish a tool allowlist") + } + var fields = try input.checkedNative(["readonly": .boolean, "is_background": .boolean]) + let name = try input.filename() + fields["name"] = .init(name) + fields["description"] = .init(try input.text("description")) + fields["model"] = input.fields["model"] + return try input.emitted( + lowering, + input.envelope( + route: .cursorAgent, + path: name + ".md", selection: "file", + value: .init(try input.frontmatter(fields, body: input.prompt())))) + case "hook": + throw input.issue( + ["event"], .unverified, + "captured Cursor hook notes do not fix the exact event vocabulary and command runner contract" + ) + case "ignore": + _ = try input.checkedNative([:]) + return try input.emitted( + lowering, + input.envelope( + route: .cursorIgnore, + selection: "managedIgnore", + value: LedgerPayload.strings(try NativeIgnoreLayoutV1.patterns(input)))) + default: + throw input.issue(["kind"], .invalid, "component does not match this concrete native profile") + } + } +} diff --git a/Sources/Components/Adapters/GeminiComponents.swift b/Sources/Components/Adapters/GeminiComponents.swift new file mode 100644 index 0000000..28393e8 --- /dev/null +++ b/Sources/Components/Adapters/GeminiComponents.swift @@ -0,0 +1,117 @@ +import AgentsCore + +extension GeminiAdapter { + static func components(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + switch input.record.kind { + case "command": + _ = try input.checkedNative([:]) + try input.noParameters() + let name = try input.relativeName() + let description = try input.quoted(input.text("description")) + let prompt = try input.quoted(input.prompt()) + let file = try input.joined(["description = " + description, "prompt = " + prompt, ""]) + return try input.emitted( + lowering, + input.envelope( + route: .geminiCommand, + path: name + ".toml", selection: "file", value: .init(file))) + case "subagent": + let native = try input.checkedNative([ + "max_turns": .positiveInteger, "timeout_mins": .positiveInteger, + ]) + let name = try input.filename() + guard name.range(of: #"^[a-z0-9_-]+$"#, options: .regularExpression) != nil else { + throw input.issue(["name"], .invalid, "Gemini agent names must be lowercase slugs") + } + let body = try input.prompt() + guard NativeComponentText.isUntrimmed(body, rust: false) else { + throw input.issue( + ["prompt"], .unsupported, "the native agent loader trims the system prompt") + } + var fields = native + fields["name"] = .init(name) + let description = try input.text("description") + guard !description.isEmpty else { + throw input.issue(["description"], .invalid, "native agent description must not be empty") + } + fields["description"] = .init(description) + fields["model"] = input.fields["model"] + if let tools = input.fields["tools"]?.array { + for (index, value) in tools.enumerated() { + guard let name = value.text, validAgentTool(name) else { + throw input.issue( + ["tools", String(index)], .invalid, "tool name is outside the pinned agent schema") + } + } + } + fields["tools"] = input.fields["tools"] + let file = try input.frontmatter(fields, body: body) + return try input.emitted( + lowering, + input.envelope( + route: .geminiAgent, + path: name + ".md", selection: "file", value: .init(file))) + case "hook": return try NativeHookLayoutV1.render(lowering, input) + case "ignore": + _ = try input.checkedNative([:]) + let patterns = try NativeIgnoreLayoutV1.patterns(input) + return try input.emitted( + lowering, + input.envelope( + route: .geminiIgnore, + selection: "managedIgnore", value: LedgerPayload.strings(patterns))) + default: + throw input.issue(["kind"], .invalid, "component does not match this concrete native profile") + } + } +} + +extension GeminiAdapter { + private static func validAgentTool(_ name: String) -> Bool { + let builtins: Set = [ + "activate_skill", + "ask_user", + "complete_task", + "enter_plan_mode", + "exit_plan_mode", + "get_internal_docs", + "glob", + "google_web_search", + "grep_search", + "invoke_agent", + "list_directory", + "list_mcp_resources", + "read_file", + "read_many_files", + "read_mcp_resource", + "replace", + "run_shell_command", + "tracker_add_dependency", + "tracker_create_task", + "tracker_get_task", + "tracker_list_tasks", + "tracker_update_task", + "tracker_visualize", + "update_topic", + "web_fetch", + "write_file", + "write_todos", + ] + if builtins.contains(name) || name == "search_file_content" + || name.hasPrefix("discovered_tool_") || name == "*" || name == "mcp_*" + { + return true + } + guard name.hasPrefix("mcp_"), !name.hasPrefix("mcp__") else { return false } + let parts = name.dropFirst(4).split( + separator: "_", maxSplits: 1, omittingEmptySubsequences: false) + guard parts.count == 2, !parts[0].isEmpty, !parts[1].isEmpty else { return false } + let slug = #"^[a-zA-Z0-9_.:-]+$"# + guard String(parts[0]).range(of: slug, options: .regularExpression) != nil else { return false } + if parts[1] == "*" { return true } + return !parts[1].allSatisfy({ $0 == "_" }) + && String(parts[1]).range(of: slug, options: .regularExpression) != nil + } +} diff --git a/Sources/Components/Adapters/OpenCodeComponents.swift b/Sources/Components/Adapters/OpenCodeComponents.swift new file mode 100644 index 0000000..bd2c5a5 --- /dev/null +++ b/Sources/Components/Adapters/OpenCodeComponents.swift @@ -0,0 +1,74 @@ +import AgentsCore +import Foundation + +extension OpenCodeAdapter { + static func components(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + switch input.record.kind { + case "command": + try input.noParameters() + var fields = try input.checkedNative(["agent": .string, "subagent": .boolean]) + fields["description"] = .init(try input.text("description")) + fields["template"] = .init(try input.prompt()) + return try input.emitted( + lowering, + input.envelope( + route: .openCodeConfig, + keys: ["commands", input.record.name], value: .init(object: fields))) + case "subagent": + guard input.fields["tools"] == nil else { + throw input.issue( + ["tools"], .unsupported, + "OpenCode agent schema has permissions rather than a tool allowlist") + } + var fields = try input.checkedNative(["hidden": .boolean, "disabled": .boolean]) + fields["system"] = .init(try input.prompt()) + fields["description"] = .init(try input.text("description")) + fields["mode"] = .init("subagent") + if let model = input.fields["model"]?.text { + guard model.range(of: #"^[^/#]+/[^#]+(?:#[^#]+)?$"#, options: .regularExpression) != nil + else { + throw input.issue( + ["model"], .invalid, "native model selection requires provider/model syntax") + } + try input.literal(model, field: ["model"]) + fields["model"] = .init(model) + } + return try input.emitted( + lowering, + input.envelope( + route: .openCodeConfig, + keys: ["agents", input.record.name], value: .init(object: fields))) + case "permissions": + _ = try input.checkedNative([:]) + let rules = try (input.fields["rules"]?.array ?? []).enumerated().map { + index, rule -> LedgerValue in + guard let fields = rule.object, let action = fields["action"]?.text, + let operation = fields["operation"], let pattern = fields["pattern"]?.text + else { + throw input.issue(["rules", String(index)], .invalid, "invalid frozen permission rule") + } + guard let name = operation.object?["tool"]?.text else { + throw input.issue( + ["rules", String(index), "operation"], .unverified, + "portable read/write/execute resource namespaces are not proved equivalent to native tool actions" + ) + } + try input.literal(name, field: ["rules", String(index), "operation"]) + try input.literal(pattern, field: ["rules", String(index), "pattern"]) + return .init(object: [ + "action": .init(name), "resource": .init(pattern), "effect": .init(action), + ]) + } + return try input.emitted( + lowering, + input.envelope( + route: .openCodeConfig, + keys: ["permissions"], selection: "orderedAppend", value: .init(array: rules))) + case "lspServer": return try NativeLSPLayoutV1.openCode(lowering, input) + default: + throw input.issue(["kind"], .invalid, "component does not match this concrete native profile") + } + } +} diff --git a/Sources/Components/CapabilityRegistry.swift b/Sources/Components/CapabilityRegistry.swift index bd8f379..80f1361 100644 --- a/Sources/Components/CapabilityRegistry.swift +++ b/Sources/Components/CapabilityRegistry.swift @@ -138,3 +138,122 @@ package enum CapabilityRegistry { evidence: evidence) } } + +package struct NativeComponentDescriptor { + package let request: NativeComponentRequest + package let kind: DeclaredComponentKind + package let format: String + package let evidence: NativeSchemaEvidence + package var knownReaders: Set { [request.surface.agent] } +} + +extension CapabilityRegistry { + package static func component( + _ request: NativeComponentRequest, + kind: DeclaredComponentKind, name: String + ) throws -> NativeComponentDescriptor { + func issue(_ field: String, _ reason: NativeAdapterIssue.Reason, _ detail: String) + -> NativeComponentIssue + { + .init( + request: request, kind: kind.rawValue, component: name, field: [field], reason: reason, + detail: detail) + } + guard ![.skills, .instructions, .mcpServer].contains(kind) else { + throw issue("kind", .invalid, "component belongs to its existing domain renderer") + } + guard request.surface != .cursorCloud else { + throw issue( + "surface", .unverified, "Cloud deployment/loading requires a separate registered surface") + } + if request.surface == .claudeCode && kind != .plugin { + throw issue( + "kind", .unverified, + "captured Claude evidence lacks this component's complete fixed native schema") + } + if kind == .command { + if request.surface == .codexCLI { + throw issue( + "kind", .unsupported, + "the pinned TUI dispatch does not register persistent named prompt files") + } + if request.surface == .cursorCLI + || (request.surface == .cursorEditor && request.scope == .user) + { + throw issue( + "scope", .unverified, + "named-command registration is not established for this surface/scope") + } + } + if kind == .lspServer && request.surface != .openCodeCLI { + throw issue( + "kind", .unverified, "no complete LSP registration schema is captured for this surface") + } + if kind == .ignore { + guard request.scope == .project else { + throw issue("scope", .unverified, "no standalone user ignore file contract is established") + } + guard request.surface == .geminiCLI || request.surface == .cursorEditor else { + throw issue( + "purpose", .unverified, + "file search/watcher filters do not establish context or indexing exclusion") + } + } + if kind == .hook && request.surface == .openCodeCLI { + throw issue( + "event", .unverified, + "OpenCode hooks require executable plugin API adaptation; equivalent event I/O is not established" + ) + } + if kind == .permissions && request.surface != .openCodeCLI { + throw issue( + "rules", .unverified, + "native policy precedence differs from ordered last-match semantics; exact translation is not established" + ) + } + let pinned = try mcp( + .init( + surface: request.surface, + scope: request.scope == .user ? .user : .project), component: name + ).evidence + let sources: [String] + switch request.surface { + case .geminiCLI: + sources = [ + "docs/cli/custom-commands.md", "packages/core/src/agents/agentLoader.ts", + "docs/hooks/reference.md", "packages/core/src/hooks/hookRunner.ts", + "packages/cli/src/config/settings.ts", "packages/cli/src/utils/envVarResolver.ts", + "docs/cli/gemini-ignore.md", "packages/cli/src/config/extension-manager.ts", + ] + case .openCodeCLI: + sources = [ + "packages/schema/src/config/command.ts", "packages/schema/src/config/agent.ts", + "packages/core/src/config/plugin/command.ts", "packages/schema/src/permission.ts", + "packages/core/src/permission.ts", "packages/schema/src/config/lsp.ts", + ] + case .codexCLI: + sources = [ + "codex-rs/config/src/config_toml.rs", "codex-rs/agent-roles/src/agent_role_config.rs", + "codex-rs/agent-roles/src/loader.rs", "codex-rs/config/src/hook_config.rs", + "codex-rs/hooks/src/engine/command_runner.rs", + ] + case .cursorEditor, .cursorCLI, .cursorCloud: + sources = [ + "https://cursor.com/docs/subagents", "https://docs.cursor.com/en/agent/chat/commands", + "https://cursor.com/docs/reference/ignore-file", + "https://cursor.com/docs/reference/plugins", + ] + case .claudeCode: sources = ["claude-plugin-discovery.json", "route-evidence.md"] + } + let revision: String + switch request.surface { + case .cursorEditor, .cursorCLI, .cursorCloud: + revision = "sha256:b5e03f48d099bce7b10892b57934b9b611a54b3d4c9cf64e309071760e1c163b" + default: revision = pinned.revision + } + let evidence = NativeSchemaEvidence(revision: revision, sources: sources) + return .init( + request: request, kind: kind, format: NativeComponentLayoutsV1.format(request.surface), + evidence: evidence) + } +} diff --git a/Sources/Components/FrozenNativeIdentity.swift b/Sources/Components/FrozenNativeIdentity.swift new file mode 100644 index 0000000..63a695e --- /dev/null +++ b/Sources/Components/FrozenNativeIdentity.swift @@ -0,0 +1,71 @@ +import AgentsCore + +/// Uses C's exact ephemeral pairing, never equal bytes or graph-local occurrence numbers alone. +enum FrozenNativeIdentity { + static func match( + _ linked: LinkedComponent, frozen: LedgerFreeze.Result, + agent: AgentID, scope: InstallScope + ) throws -> (id: String, occurrences: [Int]) { + let ledger = frozen.ledger + let sourceIDs = frozen.sources + func invalid(_ detail: String) -> CoreError { .invalidState(detail) } + guard linked.recipients.contains(agent), case .declaration(let declaration) = linked.payload, + let name = declaration.name + else { throw invalid("the linked component does not target this recipient") } + let ids = Set(linked.origins.map(\.occurrence)) + let occurrences = ledger.occurrences.filter { ids.contains($0.id) } + let owners = Set(occurrences.map(\.component)) + guard !ids.isEmpty, occurrences.count == ids.count, owners.count == 1, + let id = owners.first, let record = ledger.components[id], + record.kind == linked.key.kind.rawValue, record.kind == declaration.kind.rawValue, + record.name == name, + record.chatGPT == linked.chatGPT, + record.declaringSource == sourceIDs[linked.declaringSnapshot], + record.source == sourceIDs[linked.snapshot], linked.key.source == linked.snapshot.source, + record.revision == linked.pin?.revision, record.version == linked.pin?.version, + record.root == linked.key.root, record.group == linked.key.group, + record.payload == (try LedgerPayload.component(declaration)), + record.conditions == linked.conditions.map(LedgerCondition.init), + Set(record.recipients) == linked.recipients, + record.resources.count == linked.resources.count + else { throw invalid("linked component and frozen occurrence graph do not match") } + for (origin, frozen) in zip(linked.origins, occurrences) { + guard origin.occurrence == frozen.id, origin.reference == frozen.reference, + frozen.declaringSource == record.declaringSource, + origin.provenance.sourceIdentity == linked.declaringSnapshot.source, + origin.dependencies.compactMap({ sourceIDs[$0] }) == frozen.dependencies, + origin.dependencies.allSatisfy({ sourceIDs[$0] != nil }), + LedgerCondition(origin.condition) == frozen.condition, + origin.provenance.relativePath == frozen.manifestPath, + Set(origin.recipients) == Set(frozen.recipients), + origin.consumerEditable == frozen.consumerEditable + else { throw invalid("linked origin and frozen occurrence do not match") } + } + for (resource, frozen) in zip(linked.resources, record.resources) { + guard let item = ledger.resources[frozen], item.path == resource.path, + item.source == sourceIDs[resource.snapshot], item.artifact == resource.artifact, + item.hash == resource.hash + else { throw invalid("linked resource and frozen evidence do not match") } + let flags: [String: Bool] + if item.entries.count == 1, item.entries[0].kind == .file, item.entries[0].path == "." { + flags = [resource.path: item.entries[0].executable] + } else { + flags = Dictionary( + uniqueKeysWithValues: item.entries.filter { $0.kind == .file }.map { + ($0.path, $0.executable) + }) + } + guard resource.executableFlags.isEmpty || resource.executableFlags == flags else { + throw invalid("linked executable flags and frozen resource do not match") + } + } + let selected = occurrences.filter { + $0.recipients.contains(agent) && ($0.condition.scopes?.contains(scope) ?? true) + && ($0.condition.agents?.contains(agent) ?? true) + } + guard !selected.isEmpty else { + throw invalid("component has no active frozen occurrence for this recipient/scope") + } + return (id, selected.map(\.id)) + } +} diff --git a/Sources/Components/MCPLowering.swift b/Sources/Components/MCPLowering.swift index 15b70ba..05f1e85 100644 --- a/Sources/Components/MCPLowering.swift +++ b/Sources/Components/MCPLowering.swift @@ -104,54 +104,25 @@ package enum NativeMCPLowering { _ linked: LinkedComponent, frozen: LedgerFreeze.Result, request: NativeMCPRequest ) throws -> NativeMCPContribution { let ledger = frozen.ledger - let sourceIDs = frozen.sources let descriptor = try CapabilityRegistry.mcp(request, component: linked.key.name) func invalid(_ detail: String) -> NativeAdapterIssue { .init( request: request, component: linked.key.name, field: ["component"], reason: .invalid, detail: detail) } - guard linked.recipients.contains(request.surface.agent), - case .declaration(let declaration) = linked.payload, + guard case .declaration(let declaration) = linked.payload, case .mcpServer(let name, let transport, _, _, let native) = declaration - else { throw invalid("the linked component does not target this MCP recipient") } - let ids = Set(linked.origins.map(\.occurrence)) - let occurrences = ledger.occurrences.filter { ids.contains($0.id) } - let owners = Set(occurrences.map(\.component)) - guard !ids.isEmpty, occurrences.count == ids.count, owners.count == 1, - let id = owners.first, let record = ledger.components[id], - record.kind == DeclaredComponentKind.mcpServer.rawValue, record.name == name, - record.declaringSource == sourceIDs[linked.declaringSnapshot], - record.source == sourceIDs[linked.snapshot], linked.key.source == linked.snapshot.source, - record.revision == linked.pin?.revision, record.version == linked.pin?.version, - record.root == linked.key.root, record.group == linked.key.group, - record.payload == (try LedgerPayload.component(declaration)), - record.conditions == linked.conditions.map(LedgerCondition.init), - Set(record.recipients) == linked.recipients, - record.resources.count == linked.resources.count - else { throw invalid("linked component and frozen occurrence graph do not match") } - for (origin, frozen) in zip(linked.origins, occurrences) { - let audience: InstallScope = request.scope == .user ? .user : .project - guard origin.occurrence == frozen.id, origin.reference == frozen.reference, - frozen.declaringSource == record.declaringSource, - origin.provenance.sourceIdentity == linked.declaringSnapshot.source, - origin.dependencies.compactMap({ sourceIDs[$0] }) == frozen.dependencies, - origin.dependencies.allSatisfy({ sourceIDs[$0] != nil }), - LedgerCondition(origin.condition) == frozen.condition, - origin.condition.scopes?.contains(audience) ?? true, - origin.condition.agents?.contains(request.surface.agent) ?? true, - origin.provenance.relativePath == frozen.manifestPath, - origin.recipients.contains(request.surface.agent), - Set(origin.recipients) == Set(frozen.recipients), - origin.consumerEditable == frozen.consumerEditable - else { throw invalid("linked origin and frozen occurrence do not match") } - } - for (resource, frozen) in zip(linked.resources, record.resources) { - guard let item = ledger.resources[frozen], item.path == resource.path, - item.source == sourceIDs[resource.snapshot], item.artifact == resource.artifact, - item.hash == resource.hash - else { throw invalid("linked resource and frozen evidence do not match") } + else { + throw invalid("the linked component is not an MCP server") } + let identity: (id: String, occurrences: [Int]) + do { + identity = try FrozenNativeIdentity.match( + linked, frozen: frozen, + agent: request.surface.agent, scope: request.scope == .user ? .user : .project) + } catch { throw invalid("linked component and frozen source identity do not match") } + let id = identity.id + let record = ledger.components[id]! let input = MCPInput( descriptor: descriptor, name: name, transport: transport, native: native[request.surface.agent.rawValue] ?? [:], resources: record.resources) @@ -164,7 +135,7 @@ package enum NativeMCPLowering { case .cursorEditor, .cursorCLI, .cursorCloud: entry = try CursorAdapter.mcp(input) } return .init( - descriptor: descriptor, component: id, name: name, occurrences: occurrences.map(\.id), + descriptor: descriptor, component: id, name: name, occurrences: identity.occurrences, recipients: [request.surface.agent], bindings: entry.placements, resourcePlacements: entry.resourcePlacements, value: .init(object: entry.fields), resources: record.resources) @@ -199,9 +170,23 @@ struct MCPInput { } func literal(_ value: String, field: [String]) throws { - guard !value.contains("\0") else { throw issue(field, .invalid, "NUL is not a native string") } + try descriptor.validateLiteral(value, component: name, field: field) + } +} + +extension NativeMCPDescriptor { + func validateLiteral(_ value: String, component: String, field: [String]) throws { + func issue(_ reason: NativeAdapterIssue.Reason, _ detail: String) -> NativeAdapterIssue { + .init(request: request, component: component, field: field, reason: reason, detail: detail) + } + guard !value.contains("\0") else { throw issue(.invalid, "NUL is not a native string") } + if let first = field.first, ["headers", "http_headers"].contains(first), + value.utf8.contains(13) || value.utf8.contains(10) + { + throw issue(.invalid, "native header value contains a line break") + } let interpolates: Bool - switch descriptor.request.surface { + switch request.surface { case .claudeCode: interpolates = value.contains("${") case .geminiCLI: interpolates = value.range(of: #"\$(?:\w|\{)"#, options: .regularExpression) != nil @@ -211,7 +196,7 @@ struct MCPInput { } guard !interpolates else { throw issue( - field, .unverified, "literal preservation across native interpolation needs evidence") + .unverified, "literal preservation across native interpolation needs evidence") } } } @@ -236,7 +221,8 @@ enum MCPReferenceSyntax { } enum MCPNativeField { - case boolean, falseOnly, string, strings, positiveNumber, durationSeconds, environmentName + case boolean, falseOnly, string, strings, positiveNumber, positiveInteger, durationSeconds, + environmentName case oneOf(Set) case positiveIntegerObject(Set) @@ -252,6 +238,9 @@ enum MCPNativeField { // Rust Duration uses u64 seconds. The f64 immediately below 2^64 is 2048 seconds // smaller, so fractional nanosecond rounding cannot overflow an accepted f64. Double(number).map { $0 >= 0 && $0 < 0x1p64 } ?? false + case (.positiveInteger, .integer(let number)): number > 0 && Double(exactly: number) != nil + case (.positiveInteger, .decimal(let text)): + Double(text).map { $0.isFinite && $0 > 0 && $0.rounded(.towardZero) == $0 } ?? false case (.positiveNumber, .integer(let number)): number > 0 case (.positiveNumber, .decimal(let number)): Double(number).map { $0.isFinite && $0 > 0 } ?? false diff --git a/Sources/Components/MCPStagedValues.swift b/Sources/Components/MCPStagedValues.swift new file mode 100644 index 0000000..a2a1133 --- /dev/null +++ b/Sources/Components/MCPStagedValues.swift @@ -0,0 +1,89 @@ +import AgentsCore +import Foundation +import NativeDocuments + +extension NativeMCPContribution { + /// Call only in E/D's private render closure. The caller admits final registered resource + /// paths and supplies its immutable environment snapshot; this method never invokes a provider. + /// The returned value is ephemeral and must not enter a lowering, ledger or public report. + package func stagedValue( + bindings supplied: RuntimeBindingValues, environment: RuntimeEnvironment, + resourcePaths: [String: String], budget: NativeDocumentBudget + ) throws -> NativeValue { + func failure(_ path: [MCPValueStep], _ detail: String) -> NativeAdapterIssue { + .init( + request: descriptor.request, component: name, field: path.fields, + reason: .invalid, detail: detail) + } + func literal(_ text: String, at path: [MCPValueStep]) throws -> NativeValue { + try budget.allocate(text.utf8.count, stage: "staged native string") + try budget.step(text.utf8.count) + try descriptor.validateLiteral(text, component: name, field: path.fields) + if case .key(let field) = path.first, + ["headers", "http_headers"].contains(field), + text.utf8.contains(13) || text.utf8.contains(10) + { + throw failure(path, "native header value contains a line break") + } + return .string(text) + } + func convert(_ value: LedgerValue, path: [MCPValueStep], depth: Int) throws -> NativeValue { + try budget.node(depth: depth) + try budget.step(bindings.count + resourcePlacements.count + 1) + if let placement = bindings.first(where: { $0.path == path }), !placement.reference { + let text: String + switch placement.binding { + case .environment(let variable): + guard let found = environment.environment[variable] else { + throw failure(path, "required native environment value is unavailable") + } + text = found + case .secret(let binding): + let bytes: Data + do { bytes = try supplied.value(for: binding) } catch { + throw failure(path, "required native binding is unavailable") + } + try budget.allocate(bytes.count, stage: "staged native UTF8") + try budget.step(bytes.count) + guard let decoded = String(data: bytes, encoding: .utf8) else { + throw failure(path, "native binding is not UTF8") + } + text = decoded + case .literal(let found): text = found + } + return try literal(text, at: path) + } + if let placement = resourcePlacements.first(where: { $0.path == path }) { + guard let final = resourcePaths[placement.resource], !final.isEmpty else { + throw failure(path, "final registered resource placement is required") + } + return try literal(final, at: path) + } + switch value.kind { + case .string, .literal: + try budget.allocate(value.text!.utf8.count, stage: "native string") + return .string(value.text!) + case .integer: return .integer(value.integer!) + case .decimal: return .decimal(value.text!) + case .boolean: return .boolean(value.boolean!) + case .null: return .null + case .array: + try budget.allocate(value.array!.count, stage: "native array") + return .array( + try value.array!.enumerated().map { index, value in + try convert(value, path: path + [.index(index)], depth: depth + 1) + }) + case .object: + var fields: [String: NativeValue] = [:] + for (key, value) in value.object!.sorted(by: { $0.key < $1.key }) { + try budget.allocate(key.utf8.count, stage: "native key") + fields[key] = try convert(value, path: path + [.key(key)], depth: depth + 1) + } + return .object(fields) + case .environment, .secret: + throw failure(path, "native symbolic slot has no binding placement") + } + } + return try convert(value, path: [], depth: 0) + } +} diff --git a/Sources/Components/NativeComponentLayoutsV1.swift b/Sources/Components/NativeComponentLayoutsV1.swift new file mode 100644 index 0000000..409414f --- /dev/null +++ b/Sources/Components/NativeComponentLayoutsV1.swift @@ -0,0 +1,75 @@ +import AgentsCore +import Foundation + +package enum NativeComponentLayoutsV1 { + package static func format(_ surface: NativeClientSurface) -> String { + switch surface { + case .claudeCode: "agents/claude-components@1" + case .codexCLI: "agents/codex-components@1" + case .geminiCLI: "agents/gemini-components@1" + case .openCodeCLI: "agents/opencode-components@1" + case .cursorEditor, .cursorCLI, .cursorCloud: "agents/cursor-components@1" + } + } + + package static func renderers(limits: LedgerLimits) -> [String: LedgerRenderer] { + [ + "agents/claude-components@1": { + try render($0, $1, $2, limits: limits, surface: .claudeCode) + }, + "agents/codex-components@1": { try render($0, $1, $2, limits: limits, surface: .codexCLI) }, + "agents/gemini-components@1": { try render($0, $1, $2, limits: limits, surface: .geminiCLI) }, + "agents/opencode-components@1": { + try render($0, $1, $2, limits: limits, surface: .openCodeCLI) + }, + "agents/cursor-components@1": { + try render($0, $1, $2, limits: limits, surface: .cursorEditor) + }, + ] + } + + private static func render( + _ lowering: LockedLowering, _ ledger: ResolvedLedger, + _ resources: [String: URL], limits: LedgerLimits, surface: NativeClientSurface + ) throws -> [ReplayedArtifact] { + func invalid() -> CoreError { .invalidState("invalid version 1 native component layout") } + guard let layout = lowering.layout.object, + Set(layout.keys) == ["surface", "scope", "occurrences"], + let declared = layout["surface"]?.text.flatMap(NativeClientSurface.init(rawValue:)), + format(declared) == format(surface), + let scope = layout["scope"]?.text.flatMap(InstallScope.init(rawValue:)), + lowering.format == format(declared), lowering.inputs.count == 1, + let component = lowering.inputs.first, let record = ledger.components[component], + lowering.resources == record.resources, + record.resources.allSatisfy({ resources[$0] != nil }), + let items = layout["occurrences"]?.array, + items.allSatisfy({ $0.kind == .integer }), !items.isEmpty + else { throw invalid() } + let occurrences = items.compactMap(\.integer) + guard Set(occurrences).count == occurrences.count, + occurrences + == ledger.occurrences.filter({ $0.component == component && occurrences.contains($0.id) }) + .map(\.id), + ledger.occurrences.filter({ occurrences.contains($0.id) }).allSatisfy({ + $0.recipients.contains(declared.agent) && ($0.condition.scopes?.contains(scope) ?? true) + && ($0.condition.agents?.contains(declared.agent) ?? true) + && ($0.condition.platforms?.contains(lowering.platform) ?? true) + }) + else { throw invalid() } + let input = ComponentRenderInput( + record: record, component: component, + request: .init(surface: declared, scope: scope), occurrences: occurrences, + resources: resources, ledger: ledger, limits: limits) + try input.validateProfile() + if record.kind == "plugin" { return try NativePluginLayoutV1.render(lowering, input) } + switch declared { + case .geminiCLI: return try GeminiAdapter.components(lowering, input) + case .openCodeCLI: return try OpenCodeAdapter.components(lowering, input) + case .codexCLI: return try CodexAdapter.components(lowering, input) + case .cursorEditor, .cursorCLI, .cursorCloud: + return try CursorAdapter.components(lowering, input) + case .claudeCode: + throw input.issue(["kind"], .unverified, "complete fixed native schema is required") + } + } +} diff --git a/Sources/Components/NativeComponentLowering.swift b/Sources/Components/NativeComponentLowering.swift new file mode 100644 index 0000000..06ac99f --- /dev/null +++ b/Sources/Components/NativeComponentLowering.swift @@ -0,0 +1,400 @@ +import AgentsCore +import Foundation +import NativeDocuments + +package struct NativeComponentRequest: Equatable { + package let surface: NativeClientSurface + package let scope: InstallScope + package init(surface: NativeClientSurface, scope: InstallScope) { + self.surface = surface + self.scope = scope + } +} + +package struct NativeComponentIssue: Error, CustomStringConvertible { + package let request: NativeComponentRequest + package let kind: String + package let component: String + package let field: [String] + package let reason: NativeAdapterIssue.Reason + package let detail: String + package var description: String { + "\(request.surface.rawValue)/\(kind)/\(component)/\(request.scope.rawValue) " + + "\(field.joined(separator: ".")): \(reason.rawValue) (\(detail))." + } +} + +/// Closed recipes are resolved/admitted by Core/E. A source cannot supply a native path. +package enum NativeComponentRoute: String { + case geminiCommand, geminiAgent, geminiSettings, geminiIgnore + case openCodeConfig, codexConfig, codexAgent, codexHooks + case cursorCommand, cursorAgent, cursorIgnore + case claudeSkillPlugin, cursorLocalPlugin, geminiExtension +} + +package enum NativeComponentLowering { + package static func lower( + _ linked: LinkedComponent, frozen: LedgerFreeze.Result, + request: NativeComponentRequest, id: String, platform: DeclarationPlatform + ) throws -> LockedLowering { + let owner: (id: String, occurrences: [Int]) + do { + owner = try FrozenNativeIdentity.match( + linked, frozen: frozen, + agent: request.surface.agent, scope: request.scope) + } catch { + throw NativeComponentIssue( + request: request, kind: linked.key.kind.rawValue, + component: linked.key.name, field: ["component"], reason: .invalid, + detail: "linked component and frozen source identity do not match") + } + let selected = Set(owner.occurrences) + guard + frozen.ledger.occurrences.filter({ selected.contains($0.id) }).allSatisfy({ + $0.condition.platforms?.contains(platform.rawValue) ?? true + }) + else { + throw NativeComponentIssue( + request: request, kind: linked.key.kind.rawValue, + component: linked.key.name, field: ["platform"], reason: .invalid, + detail: "frozen occurrence does not target the requested output platform") + } + let format = NativeComponentLayoutsV1.format(request.surface) + let record = frozen.ledger.components[owner.id]! + let input = ComponentRenderInput( + record: record, component: owner.id, request: request, + occurrences: owner.occurrences, resources: [:], ledger: frozen.ledger, limits: .standard) + try input.validateProfile() + return .init( + id: id, format: format, inputs: [owner.id], resources: record.resources, deployments: [], + layout: .init(object: [ + "surface": .init(request.surface.rawValue), + "scope": .init(request.scope.rawValue), + "occurrences": .init(array: owner.occurrences.map { .init(integer: $0) }), + ]), + platform: platform.rawValue, artifacts: []) + } +} + +/// A concrete profile emits its native file contents or regional values plus route/ownership +/// metadata. E alone groups these contributions into physical documents and transactions. +struct ComponentRenderInput { + let record: LedgerComponent + let component: String + let request: NativeComponentRequest + let occurrences: [Int] + let resources: [String: URL] + let ledger: ResolvedLedger + let limits: LedgerLimits + let budget: NativeDocumentBudget + init( + record: LedgerComponent, component: String, request: NativeComponentRequest, + occurrences: [Int], resources: [String: URL], ledger: ResolvedLedger, limits: LedgerLimits + ) { + self.record = record + self.component = component + self.request = request + self.occurrences = occurrences + self.resources = resources + self.ledger = ledger + self.limits = limits + budget = .init( + limits: .init( + storage: limits.encodedBytes, work: limits.encodedBytes, + nodes: limits.nodes, depth: limits.depth, uninterruptedBytes: limits.resourceBytes)) + } + var fields: [String: LedgerValue] { record.payload.object! } + var native: [String: LedgerValue] { + fields["native"]?.object?[request.surface.agent.rawValue]?.object ?? [:] + } + + func issue(_ field: [String], _ reason: NativeAdapterIssue.Reason, _ detail: String) + -> NativeComponentIssue + { + .init( + request: request, kind: record.kind, component: record.name, field: field, + reason: reason, detail: detail) + } + + func validateProfile() throws { + func admit(_ value: LedgerValue, depth: Int) throws { + try budget.node(depth: depth) + if let text = value.text { + try budget.allocate(text.utf8.count, stage: "native input string") + try budget.step(text.utf8.count) + } + for item in value.array ?? [] { try admit(item, depth: depth + 1) } + for (key, item) in value.object ?? [:] { + try budget.allocate(key.utf8.count, stage: "native input key") + try budget.step(key.utf8.count) + try admit(item, depth: depth + 1) + } + } + try admit(record.payload, depth: 0) + guard record.recipients.contains(request.surface.agent) else { + throw issue(["recipients"], .invalid, "component does not target this recipient") + } + try literal(record.name, field: ["name"]) + for key in ["model", "tools", "matcher"] { + if let value = fields[key] { + try NativeProgramV1.validateLiterals(value, input: self, path: [key]) + } + } + guard let kind = DeclaredComponentKind(rawValue: record.kind) else { + throw issue(["kind"], .invalid, "invalid frozen component kind") + } + _ = try CapabilityRegistry.component(request, kind: kind, name: record.name) + if kind == .ignore, fields["purpose"]?.text != "context" { + throw issue( + ["purpose"], .unverified, "a distinct current indexing-only contract is not established") + } + } + + func checkedNative(_ rules: [String: MCPNativeField]) throws -> [String: LedgerValue] { + for (key, value) in native.sorted(by: { $0.key < $1.key }) { + guard let rule = rules[key] else { + throw issue( + ["native", request.surface.agent.rawValue, key], .unverified, + "no verified field mapping in this native schema") + } + try NativeProgramV1.validateLiterals( + value, input: self, path: ["native", request.surface.agent.rawValue, key]) + guard rule.accepts(try nativeValue(value)) else { + throw issue( + ["native", request.surface.agent.rawValue, key], .invalid, + "value is outside the verified native field profile") + } + } + return native + } + + func text(_ key: String) throws -> String { + guard let value = fields[key]?.text else { + throw issue([key], .invalid, "required frozen string is missing") + } + try literal(value, field: [key]) + return value + } + + func literal(_ value: String, field: [String], prompt: Bool = false) throws { + guard !value.utf8.contains(0) else { + throw issue(field, .invalid, "NUL is not a native string") + } + if prompt && value.contains("$${input:") { + throw issue( + field, .unverified, "literal input-token escaping needs a verified native representation") + } + let interpolation: Bool + switch request.surface { + case .openCodeCLI: + interpolation = + value.contains("{env:") || value.contains("{file:") + || (prompt + && (value.range(of: #"\$(?:ARGUMENTS|[1-9])|!`"#, options: .regularExpression) != nil)) + case .geminiCLI: + interpolation = + (record.kind == "hook" + && value.range( + of: #"\$(?:[A-Za-z0-9_]+|\{[^}]+?(?::-[^}]*)?\})"#, options: .regularExpression) != nil) + || (prompt && (value.contains("{{args}}") || value.contains("!{") || value.contains("@{"))) + default: interpolation = false + } + guard !interpolation else { + throw issue( + field, .unverified, "exact literal preservation across native interpolation needs evidence") + } + if prompt && request.surface == .openCodeCLI, + !NativeComponentText.isUntrimmed(value, rust: false) + { + throw issue( + field, .unsupported, "the native template evaluator trims leading and trailing whitespace") + } + } + + func prompt() throws -> String { + guard let prompt = fields["prompt"] else { + throw issue(["prompt"], .invalid, "missing frozen prompt") + } + let value: String + if prompt.kind == .literal { + value = prompt.text! + } else { + guard let id = record.resources.first, let resource = ledger.resources[id], + resource.path == prompt.object?["file"]?.object?["path"]?.text, + let url = resources[id], resource.entries.count == 1, + resource.entries[0].kind == .file, resource.entries[0].path == "." + else { throw issue(["prompt"], .invalid, "frozen prompt resource is not a single file") } + guard let size = resource.entries[0].byteCount, size <= limits.resourceBytes else { + throw issue(["prompt"], .invalid, "prompt resource exceeds output budget") + } + try budget.allocate(size, stage: "frozen prompt bytes") + try budget.allocate(size, stage: "frozen prompt UTF8") + try budget.step(size) + let bytes = try Data(contentsOf: url) + guard bytes.count == size, let decoded = String(data: bytes, encoding: .utf8) else { + throw issue(["prompt"], .invalid, "prompt resource is not exact UTF8") + } + value = decoded + } + guard value.utf8.count <= limits.resourceBytes else { + throw issue(["prompt"], .invalid, "prompt exceeds output budget") + } + try literal(value, field: ["prompt"], prompt: record.kind == "command") + return value + } + + func relativeName() throws -> String { + do { + let name = try PathSafety.sanitizeSubpath(record.name) + guard name == record.name, name != "." else { throw CoreError.invalidState("invalid name") } + return name + } catch { + throw issue(["name"], .invalid, "native filename requires an exact contained relative name") + } + } + + func filename() throws -> String { + let name = try relativeName() + guard !name.contains("/") else { + throw issue( + ["name"], .unverified, "nested file discovery is not established by this native profile") + } + return name + } + + func noParameters() throws { + guard fields["parameters"]?.array?.isEmpty ?? true else { + throw issue( + ["parameters"], .unsupported, + "native command schema does not represent named parameter descriptions/defaults") + } + } + + func nativeValue(_ value: LedgerValue) throws -> NativeValue { + switch value.kind { + case .string, .literal: return .string(value.text!) + case .integer: return .integer(value.integer!) + case .decimal: return .decimal(value.text!) + case .boolean: return .boolean(value.boolean!) + case .null: return .null + case .array: return .array(try value.array!.map(nativeValue)) + case .object: return .object(try value.object!.mapValues(nativeValue)) + case .environment, .secret: + throw issue( + ["value"], .integrationRequired, "native binding requires private staged conversion") + } + } + + func envelope( + route: NativeComponentRoute, path: String? = nil, + keys: [String] = [], selection: String = "key", value: LedgerValue + ) -> LedgerValue { + var result: [String: LedgerValue] = [ + "route": .init(route.rawValue), + "surface": .init(request.surface.rawValue), "scope": .init(request.scope.rawValue), + "kind": .init(record.kind), "name": .init(record.name), "component": .init(component), + "occurrences": .init(array: occurrences.map { .init(integer: $0) }), + "recipients": LedgerPayload.strings([request.surface.agent.rawValue]), + "knownReaders": LedgerPayload.strings([request.surface.agent.rawValue]), + "keys": LedgerPayload.strings(keys), "selection": .init(selection), "value": value, + ] + result["path"] = path.map { .init($0) } + return .init(object: result) + } + + func quoted(_ value: String) throws -> String { + guard limits.resourceBytes >= 2, value.utf8.count <= (limits.resourceBytes - 2) / 6 else { + throw issue(["output"], .invalid, "native string exceeds encoding budget") + } + try budget.allocate(value.utf8.count * 6 + 2, stage: "native scalar encoding") + try budget.step(value.utf8.count) + let encoder = JSONEncoder() + encoder.outputFormatting = [.withoutEscapingSlashes] + return String(decoding: try encoder.encode(value), as: UTF8.self) + .replacingOccurrences(of: "\u{0085}", with: "\\u0085") + .replacingOccurrences(of: "\u{2028}", with: "\\u2028") + .replacingOccurrences(of: "\u{2029}", with: "\\u2029") + } + + func joined(_ parts: [String], separator: String = "\n") throws -> String { + var size = 0 + for part in parts { + guard part.utf8.count <= limits.resourceBytes - size else { + throw issue(["output"], .invalid, "native file exceeds output budget") + } + size += part.utf8.count + } + for _ in parts.dropFirst() { + guard separator.utf8.count <= limits.resourceBytes - size else { + throw issue(["output"], .invalid, "native file exceeds output budget") + } + size += separator.utf8.count + } + try budget.allocate(size, stage: "native file") + try budget.step(size) + return parts.joined(separator: separator) + } + + func frontmatter(_ values: [String: LedgerValue], body: String) throws -> String { + var lines = ["---"] + for (key, value) in values.sorted(by: { $0.key < $1.key }) { + let text: String + if value.kind == .decimal, let decimal = value.text { + text = decimal + } else if let value = value.text { + text = try quoted(value) + } else if let values = value.array { + text = try joined(values.map { try quoted($0.text!) }, separator: ", ") + lines.append("\(key): [\(text)]") + continue + } else if let value = value.boolean { + text = value ? "true" : "false" + } else if let value = value.integer { + text = String(value) + } else { + throw issue(["native", key], .invalid, "unsupported frontmatter scalar") + } + lines.append("\(key): \(text)") + } + lines.append("---") + lines.append(body) + return try joined(lines) + } + + func emitted(_ lowering: LockedLowering, _ envelope: LedgerValue) throws -> [ReplayedArtifact] { + try envelope.validate() + func admit(_ value: LedgerValue, depth: Int) throws { + try budget.node(depth: depth) + if let text = value.text { + try budget.allocate(text.utf8.count, stage: "native output") + try budget.step(text.utf8.count) + } + for child in value.array ?? [] { try admit(child, depth: depth + 1) } + for (key, child) in value.object ?? [:] { + try budget.allocate(key.utf8.count, stage: "native output key") + try admit(child, depth: depth + 1) + } + } + try admit(envelope, depth: 0) + return [.init(name: lowering.id, kind: .ownedValues, values: envelope)] + } +} + +/// Source-pinned loaders use JavaScript trim or Rust str::trim, whose Unicode edge sets differ. +enum NativeComponentText { + static func whitespace(_ scalar: Unicode.Scalar, rust: Bool) -> Bool { + let value = scalar.value + return (9...13).contains(value) + || [0x20, 0xA0, 0x1680, 0x2028, 0x2029, 0x202F, 0x205F, 0x3000].contains(value) + || (0x2000...0x200A).contains(value) || (rust ? value == 0x85 : value == 0xFEFF) + } + static func isUntrimmed(_ value: String, rust: Bool) -> Bool { + guard let first = value.unicodeScalars.first, let last = value.unicodeScalars.last else { + return true + } + return !whitespace(first, rust: rust) && !whitespace(last, rust: rust) + } + static func isBlank(_ value: String, rust: Bool) -> Bool { + value.unicodeScalars.allSatisfy { whitespace($0, rust: rust) } + } +} diff --git a/Sources/Components/NativeHookLayoutV1.swift b/Sources/Components/NativeHookLayoutV1.swift new file mode 100644 index 0000000..ab3702d --- /dev/null +++ b/Sources/Components/NativeHookLayoutV1.swift @@ -0,0 +1,103 @@ +import AgentsCore + +enum NativeHookLayoutV1 { + static func render(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + let events: Set + let route: NativeComponentRoute + switch input.request.surface { + case .codexCLI: + events = [ + "PreToolUse", "PermissionRequest", "PostToolUse", "PreCompact", "PostCompact", + "SessionStart", "SessionEnd", "UserPromptSubmit", "SubagentStart", "SubagentStop", "Stop", + "Interrupt", + ] + route = .codexHooks + case .geminiCLI: + events = [ + "BeforeTool", "AfterTool", "BeforeAgent", "Notification", "AfterAgent", "SessionStart", + "SessionEnd", + "PreCompress", "BeforeModel", "AfterModel", "BeforeToolSelection", + ] + route = .geminiSettings + default: + throw input.issue( + ["event"], .unverified, "the native event/runner contract is not established") + } + guard let event = input.fields["event"]?.object?["native"]?.text else { + throw input.issue( + ["event"], .unverified, + "portable event payload/output equivalence is not established; select an explicit native event" + ) + } + guard events.contains(event) else { + throw input.issue( + ["event"], .unsupported, "event is absent from the pinned native event enum") + } + if input.request.surface == .codexCLI, let matcher = input.fields["matcher"]?.text { + guard !["UserPromptSubmit", "Stop", "Interrupt"].contains(event) else { + throw input.issue(["matcher"], .unsupported, "this native event ignores matchers") + } + guard + matcher.isEmpty || matcher == "*" + || matcher.utf8.allSatisfy({ + (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) || $0 == 95 + || $0 == 124 + }) + else { + throw input.issue( + ["matcher"], .unverified, + "exact Rust-regex syntax admission is required beyond the native literal/alternative matcher form" + ) + } + } + let native = try input.checkedNative( + input.request.surface == .geminiCLI ? ["sequential": .boolean] : [:]) + guard let run = input.fields["run"]?.object else { + throw input.issue(["run"], .invalid, "missing frozen hook program") + } + var program = run + program["executable"] = try NativeProgramV1.executable(run, input: input) + if run["workingDirectory"] != nil { + let index = run["executable"]?.text?.contains("/") == true ? 1 : 0 + guard input.record.resources.indices.contains(index) else { + throw input.issue(["run", "workingDirectory"], .invalid, "missing frozen hook directory") + } + program["workingDirectory"] = .init(object: ["resource": .init(input.record.resources[index])] + ) + } + try NativeProgramV1.validateLiterals(.init(object: program), input: input, path: ["run"]) + var hook: [String: LedgerValue] = [ + "type": .init("command"), "command": .init(object: ["program": .init(object: program)]), + ] + if let seconds = input.fields["timeoutSeconds"]?.integer { + let factor = input.request.surface == .geminiCLI ? 1000 : 1 + guard seconds > 0, seconds <= Int.max / factor else { + throw input.issue( + ["timeoutSeconds"], .invalid, "native timeout is outside its representable range") + } + if input.request.surface == .codexCLI, ["SessionEnd", "Interrupt"].contains(event), + seconds > 3 + { + throw input.issue( + ["timeoutSeconds"], .unsupported, + "the pinned native teardown hook clamps its timeout to three seconds") + } + if input.request.surface == .geminiCLI, seconds * factor > 2_147_483_647 { + throw input.issue( + ["timeoutSeconds"], .invalid, + "native Node timer milliseconds exceed its representable range") + } + hook["timeout"] = .init(integer: seconds * factor) + } + var group: [String: LedgerValue] = ["hooks": .init(array: [.init(object: hook)])] + group["matcher"] = input.fields["matcher"] + group["sequential"] = native["sequential"] + return try input.emitted( + lowering, + input.envelope( + route: route, + keys: ["hooks", event], selection: "hookGroup", value: .init(object: group))) + } +} diff --git a/Sources/Components/NativeIgnoreLayoutV1.swift b/Sources/Components/NativeIgnoreLayoutV1.swift new file mode 100644 index 0000000..d992cf7 --- /dev/null +++ b/Sources/Components/NativeIgnoreLayoutV1.swift @@ -0,0 +1,17 @@ +import AgentsCore + +/// Patterns form an ordered managed-block contribution for E's ignore preparation. +/// This renderer does not own a second ignore editor or infer ownership from matching lines. +enum NativeIgnoreLayoutV1 { + static func patterns(_ input: ComponentRenderInput) throws -> [String] { + try (input.fields["patterns"]?.array ?? []).enumerated().map { index, value in + guard let pattern = value.text, !pattern.isEmpty, + !pattern.utf8.contains(0), !pattern.utf8.contains(10), !pattern.utf8.contains(13) + else { + throw input.issue( + ["patterns", String(index)], .invalid, "ignore pattern must occupy one nonempty line") + } + return pattern + } + } +} diff --git a/Sources/Components/NativeLSPLayoutV1.swift b/Sources/Components/NativeLSPLayoutV1.swift new file mode 100644 index 0000000..f7b5360 --- /dev/null +++ b/Sources/Components/NativeLSPLayoutV1.swift @@ -0,0 +1,36 @@ +import AgentsCore + +enum NativeLSPLayoutV1 { + static func openCode(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + guard input.fields["languages"]?.object?.isEmpty ?? true else { + throw input.issue( + ["languages"], .unverified, + "native extensions do not encode extension-to-language IDs; runtime equivalence is not established" + ) + } + var fields = try input.checkedNative(["extensions": .strings, "disabled": .boolean]) + guard let run = input.fields["run"]?.object else { + throw input.issue(["run"], .invalid, "missing frozen LSP executable") + } + guard run["workingDirectory"] == nil else { + throw input.issue( + ["run", "workingDirectory"], .unsupported, + "the pinned LSP schema has no working-directory field") + } + fields["command"] = .init( + array: [try NativeProgramV1.executable(run, input: input)] + (run["arguments"]?.array ?? [])) + if let environment = run["environment"]?.object, !environment.isEmpty { + fields["env"] = .init(object: environment) + } + fields["initialization"] = input.fields["initializationOptions"] + // OpenCode performs raw JSON substitution on every string in the native document. + try NativeProgramV1.validateLiterals(.init(object: fields), input: input, path: []) + return try input.emitted( + lowering, + input.envelope( + route: .openCodeConfig, + keys: ["lsp", input.record.name], selection: "lsp", value: .init(object: fields))) + } +} diff --git a/Sources/Components/NativePluginLayoutV1.swift b/Sources/Components/NativePluginLayoutV1.swift new file mode 100644 index 0000000..117c322 --- /dev/null +++ b/Sources/Components/NativePluginLayoutV1.swift @@ -0,0 +1,116 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// Opaque native preservation is confined to a verified native container and one recipient. +/// Decomposition consumes G's typed children, not a second parser hidden in a renderer. +enum NativePluginLayoutV1 { + static func render(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + _ = try input.checkedNative([:]) + guard input.fields["mode"]?.text == "native" else { + throw input.issue( + ["mode"], .integrationRequired, + "decomposed plugins require G's typed child declarations linked/frozen with their source provenance" + ) + } + guard input.record.recipients == [input.request.surface.agent] else { + throw input.issue( + ["recipients"], .invalid, + "opaque native plugin preservation requires exactly one native recipient") + } + guard input.fields["select"] == nil, input.fields["exclude"]?.array?.isEmpty ?? true else { + throw input.issue( + ["select", "exclude"], .invalid, + "native container preservation cannot filter child components") + } + let route: NativeComponentRoute + let manifest: String + switch input.request.surface { + case .claudeCode: + route = .claudeSkillPlugin + manifest = ".claude-plugin/plugin.json" + case .geminiCLI where input.request.scope == .user: + route = .geminiExtension + manifest = "gemini-extension.json" + case .cursorEditor where input.request.scope == .user: + route = .cursorLocalPlugin + manifest = ".cursor-plugin/plugin.json" + default: + throw input.issue( + ["scope"], .unverified, + "native container registration/loading is not established for this surface/scope") + } + let name = try input.filename() + guard input.record.resources.count == 1, let id = input.record.resources.first, + let record = input.ledger.resources[id], let root = input.resources[id], + let entry = record.entries.first(where: { $0.path == manifest }), entry.kind == .file, + let size = entry.byteCount, size <= input.limits.resourceBytes + else { + throw input.issue( + ["path"], .invalid, "frozen native plugin requires its exact container manifest") + } + if input.request.surface == .geminiCLI, + record.entries.contains(where: { + [".gemini-extension-install.json", ".env"].contains($0.path) + }) + { + throw input.issue( + ["path"], .invalid, "runtime-local extension metadata/settings cannot be vendor resources") + } + try input.budget.allocate(size, stage: "native plugin manifest") + try input.budget.step(size) + let bytes = try Data(contentsOf: PathSafety.resolvedChild(base: root, subpath: manifest)) + let document = try NativeDocument(bytes: bytes, format: .json, budget: input.budget) + guard bytes.count == size, + case .object(let manifestFields) = try document.read(.init(keys: []))?.value + else { + throw input.issue(["path"], .invalid, "native plugin manifest is not an exact JSON object") + } + for (key, value) in manifestFields { + let metadata = + input.request.surface == .geminiCLI + ? ["name", "version"] : ["name", "version", "description"] + guard metadata.contains(key) else { + throw input.issue( + ["manifest", key], .unverified, + "this native manifest field's registration/path semantics are not captured by the fixed profile" + ) + } + guard case .string(let text) = value, !text.utf8.contains(0) else { + throw input.issue(["manifest", key], .invalid, "native metadata must be a string") + } + } + guard try document.read(.init(keys: ["name"]))?.value == .string(name) else { + throw input.issue( + ["name"], .invalid, "native manifest name does not match the frozen component") + } + if input.request.surface == .cursorEditor, case .string(let version) = manifestFields["version"] + { + do { + guard try SourceRequirement.exact(version).canonicalized() == .exact(version) else { + throw CoreError.invalidState("invalid native version") + } + } catch { + throw input.issue( + ["manifest", "version"], .invalid, "native plugin version must be canonical SemVer") + } + } + if input.request.surface == .geminiCLI { + guard name.range(of: #"^[a-zA-Z0-9-]+$"#, options: .regularExpression) != nil else { + throw input.issue( + ["name"], .invalid, "native extension name requires alphanumeric characters and hyphens") + } + guard case .string(let version) = manifestFields["version"], !version.isEmpty else { + throw input.issue( + ["manifest", "version"], .invalid, "native extension requires a version string") + } + } + let envelope = input.envelope( + route: route, path: name, selection: "nativePlugin", + value: .init(object: ["resource": .init(id), "manifest": .init(manifest)])) + return try input.emitted(lowering, envelope) + + [.init(name: lowering.id + "/bundle", kind: .tree, tree: root)] + } +} diff --git a/Sources/Components/NativeProgramV1.swift b/Sources/Components/NativeProgramV1.swift new file mode 100644 index 0000000..f59f396 --- /dev/null +++ b/Sources/Components/NativeProgramV1.swift @@ -0,0 +1,201 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// Native command strings use the pinned clients' POSIX shell runner on supported platforms. +/// Each argument is quoted as one word. Source scripts remain frozen files, never inline code. +package enum NativeProgramV1 { + /// E supplies this only after verifying the native client's command runner, independently + /// of the applying process's environment. Gemini's pinned Unix runner selects bash itself. + package enum CommandShell { case posix } + + static func executable(_ run: [String: LedgerValue], input: ComponentRenderInput) throws + -> LedgerValue + { + guard let executable = run["executable"]?.text, !executable.isEmpty else { + throw input.issue(["run", "executable"], .invalid, "missing native executable") + } + if executable.contains("/") { + guard let resource = input.record.resources.first else { + throw input.issue(["run", "executable"], .invalid, "missing frozen executable resource") + } + return .init(object: ["resource": .init(resource)]) + } + try input.literal(executable, field: ["run", "executable"]) + return .init(executable) + } + + static func validateLiterals(_ value: LedgerValue, input: ComponentRenderInput, path: [String]) + throws + { + if value.kind == .string || value.kind == .literal { + try input.literal(value.text!, field: path) + } + for (index, item) in (value.array ?? []).enumerated() { + try validateLiterals(item, input: input, path: path + [String(index)]) + } + for (key, item) in value.object ?? [:] { + try input.literal(key, field: path + ["key"]) + try validateLiterals(item, input: input, path: path + [key]) + } + } + + /// E calls this only inside its private render closure, with the already obtained Core values. + /// This converts hookGroup/LSP intentions emitted by the concrete versioned profiles. + package static func stagedValue( + _ envelope: LedgerValue, bindings: RuntimeBindingValues, + environment: RuntimeEnvironment, resourcePaths: [String: String], budget: NativeDocumentBudget, + codexCommandShell: CommandShell? = nil + ) throws -> NativeValue { + guard let metadata = envelope.object, + let surface = metadata["surface"]?.text.flatMap(NativeClientSurface.init(rawValue:)), + let scope = metadata["scope"]?.text.flatMap(InstallScope.init(rawValue:)), + let kind = metadata["kind"]?.text, let component = metadata["name"]?.text, + let value = metadata["value"], let selection = metadata["selection"]?.text, + ["hookGroup", "lsp"].contains(selection) + else { throw CoreError.invalidState("invalid staged native program intention") } + func issue(_ path: [String], _ detail: String) -> NativeComponentIssue { + .init( + request: .init(surface: surface, scope: scope), kind: kind, component: component, + field: path, reason: .invalid, detail: detail) + } + if surface == .codexCLI { + guard codexCommandShell == .posix + else { + throw NativeComponentIssue( + request: .init(surface: surface, scope: scope), kind: kind, + component: component, field: ["run"], reason: .integrationRequired, + detail: + "E must supply the verified native POSIX command-shell contract; the apply environment is not that evidence" + ) + } + } + func check(_ text: String, path: [String]) throws -> String { + try budget.allocate(text.utf8.count, stage: "native program string") + try budget.step(text.utf8.count) + guard !text.utf8.contains(0) else { throw issue(path, "NUL is not a native string") } + if surface == .openCodeCLI, text.contains("{env:") || text.contains("{file:") { + throw issue(path, "literal cannot cross native interpolation exactly") + } + // Settings expand environment tokens before the hook runner sees shell quoting. + if surface == .geminiCLI, + text.range(of: #"\$(?:[A-Za-z0-9_]+|\{[^}]+?(?::-[^}]*)?\})"#, options: .regularExpression) + != nil + { + throw issue(path, "literal cannot cross native settings interpolation exactly") + } + return text + } + func string(_ value: LedgerValue, path: [String]) throws -> String { + if let resource = value.object?["resource"]?.text { + guard let final = resourcePaths[resource], !final.isEmpty else { + throw issue(path, "final registered resource placement is required") + } + return try check(final, path: path) + } + switch value.kind { + case .string, .literal: return try check(value.text!, path: path) + case .environment: + guard let text = environment.environment[value.text!] else { + throw issue(path, "required environment value is unavailable") + } + return try check(text, path: path) + case .secret: + let data: Data + do { data = try bindings.value(for: value.text!) } catch { + throw issue(path, "required binding is unavailable") + } + try budget.allocate(data.count, stage: "native program UTF8") + guard let text = String(data: data, encoding: .utf8) else { + throw issue(path, "native binding is not UTF8") + } + return try check(text, path: path) + default: throw issue(path, "expected native program string") + } + } + func quote(_ text: String) throws -> String { + guard text.utf8.count <= (Int.max - 2) / 4 else { + throw issue(["run"], "native command exceeds budget") + } + try budget.allocate(text.utf8.count * 4 + 2, stage: "native shell word") + return "'" + text.replacingOccurrences(of: "'", with: "'\\''") + "'" + } + func program(_ run: [String: LedgerValue]) throws -> String { + var words: [String] = [] + if let cwd = run["workingDirectory"] { + // Working directories are frozen resources; original authored paths never become native paths. + guard let resource = cwd.object?["resource"]?.text, let final = resourcePaths[resource] + else { + throw issue( + ["run", "workingDirectory"], "final registered directory placement is required") + } + words.append( + "cd -- " + (try quote(check(final, path: ["run", "workingDirectory"]))) + " &&") + } + if let env = run["environment"]?.object, !env.isEmpty { + words.append("env") + for (key, value) in env.sorted(by: { $0.key < $1.key }) { + guard MCPReferenceSyntax.isName(key) else { + throw issue(["run", "environment"], "native environment key is invalid") + } + words.append(try quote(key + "=" + string(value, path: ["run", "environment", key]))) + } + } + guard let executable = run["executable"] else { + throw issue(["run", "executable"], "missing executable") + } + words.append(try quote(string(executable, path: ["run", "executable"]))) + for (index, argument) in (run["arguments"]?.array ?? []).enumerated() { + words.append(try quote(string(argument, path: ["run", "arguments", String(index)]))) + } + var size = 0 + for word in words { + guard word.utf8.count < Int.max - size else { + throw issue(["run"], "native command exceeds budget") + } + size += word.utf8.count + 1 + } + try budget.allocate(size, stage: "native command") + return words.joined(separator: " ") + } + func convert(_ value: LedgerValue, path: [String], depth: Int) throws -> NativeValue { + try budget.node(depth: depth) + try budget.step() + if selection == "hookGroup", path == ["hooks", "0", "command"] { + guard let run = value.object?["program"]?.object else { + throw issue(path, "missing native hook program") + } + return .string(try program(run)) + } + if selection == "lsp", path == ["command", "0"], value.object?["resource"] != nil { + return .string(try string(value, path: path)) + } + if value.kind == .environment || value.kind == .secret { + guard selection == "lsp", path.count == 2, path.first == "env" else { + throw issue(path, "symbolic binding is outside a native environment slot") + } + return .string(try string(value, path: path)) + } + switch value.kind { + case .string, .literal: return .string(try string(value, path: path)) + case .integer: return .integer(value.integer!) + case .boolean: return .boolean(value.boolean!) + case .decimal: return .decimal(value.text!) + case .null: return .null + case .array: + return .array( + try value.array!.enumerated().map { + try convert($0.element, path: path + [String($0.offset)], depth: depth + 1) + }) + case .object: + var fields: [String: NativeValue] = [:] + for (key, value) in value.object!.sorted(by: { $0.key < $1.key }) { + fields[key] = try convert(value, path: path + [key], depth: depth + 1) + } + return .object(fields) + case .environment, .secret: throw issue(path, "invalid symbolic value") + } + } + return try convert(value, path: [], depth: 0) + } +} diff --git a/Sources/NativeDocuments/Model.swift b/Sources/NativeDocuments/Model.swift index 24f4128..ba77bbf 100644 --- a/Sources/NativeDocuments/Model.swift +++ b/Sources/NativeDocuments/Model.swift @@ -54,10 +54,14 @@ package enum NativePathStep: Equatable { package struct NativeOccurrenceEvidence: Equatable { package let idKey: String? package let id: String? - let snapshot: Data? - let ordinal: Int? - let previous: Data? - let next: Data? + /// Versioned format owners may retain these semantic fingerprints and neighbor evidence. + /// They contain no byte offsets and do not authorize adoption of an observed occurrence. + /// Fingerprints contain value bytes: secret-bearing matches stay in E/D's private plan, + /// while only non-secret semantic evidence may enter a versioned locked layout. + package let snapshot: Data? + package let ordinal: Int? + package let previous: Data? + package let next: Data? package init(idKey: String, id: String) { self.idKey = idKey self.id = id @@ -66,7 +70,7 @@ package struct NativeOccurrenceEvidence: Equatable { previous = nil next = nil } - init(snapshot: Data, ordinal: Int, previous: Data?, next: Data?) { + package init(snapshot: Data, ordinal: Int, previous: Data?, next: Data?) { idKey = nil id = nil self.snapshot = snapshot diff --git a/Tests/ComponentsTests/NativeComponentTests.swift b/Tests/ComponentsTests/NativeComponentTests.swift new file mode 100644 index 0000000..9cb5bc5 --- /dev/null +++ b/Tests/ComponentsTests/NativeComponentTests.swift @@ -0,0 +1,600 @@ +import AgentsManifest +import Foundation +import NativeDocuments +import Testing + +@testable import AgentsCore +@testable import Components + +@Suite("Concrete native component profiles") +struct NativeComponentTests { + @Test func geminiCommandPreservesQuotedLiteralAndFrozenFileBody() throws { + let fixture = try LinkFixture() + let body = "Review \\\"quoted\\\" paths\nKeep exact content.\n" + try fixture.write(body, to: "prompt.md", base: fixture.project) + let item: [String: Any] = [ + "kind": "command", "name": "review", "description": "Review sources", + "prompt": ["file": ["path": "prompt.md"]], "agents": ["gemini-cli"], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .geminiCLI)] + ledger = try prepared(ledger, fixture) + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + try FileManager.default.removeItem(at: fixture.project) + let restored = try ResolvedLedgerCodec.decode(encoded, limits: .standard) + try replay(restored, fixture) { outputs in + let envelope = try #require(outputs[0].values?.object) + #expect(envelope["route"]?.text == "geminiCommand") + #expect(envelope["path"]?.text == "review.toml") + let file = try #require(envelope["value"]?.text) + let native = try NativeDocument(bytes: Data(file.utf8), format: .toml, budget: budget()) + #expect(try native.read(.init(keys: ["prompt"]))?.value == .string(body)) + #expect(try native.read(.init(keys: ["description"]))?.value == .string("Review sources")) + #expect(!String(describing: envelope).contains(fixture.project.path)) + } + } + + @Test(arguments: [NativeClientSurface.geminiCLI, .cursorEditor]) + func agentFrontmatterKeepsDescriptionAndToolSemantics(_ surface: NativeClientSurface) throws { + let fixture = try LinkFixture() + var item: [String: Any] = [ + "kind": "subagent", "name": "security-auditor", + "description": "Audit: source\n---\nLiteral metadata", + "prompt": "Inspect the source.", + "model": "inherit", "agents": [surface.agent.rawValue], + ] + if surface == .geminiCLI { item["tools"] = ["read_file", "grep_search"] } + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: surface)] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + let envelope = try #require(output[0].values?.object) + let text = try #require(envelope["value"]?.text) + #expect(text.hasPrefix("---\ndescription: \"Audit: source\\n---\\nLiteral metadata\"\n")) + #expect(text.hasSuffix("---\nInspect the source.")) + #expect(envelope["knownReaders"] == LedgerPayload.strings([surface.agent.rawValue])) + if surface == .geminiCLI { #expect(text.contains("tools: [\"read_file\", \"grep_search\"]")) } + } + } + + @Test func codexRoleFreezesItsConfigAndRegistrationTogether() throws { + let fixture = try LinkFixture() + let item: [String: Any] = [ + "kind": "subagent", "name": "researcher", "description": "Research-focused role.", + "prompt": "Read exact sources.\n", "model": "fixture-model", "agents": ["codex"], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .codexCLI)] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + let envelopes = try #require(output[0].values?.array) + #expect(envelopes.count == 2) + let text = try #require(envelopes[0].object?["value"]?.text) + let doc = try NativeDocument(bytes: Data(text.utf8), format: .toml, budget: budget()) + #expect( + try doc.read(.init(keys: ["developer_instructions"]))?.value + == .string("Read exact sources.\n")) + #expect(envelopes[1].object?["keys"] == LedgerPayload.strings(["agents", "researcher"])) + #expect( + envelopes[1].object?["value"]?.object?["config_file"]?.text == "./agents/researcher.toml") + } + } + + @Test func openCodeCommandAgentAndOrderedNativeToolPermissions() throws { + let fixture = try LinkFixture() + let components: [[String: Any]] = [ + [ + "kind": "command", "name": "review", "description": "Review sources", + "prompt": "Review the source.", "agents": ["opencode"], + ], + [ + "kind": "subagent", "name": "reviewer", "description": "Review sources", + "prompt": "Inspect source.", "model": "provider/model", "agents": ["opencode"], + ], + [ + "kind": "permissions", "name": "policy", + "rules": [ + ["effect": "deny", "operation": ["tool": "read"], "pattern": "*"], + ["effect": "allow", "operation": ["tool": "read"], "pattern": "src/**"], + ["effect": "ask", "operation": ["tool": "read"], "pattern": "src/private/**"], + ], "agents": ["opencode"], + ], + ] + let (linked, frozen) = try freeze(components, fixture) + var ledger = frozen.ledger + ledger.lowerings = try linked.enumerated().map { + try lower($0.element, frozen, surface: .openCodeCLI, id: "component-\($0.offset)") + } + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + #expect(output[0].values?.object?["keys"] == LedgerPayload.strings(["commands", "review"])) + #expect(output[0].values?.object?["value"]?.object?["template"]?.text == "Review the source.") + #expect(output[1].values?.object?["value"]?.object?["mode"]?.text == "subagent") + #expect(output[2].values?.object?["selection"]?.text == "orderedAppend") + let rules = try #require(output[2].values?.object?["value"]?.array) + #expect(rules.compactMap { $0.object?["effect"]?.text } == ["deny", "allow", "ask"]) + #expect( + rules.compactMap { $0.object?["resource"]?.text } == ["*", "src/**", "src/private/**"]) + #expect( + output.map { $0.values?.object?["occurrences"] } + == linked.map { .init(array: $0.origins.map { .init(integer: $0.occurrence) }) }) + } + } + + @Test(arguments: [NativeClientSurface.geminiCLI, .codexCLI]) + func nativeHookFreezesProgramAndStagedArgumentsWithoutExecuting(_ surface: NativeClientSurface) + throws + { + let fixture = try LinkFixture() + try fixture.write( + "#!/bin/sh\n# source-owned fixture; never executed\n", to: "scripts/check", + base: fixture.project) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: fixture.project.appendingPathComponent("scripts/check").path) + try fixture.write("data", to: "working/data", base: fixture.project) + let item: [String: Any] = [ + "kind": "hook", "name": "check", "event": ["native": "SessionStart"], + "run": [ + "executable": "./scripts/check", + "arguments": ["a'b", "$(never-execute)", surface == .geminiCLI ? "plain" : "$ordinary"], + "workingDirectory": ["path": "working"], + "environment": ["TOKEN": ["secret": "fixture/token"]], + ], + "matcher": "startup", "timeoutSeconds": 7, "agents": [surface.agent.rawValue], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: surface)] + ledger = try prepared(ledger, fixture) + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + #expect(!String(decoding: encoded, as: UTF8.self).contains("private staged fixture")) + try replay(ledger, fixture) { output in + let envelope = try #require(output[0].values) + let placements = Dictionary( + uniqueKeysWithValues: frozen.ledger.components.values.first!.resources.enumerated().map { + ($0.element, $0.offset == 0 ? "/registered/scripts/check" : "/registered/working") + }) + let native = try NativeProgramV1.stagedValue( + envelope, + bindings: RuntimeBindingValues(["fixture/token": Data("private staged fixture".utf8)]), + environment: fixture.environment, resourcePaths: placements, budget: budget(), + codexCommandShell: .posix) + guard case .object(let group) = native, case .array(let hooks) = group["hooks"], + case .object(let hook) = hooks.first + else { + Issue.record("missing native hook group") + return + } + #expect(hook["timeout"] == .integer(surface == .geminiCLI ? 7000 : 7)) + #expect( + hook["command"] + == .string( + "cd -- '/registered/working' && env 'TOKEN=private staged fixture' '/registered/scripts/check' 'a'\\''b' '$(never-execute)' '" + + (surface == .geminiCLI ? "plain" : "$ordinary") + "'" + )) + } + } + + @Test func openCodeLSPPreservesSymbolicEnvAndInitialization() throws { + let fixture = try LinkFixture() + let item: [String: Any] = [ + "kind": "lspServer", "name": "fixture", + "run": [ + "executable": "fixture-lsp", "arguments": ["--stdio"], + "environment": ["TOKEN": ["env": "SOURCE"]], + ], + "languages": [:], + "initializationOptions": [ + "nested": ["enabled": true], "resource": "ordinary", "program": ["setting": "retained"], + ], + "agents": ["opencode"], + "native": ["opencode": ["extensions": [".fixture"]]], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .openCodeCLI)] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + let envelope = try #require(output[0].values) + let environment = RuntimeEnvironment( + projectDirectory: fixture.project, homeDirectory: fixture.home, + environment: ["SOURCE": "fixture value"]) + let value = try NativeProgramV1.stagedValue( + envelope, bindings: RuntimeBindingValues([:]), environment: environment, resourcePaths: [:], + budget: budget()) + #expect( + value + == .object([ + "command": .array([.string("fixture-lsp"), .string("--stdio")]), + "env": .object(["TOKEN": .string("fixture value")]), + "initialization": .object([ + "nested": .object(["enabled": .boolean(true)]), "resource": .string("ordinary"), + "program": .object(["setting": .string("retained")]), + ]), + "extensions": .array([.string(".fixture")]), + ])) + } + } + + @Test func nativePluginColdReplayKeepsManifestScriptsAndExecutableBits() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"fixture-plugin","version":"1.0.0","description":"Fixture"}"#, + to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + try fixture.write( + "#!/bin/sh\n# never executed\n", to: "bundle/scripts/check", base: fixture.project) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: fixture.project.appendingPathComponent("bundle/scripts/check").path) + try fixture.write("Review source.", to: "bundle/commands/review.md", base: fixture.project) + let item: [String: Any] = [ + "kind": "plugin", "name": "fixture-plugin", "path": "bundle", "source": ".", "mode": "native", + "agents": ["claude-code"], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .claudeCode)] + ledger = try prepared(ledger, fixture) + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + try FileManager.default.removeItem(at: fixture.project) + try replay(ResolvedLedgerCodec.decode(bytes, limits: .standard), fixture) { output in + #expect(output[0].values?.object?["route"]?.text == "claudeSkillPlugin") + let root = try #require(output[1].tree) + #expect( + try String(contentsOf: root.appendingPathComponent("commands/review.md"), encoding: .utf8) + == "Review source.") + let attributes = try FileManager.default.attributesOfItem( + atPath: root.appendingPathComponent("scripts/check").path) + #expect((attributes[.posixPermissions] as! NSNumber).intValue & 0o111 != 0) + } + } + + @Test func arrayOccurrenceEvidenceRematchesAndPreservesUnmanagedSiblings() throws { + let before = + #"{"permissions":[{"action":"read","resource":"a","effect":"deny"}, {"action":"read","resource":"b","effect":"ask"}, {"action":"read","resource":"c","effect":"allow"}],"privateSibling":"keep"}"# + let doc = try NativeDocument(bytes: Data(before.utf8), format: .json, budget: budget()) + let array = try #require(try doc.read(.init(keys: ["permissions"]))) + let original = array.occurrences[1] + let retained = NativeOccurrenceEvidence( + snapshot: try #require(original.snapshot), ordinal: try #require(original.ordinal), + previous: original.previous, next: original.next) + let region = NativeRegion([.key("permissions"), .occurrence(retained)]) + let knownOwned = try #require(try doc.read(region)) + let prepared = try doc.prepare([.remove(region: region, expected: .owned(knownOwned))]) + #expect(String(decoding: prepared.bytes, as: UTF8.self).contains(#""privateSibling":"keep""#)) + let changed = try NativeDocument( + bytes: Data( + before.replacingOccurrences(of: #""resource":"b""#, with: #""resource":"external""#).utf8), + format: .json, budget: budget()) + #expect(throws: NativeDocumentError.self) { + try changed.prepare([.remove(region: region, expected: .owned(knownOwned))]) + } + } + + @Test func unsupportedAndUnverifiedRemainPreciseAndValueFree() throws { + let fixture = try LinkFixture() + let item: [String: Any] = [ + "kind": "command", "name": "exact", "description": "Fixture", + "prompt": "SENSITIVE_FIXTURE", "agents": ["codex"], + ] + let (linked, frozen) = try freeze([item], fixture) + do { + _ = try lower(linked[0], frozen, surface: .codexCLI) + Issue.record("persistent Codex command accepted") + } catch let issue as NativeComponentIssue { + #expect(issue.reason == .unsupported) + #expect(issue.field == ["kind"]) + #expect(issue.component == "exact") + #expect(!issue.description.contains("SENSITIVE_FIXTURE")) + } + #expect(throws: NativeComponentIssue.self) { + try CapabilityRegistry.component( + .init(surface: .cursorCloud, scope: .project), kind: .subagent, name: "exact") + } + #expect(throws: NativeComponentIssue.self) { + try CapabilityRegistry.component( + .init(surface: .cursorEditor, scope: .user), kind: .command, name: "exact") + } + #expect(throws: NativeComponentIssue.self) { + try CapabilityRegistry.component( + .init(surface: .codexCLI, scope: .project), kind: .permissions, name: "exact") + } + } + + @Test func currentIgnoreProfilesKeepOrderAndPurpose() throws { + let fixture = try LinkFixture() + for surface in [NativeClientSurface.geminiCLI, .cursorEditor] { + let item: [String: Any] = [ + "kind": "ignore", "name": "private", "patterns": ["private/**", "!private/public.txt"], + "purpose": "context", "agents": [surface.agent.rawValue], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: surface)] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + #expect(output[0].values?.object?["selection"]?.text == "managedIgnore") + #expect( + output[0].values?.object?["value"] + == LedgerPayload.strings(["private/**", "!private/public.txt"])) + } + } + } + + @Test func profileLossAndInterpolationFailBeforePublication() throws { + let fixture = try LinkFixture() + let cases: [([String: Any], NativeClientSurface, [String], NativeAdapterIssue.Reason)] = [ + ( + [ + "kind": "command", "name": "exact", "description": "Fixture", + "prompt": "$${input:literal}", "agents": ["gemini-cli"], + ], + .geminiCLI, ["prompt"], .unverified + ), + ( + [ + "kind": "command", "name": "exact", "description": "Fixture", "prompt": "$ARGUMENTS", + "agents": ["opencode"], + ], .openCodeCLI, ["prompt"], .unverified + ), + ( + [ + "kind": "command", "name": "exact", "description": "Fixture", "prompt": " indented", + "agents": ["opencode"], + ], .openCodeCLI, ["prompt"], .unsupported + ), + ( + [ + "kind": "command", "name": "exact", "description": "Fixture", + "prompt": "Use ${input:branch}", + "parameters": [["name": "branch", "description": "Branch", "defaultValue": "main"]], + "agents": ["gemini-cli"], + ], .geminiCLI, ["parameters"], .unsupported + ), + ( + [ + "kind": "subagent", "name": "exact", "description": "Fixture", "prompt": "Prompt", + "native": ["gemini-cli": ["max_turns": 1.5]], "agents": ["gemini-cli"], + ], .geminiCLI, ["native", "gemini-cli", "max_turns"], .invalid + ), + ( + [ + "kind": "lspServer", "name": "exact", "run": ["executable": "fixture"], + "languages": [".ts": "typescript"], "agents": ["opencode"], + ], .openCodeCLI, ["languages"], .unverified + ), + ] + for (item, surface, field, reason) in cases { + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: surface)] + do { + _ = try prepared(ledger, fixture) + Issue.record("unrepresentable native profile accepted") + } catch let issue as NativeComponentIssue { + #expect(issue.field == field) + #expect(issue.reason == reason) + #expect(issue.component == "exact") + } + } + } + + @Test func cursorProjectCommandAndGeminiNativeExtensionHaveClosedRoutes() throws { + let fixture = try LinkFixture() + let command: [String: Any] = [ + "kind": "command", "name": "review", "description": "", "prompt": "Review source.\n", + "agents": ["cursor"], + ] + let (linked, frozen) = try freeze([command], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .cursorEditor)] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + #expect(output[0].values?.object?["value"]?.text == "Review source.\n") + #expect(output[0].values?.object?["route"]?.text == "cursorCommand") + } + try fixture.write( + #"{"name":"extension-fixture","version":"1.0.0"}"#, to: "extension/gemini-extension.json", + base: StateStore(scope: .user, environment: fixture.environment).directory) + try fixture.write( + #"prompt = "Review source.""# + "\n", to: "extension/commands/review.toml", + base: StateStore(scope: .user, environment: fixture.environment).directory) + let plugin: [String: Any] = [ + "kind": "plugin", "name": "extension-fixture", "path": "extension", "source": ".", + "mode": "native", "agents": ["gemini-cli"], + ] + let (plugins, pluginFrozen) = try freeze([plugin], fixture, scope: .user) + var pluginLedger = pluginFrozen.ledger + pluginLedger.lowerings = [ + try NativeComponentLowering.lower( + plugins[0], frozen: pluginFrozen, + request: .init(surface: .geminiCLI, scope: .user), id: "extension", platform: platform) + ] + pluginLedger = try prepared(pluginLedger, fixture) + try replay(pluginLedger, fixture) { output in + #expect(output[0].values?.object?["route"]?.text == "geminiExtension") + #expect(output[0].values?.object?["scope"]?.text == "user") + let root = try #require(output[1].tree) + let bytes = try Data(contentsOf: root.appendingPathComponent("commands/review.toml")) + let native = try NativeDocument(bytes: bytes, format: .toml, budget: budget()) + #expect(try native.read(.init(keys: ["prompt"]))?.value == .string("Review source.")) + } + } + + @Test func sourceDerivedNativeRejectionsAndLockedOutputBudget() throws { + let fixture = try LinkFixture() + let cases: [([String: Any], NativeClientSurface, [String])] = [ + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "SessionEnd"], "timeoutSeconds": 4, + "run": ["executable": "fixture"], "agents": ["codex"], + ], .codexCLI, ["timeoutSeconds"] + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "Stop"], "matcher": "ignored", + "run": ["executable": "fixture"], "agents": ["codex"], + ], .codexCLI, ["matcher"] + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "SessionStart"], + "run": ["executable": "fixture", "arguments": ["$ordinary"]], "agents": ["gemini-cli"], + ], + .geminiCLI, ["run", "arguments", "0"] + ), + ( + [ + "kind": "hook", "name": "exact", "event": "beforeTool", "run": ["executable": "fixture"], + "agents": ["gemini-cli"], + ], .geminiCLI, ["event"] + ), + ( + [ + "kind": "subagent", "name": "exact", "description": "Description", "prompt": "Prompt", + "tools": ["not_a_native_tool"], "agents": ["gemini-cli"], + ], .geminiCLI, ["tools", "0"] + ), + ( + [ + "kind": "subagent", "name": "exact", "description": "Description", + "prompt": "Prompt\u{FEFF}", + "agents": ["gemini-cli"], + ], .geminiCLI, ["prompt"] + ), + ] + for (item, surface, field) in cases { + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: surface)] + do { + _ = try prepared(ledger, fixture) + Issue.record("native loss was accepted") + } catch let issue as NativeComponentIssue { #expect(issue.field == field) } + } + let item: [String: Any] = [ + "kind": "command", "name": "budget", "description": "Description", "prompt": "Body", + "agents": ["gemini-cli"], + ] + let (linked, frozen) = try freeze([item], fixture) + let lowering = try lower(linked[0], frozen, surface: .geminiCLI) + var limits = LedgerLimits.standard + limits.resourceBytes = 1 + let render = try #require(NativeComponentLayoutsV1.renderers(limits: limits)[lowering.format]) + #expect(throws: NativeComponentIssue.self) { try render(lowering, frozen.ledger, [:]) } + var ledger = frozen.ledger + ledger.lowerings = [lowering] + ledger = try prepared(ledger, fixture) + ledger.lowerings[0].format = "agents/gemini-components@999" + #expect(throws: CoreError.self) { try replay(ledger, fixture) { _ in } } + } + + @Test func coalescedConditionsKeepInactiveOriginsAndSelectTheActiveOccurrence() throws { + let fixture = try LinkFixture() + let base: [String: Any] = [ + "kind": "permissions", "name": "same", "agents": ["opencode"], + "rules": [["effect": "allow", "operation": ["tool": "read"], "pattern": "src/**"]], + ] + var project = base + project["condition"] = ["scopes": ["project"], "platforms": [platform.rawValue]] + var user = base + user["condition"] = ["scopes": ["user"], "platforms": [platform.rawValue]] + let (linked, frozen) = try freeze([project, user], fixture) + #expect(linked.count == 1) + #expect(linked[0].origins.count == 2) + #expect(frozen.ledger.occurrences.count == 2) + #expect(frozen.ledger.components.values.first?.conditions.count == 2) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .openCodeCLI)] + let otherPlatform: DeclarationPlatform = platform == .macOS ? .linux : .macOS + do { + _ = try NativeComponentLowering.lower( + linked[0], frozen: frozen, request: .init(surface: .openCodeCLI, scope: .project), + id: "wrong-platform", platform: otherPlatform) + Issue.record("accepted an output platform excluded by its frozen occurrence") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["platform"]) + #expect(issue.reason == .invalid) + } + var mismatched = ledger.lowerings[0] + mismatched.platform = otherPlatform.rawValue + let renderer = try #require( + NativeComponentLayoutsV1.renderers(limits: .standard)[mismatched.format]) + #expect(throws: CoreError.self) { try renderer(mismatched, ledger, [:]) } + #expect( + ledger.lowerings[0].layout.object?["occurrences"] + == .init(array: [.init(integer: linked[0].origins[0].occurrence)])) + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + #expect( + output[0].values?.object?["occurrences"] + == .init(array: [.init(integer: linked[0].origins[0].occurrence)])) + } + #expect(ledger.occurrences.count == 2) + } + + private var platform: DeclarationPlatform { + #if os(macOS) + .macOS + #else + .linux + #endif + } + + private func lower( + _ linked: LinkedComponent, _ frozen: LedgerFreeze.Result, + surface: NativeClientSurface, id: String = "native" + ) throws -> LockedLowering { + try NativeComponentLowering.lower( + linked, frozen: frozen, + request: .init(surface: surface, scope: .project), id: id, platform: platform) + } + private func freeze( + _ items: [[String: Any]], _ fixture: LinkFixture, scope: InstallScope = .project + ) throws -> ( + [LinkedComponent], LedgerFreeze.Result + ) { + let bytes = try JSONSerialization.data( + withJSONObject: ["version": 1, "components": items], options: [.sortedKeys]) + let document = try DeclarationDocument( + bytes: Array(bytes), identity: .init("consumer/agents.yaml")) + let store = StateStore(scope: scope, environment: fixture.environment) + let packageRoot = scope == .project ? fixture.project : store.directory + return try ComponentLinker.withLinkedComponents( + document: document, store: store, + platform: platform + ) { graph, session in + ( + graph.components, + try LedgerFreeze.freezeWithSources( + graph, session: session, + locations: .init(sources: [ + "local:" + packageRoot.path: .init( + kind: .registered, root: scope == .project ? "project" : "userState", path: ".") + ]), limits: .standard) + ) + } + } + private func prepared(_ ledger: ResolvedLedger, _ fixture: LinkFixture) throws -> ResolvedLedger { + try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: .standard, + renderers: NativeComponentLayoutsV1.renderers(limits: .standard)) + } + private func replay( + _ ledger: ResolvedLedger, _ fixture: LinkFixture, _ body: ([ReplayedArtifact]) throws -> Void + ) throws { + try LedgerReplay.withReplay( + ledger, store: fixture.store, roots: [:], limits: .standard, + renderers: NativeComponentLayoutsV1.renderers(limits: .standard), body) + } + private func budget() -> NativeDocumentBudget { + .init( + limits: .init( + storage: 32_000_000, work: 100_000_000, nodes: 100_000, depth: 128, + uninterruptedBytes: 1_000_000)) + } +} diff --git a/Tests/ComponentsTests/NativeMCPTests.swift b/Tests/ComponentsTests/NativeMCPTests.swift index 07881db..fa73595 100644 --- a/Tests/ComponentsTests/NativeMCPTests.swift +++ b/Tests/ComponentsTests/NativeMCPTests.swift @@ -1,9 +1,9 @@ -import AgentsCore import AgentsManifest import Foundation import NativeDocuments import Testing +@testable import AgentsCore @testable import Components @Suite("Native MCP mapping and replay") @@ -550,6 +550,25 @@ struct NativeMCPTests { request: .init(surface: .codexCLI, scope: .project)) #expect(contribution.resourcePlacements.map(\.path) == [[.key("command")], [.key("cwd")]]) #expect(contribution.resourcePlacements.map(\.resource) == contribution.resources) + let final = try contribution.stagedValue( + bindings: RuntimeBindingValues([:]), + environment: fixture.environment, + resourcePaths: [ + contribution.resources[0]: "/registered/bin/server", + contribution.resources[1]: "/registered/data", + ], + budget: budget()) + #expect( + final + == .object([ + "command": .string("/registered/bin/server"), "args": .array([]), + "cwd": .string("/registered/data"), + ])) + #expect(throws: NativeAdapterIssue.self) { + try contribution.stagedValue( + bindings: RuntimeBindingValues([:]), environment: fixture.environment, + resourcePaths: [:], budget: budget()) + } #expect(throws: NativeAdapterIssue.self) { try contribution.referenceValue() } var candidate = frozen.ledger candidate.lowerings = [ @@ -692,6 +711,91 @@ struct NativeMCPTests { } } + @Test func stagedMCPUsesSuppliedValuesAndKeepsReferencesSymbolic() throws { + try withMCP( + [ + server( + "staged", + transport: stdio(environment: [ + "INHERITED": ["env": "INHERITED"], "RENAMED": ["env": "SOURCE"], + "TOKEN": ["secret": "fixture/token"], + ]), agents: ["codex"]) + ], + request: .init(surface: .codexCLI, scope: .project) + ) { contribution, ledger, fixture in + let before = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + let environment = RuntimeEnvironment( + projectDirectory: fixture.project, homeDirectory: fixture.home, + environment: ["SOURCE": "exact environment fixture"]) + let supplied = RuntimeBindingValues(["fixture/token": Data("private fixture value".utf8)]) + let native = try contribution.stagedValue( + bindings: supplied, environment: environment, + resourcePaths: [:], budget: budget()) + guard case .object(let fields) = native else { + Issue.record("missing native object") + return + } + #expect( + fields["env"] + == .object([ + "RENAMED": .string("exact environment fixture"), + "TOKEN": .string("private fixture value"), + ])) + #expect(fields["env_vars"] == .array([.string("INHERITED")])) + #expect(try ResolvedLedgerCodec.encode(ledger, limits: .standard) == before) + #expect(!String(describing: contribution.value).contains("private fixture value")) + for data in [Data([0xff]), Data([0])] { + do { + _ = try contribution.stagedValue( + bindings: RuntimeBindingValues(["fixture/token": data]), + environment: environment, resourcePaths: [:], budget: budget()) + Issue.record("invalid native binding accepted") + } catch let issue as NativeAdapterIssue { + #expect(issue.reason == .invalid) + #expect(issue.field == ["env", "TOKEN"]) + #expect(!issue.description.contains("fixture/token")) + } + } + } + } + + @Test func stagedOpenCodeRejectsInterpolationAndHeaderInjection() throws { + try withMCP( + [ + server( + "staged", + transport: [ + "kind": "streamableHTTP", "url": "https://example.invalid/mcp", + "headers": ["X-Token": ["secret": "fixture/token"]], + ], agents: ["opencode"]) + ], + request: .init(surface: .openCodeCLI, scope: .project) + ) { contribution, _, fixture in + for value in ["{file:private.txt}", "{env:TOKEN}", "line\r\nInjected: value", "nul\0"] { + do { + _ = try contribution.stagedValue( + bindings: RuntimeBindingValues(["fixture/token": Data(value.utf8)]), + environment: fixture.environment, resourcePaths: [:], budget: budget()) + Issue.record("unrepresentable staged literal accepted") + } catch let issue as NativeAdapterIssue { + #expect(issue.field == ["headers", "X-Token"]) + #expect(!issue.description.contains(value)) + } + } + let value = #"C:\new"# + let native = try contribution.stagedValue( + bindings: RuntimeBindingValues(["fixture/token": Data(value.utf8)]), + environment: fixture.environment, resourcePaths: [:], budget: budget()) + let region = try contribution.descriptor.region(server: contribution.name) + let doc = try document("{}", contribution) + let prepared = try doc.prepare([.put(region: region, expected: .absent, value: native)]) + let reread = try NativeDocument(bytes: prepared.bytes, format: .json, budget: budget()) + #expect( + try reread.read(.init(keys: ["mcp", "servers", "staged", "headers", "X-Token"]))?.value + == .string(value)) + } + } + private var platform: DeclarationPlatform { #if os(macOS) .macOS From 721b2aa61a333e68cf1c247c7f0379ef1dc7285d Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:45:32 +0800 Subject: [PATCH 072/171] feat: import declared component sources and locks --- Documentation/Architecture/Package.md | 2 +- Package.swift | 4 +- Sources/AgentsManifest/YAMLParser.swift | 20 +- Sources/AgentsManifest/YAMLReader.swift | 30 + Sources/AgentsManifest/YAMLScalar.swift | 6 +- .../Components/Import/APMInputImport.swift | 73 ++ .../Import/APMPackageContentImport.swift | 90 +++ .../Components/Import/ImportFrontmatter.swift | 48 ++ Sources/Components/Import/ImportInput.swift | 206 +++++ .../Import/ImportSkillContent.swift | 119 +++ .../Import/RulesyncConfigImport.swift | 705 +++++++++++++++++ .../Import/RulesyncSourceImport.swift | 247 ++++++ Sources/Components/Import/SourceImport.swift | 70 ++ .../Import/SourceImportProposal.swift | 212 ++++++ .../Import/VercelSourceImport.swift | 227 ++++++ .../Components/Import/YAMLSourceImport.swift | 718 ++++++++++++++++++ .../AgentsManifestTests/YAMLReaderTests.swift | 49 ++ .../ImportPinnedFixtures.swift | 114 +++ .../ComponentsTests/ImportProfileTests.swift | 540 +++++++++++++ Tests/ComponentsTests/ImportSourceTests.swift | 359 +++++++++ 20 files changed, 3828 insertions(+), 11 deletions(-) create mode 100644 Sources/AgentsManifest/YAMLReader.swift create mode 100644 Sources/Components/Import/APMInputImport.swift create mode 100644 Sources/Components/Import/APMPackageContentImport.swift create mode 100644 Sources/Components/Import/ImportFrontmatter.swift create mode 100644 Sources/Components/Import/ImportInput.swift create mode 100644 Sources/Components/Import/ImportSkillContent.swift create mode 100644 Sources/Components/Import/RulesyncConfigImport.swift create mode 100644 Sources/Components/Import/RulesyncSourceImport.swift create mode 100644 Sources/Components/Import/SourceImport.swift create mode 100644 Sources/Components/Import/SourceImportProposal.swift create mode 100644 Sources/Components/Import/VercelSourceImport.swift create mode 100644 Sources/Components/Import/YAMLSourceImport.swift create mode 100644 Tests/AgentsManifestTests/YAMLReaderTests.swift create mode 100644 Tests/ComponentsTests/ImportPinnedFixtures.swift create mode 100644 Tests/ComponentsTests/ImportProfileTests.swift create mode 100644 Tests/ComponentsTests/ImportSourceTests.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 2505c18..4db7929 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -13,7 +13,7 @@ terminal/UI presentation and executable distribution. AgentsManifest → AgentsCore, TreeSitterYAML, TreeSitter, Yams AgentsSkills → AgentsCore, AgentsManifest, Yams AgentsInstructions → AgentsCore, AgentsManifest, Markdown -Components → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions +Components → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, NativeDocuments AgentsUpdates → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions NativeDocuments → AgentsCore, TOMLSemantics, TreeSitterTOML, TreeSitter TOMLSemantics → Foundation diff --git a/Package.swift b/Package.swift index b0f6fd2..abc8b5c 100644 --- a/Package.swift +++ b/Package.swift @@ -67,7 +67,9 @@ let package = Package( ]), .target( name: "Components", - dependencies: ["AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions"]), + dependencies: [ + "AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions", "NativeDocuments", + ]), .testTarget( name: "ComponentsTests", dependencies: [ diff --git a/Sources/AgentsManifest/YAMLParser.swift b/Sources/AgentsManifest/YAMLParser.swift index 84cfcd0..b3d858f 100644 --- a/Sources/AgentsManifest/YAMLParser.swift +++ b/Sources/AgentsManifest/YAMLParser.swift @@ -5,7 +5,7 @@ import TreeSitterYAML import Yams /// Ordered, decoded data with concrete UTF-8 ranges. Mapping order is retained independently -/// of the domain's dictionary semantics. The parser tree never escapes this module. +/// of the domain's dictionary semantics. Concrete parser and editing trees stay internal. indirect enum YAMLData: Sendable, Equatable { case scalar(String, quoted: Bool, decimalTag: Bool) case sequence([YAMLNode]) @@ -23,21 +23,29 @@ indirect enum YAMLData: Sendable, Equatable { } } -struct YAMLNode: Sendable, Equatable { +package struct YAMLNode: Sendable, Equatable { let data: YAMLData - let range: Range + package let range: Range let entryRange: Range let flow: Bool - var text: String? { + /// Scalar spelling and style are read-only; node and graph construction remain internal. + package var scalar: (text: String, quoted: Bool, decimalTag: Bool)? { + if case .scalar(let text, let quoted, let decimalTag) = data { + return (text, quoted, decimalTag) + } + return nil + } + + package var text: String? { if case .scalar(let text, _, _) = data { return text } return nil } - var pairs: [(key: YAMLNode, value: YAMLNode)]? { + package var pairs: [(key: YAMLNode, value: YAMLNode)]? { if case .mapping(let pairs) = data { return pairs } return nil } - var items: [YAMLNode]? { + package var items: [YAMLNode]? { if case .sequence(let items) = data { return items } return nil } diff --git a/Sources/AgentsManifest/YAMLReader.swift b/Sources/AgentsManifest/YAMLReader.swift new file mode 100644 index 0000000..3cad2b7 --- /dev/null +++ b/Sources/AgentsManifest/YAMLReader.swift @@ -0,0 +1,30 @@ +import AgentsCore + +/// Read-only access to the admitted YAML data graph, without canonical manifest validation. +/// Parser limits, duplicate admission and YAML 1.2 scalar identity remain owned by this module. +package struct YAMLReader: Sendable { + package let root: YAMLNode + private let source: SourceText + + package init(bytes: [UInt8], identity: DocumentIdentity) throws { + let source = SourceText(bytes, identity: identity) + do { + root = try YAMLParser.parse(source).root + self.source = source + } catch is CancellationError { + throw CancellationError() + } catch let failure as ManifestFailure { + // Decoder and duplicate-key messages can contain source values. Only coordinates escape. + throw YAMLReadFailure(span: failure.diagnostics.first?.span ?? source.span(0..<0)) + } catch { + throw YAMLReadFailure(span: source.span(0..<0)) + } + } + + package func span(of node: YAMLNode) -> SourceSpan { source.span(node.range) } +} + +package struct YAMLReadFailure: Error, Sendable, CustomStringConvertible { + package let span: SourceSpan + package var description: String { "YAML input is not admitted." } +} diff --git a/Sources/AgentsManifest/YAMLScalar.swift b/Sources/AgentsManifest/YAMLScalar.swift index da930bd..af38f57 100644 --- a/Sources/AgentsManifest/YAMLScalar.swift +++ b/Sources/AgentsManifest/YAMLScalar.swift @@ -2,10 +2,10 @@ import AgentsCore import Foundation /// YAML 1.2 Core resolution. Number conversion never passes through floating-point formatting. -enum YAMLScalar: Equatable { +package enum YAMLScalar: Equatable, Sendable { case string, integer, decimal, boolean, null - static func classify(_ text: String) -> Self { + package static func classify(_ text: String) -> Self { if ["", "~", "null", "Null", "NULL"].contains(text) { return .null } if ["true", "True", "TRUE", "false", "False", "FALSE"].contains(text) { return .boolean } if matches(text, #"^[-+]?(0o[0-7]+|0x[0-9a-fA-F]+|[0-9]+)$"#) { return .integer } @@ -17,7 +17,7 @@ enum YAMLScalar: Equatable { return .string } - static func integer(_ text: String) -> Int? { + package static func integer(_ text: String) -> Int? { var digits = text let negative = digits.hasPrefix("-") if digits.hasPrefix("-") || digits.hasPrefix("+") { digits.removeFirst() } diff --git a/Sources/Components/Import/APMInputImport.swift b/Sources/Components/Import/APMInputImport.swift new file mode 100644 index 0000000..ec49773 --- /dev/null +++ b/Sources/Components/Import/APMInputImport.swift @@ -0,0 +1,73 @@ +import AgentsCore +import Foundation + +extension SourceImport { + /// Manifest intent and a caller-selected lock retain distinct provenance. Matching requires + /// unambiguous repository, resource root and requested-ref evidence; no ref is resolved here. + package static func previewAPM( + manifest: SourceImportInput, lock: SourceImportInput?, limits: SourceImportLimits = .init() + ) throws -> SourceImportProposal { + guard manifest.profile == .apmManifest, lock == nil || lock?.profile == .apmLock else { + var result = SourceImportProposal(profile: .apmManifest) + result.diagnostics.append( + .init( + code: .invalidInput, location: .init(document: manifest.document, pointer: ""), + message: "APM composition requires an explicit manifest and optional APM lock profile.")) + return result + } + var result = try preview(manifest, limits: limits) + guard let lock else { return result } + let locked = try preview(lock, limits: limits) + result.diagnostics += locked.diagnostics + result.bindings += locked.bindings + result.deployments += locked.deployments + result.selections += locked.selections + // Keep every independent locked source and preservation plan, including transitives. + result.sources += locked.sources + result.resources += locked.resources + result.components += locked.components + for index in result.sources.indices where index < result.sources.count - locked.sources.count { + let source = result.sources[index] + guard let declaration = source.declaration, declaration.kind == .git, + let identity = try? declaration.transportIdentity() + else { continue } + let matches = locked.sources.filter { + guard let candidate = $0.declaration, candidate.kind == .git, + (try? candidate.transportIdentity()) == identity, + (candidate.path ?? ".") == (declaration.path ?? ".") + else { return false } + return true + } + guard matches.count == 1, let matched = matches.first else { + if !matches.isEmpty { + result.diagnostics.append( + .init( + code: .ambiguousSource, location: source.origin, + message: "Multiple locked entries match this manifest source; no pin is selected.")) + } + continue + } + if let requested = source.requestedRef, + ![matched.resolvedRef, matched.requestedRef, matched.pin.commit].contains(requested) + { + result.diagnostics.append( + .init( + code: .ambiguousSource, location: source.origin, + message: "Locked ref evidence does not match manifest intent; no pin is selected.")) + continue + } + guard let commit = matched.pin.commit else { continue } + var exact = declaration + exact.requirement = .revision(commit) + result.sources[index] = .init( + alias: source.alias, origin: source.origin, declaration: exact, pin: matched.pin, + requestedRef: source.requestedRef, producerPath: source.producerPath, + producerIdentity: source.producerIdentity, resolvedRef: matched.resolvedRef, + developmentOnly: source.developmentOnly) + result.diagnostics.removeAll { + $0.code == .incompletePin && $0.location == source.origin + } + } + return result + } +} diff --git a/Sources/Components/Import/APMPackageContentImport.swift b/Sources/Components/Import/APMPackageContentImport.swift new file mode 100644 index 0000000..2e417d8 --- /dev/null +++ b/Sources/Components/Import/APMPackageContentImport.swift @@ -0,0 +1,90 @@ +import AgentsCore +import Foundation + +/// APM-native authoring content is authoritative when .apm exists. Plugin-native layouts need +/// their verified container adapter; absence of .apm never selects an arbitrary fallback tree. +enum APMPackageContentImport { + static func read( + input: SourceImportInput, origin: ImportLocation, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + let parent = (input.document as NSString).deletingLastPathComponent + let path = parent.isEmpty ? ".apm" : parent + "/.apm" + let view = try ImportInput.snapshot(input.root) + let directory = try view.resource(path) + guard FileManager.default.fileExists(atPath: directory.path) else { return } + let attributes = try FileManager.default.attributesOfItem(atPath: directory.path) + guard attributes[.type] as? FileAttributeType == .typeDirectory else { + diagnostics.add(.unsafePath, origin, "APM source layout is not an admitted directory.") + return + } + var remaining = limits.resourceEntries + func children(_ path: String) throws -> [String] { + let directory = try view.resource(path) + guard FileManager.default.fileExists(atPath: directory.path) else { return [] } + guard + let iterator = FileManager.default.enumerator( + at: directory, includingPropertiesForKeys: nil, options: [.skipsSubdirectoryDescendants]) + else { throw ImportReadFailure.invalid } + var result: [String] = [] + for case let child as URL in iterator { + try Task.checkCancellation() + guard remaining > 0 else { throw ImportReadFailure.invalid } + remaining -= 1 + result.append(child.lastPathComponent) + } + return result.sorted() + } + for (index, name) in try children(path).enumerated() where name != "skills" { + diagnostics.add( + .unconverted, origin.appending("layout/member[\(index)]"), + "APM primitive requires its component semantics adapter; no native container fallback is selected." + ) + } + for (index, name) in try children(path + "/skills").enumerated() { + let location = origin.appending("skills/member[\(index)]") + guard ImportInput.name(name) else { + diagnostics.add(.unsafePath, location, "Invalid APM skill resource name.") + continue + } + let skillPath = path + "/skills/" + name + do { + let gitBoundary = try view.resource(skillPath + "/.git") + if FileManager.default.fileExists(atPath: gitBoundary.path) { + diagnostics.add( + .unconverted, location, "Nested Git checkout is outside APM authoring discovery.") + continue + } + let content = try ImportSkillContent.read(skillPath, input: input, limits: limits) + diagnostics.proposal.diagnostics += content.diagnostics + diagnostics.proposal.bindings += content.bindings + let alias = "apm-local-skill-\(index)" + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: location, + declaration: .init( + kind: .local, location: content.path, + environment: .init(projectDirectory: input.root, homeDirectory: input.root)), + pin: .init(), requestedRef: nil, producerPath: nil)) + diagnostics.proposal.resources.append( + .init( + origin: location, sourceAlias: alias, producerName: name, path: ".", + producerIntegrity: nil, observedHash: content.hash, executableFlags: content.flags, + requiresStandaloneSource: true, kind: .skills)) + diagnostics.proposal.components.append( + .init( + origin: location, + declaration: .skills( + source: alias, + .init(select: .names([content.skill.name]), condition: content.skill.condition)))) + } catch is CancellationError { throw CancellationError() } catch CoreError.unsafePath { + diagnostics.add( + .unsafePath, location, "APM skill resource escapes its explicit source boundary.") + } catch { + diagnostics.add( + .unconverted, location, + "APM skill resource is missing, malformed or exceeds content bounds.") + } + } + } +} diff --git a/Sources/Components/Import/ImportFrontmatter.swift b/Sources/Components/Import/ImportFrontmatter.swift new file mode 100644 index 0000000..4635c28 --- /dev/null +++ b/Sources/Components/Import/ImportFrontmatter.swift @@ -0,0 +1,48 @@ +import AgentsCore +import AgentsManifest +import Foundation + +/// Markdown delimiters select YAML bytes; YAML syntax and scalar admission remain in AgentsManifest. +/// Padding the opening delimiter preserves original UTF-8 offsets and line numbers. +enum ImportFrontmatter { + static func inspect( + _ bytes: Data, document: String, converted: Set, profile: SourceImportProfile, + limits: SourceImportLimits + ) throws -> (diagnostics: [SourceImportDiagnostic], bindings: [ImportBindingRequirement]) { + let source = Array(bytes) + let bom = source.starts(with: [0xEF, 0xBB, 0xBF]) ? 3 : 0 + guard source.count >= bom + 4, Array(source[bom..<(bom + 3)]) == [45, 45, 45], + [10, 13].contains(source[bom + 3]) + else { return ([], []) } + var index = bom + 3 + if source[index] == 13 { index += 1 } + if index < source.count, source[index] == 10 { index += 1 } + while index < source.count { + try Task.checkCancellation() + guard index <= min(limits.documentBytes, ManifestLimits.Input.bytes) else { + throw ImportReadFailure.invalid + } + let start = index + while index < source.count, ![10, 13].contains(source[index]) { + guard index <= min(limits.documentBytes, ManifestLimits.Input.bytes) else { + throw ImportReadFailure.invalid + } + index += 1 + } + if Array(source[start.. [String: + Any] + { + let bytes = try bytes(input, limits: limits) + try LedgerAdmission.check( + Data([91]) + bytes + Data([93]), + limits: .init( + encodedBytes: limits.documentBytes + 2, depth: limits.depth + 1, nodes: limits.nodes + 1, + objectBytes: limits.documentBytes, entries: limits.nodes, keyBytes: limits.documentBytes)) + guard let object = try JSONSerialization.jsonObject(with: bytes) as? [String: Any] else { + throw ImportReadFailure.invalid + } + return object + } + + static func bytes(_ input: SourceImportInput, limits: SourceImportLimits) throws -> Data { + guard limits.documentBytes >= 0, limits.documentBytes <= Int.max - 2, + limits.depth > 0, limits.depth < Int.max, limits.nodes > 0, limits.nodes < Int.max + else { throw ImportReadFailure.invalid } + let view = try snapshot(input.root) + let file = try view.resource(input.document) + let info = try FileManager.default.attributesOfItem(atPath: file.path) + guard info[.type] as? FileAttributeType == .typeRegular, + let size = (info[.size] as? NSNumber)?.intValue, + size <= limits.documentBytes + else { throw ImportReadFailure.invalid } + let handle = try FileHandle(forReadingFrom: file) + defer { try? handle.close() } + let bytes = try handle.read(upToCount: limits.documentBytes + 1) ?? Data() + guard bytes.count <= limits.documentBytes, + (try handle.read(upToCount: 1) ?? Data()).isEmpty + else { throw ImportReadFailure.invalid } + return bytes + } + + static func snapshot(_ root: URL) throws -> SourceSnapshot { + guard root.isFileURL else { throw ImportReadFailure.invalid } + return try SourceSnapshot( + snapshot: .init(source: "explicit-import", revision: "local"), pin: nil, root: root) + } + + static func string(_ value: Any?) -> String? { value as? String } + + static func version(_ value: Any?, equals expected: Int) -> Bool { + guard let value = value as? NSNumber, CFGetTypeID(value) != CFBooleanGetTypeID() else { + return false + } + return value.stringValue == String(expected) + } + + static func strings(_ value: Any?) -> [String]? { + guard let list = value as? [Any], list.allSatisfy({ $0 is String }) else { return nil } + return list.map { $0 as! String } + } + + static func name(_ value: String) -> Bool { + !value.isEmpty && value != "." && value != ".." && value.utf8.count <= 255 + && !value.contains("/") && !value.contains("\\") + && !value.unicodeScalars.contains { CharacterSet.controlCharacters.contains($0) } + } + + static func packageVersion(_ value: String?) -> Bool { + guard let value else { return false } + guard + value.range( + of: + #"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$"#, + options: .regularExpression) != nil + else { return false } + let build = value.split(separator: "+", maxSplits: 1, omittingEmptySubsequences: false) + if build.count == 2, + build[1].split(separator: ".", omittingEmptySubsequences: false).contains("") + { + return false + } + let prerelease = build[0].split(separator: "-", maxSplits: 1) + if prerelease.count == 2 { + for item in prerelease[1].split(separator: ".", omittingEmptySubsequences: false) { + if item.isEmpty + || (item.utf8.allSatisfy { (48...57).contains($0) } && item.count > 1 + && item.first == "0") + { + return false + } + } + } + return true + } + + static func path(_ value: String) throws -> String { + guard !value.hasPrefix("~"), !value.contains("\\"), + !value.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }) + else { throw ImportReadFailure.invalid } + return try PathSafety.sanitizeSubpath(value) + } + + static func hex(_ value: String?, count: Int) -> String? { + guard let value, value.utf8.count == count, + value.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }) + else { return nil } + return value + } + + static func credentialField(_ name: String) -> Bool { + let normalized = name.lowercased().filter { $0.isLetter || $0.isNumber } + return [ + "env", "headers", "token", "password", "credentials", "auth", "apikey", "accesstoken", + "secret", "authorization", "clientsecret", + ].contains(normalized) + } + + /// Source URL credentials and query tokens become local binding requirements, never provenance. + static func safeLocator(_ value: String) -> Bool { + guard !value.isEmpty, + !value.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }), + !value.contains("?"), !value.contains("#") + else { return false } + if value.contains("://") { + guard let url = URLComponents(string: value), + url.user == nil || (url.scheme == "ssh" && url.user == "git"), url.password == nil + else { + return false + } + } else if value.contains("@") { + // SCP-style git@host:path is a transport username; arbitrary userinfo is not. + return value.hasPrefix("git@") && value.contains(":") + } + return true + } +} + +enum ImportReadFailure: Error { case invalid } + +struct ImportDiagnostics { + var proposal: SourceImportProposal + + mutating func add( + _ code: SourceImportDiagnostic.Code, _ location: ImportLocation, _ message: String + ) { + proposal.diagnostics.append(.init(code: code, location: location, message: message)) + } + + mutating func unknown(_ fields: [String: Any], allowed: Set, at location: ImportLocation) + { + for (index, field) in fields.keys.sorted().enumerated() where !allowed.contains(field) { + let child = location.appending("member[\(index)]") + if ImportInput.credentialField(field) { binding(child) } + unconverted(fields[field]!, at: child) + } + } + + private mutating func unconverted(_ value: Any, at location: ImportLocation) { + add(.unconverted, location, "Unrecognized field or item is not converted.") + if let fields = value as? [String: Any] { + for (index, field) in fields.keys.sorted().enumerated() { + let child = location.appending("member[\(index)]") + if ImportInput.credentialField(field) { binding(child) } + unconverted(fields[field]!, at: child) + } + } else if let items = value as? [Any] { + for (index, item) in items.enumerated() { + unconverted(item, at: location.appending(String(index))) + } + } else if let value = value as? String, value.contains("://"), !ImportInput.safeLocator(value) { + binding(location) + } + } + + mutating func typedFields( + _ fields: [String: Any], strings: Set, required: Set = [], + arrays: Set = [], at location: ImportLocation + ) -> Bool { + var valid = true + for field in strings.sorted() where fields[field] != nil || required.contains(field) { + if ImportInput.string(fields[field]) == nil { + add(.invalidInput, location.appending(field), "Expected a string field.") + valid = false + } + } + for field in arrays.sorted() where fields[field] != nil { + if ImportInput.strings(fields[field]) == nil { + add(.invalidInput, location.appending(field), "Expected an array of strings.") + valid = false + } + } + return valid + } + + mutating func binding(_ location: ImportLocation, environmentVariable: String? = nil) { + guard !proposal.bindings.contains(where: { $0.location == location }) else { return } + proposal.bindings.append( + .init( + location: location, reason: "Credential-bearing input requires an explicit local binding.", + environmentVariable: environmentVariable) + ) + add(.credentialBinding, location, "Credential literals cannot be retained in import proposals.") + } +} diff --git a/Sources/Components/Import/ImportSkillContent.swift b/Sources/Components/Import/ImportSkillContent.swift new file mode 100644 index 0000000..0cbbc40 --- /dev/null +++ b/Sources/Components/Import/ImportSkillContent.swift @@ -0,0 +1,119 @@ +import AgentsCore +import AgentsSkills +import Foundation + +struct ImportSkillContent { + let path: String + let hash: String + let flags: [String: Bool] + let skill: SnapshotSkill + let files: [(String, Data)] + let diagnostics: [SourceImportDiagnostic] + let bindings: [ImportBindingRequirement] + + static func read(_ path: String, input: SourceImportInput, limits: SourceImportLimits) throws + -> Self + { + let path = try ImportInput.path(path) + let source = try ImportInput.snapshot(input.root) + let directory = try source.resource(path) + // Admit the finite tree before readers that sort directory entries or recursively discover. + // This capture profile refuses links rather than changing their producer hash semantics. + guard limits.resourceEntries > 0, limits.resourceBytes >= 0, limits.depth > 0, + let iterator = FileManager.default.enumerator(at: directory, includingPropertiesForKeys: nil) + else { throw ImportReadFailure.invalid } + var entries = 1 + var total = 0 + for case let entry as URL in iterator { + try Task.checkCancellation() + entries += 1 + guard entries <= limits.resourceEntries else { throw ImportReadFailure.invalid } + let relative = try source.relativePath(entry) + let depth = + relative.split(separator: "/").count - (path == "." ? 0 : path.split(separator: "/").count) + guard depth <= limits.depth else { throw ImportReadFailure.invalid } + let attributes = try FileManager.default.attributesOfItem(atPath: entry.path) + let type = attributes[.type] as? FileAttributeType + guard type == .typeDirectory || type == .typeRegular else { throw ImportReadFailure.invalid } + if type == .typeRegular { + guard let size = (attributes[.size] as? NSNumber)?.intValue, + size >= 0, size <= limits.resourceBytes - total + else { throw ImportReadFailure.invalid } + total += size + } + } + let frozen = try LedgerResources.capture( + directory, embed: true, + limits: .init( + encodedBytes: limits.resourceBytes, depth: limits.depth, nodes: limits.nodes, + objectBytes: limits.resourceBytes, entries: limits.resourceEntries, + keyBytes: limits.resourceBytes, + resourceBytes: limits.resourceBytes), sourceRoot: directory) + // Link identity and link-following producer hashes are different contracts. This bounded + // capture supports regular content; linked trees need explicit conversion before import. + guard frozen.entries.allSatisfy({ $0.kind != .symlink }), frozen.support.isEmpty else { + throw ImportReadFailure.invalid + } + let files = try frozen.entries.filter { $0.kind == .file }.map { entry -> (String, Data) in + guard let object = entry.object, let bytes = frozen.objects[object] else { + throw ImportReadFailure.invalid + } + return (entry.path, bytes) + } + guard files.contains(where: { $0.0 == "SKILL.md" }) else { throw ImportReadFailure.invalid } + var semanticDiagnostics: [SourceImportDiagnostic] = [] + var bindings: [ImportBindingRequirement] = [] + // Validate captured skill YAML before existing discovery, then compare its observed tree + // with the capture. The consuming preparation owns the stable source view and freshness. + for (name, bytes) in files where name == "SKILL.md" || name.hasSuffix("/SKILL.md") { + let semantics = try ImportFrontmatter.inspect( + bytes, document: path + "/" + name, + converted: ["name", "description", "agents", "platforms", "scopes"], profile: input.profile, + limits: limits) + semanticDiagnostics += semantics.diagnostics + bindings += semantics.bindings + } + let selected = try SourceSnapshot( + snapshot: source.snapshot, pin: nil, root: input.root, discoveryPath: path) + let skills = try SkillSnapshotReader.read(selected) + guard let skill = skills.first(where: { $0.path == path }) else { + throw ImportReadFailure.invalid + } + guard skill.hash == frozen.hash else { throw ImportReadFailure.invalid } + return .init( + path: path, hash: frozen.hash, flags: frozen.flags, skill: skill, files: files, + diagnostics: semanticDiagnostics, bindings: bindings) + } + + /// Vercel skills 1.8.1 src/skill-hash.ts: byte-sorted paths, NUL-framed lengths, + /// CRLF normalization for nonbinary files, and the installer's excluded names. + static func vercelHash(_ content: Self) -> String { + var framed = Data() + let files = content.files.map { ($0.0.replacingOccurrences(of: "\\", with: "/"), $0.1) } + for (path, bytes) in files.sorted(by: { $0.0.utf8.lexicographicallyPrecedes($1.0.utf8) } + ) { + let parts = path.split(separator: "/") + if parts.contains("metadata.json") + || parts.dropLast().contains(where: { + [".git", "__pycache__", "__pypackages__"].contains($0) + }) + { + continue + } + var normalized = Data() + if bytes.contains(0) { + normalized = bytes + } else { + var index = 0 + while index < bytes.count { + if bytes[index] == 13, index + 1 < bytes.count, bytes[index + 1] == 10 { index += 1 } + normalized.append(bytes[index]) + index += 1 + } + } + framed.append(Data((path + "\0" + String(normalized.count) + "\0").utf8)) + framed.append(normalized) + } + return FileHash.sha256Hex(data: framed) + } +} diff --git a/Sources/Components/Import/RulesyncConfigImport.swift b/Sources/Components/Import/RulesyncConfigImport.swift new file mode 100644 index 0000000..a6e484c --- /dev/null +++ b/Sources/Components/Import/RulesyncConfigImport.swift @@ -0,0 +1,705 @@ +import AgentsCore +import Foundation +import NativeDocuments + +struct ImportLocatedFailure: Error { let location: ImportLocation } + +struct ImportJSONC { + let input: SourceImportInput + let document: NativeDocument + let fields: [String: NativeValue] + + init(_ input: SourceImportInput, limits: SourceImportLimits) throws { + let bytes = try ImportInput.bytes(input, limits: limits) + guard limits.documentBytes >= 0, limits.documentBytes <= (Int.max - 1024) / 64, + limits.nodes > 0, limits.depth > 0 + else { throw ImportReadFailure.invalid } + let budget = NativeDocumentBudget( + limits: .init( + storage: limits.documentBytes * 32 + 1024, work: limits.documentBytes * 64 + 1024, + nodes: limits.nodes, depth: limits.depth, uninterruptedBytes: limits.documentBytes)) + do { + let document = try NativeDocument( + bytes: bytes, format: .jsonc(trailingCommas: true), budget: budget) + guard let observation = try document.read(.init(keys: [])), + observation.projectionFailure == nil, + case .object(let fields) = observation.value + else { throw ImportReadFailure.invalid } + self.input = input + self.document = document + self.fields = fields + } catch NativeDocumentError.cancelled { + throw CancellationError() + } catch NativeDocumentError.invalidDocument(_, let range) { + throw ImportLocatedFailure( + location: .init( + document: input.document, pointer: "", + span: range.map { importSpan(bytes, document: input.document, range: $0) })) + } + } + func location(_ field: String? = nil) -> ImportLocation { + let region = NativeRegion(keys: field.map { [$0] } ?? []) + let range = (try? document.read(region))?.valueRange + return .init( + document: input.document, pointer: field.map { "/" + $0 } ?? "", + span: range.map { importSpan(document.bytes, document: input.document, range: $0) }) + } +} + +func importSpan(_ bytes: Data, document: String, range: Range) -> SourceSpan { + var line = 1 + var start = 0 + var index = 0 + let end = min(range.lowerBound, bytes.count) + while index < end { + if bytes[index] == 13 { + if index + 1 < end, bytes[index + 1] == 10 { index += 1 } + line += 1 + start = index + 1 + } else if bytes[index] == 10 { + line += 1 + start = index + 1 + } + index += 1 + } + return .init( + document: .init(document), start: end, end: min(range.upperBound, bytes.count), line: line, + column: end - start + 1) +} + +extension NativeValue { + var importString: String? { if case .string(let value) = self { value } else { nil } } + var importStrings: [String]? { + guard case .array(let values) = self, values.allSatisfy({ $0.importString != nil }) else { + return nil + } + return values.compactMap(\.importString) + } + var importObject: [String: NativeValue]? { + if case .object(let value) = self { value } else { nil } + } +} + +enum RulesyncConfigImport { + static func read( + _ input: SourceImportInput, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + try read(configs: [input], locks: [], limits: limits, into: &diagnostics) + } + + static func read( + configs: [SourceImportInput], locks: [SourceImportInput], limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + guard !configs.isEmpty, configs.count <= 2, + configs.allSatisfy({ $0.profile == .rulesyncConfig }), + locks.allSatisfy({ [.rulesyncSourcesV1, .rulesyncNpmV1].contains($0.profile) }) + else { throw ImportReadFailure.invalid } + var effective: [String: (NativeValue, ImportJSONC)] = [:] + for input in configs { + let parsed = try ImportJSONC(input, limits: limits) + if parsed.fields["inputRoot"] != nil && parsed.fields["inputRoots"] != nil { + diagnostics.add( + .invalidInput, parsed.location(), + "inputRoot and inputRoots cannot coexist in one producer config.") + return + } + if parsed.fields["targets"]?.importObject != nil && parsed.fields["features"] != nil { + diagnostics.add( + .invalidInput, parsed.location("features"), + "Object-form targets cannot be combined with features.") + return + } + for (key, value) in parsed.fields { effective[key] = (value, parsed) } + for (index, key) in parsed.fields.keys.sorted().enumerated() + where !["sources", "inputRoot", "inputRoots", "targets", "features"].contains(key) { + let location = parsed.location().appending("member[\(index)]") + if ImportInput.credentialField(key) { diagnostics.binding(location) } + unconverted(parsed.fields[key]!, at: location, into: &diagnostics) + } + } + for field in ["targets", "features"] { + guard let (value, parsed) = effective[field] else { continue } + if field == "targets", let values = value.importStrings, values.allSatisfy(ImportInput.name) { + diagnostics.proposal.selections.append( + .init( + origin: parsed.location(field), sourceAlias: nil, kind: .targets, values: values, + automatic: false, developmentOnly: false)) + } + unconverted(value, at: parsed.location(field), into: &diagnostics) + } + if effective["targets"]?.0.importObject != nil, effective["features"] != nil { + diagnostics.add( + .invalidInput, effective["features"]!.1.location("features"), + "Object-form targets cannot be combined with features.") + return + } + var entries: [(ImportOrderedSource, SourceDeclaration?, [String: NativeValue])] = [] + if let (value, parsed) = effective["sources"] { + guard case .array(let sources) = value else { throw ImportReadFailure.invalid } + for (index, source) in sources.enumerated() { + let location = parsed.location("sources").appending(String(index)) + guard let object = source.importObject, let raw = object["source"]?.importString, + !raw.isEmpty + else { + diagnostics.add(.invalidInput, location, "Expected a producer source entry.") + continue + } + for (ordinal, key) in object.keys.sorted().enumerated() + where ![ + "source", "skills", "rules", "transport", "ref", "path", "rulesPath", "registry", + "tokenEnv", + ].contains(key) { + unconverted( + object[key]!, at: location.appending("member[\(ordinal)]"), into: &diagnostics) + } + guard + ["transport", "ref", "path", "rulesPath", "registry", "tokenEnv"].allSatisfy({ + object[$0] == nil || object[$0]?.importString != nil + }) + else { + diagnostics.add( + .invalidInput, location, "Source fields require producer string identity.") + continue + } + if let selection = parsed.input.selection, !selection.contains(raw) { continue } + let transport = object["transport"]?.importString ?? "github" + guard ["github", "git", "npm"].contains(transport), + object["skills"] == nil || object["skills"]?.importStrings != nil, + object["rules"] == nil || object["rules"]?.importStrings != nil, + object["ref"] == nil || object["ref"]?.importString != nil + else { + diagnostics.add(.invalidInput, location, "Invalid source transport or selection.") + continue + } + if object["registry"] != nil || object["tokenEnv"] != nil { + guard transport == "npm" else { + diagnostics.add( + .invalidInput, location, "Registry bindings are npm-only producer fields.") + continue + } + if let registry = object["registry"]?.importString { + guard ImportInput.safeLocator(registry) else { + diagnostics.binding(location.appending("registry")) + continue + } + guard let url = URLComponents(string: registry), + ["http", "https"].contains(url.scheme), url.host?.isEmpty == false + else { + diagnostics.add( + .invalidInput, location, "Registry requires an explicit HTTP(S) locator.") + continue + } + } + if let token = object["tokenEnv"]?.importString { + guard token.range(of: #"^[A-Za-z_][A-Za-z0-9_]*$"#, options: .regularExpression) != nil + else { + diagnostics.add( + .invalidInput, location, + "Registry token binding requires an environment variable name.") + continue + } + diagnostics.binding(location.appending("tokenEnv"), environmentVariable: token) + } + } + var ref = object["ref"]?.importString + var sourcePath = object["path"]?.importString + var declaration: SourceDeclaration? + var identity = raw + if transport == "github" { + guard let github = githubLocator(raw) else { + diagnostics.add( + .unconverted, location, "Unsupported or ambiguous GitHub source selector.") + continue + } + ref = ref ?? github.ref + sourcePath = sourcePath ?? github.path + identity = raw + declaration = .init(kind: .git, location: github.location) + } else if transport == "git" { + guard ImportInput.safeLocator(raw) else { + diagnostics.binding(location) + continue + } + guard (try? SourceDeclaration(kind: .git, location: raw).transportIdentity()) != nil + else { + diagnostics.add(.invalidInput, location, "Invalid explicit Git source locator.") + continue + } + declaration = .init(kind: .git, location: raw) + } else { + guard + raw.range( + of: #"^(@[a-z0-9~][a-z0-9._~-]*/)?[a-z0-9~][a-z0-9._~-]*$"#, + options: .regularExpression) != nil + else { + diagnostics.add(.invalidInput, location, "Invalid npm source package selector.") + continue + } + diagnostics.add( + .unconverted, location, + "Experimental npm source requires locked archive and captured content.") + } + if let ref, + ref.hasPrefix("-") + || ref.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }) + { + diagnostics.add(.invalidInput, location, "Invalid requested producer ref.") + continue + } + let skillsPath = sourcePath ?? "skills" + let rulesPath = object["rulesPath"]?.importString ?? "rules" + guard !skillsPath.contains(".."), !rulesPath.contains(".."), + (try? ImportInput.path(skillsPath)) != nil, (try? ImportInput.path(rulesPath)) != nil + else { + diagnostics.add( + .unsafePath, location, "Source paths must remain within their repository.") + continue + } + let intent = ImportOrderedSource( + origin: location, alias: "rulesync-source-\(index)", identity: identity, + transport: transport, registry: object["registry"]?.importString, requestedRef: ref, + skillsPath: skillsPath, rulesPath: rulesPath, + skills: object["skills"]?.importStrings ?? (object["rules"] == nil ? ["*"] : nil), + rules: object["rules"]?.importStrings?.map { + $0.hasSuffix(".md") ? String($0.dropLast(3)) : $0 + }) + entries.append((intent, declaration, object)) + diagnostics.proposal.orderedSources.append(intent) + } + } + let keys = lockKeys(entries) + var locked: [String: (ImportedSource, [ImportResourceProposal], [String: Any])] = [:] + for lock in locks { + var request = lock + for (index, entry) in entries.enumerated() + where (entry.0.transport == "npm") == (lock.profile == .rulesyncNpmV1) { + if let declaration = entry.1 { request.sourceDeclarations[keys[index]] = declaration } + } + var result = ImportDiagnostics(proposal: .init(profile: lock.profile)) + let fields = try ImportInput.document(request, limits: limits) + try RulesyncSourceImport.read(fields, input: request, into: &result) + diagnostics.proposal.diagnostics += result.proposal.diagnostics + diagnostics.proposal.bindings += result.proposal.bindings + for source in result.proposal.sources where !source.alias.contains("-skill-") { + // Lookup uses exact producer lock coordinates; a normalized repository is not enough. + let map = fields["sources"] as? [String: Any] ?? [:] + let sorted = map.keys.sorted() + guard let ordinal = Int(source.alias.replacingOccurrences(of: "import-source-", with: "")), + ordinal < sorted.count + else { continue } + let key = (lock.profile == .rulesyncNpmV1 ? "npm:" : "git:") + sorted[ordinal] + if locked[key] != nil { + diagnostics.add(.ambiguousSource, source.origin, "Duplicate explicit lock identity.") + continue + } + locked[key] = ( + source, result.proposal.resources.filter { $0.sourceAlias == source.alias }, + map[sorted[ordinal]] as? [String: Any] ?? [:] + ) + } + } + let declaredKeys = Set( + entries.enumerated().map { + ($0.element.0.transport == "npm" ? "npm:" : "git:") + keys[$0.offset] + }) + for key in locked.keys.sorted() where !declaredKeys.contains(key) { + diagnostics.add( + .unconverted, locked[key]!.0.origin, + "Lock entry is absent from the effective ordered source config.") + } + var winners: Set = [] + for (index, entry) in entries.enumerated() { + let (intent, declaration, _) = entry + let key = (intent.transport == "npm" ? "npm:" : "git:") + keys[index] + var match = locked[key] + if let candidate = match { + let pathMatches = + (candidate.2["skillsPath"] as? String).map { + (try? ImportInput.path($0)) == (try? ImportInput.path(intent.skillsPath)) + } ?? true + let rulesMatch = + (candidate.2["rulesPath"] as? String).map { + (try? ImportInput.path($0)) == (try? ImportInput.path(intent.rulesPath)) + } ?? true + let refMatches = + intent.requestedRef == nil || intent.requestedRef == candidate.0.requestedRef + let registryMatches = + intent.registry == nil + || intent.registry?.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + == candidate.0.registry?.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + if !pathMatches || !rulesMatch || !refMatches || !registryMatches { + diagnostics.add( + .ambiguousSource, candidate.0.origin, + "Lock coordinates do not match the current ordered source declaration.") + match = nil + } + } + var exactDeclaration = declaration + if let commit = match?.0.pin.commit { exactDeclaration?.requirement = .revision(commit) } + diagnostics.proposal.sources.append( + .init( + alias: intent.alias, origin: intent.origin, declaration: exactDeclaration, + pin: match?.0.pin ?? .init(), requestedRef: intent.requestedRef, + producerPath: intent.skillsPath, producerIdentity: intent.identity, + registry: intent.registry ?? match?.0.registry, resolvedRef: match?.0.resolvedRef)) + if match == nil { + diagnostics.add( + .incompletePin, intent.origin, + "Ordered source has no matching explicitly supplied lock entry.") + } + for (resourceIndex, resource) in (match?.1 ?? []).enumerated() { + let kind = resource.kind == .instructions ? "rules" : "skills" + let selection = kind == "rules" ? intent.rules : intent.skills + guard selection == ["*"] || selection?.contains(resource.producerName) == true else { + diagnostics.add( + .unconverted, resource.origin, + "Locked artifact is outside the current explicit producer selection.") + continue + } + let collision = kind + ":" + resource.producerName + let selected = winners.insert(collision).inserted + if !selected { + diagnostics.add( + .unconverted, resource.origin, + "Earlier declared remote source wins this producer artifact collision.") + } + diagnostics.proposal.resources.append( + .init( + origin: resource.origin, sourceAlias: intent.alias, producerName: resource.producerName, + path: resource.path, producerIntegrity: resource.producerIntegrity, observedHash: nil, + executableFlags: [:], requiresStandaloneSource: true, kind: resource.kind, + selected: selected)) + if selected, resource.kind == .skills, let path = resource.path, var source = declaration { + let alias = intent.alias + "-skill-\(resourceIndex)" + source.path = path + source.requirement = match?.0.pin.commit.map(SourceRequirement.revision) + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: resource.origin, declaration: source, + pin: match?.0.pin ?? .init(), requestedRef: intent.requestedRef, producerPath: path, + producerIdentity: intent.identity)) + diagnostics.proposal.components.append( + .init( + origin: resource.origin, + declaration: .skills(source: alias, .init(select: .names([resource.producerName]))))) + } + } + } + let roots: [(String, SourceImportInput, ImportLocation)] + if let (value, parsed) = effective["inputRoots"] { + guard let values = value.importStrings, !values.isEmpty else { + throw ImportReadFailure.invalid + } + roots = values.enumerated().map { + ($0.element, parsed.input, parsed.location("inputRoots").appending(String($0.offset))) + } + } else if let (value, parsed) = effective["inputRoot"] { + guard let value = value.importString else { throw ImportReadFailure.invalid } + roots = [ + ( + value == "." ? ".rulesync" : value + "/.rulesync", parsed.input, + parsed.location("inputRoot") + ) + ] + } else { + roots = [ + ( + ".rulesync", configs[0], + .init(document: configs[0].document, pointer: "/inputRoots/default") + ) + ] + } + try localContent(roots, limits: limits, into: &diagnostics) + } + + private static func unconverted( + _ value: NativeValue, at location: ImportLocation, into diagnostics: inout ImportDiagnostics + ) { + diagnostics.add( + .unconverted, location, + "Producer configuration semantics are not canonical installation intent.") + if let text = value.importString, text.contains("://"), !ImportInput.safeLocator(text) { + diagnostics.binding(location) + } + if case .object(let fields) = value { + for (index, key) in fields.keys.sorted().enumerated() { + let child = location.appending("member[\(index)]") + if ImportInput.credentialField(key) { + diagnostics.binding(child) + } + unconverted(fields[key]!, at: child, into: &diagnostics) + } + } else if case .array(let values) = value { + for (index, item) in values.enumerated() { + unconverted(item, at: location.appending(String(index)), into: &diagnostics) + } + } + } + + private static func githubLocator(_ raw: String) -> ( + location: String, ref: String?, path: String? + )? { + guard !raw.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }), + !raw.contains("?"), !raw.contains("#") + else { return nil } + if raw.hasPrefix("http://") || raw.hasPrefix("https://") { + guard ImportInput.safeLocator(raw), let url = URLComponents(string: raw), + let host = url.host?.lowercased(), + ["github.com", "www.github.com", "gitlab.com", "www.gitlab.com"].contains(host) + else { return nil } + let parts = url.percentEncodedPath.split(separator: "/").map(String.init) + guard parts.count >= 2, parts.prefix(2).allSatisfy(ImportInput.name) else { return nil } + let repo = parts[1].hasSuffix(".git") ? String(parts[1].dropLast(4)) : parts[1] + let location = + "https://" + (host.contains("gitlab") ? "gitlab.com" : "github.com") + "/" + parts[0] + "/" + + repo + if parts.count > 2, ["tree", "blob"].contains(parts[2]) { + guard parts.count > 3, let ref = parts[3].removingPercentEncoding else { return nil } + let path = + parts.count > 4 ? parts.dropFirst(4).joined(separator: "/").removingPercentEncoding : nil + if parts.count > 4 && path == nil { return nil } + return (location, ref, path) + } + return (location, nil, nil) + } + var value = raw + var host = "github.com" + for provider in ["github", "gitlab"] where value.hasPrefix(provider + ":") { + host = provider + ".com" + value.removeFirst(provider.count + 1) + break + } + let pathParts = value.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false) + let refParts = pathParts[0].split( + separator: "@", maxSplits: 1, omittingEmptySubsequences: false) + let parts = refParts[0].split(separator: "/").map(String.init) + guard parts.count >= 2, + parts.allSatisfy({ $0.range(of: #"^[A-Za-z0-9._-]+$"#, options: .regularExpression) != nil }), + !value.contains("?"), + pathParts.count < 2 || !pathParts[1].isEmpty, refParts.count < 2 || !refParts[1].isEmpty + else { return nil } + return ( + "https://" + host + "/" + parts.joined(separator: "/"), + refParts.count == 2 ? String(refParts[1]) : nil, + pathParts.count == 2 ? String(pathParts[1]) : nil + ) + } + + private static func normalizedKey(_ value: String) -> String { + var result = value + for prefix in [ + "https://www.github.com/", "https://github.com/", "http://www.github.com/", + "http://github.com/", "https://www.gitlab.com/", "https://gitlab.com/", + "http://www.gitlab.com/", "http://gitlab.com/", + ] where result.lowercased().hasPrefix(prefix) { + result.removeFirst(prefix.count) + break + } + for prefix in ["github:", "gitlab:"] where result.hasPrefix(prefix) { + result.removeFirst(prefix.count) + break + } + while result.hasSuffix("/") { result.removeLast() } + if result.hasSuffix(".git") { result.removeLast(4) } + return result.lowercased() + } + private static func lockKeys( + _ entries: [(ImportOrderedSource, SourceDeclaration?, [String: NativeValue])] + ) -> [String] { + let bare = entries.map { normalizedKey($0.0.identity) } + var counts: [String: Int] = [:] + for (index, entry) in entries.enumerated() where entry.0.transport != "npm" { + counts[bare[index], default: 0] += 1 + } + var occurrences: [String: Int] = [:] + let allowed = CharacterSet( + charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~*'()/") + return entries.enumerated().map { index, entry in + guard entry.0.transport != "npm", counts[bare[index], default: 0] > 1 else { + return bare[index] + } + var qualifiers: [String] = [] + for field in ["path", "rulesPath", "ref"] { + guard var value = entry.2[field]?.importString else { continue } + if field != "ref" { value = (try? ImportInput.path(value)) ?? value } + qualifiers.append( + field + "=" + (value.addingPercentEncoding(withAllowedCharacters: allowed) ?? "")) + } + let base = bare[index] + (qualifiers.isEmpty ? "" : "#" + qualifiers.joined(separator: "&")) + occurrences[base, default: 0] += 1 + let occurrence = occurrences[base]! + return occurrence == 1 + ? base : base + (qualifiers.isEmpty ? "#" : "&") + "entry=\(occurrence)" + } + } + + private static func localContent( + _ roots: [(String, SourceImportInput, ImportLocation)], limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + struct Candidate { + let name: String + let path: String + let input: SourceImportInput + let origin: ImportLocation + let skill: Bool + } + var candidates: [String: Candidate] = [:] + var remaining = limits.resourceEntries + var seenRoots: Set = [] + for (rootIndex, root) in roots.enumerated() { + let (path, input, origin) = root + guard let relative = try? ImportInput.path(path) else { + diagnostics.add(.unsafePath, origin, "Input root must stay within its explicit boundary.") + continue + } + let view = try ImportInput.snapshot(input.root) + let directory = try view.resource(relative) + guard seenRoots.insert(directory.standardizedFileURL.path).inserted else { continue } + guard FileManager.default.fileExists(atPath: directory.path) else { + if rootIndex == 0 { + diagnostics.add(.missingResource, origin, "Primary rulesync input root is absent.") + } + continue + } + func children(_ path: String) throws -> [String] { + let file = try view.resource(path) + guard FileManager.default.fileExists(atPath: file.path) else { return [] } + guard + let iterator = FileManager.default.enumerator( + at: file, includingPropertiesForKeys: nil, options: [.skipsSubdirectoryDescendants]) + else { throw ImportReadFailure.invalid } + var values: [String] = [] + for case let entry as URL in iterator { + try Task.checkCancellation() + guard remaining > 0 else { throw ImportReadFailure.invalid } + remaining -= 1 + values.append(entry.lastPathComponent) + } + return values.sorted() + } + for (folder, skill) in [("skills", true), ("rules", false)] { + for curated in [true, false] { + let base = relative + "/" + folder + (curated ? "/.curated" : "") + for (ordinal, child) in try children(base).enumerated() where child != ".curated" { + let location = origin.appending( + "\(folder)/\(curated ? "curated" : "local")/member[\(ordinal)]") + guard ImportInput.name(child), skill || child.hasSuffix(".md") else { + diagnostics.add(.unconverted, location, "Unrecognized rulesync source artifact.") + continue + } + let itemPath = base + "/" + child + let file = try view.resource(itemPath) + let attributes = try FileManager.default.attributesOfItem(atPath: file.path) + guard attributes[.type] as? FileAttributeType == (skill ? .typeDirectory : .typeRegular) + else { + diagnostics.add( + .unsafePath, location, "Rulesync source artifact is not admitted regular content.") + continue + } + let name = skill ? child : String(child.dropLast(3)) + let key = folder + ":" + name + if let previous = candidates[key] { + diagnostics.add( + .unconverted, previous.origin, + "Producer precedence selects local over curated and later input roots over earlier roots." + ) + } + candidates[key] = Candidate( + name: name, path: itemPath, input: input, origin: location, skill: skill) + } + } + } + for (ordinal, child) in try children(relative).enumerated() + where !["skills", "rules"].contains(child) { + diagnostics.add( + .unconverted, origin.appending("member[\(ordinal)]"), + "Source tree item requires its producer component/native adapter.") + } + } + for (index, key) in candidates.keys.sorted().enumerated() { + let candidate = candidates[key]! + let alias = "rulesync-local-\(index)" + if candidate.skill { + do { + let content = try ImportSkillContent.read( + candidate.path, input: candidate.input, limits: limits) + diagnostics.proposal.diagnostics += content.diagnostics + diagnostics.proposal.bindings += content.bindings + for resourceIndex in diagnostics.proposal.resources.indices { + let resource = diagnostics.proposal.resources[resourceIndex] + if resource.selected, resource.producerName == candidate.name, + resource.kind == (candidate.skill ? .skills : .instructions) + { + diagnostics.proposal.resources[resourceIndex].selected = false + diagnostics.proposal.components.removeAll { $0.origin == resource.origin } + diagnostics.add( + .unconverted, resource.origin, + "Explicit local source content supersedes the remote curated artifact.") + } + } + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: candidate.origin, + declaration: .init( + kind: .local, location: candidate.path, + environment: .init( + projectDirectory: candidate.input.root, homeDirectory: candidate.input.root)), + pin: .init(), requestedRef: nil, producerPath: candidate.path)) + diagnostics.proposal.components.append( + .init( + origin: candidate.origin, + declaration: .skills( + source: alias, + .init(select: .names([content.skill.name]), condition: content.skill.condition)))) + diagnostics.proposal.resources.append( + .init( + origin: candidate.origin, sourceAlias: alias, producerName: candidate.name, path: ".", + producerIntegrity: nil, observedHash: content.hash, executableFlags: content.flags, + requiresStandaloneSource: true, kind: candidate.skill ? .skills : .instructions)) + } catch is CancellationError { throw CancellationError() } catch { + diagnostics.add( + .invalidInput, candidate.origin, + "Selected skill content is not admitted within the explicit source boundary.") + } + } else { + var request = candidate.input + request = .init(profile: request.profile, root: request.root, document: candidate.path) + let bytes = try ImportInput.bytes(request, limits: limits) + let semantics = try ImportFrontmatter.inspect( + bytes, document: candidate.path, converted: [], profile: .rulesyncConfig, limits: limits) + diagnostics.proposal.diagnostics += semantics.diagnostics + diagnostics.proposal.bindings += semantics.bindings + for resourceIndex in diagnostics.proposal.resources.indices { + let resource = diagnostics.proposal.resources[resourceIndex] + if resource.selected, resource.producerName == candidate.name, + resource.kind == (candidate.skill ? .skills : .instructions) + { + diagnostics.proposal.resources[resourceIndex].selected = false + diagnostics.proposal.components.removeAll { $0.origin == resource.origin } + diagnostics.add( + .unconverted, resource.origin, + "Explicit local source content supersedes the remote curated artifact.") + } + } + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: candidate.origin, + declaration: .init(kind: .local, location: candidate.input.root.path), pin: .init(), + requestedRef: nil, producerPath: nil)) + diagnostics.proposal.resources.append( + .init( + origin: candidate.origin, sourceAlias: alias, producerName: candidate.name, + path: candidate.path, producerIntegrity: nil, + observedHash: "sha256:" + FileHash.sha256Hex(data: bytes), executableFlags: [:], + requiresStandaloneSource: true, kind: candidate.skill ? .skills : .instructions)) + diagnostics.add( + .unconverted, candidate.origin, + "Rulesync rule frontmatter and generation semantics require explicit conversion before canonical instructions." + ) + } + } + } +} diff --git a/Sources/Components/Import/RulesyncSourceImport.swift b/Sources/Components/Import/RulesyncSourceImport.swift new file mode 100644 index 0000000..176de84 --- /dev/null +++ b/Sources/Components/Import/RulesyncSourceImport.swift @@ -0,0 +1,247 @@ +import AgentsCore +import Foundation + +enum RulesyncSourceImport { + static func read( + _ fields: [String: Any], input: SourceImportInput, into diagnostics: inout ImportDiagnostics + ) throws { + let origin = ImportLocation(document: input.document, pointer: "") + guard ImportInput.version(fields["lockfileVersion"], equals: 1) else { + diagnostics.add( + .unsupportedVersion, origin.appending("lockfileVersion"), "Expected lock version 1.") + return + } + diagnostics.unknown(fields, allowed: ["lockfileVersion", "sources"], at: origin) + guard let sources = fields["sources"] as? [String: Any] else { + diagnostics.add(.invalidInput, origin.appending("sources"), "Expected a source map.") + return + } + let npm = input.profile == .rulesyncNpmV1 + if npm { + diagnostics.add( + .unconverted, origin, "This npm source lock is an experimental producer format.") + } + for (index, key) in sources.keys.sorted().enumerated() { + try Task.checkCancellation() + guard input.selection?.contains(key) ?? true else { continue } + let location = origin.appending("sources/member[\(index)]") + guard let entry = sources[key] as? [String: Any] else { + diagnostics.add(.invalidInput, location, "Expected a locked source object.") + continue + } + diagnostics.unknown( + entry, + allowed: Set([ + "requestedRef", "resolvedRef", "requestedVersion", "resolvedVersion", "registry", + "integrity", "resolvedAt", "skills", "skillSelection", "skillsPath", "rules", + "ruleSelection", "rulesPath", "resolvedRuleNames", + ]).subtracting( + npm + ? ["requestedRef", "resolvedRef"] + : [ + "requestedVersion", "resolvedVersion", "registry", "integrity", + ]), at: location) + guard + diagnostics.typedFields( + entry, + strings: npm + ? [ + "requestedVersion", "resolvedVersion", "registry", "integrity", "resolvedAt", + "skillsPath", "rulesPath", + ] + : ["requestedRef", "resolvedRef", "resolvedAt", "skillsPath", "rulesPath"], + required: npm ? ["resolvedVersion"] : ["resolvedRef"], + arrays: ["skillSelection", "ruleSelection", "resolvedRuleNames"], at: location) + else { continue } + let commit = npm ? nil : ImportInput.hex(ImportInput.string(entry["resolvedRef"]), count: 40) + let version = npm ? ImportInput.string(entry["resolvedVersion"]) : nil + let integrity = npm ? sri(ImportInput.string(entry["integrity"])) : nil + let requested = ImportInput.string(entry[npm ? "requestedVersion" : "requestedRef"]) + if npm ? (!ImportInput.packageVersion(version) || integrity == nil) : commit == nil { + diagnostics.add( + .incompletePin, location, + npm + ? "Exact package version and tarball SRI are required for complete package provenance." + : "Only a full lowercase resolvedRef commit proves this Git pin.") + } + if let registry = ImportInput.string(entry["registry"]), !ImportInput.safeLocator(registry) { + diagnostics.binding(location.appending("registry")) + continue + } + let repository = key.components(separatedBy: "#")[0] + if npm, + key.range( + of: #"^(@[a-z0-9~][a-z0-9._~-]*/)?[a-z0-9~][a-z0-9._~-]*$"#, options: .regularExpression) + == nil + { + diagnostics.add(.invalidInput, location, "Expected an npm package name as source key.") + continue + } + if !npm, !ImportInput.safeLocator(repository) { + diagnostics.binding(location) + continue + } + if !npm, repository != key, input.sourceDeclarations[key] == nil { + diagnostics.add( + .unconverted, location, + "Qualified source-key selection requires its ordered producer config; only repository identity is retained." + ) + } + var source = input.sourceDeclarations[key] + if let declaration = source, !ImportInput.safeLocator(declaration.location) { + diagnostics.binding(location) + continue + } + if npm { + source = nil + diagnostics.add( + .unconverted, location, + "npm transport requires captured content before canonical source creation.") + } else if source == nil { + diagnostics.add( + .ambiguousSource, location, + "A normalized source lock key does not establish the original provider and transport; supply the source declaration." + ) + } else if source?.kind != .git { + diagnostics.add( + .invalidInput, location, "Git source locks require a Git source declaration.") + source = nil + } + if let commit, source != nil { source?.requirement = .revision(commit) } + let alias = "import-source-\(index)" + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: location, declaration: source, + pin: .init( + commit: commit, version: ImportInput.packageVersion(version) ? version : nil, + integrity: integrity), + requestedRef: requested, producerPath: nil, producerIdentity: npm ? key : repository, + registry: ImportInput.string(entry["registry"]), + resolvedRef: npm ? nil : ImportInput.string(entry["resolvedRef"]))) + for field in ["skillSelection", "ruleSelection", "resolvedRuleNames"] + where entry[field] != nil { + // Lock artifact maps are concrete resources, while selections describe producer intent. + diagnostics.add( + .unconverted, location.appending(field), + "Producer selection is not a canonical all-member declaration.") + } + try artifacts( + entry, field: "skills", pathField: "skillsPath", alias: alias, source: source, + location: location, into: &diagnostics) + if entry["rules"] != nil { + try artifacts( + entry, field: "rules", pathField: "rulesPath", alias: alias, source: source, + location: location, into: &diagnostics) + } + for field in ["resolvedAt"] where entry[field] != nil { + diagnostics.add( + .unconverted, location.appending(field), + "Producer resolution bookkeeping is not imported.") + } + } + if let selection = input.selection, !selection.isSubset(of: Set(sources.keys)) { + diagnostics.add( + .invalidInput, origin.appending("sources"), + "A selected source is absent from this document.") + } + } + + private static func artifacts( + _ entry: [String: Any], field: String, pathField: String, alias: String, + source: SourceDeclaration?, location: ImportLocation, into diagnostics: inout ImportDiagnostics + ) throws { + let location = location.appending(field) + guard let artifacts = entry[field] as? [String: Any] else { + diagnostics.add(.invalidInput, location, "Expected an artifact integrity map.") + return + } + let rawPath = ImportInput.string(entry[pathField]) ?? source?.path + let path: String? + do { path = try rawPath.map(ImportInput.path) } catch { + diagnostics.add( + .unsafePath, location, "Producer resource path must remain relative to its source.") + return + } + if path == nil { + diagnostics.add( + .unconverted, location, "Resource root is absent from this lock; supply its declared path.") + } + for (index, name) in artifacts.keys.sorted().enumerated() { + let item = location.appending("member[\(index)]") + guard ImportInput.name(name), let object = artifacts[name] as? [String: Any] else { + diagnostics.add(.invalidInput, item, "Expected a safe artifact name and integrity object.") + continue + } + diagnostics.unknown(object, allowed: ["integrity"], at: item) + let hash = ImportInput.string(object["integrity"]) + let integrity: ImportPin.Integrity? + if let hash, hash.hasPrefix("sha256-"), + ImportInput.hex(String(hash.dropFirst(7)), count: 64) != nil + { + integrity = .init(kind: .rulesyncSHA256, value: hash) + } else { + integrity = nil + diagnostics.add( + .incompletePin, item.appending("integrity"), + "Artifact SHA-256 integrity is missing or invalid.") + } + let selection = ImportInput.strings(entry["skillSelection"]) + let memberDirectory = selection.map { $0 == ["*"] || $0.count > 1 } ?? false + let resourcePath: String? + if let path, field == "rules" || memberDirectory { + let file = field == "rules" ? name + ".md" : name + resourcePath = path == "." ? file : path + "/" + file + } else { + resourcePath = nil + if path != nil { + diagnostics.add( + .unconverted, item, + "This selection can use producer root fallback; the lock does not prove the member resource path." + ) + } + } + diagnostics.proposal.resources.append( + .init( + origin: item, sourceAlias: alias, producerName: name, path: resourcePath, + producerIntegrity: integrity, observedHash: nil, executableFlags: [:], + requiresStandaloneSource: true, kind: field == "skills" ? .skills : .instructions)) + if field == "skills", let source, let resourcePath { + // Each resource root gets its own alias: canonical discovery paths belong to sources. + let itemAlias = alias + "-skill-\(index)" + var declaration = source + declaration.path = resourcePath + diagnostics.proposal.sources.append( + .init( + alias: itemAlias, origin: item, declaration: declaration, + pin: diagnostics.proposal.sources.first(where: { $0.alias == alias })!.pin, + requestedRef: diagnostics.proposal.sources.first(where: { $0.alias == alias })! + .requestedRef, + producerPath: resourcePath, + producerIdentity: diagnostics.proposal.sources.first(where: { $0.alias == alias })! + .producerIdentity)) + diagnostics.proposal.components.append( + .init( + origin: item, declaration: .skills(source: itemAlias, .init(select: .names([name]))))) + } else if field == "rules" { + diagnostics.add( + .unconverted, item, + "Rulesync rule frontmatter and targeting require semantic conversion before canonical instructions." + ) + } + } + } + + private static func sri(_ value: String?) -> ImportPin.Integrity? { + guard let value else { return nil } + let parts = value.split(separator: " ", omittingEmptySubsequences: true) + guard !parts.isEmpty else { return nil } + for part in parts { + let fields = part.split(separator: "-", maxSplits: 1) + guard fields.count == 2, + let size = ["sha256": 32, "sha384": 48, "sha512": 64][String(fields[0])], + let bytes = Data(base64Encoded: String(fields[1])), bytes.count == size + else { return nil } + } + return .init(kind: .npmSRI, value: value) + } +} diff --git a/Sources/Components/Import/SourceImport.swift b/Sources/Components/Import/SourceImport.swift new file mode 100644 index 0000000..5844194 --- /dev/null +++ b/Sources/Components/Import/SourceImport.swift @@ -0,0 +1,70 @@ +import AgentsCore +import AgentsManifest +import Foundation + +package enum SourceImport { + /// First explicit config is the project config; the optional second is its local override. + /// Each document retains its caller-selected boundary. No ambient config or lock is discovered. + package static func previewRulesync( + configs: [SourceImportInput], locks: [SourceImportInput] = [], + limits: SourceImportLimits = .init() + ) throws -> SourceImportProposal { + var diagnostics = ImportDiagnostics(proposal: .init(profile: .rulesyncConfig)) + do { + try RulesyncConfigImport.read( + configs: configs, locks: locks, limits: limits, into: &diagnostics) + } catch is CancellationError { throw CancellationError() } catch let failure + as ImportLocatedFailure + { + diagnostics.add(.invalidInput, failure.location, "Explicit JSONC input is not admitted.") + } catch CoreError.unsafePath { + diagnostics.add( + .unsafePath, .init(document: configs.first?.document ?? "", pointer: ""), + "Input path escapes its explicit root.") + } catch { + diagnostics.add( + .invalidInput, .init(document: configs.first?.document ?? "", pointer: ""), + "Explicit rulesync inputs are not admitted.") + } + return diagnostics.proposal + } + + /// Reads only the chosen local document and explicitly supplied content. No source resolution, + /// component execution, config discovery, ownership inference or filesystem write occurs here. + package static func preview( + _ input: SourceImportInput, limits: SourceImportLimits = .init() + ) throws -> SourceImportProposal { + try Task.checkCancellation() + let origin = ImportLocation(document: input.document, pointer: "") + var diagnostics = ImportDiagnostics(proposal: .init(profile: input.profile)) + do { + _ = try ImportInput.path(input.document) + switch input.profile { + case .apmManifest, .apmLock, .rulesyncGitHubV1, .rulesyncAPMV1: + try YAMLSourceImport.read(input, limits: limits, into: &diagnostics) + case .rulesyncConfig: + try RulesyncConfigImport.read(input, limits: limits, into: &diagnostics) + case .rulesyncSourcesV1, .rulesyncNpmV1: + try RulesyncSourceImport.read( + ImportInput.document(input, limits: limits), input: input, into: &diagnostics) + case .vercelProjectV2, .vercelUserV3: + try VercelSourceImport.read( + ImportInput.document(input, limits: limits), input: input, limits: limits, + into: &diagnostics) + } + } catch is CancellationError { throw CancellationError() } catch let failure as YAMLReadFailure + { + diagnostics.add( + .invalidInput, .init(document: input.document, pointer: "", span: failure.span), + "Input is not admitted YAML.") + } catch let failure as ImportLocatedFailure { + diagnostics.add(.invalidInput, failure.location, "Explicit JSONC input is not admitted.") + } catch CoreError.unsafePath { + diagnostics.add(.unsafePath, origin, "Input path escapes its explicit root.") + } catch { + diagnostics.add( + .invalidInput, origin, "Input is not an admitted, readable producer document.") + } + return diagnostics.proposal + } +} diff --git a/Sources/Components/Import/SourceImportProposal.swift b/Sources/Components/Import/SourceImportProposal.swift new file mode 100644 index 0000000..d953944 --- /dev/null +++ b/Sources/Components/Import/SourceImportProposal.swift @@ -0,0 +1,212 @@ +import AgentsCore +import Foundation + +/// Each profile describes one producer format at an inspected release, not a format guess. +package enum SourceImportProfile: String, Sendable { + case rulesyncSourcesV1, rulesyncNpmV1, vercelProjectV2, vercelUserV3 + case apmManifest, apmLock, rulesyncConfig, rulesyncGitHubV1, rulesyncAPMV1 + + package var specificationStatus: String { + switch self { + case .apmManifest, .apmLock: "APM working-draft profile; schema amendments are unratified" + default: "Pinned producer implementation format" + } + } + + package var producerRevision: String { + switch self { + case .rulesyncSourcesV1, .rulesyncNpmV1, .rulesyncConfig, .rulesyncGitHubV1, .rulesyncAPMV1: + "fbe4fe58334cab4e84b87f20d730d6450a35e0f7" + case .apmManifest, .apmLock: + "787a97cc52fbbcc344374e1567b2a1e5b8adf441" + case .vercelProjectV2, .vercelUserV3: + "e781cb4d07433dfe1d19e924ed45cc61738c55ec" + } + } +} + +package struct ImportLocation: Equatable, Sendable { + package let document: String + /// Object-map entries use sorted member ordinals, so credential-bearing keys are never echoed. + package let pointer: String + package var span: SourceSpan? = nil + + func appending(_ field: String) -> Self { + .init(document: document, pointer: pointer + "/" + field, span: span) + } +} + +package struct SourceImportDiagnostic: Equatable, Sendable { + package enum Code: String, Sendable { + case invalidInput, unsupportedVersion, unconverted, incompletePin, ambiguousSource + case unsafePath, credentialBinding, integrityMismatch, missingResource + } + package let code: Code + package let location: ImportLocation + /// Messages describe fields and semantics; they never interpolate imported values. + package let message: String +} + +package struct ImportBindingRequirement: Equatable, Sendable { + package let location: ImportLocation + package let reason: String + /// Symbolic producer binding only; the process environment is never read. + package var environmentVariable: String? = nil +} + +package struct ImportPin: Equatable, Sendable { + package enum IntegrityKind: String, Sendable { + case rulesyncSHA256, npmSRI, vercelInstalledSHA256, githubTree, apmDigest + } + package struct Integrity: Equatable, Sendable { + package let kind: IntegrityKind + package let value: String + + package init(kind: IntegrityKind, value: String) { + self.kind = kind + self.value = value + } + } + package var commit: String? + package var version: String? + package var integrity: Integrity? +} + +package struct ImportedSource: Equatable, Sendable { + package let alias: String + package let origin: ImportLocation + package let declaration: SourceDeclaration? + package let pin: ImportPin + package let requestedRef: String? + package let resolvedRef: String? + package let resolvedURL: String? + package let developmentOnly: Bool + package let producerPath: String? + package let producerIdentity: String? + package let registry: String? + + init( + alias: String, origin: ImportLocation, declaration: SourceDeclaration?, pin: ImportPin, + requestedRef: String?, producerPath: String?, producerIdentity: String? = nil, + registry: String? = nil, resolvedRef: String? = nil, resolvedURL: String? = nil, + developmentOnly: Bool = false + ) { + self.alias = alias + self.origin = origin + self.declaration = declaration + self.pin = pin + self.requestedRef = requestedRef + self.resolvedRef = resolvedRef + self.resolvedURL = resolvedURL + self.developmentOnly = developmentOnly + self.producerPath = producerPath + self.producerIdentity = producerIdentity + self.registry = registry + } +} + +package struct ImportedComponent: Equatable, Sendable { + package let origin: ImportLocation + package let declaration: ComponentDeclaration +} + +/// This is a preservation intention, not a retained object or an adoption receipt. E must freeze +/// independent authoring content before any target containing these bytes can be overwritten. +package struct ImportResourceProposal: Equatable, Sendable { + package let origin: ImportLocation + package let sourceAlias: String + package let producerName: String + /// Relative to the corresponding source root. Nil means exact producer coordinates are absent. + package let path: String? + package let producerIntegrity: ImportPin.Integrity? + package let observedHash: String? + package let executableFlags: [String: Bool] + package let requiresStandaloneSource: Bool + package var kind: DeclaredComponentKind? = nil + package var selected = true +} + +/// Canonical intent and evidence only. Raw documents and literal credentials never escape parsing. +/// Application, target ownership and adoption belong to the shared import lifecycle. +package struct SourceImportProposal: Equatable, Sendable { + package let profile: SourceImportProfile + package var sources: [ImportedSource] = [] + package var components: [ImportedComponent] = [] + package var resources: [ImportResourceProposal] = [] + package var diagnostics: [SourceImportDiagnostic] = [] + package var bindings: [ImportBindingRequirement] = [] + package var selections: [ImportProducerSelection] = [] + package var deployments: [ImportDeploymentEvidence] = [] + package var orderedSources: [ImportOrderedSource] = [] +} + +package struct SourceImportInput: Sendable { + package let profile: SourceImportProfile + /// Caller-selected read boundary. Consuming preparation owns source stability and freshness. + package let root: URL + package let document: String + /// Nil selects every entry; empty selects none. JSON maps use producer keys, YAML lists use + /// decimal ordinals, and rulesync config sources use their explicit source selector. + package var selection: Set? = nil + /// Source lock keys do not reliably identify a transport/provider. These are explicit input, + /// normally supplied by the config adapter, and never inferred from a normalized lock key. + package var sourceDeclarations: [String: SourceDeclaration] = [:] + /// Actual content is read only from these explicitly supplied, input-root-relative paths. + package var installedSkills: [String: String] = [:] + + package init( + profile: SourceImportProfile, root: URL, document: String, selection: Set? = nil, + sourceDeclarations: [String: SourceDeclaration] = [:], installedSkills: [String: String] = [:] + ) { + self.profile = profile + self.root = root + self.document = document + self.selection = selection + self.sourceDeclarations = sourceDeclarations + self.installedSkills = installedSkills + } +} + +package struct SourceImportLimits: Sendable { + package var documentBytes = 16 * 1024 * 1024 + package var nodes = 200_000 + package var depth = 64 + package var resourceBytes = 64 * 1024 * 1024 + package var resourceEntries = 20_000 + package init() {} +} + +/// Producer intent is retained independently of canonical installation conditions. +package struct ImportProducerSelection: Equatable, Sendable { + package enum Kind: String, Sendable { case includes, targets, skills, rules } + package let origin: ImportLocation + package let sourceAlias: String? + package let kind: Kind + package let values: [String] + package let automatic: Bool + package let developmentOnly: Bool +} + +/// These are third-party deployment claims, never canonical ownership or adoption receipts. +package struct ImportDeploymentEvidence: Equatable, Sendable { + package let origin: ImportLocation + package let sourceAlias: String? + package let agent: String? + package let scope: String? + package let installDirectory: String? + package let files: [String] +} + +/// Declaration order governs remote source collisions, independently of lock-map order. +package struct ImportOrderedSource: Equatable, Sendable { + package let origin: ImportLocation + package let alias: String + package let identity: String + package let transport: String + package let registry: String? + package let requestedRef: String? + package let skillsPath: String + package let rulesPath: String + package let skills: [String]? + package let rules: [String]? +} diff --git a/Sources/Components/Import/VercelSourceImport.swift b/Sources/Components/Import/VercelSourceImport.swift new file mode 100644 index 0000000..d2176f0 --- /dev/null +++ b/Sources/Components/Import/VercelSourceImport.swift @@ -0,0 +1,227 @@ +import AgentsCore +import Foundation + +enum VercelSourceImport { + static func read( + _ fields: [String: Any], input: SourceImportInput, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + let origin = ImportLocation(document: input.document, pointer: "") + let project = input.profile == .vercelProjectV2 + guard ImportInput.version(fields["version"], equals: project ? 2 : 3) else { + diagnostics.add( + .unsupportedVersion, origin.appending("version"), + "Lock version does not match the explicit profile.") + return + } + diagnostics.unknown( + fields, + allowed: project + ? ["version", "skills"] : ["version", "skills", "dismissed", "lastSelectedAgents"], + at: origin) + for field in ["dismissed", "lastSelectedAgents"] where fields[field] != nil { + diagnostics.add( + .unconverted, origin.appending(field), + "Global installer UI bookkeeping does not specify individual skill recipients.") + } + guard let skills = fields["skills"] as? [String: Any] else { + diagnostics.add(.invalidInput, origin.appending("skills"), "Expected a skill map.") + return + } + for (index, name) in skills.keys.sorted().enumerated() { + try Task.checkCancellation() + guard input.selection?.contains(name) ?? true else { continue } + let location = origin.appending("skills/member[\(index)]") + guard ImportInput.name(name), let entry = skills[name] as? [String: Any], + let source = ImportInput.string(entry["source"]), + let sourceType = ImportInput.string(entry["sourceType"]) + else { + diagnostics.add( + .invalidInput, location, "Expected a safe skill name, source and sourceType.") + continue + } + diagnostics.unknown( + entry, + allowed: project + ? [ + "source", "sourceType", "sourceUrl", "ref", "skillPath", "version", "via", + "computedHash", "subagents", "wellKnownDigest", "installMode", + ] + : [ + "source", "sourceType", "sourceUrl", "ref", "skillPath", "skillFolderHash", + "installedAt", "updatedAt", "pluginName", "sourceBaseUrl", "wellKnownDigest", + "installMode", + ], + at: location) + guard + diagnostics.typedFields( + entry, + strings: project + ? [ + "source", "sourceType", "sourceUrl", "ref", "skillPath", "version", "via", + "computedHash", "wellKnownDigest", "installMode", + ] + : [ + "source", "sourceType", "sourceUrl", "ref", "skillPath", "skillFolderHash", + "installedAt", "updatedAt", "pluginName", "sourceBaseUrl", "wellKnownDigest", + "installMode", + ], + required: project + ? ["source", "sourceType", "computedHash"] + : ["source", "sourceType", "sourceUrl", "skillFolderHash", "installedAt", "updatedAt"], + arrays: project ? ["subagents"] : [], at: location) + else { continue } + let sourceURL = ImportInput.string(entry["sourceUrl"]) + guard ImportInput.safeLocator(source), sourceURL.map(ImportInput.safeLocator) ?? project, + ImportInput.string(entry["sourceBaseUrl"]).map(ImportInput.safeLocator) ?? true + else { + diagnostics.binding(location.appending("sourceUrl")) + continue + } + let path: String? + do { path = try ImportInput.string(entry["skillPath"]).map(ImportInput.path) } catch { + diagnostics.add( + .unsafePath, location.appending("skillPath"), + "Skill path must remain inside the producer source.") + continue + } + if path == nil, input.installedSkills[name] == nil { + diagnostics.add( + .unconverted, location.appending("skillPath"), + "Original resource coordinates are absent; supply actual installed content for capture.") + } + let hashField = project ? "computedHash" : "skillFolderHash" + let hash = ImportInput.hex(ImportInput.string(entry[hashField]), count: project ? 64 : 40) + let integrity = hash.map { + ImportPin.Integrity(kind: project ? .vercelInstalledSHA256 : .githubTree, value: $0) + } + if integrity == nil { + diagnostics.add( + .incompletePin, location.appending(hashField), + "Producer content integrity is missing or invalid.") + } + // Neither release format persists a resolved repository commit. A full-looking hash in + // either integrity field or a requested ref cannot be promoted into that missing evidence. + diagnostics.add( + .incompletePin, location, + "This lock does not prove an exact upstream repository commit; no ref is fetched.") + let alias = "import-skill-\(index)" + let version = ImportInput.string(entry["version"]) + if version != nil, !ImportInput.packageVersion(version) { + diagnostics.add( + .incompletePin, location.appending("version"), + "Package version is not an exact semantic version.") + } + let upstream = canonicalSource(source: source, url: sourceURL, type: sourceType, path: path) + if upstream == nil { + diagnostics.add( + .unconverted, location.appending("sourceType"), + "Source transport cannot be represented as a canonical source without explicit content.") + } + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: location, declaration: upstream, + pin: .init( + commit: nil, version: ImportInput.packageVersion(version) ? version : nil, + integrity: integrity), + requestedRef: ImportInput.string(entry["ref"]), producerPath: path, + producerIdentity: source)) + for field in [ + "via", "subagents", "pluginName", "sourceBaseUrl", "wellKnownDigest", "installMode", + "installedAt", "updatedAt", + ] where entry[field] != nil { + diagnostics.add( + .unconverted, location.appending(field), + "Producer placement, source or bookkeeping semantics require an explicit import decision." + ) + } + if let local = input.installedSkills[name] { + do { + let captured = try ImportSkillContent.read(local, input: input, limits: limits) + diagnostics.proposal.diagnostics += captured.diagnostics + diagnostics.proposal.bindings += captured.bindings + if project, let hash, ImportSkillContent.vercelHash(captured) != hash { + diagnostics.add( + .integrityMismatch, location.appending(hashField), + "Explicit installed content does not match the recorded installed-files hash.") + continue + } + if !project { + diagnostics.add( + .unconverted, location.appending(hashField), + "Captured actual local content has a SHA-256 pin; the recorded GitHub tree hash is not verified." + ) + } + let contentAlias = alias + "-content" + diagnostics.proposal.sources.append( + .init( + alias: contentAlias, origin: location, + declaration: .init( + kind: .local, location: captured.path, + environment: .init(projectDirectory: input.root, homeDirectory: input.root)), + pin: .init(commit: nil, version: nil, integrity: nil), requestedRef: nil, + producerPath: nil)) + diagnostics.proposal.resources.append( + .init( + origin: location, sourceAlias: contentAlias, producerName: name, path: ".", + producerIntegrity: integrity, observedHash: captured.hash, + executableFlags: captured.flags, requiresStandaloneSource: true)) + diagnostics.proposal.components.append( + .init( + origin: location, + declaration: .skills( + source: contentAlias, + .init(select: .names([captured.skill.name]), condition: captured.skill.condition)))) + } catch is CancellationError { throw CancellationError() } catch CoreError.unsafePath { + diagnostics.add( + .unsafePath, location, "Explicit installed content escapes its input root.") + } catch { + diagnostics.add( + .missingResource, location, + "Explicit installed content is missing, unsafe, malformed or exceeds resource limits.") + } + } else if let upstream { + diagnostics.proposal.resources.append( + .init( + origin: location, sourceAlias: alias, producerName: name, path: upstream.path, + producerIntegrity: integrity, observedHash: nil, executableFlags: [:], + requiresStandaloneSource: true)) + diagnostics.proposal.components.append( + .init( + origin: location, declaration: .skills(source: alias, .init(select: .names([name]))))) + } + } + if let selection = input.selection, !selection.isSubset(of: Set(skills.keys)) { + diagnostics.add( + .invalidInput, origin.appending("skills"), "A selected skill is absent from this document.") + } + } + + private static func canonicalSource( + source: String, url: String?, type: String, path: String? + ) -> SourceDeclaration? { + let location: String + switch type { + case "github": + if let url { + location = url + } else { + let parts = source.split(separator: "/") + guard parts.count == 2, parts.allSatisfy({ ImportInput.name(String($0)) }) else { + return nil + } + location = "https://github.com/" + source + } + case "git": + guard let url else { return nil } + location = url + default: return nil + } + let directory = path.map { + $0.hasSuffix("/SKILL.md") ? String($0.dropLast(9)) : ($0 == "SKILL.md" ? "." : $0) + } + let declaration = SourceDeclaration(kind: .git, location: location, path: directory) + guard (try? declaration.transportIdentity()) != nil else { return nil } + return declaration + } +} diff --git a/Sources/Components/Import/YAMLSourceImport.swift b/Sources/Components/Import/YAMLSourceImport.swift new file mode 100644 index 0000000..9a35e3e --- /dev/null +++ b/Sources/Components/Import/YAMLSourceImport.swift @@ -0,0 +1,718 @@ +import AgentsCore +import AgentsManifest +import Foundation + +/// A view of the existing immutable YAML graph; no decoded dictionary or parallel value graph. +struct ImportYAML { + let reader: YAMLReader + let node: YAMLNode + let pointer: String + + var location: ImportLocation { + .init( + document: reader.span(of: node).document.rawValue, pointer: pointer, + span: reader.span(of: node)) + } + var string: String? { + guard let scalar = node.scalar, !scalar.decimalTag, + scalar.quoted || YAMLScalar.classify(scalar.text) == .string + else { return nil } + return scalar.text + } + var integer: Int? { + guard let scalar = node.scalar, !scalar.quoted, !scalar.decimalTag, + YAMLScalar.classify(scalar.text) == .integer + else { return nil } + return YAMLScalar.integer(scalar.text) + } + var boolean: Bool? { + guard let scalar = node.scalar, !scalar.quoted, !scalar.decimalTag, + YAMLScalar.classify(scalar.text) == .boolean + else { return nil } + return scalar.text.lowercased() == "true" + } + var pairs: [(String, ImportYAML)]? { + guard let pairs = node.pairs else { return nil } + var result: [(String, ImportYAML)] = [] + for (index, pair) in pairs.enumerated() { + let key = ImportYAML(reader: reader, node: pair.key, pointer: pointer) + guard let name = key.string else { return nil } + result.append( + (name, .init(reader: reader, node: pair.value, pointer: pointer + "/member[\(index)]"))) + } + return result + } + var items: [ImportYAML]? { + node.items?.enumerated().map { + .init(reader: reader, node: $0.element, pointer: pointer + "/\($0.offset)") + } + } + var strings: [String]? { + guard let items, items.allSatisfy({ $0.string != nil }) else { return nil } + return items.compactMap(\.string) + } + subscript(_ field: String) -> ImportYAML? { pairs?.first { $0.0 == field }?.1 } + + static func check(_ root: YAMLNode, limits: SourceImportLimits) throws { + var remaining = limits.nodes + func visit(_ node: YAMLNode, depth: Int) throws { + try Task.checkCancellation() + guard remaining > 0, depth <= limits.depth else { throw ImportReadFailure.invalid } + remaining -= 1 + for pair in node.pairs ?? [] { + try visit(pair.key, depth: depth + 1) + try visit(pair.value, depth: depth + 1) + } + for item in node.items ?? [] { try visit(item, depth: depth + 1) } + } + try visit(root, depth: 0) + } + + func validate( + strings: Set = [], required: Set = [], arrays: Set = [], + booleans: Set = [], integers: Set = [], + into diagnostics: inout ImportDiagnostics + ) -> Bool { + var valid = true + for field in strings.union(required).sorted() + where self[field] != nil || required.contains(field) { + if self[field]?.string == nil { + diagnostics.add( + .invalidInput, self[field]?.location ?? location, "Expected a producer string field.") + valid = false + } + } + for field in arrays.sorted() where self[field] != nil { + if self[field]?.strings == nil { + diagnostics.add( + .invalidInput, self[field]!.location, "Expected producer string selections.") + valid = false + } + } + for field in booleans.sorted() where self[field] != nil { + if self[field]?.boolean == nil { + diagnostics.add(.invalidInput, self[field]!.location, "Expected a producer boolean field.") + valid = false + } + } + for field in integers.sorted() where self[field] != nil { + if self[field]?.integer.map({ $0 >= 0 }) != true { + diagnostics.add( + .invalidInput, self[field]!.location, "Expected a nonnegative producer integer field.") + valid = false + } + } + return valid + } + + func unknown(_ allowed: Set, into diagnostics: inout ImportDiagnostics) { + for (name, value) in pairs ?? [] where !allowed.contains(name) { + if ImportInput.credentialField(name) { + diagnostics.binding(value.location) + } + value.unconverted(into: &diagnostics) + } + } + func unconverted(into diagnostics: inout ImportDiagnostics) { + diagnostics.add(.unconverted, location, "Producer field or item has no canonical conversion.") + // Literal connection fields are never retained, including inside an otherwise unsupported item. + if let value = string, value.contains("://"), !ImportInput.safeLocator(value) { + diagnostics.binding(location) + } + for (key, value) in pairs ?? [] { + if ImportInput.credentialField(key) { + diagnostics.binding(value.location) + } + value.unconverted(into: &diagnostics) + } + for value in items ?? [] { value.unconverted(into: &diagnostics) } + } +} + +enum YAMLSourceImport { + static func read( + _ input: SourceImportInput, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + var admission = limits + admission.documentBytes = min(limits.documentBytes, ManifestLimits.Input.bytes) + let bytes = try ImportInput.bytes(input, limits: admission) + let reader = try YAMLReader(bytes: Array(bytes), identity: .init(input.document)) + let root = ImportYAML(reader: reader, node: reader.root, pointer: "") + try ImportYAML.check(root.node, limits: limits) + guard root.pairs != nil else { + diagnostics.add(.invalidInput, root.location, "Expected a YAML mapping with string keys.") + return + } + switch input.profile { + case .apmManifest: try manifest(root, input: input, limits: limits, into: &diagnostics) + case .apmLock, .rulesyncAPMV1: try lock(root, input: input, into: &diagnostics) + case .rulesyncGitHubV1: try github(root, input: input, into: &diagnostics) + default: preconditionFailure("YAML profile dispatch") + } + guard !diagnostics.proposal.diagnostics.contains(where: { $0.code == .unsupportedVersion }) + else { return } + for (index, name) in input.installedSkills.keys.sorted().enumerated() { + let location = root.location.appending("explicitContent/member[\(index)]") + guard ImportInput.name(name), let path = input.installedSkills[name] else { + diagnostics.add(.invalidInput, location, "Invalid explicit installed skill selection.") + continue + } + do { + let content = try ImportSkillContent.read(path, input: input, limits: limits) + diagnostics.proposal.diagnostics += content.diagnostics + diagnostics.proposal.bindings += content.bindings + let alias = "yaml-content-\(index)" + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: location, + declaration: .init( + kind: .local, location: content.path, + environment: .init(projectDirectory: input.root, homeDirectory: input.root)), + pin: .init(), requestedRef: nil, producerPath: nil)) + diagnostics.proposal.resources.append( + .init( + origin: location, sourceAlias: alias, producerName: name, path: ".", + producerIntegrity: nil, observedHash: content.hash, executableFlags: content.flags, + requiresStandaloneSource: true, kind: .skills)) + diagnostics.proposal.components.append( + .init( + origin: location, + declaration: .skills( + source: alias, + .init(select: .names([content.skill.name]), condition: content.skill.condition)))) + diagnostics.add( + .unconverted, location, + "Actual explicitly selected local content is captured independently; it does not verify recovery of the producer's upstream commit." + ) + } catch is CancellationError { throw CancellationError() } catch CoreError.unsafePath { + diagnostics.add(.unsafePath, location, "Explicit content escapes its input root.") + } catch { + diagnostics.add( + .missingResource, location, + "Explicit installed skill content is missing, malformed or exceeds bounds.") + } + } + } + + private static func manifest( + _ root: ImportYAML, input: SourceImportInput, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + guard root["name"]?.string?.isEmpty == false, root["version"]?.string != nil else { + diagnostics.add( + .invalidInput, root.location, "APM manifest requires string name and version.") + return + } + if let schema = root["$schema"] { + let admitted = [ + "https://microsoft.github.io/apm/specs/schemas/manifest-v0.1.schema.json", + "https://microsoft.github.io/apm/specs/schemas/manifest-v0.1.48.schema.json", + ] + guard let identity = schema.string, admitted.contains(identity) else { + diagnostics.add(.unsupportedVersion, schema.location, "Unsupported APM schema identity.") + return + } + } + for field in ["name", "version"] { root[field]!.unconverted(into: &diagnostics) } + root.unknown( + [ + "$schema", "name", "version", "target", "targets", "includes", "dependencies", + "devDependencies", + ], into: &diagnostics) + if root["target"] != nil && root["targets"] != nil { + diagnostics.add( + .invalidInput, root.location, "APM target and targets are mutually exclusive.") + return + } + if let targets = root["targets"] ?? root["target"] { + selection( + targets, kind: .targets, scalar: true, alias: nil, development: false, into: &diagnostics) + } + if let includes = root["includes"] { + if includes.string == "auto" { + diagnostics.proposal.selections.append( + .init( + origin: includes.location, sourceAlias: nil, kind: .includes, values: [], + automatic: true, developmentOnly: false)) + } else { + selection( + includes, kind: .includes, scalar: false, alias: nil, development: false, + into: &diagnostics) + } + } + for group in ["dependencies", "devDependencies"] { + guard let block = root[group] else { continue } + guard block.pairs != nil else { + diagnostics.add(.invalidInput, block.location, "Expected an APM dependency mapping.") + continue + } + block.unknown(["apm"], into: &diagnostics) + guard let apm = block["apm"] else { continue } + guard let items = apm.items else { + diagnostics.add(.invalidInput, apm.location, "Expected an APM dependency list.") + continue + } + for (index, item) in items.enumerated() { + try Task.checkCancellation() + let alias = "apm-\(group)-\(index)" + guard input.selection?.contains(String(index)) ?? true else { continue } + let development = group == "devDependencies" + let raw: String + var requested: String? + var path: String? + var local = false + var registry = false + if let value = item.string { + raw = value + local = + value.hasPrefix("./") || value.hasPrefix("../") || value.hasPrefix("/") + || value.hasPrefix("~") + } else if item.pairs != nil { + guard + item.validate( + strings: ["git", "path", "ref", "version", "id", "registry", "alias"], + arrays: ["skills", "targets"], into: &diagnostics) + else { continue } + item.unknown( + ["git", "path", "ref", "version", "id", "registry", "alias", "skills", "targets"], + into: &diagnostics) + guard let value = item["git"]?.string ?? item["id"]?.string ?? item["path"]?.string else { + diagnostics.add( + .invalidInput, item.location, "APM dependency has no admitted source selector.") + continue + } + raw = value + registry = item["id"] != nil || item["registry"] != nil + if item["git"] != nil && registry { + diagnostics.add( + .invalidInput, item.location, "Conflicting APM dependency source selectors.") + continue + } + local = item["git"] == nil && !registry + requested = item["ref"]?.string ?? item["version"]?.string + if item["git"] != nil { path = item["path"]?.string } + for (field, kind) in [ + ("skills", ImportProducerSelection.Kind.skills), ("targets", .targets), + ] { + if let value = item[field] { + selection( + value, kind: kind, scalar: false, alias: alias, development: development, + into: &diagnostics) + } + } + if let value = item["alias"] { value.unconverted(into: &diagnostics) } + if item["ref"] != nil, let value = item["version"] { + value.unconverted(into: &diagnostics) + } + } else { + diagnostics.add( + .invalidInput, item.location, "Expected an APM dependency string or mapping.") + continue + } + let defaultRegistry = root["registries"]?["default"]?.string != nil + let explicitGit = item["git"] != nil || raw.contains("://") || raw.hasPrefix("git@") + if registry || (!local && !explicitGit && (defaultRegistry || root["default_host"] != nil)) + { + diagnostics.add( + .unconverted, item.location, + "Registry or host-dependent resolution needs explicit locked coordinates; no resolver or user defaults are consulted." + ) + diagnostics.add( + .incompletePin, item.location, "Manifest dependency is not a resolved source pin.") + continue + } + let declaration: SourceDeclaration? + let locator: String + if local { + do { + let relative = try ImportInput.path(raw) + let base = (input.document as NSString).deletingLastPathComponent + let joined = base.isEmpty ? relative : base + "/" + relative + _ = try ImportInput.snapshot(input.root).resource(joined) + locator = joined + declaration = .init( + kind: .local, location: input.root.appendingPathComponent(joined).path) + } catch { + diagnostics.add( + .unsafePath, item.location, + "Local APM source must be explicitly readable within its input root.") + continue + } + } else { + guard let parsed = gitLocator(raw, explicitPath: path, requested: requested) else { + if !ImportInput.safeLocator(raw.components(separatedBy: "#")[0]) { + diagnostics.binding(item.location) + } + diagnostics.add( + .unconverted, item.location, + "Source coordinates are ambiguous or require producer resolution.") + continue + } + locator = parsed.location + path = parsed.path + requested = parsed.ref + declaration = .init(kind: .git, location: locator, path: path) + } + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: item.location, declaration: declaration, pin: .init(), + requestedRef: requested, producerPath: path, producerIdentity: locator, + developmentOnly: development)) + diagnostics.proposal.resources.append( + .init( + origin: item.location, sourceAlias: alias, producerName: "package", path: path ?? ".", + producerIntegrity: nil, observedHash: nil, executableFlags: [:], + requiresStandaloneSource: true)) + diagnostics.add( + .incompletePin, item.location, + "Manifest intent requires a resolved lock commit or explicitly captured installed content." + ) + diagnostics.add( + .unconverted, item.location, + "APM package primitives require content inspection before canonical component conversion." + ) + } + } + try APMPackageContentImport.read( + input: input, origin: root.location.appending("localContent"), limits: limits, + into: &diagnostics) + } + + private static func selection( + _ value: ImportYAML, kind: ImportProducerSelection.Kind, scalar: Bool, alias: String?, + development: Bool, into diagnostics: inout ImportDiagnostics + ) { + guard let values = value.strings ?? (scalar ? value.string.map { [$0] } : nil) else { + diagnostics.add(.invalidInput, value.location, "Expected producer selection strings.") + return + } + if kind == .includes, values.contains(where: { (try? ImportInput.path($0)) == nil }) { + diagnostics.add( + .unsafePath, value.location, "Includes must remain within the package source.") + return + } + if kind == .targets { + let admitted: Set = [ + "all", "copilot", "vscode", "claude", "grok-build", "cursor", "opencode", "codex", "gemini", + "antigravity", "windsurf", "kiro", "agent-skills", "hermes", "grok-bot", "grok-cloud", + "openclaw", "copilot-cowork", "copilot-app", + ] + guard !values.isEmpty, values.allSatisfy(admitted.contains) else { + diagnostics.add(.invalidInput, value.location, "Unsupported APM producer target.") + return + } + } + diagnostics.proposal.selections.append( + .init( + origin: value.location, sourceAlias: alias, kind: kind, values: values, automatic: false, + developmentOnly: development)) + diagnostics.add( + .unconverted, value.location, + "Producer selection is retained independently of canonical installation scope.") + } + + /// Only syntactically unambiguous GitHub shorthand and explicit clone coordinates are converted. + static func gitLocator(_ value: String, explicitPath: String? = nil, requested: String? = nil) + -> (location: String, path: String?, ref: String?)? + { + let pieces = value.split(separator: "#", maxSplits: 1, omittingEmptySubsequences: false) + guard let base = pieces.first.map(String.init), !base.isEmpty, ImportInput.safeLocator(base), + base != "parent" + else { return nil } + let ref = requested ?? (pieces.count == 2 ? String(pieces[1]) : nil) + if let ref, + ref.isEmpty || ref.hasPrefix("-") + || ref.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }) + { + return nil + } + var path = explicitPath + let location: String + if base.contains("://") || base.hasPrefix("git@") { + guard (try? SourceDeclaration(kind: .git, location: base).transportIdentity()) != nil else { + return nil + } + location = base + } else { + let parts = base.split(separator: "/").map(String.init) + guard parts.count >= 2, !parts[0].contains(":"), !parts[0].contains("."), + parts.allSatisfy(ImportInput.name) + else { return nil } + location = "https://github.com/" + parts[0] + "/" + parts[1] + if parts.count > 2 { + guard explicitPath == nil else { return nil } + path = parts.dropFirst(2).joined(separator: "/") + } + } + if let path, (try? ImportInput.path(path)) == nil { return nil } + return (location, path, ref) + } + + private static func lock( + _ root: ImportYAML, input: SourceImportInput, into diagnostics: inout ImportDiagnostics + ) throws { + let mirror = input.profile == .rulesyncAPMV1 + guard let version = root["lockfile_version"]?.string, + (mirror ? ["1"] : ["1", "2"]).contains(version) + else { + diagnostics.add( + .unsupportedVersion, root["lockfile_version"]?.location ?? root.location, + "Unsupported producer YAML lock version.") + return + } + guard + root.validate( + strings: ["generated_at", "apm_version"], + required: mirror ? ["generated_at", "apm_version"] : [], into: &diagnostics) + else { return } + root.unknown( + ["lockfile_version", "dependencies", "generated_at", "apm_version"], into: &diagnostics) + guard let items = root["dependencies"]?.items else { + diagnostics.add(.invalidInput, root.location, "Expected locked dependencies.") + return + } + for (index, item) in items.enumerated() { + try Task.checkCancellation() + guard input.selection?.contains(String(index)) ?? true else { continue } + guard item.pairs != nil, let repo = item["repo_url"]?.string else { + diagnostics.add(.invalidInput, item.location, "Expected a locked repository entry.") + continue + } + let common: Set = [ + "repo_url", "resolved_commit", "resolved_ref", "version", "depth", "resolved_by", + "package_type", "content_hash", "is_dev", "deployed_files", "source", "local_path", + "virtual_path", "is_virtual", + ] + item.unknown( + mirror + ? common + : common.union([ + "resolved_url", "resolved_hash", "tree_sha256", "constraint", "resolved_tag", + "skill_subset", + ]), into: &diagnostics) + guard + item.validate( + strings: common.subtracting(["depth", "is_dev", "deployed_files", "is_virtual"]).union( + mirror + ? [] : ["resolved_url", "resolved_hash", "tree_sha256", "constraint", "resolved_tag"]), + required: mirror ? ["repo_url", "package_type"] : ["repo_url"], + arrays: mirror ? ["deployed_files"] : ["deployed_files", "skill_subset"], + booleans: ["is_dev", "is_virtual"], integers: ["depth"], into: &diagnostics) + else { continue } + if mirror, item["depth"]?.integer == nil || item["deployed_files"]?.strings == nil { + diagnostics.add( + .invalidInput, item.location, "Rulesync APM mirror requires depth and deployed files.") + continue + } + guard ImportInput.safeLocator(repo) else { + diagnostics.binding(item.location) + continue + } + let commit = ImportInput.hex(item["resolved_commit"]?.string, count: 40) + let sourceKind = item["source"]?.string + if let sourceKind, !["local", "registry"].contains(sourceKind) { + diagnostics.add( + .unconverted, item["source"]!.location, + "Unknown producer source transport cannot establish a canonical Git source.") + continue + } + let registry = sourceKind == "registry" + let local = sourceKind == "local" + let alias = "apm-lock-\(index)" + var declaration: SourceDeclaration? + var path = item["virtual_path"]?.string + if let value = path, (try? ImportInput.path(value)) == nil { + diagnostics.add( + .unsafePath, item.location, "Virtual package path must remain relative to its source.") + path = nil + } else if !registry && !local, let parsed = gitLocator(repo, explicitPath: path) { + declaration = .init( + kind: .git, location: parsed.location, requirement: commit.map { .revision($0) }, + path: path) + } + let digestField = + registry && !mirror + ? "resolved_hash" : !mirror && item["tree_sha256"] != nil ? "tree_sha256" : "content_hash" + let integrity = + mirror ? rulesyncDigest(item[digestField]?.string) : digest(item[digestField]?.string) + var resolvedURL: String? + if registry, !mirror { + if let locator = item["resolved_url"]?.string { + if ImportInput.safeLocator(locator) { + resolvedURL = locator + } else { + diagnostics.binding(item["resolved_url"]!.location) + } + } + diagnostics.add( + .unconverted, item.location, + "Registry archive source requires explicit content capture; no Git revision is inferred.") + } else if local { + diagnostics.add( + .unconverted, item.location, + "Local lock paths require explicit source/content selection; deployment coordinates are not authoring sources." + ) + } + if registry + ? (integrity == nil || resolvedURL == nil + || !ImportInput.packageVersion(item["version"]?.string)) : commit == nil + { + diagnostics.add( + .incompletePin, item.location, + "Locked source lacks a complete exact pin for its transport.") + } + if item[digestField] != nil && integrity == nil { + diagnostics.add( + .unconverted, item[digestField]!.location, + "Producer content hash is not a recognized digest envelope.") + } + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: item.location, declaration: declaration, + pin: .init( + commit: registry || local ? nil : commit, + version: ImportInput.packageVersion(item["version"]?.string) + ? item["version"]?.string : nil, integrity: integrity), + requestedRef: item["constraint"]?.string, producerPath: path, producerIdentity: repo, + registry: nil, resolvedRef: item["resolved_ref"]?.string, resolvedURL: resolvedURL, + developmentOnly: item["is_dev"]?.boolean == true)) + diagnostics.proposal.resources.append( + .init( + origin: item.location, sourceAlias: alias, producerName: "package", path: path, + producerIntegrity: integrity, observedHash: nil, executableFlags: [:], + requiresStandaloneSource: true)) + if let files = item["deployed_files"] { + deployment(files, alias: alias, agent: nil, scope: nil, directory: nil, into: &diagnostics) + } + for field in [ + "resolved_by", "package_type", "depth", "is_dev", "local_path", "is_virtual", + "resolved_tag", "version", + ] where item[field] != nil { item[field]!.unconverted(into: &diagnostics) } + if let skills = item["skill_subset"] { + selection( + skills, kind: .skills, scalar: false, alias: alias, + development: item["is_dev"]?.boolean == true, into: &diagnostics) + } + diagnostics.add( + .unconverted, item.location, + "Lock provenance does not establish package component content or native ownership.") + } + } + + private static func github( + _ root: ImportYAML, input: SourceImportInput, into diagnostics: inout ImportDiagnostics + ) throws { + guard root["lockfile_version"]?.string == "1" else { + diagnostics.add( + .unsupportedVersion, root.location, "Expected rulesync GitHub deployment lock version 1.") + return + } + guard root.validate(required: ["generated_at"], into: &diagnostics) else { return } + root.unknown(["lockfile_version", "generated_at", "installations"], into: &diagnostics) + guard let items = root["installations"]?.items else { + diagnostics.add(.invalidInput, root.location, "Expected GitHub deployment installations.") + return + } + for (index, item) in items.enumerated() { + try Task.checkCancellation() + guard input.selection?.contains(String(index)) ?? true else { continue } + item.unknown( + [ + "source", "owner", "repo", "agent", "scope", "skill", "requested_ref", "resolved_ref", + "resolved_commit", "install_dir", "deployed_files", "content_hash", + ], into: &diagnostics) + guard + item.validate( + strings: ["requested_ref", "content_hash"], + required: [ + "source", "owner", "repo", "agent", "scope", "skill", "resolved_ref", "resolved_commit", + "install_dir", + ], arrays: ["deployed_files"], into: &diagnostics), item["deployed_files"]?.strings != nil + else { continue } + guard let owner = item["owner"]?.string, let repo = item["repo"]?.string, + let source = item["source"]?.string, + source.lowercased() == (owner + "/" + repo).lowercased(), + ImportInput.name(owner), ImportInput.name(repo), let name = item["skill"]?.string, + ImportInput.name(name), + let agent = item["agent"]?.string, ImportInput.name(agent), + let scope = item["scope"]?.string, ["project", "user"].contains(scope) + else { + diagnostics.add( + .invalidInput, item.location, "Invalid GitHub source, skill or deployment coordinates.") + continue + } + let commit = ImportInput.hex(item["resolved_commit"]?.string, count: 40) + if commit == nil { + diagnostics.add( + .incompletePin, item.location, "GitHub deployment lacks a full resolved commit.") + } + if item["content_hash"] != nil && rulesyncDigest(item["content_hash"]?.string) == nil { + diagnostics.add( + .unconverted, item["content_hash"]!.location, + "Producer content hash is not a recognized rulesync SHA-256 envelope.") + } + let alias = "rulesync-gh-\(index)" + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: item.location, + declaration: .init( + kind: .git, location: "https://github.com/" + owner + "/" + repo, + requirement: commit.map { .revision($0) }), + pin: .init(commit: commit, integrity: rulesyncDigest(item["content_hash"]?.string)), + requestedRef: item["requested_ref"]?.string, producerPath: nil, producerIdentity: source, + resolvedRef: item["resolved_ref"]?.string)) + diagnostics.proposal.resources.append( + .init( + origin: item.location, sourceAlias: alias, producerName: name, path: nil, + producerIntegrity: rulesyncDigest(item["content_hash"]?.string), observedHash: nil, + executableFlags: [:], requiresStandaloneSource: true)) + if let files = item["deployed_files"] { + deployment( + files, alias: alias, agent: agent, scope: scope, directory: item["install_dir"]?.string, + into: &diagnostics) + } + diagnostics.add( + .unconverted, item.location, + "Deployment lock has no source skill path; target and scope are evidence, not canonical installation conditions or ownership." + ) + } + } + + private static func deployment( + _ files: ImportYAML, alias: String, agent: String?, scope: String?, directory: String?, + into diagnostics: inout ImportDiagnostics + ) { + guard let paths = files.strings, paths.allSatisfy({ (try? ImportInput.path($0)) != nil }), + directory.map({ (try? ImportInput.path($0)) != nil }) ?? true + else { + diagnostics.add( + .unsafePath, files.location, + "Deployment paths are outside the bounded relative-path profile; no ownership is inferred.") + return + } + diagnostics.proposal.deployments.append( + .init( + origin: files.location, sourceAlias: alias, agent: agent, scope: scope, + installDirectory: directory, files: paths)) + } + + private static func rulesyncDigest(_ value: String?) -> ImportPin.Integrity? { + guard let value, value.hasPrefix("sha256:"), + ImportInput.hex(String(value.dropFirst(7)), count: 64) != nil + else { return nil } + return .init(kind: .rulesyncSHA256, value: value) + } + + static func digest(_ value: String?) -> ImportPin.Integrity? { + guard let value else { return nil } + let parts = value.split(separator: ":", maxSplits: 1).map(String.init) + if parts.count == 1, ImportInput.hex(value, count: 64) != nil { + return .init(kind: .apmDigest, value: value) + } + guard parts.count == 2, let count = ["sha256": 64, "sha384": 96, "sha512": 128][parts[0]], + ImportInput.hex(parts[1], count: count) != nil + else { return nil } + return .init(kind: .apmDigest, value: value) + } +} diff --git a/Tests/AgentsManifestTests/YAMLReaderTests.swift b/Tests/AgentsManifestTests/YAMLReaderTests.swift new file mode 100644 index 0000000..d29809d --- /dev/null +++ b/Tests/AgentsManifestTests/YAMLReaderTests.swift @@ -0,0 +1,49 @@ +import AgentsCore +import AgentsManifest +import Testing + +struct YAMLReaderTests { + @Test func readerRetainsOrderedDataAndYAML12ScalarIdentity() throws { + let reader = try YAMLReader( + bytes: Array( + "name: on\r\nquoted: 'true'\r\nflag: true\r\nnumber: 0x10\r\né: [one, two]\r\n".utf8), + identity: .init("producer.yml")) + let pairs = try #require(reader.root.pairs) + #expect(pairs.map { $0.key.text } == ["name", "quoted", "flag", "number", "é"]) + #expect(pairs[0].value.scalar?.text == "on") + #expect(pairs[0].value.scalar?.quoted == false) + #expect(pairs[1].value.scalar?.text == "true") + #expect(pairs[1].value.scalar?.quoted == true) + #expect(YAMLScalar.classify("on") == .string) + #expect(YAMLScalar.classify("true") == .boolean) + #expect(YAMLScalar.integer("0x10") == 16) + #expect(pairs[4].value.items?.compactMap(\.text) == ["one", "two"]) + let span = reader.span(of: pairs[4].value) + #expect(span.document == .init("producer.yml")) + #expect(span.line == 5) + #expect(span.column == 5) + #expect( + Array("name: on\r\nquoted: 'true'\r\nflag: true\r\nnumber: 0x10\r\né: ".utf8).count + == span.start) + } + + @Test(arguments: [ + "token: secret-sentinel\n\"\\u0074oken\": secret-sentinel\n", + "token: secret-sentinel\ntoken: secret-sentinel\n", + "token: &secret-sentinel value\nother: *secret-sentinel\n", + "token: !secret-sentinel value\n", + "true: secret-sentinel\n", + ]) + func readerRefusesUnsupportedOrAmbiguousDataWithValueFreeLocatedFailure(_ text: String) throws { + do { + _ = try YAMLReader(bytes: Array(text.utf8), identity: .init("chosen.yml")) + Issue.record("Expected YAML admission failure") + } catch let failure as YAMLReadFailure { + #expect(failure.span.document == .init("chosen.yml")) + #expect(failure.span.line >= 1) + #expect(failure.span.start <= text.utf8.count) + #expect(!String(reflecting: failure).contains("secret-sentinel")) + #expect(failure.description == "YAML input is not admitted.") + } + } +} diff --git a/Tests/ComponentsTests/ImportPinnedFixtures.swift b/Tests/ComponentsTests/ImportPinnedFixtures.swift new file mode 100644 index 0000000..969550e --- /dev/null +++ b/Tests/ComponentsTests/ImportPinnedFixtures.swift @@ -0,0 +1,114 @@ +// Exact sample data from the pinned producer releases. No fixture command is executed. +enum ImportPinnedFixtures { + // https://github.com/microsoft/apm/blob/787a97cc52fbbcc344374e1567b2a1e5b8adf441/apm.yml + static let apmManifest = #""" + name: apm + version: 0.10.0 + description: APM (Agent Package Manager) -- ship and govern AI agent context + includes: auto + author: Microsoft + license: Apache-2.0 + + # Pinned so every contributor's `apm install` deploys the same tree this + # repo commits (.github/ plus .agents/skills/ via skills convergence), + # instead of auto-detecting whichever harness their machine signals. + # Contributors on another harness opt in with `apm install --target `. + targets: + - copilot + + # Local-path manifest deps on the extracted skill packages. + # Each was INLINE in .apm/skills/ until the v2 extraction. + # Extraction unlocks consumer reuse of each primitive standalone + # (consumers can install just a panel for single-PR review / single- + # issue triage, or an orchestrator entrypoint which transitively + # pulls its engine + panels). + # + # User-facing schedulers are declared here. Workers arrive + # transitively: + # - autopilot-issue-triage-scheduler -> autopilot-issue-triage-worker + # - autopilot-issue-delivery-scheduler -> autopilot-issue-delivery-worker + # - autopilot-pr-triage-scheduler -> autopilot-pr-triage-worker + # - autopilot-pr-review-scheduler -> autopilot-pr-review-worker + # - autopilot-pr-merge-worker is summoned by name (never by + # the PR review scheduler) + dependencies: + apm: + - ./packages/autopilot/autopilot-issue-triage-scheduler + - ./packages/autopilot/autopilot-issue-delivery-scheduler + - ./packages/autopilot/autopilot-pr-triage-scheduler + - ./packages/autopilot/autopilot-pr-review-scheduler + - ./packages/autopilot/autopilot-pr-merge-worker + mcp: [] + + scripts: {} + """# + "\n" + // https://github.com/dyoshikawa/rulesync/blob/fbe4fe58334cab4e84b87f20d730d6450a35e0f7/rulesync.jsonc + static let rulesyncConfig = #""" + { + "$schema": "https://github.com/dyoshikawa/rulesync/releases/latest/download/config-schema.json", + + // Per-target features using the new object form on `targets`. + // See docs/guide/configuration.md for details. + "targets": { + "copilot": { + "rules": { + "ruleDiscoveryMode": "explicit", + "includeLocalRoot": false + }, + "commands": true, + "mcp": false, + "subagents": true, + "skills": true, + "hooks": true + }, + "claudecode": { + "rules": true, + "commands": true, + "mcp": true, + "subagents": true, + "skills": true, + "hooks": true + }, + "opencode": { + "rules": true, + "commands": true, + "mcp": true, + "subagents": true, + "skills": true, + "hooks": true + }, + "codexcli": { + "rules": true, + "commands": false, + "mcp": false, + "subagents": true, + "skills": true, + "hooks": false, + "permissions": true + }, + "takt": { + "rules": true, + "commands": true, + "subagents": true, + "skills": true + } + }, + + // Output root directory or directories for generation. + "outputRoots": ["."], + + // Delete existing files before generating + "delete": true, + "verbose": true, + "silent": false, + + "simulateCommands": true, + "simulateSubagents": true, + "simulateSkills": true, + + // When true (default), `rulesync gitignore` only emits entries for the + // tools listed in `targets`. + "gitignoreTargetsOnly": false + } + """# + "\n" +} diff --git a/Tests/ComponentsTests/ImportProfileTests.swift b/Tests/ComponentsTests/ImportProfileTests.swift new file mode 100644 index 0000000..a1f5188 --- /dev/null +++ b/Tests/ComponentsTests/ImportProfileTests.swift @@ -0,0 +1,540 @@ +import AgentsCore +import Components +import Foundation +import Testing + +struct ImportProfileTests { + @Test func pinnedProducerSamplesRemainReadOnlyAndReportUnconvertedSemantics() throws { + let fixture = try ImportProfileFixture() + #expect( + FileHash.sha256Hex(data: Data(ImportPinnedFixtures.apmManifest.utf8)) + == "66261774fac336a23e4521fde39fb822e606527e32a0de8144993710bf4ce726") + #expect( + FileHash.sha256Hex(data: Data(ImportPinnedFixtures.rulesyncConfig.utf8)) + == "68c1da2097de1f81408cf08eac0f033cdf8c793d75d2e340cb10113b2f652fb7") + try fixture.write("apm.yml", ImportPinnedFixtures.apmManifest) + try fixture.write("rulesync.jsonc", ImportPinnedFixtures.rulesyncConfig) + try fixture.directory(".rulesync") + let before = try fixture.hash() + let apm = try SourceImport.preview(fixture.input(.apmManifest, "apm.yml")) + let rulesync = try SourceImport.preview(fixture.input(.rulesyncConfig, "rulesync.jsonc")) + #expect(try fixture.hash() == before) + #expect(apm.sources.count == 5) + #expect(apm.selections.first?.values == ["copilot"]) + #expect(apm.selections.last?.automatic == true) + #expect(apm.diagnostics.contains { $0.code == .incompletePin }) + #expect(!rulesync.diagnostics.contains { $0.code == .invalidInput }) + #expect(rulesync.diagnostics.contains { $0.code == .unconverted }) + #expect(rulesync.components.isEmpty) + } + + @Test func apmCompositionNeedsMatchingCoordinatesAndCapturesExplicitContentHonestly() throws { + let fixture = try ImportProfileFixture() + try fixture.write( + "apm.yml", + "name: fixture\nversion: '1.0.0'\ndependencies:\n apm:\n - git: https://github.com/acme/repo\n path: exports\n ref: main\n" + ) + try fixture.write( + "apm.lock.yaml", + "lockfile_version: '1'\ndependencies:\n - repo_url: https://github.com/acme/repo\n virtual_path: exports\n resolved_ref: main\n resolved_commit: \(String(repeating: "a", count: 40))\n" + ) + let result = try SourceImport.previewAPM( + manifest: fixture.input(.apmManifest, "apm.yml"), + lock: fixture.input(.apmLock, "apm.lock.yaml")) + #expect(result.sources[0].pin.commit == String(repeating: "a", count: 40)) + #expect(result.sources[0].requestedRef == "main") + #expect( + result.sources[0].declaration?.requirement == .revision(String(repeating: "a", count: 40))) + #expect( + !result.diagnostics.contains { + $0.code == .incompletePin && $0.location.document == "apm.yml" + }) + try fixture.write( + "apm.yml", + "name: fixture\nversion: '1.0.0'\ndependencies:\n apm:\n - git: https://github.com/acme/repo\n path: exports\n ref: changed\n" + ) + let mismatch = try SourceImport.previewAPM( + manifest: fixture.input(.apmManifest, "apm.yml"), + lock: fixture.input(.apmLock, "apm.lock.yaml")) + #expect(mismatch.sources[0].pin.commit == nil) + #expect(mismatch.diagnostics.contains { $0.code == .ambiguousSource }) + try fixture.write( + "installed/review/SKILL.md", + "---\nname: review\ndescription: fixture\nx-unknown: value\nenv: {TOKEN: secret-sentinel}\n---\nactual installed bytes\n" + ) + var input = fixture.input(.apmLock, "apm.lock.yaml") + input.installedSkills = ["review": "installed/review"] + let before = try fixture.hash() + let captured = try SourceImport.preview(input) + #expect(try fixture.hash() == before) + #expect(captured.resources.last?.observedHash?.hasPrefix("sha256:") == true) + #expect(captured.resources.last?.requiresStandaloneSource == true) + #expect(captured.components.count == 1) + #expect(captured.sources.last?.pin.commit == nil) + #expect(!captured.bindings.isEmpty) + #expect(!String(reflecting: captured).contains("secret-sentinel")) + } + + @Test func apmNativeSkillLayoutDoesNotGuessPluginFallbackOrTreatIncludesAsScope() throws { + let fixture = try ImportProfileFixture() + try fixture.write( + "apm.yml", + "name: fixture\nversion: '1.0.0'\nincludes: [.apm/instructions]\ntargets: [codex]\n") + try fixture.write( + ".apm/skills/review/SKILL.md", + "---\nname: review\ndescription: fixture\n---\nactual source bytes\n") + try fixture.write( + ".apm/instructions/review.instructions.md", "---\ndescription: review\n---\nbody\n") + try fixture.write( + "skills/fallback/SKILL.md", + "---\nname: fallback\ndescription: fixture\n---\nunselected plugin-native bytes\n") + let before = try fixture.hash() + let result = try SourceImport.preview(fixture.input(.apmManifest, "apm.yml")) + #expect(try fixture.hash() == before) + #expect(result.components.count == 1) + #expect(result.resources.first?.producerName == "review") + #expect(result.resources.first?.observedHash?.hasPrefix("sha256:") == true) + #expect(result.resources.first?.requiresStandaloneSource == true) + #expect(result.sources.first?.declaration?.location == ".apm/skills/review") + #expect( + result.diagnostics.contains { + $0.code == .unconverted && $0.location.pointer.contains("layout") + }) + #expect(result.selections.first?.values == ["codex"]) + #expect(result.selections.last?.values == [".apm/instructions"]) + } + + @Test func apmManifestPreservesIntentAndRefPrecedenceWithoutPinsOrScopeGuessing() throws { + let fixture = try ImportProfileFixture() + try fixture.write( + "apm.yml", + """ + name: on + version: '1.2.3' + targets: [claude, codex] + includes: [docs, .apm/skills] + dependencies: + apm: + - git: https://github.com/acme/repo + ref: main + version: old-version + path: packages/review + skills: [review] + targets: [claude] + x-extra: not-retained + mcp: + - name: private + env: + TOKEN: secret-sentinel + scripts: + start: never-execute-sentinel + devDependencies: + apm: [acme/dev#v2] + x-extension: secret-sentinel + """) + let before = try fixture.hash() + let proposal = try SourceImport.preview(fixture.input(.apmManifest, "apm.yml")) + #expect(try fixture.hash() == before) + #expect(proposal.sources.count == 2) + #expect(proposal.sources[0].requestedRef == "main") + #expect(proposal.sources[0].declaration?.location == "https://github.com/acme/repo") + #expect(proposal.sources[0].declaration?.path == "packages/review") + #expect(proposal.sources.allSatisfy { $0.pin.commit == nil }) + #expect(proposal.components.isEmpty) + #expect(proposal.resources.allSatisfy { $0.requiresStandaloneSource }) + #expect(proposal.selections.map(\.kind) == [.targets, .includes, .skills, .targets]) + #expect(!proposal.bindings.isEmpty) + #expect(proposal.diagnostics.contains { $0.location.span?.line == 22 }) + #expect(!String(reflecting: proposal).contains("secret-sentinel")) + #expect(!String(reflecting: proposal).contains("never-execute-sentinel")) + #expect(proposal.profile.specificationStatus.contains("unratified")) + } + + @Test func apmLocksKeepGitCommitRegistryIntegrityAndResolvedRefDistinct() throws { + let fixture = try ImportProfileFixture() + try fixture.write( + "apm.lock.yaml", + """ + lockfile_version: '2' + apm_version: '0.35.1' + dependencies: + - repo_url: https://github.com/acme/repo + resolved_commit: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + resolved_ref: moving-branch + version: '1.2.3' + virtual_path: packages/review + deployed_files: [.agents/skills/review/SKILL.md] + tree_sha256: sha256:\(String(repeating: "b", count: 64)) + - repo_url: acme/archive + source: registry + version: '2.0.0' + resolved_url: https://registry.example/archive.tgz + resolved_hash: sha512:\(String(repeating: "c", count: 128)) + - repo_url: https://github.com/acme/unlocked + resolved_ref: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + local_deployed_files: [.agents/skills/local/SKILL.md] + mcp_configs: + hidden: + headers: {Authorization: secret-sentinel} + """) + let before = try fixture.hash() + let proposal = try SourceImport.preview(fixture.input(.apmLock, "apm.lock.yaml")) + #expect(try fixture.hash() == before) + #expect(proposal.sources.count == 3) + #expect(proposal.sources[0].pin.commit == String(repeating: "a", count: 40)) + #expect(proposal.sources[0].resolvedRef == "moving-branch") + #expect(proposal.sources[0].pin.integrity?.kind == .apmDigest) + #expect(proposal.sources[1].pin.commit == nil) + #expect( + proposal.sources[1].pin.integrity?.value == "sha512:" + String(repeating: "c", count: 128)) + #expect(proposal.sources[1].resolvedURL == "https://registry.example/archive.tgz") + #expect(proposal.sources[2].pin.commit == nil) + #expect(proposal.deployments.first?.files == [".agents/skills/review/SKILL.md"]) + #expect(proposal.components.isEmpty) + #expect(!proposal.bindings.isEmpty) + #expect(!String(reflecting: proposal).contains("secret-sentinel")) + } + + @Test func rulesyncYAMLLocksAreDistinctAndDeploymentsDoNotInventSkillSourcePaths() throws { + let fixture = try ImportProfileFixture() + try fixture.write( + "gh.yml", + """ + lockfile_version: '1' + generated_at: '2026-01-01' + installations: + - source: acme/repo + owner: acme + repo: repo + agent: codex + scope: user + skill: review + requested_ref: main + resolved_ref: main + resolved_commit: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + install_dir: .agents/skills/review + deployed_files: [.agents/skills/review/SKILL.md] + content_hash: sha256:\(String(repeating: "b", count: 64)) + new_field: hidden + """) + let gh = try SourceImport.preview(fixture.input(.rulesyncGitHubV1, "gh.yml")) + #expect(gh.sources.first?.pin.commit == String(repeating: "a", count: 40)) + #expect(gh.sources.first?.requestedRef == "main") + #expect(gh.sources.first?.pin.integrity?.kind == .rulesyncSHA256) + #expect(gh.resources.first?.path == nil) + #expect(gh.deployments.first?.scope == "user") + #expect(gh.deployments.first?.agent == "codex") + #expect(gh.components.isEmpty) + #expect(gh.diagnostics.contains { $0.code == .unconverted }) + try fixture.write( + "mirror.yml", + """ + lockfile_version: '1' + generated_at: '2026-01-01' + apm_version: rulesync-compat + dependencies: + - repo_url: https://github.com/acme/repo + resolved_ref: main + depth: 1 + package_type: apm_package + content_hash: arbitrary-producer-string + deployed_files: [] + """) + let mirror = try SourceImport.preview(fixture.input(.rulesyncAPMV1, "mirror.yml")) + #expect(mirror.sources.first?.pin.commit == nil) + #expect(mirror.sources.first?.pin.integrity == nil) + #expect(mirror.sources.first?.resolvedRef == "main") + #expect(mirror.diagnostics.contains { $0.code == .incompletePin }) + #expect(mirror.profile.producerRevision != SourceImportProfile.apmLock.producerRevision) + #expect(!String(reflecting: mirror).contains("arbitrary-producer-string")) + } + + @Test(arguments: ["3", "true", "1"]) + func yamlLockVersionUsesStringIdentityAndRefusesCandidates(_ version: String) throws { + let fixture = try ImportProfileFixture() + try fixture.write("lock.yml", "lockfile_version: \(version)\ndependencies: []\n") + let result = try SourceImport.preview(fixture.input(.apmLock, "lock.yml")) + #expect(result.sources.isEmpty) + #expect(result.diagnostics.first?.code == .unsupportedVersion) + #expect(result.diagnostics.first?.location.span?.line == 1) + } + + @Test func yamlAdmissionLocationsAndLimitsAreValueFree() throws { + let fixture = try ImportProfileFixture() + try fixture.write("bad.yml", "name: secret-sentinel\nname: secret-sentinel\n") + let result = try SourceImport.preview(fixture.input(.apmManifest, "bad.yml")) + #expect(result.diagnostics.first?.code == .invalidInput) + #expect(result.diagnostics.first?.location.span != nil) + #expect(!String(reflecting: result).contains("secret-sentinel")) + try fixture.write("deep.yml", "name: a\nversion: '1.0.0'\nx-extra: [[[[[deep]]]]]\n") + var limits = SourceImportLimits() + limits.depth = 3 + let bounded = try SourceImport.preview(fixture.input(.apmManifest, "deep.yml"), limits: limits) + #expect(bounded.sources.isEmpty) + #expect(bounded.diagnostics.last?.code == .invalidInput) + } + + @Test func configJSONCPreservesBytesAndLocalOverrideDoesNotMergeSourceArrays() throws { + let fixture = try ImportProfileFixture() + try fixture.write( + "rulesync.jsonc", + """ + // Explicit project config; no init-template discovery. + {"sources":[{"source":"acme/base"}], "inputRoots":["primary"], + "targets":["codex"], "features":["skills"],} + """) + try fixture.write( + "local.jsonc", + """ + {"sources":[{"source":"gitlab:acme/local@release:export", "skills":["*"]}], + "inputRoot":"legacy", "targets":["claudecode"]} + """) + try fixture.directory("primary") + let before = try fixture.hash() + let result = try SourceImport.previewRulesync(configs: [ + fixture.input(.rulesyncConfig, "rulesync.jsonc"), + fixture.input(.rulesyncConfig, "local.jsonc"), + ]) + #expect(try fixture.hash() == before) + #expect(result.orderedSources.count == 1) + #expect(result.orderedSources[0].identity == "gitlab:acme/local@release:export") + #expect(result.orderedSources[0].requestedRef == "release") + #expect(result.orderedSources[0].skillsPath == "export") + #expect(result.sources[0].declaration?.location == "https://gitlab.com/acme/local") + #expect(result.selections.first?.values == ["claudecode"]) + #expect(!result.diagnostics.contains { $0.code == .missingResource }) + } + + @Test func remoteSourceOrderWinsIndependentlyOfSortedLockOrder() throws { + let fixture = try ImportProfileFixture() + try fixture.directory(".rulesync") + try fixture.write( + "rulesync.jsonc", + """ + {"sources":[{"source":"z/first"},{"source":"a/last"}]} + """) + try fixture.write( + "rulesync.lock", + """ + {"lockfileVersion":1,"sources":{ + "a/last":{"resolvedRef":"\(String(repeating: "a", count: 40))","skillsPath":"skills","skillSelection":["*"],"skills":{"review":{"integrity":"sha256-\(String(repeating: "b", count: 64))"}}}, + "z/first":{"resolvedRef":"\(String(repeating: "c", count: 40))","skillsPath":"skills","skillSelection":["*"],"skills":{"review":{"integrity":"sha256-\(String(repeating: "d", count: 64))"}}}}} + """) + let before = try fixture.hash() + let result = try SourceImport.previewRulesync( + configs: [fixture.input(.rulesyncConfig, "rulesync.jsonc")], + locks: [fixture.input(.rulesyncSourcesV1, "rulesync.lock")]) + #expect(try fixture.hash() == before) + #expect( + result.sources.filter { !$0.alias.contains("-skill-") }.map(\.pin.commit) == [ + String(repeating: "c", count: 40), String(repeating: "a", count: 40), + ]) + #expect(result.resources.map(\.selected) == [true, false]) + #expect(result.components.count == 1) + #expect( + result.components.first?.declaration + == .skills(source: "rulesync-source-0-skill-0", .init(select: .names(["review"])))) + #expect(result.resources.map(\.sourceAlias) == ["rulesync-source-0", "rulesync-source-1"]) + #expect(result.resources.allSatisfy { $0.requiresStandaloneSource }) + } + + @Test func npmConfigRetainsRegistryAndSymbolicBindingWithoutConsultingEnvironment() throws { + let fixture = try ImportProfileFixture() + try fixture.directory(".rulesync") + try fixture.write( + "config.jsonc", + "{\"sources\":[{\"source\":\"@acme/pkg\",\"transport\":\"npm\",\"ref\":\"latest\",\"registry\":\"https://registry.example\",\"tokenEnv\":\"IMPORT_PRIVATE_TOKEN\"}]}" + ) + let result = try SourceImport.preview(fixture.input(.rulesyncConfig, "config.jsonc")) + #expect(result.orderedSources.first?.registry == "https://registry.example") + #expect(result.sources.first?.registry == "https://registry.example") + #expect(result.sources.first?.requestedRef == "latest") + #expect(result.bindings.first?.environmentVariable == "IMPORT_PRIVATE_TOKEN") + #expect(result.sources.first?.pin.commit == nil) + #expect(result.sources.first?.pin.version == nil) + #expect(result.diagnostics.contains { $0.code == .incompletePin }) + #expect(result.components.isEmpty) + } + + @Test func repeatedRepositoryQualifiersUseExplicitConfigFieldsAndOccurrenceOrder() throws { + let fixture = try ImportProfileFixture() + try fixture.directory(".rulesync") + try fixture.write( + "config.jsonc", + """ + {"sources":[{"source":"acme/repo", "path":"skills/a", "ref":"team/release"}, + {"source":"acme/repo", "path":"skills/a", "ref":"team/release"}]} + """) + let hash = String(repeating: "a", count: 40) + try fixture.write( + "lock.json", + """ + {"lockfileVersion":1,"sources":{ + "acme/repo#path=skills/a&ref=team/release":{"requestedRef":"team/release","resolvedRef":"\(hash)","skillsPath":"skills/a","skills":{}}, + "acme/repo#path=skills/a&ref=team/release&entry=2":{"requestedRef":"team/release","resolvedRef":"\(hash)","skillsPath":"skills/a","skills":{}}}} + """) + let result = try SourceImport.previewRulesync( + configs: [fixture.input(.rulesyncConfig, "config.jsonc")], + locks: [fixture.input(.rulesyncSourcesV1, "lock.json")]) + #expect(result.sources.count == 2) + #expect(result.sources.allSatisfy { $0.pin.commit == hash }) + #expect( + !result.diagnostics.contains { $0.code == .ambiguousSource || $0.code == .incompletePin }) + } + + @Test func staleLockAndExplicitEmptySelectionsCannotBroadenCurrentSourceIntent() throws { + let fixture = try ImportProfileFixture() + try fixture.directory(".rulesync") + try fixture.write( + "config.jsonc", "{\"sources\":[{\"source\":\"acme/repo\",\"ref\":\"new\",\"skills\":[]}]}") + try fixture.write( + "lock.json", + "{\"lockfileVersion\":1,\"sources\":{\"acme/repo\":{\"requestedRef\":\"old\",\"resolvedRef\":\"\(String(repeating: "a", count: 40))\",\"skillsPath\":\"skills\",\"skillSelection\":[\"*\"],\"skills\":{\"review\":{\"integrity\":\"sha256-\(String(repeating: "b", count: 64))\"}}}}}" + ) + let stale = try SourceImport.previewRulesync( + configs: [fixture.input(.rulesyncConfig, "config.jsonc")], + locks: [fixture.input(.rulesyncSourcesV1, "lock.json")]) + #expect(stale.sources.first?.pin.commit == nil) + #expect(stale.resources.isEmpty) + #expect(stale.components.isEmpty) + #expect(stale.diagnostics.contains { $0.code == .ambiguousSource }) + try fixture.write( + "config.jsonc", "{\"sources\":[{\"source\":\"acme/repo\",\"ref\":\"old\",\"skills\":[]}]}") + let empty = try SourceImport.previewRulesync( + configs: [fixture.input(.rulesyncConfig, "config.jsonc")], + locks: [fixture.input(.rulesyncSourcesV1, "lock.json")]) + #expect(empty.sources.first?.pin.commit == String(repeating: "a", count: 40)) + #expect(empty.resources.isEmpty) + #expect(empty.components.isEmpty) + #expect(empty.orderedSources.first?.skills == []) + } + + @Test func nativeInputConflictsAndYAMLCredentialLocatorsStayExplicit() throws { + let fixture = try ImportProfileFixture() + try fixture.write("bad.jsonc", "{\"targets\":{},\"features\":[]}") + let conflict = try SourceImport.preview(fixture.input(.rulesyncConfig, "bad.jsonc")) + #expect(conflict.diagnostics.last?.code == .invalidInput) + #expect(conflict.diagnostics.last?.location.span?.line == 1) + try fixture.write( + "bad.yml", + "lockfile_version: '2'\ndependencies:\n - repo_url: acme/archive\n source: registry\n version: '1.0.0'\n resolved_hash: sha256:\(String(repeating: "a", count: 64))\n resolved_url: https://user:secret-sentinel@registry.example/archive\n" + ) + let secret = try SourceImport.preview(fixture.input(.apmLock, "bad.yml")) + #expect(secret.sources.first?.resolvedURL == nil) + #expect(!secret.bindings.isEmpty) + #expect(secret.diagnostics.contains { $0.code == .incompletePin }) + #expect(!String(reflecting: secret).contains("secret-sentinel")) + try fixture.write("bad.yml", "lockfile_version: '3'\ndependencies: []\n") + try fixture.write( + "installed/review/SKILL.md", "---\nname: review\ndescription: fixture\n---\nprivate\n") + var request = fixture.input(.apmLock, "bad.yml") + request.installedSkills = ["review": "installed/review"] + let unsupported = try SourceImport.preview(request) + #expect(unsupported.resources.isEmpty) + #expect(unsupported.components.isEmpty) + } + + @Test func localCuratedAndInputRootCollisionsSelectActualContent() throws { + let fixture = try ImportProfileFixture() + try fixture.write("config.jsonc", "{\"inputRoots\":[\"one\",\"two\"]}") + for (path, body) in [ + ("one/skills/.curated/review/SKILL.md", "curated-one"), + ("one/skills/review/SKILL.md", "local-one"), + ("two/skills/.curated/review/SKILL.md", "curated-two"), + ("two/skills/review/SKILL.md", "local-two"), + ("one/rules/.curated/overview.md", "curated-rule"), + ("one/rules/overview.md", "local-rule"), + ] { try fixture.write(path, "---\nname: review\ndescription: fixture\n---\n\(body)\n") } + let before = try fixture.hash() + let result = try SourceImport.preview(fixture.input(.rulesyncConfig, "config.jsonc")) + #expect(try fixture.hash() == before) + #expect(result.resources.count == 2) + let skill = try #require(result.resources.first { $0.kind == .skills }) + #expect(skill.path == ".") + #expect(skill.observedHash != nil) + #expect(result.sources.last?.declaration?.location == "two/skills/review") + #expect(result.components.count == 1) + #expect(result.diagnostics.filter { $0.message.contains("precedence") }.count == 4) + } + + @Test func unknownSecretFieldsAndJSONCDuplicatesCannotEscape() throws { + let fixture = try ImportProfileFixture() + try fixture.write("config.jsonc", "{\"future\":{\"env\":{\"TOKEN\":\"secret-sentinel\"}}}") + let result = try SourceImport.preview(fixture.input(.rulesyncConfig, "config.jsonc")) + #expect(!result.bindings.isEmpty) + #expect(!String(reflecting: result).contains("secret-sentinel")) + try fixture.write("duplicate.jsonc", "{\"sources\":[], /* keep */ \"\\u0073ources\":[]}") + let duplicate = try SourceImport.preview(fixture.input(.rulesyncConfig, "duplicate.jsonc")) + #expect(duplicate.sources.isEmpty) + #expect(duplicate.diagnostics.last?.code == .invalidInput) + var limits = SourceImportLimits() + limits.documentBytes = 5 + #expect( + try SourceImport.preview(fixture.input(.rulesyncConfig, "config.jsonc"), limits: limits) + .diagnostics.last?.code == .invalidInput) + } + + @Test(arguments: ["alias", "entries", "bytes", "depth"]) + func capturedContentAdmissionRejectsMaliciousYAMLAndExceededBudgets(_ kind: String) throws { + let fixture = try ImportProfileFixture() + try fixture.write("lock.yml", "lockfile_version: '1'\ndependencies: []\n") + let header = + kind == "alias" + ? "name: &hidden review\ndescription: *hidden\n" + : "name: review\ndescription: fixture\nx-depth: [[[deep]]]\n" + try fixture.write("installed/review/SKILL.md", "---\n" + header + "---\nbody\n") + var limits = SourceImportLimits() + if kind == "entries" { limits.resourceEntries = 1 } + if kind == "bytes" { limits.resourceBytes = 10 } + if kind == "depth" { limits.depth = 2 } + var input = fixture.input(.apmLock, "lock.yml") + input.installedSkills = ["review": "installed/review"] + let before = try fixture.hash() + let result = try SourceImport.preview(input, limits: limits) + #expect(try fixture.hash() == before) + #expect(result.resources.isEmpty) + #expect(result.components.isEmpty) + #expect(result.diagnostics.contains { $0.code == .missingResource }) + #expect(!String(reflecting: result).contains("hidden")) + } + + @Test func inputRootsCannotEscapeOrReadLinkedContentOutsideBoundary() throws { + let fixture = try ImportProfileFixture() + let outside = try ImportProfileFixture() + try outside.write( + "skills/review/SKILL.md", "---\nname: review\ndescription: fixture\n---\nprivate\n") + try fixture.write("config.jsonc", "{\"inputRoots\":[\"../outside\"]}") + let traversal = try SourceImport.preview(fixture.input(.rulesyncConfig, "config.jsonc")) + #expect(traversal.diagnostics.contains { $0.code == .unsafePath }) + try FileManager.default.createSymbolicLink( + at: fixture.root.appendingPathComponent("linked"), withDestinationURL: outside.root) + try fixture.write("config.jsonc", "{\"inputRoots\":[\"linked\"]}") + let before = try outside.hash() + let linked = try SourceImport.preview(fixture.input(.rulesyncConfig, "config.jsonc")) + #expect(linked.resources.isEmpty) + #expect(linked.diagnostics.contains { $0.code == .unsafePath }) + #expect(try outside.hash() == before) + } +} + +private final class ImportProfileFixture { + let root: URL + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "import-profiles-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + deinit { try? FileManager.default.removeItem(at: root) } + func directory(_ path: String) throws { + try FileManager.default.createDirectory( + at: root.appendingPathComponent(path), withIntermediateDirectories: true) + } + func write(_ path: String, _ text: String) throws { + try directory((path as NSString).deletingLastPathComponent) + try Data(text.utf8).write(to: root.appendingPathComponent(path)) + } + func input(_ profile: SourceImportProfile, _ document: String) -> SourceImportInput { + .init(profile: profile, root: root, document: document) + } + func hash() throws -> String { try FileHash.folderHash(root) } +} diff --git a/Tests/ComponentsTests/ImportSourceTests.swift b/Tests/ComponentsTests/ImportSourceTests.swift new file mode 100644 index 0000000..997c072 --- /dev/null +++ b/Tests/ComponentsTests/ImportSourceTests.swift @@ -0,0 +1,359 @@ +import AgentsCore +import Components +import Foundation +import Testing + +struct ImportSourceTests { + @Test func rulesyncGitPinAndCanonicalSkillPreserveResourceCoordinates() throws { + let fixture = try ImportSourceFixture() + try fixture.write( + """ + {"lockfileVersion":1,"sources":{"acme/repo":{"requestedRef":"main", + "resolvedRef":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","skillsPath":"exports/skills", + "skills":{"review":{"integrity":"sha256-\(String(repeating: "b", count: 64))"}}, + "rulesPath":"rules","rules":{"overview":{"integrity":"sha256-\(String(repeating: "c", count: 64))"}}, + "skillSelection":["*"],"future":true}}} + """) + var input = fixture.input(.rulesyncSourcesV1) + input.sourceDeclarations = [ + "acme/repo": .init(kind: .git, location: "https://gitlab.com/acme/repo") + ] + let before = try FileHash.folderHash(fixture.root) + let proposal = try SourceImport.preview(input) + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(proposal.profile.producerRevision == "fbe4fe58334cab4e84b87f20d730d6450a35e0f7") + #expect(proposal.sources.first?.pin.commit == String(repeating: "a", count: 40)) + #expect(proposal.sources.first?.requestedRef == "main") + #expect(proposal.sources.last?.declaration?.location == "https://gitlab.com/acme/repo") + #expect(proposal.sources.last?.declaration?.path == "exports/skills/review") + #expect( + proposal.components.map(\.declaration) == [ + .skills(source: "import-source-0-skill-0", .init(select: .names(["review"]))) + ]) + #expect(proposal.resources.map(\.path) == ["exports/skills/review", "rules/overview.md"]) + #expect(proposal.resources.allSatisfy { $0.requiresStandaloneSource }) + #expect(proposal.diagnostics.filter { $0.code == .unconverted }.count == 3) + #expect(proposal.diagnostics.allSatisfy { $0.location.document == "input.json" }) + } + + @Test func normalizedRulesyncKeyNeverGuessesProviderOrPinsRequestedRef() throws { + let fixture = try ImportSourceFixture() + try fixture.write( + """ + {"lockfileVersion":1,"sources":{"org/repo#path=skills&ref=main":{ + "requestedRef":"\(String(repeating: "a", count: 40))","resolvedRef":"main", + "skillsPath":"skills","skills":{"review":{"integrity":""}}}}} + """) + let proposal = try SourceImport.preview(fixture.input(.rulesyncSourcesV1)) + #expect(proposal.components.isEmpty) + #expect(proposal.sources.first?.declaration == nil) + #expect(proposal.sources.first?.pin.commit == nil) + #expect(proposal.diagnostics.contains { $0.code == .ambiguousSource }) + #expect(proposal.diagnostics.filter { $0.code == .incompletePin }.count == 2) + } + + @Test func rulesyncRootFallbackDoesNotInventMemberDirectory() throws { + let fixture = try ImportSourceFixture() + try fixture.write( + """ + {"lockfileVersion":1,"sources":{"org/repo":{"resolvedRef":"\(String(repeating: "a", count: 40))", + "skillsPath":"exports","skillSelection":["review"], + "skills":{"review":{"integrity":"sha256-\(String(repeating: "b", count: 64))"}}}}} + """) + var input = fixture.input(.rulesyncSourcesV1) + input.sourceDeclarations = [ + "org/repo": .init(kind: .git, location: "https://github.com/org/repo") + ] + let proposal = try SourceImport.preview(input) + #expect(proposal.components.isEmpty) + #expect(proposal.resources.first?.producerName == "review") + #expect(proposal.resources.first?.path == nil) + #expect( + proposal.resources.first?.producerIntegrity?.value == "sha256-" + + String(repeating: "b", count: 64)) + #expect(proposal.diagnostics.contains { $0.message.contains("root fallback") }) + } + + @Test func npmProfileKeepsTarballAndResourceIntegritySeparate() throws { + let fixture = try ImportSourceFixture() + let sri = "sha512-" + Data(repeating: 1, count: 64).base64EncodedString() + try fixture.write( + """ + {"lockfileVersion":1,"sources":{ + "@acme/with-integrity":{"resolvedVersion":"1.2.3","requestedVersion":"latest","integrity":"\(sri)", + "skillsPath":"skills","skills":{"review":{"integrity":"sha256-\(String(repeating: "b", count: 64))"}}}, + "@acme/without-integrity":{"resolvedVersion":"1.2.3","skillsPath":"skills","skills":{}}}} + """) + let proposal = try SourceImport.preview(fixture.input(.rulesyncNpmV1)) + #expect(proposal.sources.count == 2) + #expect(proposal.sources[0].pin.integrity == .init(kind: .npmSRI, value: sri)) + #expect(proposal.sources[0].pin.version == "1.2.3") + #expect(proposal.sources[0].pin.commit == nil) + #expect(proposal.resources.first?.producerIntegrity?.kind == .rulesyncSHA256) + #expect(proposal.diagnostics.filter { $0.code == .incompletePin }.count == 1) + #expect(proposal.components.isEmpty) + } + + @Test(arguments: ["latest", "^1.2.3", "1.2.3-01", "1.2.3+.."]) + func npmResolvedVersionMustBeExact(_ version: String) throws { + let fixture = try ImportSourceFixture() + let sri = "sha512-" + Data(repeating: 1, count: 64).base64EncodedString() + try fixture.write( + """ + {"lockfileVersion":1,"sources":{"@acme/package":{"resolvedVersion":"\(version)", + "integrity":"\(sri)","skillsPath":"skills","skills":{}}}} + """) + let proposal = try SourceImport.preview(fixture.input(.rulesyncNpmV1)) + #expect(proposal.sources.first?.pin.version == nil) + #expect(proposal.sources.first?.pin.integrity?.kind == .npmSRI) + #expect(proposal.diagnostics.contains { $0.code == .incompletePin }) + } + + @Test func vercelProjectCapturesActualContentWithoutInventingGitCommit() throws { + let fixture = try ImportSourceFixture() + try fixture.skill() + try fixture.write("first\r\nsecond\r\n", at: "installed/review/guide.txt") + try Data([0, 13, 10]).write(to: fixture.root.appendingPathComponent("installed/review/binary")) + try fixture.write("{}", at: "installed/review/metadata.json/ignored.txt") + try fixture.write( + """ + {"version":2,"skills":{"review":{"source":"acme/repo","sourceType":"github","ref":"main", + "skillPath":"skills/review/SKILL.md","computedHash":"8ab07122fdd17957fa92a18c05f175744b26f661c87f3f479ad6279e200713e3"}}} + """) + var input = fixture.input(.vercelProjectV2) + input.installedSkills = ["review": "installed/review"] + let before = try FileHash.folderHash(fixture.root) + let proposal = try SourceImport.preview(input) + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(proposal.sources.first?.pin.commit == nil) + #expect(proposal.sources.first?.pin.integrity?.kind == .vercelInstalledSHA256) + #expect(proposal.sources.first?.declaration?.path == "skills/review") + #expect(proposal.sources.last?.declaration?.kind == .local) + #expect(proposal.sources.last?.declaration?.location == "installed/review") + #expect( + proposal.resources.first?.observedHash == "sha256:" + + (try FileHash.folderHash(fixture.root.appendingPathComponent("installed/review")))) + #expect(proposal.resources.first?.requiresStandaloneSource == true) + #expect(proposal.resources.first?.path == ".") + #expect(proposal.components.count == 1) + #expect(proposal.diagnostics.map(\.code) == [.incompletePin]) + } + + @Test func vercelChangedContentCannotBePresentedAsLockedContent() throws { + let fixture = try ImportSourceFixture() + try fixture.skill() + try fixture.write( + """ + {"version":2,"skills":{"review":{"source":"acme/repo","sourceType":"github", + "computedHash":"\(String(repeating: "a", count: 64))"}}} + """) + var input = fixture.input(.vercelProjectV2) + input.installedSkills = ["review": "installed/review"] + let proposal = try SourceImport.preview(input) + #expect(proposal.components.isEmpty) + #expect(proposal.resources.isEmpty) + #expect(proposal.diagnostics.contains { $0.code == .integrityMismatch }) + } + + @Test func vercelUserTreeHashAndLastSelectionAreNotCommitOrTargeting() throws { + let fixture = try ImportSourceFixture() + try fixture.write( + """ + {"version":3,"lastSelectedAgents":["codex"],"skills":{"review":{ + "source":"acme/repo","sourceType":"github","sourceUrl":"https://github.com/acme/repo", + "skillFolderHash":"\(String(repeating: "a", count: 40))","ref":"main", + "installedAt":"2026-11-10T00:00:00Z","updatedAt":"2026-11-10T00:00:00Z", + "future":{"token":"SECRET_LITERAL"}}}} + """) + let proposal = try SourceImport.preview(fixture.input(.vercelUserV3)) + #expect(proposal.sources.first?.pin.commit == nil) + #expect(proposal.sources.first?.pin.integrity?.kind == .githubTree) + guard case .skills(_, let skill) = proposal.components.first?.declaration else { + Issue.record("Expected skill proposal") + return + } + #expect(skill.agents == nil) + #expect( + proposal.diagnostics.contains { + $0.code == .unconverted && $0.location.pointer == "/lastSelectedAgents" + }) + #expect( + proposal.diagnostics.contains { + $0.code == .unconverted && $0.location.pointer.hasSuffix("/member[0]/member[0]") + }) + #expect(!proposal.bindings.isEmpty) + #expect(!String(describing: proposal).contains("SECRET_LITERAL")) + } + + @Test func credentialSourceDoesNotEscapeThroughProvenanceOrDiagnostics() throws { + let fixture = try ImportSourceFixture() + try fixture.write( + """ + {"version":2,"skills":{"review":{"source":"https://SECRET_LITERAL@github.com/acme/repo", + "sourceType":"github","sourceUrl":"https://github.com/acme/repo?token=SECRET_LITERAL","computedHash":""}}} + """) + let before = try FileHash.folderHash(fixture.root) + let proposal = try SourceImport.preview(fixture.input(.vercelProjectV2)) + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(proposal.sources.isEmpty) + #expect(proposal.bindings.count == 1) + #expect(proposal.diagnostics.map(\.code) == [.credentialBinding]) + #expect(!String(describing: proposal).contains("SECRET_LITERAL")) + } + + @Test func vercelUserCapturePinsActualContentAndKeepsProducerTreeUnverified() throws { + let fixture = try ImportSourceFixture() + try fixture.skill() + try fixture.write( + """ + {"version":3,"skills":{"review":{"source":"acme/repo","sourceType":"github", + "sourceUrl":"https://github.com/acme/repo","skillFolderHash":"\(String(repeating: "a", count: 40))", + "installedAt":"2026-11-10T00:00:00Z","updatedAt":"2026-11-10T00:00:00Z"}}} + """) + var input = fixture.input(.vercelUserV3) + input.installedSkills = ["review": "installed/review"] + let before = try FileHash.folderHash(fixture.root) + let proposal = try SourceImport.preview(input) + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(proposal.sources.allSatisfy { $0.pin.commit == nil }) + #expect(proposal.sources.last?.declaration?.kind == .local) + #expect(proposal.components.count == 1) + #expect(proposal.resources.first?.observedHash?.hasPrefix("sha256:") == true) + #expect(proposal.resources.first?.producerIntegrity?.kind == .githubTree) + #expect(proposal.diagnostics.contains { $0.message.contains("not verified") }) + } + + @Test(arguments: [ + "{\"version\":2,\"version\":2,\"skills\":{}}", + "{\"version\":2,\"skills\":{},\"sk\\u0069lls\":{}}", + "{\"version\":2,\"skills\":{}} trailing", + "[]", + "{\"version\":2,\"skills\":{},}", + ]) func malformedOrAmbiguousJSONIsRejected(_ text: String) throws { + let fixture = try ImportSourceFixture() + try fixture.write(text) + let proposal = try SourceImport.preview(fixture.input(.vercelProjectV2)) + #expect(proposal.components.isEmpty) + #expect(proposal.diagnostics.map(\.code) == [.invalidInput]) + } + + @Test(arguments: ["true", "1", "3", "null", "\"2\""]) + func unsupportedVersionDoesNotPartiallyImport(_ version: String) throws { + let fixture = try ImportSourceFixture() + try fixture.write("{\"version\":\(version),\"skills\":{}}") + let proposal = try SourceImport.preview(fixture.input(.vercelProjectV2)) + #expect(proposal.sources.isEmpty) + #expect(proposal.diagnostics.map(\.code) == [.unsupportedVersion]) + } + + @Test func selectionIsExplicitAndMissingSelectionIsDiagnosed() throws { + let fixture = try ImportSourceFixture() + try fixture.write("{\"version\":2,\"skills\":{\"unselected\":{\"bad\":true}}}") + var input = fixture.input(.vercelProjectV2) + input.selection = [] + #expect(try SourceImport.preview(input).diagnostics.isEmpty) + input.selection = ["absent"] + #expect(try SourceImport.preview(input).diagnostics.map(\.code) == [.invalidInput]) + } + + @Test func unknownPayloadAndWrongOptionalTypeAreNeverSilentlyAccepted() throws { + let fixture = try ImportSourceFixture() + try fixture.write( + """ + {"version":2,"contentObjects":{"unknown":"SECRET_LITERAL"},"skills":{"review":{ + "source":"acme/repo","sourceType":"github","computedHash":"","skillPath":17}}} + """) + let proposal = try SourceImport.preview(fixture.input(.vercelProjectV2)) + #expect(proposal.sources.isEmpty) + #expect(proposal.diagnostics.contains { $0.code == .unconverted }) + #expect(proposal.diagnostics.contains { $0.code == .invalidInput }) + #expect(proposal.diagnostics.last?.location.pointer == "/skills/member[0]/skillPath") + #expect(!String(describing: proposal).contains("SECRET_LITERAL")) + } + + @Test func rulesyncCredentialKeyIsRedactedAndLockProfilesAreDistinct() throws { + let fixture = try ImportSourceFixture() + try fixture.write( + """ + {"lockfileVersion":1,"sources":{"https://SECRET_LITERAL@github.com/org/repo":{ + "resolvedRef":"\(String(repeating: "a", count: 40))","skillsPath":"skills","skills":{}}}} + """) + let git = try SourceImport.preview(fixture.input(.rulesyncSourcesV1)) + #expect(git.sources.isEmpty) + #expect(git.bindings.count == 1) + #expect(!String(describing: git).contains("SECRET_LITERAL")) + let npm = try SourceImport.preview(fixture.input(.rulesyncNpmV1)) + #expect(npm.sources.isEmpty) + #expect(npm.diagnostics.contains { $0.code == .invalidInput }) + #expect(!String(describing: npm).contains("SECRET_LITERAL")) + } + + @Test func resourceLinksAndDocumentLimitsLeaveInputsUntouched() throws { + let fixture = try ImportSourceFixture() + try fixture.skill() + try FileManager.default.createSymbolicLink( + atPath: fixture.root.appendingPathComponent("installed/review/secret").path, + withDestinationPath: "/etc/hosts") + try fixture.write( + """ + {"version":2,"skills":{"review":{"source":"acme/repo","sourceType":"github", + "computedHash":"\(String(repeating: "a", count: 64))"}}} + """) + var input = fixture.input(.vercelProjectV2) + input.installedSkills = ["review": "installed/review"] + let before = try FileHash.folderHash(fixture.root) + let proposal = try SourceImport.preview(input) + #expect(proposal.components.isEmpty) + #expect(proposal.diagnostics.contains { $0.code == .unsafePath }) + var limits = SourceImportLimits() + limits.documentBytes = 8 + #expect( + try SourceImport.preview(input, limits: limits).diagnostics.map(\.code) == [.invalidInput]) + #expect(try FileHash.folderHash(fixture.root) == before) + } + + @Test func pathTraversalAndExternalSymlinksNeverBecomeResources() throws { + let fixture = try ImportSourceFixture() + try fixture.write( + """ + {"version":2,"skills":{"review":{"source":"acme/repo","sourceType":"github", + "skillPath":"../outside/SKILL.md","computedHash":""}}} + """) + #expect( + try SourceImport.preview(fixture.input(.vercelProjectV2)).diagnostics.map(\.code) == [ + .unsafePath + ]) + try FileManager.default.createSymbolicLink( + atPath: fixture.root.appendingPathComponent("external.json").path, + withDestinationPath: "/etc/hosts") + var input = fixture.input(.vercelProjectV2) + input = .init(profile: input.profile, root: input.root, document: "external.json") + #expect(try SourceImport.preview(input).diagnostics.map(\.code) == [.unsafePath]) + } +} + +private final class ImportSourceFixture { + let root: URL + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "import-tests-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + deinit { + do { try FileManager.default.removeItem(at: root) } catch { Issue.record(error) } + } + func write(_ text: String, at path: String = "input.json") throws { + let file = root.appendingPathComponent(path) + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: file) + } + func input(_ profile: SourceImportProfile) -> SourceImportInput { + .init(profile: profile, root: root, document: "input.json") + } + func skill() throws { + try write( + "---\nname: review\ndescription: Review changes\n---\n# Review\n", + at: "installed/review/SKILL.md") + } +} From fe62344a1612408b58afe0a8721e09075c551738 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:18:44 +0800 Subject: [PATCH 073/171] feat: unify component configuration lifecycle --- Documentation/Architecture/Instructions.md | 13 +- Documentation/Architecture/Package.md | 29 +- Documentation/Architecture/State.md | 174 ++---- Documentation/Architecture/Updates.md | 226 ++++--- Package.swift | 15 +- README.md | 13 +- .../AgentsCore/LedgerDisplayEvidence.swift | 60 ++ Sources/AgentsCore/LedgerProjection.swift | 92 +++ Sources/AgentsCore/LedgerStateStore.swift | 61 +- Sources/AgentsCore/ResolvedLedger.swift | 303 +++++----- Sources/AgentsCore/ResolvedState.swift | 2 +- .../AgentsCore/ResolvedStateEncoding.swift | 26 - Sources/AgentsCore/RetentionReferences.swift | 31 +- Sources/AgentsCore/SourceCache.swift | 18 +- Sources/AgentsCore/StateStore.swift | 8 +- Sources/AgentsCore/UpdatePreconditions.swift | 11 +- Sources/AgentsCore/WatchOperations.swift | 16 +- .../InstructionDoctor.swift | 24 +- .../InstructionExport.swift | 56 +- .../InstructionLifecycleModels.swift | 42 +- .../InstructionModels.swift | 2 +- .../InstructionOperations.swift | 463 +------------- .../InstructionSources.swift | 68 +-- .../InstructionTargets.swift | 15 +- .../InstructionUpdatePlan.swift | 71 --- Sources/AgentsManifest/DeploymentSubset.swift | 71 --- Sources/AgentsManifest/ManifestState.swift | 42 +- Sources/AgentsSkills/SkillLifecycle.swift | 352 +---------- Sources/AgentsSkills/SkillModels.swift | 57 ++ Sources/AgentsSkills/SkillOperations.swift | 551 +++-------------- Sources/AgentsSkills/SkillUpdatePlan.swift | 85 --- .../AgentsUpdates/InstructionOperations.swift | 176 ++++++ Sources/AgentsUpdates/PreparedUpdate.swift | 5 +- Sources/AgentsUpdates/SkillOperations.swift | 141 +++++ Sources/AgentsUpdates/UpdateInputs.swift | 45 ++ Sources/AgentsUpdates/UpdateModels.swift | 38 +- Sources/AgentsUpdates/UpdateOperations.swift | 115 +++- Sources/AgentsUpdates/UpdatePlan.swift | 568 +++++++++++++++--- Sources/AgentsUpdates/UpdateReporting.swift | 168 ++++++ Sources/AgentsUpdates/UpdateRequest.swift | 37 ++ Sources/Components/ArtifactAggregation.swift | 558 +++++++++++++++++ Sources/Components/ComponentFields.swift | 2 +- .../Components/DeploymentConstruction.swift | 208 +++++++ Sources/Components/LedgerImpact.swift | 186 ++++++ Sources/Components/LedgerReplay.swift | 30 +- .../CachePublicationTests.swift | 15 +- .../DeclarationStateTests.swift | 2 +- Tests/AgentsCoreTests/GitErrorTests.swift | 12 +- .../IndependentLedgerAdmissionTests.swift | 8 +- .../PreparationEvidenceTests.swift | 1 + .../RequirementSemanticsTests.swift | 36 +- Tests/AgentsCoreTests/SourceCacheTests.swift | 40 +- .../AgentsCoreTests/StateEncodingTests.swift | 1 + .../StateInspectionTests.swift | 1 + Tests/AgentsCoreTests/StateModelTests.swift | 99 ++- Tests/AgentsCoreTests/WatchSourceTests.swift | 1 + .../DeclarationDocumentTests.swift | 1 + .../DoctorLifecycleTests.swift | 1 + .../FileReadAccessTests.swift | 1 + .../LifecycleFixture.swift | 1 + .../LifecycleSafetyTests.swift | 50 +- .../LifecycleTests.swift | 8 +- .../OwnershipAndPlacementTests.swift | 1 + .../SourceDiagnosticTests.swift | 2 + .../SourceShorthandTests.swift | 1 + .../TargetLifecycleTests.swift | 7 +- .../FullDeclarationTests.swift | 7 - .../ArchiveSafetyTests.swift | 6 +- .../DefaultResolutionTests.swift | 2 + .../DiscoveryBehaviorTests.swift | 21 +- .../FileReadAccessTests.swift | 3 +- .../InstallationSafetyTests.swift | 1 + .../InstalledInventoryTests.swift | 4 +- .../LifecycleRegressionTests.swift | 2 + .../LockedArtifactLifecycleTests.swift | 225 ------- .../ManifestLifecycleTests.swift | 4 +- .../PublicLifecycleTests.swift | 32 +- .../ReadOnlyInspectionTests.swift | 1 + .../RetainedLifecycleTests.swift | 1 + .../SkillLifecycleTests.swift | 11 +- .../AgentsSkillsTests/SourceAliasTests.swift | 1 + .../SourceShorthandTests.swift | 2 + .../TransactionDoctorTests.swift | 2 + .../UnmanagedTargetTests.swift | 1 + .../UpdateReportingTests.swift | 60 +- .../WatchSubscriptionTests.swift | 2 + .../CombinedUpdateTests.swift | 12 +- .../LifecycleCompositionTests.swift | 396 ++++++++++++ .../RequirementUpdateTests.swift | 50 +- Tests/AgentsUpdatesTests/UpdateFixture.swift | 1 + .../PrivateMaterializationProbe.swift | 1 + Tests/StateTestProcess/main.swift | 25 +- .../DeclarationStateFixture.swift | 57 ++ 93 files changed, 3856 insertions(+), 2637 deletions(-) create mode 100644 Sources/AgentsCore/LedgerDisplayEvidence.swift create mode 100644 Sources/AgentsCore/LedgerProjection.swift delete mode 100644 Sources/AgentsCore/ResolvedStateEncoding.swift delete mode 100644 Sources/AgentsInstructions/InstructionUpdatePlan.swift delete mode 100644 Sources/AgentsManifest/DeploymentSubset.swift delete mode 100644 Sources/AgentsSkills/SkillUpdatePlan.swift create mode 100644 Sources/AgentsUpdates/InstructionOperations.swift create mode 100644 Sources/AgentsUpdates/SkillOperations.swift create mode 100644 Sources/AgentsUpdates/UpdateInputs.swift create mode 100644 Sources/AgentsUpdates/UpdateReporting.swift create mode 100644 Sources/AgentsUpdates/UpdateRequest.swift create mode 100644 Sources/Components/ArtifactAggregation.swift create mode 100644 Sources/Components/DeploymentConstruction.swift create mode 100644 Sources/Components/LedgerImpact.swift delete mode 100644 Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift create mode 100644 Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift create mode 100644 Tests/StateTestSupport/DeclarationStateFixture.swift diff --git a/Documentation/Architecture/Instructions.md b/Documentation/Architecture/Instructions.md index 0a9cda0..aa6957a 100644 --- a/Documentation/Architecture/Instructions.md +++ b/Documentation/Architecture/Instructions.md @@ -164,15 +164,14 @@ The optional throwing `beforeApply` callback runs before replacements so a consumer can show differences or cancel. Target bytes are checked again after the callback; intervening edits stop the commit. Update also revalidates state 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). +before and after retention. Lifecycle methods are public extensions in +`AgentsUpdates`, which owns the complete linked ledger and one transaction for +selected deployments, declaration, resources and pruning. Consumers import that +product for lifecycle and locked ChatGPT rendering; pure text APIs remain here. +See [Updates](Updates.md) for selection, prepared handles and exact restore. 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, +files, forwarding files, declaration, ledger, materializations and cache pruning. The journal has fixed project instruction paths, nested project `AGENTS.md` and `GEMINI.md` paths, configured user instruction roots and new top-level named Markdown files in `.agent/instructions/`. Initialization uses the project's state lock and journal without creating a diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 4db7929..445a59e 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -14,7 +14,7 @@ AgentsManifest → AgentsCore, TreeSitterYAML, TreeSitter, Yams AgentsSkills → AgentsCore, AgentsManifest, Yams AgentsInstructions → AgentsCore, AgentsManifest, Markdown Components → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, NativeDocuments -AgentsUpdates → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions +AgentsUpdates → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, Components NativeDocuments → AgentsCore, TOMLSemantics, TreeSitterTOML, TreeSitter TOMLSemantics → Foundation TreeSitterTOML → (vendored C grammar) @@ -88,9 +88,8 @@ and the existing state, linking, lifecycle and recovery guarantees. carry document coordinates and origins without syntax or source access. - `Declaration` holds complete typed symbolic manifest intent: ordered component and group occurrences, conditions, native values, symbolic group references and - source declaration directories. It has no serialized form. `ResolvedState` - defines version 1 skill/instruction state, including instruction sections, - prompts and physical targets. + source declaration directories. It has no serialized form. `ResolvedLedger` owns version 2 resolved state. `ResolvedState` is the derived + skill/instruction inventory view, including sections, prompts and physical targets. - `StateStore` owns scope paths, validation, deterministic lock and watch encoding and state persistence. It holds declaration bytes, their evidence, the absent-declaration rule and publication without knowing the declaration @@ -123,7 +122,8 @@ and the existing state, linking, lifecycle and recovery guarantees. Core has no dependency on manifest syntax, skill discovery, frontmatter, Yams or Markdown. -`AgentsInstructions` owns instruction text transformations and lifecycle. +`AgentsInstructions` owns instruction text transformations, inventory and diagnostics. +`AgentsUpdates` owns its deployment lifecycle. `InstructionLocations` supplies fixed target locations to lifecycle and journal validation. @@ -189,7 +189,7 @@ means the before membership is unrecorded, not that files were absent. equal hashes do not suppress mode-only changes. The optional `beforeApply` callback runs before any replacement, and a thrown -error cancels the operation. The extracted `SkillUpdatePlan` validates state +error cancels the operation. The shared Updates plan validates state and target preconditions around content retention, including execute flags. Prepared, cached and staged skill content must agree in bytes and mode. A CLI auditing several projects calls `doctor` with an explicit environment @@ -337,7 +337,7 @@ Versioned replay produces verified artifacts and owned-region intentions; its compatibility renderer table contains only existing formats. Test process formats are supplied explicitly and are absent from production registration. These package seams do not publish state. -The existing public lifecycle operations still enforce their deployment subset. +Updates consumes the full linked graph and paired ledger freeze for deployment. Root package resources use the project directory in project scope and the user-state directory in user scope. Explicit sources retain their declaring @@ -354,12 +354,15 @@ lock through preparation and the synchronous consumer closure. Its retained or reused handles fail before I/O after closure exit. Reports cannot be reconstructed into applicable plans. -Package-visible `SkillUpdatePlan` and `InstructionUpdatePlan` own discovery, -reports, preconditions, retention and staging for their domains. Standalone -updates use those same plans and preserve the other domain. Neither domain -depends on the other or on `AgentsUpdates`. The composition target merges -owned records and commits both kinds, changed state and cache pruning in one -`FileTransaction`; the skill-only consumer need not link Markdown. +`UpdatePlan` owns complete declaration linking, paired freeze, locked replay, +artifact aggregation, the v2 ledger and the one publication transaction. Domain +lifecycle methods are public extensions in Updates, so their consumers add an +`AgentsUpdates` dependency and import. The domain modules keep discovery, +frontmatter, rendering, inventory and diagnostic helpers. Restricted requests +protect the recorded other-domain semantics and independent direct pins. +Preview uses temporary acquisition; prepared callbacks remain inside both source +and replay resource closures. Shared native files are aggregated once per physical +destination, and reports expose selected owned changes only. See [combined updates](Updates.md) for callback restrictions, state-only changes, cancellation, failure dispositions and recovery. diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index f2128bf..9805338 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -43,7 +43,7 @@ components: - {kind: skills, source: team, exclude: [retired]} ``` -### Deployable subset +### Complete declarations `loadDeclaration()` projects every declared component family, including MCP, hooks, subagents, commands, LSP, permissions, ignores and plugins. It preserves @@ -53,20 +53,14 @@ are the ordered owners; alias dictionaries and the flat skill/instruction access are derived views. Source aliases retain their declaring project and home directories so importing code cannot reinterpret their relative paths. -The current skill/instruction deployment paths use -`readDeploymentDeclaration(prepared:)`. This explicit boundary accepts root -`defaultAgents`, `sources` and `watch`, and root `skills` and `instructions` -components: at most one skills occurrence per alias and one instructions -occurrence, with no condition on a component, section or prompt and empty native -configuration. Unused groups and exports remain preserved. Active group uses, -own-package skill discovery and other component families require linking or -native lowering and fail with a located `manifest.unsupported` before source work -or deployment. Repeated matching root selections fail with `manifest.ambiguous` -and related occurrence locations. Full declaration reads do not use this gate. +`AgentsUpdates` links the complete declaration, including group uses, conditions, +producer restrictions and native payloads, before choosing concrete deployments. +Concrete adapters own supported schemas and registered routes. A missing mapping +or route is an explicit preparation error, not a declaration-reader restriction. `Declaration.skills` and `instructions` are throwing root-selection views: they reject multiple matching occurrences. `setSkills`, `setInstructions`, -`updateSkills` and `updateInstructions` serve the current domain operations and +`updateSkills` and `updateInstructions` serve unambiguous root selections and preserve unrelated components. Full occurrence edits use `components`, group payloads and typed section references directly. `Declaration.validate(environment:)` checks source identities using the aliases' declaring directories and validates @@ -203,66 +197,54 @@ and newly serialized requirement fields. | --- | --- | | Declaration IR and dump | Canonical requirement kinds and normalized version strings; a factory and a literal range with equal bounds compare equal. | | Declaration writes and `upsertSource` | Semantic values are compared; an equal edit keeps the original source bytes. New or changed nodes print canonically; untouched spelling is retained. | -| `LockedSource.requirement` in the lock | Newly written records use canonical requirements. Existing records keep their bytes and are compared through a semantic view. A requirement-spelling difference alone never changes pins, reports an update or stages a write. | -| Skill and instruction lock producers, combined update conflicts and change detection | Source identity, discovery root and semantic requirement values are compared; equal ranges merge without a conflict. A semantically unchanged lock keeps its original bytes even when another state file changes; a necessary rewrite emits canonical requirements. | +| `LedgerSourceUse.requirement` in the ledger | Newly written records use canonical requirements. Existing records keep their bytes and are compared through a semantic view. A requirement-spelling difference alone never changes pins, reports an update or stages a write. | +| Linked component pins and change detection | Source identity, discovery root and semantic requirement values are compared; equal ranges have equal meaning. A semantically unchanged lock keeps its original bytes even when another state file changes; a necessary rewrite emits canonical requirements. | | Resolution-session reuse and cache descriptors | Requirements are keyed by semantic value. Cache identity and materialization keys use source identity and exact revision or artifact digest; restoration uses the stored pins without re-resolving requirements. | | `agents.watch` | Stores source identities and seen baselines, with no requirement. Re-evaluating an equivalent declaration preserves the subscription and baseline; watch-created lock descriptors follow the lock rule. | State transactions compare semantic state before choosing any serialization and never rewrite records on read. -## Lock - -`agents.resolved` version 1 has identity-keyed `sources` and `skills`, and an -`instructions` object containing `sections`, `chatgpt` and `targets`. - -The lock is 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. A semantically -unchanged lock keeps its original bytes; a changed lock is written in that -layout. When the prepared generation has neither a lock nor a declaration and -the resulting lock is empty, no lock is created, because lock state without a -declaration would stop every later access to the scope. A scope with a -declaration receives a lock even when it is empty. Empty lock sections such as -`"skills": {}` remain, because earlier readers require them. Journals, -`agents.watch` and content hashes keep the encoder's fixed layout. - -A locked source records its kind, Git URL where applicable, requirement and -search path. A skill records its source ID, its own revision and optional -version, relative directory path, content hash and `installs` mapping agent IDs -to `link`, `copy` or `edit`. Every non-edit item carries an immutable pin. -Updating one skill leaves other item pins unchanged. - -Well-known items record an artifact's `type`, `url` and SHA-256 `digest`. -`files` artifacts additionally record every file's URL, path and digest. Their -aggregate digest covers the sorted, deterministically encoded file records. -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; 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. - -Maps are key sorted. Unordered selections and agent lists are sorted; section -arrays and each prompt's section order are preserved. Files have a trailing -newline and no timestamps. State and journal JSON must be UTF-8 without a byte -order mark; validation consumes the entire document. Other encodings, invalid -state, duplicate JSON keys at any depth and fields that would be discarded by -decoding cause an error. Tree hashes use length-prefixed paths and typed entry -payloads, including empty directories and symbolic link destinations. - -Tree hashes intentionally exclude permissions. Skill update snapshots compare -the any-execute-bit Boolean separately for regular files. Preparation, retention -and transaction staging verify that dimension without changing stored hashes, -pins, the declaration or the version 1 lock and watch schemas. +## Resolved ledger + +`agents.resolved` is a version 2 JSON ledger. It records exact sources and source +uses, symbolic components, ordered occurrences and group dependencies, complete +resources, ownership, deployments and versioned lowerings. Local and artifact +resources retain deduplicated non-secret content objects; Git resources retain +exact acquisition coordinates and commits. Trees record empty directories, +symlinks and execute flags. Runtime bindings remain symbolic. + +The codec accepts one ledger version and rejects unknown fields, duplicate keys, +invalid references, unsupported versions and corrupt content objects. Admission +bounds bytes, depth, nodes, entries and decoded content before object decoding. +Equivalent state preserves the original bytes. Newly encoded state is deterministic +JSON with sorted map keys, meaningful array order, a trailing newline and no time +or machine-temporary fields. Journals and watch state keep their own encoders. + +`StateStore.loadResolved()` supplies the existing skill/instruction inventory view +by projecting the ledger. This view is not a second stored graph and is never +saved as a lock. Native components and dependency relationships remain in the +ledger. Listings, diagnostics and watch validate the same committed generation. +An unconfigured empty scope needs no resolved file; a declaration-backed empty +ledger remains valid. + +Updates link the complete declaration and freeze one paired source result before +lowering. Restore uses only locked format/layout/resources and verifies every +rendered artifact. It never selects current producer requirements or refs. +Embedded inputs can reconstruct without their authoring tree; live edit skills +remain explicit live locations. Regional ownership is distinct from whole-file +freshness, and existing unmanaged equal values do not grant ownership. + +`RetentionReferences` derives the complete source/resource closure, including +empty groups, container parents, other component domains, watch pins and live +locations. The last skill's removal cannot prune resources still referenced by +instructions, native components or watch. New materializations and pruning share +the configuration transaction. Source ref cleanup follows the committed closure +only after physical commit or recovery. + +Tree content hashes exclude permissions. Resource entries and staging separately +verify regular-file execute flags. Pinned resource bytes, modes and locked renderer +outputs must agree before publication. ## State Transaction and Recovery @@ -646,6 +628,11 @@ do not claim native parser, adapter or real-client acceptance. ### Read-only access +Configuration preview additionally keeps all source acquisition temporary and never +creates persistent cache or shared coordination locks, retains content or invokes +a runtime binding provider. Exact cached objects are reused only through existing +read locks; missing objects and extraction are cleaned on every exit. + Non-applying skill and instruction operations, listings, previews, watch status and watch diff take an existing shared lock, report pending recovery and never replay it or create state files. With no lock, inspection rechecks for a new @@ -768,7 +755,7 @@ without a requirement. Local non-Git directories support edit mode. Git-backed link and copy operations read committed trees, including when the source has uncommitted changes. -An update preview or source listing can fetch into a mirror. Inspection +Source listing can fetch into a mirror. Configuration previews use temporary acquisition and never mutate persistent mirrors, refs, cache contents or locks. Inspection snapshots are disposable and do not move an installed tree or write state or targets. Skill and instruction `add` discover choices through the read path when no names or `all` are supplied, and for `listOnly`. Their discovery uses @@ -827,44 +814,15 @@ matching Git resolutions and uncommitted changes in selected local source paths. `install` restores all recorded recipients and modes without changing lock bytes. The consuming CLI controls presentation and user interaction. -## Version 2 ledger package interfaces - -`ResolvedLedger` is the package-internal version 2 representation of the same -`agents.resolved` file. `ResolvedLedgerCodec` accepts version 2 only. It preserves -unchanged bytes and rejects unknown fields, duplicate keys, invalid references, -corrupt embedded objects and unsupported versions. `LedgerAdmission` bounds -encoded bytes, structural depth and nodes, embedded decoded bytes and tree -entries before decoding. Scope reads also bound file bytes while reading. - -The ledger stores source uses and independent pins, complete symbolic component -payloads, ordered occurrences and group child closures, producer manifest -hashes, resource trees, deployment ownership and format-pinned lowerings. -Content objects embed deduplicated non-secret bytes for local and artifact -resources. Trees preserve directories, symlinks and executable files. Actual -local edit skills retain explicit live locations. Registered-root-relative -locations relocate with their registered root; explicit absolute locations keep -their authored meaning. Runtime secret values are not binding inputs to this -codec or the pure renderers. - -`Components.LedgerFreeze` consumes borrowed B graph resources inside the source -session. Its caller supplies explicit authoring coordinates and lowering/layout -choices. `LedgerReplay.prepareLowerings` seals symbolic output identities; -`withReplay` reconstructs exact resources, selects only the locked renderer -format and verifies outputs before returning borrowed artifacts and owned-value -intentions. Exact Git acquisition uses the recorded commit. Embedded resources -require no authoring tree or cache. Compatibility formats cover existing skill, -instruction, ChatGPT and Claude import rendering. Production native format -registration and document editing are owned by the native adapters. - -`RetentionReferences` validates and derives the complete source/resource closure, -including container ancestry and empty groups, then unions watch references. -Cache pruning stages deletions in the caller's `FileTransaction`. Ref cleanup -runs only after physical journal recovery or commit; unfinished journals prevent -independent pruning. Recovery interprets physical evidence and does not invoke -renderers or source providers. - -The existing public lifecycle methods continue to use their version 1 model and -reject version 2 input. Public lifecycle composition owns their eventual version -2 integration. Conversion tooling is external to the package and requires old -locks, original authoring inputs and explicit target layouts; it does not adopt -current deployed bytes. +## Ledger composition interfaces + +`LedgerFreeze.freezeWithSources` returns the ledger and its ephemeral source map +from one linked result. Native lowering consumes that paired result inside the +source session. `LedgerReplay.withPreparedLowerings` seals artifact identities and +keeps all acquired resources alive through its callback. `withLockedResources` +replays a locked candidate with the same resource lifetime. Borrowed URLs never +escape into public reports or outlive a prepared handle's synchronous closure. +The production renderer table is explicit and format-versioned. Tests supply +separate renderers without registering production fallback behavior. + +`StateStore.loadLedger()` returns the complete public ledger model without resolving sources or recovering transactions. `loadResolved()` returns the derived skill/instruction summary for domain consumers; it is never a persisted state format. diff --git a/Documentation/Architecture/Updates.md b/Documentation/Architecture/Updates.md index ed53e76..7ee5faa 100644 --- a/Documentation/Architecture/Updates.md +++ b/Documentation/Architecture/Updates.md @@ -1,125 +1,113 @@ -# Combined Updates - -`AgentsUpdates` composes the skill and instruction planners for one project or -user scope. It updates all declared skills, instruction recipients and named -ChatGPT prompts. Named skill selection and instruction recipient overrides -belong to the standalone APIs. Consumers own rendering and completion output. - -## Reports and Preparation - -`UpdateOperations.preview(scope:environment:)` returns `CombinedUpdateReport` -under one existing shared scope lock. It never returns an applicable handle, -retains source trees, writes state or replays recovery. Mirror fetching and -disposable snapshots are allowed. If a first writer appears during an -unprotected inspection, the result or error is discarded and inspection -retries under the shared lock. - -`UpdateOperations.withPreparedUpdate(scope:environment:_:)` acquires the -writer lock, recovers pending work before reading the baseline, and prepares -both kinds before calling the consumer. Shared pinned sources use one exact -snapshot per normalized identity and effective declaration, so source movement -between domain planners cannot produce different pins for the same source. -Independent sources are not promised a simultaneous upstream snapshot. - -The combined lock takes skills from the skill plan and instruction records -from the instruction plan. It merges compatible source updates and retained -baseline records, preserves declaration and watch data, and then validates the -complete prospective state. Domain preparation defers whole-state validation -until this merge so shared source changes are checked against both domains' -prospective records. Standalone operations validate their complete resulting -state before returning a preview or invoking a consumer callback. Applying -preparation checks ownership and physical path collisions before the closure. -Preview can report prospective membership that an applying preparation rejects -as unmanaged. - -The report contains `scope`, `skills`, `instructions`, `lockMissing` and -`hasChanges`. The last includes normalized lock changes, physical differences -and required missing-lock reconstruction. An empty unconfigured scope is -unchanged. Section ordering and identical-content prompt repins can require -application even without changed target bytes or changed prompt names. - -Skill results expose old/new versions from the resolved records, full revisions -and hashes. Versions remain nil for absent sides, edit installations, -well-known artifacts and Git resolutions without a selected version tag. -`SkillFileEntry.file(Data, executable: Bool)` uses the same any-execute-bit rule -as watch. Directories and links keep their own entry types; a symlink's mode is -not its destination's mode. Persistent content hashes do not include mode. - -Each result's `membership` has one `SkillMembershipChange` per agent in the -union of previous and prospective installations, sorted by agent raw value. -`SkillMembership` is `.absent` or `.installed(mode:)`. These are managed -membership states, independent of physical presence. Rows use physical paths -with resolved parents and unfollowed final entries. Agents sharing a path -retain separate rows while physical changes remain deduplicated. Unchanged -results include membership too; `installed` retains its post-apply meaning. - -A missing `agents.resolved` makes the before membership unrecorded and -`lockMissing` true. A correct existing live link can therefore have added -membership and no physical diff. It still fails applying preparation's -unmanaged-content guard. A locked but missing target remains installed on the -before side. If both record and selection are lost, no removal is invented. -Loss of resolved state is distinct from replacing the never-removed writer -lock file. - -## Handle Lifetime and Application - -The closure receives a `PreparedUpdate` with a report and `apply()`. The handle -has no public initializer, serialization or `Sendable` conformance. Its -internal plan is separate from the report. Any apply attempt consumes it; -inactive, repeated or wrong-thread use fails before I/O. Closure exit -invalidates retained handles and releases their disposable planning resources. - -The writer lock remains held through preparation, rendering and apply. The -closure must stay synchronous on its preparing thread and must not re-enter -scope operations, await work, or dispatch the handle. In particular, reading -a separate output inventory can deadlock. Render the supplied report and -apply or return. An interactive pause holds off other scope users; a UI that -needs a long pause should preview first and prepare/display a fresh plan when -ready to apply. - -Returning or throwing before apply cancels without publishing targets, state -or retained content. A caller error after successful apply does not undo it. -Applying revalidates declaration/resolved/watch bytes and presence, target -entries, execute flags, links, path ancestry, instruction bytes and forwarding -decision inputs. Live source identities and usable skill metadata are checked; -their contents remain live. Pinned content is retained and verified, then -preconditions are rechecked before one transaction stages both kinds, changed -state and pruning. Copy staging and pinned-link destinations are verified -against prepared bytes and execute flags before publication. - -`UpdateApplyResult` contains the rendered `report` and `installedSkills` -receipts. A no-change apply returns receipts without rewriting state. -Standalone skill and instruction updates use the same domain planners and -staging functions, with their existing callback signatures and domain isolation. +# Configuration Lifecycle + +`AgentsUpdates` owns configuration update, declaration edit, removal and locked +restore for one project or user scope. It composes the complete YAML declaration, +linked source graph, resolved ledger, domain rendering and native regional edits. +Consumers own command parsing, presentation and completion output. + +## Requests and Reports + +`UpdateRequest.operation` selects source update, locked restore, typed YAML edits, +a complete declaration replacement, or removal. `kinds` restricts the component +domains and `names` restricts members. A restricted operation protects the other +recorded components' pins, payloads, resources and effective recipients. A change +that requires a wider operation reports `requiresCombinedUpdate` before publishing. +Producer-owned children cannot be edited as consumer declarations; their diagnostic +identifies the producer and group reference. Root occurrence edits use +`ManifestEdit` and digest-scoped document handles. + +`UpdateOperations.preview(_:scope:environment:)` returns a serializable +`CombinedUpdateReport`. It uses existing shared locks and never creates persistent +scope, cache or native coordination locks, changes refs, retains content, recovers a +journal, invokes a binding provider or runs source programs. Existing exact cached +objects may be read under their existing locks. Missing objects, downloads, +extraction and their locks remain temporary and are cleaned on success, failure +and cancellation. A first writer invalidates an unlocked inspection attempt. + +Reports include skill membership and typed file differences, instruction targets +and prompts, selected native changes, missing-lock status, `hasChanges` and a +`displayedFingerprint`. Native reports contain the owned symbolic values; complete +shared documents, unrelated siblings, runtime secret values and private freshness +evidence remain internal. Equal unmanaged values do not establish ownership. +`hasChanges` includes declaration and ledger changes even when target bytes agree. + +The versioned display fingerprint covers the operation and selection, complete +candidate declaration and ledger, exact pins, resources, locked renderer/layout, +ownership, actual destinations and stable access semantics. It excludes temporary +paths and inodes, random IDs, timestamps, runtime secret values and complete native +preimage digests. Repeated preparation of the same candidate and environment has +the same fingerprint. This is a presentation comparison, not an authorization token. + +## Preparation and Application + +`withPreparedUpdate(_:scope:environment:_:)` acquires the request and pending-journal +footprint before the scope writer lock. Source linking can discover a larger +footprint; preparation releases the locks and readmits the union before delivering +the consumer closure. This never repeats a delivered callback or binding provider. +It captures declaration, ledger and watch together, links and freezes one paired +source result, lowers it and aggregates contributions by physical destination. +Shared native files receive one aggregated regional edit with all logical owners. + +The closure receives `PreparedUpdate.report` and `apply(ifUnchangedFrom:)`. Any +apply attempt consumes the handle. It has no public initializer, serialization or +`Sendable` conformance. It is valid only on its preparing thread inside the +synchronous closure; exit invalidates retained handles and releases all borrowed +source/replay resources. Do not re-enter scope operations, await, or dispatch the +handle. Render the supplied report directly. + +A UI may preview without holding a writer lock, then prepare on a worker thread +and pass the displayed fingerprint to `apply(ifUnchangedFrom:)`. A changed +fingerprint requires a refreshed report. Matching fingerprints still execute all +private freshness, ownership, permission, binding and publication checks. + +Application validates the captured state, targets, linked inputs and forwarding +decisions. Live skill contents stay live while their source identity and valid +metadata remain required. It retains the complete ledger/watch closure, stages +resources, selected deployments, declaration, ledger, receipts and pruning, and +commits through one `FileTransaction`. Required literal bindings are resolved only +inside Core's private staged render. Ordinary application never starts an MCP +server, hook, plugin or model call. + +Returning or throwing before apply cancels publication. A caller error after a +successful apply does not undo the commit. A no-change apply returns receipts +without rewriting state. + +## Exact Restore and Domain APIs + +`UpdateOperations.restore(scope:environment:)` restores the complete locked +deployment in one transaction. Restore acquires resources and runs the locked +format/layout; it does not link mutable producer declarations, choose current +refs or select a newer adapter. Missing resources, unknown renderers, output +mismatches and incompatible platforms fail before publication. Embedded resources +support cold reconstruction without the authoring tree. Live skills retain their +explicit authoring location. Native restore preserves unmanaged regions. + +`SkillOperations` and `InstructionOperations` retain their type identities. +Their add, update, remove and restore methods are public extensions in +`AgentsUpdates`; consumers calling them must depend on and import `AgentsUpdates` +as well as the domain product. Discovery, frontmatter and text rendering stay in +the domain modules. Skill-only restore and update apply only the skill domain. +`InstructionOperations.renderChatGPT` renders the locked prompt resources. +Watch remains a separate subscription API. Add inspection returns source-relative `Skill.path` and `Skill.skillFile` coordinates, never paths into a released snapshot. ## Failure and Recovery -Handle misuse throws `CoreError.invalidState` before I/O. Failures during plan -validation or application throw `UpdateApplyError`, preserving -`underlyingError` and an `UpdateApplyDisposition`: +Handle misuse fails before I/O. Apply failures are `UpdateApplyError` with the +underlying error and a disposition: | Disposition | Established result | | --- | --- | -| `unchanged` | No combined target/state publication, or validated rollback | -| `committed` | The new combined generation is confirmed; a later failure still makes the operation fail | -| `recoveryRequired` | Recovery could not establish a consistent completed generation | - -Errors before preparation finishes and caller errors retain their original -types. A commit error does not itself imply rollback: publication of the -committed marker can precede a cleanup error. Outcome tracking follows the -owning journal through validated recovery, including enclosing scope cleanup, -and does not infer disposition from journal-file presence. Cache-only -publication journals cannot claim the combined update committed. - -The next applying operation recovers an abandoned transaction and raises -`CoreError.transactionRecovered`. Consumers retry the entire preparation and -render its fresh report. Read-only preview rejects pending recovery. The -existing journal, descriptor-relative path checks, metadata preservation and -fsync barriers supply the durability guarantees described in [State](State.md). -The lock remains advisory: preconditions detect changes made while rendering -but do not provide compare-and-swap against editors racing the final check. - -## Consumer Example +| `unchanged` | No publication, or validated rollback | +| `committed` | The generation committed; a later failure still makes the operation fail | +| `recoveryRequired` | Recovery could not establish a consistent generation | + +Preparation errors retain their original type. Domain convenience APIs also unwrap unchanged apply failures; committed and recovery-required failures retain their disposition. Commit-marker publication can +precede a cleanup error, so callers must inspect the disposition before retrying. +The next writer recovers an abandoned journal and raises +`CoreError.transactionRecovered`; retry the whole preparation. Read-only access +reports pending recovery. Recovery uses sealed physical evidence and never invokes +linkers, renderers or binding providers. See [State](State.md) for durability and +concurrent-writer guarantees. ```swift import AgentsUpdates @@ -131,7 +119,5 @@ let receipt = try UpdateOperations.withPreparedUpdate { update in renderCompletion(receipt) ``` -`render` and `renderCompletion` are consumer-owned functions. Consumers should -render the combined report once before applying, use `hasChanges` for the -no-change decision, and report completion only after the closure returns. -Serialized reports are presentation values, not offline approval tokens. +`render` and `renderCompletion` belong to the consumer. Completion is reported only +after the closure returns. diff --git a/Package.swift b/Package.swift index abc8b5c..d4f3938 100644 --- a/Package.swift +++ b/Package.swift @@ -63,7 +63,8 @@ let package = Package( .target( name: "AgentsUpdates", dependencies: [ - "AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions", "CPlatform", + "AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions", "Components", + "CPlatform", ]), .target( name: "Components", @@ -76,7 +77,9 @@ let package = Package( "Components", "AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions", "StateTestProcess", "StateTestSupport", ]), - .target(name: "StateTestSupport", path: "Tests/StateTestSupport"), + .target( + name: "StateTestSupport", dependencies: ["AgentsCore", "AgentsManifest"], + path: "Tests/StateTestSupport"), .executableTarget( name: "StateTestProcess", dependencies: [ @@ -90,7 +93,10 @@ let package = Package( "AgentsCore", "AgentsManifest", "StateTestProcess", "StateTestSupport", "CPlatform", ]), .testTarget( - name: "AgentsInstructionsTests", dependencies: ["AgentsInstructions", "AgentsManifest"]), + name: "AgentsInstructionsTests", + dependencies: [ + "AgentsInstructions", "AgentsSkills", "AgentsManifest", "AgentsUpdates", "StateTestSupport", + ]), .target( name: "ManifestTestSupport", dependencies: ["AgentsManifest"], path: "Tests/ManifestTestSupport"), @@ -112,7 +118,8 @@ let package = Package( .testTarget( name: "AgentsSkillsTests", dependencies: [ - "AgentsSkills", "AgentsCore", "AgentsManifest", "AgentsInstructions", "Yams", + "AgentsSkills", "AgentsCore", "AgentsManifest", "AgentsInstructions", "AgentsUpdates", + "Yams", "StateTestProcess", "StateTestSupport", "CPlatform", ]), ], diff --git a/README.md b/README.md index 937ff5e..da52335 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ the live source for Codex and list the installed skills: ```swift import AgentsCore import AgentsSkills +import AgentsUpdates let environment = RuntimeEnvironment() _ = try SkillOperations.add(AddOptions( @@ -130,9 +131,9 @@ control. The declaration records source aliases, requirements, skill selections and recipients in the [manifest language](Documentation/Reference/Manifest.md). -Tool writes edit only the changed source ranges and keep comments. The version 1 -lock records each skill's independent revision or artifact digest, content hash -and agent-to-mode mapping. `link` uses shared cached content, `copy` writes a +Tool writes edit only the changed source ranges and keep comments. The version 2 +ledger records the full linked graph, independent pins, resources, ownership and +versioned deployments. `link` uses shared cached content, `copy` writes a directory, and `edit` links a live local source with no requirement or pin. Local Git installs in `link` and `copy` use committed content. @@ -140,8 +141,8 @@ Local Git installs in `link` and `copy` use committed content. lock models. `loadDeclaration()` preserves all component families, conditions and symbolic groups; deployment support is checked by the owning operation. Skill -operations preserve the instruction and watch declarations and the locked -instruction records. +operations use the shared composition layer and preserve recorded other-domain +semantics and watch state. Import `AgentsUpdates` for domain lifecycle methods. Mutating state operations recover interrupted transactions before proceeding and report `CoreError.transactionRecovered` when the command should be retried. The @@ -195,7 +196,7 @@ diff leave declaration, lock, watch state and installed content unchanged. ### Combined updates -`UpdateOperations.preview(...)` returns both kinds under one shared scope lock. +`UpdateOperations.preview(...)` returns the selected configuration under existing shared locks with temporary source acquisition. For application, `withPreparedUpdate(...)` prepares both kinds and holds the writer lock while the consumer renders `update.report` and calls `update.apply()`. Apply commits both kinds, changed state and pruning together. diff --git a/Sources/AgentsCore/LedgerDisplayEvidence.swift b/Sources/AgentsCore/LedgerDisplayEvidence.swift new file mode 100644 index 0000000..a920a3f --- /dev/null +++ b/Sources/AgentsCore/LedgerDisplayEvidence.swift @@ -0,0 +1,60 @@ +import Foundation + +extension TargetPrecondition { + package func capturingPublicationAccess() throws -> Self { try capturingAccess() } + /// Stable access semantics omit inode generations, timestamps and private payload digests. + package func displayEvidence(includeContent: Bool) throws -> String { + struct Access: Encodable { + let owner: UInt32 + let group: UInt32 + let mode: UInt32 + let acl: Data + let defaults: Data + init(_ evidence: FileAccessEvidence) { + owner = evidence.owner + group = evidence.group + mode = UInt32(evidence.mode) + acl = evidence.acl + defaults = evidence.defaultACL + } + } + struct Display: Encodable { + let path: String + let exists: Bool + let content: String? + let target: Access? + let ancestry: [Access] + let linkOwner: UInt32? + let linkGroup: UInt32? + } + let access = try TargetAccessPrecondition.capture(at: physicalURL) + return try ResolvedLedgerCodec.digest( + Display( + path: physicalURL.path, exists: snapshot != nil, + content: includeContent ? snapshot?.digest : nil, + target: access.target.map(Access.init), + ancestry: access.ancestry.directories.map(Access.init), linkOwner: access.linkOwner, + linkGroup: access.linkGroup)) + } +} + +extension TargetPrecondition { + /// Publication may create previously absent ancestry. Existing access and the leaf generation + /// stay fixed; the transaction separately owns every created container. + package func validateDuringPublication() throws { + try validateIdentity() + if let access { + let current = try TargetAccessPrecondition.capture(at: physicalURL) + guard current.target == access.target, current.linkOwner == access.linkOwner, + current.linkGroup == access.linkGroup, + current.ancestry.directories.starts(with: access.ancestry.directories) + else { + throw CoreError.invalidState( + "target or existing ancestry access changed during publication") + } + } + guard try FileSnapshot.read(at: url) == snapshot else { + throw CoreError.invalidState("target changed during preparation: \(url.path)") + } + } +} diff --git a/Sources/AgentsCore/LedgerProjection.swift b/Sources/AgentsCore/LedgerProjection.swift new file mode 100644 index 0000000..37856fc --- /dev/null +++ b/Sources/AgentsCore/LedgerProjection.swift @@ -0,0 +1,92 @@ +import Foundation + +extension ResolvedLedger { + /// Domain inventory views are derived from the ledger; they are never persisted as state. + package func domainProjection(roots: [String: URL]) throws -> ResolvedState { + var result = ResolvedState() + let contentSources = Set( + components.values.filter { ["skills", "instructions"].contains($0.kind) }.map(\.source)) + for (id, source) in sources where contentSources.contains(id) { + let identity = try sourceIdentity(id, roots: roots) + result.sources[identity] = LockedSource( + kind: source.kind, url: source.transport, + requirement: sourceUses.first(where: { $0.source == id })?.requirement, + path: sourceUses.first(where: { $0.source == id }).flatMap { + $0.root == "." ? nil : $0.root + }) + } + var seen = Set() + for occurrence in occurrences { + guard let component = components[occurrence.component] else { continue } + let id = occurrence.component + let source = try sourceIdentity(component.source, roots: roots) + let resource = component.resources.first.flatMap { resources[$0] } + if component.kind == DeclaredComponentKind.skills.rawValue, let resource { + let mode = component.payload.object?["mode"]?.text.flatMap(InstallMode.init) ?? .copy + let name = PathSafety.sanitizeName(component.name) + var skill = + result.skills[name] + ?? LockedSkill( + source: source, revision: component.revision, version: component.version, + artifact: resource.artifact, path: resource.path, + hash: mode == .edit ? nil : resource.hash, installs: [:]) + for agent in component.recipients { skill.installs[agent.rawValue] = mode } + result.skills[name] = skill + } else if component.kind == DeclaredComponentKind.instructions.rawValue, let resource { + let own = + resource.path.hasPrefix(".agent/instructions/") + && sources[component.source]?.revision == "live" + && sources[component.source]?.location?.root == "project" + let section = LockedSection( + name: component.name, source: own ? "." : source, + revision: component.revision, version: component.version, + artifact: resource.artifact, path: resource.path, + hash: component.payload.object?["sourceHash"]?.text ?? resource.hash) + if component.chatGPT, let prompt = component.payload.object?["prompt"]?.text { + result.instructions.chatgpt[prompt, default: LockedPrompt(sections: [])].sections.append( + section) + if let append = component.resources.dropFirst().first.flatMap({ resources[$0] }) { + result.instructions.chatgpt[prompt]?.append = append.path + } + } else if !component.recipients.isEmpty { + result.instructions.sections.append(section) + } + } + seen.insert(id) + } + for deployment in deployments where deployment.ownership != .ownedValues { + guard deployment.route != "agents/skill@1" else { continue } + let file = try deployment.target.resolve(roots: roots) + let base = roots["project"]! + let home = roots["home"]! + let key: String + if deployment.target.root == "project" { + key = PathSafety.relativePath(file.path, to: base.path) + } else if PathSafety.isContained(file, in: home) { + key = "~/" + PathSafety.relativePath(file.path, to: home.path) + } else { + key = file.path + } + result.instructions.targets[key] = LockedTarget( + agents: deployment.recipients, headingOffset: deployment.headingOffset, + import: deployment.importReference, blockHash: deployment.expectedHash, + created: deployment.created) + } + return result + } + + package func sourceIdentity(_ id: String, roots: [String: URL]) throws -> String { + guard let source = sources[id] else { throw CoreError.invalidState("missing ledger source") } + if let parent = source.container { + return try sourceIdentity(parent, roots: roots) + (source.namespace ?? "") + } + if let location = source.location { + return "local:" + (try location.resolve(roots: roots).path) + } + if let transport = source.transport { + return try SourceDeclaration(kind: source.kind, location: transport).identity( + environment: RuntimeEnvironment(environment: [:])) + } + throw CoreError.invalidState("missing source identity coordinates") + } +} diff --git a/Sources/AgentsCore/LedgerStateStore.swift b/Sources/AgentsCore/LedgerStateStore.swift index c96d247..d6c41b1 100644 --- a/Sources/AgentsCore/LedgerStateStore.swift +++ b/Sources/AgentsCore/LedgerStateStore.swift @@ -1,15 +1,51 @@ import Foundation extension StateStore { - /// Internal v2 access preserves the existing read/recovery boundary; public v1 readers reject v2. + /// Reads the complete committed v2 ledger without resolution, recovery or persistent writes. + public func loadLedger() throws -> ResolvedLedger { + try loadLedger(limits: .standard) + } + + /// Reads the single resolved ledger without recovery or persistent writes. package func loadLedger(limits: LedgerLimits) throws -> ResolvedLedger { try withReadLock { _ = try declarationBytes() - guard let bytes = try ledgerBytes(limits: limits) else { - throw CoreError.notFound("resolved ledger") + return try readLedger(limits: limits) + } + } + + package func readLedger( + prepared: StatePrecondition? = nil, limits: LedgerLimits = .standard + ) throws -> ResolvedLedger { + let bytes = + try prepared.map { try $0.bytes(for: resolvedURL) } + ?? ledgerBytes(limits: limits) + guard let bytes else { return ResolvedLedger() } + do { return try ResolvedLedgerCodec.decode(bytes, limits: limits) } catch let error + as DecodingError + { throw CoreError.invalidState("invalid resolved ledger: " + String(describing: error)) } + } + + package var ledgerRoots: [String: URL] { + var roots = [ + "project": environment.projectDirectory, "home": environment.homeDirectory, + "state": directory, + ] + roots[NativeTargetRoute.projectRoot] = environment.projectDirectory.resolvingSymlinksInPath() + roots[NativeTargetRoute.globalRoot] = + environment.environment["CLAUDE_CONFIG_DIR"].flatMap { + $0.isEmpty ? nil : URL(fileURLWithPath: $0) + } ?? environment.homeDirectory + roots[NativeTargetRoute.globalRoot] = roots[NativeTargetRoute.globalRoot]? + .resolvingSymlinksInPath() + for agent in AgentID.allCases { + roots["skills-" + agent.rawValue] = AgentRegistry.installSkillsDirectory( + for: agent, scope: scope, environment: environment) + if let file = InstructionLocations.file(for: agent, scope: scope, environment: environment) { + roots["instructions-" + agent.rawValue] = file.deletingLastPathComponent() } - return try ResolvedLedgerCodec.decode(bytes, limits: limits) } + return roots } package func stageLedger( @@ -34,20 +70,7 @@ extension StateStore { /// Ref cleanup consumes the committed closure after physical journal recovery. func retentionReferences() throws -> RetentionReferences { guard let bytes = try ledgerBytes(limits: .standard) else { return RetentionReferences() } - struct Version: Decodable { let version: Int } - // This boundary is used only by recovery's cache reconciliation, never to reinterpret v2 - // as a v1 lifecycle model. Admission bounds decoding before examining the version. - try LedgerAdmission.check(bytes, limits: LedgerLimits.standard) - let version = try JSONDecoder().decode(Version.self, from: bytes).version - if version == 2 { - return try RetentionReferences( - ledger: ResolvedLedgerCodec.decode(bytes, limits: LedgerLimits.standard), - roots: [ - "project": environment.projectDirectory, "home": environment.homeDirectory, - "state": directory, - ]) - } - let resolved = try StateStore.decode(bytes, as: ResolvedState.self) - return try RetentionReferences(resolved: resolved, cache: SourceCache(store: self)) + return try RetentionReferences( + ledger: ResolvedLedgerCodec.decode(bytes, limits: .standard), roots: ledgerRoots) } } diff --git a/Sources/AgentsCore/ResolvedLedger.swift b/Sources/AgentsCore/ResolvedLedger.swift index 09c9150..ab5dfab 100644 --- a/Sources/AgentsCore/ResolvedLedger.swift +++ b/Sources/AgentsCore/ResolvedLedger.swift @@ -1,31 +1,31 @@ import Foundation /// Version 2 of the scope's single resolved file. Arrays preserve contribution and render order. -package struct ResolvedLedger: Codable, Equatable, Sendable { - package var version = 2 - package var sources: [String: LedgerSource] = [:] - package var sourceUses: [LedgerSourceUse] = [] - package var components: [String: LedgerComponent] = [:] - package var occurrences: [LedgerOccurrence] = [] - package var groups: [LedgerGroup] = [] - package var resources: [String: LedgerResource] = [:] - package var deployments: [LedgerDeployment] = [] - package var lowerings: [LockedLowering] = [] +public struct ResolvedLedger: Codable, Equatable, Sendable { + public var version = 2 + public var sources: [String: LedgerSource] = [:] + public var sourceUses: [LedgerSourceUse] = [] + public var components: [String: LedgerComponent] = [:] + public var occurrences: [LedgerOccurrence] = [] + public var groups: [LedgerGroup] = [] + public var resources: [String: LedgerResource] = [:] + public var deployments: [LedgerDeployment] = [] + public var lowerings: [LockedLowering] = [] /// Digest-keyed non-secret bytes. These are authoritative; materializations are disposable. - package var contentObjects: [String: Data] = [:] - package init() {} + public var contentObjects: [String: Data] = [:] + public init() {} } -package struct LedgerSource: Codable, Equatable, Sendable { - package var kind: SourceKind - package var transport: String? - package var location: LedgerLocation? - package var revision: String - package var version: String? - package var container: String? - package var namespace: String? +public struct LedgerSource: Codable, Equatable, Sendable { + public var kind: SourceKind + public var transport: String? + public var location: LedgerLocation? + public var revision: String + public var version: String? + public var container: String? + public var namespace: String? - package init( + public init( kind: SourceKind, transport: String? = nil, location: LedgerLocation? = nil, revision: String, version: String? = nil, container: String? = nil, namespace: String? = nil ) { @@ -39,12 +39,17 @@ package struct LedgerSource: Codable, Equatable, Sendable { } } -package struct LedgerSourceUse: Codable, Equatable, Sendable { - package var source: String - package var root: String - package var requirement: SourceRequirement? +public struct LedgerSourceUse: Codable, Equatable, Sendable { + public var source: String + public var root: String + public var requirement: SourceRequirement? - package init(source: String, root: String, requirement: SourceRequirement? = nil) { + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.source == rhs.source && lhs.root == rhs.root + && ledgerRequirementsEqual(lhs.requirement, rhs.requirement) + } + + public init(source: String, root: String, requirement: SourceRequirement? = nil) { self.source = source self.root = root self.requirement = requirement @@ -52,11 +57,11 @@ package struct LedgerSourceUse: Codable, Equatable, Sendable { } /// Physical URLs are supplied by the caller. Absolute authored locations retain their meaning. -package struct LedgerLocation: Codable, Equatable, Hashable, Sendable { - package enum Kind: String, Codable, Sendable { case registered, authoringRelative, absolute } - package var kind: Kind - package var root: String? - package var path: String +public struct LedgerLocation: Codable, Equatable, Hashable, Sendable { + public enum Kind: String, Codable, Sendable { case registered, authoringRelative, absolute } + public var kind: Kind + public var root: String? + public var path: String package func resolve(roots: [String: URL]) throws -> URL { try validate() @@ -89,7 +94,7 @@ package struct LedgerLocation: Codable, Equatable, Hashable, Sendable { } } - package init(kind: Kind, root: String? = nil, path: String) { + public init(kind: Kind, root: String? = nil, path: String) { self.kind = kind self.root = root self.path = path @@ -97,38 +102,38 @@ package struct LedgerLocation: Codable, Equatable, Hashable, Sendable { } /// A closed tagged value vocabulary, independent of Swift's synthesized enum representation. -package struct LedgerValue: Codable, Equatable, Sendable { - package enum Kind: String, Codable, Sendable { +public struct LedgerValue: Codable, Equatable, Sendable { + public enum Kind: String, Codable, Sendable { case string, integer, decimal, boolean, null, array, object, literal, environment, secret } - package var kind: Kind - package var text: String? - package var integer: Int? - package var boolean: Bool? - package var array: [LedgerValue]? - package var object: [String: LedgerValue]? - - package init(_ text: String, kind: Kind = .string) { + public var kind: Kind + public var text: String? + public var integer: Int? + public var boolean: Bool? + public var array: [LedgerValue]? + public var object: [String: LedgerValue]? + + public init(_ text: String, kind: Kind = .string) { self.kind = kind self.text = text } - package init(integer: Int) { + public init(integer: Int) { kind = .integer self.integer = integer } - package init(boolean: Bool) { + public init(boolean: Bool) { kind = .boolean self.boolean = boolean } - package init(array: [LedgerValue]) { + public init(array: [LedgerValue]) { kind = .array self.array = array } - package init(object: [String: LedgerValue]) { + public init(object: [String: LedgerValue]) { kind = .object self.object = object } - package init() { kind = .null } + public init() { kind = .null } package func validate() throws { let fields = [text != nil, integer != nil, boolean != nil, array != nil, object != nil] @@ -149,34 +154,34 @@ package struct LedgerValue: Codable, Equatable, Sendable { } } -package struct LedgerCondition: Codable, Equatable, Sendable { - package var agents: [AgentID]? - package var scopes: [InstallScope]? - package var platforms: [String]? +public struct LedgerCondition: Codable, Equatable, Sendable { + public var agents: [AgentID]? + public var scopes: [InstallScope]? + public var platforms: [String]? - package init(_ condition: DeclarationCondition) { + public init(_ condition: DeclarationCondition) { agents = condition.agents scopes = condition.scopes platforms = condition.platforms?.map(\.rawValue) } } -package struct LedgerComponent: Codable, Equatable, Sendable { - package var declaringSource: String - package var source: String - package var root: String - package var group: String? - package var kind: String - package var name: String - package var revision: String? - package var version: String? - package var payload: LedgerValue - package var conditions: [LedgerCondition] - package var recipients: [AgentID] - package var chatGPT: Bool - package var resources: [String] - - package init( +public struct LedgerComponent: Codable, Equatable, Sendable { + public var declaringSource: String + public var source: String + public var root: String + public var group: String? + public var kind: String + public var name: String + public var revision: String? + public var version: String? + public var payload: LedgerValue + public var conditions: [LedgerCondition] + public var recipients: [AgentID] + public var chatGPT: Bool + public var resources: [String] + + public init( declaringSource: String, source: String, root: String, group: String? = nil, kind: String, name: String, revision: String? = nil, version: String? = nil, payload: LedgerValue, conditions: [LedgerCondition], recipients: [AgentID], chatGPT: Bool, resources: [String] @@ -197,18 +202,18 @@ package struct LedgerComponent: Codable, Equatable, Sendable { } } -package struct LedgerOccurrence: Codable, Equatable, Sendable { - package var declaringSource: String - package var manifestPath: String - package var id: Int - package var component: String - package var reference: Int? - package var dependencies: [String] - package var condition: LedgerCondition - package var recipients: [AgentID] - package var consumerEditable: Bool - - package init( +public struct LedgerOccurrence: Codable, Equatable, Sendable { + public var declaringSource: String + public var manifestPath: String + public var id: Int + public var component: String + public var reference: Int? + public var dependencies: [String] + public var condition: LedgerCondition + public var recipients: [AgentID] + public var consumerEditable: Bool + + public init( declaringSource: String, manifestPath: String, id: Int, component: String, reference: Int? = nil, dependencies: [String], condition: LedgerCondition, recipients: [AgentID], consumerEditable: Bool @@ -225,17 +230,23 @@ package struct LedgerOccurrence: Codable, Equatable, Sendable { } } -package struct LedgerGroup: Codable, Equatable, Sendable { - package var id: Int - package var parent: Int? - package var source: String - package var root: String - package var name: String - package var requirement: SourceRequirement? - package var manifestHash: String - package var children: [Int] - - package init( +public struct LedgerGroup: Codable, Equatable, Sendable { + public var id: Int + public var parent: Int? + public var source: String + public var root: String + public var name: String + public var requirement: SourceRequirement? + public var manifestHash: String + public var children: [Int] + + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.id == rhs.id && lhs.parent == rhs.parent && lhs.source == rhs.source && lhs.root == rhs.root + && lhs.name == rhs.name && lhs.manifestHash == rhs.manifestHash + && lhs.children == rhs.children && ledgerRequirementsEqual(lhs.requirement, rhs.requirement) + } + + public init( id: Int, parent: Int? = nil, source: String, root: String, name: String, requirement: SourceRequirement? = nil, manifestHash: String, children: [Int] ) { @@ -250,16 +261,16 @@ package struct LedgerGroup: Codable, Equatable, Sendable { } } -package struct LedgerEntry: Codable, Equatable, Sendable { - package enum Kind: String, Codable, Sendable { case file, directory, symlink } - package var path: String - package var kind: Kind - package var object: String? - package var link: String? - package var executable: Bool - package var byteCount: Int? +public struct LedgerEntry: Codable, Equatable, Sendable { + public enum Kind: String, Codable, Sendable { case file, directory, symlink } + public var path: String + public var kind: Kind + public var object: String? + public var link: String? + public var executable: Bool + public var byteCount: Int? - package init( + public init( path: String, kind: Kind, object: String? = nil, link: String? = nil, executable: Bool, byteCount: Int? = nil ) { @@ -272,19 +283,19 @@ package struct LedgerEntry: Codable, Equatable, Sendable { } } -package struct LedgerResource: Codable, Equatable, Sendable { - package enum Kind: String, Codable, Sendable { case git, artifact, embedded, liveEdit } - package var kind: Kind - package var source: String - package var path: String - package var hash: String +public struct LedgerResource: Codable, Equatable, Sendable { + public enum Kind: String, Codable, Sendable { case git, artifact, embedded, liveEdit } + public var kind: Kind + public var source: String + public var path: String + public var hash: String /// Single files use path "."; directory entries are relative to the selected resource. - package var entries: [LedgerEntry] - package var support: [LedgerEntry] - package var artifact: LockedArtifact? - package var location: LedgerLocation? + public var entries: [LedgerEntry] + public var support: [LedgerEntry] + public var artifact: LockedArtifact? + public var location: LedgerLocation? - package init( + public init( kind: Kind, source: String, path: String, hash: String, entries: [LedgerEntry], support: [LedgerEntry] = [], artifact: LockedArtifact? = nil, location: LedgerLocation? = nil ) { @@ -299,20 +310,20 @@ package struct LedgerResource: Codable, Equatable, Sendable { } } -package struct LedgerDeployment: Codable, Equatable, Sendable { - package enum Ownership: String, Codable, Sendable { case generated, importBlock, ownedValues } - package var id: String - package var target: LedgerLocation - package var route: String - package var owners: [String] - package var recipients: [AgentID] - package var ownership: Ownership - package var expectedHash: String - package var created: Bool - package var importReference: String? - package var headingOffset: Int? - - package init( +public struct LedgerDeployment: Codable, Equatable, Sendable { + public enum Ownership: String, Codable, Sendable { case generated, importBlock, ownedValues } + public var id: String + public var target: LedgerLocation + public var route: String + public var owners: [String] + public var recipients: [AgentID] + public var ownership: Ownership + public var expectedHash: String + public var created: Bool + public var importReference: String? + public var headingOffset: Int? + + public init( id: String, target: LedgerLocation, route: String, owners: [String], recipients: [AgentID], ownership: Ownership, expectedHash: String, created: Bool, importReference: String? = nil, headingOffset: Int? = nil @@ -331,17 +342,17 @@ package struct LedgerDeployment: Codable, Equatable, Sendable { } /// Format identity fixes schema, ordering, paths, resource mappings and serialization semantics. -package struct LockedLowering: Codable, Equatable, Sendable { - package var id: String - package var format: String - package var inputs: [String] - package var resources: [String] - package var deployments: [String] - package var layout: LedgerValue - package var platform: String - package var artifacts: [LedgerArtifactDigest] - - package init( +public struct LockedLowering: Codable, Equatable, Sendable { + public var id: String + public var format: String + public var inputs: [String] + public var resources: [String] + public var deployments: [String] + public var layout: LedgerValue + public var platform: String + public var artifacts: [LedgerArtifactDigest] + + public init( id: String, format: String, inputs: [String], resources: [String], deployments: [String], layout: LedgerValue, platform: String, artifacts: [LedgerArtifactDigest] ) { @@ -356,13 +367,13 @@ package struct LockedLowering: Codable, Equatable, Sendable { } } -package struct LedgerArtifactDigest: Codable, Equatable, Sendable { - package enum Kind: String, Codable, Sendable { case file, tree, ownedValues, registration, link } - package var name: String - package var kind: Kind - package var hash: String +public struct LedgerArtifactDigest: Codable, Equatable, Sendable { + public enum Kind: String, Codable, Sendable { case file, tree, ownedValues, registration, link } + public var name: String + public var kind: Kind + public var hash: String - package init(name: String, kind: Kind, hash: String) { + public init(name: String, kind: Kind, hash: String) { self.name = name self.kind = kind self.hash = hash @@ -376,3 +387,11 @@ package func ledgerPath(_ path: String) throws { throw CoreError.invalidState("noncanonical ledger path") } } + +private func ledgerRequirementsEqual(_ lhs: SourceRequirement?, _ rhs: SourceRequirement?) -> Bool { + switch (lhs, rhs) { + case (nil, nil): true + case (.some(let left), .some(let right)): left == right || left.declarationEquivalent(to: right) + default: false + } +} diff --git a/Sources/AgentsCore/ResolvedState.swift b/Sources/AgentsCore/ResolvedState.swift index fbe49b8..7de8947 100644 --- a/Sources/AgentsCore/ResolvedState.swift +++ b/Sources/AgentsCore/ResolvedState.swift @@ -184,7 +184,7 @@ public struct LockedInstructions: Codable, Equatable, Sendable { } } -/// Version 1 of agents.resolved. Every item carries its independent immutable pin. +/// Skill/instruction inventory projection. The persisted ledger owns pins and deployments. public struct ResolvedState: Codable, Equatable, Sendable { public var version: Int public var sources: [String: LockedSource] diff --git a/Sources/AgentsCore/ResolvedStateEncoding.swift b/Sources/AgentsCore/ResolvedStateEncoding.swift deleted file mode 100644 index 1f00b97..0000000 --- a/Sources/AgentsCore/ResolvedStateEncoding.swift +++ /dev/null @@ -1,26 +0,0 @@ -import Foundation - -extension ResolvedState { - /// Producers compare the complete ledger before serializing. An unchanged ledger retains - /// its original bytes even when a declaration or physical target needs a transaction. - package func replacementData(comparedTo existing: Data?) throws -> Data? { - if let existing { - let previous = try StateStore.decode(existing, as: ResolvedState.self) - if normalized == previous.normalized { return nil } - } - return try StateStore.encodeState(normalized) - } - - /// The replacement for the prepared generation's lock. A scope whose prepared generation has - /// neither a lock nor a declaration receives no empty ledger, because lock state without a - /// declaration stops every later access to the scope. - package func replacementData(in store: StateStore, prepared: StatePrecondition) throws -> Data? { - let existing = try prepared.bytes(for: store.resolvedURL) - if existing == nil, try prepared.bytes(for: store.declarationURL) == nil, - normalized == ResolvedState().normalized - { - return nil - } - return try replacementData(comparedTo: existing) - } -} diff --git a/Sources/AgentsCore/RetentionReferences.swift b/Sources/AgentsCore/RetentionReferences.swift index 0ac3d7c..bf6fe64 100644 --- a/Sources/AgentsCore/RetentionReferences.swift +++ b/Sources/AgentsCore/RetentionReferences.swift @@ -33,6 +33,7 @@ package struct RetentionReferences: Sendable { git.insert(.init(source: identity, revision: source.revision)) sourceLocations[identity] = location } + artifacts.formUnion(ledger.resources.filter { $0.value.kind != .liveEdit }.keys) for resource in ledger.resources.values { if let artifact = resource.artifact { retain(artifact) } if resource.kind == .liveEdit, let location = resource.location { @@ -41,36 +42,6 @@ package struct RetentionReferences: Sendable { } } - init(resolved: ResolvedState, cache: SourceCache) throws { - try resolved.validate() - for (id, source) in resolved.sources where source.kind != .wellKnown { - sourceLocations[id] = source.kind == .local ? String(id.dropFirst(6)) : source.url - } - for skill in resolved.skills.values { - if let revision = skill.revision { - git.insert(.init(source: skill.source, revision: revision)) - } - if let artifact = skill.artifact { retain(artifact) } - if skill.installs.values.contains(.edit), let source = resolved.sources[skill.source] { - let root = - source.kind == .local - ? URL(fileURLWithPath: String(skill.source.dropFirst(6))) - : cache.store.directory - live.append( - try PathSafety.resolvedChild(base: root, subpath: skill.path ?? ".") - .resolvingSymlinksInPath()) - } - } - for section in resolved.instructions.sections - + resolved.instructions.chatgpt.values.flatMap(\.sections) - { - if let revision = section.revision { - git.insert(.init(source: section.source, revision: revision)) - } - if let artifact = section.artifact { retain(artifact) } - } - } - package mutating func include(watch: WatchState) throws { try watch.validate() for (id, source) in watch.sources { diff --git a/Sources/AgentsCore/SourceCache.swift b/Sources/AgentsCore/SourceCache.swift index c07d08c..86be8c6 100644 --- a/Sources/AgentsCore/SourceCache.swift +++ b/Sources/AgentsCore/SourceCache.swift @@ -550,19 +550,6 @@ package struct SourceCache { } } - /// Retains pins and any cache tree containing a live edit source. - /// The caller holds the scope lock, including during failure cleanup. - package func prune( - referencedBy lock: ResolvedState, watch: WatchState? = nil, - transaction: FileTransaction? = nil - ) throws { - var references = try RetentionReferences(resolved: lock, cache: self) - try references.include(watch: watch ?? store.readWatch()) - let transactionToUse = transaction ?? FileTransaction(store: store) - try prune(references: references, transaction: transactionToUse) - if transaction == nil { try transactionToUse.commit() } - } - /// The caller stages pruning with its state generation and commits only after validation. package func prune(references: RetentionReferences, transaction: FileTransaction) throws { guard let scope = try store.openDirectoryIfPresent(), try scope.info("cache") != nil else { @@ -592,7 +579,10 @@ package struct SourceCache { let tree = try source.child(pin) if !paths.contains(tree.url.path) && !edited(tree.url) { unused.append(pin) } } - if unused.count == pins.count { + let retainsDescendant = paths.contains { + PathSafety.isContained(URL(fileURLWithPath: $0), in: source.url) + } + if unused.count == pins.count && !retainsDescendant { try transactionToUse.delete(materialized.url.appendingPathComponent(name)) } else { for pin in unused { try transactionToUse.delete(source.url.appendingPathComponent(pin)) } diff --git a/Sources/AgentsCore/StateStore.swift b/Sources/AgentsCore/StateStore.swift index 4d3f04f..1bd580d 100644 --- a/Sources/AgentsCore/StateStore.swift +++ b/Sources/AgentsCore/StateStore.swift @@ -51,9 +51,7 @@ public struct StateStore: Sendable { } package func readResolved(prepared: StatePrecondition? = nil) throws -> ResolvedState { - let lock: ResolvedState = try load(resolvedURL, prepared: prepared) ?? ResolvedState() - try lock.validate() - return lock + try readLedger(prepared: prepared).domainProjection(roots: ledgerRoots) } /// Reads watch state under a shared lock, without recovery or creating files. @@ -108,9 +106,9 @@ public struct StateStore: Sendable { if ![".agents.lock", TransactionJournal.fileName, "watch-refs.pending"].contains(where: { FileManager.default.fileExists(atPath: directory.appendingPathComponent($0).path) }) { - _ = try readResolved() - _ = try readWatch() _ = try declarationBytes() + _ = try readLedger() + _ = try readWatch() } let base = scope == .project ? environment.projectDirectory : environment.homeDirectory let physicalDirectory = base.resolvingSymlinksInPath().appendingPathComponent( diff --git a/Sources/AgentsCore/UpdatePreconditions.swift b/Sources/AgentsCore/UpdatePreconditions.swift index 587cdb7..6314ffb 100644 --- a/Sources/AgentsCore/UpdatePreconditions.swift +++ b/Sources/AgentsCore/UpdatePreconditions.swift @@ -146,14 +146,21 @@ package struct TargetPrecondition { struct TargetAccessPrecondition: Equatable { let ancestry: DirectoryAccessEvidence let target: FileAccessEvidence? + let linkOwner: UInt32? + let linkGroup: UInt32? static func capture(at url: URL) throws -> Self { let parentURL = url.deletingLastPathComponent() let ancestry = try DirectoryAccessEvidence.capture(at: parentURL) let complete = ancestry.directories.count == parentURL.standardizedFileURL.pathComponents.count + var info = stat() + let link = lstat(url.path, &info) == 0 && info.st_mode & S_IFMT == S_IFLNK let target = - try complete ? DirectoryHandle(at: parentURL).accessEvidence(url.lastPathComponent) : nil - return Self(ancestry: ancestry, target: target) + try complete && !link + ? DirectoryHandle(at: parentURL).accessEvidence(url.lastPathComponent) : nil + return Self( + ancestry: ancestry, target: target, linkOwner: link ? info.st_uid : nil, + linkGroup: link ? info.st_gid : nil) } func validate(at url: URL) throws { diff --git a/Sources/AgentsCore/WatchOperations.swift b/Sources/AgentsCore/WatchOperations.swift index b265056..00290e0 100644 --- a/Sources/AgentsCore/WatchOperations.swift +++ b/Sources/AgentsCore/WatchOperations.swift @@ -33,7 +33,7 @@ public struct WatchOperations: Sendable { let baseline = try StatePrecondition(store: store) let previous = try declarations.read(store, baseline) var declaration = previous - let lock = try store.readResolved(prepared: baseline) + let lock = try store.readLedger(prepared: baseline) var watch = try store.readWatch(prepared: baseline) var argument = try SourceArgument(source) guard argument.name == nil else { @@ -78,7 +78,7 @@ public struct WatchOperations: Sendable { let store = StateStore(scope: scope, environment: environment) return try store.withReadLock { let declaration = try declarations.read(store, nil) - _ = try store.readResolved() + _ = try store.readLedger() let watch = try store.readWatch() return try (declaration.watch ?? []).sorted().map { alias in try inspect(alias: alias, declaration: declaration, watch: watch, store: store) @@ -94,7 +94,7 @@ public struct WatchOperations: Sendable { let store = StateStore(scope: scope, environment: environment) return try store.withReadLock { let declaration = try declarations.read(store, nil) - _ = try store.readResolved() + _ = try store.readLedger() let watch = try store.readWatch() let alias = try subscription(source, declaration: declaration, environment: environment) var result = try inspect(alias: alias, declaration: declaration, watch: watch, store: store) @@ -114,7 +114,7 @@ public struct WatchOperations: Sendable { return try store.withLock(checkpoint: checkpoint) { let baseline = try StatePrecondition(store: store) let declaration = try declarations.read(store, baseline) - let lock = try store.readResolved(prepared: baseline) + let lock = try store.readLedger(prepared: baseline) var watch = try store.readWatch(prepared: baseline) let alias = try subscription(source, declaration: declaration, environment: environment) let declared = declaration.sources[alias]! @@ -137,7 +137,7 @@ public struct WatchOperations: Sendable { let baseline = try StatePrecondition(store: store) let previous = try declarations.read(store, baseline) var declaration = previous - let lock = try store.readResolved(prepared: baseline) + let lock = try store.readLedger(prepared: baseline) var watch = try store.readWatch(prepared: baseline) let alias = try subscription(source, declaration: declaration, environment: environment) let id = try declaration.sources[alias]!.identity(environment: environment) @@ -181,7 +181,7 @@ public struct WatchOperations: Sendable { /// The prepared generation, captured before any network acknowledgment, is the journal's /// preimage evidence and also guards the lock that pruning follows. private func commit( - _ change: DeclarationChange?, watch: WatchState, lock: ResolvedState, store: StateStore, + _ change: DeclarationChange?, watch: WatchState, lock: ResolvedLedger, store: StateStore, baseline: StatePrecondition ) throws { try watch.validate() @@ -191,7 +191,9 @@ public struct WatchOperations: Sendable { try transaction.replace( store.watchURL, with: .data(StateStore.encode(watch)), expecting: baseline.evidence(for: store.watchURL)) - try SourceCache(store: store).prune(referencedBy: lock, watch: watch, transaction: transaction) + var references = try RetentionReferences(ledger: lock, roots: store.ledgerRoots) + try references.include(watch: watch) + try SourceCache(store: store).prune(references: references, transaction: transaction) try transaction.commit() } diff --git a/Sources/AgentsInstructions/InstructionDoctor.swift b/Sources/AgentsInstructions/InstructionDoctor.swift index 9f8b4ca..d818dca 100644 --- a/Sources/AgentsInstructions/InstructionDoctor.swift +++ b/Sources/AgentsInstructions/InstructionDoctor.swift @@ -23,7 +23,7 @@ extension InstructionOperations { try other.withReadLock( onPendingRecovery: { (nil, [pendingRecovery(other)]) }, { - _ = try other.readDeploymentDeclaration() + _ = try other.readDeclaration() return (try other.readResolved().instructions.sections, []) }) let root = scope == .project ? environment.projectDirectory : environment.homeDirectory @@ -33,15 +33,20 @@ extension InstructionOperations { root: root, diagnostics: otherDiagnostics + [pendingRecovery(store)]) }, { - let declaration = try store.readDeploymentDeclaration() + let declaration = try store.readDeclaration() let lock = try store.readResolved() var diagnostics = otherDiagnostics func report(_ kind: InstructionDiagnostic.Kind, _ message: String, _ path: URL? = nil) { diagnostics.append(InstructionDiagnostic(kind: kind, message: message, path: path)) } if !FileManager.default.fileExists(atPath: store.resolvedURL.path), - try !((declaration.instructions)?.sections.isEmpty ?? true) - || !((declaration.instructions)?.chatgpt?.isEmpty ?? true) + declaration.components.contains(where: { + if case .instructions(let s) = $0 { + !s.sectionReferences.isEmpty || !s.prompts.isEmpty + } else { + false + } + }) { report( .missingLock, "Instruction declaration has no lock; update can reconstruct it.", @@ -126,8 +131,15 @@ extension InstructionOperations { report(.duplicateScope, "Section is installed at both scopes: \(id)") } } - let agents = Set(lock.instructions.targets.values.flatMap(\.agents)) - .union((try declaration.instructions)?.agents ?? declaration.defaultAgents) + let selections = declaration.components.compactMap { + component -> InstructionsDeclaration? in + if case .instructions(let selection) = component { selection } else { nil } + } + let declaredAgents = + selections.isEmpty + ? declaration.defaultAgents + : selections.flatMap { $0.agents ?? declaration.defaultAgents } + let agents = Set(lock.instructions.targets.values.flatMap(\.agents)).union(declaredAgents) let claudeTargets = lock.instructions.targets.filter { $0.value.import == nil && $0.value.agents.contains(.claudeCode) }.keys.sorted() diff --git a/Sources/AgentsInstructions/InstructionExport.swift b/Sources/AgentsInstructions/InstructionExport.swift index a94143e..c317079 100644 --- a/Sources/AgentsInstructions/InstructionExport.swift +++ b/Sources/AgentsInstructions/InstructionExport.swift @@ -60,39 +60,41 @@ extension InstructionOperations { return try store.withReadLock( onPendingRecovery: { empty(.pendingRecovery) }, { - _ = try store.readDeploymentDeclaration() + _ = 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] = [] - // User targets receive every section, so their placement needs no content. - for record in lock.instructions.sections { - 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) + let ledger = try store.readLedger() + let lock = try ledger.domainProjection(roots: store.ledgerRoots) + let targets = try ledger.deployments.filter { + ["agents/instructions@1", "agents/claude-import@1"].contains($0.route) + }.map { deployment in + let file = try deployment.target.resolve(roots: store.ledgerRoots) + let key = InstructionLocations.key(for: file, store: store) + let sections = try deployment.owners.compactMap { ledger.components[$0] }.compactMap { + component throws -> LockedSection? in + guard deployment.ownership != .importBlock, let id = component.resources.first, + let resource = ledger.resources[id] + else { return nil } + return LockedSection( + name: component.name, + source: try lock.instructions.sections.first(where: { + $0.name == component.name && $0.path == resource.path + && $0.revision == component.revision + })?.source + ?? (try ledger.sourceIdentity(component.source, roots: store.ledgerRoots)), + revision: component.revision, version: component.version, + artifact: resource.artifact, + path: resource.path, + hash: component.payload.object?["sourceHash"]?.text ?? resource.hash) } - } - 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) - } + target: key, agents: deployment.recipients, sections: sections, + import: deployment.importReference) + }.sorted { $0.target < $1.target } + return InstructionMapping( - scope: scope, root: root, status: .locked, targets: targets, unplaced: unplaced, + scope: scope, root: root, status: .locked, targets: targets, unplaced: [], prompts: lock.instructions.chatgpt.mapValues(\.sections)) }) } catch { diff --git a/Sources/AgentsInstructions/InstructionLifecycleModels.swift b/Sources/AgentsInstructions/InstructionLifecycleModels.swift index dd644f6..4ae02cf 100644 --- a/Sources/AgentsInstructions/InstructionLifecycleModels.swift +++ b/Sources/AgentsInstructions/InstructionLifecycleModels.swift @@ -47,14 +47,25 @@ public struct InstructionAddOutcome: Sendable { public let available: [InstructionUnit] /// Nil means source inspection or a multi-unit source awaiting a selection. public let result: InstructionUpdateReport? + + package init(sourceID: String, available: [InstructionUnit], result: InstructionUpdateReport?) { + self.sourceID = sourceID + self.available = available + self.result = result + } } -public struct InstructionSectionChange: Sendable, Equatable { +public struct InstructionSectionChange: Codable, Sendable, Equatable { public let before: LockedSection? public let after: LockedSection? + + package init(before: LockedSection?, after: LockedSection?) { + self.before = before + self.after = after + } } -public struct InstructionTargetChange: Sendable, Equatable { +public struct InstructionTargetChange: Codable, Sendable, Equatable { /// The lock's physical target key; user paths outside home are absolute. public let target: String public let url: URL @@ -77,9 +88,23 @@ public struct InstructionTargetChange: Sendable, Equatable { /// A missing previous entry (`beforeAgents == nil`) differs from any planned list. /// Use `InstructionUpdateReport.hasChanges` to detect any update in the report. public var agentsChanged: Bool { beforeAgents != afterAgents } + + package init( + target: String, url: URL, before: Data?, after: Data?, beforeAgents: [AgentID]?, + afterAgents: [AgentID], drift: InstructionDrift?, foreign: Bool + ) { + self.target = target + self.url = url + self.before = before + self.after = after + self.beforeAgents = beforeAgents + self.afterAgents = afterAgents + self.drift = drift + self.foreign = foreign + } } -public struct InstructionUpdateReport: Sendable, Equatable { +public struct InstructionUpdateReport: Codable, Sendable, Equatable { public let sections: [InstructionSectionChange] /// Every affected target, including unchanged files recorded again after loss of a lock. public let targets: [InstructionTargetChange] @@ -91,6 +116,17 @@ public struct InstructionUpdateReport: Sendable, Equatable { /// target recipients, and prompts), target bytes, or reconstructs a missing lock with targets. /// Consumers should use this property to detect updates, including changes with identical bytes. public let hasChanges: Bool + + package init( + sections: [InstructionSectionChange], targets: [InstructionTargetChange], + changedPrompts: [String], lockMissing: Bool, hasChanges: Bool + ) { + self.sections = sections + self.targets = targets + self.changedPrompts = changedPrompts + self.lockMissing = lockMissing + self.hasChanges = hasChanges + } } public struct InstructionDiagnostic: Sendable, Equatable { diff --git a/Sources/AgentsInstructions/InstructionModels.swift b/Sources/AgentsInstructions/InstructionModels.swift index 6b7b462..1fa3003 100644 --- a/Sources/AgentsInstructions/InstructionModels.swift +++ b/Sources/AgentsInstructions/InstructionModels.swift @@ -22,7 +22,7 @@ public struct InstructionSection: Sendable, Equatable { public var directory: String { Instructions.directory(for: paths) } } -public enum InstructionDrift: Sendable, Equatable { +public enum InstructionDrift: Codable, Sendable, Equatable { case clean case drifted case missing diff --git a/Sources/AgentsInstructions/InstructionOperations.swift b/Sources/AgentsInstructions/InstructionOperations.swift index 1929a7c..d528877 100644 --- a/Sources/AgentsInstructions/InstructionOperations.swift +++ b/Sources/AgentsInstructions/InstructionOperations.swift @@ -2,122 +2,14 @@ import AgentsCore import AgentsManifest import Foundation -/// Scope-bound instruction workflows. Consumers own argument parsing and difference presentation. public enum InstructionOperations { - /// A thrown callback cancels before target, declaration or lock replacements. - public static func add( - _ options: InstructionAddOptions, - beforeApply: ((InstructionUpdateReport) throws -> Void)? = nil - ) throws -> InstructionAddOutcome { - var automaticSelection: (sourceID: String, name: String)? - if options.listOnly || (options.names.isEmpty && !options.all) { - let outcome = try add(options, apply: false, beforeApply: nil) - if options.listOnly || outcome.available.count > 1 { return outcome } - automaticSelection = outcome.available.first.map { (outcome.sourceID, $0.record.name) } - } - return try add( - options, apply: true, automaticSelection: automaticSelection, beforeApply: beforeApply) - } - - private static func add( - _ options: InstructionAddOptions, apply: Bool, - automaticSelection: (sourceID: String, name: String)? = nil, - beforeApply: ((InstructionUpdateReport) throws -> Void)? - ) throws -> InstructionAddOutcome { - let store = StateStore(scope: options.scope, environment: options.environment) - return try operate(store, apply: apply) { previousDeclaration, previous, baseline in - var declaration = previousDeclaration - let selectionChanged = CoreError.invalidState( - "automatic instruction selection changed during discovery; retry the command") - let sources = InstructionSources(store: store) - let id: String - let alias: String? - let available: [InstructionUnit] - if options.source == InstructionSources.own { - id = InstructionSources.own - alias = nil - // 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 { - 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) - } - guard options.listOnly || automaticSelection != nil || !available.isEmpty else { - throw CoreError.notFound("source provides no instructions") - } - if !apply { - return InstructionAddOutcome(sourceID: id, available: available, result: nil) - } - let selected: [InstructionUnit] - if let automaticSelection { - guard let unit = available.first(where: { $0.record.name == automaticSelection.name }) - else { throw selectionChanged } - selected = [unit] - } else if options.names.isEmpty { - selected = available - } else { - selected = try options.names.map { name in - guard let unit = available.first(where: { $0.record.name == name }) else { - throw CoreError.notFound("instruction section: \(name)") - } - return unit - } - } - guard !selected.isEmpty else { throw CoreError.notFound("source provides no instructions") } - var instructions = (try declaration.instructions) ?? InstructionsDeclaration() - if let agents = options.agents { instructions.agents = agents } - let references = selected.map { (alias.map { $0 + ":" } ?? "") + $0.record.name } - for reference in references where !instructions.sections.contains(reference) { - instructions.sections.append(reference) - } - try declaration.setInstructions(instructions) - let prepared = try prepare( - declaration: declaration, previous: previous, sources: sources, resolving: Set(references)) - let plan = try plan( - declaration: declaration, previousDeclaration: previousDeclaration, - previous: previous, prepared: prepared, store: store) - try plan.lock.validate() - let change = try store.planDeclaration( - declaration, replacing: previousDeclaration, prepared: baseline) - if !options.replace { try requireOwnership(plan.report) } - try beforeApply?(plan.report) - try Self.apply( - declaration: declaration, change: change, next: plan.lock, report: plan.report, - sources: sources, baseline: baseline, expectations: plan.expectations) - return InstructionAddOutcome(sourceID: id, available: available, result: plan.report) - } - } - - /// Returns committed, validated units. Inspection may fetch mirror objects but never publishes pins. public static func list( source: SourceDeclaration, scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> [InstructionUnit] { let store = StateStore(scope: scope, environment: environment) return try operate(store, apply: false) { _, _ in - try InstructionSources(store: store).discover(source) + try inspectSource(source, store: store) } } @@ -138,176 +30,6 @@ public enum InstructionOperations { } } - /// Resolves declared content and reports every affected target before any replacement. - /// `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) - return try operate(store, apply: apply) { previousDeclaration, previous, baseline in - var declaration = previousDeclaration - if let agents { - var instructions = (try declaration.instructions) ?? InstructionsDeclaration() - instructions.agents = agents - try declaration.setInstructions(instructions) - } - let resolutions = try SourceResolutionSession(store: store) - let plan = try prepareUpdate( - store: store, declaration: declaration, previousDeclaration: previousDeclaration, - previous: previous, resolutions: resolutions, replace: replace) - try plan.next.validate() - try baseline.validate() - if apply { - let change = try store.planDeclaration( - declaration, replacing: previousDeclaration, prepared: baseline) - if !replace { try requireOwnership(plan.report) } - try beforeApply?(plan.report) - try baseline.validate() - try plan.validate() - try plan.retain() - let transaction = FileTransaction(store: store) - transaction.requireUnchanged(since: baseline, plan) - try plan.stage(transaction: transaction) - try store.stageDeclaration(change, in: transaction, prepared: baseline) - if let data = try plan.next.replacementData(in: store, prepared: baseline) { - try transaction.replace( - store.resolvedURL, with: .data(data), - expecting: baseline.evidence(for: store.resolvedURL)) - } - try SourceCache(store: store).prune( - referencedBy: plan.next, watch: store.readWatch(prepared: baseline), - transaction: transaction) - try transaction.commit() - } - return plan.report - } - } - - /// 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, 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) - return try InstructionUpdatePlan( - next: plan.lock, report: plan.report, sources: sources, replace: replace, - expectedTargets: plan.expectations) - } - - /// Restores only recorded pins and targets, without changing either state file. - public static func installResolvedReport( - scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() - ) throws -> InstructionUpdateReport { - let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: true) { declaration, lock, baseline in - let sources = InstructionSources(store: store) - let sections = try sources.restore(lock.instructions.sections, sources: lock.sources) - for prompt in lock.instructions.chatgpt.values { - _ = try Instructions.renderChatGPT( - 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, - restoring: true) - let report = InstructionUpdateReport( - 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, change: nil, next: lock, report: report, sources: sources, - baseline: baseline, expectations: targets.expectations, writeState: false) - return report - } - } - - /// 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, - environment: RuntimeEnvironment = RuntimeEnvironment(), - beforeApply: ((InstructionUpdateReport) throws -> Void)? = nil - ) throws -> InstructionUpdateReport { - let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: true) { previousDeclaration, previous, baseline in - var declaration = previousDeclaration - var instructions = (try declaration.instructions) ?? InstructionsDeclaration() - let references = Set( - instructions.sections + (instructions.chatgpt ?? [:]).values.flatMap(\.sections)) - var removed = Set() - for name in names { - // 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)") - } - removed.insert(reference) - } - instructions.sections.removeAll { removed.contains($0) } - for name in (instructions.chatgpt ?? [:]).keys { - instructions.chatgpt?[name]?.sections.removeAll { removed.contains($0) } - if instructions.chatgpt?[name]?.sections.isEmpty == true { - instructions.chatgpt?[name] = nil - } - } - if let agents { instructions.agents = agents } - try declaration.setInstructions(instructions) - let sources = InstructionSources(store: store) - let prepared = try prepare( - declaration: declaration, previous: previous, sources: sources, resolving: []) - let plan = try plan( - declaration: declaration, previousDeclaration: previousDeclaration, - previous: previous, prepared: prepared, store: store) - try plan.lock.validate() - let change = try store.planDeclaration( - declaration, replacing: previousDeclaration, prepared: baseline) - try requireOwnership(plan.report) - try beforeApply?(plan.report) - try apply( - declaration: declaration, change: change, next: plan.lock, report: plan.report, - sources: sources, baseline: baseline, expectations: plan.expectations) - return plan.report - } - } - - /// Appends the current custom file to verified locked sections; never resolves declared requirements. - public static func renderChatGPT( - prompt name: String, scope: InstallScope = .project, - environment: RuntimeEnvironment = RuntimeEnvironment() - ) throws -> Data { - let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: false) { _, lock in - guard let prompt = lock.instructions.chatgpt[name], !prompt.sections.isEmpty else { - throw InstructionError.emptyPrompt - } - let sections = try InstructionSources(store: store).restore( - prompt.sections, sources: lock.sources) - var custom: Data? - if let append = prompt.append { - let root = scope == .project ? environment.projectDirectory : environment.homeDirectory - let file = try PathSafety.resolvedChild(base: root, subpath: append) - try InstructionSources.contained(file, in: root) - custom = try FileSystem.read(at: file) - } - return try Instructions.renderChatGPT( - sections: sections.map(\.section), customContent: custom) - } - } - /// 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 @@ -338,173 +60,50 @@ public enum InstructionOperations { } } - private static func prepare( - declaration: Declaration, previous: ResolvedState, sources: InstructionSources, - resolving: Set? = nil - ) throws -> (lock: ResolvedState, sections: [InstructionSection]) { - try declaration.validate(environment: sources.store.environment) - var next = previous - next.instructions = LockedInstructions() - let old = - previous.instructions.sections + previous.instructions.chatgpt.values.flatMap(\.sections) - func units(_ references: [String], locked: [LockedSection]) throws -> [InstructionUnit] { - try references.map { reference in - // 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) - { - 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] - } - } - let sections = try units( - (try declaration.instructions)?.sections ?? [], locked: previous.instructions.sections) - next.instructions.sections = sections.map(\.record) - for (name, prompt) in ((try declaration.instructions)?.chatgpt ?? [:]).sorted(by: { - $0.key < $1.key - }) { - let selected = try units( - prompt.sections, locked: previous.instructions.chatgpt[name]?.sections ?? []) - _ = try Instructions.renderChatGPT(sections: selected.map(\.section)) - next.instructions.chatgpt[name] = LockedPrompt( - sections: selected.map(\.record), append: prompt.append) - } - return (next, sections.map(\.section)) - } - - private static func plan( - declaration: Declaration, previousDeclaration: Declaration, previous: ResolvedState, - prepared: (lock: ResolvedState, sections: [InstructionSection]), store: StateStore - ) throws -> ( - lock: ResolvedState, report: InstructionUpdateReport, expectations: [String: TargetPrecondition] - ) { - var next = prepared.lock - let targets = try InstructionTargets(store: store).plan( - sections: prepared.sections, - agents: (try declaration.instructions)?.agents ?? declaration.defaultAgents, - previous: previous.instructions) - next.instructions.targets = targets.targets - try InstructionTargets.validateSourceDirectories(targets.changes, sources: next.sources) - let before = previous.instructions.sections - let after = next.instructions.sections - let identities = Set((before + after).map(InstructionSources.identity)) - let changes = identities.sorted().compactMap { id -> InstructionSectionChange? in - let old = before.first { InstructionSources.identity($0) == id } - let new = after.first { InstructionSources.identity($0) == id } - return old == new ? nil : InstructionSectionChange(before: old, after: new) - } - let prompts = Set(previous.instructions.chatgpt.keys).union(next.instructions.chatgpt.keys) - .sorted().filter { name in - let old = previous.instructions.chatgpt[name] - let new = next.instructions.chatgpt[name] - return old?.append != new?.append - || old?.sections.map { InstructionSources.identity($0) + $0.hash } - != new?.sections.map { InstructionSources.identity($0) + $0.hash } - } - let lockMissing = !FileManager.default.fileExists(atPath: store.resolvedURL.path) - let hasChanges = - declaration.normalized != previousDeclaration.normalized - || next.normalized != previous.normalized || targets.changes.contains(where: \.changed) - || (lockMissing && !targets.changes.isEmpty) - return ( - next, - InstructionUpdateReport( - sections: changes, targets: targets.changes, changedPrompts: prompts, - lockMissing: lockMissing, hasChanges: hasChanges), - targets.expectations - ) - } - - /// 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) } - } - - /// `change` is the declaration edit planned before any callback, retention or staging. - private static func apply( - declaration: Declaration, change: DeclarationChange?, next: ResolvedState, - report: InstructionUpdateReport, sources: InstructionSources, baseline: StatePrecondition, - expectations: [String: TargetPrecondition], writeState: Bool = true - ) throws { - let store = sources.store - try declaration.validate(environment: store.environment) - try next.validate() - let plan = try InstructionUpdatePlan( - next: next, report: report, sources: sources, replace: true, expectedTargets: expectations) - try baseline.validate() - try plan.validate() - do { - try plan.retain() - let transaction = FileTransaction(store: store) - transaction.requireUnchanged(since: baseline, plan) - try plan.stage(transaction: transaction) - if writeState { - try store.stageDeclaration(change, in: transaction, prepared: baseline) - if let data = try next.replacementData(in: store, prepared: baseline) { - try transaction.replace( - store.resolvedURL, with: .data(data), - expecting: baseline.evidence(for: store.resolvedURL)) - } - } - try sources.cache.prune( - referencedBy: next, watch: store.readWatch(prepared: baseline), transaction: transaction) - try transaction.commit() - } catch { - if let recovered = try? store.readResolved() { - try? sources.cache.prune(referencedBy: recovered) - } - throw error - } - } - - private static func operate(_ store: StateStore, apply: Bool, _ body: () throws -> T) throws - -> T - { - if apply { return try store.withLock(body) } - return try store.withReadLock(body) - } - static func operate( _ store: StateStore, apply: Bool, _ body: (Declaration, ResolvedState) throws -> T ) throws -> T { if apply { return try store.withLock { - try body(store.readDeploymentDeclaration(), store.readResolved()) + try body(store.readDeclaration(), store.readResolved()) } } return try store.withReadLock { - try body(store.readDeploymentDeclaration(), store.readResolved()) + try body(store.readDeclaration(), store.readResolved()) } } - private static func operate( - _ store: StateStore, apply: Bool, - _ body: (Declaration, ResolvedState, StatePrecondition) throws -> T - ) throws -> T { - try operate(store, apply: apply) { - let baseline = try StatePrecondition(store: store) - return try body( - store.readDeploymentDeclaration(prepared: baseline), store.readResolved(prepared: baseline), - baseline) - } +} + +extension InstructionOperations { + package static func inspectOwn(names: [String], environment: RuntimeEnvironment) throws + -> [InstructionUnit] + { + let sources = InstructionSources(store: StateStore(scope: .project, environment: environment)) + return try names.isEmpty ? sources.own() : names.map(sources.own(named:)) } +} - private static func sourceDeclaration(_ options: InstructionAddOptions, declaration: Declaration) - throws -> SourceDeclaration +extension InstructionOperations { + package static func inspectSource(_ source: SourceDeclaration, store: StateStore) throws + -> [InstructionUnit] { - let argument = try SourceArgument(options.source) - guard argument.name == nil else { - throw CoreError.invalidSource("@skill: selects skills; pass section names separately") + try SourceResolutionSession.withTemporaryRead(store: store) { session in + guard source.kind != .wellKnown else { + throw CoreError.unsupported("instructions require source files") + } + if try session.isGitSource(source) { + return try InstructionSources(store: store, resolutions: session).discover( + source, cacheSource: false) + } + let view = try session.localSnapshot(source) + return try InstructionSnapshotReader.read(view).map { unit in + InstructionUnit( + record: LockedSection( + name: unit.name, source: view.snapshot.source, + revision: view.pin?.revision, version: view.pin?.version, + path: unit.path, hash: unit.section.hash), section: unit.section) + } } - let selection = try argument.selection( - in: declaration, requirement: options.sourceRequirement, path: options.path, - environment: options.environment) - return selection.applied(to: selection.source) } } diff --git a/Sources/AgentsInstructions/InstructionSources.swift b/Sources/AgentsInstructions/InstructionSources.swift index 04ad541..6d70be3 100644 --- a/Sources/AgentsInstructions/InstructionSources.swift +++ b/Sources/AgentsInstructions/InstructionSources.swift @@ -21,12 +21,6 @@ final class InstructionSources { cache = SourceCache(store: store) } - func lockedSource(_ source: SourceDeclaration) -> LockedSource { - LockedSource( - kind: source.kind, url: source.kind == .git ? source.gitURL : nil, - requirement: source.requirement, path: source.path) - } - func discover(_ source: SourceDeclaration, cacheSource: Bool = true) throws -> [InstructionUnit] { let id = try source.identity(environment: store.environment) if let units = discovered[id] { return units } @@ -107,30 +101,41 @@ final class InstructionSources { 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 { - return try own(named: reference) - } - guard let source = declaration.sources[alias] else { - throw CoreError.invalidState("invalid instruction reference: \(reference)") - } - 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) - return unit - } - } - func restore( _ records: [LockedSection], sources: [String: LockedSource], cachedOnly: Bool = false ) throws -> [InstructionUnit] { try records.map { record in + let ledger = try store.readLedger() + for component in ledger.components.values + where component.kind == "instructions" && component.name == record.name { + guard let id = component.resources.first, let resource = ledger.resources[id], + resource.path == record.path, + component.revision == record.revision, + try + (record.source == Self.own + || ledger.sourceIdentity(component.source, roots: store.ledgerRoots) == record.source) + else { continue } + let bytes: Data? + if let object = resource.entries.first(where: { $0.path == "." && $0.kind == .file })? + .object + { + bytes = ledger.contentObjects[object] + } else { + let file = store.cacheDirectory.appendingPathComponent( + "artifact-content/" + String(id.dropFirst(7)) + "/payload") + bytes = try? FileSystem.read(at: file) + } + if let bytes { + let section = try Instructions.validateSource( + bytes, id: Self.identity(record), allowRestrictions: true) + guard section.hash == record.hash else { + throw CoreError.invalidState("locked instruction digest mismatch") + } + return InstructionUnit(record: record, section: section) + } + } if record.source == Self.own { guard let unit = try? own(named: record.name), unit.record.path == record.path, unit.record.hash == record.hash @@ -171,21 +176,6 @@ final class InstructionSources { } } - func retain(_ lock: ResolvedState) throws { - let records = lock.instructions.sections + lock.instructions.chatgpt.values.flatMap(\.sections) - 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") - } - let root = try cache.materialize(sourceID: record.source, source: source, revision: revision) - let file = try PathSafety.resolvedChild(base: root, subpath: record.path) - try Self.contained(file, in: root) - guard Instructions.hash(try FileSystem.read(at: file)) == record.hash else { - throw CoreError.invalidState("cached instruction digest mismatch: \(record.name)") - } - } - } - /// `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 } diff --git a/Sources/AgentsInstructions/InstructionTargets.swift b/Sources/AgentsInstructions/InstructionTargets.swift index a277855..6597d8d 100644 --- a/Sources/AgentsInstructions/InstructionTargets.swift +++ b/Sources/AgentsInstructions/InstructionTargets.swift @@ -1,13 +1,14 @@ import AgentsCore import Foundation -struct InstructionTargets { +package struct InstructionTargets { + package init(store: StateStore) { self.store = store } 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 targets, /// recipients and Claude imports, and requires each rendering to match its locked hash. - func plan( + package func plan( sections: [InstructionSection], agents: [AgentID], previous: LockedInstructions, restoring: Bool = false ) throws -> ( @@ -284,7 +285,7 @@ struct InstructionTargets { } /// Rejects targets inside an instructions container of a local source. - static func validateSourceDirectories( + package static func validateSourceDirectories( _ changes: [InstructionTargetChange], sources: [String: LockedSource] ) throws { for source in sources where source.value.kind == .local { @@ -315,7 +316,13 @@ struct InstructionTargets { return try FileSystem.read(at: file) } - private static func importBlock(in bytes: Data, at path: ClaudeInstructionPath) throws + package static func ownedImportBytes(_ bytes: Data?) throws -> Data? { + guard let bytes else { return nil } + let document = try MarkdownDocument(bytes: bytes) + return try document.managedBlock().map { Data(document.normalized($0).utf8) } + } + + package static func importBlock(in bytes: Data, at path: ClaudeInstructionPath) throws -> (bytes: Data, blockHash: String) { let document = try MarkdownDocument(bytes: bytes) diff --git a/Sources/AgentsInstructions/InstructionUpdatePlan.swift b/Sources/AgentsInstructions/InstructionUpdatePlan.swift deleted file mode 100644 index 613ed4e..0000000 --- a/Sources/AgentsInstructions/InstructionUpdatePlan.swift +++ /dev/null @@ -1,71 +0,0 @@ -import AgentsCore -import Foundation - -/// Assembly and retention inputs for one scope generation; the caller owns commit and pruning. -package final class InstructionUpdatePlan: PreparedEvidence { - package let next: ResolvedState - package let report: InstructionUpdateReport - private let sources: InstructionSources - private let identities: [TargetPrecondition] - private let replace: Bool - - init( - next: ResolvedState, report: InstructionUpdateReport, sources: InstructionSources, - replace: Bool, expectedTargets: [String: TargetPrecondition] - ) 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 }) { - if let logical = InstructionLocations.file( - for: agent, scope: store.scope, environment: store.environment) - { - paths.append(logical) - } - } - if store.scope == .project, - next.instructions.targets.values.contains(where: { $0.agents.contains(.claudeCode) }) - { - let candidates = ClaudeInstructionPath.allCases.map { - store.environment.projectDirectory.appendingPathComponent($0.rawValue) - } - paths.append(contentsOf: candidates) - paths.append(contentsOf: candidates.map { $0.resolvingSymlinksInPath() }) - } - var evidence = expectedTargets - for path in Set(paths.map { $0.standardizedFileURL.path }) where evidence[path] == nil { - evidence[path] = try TargetPrecondition(URL(fileURLWithPath: path)) - } - identities = evidence.keys.sorted().map { evidence[$0]! } - } - - package func validate(excludingTargets targets: Set = []) throws { - if !replace { try InstructionOperations.requireOwnership(report) } - for identity in identities where !targets.contains(identity.url.path) { - try identity.validate() - } - try InstructionTargets.validateSourceDirectories(report.targets, sources: next.sources) - } - - package func retain() throws { try sources.retain(next) } - - package func stage(transaction: FileTransaction) throws { - for change in report.targets.sorted(by: { $0.url.path < $1.url.path }) where change.changed { - guard - let evidence = identities.first(where: { - $0.url.path == change.url.standardizedFileURL.path - }) - else { - throw CoreError.invalidState("instruction target has no prepared preimage") - } - if let after = change.after { - try transaction.replace(change.url, with: .data(after), expecting: evidence) - } else { - try transaction.delete(change.url, expecting: evidence) - } - } - } -} diff --git a/Sources/AgentsManifest/DeploymentSubset.swift b/Sources/AgentsManifest/DeploymentSubset.swift deleted file mode 100644 index 3866ec6..0000000 --- a/Sources/AgentsManifest/DeploymentSubset.swift +++ /dev/null @@ -1,71 +0,0 @@ -import AgentsCore - -extension DeclarationDocument { - /// Validates the concrete input expected by the current skill/instruction deployment paths. - /// Full declaration readers and source-only watch operations do not use this gate. - func requireDeploymentSubset() throws { - func fail( - _ pointer: String, _ message: String, code: String = "manifest.unsupported", - related: [String] = [] - ) -> ManifestFailure { - func span(_ pointer: String) -> SourceSpan { - sourceMap.locations(at: pointer).first?.span ?? source.span(0..<0) - } - return ManifestFailure( - ManifestDiagnostic( - code: code, message: message, span: span(pointer), related: related.map(span))) - } - if !declaration.uses.isEmpty { throw fail("/uses/0", "group uses require component linking") } - var matches: [String: [String]] = [:] - var order: [String] = [] - for (index, component) in declaration.components.enumerated() { - let key: String - switch component.kind { - case "skills": key = "skills occurrence: " + component["source"]!.string! - case "instructions": key = "instructions occurrence" - default: continue - } - if matches[key] == nil { order.append(key) } - matches[key, default: []].append("/components/\(index)") - } - for key in order { - let locations = matches[key]! - if locations.count > 1 { - throw fail( - locations[0], "ambiguous " + key, code: "manifest.ambiguous", - related: Array(locations.dropFirst())) - } - } - for (index, component) in declaration.components.enumerated() { - let path = "/components/\(index)" - guard ["skills", "instructions"].contains(component.kind) else { - throw fail(path, "\(component.kind) components require native lowering") - } - guard component["condition"] == .null else { - throw fail(path + "/condition", "conditional components require component linking") - } - guard component["native"] == .dictionary([:]) else { - throw fail(path + "/native", "native configuration requires native lowering") - } - if component.kind == "skills", component["source"]?.string == "." { - throw fail(path + "/source", "own-package skills require component linking") - } - func sections(_ record: DeclarationRecord, _ path: String) throws { - for (index, value) in (record["sections"]?.elements ?? []).enumerated() - where value.record?["condition"] != .null { - throw fail( - path + "/sections/\(index)/condition", "conditional sections require component linking") - } - } - try sections(component, path) - for (index, value) in (component["chatGPT"]?.elements ?? []).enumerated() { - let prompt = value.record! - let path = path + "/chatGPT/\(index)" - guard prompt["condition"] == .null else { - throw fail(path + "/condition", "conditional prompts require component linking") - } - try sections(prompt, path) - } - } - } -} diff --git a/Sources/AgentsManifest/ManifestState.swift b/Sources/AgentsManifest/ManifestState.swift index 8122a7d..cc04690 100644 --- a/Sources/AgentsManifest/ManifestState.swift +++ b/Sources/AgentsManifest/ManifestState.swift @@ -11,14 +11,6 @@ extension StateStore { return try ManifestProjection.declaration(of: document, environment: environment) } - /// Existing skill/instruction deployment paths require a flat selection until linking and - /// native lowering are supplied by their owning lifecycle layer. - package func readDeploymentDeclaration(prepared: StatePrecondition? = nil) throws -> Declaration { - guard let document = try declarationDocument(prepared: prepared) else { return Declaration() } - try document.requireDeploymentSubset() - return try ManifestProjection.declaration(of: document, environment: environment) - } - /// Plans `next` as an edit of the prepared document that `previous` was read from. Nil means /// no semantic change. A document that no longer projects to `previous` is a stale /// preparation. @@ -41,38 +33,6 @@ extension StateStore { return output.map { DeclarationChange(bytes: Data($0)) } } - /// Commits state through the scope journal. Omitting watch preserves its existing bytes. A - /// scope without a declaration document receives one, so the saved lock is never orphaned. - package func save( - declaration: Declaration, resolved: ResolvedState, watch: WatchState? = nil - ) throws { - try withLock { - try declaration.validate(environment: environment) - try resolved.validate() - try watch?.validate() - let baseline = try StatePrecondition(store: self) - let previous = try readDeclaration(prepared: baseline) - _ = try readResolved(prepared: baseline) - var change = try planDeclaration(declaration, replacing: previous, prepared: baseline) - if change == nil, try declarationBytes(prepared: baseline) == nil { - change = DeclarationChange( - bytes: Data( - YAMLWriter.manifest(YAMLConstruction.root(declaration)))) - } - let transaction = FileTransaction(store: self) - transaction.requireUnchanged(since: baseline) - try stageDeclaration(change, in: transaction, prepared: baseline) - try transaction.replace( - resolvedURL, with: .data(Self.encodeState(resolved.normalized)), - expecting: baseline.evidence(for: resolvedURL)) - if let watch { - try transaction.replace( - watchURL, with: .data(Self.encode(watch)), expecting: baseline.evidence(for: watchURL)) - } - try transaction.commit() - } - } - /// Reads the complete declaration under a shared lock, without recovery or creating files. public func loadDeclaration() throws -> Declaration { try withReadLock { try readDeclaration() } @@ -86,7 +46,7 @@ extension StateStore { private var declarationIdentity: DocumentIdentity { DocumentIdentity(declarationURL.path) } - private func declarationDocument(prepared: StatePrecondition?) throws -> DeclarationDocument? { + package func declarationDocument(prepared: StatePrecondition?) throws -> DeclarationDocument? { try declarationBytes(prepared: prepared).map { try DeclarationDocument(bytes: Array($0), identity: declarationIdentity) } diff --git a/Sources/AgentsSkills/SkillLifecycle.swift b/Sources/AgentsSkills/SkillLifecycle.swift index 20f69c3..e8bf104 100644 --- a/Sources/AgentsSkills/SkillLifecycle.swift +++ b/Sources/AgentsSkills/SkillLifecycle.swift @@ -3,47 +3,22 @@ import AgentsManifest import Foundation struct DiscoveredSource { - var source: SourceDeclaration var id: String var root: URL - var pin: SourceRevision? var skills: [Skill] - var artifacts: [String: WellKnownRemoteSkill] } -struct PreparedSkill { - var lock: LockedSkill - var directory: URL - var payloads: [String: Data] - let executableFlags: [String: Bool]? - let identity: PathIdentity - let sourceIdentity: PathIdentity - - init(lock: LockedSkill, directory: URL, payloads: [String: Data], sourcePath: URL? = nil) throws { - self.lock = lock - self.directory = directory - self.payloads = payloads - executableFlags = try lock.hash == nil ? nil : FileHash.executableFlags(directory) - identity = try PathIdentity(directory.resolvingSymlinksInPath()) - sourceIdentity = try PathIdentity(sourcePath ?? directory) - } -} - -final class SkillLifecycle { +package final class SkillLifecycle { let store: StateStore let cache: SourceCache let provider: WellKnownProvider let workspace: URL let resolutions: SourceResolutionSession? - /// Receives the applying transaction's checkpoints. - let checkpoint: (String) throws -> Void init( - store: StateStore, provider: WellKnownProvider, resolutions: SourceResolutionSession? = nil, - checkpoint: @escaping (String) throws -> Void = { _ in } + store: StateStore, provider: WellKnownProvider, resolutions: SourceResolutionSession? = nil ) throws { self.resolutions = resolutions - self.checkpoint = checkpoint self.store = store self.cache = SourceCache(store: store) self.provider = provider @@ -54,19 +29,12 @@ final class SkillLifecycle { deinit { try? FileManager.default.removeItem(at: workspace) } - func lockedSource(_ source: SourceDeclaration) -> LockedSource { - LockedSource( - kind: source.kind, url: source.kind == .git ? source.gitURL : nil, - requirement: source.requirement, path: source.path) - } - func discover( _ source: SourceDeclaration, live: Bool, fullDepth: Bool, names: [String]? = nil, exclude: [String] = [], cacheSource: Bool = true ) throws -> DiscoveredSource { let id = try source.identity(environment: store.environment) let root: URL - var pin: SourceRevision? var artifacts: [String: WellKnownRemoteSkill] = [:] if source.kind == .wellKnown { root = workspace.appendingPathComponent(UUID().uuidString) @@ -87,14 +55,18 @@ final class SkillLifecycle { root = source.localURL(environment: store.environment) } else { root = workspace.appendingPathComponent(UUID().uuidString) - func copy(_ resolved: SourceRevision, _ snapshot: URL) throws { - pin = resolved + func copy(_: SourceRevision, _ snapshot: URL) throws { try FileSystem.withAccessErrors(at: root) { try FileManager.default.copyItem(at: snapshot, to: root) } } if let resolutions { - try resolutions.withSnapshot(source, copy) + if try resolutions.isGitSource(source) { + try resolutions.withSnapshot(source, copy) + } else { + let view = try resolutions.localSnapshot(source) + try FileManager.default.copyItem(at: view.root, to: root) + } } else { try cache.withResolvedSnapshot(source, cacheSource: cacheSource, copy) } @@ -115,8 +87,7 @@ final class SkillLifecycle { throw CoreError.invalidSkill("artifact name differs from SKILL.md name") } } - return DiscoveredSource( - source: source, id: id, root: root, pin: pin, skills: skills, artifacts: artifacts) + return DiscoveredSource(id: id, root: root, skills: skills) } func select(_ skills: [Skill], names: [String]) throws -> [Skill] { @@ -132,288 +103,13 @@ final class SkillLifecycle { return selected } - func prepare( - _ skill: Skill, in source: DiscoveredSource, declaration: SkillDeclaration, - defaultAgents: [AgentID] - ) throws -> PreparedSkill { - let name = PathSafety.sanitizeName(skill.name) - let override = declaration.overrides?[name] - let agents = override?.agents ?? declaration.agents ?? defaultAgents - let mode = override?.mode ?? declaration.mode ?? .link - guard !agents.isEmpty else { throw CoreError.invalidSkill("skill has no recipients: \(name)") } - let path = PathSafety.relativePath(skill.path, to: source.root.path) - var directory = URL(fileURLWithPath: skill.path) - let artifact = source.artifacts[name] - let lock: LockedSkill - if mode == .edit { - guard source.source.kind == .local, source.source.requirement == nil else { - throw CoreError.invalidSource("edit requires a local source with no requirement") - } - directory = try PathSafety.resolvedChild( - base: source.source.localURL(environment: store.environment), subpath: path) - guard - FileManager.default.fileExists(atPath: directory.appendingPathComponent("SKILL.md").path) - else { throw CoreError.notFound("live skill directory") } - lock = LockedSkill( - source: source.id, path: path, - installs: Dictionary(uniqueKeysWithValues: Set(agents).map { ($0.rawValue, mode) })) - } else { - guard source.pin != nil || artifact != nil else { - throw CoreError.invalidSource("link and copy require committed Git content") - } - lock = LockedSkill( - source: source.id, revision: source.pin?.revision, version: source.pin?.version, - artifact: artifact?.artifact, path: artifact == nil ? path : nil, - hash: "sha256:" + (try FileHash.folderHash(directory)), - installs: Dictionary(uniqueKeysWithValues: Set(agents).map { ($0.rawValue, mode) })) - } - return try PreparedSkill( - lock: lock, directory: directory, payloads: artifact?.payloads ?? [:], - sourcePath: mode == .edit ? URL(fileURLWithPath: skill.path) : nil) - } - - func restore(name: String, skill: LockedSkill, sources: [String: LockedSource]) throws - -> PreparedSkill - { - guard let source = sources[skill.source] else { - throw CoreError.invalidState("unknown locked source") - } - let directory: URL - var payloads: [String: Data] = [:] - if skill.installs.values.allSatisfy({ $0 == .edit }) { - let declaration = try cache.declaration(sourceID: skill.source, source: source) - directory = try PathSafety.resolvedChild( - base: declaration.localURL(environment: store.environment), subpath: skill.path ?? ".") - } else if let artifact = skill.artifact { - let restored = try provider.restore(artifact, cache: cache) - payloads = restored.payloads - directory = workspace.appendingPathComponent(UUID().uuidString) - try write(restored.files, to: directory) - } else { - guard let revision = skill.revision, let path = skill.path else { - throw CoreError.invalidState("missing locked revision or path") - } - let cached = cache.materializedURL(sourceID: skill.source, revision: revision) - try cache.validatePath(cached) - let root: URL - if FileManager.default.fileExists(atPath: cached.path) { - root = cached - } else { - root = workspace.appendingPathComponent(UUID().uuidString) - try cache.withSnapshot(sourceID: skill.source, source: source, revision: revision) { - snapshot in - try FileSystem.withAccessErrors(at: root) { - try FileManager.default.copyItem(at: snapshot, to: root) - } - } - } - directory = try PathSafety.resolvedChild(base: root, subpath: path) - } - guard FileManager.default.fileExists(atPath: directory.appendingPathComponent("SKILL.md").path) - else { throw CoreError.notFound("locked skill is unavailable: \(name)") } - if let hash = skill.hash, try "sha256:" + FileHash.folderHash(directory) != hash { - throw CoreError.invalidState("locked skill digest mismatch: \(name)") - } - return try PreparedSkill(lock: skill, directory: directory, payloads: payloads) - } - - /// `declaration` replaces `previousDeclaration`, which was read from `baseline`. Its edit is - /// planned before content retention, so a declaration that cannot be edited fails without - /// side effects. Without `writeState` the declaration and lock stay unchanged. - func apply( - declaration: Declaration, replacing previousDeclaration: Declaration, - previous: ResolvedState, next: ResolvedState, prepared: [String: PreparedSkill], - names: Set, baseline: StatePrecondition, writeState: Bool = true - ) throws -> [InstallResult] { - try declaration.validate(environment: store.environment) - try next.validate() - let change = - writeState - ? try store.planDeclaration(declaration, replacing: previousDeclaration, prepared: baseline) - : nil - let plan = try SkillUpdatePlan( - lifecycle: self, previous: previous, next: next, prepared: prepared, names: names, results: [] - ) - try plan.validateOwnership() - try baseline.validate() - try plan.validate() - let retained = try plan.retain() - let transaction = FileTransaction(store: store, checkpoint: checkpoint) - transaction.requireUnchanged(since: baseline, plan) - try plan.stage(retained: retained, transaction: transaction) - if writeState { - try store.stageDeclaration(change, in: transaction, prepared: baseline) - if let data = try next.replacementData(in: store, prepared: baseline) { - try transaction.replace( - store.resolvedURL, with: .data(data), expecting: baseline.evidence(for: store.resolvedURL) - ) - } - } - try cache.prune( - referencedBy: next, watch: store.readWatch(prepared: baseline), transaction: transaction) - try transaction.commit() - return receipts(next: next, names: names) - } - - func validateOwnership(previous: ResolvedState, next: ResolvedState, names: Set) throws { - let oldTargets = try targets(previous) - let newTargets = try targets(next) - // Only recorded targets belong to this scope. Dangling or looping links hold no content. - for (path, target) in newTargets.sorted(by: { $0.key < $1.key }) - where names.contains(target.name) && oldTargets[path] == nil && Self.holdsContent(atPath: path) - { - throw CoreError.invalidSkill( - "skill '\(target.name)' in \(store.scope.rawValue) scope cannot be installed at \(path): " - + "an entry this scope does not manage already exists there; move or remove it first") - } - } - - func retain(prepared: [String: PreparedSkill], next: ResolvedState) throws -> [String: URL] { - var retained: [String: URL] = [:] - for (name, item) in prepared.sorted(by: { $0.key < $1.key }) { - try validate(item, name: name) - let skill = item.lock - let path: URL - if let revision = skill.revision, let source = next.sources[skill.source] { - let root = try cache.materialize(sourceID: skill.source, source: source, revision: revision) - path = try PathSafety.resolvedChild(base: root, subpath: skill.path ?? ".") - } else if let artifact = skill.artifact { - for (digest, data) in item.payloads { _ = try cache.storeArtifact(data, digest: digest) } - guard let hash = skill.hash else { - throw CoreError.invalidState("missing artifact content hash") - } - path = try cache.materializeArtifact(item.directory, digest: artifact.digest, hash: hash) - } else { - path = item.directory - } - if let hash = skill.hash { - guard try "sha256:" + FileHash.folderHash(path) == hash, - try FileHash.executableFlags(path) == item.executableFlags - else { - throw CoreError.invalidState("cached skill content or executable mode mismatch: \(name)") - } - } - retained[name] = path - } - return retained - } - - func validate(_ item: PreparedSkill, name: String) throws { - try item.identity.validate() - try item.sourceIdentity.validate() - if let hash = item.lock.hash { - guard try "sha256:" + FileHash.folderHash(item.directory) == hash, - try FileHash.executableFlags(item.directory) == item.executableFlags - else { throw CoreError.invalidState("prepared skill changed: \(name)") } - } else { - guard - let skill = try Discovery.parseSkill( - at: item.directory.appendingPathComponent("SKILL.md"), includeInternal: true), - PathSafety.sanitizeName(skill.name) == name - else { throw CoreError.invalidSkill("live skill is unavailable: \(name)") } - } - } - - func stage( - previous: ResolvedState, next: ResolvedState, prepared: [String: PreparedSkill], - retained: [String: URL], names: Set, transaction: FileTransaction, - expectations: [String: TargetPrecondition] - ) throws { - let oldTargets = try targets(previous) - let newTargets = try targets(next) - for path in Set(oldTargets.keys).union(newTargets.keys).sorted() { - if let target = newTargets[path], names.contains(target.name), - let content = retained[target.name], let item = prepared[target.name] - { - guard let evidence = expectations[path] else { - throw CoreError.invalidState("skill target has no prepared preimage") - } - guard - !PathSafety.isContained( - content.resolvingSymlinksInPath(), in: URL(fileURLWithPath: path).standardizedFileURL) - else { throw CoreError.unsafePath("installation would replace its own source") } - try transaction.replace( - URL(fileURLWithPath: path), with: target.mode == .copy ? .copy(content) : .link(content), - expectedHash: item.lock.hash, executableFlags: item.executableFlags, expecting: evidence) - } else if let target = oldTargets[path], names.contains(target.name), newTargets[path] == nil - { - guard let evidence = expectations[path] else { - throw CoreError.invalidState("skill target has no prepared preimage") - } - try transaction.delete(URL(fileURLWithPath: path), expecting: evidence) - } - } - } - - func receipts(next: ResolvedState, names: Set) -> [InstallResult] { - names.sorted().flatMap { name in - (next.skills[name]?.installs ?? [:]).sorted(by: { $0.key < $1.key }).compactMap { raw, mode in - guard let agent = AgentID(rawValue: raw) else { return nil } - return InstallResult( - skill: name, agent: agent, scope: store.scope, mode: mode, - path: Self.target(name: name, agent: agent, store: store).path) - } - } - } - - func membership(name: String, old: LockedSkill?, new: LockedSkill?) -> [SkillMembershipChange] { - Set((old?.installs ?? [:]).keys).union((new?.installs ?? [:]).keys).sorted().compactMap { raw in - guard let agent = AgentID(rawValue: raw) else { return nil } - return SkillMembershipChange( - agent: agent, - path: Self.physicalTarget(Self.target(name: name, agent: agent, store: store)).path, - before: old?.installs[raw].map { .installed(mode: $0) } ?? .absent, - after: new?.installs[raw].map { .installed(mode: $0) } ?? .absent) - } - } - - func changes(name: String, old: LockedSkill?, new: PreparedSkill?) throws -> [SkillFileChange] { - let oldTargets = try targets(ResolvedState(skills: old.map { [name: $0] } ?? [:])) - let newTargets = try targets(ResolvedState(skills: new.map { [name: $0.lock] } ?? [:])) - var result: [SkillFileChange] = [] - for path in Set(oldTargets.keys).union(newTargets.keys).sorted() { - let target = URL(fileURLWithPath: path) - let before = try entries(target) - var after: [String: SkillFileEntry] = [:] - if let planned = newTargets[path], let new { - after = try entries(new.directory) - if planned.mode != .copy { - let content: URL - if let revision = new.lock.revision { - content = try PathSafety.resolvedChild( - base: cache.materializedURL(sourceID: new.lock.source, revision: revision), - subpath: new.lock.path ?? ".") - } else if let artifact = new.lock.artifact { - content = store.cacheDirectory.appendingPathComponent( - "artifact-content/" + artifact.digest.dropFirst(7)) - } else { - content = new.directory - } - after["."] = .symbolicLink( - FileTransaction.linkDestination( - content, parent: target.deletingLastPathComponent(), store: store)) - } else { - after["."] = .directory - } - } - for relative in Set(before.keys).union(after.keys).sorted() - where before[relative] != after[relative] { - result.append( - SkillFileChange( - path: relative == "." ? path : target.appendingPathComponent(relative).path, - before: before[relative], after: after[relative])) - } - } - return result - } - - static func target(name: String, agent: AgentID, store: StateStore) -> URL { + package static func target(name: String, agent: AgentID, store: StateStore) -> URL { AgentRegistry.installSkillsDirectory( for: agent, scope: store.scope, environment: store.environment ).appendingPathComponent(name).standardizedFileURL } - static func holdsContent(atPath path: String) -> Bool { + package static func holdsContent(atPath path: String) -> Bool { guard let attributes = try? FileManager.default.attributesOfItem(atPath: path) else { return false } @@ -421,29 +117,11 @@ final class SkillLifecycle { || FileManager.default.fileExists(atPath: path) } - static func physicalTarget(_ url: URL) -> URL { + package static func physicalTarget(_ url: URL) -> URL { url.deletingLastPathComponent().resolvingSymlinksInPath() .appendingPathComponent(url.lastPathComponent).standardizedFileURL } - func targets(_ lock: ResolvedState) throws -> [String: (name: String, mode: InstallMode)] { - var result: [String: (name: String, mode: InstallMode)] = [:] - for (name, skill) in lock.skills { - for (raw, mode) in skill.installs { - guard let agent = AgentID(rawValue: raw) else { - throw CoreError.invalidState("unknown locked agent") - } - let url = Self.target(name: name, agent: agent, store: store) - let physical = Self.physicalTarget(url).path - if let existing = result[physical], existing.name != name || existing.mode != mode { - throw CoreError.invalidState("agents sharing a skill directory must use the same mode") - } - result[physical] = (name, mode) - } - } - return result - } - private func write(_ files: [String: Data], to directory: URL) throws { try FileSystem.createDirectory(at: directory) for (path, data) in files { @@ -453,7 +131,9 @@ final class SkillLifecycle { } } - func entries(_ directory: URL, followRoot: Bool = true) throws -> [String: SkillFileEntry] { + package static func entries(_ directory: URL, followRoot: Bool = true) throws -> [String: + SkillFileEntry] + { func entry(_ url: URL) throws -> SkillFileEntry? { guard let attributes = try? FileManager.default.attributesOfItem(atPath: url.path) else { return nil diff --git a/Sources/AgentsSkills/SkillModels.swift b/Sources/AgentsSkills/SkillModels.swift index 5de52cb..0667963 100644 --- a/Sources/AgentsSkills/SkillModels.swift +++ b/Sources/AgentsSkills/SkillModels.swift @@ -43,6 +43,16 @@ public struct AddOutcome: Sendable { public var availableSkills: [Skill] /// Empty when inspection or multiple unselected skills require a CLI choice. public var installed: [InstallResult] + + package init( + source: SourceDeclaration, sourceID: String, availableSkills: [Skill], + installed: [InstallResult] + ) { + self.source = source + self.sourceID = sourceID + self.availableSkills = availableSkills + self.installed = installed + } } public struct InstallResult: Codable, Equatable, Sendable { @@ -51,10 +61,23 @@ public struct InstallResult: Codable, Equatable, Sendable { public var scope: InstallScope public var mode: InstallMode public var path: String + + package init(skill: String, agent: AgentID, scope: InstallScope, mode: InstallMode, path: String) + { + self.skill = skill + self.agent = agent + self.scope = scope + self.mode = mode + self.path = path + } } public struct ResolvedInstallReport: Sendable { public var installed: [InstallResult] + + package init(installed: [InstallResult]) { + self.installed = installed + } } public enum InstalledSkillStatus: String, Codable, Sendable { @@ -88,6 +111,12 @@ public struct SkillFileChange: Codable, Equatable, Sendable { public var path: String public var before: SkillFileEntry? public var after: SkillFileEntry? + + package init(path: String, before: SkillFileEntry?, after: SkillFileEntry?) { + self.path = path + self.before = before + self.after = after + } } /// Membership recorded by the lock, independent of filesystem presence. @@ -101,6 +130,13 @@ public struct SkillMembershipChange: Codable, Equatable, Sendable { public let path: String public let before: SkillMembership public let after: SkillMembership + + package init(agent: AgentID, path: String, before: SkillMembership, after: SkillMembership) { + self.agent = agent + self.path = path + self.before = before + self.after = after + } } public struct UpdateResult: Codable, Equatable, Sendable { @@ -117,6 +153,27 @@ public struct UpdateResult: Codable, Equatable, Sendable { public var membership: [SkillMembershipChange] public var changes: [SkillFileChange] public var installed: [InstallResult] + + package init( + skill: String, sourceIdentity: String, changed: Bool, oldRevision: String?, + newRevision: String?, oldVersion: String?, newVersion: String?, oldHash: String?, + newHash: String?, lockMissing: Bool, membership: [SkillMembershipChange], + changes: [SkillFileChange], installed: [InstallResult] + ) { + self.skill = skill + self.sourceIdentity = sourceIdentity + self.changed = changed + self.oldRevision = oldRevision + self.newRevision = newRevision + self.oldVersion = oldVersion + self.newVersion = newVersion + self.oldHash = oldHash + self.newHash = newHash + self.lockMissing = lockMissing + self.membership = membership + self.changes = changes + self.installed = installed + } } public enum DoctorCheckStatus: String, Codable, Sendable { case ok, warning, error } diff --git a/Sources/AgentsSkills/SkillOperations.swift b/Sources/AgentsSkills/SkillOperations.swift index ff00783..1093a4e 100644 --- a/Sources/AgentsSkills/SkillOperations.swift +++ b/Sources/AgentsSkills/SkillOperations.swift @@ -3,388 +3,6 @@ import AgentsManifest import Foundation public enum SkillOperations { - public static func add(_ options: AddOptions) throws -> AddOutcome { - try add(options, provider: WellKnownProvider()) - } - - /// Reports the scope lock's and the applying transaction's named checkpoints. - package static func add( - _ options: AddOptions, checkpoint: @escaping (String) throws -> Void - ) throws -> AddOutcome { - try add(options, provider: WellKnownProvider(), checkpoint: checkpoint) - } - - static func add( - _ options: AddOptions, provider: WellKnownProvider, - checkpoint: @escaping (String) throws -> Void = { _ in } - ) throws -> AddOutcome { - var options = options - if let name = try SourceArgument(options.source).name { - guard !options.all else { - throw CoreError.invalidSource("@skill: names one skill and cannot be combined with all") - } - if !options.skillNames.contains(name) { options.skillNames.append(name) } - } - var automaticSelection: (sourceID: String, name: String)? - if options.listOnly || (options.skillNames.isEmpty && !options.all) { - let outcome = try add(options, provider: provider, apply: false) - if options.listOnly || outcome.availableSkills.count > 1 { return outcome } - automaticSelection = outcome.availableSkills.first.map { (outcome.sourceID, $0.name) } - } - return try add( - options, provider: provider, apply: true, automaticSelection: automaticSelection, - checkpoint: checkpoint) - } - - private static func add( - _ options: AddOptions, provider: WellKnownProvider, apply: Bool, - automaticSelection: (sourceID: String, name: String)? = nil, - checkpoint: @escaping (String) throws -> Void = { _ in } - ) throws -> AddOutcome { - let store = StateStore(scope: options.scope, environment: options.environment) - return try operate(store, apply: apply, checkpoint: checkpoint) { - previousDeclaration, lock, baseline in - let lifecycle = try SkillLifecycle(store: store, provider: provider, checkpoint: checkpoint) - var declaration = previousDeclaration - let selectionChanged = CoreError.invalidState( - "automatic skill selection changed during discovery; retry the command") - let source: SourceDeclaration - 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)") - } - declaration.sources[alias] = source - try declaration.validate(environment: options.environment) - let available = try lifecycle.discover( - source, - live: options.mode == .edit - || (options.listOnly && source.kind == .local && source.requirement == nil), - fullDepth: options.fullDepth, cacheSource: apply) - let selected: [Skill] - if let automaticSelection { - guard let skill = available.skills.first(where: { $0.name == automaticSelection.name }) - else { throw selectionChanged } - selected = [skill] - } else { - selected = try lifecycle.select(available.skills, names: options.skillNames) - } - guard options.listOnly || !selected.isEmpty else { - throw CoreError.notFound("no skills found in \(options.source)") - } - if !apply { - return AddOutcome(source: source, sourceID: id, availableSkills: selected, installed: []) - } - var selection = (try declaration.skills)?[alias] ?? SkillDeclaration(select: .names([])) - let names = selected.map { PathSafety.sanitizeName($0.name) } - if options.all { - selection.select = .all - } else if case .names(let previous) = selection.select { - selection.select = .names(Array(Set(previous + names)).sorted()) - } - selection.exclude = selection.exclude?.filter { !names.contains($0) } - if (try declaration.skills)?[alias] == nil || options.all { - selection.agents = options.agents - selection.mode = options.mode - } else { - var overrides = selection.overrides ?? [:] - for name in names { - let recipients = options.agents ?? overrides[name]?.agents ?? selection.agents - overrides[name] = SkillOverride(agents: recipients, mode: options.mode) - } - selection.overrides = overrides - } - try declaration.updateSkills { - var selections = $0 ?? [:] - selections[alias] = selection - $0 = selections - } - try declaration.validate(environment: options.environment) - var next = lock - next.sources[id] = lifecycle.lockedSource(source) - var prepared: [String: PreparedSkill] = [:] - for skill in selected { - let name = PathSafety.sanitizeName(skill.name) - if let current = lock.skills[name], current.source != id { - let ownerAlias = try declaration.sources.keys.sorted().first { - try declaration.sources[$0]?.identity(environment: options.environment) - == current.source - } - let owner = ownerAlias.map { "'\($0)' (\(current.source))" } ?? current.source - let locations = AgentID.allCases.filter { current.installs[$0.rawValue] != nil }.map { - "\($0.rawValue) at \(SkillLifecycle.target(name: name, agent: $0, store: store).path)" - }.joined(separator: ", ") - throw CoreError.invalidSkill( - "skill '\(name)' in \(options.scope.rawValue) scope already belongs to source \(owner); " - + "cannot add from source '\(alias)' (\(id)). Existing installations: \(locations)") - } - let item = try lifecycle.prepare( - skill, in: available, declaration: selection, defaultAgents: declaration.defaultAgents) - prepared[name] = item - next.skills[name] = item.lock - } - try next.validate() - let installed = try lifecycle.apply( - declaration: declaration, replacing: previousDeclaration, previous: lock, next: next, - prepared: prepared, names: Set(names), baseline: baseline) - return AddOutcome( - source: source, sourceID: id, availableSkills: selected, installed: installed) - } - } - - /// Resolves declared intent. The callback runs before any target or state replacement. - public static func updateInstalled( - scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), - skillNames: [String] = [], apply: Bool = false, - beforeApply: (([UpdateResult]) throws -> Void)? = nil - ) throws -> [UpdateResult] { - try update( - scope: scope, environment: environment, skillNames: skillNames, apply: apply, - beforeApply: beforeApply, provider: WellKnownProvider()) - } - - static func update( - scope: InstallScope, environment: RuntimeEnvironment, skillNames: [String], apply: Bool, - beforeApply: (([UpdateResult]) throws -> Void)? = nil, provider: WellKnownProvider - ) throws -> [UpdateResult] { - let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: apply) { declaration, previous, baseline in - let resolutions = try SourceResolutionSession(store: store) - let plan = try prepareUpdate( - store: store, declaration: declaration, previous: previous, resolutions: resolutions, - skillNames: skillNames, provider: provider) - try plan.next.validate() - try baseline.validate() - var results = plan.results - if apply { - try plan.validateOwnership() - try beforeApply?(results) - try baseline.validate() - try plan.validate() - let retained = try plan.retain() - let transaction = FileTransaction(store: store) - transaction.requireUnchanged(since: baseline, plan) - try plan.stage(retained: retained, transaction: transaction) - if let data = try plan.next.replacementData(in: store, prepared: baseline) { - try transaction.replace( - store.resolvedURL, with: .data(data), - expecting: baseline.evidence(for: store.resolvedURL)) - } - try SourceCache(store: store).prune( - referencedBy: plan.next, watch: store.readWatch(prepared: baseline), - transaction: transaction) - try transaction.commit() - let installed = plan.receipts - for index in results.indices { - results[index].installed = installed.filter { $0.skill == results[index].skill } - } - } - return results - } - } - - /// Prepares skill-owned records; the caller validates the complete generation after assembly. - package static func prepareUpdate( - store: StateStore, declaration: Declaration, previous: ResolvedState, - resolutions: SourceResolutionSession, skillNames: [String] = [] - ) throws -> SkillUpdatePlan { - try prepareUpdate( - store: store, declaration: declaration, previous: previous, resolutions: resolutions, - skillNames: skillNames, provider: WellKnownProvider()) - } - - private static func prepareUpdate( - store: StateStore, declaration: Declaration, previous: ResolvedState, - resolutions: SourceResolutionSession, skillNames: [String], provider: WellKnownProvider - ) throws -> SkillUpdatePlan { - let environment = store.environment - let lifecycle = try SkillLifecycle(store: store, provider: provider, resolutions: resolutions) - let requested = Set(skillNames.map(PathSafety.sanitizeName)) - var next = previous - var prepared: [String: PreparedSkill] = [:] - for alias in ((try declaration.skills) ?? [:]).keys.sorted() { - guard let selection = (try declaration.skills)?[alias], - let source = declaration.sources[alias] - else { continue } - let id = try source.identity(environment: environment) - let requestedHere = requested.filter { name in - if let installed = previous.skills[name] { return installed.source == id } - if case .names(let names) = selection.select { return names.contains(name) } - return !(selection.exclude ?? []).contains(name) - } - if !requested.isEmpty && requestedHere.isEmpty { continue } - if case .names(let names) = selection.select, names.isEmpty { continue } - func mode(_ name: String) -> InstallMode { - selection.overrides?[name]?.mode ?? selection.mode ?? .link - } - let explicit: [String]? - if !requested.isEmpty { - explicit = requestedHere.sorted() - } else if case .names(let names) = selection.select { - explicit = names - } else { - explicit = nil - } - let primaryLive = - explicit.map { $0.allSatisfy { mode($0) == .edit } } ?? (selection.mode == .edit) - var liveSource: DiscoveredSource? - var pinnedSource: DiscoveredSource? - func discover(live: Bool) throws -> DiscoveredSource { - if live, let liveSource { return liveSource } - if !live, let pinnedSource { return pinnedSource } - let result = try lifecycle.discover( - source, live: live, fullDepth: explicit != nil, names: explicit, - exclude: selection.exclude ?? []) - if live { liveSource = result } else { pinnedSource = result } - return result - } - let primary = try discover(live: primaryLive) - var names = explicit ?? primary.skills.map { PathSafety.sanitizeName($0.name) } - if explicit == nil { - let overrides = (selection.overrides ?? [:]).keys.filter { - (mode($0) == .edit) != primaryLive - } - for name in overrides { - let alternate = try discover(live: mode(name) == .edit) - if !Discovery.filter(alternate.skills, names: [name]).isEmpty { names.append(name) } - } - names = Array(Set(names)).filter { !(selection.exclude ?? []).contains($0) }.sorted() - } - for name in names { - let discovered = try discover(live: mode(name) == .edit) - let matches = Discovery.filter(discovered.skills, names: [name]) - if matches.isEmpty, explicit == nil { continue } - if matches.isEmpty, previous.skills[name] == nil, !requested.isEmpty, - !selection.hasNamedSelection - { - continue - } - let skill = try lifecycle.select(discovered.skills, names: [name])[0] - if let current = prepared[name], current.lock.source != id { - throw CoreError.invalidSkill("duplicate skill name: \(name)") - } - if let current = previous.skills[name], current.source != id { - throw CoreError.invalidSkill("skill '\(name)' already belongs to \(current.source)") - } - let item = try lifecycle.prepare( - skill, in: discovered, declaration: selection, defaultAgents: declaration.defaultAgents) - prepared[name] = item - next.skills[name] = item.lock - } - next.sources[id] = lifecycle.lockedSource(source) - } - guard requested.isSubset(of: Set(prepared.keys)) else { - throw CoreError.notFound("requested skill is not declared or is missing upstream") - } - if requested.isEmpty { next.skills = prepared.mapValues(\.lock) } - let affected = requested.isEmpty ? Set(previous.skills.keys).union(prepared.keys) : requested - let results = try affected.sorted().map { name in - let old = previous.skills[name] - let new = next.skills[name] - let changes = try lifecycle.changes(name: name, old: old, new: prepared[name]) - return UpdateResult( - skill: name, sourceIdentity: new?.source ?? old?.source ?? "", - changed: old != new || !changes.isEmpty, oldRevision: old?.revision, - newRevision: new?.revision, oldVersion: old?.version, newVersion: new?.version, - oldHash: old?.hash, newHash: new?.hash, - lockMissing: !FileManager.default.fileExists(atPath: store.resolvedURL.path), - membership: lifecycle.membership(name: name, old: old, new: new), changes: changes, - installed: []) - } - return try SkillUpdatePlan( - lifecycle: lifecycle, previous: previous, next: next, prepared: prepared, - names: affected, results: results) - } - - /// Restores each locked pin and recipient. Never resolves requirements or consults an index. - public static func installResolvedReport( - scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() - ) throws -> ResolvedInstallReport { - try install(scope: scope, environment: environment, provider: WellKnownProvider()) - } - - static func install( - scope: InstallScope, environment: RuntimeEnvironment, provider: WellKnownProvider - ) throws -> ResolvedInstallReport { - let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: true) { declaration, lock, baseline in - let lifecycle = try SkillLifecycle(store: store, provider: provider) - var prepared: [String: PreparedSkill] = [:] - for (name, skill) in lock.skills { - prepared[name] = try lifecycle.restore(name: name, skill: skill, sources: lock.sources) - } - return ResolvedInstallReport( - installed: try lifecycle.apply( - declaration: declaration, replacing: declaration, previous: lock, next: lock, - prepared: prepared, names: Set(lock.skills.keys), baseline: baseline, - writeState: false)) - } - } - - @discardableResult - public static func remove( - skillNames: [String], scope: InstallScope = .project, agents: [AgentID]? = nil, - environment: RuntimeEnvironment = RuntimeEnvironment() - ) throws -> [String] { - let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: true) { previousDeclaration, lock, baseline in - var declaration = previousDeclaration - var next = lock - let names = Set(skillNames.map(PathSafety.sanitizeName)) - guard names.isSubset(of: Set(lock.skills.keys)) else { - throw CoreError.notFound("skill is not installed") - } - for name in names { - guard var skill = next.skills[name] else { continue } - if let agents { - for agent in agents { skill.installs.removeValue(forKey: agent.rawValue) } - } else { - skill.installs = [:] - } - next.skills[name] = skill.installs.isEmpty ? nil : skill - for alias in ((try declaration.skills) ?? [:]).keys { - guard let source = declaration.sources[alias], - try source.identity(environment: environment) == skill.source, - var selection = (try declaration.skills)?[alias] - else { continue } - if skill.installs.isEmpty { - if case .all = selection.select { - selection.exclude = Array(Set((selection.exclude ?? []) + [name])).sorted() - } else if case .names(let members) = selection.select { - selection.select = .names(members.filter { $0 != name }) - } - selection.overrides?.removeValue(forKey: name) - } else { - var overrides = selection.overrides ?? [:] - let mode = overrides[name]?.mode - overrides[name] = SkillOverride( - agents: skill.installs.keys.compactMap(AgentID.init(rawValue:)), mode: mode) - selection.overrides = overrides - } - try declaration.updateSkills { $0?[alias] = selection } - } - } - let lifecycle = try SkillLifecycle(store: store, provider: WellKnownProvider()) - _ = try lifecycle.apply( - declaration: declaration, replacing: previousDeclaration, previous: lock, next: next, - prepared: [:], names: names, baseline: baseline) - return names.sorted() - } - } - public static func removableSkillNames( scope: InstallScope = .project, agents: [AgentID]? = nil, environment: RuntimeEnvironment = RuntimeEnvironment() @@ -398,41 +16,61 @@ public enum SkillOperations { environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> [InstalledSkill] { let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: false) { _, lock in - try managedInventory(store: store, lock: lock, agents: agents) + return try store.withReadLock { + _ = try store.readDeclaration() + let ledger = try store.readLedger() + return try managedInventory(store: store, ledger: ledger, agents: agents) } } - private static func managedInventory(store: StateStore, lock: ResolvedState, agents: [AgentID]?) - throws -> [InstalledSkill] - { - try lock.skills.keys.sorted().flatMap { name in - guard let skill = lock.skills[name] else { return [InstalledSkill]() } - return try skill.installs.keys.sorted().compactMap { raw in - guard let agent = AgentID(rawValue: raw), let mode = skill.installs[raw], - agents?.contains(agent) ?? true - else { return nil } - let target = SkillLifecycle.target(name: name, agent: agent, store: store) - let present = FileManager.default.fileExists( - atPath: target.appendingPathComponent("SKILL.md").path) - var status: InstalledSkillStatus = - present ? (mode == .edit ? .editLinked : .installed) : .missing - if present, mode != .edit, let hash = skill.hash, - try "sha256:" + FileHash.folderHash(target) != hash + private static func managedInventory( + store: StateStore, ledger: ResolvedLedger, agents: [AgentID]? + ) throws -> [InstalledSkill] { + var result: [InstalledSkill] = [] + for deployment in ledger.deployments where deployment.route == "agents/skill@1" { + guard + let lowering = ledger.lowerings.first(where: { $0.deployments.contains(deployment.id) }), + let component = deployment.owners.first.flatMap({ ledger.components[$0] }), + let resource = component.resources.first.flatMap({ ledger.resources[$0] }) + else { continue } + let mode = lowering.layout.object?["mode"]?.text.flatMap(InstallMode.init(rawValue:)) ?? .copy + let target = try deployment.target.resolve(roots: store.ledgerRoots) + let present = FileManager.default.fileExists( + atPath: target.appendingPathComponent("SKILL.md").path) + var status: InstalledSkillStatus = + present ? (mode == .edit ? .editLinked : .installed) : .missing + if present, mode != .edit { + let flags = Dictionary( + uniqueKeysWithValues: resource.entries.filter { $0.kind == .file }.map { + ($0.path, $0.executable) + }) + if try "sha256:" + FileHash.folderHash(target) != resource.hash + || FileHash.executableFlags(target) != flags { status = .copyDrift } - if !present, - (try? FileManager.default.destinationOfSymbolicLink(atPath: target.path)) != nil - { - status = .brokenLink + } + if !present, (try? FileManager.default.destinationOfSymbolicLink(atPath: target.path)) != nil + { + status = .brokenLink + } + for agent in deployment.recipients where agents?.contains(agent) ?? true { + if !result.contains(where: { + $0.name == PathSafety.sanitizeName(component.name) && $0.agent == agent + && $0.path == target.path + }) { + result.append( + InstalledSkill( + name: PathSafety.sanitizeName(component.name), agent: agent, scope: store.scope, + path: target.path, + sourceIdentity: try ledger.sourceIdentity(component.source, roots: store.ledgerRoots), + isInstalled: present, status: status, mode: mode)) } - return InstalledSkill( - name: name, agent: agent, scope: store.scope, path: target.path, - sourceIdentity: skill.source, - isInstalled: present, status: status, mode: mode) } } + return result.sorted { + ($0.name, $0.agent.rawValue, $0.path) < ($1.name, $1.agent.rawValue, $1.path) + } } public static func listInstalled( @@ -440,8 +78,10 @@ public enum SkillOperations { environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> [InstalledSkill] { let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: false) { _, lock in - var result = try managedInventory(store: store, lock: lock, agents: agents).filter { + return try store.withReadLock { + _ = try store.readDeclaration() + let ledger = try store.readLedger() + var result = try managedInventory(store: store, ledger: ledger, agents: agents).filter { $0.isInstalled && (try? Discovery.parseSkill( at: URL(fileURLWithPath: $0.path).appendingPathComponent("SKILL.md"), @@ -498,9 +138,9 @@ public enum SkillOperations { ]) }, { - let declaration = try store.readDeploymentDeclaration() - let lock = try store.readResolved() - var checks = try managedInventory(store: store, lock: lock, agents: agents).filter { + let declaration = try store.readDeclaration() + let ledger = try store.readLedger() + var checks = try managedInventory(store: store, ledger: ledger, agents: agents).filter { $0.status != .installed && $0.status != .editLinked }.map { DoctorCheck( @@ -510,10 +150,13 @@ public enum SkillOperations { let cache = SourceCache(store: store) for (alias, source) in declaration.sources.sorted(by: { $0.key < $1.key }) { let id = try source.identity(environment: environment) - let skills = lock.skills.values.filter { $0.source == id } + let skills = try ledger.components.values.filter { + guard $0.kind == "skills", !$0.recipients.isEmpty else { return false } + return try ledger.sourceIdentity($0.source, roots: store.ledgerRoots) == id + } guard !skills.isEmpty else { continue } if source.kind == .local { - let paths = skills.compactMap(\.path) + let paths = skills.flatMap { $0.resources.compactMap { ledger.resources[$0]?.path } } let output = try? ProcessRunner.git( [ "--no-optional-locks", "-C", source.localURL(environment: environment).path, @@ -557,7 +200,7 @@ public enum SkillOperations { let store = StateStore( scope: .project, environment: RuntimeEnvironment(projectDirectory: directory)) return try store.withLock(createIfMissing: false) { - _ = try store.readDeploymentDeclaration() + _ = try store.readDeclaration() _ = try store.readResolved() let name = name.map(PathSafety.sanitizeName) let root = name.map { directory.appendingPathComponent($0) } ?? directory @@ -578,56 +221,48 @@ public enum SkillOperations { } } - private static func operate( - _ store: StateStore, apply: Bool, checkpoint: @escaping (String) throws -> Void = { _ in }, - _ body: () throws -> T - ) throws -> T { - if apply { return try store.withLock(checkpoint: checkpoint, body) } - return try store.withReadLock(body) - } - - private static func operate( - _ store: StateStore, apply: Bool, _ body: (Declaration, ResolvedState) throws -> T - ) throws -> T { - if apply { - return try store.withLock { - try body(store.readDeploymentDeclaration(), store.readResolved()) - } - } - return try store.withReadLock { - try body(store.readDeploymentDeclaration(), store.readResolved()) - } - } - - private static func operate( - _ store: StateStore, apply: Bool, checkpoint: @escaping (String) throws -> Void = { _ in }, - _ body: (Declaration, ResolvedState, StatePrecondition) throws -> T - ) throws -> T { - try operate(store, apply: apply, checkpoint: checkpoint) { - let baseline = try StatePrecondition(store: store) - return try body( - store.readDeploymentDeclaration(prepared: baseline), store.readResolved(prepared: baseline), - baseline) - } - } +} - private static func sourceDeclaration(_ options: AddOptions, declaration: Declaration) throws - -> SourceDeclaration - { - let selection = try SourceArgument(options.source).selection( +extension SkillOperations { + package static func inspect( + _ options: AddOptions, declaration: Declaration + ) throws -> (SourceDeclaration, String, [Skill]) { + let argument = try SourceArgument(options.source).selection( in: declaration, requirement: options.sourceRequirement, path: options.path, environment: options.environment) - let source = selection.applied(to: selection.source) + let source = argument.applied(to: argument.source) if options.mode == .edit, source.kind != .local || source.requirement != nil { throw CoreError.invalidSource("edit requires a local source with no requirement") } - return source + let store = StateStore(scope: options.scope, environment: options.environment) + return try SourceResolutionSession.withTemporaryRead(store: store) { session in + let lifecycle = try SkillLifecycle( + store: store, provider: WellKnownProvider(), resolutions: session) + let found = try lifecycle.discover( + source, + live: options.mode == .edit + || (options.listOnly && source.kind == .local && source.requirement == nil), + fullDepth: options.fullDepth, cacheSource: false) + let selected = try lifecycle.select(found.skills, names: options.skillNames) + let available = selected.map { skill in + var skill = skill + if PathSafety.isContained(URL(fileURLWithPath: skill.path), in: found.root) { + skill.path = PathSafety.relativePath(skill.path, to: found.root.path) + skill.skillFile = PathSafety.relativePath(skill.skillFile, to: found.root.path) + } + return skill + } + return (source, found.id, available) + } } } -extension SkillDeclaration { - fileprivate var hasNamedSelection: Bool { - if case .names = select { return true } - return false +extension SkillOperations { + package static func validateLiveMetadata(at directory: URL, name: String) throws { + let metadata = try Discovery.parseSkill( + at: directory.appendingPathComponent("SKILL.md"), includeInternal: true) + guard metadata?.name == name else { + throw CoreError.invalidSkill("live skill metadata changed during preparation") + } } } diff --git a/Sources/AgentsSkills/SkillUpdatePlan.swift b/Sources/AgentsSkills/SkillUpdatePlan.swift deleted file mode 100644 index ecbf3e0..0000000 --- a/Sources/AgentsSkills/SkillUpdatePlan.swift +++ /dev/null @@ -1,85 +0,0 @@ -import AgentsCore -import Foundation - -/// A domain plan borrows the scope lock and never commits or prunes independently. -package final class SkillUpdatePlan: PreparedEvidence { - package let next: ResolvedState - package let results: [UpdateResult] - package let targetPaths: [URL] - private let lifecycle: SkillLifecycle - private let previous: ResolvedState - private let prepared: [String: PreparedSkill] - private let names: Set - private let before: [TargetPrecondition] - private let linkedInputs: [TargetPrecondition] - private let recipientPaths: [(URL, PathIdentity)] - - init( - lifecycle: SkillLifecycle, previous: ResolvedState, next: ResolvedState, - prepared: [String: PreparedSkill], names: Set, results: [UpdateResult] - ) throws { - self.lifecycle = lifecycle - self.previous = previous - self.next = next - self.prepared = prepared - self.names = names - self.results = results - let oldTargets = try lifecycle.targets(previous).filter { names.contains($0.value.name) } - let newTargets = try lifecycle.targets(next).filter { names.contains($0.value.name) } - targetPaths = Set(oldTargets.keys).union(newTargets.keys).sorted().map { - URL(fileURLWithPath: $0) - } - before = try targetPaths.map { try TargetPrecondition($0) } - linkedInputs = try targetPaths.compactMap { url in - guard oldTargets[url.path]?.mode != .edit else { return nil } - let physical = url.resolvingSymlinksInPath() - return physical == url ? nil : try TargetPrecondition(physical) - } - recipientPaths = try names.sorted().flatMap { name in - Set((previous.skills[name]?.installs ?? [:]).keys) - .union((next.skills[name]?.installs ?? [:]).keys).compactMap { raw in - AgentID(rawValue: raw).map { - SkillLifecycle.target(name: name, agent: $0, store: lifecycle.store) - } - } - }.map { (SkillLifecycle.physicalTarget($0), try PathIdentity($0)) } - } - - package func validateOwnership() throws { - try lifecycle.validateOwnership(previous: previous, next: next, names: names) - for (path, target) in try lifecycle.targets(next) { - if let item = prepared[target.name], item.lock.hash == nil, - PathSafety.isContained(item.directory, in: URL(fileURLWithPath: path)) - { - throw CoreError.unsafePath("installation would replace its own source") - } - } - } - - package func validate(excludingTargets targets: Set = []) throws { - for (url, identity) in recipientPaths where !targets.contains(url.path) { - try identity.validate() - } - for evidence in before where !targets.contains(evidence.url.path) { try evidence.validate() } - for evidence in linkedInputs - where !targets.contains(where: { - PathSafety.isContained(evidence.url, in: URL(fileURLWithPath: $0)) - }) { - try evidence.validate() - } - for (name, item) in prepared { try lifecycle.validate(item, name: name) } - } - - package func retain() throws -> [String: URL] { - try lifecycle.retain(prepared: prepared, next: next) - } - - package func stage(retained: [String: URL], transaction: FileTransaction) throws { - try lifecycle.stage( - previous: previous, next: next, prepared: prepared, retained: retained, - names: names, transaction: transaction, - expectations: Dictionary(uniqueKeysWithValues: zip(targetPaths.map(\.path), before))) - } - - package var receipts: [InstallResult] { lifecycle.receipts(next: next, names: names) } -} diff --git a/Sources/AgentsUpdates/InstructionOperations.swift b/Sources/AgentsUpdates/InstructionOperations.swift new file mode 100644 index 0000000..d001f0c --- /dev/null +++ b/Sources/AgentsUpdates/InstructionOperations.swift @@ -0,0 +1,176 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import Components +import Foundation + +extension InstructionOperations { + public static func add( + _ options: InstructionAddOptions, beforeApply: ((InstructionUpdateReport) throws -> Void)? = nil + ) throws -> InstructionAddOutcome { + let store = StateStore(scope: options.scope, environment: options.environment) + let (declaration, digest, initial, available, id, alias) = try store.withReadLock { + let declaration = try store.readDeclaration() + let digest = try store.declarationDocument(prepared: nil)?.digest ?? "absent" + var next = declaration + let available: [InstructionUnit] + let id: String + let alias: String? + if options.source == "." { + available = try inspectOwn( + names: options.listOnly || options.all ? [] : options.names, + environment: options.environment) + id = "." + alias = nil + } else { + let argument = try SourceArgument(options.source) + guard argument.name == nil else { + throw CoreError.invalidSource("@skill: selects skills; pass section names separately") + } + let selection = try argument.selection( + in: declaration, requirement: options.sourceRequirement, path: options.path, + environment: options.environment) + let source = selection.applied(to: selection.source) + id = try source.identity(environment: options.environment) + available = try inspectSource(source, store: store) + 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 prior = declaration.sources[name], + try prior.identity(environment: options.environment) != id + { + throw CoreError.invalidSource("source alias already refers to another source") + } + next.sources[name] = source + alias = name + } + return (declaration, digest, next, available, id, alias) + } + var next = initial + if options.listOnly || (options.names.isEmpty && !options.all && available.count > 1) { + return InstructionAddOutcome(sourceID: id, available: available, result: nil) + } + let selected = + options.names.isEmpty + ? available + : try options.names.map { name in + guard let item = available.first(where: { $0.record.name == name }) else { + throw CoreError.notFound("instruction section: " + name) + } + return item + } + guard !selected.isEmpty else { throw CoreError.notFound("source provides no instructions") } + let references = selected.map { SectionDeclaration(name: $0.record.name, source: alias) } + let editable = next.components.indices.filter { index in + if case .instructions(let selection) = next.components[index] { + selection.condition == nil && selection.native.isEmpty + && selection.sectionReferences.allSatisfy { $0.condition == nil } + } else { + false + } + } + let matching = editable.filter { index in + guard case .instructions(let selection) = next.components[index] else { return false } + return options.agents.map { Set($0) == Set(selection.agents ?? declaration.defaultAgents) } + ?? false + } + if let index = editable.count == 1 + ? editable.first : matching.count == 1 ? matching.first : nil, + case .instructions(var instructions) = next.components[index] + { + if let agents = options.agents { instructions.agents = agents } + for reference in references where !instructions.sectionReferences.contains(reference) { + instructions.sectionReferences.append(reference) + } + next.components[index] = .instructions(instructions) + } else { + var instructions = InstructionsDeclaration(agents: options.agents) + instructions.sectionReferences = references + next.components.append(.instructions(instructions)) + } + return try UpdateOperations.withDomainUpdate( + UpdateRequest( + operation: .declaration(next), kinds: [.instructions], replace: options.replace, + expectedDeclarationDigest: digest), scope: options.scope, environment: options.environment + ) { prepared in + try beforeApply?(prepared.report.instructions) + return InstructionAddOutcome( + sourceID: id, available: available, result: try prepared.apply().report.instructions) + } + } + + 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 { + var request = UpdateRequest(kinds: [.instructions], replace: replace) + if let agents { + var declaration = try StateStore(scope: scope, environment: environment).loadDeclaration() + declaration.components = declaration.components.map { component in + if case .instructions(var selection) = component { + selection.agents = agents + return .instructions(selection) + } + return component + } + request.operation = .declaration(declaration) + } + if !apply { + return try UpdateOperations.preview(request, scope: scope, environment: environment) + .instructions + } + return try UpdateOperations.withDomainUpdate(request, scope: scope, environment: environment) { + prepared in + try beforeApply?(prepared.report.instructions) + return try prepared.apply().report.instructions + } + } + + public static func installResolvedReport( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> InstructionUpdateReport { + try UpdateOperations.withDomainUpdate( + UpdateRequest(operation: .restore, kinds: [.instructions]), scope: scope, + environment: environment + ) { try $0.apply().report.instructions } + } + + @discardableResult + public static func remove( + names: [String], scope: InstallScope = .project, agents: [AgentID]? = nil, + environment: RuntimeEnvironment = RuntimeEnvironment(), + beforeApply: ((InstructionUpdateReport) throws -> Void)? = nil + ) throws -> InstructionUpdateReport { + try UpdateOperations.withDomainUpdate( + UpdateRequest(operation: .remove, kinds: [.instructions], names: names, agents: agents), + scope: scope, environment: environment + ) { prepared in + try beforeApply?(prepared.report.instructions) + return try prepared.apply().report.instructions + } + } +} + +extension InstructionOperations { + public static func renderChatGPT( + prompt name: String, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> Data { + let store = StateStore(scope: scope, environment: environment) + return try store.withReadLock { + _ = try store.readDeclaration() + let ledger = try store.readLedger() + return try LedgerReplay.withReplay( + ledger, store: store, roots: store.ledgerRoots, limits: .standard + ) { artifacts in + guard let bytes = artifacts.first(where: { $0.name == "prompt:" + name })?.bytes else { + throw InstructionError.emptyPrompt + } + return bytes + } + } + } +} diff --git a/Sources/AgentsUpdates/PreparedUpdate.swift b/Sources/AgentsUpdates/PreparedUpdate.swift index 9c3d194..f1d4a15 100644 --- a/Sources/AgentsUpdates/PreparedUpdate.swift +++ b/Sources/AgentsUpdates/PreparedUpdate.swift @@ -19,7 +19,7 @@ public final class PreparedUpdate { self.outcome = outcome } - public func apply() throws -> UpdateApplyResult { + public func apply(ifUnchangedFrom fingerprint: String? = nil) throws -> UpdateApplyResult { let pending = try gate.withLock { guard active, !attempted, let plan else { throw CoreError.invalidState("prepared update is inactive, consumed or on another thread") @@ -31,6 +31,9 @@ public final class PreparedUpdate { return plan } do { + if let fingerprint, fingerprint != report.displayedFingerprint { + throw CoreError.invalidState("displayed update candidate changed; refresh the report") + } return try pending.apply(outcome: outcome) } catch { pending.recover(outcome: outcome) diff --git a/Sources/AgentsUpdates/SkillOperations.swift b/Sources/AgentsUpdates/SkillOperations.swift new file mode 100644 index 0000000..e4555f2 --- /dev/null +++ b/Sources/AgentsUpdates/SkillOperations.swift @@ -0,0 +1,141 @@ +import AgentsCore +import AgentsManifest +import AgentsSkills +import Foundation + +extension SkillOperations { + public static func add(_ options: AddOptions) throws -> AddOutcome { + try add(options, checkpoint: { _ in }) + } + + package static func add(_ supplied: AddOptions, checkpoint: @escaping (String) throws -> Void) + throws -> AddOutcome + { + var options = supplied + if let name = try SourceArgument(options.source).name { + guard !options.all else { + throw CoreError.invalidSource("a named skill cannot be combined with all") + } + if !options.skillNames.contains(name) { options.skillNames.append(name) } + } + let store = StateStore(scope: options.scope, environment: options.environment) + let (declaration, digest, source, id, available) = try store.withReadLock { + let declaration = try store.readDeclaration() + let digest = try store.declarationDocument(prepared: nil)?.digest ?? "absent" + let (source, id, available) = try SkillOperations.inspect(options, declaration: declaration) + return (declaration, digest, source, id, available) + } + if options.listOnly || (options.skillNames.isEmpty && !options.all && available.count > 1) { + return AddOutcome(source: source, sourceID: id, availableSkills: available, installed: []) + } + guard !available.isEmpty else { + throw CoreError.notFound("no skills found in " + source.location) + } + var next = declaration + 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 prior = declaration.sources[alias], + try prior.identity(environment: options.environment) != id + { + throw CoreError.invalidSource("source alias already refers to another source") + } + next.sources[alias] = source + let names = available.map { PathSafety.sanitizeName($0.name) } + var updated = false + for index in next.components.indices { + guard case .skills(let selectedAlias, var selection) = next.components[index], + selectedAlias == alias + else { continue } + guard !updated else { + throw CoreError.invalidState( + "skill selection is ambiguous; edit the specific YAML occurrence") + } + updated = true + if options.all { + selection.select = .all + } else if case .names(let old) = selection.select { + selection.select = .names(Array(Set(old + names)).sorted()) + } + selection.exclude = selection.exclude?.filter { !names.contains($0) } + var overrides = selection.overrides ?? [:] + for name in names { + overrides[name] = SkillOverride( + agents: options.agents ?? overrides[name]?.agents ?? selection.agents, mode: options.mode) + } + selection.overrides = overrides + next.components[index] = .skills(source: alias, selection) + } + if !updated { + next.components.append( + .skills( + source: alias, + SkillDeclaration( + select: options.all ? .all : .names(names), agents: options.agents, mode: options.mode)) + ) + } + var request = UpdateRequest( + operation: .declaration(next), kinds: [.skills], names: names, + expectedDeclarationDigest: digest) + if options.skillNames.isEmpty && !options.all { + request.automaticSkill = (id, available[0].name) + } + return try UpdateOperations.withDomainUpdate( + request, scope: options.scope, environment: options.environment, checkpoint: checkpoint + ) { prepared in + let result = try prepared.apply() + return AddOutcome( + source: source, sourceID: id, availableSkills: available, installed: result.installedSkills) + } + } + + public static func updateInstalled( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + skillNames: [String] = [], apply: Bool = false, + beforeApply: (([UpdateResult]) throws -> Void)? = nil + ) throws -> [UpdateResult] { + let request = UpdateRequest(kinds: [.skills], names: skillNames) + if !apply { + return try UpdateOperations.preview(request, scope: scope, environment: environment).skills + } + return try UpdateOperations.withDomainUpdate(request, scope: scope, environment: environment) { + prepared in + try beforeApply?(prepared.report.skills) + let applied = try prepared.apply() + return applied.report.skills.map { item in + var item = item + item.installed = applied.installedSkills.filter { $0.skill == item.skill } + return item + } + } + } + + public static func installResolvedReport( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> ResolvedInstallReport { + try UpdateOperations.withDomainUpdate( + UpdateRequest(operation: .restore, kinds: [.skills]), scope: scope, environment: environment + ) { + ResolvedInstallReport(installed: try $0.apply().installedSkills) + } + } + + @discardableResult + public static func remove( + skillNames: [String], scope: InstallScope = .project, agents: [AgentID]? = nil, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> [String] { + let names = skillNames.map(PathSafety.sanitizeName) + return try UpdateOperations.withDomainUpdate( + UpdateRequest(operation: .remove, kinds: [.skills], names: names, agents: agents), + scope: scope, environment: environment + ) { + guard Set(names).isSubset(of: Set($0.report.skills.map(\.skill))) else { + throw CoreError.notFound("skill is not installed") + } + _ = try $0.apply() + return names.sorted() + } + } +} diff --git a/Sources/AgentsUpdates/UpdateInputs.swift b/Sources/AgentsUpdates/UpdateInputs.swift new file mode 100644 index 0000000..9ff3d69 --- /dev/null +++ b/Sources/AgentsUpdates/UpdateInputs.swift @@ -0,0 +1,45 @@ +import AgentsCore +import AgentsSkills +import Foundation + +/// Live skill content remains live; its authored directory identity and valid metadata cannot change. +final class UpdateInputs: PreparedEvidence { + private struct LiveSkill { + let url: URL + let name: String + let logical: PathIdentity + let physical: PathIdentity + } + private let frozen: [TargetPrecondition] + private let live: [LiveSkill] + + init( + ledger: ResolvedLedger, resources: [String: URL], decisions: [TargetPrecondition], + originals: [TargetPrecondition] + ) throws { + frozen = decisions + originals + live = try ledger.components.values.compactMap { component in + guard component.kind == "skills", let id = component.resources.first, + ledger.resources[id]?.kind == .liveEdit, let url = resources[id] + else { return nil } + return try LiveSkill( + url: url, name: component.payload.object?["name"]?.text ?? component.name, + logical: PathIdentity(url), physical: PathIdentity(url.resolvingSymlinksInPath())) + } + } + + func validate(excludingTargets targets: Set = []) throws { + for evidence in frozen where !targets.contains(evidence.url.path) { + if targets.isEmpty { + try evidence.validate() + } else { + try evidence.validateDuringPublication() + } + } + for item in live { + try item.logical.validate() + try item.physical.validate() + try SkillOperations.validateLiveMetadata(at: item.url, name: item.name) + } + } +} diff --git a/Sources/AgentsUpdates/UpdateModels.swift b/Sources/AgentsUpdates/UpdateModels.swift index 056a950..db45b9b 100644 --- a/Sources/AgentsUpdates/UpdateModels.swift +++ b/Sources/AgentsUpdates/UpdateModels.swift @@ -2,13 +2,15 @@ import AgentsCore import AgentsInstructions import AgentsSkills -public struct CombinedUpdateReport: Sendable, Equatable { +public struct CombinedUpdateReport: Codable, Sendable, Equatable { public let scope: InstallScope public let skills: [UpdateResult] public let instructions: InstructionUpdateReport public let lockMissing: Bool /// Includes normalized state changes and missing-lock reconstruction, even without file diffs. public let hasChanges: Bool + public let displayedFingerprint: String + public let components: [ComponentUpdateChange] } public struct UpdateApplyResult: Sendable { @@ -37,3 +39,37 @@ public struct UpdateApplyError: Error { (underlyingError as? UpdateApplyError)?.underlyingError ?? underlyingError } } + +public struct ComponentUpdateChange: Codable, Sendable, Equatable { + public let sourceIdentity: String + public let revision: String? + public let version: String? + public let format: String + public let ownership: String + public let resources: [ComponentResourceInfo] + public let requiredBindings: [String] + public let privateMaterialization: Bool + public let permissionChange: ComponentPermissionChange? + public let symbolicBefore: String? + public let symbolicAfter: String? + public let kind: String + public let name: String + public let path: String + public let agents: [AgentID] + public let changed: Bool +} + +public struct ComponentResourceInfo: Codable, Sendable, Equatable { + public let path: String + public let hash: String + public let executableFiles: [String: Bool] +} + +public struct ComponentPermissionChange: Codable, Sendable, Equatable { + public let beforeOwner: UInt32 + public let beforeGroup: UInt32 + public let beforeMode: UInt32 + public let afterOwner: UInt32 + public let afterMode: UInt32 + public let ownerOnly: Bool +} diff --git a/Sources/AgentsUpdates/UpdateOperations.swift b/Sources/AgentsUpdates/UpdateOperations.swift index 4cd1383..52aae6d 100644 --- a/Sources/AgentsUpdates/UpdateOperations.swift +++ b/Sources/AgentsUpdates/UpdateOperations.swift @@ -1,54 +1,123 @@ import AgentsCore +import AgentsManifest import Foundation +struct RequiredBindingProvider: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + throw CoreError.invalidState("this materialization requires a runtime binding provider") + } +} + public enum UpdateOperations { - /// Resolves a fresh, read-only report under one shared scope lock. Pending recovery stops inspection. public static func preview( - scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + _ request: UpdateRequest = UpdateRequest(), scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> CombinedUpdateReport { - try preview(scope: scope, environment: environment, checkpoint: { _ in }) + try preview(request, scope: scope, environment: environment, checkpoint: { _ in }) } package static func preview( - scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + _ request: UpdateRequest = UpdateRequest(), scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), checkpoint: @escaping (String) throws -> Void ) throws -> CombinedUpdateReport { let store = StateStore(scope: scope, environment: environment) - return try store.withReadLock { try UpdatePlan(store: store, checkpoint: checkpoint).report } + var admitted = Set() + while true { + do { + return try store.withReadLock(footprint: admitted) { + try UpdatePlan.withPlan( + request: request, store: store, admitted: admitted, + checkpoint: checkpoint, provider: RequiredBindingProvider() + ) { $0.report } + } + } catch let required as RequiredRoutes { admitted.formUnion(required.routes) } + } } - /// Holds the writer lock through preparation, synchronous rendering and optional application. - /// Returning or throwing before apply cancels. A caller error after apply does not undo the commit. + /// Holds admitted locks and borrowed resources through this synchronous, same-thread closure. public static func withPreparedUpdate( - scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + _ request: UpdateRequest = UpdateRequest(), scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), _ body: (PreparedUpdate) throws -> Result ) throws -> Result { - try withPreparedUpdate(scope: scope, environment: environment, checkpoint: { _ in }, body) + try withPreparedUpdate( + request, scope: scope, environment: environment, checkpoint: { _ in }, body) } package static func withPreparedUpdate( - scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + _ request: UpdateRequest = UpdateRequest(), scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), checkpoint: @escaping (String) throws -> Void, _ body: (PreparedUpdate) throws -> Result + ) throws -> Result { + try prepare( + request, scope: scope, environment: environment, checkpoint: checkpoint, + provider: RequiredBindingProvider(), body) + } + + package static func prepare( + _ request: UpdateRequest, scope: InstallScope, environment: RuntimeEnvironment, + checkpoint: @escaping (String) throws -> Void, provider: any RuntimeBindingProvider, + _ body: (PreparedUpdate) throws -> Result ) throws -> Result { let store = StateStore(scope: scope, environment: environment) let outcome = TransactionOutcome() + var delivered = false var returned = false - do { - return try store.withLock(checkpoint: checkpoint, outcome: outcome) { - let plan = try UpdatePlan(store: store, checkpoint: checkpoint) - try plan.validateOwnership() - let update = PreparedUpdate(plan: plan, outcome: outcome) - defer { update.invalidate() } - let result = try body(update) - returned = true - return result - } - } catch { - if returned || error is UpdateApplyError { - throw UpdateApplyError(outcome: outcome, underlyingError: error) + var admitted = Set() + while true { + do { + return try store.withLock(checkpoint: checkpoint, outcome: outcome, footprint: admitted) { + try UpdatePlan.withPlan( + request: request, store: store, admitted: admitted, + checkpoint: checkpoint, provider: provider + ) { plan in + let update = PreparedUpdate(plan: plan, outcome: outcome) + defer { update.invalidate() } + delivered = true + let result = try body(update) + returned = true + return result + } + } + } catch let required as RequiredRoutes where !delivered { + admitted.formUnion(required.routes) + } catch { + if returned || error is UpdateApplyError { + throw UpdateApplyError(outcome: outcome, underlyingError: error) + } + throw error } + } + } + + static func withDomainUpdate( + _ request: UpdateRequest, scope: InstallScope, environment: RuntimeEnvironment, + checkpoint: @escaping (String) throws -> Void = { _ in }, + _ body: (PreparedUpdate) throws -> Result + ) throws -> Result { + do { + return try withPreparedUpdate( + request, scope: scope, environment: environment, checkpoint: checkpoint, body) + } catch let error as UpdateApplyError { + if case .unchanged = error.disposition { throw error.underlyingError } throw error } } + + static func declarationSnapshot(_ store: StateStore) throws -> (Declaration, String) { + try store.withReadLock { + let document = try store.declarationDocument(prepared: nil) + return (try store.readDeclaration(), document?.digest ?? "absent") + } + } + + public static func restore( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> UpdateApplyResult { + try withPreparedUpdate( + UpdateRequest(operation: .restore), scope: scope, environment: environment + ) { try $0.apply() } + } } diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 72b4656..6ffda1d 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -2,119 +2,517 @@ import AgentsCore import AgentsInstructions import AgentsManifest import AgentsSkills +import Components import Foundation -/// Domain plans share resolution, but contribute only their owned records to the next generation. +struct RequiredRoutes: Error { let routes: Set } + +/// The composition plan borrows both source/replay resources and the admitted writer scope. final class UpdatePlan { let report: CombinedUpdateReport private let store: StateStore private let baseline: StatePrecondition - private let declaration: Declaration - private let previous: ResolvedState - private let next: ResolvedState + private let next: ResolvedLedger private let watch: WatchState - private let skills: SkillUpdatePlan - private let instructions: InstructionUpdatePlan - private let resolutions: SourceResolutionSession + private let declarationChange: DeclarationChange? + private let aggregation: ArtifactAggregation private let checkpoint: (String) throws -> Void + private let provider: any RuntimeBindingProvider + private let inputs: UpdateInputs + private let receipts: [InstallResult] - init(store: StateStore, checkpoint: @escaping (String) throws -> Void = { _ in }) throws { + static func withPlan( + request: UpdateRequest, store: StateStore, admitted: Set, + checkpoint: @escaping (String) throws -> Void, provider: any RuntimeBindingProvider, + _ body: (UpdatePlan) throws -> T + ) throws -> T { + let baseline = try StatePrecondition(store: store) + let previous = try store.readLedger(prepared: baseline) + let restoringRequest: Bool + if case .restore = request.operation { + restoringRequest = true + } else { + restoringRequest = false + } + _ = try store.declarationBytes(prepared: baseline) + let declaration = + try restoringRequest ? Declaration() : store.readDeclaration(prepared: baseline) + let watch = try store.readWatch(prepared: baseline) + let original = try restoringRequest ? nil : store.declarationDocument(prepared: baseline) + if let expected = request.expectedDeclarationDigest, expected != (original?.digest ?? "absent") + { + throw CoreError.invalidState("declaration changed during discovery; retry the command") + } + var candidate = declaration + var change: DeclarationChange? + let restoring: Bool + switch request.operation { + case .restore: restoring = true + case .update: restoring = false + case .edit(let edits): + restoring = false + guard let original else { throw CoreError.notFound("declaration document") } + let edited = try original.preparing(edits) + change = edited.bytes == original.bytes ? nil : DeclarationChange(bytes: Data(edited.bytes)) + candidate = try ManifestProjection.declaration( + of: DeclarationDocument( + bytes: edited.bytes, identity: DocumentIdentity(store.declarationURL.path)), + environment: store.environment) + case .declaration(let replacement): + restoring = false + candidate = replacement + change = try store.planDeclaration(candidate, replacing: declaration, prepared: baseline) + case .remove: + restoring = false + try LedgerImpact.requireEditable( + previous, kinds: request.kinds ?? Set(DeclaredComponentKind.allCases), + names: Set(request.names), roots: store.ledgerRoots) + candidate = try removing(request, from: declaration, ledger: previous, store: store) + change = try store.planDeclaration(candidate, replacing: declaration, prepared: baseline) + } + if restoring { + let routes = try DeploymentConstruction.routes(previous) + guard routes.isSubset(of: admitted) else { throw RequiredRoutes(routes: routes) } + return try LedgerReplay.withLockedResources( + previous, store: store, roots: store.ledgerRoots, limits: .standard + ) { artifacts, resources, workspace in + try body( + UpdatePlan( + request: request, store: store, baseline: baseline, previous: previous, next: previous, + watch: watch, change: nil, artifacts: artifacts, resources: resources, + workspace: workspace, + decisionInputs: [], originalInputs: [], + checkpoint: checkpoint, provider: provider)) + } + } + var document: DeclarationDocument + if let change { + document = try DeclarationDocument( + bytes: Array(change.bytes), identity: DocumentIdentity(store.declarationURL.path)) + } else if let original { + document = original + } else { + document = try DeclarationDocument( + bytes: Array("version: 1\n".utf8), identity: DocumentIdentity(store.declarationURL.path)) + } + let updating: Bool + if case .update = request.operation { updating = true } else { updating = false } + if updating, !request.names.isEmpty, request.kinds?.contains(.skills) ?? true { + var linkingDeclaration = candidate + for index in linkingDeclaration.components.indices { + guard case .skills(let alias, var selection) = linkingDeclaration.components[index], + case .all = selection.select, let source = linkingDeclaration.sources[alias] + else { continue } + let identity = try source.identity(environment: store.environment) + let existing = try previous.components.values.filter { component in + guard component.kind == "skills", component.group == nil else { return false } + return try previous.sourceIdentity(component.source, roots: store.ledgerRoots) == identity + }.map { PathSafety.sanitizeName($0.name) } + let selected = request.names.filter { name in + !previous.components.values.contains { $0.kind == "skills" && $0.name == name } + || existing.contains(name) + } + selection.select = .names(Array(Set(existing + selected)).sorted()) + linkingDeclaration.components[index] = .skills(source: alias, selection) + } + if let bytes = try store.planDeclaration( + linkingDeclaration, replacing: declaration, prepared: baseline)?.bytes + { + document = try DeclarationDocument( + bytes: Array(bytes), identity: DocumentIdentity(store.declarationURL.path)) + } + } + let impact = try LedgerImpact( + ledger: previous, roots: store.ledgerRoots, + kinds: request.kinds ?? Set(DeclaredComponentKind.allCases), names: Set(request.names), + updating: updating) + #if os(macOS) + let platform = DeclarationPlatform.macOS + #else + let platform = DeclarationPlatform.linux + #endif + return try ComponentLinker.withLinkedComponents( + document: document, store: store, platform: platform, + preserving: impact.pins, directPins: impact.directPins + ) { linked, session in + if let expected = request.automaticSkill { + guard + linked.components.contains(where: { component in + if case .skill(let skill, _, _) = component.payload { + return skill.name == expected.name && component.snapshot.source == expected.source + } + return false + }) + else { + throw CoreError.invalidState( + "automatic skill selection changed during discovery; retry the command") + } + } + var locations: [String: LedgerLocation] = [:] + let packageRoot = + store.scope == .project ? store.environment.projectDirectory : store.directory + for evidence in linked.sourceSnapshots + linked.declaringSnapshots + where evidence.container == nil && evidence.snapshot.source.hasPrefix("local:") { + let path = String(evidence.snapshot.source.dropFirst(6)) + if path == packageRoot.path { + locations[evidence.snapshot.source] = .init( + kind: .registered, root: store.scope == .project ? "project" : "state", path: ".") + } else if let authored = try candidate.sources.values.first(where: { + try $0.identity(environment: store.environment) == evidence.snapshot.source + }), + !authored.location.hasPrefix("/") + { + if authored.location == "~" || authored.location.hasPrefix("~/") { + locations[evidence.snapshot.source] = .init( + kind: .authoringRelative, root: "home", + path: authored.location == "~" ? "." : String(authored.location.dropFirst(2))) + } else if authored.environment?.projectDirectory.path + == store.environment.projectDirectory.path || authored.environment == nil + { + locations[evidence.snapshot.source] = .init( + kind: .authoringRelative, root: "project", path: authored.location) + } else { + locations[evidence.snapshot.source] = .init(kind: .absolute, path: path) + } + } else { + locations[evidence.snapshot.source] = .init(kind: .absolute, path: path) + } + } + let frozen = try LedgerFreeze.freezeWithSources( + linked, session: session, locations: .init(sources: locations), limits: .standard) + let native = try DeploymentConstruction.lowerNative( + linked: linked, frozen: frozen, scope: store.scope, platform: platform) + let routes = try DeploymentConstruction.routes(native).union( + DeploymentConstruction.routes(previous)) + guard routes.isSubset(of: admitted) else { throw RequiredRoutes(routes: routes) } + if let kinds = request.kinds { + try LedgerImpact.requireProtected( + previous: previous, next: native, kinds: kinds, names: Set(request.names), + roots: store.ledgerRoots) + } + let complete = try DeploymentConstruction.complete( + native, linked: linked, store: store, previous: previous, platform: platform) + let originals = try linked.components.flatMap { c -> [TargetPrecondition] in + if case .skill(_, .edit, _) = c.payload { return [] } + return try c.resources.filter { $0.snapshot.revision == "live" }.map { + try TargetPrecondition(session.resource(snapshot: $0.snapshot, path: $0.path)) + } + } + try checkpoint("plan.skills") + return try LedgerReplay.withPreparedLowerings( + complete.ledger, store: store, roots: store.ledgerRoots, limits: .standard + ) { next, artifacts, resources, workspace in + try body( + UpdatePlan( + request: request, store: store, baseline: baseline, previous: previous, next: next, + watch: watch, change: change, artifacts: artifacts, resources: resources, + workspace: workspace, + decisionInputs: complete.inputs, originalInputs: originals, + checkpoint: checkpoint, provider: provider)) + } + } + } + + private init( + request: UpdateRequest, store: StateStore, baseline: StatePrecondition, + previous: ResolvedLedger, next: ResolvedLedger, watch: WatchState, + change: DeclarationChange?, artifacts: [ReplayedArtifact], resources: [String: URL], + workspace: URL, + decisionInputs: [TargetPrecondition], originalInputs: [TargetPrecondition], + checkpoint: @escaping (String) throws -> Void, provider: any RuntimeBindingProvider + ) throws { self.store = store + self.baseline = baseline + self.watch = watch + declarationChange = change self.checkpoint = checkpoint - baseline = try StatePrecondition(store: store) - declaration = try store.readDeploymentDeclaration(prepared: baseline) - previous = try store.readResolved(prepared: baseline) - watch = try store.readWatch(prepared: baseline) - resolutions = try SourceResolutionSession(store: store) - skills = try SkillOperations.prepareUpdate( - store: store, declaration: declaration, previous: previous, resolutions: resolutions) - try checkpoint("plan.skills") - instructions = try InstructionOperations.prepareUpdate( - store: store, declaration: declaration, previousDeclaration: declaration, - previous: previous, resolutions: resolutions) - var next = previous - next.skills = skills.next.skills - next.instructions = instructions.next.instructions - next.sources = try Self.mergedSources( - previous: previous.sources, skills: skills.next.sources, - instructions: instructions.next.sources) - try declaration.validate(environment: store.environment) - try next.validate() - self.next = next + self.provider = provider + inputs = try UpdateInputs( + ledger: next, resources: resources, decisions: decisionInputs, originals: originalInputs) + aggregation = try ArtifactAggregation( + ledger: next, previous: previous, artifacts: artifacts, + resources: resources, workspace: workspace, store: store, replace: request.replace, + changingAccess: request.changingAccess, kinds: request.kinds) + self.next = aggregation.ledger + try self.next.validate() let lockMissing = try baseline.bytes(for: store.resolvedURL) == nil + let before = try previous.domainProjection(roots: store.ledgerRoots) + let after = try self.next.domainProjection(roots: store.ledgerRoots) + let allResults = try UpdateReporting.skills( + previous: previous, next: self.next, resources: resources, + changes: aggregation.changes, store: store, lockMissing: lockMissing, + included: request.kinds == nil || request.kinds!.contains(.skills)) + let results = + request.names.isEmpty ? allResults : allResults.filter { request.names.contains($0.skill) } + receipts = results.flatMap(\.installed) + let publicResults = results.map { + var result = $0 + result.installed = [] + return result + } + func instructionArtifacts(_ ledger: ResolvedLedger) -> [String: String] { + var result: [String: String] = [:] + for lowering in ledger.lowerings + where ["agents/instructions@1", "agents/claude-import@1", "agents/chatgpt@1"].contains( + lowering.format) + { + for artifact in lowering.artifacts { + result[lowering.format + ":" + artifact.name] = artifact.hash + } + } + return result + } + let instructions = try UpdateReporting.instructions( + before: before.instructions, after: after.instructions, + changes: aggregation.changes, lockMissing: lockMissing, + included: request.kinds == nil || request.kinds!.contains(.instructions), store: store, + stateChanged: instructionArtifacts(previous) != instructionArtifacts(self.next) + || (change != nil && request.kinds == [.instructions])) + let operation: String + switch request.operation { + case .update: operation = "update" + case .restore: operation = "restore" + case .remove: operation = "remove" + case .edit, .declaration: operation = "edit" + } + struct Fingerprint: Encodable { + let version = 1 + let operation: String + let scope: InstallScope + let kinds: [String]? + let names: [String] + let replace: Bool + let changingAccess: Bool + let candidate: ResolvedLedger + let baseline: ResolvedLedger + let declaration: String? + let targets: [String] + } + let fingerprint = try ResolvedLedgerCodec.digest( + Fingerprint( + operation: operation, scope: store.scope, kinds: request.kinds?.map(\.rawValue).sorted(), + names: request.names.sorted(), replace: request.replace, + changingAccess: request.changingAccess, + candidate: self.next, baseline: previous, + declaration: try (change?.bytes ?? baseline.bytes(for: store.declarationURL)).map { + "sha256:" + FileHash.sha256Hex(data: $0) + }, + targets: (aggregation.fingerprints + + (try decisionInputs.map { try $0.displayEvidence(includeContent: false) })).sorted())) + let finalNext = self.next report = CombinedUpdateReport( - scope: store.scope, skills: skills.results, instructions: instructions.report, + scope: store.scope, skills: publicResults, instructions: instructions, lockMissing: lockMissing, - hasChanges: next.normalized != previous.normalized - || skills.results.contains(where: \.changed) || instructions.report.hasChanges - || (lockMissing && declaration.normalized != Declaration().normalized)) + hasChanges: self.next != previous || change != nil + || aggregation.changes.contains(where: \.changed), + displayedFingerprint: fingerprint, + components: try aggregation.changes.filter(\.native).map { change in + let owner = change.deployment.owners[0] + let ledger = finalNext.components[owner] == nil ? previous : finalNext + let component = ledger.components[owner]! + return ComponentUpdateChange( + sourceIdentity: try ledger.sourceIdentity(component.source, roots: store.ledgerRoots), + revision: component.revision, version: component.version, + format: change.deployment.route, ownership: change.deployment.ownership.rawValue, + resources: component.resources.compactMap { ledger.resources[$0] }.map { resource in + ComponentResourceInfo( + path: resource.path, hash: resource.hash, + executableFiles: Dictionary( + uniqueKeysWithValues: resource.entries.filter { $0.kind == .file }.map { + ($0.path, $0.executable) + })) + }, requiredBindings: change.requiredBindings, + privateMaterialization: change.privateMaterialization, + permissionChange: change.accessChange.map { access in + ComponentPermissionChange( + beforeOwner: access.before.owner, beforeGroup: access.before.group, + beforeMode: UInt32(access.before.mode), afterOwner: access.owner, + afterMode: access.mode, ownerOnly: true) + }, + symbolicBefore: try change.symbolicBefore.map { + String(decoding: try ResolvedLedgerCodec.bytes($0), as: UTF8.self) + }, + symbolicAfter: try change.symbolicAfter.map { + String(decoding: try ResolvedLedgerCodec.bytes($0), as: UTF8.self) + }, + kind: component.kind, name: component.name, path: change.url.path, + agents: change.deployment.recipients, changed: change.changed) + }) try baseline.validate() } - func validateOwnership() throws { - try skills.validateOwnership() - let paths = skills.targetPaths + instructions.report.targets.map(\.url) - for (index, path) in paths.enumerated() { - guard - !paths.prefix(index).contains(where: { - PathSafety.isContained(path, in: $0) || PathSafety.isContained($0, in: path) - }) - else { throw CoreError.invalidState("overlapping update targets") } - } - try skills.validate() - try instructions.validate() - } - - static func mergedSources( - previous: [String: LockedSource], skills: [String: LockedSource], - instructions: [String: LockedSource] - ) throws -> [String: LockedSource] { - var next = previous - for (id, source) in skills where source != previous[id] { next[id] = source } - for id in instructions.keys.sorted() { - let source = instructions[id]! - guard source != previous[id] else { continue } - if let other = skills[id], other != previous[id], other != source { - throw CoreError.invalidState("incompatible planned source records: \(id)") - } - next[id] = source - } - return next - } - func apply(outcome: TransactionOutcome) throws -> UpdateApplyResult { - try validate() + try baseline.validate() + try aggregation.validate() + try aggregation.requireOwnership() + try inputs.validate() if report.hasChanges { - let retained = try skills.retain() - try instructions.retain() + var references = try RetentionReferences(ledger: next, roots: store.ledgerRoots) + try references.include(watch: watch) + let cache = SourceCache(store: store, checkpoint: checkpoint) + try cache.retain(references: references) try checkpoint("apply.retained") + try baseline.validate() + try aggregation.validate() + try inputs.validate() let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) - transaction.requireUnchanged(since: baseline, skills, instructions) - try skills.stage(retained: retained, transaction: transaction) - try instructions.stage(transaction: transaction) - if let resolvedBytes = try next.replacementData(in: store, prepared: baseline) { - try transaction.replace( - store.resolvedURL, with: .data(resolvedBytes), - expecting: baseline.evidence(for: store.resolvedURL)) + transaction.requireUnchanged(since: baseline, aggregation, inputs) + try aggregation.stage(transaction: transaction, provider: provider) + try store.stageDeclaration(declarationChange, in: transaction, prepared: baseline) + // Empty scopes need no lock file; a declaration edit always accompanies first deployment. + if try store.declarationBytes(prepared: baseline) != nil || declarationChange != nil { + try store.stageLedger(next, limits: .standard, transaction: transaction, prepared: baseline) } - try SourceCache(store: store).prune( - referencedBy: next, watch: watch, transaction: transaction) + try cache.prune(references: references, transaction: transaction) try transaction.commit() } - return UpdateApplyResult(report: report, installedSkills: skills.receipts) - } - - private func validate() throws { - try baseline.validate() - try skills.validate() - try instructions.validate() + return UpdateApplyResult(report: report, installedSkills: receipts) } func recover(outcome: TransactionOutcome) { - do { - _ = try FileTransaction.recover(store: store, outcome: outcome) - } catch { + do { _ = try FileTransaction.recover(store: store, outcome: outcome) } catch { outcome.disposition = .recoveryRequired } } + + private static func removing( + _ request: UpdateRequest, from declaration: Declaration, ledger: ResolvedLedger, + store: StateStore + ) throws -> Declaration { + var result = declaration + let names = Set(request.names) + let kinds = request.kinds ?? Set(DeclaredComponentKind.allCases) + let references = Set( + declaration.components.flatMap { component -> [String] in + if case .instructions(let value) = component { + return value.sectionReferences.map(\.reference) + + value.prompts.flatMap { $0.prompt.sectionReferences.map(\.reference) } + } + return [] + }) + var instructionReferences = Set() + if kinds.contains(.instructions) { + for name in names { + let exact = references.filter { $0 == name } + let matches = + exact.isEmpty + ? references.filter { $0.split(separator: ":").last.map(String.init) == name } : exact + guard matches.count == 1, let reference = matches.first else { + throw CoreError.notFound("instruction name is missing or ambiguous: " + name) + } + instructionReferences.insert(reference) + } + } + result.components = declaration.components.compactMap { component in + switch component { + case .skills(let alias, var selection) where kinds.contains(.skills): + if case .all = selection.select { + selection.exclude = Array(Set(selection.exclude ?? []).union(names)).sorted() + } else if case .names(let selected) = selection.select { + selection.select = .names(selected.filter { !names.contains($0) }) + } + if request.agents == nil { + selection.overrides = selection.overrides?.filter { !names.contains($0.key) } + } + if let agents = request.agents { + selection = { + var original = selection + for name in names { + let current = ledger.components.values.first { + $0.name == name && $0.kind == "skills" + } + var overrides = original.overrides ?? [:] + overrides[name] = SkillOverride( + agents: current?.recipients.filter { !agents.contains($0) } ?? [], + mode: original.overrides?[name]?.mode) + original.overrides = overrides + } + return original + }() + if let prior = declaration.components.first(where: { + if case .skills(let a, _) = $0 { a == alias } else { false } + }), case .skills(_, let original) = prior { + selection.select = original.select + selection.exclude = original.exclude + } + } + return .skills(source: alias, selection) + case .instructions(var selection) where kinds.contains(.instructions): + selection.sectionReferences.removeAll { + instructionReferences.contains($0.reference) + } + for index in selection.prompts.indices { + selection.prompts[index].prompt.sectionReferences.removeAll { + instructionReferences.contains($0.reference) + } + } + selection.prompts.removeAll { $0.prompt.sectionReferences.isEmpty } + if let agents = request.agents { selection.agents = agents } + return .instructions(selection) + default: + guard kinds.contains(component.kind), names.contains(component.name ?? "") else { + return component + } + if let agents = request.agents { + let recipients = (component.selectedAgents ?? declaration.defaultAgents).filter { + !agents.contains($0) + } + return component.replacingAgents(recipients) + } + return nil + } + } + return result + } +} + +extension ComponentDeclaration { + fileprivate var selectedAgents: [AgentID]? { + switch self { + case .skills(_, let s): s.agents + case .instructions(let s): s.agents + case .mcpServer(_, _, let a, _, _), .hook(_, _, _, _, _, let a, _, _), + .subagent(_, _, _, _, _, let a, _, _), .command(_, _, _, _, let a, _, _), + .lspServer(_, _, _, _, let a, _, _), .permissions(_, _, let a, _, _), + .ignore(_, _, _, let a, _, _), .plugin(_, _, _, _, _, _, let a, _, _): + a + } + } + + fileprivate func replacingAgents(_ agents: [AgentID]) -> ComponentDeclaration { + switch self { + case .skills(let source, var value): + value.agents = agents + return .skills(source: source, value) + case .instructions(var value): + value.agents = agents + return .instructions(value) + case .mcpServer(let n, let t, _, let c, let v): + return .mcpServer(name: n, transport: t, agents: agents, condition: c, native: v) + case .hook(let n, let e, let r, let m, let t, _, let c, let v): + return .hook( + name: n, event: e, run: r, matcher: m, timeoutSeconds: t, agents: agents, condition: c, + native: v) + case .subagent(let n, let d, let p, let m, let t, _, let c, let v): + return .subagent( + name: n, description: d, prompt: p, model: m, tools: t, agents: agents, condition: c, + native: v) + case .command(let n, let d, let p, let args, _, let c, let v): + return .command( + name: n, description: d, prompt: p, parameters: args, agents: agents, condition: c, + native: v) + case .lspServer(let n, let r, let l, let o, _, let c, let v): + return .lspServer( + name: n, run: r, languages: l, initializationOptions: o, agents: agents, condition: c, + native: v) + case .permissions(let n, let r, _, let c, let v): + return .permissions(name: n, rules: r, agents: agents, condition: c, native: v) + case .ignore(let n, let p, let u, _, let c, let v): + return .ignore(name: n, patterns: p, purpose: u, agents: agents, condition: c, native: v) + case .plugin(let n, let p, let s, let m, let select, let exclude, _, let c, let v): + return .plugin( + name: n, path: p, source: s, mode: m, select: select, exclude: exclude, agents: agents, + condition: c, native: v) + } + } } diff --git a/Sources/AgentsUpdates/UpdateReporting.swift b/Sources/AgentsUpdates/UpdateReporting.swift new file mode 100644 index 0000000..d5577b2 --- /dev/null +++ b/Sources/AgentsUpdates/UpdateReporting.swift @@ -0,0 +1,168 @@ +import AgentsCore +import AgentsInstructions +import AgentsSkills +import Components +import Foundation + +/// Public domain reports expose owned content. Shared native documents never enter these diffs. +enum UpdateReporting { + static func skills( + previous: ResolvedLedger, next: ResolvedLedger, resources: [String: URL], + changes: [AggregatedChange], store: StateStore, lockMissing: Bool, included: Bool + ) throws -> [UpdateResult] { + guard included else { return [] } + struct Item { + let name: String + var record: LockedSkill + let resource: String + } + func items(_ ledger: ResolvedLedger) throws -> [String: Item] { + var result: [String: Item] = [:] + for component in ledger.components.values + where component.kind == "skills" && !component.recipients.isEmpty { + guard let id = component.resources.first, let resource = ledger.resources[id] else { + continue + } + let source = try ledger.sourceIdentity(component.source, roots: store.ledgerRoots) + let producer = try ledger.sourceIdentity( + component.declaringSource, roots: store.ledgerRoots) + let identity = try ResolvedLedgerCodec.digest( + LedgerValue(object: [ + "producer": LedgerValue(producer), "source": .init(source), + "root": .init(component.root), + "group": component.group.map { .init($0) } ?? .init(), + "name": .init(PathSafety.sanitizeName(component.name)), + "path": .init(resource.path), + "conditions": .init(try ResolvedLedgerCodec.digest(component.conditions)), + ])) + let mode = + component.payload.object?["mode"]?.text.flatMap(InstallMode.init(rawValue:)) ?? .copy + var record = + result[identity]?.record + ?? LockedSkill( + source: source, revision: component.revision, + version: component.version, artifact: resource.artifact, path: resource.path, + hash: mode == .edit ? nil : resource.hash, installs: [:]) + for agent in component.recipients { record.installs[agent.rawValue] = mode } + result[identity] = Item( + name: PathSafety.sanitizeName(component.name), record: record, resource: id) + } + return result + } + let before = try items(previous) + let after = try items(next) + return try Set(before.keys).union(after.keys).sorted().map { identity in + let old = before[identity]?.record + let new = after[identity]?.record + let name = after[identity]?.name ?? before[identity]!.name + let membership = Set((old?.installs ?? [:]).keys).union((new?.installs ?? [:]).keys).sorted() + .compactMap { raw -> SkillMembershipChange? in + guard let agent = AgentID(rawValue: raw) else { return nil } + let path = SkillLifecycle.target(name: name, agent: agent, store: store).path + return SkillMembershipChange( + agent: agent, path: path, + before: old?.installs[raw].map { .installed(mode: $0) } ?? .absent, + after: new?.installs[raw].map { .installed(mode: $0) } ?? .absent) + } + let installed = (new?.installs ?? [:]).keys.sorted().compactMap { raw -> InstallResult? in + guard let agent = AgentID(rawValue: raw), let mode = new?.installs[raw] else { return nil } + return InstallResult( + skill: name, agent: agent, scope: store.scope, mode: mode, + path: SkillLifecycle.target(name: name, agent: agent, store: store).path) + } + let content = after[identity].flatMap { resources[$0.resource] } + var diffs: [SkillFileChange] = [] + for member in membership { + let oldFiles = try entries(URL(fileURLWithPath: member.path)) + var newFiles = + try new?.installs[member.agent.rawValue] == nil ? [:] : content.map(entries) ?? [:] + if let change = changes.first(where: { $0.url.path == member.path }), + let destination = change.afterLink + { + newFiles["."] = .symbolicLink( + FileTransaction.linkDestination( + destination, parent: URL(fileURLWithPath: member.path).deletingLastPathComponent(), + store: store)) + } + for path in Set(oldFiles.keys).union(newFiles.keys).sorted() + where oldFiles[path] != newFiles[path] { + diffs.append( + SkillFileChange( + path: path == "." + ? member.path : URL(fileURLWithPath: member.path).appendingPathComponent(path).path, + before: oldFiles[path], after: newFiles[path])) + } + } + let paths = Set(membership.map(\.path)) + let physical = changes.contains { + $0.deployment.route == "agents/skill@1" && paths.contains($0.url.path) && $0.changed + } + return UpdateResult( + skill: name, sourceIdentity: new?.source ?? old?.source ?? "", + changed: old != new || physical, + oldRevision: old?.revision, newRevision: new?.revision, oldVersion: old?.version, + newVersion: new?.version, + oldHash: old?.hash, newHash: new?.hash, lockMissing: lockMissing, membership: membership, + changes: diffs, installed: installed) + }.sorted { + ($0.skill, $0.sourceIdentity, $0.membership.first?.path ?? "") < ( + $1.skill, $1.sourceIdentity, $1.membership.first?.path ?? "" + ) + } + } + + static func instructions( + before: LockedInstructions, after: LockedInstructions, changes: [AggregatedChange], + lockMissing: Bool, included: Bool, store: StateStore, stateChanged: Bool + ) throws -> InstructionUpdateReport { + guard included else { + return InstructionUpdateReport( + sections: [], targets: [], changedPrompts: [], lockMissing: lockMissing, hasChanges: false) + } + func identity(_ section: LockedSection) -> String { section.source + ":" + section.name } + let sectionChanges = Set((before.sections + after.sections).map(identity)).sorted().compactMap { + id -> InstructionSectionChange? in + let old = before.sections.first { identity($0) == id } + let new = after.sections.first { identity($0) == id } + return old == new ? nil : InstructionSectionChange(before: old, after: new) + } + let targets = try changes.filter { !$0.native && $0.deployment.route != "agents/skill@1" }.map { + change in + let key = InstructionLocations.key(for: change.url, store: store) + let old = before.targets[key] + let drift = try old.map { old -> InstructionDrift in + guard let bytes = change.before else { return .missing } + if old.import != nil { + return try Instructions.detectDrift(in: bytes, lockedBlockHash: old.blockHash) + } + return ("sha256:" + FileHash.sha256Hex(data: bytes)) == old.blockHash ? .clean : .drifted + } + return InstructionTargetChange( + target: key, url: change.url, + before: try change.deployment.ownership == .importBlock + ? InstructionTargets.ownedImportBytes(change.before) : change.before, + after: try change.deployment.ownership == .importBlock + ? InstructionTargets.ownedImportBytes(change.after) : change.after, + beforeAgents: old?.agents, + afterAgents: change.after == nil ? [] : change.deployment.recipients, + drift: drift, + foreign: change.deployment.ownership != .importBlock + && change.before.map { $0 != change.after && !Instructions.isOwned($0) } ?? false) + } + let prompts = Set(before.chatgpt.keys).union(after.chatgpt.keys).filter { + let old = before.chatgpt[$0] + let new = after.chatgpt[$0] + return old?.append != new?.append + || old?.sections.map { identity($0) + $0.hash } + != new?.sections.map { identity($0) + $0.hash } + }.sorted() + return InstructionUpdateReport( + sections: sectionChanges, targets: targets, changedPrompts: prompts, + lockMissing: lockMissing, + hasChanges: stateChanged || before != after || targets.contains(where: \.changed)) + } + + private static func entries(_ root: URL) throws -> [String: SkillFileEntry] { + try SkillLifecycle.entries(root) + } +} diff --git a/Sources/AgentsUpdates/UpdateRequest.swift b/Sources/AgentsUpdates/UpdateRequest.swift new file mode 100644 index 0000000..438765a --- /dev/null +++ b/Sources/AgentsUpdates/UpdateRequest.swift @@ -0,0 +1,37 @@ +import AgentsCore +import AgentsManifest + +public enum UpdateOperation: Sendable { + case update + case restore + case edit([ManifestEdit]) + case declaration(Declaration) + case remove +} + +/// Selection constrains application and protects the recorded semantics of every other domain. +public struct UpdateRequest: Sendable { + package var automaticSkill: (source: String, name: String)? + public var operation: UpdateOperation + public var kinds: Set? + public var names: [String] + /// Recipient removal for skills and native components; replacement recipients for instruction removal. + public var agents: [AgentID]? + public var replace: Bool + public var expectedDeclarationDigest: String? + public var changingAccess: Bool + + public init( + operation: UpdateOperation = .update, kinds: Set? = nil, + names: [String] = [], agents: [AgentID]? = nil, replace: Bool = false, + changingAccess: Bool = false, expectedDeclarationDigest: String? = nil + ) { + self.operation = operation + self.kinds = kinds + self.names = names + self.agents = agents + self.replace = replace + self.changingAccess = changingAccess + self.expectedDeclarationDigest = expectedDeclarationDigest + } +} diff --git a/Sources/Components/ArtifactAggregation.swift b/Sources/Components/ArtifactAggregation.swift new file mode 100644 index 0000000..ccf1627 --- /dev/null +++ b/Sources/Components/ArtifactAggregation.swift @@ -0,0 +1,558 @@ +import AgentsCore +import AgentsInstructions +import Foundation +import NativeDocuments + +package struct AggregatedChange { + package let deployment: LedgerDeployment + package let url: URL + package let before: Data? + package let after: Data? + package let changed: Bool + package let native: Bool + package var afterLink: URL? = nil + package var accessChange: PrivateAccessChange? = nil + package var privateMaterialization = false + package var requiredBindings: [String] = [] + package var symbolicBefore: LedgerValue? = nil + package var symbolicAfter: LedgerValue? = nil +} + +/// One prepared physical replacement owns all logical contributions at that destination. +package final class ArtifactAggregation: PreparedEvidence { + package private(set) var ledger: ResolvedLedger + package private(set) var changes: [AggregatedChange] = [] + package private(set) var fingerprints: [String] = [] + private let store: StateStore + private let resources: [String: URL] + private let replace: Bool + private var unownedInstructions: [String] = [] + private var targets: [String: TargetPrecondition] = [:] + private var writes: [String: FileTransaction.Source] = [:] + private var deletes = Set() + private var capsules: [String: URL] = [:] + private var skillContent: [String: (String, [String: Bool])] = [:] + private var privateWrites: + [(PreparedPrivateMaterialization, Set, (RuntimeBindingValues) throws -> Data)] = [] + private var resourceEvidence: [TargetPrecondition] = [] + + package init( + ledger: ResolvedLedger, previous: ResolvedLedger, artifacts: [ReplayedArtifact], + resources: [String: URL], workspace: URL, store: StateStore, replace: Bool, + changingAccess: Bool, + kinds: Set? = nil + ) throws { + self.ledger = ledger + self.store = store + self.resources = resources + self.replace = replace + for (id, file) in resources where ledger.resources[id]?.kind != .liveEdit { + resourceEvidence.append(try TargetPrecondition(file)) + } + func selected(_ deployment: LedgerDeployment, in ledger: ResolvedLedger) -> Bool { + kinds == nil + || deployment.owners.contains { + ledger.components[$0].flatMap { DeclaredComponentKind(rawValue: $0.kind) }.map { + kinds!.contains($0) + } ?? false + } + } + for (id, source) in resources where ledger.resources[id]?.kind != .liveEdit { + let resource = ledger.resources[id]! + let destination = try resourceDestination(id) + if FileManager.default.fileExists(atPath: destination.path) { + resourceEvidence.append(try TargetPrecondition(destination)) + } + if resource.kind == .embedded || resource.kind == .artifact { + let capsule = workspace.appendingPathComponent( + "capsule-" + FileHash.sha256Hex(data: Data(id.utf8))) + try FileSystem.createDirectory(at: capsule) + if resource.support.isEmpty { + try FileManager.default.copyItem( + at: source, to: capsule.appendingPathComponent("payload")) + } else { + var sourceRoot = source + if resource.path != "." { + for _ in resource.path.split(separator: "/") { sourceRoot.deleteLastPathComponent() } + } + let captured = try LedgerResources.capture( + source, embed: true, limits: .standard, sourceRoot: sourceRoot) + guard captured.hash == resource.hash else { + throw CoreError.invalidState("retention input changed") + } + var embedded = resource + embedded.kind = .embedded + embedded.entries = captured.entries + embedded.support = captured.support + try LedgerResources.materialize(embedded, objects: captured.objects, at: capsule) + } + capsules[id] = capsule + resourceEvidence.append(try TargetPrecondition(capsule)) + } + } + let roots = store.ledgerRoots + let artifacts = Dictionary(uniqueKeysWithValues: artifacts.map { ($0.name, $0) }) + let previousByPath = try Dictionary( + grouping: previous.deployments.filter { selected($0, in: previous) } + ) { + InstructionLocations.physical(try $0.target.resolve(roots: roots)).path + } + var byPath = try Dictionary(grouping: ledger.deployments.filter { selected($0, in: ledger) }) { + InstructionLocations.physical(try $0.target.resolve(roots: roots)).path + } + var native: [String: [(LockedLowering, NativeMCPContribution, MaterializationTarget)]] = [:] + for lowering in ledger.lowerings + where lowering.format.hasSuffix("-mcp@1") && (kinds == nil || kinds!.contains(.mcpServer)) { + let contribution = try MCPLayoutV1.contribution(lowering, ledger: ledger) + let route = try DeploymentConstruction.route(contribution) + let target = try store.nativeTarget(for: route) + native[target.url.path, default: []].append((lowering, contribution, target)) + } + // Removed native regions still participate in the same physical aggregation. + for lowering in previous.lowerings + where lowering.format.hasSuffix("-mcp@1") && (kinds == nil || kinds!.contains(.mcpServer)) { + let c = try MCPLayoutV1.contribution(lowering, ledger: previous) + let target = try store.nativeTarget(for: DeploymentConstruction.route(c)) + if native[target.url.path] == nil { native[target.url.path] = [] } + } + for path in native.keys.sorted() { + try prepareNative( + path: path, contributions: native[path]!, previous: previous, + changingAccess: changingAccess) + byPath.removeValue(forKey: path) + } + for path in Set(byPath.keys).union(previousByPath.keys).sorted() where native[path] == nil { + let url = URL(fileURLWithPath: path) + let capture = try TargetPrecondition(url).capturingPublicationAccess() + targets[path] = capture + let old = previousByPath[path] ?? [] + let next = byPath[path] ?? [] + let sharedImport = (old + next).contains { $0.ownership == .importBlock } + fingerprints.append(try capture.displayEvidence(includeContent: !sharedImport)) + if sharedImport { + let observed = try InstructionTargets.ownedImportBytes( + TargetPrecondition.readingFile(url).bytes) + fingerprints.append(try ResolvedLedgerCodec.digest([path: observed])) + } + if next.isEmpty { + guard let deployment = old.first else { continue } + if deployment.route == "agents/skill@1" { + deletes.insert(path) + changes.append( + .init( + deployment: deployment, url: url, before: nil, after: nil, + changed: FileManager.default.fileExists(atPath: path), native: false)) + } else { + let before = try TargetPrecondition.readingFile(url).bytes + let after = try InstructionCompatibility.obsolete(deployment, before: before) + if before != after { + if let after { writes[path] = .data(after) } else { deletes.insert(path) } + } + changes.append( + .init( + deployment: deployment, url: url, before: before, after: after, + changed: before != after, native: false)) + } + continue + } + let entries = try next.map { + deployment -> (LedgerDeployment, ReplayedArtifact, LockedLowering) in + guard + let lowering = ledger.lowerings.first(where: { $0.deployments.contains(deployment.id) }), + let name = lowering.artifacts.first?.name, let artifact = artifacts[name] + else { throw CoreError.invalidState("deployment has no rendered artifact") } + return (deployment, artifact, lowering) + } + let first = entries[0] + guard + try entries.allSatisfy({ + try $0.1.digest(limits: .standard).hash == first.1.digest(limits: .standard).hash + && $0.1.kind == first.1.kind + && $0.2.layout.object?["mode"] == first.2.layout.object?["mode"] + }) + else { + throw CoreError.invalidState("incompatible contributions share a physical target") + } + let deployment = first.0 + let artifact = first.1 + if deployment.route == "agents/skill@1" { + if let prior = old.first, + previous.components[prior.owners[0]]?.payload.object?["mode"]?.text != "edit", + url.resolvingSymlinksInPath().path != url.path + { + resourceEvidence.append(try TargetPrecondition(url.resolvingSymlinksInPath())) + } + guard + !old.isEmpty + || !FileManager.default.fileExists(atPath: path) + else { + throw CoreError.invalidSkill( + "skill '\(ledger.components[deployment.owners[0]]!.name)' in \(store.scope.rawValue) scope has unmanaged content at \(path); move or remove it first" + ) + } + let mode = first.2.layout.object?["mode"]?.text ?? "copy" + let source: FileTransaction.Source + if let location = artifact.location { + source = .link(try location.resolve(roots: roots)) + } else if mode == InstallMode.link.rawValue { + source = .link(try resourceDestination(first.2.resources[0])) + } else if let tree = artifact.tree { + if let real = PathSafety.realPath(tree.path), + let children = FileManager.default.enumerator( + at: tree, includingPropertiesForKeys: [.isSymbolicLinkKey]) + { + for case let child as URL in children + where try child.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true { + guard try PathSafety.linkStaysInside(child, root: real) else { + throw CoreError.unsafePath("copied skill link escapes its installed subtree") + } + } + } + source = .copy(tree) + } else { + throw CoreError.invalidState("skill artifact has no content") + } + let changed: Bool + switch source { + case .link(let destination): + let existing = try? FileManager.default.destinationOfSymbolicLink(atPath: path) + let current = existing.map { + URL(fileURLWithPath: $0, relativeTo: url.deletingLastPathComponent()) + .standardizedFileURL.path + } + changed = current != destination.standardizedFileURL.path + case .copy(let tree): + let hash = try FileHash.folderHash(tree) + let flags = try FileHash.executableFlags(tree) + let type = + try? FileManager.default.attributesOfItem(atPath: url.path)[.type] as? FileAttributeType + changed = + type != .typeDirectory || (try? FileHash.folderHash(url)) != hash + || (try? FileHash.executableFlags(url)) != flags + default: changed = true + } + if let tree = artifact.tree, let id = first.2.resources.first, + let resource = ledger.resources[id] + { + skillContent[path] = (resource.hash, try FileHash.executableFlags(tree)) + } + if changed { writes[path] = source } + changes.append( + .init( + deployment: deployment, url: url, before: nil, after: nil, + changed: changed, native: false, + afterLink: { if case .link(let url) = source { url } else { nil } }())) + } else { + let before = try TargetPrecondition.readingFile(url).bytes + var after = artifact.bytes + if deployment.ownership == .importBlock { + guard let path = ClaudeInstructionPath(rawValue: deployment.target.path) else { + throw CoreError.invalidState("invalid locked import location") + } + after = + before == nil && !old.isEmpty + ? nil : try InstructionTargets.importBlock(in: before ?? Data(), at: path).bytes + } else if let before, before != after, !Instructions.isOwned(before), !replace { + unownedInstructions.append(InstructionLocations.key(for: url, store: store)) + } + if before != after { + if let after { writes[path] = .data(after) } else { deletes.insert(path) } + } + changes.append( + .init( + deployment: deployment, url: url, before: before, after: after, + changed: before != after, native: false)) + } + } + try validate() + } + + private func resourceDestination(_ id: String, in selected: ResolvedLedger? = nil) throws -> URL { + let ledger = selected ?? self.ledger + guard let resource = ledger.resources[id] else { + throw CoreError.invalidState("missing deployment resource") + } + if let location = resource.location { return try location.resolve(roots: store.ledgerRoots) } + if let root = try gitDestination(resource, ledger: ledger) { + return root.appendingPathComponent(resource.path) + } + let base = store.cacheDirectory.appendingPathComponent( + "artifact-content/" + String(id.dropFirst(7))) + return base.appendingPathComponent(resource.support.isEmpty ? "payload" : resource.path) + } + + private func gitDestination(_ resource: LedgerResource, ledger: ResolvedLedger) throws -> URL? { + guard resource.kind == .git else { return nil } + var sourceID = resource.source + while let parent = ledger.sources[sourceID]?.container { sourceID = parent } + guard let source = ledger.sources[sourceID] else { + throw CoreError.invalidState("missing resource source") + } + return SourceCache(store: store).materializedURL( + sourceID: try ledger.sourceIdentity(sourceID, roots: store.ledgerRoots), + revision: source.revision) + } + + private func prepareNative( + path: String, contributions: [(LockedLowering, NativeMCPContribution, MaterializationTarget)], + previous: ResolvedLedger, changingAccess: Bool + ) throws { + let url = URL(fileURLWithPath: path) + let capture = try TargetPrecondition.readingFile(url) + targets[path] = try capture.evidence.capturingPublicationAccess() + fingerprints.append(try capture.evidence.displayEvidence(includeContent: false)) + let old = try previous.lowerings.filter { $0.format.hasSuffix("-mcp@1") }.compactMap { + lowering -> NativeMCPContribution? in + let c = try MCPLayoutV1.contribution(lowering, ledger: previous) + return try store.nativeTarget(for: DeploymentConstruction.route(c)).url.path == path ? c : nil + } + guard let descriptor = contributions.first?.1.descriptor ?? old.first?.descriptor else { + return + } + let document = try NativeDocument( + bytes: capture.bytes ?? Data("{}\n".utf8), + format: descriptor.documentFormat, + budget: NativeDocumentBudget( + limits: .init( + storage: LedgerLimits.standard.resourceBytes, work: LedgerLimits.standard.encodedBytes, + nodes: LedgerLimits.standard.nodes, depth: LedgerLimits.standard.depth, + uninterruptedBytes: LedgerLimits.standard.keyBytes))) + var desired: [String: NativeMCPContribution] = [:] + for (_, c, _) in contributions { + if let prior = desired[c.name], + prior.value != c.value || prior.bindings != c.bindings + || prior.resourcePlacements != c.resourcePlacements + { + throw CoreError.invalidState("conflicting native region contributions") + } + desired[c.name] = c + } + let oldByName = Dictionary(old.map { ($0.name, $0) }, uniquingKeysWith: { first, _ in first }) + let names = Set(desired.keys).union(oldByName.keys).sorted() + let sensitive = (old + contributions.map(\.1)).contains { + $0.bindings.contains { !$0.reference } + } + let target: MaterializationTarget + if let provided = contributions.first?.2 { + target = provided + } else { + target = try store.nativeTarget(for: DeploymentConstruction.route(old[0])) + } + let privatePlan = + try sensitive + ? store.preparePrivateMaterialization( + target, changingAccess: changingAccess, + requiringReceiptForExistingTarget: old.contains { $0.bindings.contains { !$0.reference } }) + : nil + var expected: [String: NativeExpectedRegion] = [:] + for name in names { + let region = try descriptor.region( + server: name, + nativeProjectKey: descriptor.request.scope == .local + ? try store.nativeTarget(for: .claudeMCPProject).url.deletingLastPathComponent().path + : nil) + if let observation = try document.read(region) { + guard let prior = oldByName[name] else { + throw NativeDocumentError.ownershipMismatch(region) + } + if !prior.bindings.contains(where: { !$0.reference }) { + guard observation.value == (try nativeValue(prior, values: nil, ledger: previous)) else { + throw NativeDocumentError.ownershipMismatch(region) + } + } + expected[name] = .owned(observation) + } else { + expected[name] = .absent + } + } + func edits(_ values: RuntimeBindingValues?) throws -> [NativeRegionEdit] { + try names.map { name in + let region = try descriptor.region( + server: name, + nativeProjectKey: descriptor.request.scope == .local + ? try self.store.nativeTarget(for: .claudeMCPProject).url.deletingLastPathComponent() + .path : nil) + if let c = desired[name] { + return .put( + region: region, expected: expected[name]!, + value: try self.nativeValue(c, values: values, ledger: self.ledger)) + } + return .remove(region: region, expected: expected[name]!) + } + } + // Symbolic placeholders never leave the private plan. A staged literal render consumes + // all regions together after Core has verified private staging and resolved bindings. + let preview = try document.prepare(edits(nil)) + let changed = preview.bytes != (capture.bytes ?? Data("{}\n".utf8)) + if let privatePlan { + let bindings = Set( + contributions.flatMap { + $0.1.bindings.filter { !$0.reference }.map { placement in + switch placement.binding { + case .environment(let n), .secret(let n): n + case .literal: "" + } + } + }) + privateWrites.append( + (privatePlan, bindings, { values in try document.prepare(edits(values)).bytes })) + } else if changed { + writes[path] = .data(preview.bytes) + } + for (lowering, contribution, _) in contributions { + let id = lowering.id + let deployment = LedgerDeployment( + id: id, + target: .init( + kind: .registered, root: String(target.path.split(separator: "/")[0]), + path: url.lastPathComponent), + route: lowering.format, owners: [contribution.component], + recipients: contribution.recipients, + ownership: .ownedValues, expectedHash: try ResolvedLedgerCodec.digest(contribution.value), + created: previous.deployments.first(where: { $0.id == id })?.created + ?? (capture.bytes == nil)) + ledger.deployments.removeAll { $0.id == id } + ledger.deployments.append(deployment) + if let i = ledger.lowerings.firstIndex(where: { $0.id == lowering.id }) { + ledger.lowerings[i].deployments = [id] + } + changes.append( + .init( + deployment: deployment, url: url, before: nil, after: nil, changed: changed || sensitive, + native: true, accessChange: privatePlan?.accessChange, privateMaterialization: sensitive, + requiredBindings: contribution.bindings.filter { !$0.reference }.map { + switch $0.binding { + case .environment(let name), .secret(let name): name + case .literal: "" + } + }.sorted(), symbolicBefore: oldByName[contribution.name]?.value, + symbolicAfter: contribution.value)) + } + for name in Set(oldByName.keys).subtracting(desired.keys).sorted() { + let old = oldByName[name]! + if let prior = previous.deployments.first(where: { + $0.ownership == .ownedValues && $0.owners.contains(old.component) + && (try? $0.target.resolve(roots: store.ledgerRoots).path) == path + }) { + let removed: Bool + if case .absent = expected[name] { removed = false } else { removed = true } + changes.append( + .init( + deployment: prior, url: url, before: nil, after: nil, changed: removed, + native: true, accessChange: privatePlan?.accessChange, + privateMaterialization: sensitive, + symbolicBefore: old.value)) + } + } + } + + private func nativeValue( + _ contribution: NativeMCPContribution, values: RuntimeBindingValues?, ledger: ResolvedLedger + ) throws -> NativeValue { + func convert(_ value: LedgerValue, path: [MCPValueStep]) throws -> NativeValue { + if let resource = contribution.resourcePlacements.first(where: { $0.path == path }), + ledger.resources[resource.resource] != nil + { + let destination = try resourceDestination(resource.resource, in: ledger) + return .string(destination.path) + } + switch value.kind { + case .environment, .secret: + guard let name = value.text else { throw CoreError.invalidState("missing binding name") } + if let values { + guard let text = String(data: try values.value(for: name), encoding: .utf8) else { + throw CoreError.invalidState("runtime binding is not UTF8") + } + return .string(text) + } + return .string("") + case .string, .literal: return .string(value.text!) + case .integer: return .integer(value.integer!) + case .decimal: return .decimal(value.text!) + case .boolean: return .boolean(value.boolean!) + case .null: return .null + case .array: + return .array( + try value.array!.enumerated().map { + try convert($0.element, path: path + [.index($0.offset)]) + }) + case .object: + return .object( + try value.object!.mapValuesWithKey { try convert($1, path: path + [.key($0)]) }) + } + } + return try convert(contribution.value, path: []) + } + + package func validate(excludingTargets excluded: Set = []) throws { + let paths = targets.keys.sorted().map { URL(fileURLWithPath: $0) } + for (index, path) in paths.enumerated() { + if paths.prefix(index).contains(where: { + PathSafety.isContained(path, in: $0) || PathSafety.isContained($0, in: path) + }) { + throw CoreError.invalidState("overlapping deployment targets") + } + } + for (path, evidence) in targets where !excluded.contains(path) { try evidence.validate() } + for evidence in resourceEvidence + where !excluded.contains(where: { + PathSafety.isContained(evidence.url, in: URL(fileURLWithPath: $0)) + }) { try evidence.validate() } + } + + package func requireOwnership() throws { + guard replace || unownedInstructions.isEmpty else { + throw InstructionError.unownedTargets(unownedInstructions.sorted()) + } + } + + package func stage(transaction: FileTransaction, provider: any RuntimeBindingProvider) throws { + var staged = Set() + for (id, source) in resources.sorted(by: { $0.key < $1.key }) { + guard let resource = ledger.resources[id], resource.kind != .liveEdit else { continue } + let destination = try resourceDestination(id) + let git = try gitDestination(resource, ledger: ledger) + let container = + git + ?? store.cacheDirectory.appendingPathComponent( + "artifact-content/" + String(id.dropFirst(7))) + guard staged.insert(container.path).inserted else { continue } + if FileManager.default.fileExists(atPath: container.path) { + let actual = try LedgerResources.capture(destination, embed: false, limits: .standard) + guard actual.hash == resource.hash else { + throw CoreError.invalidState("retained resource mismatch") + } + } else if git != nil { + var root = source + if resource.path != "." { + for _ in resource.path.split(separator: "/") { root.deleteLastPathComponent() } + } + try transaction.replace(container, with: .copy(root)) + } else if let capsule = capsules[id] { + try transaction.replace(container, with: .copy(capsule)) + } else { + throw CoreError.invalidState("missing retained resource capsule") + } + } + for path in writes.keys.sorted() { + try transaction.replace( + URL(fileURLWithPath: path), with: writes[path]!, + expectedHash: { if case .link = writes[path]! { nil } else { skillContent[path]?.0 } }(), + executableFlags: { if case .link = writes[path]! { nil } else { skillContent[path]?.1 } }(), + expecting: targets[path]) + } + for path in deletes.sorted() { + try transaction.delete(URL(fileURLWithPath: path), expecting: targets[path]) + } + for (prepared, bindings, render) in privateWrites { + try transaction.replacePrivate( + prepared, bindings: bindings, provider: provider, render: render) + } + } +} + +extension Dictionary { + fileprivate func mapValuesWithKey(_ transform: (Key, Value) throws -> T) rethrows -> [Key: T] { + try [Key: T](uniqueKeysWithValues: map { (key, value) in (key, try transform(key, value)) }) + } +} diff --git a/Sources/Components/ComponentFields.swift b/Sources/Components/ComponentFields.swift index 0720e7f..1328299 100644 --- a/Sources/Components/ComponentFields.swift +++ b/Sources/Components/ComponentFields.swift @@ -1,7 +1,7 @@ import AgentsCore extension ComponentDeclaration { - var name: String? { + package var name: String? { switch self { case .skills, .instructions: nil case .mcpServer(let name, _, _, _, _), .hook(let name, _, _, _, _, _, _, _), diff --git a/Sources/Components/DeploymentConstruction.swift b/Sources/Components/DeploymentConstruction.swift new file mode 100644 index 0000000..888a07b --- /dev/null +++ b/Sources/Components/DeploymentConstruction.swift @@ -0,0 +1,208 @@ +import AgentsCore +import AgentsInstructions +import Foundation + +package enum DeploymentConstruction { + package struct Result { + package let ledger: ResolvedLedger + package let inputs: [TargetPrecondition] + } + package static func routes(_ ledger: ResolvedLedger) throws -> Set { + var result = Set() + for lowering in ledger.lowerings where lowering.format.hasSuffix("-mcp@1") { + let contribution = try MCPLayoutV1.contribution(lowering, ledger: ledger) + result.insert(try route(contribution)) + } + return result + } + + package static func route(_ contribution: NativeMCPContribution) throws -> NativeTargetRoute { + guard contribution.descriptor.request.surface == .claudeCode else { + throw NativeAdapterIssue( + request: contribution.descriptor.request, component: contribution.name, field: ["route"], + reason: .integrationRequired, detail: "Core registered route is pending integration") + } + switch contribution.descriptor.request.scope { + case .project: return .claudeMCPProject + case .local: return .claudeMCPLocal + case .user: return .claudeMCPUser + } + } + + package static func lowerNative( + linked: LinkedComponents, frozen: LedgerFreeze.Result, scope: InstallScope, + platform: DeclarationPlatform + ) throws -> ResolvedLedger { + var ledger = frozen.ledger + for component in linked.components { + guard case .declaration = component.payload else { continue } + guard component.key.kind == .mcpServer else { + if !component.recipients.isEmpty { + throw CoreError.invalidState( + "\(component.key.kind.rawValue)/\(component.key.name): production adapter integration is pending" + ) + } + continue + } + for agent in component.recipients.sorted(by: { $0.rawValue < $1.rawValue }) { + let surface: NativeClientSurface + switch agent { + case .claudeCode: surface = .claudeCode + case .codex: surface = .codexCLI + case .cursor: surface = .cursorEditor + case .geminiCLI: surface = .geminiCLI + case .opencode: surface = .openCodeCLI + } + var contribution = try NativeMCPLowering.lower( + component, frozen: frozen, + request: .init(surface: surface, scope: scope == .user ? .user : .project)) + if scope == .project, surface == .claudeCode, + contribution.bindings.contains(where: { !$0.reference }) + { + contribution = try NativeMCPLowering.lower( + component, frozen: frozen, request: .init(surface: surface, scope: .local)) + } + let id = "mcp:" + String(component.origins[0].occurrence) + ":" + agent.rawValue + ledger.lowerings.append(contribution.lowering(id: id, artifact: id, platform: platform)) + } + } + return ledger + } + + package static func complete( + _ native: ResolvedLedger, linked: LinkedComponents, store: StateStore, + previous: ResolvedLedger, platform: DeclarationPlatform + ) throws -> Result { + var ledger = native + var inputs: [TargetPrecondition] = [] + let owners = Dictionary(uniqueKeysWithValues: ledger.occurrences.map { ($0.id, $0.component) }) + func owner(_ component: LinkedComponent) -> String { owners[component.origins[0].occurrence]! } + func add( + id: String, format: String, inputs: [String], resources: [String], location: LedgerLocation?, + agents: [AgentID], hash: String, layout: [String: LedgerValue], + ownership: LedgerDeployment.Ownership = .generated, created: Bool = false, + reference: String? = nil + ) { + let deployment = location.map { location in + LedgerDeployment( + id: id, target: location, route: format, owners: inputs, recipients: agents, + ownership: ownership, expectedHash: hash, created: created, + importReference: reference, headingOffset: ownership == .generated ? 0 : nil) + } + if let deployment { ledger.deployments.append(deployment) } + ledger.lowerings.append( + .init( + id: id, format: format, inputs: inputs, resources: resources, + deployments: deployment == nil ? [] : [id], layout: .init(object: layout), + platform: platform.rawValue, artifacts: [])) + } + for component in linked.components { + guard case .skill(_, _, _) = component.payload else { continue } + let key = owner(component) + let record = ledger.components[key]! + let resource = ledger.resources[record.resources[0]]! + for agent in component.recipients.sorted(by: { $0.rawValue < $1.rawValue }) { + let id = "skill:" + String(component.origins[0].occurrence) + ":" + agent.rawValue + add( + id: id, format: "agents/skill@1", inputs: [key], resources: record.resources, + location: .init( + kind: .registered, root: "skills-" + agent.rawValue, + path: PathSafety.sanitizeName(component.key.name)), + agents: [agent], hash: resource.hash, + layout: ["name": .init(id), "mode": record.payload.object!["mode"]!]) + } + } + let instructions = linked.components.filter { + if case .instruction = $0.payload { true } else { false } + } + let old = try previous.domainProjection(roots: store.ledgerRoots).instructions + var merged: [String: (LockedTarget, [String], [String])] = [:] + for agent in AgentID.allCases { + let selected = instructions.filter { $0.recipients.contains(agent) } + let sections = selected.compactMap { component in + if case .instruction(let unit, _, _) = component.payload { return unit.section } + return nil + } + guard !sections.isEmpty else { continue } + let planned = try InstructionTargets(store: store).plan( + sections: sections, agents: [agent], previous: old) + for (id, source) in ledger.sources where source.kind == .local && source.location != nil { + let identity = try ledger.sourceIdentity(id, roots: store.ledgerRoots) + let roots = ledger.sourceUses.filter { $0.source == id }.map(\.root) + for root in roots.isEmpty ? ["."] : roots { + try InstructionTargets.validateSourceDirectories( + planned.changes, + sources: [identity: LockedSource(kind: .local, path: root == "." ? nil : root)]) + } + } + inputs += try planned.expectations.values.map { try $0.capturingPublicationAccess() } + let targets = planned.targets + for (path, target) in targets { + let selected = selected.filter { component in + if target.import != nil { return true } + if case .instruction(let unit, _, _) = component.payload { + let directory = store.scope == .project ? unit.section.directory : "" + return store.scope == .user || (path as NSString).deletingLastPathComponent == directory + || (directory.isEmpty && !(path.contains("/"))) + } + return false + } + let owners = selected.map(owner) + let resources = owners.map { ledger.components[$0]!.resources[0] } + if var existing = merged[path] { + guard existing.0.blockHash == target.blockHash, existing.1 == owners else { + throw CoreError.invalidState( + "instruction recipients require incompatible shared output: \(path)") + } + existing.0.agents += target.agents + merged[path] = existing + } else { + merged[path] = (target, owners, resources) + } + } + } + for path in merged.keys.sorted() { + let (target, owners, resources) = merged[path]! + let file = try InstructionLocations.file(for: path, store: store) + let location: LedgerLocation + if store.scope == .project { + location = .init(kind: .registered, root: "project", path: path) + } else if let agent = target.agents.first { + location = .init( + kind: .registered, root: "instructions-" + agent.rawValue, path: file.lastPathComponent) + } else { + throw CoreError.invalidState("missing instruction recipient") + } + let id = "instructions:" + path + let format = target.import == nil ? "agents/instructions@1" : "agents/claude-import@1" + add( + id: id, format: format, inputs: owners, resources: target.import == nil ? resources : [], + location: location, agents: Array(Set(target.agents)).sorted { $0.rawValue < $1.rawValue }, + hash: target.blockHash, + layout: [ + "name": .init(target.import == nil ? id : path), "headingOffset": .init(integer: 0), + ], + ownership: target.import == nil ? .generated : .importBlock, + created: target.created, reference: target.import) + } + var prompts: [String: [LinkedComponent]] = [:] + for component in instructions where component.chatGPT { + if case .instruction(_, let prompt?, _) = component.payload { + prompts[prompt, default: []].append(component) + } + } + for name in prompts.keys.sorted() { + let selected = prompts[name]! + let owners = selected.map(owner) + var resources = owners.map { ledger.components[$0]!.resources[0] } + if let append = ledger.components[owners[0]]!.resources.dropFirst().first { + resources.append(append) + } + add( + id: "prompt:" + name, format: "agents/chatgpt@1", inputs: owners, resources: resources, + location: nil, agents: [], hash: "sha256:" + String(repeating: "0", count: 64), + layout: ["name": .init("prompt:" + name), "sectionCount": .init(integer: selected.count)]) + } + return Result(ledger: ledger, inputs: inputs) + } +} diff --git a/Sources/Components/LedgerImpact.swift b/Sources/Components/LedgerImpact.swift new file mode 100644 index 0000000..ac6ef1e --- /dev/null +++ b/Sources/Components/LedgerImpact.swift @@ -0,0 +1,186 @@ +import AgentsCore +import Foundation + +/// Selection and protection are projections of the recorded graph, never of mutable producers. +package struct LedgerImpact { + package let pins: [String: SourceRevision] + package let directPins: [ComponentKey: SourceRevision] + + package init( + ledger: ResolvedLedger, roots: [String: URL], kinds: Set, + names: Set, updating: Bool + ) throws { + func selected(_ c: LedgerComponent) -> Bool { + kinds.contains(DeclaredComponentKind(rawValue: c.kind)!) + && (names.isEmpty + || names.contains(c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name)) + } + var affected = Set() + if updating { + for occurrence in ledger.occurrences { + if let c = ledger.components[occurrence.component], selected(c) { + affected.formUnion(occurrence.dependencies) + affected.insert(c.source) + } + } + } + var pins: [String: SourceRevision] = [:] + for group in ledger.groups where !affected.contains(group.source) { + let source = ledger.sources[group.source]! + if SourceCache.isObjectID(source.revision) { + pins[try ledger.sourceIdentity(group.source, roots: roots)] = SourceRevision( + revision: source.revision, version: source.version) + } + } + var direct: [ComponentKey: SourceRevision] = [:] + for c in ledger.components.values where !updating || !selected(c) { + guard c.group == nil, let revision = c.revision else { continue } + direct[ + ComponentKey( + source: try ledger.sourceIdentity(c.declaringSource, roots: roots), root: c.root, + group: nil, kind: DeclaredComponentKind(rawValue: c.kind)!, name: c.name + )] = SourceRevision(revision: revision, version: c.version) + } + self.pins = pins + directPins = direct + } + + package static func requireProtected( + previous: ResolvedLedger, next: ResolvedLedger, kinds: Set, + names: Set = [], roots: [String: URL] + ) throws { + struct Projection: Encodable { + let component: LedgerComponent + let sources: [[LedgerSource]] + let resources: [LedgerResource] + } + func streams(_ ledger: ResolvedLedger) throws -> [String: [String]] { + var result: [String: [String]] = [:] + for occurrence in ledger.occurrences { + guard var c = ledger.components[occurrence.component], + !kinds.contains(DeclaredComponentKind(rawValue: c.kind)!) + || (!names.isEmpty + && !names.contains(c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name)) + else { continue } + func sourceChain(_ id: String) throws -> [LedgerSource] { + var result: [LedgerSource] = [] + var next: String? = id + while let current = next, var source = ledger.sources[current] { + next = source.container + source.container = nil + source.version = nil + if source.kind == .local, !SourceCache.isObjectID(source.revision) { + source.revision = "local" + } + if let transport = source.transport { + source.transport = try SourceDeclaration(kind: source.kind, location: transport) + .identity(environment: RuntimeEnvironment(environment: [:])) + } + if let location = source.location { + source.location = .init( + kind: .absolute, path: try location.resolve(roots: roots).path) + } + result.append(source) + } + return result + } + let sources = + try [sourceChain(c.source), sourceChain(c.declaringSource)] + + c.resources.map { try sourceChain(ledger.resources[$0]!.source) } + let resources = c.resources.enumerated().map { index, id in + var resource = ledger.resources[id]! + resource.source = "resource:" + String(index) + if resource.kind == .liveEdit { resource.hash = "live" } + return resource + } + if var payload = c.payload.object { + if let agents = payload["agents"]?.array { + payload["agents"] = .init(array: agents.sorted { ($0.text ?? "") < ($1.text ?? "") }) + } + if var condition = payload["condition"]?.object { + for key in ["agents", "scopes", "platforms"] { + if let values = condition[key]?.array { + condition[key] = .init(array: values.sorted { ($0.text ?? "") < ($1.text ?? "") }) + } + } + payload["condition"] = .init(object: condition) + } + if c.kind == "skills", payload["mode"]?.text == "edit" { payload["description"] = nil } + c.payload = .init(object: payload) + } + for index in c.conditions.indices { + c.conditions[index].agents?.sort { $0.rawValue < $1.rawValue } + c.conditions[index].scopes?.sort { $0.rawValue < $1.rawValue } + c.conditions[index].platforms?.sort() + } + if ["hook", "permissions"].contains(c.kind) { + try c.conditions.sort { + try ResolvedLedgerCodec.digest($0) < ResolvedLedgerCodec.digest($1) + } + c.conditions = c.conditions.reduce(into: []) { result, condition in + if !result.contains(condition) { result.append(condition) } + } + } + if c.kind == "skills" { c.name = PathSafety.sanitizeName(c.name) } + c.source = "input" + c.declaringSource = "producer" + c.resources = resources.map(\.hash) + let digest = try ResolvedLedgerCodec.digest( + Projection(component: c, sources: sources, resources: resources)) + let destinations: [String] + if c.kind == DeclaredComponentKind.instructions.rawValue { + destinations = + c.recipients.map(\.rawValue) + + (c.chatGPT ? ["prompt:" + (c.payload.object?["prompt"]?.text ?? "")] : []) + } else if ["hook", "permissions", "ignore", "plugin"].contains(c.kind) { + destinations = c.recipients.map { c.kind + ":" + $0.rawValue } + } else { + destinations = [c.kind + ":" + c.root + ":" + (c.group ?? "") + ":" + c.name] + } + for destination in destinations.isEmpty + ? ["inactive:" + c.kind + ":" + c.name] : destinations + { + // Coalesced origins do not change effective content; instruction occurrences retain order. + if c.kind == DeclaredComponentKind.instructions.rawValue + || !result[destination, default: []].contains(digest) + { + result[destination, default: []].append(digest) + } + } + } + return result + } + let before = try streams(previous) + let after = try streams(next) + let changed = Set(before.keys).union(after.keys).filter { before[$0] != after[$0] }.sorted() + guard changed.isEmpty else { + throw CoreError.invalidState( + "requiresCombinedUpdate: selected changes affect protected components: " + + changed.joined(separator: ", ")) + } + } + + package static func requireEditable( + _ ledger: ResolvedLedger, kinds: Set, names: Set, + roots: [String: URL] + ) throws { + for occurrence in ledger.occurrences where !occurrence.consumerEditable { + let c = ledger.components[occurrence.component]! + if kinds.contains(DeclaredComponentKind(rawValue: c.kind)!), names.contains(c.name) { + let producer = try ledger.sourceIdentity(occurrence.declaringSource, roots: roots) + let groups = Dictionary(uniqueKeysWithValues: ledger.groups.map { ($0.id, $0) }) + var chain: [String] = [] + var parent = occurrence.reference + while let reference = parent, let group = groups[reference] { + chain.append( + try ledger.sourceIdentity(group.source, roots: roots) + ":" + group.root + "#" + + group.name) + parent = group.parent + } + throw CoreError.invalidState( + "notEditableHere: \(c.name) is owned by producer \(producer), via \(chain.reversed().joined(separator: " -> ")) (\(occurrence.manifestPath))" + ) + } + } + } +} diff --git a/Sources/Components/LedgerReplay.swift b/Sources/Components/LedgerReplay.swift index ab79806..200803b 100644 --- a/Sources/Components/LedgerReplay.swift +++ b/Sources/Components/LedgerReplay.swift @@ -87,7 +87,29 @@ package enum LedgerReplay { try run( ledger, store: store, roots: roots, limits: limits, renderers: renderers, recording: false - ) { artifacts, _ in try body(artifacts) } + ) { artifacts, _, _, _ in try body(artifacts) } + } + + package static func withPreparedLowerings( + _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], limits: LedgerLimits, + _ body: (ResolvedLedger, [ReplayedArtifact], [String: URL], URL) throws -> T + ) throws -> T { + try run(ledger, store: store, roots: roots, limits: limits, renderers: nil, recording: true) { + artifacts, lowerings, resources, workspace in + var candidate = ledger + candidate.lowerings = lowerings + try candidate.validate() + return try body(candidate, artifacts, resources, workspace) + } + } + + package static func withLockedResources( + _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], limits: LedgerLimits, + _ body: ([ReplayedArtifact], [String: URL], URL) throws -> T + ) throws -> T { + try run(ledger, store: store, roots: roots, limits: limits, renderers: nil, recording: false) { + artifacts, _, resources, workspace in try body(artifacts, resources, workspace) + } } /// Seals renderer output identities into a candidate before encoding or publication. @@ -98,7 +120,7 @@ package enum LedgerReplay { try run( ledger, store: store, roots: roots, limits: limits, renderers: renderers, recording: true - ) { _, lowerings in + ) { _, lowerings, _, _ in var candidate = ledger candidate.lowerings = lowerings try candidate.validate() @@ -109,7 +131,7 @@ package enum LedgerReplay { private static func run( _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], limits: LedgerLimits, renderers: [String: LedgerRenderer]?, recording: Bool, - _ body: ([ReplayedArtifact], [LockedLowering]) throws -> T + _ body: ([ReplayedArtifact], [LockedLowering], [String: URL], URL) throws -> T ) throws -> T { try ResolvedLedgerCodec.checkModel(ledger, limits: limits) try ledger.validate() @@ -241,7 +263,7 @@ package enum LedgerReplay { sealed.append(locked) result += rendered } - return try body(result, sealed) + return try body(result, sealed, acquired, workspace) } } diff --git a/Tests/AgentsCoreTests/CachePublicationTests.swift b/Tests/AgentsCoreTests/CachePublicationTests.swift index 8310f5c..b27eb70 100644 --- a/Tests/AgentsCoreTests/CachePublicationTests.swift +++ b/Tests/AgentsCoreTests/CachePublicationTests.swift @@ -230,9 +230,18 @@ private final class CacheFixture { destination = store.cacheDirectory.appendingPathComponent( "artifact-content/" + digest.dropFirst(7)) } - try store.save( - declaration: Declaration(), - resolved: ResolvedState(sources: [sourceID: source], skills: ["demo": skill])) + var ledger = ResolvedLedger() + ledger.sources["source"] = LedgerSource( + kind: source.kind, + transport: source.kind == .wellKnown ? sourceID : source.url, + location: source.kind == .local + ? .init(kind: .absolute, path: String(sourceID.dropFirst(6))) : nil, + revision: revision ?? digest) + ledger.resources["resource"] = LedgerResource( + kind: revision == nil ? .artifact : .git, + source: "source", path: ".", hash: skill.hash!, + entries: [.init(path: ".", kind: .directory, executable: false)], artifact: skill.artifact) + try store.save(declaration: Declaration(), ledger: ledger) lockBytes = try Data(contentsOf: store.resolvedURL) } catch { removeTemporaryDirectory(root) diff --git a/Tests/AgentsCoreTests/DeclarationStateTests.swift b/Tests/AgentsCoreTests/DeclarationStateTests.swift index ef84fc1..6c874ea 100644 --- a/Tests/AgentsCoreTests/DeclarationStateTests.swift +++ b/Tests/AgentsCoreTests/DeclarationStateTests.swift @@ -109,7 +109,7 @@ struct DeclarationStateTests { projectDirectory: store.environment.projectDirectory, homeDirectory: store.environment.homeDirectory)) #expect(try store.loadManifest()?.bytes == Array(bytes)) - #expect(throws: ManifestFailure.self) { try store.readDeploymentDeclaration() } + #expect(try store.readDeclaration() == declaration) #expect(try FileHash.folderHash(fixture.root) == before) } diff --git a/Tests/AgentsCoreTests/GitErrorTests.swift b/Tests/AgentsCoreTests/GitErrorTests.swift index 3a378aa..a7375a3 100644 --- a/Tests/AgentsCoreTests/GitErrorTests.swift +++ b/Tests/AgentsCoreTests/GitErrorTests.swift @@ -1,5 +1,6 @@ import AgentsManifest import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -147,9 +148,14 @@ struct GitErrorTests { let source = SourceDeclaration(kind: .local, location: upstream.path) let id = try source.identity(environment: store.environment) // Recovery knows a source location from the lock or watch state, never the declaration. - try store.save( - declaration: Declaration(sources: ["source": source]), - resolved: ResolvedState(sources: [id: LockedSource(kind: .local)])) + let head = try ProcessRunner.git( + ["-C", upstream.path, "rev-parse", "HEAD"], operation: .resolveRevision(revision: "HEAD"), + source: upstream.path + ).stdout.trimmingCharacters(in: .whitespacesAndNewlines) + var ledger = ResolvedLedger() + ledger.sources[id] = .init( + kind: .local, location: .init(kind: .absolute, path: upstream.path), revision: head) + try store.save(declaration: Declaration(sources: ["source": source]), ledger: ledger) let cache = SourceCache(store: store) _ = try cache.resolve(source) try cache.beginWatchReferenceUpdate() diff --git a/Tests/AgentsCoreTests/IndependentLedgerAdmissionTests.swift b/Tests/AgentsCoreTests/IndependentLedgerAdmissionTests.swift index e8a2493..9d6110c 100644 --- a/Tests/AgentsCoreTests/IndependentLedgerAdmissionTests.swift +++ b/Tests/AgentsCoreTests/IndependentLedgerAdmissionTests.swift @@ -1,5 +1,6 @@ import AgentsManifest import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -199,7 +200,7 @@ struct IndependentLedgerAdmissionTests { } } - @Test func publicV1OperationsPreserveV2Files() throws { + @Test func publicDomainInventoryReadsV2WithoutRewriting() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } let environment = RuntimeEnvironment( @@ -209,10 +210,7 @@ struct IndependentLedgerAdmissionTests { let declaration = try Data(contentsOf: store.declarationURL) let bytes = try wire(fixture()) try bytes.write(to: store.resolvedURL) - #expect(throws: (any Error).self) { _ = try store.loadResolved() } - #expect(throws: (any Error).self) { - try store.save(declaration: Declaration(), resolved: ResolvedState()) - } + #expect(try store.loadResolved() == ResolvedState()) #expect(try Data(contentsOf: store.resolvedURL) == bytes) #expect(try Data(contentsOf: store.declarationURL) == declaration) } diff --git a/Tests/AgentsCoreTests/PreparationEvidenceTests.swift b/Tests/AgentsCoreTests/PreparationEvidenceTests.swift index 5a01bc9..032610d 100644 --- a/Tests/AgentsCoreTests/PreparationEvidenceTests.swift +++ b/Tests/AgentsCoreTests/PreparationEvidenceTests.swift @@ -1,5 +1,6 @@ import AgentsManifest import Foundation +import StateTestSupport import Testing @testable import AgentsCore diff --git a/Tests/AgentsCoreTests/RequirementSemanticsTests.swift b/Tests/AgentsCoreTests/RequirementSemanticsTests.swift index fecdfc9..1684ca5 100644 --- a/Tests/AgentsCoreTests/RequirementSemanticsTests.swift +++ b/Tests/AgentsCoreTests/RequirementSemanticsTests.swift @@ -77,26 +77,22 @@ struct RequirementSemanticsTests { == .upToNextMinor(from: "1.2.0")) } - @Test func fullLedgerComparisonPreservesBytesAndCanonicalizesOnlyRequiredRewrites() throws { - let bytes = Data( - #"{ "version":1,"sources":{"intranet/team":{"kind":"git","url":"https://intranet/team.git","requirement":{"from":"v1.2.0","to":"2.0.0+meta"}}},"skills":{},"instructions":{"sections":[],"chatgpt":{},"targets":{}}}"# - .utf8) - let old = try StateStore.decode(bytes, as: ResolvedState.self) - try old.validate() - var next = old - next.sources["intranet/team"] = LockedSource( - kind: .git, url: "https://intranet/team.git", requirement: .upToNextMajor(from: "1.2.0")) - #expect(try next.replacementData(comparedTo: bytes) == nil) - #expect(old.sources["intranet/team"]?.requirement == .range(from: "v1.2.0", to: "2.0.0+meta")) - next.sources["other/team"] = LockedSource( - kind: .git, url: "https://other/team.git", requirement: .range(from: "v1.2.0", to: "1.3.0")) - let rewritten = try #require(try next.replacementData(comparedTo: bytes)) - let root = try #require(JSONSerialization.jsonObject(with: rewritten) as? [String: Any]) - let sources = try #require(root["sources"] as? [String: [String: Any]]) - #expect(sources["intranet/team"]?["requirement"] as? [String: String] == ["from": "1.2.0"]) - #expect( - sources["other/team"]?["requirement"] as? [String: String] == ["upToNextMinor": "1.2.0"]) - #expect(try ResolvedState().replacementData(comparedTo: nil) != nil) + @Test func fullLedgerComparisonPreservesEquivalentRequirementBytes() throws { + var ledger = ResolvedLedger() + ledger.sources["source"] = LedgerSource( + kind: .git, transport: "https://intranet/team.git", + revision: String(repeating: "a", count: 40)) + ledger.sourceUses = [ + .init(source: "source", root: ".", requirement: .range(from: "v1.2.0", to: "2.0.0+meta")) + ] + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + var next = ledger + next.sourceUses[0].requirement = .upToNextMajor(from: "1.2.0") + #expect(try ResolvedLedgerCodec.replacement(next, existing: bytes, limits: .standard) == nil) + next.sourceUses[0].requirement = .upToNextMinor(from: "1.2.0") + let changed = try #require( + try ResolvedLedgerCodec.replacement(next, existing: bytes, limits: .standard)) + #expect(try ResolvedLedgerCodec.decode(changed, limits: .standard) == next) } @Test func resolutionSessionsReuseEqualRequirementsAndCacheKeysKeepExactPins() throws { diff --git a/Tests/AgentsCoreTests/SourceCacheTests.swift b/Tests/AgentsCoreTests/SourceCacheTests.swift index e18be18..9617be4 100644 --- a/Tests/AgentsCoreTests/SourceCacheTests.swift +++ b/Tests/AgentsCoreTests/SourceCacheTests.swift @@ -1,5 +1,6 @@ import AgentsManifest import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -38,15 +39,12 @@ struct SourceCacheTests { #expect( !FileManager.default.fileExists( atPath: cache.materializedURL(sourceID: id, revision: second.revision).path)) - let section = LockedSection( - name: "rules", source: id, revision: first.revision, path: "content", - hash: "sha256:" + String(repeating: "a", count: 64)) - try cache.prune( - referencedBy: ResolvedState( - sources: [id: locked], - instructions: LockedInstructions(chatgpt: ["prompt": LockedPrompt(sections: [section])]))) + var references = RetentionReferences() + references.git.insert(.init(source: id, revision: first.revision)) + references.sourceLocations[id] = repo.path + try prune(cache, references: references) #expect(FileManager.default.fileExists(atPath: tree.path)) - try cache.prune(referencedBy: ResolvedState()) + try prune(cache, references: RetentionReferences()) #expect(!FileManager.default.fileExists(atPath: tree.path)) } @@ -170,14 +168,10 @@ extension SourceCacheTests { try FileManager.default.createDirectory( at: link.deletingLastPathComponent(), withIntermediateDirectories: true) try FileManager.default.createSymbolicLink(at: link, withDestinationURL: external) - let state = ResolvedState( - sources: [id: LockedSource(kind: .local)], - skills: [ - "demo": LockedSkill( - source: id, revision: revision, path: ".", - hash: "sha256:" + String(repeating: "b", count: 64), installs: ["codex": .link]) - ]) - #expect(throws: CoreError.self) { try cache.prune(referencedBy: state) } + var references = RetentionReferences() + references.git.insert(.init(source: id, revision: revision)) + references.sourceLocations[id] = String(id.dropFirst(6)) + #expect(throws: CoreError.self) { try prune(cache, references: references) } #expect( try String(contentsOf: external.appendingPathComponent("unrelated"), encoding: .utf8) == "keep") @@ -194,13 +188,17 @@ extension SourceCacheTests { try FileManager.default.createDirectory( at: content.appendingPathComponent("nested"), withIntermediateDirectories: true) try Data("live".utf8).write(to: content.appendingPathComponent("nested/SKILL.md")) - let id = "local:" + content.path - let state = ResolvedState( - sources: [id: LockedSource(kind: .local)], - skills: ["live": LockedSkill(source: id, path: "nested", installs: ["codex": .edit])]) - try SourceCache(store: store).prune(referencedBy: state) + var references = RetentionReferences() + references.live = [content.appendingPathComponent("nested")] + try prune(SourceCache(store: store), references: references) #expect( FileManager.default.fileExists(atPath: content.appendingPathComponent("nested/SKILL.md").path) ) } + private func prune(_ cache: SourceCache, references: RetentionReferences) throws { + let transaction = FileTransaction(store: cache.store) + try cache.prune(references: references, transaction: transaction) + try transaction.commit() + } + } diff --git a/Tests/AgentsCoreTests/StateEncodingTests.swift b/Tests/AgentsCoreTests/StateEncodingTests.swift index 4c0ef85..3aedaa9 100644 --- a/Tests/AgentsCoreTests/StateEncodingTests.swift +++ b/Tests/AgentsCoreTests/StateEncodingTests.swift @@ -1,5 +1,6 @@ import AgentsManifest import Foundation +import StateTestSupport import Testing @testable import AgentsCore diff --git a/Tests/AgentsCoreTests/StateInspectionTests.swift b/Tests/AgentsCoreTests/StateInspectionTests.swift index 12804c5..1c1fb25 100644 --- a/Tests/AgentsCoreTests/StateInspectionTests.swift +++ b/Tests/AgentsCoreTests/StateInspectionTests.swift @@ -1,5 +1,6 @@ import AgentsManifest import Foundation +import StateTestSupport import Synchronization import Testing diff --git a/Tests/AgentsCoreTests/StateModelTests.swift b/Tests/AgentsCoreTests/StateModelTests.swift index 1f7c02b..7300271 100644 --- a/Tests/AgentsCoreTests/StateModelTests.swift +++ b/Tests/AgentsCoreTests/StateModelTests.swift @@ -1,5 +1,6 @@ import AgentsManifest import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -92,10 +93,10 @@ struct StateModelTests { "CLAUDE.md": LockedTarget( agents: [.claudeCode], import: "AGENTS.md", blockHash: digest, created: false), ])) - try store.save(declaration: declaration, resolved: lock) + try store.save(declaration: declaration, ledger: ledgerFixture(lock)) let first = try Data(contentsOf: store.resolvedURL) let firstDeclaration = try Data(contentsOf: store.declarationURL) - try store.save(declaration: declaration, resolved: lock) + try store.save(declaration: declaration, ledger: ledgerFixture(lock)) #expect(try Data(contentsOf: store.resolvedURL) == first) #expect(try Data(contentsOf: store.declarationURL) == firstDeclaration) // The document spells the Git location as a URL; the projection keeps its meaning. @@ -103,7 +104,9 @@ struct StateModelTests { ManifestProjection.equivalent( try store.loadDeclaration(), declaration, environment: environment)) #expect(try store.loadResolved() == lock) - #expect(String(decoding: first, as: UTF8.self).contains("\"from\": \"1.0.0\"")) + #expect( + try store.loadLedger().sourceUses.contains { $0.requirement == .upToNextMajor(from: "1.0.0") } + ) } @Test func rejectsCorruptionWithoutReplacingFiles() throws { @@ -168,3 +171,93 @@ extension StateModelTests { #expect(try Data(contentsOf: store.resolvedURL) == beforeLock) } } + +private func ledgerFixture(_ model: ResolvedState) throws -> ResolvedLedger { + var ledger = ResolvedLedger() + func source(_ identity: String, revision: String?, version: String?) -> String { + let record = model.sources[identity]! + let id = identity + ":" + (revision ?? "live") + ":" + (version ?? "") + ledger.sources[id] = LedgerSource( + kind: record.kind, transport: record.url, + location: record.kind == .local + ? .init(kind: .absolute, path: String(identity.dropFirst(6))) : nil, + revision: revision ?? "live", version: version) + ledger.sourceUses.append( + .init(source: id, root: record.path ?? ".", requirement: record.requirement)) + return id + } + func occurrence(_ id: String, source: String) { + ledger.occurrences.append( + .init( + declaringSource: source, manifestPath: ".agent/agents.yaml", id: ledger.occurrences.count, + component: id, dependencies: [source], condition: .init(DeclarationCondition()), + recipients: ledger.components[id]!.recipients, consumerEditable: true)) + } + for (name, skill) in model.skills { + let sid = source(skill.source, revision: skill.revision, version: skill.version) + let rid = "skill:" + name + ledger.resources[rid] = .init( + kind: .git, source: sid, path: skill.path!, hash: skill.hash!, + entries: [.init(path: ".", kind: .directory, executable: false)]) + ledger.components[rid] = .init( + declaringSource: sid, source: sid, root: ".", kind: "skills", name: name, + revision: skill.revision, version: skill.version, + payload: .init(object: ["mode": .init(skill.installs.values.first!.rawValue)]), + conditions: [], recipients: skill.installs.keys.compactMap(AgentID.init(rawValue:)), + chatGPT: false, resources: [rid]) + occurrence(rid, source: sid) + } + var sectionOwners: [String] = [] + func section(_ record: LockedSection, prompt: String? = nil, append: String? = nil) { + let sid = source(record.source, revision: record.revision, version: record.version) + let id = "section:" + String(ledger.components.count) + let rid = id + ":resource" + ledger.resources[rid] = .init( + kind: .git, source: sid, path: record.path, hash: record.hash, + entries: [.init(path: ".", kind: .file, executable: false, byteCount: 0)]) + var payload = ["name": LedgerValue(record.name), "sourceHash": .init(record.hash)] + payload["prompt"] = prompt.map { .init($0) } + var resources = [rid] + if let append { + let aid = id + ":append" + ledger.resources[aid] = .init( + kind: .git, source: sid, path: append, hash: record.hash, + entries: [.init(path: ".", kind: .file, executable: false, byteCount: 0)]) + resources.append(aid) + } + ledger.components[id] = .init( + declaringSource: sid, source: sid, root: ".", kind: "instructions", name: record.name, + revision: record.revision, version: record.version, payload: .init(object: payload), + conditions: [], + recipients: prompt == nil ? [.codex, .claudeCode] : [], chatGPT: prompt != nil, + resources: resources) + occurrence(id, source: sid) + if prompt == nil { sectionOwners.append(id) } + } + for item in model.instructions.sections { section(item) } + for (name, prompt) in model.instructions.chatgpt { + for item in prompt.sections { section(item, prompt: name, append: prompt.append) } + } + #if os(macOS) + let platform = "macos" + #else + let platform = "linux" + #endif + for (path, target) in model.instructions.targets { + let id = "target:" + path + let route = target.import == nil ? "agents/instructions@1" : "agents/claude-import@1" + ledger.deployments.append( + .init( + id: id, target: .init(kind: .registered, root: "project", path: path), route: route, + owners: sectionOwners, + recipients: target.agents, ownership: target.import == nil ? .generated : .importBlock, + expectedHash: target.blockHash, + created: target.created, importReference: target.import, headingOffset: target.headingOffset + )) + ledger.lowerings.append( + .init( + id: id, format: route, inputs: sectionOwners, resources: [], deployments: [id], + layout: .init(), platform: platform, artifacts: [])) + } + return ledger +} diff --git a/Tests/AgentsCoreTests/WatchSourceTests.swift b/Tests/AgentsCoreTests/WatchSourceTests.swift index 0a40ebf..07c613b 100644 --- a/Tests/AgentsCoreTests/WatchSourceTests.swift +++ b/Tests/AgentsCoreTests/WatchSourceTests.swift @@ -1,5 +1,6 @@ import AgentsManifest import Foundation +import StateTestSupport import Testing @testable import AgentsCore diff --git a/Tests/AgentsInstructionsTests/DeclarationDocumentTests.swift b/Tests/AgentsInstructionsTests/DeclarationDocumentTests.swift index baa3bf9..cf45718 100644 --- a/Tests/AgentsInstructionsTests/DeclarationDocumentTests.swift +++ b/Tests/AgentsInstructionsTests/DeclarationDocumentTests.swift @@ -1,6 +1,7 @@ import AgentsCore import AgentsInstructions import AgentsManifest +import AgentsUpdates import Foundation import Testing diff --git a/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift b/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift index 555768d..31af69c 100644 --- a/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsInstructions +import AgentsUpdates import Foundation import Testing diff --git a/Tests/AgentsInstructionsTests/FileReadAccessTests.swift b/Tests/AgentsInstructionsTests/FileReadAccessTests.swift index 5ae3c85..a97647a 100644 --- a/Tests/AgentsInstructionsTests/FileReadAccessTests.swift +++ b/Tests/AgentsInstructionsTests/FileReadAccessTests.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsUpdates import Foundation import Testing diff --git a/Tests/AgentsInstructionsTests/LifecycleFixture.swift b/Tests/AgentsInstructionsTests/LifecycleFixture.swift index a5e8720..e7f1f38 100644 --- a/Tests/AgentsInstructionsTests/LifecycleFixture.swift +++ b/Tests/AgentsInstructionsTests/LifecycleFixture.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsInstructions +import AgentsUpdates import Foundation import Testing diff --git a/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift b/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift index 4074063..0941f76 100644 --- a/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift +++ b/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift @@ -1,7 +1,10 @@ import AgentsCore import AgentsInstructions import AgentsManifest +import AgentsSkills +import AgentsUpdates import Foundation +import StateTestSupport import Testing @Suite("Instruction lifecycle safety") @@ -11,10 +14,16 @@ struct InstructionLifecycleSafetyTests { try fixture.section("rules") try fixture.commit() try fixture.add(agents: [.codex, .geminiCLI]) - let original = try fixture.store().loadResolved() + let original = try fixture.store().loadLedger() var lock = original - lock.instructions.sections[0].revision = String(repeating: "a", count: 40) - try fixture.store().save(declaration: fixture.store().loadDeclaration(), resolved: lock) + let unavailable = String(repeating: "a", count: 40) + for id in lock.sources.keys where lock.sources[id]!.revision != "live" { + lock.sources[id]!.revision = unavailable + } + for id in lock.components.keys where lock.components[id]!.revision != nil { + lock.components[id]!.revision = unavailable + } + try fixture.store().save(declaration: fixture.store().loadDeclaration(), ledger: lock) try fixture.write("Custom target.\n", to: fixture.project.appendingPathComponent("AGENTS.md")) let before = try fixture.snapshot(fixture.project, excludingCache: true) #expect(throws: (any Error).self) { @@ -22,8 +31,10 @@ struct InstructionLifecycleSafetyTests { } #expect(try fixture.snapshot(fixture.project, excludingCache: true) == before) lock = original - lock.instructions.sections[0].hash = "sha256:" + String(repeating: "a", count: 64) - try fixture.store().save(declaration: fixture.store().loadDeclaration(), resolved: lock) + for id in lock.resources.keys { + lock.resources[id]!.hash = "sha256:" + String(repeating: "a", count: 64) + } + try fixture.store().save(declaration: fixture.store().loadDeclaration(), ledger: lock) #expect(throws: (any Error).self) { try InstructionOperations.installResolvedReport(environment: fixture.environment) } @@ -70,14 +81,17 @@ struct InstructionLifecycleSafetyTests { try fixture.section("two") try fixture.commit() try fixture.add(names: ["one"]) - var declaration = try fixture.store().loadDeclaration() - var lock = try fixture.store().loadResolved() + try fixture.write( + "---\nname: example\ndescription: Example\n---\nExample\n", + to: fixture.repo.appendingPathComponent("skills/example/SKILL.md")) + try fixture.commit() + _ = try SkillOperations.add( + AddOptions( + source: "rules", agents: [.claudeCode], skillNames: ["example"], + environment: fixture.environment)) + let declaration = try fixture.store().loadDeclaration() + let lock = try fixture.store().loadResolved() let previous = lock.instructions.sections[0] - try declaration.setSkills(["rules": SkillDeclaration(select: .names([]))]) - lock.skills["example"] = LockedSkill( - source: previous.source, revision: previous.revision, - path: "skills/example", hash: previous.hash, installs: ["codex": .copy]) - try fixture.store().save(declaration: declaration, resolved: lock) try fixture.section("one", body: "Changed") try fixture.commit() try fixture.add(names: ["two"]) @@ -159,7 +173,7 @@ struct InstructionLifecycleSafetyTests { #expect(try String(contentsOf: outside, encoding: .utf8) == "Owner content.\n") } - @Test func promptAppendCannotEscapeScopeThroughSymlinks() throws { + @Test func frozenPromptAppendIgnoresSubsequentEscapingSymlink() throws { let fixture = try InstructionFixture() try fixture.section("rules") try fixture.commit() @@ -171,13 +185,21 @@ struct InstructionLifecycleSafetyTests { ] } try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) + let append = fixture.project.appendingPathComponent("custom.md") + try fixture.write("Frozen custom text.\n", to: append) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + let rendered = try InstructionOperations.renderChatGPT( + prompt: "prompt", environment: fixture.environment) + try FileManager.default.removeItem(at: append) let outside = fixture.root.appendingPathComponent("outside.md") try fixture.write("Owner content.\n", to: outside) try FileManager.default.createSymbolicLink( at: fixture.project.appendingPathComponent("custom.md"), withDestinationURL: outside) - #expect(throws: (any Error).self) { + #expect( try InstructionOperations.renderChatGPT(prompt: "prompt", environment: fixture.environment) + == rendered) + #expect(throws: (any Error).self) { + try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) } } diff --git a/Tests/AgentsInstructionsTests/LifecycleTests.swift b/Tests/AgentsInstructionsTests/LifecycleTests.swift index f748200..1dbdd2c 100644 --- a/Tests/AgentsInstructionsTests/LifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/LifecycleTests.swift @@ -1,7 +1,9 @@ import AgentsCore import AgentsInstructions import AgentsManifest +import AgentsUpdates import Foundation +import StateTestSupport import Testing @Suite("Instruction lifecycle") @@ -344,11 +346,11 @@ struct InstructionLifecycleTests { try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { $0.kind == .uncommittedSource }) - #expect(throws: (any Error).self) { + #expect( try InstructionOperations.list( source: SourceDeclaration(kind: .local, location: fixture.home.path), - environment: fixture.environment) - } + environment: fixture.environment + ).isEmpty) } @Test func discoveryRejectsInvalidNamesSymbolicLinksAndDuplicates() throws { diff --git a/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift b/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift index 636c370..5b30bf4 100644 --- a/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift +++ b/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift @@ -1,6 +1,7 @@ import AgentsCore import AgentsInstructions import AgentsManifest +import AgentsUpdates import Foundation import Testing diff --git a/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift b/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift index 914148a..3d1c913 100644 --- a/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift +++ b/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift @@ -1,7 +1,9 @@ import AgentsCore import AgentsInstructions import AgentsManifest +import AgentsUpdates import Foundation +import StateTestSupport import Testing @Suite("Instruction source diagnostics") diff --git a/Tests/AgentsInstructionsTests/SourceShorthandTests.swift b/Tests/AgentsInstructionsTests/SourceShorthandTests.swift index 5fb4d04..81aa224 100644 --- a/Tests/AgentsInstructionsTests/SourceShorthandTests.swift +++ b/Tests/AgentsInstructionsTests/SourceShorthandTests.swift @@ -1,6 +1,7 @@ import AgentsCore import AgentsInstructions import AgentsManifest +import AgentsUpdates import Foundation import Testing diff --git a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift index 0f00d9e..1c2bea4 100644 --- a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift @@ -1,6 +1,7 @@ import AgentsCore import AgentsInstructions import AgentsManifest +import AgentsUpdates import Foundation import Testing @@ -48,9 +49,9 @@ struct TargetLifecycleTests { try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { $0.kind == .ownChanged }) - #expect(throws: InstructionError.ownChanged(name: "guide")) { - try InstructionOperations.installResolvedReport(environment: fixture.environment) - } + let locked = try fixture.bytes() + _ = try InstructionOperations.installResolvedReport(environment: fixture.environment) + #expect(try fixture.bytes() == locked) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) #expect(try fixture.text().contains("# Project Guide\n\nEdited")) #expect( diff --git a/Tests/AgentsManifestTests/FullDeclarationTests.swift b/Tests/AgentsManifestTests/FullDeclarationTests.swift index 4ceafdd..2b693bc 100644 --- a/Tests/AgentsManifestTests/FullDeclarationTests.swift +++ b/Tests/AgentsManifestTests/FullDeclarationTests.swift @@ -363,13 +363,6 @@ struct FullDeclarationTests { #expect(declaration.components.count == 3) #expect(throws: CoreError.self) { try declaration.skills } #expect(throws: CoreError.self) { try declaration.setSkills(nil) } - do { - try doc.requireDeploymentSubset() - Issue.record("ambiguous deployment selection accepted") - } catch let failure as ManifestFailure { - #expect(failure.diagnostics.map(\.code) == ["manifest.ambiguous"]) - #expect(failure.diagnostics.first?.related.count == 2) - } guard case .skills(let source, var selection) = declaration.components[1] else { return } selection.agents = [] declaration.components[1] = .skills(source: source, selection) diff --git a/Tests/AgentsSkillsTests/ArchiveSafetyTests.swift b/Tests/AgentsSkillsTests/ArchiveSafetyTests.swift index 1fbae37..64f5039 100644 --- a/Tests/AgentsSkillsTests/ArchiveSafetyTests.swift +++ b/Tests/AgentsSkillsTests/ArchiveSafetyTests.swift @@ -1,3 +1,4 @@ +import AgentsUpdates import Foundation import Testing @@ -36,10 +37,7 @@ struct ArchiveSafetyTests { ? "subpath must be relative: \(path)" : "subpath contains path traversal segment: \(path)" ) #expect(throws: expected) { - try SkillOperations.add( - AddOptions( - source: "https://zip.test", agents: [.codex], all: true, environment: fixture.environment), - provider: provider) + _ = try provider.fetchAllSkills(from: "https://zip.test") } #expect(try fixture.stateAndTargetBytes() == before) } diff --git a/Tests/AgentsSkillsTests/DefaultResolutionTests.swift b/Tests/AgentsSkillsTests/DefaultResolutionTests.swift index 1462a50..10ab585 100644 --- a/Tests/AgentsSkillsTests/DefaultResolutionTests.swift +++ b/Tests/AgentsSkillsTests/DefaultResolutionTests.swift @@ -1,5 +1,7 @@ import AgentsManifest +import AgentsUpdates import Foundation +import StateTestSupport import Testing @testable import AgentsCore diff --git a/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift b/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift index 9532fdd..5364698 100644 --- a/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift +++ b/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift @@ -1,5 +1,7 @@ import AgentsManifest +import AgentsUpdates import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -103,21 +105,16 @@ struct SkillDiscoveryTests { let locked = try temporaryDirectory() defer { removeTemporaryDirectory(locked) } + let upstream = try temporaryDirectory() + defer { removeTemporaryDirectory(upstream) } try writeDiscoverySkill( - locked.appendingPathComponent(".agents/skills/installed-skill"), name: "installed-skill") + upstream.appendingPathComponent("installed-skill"), name: "installed-skill") try writeDiscoverySkill( locked.appendingPathComponent("skills/source-skill"), name: "source-skill") - let store = StateStore( - scope: .project, environment: RuntimeEnvironment(projectDirectory: locked)) - let id = "local:" + locked.path - try store.save( - declaration: Declaration(), - resolved: ResolvedState( - sources: [id: LockedSource(kind: .local)], - skills: [ - "installed-skill": LockedSkill( - source: id, path: ".agents/skills/installed-skill", installs: ["codex": .edit]) - ])) + _ = try SkillOperations.add( + AddOptions( + source: upstream.path, + agents: [.codex], mode: .edit, environment: RuntimeEnvironment(projectDirectory: locked))) #expect(try Discovery.discover(in: locked).map(\.name) == ["source-skill"]) } diff --git a/Tests/AgentsSkillsTests/FileReadAccessTests.swift b/Tests/AgentsSkillsTests/FileReadAccessTests.swift index a6d781b..dd34b16 100644 --- a/Tests/AgentsSkillsTests/FileReadAccessTests.swift +++ b/Tests/AgentsSkillsTests/FileReadAccessTests.swift @@ -34,8 +34,7 @@ struct SkillFileReadAccessTests { try fixture.skill("demo", body: "Original") let directory = fixture.repo.appendingPathComponent("skills/demo") let file = directory.appendingPathComponent("SKILL.md") - let lifecycle = try SkillLifecycle(store: fixture.store(), provider: WellKnownProvider()) - try withUnreadableFile(file) { _ = try lifecycle.entries(directory) } + try withUnreadableFile(file) { _ = try SkillLifecycle.entries(directory) } try withUnreadableFile(file) { _ = try Discovery.parseSkill(at: file) } } diff --git a/Tests/AgentsSkillsTests/InstallationSafetyTests.swift b/Tests/AgentsSkillsTests/InstallationSafetyTests.swift index fcbc126..cdc33e7 100644 --- a/Tests/AgentsSkillsTests/InstallationSafetyTests.swift +++ b/Tests/AgentsSkillsTests/InstallationSafetyTests.swift @@ -1,3 +1,4 @@ +import AgentsUpdates import Foundation import Testing diff --git a/Tests/AgentsSkillsTests/InstalledInventoryTests.swift b/Tests/AgentsSkillsTests/InstalledInventoryTests.swift index 717e71c..a23483a 100644 --- a/Tests/AgentsSkillsTests/InstalledInventoryTests.swift +++ b/Tests/AgentsSkillsTests/InstalledInventoryTests.swift @@ -1,4 +1,5 @@ import AgentsManifest +import AgentsUpdates import Foundation import Testing @@ -121,10 +122,9 @@ struct InstalledInventoryTests { _ = try SkillOperations.doctor(scope: scope, environment: fixture.environment) } #expect(try Data(contentsOf: file) == bytes) - // The declaration is parsed under the scope lock, which a first writer creates. #expect( try Set(FileManager.default.contentsOfDirectory(atPath: store.directory.path)) - == Set([file.lastPathComponent] + (corruptDeclaration ? [".agents.lock"] : []))) + == Set([file.lastPathComponent])) #expect(!FileManager.default.fileExists(atPath: store.cacheDirectory.path)) #expect( !FileManager.default.fileExists( diff --git a/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift b/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift index e452104..eed760a 100644 --- a/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift +++ b/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift @@ -1,5 +1,7 @@ import AgentsManifest +import AgentsUpdates import Foundation +import StateTestSupport import Testing @testable import AgentsCore diff --git a/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift b/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift deleted file mode 100644 index 1445744..0000000 --- a/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift +++ /dev/null @@ -1,225 +0,0 @@ -import CPlatform -import Foundation -import StateTestSupport -import Testing - -@testable import AgentsCore -@testable import AgentsSkills - -@Suite("Locked artifacts") -struct LockedArtifactLifecycleTests { - @Test func automaticSelectionRediscoversContentUnderTheWriterLock() throws { - let fixture = try SkillFixture() - let store = fixture.store() - let lock = store.directory.appendingPathComponent(".agents.lock") - let observations = fixture.root.appendingPathComponent("discovery-phases") - let content = "---\nname: demo\ndescription: Test skill\n---\n" - let provider = WellKnownProvider { _ in - let applying = FileManager.default.fileExists(atPath: lock.path) - let before = (try? Data(contentsOf: observations)) ?? Data() - try (before + Data((applying ? "apply\n" : "inspect\n").utf8)).write(to: observations) - return Data((content + (applying ? "Current\n" : "Previous\n")).utf8) - } - let outcome = try SkillOperations.add( - AddOptions( - source: "https://example.test/demo/SKILL.md", agents: [.codex], mode: .copy, - environment: fixture.environment), provider: provider) - #expect(outcome.installed.map(\.skill) == ["demo"]) - #expect(try Data(contentsOf: observations) == Data("inspect\napply\n".utf8)) - #expect(try fixture.body(fixture.target("demo")) == content + "Current\n") - #expect(try store.loadResolved().skills["demo"]?.artifact != nil) - } - - @Test(arguments: [false, true]) - func restoresWithoutIndexAndVerifiesDigests(_ filesArtifact: Bool) throws { - let fixture = try SkillFixture() - let content = Data("---\nname: demo\ndescription: Test skill\n---\nA\n".utf8) - let digest = "sha256:" + FileHash.sha256Hex(data: content) - let base = "https://example.test" - let artifactURL = base + "/demo/SKILL.md" - let fileURL = base + "/.well-known/agent-skills/demo/SKILL.md" - let index = - filesArtifact - ? Data(#"{"skills":[{"name":"demo","description":"Test skill","files":["SKILL.md"]}]}"#.utf8) - : Data( - "{\"$schema\":\"https://schemas.agentskills.io/discovery/0.2.0/schema.json\",\"skills\":[{\"name\":\"demo\",\"description\":\"Test skill\",\"type\":\"skill-md\",\"url\":\"\(artifactURL)\",\"digest\":\"\(digest)\"}]}" - .utf8) - let provider = WellKnownProvider { url in - if url.path.hasSuffix("index.json") { return index } - if [artifactURL, fileURL].contains(url.absoluteString) { return content } - throw CoreError.notFound("URL") - } - _ = try SkillOperations.add( - AddOptions( - source: base, agents: [.codex], mode: .copy, all: true, environment: fixture.environment), - provider: provider) - let locked = try fixture.store().loadResolved() - let artifact = try #require(locked.skills["demo"]?.artifact) - #expect(artifact.type == (filesArtifact ? .files : .skillMD)) - if filesArtifact { - #expect(artifact.files?.first?.url == fileURL) - #expect(artifact.files?.first?.digest == digest) - } - let lockBytes = try Data(contentsOf: fixture.store().resolvedURL) - try FileManager.default.removeItem(at: fixture.store().cacheDirectory) - try FileManager.default.removeItem(at: fixture.target("demo")) - let restore = WellKnownProvider { url in - guard [artifactURL, fileURL].contains(url.absoluteString) else { - throw CoreError.invalidState("restore consulted index") - } - return content - } - _ = try SkillOperations.install( - scope: .project, environment: fixture.environment, provider: restore) - #expect( - try Data(contentsOf: fixture.target("demo").appendingPathComponent("SKILL.md")) == content) - #expect(try Data(contentsOf: fixture.store().resolvedURL) == lockBytes) - try FileManager.default.removeItem(at: fixture.store().cacheDirectory) - let before = try fixture.stateAndTargetBytes() - let mismatch = WellKnownProvider { _ in Data("different content".utf8) } - #expect(throws: (any Error).self) { - try SkillOperations.install( - scope: .project, environment: fixture.environment, provider: mismatch) - } - #expect(try fixture.stateAndTargetBytes() == before) - } - - @Test func cachedArtifactCorruptionStopsRestore() throws { - let fixture = try SkillFixture() - let content = Data("---\nname: demo\ndescription: Test skill\n---\nA\n".utf8) - let url = "https://example.test/demo/SKILL.md" - let provider = WellKnownProvider { _ in content } - _ = try SkillOperations.add( - AddOptions(source: url, agents: [.codex], mode: .copy, environment: fixture.environment), - provider: provider) - let locked = try fixture.store().loadResolved() - let digest = try #require(locked.skills["demo"]?.artifact?.digest) - let cached = try SourceCache(store: fixture.store()).artifactURL(digest: digest) - try Data("corrupt".utf8).write(to: cached) - let before = try fixture.stateAndTargetBytes() - #expect(throws: (any Error).self) { - try SkillOperations.install( - scope: .project, environment: fixture.environment, provider: provider) - } - #expect(try fixture.stateAndTargetBytes() == before) - } -} - -extension LockedArtifactLifecycleTests { - @Test func namedUpdateFetchesOnlySelectedArtifactAndAllFollowsEmptyIndex() throws { - let fixture = try SkillFixture() - let first = Data("---\nname: one\ndescription: Test\n---\nA\n".utf8) - let second = Data("---\nname: two\ndescription: Test\n---\nA\n".utf8) - let index = Data( - #"{"skills":[{"name":"one","description":"Test","files":["SKILL.md"]},{"name":"two","description":"Test","files":["SKILL.md"]}]}"# - .utf8) - let provider = WellKnownProvider { url in - if url.path.hasSuffix("index.json") { return index } - return url.path.contains("/one/") ? first : second - } - _ = try SkillOperations.add( - AddOptions( - source: "https://example.test", agents: [.codex], all: true, - environment: fixture.environment), provider: provider) - let old = try fixture.store().loadResolved().skills["two"] - let changed = Data("---\nname: one\ndescription: Test\n---\nB\n".utf8) - let selectedOnly = WellKnownProvider { url in - if url.path.hasSuffix("index.json") { return index } - guard url.path.contains("/one/") else { - throw CoreError.invalidState("unselected artifact fetched") - } - return changed - } - let updated = try SkillOperations.update( - scope: .project, environment: fixture.environment, skillNames: ["one"], apply: true, - provider: selectedOnly) - #expect(updated.allSatisfy { $0.oldVersion == nil && $0.newVersion == nil }) - #expect(try fixture.store().loadResolved().skills["two"] == old) - let empty = WellKnownProvider { _ in Data(#"{"skills":[]}"#.utf8) } - _ = try SkillOperations.update( - scope: .project, environment: fixture.environment, skillNames: [], apply: true, - provider: empty) - #expect(try fixture.store().loadResolved().skills.isEmpty) - } -} - -extension LockedArtifactLifecycleTests { - @Test func restoresArchiveLockAfterInterruptedExpansionPublication() throws { - let fixture = try SkillFixture() - let project = fixture.environment.projectDirectory - let expanded = project.appendingPathComponent("new") - try FileManager.default.createDirectory(at: expanded, withIntermediateDirectories: true) - let markdown = Data("---\nname: demo\ndescription: Test skill\n---\narchive content\n".utf8) - try markdown.write(to: expanded.appendingPathComponent("SKILL.md")) - try Data("reference".utf8).write(to: expanded.appendingPathComponent("z-reference.md")) - let archive = fixture.root.appendingPathComponent("demo.tar.gz") - try ProcessRunner.run( - "/usr/bin/env", arguments: ["tar", "-czf", archive.path, "-C", expanded.path, "."]) - let bytes = try Data(contentsOf: archive) - let digest = "sha256:" + FileHash.sha256Hex(data: bytes) - let base = "https://example.test" - let url = base + "/demo.tar.gz" - let index = try JSONSerialization.data(withJSONObject: [ - "$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json", - "skills": [ - [ - "name": "demo", "description": "Test skill", "type": "archive", "url": url, - "digest": digest, - ] - ], - ]) - _ = try SkillOperations.add( - AddOptions(source: base, agents: [.codex], all: true, environment: fixture.environment), - provider: WellKnownProvider { $0.path.hasSuffix("index.json") ? index : bytes }) - let store = fixture.store() - let lock = try Data(contentsOf: store.resolvedURL) - try FileManager.default.removeItem(at: store.cacheDirectory) - try FileManager.default.removeItem(at: fixture.target("demo")) - let child = try artifactTestProcess(root: project) - defer { terminateProcess(child) } - let marker = project.appendingPathComponent("ready") - try ProcessWait.marker(marker, child: child, root: fixture.root) - let final = store.cacheDirectory.appendingPathComponent( - "artifact-content/" + digest.dropFirst(7)) - #expect(!FileManager.default.fileExists(atPath: final.path)) - terminateProcess(child) - let restore = WellKnownProvider { - guard $0.absoluteString == url else { - throw CoreError.invalidState("restore consulted index") - } - return bytes - } - #expect(throws: CoreError.transactionRecovered(store.directory.path)) { - try SkillOperations.install( - scope: .project, environment: fixture.environment, provider: restore) - } - _ = try SkillOperations.install( - scope: .project, environment: fixture.environment, provider: restore) - #expect(try FileHash.folderHash(fixture.target("demo")) == FileHash.folderHash(expanded)) - #expect(try Data(contentsOf: store.resolvedURL) == lock) - #expect( - try FileManager.default.contentsOfDirectory(atPath: final.deletingLastPathComponent().path) - == [final.lastPathComponent]) - } - - private func artifactTestProcess(root: URL) throws -> Process { - var directory = Bundle(for: ArtifactTestBundle.self).bundleURL - while !FileManager.default.isExecutableFile( - atPath: directory.appendingPathComponent("StateTestProcess").path), directory.path != "/" - { - directory.deleteLastPathComponent() - } - let process = Process() - process.executableURL = directory.appendingPathComponent("StateTestProcess") - process.arguments = [ - root.path, "cache-content", - TransactionCheckpoint.copy( - 0, .init(path: TransactionSlot.staged.name(0) + "/SKILL.md", step: .entryCopied) - ).name, - ] - try process.run() - return process - } -} - -private final class ArtifactTestBundle: NSObject {} diff --git a/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift b/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift index b1766f5..8dc9329 100644 --- a/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift @@ -1,5 +1,6 @@ import AgentsManifest import AgentsSkills +import AgentsUpdates import CPlatform import Foundation import StateTestSupport @@ -28,7 +29,8 @@ struct ManifestLifecycleTests { entries.value = journal.entries }) #expect( - entries.value.map(\.path) == ["codex/demo", "state/agents.yaml", "state/agents.resolved"]) + Set(["codex/demo", "state/agents.yaml", "state/agents.resolved"]).isSubset( + of: Set(entries.value.map(\.path)))) #expect(entries.value.allSatisfy { $0.preimage == nil }) #expect( String(decoding: try Data(contentsOf: store.declarationURL), as: UTF8.self) == """ diff --git a/Tests/AgentsSkillsTests/PublicLifecycleTests.swift b/Tests/AgentsSkillsTests/PublicLifecycleTests.swift index 5094556..4974546 100644 --- a/Tests/AgentsSkillsTests/PublicLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/PublicLifecycleTests.swift @@ -1,7 +1,9 @@ import AgentsCore import AgentsManifest import AgentsSkills +import AgentsUpdates import Foundation +import StateTestSupport import Testing @Suite("Public lifecycle API") @@ -80,9 +82,15 @@ struct PublicLifecycleTests { try fixture.skill("two", body: "A") try fixture.commit() _ = try fixture.add(mode: .copy) - var lock = try fixture.store().loadResolved() - lock.skills["two"]?.revision = String(repeating: "a", count: 40) - try fixture.store().save(declaration: fixture.store().loadDeclaration(), resolved: lock) + var lock = try fixture.store().loadLedger() + let unavailable = String(repeating: "a", count: 40) + for id in lock.sources.keys where lock.sources[id]!.revision != "live" { + lock.sources[id]!.revision = unavailable + } + for id in lock.components.keys where lock.components[id]!.revision != nil { + lock.components[id]!.revision = unavailable + } + try fixture.store().save(declaration: fixture.store().loadDeclaration(), ledger: lock) try Data("custom".utf8).write(to: fixture.target("one").appendingPathComponent("SKILL.md")) let bytes = try Data(contentsOf: fixture.store().resolvedURL) #expect(throws: (any Error).self) { @@ -97,9 +105,21 @@ struct PublicLifecycleTests { try fixture.skill("demo", body: "A") try fixture.commit() _ = try fixture.add() - var lock = try fixture.store().loadResolved() - lock.skills["demo"]?.installs["cursor"] = .copy - try fixture.store().save(declaration: fixture.store().loadDeclaration(), resolved: lock) + var lock = try fixture.store().loadLedger() + var deployment = try #require(lock.deployments.first { $0.route == "agents/skill@1" }) + var lowering = try #require(lock.lowerings.first { $0.deployments.contains(deployment.id) }) + let id = deployment.id + ":cursor" + deployment.id = id + deployment.target.root = "skills-cursor" + deployment.recipients = [.cursor] + lowering.id = id + lowering.deployments = [id] + lowering.layout.object?["mode"] = .init("copy") + lowering.layout.object?["name"] = .init(id) + for index in lowering.artifacts.indices { lowering.artifacts[index].name = id } + lock.deployments.append(deployment) + lock.lowerings.append(lowering) + try fixture.store().save(declaration: fixture.store().loadDeclaration(), ledger: lock) let bytes = try fixture.stateAndTargetBytes() #expect(throws: (any Error).self) { try SkillOperations.installResolvedReport(environment: fixture.environment) diff --git a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift index 22c9f2f..89c40ea 100644 --- a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift +++ b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift @@ -1,6 +1,7 @@ import AgentsInstructions import AgentsManifest import AgentsSkills +import AgentsUpdates import CPlatform import Foundation import StateTestSupport diff --git a/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift b/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift index 4ba46cd..2d732e2 100644 --- a/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift @@ -1,4 +1,5 @@ import AgentsManifest +import AgentsUpdates import Foundation import Testing diff --git a/Tests/AgentsSkillsTests/SkillLifecycleTests.swift b/Tests/AgentsSkillsTests/SkillLifecycleTests.swift index 5e3b91d..bc800ae 100644 --- a/Tests/AgentsSkillsTests/SkillLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/SkillLifecycleTests.swift @@ -1,6 +1,8 @@ import AgentsCore import AgentsManifest +import AgentsUpdates import Foundation +import StateTestSupport import Testing @testable import AgentsSkills @@ -158,7 +160,9 @@ struct SkillLifecycleTests { @Test( arguments: [StateStore.declarationFileName, StateStore.resolvedFileName], ["add", "update", "install", "remove"]) - func corruptStateStopsEveryMutation(_ filename: String, _ operation: String) throws { + func corruptStateStopsDeclarationEditsAndInvalidLedgerStopsRestore( + _ filename: String, _ operation: String + ) throws { let fixture = try SkillFixture() try fixture.skill("demo", body: "A") try fixture.commit() @@ -166,6 +170,11 @@ struct SkillLifecycleTests { let corrupt = fixture.store().directory.appendingPathComponent(filename) try Data("{broken".utf8).write(to: corrupt) let before = try fixture.stateAndTargetBytes() + if filename == StateStore.declarationFileName && operation == "install" { + _ = try SkillOperations.installResolvedReport(environment: fixture.environment) + #expect(try fixture.stateAndTargetBytes() == before) + return + } #expect(throws: (any Error).self) { switch operation { case "add": _ = try fixture.add() diff --git a/Tests/AgentsSkillsTests/SourceAliasTests.swift b/Tests/AgentsSkillsTests/SourceAliasTests.swift index bd49f72..942d411 100644 --- a/Tests/AgentsSkillsTests/SourceAliasTests.swift +++ b/Tests/AgentsSkillsTests/SourceAliasTests.swift @@ -1,6 +1,7 @@ import AgentsCore import AgentsManifest import AgentsSkills +import AgentsUpdates import Foundation import Testing diff --git a/Tests/AgentsSkillsTests/SourceShorthandTests.swift b/Tests/AgentsSkillsTests/SourceShorthandTests.swift index adf8f0e..3565faf 100644 --- a/Tests/AgentsSkillsTests/SourceShorthandTests.swift +++ b/Tests/AgentsSkillsTests/SourceShorthandTests.swift @@ -1,7 +1,9 @@ import AgentsCore import AgentsManifest import AgentsSkills +import AgentsUpdates import Foundation +import StateTestSupport import Testing @Suite("Typed source shorthand") diff --git a/Tests/AgentsSkillsTests/TransactionDoctorTests.swift b/Tests/AgentsSkillsTests/TransactionDoctorTests.swift index 4747e54..b60e0b0 100644 --- a/Tests/AgentsSkillsTests/TransactionDoctorTests.swift +++ b/Tests/AgentsSkillsTests/TransactionDoctorTests.swift @@ -1,7 +1,9 @@ import AgentsInstructions import AgentsManifest import AgentsSkills +import AgentsUpdates import Foundation +import StateTestSupport import Testing @testable import AgentsCore diff --git a/Tests/AgentsSkillsTests/UnmanagedTargetTests.swift b/Tests/AgentsSkillsTests/UnmanagedTargetTests.swift index 14233b3..359d5e0 100644 --- a/Tests/AgentsSkillsTests/UnmanagedTargetTests.swift +++ b/Tests/AgentsSkillsTests/UnmanagedTargetTests.swift @@ -1,3 +1,4 @@ +import AgentsUpdates import Foundation import Testing diff --git a/Tests/AgentsSkillsTests/UpdateReportingTests.swift b/Tests/AgentsSkillsTests/UpdateReportingTests.swift index 7f3e189..8db02bf 100644 --- a/Tests/AgentsSkillsTests/UpdateReportingTests.swift +++ b/Tests/AgentsSkillsTests/UpdateReportingTests.swift @@ -1,5 +1,7 @@ import AgentsManifest +import AgentsUpdates import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -92,64 +94,6 @@ struct UpdateReportingTests { #expect(try !flag(file)) } - @Test(arguments: ["prepared", "cached", "staged"]) - func rejectsModeDisagreementBeforePublication(_ kind: String) throws { - let fixture = try SkillFixture() - try fixture.skill("demo", body: "same") - try fixture.commit() - _ = try fixture.add(mode: .copy) - let store = fixture.store() - let before = try fixture.stateAndTargetBytes() - try store.withLock { - let resolutions = try SourceResolutionSession(store: store) - let plan = try SkillOperations.prepareUpdate( - store: store, declaration: store.readDeclaration(), previous: store.readResolved(), - resolutions: resolutions) - if kind == "prepared" { - let lifecycle = try SkillLifecycle(store: store, provider: WellKnownProvider()) - let source = try lifecycle.discover( - store.readDeclaration().sources["fixture"]!, live: false, fullDepth: true) - let prepared = try lifecycle.prepare( - source.skills[0], in: source, - declaration: SkillDeclaration(select: .all, mode: .copy), defaultAgents: [.codex]) - try FileManager.default.setAttributes( - [.posixPermissions: 0o755], - ofItemAtPath: prepared.directory.appendingPathComponent("SKILL.md").path) - #expect(throws: CoreError.self) { try lifecycle.validate(prepared, name: "demo") } - } else if kind == "cached" { - let record = try #require(plan.next.skills["demo"]) - let path = SourceCache(store: store).materializedURL( - sourceID: record.source, revision: record.revision! - ) - .appendingPathComponent("skills/demo/SKILL.md") - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: path.path) - #expect(throws: CoreError.self) { try plan.retain() } - } else { - let retained = try plan.retain() - let transaction = FileTransaction(store: store) { step in - if step == TransactionCheckpoint.stage(0, .constructed).name { - let parent = fixture.target("demo").deletingLastPathComponent() - let staged = try #require( - FileManager.default.contentsOfDirectory( - at: parent, - includingPropertiesForKeys: nil - ).first { $0.lastPathComponent.hasPrefix(".agents-") } - ) - .appendingPathComponent(TransactionSlot.exchanged.name(0)) - try FileManager.default.setAttributes( - [.posixPermissions: 0o755], - ofItemAtPath: staged.appendingPathComponent("SKILL.md").path) - } - } - try plan.stage(retained: retained, transaction: transaction) - #expect(throws: CoreError.invalidState("staged content executable mode mismatch")) { - try transaction.commit() - } - } - } - #expect(try fixture.stateAndTargetBytes() == before) - } - @Test(arguments: [[AgentID.codex, .claudeCode], [.codex, .cursor]]) func liveMembershipAndLostLockPreserveOwnership(_ agents: [AgentID]) throws { let fixture = try SkillFixture() diff --git a/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift b/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift index 3dc6430..d936d3a 100644 --- a/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift +++ b/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift @@ -1,7 +1,9 @@ import AgentsCore import AgentsManifest import AgentsSkills +import AgentsUpdates import Foundation +import StateTestSupport import Testing @Suite("Watch subscriptions") diff --git a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift index 83e8269..bbaa515 100644 --- a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift +++ b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift @@ -2,6 +2,7 @@ import AgentsInstructions import AgentsManifest import AgentsSkills import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -60,7 +61,12 @@ struct CombinedUpdateTests { 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.apply() } throws: { error in + guard let failure = error as? UpdateApplyError, case .unchanged = failure.disposition, + let underlying = failure.underlyingError as? InstructionError + else { return false } + return underlying == .unownedTargets(["GEMINI.md"]) + } #expect(try fixture.snapshot() == before) #expect(try fixture.bytes(fixture.instruction(.geminiCLI)) == Data("Hand written.\n".utf8)) } @@ -75,7 +81,7 @@ struct CombinedUpdateTests { try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) let before = try fixture.snapshot() var called = false - #expect(throws: CoreError.invalidState("edit installs must be local, unpinned live links")) { + #expect(throws: CoreError.self) { try InstructionOperations.updateInstalled( environment: fixture.environment, apply: apply, beforeApply: { _ in called = true }) } @@ -97,7 +103,7 @@ struct CombinedUpdateTests { try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) let before = try fixture.snapshot() var called = false - #expect(throws: CoreError.invalidState("edit installs must be local, unpinned live links")) { + #expect(throws: CoreError.self) { try SkillOperations.updateInstalled( environment: fixture.environment, skillNames: ["demo"], apply: apply, beforeApply: { _ in called = true }) diff --git a/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift b/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift new file mode 100644 index 0000000..14e8cff --- /dev/null +++ b/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift @@ -0,0 +1,396 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsUpdates + +@Suite("Ledger lifecycle composition") +struct LifecycleCompositionTests { + @Test(arguments: [InstallMode.copy, .link]) + func exactColdRestoreKeepsFrozenOwnInstructionsAndSkillResources(_ mode: InstallMode) throws { + let fixture = try UpdateFixture() + let source = fixture.root.appendingPathComponent("local-skills") + try fixture.write( + "---\nname: frozen\ndescription: Frozen\n---\nOriginal skill\n", + to: source.appendingPathComponent("frozen/SKILL.md")) + let script = source.appendingPathComponent("frozen/run") + try fixture.write("#!/bin/sh\nexit 0\n", to: script) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: script.path) + try fixture.write( + "---\ndescription: Frozen\n---\n# Frozen\n\nOriginal instructions\n", + to: fixture.root.appendingPathComponent(".agent/instructions/frozen.md")) + try fixture.store.save( + declaration: Declaration( + sources: ["local": .init(kind: .local, location: source.path)], + skills: ["local": .init(select: .all, agents: [.claudeCode], mode: mode)], + instructions: .init(agents: [.codex], sections: ["frozen"])), resolved: ResolvedState()) + _ = try fixture.apply() + let instruction = try fixture.bytes(fixture.instruction()) + let skill = try fixture.bytes( + fixture.target(.claudeCode).deletingLastPathComponent().appendingPathComponent( + "frozen/SKILL.md")) + let cold = fixture.root.appendingPathComponent("cold") + var environment = fixture.environment + environment.projectDirectory = cold + let store = StateStore(scope: .project, environment: environment) + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + try fixture.bytes(fixture.store.declarationURL).write(to: store.declarationURL) + let locked = try fixture.bytes(fixture.store.resolvedURL) + try locked.write(to: store.resolvedURL) + try FileManager.default.removeItem(at: source) + try FileManager.default.removeItem( + at: fixture.root.appendingPathComponent(".agent/instructions")) + _ = try UpdateOperations.restore(environment: environment) + #expect(try Data(contentsOf: cold.appendingPathComponent("AGENTS.md")) == instruction) + let restored = cold.appendingPathComponent(".claude/skills/frozen") + #expect(try Data(contentsOf: restored.appendingPathComponent("SKILL.md")) == skill) + let flags = + try FileManager.default.attributesOfItem(atPath: restored.appendingPathComponent("run").path)[ + .posixPermissions] as? NSNumber + #expect((flags?.intValue ?? 0) & 0o111 != 0) + #expect(try Data(contentsOf: store.resolvedURL) == locked) + #expect( + try store.loadResolved().skills["frozen"]?.installs == [AgentID.claudeCode.rawValue: mode]) + } + + @Test func purePreviewAndStableFingerprintUseNoPersistentSourceWrites() throws { + let fixture = try UpdateFixture() + try fixture.declare(agents: [.claudeCode]) + let before = try FileHash.folderHash(fixture.root) + let first = try fixture.preview() + let second = try fixture.preview() + #expect(first.displayedFingerprint == second.displayedFingerprint) + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + _ = try fixture.apply() + let installed = try FileHash.folderHash(fixture.root) + let request = UpdateRequest(operation: .restore) + let a = try UpdateOperations.preview(request, environment: fixture.environment) + let b = try UpdateOperations.preview(request, environment: fixture.environment) + #expect(a.displayedFingerprint == b.displayedFingerprint) + #expect(try FileHash.folderHash(fixture.root) == installed) + #expect(try JSONSerialization.jsonObject(with: JSONEncoder().encode(a)) is [String: Any]) + } + + @Test func directSkillPinUpdatePreservesRecordedInstructionPinAndLastRemovalRetention() throws { + let fixture = try UpdateFixture() + try fixture.install(agents: [.claudeCode]) + let old = try fixture.store.loadResolved() + let bytes = try fixture.bytes(fixture.instruction(.claudeCode)) + try fixture.advance() + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + let updated = try fixture.store.loadResolved() + #expect(updated.skills["demo"]?.revision != old.skills["demo"]?.revision) + #expect(updated.instructions == old.instructions) + #expect(try fixture.bytes(fixture.instruction(.claudeCode)) == bytes) + _ = try SkillOperations.watchOperations().add("fixture", environment: fixture.environment) + _ = try SkillOperations.remove(skillNames: ["demo"], environment: fixture.environment) + #expect(try SkillOperations.listManaged(environment: fixture.environment).isEmpty) + #expect(try fixture.store.loadResolved().instructions == old.instructions) + #expect(try fixture.bytes(fixture.instruction(.claudeCode)) == bytes) + _ = try SkillOperations.watchOperations().status(environment: fixture.environment) + _ = try SkillOperations.doctor(environment: fixture.environment) + _ = try InstructionOperations.doctor(environment: fixture.environment) + _ = try InstructionOperations.renderChatGPT(prompt: "weekly", environment: fixture.environment) + _ = try InstructionOperations.installResolvedReport(environment: fixture.environment) + } + + @Test func nativeSiblingsStayPrivateAndEqualUnmanagedValuesAreNotAdopted() throws { + let fixture = try UpdateFixture() + let declaration = Declaration(components: [ + .mcpServer( + name: "server", transport: .stdio(.init(executable: "fixture-server")), + agents: [.claudeCode]) + ]) + try fixture.store.save(declaration: declaration, resolved: ResolvedState()) + let native = fixture.root.appendingPathComponent(".mcp.json") + try fixture.write("{\"unmanaged\":{\"secret\":\"private sibling sentinel\"}}\n", to: native) + let report = try fixture.preview() + #expect( + !String(decoding: try JSONEncoder().encode(report), as: UTF8.self).contains( + "private sibling sentinel")) + _ = try fixture.apply() + let owned = try fixture.bytes(native) + #expect(String(decoding: owned, as: UTF8.self).contains("private sibling sentinel")) + let original = try fixture.preview().displayedFingerprint + try fixture.write( + String(decoding: owned, as: UTF8.self).replacingOccurrences( + of: "private sibling sentinel", with: "rotated private sibling"), to: native) + #expect(try fixture.preview().displayedFingerprint == original) + try UpdateOperations.withPreparedUpdate(environment: fixture.environment) { prepared in + try fixture.write(String(decoding: owned, as: UTF8.self), to: native) + #expect(throws: UpdateApplyError.self) { try prepared.apply() } + } + try FileManager.default.removeItem(at: fixture.store.resolvedURL) + let before = try FileHash.folderHash(fixture.root) + #expect(throws: (any Error).self) { try fixture.preview() } + #expect(try FileHash.folderHash(fixture.root) == before) + } + + @Test func combinedFaultRollsBackSkillInstructionAndNativeOwnedKey() throws { + let fixture = try UpdateFixture() + try fixture.declare(agents: [.claudeCode]) + var declaration = try fixture.store.loadDeclaration() + declaration.components.append( + .mcpServer( + name: "server", transport: .stdio(.init(executable: "before")), agents: [.claudeCode])) + try fixture.store.save(declaration: declaration, resolved: ResolvedState()) + _ = try fixture.apply() + let native = fixture.root.appendingPathComponent(".mcp.json") + let oldNative = try fixture.bytes(native) + let before = try fixture.snapshot() + try fixture.advance() + declaration.components[declaration.components.count - 1] = .mcpServer( + name: "server", transport: .stdio(.init(executable: "after")), agents: [.claudeCode]) + try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + let state = try fixture.snapshot() + struct Interrupted: Error {} + var interrupted = false + #expect(throws: UpdateApplyError.self) { + try UpdateOperations.withPreparedUpdate( + environment: fixture.environment, + checkpoint: { _ in + if !interrupted, (try? fixture.bytes(native)) != oldNative { + interrupted = true + throw Interrupted() + } + }, { try $0.apply() }) + } + #expect(interrupted) + #expect(try fixture.snapshot() == state) + #expect(try fixture.bytes(native) == oldNative) + #expect( + before[fixture.instruction(.claudeCode).path] == state[fixture.instruction(.claudeCode).path]) + _ = try fixture.apply() + #expect(try fixture.bytes(native) != oldNative) + } +} + +private final class FixtureBindings: RuntimeBindingProvider { + var calls = 0 + var value = "private literal sentinel" + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + calls += 1 + return Data(value.utf8) + } +} + +extension LifecycleCompositionTests { + @Test func literalBindingsStayInsidePrivateStagingAndDoNotChangeDisplayIdentity() throws { + let fixture = try UpdateFixture() + try fixture.store.save( + declaration: Declaration(components: [ + .mcpServer( + name: "bound", + transport: .stdio( + .init(executable: "fixture-server", environment: ["TOKEN": .secret("fixture-token")])), + agents: [.claudeCode]) + ]), resolved: ResolvedState()) + var environment = fixture.environment + environment.environment["CLAUDE_CONFIG_DIR"] = nil + let provider = FixtureBindings() + let request = UpdateRequest() + try UpdateOperations.prepare( + request, scope: .project, environment: environment, checkpoint: { _ in }, + provider: provider, + { prepared in + #expect(provider.calls == 0) + let json = String(decoding: try JSONEncoder().encode(prepared.report), as: UTF8.self) + #expect(!json.contains(provider.value)) + _ = try prepared.apply() + }) + #expect(provider.calls == 1) + let native = environment.homeDirectory.appendingPathComponent(".claude.json") + #expect(String(decoding: try fixture.bytes(native), as: UTF8.self).contains(provider.value)) + #expect( + !String(decoding: try fixture.bytes(fixture.store.resolvedURL), as: UTF8.self).contains( + provider.value)) + let a = try UpdateOperations.preview(environment: environment).displayedFingerprint + provider.value = "rotated private literal" + try UpdateOperations.prepare( + request, scope: .project, environment: environment, checkpoint: { _ in }, + provider: provider, + { prepared in + #expect(prepared.report.displayedFingerprint == a) + #expect(provider.calls == 1) + _ = try prepared.apply() + }) + #expect(provider.calls == 2) + #expect(try UpdateOperations.preview(environment: environment).displayedFingerprint == a) + let mode = + try FileManager.default.attributesOfItem(atPath: native.path)[.posixPermissions] as? NSNumber + #expect(mode?.intValue == 0o600) + } + + @Test func producerOwnedSkillCannotBeRemovedAndChangedProtectedGroupRequiresCombinedUpdate() + throws + { + let fixture = try UpdateFixture() + try fixture.write( + """ + version: 1 + components: [] + groups: + skills: + components: [{kind: skills, source: ., select: [demo], mode: copy, agents: [claude-code]}] + tools: + components: [{kind: mcpServer, name: server, transport: {kind: stdio, executable: before}, agents: [claude-code]}] + exports: [skills, tools] + """, to: fixture.repo.appendingPathComponent(".agent/agents.yaml")) + try fixture.commit() + try fixture.write( + """ + version: 1 + sources: + producer: {path: \(fixture.repo.path)} + uses: + - {source: producer, group: skills} + - {source: producer, group: tools} + """, to: fixture.store.declarationURL) + _ = try fixture.apply() + let before = try fixture.snapshot() + #expect(throws: (any Error).self) { + try SkillOperations.remove(skillNames: ["demo"], environment: fixture.environment) + } + #expect(try fixture.snapshot() == before) + let manifest = fixture.repo.appendingPathComponent(".agent/agents.yaml") + let changed = try String(contentsOf: manifest, encoding: .utf8).replacingOccurrences( + of: "executable: before", with: "executable: after") + try fixture.write(changed, to: manifest) + try fixture.writeSource("new producer skill") + try fixture.commit() + do { + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + Issue.record("protected producer group was changed by skill-only update") + } catch let error as CoreError { + #expect(error.description.contains("requiresCombinedUpdate")) + } + #expect(try fixture.snapshot() == before) + } + + @Test func completeYAMLEditPreservesUnusedIntentAndChangesItsDisplayIdentity() throws { + let fixture = try UpdateFixture() + try fixture.write( + """ + # retained preamble + version: 1 + components: + - {kind: mcpServer, name: inactive, transport: {kind: stdio, executable: fixture}, agents: [], native: {claude-code: {value: !!float 1.00}}} + groups: + unused: + components: [{kind: ignore, name: unused, patterns: [build], condition: {platforms: []}}] + """, to: fixture.store.declarationURL) + let before = try fixture.bytes(fixture.store.declarationURL) + let a = try fixture.preview().displayedFingerprint + let document = try #require(try fixture.store.loadManifest()) + let request = UpdateRequest( + operation: .edit([.setDefaultAgents([.claudeCode])]), + expectedDeclarationDigest: document.digest) + _ = try UpdateOperations.withPreparedUpdate(request, environment: fixture.environment) { + try $0.apply() + } + let after = try fixture.bytes(fixture.store.declarationURL) + let text = String(decoding: after, as: UTF8.self) + #expect(text.contains("# retained preamble") && text.contains("!!float 1.00")) + #expect(text.contains("unused:") && text.contains("platforms: []")) + #expect(after != before) + #expect(try fixture.preview().displayedFingerprint != a) + #expect(try fixture.store.loadDeclaration().groups.count == 1) + } +} + +extension LifecycleCompositionTests { + @Test func nonGitSeparateGroupsSharingAProducerProtectActualNativeSemantics() throws { + let fixture = try UpdateFixture() + let producer = fixture.root.appendingPathComponent("producer") + try fixture.write( + "---\nname: demo\ndescription: Local\n---\nBefore\n", + to: producer.appendingPathComponent("skills/demo/SKILL.md")) + try fixture.write( + """ + version: 1 + groups: + skills: + components: [{kind: skills, source: ., select: [demo], mode: copy, agents: [claude-code]}] + tools: + components: [{kind: mcpServer, name: stable, transport: {kind: stdio, executable: fixture-server}, agents: [claude-code]}] + exports: [skills, tools] + """, to: producer.appendingPathComponent(".agent/agents.yaml")) + try fixture.write( + """ + version: 1 + sources: {producer: {path: \(producer.path)}} + uses: [{source: producer, group: skills}, {source: producer, group: tools}] + """, to: fixture.store.declarationURL) + _ = try fixture.apply() + let native = fixture.root.appendingPathComponent(".mcp.json") + let bytes = try fixture.bytes(native) + try fixture.write( + "---\nname: demo\ndescription: Local\n---\nAfter\n", + to: producer.appendingPathComponent("skills/demo/SKILL.md")) + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(try fixture.bytes(native) == bytes) + #expect( + String( + decoding: try fixture.bytes(fixture.target(.claudeCode).appendingPathComponent("SKILL.md")), + as: UTF8.self + ).contains("After")) + } +} + +extension LifecycleCompositionTests { + @Test func sameSkillNameFromDisjointSourcesKeepsSeparatePublicInventoryAndReport() throws { + let fixture = try UpdateFixture() + let second = fixture.root.appendingPathComponent("second") + try fixture.write( + "---\nname: demo\ndescription: Other\n---\nSecond\n", + to: second.appendingPathComponent("skills/demo/SKILL.md")) + try fixture.store.save( + declaration: Declaration( + sources: [ + "first": .init(kind: .local, location: fixture.repo.path), + "second": .init(kind: .local, location: second.path), + ], + components: [ + .skills(source: "first", .init(select: .all, agents: [.codex], mode: .copy)), + .skills(source: "second", .init(select: .all, agents: [.claudeCode], mode: .copy)), + ]), resolved: ResolvedState()) + let report = try fixture.preview() + #expect(report.skills.count == 2) + #expect(Set(report.skills.map(\.sourceIdentity)).count == 2) + _ = try fixture.apply() + let inventory = try SkillOperations.listManaged(environment: fixture.environment) + #expect(Set(inventory.compactMap(\.sourceIdentity)).count == 2) + #expect(Set(inventory.map(\.agent)) == [.codex, .claudeCode]) + #expect( + try fixture.store.loadLedger().components.values.filter { $0.kind == "skills" }.count == 2) + } +} + +extension LifecycleCompositionTests { + @Test func forwardingSiblingsStayPrivateWhileFreshnessRemainsStrict() throws { + let fixture = try UpdateFixture() + try fixture.declare(agents: [.claudeCode]) + let file = fixture.root.appendingPathComponent("CLAUDE.md") + try fixture.write("# Private sibling sentinel\n", to: file) + let report = try fixture.preview() + #expect( + !String(decoding: try JSONEncoder().encode(report), as: UTF8.self).contains( + "Private sibling sentinel")) + _ = try fixture.apply() + let before = try fixture.bytes(file) + let fingerprint = try fixture.preview().displayedFingerprint + try fixture.write( + String(decoding: before, as: UTF8.self).replacingOccurrences( + of: "Private sibling sentinel", with: "Rotated sibling"), to: file) + #expect(try fixture.preview().displayedFingerprint == fingerprint) + try UpdateOperations.withPreparedUpdate(environment: fixture.environment) { update in + try before.write(to: file) + #expect(throws: UpdateApplyError.self) { try update.apply() } + } + } +} diff --git a/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift b/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift index f0d5aaf..9bdd662 100644 --- a/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift +++ b/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift @@ -3,39 +3,13 @@ import AgentsInstructions import AgentsManifest import AgentsSkills import Foundation +import StateTestSupport import Testing @testable import AgentsUpdates @Suite("Semantic requirement updates") struct RequirementUpdateTests { - @Test func sourceMergingAcceptsEqualRangesAndRejectsDifferentRootsAndRequirements() throws { - let old = LockedSource( - kind: .git, url: "https://example.org/team.git", requirement: .branch("main")) - var legacy = old - legacy.requirement = .range(from: "v1.2.0+lower", to: "2.0.0+upper") - let canonical = LockedSource( - kind: .git, url: "ssh://user@EXAMPLE.org/team", requirement: .upToNextMajor(from: "1.2.0")) - let merged = try UpdatePlan.mergedSources( - previous: ["id": old], skills: ["id": legacy], instructions: ["id": canonical]) - #expect(merged["id"] == canonical) - let unchanged = try UpdatePlan.mergedSources( - previous: ["id": legacy], skills: ["id": canonical], instructions: ["id": legacy]) - #expect(unchanged["id"]?.requirement == legacy.requirement) - var different = canonical - different.path = "other" - #expect(throws: CoreError.self) { - try UpdatePlan.mergedSources( - previous: ["id": old], skills: ["id": legacy], instructions: ["id": different]) - } - different = canonical - different.requirement = .upToNextMinor(from: "1.2.0") - #expect(throws: CoreError.self) { - try UpdatePlan.mergedSources( - previous: ["id": old], skills: ["id": legacy], instructions: ["id": different]) - } - } - @Test func skillInstructionAndCombinedUpdatesKeepPinsAndOriginalLedgerBytes() throws { let fixture = try UpdateFixture() try fixture.git(["tag", "1.2.0"]) @@ -50,13 +24,13 @@ struct RequirementUpdateTests { var object = try #require( JSONSerialization.jsonObject(with: fixture.bytes(fixture.store.resolvedURL)) as? [String: Any] ) - var sources = try #require(object["sources"] as? [String: [String: Any]]) - let id = try #require(sources.keys.first) - sources[id]?["requirement"] = ["from": "v1.2.0+lower", "to": "2.0.0+upper"] - object["sources"] = sources - let legacyBytes = try JSONSerialization.data( + var sourceUses = try #require(object["sourceUses"] as? [[String: Any]]) + let id = try #require(sourceUses.indices.first { sourceUses[$0]["requirement"] != nil }) + sourceUses[id]["requirement"] = ["from": "v1.2.0+lower", "to": "2.0.0+upper"] + object["sourceUses"] = sourceUses + let recordedBytes = try JSONSerialization.data( withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes]) - try legacyBytes.write(to: fixture.store.resolvedURL) + try recordedBytes.write(to: fixture.store.resolvedURL) let beforeAttributes = try FileManager.default.attributesOfItem( atPath: fixture.store.resolvedURL.path) #expect(try !fixture.preview().hasChanges) @@ -67,7 +41,7 @@ struct RequirementUpdateTests { #expect(!instructions.hasChanges) let combined = try fixture.apply() #expect(!combined.report.hasChanges) - #expect(try fixture.bytes(fixture.store.resolvedURL) == legacyBytes) + #expect(try fixture.bytes(fixture.store.resolvedURL) == recordedBytes) #expect(try fixture.store.loadResolved() == original) let afterAttributes = try FileManager.default.attributesOfItem( atPath: fixture.store.resolvedURL.path) @@ -80,15 +54,15 @@ struct RequirementUpdateTests { agents: [.codex], environment: fixture.environment, apply: true) #expect(intentOnly.hasChanges) #expect(try fixture.store.loadDeclaration().instructions?.agents == [.codex]) - #expect(try fixture.bytes(fixture.store.resolvedURL) == legacyBytes) + #expect(try fixture.bytes(fixture.store.resolvedURL) == recordedBytes) try fixture.advance() try fixture.git(["tag", "1.3.0"]) _ = try fixture.apply() let changed = try fixture.bytes(fixture.store.resolvedURL) - #expect(changed != legacyBytes) + #expect(changed != recordedBytes) let rewritten = try #require(JSONSerialization.jsonObject(with: changed) as? [String: Any]) - let rewrittenSources = try #require(rewritten["sources"] as? [String: [String: Any]]) - #expect(rewrittenSources[id]?["requirement"] as? [String: String] == ["from": "1.2.0+lower"]) + let rewrittenSources = try #require(rewritten["sourceUses"] as? [[String: Any]]) + #expect(rewrittenSources[id]["requirement"] as? [String: String] == ["from": "1.2.0"]) #expect( try fixture.store.loadResolved().skills["demo"]?.revision == fixture.git(["rev-parse", "HEAD"])) diff --git a/Tests/AgentsUpdatesTests/UpdateFixture.swift b/Tests/AgentsUpdatesTests/UpdateFixture.swift index 7ae5177..8e8c625 100644 --- a/Tests/AgentsUpdatesTests/UpdateFixture.swift +++ b/Tests/AgentsUpdatesTests/UpdateFixture.swift @@ -4,6 +4,7 @@ import AgentsManifest import AgentsSkills import AgentsUpdates import Foundation +import StateTestSupport import Testing final class UpdateFixture { diff --git a/Tests/StateTestProcess/PrivateMaterializationProbe.swift b/Tests/StateTestProcess/PrivateMaterializationProbe.swift index f7194b0..8458032 100644 --- a/Tests/StateTestProcess/PrivateMaterializationProbe.swift +++ b/Tests/StateTestProcess/PrivateMaterializationProbe.swift @@ -1,6 +1,7 @@ import AgentsCore import AgentsInstructions import AgentsSkills +import AgentsUpdates import Foundation func privateMaterializationProbe( diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 88a54a6..f3595cd 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -312,21 +312,26 @@ if arguments[2].hasPrefix("ledger-") { || arguments[2] == "cache-bytes" { let cache = SourceCache(store: store) { try stop($0) } - let lock = try store.readResolved() - guard let skill = lock.skills["demo"], let hash = skill.hash else { - throw CoreError.invalidState("missing fixture skill") + let ledger = try store.readLedger() + guard let resource = ledger.resources["resource"], + let source = ledger.sources[resource.source] + else { + throw CoreError.invalidState("missing fixture resource") } - if arguments[2] == "cache-content", let artifact = skill.artifact { + if arguments[2] == "cache-content", let artifact = resource.artifact { _ = try cache.materializeArtifact( - root.appendingPathComponent("new"), digest: artifact.digest, hash: hash) - } else if arguments[2] == "cache-bytes", let artifact = skill.artifact { + root.appendingPathComponent("new"), digest: artifact.digest, hash: resource.hash) + } else if arguments[2] == "cache-bytes", let artifact = resource.artifact { _ = try cache.storeArtifact( Data(contentsOf: root.appendingPathComponent("payload")), digest: artifact.digest) - } else if let revision = skill.revision, let source = lock.sources[skill.source] { - _ = try cache.materialize(sourceID: skill.source, source: source, revision: revision) + } else if let location = source.location { + let identity = "local:" + (try location.resolve(roots: store.ledgerRoots).path) + _ = try cache.materialize( + sourceID: identity, source: LockedSource(kind: .local), revision: source.revision) } else { throw CoreError.invalidState("missing fixture pin") } + } else if arguments[2] == "inspection-transaction" { let transaction = FileTransaction(store: store) { try stop($0) } try transaction.replace( @@ -340,7 +345,9 @@ if arguments[2].hasPrefix("ledger-") { with: .data(Data("New instructions\n".utf8))) try transaction.replace( store.declarationURL, with: .data(manifestText("defaultAgents: [\"cursor\"]\n"))) - try transaction.replace(store.resolvedURL, with: .data(StateStore.encode(ResolvedState()))) + try transaction.replace( + store.resolvedURL, + with: .data(try ResolvedLedgerCodec.encode(ResolvedLedger(), limits: .standard))) try transaction.commit() } else if arguments[2] == "watch-crash" { let baseline = try StatePrecondition(store: store) diff --git a/Tests/StateTestSupport/DeclarationStateFixture.swift b/Tests/StateTestSupport/DeclarationStateFixture.swift new file mode 100644 index 0000000..3759858 --- /dev/null +++ b/Tests/StateTestSupport/DeclarationStateFixture.swift @@ -0,0 +1,57 @@ +import AgentsCore +import AgentsManifest +import Foundation + +extension StateStore { + package func save(declaration: Declaration, resolved: ResolvedState, watch: WatchState? = nil) + throws + { + try withLock { + try declaration.validate(environment: environment) + try resolved.validate() + try watch?.validate() + let baseline = try StatePrecondition(store: self) + let previous = try readDeclaration(prepared: baseline) + var change = try planDeclaration(declaration, replacing: previous, prepared: baseline) + if change == nil, try declarationBytes(prepared: baseline) == nil { + change = DeclarationChange(bytes: Data("version: 1\n".utf8)) + } + let transaction = FileTransaction(store: self) + transaction.requireUnchanged(since: baseline) + try stageDeclaration(change, in: transaction, prepared: baseline) + let existing = try readLedger(prepared: baseline) + let view = try existing.domainProjection(roots: ledgerRoots) + guard resolved == ResolvedState() || view == resolved + else { + throw CoreError.invalidState("fixture must seed an explicit resolved ledger") + } + let ledger = resolved == ResolvedState() ? ResolvedLedger() : existing + try stageLedger(ledger, limits: .standard, transaction: transaction, prepared: baseline) + if let watch { + try transaction.replace( + watchURL, with: .data(StateStore.encode(watch)), + expecting: baseline.evidence(for: watchURL)) + } + try transaction.commit() + } + } + +} + +extension StateStore { + package func save(declaration: Declaration, ledger: ResolvedLedger) throws { + try withLock { + let baseline = try StatePrecondition(store: self) + let previous = try readDeclaration(prepared: baseline) + let change = + try planDeclaration(declaration, replacing: previous, prepared: baseline) + ?? (try declarationBytes(prepared: baseline) == nil + ? DeclarationChange(bytes: Data("version: 1\n".utf8)) : nil) + let transaction = FileTransaction(store: self) + transaction.requireUnchanged(since: baseline) + try stageDeclaration(change, in: transaction, prepared: baseline) + try stageLedger(ledger, limits: .standard, transaction: transaction, prepared: baseline) + try transaction.commit() + } + } +} From 3e3158289f026e58daf0f382f6b7b323a532258e Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:41:59 +0800 Subject: [PATCH 074/171] fix: preserve read-only and recorded target boundaries --- Sources/AgentsCore/FileTransaction.swift | 6 +- .../AgentsCore/NativeTargetCoordination.swift | 61 ++++++- .../AgentsCore/PrivateMaterialization.swift | 18 ++- Sources/AgentsCore/TransactionPaths.swift | 32 +++- .../RegisteredNativeTargetTests.swift | 150 ++++++++++++++++++ 5 files changed, 257 insertions(+), 10 deletions(-) diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index ef039e2..2277526 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -101,7 +101,11 @@ package final class FileTransaction { guard prepared.target.scope.path == store.directory.path, prepared.owner == geteuid(), bindings.allSatisfy({ !$0.isEmpty && !$0.contains("\0") }) else { throw CoreError.invalidState("invalid private materialization inputs") } - try prepared.receiptEvidence.validate() + guard let receiptEvidence = prepared.receiptEvidence else { + throw CoreError.invalidState( + "private publication requires an existing admitted native parent") + } + try receiptEvidence.validate() let (path, evidence, previous) = try request(prepared.target.url, expecting: prepared.evidence) guard path == prepared.target.path else { throw CoreError.invalidState("materialization registration changed") diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index 8cc41cc..3101b64 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -339,6 +339,34 @@ final class SharedResource { } } +/// Absence has no physical resource key. Only read admission may carry this evidence; +/// a writer must create and open the real parent before deriving its coordination domain. +struct AbsentSharedRoot { + let route: NativeTargetRoute + let logical: URL + let physical: URL + let ancestry: DirectoryAccessEvidence + + init?(store: StateStore, route: NativeTargetRoute) throws { + logical = try route.logicalDirectory(store.environment) + physical = logical.resolvingSymlinksInPath() + ancestry = try DirectoryAccessEvidence.capture(at: physical) + guard ancestry.directories.count < physical.pathComponents.count else { return nil } + self.route = route + } + + func remainsAbsent() throws -> Bool { + guard logical.resolvingSymlinksInPath().path == physical.path else { + throw CoreError.invalidState("registered native root changed during inspection") + } + let current = try DirectoryAccessEvidence.capture(at: physical) + guard current.directories.starts(with: ancestry.directories) else { + throw CoreError.invalidState("registered native ancestry changed during inspection") + } + return current.directories.count < physical.pathComponents.count + } +} + /// Synchronous, thread-confined admission. There is no lock acquisition inside a transaction. final class TransactionLockContext { private static let threadKey = "agents.core.transaction-lock-context" @@ -346,15 +374,20 @@ final class TransactionLockContext { let resources: [SharedResource] let writable: Bool let requestedShared: Bool + let absentRoots: [AbsentSharedRoot] private var scopeDirectory: DirectoryHandle? private var scopeDescriptor: Int32? private var scopeLockIdentity: FileObjectIdentity? - init(store: StateStore, resources: [SharedResource], writable: Bool, requestedShared: Bool) { + init( + store: StateStore, resources: [SharedResource], writable: Bool, requestedShared: Bool, + absentRoots: [AbsentSharedRoot] = [] + ) { scopeURL = store.directory.standardizedFileURL self.resources = resources self.writable = writable self.requestedShared = requestedShared + self.absentRoots = absentRoots } static var isHeld: Bool { Thread.current.threadDictionary[threadKey] != nil } @@ -429,6 +462,19 @@ final class TransactionLockContext { return try self.resource(resource.identity) } + func absentRoot(for route: NativeTargetRoute) throws -> AbsentSharedRoot? { + guard !writable, let absent = absentRoots.first(where: { $0.route.root == route.root }) else { + return nil + } + guard try absent.remainsAbsent() else { throw CoordinationReadmission.required } + return absent + } + + func targetDirectory(for route: NativeTargetRoute) throws -> URL { + if let absent = try absentRoot(for: route) { return absent.physical } + return try resource(for: route).parent.url + } + func validate(_ journal: TransactionJournal, scope: DirectoryHandle) throws { try journal.validateCoordination() try validateScope() @@ -450,7 +496,7 @@ extension StateStore { let logical = try route.logicalDirectory(environment) let parent: URL if route.shared, let context = TransactionLockContext.current(self) { - parent = try context.resource(for: route).parent.url + parent = try context.targetDirectory(for: route) } else { parent = logical.resolvingSymlinksInPath() } @@ -470,6 +516,7 @@ extension StateStore { while true { let before = try pendingCoordinationJournal(diagnosing: !writable) var resources: [SharedResource] = [] + var absentRoots: [AbsentSharedRoot] = [] let pending = before?.footprint ?? [] var requested = Set( routes.filter(\.shared).map { route in @@ -494,6 +541,10 @@ extension StateStore { } for route in ordered { let recovering = pending.contains { $0.basename == route.basename } + if !writable, !recovering, let absent = try AbsentSharedRoot(store: self, route: route) { + absentRoots.append(absent) + continue + } let resource: SharedResource do { resource = try SharedResource(store: self, route: route, create: writable && !recovering) @@ -519,7 +570,7 @@ extension StateStore { } let context = TransactionLockContext( store: self, resources: resources.sorted { $0.identity < $1.identity }, writable: writable, - requestedShared: routes.contains(where: \.shared)) + requestedShared: routes.contains(where: \.shared), absentRoots: absentRoots) func locked(_ index: Int) throws -> T? { if index < context.resources.count { let resource = context.resources[index] @@ -546,7 +597,9 @@ extension StateStore { return try locked(index + 1) }) } - return try context.run { try body() } + let result = Result { try context.run { try body() } } + for absent in absentRoots where try !absent.remainsAbsent() { return nil } + return try result.get() } // The scope-lock body checks that the preflight footprint still covers the journal. do { diff --git a/Sources/AgentsCore/PrivateMaterialization.swift b/Sources/AgentsCore/PrivateMaterialization.swift index 0d2ad0e..f513fb5 100644 --- a/Sources/AgentsCore/PrivateMaterialization.swift +++ b/Sources/AgentsCore/PrivateMaterialization.swift @@ -53,7 +53,7 @@ package struct PreparedPrivateMaterialization { package let accessChange: PrivateAccessChange? package let target: MaterializationTarget let evidence: TargetPrecondition - let receiptEvidence: TargetPrecondition + let receiptEvidence: TargetPrecondition? var ancestry: DirectoryAccessEvidence { evidence.access!.ancestry } var beforeAccess: FileAccessEvidence? { evidence.access?.target } @@ -96,6 +96,11 @@ extension StateStore { guard target.scope.path == directory.path, try TransactionPaths(store: self).path(for: target.url) == target.path else { throw CoreError.invalidState("materialization target belongs to another scope") } + if let route = NativeTargetRoute.sharedRoute(target.path), + try TransactionLockContext.current(self)?.absentRoot(for: route) != nil + { + return nil + } guard let record = try materializationReceipts(for: target.path).records.targets[target.path] else { return nil @@ -112,6 +117,17 @@ extension StateStore { guard target.scope.path == directory.path, try TransactionPaths(store: self).path(for: target.url) == target.path else { throw CoreError.invalidState("materialization target belongs to another scope") } + if let route = NativeTargetRoute.sharedRoute(target.path), + try TransactionLockContext.current(self)?.absentRoot(for: route) != nil + { + guard generation == nil else { + throw CoreError.invalidState("materialization receipt generation changed or is missing") + } + let evidence = try TargetPrecondition(target.url).capturingAccess() + return PreparedPrivateMaterialization( + owner: UInt32(geteuid()), receiptGeneration: nil, accessChange: nil, target: target, + evidence: evidence, receiptEvidence: nil) + } let receipt = try materializationReceipts(for: target.path) let record = receipt.records.targets[target.path] if let generation, record?.generation != generation { diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index a40278d..c016dff 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -41,7 +41,7 @@ struct TransactionPaths { guard let context = TransactionLockContext.current(store) else { throw CoreError.invalidState("shared target requires its held footprint") } - _ = try context.resource(for: route) + _ = try context.targetDirectory(for: route) } return target.path } @@ -52,6 +52,11 @@ struct TransactionPaths { let physical = logical.resolvingSymlinksInPath() let parent = destination.deletingLastPathComponent().standardizedFileURL if parent.path == logical.standardizedFileURL.path || parent.path == physical.path { + guard + try PathSafety.sanitizeName(destination.lastPathComponent) + == destination.lastPathComponent + || persistedInstallation(destination.lastPathComponent, agent: agent) + else { throw CoreError.unsafePath("unrecorded noncanonical installation target") } let path = agent.rawValue + "/" + destination.lastPathComponent _ = try components(path) return path @@ -89,7 +94,7 @@ struct TransactionPaths { guard let context = TransactionLockContext.current(store) else { throw CoreError.invalidState("shared target requires its held footprint") } - url = try context.resource(for: route).parent.url + url = try context.targetDirectory(for: route) } else { url = try route.logicalDirectory(store.environment).resolvingSymlinksInPath() } @@ -131,6 +136,26 @@ struct TransactionPaths { return result } + /// Only committed exact recipients authorize legacy spellings at the queue boundary. + /// Recovery instead consumes the journal's already-admitted single-component path. + private func persistedInstallation(_ name: String, agent: AgentID) throws -> Bool { + guard !name.isEmpty, name != ".", name != "..", !name.contains("/"), + !name.contains("\\"), !name.contains("\0"), + let bytes = try store.existingData(store.resolvedURL) + else { return false } + try LedgerAdmission.check(bytes, limits: .standard) + struct Version: Decodable { let version: Int } + if try JSONDecoder().decode(Version.self, from: bytes).version == 2 { + let ledger = try ResolvedLedgerCodec.decode(bytes, limits: .standard) + return ledger.deployments.contains { + $0.target.kind == .registered && $0.target.root == "skills-" + agent.rawValue + && $0.target.path == name && $0.recipients.contains(agent) + && $0.route == "agents/skill@1" + } + } + return false + } + /// 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, @@ -181,8 +206,7 @@ struct TransactionPaths { throw CoreError.unsafePath("unmanaged user instruction path") } } else { - guard AgentID(rawValue: key) != nil, descendants.count == 1, - PathSafety.sanitizeName(descendants[0]) == descendants[0] + guard AgentID(rawValue: key) != nil, descendants.count == 1 else { throw CoreError.unsafePath("unmanaged installation transaction path") } } return (key, descendants) diff --git a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift index 1ff9061..7e57782 100644 --- a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift +++ b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift @@ -7,6 +7,156 @@ import Testing @Suite("Registered native MCP files") struct RegisteredNativeTargetTests { + @Test func absentSharedRootPreviewIsPureAndApplyCreatesPrivateObjects() throws { + let fixture = try NativeRouteFixture() + var environment = fixture.store.environment + let missing = fixture.root.appendingPathComponent("fresh/nested") + environment.environment["CLAUDE_CONFIG_DIR"] = missing.path + let store = StateStore(scope: .project, environment: environment) + let before = try FileSnapshot.read(at: fixture.root) + try store.withReadLock(footprint: [.claudeMCPLocal, .codexMCPUser]) { + let target = try store.nativeTarget(for: .claudeMCPLocal) + #expect(target.url == missing.appendingPathComponent(".claude.json")) + #expect(try store.materializationReceipt(for: target) == nil) + let prepared = try store.preparePrivateMaterialization(target) + #expect(prepared.receiptGeneration == nil && prepared.beforeAccess == nil) + #expect(throws: CoreError.self) { + let transaction = FileTransaction(store: store) + try transaction.replacePrivate(prepared, provider: NativeRouteBindings()) { _ in Data() } + } + } + #expect(try FileSnapshot.read(at: fixture.root) == before) + try store.withLock(footprint: [.claudeMCPLocal]) { + let target = try store.nativeTarget(for: .claudeMCPLocal) + let transaction = FileTransaction(store: store) + try transaction.replacePrivate( + store.preparePrivateMaterialization(target), provider: NativeRouteBindings() + ) { _ in Data("private fixture".utf8) } + try transaction.commit() + #expect(try store.materializationReceipt(for: target) != nil) + _ = try DirectoryHandle(at: missing).requirePrivateAccess(".claude.json") + } + } + + @Test func absentRootAppearanceReadmitsWithoutInventingAMetadataIdentity() throws { + let fixture = try NativeRouteFixture() + var environment = fixture.store.environment + let root = fixture.root.appendingPathComponent("fresh") + environment.environment["CLAUDE_CONFIG_DIR"] = root.path + let store = StateStore(scope: .project, environment: environment) + let bytes = try store.withReadLock(footprint: [.claudeMCPLocal]) { + let target = try store.nativeTarget(for: .claudeMCPLocal) + if !FileManager.default.fileExists(atPath: root.path) { + // An external native writer does not participate in Core coordination. + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try Data("external generation".utf8).write(to: target.url) + return Data("stale absence".utf8) + } + return try Data(contentsOf: target.url) + } + #expect(bytes == Data("external generation".utf8)) + #expect( + !FileManager.default.fileExists(atPath: root.appendingPathComponent(".agents-native").path)) + #expect(!FileManager.default.fileExists(atPath: store.directory.path)) + } + + @Test(arguments: ["alias", "ancestor"]) + func absentRootInspectionRefusesRedirectedAuthority(_ change: String) throws { + let fixture = try NativeRouteFixture() + let parent = fixture.root.appendingPathComponent("authority") + let other = fixture.root.appendingPathComponent("unrelated") + for path in [parent, other] { + try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true) + } + var environment = fixture.store.environment + let root = parent.appendingPathComponent("fresh") + environment.environment["CLAUDE_CONFIG_DIR"] = root.path + let store = StateStore(scope: .project, environment: environment) + #expect(throws: CoreError.self) { + try store.withReadLock(footprint: [.claudeMCPLocal]) { + _ = try store.nativeTarget(for: .claudeMCPLocal) + if change == "alias" { + try FileManager.default.createSymbolicLink(at: root, withDestinationURL: other) + } else { + try FileManager.default.moveItem(at: parent, to: parent.appendingPathExtension("old")) + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + } + } + } + #expect(try DirectoryHandle(at: other).names().isEmpty) + #expect(!FileManager.default.fileExists(atPath: store.directory.path)) + } + + @Test(arguments: [false, true]) + func legacyInstallationSpellingRequiresItsExactCommittedRecipient(_ rollback: Bool) throws { + let fixture = try NativeRouteFixture() + let store = fixture.store + let parent = AgentRegistry.installSkillsDirectory( + for: .codex, scope: .project, environment: store.environment) + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + let legacy = parent.appendingPathComponent("Example Skill") + try Data("old".utf8).write(to: legacy) + var ledger = ResolvedLedger() + ledger.sources["fixture"] = LedgerSource(kind: .local, revision: "live") + ledger.components["skill"] = LedgerComponent( + declaringSource: "fixture", source: "fixture", root: ".", kind: "skills", + name: "Example Skill", + payload: .init(object: [:]), conditions: [], recipients: [.codex], chatGPT: false, + resources: []) + ledger.deployments = [ + LedgerDeployment( + id: "deployment", + target: .init(kind: .registered, root: "skills-codex", path: "Example Skill"), + route: "agents/skill@1", owners: ["skill"], recipients: [.codex], ownership: .generated, + expectedHash: "sha256:" + FileHash.sha256Hex(data: Data("old".utf8)), created: true) + ] + ledger.lowerings = [ + LockedLowering( + id: "lowering", format: "agents/skill@1", inputs: ["skill"], resources: [], + deployments: ["deployment"], layout: .init(object: [:]), platform: "macos", artifacts: []) + ] + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + try ResolvedLedgerCodec.encode(ledger, limits: .standard).write(to: store.resolvedURL) + let transaction = FileTransaction(store: store) { point in + if rollback && point == "entry.1.applied" { throw CoreError.invalidState("fixture rollback") } + } + try transaction.replace(legacy, with: .data(Data("next".utf8))) + #expect(throws: CoreError.self) { + try transaction.replace( + parent.appendingPathComponent("Unrecorded Skill"), with: .data(Data())) + } + let other = AgentRegistry.installSkillsDirectory( + for: .claudeCode, scope: .project, environment: store.environment) + #expect(throws: CoreError.self) { + try transaction.replace(other.appendingPathComponent("Example Skill"), with: .data(Data())) + } + let outside = fixture.root.appendingPathComponent("outside") + try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true) + let alias = parent.appendingPathComponent("Traversal Skill") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: outside) + #expect(throws: CoreError.self) { + try transaction.replace(alias.appendingPathComponent("child"), with: .data(Data())) + } + #expect(try DirectoryHandle(at: outside).names().isEmpty) + for path in ["codex/..", "codex/.", "codex/a/b", "codex/a\\b"] { + #expect(throws: CoreError.self) { try TransactionPaths(store: store).components(path) } + } + try transaction.replace( + store.resolvedURL, + with: .data(ResolvedLedgerCodec.encode(ResolvedLedger(), limits: .standard))) + if rollback { + #expect(throws: CoreError.self) { try transaction.commit() } + #expect( + try ResolvedLedgerCodec.decode(Data(contentsOf: store.resolvedURL), limits: .standard) + == ledger) + } else { + try transaction.commit() + } + #expect(try Data(contentsOf: legacy) == Data((rollback ? "old" : "next").utf8)) + #expect( + !FileManager.default.fileExists(atPath: parent.appendingPathComponent("example-skill").path)) + } + @Test(arguments: NativeTargetRoute.allCases) func registeredFilesPublishPrivatelyAndRetainTheirReceipt(_ route: NativeTargetRoute) throws { let fixture = try NativeRouteFixture() From 22d891c243eb80d951cf9d3869d7c9192d3d2012 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:52:06 +0800 Subject: [PATCH 075/171] feat: map Claude and Cursor native component fields --- .../Adapters/ClaudeComponents.swift | 84 +++ .../Adapters/CursorComponents.swift | 9 +- Sources/Components/CapabilityRegistry.swift | 40 +- Sources/Components/MCPLowering.swift | 8 + .../Components/NativeComponentLayoutsV1.swift | 30 +- .../Components/NativeComponentLowering.swift | 19 +- .../Components/NativeDocumentedHooksV1.swift | 203 ++++++ Sources/Components/NativeLSPLayoutV1.swift | 68 ++ Sources/Components/NativePluginFieldsV1.swift | 678 ++++++++++++++++++ Sources/Components/NativePluginLayoutV1.swift | 28 +- Sources/Components/NativeProgramV1.swift | 49 +- .../NativeComponentTests.swift | 521 ++++++++++++++ 12 files changed, 1694 insertions(+), 43 deletions(-) create mode 100644 Sources/Components/Adapters/ClaudeComponents.swift create mode 100644 Sources/Components/NativeDocumentedHooksV1.swift create mode 100644 Sources/Components/NativePluginFieldsV1.swift diff --git a/Sources/Components/Adapters/ClaudeComponents.swift b/Sources/Components/Adapters/ClaudeComponents.swift new file mode 100644 index 0000000..fed965f --- /dev/null +++ b/Sources/Components/Adapters/ClaudeComponents.swift @@ -0,0 +1,84 @@ +import AgentsCore +import Foundation + +extension ClaudeAdapter { + static func components(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + switch input.record.kind { + case "command": + try input.noParameters() + var fields = try input.checkedNative([ + "argument-hint": .string, "allowed-tools": .strings, + "disallowed-tools": .strings, "when_to_use": .string, + "disable-model-invocation": .boolean, "user-invocable": .boolean, + "model": .string, "context": .oneOf(["fork"]), "agent": .string, + "background": .boolean, "effort": .oneOf(["low", "medium", "high", "xhigh", "max"]), + ]) + for key in ["agent", "background"] + where fields[key] != nil && fields["context"]?.text != "fork" { + throw input.issue( + ["native", "claude-code", key], .unsupported, + "this native command field applies only with context fork") + } + fields["description"] = .init(try input.text("description")) + let name = try input.relativeName() + return try input.emitted( + lowering, + input.envelope( + route: .claudeCommand, path: name + ".md", selection: "file", + value: .init(try input.frontmatter(fields, body: input.prompt())))) + case "subagent": + var fields = try input.checkedNative([ + "disallowedTools": .strings, + "permissionMode": .oneOf([ + "default", "manual", "acceptEdits", "auto", "dontAsk", "bypassPermissions", "plan", + ]), + "maxTurns": .positiveInteger, "skills": .strings, + "memory": .oneOf(["user", "project", "local"]), "background": .boolean, + "omitClaudeMd": .boolean, "isolation": .oneOf(["worktree"]), + "effort": .oneOf(["low", "medium", "high", "xhigh", "max"]), + ]) + let name = try input.filename() + guard name.count <= 256, !name.contains(":") else { + throw input.issue( + ["name"], .invalid, "native agent name is limited to 256 characters and excludes colon") + } + let description = try input.text("description") + guard !description.isEmpty else { + throw input.issue(["description"], .invalid, "native agent description is required") + } + fields["name"] = .init(name) + fields["description"] = .init(description) + fields["model"] = input.fields["model"] + fields["tools"] = input.fields["tools"] + return try input.emitted( + lowering, + input.envelope( + route: .claudeAgent, path: name + ".md", selection: "file", + value: .init(try input.frontmatter(fields, body: input.prompt())))) + case "hook": return try NativeDocumentedHooksV1.claude(lowering, input) + case "permissions": + guard input.fields["rules"]?.array?.isEmpty ?? true else { + throw input.issue( + ["rules"], .unverified, + "ordered last-match portable policy is not equivalent to native deny/ask/allow precedence; use explicit native categories" + ) + } + let fields = try input.checkedNative([ + "allow": .strings, "ask": .strings, "deny": .strings, + "defaultMode": .oneOf([ + "default", "acceptEdits", "auto", "dontAsk", "bypassPermissions", "plan", + ]), + ]) + return try input.emitted( + lowering, + input.envelope( + route: .claudeSettings, keys: ["permissions"], selection: "nativePolicy", + value: .init(object: fields))) + case "lspServer": return try NativeLSPLayoutV1.claude(lowering, input) + default: + throw input.issue(["kind"], .invalid, "component does not match this concrete native profile") + } + } +} diff --git a/Sources/Components/Adapters/CursorComponents.swift b/Sources/Components/Adapters/CursorComponents.swift index d8177ad..a064917 100644 --- a/Sources/Components/Adapters/CursorComponents.swift +++ b/Sources/Components/Adapters/CursorComponents.swift @@ -37,10 +37,11 @@ extension CursorAdapter { path: name + ".md", selection: "file", value: .init(try input.frontmatter(fields, body: input.prompt())))) case "hook": - throw input.issue( - ["event"], .unverified, - "captured Cursor hook notes do not fix the exact event vocabulary and command runner contract" - ) + guard input.profileVersion == 2 else { + throw input.issue( + ["event"], .unverified, "native event/runner schema requires profile version 2") + } + return try NativeDocumentedHooksV1.cursor(lowering, input) case "ignore": _ = try input.checkedNative([:]) return try input.emitted( diff --git a/Sources/Components/CapabilityRegistry.swift b/Sources/Components/CapabilityRegistry.swift index 80f1361..35d1bf5 100644 --- a/Sources/Components/CapabilityRegistry.swift +++ b/Sources/Components/CapabilityRegistry.swift @@ -144,10 +144,21 @@ package struct NativeComponentDescriptor { package let kind: DeclaredComponentKind package let format: String package let evidence: NativeSchemaEvidence - package var knownReaders: Set { [request.surface.agent] } + package var knownReaders: Set { + CapabilityRegistry.componentReaders( + request, kind: kind, profileVersion: NativeComponentLayoutsV1.profileVersion(request.surface)) + } } extension CapabilityRegistry { + static func componentReaders( + _ request: NativeComponentRequest, kind: DeclaredComponentKind, profileVersion: Int + ) -> Set { + if profileVersion == 2, request.surface == .claudeCode, [.hook, .subagent].contains(kind) { + return [.claudeCode, .cursor] + } + return [request.surface.agent] + } package static func component( _ request: NativeComponentRequest, kind: DeclaredComponentKind, name: String @@ -162,15 +173,10 @@ extension CapabilityRegistry { guard ![.skills, .instructions, .mcpServer].contains(kind) else { throw issue("kind", .invalid, "component belongs to its existing domain renderer") } - guard request.surface != .cursorCloud else { + guard request.surface != .cursorCloud || (kind == .hook && request.scope == .project) else { throw issue( "surface", .unverified, "Cloud deployment/loading requires a separate registered surface") } - if request.surface == .claudeCode && kind != .plugin { - throw issue( - "kind", .unverified, - "captured Claude evidence lacks this component's complete fixed native schema") - } if kind == .command { if request.surface == .codexCLI { throw issue( @@ -185,7 +191,7 @@ extension CapabilityRegistry { "named-command registration is not established for this surface/scope") } } - if kind == .lspServer && request.surface != .openCodeCLI { + if kind == .lspServer && request.surface != .openCodeCLI && request.surface != .claudeCode { throw issue( "kind", .unverified, "no complete LSP registration schema is captured for this surface") } @@ -205,7 +211,7 @@ extension CapabilityRegistry { "OpenCode hooks require executable plugin API adaptation; equivalent event I/O is not established" ) } - if kind == .permissions && request.surface != .openCodeCLI { + if kind == .permissions && request.surface != .openCodeCLI && request.surface != .claudeCode { throw issue( "rules", .unverified, "native policy precedence differs from ordered last-match semantics; exact translation is not established" @@ -213,7 +219,7 @@ extension CapabilityRegistry { } let pinned = try mcp( .init( - surface: request.surface, + surface: request.surface == .cursorCloud ? .cursorEditor : request.surface, scope: request.scope == .user ? .user : .project), component: name ).evidence let sources: [String] @@ -242,13 +248,21 @@ extension CapabilityRegistry { "https://cursor.com/docs/subagents", "https://docs.cursor.com/en/agent/chat/commands", "https://cursor.com/docs/reference/ignore-file", "https://cursor.com/docs/reference/plugins", + "https://cursor.com/docs/hooks", + ] + case .claudeCode: + sources = [ + "https://code.claude.com/docs/en/skills", "https://code.claude.com/docs/en/sub-agents", + "https://code.claude.com/docs/en/hooks", "https://code.claude.com/docs/en/permissions", + "https://code.claude.com/docs/en/plugins/manifest-reference", + "https://cursor.com/docs/reference/third-party-hooks", "https://cursor.com/docs/subagents", + "claude-plugin-discovery.json", "route-evidence.md", ] - case .claudeCode: sources = ["claude-plugin-discovery.json", "route-evidence.md"] } let revision: String switch request.surface { - case .cursorEditor, .cursorCLI, .cursorCloud: - revision = "sha256:b5e03f48d099bce7b10892b57934b9b611a54b3d4c9cf64e309071760e1c163b" + case .claudeCode, .cursorEditor, .cursorCLI, .cursorCloud: + revision = "sha256:663204a0c4521fccc5ed534e5b81f3c084e9bd691cadf6882a2e95667519b9e0" default: revision = pinned.revision } let evidence = NativeSchemaEvidence(revision: revision, sources: sources) diff --git a/Sources/Components/MCPLowering.swift b/Sources/Components/MCPLowering.swift index 05f1e85..0c760fc 100644 --- a/Sources/Components/MCPLowering.swift +++ b/Sources/Components/MCPLowering.swift @@ -225,9 +225,17 @@ enum MCPNativeField { environmentName case oneOf(Set) case positiveIntegerObject(Set) + case numberOrNull + case object, nonnegativeInteger func accepts(_ value: NativeValue) -> Bool { switch (self, value) { + case (.object, .object): true + case (.nonnegativeInteger, .integer(let value)): value >= 0 && Double(exactly: value) != nil + case (.nonnegativeInteger, .decimal(let value)): + Double(value).map { $0.isFinite && $0 >= 0 && $0.rounded(.towardZero) == $0 } ?? false + case (.numberOrNull, .null), (.numberOrNull, .integer): true + case (.numberOrNull, .decimal(let number)): Double(number)?.isFinite == true case (.boolean, .boolean): true case (.falseOnly, .boolean(false)): true case (.string, .string), (.environmentName, .string): true diff --git a/Sources/Components/NativeComponentLayoutsV1.swift b/Sources/Components/NativeComponentLayoutsV1.swift index 409414f..9ce825d 100644 --- a/Sources/Components/NativeComponentLayoutsV1.swift +++ b/Sources/Components/NativeComponentLayoutsV1.swift @@ -2,13 +2,22 @@ import AgentsCore import Foundation package enum NativeComponentLayoutsV1 { + static func profileVersion(_ surface: NativeClientSurface) -> Int { + switch surface { + case .claudeCode, .cursorEditor, .cursorCLI, .cursorCloud: 2 + default: 1 + } + } package static func format(_ surface: NativeClientSurface) -> String { + format(surface, version: profileVersion(surface)) + } + private static func format(_ surface: NativeClientSurface, version: Int) -> String { switch surface { - case .claudeCode: "agents/claude-components@1" + case .claudeCode: "agents/claude-components@\(version)" case .codexCLI: "agents/codex-components@1" case .geminiCLI: "agents/gemini-components@1" case .openCodeCLI: "agents/opencode-components@1" - case .cursorEditor, .cursorCLI, .cursorCloud: "agents/cursor-components@1" + case .cursorEditor, .cursorCLI, .cursorCloud: "agents/cursor-components@\(version)" } } @@ -17,6 +26,9 @@ package enum NativeComponentLayoutsV1 { "agents/claude-components@1": { try render($0, $1, $2, limits: limits, surface: .claudeCode) }, + "agents/claude-components@2": { + try render($0, $1, $2, limits: limits, surface: .claudeCode, version: 2) + }, "agents/codex-components@1": { try render($0, $1, $2, limits: limits, surface: .codexCLI) }, "agents/gemini-components@1": { try render($0, $1, $2, limits: limits, surface: .geminiCLI) }, "agents/opencode-components@1": { @@ -25,12 +37,15 @@ package enum NativeComponentLayoutsV1 { "agents/cursor-components@1": { try render($0, $1, $2, limits: limits, surface: .cursorEditor) }, + "agents/cursor-components@2": { + try render($0, $1, $2, limits: limits, surface: .cursorEditor, version: 2) + }, ] } private static func render( _ lowering: LockedLowering, _ ledger: ResolvedLedger, - _ resources: [String: URL], limits: LedgerLimits, surface: NativeClientSurface + _ resources: [String: URL], limits: LedgerLimits, surface: NativeClientSurface, version: Int = 1 ) throws -> [ReplayedArtifact] { func invalid() -> CoreError { .invalidState("invalid version 1 native component layout") } guard let layout = lowering.layout.object, @@ -38,7 +53,7 @@ package enum NativeComponentLayoutsV1 { let declared = layout["surface"]?.text.flatMap(NativeClientSurface.init(rawValue:)), format(declared) == format(surface), let scope = layout["scope"]?.text.flatMap(InstallScope.init(rawValue:)), - lowering.format == format(declared), lowering.inputs.count == 1, + lowering.format == format(declared, version: version), lowering.inputs.count == 1, let component = lowering.inputs.first, let record = ledger.components[component], lowering.resources == record.resources, record.resources.allSatisfy({ resources[$0] != nil }), @@ -59,7 +74,7 @@ package enum NativeComponentLayoutsV1 { let input = ComponentRenderInput( record: record, component: component, request: .init(surface: declared, scope: scope), occurrences: occurrences, - resources: resources, ledger: ledger, limits: limits) + resources: resources, ledger: ledger, limits: limits, profileVersion: version) try input.validateProfile() if record.kind == "plugin" { return try NativePluginLayoutV1.render(lowering, input) } switch declared { @@ -69,7 +84,10 @@ package enum NativeComponentLayoutsV1 { case .cursorEditor, .cursorCLI, .cursorCloud: return try CursorAdapter.components(lowering, input) case .claudeCode: - throw input.issue(["kind"], .unverified, "complete fixed native schema is required") + guard version == 2 else { + throw input.issue(["kind"], .unverified, "complete fixed native schema is required") + } + return try ClaudeAdapter.components(lowering, input) } } } diff --git a/Sources/Components/NativeComponentLowering.swift b/Sources/Components/NativeComponentLowering.swift index 06ac99f..687810d 100644 --- a/Sources/Components/NativeComponentLowering.swift +++ b/Sources/Components/NativeComponentLowering.swift @@ -30,6 +30,7 @@ package enum NativeComponentRoute: String { case openCodeConfig, codexConfig, codexAgent, codexHooks case cursorCommand, cursorAgent, cursorIgnore case claudeSkillPlugin, cursorLocalPlugin, geminiExtension + case claudeCommand, claudeAgent, claudeSettings, cursorHooks } package enum NativeComponentLowering { @@ -63,7 +64,8 @@ package enum NativeComponentLowering { let record = frozen.ledger.components[owner.id]! let input = ComponentRenderInput( record: record, component: owner.id, request: request, - occurrences: owner.occurrences, resources: [:], ledger: frozen.ledger, limits: .standard) + occurrences: owner.occurrences, resources: [:], ledger: frozen.ledger, limits: .standard, + profileVersion: NativeComponentLayoutsV1.profileVersion(request.surface)) try input.validateProfile() return .init( id: id, format: format, inputs: [owner.id], resources: record.resources, deployments: [], @@ -87,9 +89,11 @@ struct ComponentRenderInput { let ledger: ResolvedLedger let limits: LedgerLimits let budget: NativeDocumentBudget + let profileVersion: Int init( record: LedgerComponent, component: String, request: NativeComponentRequest, - occurrences: [Int], resources: [String: URL], ledger: ResolvedLedger, limits: LedgerLimits + occurrences: [Int], resources: [String: URL], ledger: ResolvedLedger, limits: LedgerLimits, + profileVersion: Int = 1 ) { self.record = record self.component = component @@ -98,6 +102,7 @@ struct ComponentRenderInput { self.resources = resources self.ledger = ledger self.limits = limits + self.profileVersion = profileVersion budget = .init( limits: .init( storage: limits.encodedBytes, work: limits.encodedBytes, @@ -186,6 +191,10 @@ struct ComponentRenderInput { } let interpolation: Bool switch request.surface { + case .claudeCode: + interpolation = + (record.kind == "hook" && value.contains("${")) + || (prompt && (value.contains("$") || value.contains("!`") || value.contains("${"))) case .openCodeCLI: interpolation = value.contains("{env:") || value.contains("{file:") @@ -295,7 +304,11 @@ struct ComponentRenderInput { "kind": .init(record.kind), "name": .init(record.name), "component": .init(component), "occurrences": .init(array: occurrences.map { .init(integer: $0) }), "recipients": LedgerPayload.strings([request.surface.agent.rawValue]), - "knownReaders": LedgerPayload.strings([request.surface.agent.rawValue]), + "knownReaders": LedgerPayload.strings( + CapabilityRegistry.componentReaders( + request, kind: DeclaredComponentKind(rawValue: record.kind)!, + profileVersion: profileVersion + ).map(\.rawValue).sorted()), "keys": LedgerPayload.strings(keys), "selection": .init(selection), "value": value, ] result["path"] = path.map { .init($0) } diff --git a/Sources/Components/NativeDocumentedHooksV1.swift b/Sources/Components/NativeDocumentedHooksV1.swift new file mode 100644 index 0000000..7cd6802 --- /dev/null +++ b/Sources/Components/NativeDocumentedHooksV1.swift @@ -0,0 +1,203 @@ +import AgentsCore + +/// Native event names retain the client's own stdin/stdout contract, not portable event aliases. +enum NativeDocumentedHooksV1 { + static let claudeEvents: Set = [ + "SessionStart", "Setup", "InstructionsLoaded", "UserPromptSubmit", "UserPromptExpansion", + "MessageDisplay", "PreToolUse", "PermissionRequest", "PermissionDenied", "PostToolUse", + "PostToolUseFailure", "PostToolBatch", "Notification", "SubagentStart", "SubagentStop", + "Stop", "StopFailure", "TeammateIdle", "TaskCreated", "TaskCompleted", "ConfigChange", + "CwdChanged", "DirectoryAdded", "FileChanged", "WorktreeCreate", "WorktreeRemove", + "PreCompact", "PostCompact", "PreModelSwitch", "PostModelSwitch", "Elicitation", + "ElicitationResult", "SessionEnd", + ] + static let claudeWithoutMatcher: Set = [ + "CwdChanged", "UserPromptSubmit", "PostToolBatch", "Stop", "TeammateIdle", "TaskCreated", + "TaskCompleted", "WorktreeCreate", "WorktreeRemove", "MessageDisplay", + ] + static let cursorEvents: Set = [ + "sessionStart", "sessionEnd", "preToolUse", "postToolUse", "postToolUseFailure", + "subagentStart", "subagentStop", "beforeShellExecution", "afterShellExecution", + "beforeMCPExecution", "afterMCPExecution", "beforeReadFile", "afterFileEdit", + "beforeSubmitPrompt", "preCompact", "stop", "afterAgentResponse", "afterAgentThought", + "beforeTabFileRead", "afterTabFileEdit", "workspaceOpen", + ] + static let cursorCloudEvents: Set = [ + "beforeShellExecution", "afterShellExecution", "beforeReadFile", "afterFileEdit", + "preToolUse", "postToolUse", "postToolUseFailure", "subagentStart", "subagentStop", + "beforeSubmitPrompt", "preCompact", "afterAgentResponse", "afterAgentThought", "stop", + ] + static let cursorMatcherEvents: Set = [ + "preToolUse", "postToolUse", "postToolUseFailure", "subagentStart", "subagentStop", + "beforeShellExecution", "afterShellExecution", "beforeReadFile", "afterFileEdit", + "beforeTabFileRead", "afterTabFileEdit", "beforeSubmitPrompt", "stop", + "afterAgentResponse", "afterAgentThought", + ] + /// These fragments are valid in the native JavaScript regex engine without substituting + /// a different engine's syntax or matching behavior. More complex syntax stays explicit. + static func admittedMatcher(_ matcher: String) -> Bool { + if matcher.isEmpty || matcher == "*" { return true } + return matcher.split(separator: "|", omittingEmptySubsequences: false).allSatisfy { part in + var part = part[...] + if part.hasPrefix("^") { part = part.dropFirst() } + if part.hasSuffix("$") { part = part.dropLast() } + if part.hasSuffix(".*") { part = part.dropLast(2) } + return !part.contains(where: { "\\[]{}()+?*^$".contains($0) }) + } + } + + static func event(_ input: ComponentRenderInput, allowed: Set) throws -> String { + guard let event = input.fields["event"]?.object?["native"]?.text else { + throw input.issue( + ["event"], .unverified, + "portable event payload/output equivalence is not established; select an explicit native event" + ) + } + guard allowed.contains(event) else { + throw input.issue( + ["event"], .unsupported, "event is absent from this documented native surface") + } + return event + } + + static func program(_ input: ComponentRenderInput) throws -> LedgerValue { + guard let run = input.fields["run"]?.object else { + throw input.issue(["run"], .invalid, "missing frozen hook program") + } + var result = run + result["executable"] = try NativeProgramV1.executable(run, input: input) + if run["workingDirectory"] != nil { + let index = run["executable"]?.text?.contains("/") == true ? 1 : 0 + guard input.record.resources.indices.contains(index) else { + throw input.issue(["run", "workingDirectory"], .invalid, "missing frozen hook directory") + } + result["workingDirectory"] = .init(object: ["resource": .init(input.record.resources[index])]) + } + try NativeProgramV1.validateLiterals(.init(object: result), input: input, path: ["run"]) + return .init(object: ["program": .init(object: result)]) + } + + static func claude(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + let event = try event(input, allowed: claudeEvents) + try commandType(input) + if input.fields["matcher"] != nil, claudeWithoutMatcher.contains(event) { + throw input.issue(["matcher"], .unsupported, "this native event ignores matchers") + } + if let matcher = input.fields["matcher"]?.text, !admittedMatcher(matcher) { + throw input.issue( + ["matcher"], .unverified, + "exact native JavaScript regex admission is required beyond this fragment profile") + } + var hook = try input.checkedNative([ + "type": .oneOf(["command"]), "statusMessage": .string, + "async": .boolean, "asyncRewake": .boolean, "if": .string, + "onFailure": .oneOf(["continue", "block"]), + ]) + let toolEvents: Set = [ + "PreToolUse", "PostToolUse", "PostToolUseFailure", "PermissionRequest", "PermissionDenied", + ] + if hook["if"] != nil, !toolEvents.contains(event) { + throw input.issue( + ["native", "claude-code", "if"], .unsupported, "native if filters never run on this event") + } + if hook["onFailure"] != nil, + !["PreToolUse", "PermissionRequest", "UserPromptSubmit"].contains(event) + { + throw input.issue( + ["native", "claude-code", "onFailure"], .unverified, + "failure blocking is not verified for this event") + } + if let timeout = input.fields["timeoutSeconds"] { + guard timeout.integer.map({ $0 > 0 }) == true else { + throw input.issue(["timeoutSeconds"], .invalid, "native timeout must be positive seconds") + } + guard hook["async"]?.boolean != true, hook["asyncRewake"]?.boolean != true else { + throw input.issue( + ["timeoutSeconds"], .unsupported, "native background hooks do not enforce this timeout") + } + if event == "SessionEnd", timeout.integer! > 60 { + throw input.issue( + ["timeoutSeconds"], .unsupported, "native SessionEnd budget is capped at sixty seconds") + } + hook["timeout"] = timeout + } + hook["type"] = .init("command") + hook["command"] = try program(input) + var group: [String: LedgerValue] = ["hooks": .init(array: [.init(object: hook)])] + group["matcher"] = input.fields["matcher"] + return try input.emitted( + lowering, + input.envelope( + route: .claudeSettings, keys: ["hooks", event], selection: "hookGroup", + value: .init(object: group))) + } + + static func cursor(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + let allowed: Set + switch input.request.surface { + case .cursorCloud: allowed = cursorCloudEvents + case .cursorCLI: allowed = cursorEvents.subtracting(["beforeTabFileRead", "afterTabFileEdit"]) + default: allowed = cursorEvents + } + let event = try event(input, allowed: allowed) + try commandType(input) + if input.fields["matcher"] != nil, !cursorMatcherEvents.contains(event) { + throw input.issue( + ["matcher"], .unverified, "the documented matcher target is not established for this event") + } + if let matcher = input.fields["matcher"]?.text, !admittedMatcher(matcher) { + throw input.issue( + ["matcher"], .unverified, + "exact native JavaScript regex admission is required beyond this fragment profile") + } + var hook = try input.checkedNative([ + "type": .oneOf(["command"]), "failClosed": .boolean, "loop_limit": .numberOrNull, + ]) + if let loop = input.native["loop_limit"] { + // Only these two event callers consume the field. Unknown/ignored fields are never dropped. + guard ["stop", "subagentStop"].contains(event) else { + throw input.issue( + ["native", "cursor", "loop_limit"], .unsupported, + "only stop/subagentStop consume loop_limit") + } + hook["loop_limit"] = loop + } + if hook["failClosed"]?.boolean == true, event == "sessionStart" { + throw input.issue( + ["native", "cursor", "failClosed"], .unsupported, + "sessionStart is fire-and-forget and cannot block creation") + } + hook["type"] = .init("command") + hook["command"] = try program(input) + hook["matcher"] = input.fields["matcher"] + hook["timeout"] = input.fields["timeoutSeconds"] + if let seconds = input.fields["timeoutSeconds"]?.integer, seconds <= 0 { + throw input.issue(["timeoutSeconds"], .invalid, "native timeout must be positive seconds") + } + var envelope = input.envelope( + route: .cursorHooks, keys: ["hooks", event], selection: "cursorHook", + value: .init(object: hook) + ).object! + envelope["rootRequirements"] = .init(object: ["version": .init(integer: 1)]) + return try input.emitted(lowering, .init(object: envelope)) + } + + private static func commandType(_ input: ComponentRenderInput) throws { + guard let type = input.native["type"] else { return } + guard let name = type.text else { + throw input.issue( + ["native", input.request.surface.agent.rawValue, "type"], .invalid, + "native handler type requires a string") + } + guard name == "command" else { + throw input.issue( + ["native", input.request.surface.agent.rawValue, "type"], .unsupported, + "an executable hook declaration cannot replace its run with a native prompt, agent, HTTP or MCP handler" + ) + } + } +} diff --git a/Sources/Components/NativeLSPLayoutV1.swift b/Sources/Components/NativeLSPLayoutV1.swift index f7b5360..88deacb 100644 --- a/Sources/Components/NativeLSPLayoutV1.swift +++ b/Sources/Components/NativeLSPLayoutV1.swift @@ -1,6 +1,74 @@ import AgentsCore enum NativeLSPLayoutV1 { + static func claude(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + let name = try input.filename() + guard NativePluginFieldsV1.validClaudeName(name) else { + throw input.issue( + ["name"], .invalid, "generated native plugin identifier contains a forbidden character") + } + guard let languages = input.fields["languages"]?.object, !languages.isEmpty, + languages.allSatisfy({ $0.key.hasPrefix(".") && $0.value.text?.isEmpty == false }) + else { + throw input.issue( + ["languages"], .invalid, + "native extensionToLanguage requires nonempty dot-prefixed extensions and language IDs") + } + guard let run = input.fields["run"]?.object else { + throw input.issue(["run"], .invalid, "missing native LSP program") + } + guard run["workingDirectory"] == nil else { + throw input.issue( + ["run", "workingDirectory"], .unsupported, + "native LSP workspaceFolder is not a process working-directory setting") + } + var config = try input.checkedNative([ + "transport": .oneOf(["stdio", "socket"]), "workspaceFolder": .string, + "startupTimeout": .positiveInteger, "shutdownTimeout": .positiveInteger, + "requestTimeout": .positiveInteger, "restartOnCrash": .boolean, "diagnostics": .boolean, + "maxRestarts": .nonnegativeInteger, "settings": .object, + ]) + config["command"] = try NativeProgramV1.executable(run, input: input) + if let command = config["command"]?.text, command.contains(" ") && !command.hasPrefix("/") { + throw input.issue( + ["run", "executable"], .invalid, "native LSP command with spaces must be absolute") + } + config["args"] = run["arguments"] + config["env"] = run["environment"] + config["extensionToLanguage"] = .init(object: languages) + config["initializationOptions"] = input.fields["initializationOptions"] + try NativeProgramV1.validateLiterals(.init(object: config), input: input, path: []) + for key in ["command", "args", "env"] { + if let value = config[key] { try validateExpansion(value, input, path: ["run", key]) } + } + let manifest: LedgerValue = .init(object: [ + "name": .init(name), "lspServers": .init(object: [name: .init(object: config)]), + ]) + return try input.emitted( + lowering, + input.envelope( + route: .claudeSkillPlugin, path: name, selection: "generatedPlugin", + value: .init(object: [".claude-plugin/plugin.json": manifest]))) + } + + private static func validateExpansion( + _ value: LedgerValue, _ input: ComponentRenderInput, path: [String] + ) throws { + if let text = value.text, value.kind == .string || value.kind == .literal, text.contains("${") { + throw input.issue( + path, .unverified, + "literal preservation across native LSP placeholders needs an exact representation") + } + for (index, child) in (value.array ?? []).enumerated() { + try validateExpansion(child, input, path: path + [String(index)]) + } + for (key, child) in value.object ?? [:] { + try validateExpansion(child, input, path: path + [key]) + } + } + static func openCode(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws -> [ReplayedArtifact] { diff --git a/Sources/Components/NativePluginFieldsV1.swift b/Sources/Components/NativePluginFieldsV1.swift new file mode 100644 index 0000000..55e485c --- /dev/null +++ b/Sources/Components/NativePluginFieldsV1.swift @@ -0,0 +1,678 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// Validates documented native container fields against the frozen bundle. Native source +/// bytes and discovery precedence are preserved; this is not decomposition or installation. +struct NativePluginFieldsV1 { + let input: ComponentRenderInput + let resource: LedgerResource + let root: URL + var claude: Bool { input.request.surface == .claudeCode } + static func validClaudeName(_ name: String) -> Bool { + !name.isEmpty + && name.unicodeScalars.allSatisfy { + !CharacterSet.whitespacesAndNewlines.contains($0) + && !"@:/\\".unicodeScalars.contains($0) && $0.properties.generalCategory != .control + && ![0x61C, 0x200E, 0x200F].contains($0.value) + && !(0x202A...0x202E).contains($0.value) && !(0x2066...0x2069).contains($0.value) + } + } + + func fail(_ path: [String], _ detail: String, _ reason: NativeAdapterIssue.Reason = .invalid) + -> NativeComponentIssue + { + input.issue(["manifest"] + path, reason, detail) + } + + func text(_ value: NativeValue, _ path: [String]) throws -> String { + guard case .string(let text) = value, !text.utf8.contains(0) else { + throw fail(path, "native field requires a string without NUL") + } + return text + } + + func strings(_ value: NativeValue, _ path: [String]) throws { + guard case .array(let values) = value else { + throw fail(path, "native field requires an array of strings") + } + for (index, value) in values.enumerated() { _ = try text(value, path + [String(index)]) } + } + + func path( + _ value: NativeValue, _ field: [String], kind: LedgerEntry.Kind? = nil, suffix: String? = nil + ) throws -> String { + let authored = try text(value, field) + if claude, !authored.hasPrefix("./"), !(field.first == "skills" && authored == ".") { + throw fail(field, "native Claude component paths require a dot-slash prefix") + } + if authored.contains("\\") { + throw fail( + field, "native backslash paths need exact frozen resource-path identity", .unverified) + } + let relative: String + do { + relative = try PathSafety.sanitizeSubpath(authored) + guard !authored.hasPrefix("/"), !authored.split(separator: "/").contains(".."), + !authored.contains("://") + else { throw CoreError.invalidState("invalid path") } + } catch { throw fail(field, "native component path must remain inside its frozen plugin root") } + if relative == ".", kind != .file, suffix == nil { return relative } + try input.budget.step(resource.entries.count) + guard let entry = resource.entries.first(where: { $0.path == relative }) else { + try input.budget.step(resource.entries.count) + if resource.entries.contains(where: { + $0.kind == .symlink && relative.hasPrefix($0.path + "/") + }) { + throw fail( + field, "native referenced symlink requires E's contained resource closure", + .integrationRequired) + } + throw fail(field, "native component path is absent from the frozen bundle") + } + guard entry.kind != .symlink else { + throw fail( + field, "native referenced symlink requires E's final contained resource closure", + .integrationRequired) + } + guard kind == nil || entry.kind == kind, suffix == nil || relative.hasSuffix(suffix!) else { + throw fail(field, "native component path has the wrong file or directory kind") + } + return relative + } + + func paths( + _ value: NativeValue, _ field: [String], kind: LedgerEntry.Kind? = nil, suffix: String? = nil + ) throws { + if case .array(let values) = value { + for (index, value) in values.enumerated() { + _ = try path(value, field + [String(index)], kind: kind, suffix: suffix) + } + } else { + _ = try path(value, field, kind: kind, suffix: suffix) + } + } + + func json(_ relative: String, field: [String]) throws -> NativeValue { + try input.budget.step(resource.entries.count) + guard let entry = resource.entries.first(where: { $0.path == relative }), entry.kind == .file, + let size = entry.byteCount, size <= input.limits.resourceBytes + else { + throw fail(field, "native JSON resource is not a bounded frozen file") + } + try input.budget.allocate(size, stage: "native plugin JSON") + try input.budget.step(size) + let bytes = try Data(contentsOf: PathSafety.resolvedChild(base: root, subpath: relative)) + guard bytes.count == size else { throw fail(field, "native JSON resource size changed") } + do { + let document = try NativeDocument(bytes: bytes, format: .json, budget: input.budget) + guard let value = try document.read(.init(keys: []))?.value else { + throw fail(field, "native JSON resource has no root value") + } + return value + } catch NativeDocumentError.invalidDocument { + throw fail(field, "native JSON resource is malformed") + } + } + + func validate(_ fields: [String: NativeValue]) throws { + if claude { + guard Self.validClaudeName(try text(fields["name"] ?? .null, ["name"])) else { + throw fail(["name"], "native plugin identifier contains a forbidden character") + } + } else { + let name = try text(fields["name"] ?? .null, ["name"]) + guard + name.range(of: #"^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$"#, options: .regularExpression) != nil + else { + throw fail( + ["name"], + "Cursor native plugin name must be a lowercase alphanumeric/hyphen/period identifier") + } + } + for (key, value) in fields.sorted(by: { $0.key < $1.key }) { + try input.budget.step() + switch key { + case "name", "version", "description", "homepage", "repository", "license": + _ = try text(value, [key]) + case "displayName" where claude: _ = try text(value, [key]) + case "keywords": try strings(value, [key]) + case "author": + guard case .object(let author) = value, author["name"] != nil else { + throw fail([key], "native author requires a name") + } + for (field, value) in author { + guard ["name", "email"].contains(field) || (claude && field == "url") else { + throw fail([key, field], "native author field is not established", .unverified) + } + _ = try text(value, [key, field]) + } + case "metadata" where claude: + guard case .object = value else { throw fail([key], "native metadata requires an object") } + case "defaultEnabled" where claude: + guard case .boolean = value else { + throw fail([key], "native defaultEnabled requires a boolean") + } + case "commands": + if claude, case .object(let commands) = value { + for (name, value) in commands { + guard case .object(let command) = value, + (command["source"] == nil) != (command["content"] == nil) + else { + throw fail([key, name], "native command requires exactly one source or content") + } + for (field, value) in command { + switch field { + case "source": _ = try path(value, [key, name, field], kind: .file, suffix: ".md") + case "content", "description", "argumentHint", "model": + _ = try text(value, [key, name, field]) + case "allowedTools": try strings(value, [key, name, field]) + default: + throw fail( + [key, name, field], "unknown native command field would lose intent", .unverified) + } + } + } + } else { + try paths(value, [key]) + } + case "agents": + try paths(value, [key], kind: claude ? .file : nil, suffix: claude ? ".md" : nil) + case "skills": try paths(value, [key], kind: claude ? .directory : nil) + case "rules" where !claude: try paths(value, [key]) + case "hooks", "mcpServers": try configurations(value, field: key) + case "lspServers" where claude: try configurations(value, field: key) + case "variables" where !claude: + try variables(value, field: [key], root: true) + case "userConfig" where claude: + try userConfig(value) + case "dependencies" where claude: + throw fail( + [key], + "native plugin dependencies require linked/frozen dependency closure rather than native installer resolution", + .integrationRequired) + case "logo" where !claude: + let logo = try text(value, [key]) + if !logo.hasPrefix("https://") && !logo.hasPrefix("http://") { + _ = try path(value, [key], kind: .file) + } + default: + throw fail( + [key], "native field needs its exact container/registration contract", .unverified) + } + } + // Native defaults retain their own merge/replacement behavior. They are not rewritten. + try input.budget.step(resource.entries.count * 3) + for (file, field) in claude + ? [("hooks/hooks.json", "hooks"), (".mcp.json", "mcpServers"), (".lsp.json", "lspServers")] + : [("hooks/hooks.json", "hooks"), ("mcp.json", "mcpServers")] + where resource.entries.contains(where: { $0.path == file }) { + if !claude, fields[field] != nil { continue } + let value = try json(file, field: [field, "default"]) + try configuration(value, field: field, wrapped: true) + } + } + + func configurations(_ value: NativeValue, field: String) throws { + try input.budget.step() + if case .array(let values) = value { + guard claude || field == "mcpServers" else { + throw fail([field], "native hooks do not accept an array of configuration sources") + } + for value in values { try configurations(value, field: field) } + } else if case .string = value { + if claude, field == "mcpServers" { + let source = try text(value, [field]) + if source.hasSuffix(".mcpb") || source.hasSuffix(".dxt") { + throw fail( + [field], + "native MCP bundle extraction and registration require frozen typed children and closed E/D routes", + .integrationRequired) + } + } + let relative = try path(value, [field], kind: .file, suffix: ".json") + try configuration(json(relative, field: [field]), field: field, wrapped: true) + } else { + guard claude else { + throw fail( + [field], + "the exact inline Cursor container wrapper requires a primary schema/example beyond its documented object type", + .unverified) + } + try configuration(value, field: field, wrapped: false) + } + } + + func configuration(_ value: NativeValue, field: String, wrapped: Bool) throws { + guard case .object(let root) = value else { + throw fail([field], "native config requires an object") + } + let map: [String: NativeValue] + if wrapped && field != "lspServers" { + let allowed: Set + if field == "mcpServers" { + allowed = [field, "$schema"] + } else { + allowed = claude ? [field, "description"] : [field, "version"] + } + guard Set(root.keys).isSubset(of: allowed) else { + throw fail( + [field], "native file root contains fields outside the captured wrapper profile", + .unverified) + } + guard case .object(let entries) = root[field] else { + throw fail( + [field], "native file requires its component wrapper", + field == "mcpServers" ? .unverified : .invalid) + } + if let description = root["description"] { + _ = try text(description, [field, "description"]) + } + if let schema = root["$schema"] { _ = try text(schema, [field, "$schema"]) } + if let version = root["version"] { + let one: Bool + switch version { + case .integer(let value): one = value == 1 + case .decimal(let value): one = Double(value) == 1 + default: one = false + } + guard one else { + throw fail( + [field, "version"], "native hook file version is outside the fixed version-one profile", + .unverified) + } + } + map = entries + } else { + map = root + } + switch field { + case "hooks": try hooks(map) + case "lspServers": + for (name, value) in map { try lsp(value, field: [field, name]) } + case "mcpServers": + for (name, value) in map { try mcp(value, field: [field, name]) } + default: throw fail([field], "unknown native config profile") + } + } + + func hooks(_ events: [String: NativeValue]) throws { + for (event, value) in events { + try input.budget.step() + guard + (claude ? NativeDocumentedHooksV1.claudeEvents : NativeDocumentedHooksV1.cursorEvents) + .contains(event), case .array(let entries) = value + else { + throw fail(["hooks", event], "native hook event or handler array is invalid") + } + for entry in entries { + guard case .object(let object) = entry else { + throw fail(["hooks", event], "native hook entry requires an object") + } + if claude { + guard Set(object.keys).isSubset(of: ["matcher", "hooks"]), + case .array(let handlers) = object["hooks"] + else { + throw fail(["hooks", event], "Claude hook group requires matcher/hooks fields") + } + if let matcher = object["matcher"] { + let pattern = try text(matcher, ["hooks", event, "matcher"]) + guard NativeDocumentedHooksV1.admittedMatcher(pattern) else { + throw fail( + ["hooks", event, "matcher"], + "exact native JavaScript regex admission is required beyond this fragment profile", + .unverified) + } + guard !NativeDocumentedHooksV1.claudeWithoutMatcher.contains(event) else { + throw fail( + ["hooks", event, "matcher"], "this native event ignores matchers", .unsupported) + } + } + for handler in handlers { try handlerFields(handler, event: event) } + } else { + try handlerFields(entry, event: event) + } + } + } + } + + func handlerFields(_ value: NativeValue, event: String) throws { + try input.budget.step() + guard case .object(let handler) = value else { + throw fail(["hooks", event], "native handler requires an object") + } + let type = try text( + handler["type"] ?? (claude ? .null : .string("command")), ["hooks", event, "type"]) + guard + claude + ? ["command", "http", "prompt", "agent", "mcp_tool"].contains(type) : type == "command" + else { + throw fail( + ["hooks", event, "type"], + claude ? "native handler type is not established" : "Cursor plugin hooks are command-only", + .unsupported) + } + if claude { + let promptAndAgentEvents: Set = [ + "PermissionDenied", "PostToolBatch", "PostToolUse", "PostToolUseFailure", "PreToolUse", + "Stop", "SubagentStop", "TaskCompleted", "TaskCreated", "TeammateIdle", + "UserPromptExpansion", "UserPromptSubmit", + ] + if (type == "agent" && !promptAndAgentEvents.contains(event)) + || (type == "prompt" && !promptAndAgentEvents.contains(event) + && event != "PermissionRequest") + || (type == "http" && ["SessionStart", "Setup"].contains(event)) + { + throw fail( + ["hooks", event, "type"], "native event skips this handler type", .unsupported) + } + } + let required: [String] + switch type { + case "command": required = ["command"] + case "http": required = ["url"] + case "prompt", "agent": required = ["prompt"] + default: required = ["server", "tool"] + } + for key in required { _ = try text(handler[key] ?? .null, ["hooks", event, key]) } + let specific: Set + switch type { + case "command": + specific = + claude + ? ["command", "args", "async", "asyncRewake", "shell", "onFailure"] + : ["command", "matcher", "failClosed", "loop_limit"] + case "http": specific = ["url", "headers", "allowedEnvVars", "onFailure"] + case "prompt", "agent": specific = ["prompt", "model"] + default: specific = ["server", "tool", "input"] + } + for (key, value) in handler { + let field = ["hooks", event, key] + guard + specific.contains(key) + || (claude ? ["type", "if", "timeout", "statusMessage"] : ["type", "timeout"]).contains( + key) + else { + throw fail(field, "native handler field is not established for its type", .unverified) + } + switch key { + case "type", "command", "url", "prompt", "model", "server", "tool": _ = try text(value, field) + case "headers": + guard case .object(let headers) = value else { + throw fail(field, "native HTTP headers require a string map") + } + for (name, value) in headers { + let header = try text(value, field + [name]) + guard !header.utf8.contains(13), !header.utf8.contains(10) else { + throw fail(field + [name], "native header contains a line break") + } + } + case "allowedEnvVars": try strings(value, field) + case "input": + guard case .object = value else { + throw fail(field, "native MCP tool input requires an object") + } + case "args" where claude: try strings(value, field) + case "statusMessage" where claude: _ = try text(value, field) + case "if" where claude: + _ = try text(value, field) + guard + [ + "PreToolUse", "PostToolUse", "PostToolUseFailure", "PermissionRequest", + "PermissionDenied", + ].contains(event) + else { throw fail(field, "native if filters never run on this event", .unsupported) } + case "matcher" where !claude: + let pattern = try text(value, field) + guard NativeDocumentedHooksV1.admittedMatcher(pattern) else { + throw fail( + field, + "exact native JavaScript regex admission is required beyond this fragment profile", + .unverified) + } + guard NativeDocumentedHooksV1.cursorMatcherEvents.contains(event) else { + throw fail(field, "native matcher target is not established for this event", .unverified) + } + case "async" where claude, "asyncRewake" where claude: + guard case .boolean = value else { throw fail(field, "native flag requires a boolean") } + case "failClosed" where !claude: + guard case .boolean = value else { throw fail(field, "native flag requires a boolean") } + if event == "sessionStart", value == .boolean(true) { + throw fail(field, "native sessionStart cannot block creation", .unsupported) + } + case "timeout": + guard MCPNativeField.positiveNumber.accepts(value) else { + throw fail(field, "native timeout requires positive seconds") + } + let seconds: Double + switch value { + case .integer(let number): seconds = Double(number) + case .decimal(let number): seconds = Double(number) ?? 0 + default: seconds = 0 + } + if claude, event == "SessionEnd", seconds > 60 { + throw fail(field, "native SessionEnd budget is capped at sixty seconds", .unsupported) + } + case "loop_limit" where !claude: + guard ["stop", "subagentStop"].contains(event), MCPNativeField.numberOrNull.accepts(value) + else { + throw fail( + field, "loop_limit applies only to stop/subagentStop and requires a number or null") + } + case "shell" where claude: + guard [.string("bash"), .string("powershell")].contains(value) else { + throw fail(field, "invalid native shell") + } + if handler["args"] != nil { + throw fail(field, "exec-form native hooks ignore shell", .unsupported) + } + case "onFailure" where claude: + guard [.string("continue"), .string("block")].contains(value) else { + throw fail(field, "invalid native failure policy") + } + if ["Stop", "SubagentStop", "TaskCompleted", "TeammateIdle"].contains(event) + || handler["async"] == .boolean(true) || handler["asyncRewake"] == .boolean(true) + { + throw fail(field, "native hook ignores this failure policy", .unsupported) + } + default: + throw fail(field, "native handler field is not established by this profile", .unverified) + } + } + if claude, type == "mcp_tool", ["SessionStart", "Setup"].contains(event) { + throw fail( + ["hooks", event, "type"], "MCP hook availability is not guaranteed during native startup", + .unverified) + } + if claude, handler["timeout"] != nil, + handler["async"] == .boolean(true) || handler["asyncRewake"] == .boolean(true) + { + throw fail( + ["hooks", event, "timeout"], "native background hook ignores timeout", .unsupported) + } + } + + func lsp(_ value: NativeValue, field: [String]) throws { + try input.budget.step() + guard case .object(let config) = value, let command = config["command"], + case .object(let languages) = config["extensionToLanguage"], !languages.isEmpty + else { + throw fail(field, "native LSP requires command and nonempty extensionToLanguage") + } + let executable = try text(command, field + ["command"]) + guard !executable.isEmpty, !executable.contains(" ") || executable.hasPrefix("/") else { + throw fail(field + ["command"], "native executable with spaces must be absolute") + } + for (ext, value) in languages { + guard ext.hasPrefix("."), !(try text(value, field + ["extensionToLanguage", ext])).isEmpty + else { + throw fail( + field + ["extensionToLanguage"], + "native extensions require a dot prefix and a language ID") + } + } + let rules: [String: MCPNativeField] = [ + "command": .string, "args": .strings, "extensionToLanguage": .object, + "transport": .oneOf(["stdio", "socket"]), "env": .object, + "initializationOptions": .object, "settings": .object, "workspaceFolder": .string, + "startupTimeout": .positiveInteger, "shutdownTimeout": .positiveInteger, + "requestTimeout": .positiveInteger, "restartOnCrash": .boolean, + "maxRestarts": .nonnegativeInteger, "diagnostics": .boolean, + ] + for (key, value) in config { + guard let rule = rules[key] else { + throw fail(field + [key], "unknown strict native LSP field", .unverified) + } + guard rule.accepts(value) else { + throw fail(field + [key], "invalid native LSP field type or range") + } + if key == "env", case .object(let env) = value { + for (name, value) in env { _ = try text(value, field + [key, name]) } + } + } + } + + func mcp(_ value: NativeValue, field: [String]) throws { + try input.budget.step() + guard case .object(let server) = value, (server["command"] == nil) != (server["url"] == nil) + else { + throw fail(field, "native MCP needs exactly one command or URL") + } + for (key, value) in server { + switch key { + case "command", "url": _ = try text(value, field + [key]) + case "cwd" where !claude: _ = try text(value, field + [key]) + case "args": try strings(value, field + [key]) + case "env", "headers": + guard case .object(let fields) = value else { + throw fail(field + [key], "native MCP requires a string map") + } + for (name, value) in fields { _ = try text(value, field + [key, name]) } + case "type" where claude: + guard + (server["command"] != nil ? [.string("stdio")] : [.string("http"), .string("sse")]) + .contains(value) + else { + throw fail(field + [key], "native MCP transport profile is not established", .unverified) + } + default: + throw fail( + field + [key], "native MCP field/selector requires an exact source contract", .unverified) + } + } + } + + func variables(_ value: NativeValue, field: [String], root: Bool = false) throws { + try input.budget.step() + guard case .object(let schema) = value else { + throw fail(field, "native variables require a schema object") + } + if root, schema["type"] != .string("object") { + throw fail(field, "native variable schema root must have object type") + } + if root { + guard case .object = schema["properties"] else { + throw fail(field, "native variable schema root requires properties") + } + } + for (key, value) in schema { + switch key { + case "type": + guard + [ + .string("object"), .string("string"), .string("number"), .string("integer"), + .string("boolean"), .string("array"), .string("null"), + ].contains(value) + else { throw fail(field + [key], "native variable schema type is invalid") } + case "title", "description": _ = try text(value, field + [key]) + case "required": try strings(value, field + [key]) + case "properties": + guard case .object(let properties) = value else { + throw fail(field + [key], "native schema properties require an object") + } + for (name, value) in properties { try variables(value, field: field + [key, name]) } + case "items": try variables(value, field: field + [key]) + case "enum": + guard case .array = value else { + throw fail(field + [key], "native schema enum requires an array") + } + case "default", "const": break + default: + throw fail( + field + [key], "native variable schema keyword is not in the captured fixed profile", + .unverified) + } + } + } + + func userConfig(_ value: NativeValue) throws { + guard case .object(let entries) = value else { + throw fail(["userConfig"], "native userConfig requires an object") + } + for (name, value) in entries { + try input.budget.step() + let field = ["userConfig", name] + guard MCPReferenceSyntax.isName(name), case .object(let option) = value, + case .string(let type) = option["type"], + ["string", "number", "boolean", "directory", "file"].contains(type) + else { throw fail(field, "native userConfig requires an identifier and a supported type") } + _ = try text(option["title"] ?? .null, field + ["title"]) + _ = try text(option["description"] ?? .null, field + ["description"]) + for (key, value) in option { + switch key { + case "type", "title", "description": _ = try text(value, field + [key]) + case "required", "multiple", "sensitive": + guard case .boolean = value else { + throw fail(field + [key], "native option flag requires a boolean") + } + if key == "multiple", type != "string" { + throw fail(field + [key], "multiple applies only to string options", .unsupported) + } + case "min", "max": + guard type == "number", case .integer = value else { + if type == "number", case .decimal(let number) = value, Double(number)?.isFinite == true + { + continue + } + throw fail( + field + [key], "native numeric bounds require a number option and a finite number") + } + case "options": + guard type == "string", option["multiple"] != .boolean(true), + option["sensitive"] != .boolean(true), case .array(let options) = value + else { + throw fail(field + [key], "native picker options require a non-sensitive single string") + } + for value in options { + let label = try text(value, field + [key]) + guard (1...64).contains(label.utf16.count) else { + throw fail(field + [key], "native picker label is outside its documented length") + } + } + if let fallback = option["default"], !options.contains(fallback) { + throw fail(field + ["default"], "native picker default must be a listed option") + } + if option["default"] == nil, option["required"] != .boolean(true) { + throw fail(field + [key], "native picker needs a listed default or required selection") + } + case "default": + if option["sensitive"] == .boolean(true), value != .string("") { + throw fail( + field + [key], "sensitive native defaults cannot enter frozen public resources", + .integrationRequired) + } + switch value { + case .string, .integer, .boolean: break + case .decimal(let number): + guard Double(number)?.isFinite == true else { + throw fail(field + [key], "native default must be finite") + } + case .array: try strings(value, field + [key]) + default: throw fail(field + [key], "native default has an unsupported value type") + } + default: throw fail(field + [key], "unknown strict native userConfig field") + } + } + } + } +} diff --git a/Sources/Components/NativePluginLayoutV1.swift b/Sources/Components/NativePluginLayoutV1.swift index 117c322..3dc213d 100644 --- a/Sources/Components/NativePluginLayoutV1.swift +++ b/Sources/Components/NativePluginLayoutV1.swift @@ -68,18 +68,22 @@ enum NativePluginLayoutV1 { else { throw input.issue(["path"], .invalid, "native plugin manifest is not an exact JSON object") } - for (key, value) in manifestFields { - let metadata = - input.request.surface == .geminiCLI - ? ["name", "version"] : ["name", "version", "description"] - guard metadata.contains(key) else { - throw input.issue( - ["manifest", key], .unverified, - "this native manifest field's registration/path semantics are not captured by the fixed profile" - ) - } - guard case .string(let text) = value, !text.utf8.contains(0) else { - throw input.issue(["manifest", key], .invalid, "native metadata must be a string") + if input.profileVersion == 2 { + try NativePluginFieldsV1(input: input, resource: record, root: root).validate(manifestFields) + } else { + for (key, value) in manifestFields { + let metadata = + input.request.surface == .geminiCLI + ? ["name", "version"] : ["name", "version", "description"] + guard metadata.contains(key) else { + throw input.issue( + ["manifest", key], .unverified, + "this native manifest field's registration/path semantics are not captured by the fixed profile" + ) + } + guard case .string(let text) = value, !text.utf8.contains(0) else { + throw input.issue(["manifest", key], .invalid, "native metadata must be a string") + } } } guard try document.read(.init(keys: ["name"]))?.value == .string(name) else { diff --git a/Sources/Components/NativeProgramV1.swift b/Sources/Components/NativeProgramV1.swift index f59f396..b25311e 100644 --- a/Sources/Components/NativeProgramV1.swift +++ b/Sources/Components/NativeProgramV1.swift @@ -45,19 +45,21 @@ package enum NativeProgramV1 { package static func stagedValue( _ envelope: LedgerValue, bindings: RuntimeBindingValues, environment: RuntimeEnvironment, resourcePaths: [String: String], budget: NativeDocumentBudget, - codexCommandShell: CommandShell? = nil + codexCommandShell: CommandShell? = nil, cursorCommandShell: CommandShell? = nil ) throws -> NativeValue { guard let metadata = envelope.object, let surface = metadata["surface"]?.text.flatMap(NativeClientSurface.init(rawValue:)), let scope = metadata["scope"]?.text.flatMap(InstallScope.init(rawValue:)), let kind = metadata["kind"]?.text, let component = metadata["name"]?.text, let value = metadata["value"], let selection = metadata["selection"]?.text, - ["hookGroup", "lsp"].contains(selection) + ["hookGroup", "cursorHook", "lsp", "generatedPlugin"].contains(selection) else { throw CoreError.invalidState("invalid staged native program intention") } - func issue(_ path: [String], _ detail: String) -> NativeComponentIssue { + func issue(_ path: [String], _ detail: String, _ reason: NativeAdapterIssue.Reason = .invalid) + -> NativeComponentIssue + { .init( request: .init(surface: surface, scope: scope), kind: kind, component: component, - field: path, reason: .invalid, detail: detail) + field: path, reason: reason, detail: detail) } if surface == .codexCLI { guard codexCommandShell == .posix @@ -70,6 +72,13 @@ package enum NativeProgramV1 { ) } } + if [.cursorEditor, .cursorCLI, .cursorCloud].contains(surface), cursorCommandShell != .posix { + throw NativeComponentIssue( + request: .init(surface: surface, scope: scope), kind: kind, + component: component, field: ["run"], reason: .integrationRequired, + detail: + "E must supply the verified native POSIX command-shell contract for this Cursor surface") + } func check(_ text: String, path: [String]) throws -> String { try budget.allocate(text.utf8.count, stage: "native program string") try budget.step(text.utf8.count) @@ -77,6 +86,18 @@ package enum NativeProgramV1 { if surface == .openCodeCLI, text.contains("{env:") || text.contains("{file:") { throw issue(path, "literal cannot cross native interpolation exactly") } + if surface == .claudeCode, text.contains("${"), + selection == "hookGroup" + || (selection == "generatedPlugin" && path.count >= 4 + && ["command", "args", "env"].contains(path[3])) + { + throw issue(path, "literal cannot cross native placeholders exactly", .unverified) + } + if [.cursorEditor, .cursorCLI, .cursorCloud].contains(surface), text.contains("${") { + throw issue( + path, "exact literal preservation across Cursor command preprocessing needs evidence", + .unverified) + } // Settings expand environment tokens before the hook runner sees shell quoting. if surface == .geminiCLI, text.range(of: #"\$(?:[A-Za-z0-9_]+|\{[^}]+?(?::-[^}]*)?\})"#, options: .regularExpression) @@ -167,11 +188,29 @@ package enum NativeProgramV1 { } return .string(try program(run)) } + if selection == "cursorHook", path == ["command"] { + guard let run = value.object?["program"]?.object else { + throw issue(path, "missing native Cursor hook program") + } + return .string(try program(run)) + } + let generatedLSP = + selection == "generatedPlugin" + && path.count >= 3 + && Array(path.prefix(3)) == [".claude-plugin/plugin.json", "lspServers", component] + if generatedLSP, path == [".claude-plugin/plugin.json", "lspServers", component, "command"], + value.object?["resource"] != nil + { + return .string(try string(value, path: path)) + } if selection == "lsp", path == ["command", "0"], value.object?["resource"] != nil { return .string(try string(value, path: path)) } if value.kind == .environment || value.kind == .secret { - guard selection == "lsp", path.count == 2, path.first == "env" else { + guard + (selection == "lsp" && path.count == 2 && path.first == "env") + || (generatedLSP && path.count == 5 && path[3] == "env") + else { throw issue(path, "symbolic binding is outside a native environment slot") } return .string(try string(value, path: path)) diff --git a/Tests/ComponentsTests/NativeComponentTests.swift b/Tests/ComponentsTests/NativeComponentTests.swift index 9cb5bc5..69c24e2 100644 --- a/Tests/ComponentsTests/NativeComponentTests.swift +++ b/Tests/ComponentsTests/NativeComponentTests.swift @@ -537,6 +537,527 @@ struct NativeComponentTests { #expect(ledger.occurrences.count == 2) } + @Test func claudeFilesUseTheirDistinctFrontmatterContracts() throws { + let fixture = try LinkFixture() + let items: [[String: Any]] = [ + [ + "kind": "command", "name": "review", "description": "Review sources", + "prompt": "Keep exact text.\n", + "agents": ["claude-code"], + "native": ["claude-code": ["disable-model-invocation": true, "allowed-tools": ["Read"]]], + ], + [ + "kind": "subagent", "name": "reviewer", "description": "Audit: sources", + "prompt": "Review source.", + "tools": ["Read", "Bash"], "model": "inherit", "agents": ["claude-code"], + "native": [ + "claude-code": [ + "disallowedTools": ["Bash"], "maxTurns": 5, "permissionMode": "plan", + "background": false, + ] + ], + ], + ] + let (linked, frozen) = try freeze(items, fixture) + var ledger = frozen.ledger + ledger.lowerings = try linked.enumerated().map { + try lower($0.element, frozen, surface: .claudeCode, id: "file-\($0.offset)") + } + #expect(ledger.lowerings.allSatisfy { $0.format == "agents/claude-components@2" }) + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + let command = try #require(output[0].values?.object?["value"]?.text) + #expect(command.contains("disable-model-invocation: true")) + #expect(command.hasSuffix("---\nKeep exact text.\n")) + #expect(!command.contains("\nname:")) + let agent = try #require(output[1].values?.object?["value"]?.text) + #expect(agent.contains("disallowedTools: [\"Bash\"]")) + #expect(agent.contains("maxTurns: 5")) + #expect(agent.contains("permissionMode: \"plan\"")) + #expect(output[0].values?.object?["route"]?.text == "claudeCommand") + #expect(output[1].values?.object?["route"]?.text == "claudeAgent") + #expect( + output[1].values?.object?["knownReaders"] + == LedgerPayload.strings(["claude-code", "cursor"])) + #expect(output[1].values?.object?["recipients"] == LedgerPayload.strings(["claude-code"])) + } + } + + @Test(arguments: [NativeClientSurface.claudeCode, .cursorEditor, .cursorCLI, .cursorCloud]) + func documentedNativeHooksKeepShapesAndPrivateArguments(_ surface: NativeClientSurface) throws { + let fixture = try LinkFixture() + let item: [String: Any] = [ + "kind": "hook", "name": "guard", + "event": ["native": surface == .claudeCode ? "PreToolUse" : "beforeShellExecution"], + "run": [ + "executable": "fixture-hook", "arguments": ["a'b", "$(never-execute)"], + "environment": ["TOKEN": ["secret": "fixture/hook"]], + ], + "matcher": surface == .claudeCode ? "Bash|Edit" : "curl|wget", "timeoutSeconds": 9, + "agents": [surface.agent.rawValue], + "native": [ + surface.agent.rawValue: surface == .claudeCode + ? ["onFailure": "block"] : ["failClosed": true] + ], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: surface)] + ledger = try prepared(ledger, fixture) + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + #expect(!String(decoding: encoded, as: UTF8.self).contains("staged hook value")) + try replay(ledger, fixture) { output in + let envelope = try #require(output[0].values) + if surface == .cursorEditor { + #expect(envelope.object?["rootRequirements"]?.object?["version"]?.integer == 1) + #expect(envelope.object?["value"]?.object?["matcher"]?.text == "curl|wget") + #expect(throws: NativeComponentIssue.self) { + try NativeProgramV1.stagedValue( + envelope, bindings: .init([:]), environment: fixture.environment, resourcePaths: [:], + budget: budget()) + } + } + let native = try NativeProgramV1.stagedValue( + envelope, bindings: .init(["fixture/hook": Data("staged hook value".utf8)]), + environment: fixture.environment, resourcePaths: [:], budget: budget(), + cursorCommandShell: .posix) + guard case .object(let object) = native else { + Issue.record("missing native hook") + return + } + let handler: [String: NativeValue] + if surface == .claudeCode { + #expect( + envelope.object?["knownReaders"] == LedgerPayload.strings(["claude-code", "cursor"])) + #expect(envelope.object?["recipients"] == LedgerPayload.strings(["claude-code"])) + #expect(object["matcher"] == .string("Bash|Edit")) + guard case .array(let handlers) = object["hooks"], case .object(let first) = handlers.first + else { + Issue.record("missing Claude group") + return + } + handler = first + #expect(handler["onFailure"] == .string("block")) + } else { + handler = object + #expect(handler["failClosed"] == .boolean(true)) + } + #expect(handler["timeout"] == .integer(9)) + #expect( + handler["command"] + == .string("env 'TOKEN=staged hook value' 'fixture-hook' 'a'\\''b' '$(never-execute)'")) + } + } + + @Test func claudeLSPFreezesGeneratedManifestAndPrivateSlots() throws { + let fixture = try LinkFixture() + try fixture.write("#!/bin/sh\n# never executed\n", to: "bin/server", base: fixture.project) + let item: [String: Any] = [ + "kind": "lspServer", "name": "fixture-lsp", + "run": [ + "executable": "./bin/server", "arguments": ["--stdio"], + "environment": ["TOKEN": ["secret": "fixture/lsp"]], + ], + "languages": [".fixture": "fixture"], + "initializationOptions": ["resource": "ordinary", "program": ["setting": true]], + "agents": ["claude-code"], + "native": [ + "claude-code": [ + "transport": "socket", "startupTimeout": 1000, "shutdownTimeout": 2000, + "requestTimeout": 3000, "restartOnCrash": false, "maxRestarts": 0, "diagnostics": false, + "settings": ["literal": "${ordinary}"], "workspaceFolder": "./workspace", + ] + ], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .claudeCode)] + ledger = try prepared(ledger, fixture) + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + try FileManager.default.removeItem(at: fixture.project) + try replay(ResolvedLedgerCodec.decode(bytes, limits: .standard), fixture) { output in + let envelope = try #require(output[0].values) + #expect(envelope.object?["selection"]?.text == "generatedPlugin") + #expect(envelope.object?["route"]?.text == "claudeSkillPlugin") + let id = try #require(frozen.ledger.components.values.first?.resources.first) + let materialized = try NativeProgramV1.stagedValue( + envelope, bindings: .init(["fixture/lsp": Data("staged LSP value".utf8)]), + environment: fixture.environment, + resourcePaths: [id: "/registered/bin/server"], budget: budget()) + guard case .object(let files) = materialized, + case .object(let manifest) = files[".claude-plugin/plugin.json"], + case .object(let servers) = manifest["lspServers"], + case .object(let config) = servers["fixture-lsp"] + else { + Issue.record("missing generated native manifest") + return + } + #expect(config["command"] == .string("/registered/bin/server")) + #expect(config["transport"] == .string("socket")) + #expect(config["diagnostics"] == .boolean(false)) + #expect(config["requestTimeout"] == .integer(3000)) + #expect(config["settings"] == .object(["literal": .string("${ordinary}")])) + #expect( + config["initializationOptions"] + == .object([ + "resource": .string("ordinary"), "program": .object(["setting": .boolean(true)]), + ])) + #expect(config["env"] == .object(["TOKEN": .string("staged LSP value")])) + for invalid in [Data([0xff]), Data([0]), Data("${CLAUDE_PLUGIN_ROOT}".utf8)] { + do { + _ = try NativeProgramV1.stagedValue( + envelope, bindings: .init(["fixture/lsp": invalid]), environment: fixture.environment, + resourcePaths: [id: "/registered/bin/server"], budget: budget()) + Issue.record("accepted a nonliteral staged native value") + } catch let issue as NativeComponentIssue { + #expect( + issue.field == [ + ".claude-plugin/plugin.json", "lspServers", "fixture-lsp", "env", "TOKEN", + ]) + #expect(!issue.description.contains("${CLAUDE_PLUGIN_ROOT}")) + } + } + } + #expect(!String(decoding: bytes, as: UTF8.self).contains("staged LSP value")) + } + + @Test func claudeExplicitNativePolicyKeepsCategoryPrecedence() throws { + let fixture = try LinkFixture() + let item: [String: Any] = [ + "kind": "permissions", "name": "native-policy", "rules": [], "agents": ["claude-code"], + "native": [ + "claude-code": [ + "allow": ["Bash(git *)"], "ask": ["Edit"], "deny": ["Read(./secret/**)"], + "defaultMode": "plan", + ] + ], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .claudeCode)] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + #expect(output[0].values?.object?["selection"]?.text == "nativePolicy") + let policy = try #require(output[0].values?.object?["value"]?.object) + #expect(policy["deny"] == LedgerPayload.strings(["Read(./secret/**)"])) + #expect(policy["allow"] == LedgerPayload.strings(["Bash(git *)"])) + } + } + + @Test func documentedIgnoredAndUnverifiedHookCombinationsAreDiagnosed() throws { + let fixture = try LinkFixture() + let cases: [([String: Any], NativeClientSurface, [String], NativeAdapterIssue.Reason)] = [ + ( + [ + "kind": "subagent", "name": "exact", "description": "Fixture", "prompt": "Prompt", + "agents": ["claude-code"], "native": ["claude-code": ["max_turns": 2]], + ], .claudeCode, ["native", "claude-code", "max_turns"], .unverified + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "Stop"], + "run": ["executable": "fixture"], "matcher": "Bash", "agents": ["claude-code"], + ], .claudeCode, ["matcher"], .unsupported + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "PreToolUse"], + "run": ["executable": "fixture"], "timeoutSeconds": 4, + "native": ["claude-code": ["async": true]], "agents": ["claude-code"], + ], .claudeCode, ["timeoutSeconds"], .unsupported + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "sessionStart"], + "run": ["executable": "fixture"], "native": ["cursor": ["failClosed": true]], + "agents": ["cursor"], + ], .cursorEditor, ["native", "cursor", "failClosed"], .unsupported + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "preToolUse"], + "run": ["executable": "fixture"], "native": ["cursor": ["loop_limit": 3]], + "agents": ["cursor"], + ], .cursorEditor, ["native", "cursor", "loop_limit"], .unsupported + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "sessionStart"], + "run": ["executable": "fixture"], "agents": ["cursor"], + ], .cursorCloud, ["event"], .unsupported + ), + ( + [ + "kind": "permissions", "name": "exact", + "rules": [ + ["effect": "deny", "operation": ["tool": "Read"], "pattern": "*"], + ["effect": "allow", "operation": ["tool": "Read"], "pattern": "src/**"], + ], "agents": ["claude-code"], + ], .claudeCode, ["rules"], .unverified + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "beforeTabFileRead"], + "run": ["executable": "fixture"], "agents": ["cursor"], + ], .cursorCLI, ["event"], .unsupported + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "beforeMCPExecution"], + "run": ["executable": "fixture"], "matcher": "native-server", "agents": ["cursor"], + ], .cursorEditor, ["matcher"], .unverified + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "PreToolUse"], + "run": ["executable": "fixture"], "matcher": "[", "agents": ["claude-code"], + ], .claudeCode, ["matcher"], .unverified + ), + ( + [ + "kind": "hook", "name": "exact", "event": "beforeTool", "run": ["executable": "fixture"], + "agents": ["claude-code"], + ], .claudeCode, ["event"], .unverified + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "preToolUse"], + "run": ["executable": "fixture"], "native": ["cursor": ["type": "prompt"]], + "agents": ["cursor"], + ], .cursorEditor, ["native", "cursor", "type"], .unsupported + ), + ] + for (item, surface, field, reason) in cases { + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: surface)] + do { + _ = try prepared(ledger, fixture) + Issue.record("accepted a lost native intent") + } catch let issue as NativeComponentIssue { + #expect(issue.field == field) + #expect(issue.reason == reason) + } + } + } + + @Test func nativeManifestFieldsPreserveFrozenChildrenAndColdV1Replay() throws { + let fixture = try LinkFixture() + let manifest: [String: Any] = [ + "name": "native-fields", "version": "build-label", "author": ["name": "Fixture"], + "commands": [ + "about": ["content": "Review source.", "argumentHint": "[file]", "allowedTools": ["Read"]] + ], + "agents": ["./agents/reviewer.md"], "skills": ["./skills"], + "userConfig": [ + "token": [ + "type": "string", "title": "Token", "description": "Native client-owned token", + "sensitive": true, + ], + "tone": [ + "type": "string", "title": "Tone", "description": "Picker", + "options": ["neutral", "warm"], "required": true, + ], + ], + "hooks": ["Stop": [["hooks": [["type": "prompt", "prompt": "Review $ARGUMENTS"]]]]], + "mcpServers": [ + "fixture": [ + "type": "stdio", "command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/server.js"], + ] + ], + "lspServers": [ + "fixture": [ + "command": "fixture-lsp", "extensionToLanguage": [".fixture": "fixture"], + "transport": "socket", "diagnostics": false, + ] + ], + ] + try fixture.write( + String(decoding: JSONSerialization.data(withJSONObject: manifest), as: UTF8.self), + to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + try fixture.write( + "---\nname: reviewer\ndescription: Fixture\n---\nReview source.", + to: "bundle/agents/reviewer.md", base: fixture.project) + try fixture.write("# Fixture", to: "bundle/skills/fixture/SKILL.md", base: fixture.project) + try fixture.write("Default command.", to: "bundle/commands/default.md", base: fixture.project) + let item: [String: Any] = [ + "kind": "plugin", "name": "native-fields", "path": "bundle", "source": ".", "mode": "native", + "agents": ["claude-code"], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .claudeCode)] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + let root = try #require(output[1].tree) + let bytes = try Data(contentsOf: root.appendingPathComponent(".claude-plugin/plugin.json")) + let object = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + #expect(object["version"] as? String == "build-label") + #expect( + FileManager.default.fileExists( + atPath: root.appendingPathComponent("commands/default.md").path)) + #expect(object["commands"] is [String: Any]) + } + var invalid = manifest + invalid["agents"] = ["agents/reviewer.md"] + try fixture.write( + String(decoding: JSONSerialization.data(withJSONObject: invalid), as: UTF8.self), + to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + let (badLinked, badFrozen) = try freeze([item], fixture) + var bad = badFrozen.ledger + bad.lowerings = [try lower(badLinked[0], badFrozen, surface: .claudeCode)] + do { + _ = try prepared(bad, fixture) + Issue.record("accepted a native path without its required prefix") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["manifest", "agents", "0"]) + #expect(issue.reason == .invalid) + } + invalid = manifest + invalid["hooks"] = [ + "PermissionRequest": [["hooks": [["type": "agent", "prompt": "Review request"]]]] + ] + try fixture.write( + String(decoding: JSONSerialization.data(withJSONObject: invalid), as: UTF8.self), + to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + let (skippedLinked, skippedFrozen) = try freeze([item], fixture) + var skipped = skippedFrozen.ledger + skipped.lowerings = [try lower(skippedLinked[0], skippedFrozen, surface: .claudeCode)] + do { + _ = try prepared(skipped, fixture) + Issue.record("accepted a handler type the native event skips") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["manifest", "hooks", "PermissionRequest", "type"]) + #expect(issue.reason == .unsupported) + } + invalid["hooks"] = [ + "Stop": [["hooks": [["type": "command", "command": "fixture", "onFailure": "block"]]]] + ] + try fixture.write( + String(decoding: JSONSerialization.data(withJSONObject: invalid), as: UTF8.self), + to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + let (ignoredLinked, ignoredFrozen) = try freeze([item], fixture) + var ignored = ignoredFrozen.ledger + ignored.lowerings = [try lower(ignoredLinked[0], ignoredFrozen, surface: .claudeCode)] + do { + _ = try prepared(ignored, fixture) + Issue.record("accepted a native failure policy with no effect") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["manifest", "hooks", "Stop", "onFailure"]) + #expect(issue.reason == .unsupported) + } + // Revision 1 uses its frozen metadata-only validator and continues to replay valid bundles. + try fixture.write( + #"{"name":"native-fields","version":"1.0.0"}"#, to: "simple/.claude-plugin/plugin.json", + base: fixture.project) + var simple = item + simple["path"] = "simple" + let (oldLinked, oldFrozen) = try freeze([simple], fixture) + var old = oldFrozen.ledger + var lowering = try lower(oldLinked[0], oldFrozen, surface: .claudeCode) + lowering.format = "agents/claude-components@1" + old.lowerings = [lowering] + old = try prepared(old, fixture) + let locked = try ResolvedLedgerCodec.encode(old, limits: .standard) + try FileManager.default.removeItem(at: fixture.project) + try replay(ResolvedLedgerCodec.decode(locked, limits: .standard), fixture) { output in + #expect(output.count == 2) + #expect(output[0].values?.object?["route"]?.text == "claudeSkillPlugin") + } + } + + @Test func cursorManifestUsesSelectedPathsAndCommandOnlyPluginHooks() throws { + let fixture = try LinkFixture() + let base = StateStore(scope: .user, environment: fixture.environment).directory + let manifest: [String: Any] = [ + "name": "cursor-fields", "version": "1.2.3", + "author": ["name": "Fixture", "email": "fixture@example.test"], + "commands": "./commands", "rules": "./rules", "agents": "./agents", "skills": "./skills", + "hooks": "./config/hooks.json", "mcpServers": ["./config/mcp.json"], + "variables": [ + "type": "object", "properties": ["TOKEN": ["type": "string", "title": "Token"]], + "required": ["TOKEN"], + ], + ] + try fixture.write( + String(decoding: JSONSerialization.data(withJSONObject: manifest), as: UTF8.self), + to: "bundle/.cursor-plugin/plugin.json", base: base) + for path in [ + "commands/check.md", "rules/check.mdc", "agents/check.md", "skills/check/SKILL.md", + ] { + try fixture.write("Fixture source.", to: "bundle/" + path, base: base) + } + try fixture.write( + #"{"hooks":{"beforeShellExecution":[{"command":"./scripts/check.sh","matcher":"curl|wget","failClosed":true}]}}"#, + to: "bundle/config/hooks.json", base: base) + try fixture.write( + #"{"mcpServers":{"fixture":{"command":"node","args":["${CURSOR_PLUGIN_ROOT}/server.js"],"cwd":"${CURSOR_PLUGIN_ROOT}"}}}"#, + to: "bundle/config/mcp.json", base: base) + // An explicit Cursor hooks path replaces this default discovery file. + try fixture.write( + #"{"hooks":{"stop":[{"type":"prompt","command":"not-selected"}]}}"#, + to: "bundle/hooks/hooks.json", base: base) + let item: [String: Any] = [ + "kind": "plugin", "name": "cursor-fields", "path": "bundle", "source": ".", "mode": "native", + "agents": ["cursor"], + ] + let (linked, frozen) = try freeze([item], fixture, scope: .user) + var ledger = frozen.ledger + ledger.lowerings = [ + try NativeComponentLowering.lower( + linked[0], frozen: frozen, request: .init(surface: .cursorEditor, scope: .user), + id: "cursor-plugin", platform: platform) + ] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + #expect(output[0].values?.object?["route"]?.text == "cursorLocalPlugin") + let tree = try #require(output[1].tree) + #expect( + try String(contentsOf: tree.appendingPathComponent("config/hooks.json"), encoding: .utf8) + .contains("failClosed")) + #expect( + try String(contentsOf: tree.appendingPathComponent("hooks/hooks.json"), encoding: .utf8) + .contains("not-selected")) + } + var changed = manifest + changed["hooks"] = "./hooks/hooks.json" + try fixture.write( + String(decoding: JSONSerialization.data(withJSONObject: changed), as: UTF8.self), + to: "bundle/.cursor-plugin/plugin.json", base: base) + let (badLinked, badFrozen) = try freeze([item], fixture, scope: .user) + var bad = badFrozen.ledger + bad.lowerings = [ + try NativeComponentLowering.lower( + badLinked[0], frozen: badFrozen, request: .init(surface: .cursorEditor, scope: .user), + id: "cursor-plugin", platform: platform) + ] + do { + _ = try prepared(bad, fixture) + Issue.record("accepted a prompt handler in a Cursor plugin") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["manifest", "hooks", "stop", "type"]) + #expect(issue.reason == .unsupported) + } + changed["hooks"] = ["hooks": ["stop": [["command": "fixture"]]]] + try fixture.write( + String(decoding: JSONSerialization.data(withJSONObject: changed), as: UTF8.self), + to: "bundle/.cursor-plugin/plugin.json", base: base) + let (inlineLinked, inlineFrozen) = try freeze([item], fixture, scope: .user) + var inline = inlineFrozen.ledger + inline.lowerings = [ + try NativeComponentLowering.lower( + inlineLinked[0], frozen: inlineFrozen, request: .init(surface: .cursorEditor, scope: .user), + id: "cursor-plugin", platform: platform) + ] + do { + _ = try prepared(inline, fixture) + Issue.record("guessed an inline Cursor wrapper") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["manifest", "hooks"]) + #expect(issue.reason == .unverified) + } + } + private var platform: DeclarationPlatform { #if os(macOS) .macOS From 8629a6b894ba139c01694ab8b0ddeb2445791c9b Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:05:39 +0800 Subject: [PATCH 076/171] fix: preserve producer input and binding semantics --- .../Import/RulesyncConfigImport.swift | 20 +++- .../Import/RulesyncSourceImport.swift | 4 +- .../Import/VercelSourceImport.swift | 9 +- .../ComponentsTests/ImportProfileTests.swift | 102 ++++++++++++++++-- Tests/ComponentsTests/ImportSourceTests.swift | 27 +++-- 5 files changed, 142 insertions(+), 20 deletions(-) diff --git a/Sources/Components/Import/RulesyncConfigImport.swift b/Sources/Components/Import/RulesyncConfigImport.swift index a6e484c..c510189 100644 --- a/Sources/Components/Import/RulesyncConfigImport.swift +++ b/Sources/Components/Import/RulesyncConfigImport.swift @@ -151,8 +151,9 @@ enum RulesyncConfigImport { "source", "skills", "rules", "transport", "ref", "path", "rulesPath", "registry", "tokenEnv", ].contains(key) { - unconverted( - object[key]!, at: location.appending("member[\(ordinal)]"), into: &diagnostics) + let member = location.appending("member[\(ordinal)]") + if ImportInput.credentialField(key) { diagnostics.binding(member) } + unconverted(object[key]!, at: member, into: &diagnostics) } guard ["transport", "ref", "path", "rulesPath", "registry", "tokenEnv"].allSatisfy({ @@ -173,6 +174,16 @@ enum RulesyncConfigImport { diagnostics.add(.invalidInput, location, "Invalid source transport or selection.") continue } + let emptySelections = ["skills", "rules"].filter { object[$0]?.importStrings == [] } + if !emptySelections.isEmpty { + for field in emptySelections { + diagnostics.add( + .invalidInput, location.appending(field), + "An empty producer selection invalidates the whole source; omit the feature or remove the source." + ) + } + continue + } if object["registry"] != nil || object["tokenEnv"] != nil { guard transport == "npm" else { diagnostics.add( @@ -208,6 +219,9 @@ enum RulesyncConfigImport { var declaration: SourceDeclaration? var identity = raw if transport == "github" { + if raw.contains("://"), !ImportInput.safeLocator(raw) { + diagnostics.binding(location.appending("source")) + } guard let github = githubLocator(raw) else { diagnostics.add( .unconverted, location, "Unsupported or ambiguous GitHub source selector.") @@ -438,7 +452,7 @@ enum RulesyncConfigImport { } } - private static func githubLocator(_ raw: String) -> ( + static func githubLocator(_ raw: String) -> ( location: String, ref: String?, path: String? )? { guard !raw.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }), diff --git a/Sources/Components/Import/RulesyncSourceImport.swift b/Sources/Components/Import/RulesyncSourceImport.swift index 176de84..273c09e 100644 --- a/Sources/Components/Import/RulesyncSourceImport.swift +++ b/Sources/Components/Import/RulesyncSourceImport.swift @@ -77,7 +77,9 @@ enum RulesyncSourceImport { diagnostics.add(.invalidInput, location, "Expected an npm package name as source key.") continue } - if !npm, !ImportInput.safeLocator(repository) { + if !npm, !ImportInput.safeLocator(repository), + RulesyncConfigImport.githubLocator(repository) == nil + { diagnostics.binding(location) continue } diff --git a/Sources/Components/Import/VercelSourceImport.swift b/Sources/Components/Import/VercelSourceImport.swift index d2176f0..8461154 100644 --- a/Sources/Components/Import/VercelSourceImport.swift +++ b/Sources/Components/Import/VercelSourceImport.swift @@ -72,7 +72,14 @@ enum VercelSourceImport { arrays: project ? ["subagents"] : [], at: location) else { continue } let sourceURL = ImportInput.string(entry["sourceUrl"]) - guard ImportInput.safeLocator(source), sourceURL.map(ImportInput.safeLocator) ?? project, + // node_modules locks store an npm package identifier, not a credentialed URL. + let packageIdentifier = + sourceType == "node_modules" + && source.range( + of: #"^(@[a-z0-9~][a-z0-9._~-]*/)?[a-z0-9~][a-z0-9._~-]*$"#, + options: .regularExpression) != nil + guard packageIdentifier || ImportInput.safeLocator(source), + sourceURL.map(ImportInput.safeLocator) ?? project, ImportInput.string(entry["sourceBaseUrl"]).map(ImportInput.safeLocator) ?? true else { diagnostics.binding(location.appending("sourceUrl")) diff --git a/Tests/ComponentsTests/ImportProfileTests.swift b/Tests/ComponentsTests/ImportProfileTests.swift index a1f5188..20efe5b 100644 --- a/Tests/ComponentsTests/ImportProfileTests.swift +++ b/Tests/ComponentsTests/ImportProfileTests.swift @@ -382,11 +382,50 @@ struct ImportProfileTests { !result.diagnostics.contains { $0.code == .ambiguousSource || $0.code == .incompletePin }) } - @Test func staleLockAndExplicitEmptySelectionsCannotBroadenCurrentSourceIntent() throws { + @Test func embeddedRulesyncSelectorPreservesExplicitSourceAndLockedResources() throws { let fixture = try ImportProfileFixture() try fixture.directory(".rulesync") try fixture.write( - "config.jsonc", "{\"sources\":[{\"source\":\"acme/repo\",\"ref\":\"new\",\"skills\":[]}]}") + "config.jsonc", #"{"sources":[{"source":"acme/repo@main:skills"}]}"#) + let commit = String(repeating: "a", count: 40) + try fixture.write( + "lock.json", + """ + {"lockfileVersion":1,"sources":{"acme/repo@main:skills":{ + "requestedRef":"main","resolvedRef":"\(commit)","skillsPath":"skills", + "skillSelection":["*"],"skills":{"review":{"integrity":"sha256-\(String(repeating: "b", count: 64))"}}}}} + """) + let before = try fixture.hash() + var lock = fixture.input(.rulesyncSourcesV1, "lock.json") + lock.sourceDeclarations = [ + "acme/repo@main:skills": .init(kind: .git, location: "https://github.com/acme/repo") + ] + let standalone = try SourceImport.preview(lock) + let ordered = try SourceImport.previewRulesync( + configs: [fixture.input(.rulesyncConfig, "config.jsonc")], locks: [lock]) + for result in [standalone, ordered] { + #expect(result.bindings.isEmpty) + #expect(result.sources.first?.producerIdentity == "acme/repo@main:skills") + #expect(result.sources.first?.pin.commit == commit) + #expect(result.sources.first?.requestedRef == "main") + #expect(result.sources.last?.declaration?.location == "https://github.com/acme/repo") + #expect(result.sources.last?.declaration?.requirement == .revision(commit)) + #expect(result.resources.map(\.path) == ["skills/review"]) + #expect( + result.resources.first?.producerIntegrity?.value == "sha256-" + + String(repeating: "b", count: 64)) + #expect(result.components.count == 1) + #expect( + !result.diagnostics.contains { $0.code == .ambiguousSource || $0.code == .incompletePin }) + } + #expect(try fixture.hash() == before) + } + + @Test func staleLockCannotBroadenCurrentSourceIntent() throws { + let fixture = try ImportProfileFixture() + try fixture.directory(".rulesync") + try fixture.write( + "config.jsonc", #"{"sources":[{"source":"acme/repo","ref":"new","skills":["*"]}]}"#) try fixture.write( "lock.json", "{\"lockfileVersion\":1,\"sources\":{\"acme/repo\":{\"requestedRef\":\"old\",\"resolvedRef\":\"\(String(repeating: "a", count: 40))\",\"skillsPath\":\"skills\",\"skillSelection\":[\"*\"],\"skills\":{\"review\":{\"integrity\":\"sha256-\(String(repeating: "b", count: 64))\"}}}}}" @@ -398,15 +437,62 @@ struct ImportProfileTests { #expect(stale.resources.isEmpty) #expect(stale.components.isEmpty) #expect(stale.diagnostics.contains { $0.code == .ambiguousSource }) + } + + @Test(arguments: [ + #""skills":[]"#, #""rules":[]"#, #""skills":[],"rules":[]"#, + #""skills":["*"],"rules":[]"#, #""skills":[],"rules":["*"]"#, + ]) + func emptySelectionInvalidatesWholeRemoteSource(_ fields: String) throws { + let fixture = try ImportProfileFixture() + try fixture.directory(".rulesync") + try fixture.write("config.jsonc", "{\"sources\":[{\"source\":\"acme/repo\",\(fields)}]}") try fixture.write( - "config.jsonc", "{\"sources\":[{\"source\":\"acme/repo\",\"ref\":\"old\",\"skills\":[]}]}") - let empty = try SourceImport.previewRulesync( + "lock.json", + """ + {"lockfileVersion":1,"sources":{"acme/repo":{"resolvedRef":"\(String(repeating: "a", count: 40))", + "skillsPath":"skills","skillSelection":["*"],"skills":{"review":{"integrity":"sha256-\(String(repeating: "b", count: 64))"}}, + "rulesPath":"rules","rules":{"overview":{"integrity":"sha256-\(String(repeating: "c", count: 64))"}}}}} + """) + let before = try fixture.hash() + let result = try SourceImport.previewRulesync( configs: [fixture.input(.rulesyncConfig, "config.jsonc")], locks: [fixture.input(.rulesyncSourcesV1, "lock.json")]) - #expect(empty.sources.first?.pin.commit == String(repeating: "a", count: 40)) - #expect(empty.resources.isEmpty) - #expect(empty.components.isEmpty) - #expect(empty.orderedSources.first?.skills == []) + #expect(result.sources.isEmpty) + #expect(result.orderedSources.isEmpty) + #expect(result.resources.isEmpty) + #expect(result.components.isEmpty) + #expect( + result.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == "config.jsonc" + && ["/sources/0/skills", "/sources/0/rules"].contains($0.location.pointer) + }) + #expect(try fixture.hash() == before) + } + + @Test func defaultGitHubCredentialsAndUnknownTokenRequireBindingsWithoutLiterals() throws { + let fixture = try ImportProfileFixture() + try fixture.directory(".rulesync") + try fixture.write( + "config.jsonc", + #"{"sources":[{"source":"https://user:SECRET_LOCATOR@github.com/acme/repo"},{"source":"acme/repo","token":"SECRET_FIELD"}]}"# + ) + let before = try fixture.hash() + let result = try SourceImport.preview(fixture.input(.rulesyncConfig, "config.jsonc")) + #expect( + result.bindings.map(\.location.pointer) == ["/sources/0/source", "/sources/1/member[1]"]) + #expect(result.bindings.allSatisfy { $0.environmentVariable == nil }) + #expect( + result.diagnostics.contains { $0.code == .unconverted && $0.location.pointer == "/sources/0" } + ) + #expect( + result.diagnostics.contains { + $0.code == .unconverted && $0.location.pointer == "/sources/1/member[1]" + }) + #expect(result.sources.map(\.producerIdentity) == ["acme/repo"]) + #expect(!String(reflecting: result).contains("SECRET_LOCATOR")) + #expect(!String(reflecting: result).contains("SECRET_FIELD")) + #expect(try fixture.hash() == before) } @Test func nativeInputConflictsAndYAMLCredentialLocatorsStayExplicit() throws { diff --git a/Tests/ComponentsTests/ImportSourceTests.swift b/Tests/ComponentsTests/ImportSourceTests.swift index 997c072..ea9d7bb 100644 --- a/Tests/ComponentsTests/ImportSourceTests.swift +++ b/Tests/ComponentsTests/ImportSourceTests.swift @@ -109,15 +109,18 @@ struct ImportSourceTests { #expect(proposal.diagnostics.contains { $0.code == .incompletePin }) } - @Test func vercelProjectCapturesActualContentWithoutInventingGitCommit() throws { + @Test(arguments: ["github", "node_modules"]) + func vercelProjectCapturesActualContentWithoutInventingGitCommit(_ sourceType: String) throws { let fixture = try ImportSourceFixture() try fixture.skill() try fixture.write("first\r\nsecond\r\n", at: "installed/review/guide.txt") try Data([0, 13, 10]).write(to: fixture.root.appendingPathComponent("installed/review/binary")) try fixture.write("{}", at: "installed/review/metadata.json/ignored.txt") + let source = sourceType == "node_modules" ? "@acme/pkg" : "acme/repo" + let metadata = sourceType == "node_modules" ? #""version":"1.2.3","# : #""ref":"main","# try fixture.write( """ - {"version":2,"skills":{"review":{"source":"acme/repo","sourceType":"github","ref":"main", + {"version":2,"skills":{"review":{"source":"\(source)","sourceType":"\(sourceType)",\(metadata) "skillPath":"skills/review/SKILL.md","computedHash":"8ab07122fdd17957fa92a18c05f175744b26f661c87f3f479ad6279e200713e3"}}} """) var input = fixture.input(.vercelProjectV2) @@ -127,7 +130,8 @@ struct ImportSourceTests { #expect(try FileHash.folderHash(fixture.root) == before) #expect(proposal.sources.first?.pin.commit == nil) #expect(proposal.sources.first?.pin.integrity?.kind == .vercelInstalledSHA256) - #expect(proposal.sources.first?.declaration?.path == "skills/review") + #expect( + proposal.sources.first?.declaration?.path == (sourceType == "github" ? "skills/review" : nil)) #expect(proposal.sources.last?.declaration?.kind == .local) #expect(proposal.sources.last?.declaration?.location == "installed/review") #expect( @@ -136,7 +140,13 @@ struct ImportSourceTests { #expect(proposal.resources.first?.requiresStandaloneSource == true) #expect(proposal.resources.first?.path == ".") #expect(proposal.components.count == 1) - #expect(proposal.diagnostics.map(\.code) == [.incompletePin]) + #expect(proposal.sources.first?.producerIdentity == source) + #expect(proposal.sources.first?.pin.version == (sourceType == "node_modules" ? "1.2.3" : nil)) + #expect(proposal.sources.allSatisfy { $0.pin.commit == nil }) + #expect(proposal.bindings.isEmpty) + #expect( + proposal.diagnostics.map(\.code) + == (sourceType == "node_modules" ? [.incompletePin, .unconverted] : [.incompletePin])) } @Test func vercelChangedContentCannotBePresentedAsLockedContent() throws { @@ -185,12 +195,15 @@ struct ImportSourceTests { #expect(!String(describing: proposal).contains("SECRET_LITERAL")) } - @Test func credentialSourceDoesNotEscapeThroughProvenanceOrDiagnostics() throws { + @Test(arguments: ["github", "node_modules"]) + func credentialSourceDoesNotEscapeThroughProvenanceOrDiagnostics(_ sourceType: String) throws { let fixture = try ImportSourceFixture() + let source = + sourceType == "node_modules" ? "@acme/pkg" : "https://SECRET_LITERAL@github.com/acme/repo" try fixture.write( """ - {"version":2,"skills":{"review":{"source":"https://SECRET_LITERAL@github.com/acme/repo", - "sourceType":"github","sourceUrl":"https://github.com/acme/repo?token=SECRET_LITERAL","computedHash":""}}} + {"version":2,"skills":{"review":{"source":"\(source)", + "sourceType":"\(sourceType)","sourceUrl":"https://github.com/acme/repo?token=SECRET_LITERAL","computedHash":""}}} """) let before = try FileHash.folderHash(fixture.root) let proposal = try SourceImport.preview(fixture.input(.vercelProjectV2)) From 741f3f6843db9f20adcb90d67d058735399b72bb Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:14:01 +0800 Subject: [PATCH 077/171] fix: admit recorded recipient paths by byte identity --- Sources/AgentsCore/TransactionPaths.swift | 13 ++- .../RegisteredNativeTargetTests.swift | 103 ++++++++++++++---- 2 files changed, 89 insertions(+), 27 deletions(-) diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index c016dff..8facf22 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -46,22 +46,29 @@ struct TransactionPaths { return target.path } } + var matchingInstallation = false for agent in AgentID.allCases { let logical = AgentRegistry.installSkillsDirectory( for: agent, scope: store.scope, environment: store.environment) let physical = logical.resolvingSymlinksInPath() let parent = destination.deletingLastPathComponent().standardizedFileURL - if parent.path == logical.standardizedFileURL.path || parent.path == physical.path { + if parent.path.utf8.elementsEqual(logical.standardizedFileURL.path.utf8) + || parent.path.utf8.elementsEqual(physical.path.utf8) + { + matchingInstallation = true guard try PathSafety.sanitizeName(destination.lastPathComponent) == destination.lastPathComponent || persistedInstallation(destination.lastPathComponent, agent: agent) - else { throw CoreError.unsafePath("unrecorded noncanonical installation target") } + else { continue } let path = agent.rawValue + "/" + destination.lastPathComponent _ = try components(path) return path } } + if matchingInstallation { + throw CoreError.unsafePath("unrecorded noncanonical installation target") + } for state in [store.directory.standardizedFileURL, physicalState] { if PathSafety.isContained(destination.standardizedFileURL, in: state) { let path = "state/" + PathSafety.relativePath(destination.path, to: state.path) @@ -149,7 +156,7 @@ struct TransactionPaths { let ledger = try ResolvedLedgerCodec.decode(bytes, limits: .standard) return ledger.deployments.contains { $0.target.kind == .registered && $0.target.root == "skills-" + agent.rawValue - && $0.target.path == name && $0.recipients.contains(agent) + && $0.target.path.utf8.elementsEqual(name.utf8) && $0.recipients.contains(agent) && $0.route == "agents/skill@1" } } diff --git a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift index 7e57782..3a3ae72 100644 --- a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift +++ b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift @@ -87,37 +87,23 @@ struct RegisteredNativeTargetTests { #expect(!FileManager.default.fileExists(atPath: store.directory.path)) } - @Test(arguments: [false, true]) - func legacyInstallationSpellingRequiresItsExactCommittedRecipient(_ rollback: Bool) throws { + @Test(arguments: [false, true], [AgentID.codex, .cursor]) + func legacyInstallationSpellingRequiresItsExactCommittedRecipient( + _ rollback: Bool, _ agent: AgentID + ) throws { let fixture = try NativeRouteFixture() let store = fixture.store let parent = AgentRegistry.installSkillsDirectory( - for: .codex, scope: .project, environment: store.environment) + for: agent, scope: .project, environment: store.environment) try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) let legacy = parent.appendingPathComponent("Example Skill") try Data("old".utf8).write(to: legacy) - var ledger = ResolvedLedger() - ledger.sources["fixture"] = LedgerSource(kind: .local, revision: "live") - ledger.components["skill"] = LedgerComponent( - declaringSource: "fixture", source: "fixture", root: ".", kind: "skills", - name: "Example Skill", - payload: .init(object: [:]), conditions: [], recipients: [.codex], chatGPT: false, - resources: []) - ledger.deployments = [ - LedgerDeployment( - id: "deployment", - target: .init(kind: .registered, root: "skills-codex", path: "Example Skill"), - route: "agents/skill@1", owners: ["skill"], recipients: [.codex], ownership: .generated, - expectedHash: "sha256:" + FileHash.sha256Hex(data: Data("old".utf8)), created: true) - ] - ledger.lowerings = [ - LockedLowering( - id: "lowering", format: "agents/skill@1", inputs: ["skill"], resources: [], - deployments: ["deployment"], layout: .init(object: [:]), platform: "macos", artifacts: []) - ] - try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) - try ResolvedLedgerCodec.encode(ledger, limits: .standard).write(to: store.resolvedURL) + let ledger = try fixture.recordSkill(name: "Example Skill", agent: agent) let transaction = FileTransaction(store: store) { point in + if point == "entry.0.applied" { + let journal = try fixture.journal() + #expect(journal.entries.first?.path == agent.rawValue + "/Example Skill") + } if rollback && point == "entry.1.applied" { throw CoreError.invalidState("fixture rollback") } } try transaction.replace(legacy, with: .data(Data("next".utf8))) @@ -157,6 +143,49 @@ struct RegisteredNativeTargetTests { !FileManager.default.fileExists(atPath: parent.appendingPathComponent("example-skill").path)) } + #if os(Linux) + @Test func distinctUnicodeFilenamesKeepSeparateInstallationAuthority() throws { + let fixture = try NativeRouteFixture() + let recorded = "\u{00E9} Skill" + let alternate = "e\u{0301} Skill" + try fixture.recordSkill(name: recorded, agent: .codex) + let parent = AgentRegistry.installSkillsDirectory( + for: .codex, scope: .project, environment: fixture.store.environment) + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + let authorized = parent.appendingPathComponent(recorded) + let unrecorded = parent.appendingPathComponent(alternate) + let recordedBytes = Data("old".utf8) + let alternateBytes = Data("unrecorded before".utf8) + let directory = try DirectoryHandle(at: parent) + try directory.write(recorded, data: recordedBytes) + try directory.write(alternate, data: alternateBytes) + #require(authorized.lastPathComponent.utf8.elementsEqual(recorded.utf8)) + #require(unrecorded.lastPathComponent.utf8.elementsEqual(alternate.utf8)) + let first = FileObjectIdentity(try #require(try directory.info(recorded))) + let second = FileObjectIdentity(try #require(try directory.info(alternate))) + #require(first != second) + let names = try directory.names() + #require(names.contains(where: { $0.utf8.elementsEqual(recorded.utf8) })) + #require(names.contains(where: { $0.utf8.elementsEqual(alternate.utf8) })) + let refused = FileTransaction(store: fixture.store) + #expect(throws: CoreError.self) { try refused.delete(unrecorded) } + #expect(throws: CoreError.self) { + try refused.replace(unrecorded, with: .data(Data("unauthorized".utf8))) + } + #expect(try directory.info(recorded).map(FileObjectIdentity.init) == first) + #expect(try directory.info(alternate).map(FileObjectIdentity.init) == second) + #expect(try Data(contentsOf: authorized) == recordedBytes) + #expect(try Data(contentsOf: unrecorded) == alternateBytes) + let allowed = FileTransaction(store: fixture.store) + try allowed.replace(authorized, with: .data(Data("recorded after".utf8))) + try allowed.commit() + #expect(try Data(contentsOf: authorized) == Data("recorded after".utf8)) + #expect(try Data(contentsOf: unrecorded) == alternateBytes) + #expect(try directory.info(alternate).map(FileObjectIdentity.init) == second) + #expect(try directory.info(recorded).map(FileObjectIdentity.init) != second) + } + #endif + @Test(arguments: NativeTargetRoute.allCases) func registeredFilesPublishPrivatelyAndRetainTheirReceipt(_ route: NativeTargetRoute) throws { let fixture = try NativeRouteFixture() @@ -514,6 +543,32 @@ private final class NativeRouteFixture { } } deinit { removeTemporaryDirectory(root) } + @discardableResult + func recordSkill(name: String, agent: AgentID) throws -> ResolvedLedger { + let store = self.store + var ledger = ResolvedLedger() + ledger.sources["fixture"] = LedgerSource(kind: .local, revision: "live") + ledger.components["skill"] = LedgerComponent( + declaringSource: "fixture", source: "fixture", root: ".", kind: "skills", + name: name, + payload: .init(object: [:]), conditions: [], recipients: [agent], chatGPT: false, + resources: []) + ledger.deployments = [ + LedgerDeployment( + id: "deployment", + target: .init(kind: .registered, root: "skills-" + agent.rawValue, path: name), + route: "agents/skill@1", owners: ["skill"], recipients: [agent], ownership: .generated, + expectedHash: "sha256:" + FileHash.sha256Hex(data: Data("old".utf8)), created: true) + ] + ledger.lowerings = [ + LockedLowering( + id: "lowering", format: "agents/skill@1", inputs: ["skill"], resources: [], + deployments: ["deployment"], layout: .init(object: [:]), platform: "macos", artifacts: []) + ] + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + try ResolvedLedgerCodec.encode(ledger, limits: .standard).write(to: store.resolvedURL) + return ledger + } func journal() throws -> TransactionJournal { try FileTransaction.readJournal( Data(contentsOf: store.directory.appendingPathComponent("transaction.json"))) From 0356e4ebd880c3769094be633dbb343b17d8dc55 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:14:01 +0800 Subject: [PATCH 078/171] feat: prune owned empty native containers atomically --- Sources/NativeDocuments/Model.swift | 10 +- Sources/NativeDocuments/NativeDocument.swift | 137 ++++++++-- .../ConditionalPruningTests.swift | 258 ++++++++++++++++++ 3 files changed, 384 insertions(+), 21 deletions(-) create mode 100644 Tests/NativeDocumentsTests/ConditionalPruningTests.swift diff --git a/Sources/NativeDocuments/Model.swift b/Sources/NativeDocuments/Model.swift index 24f4128..76a06ba 100644 --- a/Sources/NativeDocuments/Model.swift +++ b/Sources/NativeDocuments/Model.swift @@ -114,16 +114,24 @@ package enum NativeExpectedRegion { package enum NativeRegionEdit { case put(region: NativeRegion, expected: NativeExpectedRegion, value: NativeValue) case remove(region: NativeRegion, expected: NativeExpectedRegion) + /// The caller must hold durable creation authority for this object or array. The observation + /// must match the preimage; removal is conditional on emptiness after all descendant edits. + /// Unowned comments or ambiguous removal syntax retain the container. + case pruneCreatedContainer(region: NativeRegion, observed: NativeObservation) var region: NativeRegion { switch self { - case .put(let r, _, _), .remove(let r, _): r + case .put(let r, _, _), .remove(let r, _), .pruneCreatedContainer(let r, _): r } } var expected: NativeExpectedRegion { switch self { case .put(_, let e, _), .remove(_, let e): e + case .pruneCreatedContainer(_, let observation): .createdContainer(observation) } } + var isConditionalPrune: Bool { + if case .pruneCreatedContainer = self { true } else { false } + } } package struct PreparedNativeChange { diff --git a/Sources/NativeDocuments/NativeDocument.swift b/Sources/NativeDocuments/NativeDocument.swift index c6d6ced..e7f8ca2 100644 --- a/Sources/NativeDocuments/NativeDocument.swift +++ b/Sources/NativeDocuments/NativeDocument.swift @@ -72,17 +72,30 @@ package struct NativeDocument { throw NativeDocumentError.unsupportedEdit(.wouldRewriteUnownedStructure, edit.region, []) } let address = try address(edit.region) - for previous in addresses { + for (index, previous) in addresses.enumerated() { try budget.step(address.reduce(0) { $0 + $1.work } + previous.reduce(0) { $0 + $1.work }) - if address.starts(with: previous) || previous.starts(with: address) { + let conditionalAncestor = + (edit.isConditionalPrune && previous.count > address.count + && previous.starts(with: address)) + || (edits[index].isConditionalPrune && address.count > previous.count + && address.starts(with: previous)) + if !conditionalAncestor + && (address.starts(with: previous) || previous.starts(with: address)) + { throw NativeDocumentError.unsupportedEdit(.overlappingEdits, edit.region, []) } } let existing = try resolve(edit.region, on: root) if case .createdContainer = edit.expected { - guard case .remove = edit, let existing, existing.kind == .object, - existing.members.isEmpty - else { throw NativeDocumentError.ownershipMismatch(edit.region) } + if edit.isConditionalPrune { + guard let existing, existing.kind == .object || existing.kind == .array else { + throw NativeDocumentError.ownershipMismatch(edit.region) + } + } else { + guard case .remove = edit, let existing, existing.kind == .object, + existing.members.isEmpty + else { throw NativeDocumentError.ownershipMismatch(edit.region) } + } } switch edit.expected { case .absent: @@ -103,9 +116,37 @@ package struct NativeDocument { var created: [NativeRegion] = [] var observed: [Int] = [] var removed: [([AddressStep], Int)] = [] - for (editIndex, edit) in edits.enumerated() { + try budget.allocate(edits.count, stage: "native edit order") + var prunes: [Int] = [] + var order: [Int] = [] + for index in edits.indices { + try budget.step() + if edits[index].isConditionalPrune { prunes.append(index) } else { order.append(index) } + } + try prunes.sort { + try budget.step() + return addresses[$0].count == addresses[$1].count + ? $0 < $1 : addresses[$0].count > addresses[$1].count + } + try budget.allocate(prunes.count, stage: "conditional prune order") + order.append(contentsOf: prunes) + for editIndex in order { + let edit = edits[editIndex] + try budget.step() let effective = try current.region(edit.region, at: addresses[editIndex], removed: removed) let old = try current.resolve(effective, on: current.root) + if edit.isConditionalPrune { + guard let old else { + // Dotted TOML parents can disappear with their last owned entry. + changed.append(edit.region) + continue + } + guard + (old.kind == .object && old.members.isEmpty) + || (old.kind == .array && old.elements.isEmpty) + else { continue } + if try current.hasComments(old) { continue } + } let desired: Node? switch edit { case .put(_, _, let value): @@ -119,7 +160,7 @@ package struct NativeDocument { let parsed = try NativeDocument(bytes: Data(text.utf8), format: .json, budget: budget) desired = parsed.root } - case .remove: + case .remove, .pruneCreatedContainer: desired = nil } if let old, let desired, try old.equal(to: desired, budget: budget) { @@ -143,31 +184,45 @@ package struct NativeDocument { expected, steps: effective.steps[...], desired: desired, region: effective, created: &created) var editor = PatchBuilder(document: current, region: effective) - if let old, let desired { - try editor.diff(old, desired: desired, path: effective.steps) - } else if let old { - try editor.remove(old, path: effective.steps) - } else if let desired { - try editor.insert( - path: effective.steps, value: desired, root: current.root) - } - let candidate = try editor.apply() let checked: NativeDocument do { + if let old, let desired { + try editor.diff(old, desired: desired, path: effective.steps) + } else if let old { + try editor.remove(old, path: effective.steps) + } else if let desired { + try editor.insert(path: effective.steps, value: desired, root: current.root) + } + let candidate = try editor.apply() checked = try NativeDocument(bytes: candidate, format: format, budget: budget) } catch NativeDocumentError.invalidDocument { + if edit.isConditionalPrune { continue } throw NativeDocumentError.unsupportedEdit( .wouldRewriteUnownedStructure, edit.region, editor.patches.map(\.range)) + } catch NativeDocumentError.unsupportedEdit(let reason, _, _) + where edit.isConditionalPrune + && [.ambiguousTrivia, .syntaxNotLocated, .wouldRewriteUnownedStructure].contains(reason) + { + continue + } + var nextRemoved = removed + if desired == nil, case .element(let ordinal) = addresses[editIndex].last { + try budget.allocate(removed.count + 1, stage: "removed occurrence addresses") + try budget.allocate(addresses[editIndex].count, stage: "removed occurrence path") + nextRemoved.append((Array(addresses[editIndex].dropLast()), ordinal)) } + try current.removeVanishedContainers( + expected, checked: checked, edits: edits, prunes: prunes, addresses: addresses, + removed: nextRemoved) guard try checked.root.equal(to: expected, budget: budget) else { + if edit.isConditionalPrune { continue } throw NativeDocumentError.unsupportedEdit( .wouldRewriteUnownedStructure, edit.region, editor.patches.map(\.range)) } if desired != nil { observed.append(editIndex) - } else if case .element(let ordinal) = addresses[editIndex].last { - removed.append((Array(addresses[editIndex].dropLast()), ordinal)) } + removed = nextRemoved current = checked changed.append(edit.region) } @@ -184,6 +239,47 @@ package struct NativeDocument { } } + /// A dotted TOML object has no independent syntax to retain after its last entry goes away. + /// Only explicitly authorized conditional containers may disappear from the expected tree. + private func removeVanishedContainers( + _ expected: Node, checked: NativeDocument, edits: [NativeRegionEdit], prunes: [Int], + addresses: [[AddressStep]], removed: [([AddressStep], Int)] + ) throws { + guard format == .toml else { return } + for index in prunes { + try budget.step() + var deleted = false + for (parent, ordinal) in removed { + try budget.step( + parent.reduce(0) { $0 + $1.work } + addresses[index].reduce(0) { $0 + $1.work }) + if addresses[index].count > parent.count, + addresses[index].prefix(parent.count).elementsEqual(parent), + addresses[index][parent.count] == .element(ordinal) + { + deleted = true + break + } + } + if deleted { continue } + let original = edits[index].region + let region: NativeRegion + do { + region = try self.region(original, at: addresses[index], removed: removed, on: expected) + } catch NativeDocumentError.ownershipMismatch { + // An earlier conditional prune may already have removed an enclosing occurrence. + continue + } + guard let node = try resolve(region, on: expected), node.kind == .object, + node.members.isEmpty, node.range == nil, node.headers.isEmpty, node.entry == nil + else { continue } + let actual = try checked.region(original, at: addresses[index], removed: removed) + guard try checked.resolve(actual, on: checked.root) == nil else { continue } + var created: [NativeRegion] = [] + try change( + expected, steps: region.steps[...], desired: nil, region: region, created: &created) + } + } + private func sameRegion(_ a: NativeRegion, _ b: NativeRegion) throws -> Bool { guard a.steps.count == b.steps.count else { return false } for (a, b) in zip(a.steps, b.steps) { @@ -253,9 +349,10 @@ package struct NativeDocument { /// Addresses refer to the original snapshot. Only removals can shift other owned occurrences. private func region( - _ original: NativeRegion, at address: [AddressStep], removed: [([AddressStep], Int)] + _ original: NativeRegion, at address: [AddressStep], removed: [([AddressStep], Int)], + on startingRoot: Node? = nil ) throws -> NativeRegion { - var node: Node? = root + var node: Node? = startingRoot ?? root var steps: [NativePathStep] = [] for (index, step) in original.steps.enumerated() { try budget.step() diff --git a/Tests/NativeDocumentsTests/ConditionalPruningTests.swift b/Tests/NativeDocumentsTests/ConditionalPruningTests.swift new file mode 100644 index 0000000..d047ecb --- /dev/null +++ b/Tests/NativeDocumentsTests/ConditionalPruningTests.swift @@ -0,0 +1,258 @@ +import AgentsCore +import Foundation +import NativeDocuments +import Testing + +@Test(arguments: ["json", "jsonc", "toml-table", "toml-dotted", "toml-inline"]) +func childRemovalPrunesCreatedAncestorsInOnePrepare(_ syntax: String) throws { + let source: String + let format: NativeDocumentFormat + switch syntax { + case "json": + source = #"{"keep":true,"outer":{"inner":{"owned":1}}}"# + format = .json + case "jsonc": + source = #"{/* root note */"keep":true,"outer":{"inner":{"owned":1}}}"# + format = .jsonc(trailingCommas: false) + case "toml-table": + source = "keep=true\n[outer.inner]\nowned=1\n" + format = .toml + case "toml-dotted": + source = "keep=true\nouter.inner.owned=1\n" + format = .toml + default: + source = "keep=true\nouter={inner={owned=1}}\n" + format = .toml + } + let doc = try document(source, format) + let outer = keyRegion("outer") + let inner = keyRegion("outer", "inner") + let child = keyRegion("outer", "inner", "owned") + let pruneOuter = NativeRegionEdit.pruneCreatedContainer( + region: outer, observed: try #require(try doc.read(outer))) + let pruneInner = NativeRegionEdit.pruneCreatedContainer( + region: inner, observed: try #require(try doc.read(inner))) + let removal = NativeRegionEdit.remove(region: child, expected: try owned(doc, child)) + let result = try doc.prepare([pruneOuter, removal, pruneInner]) + #expect(try doc.prepare([removal, pruneInner, pruneOuter]).bytes == result.bytes) + let checked = try NativeDocument(bytes: result.bytes, format: format, budget: generousBudget()) + #expect(try checked.read(outer) == nil) + #expect(try checked.read(keyRegion("keep"))?.value == .boolean(true)) + #expect(result.changedRegions.contains(outer)) + #expect(result.changedRegions.contains(inner)) + if syntax == "json" { #expect(text(result) == #"{"keep":true}"#) } + if syntax == "jsonc" { #expect(text(result) == #"{/* root note */"keep":true}"#) } + if format == .toml { #expect(text(result).hasPrefix("keep=true\n")) } +} + +@Test(arguments: ["jsonc", "jsonc-between", "toml"]) +func conditionalPruningRetainsCommentsAndUnmanagedSiblings(_ syntax: String) throws { + let source: String + switch syntax { + case "jsonc": + source = #"{"outer":{"owned":1 /* keep note */},"other":{"owned":2,"unmanaged":3},"empty":{}}"# + case "jsonc-between": + source = #"{"outer":/* keep note */{"owned":1},"other":{"owned":2,"unmanaged":3},"empty":{}}"# + default: + source = "[outer] # keep note\nowned=1\n[other]\nowned=2\nunmanaged=3\n[empty]\n" + } + let format: NativeDocumentFormat = + syntax.hasPrefix("jsonc") ? .jsonc(trailingCommas: true) : .toml + let doc = try document(source, format) + var edits: [NativeRegionEdit] = [] + for name in ["outer", "other"] { + let parent = keyRegion(name) + let child = keyRegion(name, "owned") + edits.append( + .pruneCreatedContainer(region: parent, observed: try #require(try doc.read(parent)))) + edits.append(.remove(region: child, expected: try owned(doc, child))) + } + let result = try doc.prepare(edits) + let checked = try NativeDocument(bytes: result.bytes, format: format, budget: generousBudget()) + #expect(try checked.read(keyRegion("outer"))?.value == .object([:])) + #expect(try checked.read(keyRegion("other"))?.value == .object(["unmanaged": .integer(3)])) + #expect(try checked.read(keyRegion("empty"))?.value == .object([:])) + #expect(text(result).contains("keep note")) + #expect(!result.changedRegions.contains(keyRegion("outer"))) + #expect(!result.changedRegions.contains(keyRegion("other"))) + if syntax == "toml" { + #expect(text(result).contains("[outer] # keep note\n")) + #expect(text(result).hasSuffix("unmanaged=3\n[empty]\n")) + } else { + #expect(text(result).contains("/* keep note */")) + #expect(text(result).hasSuffix(#""unmanaged":3},"empty":{}}"#)) + } +} + +@Test func creationResultsSupplyOnlyTheContainersActuallyCreated() throws { + let original = try document(#"{"existing":{},"keep":true}"#, .json) + let child = keyRegion("outer", "inner", "owned") + let installation = try original.prepare([ + .put(region: child, expected: .absent, value: .integer(1)) + ]) + #expect(!installation.createdContainers.contains(keyRegion("existing"))) + let fresh = try NativeDocument( + bytes: installation.bytes, format: .json, budget: generousBudget()) + var edits: [NativeRegionEdit] = [.remove(region: child, expected: try owned(fresh, child))] + for region in installation.createdContainers { + edits.append( + .pruneCreatedContainer(region: region, observed: try #require(try fresh.read(region)))) + } + let removal = try fresh.prepare(edits) + #expect(removal.bytes == original.bytes) +} + +@Test func pruningUsesFreshRegionEvidenceWithoutAdoptingEmptyContainers() throws { + let original = try document(#"{"created":{"owned":1},"equal":{"owned":1},"unowned":{}}"#, .json) + let parent = keyRegion("created") + let child = keyRegion("created", "owned") + let observation = try #require(try original.read(parent)) + let changed = try document(#"{"created":{"owned":2},"equal":{"owned":1},"unowned":{}}"#, .json) + do { + _ = try changed.prepare([ + .remove(region: child, expected: owned(changed, child)), + .pruneCreatedContainer(region: parent, observed: observation), + ]) + Issue.record("stale creation observation authorized a draft") + } catch NativeDocumentError.ownershipMismatch {} + do { + _ = try original.prepare([ + .pruneCreatedContainer(region: keyRegion("equal"), observed: observation) + ]) + Issue.record("equal payload supplied another region's authority") + } catch NativeDocumentError.ownershipMismatch {} + let removal = try original.prepare([.remove(region: child, expected: owned(original, child))]) + let checked = try NativeDocument(bytes: removal.bytes, format: .json, budget: generousBudget()) + #expect(try checked.read(parent)?.value == .object([:])) + #expect(try checked.read(keyRegion("unowned"))?.value == .object([:])) + #expect(throws: NativeDocumentError.self) { + try original.prepare([ + .pruneCreatedContainer( + region: NativeRegion(keys: []), + observed: #require(try original.read(NativeRegion(keys: [])))) + ]) + } + let commented = try document( + #"{"created":{/* new note */"owned":1},"equal":{"owned":1},"unowned":{}}"#, + .jsonc(trailingCommas: false)) + let retained = try commented.prepare([ + .remove(region: child, expected: owned(commented, child)), + .pruneCreatedContainer(region: parent, observed: observation), + ]) + #expect(text(retained).contains(#""created":{/* new note */}"#)) +} + +@Test func conditionalAncestorsDoNotWeakenOrdinaryOverlapChecks() throws { + let doc = try document(#"{"outer":{"child":{"owned":1}}}"#, .json) + let parent = keyRegion("outer") + let child = keyRegion("outer", "child") + let parentObservation = try #require(try doc.read(parent)) + let childObservation = try #require(try doc.read(child)) + let conflicting: [[NativeRegionEdit]] = [ + [ + .remove(region: parent, expected: .owned(parentObservation)), + .remove(region: child, expected: .owned(childObservation)), + ], + [ + .remove(region: parent, expected: .owned(parentObservation)), + .pruneCreatedContainer(region: child, observed: childObservation), + ], + [ + .pruneCreatedContainer(region: parent, observed: parentObservation), + .pruneCreatedContainer(region: parent, observed: parentObservation), + ], + ] + for edits in conflicting { + do { + _ = try doc.prepare(edits) + Issue.record("overlapping mandatory/duplicate authority was accepted") + } catch NativeDocumentError.unsupportedEdit(.overlappingEdits, _, _) {} + } + do { + _ = try doc.prepare([.remove(region: parent, expected: .createdContainer(parentObservation))]) + Issue.record("mandatory creation-only removal accepted a populated preimage") + } catch NativeDocumentError.ownershipMismatch {} +} + +@Test(arguments: ["json", "toml"]) +func conditionalPruningRemapsOccurrencesAfterOwnedRemovals(_ syntax: String) throws { + let source = + syntax == "json" + ? #"{"items":[{"id":"first","owned":0},{"payload":{"owned":1}},{"keep":true}],"outside":7}"# + : "[[items]]\nid='first'\nowned=0\n[[items]]\n[items.payload]\nowned=1\n[[items]]\nkeep=true\n[outside]\nx=7\n" + let format: NativeDocumentFormat = syntax == "json" ? .json : .toml + let doc = try document(source, format) + let array = keyRegion("items") + let occurrences = try #require(try doc.read(array)).occurrences + let first = NativeRegion([.key("items"), .occurrence(.init(idKey: "id", id: "first"))]) + let selected = NativeRegion([.key("items"), .occurrence(occurrences[1])]) + let payload = NativeRegion(selected.steps + [.key("payload")]) + let child = NativeRegion(payload.steps + [.key("owned")]) + let kept = NativeRegion([.key("items"), .occurrence(occurrences[2]), .key("keep")]) + let result = try doc.prepare([ + .pruneCreatedContainer(region: array, observed: #require(try doc.read(array))), + .pruneCreatedContainer(region: selected, observed: #require(try doc.read(selected))), + .remove(region: first, expected: owned(doc, first)), + .remove(region: child, expected: owned(doc, child)), + .put(region: kept, expected: owned(doc, kept), value: .boolean(false)), + .pruneCreatedContainer(region: payload, observed: #require(try doc.read(payload))), + ]) + let checked = try NativeDocument(bytes: result.bytes, format: format, budget: generousBudget()) + #expect(try checked.read(array)?.value == .array([.object(["keep": .boolean(false)])])) + #expect(!result.changedRegions.contains(array)) + let observation = try #require(result.observations.first) + #expect(try checked.read(observation.region)?.value == .boolean(false)) + if syntax == "json" { + #expect(text(result) == #"{"items":[{"keep":false}],"outside":7}"#) + } else { + #expect(text(result).hasSuffix("keep=false\n[outside]\nx=7\n")) + } +} + +@Test func implicitTOMLParentsRequireTheirOwnCreationAuthority() throws { + let doc = try document("outer.inner.owned=1\nkeep=true\n") + let inner = keyRegion("outer", "inner") + let child = keyRegion("outer", "inner", "owned") + do { + _ = try doc.prepare([ + .remove(region: child, expected: owned(doc, child)), + .pruneCreatedContainer(region: inner, observed: #require(try doc.read(inner))), + ]) + Issue.record("an unrecorded implicit ancestor disappeared") + } catch NativeDocumentError.unsupportedEdit(.wouldRewriteUnownedStructure, _, _) {} +} + +@Test(arguments: ["json", "toml"]) +func lastOwnedOccurrenceAndCreatedArrayCanBeRemovedTogether(_ syntax: String) throws { + let format: NativeDocumentFormat = syntax == "json" ? .json : .toml + let doc = try document( + syntax == "json" ? #"{"items":[{"owned":1}]}"# : "[[items]]\nowned=1\n", format) + let array = keyRegion("items") + let occurrence = NativeRegion([ + .key("items"), .occurrence(try #require(try doc.read(array)).occurrences[0]), + ]) + let result = try doc.prepare([ + .remove(region: occurrence, expected: owned(doc, occurrence)), + .pruneCreatedContainer(region: array, observed: #require(try doc.read(array))), + ]) + let checked = try NativeDocument(bytes: result.bytes, format: format, budget: generousBudget()) + #expect(try checked.read(NativeRegion(keys: []))?.value == .object([:])) +} + +@Test(arguments: ["json", "toml"]) +func conditionalPruningDoesNotResolveNewAmbiguityByPosition(_ syntax: String) throws { + let format: NativeDocumentFormat = syntax == "json" ? .json : .toml + let doc = try document( + syntax == "json" + ? #"{"items":[{},{},{"owned":1},{},{}]}"# : "items=[{},{},{owned=1},{},{}]\n", format) + let evidence = try #require(try doc.read(keyRegion("items"))).occurrences[2] + let selected = NativeRegion([.key("items"), .occurrence(evidence)]) + let child = NativeRegion(selected.steps + [.key("owned")]) + do { + _ = try doc.prepare([ + .remove(region: child, expected: owned(doc, child)), + .pruneCreatedContainer(region: selected, observed: #require(try doc.read(selected))), + ]) + Issue.record("an ambiguous empty occurrence was selected by its old position") + } catch NativeDocumentError.unsupportedEdit(.ambiguousOccurrence, _, _) {} +} From 71f9e406613cdc3fe86d8ca3fbe78c204be2625c Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:14:01 +0800 Subject: [PATCH 079/171] fix: preserve exact sources and authored prompt references --- Documentation/Architecture/Instructions.md | 27 +- Documentation/Architecture/Package.md | 24 +- Sources/AgentsCore/LedgerValidation.swift | 7 + Sources/AgentsCore/ResolvedLedger.swift | 33 ++ Sources/AgentsCore/SourceCache.swift | 12 + .../AgentsCore/SourceResolutionSession.swift | 77 ++++- .../InstructionSnapshotReader.swift | 33 +- .../InstructionSources.swift | 2 +- Sources/Components/Expansion.swift | 90 +++-- Sources/Components/LedgerFreeze.swift | 1 + Sources/Components/LinkedComponents.swift | 3 + .../LinkingIntegrationTests.swift | 320 ++++++++++++++++++ .../PromptReferenceTests.swift | 137 ++++++++ Tests/ComponentsTests/UserScopeTests.swift | 25 +- 14 files changed, 718 insertions(+), 73 deletions(-) create mode 100644 Tests/ComponentsTests/LinkingIntegrationTests.swift create mode 100644 Tests/ComponentsTests/PromptReferenceTests.swift diff --git a/Documentation/Architecture/Instructions.md b/Documentation/Architecture/Instructions.md index 0a9cda0..a87e1af 100644 --- a/Documentation/Architecture/Instructions.md +++ b/Documentation/Architecture/Instructions.md @@ -200,18 +200,23 @@ generated files, takes over others only with `replace`, and records targets as ## ChatGPT Prompts -`.instructions(chatGPT: [.prompt(name:sections:append:)])` declares a named -prompt with ordered `sections` and an optional scope-relative `append` file. -Update locks prompt sections with file targets. Reports list prompts whose -section content, order, membership or append path changed. A -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. +An instructions component's `chatgpt` mapping declares named prompts with ordered +`sections` and an optional `append` path. Update locks prompt sections with file +targets. Reports list prompts whose section content, order, membership or append +path changed. A revision change with identical section hashes alone does not mark +a prompt changed. -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. +For consumer-authored prompts, append remains current owner content. Its authored +path is project-relative in project scope and home-relative in user scope. Update +and installation do not require that export-only file to exist. Export verifies +locked section hashes, renders them without the notice and reads the current append +bytes. Missing, unreadable or escaping append content fails export; recorded bytes +are never a fallback. Append edits do not require a lock update. Export never writes +to ChatGPT. + +The component freeze seam records consumer append coordinates as payload metadata, +separate from deterministic installation inputs. Producer-owned append content is +instead read from the selected source snapshot and retained as an exact resource. ## Diagnostics diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 1c1d5bf..d5ee43b 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -322,8 +322,10 @@ retaining their origins. Logical conflicts are checked before artifact lowering. Core owns frozen Git candidate evidence, exact snapshots, source containment and the scoped temporary-read session. Export constraints share one version variable per normalized source; discovery roots remain distinct namespaces. Direct skill -and section pins are independent. The session reuses existing exact cached -objects only under existing locks; other mirrors, refs, locks and content remain +and section pins are independent. Exact annotated Git objects are peeled to commits +before conjunction, candidate selection and snapshot identity. Acquiring a known +object does not enumerate mutable refs or refresh the frozen reference mirror. +The session reuses existing exact cached objects only under existing locks; other mirrors, refs, locks and content remain temporary. The caller consumes borrowed resources within the linking closure; cleanup runs on success, error and cooperative cancellation. The synchronous Git runner completes owned in-flight work before cancellation returns. @@ -336,8 +338,13 @@ remain subject to lexical and real symlink containment. `SkillSnapshotReader` and `InstructionSnapshotReader` consume already selected views without independently resolving or retaining sources. Actual local edit -skills preserve their live paths. Remote-contained local sources inherit the -producer snapshot. Existing skill-index formats supply skill artifacts, and do +skills preserve their live paths. Skill keys, exclusions and overrides use canonical +semantic names while resource paths and display names retain their source spelling. +An all-selection includes members from their effective override views, admits live-only +members only when that view is selected, and omits missing effective-view members; +named selections still require their members. Named own-instruction reads validate only +the selected path and its ancestors, while full enumeration remains strict. +Remote-contained local sources inherit the producer snapshot. Existing skill-index formats supply skill artifacts, and do not define an export-package format. The linked result records relative resource evidence, source requirements, @@ -355,8 +362,13 @@ The existing public lifecycle operations still enforce their deployment subset. Root package resources use the project directory in project scope and the user-state directory in user scope. Explicit sources retain their declaring environment. Root user instructions require named sources, while imported -producer groups retain their own sections. User prompt append content is -read relative to the runtime home. +producer groups retain their own sections. Consumer-owned prompt append references +are metadata anchored to the project or, for root user declarations, runtime home. +Linking and freezing do not open these export-only inputs. Public export reads their +current bytes with lexical and real containment checks; missing or unreadable content +fails export without a frozen-byte fallback. Producer-owned append content remains +anchored to the selected immutable source and is a frozen replay resource. Installation +replay reads only its recorded resources and does not open consumer append references. The package-only `MCPConnectionRunner` performs one explicit connection test on already-bound ephemeral values. Only Components links the exact official MCP SDK; diff --git a/Sources/AgentsCore/LedgerValidation.swift b/Sources/AgentsCore/LedgerValidation.swift index 7486484..760c780 100644 --- a/Sources/AgentsCore/LedgerValidation.swift +++ b/Sources/AgentsCore/LedgerValidation.swift @@ -136,6 +136,13 @@ extension ResolvedLedger { throw CoreError.invalidState("invalid component identity") } try component.payload.validate() + if let append = component.payload.object?["localAppend"] { + let location = try LedgerLocation(ledgerValue: append) + guard component.kind == "instructions", + component.payload.object?["prompt"]?.kind == .string, + location.kind == .registered, ["project", "home"].contains(location.root) + else { throw CoreError.invalidState("invalid local prompt append") } + } try requireResources(component.resources) for condition in component.conditions { try validate(condition) } } diff --git a/Sources/AgentsCore/ResolvedLedger.swift b/Sources/AgentsCore/ResolvedLedger.swift index 09c9150..d381242 100644 --- a/Sources/AgentsCore/ResolvedLedger.swift +++ b/Sources/AgentsCore/ResolvedLedger.swift @@ -94,6 +94,39 @@ package struct LedgerLocation: Codable, Equatable, Hashable, Sendable { self.root = root self.path = path } + + package var ledgerValue: LedgerValue { + var fields: [String: LedgerValue] = ["kind": .init(kind.rawValue), "path": .init(path)] + fields["root"] = root.map { .init($0) } + return .init(object: fields) + } + + package init(ledgerValue value: LedgerValue) throws { + try value.validate() + guard let fields = value.object, + Set(fields.keys).isSubset(of: ["kind", "root", "path"]), + let kind = fields["kind"], kind.kind == .string, + let parsed = kind.text.flatMap(Kind.init(rawValue:)), + let path = fields["path"], path.kind == .string, let text = path.text, + fields["root"] == nil || fields["root"]?.kind == .string + else { throw CoreError.invalidState("invalid ledger location payload") } + self.init(kind: parsed, root: fields["root"]?.text, path: text) + try validate() + } + + /// Consumer operations read current bytes only after validating lexical and real containment. + /// Frozen replay consumes resource records and never calls this operation. + package func readContainedFile(roots: [String: URL]) throws -> Data { + guard kind == .registered, let root, let base = roots[root] else { + throw CoreError.invalidState("current file needs a registered root") + } + let file = try resolve(roots: roots) + guard + PathSafety.isContained( + file.resolvingSymlinksInPath(), in: base.resolvingSymlinksInPath()) + else { throw CoreError.unsafePath("current file escapes its registered root") } + return try FileSystem.read(at: file) + } } /// A closed tagged value vocabulary, independent of Swift's synthesized enum representation. diff --git a/Sources/AgentsCore/SourceCache.swift b/Sources/AgentsCore/SourceCache.swift index c07d08c..f9d1d79 100644 --- a/Sources/AgentsCore/SourceCache.swift +++ b/Sources/AgentsCore/SourceCache.swift @@ -99,6 +99,18 @@ package struct SourceCache { } ?? nil } + /// Acquires a known object in an owned cache, without enumerating or selecting mutable refs. + func acquireCommit(_ object: String, source: SourceDeclaration) throws -> String { + guard Self.isObjectID(object) else { + throw CoreError.invalidSource("expected an exact Git object") + } + if let commit = try catalogRevision(object, source: source) { return commit } + let mirror = try fetch(source, id: source.identity(environment: store.environment)) + return try git( + mirror, ["rev-parse", "--verify", object + "^{commit}"], + operation: .resolveRevision(revision: object), source: source.location) + } + /// Subscriptions follow branches even when installations select a tag or version range. func watchRevision(_ source: SourceDeclaration, revision: String? = nil) throws -> String { let id = try source.identity(environment: store.environment) diff --git a/Sources/AgentsCore/SourceResolutionSession.swift b/Sources/AgentsCore/SourceResolutionSession.swift index 82eda74..b9e0503 100644 --- a/Sources/AgentsCore/SourceResolutionSession.swift +++ b/Sources/AgentsCore/SourceResolutionSession.swift @@ -13,6 +13,9 @@ package final class SourceResolutionSession { package enum ReadMode { case persistentCache, temporary } private let mode: ReadMode private let temporaryCache: SourceCache + /// Exact-object acquisition cannot update the mirror behind frozen reference evidence. + private let objectCache: SourceCache + private var commits: [SourceSnapshotID: String] = [:] private var catalogs: [String: SourceCatalog] = [:] private var exact: [SourceSnapshotID: SourceSnapshot] = [:] private var localTrees: [String: SourceSnapshot] = [:] @@ -32,6 +35,8 @@ package final class SourceResolutionSession { var environment = store.environment environment.projectDirectory = workspace.appendingPathComponent("sources") temporaryCache = SourceCache(store: StateStore(scope: .project, environment: environment)) + environment.projectDirectory = workspace.appendingPathComponent("objects") + objectCache = SourceCache(store: StateStore(scope: .project, environment: environment)) } deinit { try? FileManager.default.removeItem(at: workspace) } @@ -61,6 +66,7 @@ package final class SourceResolutionSession { localTrees.removeAll() borrowed.removeAll() evidence.removeAll() + commits.removeAll() } private func requireOpen() throws { @@ -75,6 +81,7 @@ package final class SourceResolutionSession { spending: (Int) throws -> Void = { _ in } ) throws -> [SourceRevision] { try requireOpen() + let source = declaringSource(source) for requirement in requirements { try requirement?.validate() } let id = try source.identity(environment: store.environment) let exactObjects = requirements.compactMap { requirement -> String? in @@ -82,7 +89,11 @@ package final class SourceResolutionSession { return nil } if exactObjects.count == requirements.compactMap({ $0 }).count, !exactObjects.isEmpty { - return Set(exactObjects).count == 1 ? [SourceRevision(revision: exactObjects[0])] : [] + let selected = try exactObjects.map { object in + try spending(1) + return try commit(object, source: source) + } + return Set(selected).count == 1 ? [SourceRevision(revision: selected[0])] : [] } if catalogs[id] == nil { catalogs[id] = try temporaryCache.referenceCatalog(source, spending: spending) @@ -91,8 +102,13 @@ package final class SourceResolutionSession { var catalog = catalogs[id]! for requirement in requirements { if case .revision(let expression) = requirement, catalog.references[expression] == nil { - catalog.references[expression] = try temporaryCache.catalogRevision( - expression, source: source) + if SourceCache.isObjectID(expression) { + try spending(1) + catalog.references[expression] = try commit(expression, source: source) + } else { + catalog.references[expression] = try temporaryCache.catalogRevision( + expression, source: source) + } } } catalogs[id] = catalog @@ -103,6 +119,9 @@ package final class SourceResolutionSession { -> SourceSnapshot { try requireOpen() + let source = declaringSource(source) + var pin = pin + pin.revision = try commit(pin.revision, source: source) let id = try source.identity(environment: store.environment) let key = SourceSnapshotID(source: id, revision: pin.revision) let base: SourceSnapshot @@ -121,17 +140,26 @@ package final class SourceResolutionSession { liveRoot: source.kind == .local && source.requirement == nil ? source.localURL(environment: store.environment) : nil) } - if catalogs[id] != nil, - try temporaryCache.catalogRevision(pin.revision, source: selected) == pin.revision - { - base = try temporaryCache.withSnapshot( + let available: SourceCache? + if try temporaryCache.catalogRevision(pin.revision, source: selected) == pin.revision { + available = temporaryCache + } else if try objectCache.catalogRevision(pin.revision, source: selected) == pin.revision { + available = objectCache + } else { + available = nil + } + if let available { + base = try available.withSnapshot( sourceID: id, source: LockedSource( kind: selected.kind, url: selected.kind == .git ? selected.gitURL : nil, requirement: selected.requirement), revision: pin.revision, copy) } else { - base = try cache.withResolvedSnapshot(selected, cacheSource: false) { _, tree in - try copy(tree) + base = try cache.withResolvedSnapshot(selected, cacheSource: false) { resolved, tree in + guard resolved.revision == pin.revision else { + throw CoreError.invalidState("resolved snapshot differs from its commit pin") + } + return try copy(tree) } } exact[key] = base @@ -150,6 +178,37 @@ package final class SourceResolutionSession { ? source.localURL(environment: store.environment) : nil) } + private func commit(_ object: String, source: SourceDeclaration) throws -> String { + guard SourceCache.isObjectID(object) else { + throw CoreError.invalidState("snapshot requires an exact Git object") + } + let key = try SourceSnapshotID( + source: source.identity(environment: store.environment), revision: object) + if let existing = commits[key] { return existing } + let resolved: String + if let cached = try cache.catalogRevision(object, source: source) { + resolved = cached + } else if let frozen = try temporaryCache.catalogRevision(object, source: source) { + resolved = frozen + } else { + resolved = try objectCache.acquireCommit(object, source: source) + } + commits[key] = resolved + commits[SourceSnapshotID(source: key.source, revision: resolved)] = resolved + try Task.checkCancellation() + return resolved + } + + private func declaringSource(_ source: SourceDeclaration) -> SourceDeclaration { + var source = source + if source.environment == nil { + source.environment = SourceEnvironment( + projectDirectory: store.environment.projectDirectory, + homeDirectory: store.environment.homeDirectory) + } + return source + } + /// Non-Git local producers are copied once, then identified by bytes and executable flags. package func localSnapshot(_ source: SourceDeclaration) throws -> SourceSnapshot { try requireOpen() diff --git a/Sources/AgentsInstructions/InstructionSnapshotReader.swift b/Sources/AgentsInstructions/InstructionSnapshotReader.swift index 5aab1b6..8bc9aae 100644 --- a/Sources/AgentsInstructions/InstructionSnapshotReader.swift +++ b/Sources/AgentsInstructions/InstructionSnapshotReader.swift @@ -10,6 +10,22 @@ package struct SnapshotInstruction: Equatable, Sendable { /// Reads conventional containers in an exact source view. It does not resolve, cache or render. package enum InstructionSnapshotReader { + /// Named own selection does not inspect unrelated authoring drafts or entries. + package static func read(_ view: SourceSnapshot, own name: String) throws -> SnapshotInstruction? + { + guard Declaration.isInstructionName(name) else { + throw CoreError.invalidSource("invalid instruction name: \(name)") + } + let root = try view.directory() + let container = + root.lastPathComponent == ".agent" ? "instructions" : InstructionSources.ownContainer + let file = root.appendingPathComponent(container).appendingPathComponent(name + ".md") + let path = try view.relativePath(file) + try InstructionSources.requireNoLinks(file, below: view.root) + guard FileManager.default.fileExists(atPath: file.path) else { return nil } + return try read(view, name: name, path: path) + } + package static func read(_ view: SourceSnapshot, own: Bool = false) throws -> [SnapshotInstruction] { @@ -28,15 +44,18 @@ package enum InstructionSnapshotReader { throw CoreError.invalidSource("duplicate instruction name: \(name)") } let path = try view.relativePath(file) - let bytes = try FileSystem.read(at: view.resource(path)) - let id = view.snapshot.source + ":" + name - let section = try Instructions.validateSource(bytes, id: id, allowRestrictions: true) - result.append( - SnapshotInstruction( - name: name, path: path, bytes: bytes, - section: section)) + result.append(try read(view, name: name, path: path)) } } return result.sorted { $0.name < $1.name } } + + private static func read(_ view: SourceSnapshot, name: String, path: String) throws + -> SnapshotInstruction + { + let bytes = try FileSystem.read(at: view.resource(path)) + let section = try Instructions.validateSource( + bytes, id: view.snapshot.source + ":" + name, allowRestrictions: true) + return SnapshotInstruction(name: name, path: path, bytes: bytes, section: section) + } } diff --git a/Sources/AgentsInstructions/InstructionSources.swift b/Sources/AgentsInstructions/InstructionSources.swift index 04ad541..6bc45f7 100644 --- a/Sources/AgentsInstructions/InstructionSources.swift +++ b/Sources/AgentsInstructions/InstructionSources.swift @@ -202,7 +202,7 @@ final class InstructionSources { } /// Rejects a symbolic link at `url` or at any directory between `tree` and it. - private static func requireNoLinks(_ url: URL, below tree: URL) throws { + 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)) diff --git a/Sources/Components/Expansion.swift b/Sources/Components/Expansion.swift index 8729c79..4043763 100644 --- a/Sources/Components/Expansion.swift +++ b/Sources/Components/Expansion.swift @@ -304,32 +304,67 @@ final class Expansion { let requestedNames: [String]? switch selection.select { case .all: requestedNames = nil - case .names(let names): requestedNames = names + case .names(let names): requestedNames = names.map(PathSafety.sanitizeName) } + let excluded = Set((selection.exclude ?? []).map(PathSafety.sanitizeName)) + var overrides: [String: SkillOverride] = [:] + for (name, override) in selection.overrides ?? [:] { + let canonical = PathSafety.sanitizeName(name) + guard overrides[canonical] == nil else { + throw LinkError.invalid("duplicate canonical skill override: \(canonical)", location) + } + overrides[canonical] = override + } + func selectedMode(_ name: String) -> InstallMode { + overrides[name]?.mode ?? selection.mode ?? .link + } + var discovered: [SourceSnapshotID: [SnapshotSkill]] = [:] + func members(_ view: SourceSnapshot, live: Bool) throws -> [SnapshotSkill] { + if let existing = discovered[view.snapshot] { return existing } + let result = try SkillSnapshotReader.read(view, live: live) + discovered[view.snapshot] = result + return result + } + // Membership comes from the default view plus only explicitly overridden alternate members. // Each direct member may retain a different pin even when it shares an alias with exports. let names: [String] if let requestedNames { names = requestedNames } else { let live = selection.mode == .edit - names = try SkillSnapshotReader.read(selectedView(address, key: nil, live: live), live: live) - .map(\.name) + let primary = try selectedView(address, key: nil, live: live) + var selected = try members(primary, live: live).map { PathSafety.sanitizeName($0.name) } + for name in overrides.keys.sorted() + where !excluded.contains(name) && (selectedMode(name) == .edit) != live { + let view = try selectedView( + address, key: key(name, kind: .skills, context: context, group: group), + live: selectedMode(name) == .edit) + if try members(view, live: selectedMode(name) == .edit).contains(where: { + PathSafety.sanitizeName($0.name) == name + }) { + selected.append(name) + } + } + names = Array(Set(selected)).sorted() } - for name in names where !(selection.exclude ?? []).contains(name) { - let componentKey = key(name, kind: .skills, context: context, group: group) - let override = selection.overrides?[name] - let mode = override?.mode ?? selection.mode ?? .link - let view = try selectedView(address, key: componentKey, live: mode == .edit) + for name in names where !excluded.contains(name) { + let requestedKey = key(name, kind: .skills, context: context, group: group) + let override = overrides[name] + let mode = selectedMode(name) + let view = try selectedView(address, key: requestedKey, live: mode == .edit) if mode == .edit, view.liveRoot == nil { throw LinkError.invalid("edit requires an actual local skill with no requirement", location) } - let matches = try SkillSnapshotReader.read(view, live: mode == .edit).filter { - $0.name == name || PathSafety.sanitizeName($0.name) == name - || URL(fileURLWithPath: $0.path).lastPathComponent == name + let matches = try members(view, live: mode == .edit).filter { + PathSafety.sanitizeName($0.name) == name + || PathSafety.sanitizeName(URL(fileURLWithPath: $0.path).lastPathComponent) == name } + if matches.isEmpty, requestedNames == nil { continue } guard matches.count == 1, let skill = matches.first else { throw LinkError.missing("skill '\(name)'", location) } + let componentKey = key( + PathSafety.sanitizeName(skill.name), kind: .skills, context: context, group: group) let effective = condition.intersecting(skill.condition) let resource = LinkedResource( snapshot: view.snapshot, path: skill.path, @@ -410,10 +445,11 @@ final class Expansion { let address = try linking.address(section.source, in: context, chain: location) let componentKey = key(section.name, kind: .instructions, context: context, group: group) let view = try selectedView(address, key: componentKey) - guard - let unit = try InstructionSnapshotReader.read(view, own: own).first(where: { - $0.name == section.name - }) + let selected = + try own + ? InstructionSnapshotReader.read(view, own: section.name) + : InstructionSnapshotReader.read(view).first(where: { $0.name == section.name }) + guard let unit = selected else { throw LinkError.missing("instruction '\(section.name)'", location) } @@ -424,20 +460,16 @@ final class Expansion { snapshot: view.snapshot, path: unit.path, hash: unit.section.hash, executableFlags: [:]) ] + var localAppend: LedgerLocation? if let appendPath { - if linking.store.scope == .user { - let home = linking.store.environment.homeDirectory - let view = try SourceSnapshot( - snapshot: SourceSnapshotID(source: "local:" + home.path, revision: "live"), - pin: nil, root: home, - localEnvironment: SourceEnvironment(projectDirectory: home, homeDirectory: home), - liveRoot: home) - try linking.budget.snapshot(view.snapshot) - linking.session.register(view) - resources.append(try resource(appendPath, in: view, chain: location)) - } else { + if context.producer { resources.append( try resource(ResourceDeclaration(path: appendPath), context: context, chain: location)) + } else { + localAppend = LedgerLocation( + kind: .registered, root: linking.store.scope == .user ? "home" : "project", + path: try PathSafety.sanitizeSubpath(appendPath)) + try localAppend?.validate() } } let recipients = @@ -452,7 +484,7 @@ final class Expansion { chatGPT: prompt != nil && effective.matches(scope: linking.store.scope, platform: linking.platform), resources: resources, chain: chain, position: position, - dependencies: dependencies + resources.map(\.snapshot)) + dependencies: dependencies + resources.map(\.snapshot), localAppend: localAppend) } private func constrainResource( @@ -513,7 +545,7 @@ final class Expansion { payload: LinkedPayload, context: LinkingDocument, group: String?, condition: DeclarationCondition, recipients: Set, chatGPT: Bool, resources: [LinkedResource], chain: [SourceSpan], position: SourceMapEntry?, - dependencies: [SourceSnapshotID] + dependencies: [SourceSnapshotID], localAppend: LedgerLocation? = nil ) throws { try linking.budget.contribution(chain: chain.count + (position?.origins.count ?? 0)) let occurrence = nextOccurrence @@ -535,7 +567,7 @@ final class Expansion { key: key, declaringSnapshot: context.view.snapshot, snapshot: snapshot, pin: pin, payload: payload, conditions: [condition], recipients: recipients, chatGPT: chatGPT, resources: resources, - origins: [origin])) + origins: [origin], localAppend: localAppend)) } func result() throws -> LinkedComponents { diff --git a/Sources/Components/LedgerFreeze.swift b/Sources/Components/LedgerFreeze.swift index 41d08b0..73eae56 100644 --- a/Sources/Components/LedgerFreeze.swift +++ b/Sources/Components/LedgerFreeze.swift @@ -133,6 +133,7 @@ package enum LedgerFreeze { "sourceHash": .init(instruction.section.hash), "native": LedgerPayload.native(native), ] fields["prompt"] = prompt.map { .init($0) } + fields["localAppend"] = component.localAppend?.ledgerValue payload = .init(object: fields) } let record = LedgerComponent( diff --git a/Sources/Components/LinkedComponents.swift b/Sources/Components/LinkedComponents.swift index 6f35f39..8dd5c6a 100644 --- a/Sources/Components/LinkedComponents.swift +++ b/Sources/Components/LinkedComponents.swift @@ -70,6 +70,8 @@ package struct LinkedComponent: Equatable, Sendable { package let chatGPT: Bool package let resources: [LinkedResource] package var origins: [ContributionOrigin] + /// Consumer-owned export input. It is not read or retained for installation replay. + package var localAppend: LedgerLocation? = nil } package struct SourceConstraint: Equatable, Sendable { @@ -129,6 +131,7 @@ package struct LinkedComponents: Equatable, Sendable { if a.key != b.key || a.snapshot != b.snapshot || a.pin != b.pin || !a.payload.sameContent(as: b.payload) || !sameConditions + || a.localAppend != b.localAppend || a.recipients != b.recipients || a.chatGPT != b.chatGPT || a.resources != b.resources || Set(a.origins.flatMap(\.dependencies)) != Set(b.origins.flatMap(\.dependencies)) { diff --git a/Tests/ComponentsTests/LinkingIntegrationTests.swift b/Tests/ComponentsTests/LinkingIntegrationTests.swift new file mode 100644 index 0000000..c99f172 --- /dev/null +++ b/Tests/ComponentsTests/LinkingIntegrationTests.swift @@ -0,0 +1,320 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import Foundation +import Testing + +@testable import Components + +@Suite("Component integration boundaries", .serialized) +struct LinkingIntegrationTests { + @Test(arguments: [SourceKind.local, .git]) + func annotatedObjectsConjoinAndFreezeAsCommits(_ kind: SourceKind) throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("one", at: repository) + try fixture.manifest( + "version: 1\nexports: [g]\ngroups: {g: {components: [{kind: skills, source: .}]}}", + at: repository) + let commit = try fixture.commit(repository, tag: "1.0.0") + try fixture.git( + repository, ["-c", "tag.gpgsign=false", "tag", "-a", "release", "-m", "release"]) + let object = try fixture.git(repository, ["rev-parse", "release"]) + let source = SourceDeclaration( + kind: kind, location: kind == .local ? repository.path : "file://localhost" + repository.path, + requirement: .revision(object)) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session throws -> Void in + #expect( + try session.candidates(for: source, requirements: [.revision(object), .revision(commit)]) + .map(\.revision) == [commit]) + #expect( + try session.candidates(for: source, requirements: [.revision(object), .exact("1.0.0")]) + .first?.revision == commit) + let selected = try session.snapshot(source, at: .init(revision: object)) + #expect(selected.snapshot.revision == commit) + #expect(selected.pin?.revision == commit) + } + let field = kind == .local ? "path" : "url" + let document = try fixture.document( + "version: 1\nsources: {p: {\(field): '\(source.location)', requirement: {revision: '\(object)'}}}\nuses: [{source: p, group: g}]" + ) + let (graph, ledger) = try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + var locations = [ + "local:" + fixture.project.path: LedgerLocation( + kind: .registered, root: "project", path: ".") + ] + if kind == .local { + locations["local:" + repository.path] = .init( + kind: .authoringRelative, root: "project", path: "../repository") + } + return ( + graph, + try LedgerFreeze.freeze( + graph, session: session, locations: .init(sources: locations), limits: .standard) + ) + } + let decoded = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(ledger, limits: .standard), limits: .standard) + #expect(decoded.components.values.first?.revision == commit) + #expect(decoded.sources.values.contains { $0.kind == kind && $0.revision == commit }) + #expect(graph.components.first?.pin?.revision == commit) + #expect(graph.references.first?.snapshot.revision == commit) + let cache = SourceCache(store: fixture.store) + _ = try cache.resolve(source) + try fixture.git(repository, ["tag", "--delete", "release"]) + try FileManager.default.removeItem(at: repository) + let before = try FileHash.folderHash(fixture.store.cacheDirectory) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session throws -> Void in + #expect( + try session.candidates(for: source, requirements: [.revision(object), .revision(commit)]) + .map(\.revision) == [commit]) + #expect(try session.snapshot(source, at: .init(revision: object)).snapshot.revision == commit) + #expect(throws: (any Error).self) { + try session.snapshot(source, at: .init(revision: "main")) + } + } + #expect(try FileHash.folderHash(fixture.store.cacheDirectory) == before) + } + + @Test func exactRelativeSourceKeepsItsDeclaringEnvironment() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("one", at: repository) + let commit = try fixture.commit(repository) + let source = SourceDeclaration( + kind: .local, location: "../repository", requirement: .revision(commit)) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let candidate = try #require( + try session.candidates(for: source, requirements: [.revision(commit)]).first) + let view = try session.snapshot(source, at: candidate) + #expect(view.snapshot.source == "local:" + repository.path) + #expect(view.localEnvironment?.projectDirectory.path == repository.path) + #expect(view.snapshot.revision == commit) + } + } + + @Test func selectedOwnSectionDoesNotReadUnrelatedDrafts() throws { + let fixture = try LinkFixture() + try fixture.instruction("guide", at: fixture.project, restrictions: "agents: [\"codex\"]\n") + try fixture.write( + "---\ndescription: [unterminated\n---\nDraft", to: ".agent/instructions/draft.md", + base: fixture.project) + let graph = try fixture.link( + "version: 1\ncomponents: [{kind: instructions, sections: [{name: guide}]}]") + #expect(graph.components.map(\.key.name) == ["guide"]) + #expect(graph.components[0].recipients == [.codex]) + let view = try SourceSnapshot( + snapshot: .init(source: "own", revision: "live"), pin: nil, root: fixture.project) + #expect(throws: (any Error).self) { try InstructionSnapshotReader.read(view, own: true) } + #expect(throws: (any Error).self) { + try fixture.link("version: 1\ncomponents: [{kind: instructions, sections: [{name: draft}]}]") + } + #expect(throws: (any Error).self) { + try fixture.link( + "version: 1\ncomponents: [{kind: instructions, sections: [{name: missing}]}]") + } + let guide = fixture.project.appendingPathComponent(".agent/instructions/guide.md") + try FileManager.default.removeItem(at: guide) + try fixture.write( + "---\ndescription: Selected\n---\nBody", to: "other.md", base: fixture.project) + try FileManager.default.createSymbolicLink( + at: guide, withDestinationURL: fixture.project.appendingPathComponent("other.md")) + #expect(throws: (any Error).self) { + try fixture.link("version: 1\ncomponents: [{kind: instructions, sections: [{name: guide}]}]") + } + } + + @Test func namedReaderPreservesDiscoveryAndRejectsSelectedContainerLinks() throws { + let fixture = try LinkFixture() + let published = fixture.project.appendingPathComponent("published") + try fixture.instruction("guide", at: published, restrictions: "scopes: [\"project\"]\n") + try fixture.write( + "---\ndescription: [broken\n---\nDraft", to: ".agent/instructions/draft.md", base: published) + let view = try SourceSnapshot( + snapshot: .init(source: "reader", revision: "live"), pin: nil, root: fixture.project, + discoveryPath: "published") + let selected = try InstructionSnapshotReader.read(view, own: "guide") + let section = try #require(selected) + #expect(section.path == "published/.agent/instructions/guide.md") + #expect(section.section.condition.scopes == [.project]) + #expect(try InstructionSnapshotReader.read(view, own: "missing") == nil) + #expect(throws: (any Error).self) { try InstructionSnapshotReader.read(view, own: "../guide") } + #expect(throws: (any Error).self) { try InstructionSnapshotReader.read(view, own: "draft") } + #expect(throws: (any Error).self) { try InstructionSnapshotReader.read(view, own: true) } + let agentRoot = try SourceSnapshot( + snapshot: view.snapshot, pin: nil, root: fixture.project, discoveryPath: "published/.agent") + #expect(try InstructionSnapshotReader.read(agentRoot, own: "guide") == section) + let container = published.appendingPathComponent(".agent/instructions") + let moved = published.appendingPathComponent("actual") + try FileManager.default.moveItem(at: container, to: moved) + try FileManager.default.createSymbolicLink(at: container, withDestinationURL: moved) + #expect(throws: (any Error).self) { try InstructionSnapshotReader.read(view, own: "guide") } + } + + @Test func exactAcquisitionDoesNotRefreshFrozenExpressions() throws { + let fixture = try LinkFixture() + let sourceRoot = fixture.root.appendingPathComponent("repository") + try fixture.initialize(sourceRoot) + try fixture.skill("one", at: sourceRoot) + let first = try fixture.commit(sourceRoot) + let source = SourceDeclaration(kind: .git, location: "file://localhost" + sourceRoot.path) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + #expect(try session.candidates(for: source, requirements: [nil]).first?.revision == first) + try fixture.skill("two", at: sourceRoot) + let second = try fixture.commit(sourceRoot) + try fixture.git(sourceRoot, ["-c", "tag.gpgsign=false", "tag", "-a", "later", "-m", "later"]) + let object = try fixture.git(sourceRoot, ["rev-parse", "later"]) + #expect( + try session.candidates(for: source, requirements: [.revision(object)]).first?.revision + == second) + #expect( + try session.candidates(for: source, requirements: [.revision("main")]).first?.revision + == first) + #expect( + try session.candidates(for: source, requirements: [.branch("main")]).first?.revision + == first) + #expect(try session.snapshot(source, at: .init(revision: second)).snapshot.revision == second) + } + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } + + @Test func allMembershipUsesOverrideViewsAndCanonicalNames() throws { + let fixture = try LinkFixture() + let source = fixture.root.appendingPathComponent("skills") + try fixture.initialize(source) + try fixture.skill("Stable Skill", at: source) + try fixture.commit(source) + try fixture.skill("Live Draft", at: source) + try FileManager.default.moveItem( + at: source.appendingPathComponent("skills/Live Draft"), + to: source.appendingPathComponent("skills/folder")) + try fixture.skill("unrelated", at: source) + func expression(_ mode: String, _ override: String, named: Bool = false) -> String { + "version: 1\nsources: {s: {path: '\(source.path)'}}\ncomponents: [{kind: skills, source: s, mode: \(mode), \(named ? "select: [live-draft], " : "")overrides: {live-draft: {mode: \(override)}}}]" + } + let copy = try fixture.link(expression("copy", "edit")) + #expect(copy.components.map(\.key.name) == ["live-draft", "stable-skill"]) + let live = try #require(copy.components.first) + guard case .skill(let skill, .edit, _) = live.payload else { + Issue.record("expected live override") + return + } + #expect(skill.name == "Live Draft") + #expect(skill.path == "skills/folder") + #expect(skill.livePath == source.appendingPathComponent("skills/folder").path) + try FileManager.default.removeItem(at: source.appendingPathComponent("skills/folder")) + #expect( + try fixture.link(expression("copy", "edit")).components.map(\.key.name) == ["stable-skill"]) + #expect(throws: (any Error).self) { try fixture.link(expression("copy", "edit", named: true)) } + try fixture.skill("Live Draft", at: source) + #expect( + try fixture.link(expression("edit", "copy")).components.map(\.key.name) == [ + "stable-skill", "unrelated", + ]) + #expect(throws: (any Error).self) { try fixture.link(expression("edit", "copy", named: true)) } + try FileManager.default.removeItem(at: source.appendingPathComponent("skills/Stable Skill")) + let inverse = try fixture.link( + "version: 1\nsources: {s: {path: '\(source.path)'}}\ncomponents: [{kind: skills, source: s, mode: edit, overrides: {stable-skill: {mode: copy}}}]" + ) + #expect(inverse.components.map(\.key.name) == ["live-draft", "stable-skill", "unrelated"]) + #expect( + try fixture.link( + "version: 1\nsources: {s: {path: '\(source.path)'}}\ncomponents: [{kind: skills, source: s, exclude: [stable-skill]}]" + ).components.isEmpty) + try fixture.write( + "---\nname: broken\ndescription: [invalid]\n---\n", to: "skills/broken/SKILL.md", base: source + ) + #expect( + try fixture.link( + "version: 1\nsources: {s: {path: '\(source.path)'}}\ncomponents: [{kind: skills, source: s, mode: copy, exclude: [stable-skill], overrides: {stable-skill: {mode: edit}}}]" + ).components.isEmpty) + + } + + @Test func canonicalKeysKeepAnUnselectedMembersExactPin() throws { + let fixture = try LinkFixture() + let source = fixture.root.appendingPathComponent("skills") + try fixture.initialize(source) + for name in ["First Skill", "Second Skill"] { try fixture.skill(name, at: source) } + let first = try fixture.commit(source, tag: "1.0.0") + let expression = + "version: 1\nsources: {s: {path: '\(source.path)'}}\ncomponents: [{kind: skills, source: s, mode: copy}]" + let before = try fixture.link(expression) + let preserved = ComponentKey( + source: "local:" + fixture.project.path, root: ".", group: nil, kind: .skills, + name: "second-skill") + #expect(before.components.map(\.key.name) == ["first-skill", "second-skill"]) + try fixture.write("new", to: "skills/First Skill/new", base: source) + try fixture.write("new", to: "skills/Second Skill/new", base: source) + let second = try fixture.commit(source, tag: "1.1.0") + let after = try fixture.link(expression, directPins: [preserved: .init(revision: first)]) + #expect(after.components.map(\.snapshot.revision) == [second, first]) + #expect(after.components.last?.key == preserved) + try FileManager.default.removeItem(at: source.appendingPathComponent("skills/Second Skill")) + let third = try fixture.commit(source, tag: "1.2.0") + let explicit = expression.replacingOccurrences( + of: "mode: copy}", with: "mode: copy, select: [first-skill, second-skill]}") + let partial = try fixture.link(explicit, directPins: [preserved: .init(revision: first)]) + #expect(partial.components.map(\.snapshot.revision) == [third, first]) + } + + @Test(arguments: [InstallScope.project, .user]) + func missingConsumerAppendFreezesAsMetadata(_ scope: InstallScope) throws { + let fixture = try LinkFixture() + let store = StateStore(scope: scope, environment: fixture.environment) + let source = fixture.project.appendingPathComponent("rules") + try fixture.initialize(source) + try fixture.instruction("guide", at: source, own: false) + try fixture.commit(source) + let document = try fixture.document( + "version: 1\nsources: {s: {path: '\(source.path)'}}\ncomponents: [{kind: instructions, chatgpt: {daily: {sections: [{name: guide, source: s}], append: custom.md}}}]" + ) + let ledger = try ComponentLinker.withLinkedComponents( + document: document, store: store, platform: .macOS + ) { graph, session in + #expect(graph.components[0].resources.count == 1) + return try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: [ + "local:" + source.path: .init(kind: .registered, root: "project", path: "rules"), + "local:" + (scope == .project ? fixture.project : store.directory).path: .init( + kind: .registered, root: scope == .project ? "project" : "state", path: "."), + ]), limits: .standard) + } + let restored = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(ledger, limits: .standard), limits: .standard) + let component = try #require(restored.components.values.first) + let append = try #require(component.payload.object?["localAppend"]?.object) + #expect(append["root"]?.text == (scope == .project ? "project" : "home")) + #expect(append["path"]?.text == "custom.md") + #expect(component.resources.count == 1) + let value = try #require(component.payload.object?["localAppend"]) + let location = try LedgerLocation(ledgerValue: value) + let roots = ["project": fixture.project, "home": fixture.home, "state": store.directory] + #expect(throws: (any Error).self) { try location.readContainedFile(roots: roots) } + let target = scope == .project ? fixture.project : fixture.home + for root in [fixture.project, fixture.home, store.directory] { + try fixture.write(root == target ? "first" : "shadow", to: "custom.md", base: root) + } + #expect(try location.readContainedFile(roots: roots) == Data("first".utf8)) + try fixture.write("current", to: "custom.md", base: target) + #expect(try location.readContainedFile(roots: roots) == Data("current".utf8)) + #expect( + try ResolvedLedgerCodec.encode(restored, limits: .standard) + == ResolvedLedgerCodec.encode(ledger, limits: .standard)) + try FileManager.default.removeItem(at: target.appendingPathComponent("custom.md")) + try FileManager.default.createDirectory( + at: target.appendingPathComponent("custom.md"), withIntermediateDirectories: true) + #expect(throws: (any Error).self) { try location.readContainedFile(roots: roots) } + try FileManager.default.removeItem(at: target.appendingPathComponent("custom.md")) + try fixture.write("outside", to: "outside.md") + try FileManager.default.createSymbolicLink( + at: target.appendingPathComponent("custom.md"), + withDestinationURL: fixture.root.appendingPathComponent("outside.md")) + #expect(throws: (any Error).self) { try location.readContainedFile(roots: roots) } + } +} diff --git a/Tests/ComponentsTests/PromptReferenceTests.swift b/Tests/ComponentsTests/PromptReferenceTests.swift new file mode 100644 index 0000000..44863aa --- /dev/null +++ b/Tests/ComponentsTests/PromptReferenceTests.swift @@ -0,0 +1,137 @@ +import AgentsCore +import Components +import Foundation +import Testing + +@Suite("Frozen prompts and current append references", .serialized) +struct PromptReferenceTests { + @Test func coldReplayDoesNotReadConsumerAppend() throws { + let fixture = try LinkFixture() + try fixture.instruction("guide", at: fixture.project) + let document = try fixture.document( + "version: 1\ncomponents: [{kind: instructions, chatgpt: {daily: {sections: [{name: guide}], append: custom.md}}}]" + ) + var ledger = try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: [ + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: ".") + ]), limits: .standard) + } + let componentID = try #require(ledger.components.keys.first) + let component = ledger.components[componentID]! + #expect(component.resources.count == 1) + #if os(macOS) + let platform = "macos" + #else + let platform = "linux" + #endif + ledger.lowerings = [ + .init( + id: "prompt:daily", format: "agents/chatgpt@1", inputs: [componentID], + resources: component.resources, deployments: [], + layout: .init(object: ["name": .init("prompt:daily"), "sectionCount": .init(integer: 1)]), + platform: platform, artifacts: []) + ] + // An escaping current append must not enter the frozen installation path. + try fixture.write("CURRENT APPEND", to: "outside.md") + try FileManager.default.createSymbolicLink( + at: fixture.project.appendingPathComponent("custom.md"), + withDestinationURL: fixture.root.appendingPathComponent("outside.md")) + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: ["project": fixture.project], limits: .standard) + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + ledger = try ResolvedLedgerCodec.decode(encoded, limits: .standard) + try FileManager.default.removeItem(at: fixture.project) + try LedgerReplay.withReplay( + ledger, store: fixture.store, roots: ["project": fixture.project], limits: .standard + ) { artifacts in + let bytes = try #require(artifacts.first?.bytes) + let text = String(decoding: bytes, as: UTF8.self) + #expect(text.contains("guide")) + #expect(!text.contains("CURRENT APPEND")) + } + } + + @Test func immutableProducerAppendRemainsAnExactResource() throws { + let fixture = try LinkFixture() + let producer = fixture.root.appendingPathComponent("producer") + try fixture.instruction("guide", at: producer) + try fixture.write("FROZEN APPEND", to: "custom.md", base: producer) + try fixture.write("CONSUMER SHADOW", to: "custom.md", base: fixture.project) + try fixture.manifest( + "version: 1\nexports: [g]\ngroups: {g: {components: [{kind: instructions, chatgpt: {daily: {sections: [{name: guide}], append: custom.md}}}]}}", + at: producer) + let document = try fixture.document( + "version: 1\nsources: {p: {path: '\(producer.path)'}}\nuses: [{source: p, group: g}]") + let ledger = try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + let component = try #require(graph.components.first) + #expect(component.localAppend == nil) + #expect(component.resources.count == 2) + try fixture.write("LIVE PRODUCER SHADOW", to: "custom.md", base: producer) + let append = component.resources[1] + #expect( + try Data(contentsOf: session.resource(snapshot: append.snapshot, path: append.path)) + == Data("FROZEN APPEND".utf8)) + return try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: [ + "local:" + producer.path: .init( + kind: .authoringRelative, root: "project", path: "../producer"), + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: "."), + ]), limits: .standard) + } + let restored = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(ledger, limits: .standard), limits: .standard) + let component = try #require(restored.components.values.first) + #expect(component.payload.object?["localAppend"] == nil) + #expect(component.resources.count == 2) + let append = try #require(restored.resources[component.resources[1]]) + let object = try #require(append.entries.first?.object) + #expect(restored.contentObjects[object] == Data("FROZEN APPEND".utf8)) + } + + @Test func codecValidatesLocalAppendLocationRatherThanReadingIt() throws { + let fixture = try LinkFixture() + try fixture.instruction("guide", at: fixture.project) + let document = try fixture.document( + "version: 1\ncomponents: [{kind: instructions, chatgpt: {daily: {sections: [{name: guide}], append: missing.md}}}]" + ) + let ledger = try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: [ + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: ".") + ]), limits: .standard) + } + let id = try #require(ledger.components.keys.first) + for invalid in [ + LedgerValue(object: [ + "kind": .init("registered"), "root": .init("state"), "path": .init("missing.md"), + ]), + LedgerValue(object: [ + "kind": .init("registered"), "root": .init("project"), "path": .init("../outside"), + ]), + LedgerValue(object: ["kind": .init("absolute"), "path": .init("/tmp/append")]), + LedgerValue(object: [ + "kind": .init("registered"), "root": .init("project"), "path": .init("missing.md"), + "fallback": .init(), + ]), + ] { + var invalidLedger = ledger + invalidLedger.components[id]!.payload.object!["localAppend"] = invalid + #expect(throws: (any Error).self) { + try ResolvedLedgerCodec.encode(invalidLedger, limits: .standard) + } + } + #expect( + try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(ledger, limits: .standard), limits: .standard) == ledger) + } +} diff --git a/Tests/ComponentsTests/UserScopeTests.swift b/Tests/ComponentsTests/UserScopeTests.swift index fa573a5..a199bfc 100644 --- a/Tests/ComponentsTests/UserScopeTests.swift +++ b/Tests/ComponentsTests/UserScopeTests.swift @@ -73,16 +73,19 @@ struct UserScopeTests { components: [{"kind": "instructions", "sections": [{"name": "rules", "source": "rules"}], "chatgpt": {"p": {"sections": [{"name": "rules", "source": "rules"}], "append": "append.md"}}}] """) try ComponentLinker.withLinkedComponents(document: document, store: store, platform: .macOS) { - graph, session in + graph, _ in #expect(graph.components.map(\.key.name) == ["rules", "rules"]) #expect(graph.components[0].snapshot.source == "local:" + source.path) #expect(graph.components[1].chatGPT) - let append = try #require(graph.components[1].resources.last) - let file = try session.resource(snapshot: append.snapshot, path: append.path) - #expect(try String(contentsOf: file, encoding: .utf8) == "home append") - #expect(append.snapshot.source == "local:" + fixture.home.path) - #expect(append.path == "append.md") - #expect(graph.components[1].origins[0].dependencies.contains(append.snapshot)) + #expect(graph.components[1].resources.count == 1) + let append = try #require(graph.components[1].localAppend) + #expect(append == LedgerLocation(kind: .registered, root: "home", path: "append.md")) + #expect( + try append.readContainedFile(roots: ["home": fixture.home]) == Data("home append".utf8)) + #expect( + !graph.components[1].origins[0].dependencies.contains { + $0.source == "local:" + fixture.home.path + }) #expect(graph.components[1].origins[0].provenance.relativePath == "agents.yaml") } } @@ -112,7 +115,7 @@ struct UserScopeTests { let producer = fixture.project.appendingPathComponent("producer") try fixture.initialize(producer) try fixture.instruction("producer", at: producer) - try fixture.write("producer append shadow", to: "append.md", base: producer) + try fixture.write("producer append", to: "append.md", base: producer) try fixture.write("package append shadow", to: "append.md", base: store.directory) try fixture.write("home append", to: "append.md", base: fixture.home) try fixture.manifest( @@ -141,8 +144,10 @@ struct UserScopeTests { #expect(prompt.origins[0].provenance == component.origins[0].provenance) let append = try #require(prompt.resources.last) let file = try session.resource(snapshot: append.snapshot, path: append.path) - #expect(try String(contentsOf: file, encoding: .utf8) == "home append") - #expect(append.snapshot.source == "local:" + fixture.home.path) + #expect(try String(contentsOf: file, encoding: .utf8) == "producer append") + #expect(append.snapshot.source == "local:" + producer.path) + #expect(append.snapshot.revision == pin) + #expect(prompt.localAppend == nil) } } } From 40680f70ff09e5926d11a9705abcc8c6bf5dce7d Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:14:01 +0800 Subject: [PATCH 080/171] fix: preserve lifecycle ownership and selection semantics --- Documentation/Architecture/Instructions.md | 9 +- Documentation/Architecture/State.md | 53 +++-- Documentation/Architecture/Updates.md | 8 +- .../AgentsUpdates/InstructionOperations.swift | 29 ++- Sources/AgentsUpdates/SkillOperations.swift | 35 +++- Sources/AgentsUpdates/UpdateOperations.swift | 1 + Sources/AgentsUpdates/UpdatePlan.swift | 27 ++- Sources/AgentsUpdates/UpdateReporting.swift | 20 +- Sources/Components/ArtifactAggregation.swift | 25 +-- .../Components/DeploymentConstruction.swift | 13 ++ Sources/Components/LedgerImpact.swift | 7 +- .../WatchDurabilityTests.swift | 2 +- .../WatchPreparationTests.swift | 6 +- Tests/AgentsCoreTests/WatchSourceTests.swift | 4 +- Tests/AgentsCoreTests/WatchStateTests.swift | 16 +- .../LedgerCompatibilityTests.swift | 2 +- .../LifecycleSafetyTests.swift | 50 +++-- .../LifecycleTests.swift | 6 +- .../SourceDiagnosticTests.swift | 8 +- .../AutomaticSelectionTests.swift | 8 +- .../DefaultResolutionTests.swift | 6 +- .../IndexedArtifactLifecycleTests.swift | 187 ++++++++++++++++++ .../LifecycleRegressionTests.swift | 33 +++- .../ManifestLifecycleTests.swift | 67 ++++--- .../PublicLifecycleTests.swift | 46 ++++- .../ReadOnlyInspectionTests.swift | 11 +- .../SkillLifecycleTests.swift | 55 ++++-- .../SourceShorthandTests.swift | 2 +- .../TransactionDoctorTests.swift | 2 +- .../UpdateReportingTests.swift | 18 +- .../WatchSubscriptionTests.swift | 30 +-- .../CombinedUpdateTests.swift | 28 +-- .../LifecycleCompositionTests.swift | 69 +++++-- .../RequirementUpdateTests.swift | 2 +- Tests/AgentsUpdatesTests/UpdateFixture.swift | 2 +- .../UpdateTransactionTests.swift | 5 + .../DeclarationStateFixture.swift | 12 +- 37 files changed, 689 insertions(+), 215 deletions(-) create mode 100644 Tests/AgentsSkillsTests/IndexedArtifactLifecycleTests.swift diff --git a/Documentation/Architecture/Instructions.md b/Documentation/Architecture/Instructions.md index aa6957a..a5d67c0 100644 --- a/Documentation/Architecture/Instructions.md +++ b/Documentation/Architecture/Instructions.md @@ -167,7 +167,7 @@ bytes/presence, target ancestry and all Claude forwarding decision inputs before and after retention. Lifecycle methods are public extensions in `AgentsUpdates`, which owns the complete linked ledger and one transaction for selected deployments, declaration, resources and pruning. Consumers import that -product for lifecycle and locked ChatGPT rendering; pure text APIs remain here. +product for lifecycle and ChatGPT export; pure text APIs remain here. See [Updates](Updates.md) for selection, prepared handles and exact restore. Mutations hold the scope writer lock and use the durable journal for instruction @@ -204,8 +204,11 @@ prompt with ordered `sections` and an optional scope-relative `append` file. Update locks prompt sections with file targets. Reports list prompts whose section content, order, membership or append path changed. A 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. +changed. Consumer-owned append files remain live owner content; their independent +edits do not require a lock update. Update and install may run before the append +file exists. Public export resolves the current file against the declaring project +or user home, and rejects missing, unreadable or escaping files. Append resources +owned by an immutable producer remain frozen and anchored to that selected source. 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 diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index 9805338..00acb7e 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -76,9 +76,10 @@ then a number is appended. A skill selection is all members, when `select` is omitted or `all`, or an explicit name array, with optional exclusions, recipients, mode and per-skill overrides. An all-member selection follows discovery membership on an unnamed -update. Removing a member adds an exclusion. Explicitly named updates resolve -only those members and fail if a requested member is missing. Skill filesystem -identities are unique within a scope across sources. +update. Removing a member adds an exclusion and uses recorded membership without +installing newly discovered members. Explicitly named updates resolve only those +members and fail if a requested member is missing. Physical skill targets have one +compatible owner; distinct sources may serve the same name at disjoint targets. Requirements are `branch:`, `revision:`, `exact:`, `from:` (up to the next major version), `upToNextMinor:` or `{from:, to:}`. Ranges include @@ -751,13 +752,14 @@ that content as a directory and rejects links escaping the installed subtree. Links to content within the same project or user state root are relative, so moving that root preserves them; external live edit links are absolute. `edit` points directly at a live local skill without pin or hash and requires a source -without a requirement. Local non-Git directories support edit mode. Git-backed -link and copy operations read committed trees, including when the source has -uncommitted changes. - -Source listing can fetch into a mirror. Configuration previews use temporary acquisition and never mutate persistent mirrors, refs, cache contents or locks. Inspection -snapshots are disposable and do not move an installed tree or write state or -targets. Skill and instruction `add` discover choices through the read path when +without a requirement. Link and copy freeze non-Git local directories into embedded +resources that support cold restore; an explicit Git requirement needs a Git source. +Git-backed link and copy operations read committed trees, including when the source +has uncommitted changes. + +Source listing and configuration previews use temporary acquisition and never +mutate persistent mirrors, refs, cache contents or locks. Inspection snapshots are +disposable and do not move an installed tree or write state or targets. Skill and instruction `add` discover choices through the read path when no names or `all` are supplied, and for `listOnly`. Their discovery uses disposable mirrors and locks, leaving the scope unchanged. Exact cached commits can be extracted under an existing mirror lock without fetching. Pending @@ -766,23 +768,20 @@ single-item addition carries the normalized source ID and exact discovered name into the writer path separately from user-entered names. Rediscovery must match that identity or fail with an error asking the caller to retry; its content and pin can refresh. Explicit names and `all` enter the writer path directly. -Applying prepares all selected content, computes differences, stages -replacements, and commits target changes and state under the scope lock. -Combined updates share a source-resolution session and baseline across skills -and instructions. The coordinator merges their owned records and rejects -incompatible source records and overlapping targets before exposing an apply -handle. It holds the writer lock while the consumer renders, revalidates -state-file bytes/presence and target/source identities, then retains pinned -content before the combined journal starts. Live edit content remains live; its -source identity and usable metadata are checked instead of a content pin. - -After retention, preconditions are checked again. One transaction queues -physical skill targets, instruction/forwarding targets, changed declaration and -lock files, and pruning against the merged lock and existing watch state. Paths -are sorted within target groups. No-change combined apply returns receipts -without rewriting state. Cancellation before apply publishes no targets, state -or retained trees; fetched mirror objects and the scope container/lock may -remain. +Applying captures the complete declaration, ledger and watch baseline under the +admitted locks. One source session links the graph with independent retained pins; +freeze keeps its ledger and source mapping paired through real lowering. Physical +aggregation rejects incompatible contributions and prepares shared native documents +once. The synchronous prepared handle retains these borrowed resources and writer +locks while the consumer renders its report and applies it. Live edit content stays +live; its identity and usable metadata are checked instead of a content pin. + +Apply validates state, targets and source evidence, retains the complete ledger/watch +reference closure, and validates again. One transaction stages resource trees and +capsules, selected physical targets, declaration, ledger, receipts and cache pruning. +No-change apply returns receipts without rewriting state. Exiting before apply +publishes no targets, state or retained trees; writer lock containers may remain. +Temporary source and replay resources are released at closure exit. Commit outcome tracking is bound to the combined journal's UUID. Recovering a separate cache publication cannot claim that the combined generation committed. diff --git a/Documentation/Architecture/Updates.md b/Documentation/Architecture/Updates.md index 7ee5faa..aff11f5 100644 --- a/Documentation/Architecture/Updates.md +++ b/Documentation/Architecture/Updates.md @@ -14,7 +14,9 @@ recorded components' pins, payloads, resources and effective recipients. A chang that requires a wider operation reports `requiresCombinedUpdate` before publishing. Producer-owned children cannot be edited as consumer declarations; their diagnostic identifies the producer and group reference. Root occurrence edits use -`ManifestEdit` and digest-scoped document handles. +`ManifestEdit` and digest-scoped document handles. Skill removal uses recorded +membership while preserving authored all-member selections and their exclusions; +new upstream members are admitted by update, not by removal. `UpdateOperations.preview(_:scope:environment:)` returns a serializable `CombinedUpdateReport`. It uses existing shared locks and never creates persistent @@ -87,7 +89,9 @@ Their add, update, remove and restore methods are public extensions in `AgentsUpdates`; consumers calling them must depend on and import `AgentsUpdates` as well as the domain product. Discovery, frontmatter and text rendering stay in the domain modules. Skill-only restore and update apply only the skill domain. -`InstructionOperations.renderChatGPT` renders the locked prompt resources. +`InstructionOperations.renderChatGPT` verifies locked sections and reads the current +consumer-owned append file at export. Update and install do not require that file; +producer-owned append resources remain frozen at their selected source. Watch remains a separate subscription API. Add inspection returns source-relative `Skill.path` and `Skill.skillFile` coordinates, never paths into a released snapshot. ## Failure and Recovery diff --git a/Sources/AgentsUpdates/InstructionOperations.swift b/Sources/AgentsUpdates/InstructionOperations.swift index d001f0c..59c5132 100644 --- a/Sources/AgentsUpdates/InstructionOperations.swift +++ b/Sources/AgentsUpdates/InstructionOperations.swift @@ -89,14 +89,27 @@ extension InstructionOperations { instructions.sectionReferences = references next.components.append(.instructions(instructions)) } - return try UpdateOperations.withDomainUpdate( - UpdateRequest( - operation: .declaration(next), kinds: [.instructions], replace: options.replace, - expectedDeclarationDigest: digest), scope: options.scope, environment: options.environment - ) { prepared in - try beforeApply?(prepared.report.instructions) - return InstructionAddOutcome( - sourceID: id, available: available, result: try prepared.apply().report.instructions) + var delivered = false + do { + return try UpdateOperations.withDomainUpdate( + UpdateRequest( + operation: .declaration(next), kinds: [.instructions], replace: options.replace, + expectedDeclarationDigest: digest), scope: options.scope, environment: options.environment + ) { prepared in + delivered = true + try beforeApply?(prepared.report.instructions) + return InstructionAddOutcome( + sourceID: id, available: available, result: try prepared.apply().report.instructions) + } + } catch let error as LinkError { + if !delivered, options.names.isEmpty, !options.all, + case .missing(let missing, _) = error, + missing == "instruction '\(selected[0].record.name)'" + { + throw CoreError.invalidState( + "automatic instruction selection changed during discovery; retry the command") + } + throw error } } diff --git a/Sources/AgentsUpdates/SkillOperations.swift b/Sources/AgentsUpdates/SkillOperations.swift index e4555f2..140555b 100644 --- a/Sources/AgentsUpdates/SkillOperations.swift +++ b/Sources/AgentsUpdates/SkillOperations.swift @@ -19,11 +19,11 @@ extension SkillOperations { if !options.skillNames.contains(name) { options.skillNames.append(name) } } let store = StateStore(scope: options.scope, environment: options.environment) - let (declaration, digest, source, id, available) = try store.withReadLock { + let (declaration, digest, ledger, source, id, available) = try store.withReadLock { let declaration = try store.readDeclaration() let digest = try store.declarationDocument(prepared: nil)?.digest ?? "absent" let (source, id, available) = try SkillOperations.inspect(options, declaration: declaration) - return (declaration, digest, source, id, available) + return (declaration, digest, try store.readLedger(), source, id, available) } if options.listOnly || (options.skillNames.isEmpty && !options.all && available.count > 1) { return AddOutcome(source: source, sourceID: id, availableSkills: available, installed: []) @@ -41,8 +41,37 @@ extension SkillOperations { { throw CoreError.invalidSource("source alias already refers to another source") } - next.sources[alias] = source let names = available.map { PathSafety.sanitizeName($0.name) } + let recipients = options.agents ?? declaration.defaultAgents + for deployment in ledger.deployments.sorted(by: { $0.id < $1.id }) + where deployment.route == "agents/skill@1" { + let target = InstructionLocations.physical( + try deployment.target.resolve(roots: store.ledgerRoots)) + guard let owner = deployment.owners.first.flatMap({ ledger.components[$0] }), + names.contains(PathSafety.sanitizeName(owner.name)) + else { continue } + let ownerID = try ledger.sourceIdentity(owner.source, roots: store.ledgerRoots) + guard ownerID != id else { continue } + let paths = names.flatMap { name in + recipients.map { agent in + ( + agent, + InstructionLocations.physical( + SkillLifecycle.target(name: name, agent: agent, store: store)) + ) + } + } + guard paths.contains(where: { $0.1 == target }) else { continue } + let ownerAlias = + try declaration.sources.keys.sorted().first { + try declaration.sources[$0]!.identity(environment: options.environment) == ownerID + } ?? owner.group ?? ownerID + let destinations = paths.map { "\($0.0.rawValue) at \($0.1.path)" }.joined(separator: ", ") + throw CoreError.invalidSkill( + "skill '\(PathSafety.sanitizeName(owner.name))' in \(options.scope.rawValue) scope is owned by '\(ownerAlias)' (\(ownerID)); '\(alias)' (\(id)) requests the same installation: \(destinations)" + ) + } + next.sources[alias] = source var updated = false for index in next.components.indices { guard case .skills(let selectedAlias, var selection) = next.components[index], diff --git a/Sources/AgentsUpdates/UpdateOperations.swift b/Sources/AgentsUpdates/UpdateOperations.swift index 52aae6d..f676cb7 100644 --- a/Sources/AgentsUpdates/UpdateOperations.swift +++ b/Sources/AgentsUpdates/UpdateOperations.swift @@ -73,6 +73,7 @@ public enum UpdateOperations { request: request, store: store, admitted: admitted, checkpoint: checkpoint, provider: provider ) { plan in + try plan.requireSkillOwnership() let update = PreparedUpdate(plan: plan, outcome: outcome) defer { update.invalidate() } delivered = true diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 6ffda1d..6eb5976 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -9,6 +9,8 @@ struct RequiredRoutes: Error { let routes: Set } /// The composition plan borrows both source/replay resources and the admitted writer scope. final class UpdatePlan { + func requireSkillOwnership() throws { try aggregation.requireSkillOwnership() } + let report: CombinedUpdateReport private let store: StateStore private let baseline: StatePrecondition @@ -97,7 +99,9 @@ final class UpdatePlan { } let updating: Bool if case .update = request.operation { updating = true } else { updating = false } - if updating, !request.names.isEmpty, request.kinds?.contains(.skills) ?? true { + let removing: Bool + if case .remove = request.operation { removing = true } else { removing = false } + if removing || (updating && !request.names.isEmpty), request.kinds?.contains(.skills) ?? true { var linkingDeclaration = candidate for index in linkingDeclaration.components.indices { guard case .skills(let alias, var selection) = linkingDeclaration.components[index], @@ -107,14 +111,25 @@ final class UpdatePlan { let existing = try previous.components.values.filter { component in guard component.kind == "skills", component.group == nil else { return false } return try previous.sourceIdentity(component.source, roots: store.ledgerRoots) == identity - }.map { PathSafety.sanitizeName($0.name) } + }.map { PathSafety.sanitizeName($0.name) }.sorted() let selected = request.names.filter { name in !previous.components.values.contains { $0.kind == "skills" && $0.name == name } || existing.contains(name) } - selection.select = .names(Array(Set(existing + selected)).sorted()) + selection.select = .names( + removing + ? existing.filter { !(selection.exclude ?? []).contains($0) } + : Array(Set(existing + selected)).sorted()) linkingDeclaration.components[index] = .skills(source: alias, selection) } + if removing { + linkingDeclaration.components.removeAll { + if case .skills(_, let selection) = $0, case .names(let names) = selection.select { + return names.isEmpty + } + return false + } + } if let bytes = try store.planDeclaration( linkingDeclaration, replacing: declaration, prepared: baseline)?.bytes { @@ -178,6 +193,12 @@ final class UpdatePlan { locations[evidence.snapshot.source] = .init(kind: .absolute, path: path) } } + for component in linked.components { + if case .skill(let skill, .copy, _) = component.payload { + try DeploymentConstruction.validateCopiedSkill( + session.resource(snapshot: component.snapshot, path: skill.path)) + } + } let frozen = try LedgerFreeze.freezeWithSources( linked, session: session, locations: .init(sources: locations), limits: .standard) let native = try DeploymentConstruction.lowerNative( diff --git a/Sources/AgentsUpdates/UpdateReporting.swift b/Sources/AgentsUpdates/UpdateReporting.swift index d5577b2..8d93edf 100644 --- a/Sources/AgentsUpdates/UpdateReporting.swift +++ b/Sources/AgentsUpdates/UpdateReporting.swift @@ -72,16 +72,20 @@ enum UpdateReporting { } let content = after[identity].flatMap { resources[$0.resource] } var diffs: [SkillFileChange] = [] - for member in membership { - let oldFiles = try entries(URL(fileURLWithPath: member.path)) - var newFiles = - try new?.installs[member.agent.rawValue] == nil ? [:] : content.map(entries) ?? [:] - if let change = changes.first(where: { $0.url.path == member.path }), + let physicalMembers = Dictionary(grouping: membership) { + InstructionLocations.physical(URL(fileURLWithPath: $0.path)).path + } + for target in physicalMembers.keys.sorted() { + let members = physicalMembers[target]! + let retained = members.contains { new?.installs[$0.agent.rawValue] != nil } + let oldFiles = try entries(URL(fileURLWithPath: target)) + var newFiles = try retained ? content.map(entries) ?? [:] : [:] + if let change = changes.first(where: { $0.url.path == target }), let destination = change.afterLink { newFiles["."] = .symbolicLink( FileTransaction.linkDestination( - destination, parent: URL(fileURLWithPath: member.path).deletingLastPathComponent(), + destination, parent: URL(fileURLWithPath: target).deletingLastPathComponent(), store: store)) } for path in Set(oldFiles.keys).union(newFiles.keys).sorted() @@ -89,11 +93,11 @@ enum UpdateReporting { diffs.append( SkillFileChange( path: path == "." - ? member.path : URL(fileURLWithPath: member.path).appendingPathComponent(path).path, + ? target : URL(fileURLWithPath: target).appendingPathComponent(path).path, before: oldFiles[path], after: newFiles[path])) } } - let paths = Set(membership.map(\.path)) + let paths = Set(physicalMembers.keys) let physical = changes.contains { $0.deployment.route == "agents/skill@1" && paths.contains($0.url.path) && $0.changed } diff --git a/Sources/Components/ArtifactAggregation.swift b/Sources/Components/ArtifactAggregation.swift index ccf1627..2b4df3e 100644 --- a/Sources/Components/ArtifactAggregation.swift +++ b/Sources/Components/ArtifactAggregation.swift @@ -27,6 +27,7 @@ package final class ArtifactAggregation: PreparedEvidence { private let resources: [String: URL] private let replace: Bool private var unownedInstructions: [String] = [] + private var unownedSkills: [String] = [] private var targets: [String: TargetPrecondition] = [:] private var writes: [String: FileTransaction.Source] = [:] private var deletes = Set() @@ -182,11 +183,8 @@ package final class ArtifactAggregation: PreparedEvidence { { resourceEvidence.append(try TargetPrecondition(url.resolvingSymlinksInPath())) } - guard - !old.isEmpty - || !FileManager.default.fileExists(atPath: path) - else { - throw CoreError.invalidSkill( + if old.isEmpty, FileManager.default.fileExists(atPath: path) { + unownedSkills.append( "skill '\(ledger.components[deployment.owners[0]]!.name)' in \(store.scope.rawValue) scope has unmanaged content at \(path); move or remove it first" ) } @@ -197,17 +195,7 @@ package final class ArtifactAggregation: PreparedEvidence { } else if mode == InstallMode.link.rawValue { source = .link(try resourceDestination(first.2.resources[0])) } else if let tree = artifact.tree { - if let real = PathSafety.realPath(tree.path), - let children = FileManager.default.enumerator( - at: tree, includingPropertiesForKeys: [.isSymbolicLinkKey]) - { - for case let child as URL in children - where try child.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true { - guard try PathSafety.linkStaysInside(child, root: real) else { - throw CoreError.unsafePath("copied skill link escapes its installed subtree") - } - } - } + try DeploymentConstruction.validateCopiedSkill(tree) source = .copy(tree) } else { throw CoreError.invalidState("skill artifact has no content") @@ -500,7 +488,12 @@ package final class ArtifactAggregation: PreparedEvidence { }) { try evidence.validate() } } + package func requireSkillOwnership() throws { + if let reason = unownedSkills.sorted().first { throw CoreError.invalidSkill(reason) } + } + package func requireOwnership() throws { + try requireSkillOwnership() guard replace || unownedInstructions.isEmpty else { throw InstructionError.unownedTargets(unownedInstructions.sorted()) } diff --git a/Sources/Components/DeploymentConstruction.swift b/Sources/Components/DeploymentConstruction.swift index 888a07b..5ab1f22 100644 --- a/Sources/Components/DeploymentConstruction.swift +++ b/Sources/Components/DeploymentConstruction.swift @@ -3,6 +3,19 @@ import AgentsInstructions import Foundation package enum DeploymentConstruction { + package static func validateCopiedSkill(_ tree: URL) throws { + guard let real = PathSafety.realPath(tree.path), + let children = FileManager.default.enumerator( + at: tree, includingPropertiesForKeys: [.isSymbolicLinkKey]) + else { return } + for case let child as URL in children + where try child.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true { + guard try PathSafety.linkStaysInside(child, root: real) else { + throw CoreError.unsafePath("copied skill link escapes its installed subtree") + } + } + } + package struct Result { package let ledger: ResolvedLedger package let inputs: [TargetPrecondition] diff --git a/Sources/Components/LedgerImpact.swift b/Sources/Components/LedgerImpact.swift index ac6ef1e..7750e1f 100644 --- a/Sources/Components/LedgerImpact.swift +++ b/Sources/Components/LedgerImpact.swift @@ -38,7 +38,8 @@ package struct LedgerImpact { direct[ ComponentKey( source: try ledger.sourceIdentity(c.declaringSource, roots: roots), root: c.root, - group: nil, kind: DeclaredComponentKind(rawValue: c.kind)!, name: c.name + group: nil, kind: DeclaredComponentKind(rawValue: c.kind)!, + name: c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name )] = SourceRevision(revision: revision, version: c.version) } self.pins = pins @@ -166,7 +167,9 @@ package struct LedgerImpact { ) throws { for occurrence in ledger.occurrences where !occurrence.consumerEditable { let c = ledger.components[occurrence.component]! - if kinds.contains(DeclaredComponentKind(rawValue: c.kind)!), names.contains(c.name) { + if kinds.contains(DeclaredComponentKind(rawValue: c.kind)!), + names.contains(c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name) + { let producer = try ledger.sourceIdentity(occurrence.declaringSource, roots: roots) let groups = Dictionary(uniqueKeysWithValues: ledger.groups.map { ($0.id, $0) }) var chain: [String] = [] diff --git a/Tests/AgentsCoreTests/WatchDurabilityTests.swift b/Tests/AgentsCoreTests/WatchDurabilityTests.swift index f2239ea..b54983f 100644 --- a/Tests/AgentsCoreTests/WatchDurabilityTests.swift +++ b/Tests/AgentsCoreTests/WatchDurabilityTests.swift @@ -171,7 +171,7 @@ final class WatchGitFixture { try store.save( declaration: Declaration(sources: [ "source": SourceDeclaration(kind: .local, location: repo.path) - ]), resolved: ResolvedState()) + ]), ledger: ResolvedLedger()) } catch { try? FileManager.default.removeItem(at: root) throw error diff --git a/Tests/AgentsCoreTests/WatchPreparationTests.swift b/Tests/AgentsCoreTests/WatchPreparationTests.swift index 5308988..93aebf6 100644 --- a/Tests/AgentsCoreTests/WatchPreparationTests.swift +++ b/Tests/AgentsCoreTests/WatchPreparationTests.swift @@ -46,8 +46,10 @@ struct WatchPreparationTests { let cached = try FileSnapshot.read(at: unreferenced) let declaration = try FileSnapshot.read(at: fixture.store.declarationURL) let watchBefore = try FileSnapshot.read(at: fixture.store.watchURL) - let edited = try StateStore.encodeState( - ResolvedState(sources: ["local:/edited": LockedSource(kind: .local)])) + var ledger = try fixture.store.loadLedger() + ledger.sources["external"] = LedgerSource( + kind: .local, location: .init(kind: .absolute, path: "/edited"), revision: "live") + let edited = try ResolvedLedgerCodec.encode(ledger, limits: .standard) let external = ExternalEdit() let watch = fixture.operations { [store = fixture.store] in try edited.write(to: store.resolvedURL) diff --git a/Tests/AgentsCoreTests/WatchSourceTests.swift b/Tests/AgentsCoreTests/WatchSourceTests.swift index 07c613b..ed5ed41 100644 --- a/Tests/AgentsCoreTests/WatchSourceTests.swift +++ b/Tests/AgentsCoreTests/WatchSourceTests.swift @@ -16,7 +16,7 @@ struct WatchSourceTests { environment: SourceEnvironment( projectDirectory: fixture.environment.projectDirectory, homeDirectory: fixture.environment.homeDirectory)) - try store.save(declaration: Declaration(sources: ["source": source]), resolved: ResolvedState()) + try store.save(declaration: Declaration(sources: ["source": source]), ledger: ResolvedLedger()) let lock = try FileSnapshot.read(at: store.resolvedURL) let added = try fixture.watch.add( @@ -40,7 +40,7 @@ struct WatchSourceTests { projectDirectory: fixture.environment.projectDirectory, homeDirectory: fixture.environment.homeDirectory)) try fixture.store.save( - declaration: Declaration(sources: ["source": source]), resolved: ResolvedState()) + declaration: Declaration(sources: ["source": source]), ledger: ResolvedLedger()) let topic = try fixture.head() try fixture.git(["branch", "topic"]) try fixture.git(["commit", "--allow-empty", "-m", "advance default branch"]) diff --git a/Tests/AgentsCoreTests/WatchStateTests.swift b/Tests/AgentsCoreTests/WatchStateTests.swift index b618224..5d044e0 100644 --- a/Tests/AgentsCoreTests/WatchStateTests.swift +++ b/Tests/AgentsCoreTests/WatchStateTests.swift @@ -30,7 +30,7 @@ struct WatchStateTests { var declaration = try store.loadDeclaration() #expect(declaration.watch == ["web", "git"]) declaration.watch = ["git", "web"] - try store.save(declaration: declaration, resolved: ResolvedState()) + try store.save(declaration: declaration, ledger: ResolvedLedger()) #expect(try Data(contentsOf: store.declarationURL) == bytes) #expect( try FileManager.default.attributesOfItem(atPath: store.declarationURL.path)[.systemFileNumber] @@ -56,7 +56,7 @@ struct WatchStateTests { "git": SourceDeclaration(kind: .local, location: "/source"), "web": SourceDeclaration(kind: .wellKnown, location: "https://example.test"), ], watch: ["web", "git"]) - try store.save(declaration: declaration, resolved: ResolvedState(), watch: watch) + try store.save(declaration: declaration, ledger: ResolvedLedger(), watch: watch) let bytes = try Data(contentsOf: store.watchURL) #expect(try store.loadWatch() == watch) #expect(bytes.last == 10) @@ -65,9 +65,9 @@ struct WatchStateTests { try #require(text.range(of: "alpha")).lowerBound < #require(text.range(of: "zebra")).lowerBound) #expect(!text.contains("timestamp")) - try store.save(declaration: declaration, resolved: ResolvedState()) + try store.save(declaration: declaration, ledger: ResolvedLedger()) #expect(try Data(contentsOf: store.watchURL) == bytes) - try store.save(declaration: declaration, resolved: ResolvedState(), watch: watch) + try store.save(declaration: declaration, ledger: ResolvedLedger(), watch: watch) #expect(try Data(contentsOf: store.watchURL) == bytes) #expect(try store.loadDeclaration().watch == ["git", "web"]) } @@ -80,7 +80,7 @@ struct WatchStateTests { environment: RuntimeEnvironment( projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: [:] )) - try store.save(declaration: Declaration(), resolved: ResolvedState(), watch: WatchState()) + try store.save(declaration: Declaration(), ledger: ResolvedLedger(), watch: WatchState()) let declaration = try Data(contentsOf: store.declarationURL) let resolved = try Data(contentsOf: store.resolvedURL) let valid = #"{"version":1,"sources":{}}"# @@ -105,7 +105,7 @@ struct WatchStateTests { try data.write(to: store.watchURL) #expect(throws: (any Error).self) { try store.loadWatch() } #expect(throws: (any Error).self) { - try store.save(declaration: Declaration(), resolved: ResolvedState(), watch: WatchState()) + try store.save(declaration: Declaration(), ledger: ResolvedLedger(), watch: WatchState()) } #expect(try Data(contentsOf: store.watchURL) == data) #expect(try Data(contentsOf: store.declarationURL) == declaration) @@ -125,7 +125,7 @@ struct WatchStateTests { try Data("invalid".utf8).write(to: store.watchURL) let before = try FileHash.folderHash(root) #expect(throws: (any Error).self) { - try store.save(declaration: Declaration(), resolved: ResolvedState()) + try store.save(declaration: Declaration(), ledger: ResolvedLedger()) } #expect(try FileHash.folderHash(root) == before) } @@ -157,7 +157,7 @@ struct WatchStateTests { let declaration = Declaration(sources: [ "source": SourceDeclaration(kind: .local, location: "/source") ]) - try store.save(declaration: declaration, resolved: ResolvedState(), watch: WatchState()) + try store.save(declaration: declaration, ledger: ResolvedLedger(), watch: WatchState()) let lockBytes = try Data(contentsOf: store.resolvedURL) let child = try stateTestProcess(root: root, arguments: ["watch-crash", checkpoint]) defer { terminateProcess(child) } diff --git a/Tests/AgentsInstructionsTests/LedgerCompatibilityTests.swift b/Tests/AgentsInstructionsTests/LedgerCompatibilityTests.swift index 2626d7c..e65d1d3 100644 --- a/Tests/AgentsInstructionsTests/LedgerCompatibilityTests.swift +++ b/Tests/AgentsInstructionsTests/LedgerCompatibilityTests.swift @@ -13,7 +13,7 @@ struct LedgerCompatibilityTests { route: "agents/instructions@1", owners: ["section"], recipients: [.codex], ownership: .generated, expectedHash: digest, created: false) - // Use the production source renderer to obtain the v1 whole-file expected hash. + // Use the production source renderer to obtain the whole-file expected hash. let root = FileManager.default.temporaryDirectory.appendingPathComponent( "ledger-compatibility-" + UUID().uuidString) try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) diff --git a/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift b/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift index 0941f76..35d67e4 100644 --- a/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift +++ b/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift @@ -173,34 +173,54 @@ struct InstructionLifecycleSafetyTests { #expect(try String(contentsOf: outside, encoding: .utf8) == "Owner content.\n") } - @Test func frozenPromptAppendIgnoresSubsequentEscapingSymlink() throws { + @Test(arguments: [InstallScope.project, .user]) + func localPromptAppendUsesCurrentScopedContentOnlyAtExport(_ scope: InstallScope) throws { let fixture = try InstructionFixture() try fixture.section("rules") try fixture.commit() - try fixture.add() - var declaration = try fixture.store().loadDeclaration() + try fixture.add(scope: scope, agents: [.codex]) + let store = fixture.store(scope) + var declaration = try store.loadDeclaration() try declaration.updateInstructions { $0?.chatgpt = [ "prompt": PromptDeclaration(sections: ["rules:rules"], append: "custom.md") ] } - try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) - let append = fixture.project.appendingPathComponent("custom.md") - try fixture.write("Frozen custom text.\n", to: append) - _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) - let rendered = try InstructionOperations.renderChatGPT( - prompt: "prompt", environment: fixture.environment) + try store.save(declaration: declaration, ledger: store.loadLedger()) + _ = try InstructionOperations.updateInstalled( + scope: scope, environment: fixture.environment, apply: true) + let lock = try Data(contentsOf: store.resolvedURL) + #expect(throws: (any Error).self) { + try InstructionOperations.renderChatGPT( + prompt: "prompt", scope: scope, environment: fixture.environment) + } + let root = scope == .project ? fixture.project : fixture.home + let other = scope == .project ? fixture.home : fixture.project + let append = root.appendingPathComponent("custom.md") + try fixture.write("Wrong scope.\n", to: other.appendingPathComponent("custom.md")) + try fixture.write("First custom text.\n", to: append) + let first = try InstructionOperations.renderChatGPT( + prompt: "prompt", scope: scope, environment: fixture.environment) + #expect(String(decoding: first, as: UTF8.self).hasSuffix("First custom text.\n")) + try fixture.write("Current custom text.\n", to: append) + try fixture.section("rules", body: "Changed upstream") + let current = try InstructionOperations.renderChatGPT( + prompt: "prompt", scope: scope, environment: fixture.environment) + let text = String(decoding: current, as: UTF8.self) + #expect(text.contains("Original") && text.hasSuffix("Current custom text.\n")) + #expect(!text.contains("Changed upstream") && !text.contains("Wrong scope")) + #expect(try Data(contentsOf: store.resolvedURL) == lock) try FileManager.default.removeItem(at: append) let outside = fixture.root.appendingPathComponent("outside.md") try fixture.write("Owner content.\n", to: outside) - try FileManager.default.createSymbolicLink( - at: fixture.project.appendingPathComponent("custom.md"), withDestinationURL: outside) - #expect( - try InstructionOperations.renderChatGPT(prompt: "prompt", environment: fixture.environment) - == rendered) + try FileManager.default.createSymbolicLink(at: append, withDestinationURL: outside) #expect(throws: (any Error).self) { - try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + try InstructionOperations.renderChatGPT( + prompt: "prompt", scope: scope, environment: fixture.environment) } + _ = try InstructionOperations.installResolvedReport( + scope: scope, environment: fixture.environment) + #expect(try Data(contentsOf: store.resolvedURL) == lock) } @Test func sourceInstructionsDirectoryCannotBeATarget() throws { diff --git a/Tests/AgentsInstructionsTests/LifecycleTests.swift b/Tests/AgentsInstructionsTests/LifecycleTests.swift index 1dbdd2c..0ff9797 100644 --- a/Tests/AgentsInstructionsTests/LifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/LifecycleTests.swift @@ -66,7 +66,7 @@ struct InstructionLifecycleTests { let store = fixture.store(.user) var declaration = try store.loadDeclaration() try declaration.updateInstructions { $0?.sections.reverse() } - try store.save(declaration: declaration, resolved: store.loadResolved()) + try store.save(declaration: declaration, ledger: store.loadLedger()) let report = try InstructionOperations.updateInstalled( scope: .user, environment: fixture.environment) #expect(report.sections.isEmpty && report.targets.isEmpty && report.changedPrompts.isEmpty) @@ -89,7 +89,7 @@ struct InstructionLifecycleTests { sources: ["rules": SourceDeclaration(kind: .local, location: fixture.repo.path)], instructions: InstructionsDeclaration( chatgpt: ["daily": PromptDeclaration(sections: ["rules:rules"])])), - resolved: ResolvedState()) + ledger: ResolvedLedger()) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) let original = try InstructionOperations.renderChatGPT( prompt: "daily", environment: fixture.environment) @@ -225,7 +225,7 @@ struct InstructionLifecycleTests { } try fixture.write( "Custom prompt.\r\n", to: fixture.project.appendingPathComponent(".agent/custom.md")) - try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) + try fixture.store().save(declaration: declaration, ledger: fixture.store().loadLedger()) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) let old = try fixture.snapshot(fixture.project, excludingCache: true) try fixture.section("one", body: "Changed") diff --git a/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift b/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift index 3d1c913..ed0a9f2 100644 --- a/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift +++ b/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift @@ -48,7 +48,7 @@ struct InstructionSourceDiagnosticTests { let object = try fixture.git(["rev-parse", "release"]) var declaration = try fixture.store().loadDeclaration() declaration.sources["rules"]?.requirement = .revision(object) - try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) + try fixture.store().save(declaration: declaration, ledger: fixture.store().loadLedger()) let mirrors = fixture.store().cacheDirectory.appendingPathComponent("mirrors") if retainMirror { try fixture.section("prompt", body: "New branch content") @@ -83,7 +83,7 @@ struct InstructionSourceDiagnosticTests { } var declaration = try fixture.store().loadDeclaration() declaration.sources["rules"]?.requirement = .revision(object) - try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) + try fixture.store().save(declaration: declaration, ledger: fixture.store().loadLedger()) let before = try fixture.snapshot() let report = try InstructionOperations.doctor(environment: fixture.environment) #expect( @@ -165,7 +165,7 @@ struct InstructionSourceDiagnosticTests { try install(fixture, kind: kind, requirement: .branch("main"), files: []) var declaration = try fixture.store().loadDeclaration() declaration.sources["rules"]?.requirement = .branch("missing") - try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) + try fixture.store().save(declaration: declaration, ledger: fixture.store().loadLedger()) let before = try fixture.snapshot() let report = try InstructionOperations.doctor(environment: fixture.environment) let failure = try #require(report.diagnostics.first { $0.kind == .sourceResolutionFailed }) @@ -211,7 +211,7 @@ struct InstructionSourceDiagnosticTests { instructions: InstructionsDeclaration( sections: files.map { "rules:" + $0 }, chatgpt: ["daily": PromptDeclaration(sections: ["rules:prompt"])])), - resolved: ResolvedState()) + ledger: ResolvedLedger()) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) } } diff --git a/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift b/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift index ff8b694..c302839 100644 --- a/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift +++ b/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift @@ -45,11 +45,15 @@ struct AutomaticSelectionTests { let replacement = fixture.root.appendingPathComponent("replacement-source") try ProcessRunner.run( "/usr/bin/git", arguments: ["clone", "--no-local", fixture.repo.path, replacement.path]) + for (key, value) in [("maintenance.auto", "false"), ("gc.auto", "0")] { + try ProcessRunner.run( + "/usr/bin/git", arguments: ["-C", replacement.path, "config", key, value]) + } declaration.sources["source"] = SourceDeclaration(kind: .local, location: replacement.path) - try store.save(declaration: declaration, resolved: ResolvedState()) + try store.save(declaration: declaration, ledger: ResolvedLedger()) } else if change == "removed-source" { declaration.sources.removeValue(forKey: "source") - try store.save(declaration: declaration, resolved: ResolvedState()) + try store.save(declaration: declaration, ledger: ResolvedLedger()) } else { if kind == "skill" { let name = change == "rename" ? "replacement" : "demo" diff --git a/Tests/AgentsSkillsTests/DefaultResolutionTests.swift b/Tests/AgentsSkillsTests/DefaultResolutionTests.swift index 10ab585..5c2f2ad 100644 --- a/Tests/AgentsSkillsTests/DefaultResolutionTests.swift +++ b/Tests/AgentsSkillsTests/DefaultResolutionTests.swift @@ -54,7 +54,7 @@ struct DefaultResolutionTests { let declaration = Declaration(sources: [ "upstream": SourceDeclaration(kind: .git, location: "file://localhost" + fixture.repo.path) ]) - try fixture.store().save(declaration: declaration, resolved: ResolvedState()) + try fixture.store().save(declaration: declaration, ledger: ResolvedLedger()) _ = try SkillOperations.add( AddOptions( source: "upstream", agents: [.codex], skillNames: ["pinned"], @@ -68,14 +68,14 @@ struct DefaultResolutionTests { #expect(FileManager.default.fileExists(atPath: mirror.path)) var unqualified = try fixture.store().loadDeclaration() unqualified.sources["upstream"]?.requirement = nil - try fixture.store().save(declaration: unqualified, resolved: fixture.store().loadResolved()) + try fixture.store().save(declaration: unqualified, ledger: fixture.store().loadLedger()) func expectDefault(_ name: String, revision: String, version: String?, body: String) throws { let cold = RuntimeEnvironment( projectDirectory: fixture.root.appendingPathComponent("cold-\(name)"), homeDirectory: fixture.environment.homeDirectory, environment: [:]) let coldStore = StateStore(scope: .project, environment: cold) - try coldStore.save(declaration: declaration, resolved: ResolvedState()) + try coldStore.save(declaration: declaration, ledger: ResolvedLedger()) #expect(!FileManager.default.fileExists(atPath: coldStore.cacheDirectory.path)) let warm = try SkillOperations.add( AddOptions( diff --git a/Tests/AgentsSkillsTests/IndexedArtifactLifecycleTests.swift b/Tests/AgentsSkillsTests/IndexedArtifactLifecycleTests.swift new file mode 100644 index 0000000..26143aa --- /dev/null +++ b/Tests/AgentsSkillsTests/IndexedArtifactLifecycleTests.swift @@ -0,0 +1,187 @@ +import AgentsCore +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +@Suite("Indexed artifact lifecycle", .serialized) +struct IndexedArtifactLifecycleTests { + @Test(arguments: [InstallMode.copy, .link], [false, true]) + func publicLifecycleUsesVerifiedIndexAndColdLockedResources( + _ mode: InstallMode, archive: Bool + ) throws { + let fixture = try SkillFixture() + let web = fixture.root.appendingPathComponent("web") + try FileManager.default.createDirectory(at: web, withIntermediateDirectories: true) + let server = try ArtifactHTTPServer(root: web) + defer { server.stop() } + func publish(_ body: String, validDigest: Bool = true) throws { + let bytes = Data("---\nname: indexed\ndescription: Indexed fixture\n---\n\(body)\n".utf8) + let payload = + archive + ? zipArchive(entries: [ + ("SKILL.md", bytes, 0o100644), + ("references/context.md", Data(("Context: " + body).utf8), 0o100644), + ]) : bytes + let file = archive ? "/skill.zip" : "/SKILL.md" + let kind = archive ? "archive" : "skill-md" + try payload.write(to: web.appendingPathComponent(String(file.dropFirst()))) + let digest = + validDigest ? FileHash.sha256Hex(data: payload) : String(repeating: "0", count: 64) + let index = web.appendingPathComponent(".well-known/agent-skills/index.json") + try FileManager.default.createDirectory( + at: index.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data( + "{\"$schema\":\"https://schemas.agentskills.io/discovery/0.2.0/schema.json\",\"skills\":[{\"name\":\"indexed\",\"type\":\"\(kind)\",\"description\":\"Indexed fixture\",\"url\":\"\(file)\",\"digest\":\"sha256:\(digest)\"}]}" + .utf8 + ).write(to: index) + } + try publish("Original") + _ = try SkillOperations.add( + AddOptions( + source: server.url, alias: "indexed", agents: [.codex], mode: mode, all: true, + environment: fixture.environment)) + let store = fixture.store() + #expect(try store.loadLedger().resources.values.contains { $0.kind == .artifact }) + #expect( + try SkillOperations.listManaged(environment: fixture.environment).map(\.name) == ["indexed"]) + let watch = SkillOperations.watchOperations() + try watch.add("indexed", environment: fixture.environment) + let original = try Data(contentsOf: store.resolvedURL) + try publish("Current") + let before = try FileHash.folderHash(fixture.environment.projectDirectory) + let preview = try SkillOperations.updateInstalled(environment: fixture.environment) + #expect(try watch.status(environment: fixture.environment).first?.changes.isEmpty == false) + #expect(preview.contains { $0.changed }) + #expect(try FileHash.folderHash(fixture.environment.projectDirectory) == before) + #expect(try Data(contentsOf: store.resolvedURL) == original) + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(try fixture.body(fixture.target("indexed")).contains("Current")) + let current = try Data(contentsOf: store.resolvedURL) + try watch.seen("indexed", environment: fixture.environment) + try watch.remove("indexed", environment: fixture.environment) + #expect(try Data(contentsOf: store.resolvedURL) == current) + try publish("Unverified", validDigest: false) + let valid = try FileHash.folderHash(fixture.environment.projectDirectory) + #expect(throws: (any Error).self) { + try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + } + #expect(try FileHash.folderHash(fixture.environment.projectDirectory) == valid) + try publish("Current") + server.stop() + try FileManager.default.removeItem(at: fixture.target("indexed")) + try FileManager.default.removeItem(at: store.cacheDirectory) + _ = try SkillOperations.installResolvedReport(environment: fixture.environment) + #expect(try Data(contentsOf: store.resolvedURL) == current) + #expect(try fixture.body(fixture.target("indexed")).contains("Current")) + if archive { + #expect( + try String( + contentsOf: fixture.target("indexed").appendingPathComponent("references/context.md"), + encoding: .utf8) == "Context: Current") + } + #expect( + try SkillOperations.listManaged(environment: fixture.environment).allSatisfy { + $0.isInstalled + }) + // An empty selection must remove the last indexed member without contacting its origin. + #expect(throws: Never.self) { + try SkillOperations.remove(skillNames: ["indexed"], environment: fixture.environment) + } + #expect(try store.loadLedger().components.values.allSatisfy { $0.kind != "skills" }) + #expect(!FileManager.default.fileExists(atPath: fixture.target("indexed").path)) + } + + @Test func namedUpdatePreservesAnUnselectedIndexedArtifact() throws { + let fixture = try SkillFixture() + let web = fixture.root.appendingPathComponent("web") + try FileManager.default.createDirectory(at: web, withIntermediateDirectories: true) + let server = try ArtifactHTTPServer(root: web) + defer { server.stop() } + func publish(_ body: String) throws { + var entries: [[String: String]] = [] + for name in ["one", "two"] { + let bytes = Data("---\nname: \(name)\ndescription: Indexed fixture\n---\n\(body)\n".utf8) + try bytes.write(to: web.appendingPathComponent(name + ".md")) + entries.append([ + "name": name, "description": "Indexed fixture", "type": "skill-md", + "url": "/" + name + ".md", "digest": "sha256:" + FileHash.sha256Hex(data: bytes), + ]) + } + let index = web.appendingPathComponent(".well-known/agent-skills/index.json") + try FileManager.default.createDirectory( + at: index.deletingLastPathComponent(), withIntermediateDirectories: true) + try JSONSerialization.data(withJSONObject: [ + "$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json", "skills": entries, + ]).write(to: index) + } + try publish("Original") + _ = try SkillOperations.add( + AddOptions( + source: server.url, alias: "indexed", agents: [.codex], mode: .copy, all: true, + environment: fixture.environment)) + let previous = try #require(fixture.store().loadResolved().skills["two"]) + try publish("Current") + _ = try SkillOperations.updateInstalled( + environment: fixture.environment, skillNames: ["one"], apply: true) + #expect(try fixture.store().loadResolved().skills["two"] == previous) + #expect(try fixture.body(fixture.target("two")).contains("Original")) + #expect(try fixture.body(fixture.target("one")).contains("Current")) + } + +} + +/// Serves fixture bytes to the production HTTP loader; no source-provided program is executed. +private final class ArtifactHTTPServer { + private let process = Process() + private let output = Pipe() + let url: String + + init(root: URL) throws { + process.executableURL = URL(fileURLWithPath: "/usr/bin/perl") + process.arguments = [ + "-e", + #""" + use IO::Socket::INET; + alarm 120; + my $root = shift; + my $server = IO::Socket::INET->new(LocalAddr => '127.0.0.1', LocalPort => 0, Listen => 8, Proto => 'tcp') or die $!; + $| = 1; print $server->sockport, "\n"; + while (my $client = $server->accept()) { + my $request = <$client>; + my ($path) = $request =~ m{^GET (/[^ ]*) HTTP/}; + while (my $line = <$client>) { last if $line eq "\r\n"; } + my $bytes = ''; + my $status = '404 Not Found'; + if (defined($path) && $path !~ /\.\./ && open(my $file, '<', "$root$path")) { + binmode $file; local $/; $bytes = <$file>; close $file; $status = '200 OK'; + } + print $client "HTTP/1.1 $status\r\nContent-Length: ", length($bytes), "\r\nConnection: close\r\n\r\n", $bytes; + close $client; + } + """#, root.path, + ] + process.standardOutput = output + try process.run() + output.fileHandleForWriting.closeFile() + var bytes = Data() + while let byte = try output.fileHandleForReading.read(upToCount: 1), !byte.isEmpty { + if byte == Data([10]) { break } + bytes.append(byte) + } + guard let port = Int(String(decoding: bytes, as: UTF8.self)) else { + if process.isRunning { process.terminate() } + process.waitUntilExit() + try? output.fileHandleForReading.close() + throw CoreError.invalidState("fixture HTTP listener did not start") + } + url = "http://127.0.0.1:\(port)" + } + + func stop() { + if process.isRunning { terminateProcess(process) } + try? output.fileHandleForReading.close() + } +} diff --git a/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift b/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift index eed760a..f9c6cd4 100644 --- a/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift +++ b/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift @@ -48,7 +48,7 @@ struct LifecycleRegressionTests { environment: fixture.environment)) var declaration = try fixture.store().loadDeclaration() try declaration.updateSkills { $0?["fixture"]?.agents = [.codex] } - try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) + try fixture.store().save(declaration: declaration, ledger: fixture.store().loadLedger()) let target = fixture.target("demo") try FileManager.default.createDirectory( at: target.appendingPathComponent("empty"), withIntermediateDirectories: true) @@ -107,7 +107,7 @@ struct LifecycleRegressionTests { try declaration.updateSkills { $0?["fixture"]?.overrides = ["demo": SkillOverride(mode: .edit)] } - try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) + try fixture.store().save(declaration: declaration, ledger: fixture.store().loadLedger()) _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) try FileManager.default.removeItem(at: fixture.repo.appendingPathComponent("skills/demo")) #expect(throws: CoreError.self) { @@ -123,7 +123,7 @@ struct LifecycleRegressionTests { let fixture = try SkillFixture() try fixture.skill("demo", body: "A") try fixture.commit() - try fixture.store().save(declaration: Declaration(agents: [.codex]), resolved: ResolvedState()) + try fixture.store().save(declaration: Declaration(agents: [.codex]), ledger: ResolvedLedger()) _ = try SkillOperations.add( AddOptions( source: fixture.repo.path, agents: [.codex, .claudeCode], environment: fixture.environment)) @@ -167,3 +167,30 @@ extension LifecycleRegressionTests { .status == .missing) } } + +extension LifecycleRegressionTests { + @Test func namedUpdatePreservesUnselectedCanonicalIdentityAndExactPin() throws { + let fixture = try SkillFixture() + try fixture.skill("example", body: "A") + try fixture.skill("selected", body: "A") + let file = fixture.repo.appendingPathComponent("skills/example/SKILL.md") + try Data("---\nname: Example Skill\ndescription: Example\n---\nOriginal".utf8).write(to: file) + try fixture.commit() + _ = try fixture.add(mode: .copy) + let original = try #require(fixture.store().loadResolved().skills["example-skill"]) + try Data("---\nname: Example Skill\ndescription: Example\n---\nChanged".utf8).write(to: file) + try fixture.skill("selected", body: "B") + try fixture.commit() + _ = try SkillOperations.updateInstalled( + environment: fixture.environment, skillNames: ["selected"], apply: true) + let lock = try fixture.store().loadResolved() + #expect(lock.skills["example-skill"] == original) + #expect(lock.skills["selected"]?.revision == (try fixture.head())) + #expect(try fixture.body(fixture.target("example-skill")).hasSuffix("Original")) + #expect(try fixture.body(fixture.target("selected")).contains("B")) + let ledger = try fixture.store().loadLedger() + #expect( + ledger.components.values.filter { $0.kind == "skills" }.compactMap(\.revision).contains( + original.revision!)) + } +} diff --git a/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift b/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift index 8dc9329..4de43e4 100644 --- a/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift @@ -178,9 +178,7 @@ struct ManifestLifecycleTests { #expect(try Data(contentsOf: store.declarationURL) == declaration) } - /// Components outside the deployable subset are reported, never dropped; the complete - /// document stays readable. - @Test func undeployableComponentsAreReportedAndStillReadable() throws { + @Test func fullDeclarationSurvivesSkillAndWatchWrites() throws { let fixture = try SkillFixture() try fixture.skill("demo", body: "A") try fixture.commit() @@ -188,35 +186,54 @@ struct ManifestLifecycleTests { try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) let declaration = Data( """ + # All declaration families remain owned by this document. version: 1 - sources: {"fixture": {"path": "\(fixture.repo.path)"}} - components: [{"kind": "skills", "source": "fixture"}, {"kind": "mcpServer", "name": "tools", "transport": {"kind": "stdio", "executable": "server"}}] + sources: + fixture: {path: "\(fixture.repo.path)"} + unused: {path: ./not-present} + groups: + unused: {components: [{kind: skills, source: unused, select: [draft]}]} + components: + - {kind: skills, source: fixture, agents: [codex], mode: copy} + # A valid inactive declaration needs no native target. + - {kind: mcpServer, name: tools, agents: [], transport: {kind: stdio, executable: never-run}} + """.utf8) try declaration.write(to: store.declarationURL) + #expect(try SkillOperations.listManaged(environment: fixture.environment).isEmpty) + _ = try UpdateOperations.withPreparedUpdate(environment: fixture.environment) { try $0.apply() } + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + let ledger = try store.loadLedger() + #expect(ledger.version == 2) + #expect(ledger.components.values.contains { $0.kind == "mcpServer" && $0.recipients.isEmpty }) + #expect(try Data(contentsOf: store.declarationURL) == declaration) + try fixture.skill("other", body: "B") + try fixture.commit() + _ = try SkillOperations.add( + AddOptions( + source: "fixture", agents: [.codex], skillNames: ["other"], mode: .copy, + environment: fixture.environment)) + let watch = SkillOperations.watchOperations() + try watch.add("fixture", environment: fixture.environment) + let lock = try Data(contentsOf: store.resolvedURL) let before = try snapshot(fixture.root) - for operation in ["update", "add", "list"] { - #expect { - switch operation { - case "update": - _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) - case "add": - _ = try SkillOperations.add( - AddOptions(source: "fixture", all: true, environment: fixture.environment)) - default: _ = try SkillOperations.listManaged(environment: fixture.environment) - } - } throws: { error in - guard let failure = error as? ManifestFailure, - let diagnostic = failure.diagnostics.first - else { return false } - return diagnostic.code == "manifest.unsupported" - && diagnostic.span.document.rawValue == store.declarationURL.path - } - } + #expect( + try SkillOperations.listManaged(environment: fixture.environment).map(\.name).sorted() == [ + "demo", "other", + ]) + _ = try SkillOperations.doctor(environment: fixture.environment) + _ = try watch.status(environment: fixture.environment) + #expect(try snapshot(fixture.root) == before) + try watch.remove("fixture", environment: fixture.environment) + #expect(try Data(contentsOf: store.resolvedURL) == lock) let document = try #require(try store.loadManifest()) - #expect(document.bytes == Array(declaration)) + #expect(document.declaration.groups.count == 1) #expect(document.declaration.components.contains { $0.kind == "mcpServer" }) - #expect(try snapshot(fixture.root).filter { !$0.key.hasSuffix(".agents.lock") } == before) + #expect(try store.loadDeclaration().sources["unused"]?.location == "./not-present") + #expect( + String(decoding: document.bytes, as: UTF8.self).contains("# A valid inactive declaration")) } + } /// Checkpoint callbacks run synchronously in the calling test. diff --git a/Tests/AgentsSkillsTests/PublicLifecycleTests.swift b/Tests/AgentsSkillsTests/PublicLifecycleTests.swift index 4974546..489489a 100644 --- a/Tests/AgentsSkillsTests/PublicLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/PublicLifecycleTests.swift @@ -17,8 +17,8 @@ struct PublicLifecycleTests { #expect(Set(added.installed.map(\.agent)) == [.codex, .claudeCode]) var declaration = try fixture.store().loadDeclaration() declaration.agents = [.cursor] - let lock = try fixture.store().loadResolved() - try fixture.store().save(declaration: declaration, resolved: lock) + let lock = try fixture.store().loadLedger() + try fixture.store().save(declaration: declaration, ledger: lock) for install in added.installed { try FileManager.default.removeItem(atPath: install.path) } let restored = try SkillOperations.installResolvedReport(environment: fixture.environment) #expect(Set(restored.installed.map(\.agent)) == [.codex, .claudeCode]) @@ -127,6 +127,48 @@ struct PublicLifecycleTests { #expect(try fixture.stateAndTargetBytes() == bytes) } + @Test func removalFingerprintPreservesRemainingIndependentMembers() throws { + let fixture = try SkillFixture() + for name in ["demo", "keep-b", "keep-a"] { try fixture.skill(name, body: name) } + try fixture.commit() + _ = try fixture.add(mode: .copy) + let pin = try fixture.head() + let request = UpdateRequest(operation: .remove, kinds: [.skills], names: ["demo"]) + let first = try UpdateOperations.preview(request, environment: fixture.environment) + let second = try UpdateOperations.preview(request, environment: fixture.environment) + #expect(first.displayedFingerprint == second.displayedFingerprint) + _ = try UpdateOperations.withPreparedUpdate(request, environment: fixture.environment) { + try $0.apply(ifUnchangedFrom: first.displayedFingerprint) + } + let ledger = try fixture.store().loadLedger() + #expect( + Set(ledger.components.values.filter { $0.kind == "skills" }.map(\.name)) == [ + "keep-a", "keep-b", + ]) + #expect( + ledger.components.values.filter { $0.kind == "skills" }.allSatisfy { $0.revision == pin }) + #expect(try fixture.body(fixture.target("keep-a")).contains("keep-a")) + #expect(try fixture.body(fixture.target("keep-b")).contains("keep-b")) + #expect(!FileManager.default.fileExists(atPath: fixture.target("demo").path)) + } + + @Test func removalDoesNotDiscoverNewAllMembers() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "Original") + try fixture.commit() + _ = try fixture.add(mode: .copy) + try fixture.skill("new-member", body: "Current") + try fixture.commit() + try SkillOperations.remove(skillNames: ["demo"], environment: fixture.environment) + #expect(try fixture.store().loadResolved().skills.isEmpty) + #expect(!FileManager.default.fileExists(atPath: fixture.target("new-member").path)) + #expect(try fixture.store().loadDeclaration().skills?["fixture"]?.select == .all) + #expect(try fixture.store().loadDeclaration().skills?["fixture"]?.exclude == ["demo"]) + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(try fixture.store().loadResolved().skills.keys.sorted() == ["new-member"]) + #expect(try fixture.body(fixture.target("new-member")).contains("Current")) + } + @Test func emptyNamedSelectionDoesNotRequireSourceAccess() throws { let fixture = try SkillFixture() try fixture.skill("demo", body: "A") diff --git a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift index 89c40ea..a87fbeb 100644 --- a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift +++ b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift @@ -121,7 +121,7 @@ struct ReadOnlyInspectionTests { projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: ["CLAUDE_CONFIG_DIR": root.appendingPathComponent("configured-claude").path]) let store = StateStore(scope: scope, environment: environment) - try store.save(declaration: Declaration(), resolved: ResolvedState()) + try store.save(declaration: Declaration(), ledger: ResolvedLedger()) let target = AgentRegistry.installSkillsDirectory( for: .codex, scope: scope, environment: environment ).appendingPathComponent("target") @@ -247,7 +247,7 @@ struct ReadOnlyInspectionTests { try fixture.store().save( declaration: Declaration(sources: [ source: SourceDeclaration(kind: .git, location: "file://localhost" + fixture.repo.path) - ]), resolved: ResolvedState()) + ]), ledger: ResolvedLedger()) _ = try SkillOperations.add( AddOptions(source: source, agents: [.codex], all: true, environment: fixture.environment)) // A cached immutable pin remains inspectable when upstream no longer provides it. @@ -281,7 +281,7 @@ struct ReadOnlyInspectionTests { try fixture.store().save( declaration: Declaration( agents: [.codex], sources: ["fixture": source], - skills: ["fixture": SkillDeclaration(select: .all)]), resolved: ResolvedState()) + skills: ["fixture": SkillDeclaration(select: .all)]), ledger: ResolvedLedger()) _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) try fixture.skill("demo", body: "Upstream") try fixture.commit() @@ -335,9 +335,8 @@ struct ReadOnlyInspectionTests { agents: [.codex], sources: ["fixture": source], skills: ["fixture": SkillDeclaration(select: .all)], instructions: InstructionsDeclaration(sections: ["fixture:rules"])), - resolved: ResolvedState()) - _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) - _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate(environment: fixture.environment) { try $0.apply() } let locks = fixture.store().cacheDirectory.appendingPathComponent("locks") let files = try FileManager.default.contentsOfDirectory( at: locks, includingPropertiesForKeys: nil) diff --git a/Tests/AgentsSkillsTests/SkillLifecycleTests.swift b/Tests/AgentsSkillsTests/SkillLifecycleTests.swift index bc800ae..997b23d 100644 --- a/Tests/AgentsSkillsTests/SkillLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/SkillLifecycleTests.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsInstructions import AgentsManifest import AgentsUpdates import Foundation @@ -150,11 +151,32 @@ struct SkillLifecycleTests { } @Test(arguments: [InstallMode.link, .copy]) - func rejectsNonGitPinnedSources(_ mode: InstallMode) throws { + func nonGitSourcesFreezeResourcesAndRejectGitRequirements(_ mode: InstallMode) throws { let fixture = try SkillFixture() - try fixture.skill("demo", body: "live") - #expect(throws: (any Error).self) { try fixture.add(mode: mode) } + try fixture.skill("demo", body: "Local snapshot") + let script = fixture.repo.appendingPathComponent("skills/demo/run.sh") + try Data("#!/bin/sh\nexit 0\n".utf8).write(to: script) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: script.path) + #expect(throws: (any Error).self) { + try SkillOperations.add( + AddOptions( + source: fixture.repo.path, agents: [.codex], mode: mode, + sourceRequirement: .branch("master"), environment: fixture.environment)) + } #expect(!FileManager.default.fileExists(atPath: fixture.store().resolvedURL.path)) + _ = try fixture.add(mode: mode) + let store = fixture.store() + let ledger = try store.loadLedger() + #expect(ledger.resources.values.contains { $0.kind == .embedded }) + let bytes = try Data(contentsOf: store.resolvedURL) + try FileManager.default.removeItem(at: fixture.repo) + try FileManager.default.removeItem(at: fixture.target("demo")) + try FileManager.default.removeItem(at: store.cacheDirectory) + _ = try SkillOperations.installResolvedReport(environment: fixture.environment) + #expect(try fixture.body(fixture.target("demo")).contains("Local snapshot")) + let flags = try FileHash.executableFlags(fixture.target("demo")) + #expect(flags["run.sh"] == true) + #expect(try Data(contentsOf: store.resolvedURL) == bytes) } @Test( @@ -206,22 +228,25 @@ struct SkillLifecycleTests { @Test func skillMutationsPreserveInstructionAndWatchDeclarations() throws { let fixture = try SkillFixture() try fixture.skill("demo", body: "A") + let instructions = fixture.repo.appendingPathComponent("instructions") + try FileManager.default.createDirectory(at: instructions, withIntermediateDirectories: true) + try Data("---\ndescription: Rules\n---\n# Rules\nFrozen rules\n".utf8).write( + to: instructions.appendingPathComponent("rules.md")) try fixture.commit() _ = try fixture.add() + _ = try InstructionOperations.add( + InstructionAddOptions( + source: "fixture", names: ["rules"], agents: [.codex], environment: fixture.environment)) var declaration = try fixture.store().loadDeclaration() - try declaration.setInstructions( - InstructionsDeclaration( - sections: ["fixture:rules"], - chatgpt: ["prompt": PromptDeclaration(sections: ["fixture:rules"])])) + try declaration.updateInstructions { + $0?.chatgpt = ["prompt": PromptDeclaration(sections: ["fixture:rules"])] + } declaration.watch = ["fixture"] - var lock = try fixture.store().loadResolved() - let skill = try #require(lock.skills["demo"]) - lock.instructions = LockedInstructions(sections: [ - LockedSection( - name: "rules", source: skill.source, revision: skill.revision, - path: "instructions/rules.md", hash: skill.hash!) - ]) - try fixture.store().save(declaration: declaration, resolved: lock) + try fixture.store().save(declaration: declaration, ledger: fixture.store().loadLedger()) + _ = try UpdateOperations.withPreparedUpdate(environment: fixture.environment) { try $0.apply() } + let lock = try fixture.store().loadResolved() + let ledger = try fixture.store().loadLedger() + #expect(ledger.version == 2) try SkillOperations.remove(skillNames: ["demo"], environment: fixture.environment) #expect(try fixture.store().loadResolved().instructions == lock.instructions) #expect(try fixture.store().loadDeclaration().instructions == (try declaration.instructions)) diff --git a/Tests/AgentsSkillsTests/SourceShorthandTests.swift b/Tests/AgentsSkillsTests/SourceShorthandTests.swift index 3565faf..12f403d 100644 --- a/Tests/AgentsSkillsTests/SourceShorthandTests.swift +++ b/Tests/AgentsSkillsTests/SourceShorthandTests.swift @@ -64,7 +64,7 @@ struct SourceShorthandTests { let fixture = try SkillFixture() try fixture.skill("demo", body: "A") try fixture.commit() - try fixture.store().save(declaration: Declaration(), resolved: ResolvedState()) + try fixture.store().save(declaration: Declaration(), ledger: ResolvedLedger()) let watch = SkillOperations.watchOperations() #expect(throws: CoreError.self) { try watch.add(fixture.repo.path + "@skill:demo", environment: fixture.environment) diff --git a/Tests/AgentsSkillsTests/TransactionDoctorTests.swift b/Tests/AgentsSkillsTests/TransactionDoctorTests.swift index b60e0b0..d59d64f 100644 --- a/Tests/AgentsSkillsTests/TransactionDoctorTests.swift +++ b/Tests/AgentsSkillsTests/TransactionDoctorTests.swift @@ -13,7 +13,7 @@ struct TransactionDoctorTests { @Test func bothDoctorsReportOwnerActionAndPreservedLocationsWithoutReplay() throws { let fixture = try SkillFixture() let store = fixture.store() - try store.save(declaration: Declaration(), resolved: ResolvedState()) + try store.save(declaration: Declaration(), ledger: ResolvedLedger()) let target = fixture.environment.projectDirectory.appendingPathComponent("AGENTS.md") try Data("original".utf8).write(to: target) let saved = fixture.root.appendingPathComponent("saved-original") diff --git a/Tests/AgentsSkillsTests/UpdateReportingTests.swift b/Tests/AgentsSkillsTests/UpdateReportingTests.swift index 8db02bf..6f2b8ba 100644 --- a/Tests/AgentsSkillsTests/UpdateReportingTests.swift +++ b/Tests/AgentsSkillsTests/UpdateReportingTests.swift @@ -103,7 +103,7 @@ struct UpdateReportingTests { declaration: Declaration( sources: ["fixture": SourceDeclaration(kind: .local, location: fixture.repo.path)], skills: ["fixture": SkillDeclaration(select: .all, agents: agents, mode: .edit)]), - resolved: ResolvedState()) + ledger: ResolvedLedger()) let initial = try #require( SkillOperations.updateInstalled(environment: fixture.environment).first) #expect(initial.membership.count == agents.count) @@ -138,7 +138,7 @@ struct UpdateReportingTests { #expect(repair.membership.allSatisfy { $0.before == $0.after } && !repair.changes.isEmpty) var declaration = try store.loadDeclaration() try declaration.setSkills(nil) - try store.save(declaration: declaration, resolved: store.loadResolved()) + try store.save(declaration: declaration, ledger: store.loadLedger()) let removed = try #require( SkillOperations.updateInstalled(environment: fixture.environment).first) #expect(removed.changed && removed.changes.isEmpty && removed.newVersion == nil) @@ -158,7 +158,7 @@ struct UpdateReportingTests { let store = fixture.store() var declaration = try store.loadDeclaration() try declaration.updateSkills { $0?["fixture"]?.agents = [.codex, .cursor, .claudeCode] } - try store.save(declaration: declaration, resolved: store.loadResolved()) + try store.save(declaration: declaration, ledger: store.loadLedger()) let added = try #require( SkillOperations.updateInstalled(environment: fixture.environment).first) #expect(added.membership.first { $0.agent == .codex }?.before == .installed(mode: .edit)) @@ -166,7 +166,7 @@ struct UpdateReportingTests { _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) try declaration.updateSkills { $0?["fixture"]?.agents = [.codex, .cursor] } try declaration.updateSkills { $0?["fixture"]?.mode = .copy } - try store.save(declaration: declaration, resolved: store.loadResolved()) + try store.save(declaration: declaration, ledger: store.loadLedger()) let changed = try #require( SkillOperations.updateInstalled(environment: fixture.environment).first) #expect(changed.membership.first { $0.agent == .claudeCode }?.after == .absent) @@ -176,6 +176,14 @@ struct UpdateReportingTests { }) #expect(Set(changed.changes.map(\.path)).count == changed.changes.count) _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + let partial = try #require( + UpdateOperations.preview( + UpdateRequest(operation: .remove, kinds: [.skills], names: ["demo"], agents: [.codex]), + environment: fixture.environment + ).skills.first) + #expect(partial.changes.isEmpty) + #expect(partial.membership.first { $0.agent == .cursor }?.after == .installed(mode: .copy)) + #expect(try fixture.body(fixture.target("demo")).contains("live")) } @Test func lossOfRecordAndSelectionDoesNotInventRemoval() throws { @@ -183,7 +191,7 @@ struct UpdateReportingTests { try fixture.skill("demo", body: "live") _ = try fixture.add(mode: .edit) let store = fixture.store() - try store.save(declaration: Declaration(), resolved: ResolvedState()) + try store.save(declaration: Declaration(), ledger: ResolvedLedger()) try FileManager.default.removeItem(at: store.resolvedURL) #expect(try SkillOperations.updateInstalled(environment: fixture.environment).isEmpty) _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) diff --git a/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift b/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift index d936d3a..1e95788 100644 --- a/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift +++ b/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsInstructions import AgentsManifest import AgentsSkills import AgentsUpdates @@ -16,7 +17,7 @@ struct WatchSubscriptionTests { try writeInstruction("removed", body: "old", fixture: fixture) try fixture.commit() let initial = try fixture.head() - try fixture.store().save(declaration: Declaration(), resolved: ResolvedState()) + try fixture.store().save(declaration: Declaration(), ledger: ResolvedLedger()) let watch = SkillOperations.watchOperations() let id = try SourceDeclaration(kind: .local, location: fixture.repo.path).identity( environment: fixture.environment) @@ -115,7 +116,7 @@ struct WatchSubscriptionTests { "source": SourceDeclaration( kind: .local, location: fixture.repo.path, requirement: .exact("1.0.0")) - ]), resolved: ResolvedState()) + ]), ledger: ResolvedLedger()) try fixture.skill("demo", body: "head") try fixture.commit() let watch = SkillOperations.watchOperations() @@ -331,7 +332,7 @@ struct WatchSubscriptionTests { { _ = try SkillOperations.remove(skillNames: ["demo"], environment: fixture.environment) }, { try fixture.store().save( - declaration: Declaration(), resolved: ResolvedState(), watch: WatchState()) + declaration: Declaration(), ledger: ResolvedLedger(), watch: WatchState()) }, ] for mutate in mutations { @@ -348,19 +349,18 @@ struct WatchSubscriptionTests { try watch.add(fixture.repo.path, environment: fixture.environment) } #expect(!FileManager.default.fileExists(atPath: fixture.store().declarationURL.path)) + let instructions = fixture.repo.appendingPathComponent("instructions") + try FileManager.default.createDirectory(at: instructions, withIntermediateDirectories: true) + try Data("---\ndescription: Canonical rules\n---\n# Rules\nCanonical\n".utf8).write( + to: instructions.appendingPathComponent("canonical.md")) try fixture.commit() - let declaration = Declaration( - sources: ["rules": SourceDeclaration(kind: .local, location: fixture.repo.path)], - instructions: InstructionsDeclaration(sections: ["rules:canonical"])) - let lock = ResolvedState( - sources: ["local:" + fixture.repo.path: LockedSource(kind: .local)], - instructions: LockedInstructions(sections: [ - LockedSection( - name: "canonical", source: "local:" + fixture.repo.path, - revision: try fixture.head(), path: "instructions/canonical.md", - hash: "sha256:" + String(repeating: "a", count: 64)) - ])) - try fixture.store().save(declaration: declaration, resolved: lock) + _ = try InstructionOperations.add( + InstructionAddOptions( + source: fixture.repo.path, alias: "rules", names: ["canonical"], agents: [.codex], + environment: fixture.environment)) + let declaration = try fixture.store().loadDeclaration() + #expect( + try fixture.store().loadLedger().components.values.contains { $0.kind == "instructions" }) let lockBytes = try Data(contentsOf: fixture.store().resolvedURL) try watch.add("rules", environment: fixture.environment) try watch.seen("rules", environment: fixture.environment) diff --git a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift index bbaa515..7201a75 100644 --- a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift +++ b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift @@ -17,7 +17,7 @@ struct CombinedUpdateTests { var declaration = try fixture.store.loadDeclaration() try declaration.updateSkills { $0?["fixture"]?.mode = .copy } declaration.sources["fixture"]?.requirement = .branch("main") - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) let before = try fixture.snapshot() let preview = try fixture.preview() let skill = try #require(preview.skills.first) @@ -57,7 +57,7 @@ struct CombinedUpdateTests { try fixture.write("Hand written.\n", to: fixture.instruction(.geminiCLI)) var declaration = try fixture.store.loadDeclaration() try declaration.updateInstructions { $0?.agents = [.codex, .geminiCLI] } - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) let preview = try fixture.preview() #expect(preview.instructions.targets.contains { $0.target == "GEMINI.md" && $0.foreign }) let before = try fixture.snapshot() @@ -78,7 +78,7 @@ struct CombinedUpdateTests { var declaration = try fixture.store.loadDeclaration() try declaration.updateSkills { $0?["fixture"]?.mode = .copy } declaration.sources["fixture"]?.requirement = .branch("main") - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) let before = try fixture.snapshot() var called = false #expect(throws: CoreError.self) { @@ -100,7 +100,7 @@ struct CombinedUpdateTests { var declaration = try fixture.store.loadDeclaration() try declaration.updateSkills { $0?["fixture"]?.mode = .copy } declaration.sources["fixture"]?.requirement = .branch("main") - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) let before = try fixture.snapshot() var called = false #expect(throws: CoreError.self) { @@ -181,7 +181,7 @@ struct CombinedUpdateTests { seen: .artifacts(["observed": "sha256:" + String(repeating: "b", count: 64)])) ]) try fixture.store.save( - declaration: declaration, resolved: fixture.store.loadResolved(), watch: watch) + declaration: declaration, ledger: fixture.store.loadLedger(), watch: watch) try fixture.advance() let before = try fixture.snapshot() #expect(throws: UpdateApplyError.self) { @@ -238,7 +238,7 @@ struct CombinedUpdateTests { sources: ["fixture": SourceDeclaration(kind: .local, location: source)], skills: ["fixture": SkillDeclaration(select: .all, agents: [.codex], mode: .copy)] ), - resolved: ResolvedState()) + ledger: ResolvedLedger()) } catch { Issue.record(error) } } try #require(finished.wait(timeout: .now() + 10) == .success) @@ -259,7 +259,7 @@ struct CombinedUpdateTests { declaration.sources["rules"] = SourceDeclaration(kind: .local, location: other.repo.path) try declaration.updateInstructions { $0?.sections = ["rules:rules"] } try declaration.updateInstructions { $0?.chatgpt?["weekly"]?.sections = ["rules:rules"] } - try fixture.store.save(declaration: declaration, resolved: ResolvedState()) + try fixture.store.save(declaration: declaration, ledger: ResolvedLedger()) _ = try fixture.apply() try fixture.advance() try other.advance() @@ -282,7 +282,7 @@ struct CombinedUpdateTests { sources: ["fixture": SourceDeclaration(kind: .local, location: fixture.repo.path)], skills: ["fixture": SkillDeclaration(select: .all, agents: [.codex], mode: .copy)], instructions: InstructionsDeclaration(agents: [.claudeCode], sections: ["fixture:rules"])), - resolved: ResolvedState()) + ledger: ResolvedLedger()) var called = false #expect(throws: CoreError.self) { try UpdateOperations.withPreparedUpdate(scope: .user, environment: environment) { _ in @@ -441,7 +441,7 @@ struct CombinedUpdateTests { try fixture.write("invalid", to: fixture.repo.appendingPathComponent("skills/demo/SKILL.md")) var declaration = try fixture.store.loadDeclaration() try declaration.updateSkills { $0?["fixture"]?.select = .names(["demo"]) } - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) try fixture.commit() } else if kind == "instructions" { try fixture.write("invalid", to: fixture.repo.appendingPathComponent("instructions/rules.md")) @@ -569,13 +569,13 @@ struct CombinedUpdateTests { try fixture.declare() var declaration = try fixture.store.loadDeclaration() try declaration.setSkills(nil) - try fixture.store.save(declaration: declaration, resolved: ResolvedState()) + try fixture.store.save(declaration: declaration, ledger: ResolvedLedger()) #expect(try fixture.apply().report.skills.isEmpty) try declaration.setInstructions(nil) try declaration.setSkills([ "fixture": SkillDeclaration(select: .all, agents: [.codex], mode: .copy) ]) - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) _ = try fixture.apply() #expect(try fixture.store.loadResolved().instructions == LockedInstructions()) #expect(try !fixture.preview().hasChanges) @@ -587,7 +587,7 @@ struct CombinedUpdateTests { var declaration = try fixture.store.loadDeclaration() try declaration.setSkills(nil) try declaration.updateInstructions { $0?.sections = [] } - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) _ = try fixture.apply() try fixture.git(["commit", "--allow-empty", "-m", "repin"]) let prompt = try fixture.preview() @@ -602,10 +602,10 @@ struct CombinedUpdateTests { try declaration.updateInstructions { $0?.chatgpt?["weekly"]?.sections = ["fixture:rules", "fixture:second"] } - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) _ = try fixture.apply() try declaration.updateInstructions { $0?.chatgpt?["weekly"]?.sections.reverse() } - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) #expect(try fixture.preview().hasChanges) _ = try fixture.apply() #expect(try !fixture.preview().hasChanges) diff --git a/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift b/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift index 14e8cff..7192c5a 100644 --- a/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift +++ b/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift @@ -27,7 +27,7 @@ struct LifecycleCompositionTests { declaration: Declaration( sources: ["local": .init(kind: .local, location: source.path)], skills: ["local": .init(select: .all, agents: [.claudeCode], mode: mode)], - instructions: .init(agents: [.codex], sections: ["frozen"])), resolved: ResolvedState()) + instructions: .init(agents: [.codex], sections: ["frozen"])), ledger: ResolvedLedger()) _ = try fixture.apply() let instruction = try fixture.bytes(fixture.instruction()) let skill = try fixture.bytes( @@ -106,7 +106,7 @@ struct LifecycleCompositionTests { name: "server", transport: .stdio(.init(executable: "fixture-server")), agents: [.claudeCode]) ]) - try fixture.store.save(declaration: declaration, resolved: ResolvedState()) + try fixture.store.save(declaration: declaration, ledger: ResolvedLedger()) let native = fixture.root.appendingPathComponent(".mcp.json") try fixture.write("{\"unmanaged\":{\"secret\":\"private sibling sentinel\"}}\n", to: native) let report = try fixture.preview() @@ -138,7 +138,7 @@ struct LifecycleCompositionTests { declaration.components.append( .mcpServer( name: "server", transport: .stdio(.init(executable: "before")), agents: [.claudeCode])) - try fixture.store.save(declaration: declaration, resolved: ResolvedState()) + try fixture.store.save(declaration: declaration, ledger: ResolvedLedger()) _ = try fixture.apply() let native = fixture.root.appendingPathComponent(".mcp.json") let oldNative = try fixture.bytes(native) @@ -146,7 +146,7 @@ struct LifecycleCompositionTests { try fixture.advance() declaration.components[declaration.components.count - 1] = .mcpServer( name: "server", transport: .stdio(.init(executable: "after")), agents: [.claudeCode]) - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) let state = try fixture.snapshot() struct Interrupted: Error {} var interrupted = false @@ -189,7 +189,7 @@ extension LifecycleCompositionTests { transport: .stdio( .init(executable: "fixture-server", environment: ["TOKEN": .secret("fixture-token")])), agents: [.claudeCode]) - ]), resolved: ResolvedState()) + ]), ledger: ResolvedLedger()) var environment = fixture.environment environment.environment["CLAUDE_CONFIG_DIR"] = nil let provider = FixtureBindings() @@ -226,17 +226,23 @@ extension LifecycleCompositionTests { #expect(mode?.intValue == 0o600) } - @Test func producerOwnedSkillCannotBeRemovedAndChangedProtectedGroupRequiresCombinedUpdate() - throws - { + @Test(arguments: [false, true]) + func producerOwnedSkillCannotBeRemovedAndChangedProtectedGroupRequiresCombinedUpdate( + nonCanonical: Bool + ) throws { let fixture = try UpdateFixture() + if nonCanonical { + try fixture.write( + "---\nname: Demo Skill\ndescription: Producer skill\n---\nOriginal\n", + to: fixture.repo.appendingPathComponent("skills/demo/SKILL.md")) + } try fixture.write( """ version: 1 components: [] groups: skills: - components: [{kind: skills, source: ., select: [demo], mode: copy, agents: [claude-code]}] + components: [{kind: skills, source: ., select: all, mode: copy, agents: [claude-code]}] tools: components: [{kind: mcpServer, name: server, transport: {kind: stdio, executable: before}, agents: [claude-code]}] exports: [skills, tools] @@ -253,8 +259,13 @@ extension LifecycleCompositionTests { """, to: fixture.store.declarationURL) _ = try fixture.apply() let before = try fixture.snapshot() - #expect(throws: (any Error).self) { - try SkillOperations.remove(skillNames: ["demo"], environment: fixture.environment) + #expect { + try SkillOperations.remove( + skillNames: [nonCanonical ? "demo-skill" : "demo"], environment: fixture.environment) + } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("notEditableHere") && reason.contains(fixture.repo.path) + && reason.contains("#skills") } #expect(try fixture.snapshot() == before) let manifest = fixture.repo.appendingPathComponent(".agent/agents.yaml") @@ -358,7 +369,7 @@ extension LifecycleCompositionTests { components: [ .skills(source: "first", .init(select: .all, agents: [.codex], mode: .copy)), .skills(source: "second", .init(select: .all, agents: [.claudeCode], mode: .copy)), - ]), resolved: ResolvedState()) + ]), ledger: ResolvedLedger()) let report = try fixture.preview() #expect(report.skills.count == 2) #expect(Set(report.skills.map(\.sourceIdentity)).count == 2) @@ -394,3 +405,37 @@ extension LifecycleCompositionTests { } } } + +extension LifecycleCompositionTests { + @Test func unusedDeclarationEditsInvalidateASelectedSkillPreparation() throws { + let fixture = try UpdateFixture() + try fixture.install(agents: [.codex]) + let authored = + String(decoding: try fixture.bytes(fixture.store.declarationURL), as: UTF8.self) + + "\ngroups:\n unused: {components: [{kind: ignore, name: draft, patterns: [build]}]}\n" + try fixture.write(authored, to: fixture.store.declarationURL) + try fixture.advance() + let ledger = try fixture.bytes(fixture.store.resolvedURL) + let target = try FileHash.folderHash(fixture.target()) + var edited = Data() + try UpdateOperations.withPreparedUpdate( + UpdateRequest(kinds: [.skills]), environment: fixture.environment + ) { prepared in + edited = Data( + authored.replacingOccurrences(of: "patterns: [build]", with: "patterns: [cache]").utf8) + try edited.write(to: fixture.store.declarationURL) + #expect { try prepared.apply() } throws: { error in + guard let failure = error as? UpdateApplyError, + case .unchanged = failure.disposition, + case CoreError.invalidState(let reason) = failure.underlyingError + else { return false } + return reason.contains("changed during preparation") + } + } + #expect(try fixture.bytes(fixture.store.declarationURL) == edited) + #expect(try fixture.bytes(fixture.store.resolvedURL) == ledger) + #expect(try FileHash.folderHash(fixture.target()) == target) + #expect(try fixture.store.loadDeclaration().groups.count == 1) + #expect(try fixture.store.loadLedger().version == 2) + } +} diff --git a/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift b/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift index 9bdd662..4b22e85 100644 --- a/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift +++ b/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift @@ -18,7 +18,7 @@ struct RequirementUpdateTests { declaration.agents = [.codex] try declaration.updateInstructions { $0?.agents = nil } declaration.sources["fixture"]?.requirement = .upToNextMajor(from: "1.2.0") - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) _ = try fixture.apply() let original = try fixture.store.loadResolved() var object = try #require( diff --git a/Tests/AgentsUpdatesTests/UpdateFixture.swift b/Tests/AgentsUpdatesTests/UpdateFixture.swift index 8e8c625..06fc782 100644 --- a/Tests/AgentsUpdatesTests/UpdateFixture.swift +++ b/Tests/AgentsUpdatesTests/UpdateFixture.swift @@ -78,7 +78,7 @@ final class UpdateFixture { instructions: InstructionsDeclaration( agents: agents, sections: ["fixture:rules"], chatgpt: ["weekly": PromptDeclaration(sections: ["fixture:rules"])])), - resolved: ResolvedState()) + ledger: ResolvedLedger()) } func install(mode: InstallMode = .copy, agents: [AgentID] = [.codex, .claudeCode]) throws { diff --git a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift index b938f7d..db107a5 100644 --- a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift +++ b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift @@ -219,6 +219,11 @@ private func launch(_ fixture: UpdateFixture, command: String, argument: String) process.arguments = [ fixture.root.path, command, argument, "--scope", fixture.store.scope.rawValue, ] + let scratch = fixture.root.appendingPathComponent("process-temporary") + try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true) + var environment = ProcessInfo.processInfo.environment + environment["TMPDIR"] = scratch.path + "/" + process.environment = environment try process.run() return process } diff --git a/Tests/StateTestSupport/DeclarationStateFixture.swift b/Tests/StateTestSupport/DeclarationStateFixture.swift index 3759858..bf479d2 100644 --- a/Tests/StateTestSupport/DeclarationStateFixture.swift +++ b/Tests/StateTestSupport/DeclarationStateFixture.swift @@ -39,8 +39,13 @@ extension StateStore { } extension StateStore { - package func save(declaration: Declaration, ledger: ResolvedLedger) throws { + package func save( + declaration: Declaration, ledger: ResolvedLedger, watch: WatchState? = nil + ) throws { try withLock { + try declaration.validate(environment: environment) + try watch?.validate() + _ = try readWatch() let baseline = try StatePrecondition(store: self) let previous = try readDeclaration(prepared: baseline) let change = @@ -51,6 +56,11 @@ extension StateStore { transaction.requireUnchanged(since: baseline) try stageDeclaration(change, in: transaction, prepared: baseline) try stageLedger(ledger, limits: .standard, transaction: transaction, prepared: baseline) + if let watch { + try transaction.replace( + watchURL, with: .data(StateStore.encode(watch)), + expecting: baseline.evidence(for: watchURL)) + } try transaction.commit() } } From 7c5ec93e9e9054738058982331f674b57b14542c Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:22:10 +0800 Subject: [PATCH 081/171] test: compile Linux filename admission assertions --- .../AgentsCoreTests/RegisteredNativeTargetTests.swift | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift index 3a3ae72..78389e3 100644 --- a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift +++ b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift @@ -159,14 +159,14 @@ struct RegisteredNativeTargetTests { let directory = try DirectoryHandle(at: parent) try directory.write(recorded, data: recordedBytes) try directory.write(alternate, data: alternateBytes) - #require(authorized.lastPathComponent.utf8.elementsEqual(recorded.utf8)) - #require(unrecorded.lastPathComponent.utf8.elementsEqual(alternate.utf8)) + try #require(authorized.lastPathComponent.utf8.elementsEqual(recorded.utf8)) + try #require(unrecorded.lastPathComponent.utf8.elementsEqual(alternate.utf8)) let first = FileObjectIdentity(try #require(try directory.info(recorded))) let second = FileObjectIdentity(try #require(try directory.info(alternate))) - #require(first != second) + try #require(first != second) let names = try directory.names() - #require(names.contains(where: { $0.utf8.elementsEqual(recorded.utf8) })) - #require(names.contains(where: { $0.utf8.elementsEqual(alternate.utf8) })) + try #require(names.contains(where: { $0.utf8.elementsEqual(recorded.utf8) })) + try #require(names.contains(where: { $0.utf8.elementsEqual(alternate.utf8) })) let refused = FileTransaction(store: fixture.store) #expect(throws: CoreError.self) { try refused.delete(unrecorded) } #expect(throws: CoreError.self) { From e8047b6e2c872eb40c2e9480897809cdd9b8f156 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:46:20 +0800 Subject: [PATCH 082/171] fix: validate native hook fields and component profiles --- .../Adapters/CursorComponents.swift | 4 -- Sources/Components/CapabilityRegistry.swift | 7 +- .../Components/NativeComponentLayoutsV1.swift | 31 ++------- .../Components/NativeComponentLowering.swift | 11 +--- .../Components/NativeDocumentedHooksV1.swift | 17 +++-- Sources/Components/NativePluginLayoutV1.swift | 11 ++-- .../NativeComponentTests.swift | 65 ++++++++++++++----- 7 files changed, 77 insertions(+), 69 deletions(-) diff --git a/Sources/Components/Adapters/CursorComponents.swift b/Sources/Components/Adapters/CursorComponents.swift index a064917..4585053 100644 --- a/Sources/Components/Adapters/CursorComponents.swift +++ b/Sources/Components/Adapters/CursorComponents.swift @@ -37,10 +37,6 @@ extension CursorAdapter { path: name + ".md", selection: "file", value: .init(try input.frontmatter(fields, body: input.prompt())))) case "hook": - guard input.profileVersion == 2 else { - throw input.issue( - ["event"], .unverified, "native event/runner schema requires profile version 2") - } return try NativeDocumentedHooksV1.cursor(lowering, input) case "ignore": _ = try input.checkedNative([:]) diff --git a/Sources/Components/CapabilityRegistry.swift b/Sources/Components/CapabilityRegistry.swift index 35d1bf5..404d0da 100644 --- a/Sources/Components/CapabilityRegistry.swift +++ b/Sources/Components/CapabilityRegistry.swift @@ -145,16 +145,15 @@ package struct NativeComponentDescriptor { package let format: String package let evidence: NativeSchemaEvidence package var knownReaders: Set { - CapabilityRegistry.componentReaders( - request, kind: kind, profileVersion: NativeComponentLayoutsV1.profileVersion(request.surface)) + CapabilityRegistry.componentReaders(request, kind: kind) } } extension CapabilityRegistry { static func componentReaders( - _ request: NativeComponentRequest, kind: DeclaredComponentKind, profileVersion: Int + _ request: NativeComponentRequest, kind: DeclaredComponentKind ) -> Set { - if profileVersion == 2, request.surface == .claudeCode, [.hook, .subagent].contains(kind) { + if request.surface == .claudeCode, [.hook, .subagent].contains(kind) { return [.claudeCode, .cursor] } return [request.surface.agent] diff --git a/Sources/Components/NativeComponentLayoutsV1.swift b/Sources/Components/NativeComponentLayoutsV1.swift index 9ce825d..eb072c8 100644 --- a/Sources/Components/NativeComponentLayoutsV1.swift +++ b/Sources/Components/NativeComponentLayoutsV1.swift @@ -2,22 +2,13 @@ import AgentsCore import Foundation package enum NativeComponentLayoutsV1 { - static func profileVersion(_ surface: NativeClientSurface) -> Int { - switch surface { - case .claudeCode, .cursorEditor, .cursorCLI, .cursorCloud: 2 - default: 1 - } - } package static func format(_ surface: NativeClientSurface) -> String { - format(surface, version: profileVersion(surface)) - } - private static func format(_ surface: NativeClientSurface, version: Int) -> String { switch surface { - case .claudeCode: "agents/claude-components@\(version)" + case .claudeCode: "agents/claude-components@1" case .codexCLI: "agents/codex-components@1" case .geminiCLI: "agents/gemini-components@1" case .openCodeCLI: "agents/opencode-components@1" - case .cursorEditor, .cursorCLI, .cursorCloud: "agents/cursor-components@\(version)" + case .cursorEditor, .cursorCLI, .cursorCloud: "agents/cursor-components@1" } } @@ -26,9 +17,6 @@ package enum NativeComponentLayoutsV1 { "agents/claude-components@1": { try render($0, $1, $2, limits: limits, surface: .claudeCode) }, - "agents/claude-components@2": { - try render($0, $1, $2, limits: limits, surface: .claudeCode, version: 2) - }, "agents/codex-components@1": { try render($0, $1, $2, limits: limits, surface: .codexCLI) }, "agents/gemini-components@1": { try render($0, $1, $2, limits: limits, surface: .geminiCLI) }, "agents/opencode-components@1": { @@ -37,15 +25,12 @@ package enum NativeComponentLayoutsV1 { "agents/cursor-components@1": { try render($0, $1, $2, limits: limits, surface: .cursorEditor) }, - "agents/cursor-components@2": { - try render($0, $1, $2, limits: limits, surface: .cursorEditor, version: 2) - }, ] } private static func render( _ lowering: LockedLowering, _ ledger: ResolvedLedger, - _ resources: [String: URL], limits: LedgerLimits, surface: NativeClientSurface, version: Int = 1 + _ resources: [String: URL], limits: LedgerLimits, surface: NativeClientSurface ) throws -> [ReplayedArtifact] { func invalid() -> CoreError { .invalidState("invalid version 1 native component layout") } guard let layout = lowering.layout.object, @@ -53,7 +38,7 @@ package enum NativeComponentLayoutsV1 { let declared = layout["surface"]?.text.flatMap(NativeClientSurface.init(rawValue:)), format(declared) == format(surface), let scope = layout["scope"]?.text.flatMap(InstallScope.init(rawValue:)), - lowering.format == format(declared, version: version), lowering.inputs.count == 1, + lowering.format == format(declared), lowering.inputs.count == 1, let component = lowering.inputs.first, let record = ledger.components[component], lowering.resources == record.resources, record.resources.allSatisfy({ resources[$0] != nil }), @@ -74,7 +59,7 @@ package enum NativeComponentLayoutsV1 { let input = ComponentRenderInput( record: record, component: component, request: .init(surface: declared, scope: scope), occurrences: occurrences, - resources: resources, ledger: ledger, limits: limits, profileVersion: version) + resources: resources, ledger: ledger, limits: limits) try input.validateProfile() if record.kind == "plugin" { return try NativePluginLayoutV1.render(lowering, input) } switch declared { @@ -83,11 +68,7 @@ package enum NativeComponentLayoutsV1 { case .codexCLI: return try CodexAdapter.components(lowering, input) case .cursorEditor, .cursorCLI, .cursorCloud: return try CursorAdapter.components(lowering, input) - case .claudeCode: - guard version == 2 else { - throw input.issue(["kind"], .unverified, "complete fixed native schema is required") - } - return try ClaudeAdapter.components(lowering, input) + case .claudeCode: return try ClaudeAdapter.components(lowering, input) } } } diff --git a/Sources/Components/NativeComponentLowering.swift b/Sources/Components/NativeComponentLowering.swift index 687810d..9ebcc6f 100644 --- a/Sources/Components/NativeComponentLowering.swift +++ b/Sources/Components/NativeComponentLowering.swift @@ -64,8 +64,7 @@ package enum NativeComponentLowering { let record = frozen.ledger.components[owner.id]! let input = ComponentRenderInput( record: record, component: owner.id, request: request, - occurrences: owner.occurrences, resources: [:], ledger: frozen.ledger, limits: .standard, - profileVersion: NativeComponentLayoutsV1.profileVersion(request.surface)) + occurrences: owner.occurrences, resources: [:], ledger: frozen.ledger, limits: .standard) try input.validateProfile() return .init( id: id, format: format, inputs: [owner.id], resources: record.resources, deployments: [], @@ -89,11 +88,9 @@ struct ComponentRenderInput { let ledger: ResolvedLedger let limits: LedgerLimits let budget: NativeDocumentBudget - let profileVersion: Int init( record: LedgerComponent, component: String, request: NativeComponentRequest, - occurrences: [Int], resources: [String: URL], ledger: ResolvedLedger, limits: LedgerLimits, - profileVersion: Int = 1 + occurrences: [Int], resources: [String: URL], ledger: ResolvedLedger, limits: LedgerLimits ) { self.record = record self.component = component @@ -102,7 +99,6 @@ struct ComponentRenderInput { self.resources = resources self.ledger = ledger self.limits = limits - self.profileVersion = profileVersion budget = .init( limits: .init( storage: limits.encodedBytes, work: limits.encodedBytes, @@ -306,8 +302,7 @@ struct ComponentRenderInput { "recipients": LedgerPayload.strings([request.surface.agent.rawValue]), "knownReaders": LedgerPayload.strings( CapabilityRegistry.componentReaders( - request, kind: DeclaredComponentKind(rawValue: record.kind)!, - profileVersion: profileVersion + request, kind: DeclaredComponentKind(rawValue: record.kind)! ).map(\.rawValue).sorted()), "keys": LedgerPayload.strings(keys), "selection": .init(selection), "value": value, ] diff --git a/Sources/Components/NativeDocumentedHooksV1.swift b/Sources/Components/NativeDocumentedHooksV1.swift index 7cd6802..693a4cd 100644 --- a/Sources/Components/NativeDocumentedHooksV1.swift +++ b/Sources/Components/NativeDocumentedHooksV1.swift @@ -102,12 +102,17 @@ enum NativeDocumentedHooksV1 { throw input.issue( ["native", "claude-code", "if"], .unsupported, "native if filters never run on this event") } - if hook["onFailure"] != nil, - !["PreToolUse", "PermissionRequest", "UserPromptSubmit"].contains(event) - { - throw input.issue( - ["native", "claude-code", "onFailure"], .unverified, - "failure blocking is not verified for this event") + if hook["onFailure"] != nil { + guard hook["async"]?.boolean != true, hook["asyncRewake"]?.boolean != true else { + throw input.issue( + ["native", "claude-code", "onFailure"], .unsupported, + "native background hooks ignore this failure policy") + } + guard ["PreToolUse", "PermissionRequest", "UserPromptSubmit"].contains(event) else { + throw input.issue( + ["native", "claude-code", "onFailure"], .unverified, + "failure blocking is not verified for this event") + } } if let timeout = input.fields["timeoutSeconds"] { guard timeout.integer.map({ $0 > 0 }) == true else { diff --git a/Sources/Components/NativePluginLayoutV1.swift b/Sources/Components/NativePluginLayoutV1.swift index 3dc213d..070d317 100644 --- a/Sources/Components/NativePluginLayoutV1.swift +++ b/Sources/Components/NativePluginLayoutV1.swift @@ -68,14 +68,9 @@ enum NativePluginLayoutV1 { else { throw input.issue(["path"], .invalid, "native plugin manifest is not an exact JSON object") } - if input.profileVersion == 2 { - try NativePluginFieldsV1(input: input, resource: record, root: root).validate(manifestFields) - } else { + if input.request.surface == .geminiCLI { for (key, value) in manifestFields { - let metadata = - input.request.surface == .geminiCLI - ? ["name", "version"] : ["name", "version", "description"] - guard metadata.contains(key) else { + guard ["name", "version"].contains(key) else { throw input.issue( ["manifest", key], .unverified, "this native manifest field's registration/path semantics are not captured by the fixed profile" @@ -85,6 +80,8 @@ enum NativePluginLayoutV1 { throw input.issue(["manifest", key], .invalid, "native metadata must be a string") } } + } else { + try NativePluginFieldsV1(input: input, resource: record, root: root).validate(manifestFields) } guard try document.read(.init(keys: ["name"]))?.value == .string(name) else { throw input.issue( diff --git a/Tests/ComponentsTests/NativeComponentTests.swift b/Tests/ComponentsTests/NativeComponentTests.swift index 69c24e2..8d8c5b1 100644 --- a/Tests/ComponentsTests/NativeComponentTests.swift +++ b/Tests/ComponentsTests/NativeComponentTests.swift @@ -563,7 +563,7 @@ struct NativeComponentTests { ledger.lowerings = try linked.enumerated().map { try lower($0.element, frozen, surface: .claudeCode, id: "file-\($0.offset)") } - #expect(ledger.lowerings.allSatisfy { $0.format == "agents/claude-components@2" }) + #expect(ledger.lowerings.allSatisfy { $0.format == "agents/claude-components@1" }) ledger = try prepared(ledger, fixture) try replay(ledger, fixture) { output in let command = try #require(output[0].values?.object?["value"]?.text) @@ -649,6 +649,42 @@ struct NativeComponentTests { } } + @Test func claudeFailurePolicyRequiresSynchronousExecution() throws { + let fixture = try LinkFixture() + for flag in ["async", "asyncRewake"] { + for policy in ["block", "continue"] { + let item: [String: Any] = [ + "kind": "hook", "name": "guard", "agents": ["claude-code"], + "event": ["native": "PreToolUse"], "run": ["executable": "fixture-hook"], + "native": ["claude-code": [flag: true, "onFailure": policy]], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .claudeCode)] + do { + _ = try prepared(ledger, fixture) + Issue.record("accepted a failure policy the background native runner ignores") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["native", "claude-code", "onFailure"]) + #expect(issue.reason == .unsupported) + } + var synchronous = item + synchronous["native"] = ["claude-code": [flag: false, "onFailure": policy]] + let (syncLinked, syncFrozen) = try freeze([synchronous], fixture) + var sync = syncFrozen.ledger + sync.lowerings = [try lower(syncLinked[0], syncFrozen, surface: .claudeCode)] + sync = try prepared(sync, fixture) + try replay(sync, fixture) { output in + let handler = try #require( + output[0].values?.object?["value"]?.object?["hooks"]?.array?.first?.object) + #expect(handler["onFailure"]?.text == policy) + #expect(handler[flag]?.boolean == false) + #expect(handler["timeout"] == nil) + } + } + } + } + @Test func claudeLSPFreezesGeneratedManifestAndPrivateSlots() throws { let fixture = try LinkFixture() try fixture.write("#!/bin/sh\n# never executed\n", to: "bin/server", base: fixture.project) @@ -841,7 +877,7 @@ struct NativeComponentTests { } } - @Test func nativeManifestFieldsPreserveFrozenChildrenAndColdV1Replay() throws { + @Test func nativeManifestFieldsPreserveFrozenChildrenAndColdReplay() throws { let fixture = try LinkFixture() let manifest: [String: Any] = [ "name": "native-fields", "version": "build-label", "author": ["name": "Fixture"], @@ -946,23 +982,22 @@ struct NativeComponentTests { #expect(issue.field == ["manifest", "hooks", "Stop", "onFailure"]) #expect(issue.reason == .unsupported) } - // Revision 1 uses its frozen metadata-only validator and continues to replay valid bundles. - try fixture.write( - #"{"name":"native-fields","version":"1.0.0"}"#, to: "simple/.claude-plugin/plugin.json", - base: fixture.project) - var simple = item - simple["path"] = "simple" - let (oldLinked, oldFrozen) = try freeze([simple], fixture) - var old = oldFrozen.ledger - var lowering = try lower(oldLinked[0], oldFrozen, surface: .claudeCode) - lowering.format = "agents/claude-components@1" - old.lowerings = [lowering] - old = try prepared(old, fixture) - let locked = try ResolvedLedgerCodec.encode(old, limits: .standard) + let locked = try ResolvedLedgerCodec.encode(ledger, limits: .standard) try FileManager.default.removeItem(at: fixture.project) try replay(ResolvedLedgerCodec.decode(locked, limits: .standard), fixture) { output in #expect(output.count == 2) #expect(output[0].values?.object?["route"]?.text == "claudeSkillPlugin") + let root = try #require(output[1].tree) + let bytes = try Data(contentsOf: root.appendingPathComponent(".claude-plugin/plugin.json")) + let object = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + #expect(object["version"] as? String == "build-label") + let commands = try #require(object["commands"] as? [String: [String: Any]]) + #expect(commands["about"]?["argumentHint"] as? String == "[file]") + let servers = try #require(object["lspServers"] as? [String: [String: Any]]) + #expect(servers["fixture"]?["transport"] as? String == "socket") + #expect( + try String(contentsOf: root.appendingPathComponent("commands/default.md"), encoding: .utf8) + == "Default command.") } } From 96007aa8c4625165041b327d943dbbdf27387f5b Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:46:20 +0800 Subject: [PATCH 083/171] fix: retain producer source occurrence identity --- .../Import/RulesyncConfigImport.swift | 44 +++++++------ .../ComponentsTests/ImportProfileTests.swift | 63 +++++++++++++++++++ 2 files changed, 84 insertions(+), 23 deletions(-) diff --git a/Sources/Components/Import/RulesyncConfigImport.swift b/Sources/Components/Import/RulesyncConfigImport.swift index c510189..a8e0495 100644 --- a/Sources/Components/Import/RulesyncConfigImport.swift +++ b/Sources/Components/Import/RulesyncConfigImport.swift @@ -135,13 +135,15 @@ enum RulesyncConfigImport { "Object-form targets cannot be combined with features.") return } - var entries: [(ImportOrderedSource, SourceDeclaration?, [String: NativeValue])] = [] + var entries: [(ImportOrderedSource, SourceDeclaration?, String)] = [] if let (value, parsed) = effective["sources"] { guard case .array(let sources) = value else { throw ImportReadFailure.invalid } + // Producer occurrence keys belong to the complete declaration order, before filtering. + let keys = lockKeys(sources) for (index, source) in sources.enumerated() { let location = parsed.location("sources").appending(String(index)) guard let object = source.importObject, let raw = object["source"]?.importString, - !raw.isEmpty + !raw.isEmpty, let key = keys[index] else { diagnostics.add(.invalidInput, location, "Expected a producer source entry.") continue @@ -279,17 +281,16 @@ enum RulesyncConfigImport { rules: object["rules"]?.importStrings?.map { $0.hasSuffix(".md") ? String($0.dropLast(3)) : $0 }) - entries.append((intent, declaration, object)) + entries.append((intent, declaration, key)) diagnostics.proposal.orderedSources.append(intent) } } - let keys = lockKeys(entries) var locked: [String: (ImportedSource, [ImportResourceProposal], [String: Any])] = [:] for lock in locks { var request = lock - for (index, entry) in entries.enumerated() + for entry in entries where (entry.0.transport == "npm") == (lock.profile == .rulesyncNpmV1) { - if let declaration = entry.1 { request.sourceDeclarations[keys[index]] = declaration } + if let declaration = entry.1 { request.sourceDeclarations[entry.2] = declaration } } var result = ImportDiagnostics(proposal: .init(profile: lock.profile)) let fields = try ImportInput.document(request, limits: limits) @@ -315,18 +316,15 @@ enum RulesyncConfigImport { } } let declaredKeys = Set( - entries.enumerated().map { - ($0.element.0.transport == "npm" ? "npm:" : "git:") + keys[$0.offset] - }) + entries.map { ($0.0.transport == "npm" ? "npm:" : "git:") + $0.2 }) for key in locked.keys.sorted() where !declaredKeys.contains(key) { diagnostics.add( .unconverted, locked[key]!.0.origin, "Lock entry is absent from the effective ordered source config.") } var winners: Set = [] - for (index, entry) in entries.enumerated() { - let (intent, declaration, _) = entry - let key = (intent.transport == "npm" ? "npm:" : "git:") + keys[index] + for (intent, declaration, lockKey) in entries { + let key = (intent.transport == "npm" ? "npm:" : "git:") + lockKey var match = locked[key] if let candidate = match { let pathMatches = @@ -519,29 +517,29 @@ enum RulesyncConfigImport { if result.hasSuffix(".git") { result.removeLast(4) } return result.lowercased() } - private static func lockKeys( - _ entries: [(ImportOrderedSource, SourceDeclaration?, [String: NativeValue])] - ) -> [String] { - let bare = entries.map { normalizedKey($0.0.identity) } + private static func lockKeys(_ sources: [NativeValue]) -> [String?] { + let fields = sources.map(\.importObject) + let bare = fields.map { $0?["source"]?.importString.map(normalizedKey) } var counts: [String: Int] = [:] - for (index, entry) in entries.enumerated() where entry.0.transport != "npm" { - counts[bare[index], default: 0] += 1 + for index in sources.indices where fields[index]?["transport"]?.importString != "npm" { + if let key = bare[index] { counts[key, default: 0] += 1 } } var occurrences: [String: Int] = [:] let allowed = CharacterSet( charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~*'()/") - return entries.enumerated().map { index, entry in - guard entry.0.transport != "npm", counts[bare[index], default: 0] > 1 else { - return bare[index] + return sources.indices.map { index in + guard let object = fields[index], let key = bare[index] else { return nil } + guard object["transport"]?.importString != "npm", counts[key, default: 0] > 1 else { + return key } var qualifiers: [String] = [] for field in ["path", "rulesPath", "ref"] { - guard var value = entry.2[field]?.importString else { continue } + guard var value = object[field]?.importString else { continue } if field != "ref" { value = (try? ImportInput.path(value)) ?? value } qualifiers.append( field + "=" + (value.addingPercentEncoding(withAllowedCharacters: allowed) ?? "")) } - let base = bare[index] + (qualifiers.isEmpty ? "" : "#" + qualifiers.joined(separator: "&")) + let base = key + (qualifiers.isEmpty ? "" : "#" + qualifiers.joined(separator: "&")) occurrences[base, default: 0] += 1 let occurrence = occurrences[base]! return occurrence == 1 diff --git a/Tests/ComponentsTests/ImportProfileTests.swift b/Tests/ComponentsTests/ImportProfileTests.swift index 20efe5b..643c3d8 100644 --- a/Tests/ComponentsTests/ImportProfileTests.swift +++ b/Tests/ComponentsTests/ImportProfileTests.swift @@ -382,6 +382,69 @@ struct ImportProfileTests { !result.diagnostics.contains { $0.code == .ambiguousSource || $0.code == .incompletePin }) } + @Test(arguments: ["empty", "valid", "selection"]) + func sourceOccurrencesStayAlignedWithCompleteProducerList(_ first: String) throws { + let fixture = try ImportProfileFixture() + try fixture.directory(".rulesync") + let firstSource = first == "selection" ? "github:acme/repo" : "acme/repo" + let firstSkills = first == "empty" ? "[]" : #"["*"]"# + try fixture.write( + "config.jsonc", + """ + {"sources":[{"source":"\(firstSource)","skills":\(firstSkills)}, + {"source":"acme/repo","skills":["*"]}]} + """) + let commitA = String(repeating: "a", count: 40) + let commitB = String(repeating: "b", count: 40) + let integrityA = "sha256-" + String(repeating: "c", count: 64) + let integrityB = "sha256-" + String(repeating: "d", count: 64) + try fixture.write( + "lock.json", + """ + {"lockfileVersion":1,"sources":{ + "acme/repo":{"resolvedRef":"\(commitA)","skillsPath":"skills","skillSelection":["*"], + "skills":{"from-a":{"integrity":"\(integrityA)"}}}, + "acme/repo#entry=2":{"resolvedRef":"\(commitB)","skillsPath":"skills","skillSelection":["*"], + "skills":{"from-b":{"integrity":"\(integrityB)"}}}}} + """) + var config = fixture.input(.rulesyncConfig, "config.jsonc") + if first == "selection" { config.selection = ["acme/repo"] } + let before = try fixture.hash() + let result = try SourceImport.previewRulesync( + configs: [config], locks: [fixture.input(.rulesyncSourcesV1, "lock.json")]) + let acceptedBoth = first == "valid" + let sources = result.sources.filter { !$0.alias.contains("-skill-") } + #expect(sources.map(\.pin.commit) == (acceptedBoth ? [commitA, commitB] : [commitB])) + #expect(sources.last?.alias == "rulesync-source-1") + #expect(sources.last?.declaration?.requirement == .revision(commitB)) + #expect( + result.orderedSources.map(\.origin.pointer) + == (acceptedBoth ? ["/sources/0", "/sources/1"] : ["/sources/1"])) + #expect( + result.resources.map(\.producerName) == (acceptedBoth ? ["from-a", "from-b"] : ["from-b"])) + #expect( + result.resources.map(\.path) + == (acceptedBoth ? ["skills/from-a", "skills/from-b"] : ["skills/from-b"])) + #expect(result.resources.last?.sourceAlias == "rulesync-source-1") + #expect(result.resources.last?.producerIntegrity?.value == integrityB) + #expect(result.resources.allSatisfy { $0.requiresStandaloneSource }) + #expect( + result.components.last?.declaration + == .skills(source: "rulesync-source-1-skill-0", .init(select: .names(["from-b"])))) + #expect(result.components.count == (acceptedBoth ? 2 : 1)) + #expect( + result.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == "config.jsonc" + && $0.location.pointer == "/sources/0/skills" + } == (first == "empty")) + #expect( + !result.diagnostics.contains { + $0.code == .incompletePin && $0.location.document == "config.jsonc" + && $0.location.pointer == "/sources/1" + }) + #expect(try fixture.hash() == before) + } + @Test func embeddedRulesyncSelectorPreservesExplicitSourceAndLockedResources() throws { let fixture = try ImportProfileFixture() try fixture.directory(".rulesync") From 4cfe2ce6f2a0ad3b6f119ffec23587aca7b2fd36 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:58:17 +0800 Subject: [PATCH 084/171] fix: retain indexed artifact content and nested resources --- Documentation/Architecture/Package.md | 10 +- .../AgentsCore/SourceResolutionSession.swift | 38 ++- .../AgentsSkills/SkillSnapshotReader.swift | 13 +- Sources/AgentsSkills/WellKnownProvider.swift | 35 ++- Sources/Components/ComponentLinker.swift | 33 ++- Sources/Components/Expansion.swift | 72 +++-- .../ArtifactLinkingTests.swift | 247 ++++++++++++++++++ 7 files changed, 413 insertions(+), 35 deletions(-) create mode 100644 Tests/ComponentsTests/ArtifactLinkingTests.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index d5ee43b..76b5b9f 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -344,8 +344,14 @@ An all-selection includes members from their effective override views, admits li members only when that view is selected, and omits missing effective-view members; named selections still require their members. Named own-instruction reads validate only the selected path and its ancestors, while full enumeration remains strict. -Remote-contained local sources inherit the producer snapshot. Existing skill-index formats supply skill artifacts, and do -not define an export-package format. +Remote-contained local sources inherit the producer snapshot. Existing skill-index +formats supply skill artifacts, and do not define an export-package format. Indexed +members have independent artifact-digest pins. A scoped link can retain an admitted +ledger alongside its direct pins: protected members borrow their exact resource trees +and content objects, while selected members download only their requested artifacts. +The recorded index transport and artifact digest must both match; a missing closure +fails rather than refreshing that member. Nested artifact files and executable flags +are materialized only inside the source session's disposable workspace. The linked result records relative resource evidence, source requirements, reference and contribution occurrences, provenance and exact dependency pins. diff --git a/Sources/AgentsCore/SourceResolutionSession.swift b/Sources/AgentsCore/SourceResolutionSession.swift index b9e0503..55f8b8c 100644 --- a/Sources/AgentsCore/SourceResolutionSession.swift +++ b/Sources/AgentsCore/SourceResolutionSession.swift @@ -283,7 +283,9 @@ package final class SourceResolutionSession { return try view.resource(path) } - package func fileSnapshot(source: String, revision: String, files: [String: Data]) throws + package func fileSnapshot( + source: String, revision: String, files: [String: Data], executableFlags: [String: Bool] = [:] + ) throws -> SourceSnapshot { try requireOpen() @@ -293,13 +295,45 @@ package final class SourceResolutionSession { try FileSystem.createDirectory(at: root) for path in files.keys.sorted() { try Task.checkCancellation() - try FileSystem.write(files[path]!, to: PathSafety.resolvedChild(base: root, subpath: path)) + let file = try PathSafety.resolvedChild(base: root, subpath: path) + try FileSystem.createDirectory(at: file.deletingLastPathComponent()) + try FileSystem.write(files[path]!, to: file) + try FileManager.default.setAttributes( + [.posixPermissions: executableFlags[path] == true ? 0o755 : 0o644], ofItemAtPath: file.path) } let result = try SourceSnapshot(snapshot: id, pin: nil, root: root) register(result) return result } + /// Reborrows an admitted artifact closure without consulting its index or download coordinates. + package func artifactSnapshot( + source: String, resource: LedgerResource, objects: [String: Data] + ) throws -> SourceSnapshot { + try requireOpen() + guard resource.kind == .artifact, let artifact = resource.artifact else { + throw CoreError.invalidState("missing pinned artifact resource") + } + try artifact.validate() + let id = SourceSnapshotID(source: source, revision: artifact.digest) + if let existing = borrowed[id] { return existing } + let root = workspace.appendingPathComponent(UUID().uuidString) + let destination = + resource.support.isEmpty + ? try PathSafety.resolvedChild(base: root, subpath: resource.path) : root + var embedded = resource + embedded.kind = .embedded + try LedgerResources.materialize(embedded, objects: objects, at: destination) + let result = try SourceSnapshot(snapshot: id, pin: nil, root: root) + let captured = try LedgerResources.capture( + result.resource(resource.path), embed: false, limits: .standard, sourceRoot: root) + guard captured.hash == resource.hash else { + throw CoreError.invalidState("pinned artifact resource hash mismatch") + } + register(result) + return result + } + package func liveSnapshot(_ source: SourceDeclaration) throws -> SourceSnapshot { try requireOpen() guard source.kind == .local, source.requirement == nil else { diff --git a/Sources/AgentsSkills/SkillSnapshotReader.swift b/Sources/AgentsSkills/SkillSnapshotReader.swift index 9c00905..952487c 100644 --- a/Sources/AgentsSkills/SkillSnapshotReader.swift +++ b/Sources/AgentsSkills/SkillSnapshotReader.swift @@ -57,13 +57,20 @@ package struct SnapshotIndexSkill: Sendable { package let name: String package let artifact: LockedArtifact package let files: [String: Data] + package let executableFlags: [String: Bool] } extension SkillSnapshotReader { - package static func index(_ source: SourceDeclaration) throws -> [SnapshotIndexSkill] { + package static func index( + _ source: SourceDeclaration, names: [String]? = nil, exclude: [String] = [] + ) throws -> [SnapshotIndexSkill] { try Task.checkCancellation() - let result = try WellKnownProvider().fetchAllSkills(from: source.location).map { - SnapshotIndexSkill(name: $0.installName, artifact: $0.artifact, files: $0.files) + let result = try WellKnownProvider().fetchAllSkills( + from: source.location, names: names, exclude: exclude + ).map { + SnapshotIndexSkill( + name: $0.installName, artifact: $0.artifact, files: $0.files, + executableFlags: $0.executableFlags) } try Task.checkCancellation() return result diff --git a/Sources/AgentsSkills/WellKnownProvider.swift b/Sources/AgentsSkills/WellKnownProvider.swift index 7e969cf..b37810c 100644 --- a/Sources/AgentsSkills/WellKnownProvider.swift +++ b/Sources/AgentsSkills/WellKnownProvider.swift @@ -12,18 +12,21 @@ struct WellKnownRemoteSkill: Equatable, Sendable { var sourceURL: URL var digest: String? var files: [String: Data] + var executableFlags: [String: Bool] var artifact: LockedArtifact var payloads: [String: Data] init( installName: String, description: String, sourceURL: URL, digest: String? = nil, - files: [String: Data], artifact: LockedArtifact? = nil, payloads: [String: Data] = [:] + files: [String: Data], artifact: LockedArtifact? = nil, payloads: [String: Data] = [:], + executableFlags: [String: Bool] = [:] ) { self.installName = installName self.description = description self.sourceURL = sourceURL self.digest = digest self.files = files + self.executableFlags = executableFlags self.artifact = artifact ?? LockedArtifact(type: .skillMD, url: sourceURL.absoluteString, digest: digest ?? "") @@ -166,11 +169,15 @@ struct WellKnownProvider: Sendable { let data = try fetch(artifactURL) try verifyDigest(data: data, expected: entry.digest) let files: [String: Data] + let executableFlags: [String: Bool] switch entry.type { case "skill-md": files = ["SKILL.md": data] + executableFlags = [:] case "archive": - files = try unpackArchive(data, artifactURL: artifactURL) + let unpacked = try unpackArchive(data, artifactURL: artifactURL) + files = unpacked.files + executableFlags = unpacked.executableFlags default: throw CoreError.invalidSource("unsupported well-known artifact type: \(entry.type)") } @@ -183,7 +190,7 @@ struct WellKnownProvider: Sendable { artifact: LockedArtifact( type: entry.type == "archive" ? .archive : .skillMD, url: artifactURL.absoluteString, digest: entry.digest), - payloads: [entry.digest: data] + payloads: [entry.digest: data], executableFlags: executableFlags ) } } @@ -209,7 +216,7 @@ struct WellKnownProvider: Sendable { return (["SKILL.md": data], payloads) case .archive: let data = try download(artifact.url, digest: artifact.digest) - return (try unpackArchive(data, artifactURL: URL(string: artifact.url)!), payloads) + return (try unpackArchive(data, artifactURL: URL(string: artifact.url)!).files, payloads) case .files: let records = artifact.files ?? [] guard try LockedArtifact.filesDigest(records) == artifact.digest else { @@ -250,7 +257,9 @@ struct WellKnownProvider: Sendable { ) } - private func unpackArchive(_ data: Data, artifactURL: URL) throws -> [String: Data] { + private func unpackArchive(_ data: Data, artifactURL: URL) throws -> ( + files: [String: Data], executableFlags: [String: Bool] + ) { let lowerPath = artifactURL.path.lowercased() if lowerPath.hasSuffix(".zip") || data.starts(with: [0x50, 0x4b]) { return try unpackZip(data) @@ -258,7 +267,9 @@ struct WellKnownProvider: Sendable { return try unpackTarGz(data) } - private func unpackTarGz(_ data: Data) throws -> [String: Data] { + private func unpackTarGz(_ data: Data) throws -> ( + files: [String: Data], executableFlags: [String: Bool] + ) { let tempRoot = FileManager.default.temporaryDirectory .appendingPathComponent("agents-artifact-" + UUID().uuidString) let archive = tempRoot.appendingPathComponent("artifact.tar.gz") @@ -298,7 +309,9 @@ struct WellKnownProvider: Sendable { return try collectExtractedFiles(from: extract) } - private func unpackZip(_ data: Data) throws -> [String: Data] { + private func unpackZip(_ data: Data) throws -> ( + files: [String: Data], executableFlags: [String: Bool] + ) { let tempRoot = FileManager.default.temporaryDirectory .appendingPathComponent("agents-artifact-" + UUID().uuidString) let archive = tempRoot.appendingPathComponent("artifact.zip") @@ -338,7 +351,9 @@ struct WellKnownProvider: Sendable { return try collectExtractedFiles(from: extract) } - private func collectExtractedFiles(from extract: URL) throws -> [String: Data] { + private func collectExtractedFiles(from extract: URL) throws -> ( + files: [String: Data], executableFlags: [String: Bool] + ) { guard let enumerator = FileManager.default.enumerator( at: extract, @@ -346,7 +361,7 @@ struct WellKnownProvider: Sendable { options: [.skipsPackageDescendants] ) else { - return [:] + return ([:], [:]) } var totalBytes = 0 @@ -368,7 +383,7 @@ struct WellKnownProvider: Sendable { guard files.keys.contains(where: { $0.lowercased() == "skill.md" }) else { throw CoreError.invalidSource("well-known archive has no SKILL.md") } - return files + return (files, try FileHash.executableFlags(extract)) } } diff --git a/Sources/Components/ComponentLinker.swift b/Sources/Components/ComponentLinker.swift index 3fb2b29..a66c126 100644 --- a/Sources/Components/ComponentLinker.swift +++ b/Sources/Components/ComponentLinker.swift @@ -9,12 +9,17 @@ package enum ComponentLinker { document: DeclarationDocument, store: StateStore, platform: DeclarationPlatform, preserving pins: [String: SourceRevision] = [:], directPins: [ComponentKey: SourceRevision] = [:], + retaining ledger: ResolvedLedger? = nil, _ body: (LinkedComponents, SourceResolutionSession) throws -> T ) throws -> T { - try SourceResolutionSession.withTemporaryRead(store: store) { session in + if let ledger { + try ResolvedLedgerCodec.checkModel(ledger, limits: .standard) + try ledger.validate() + } + return try SourceResolutionSession.withTemporaryRead(store: store) { session in let linker = Linking( document: document, store: store, platform: platform, - session: session, directPins: directPins) + session: session, directPins: directPins, retainedLedger: ledger) let graph = try linker.solve(preserving: pins) return try body(graph, session) } @@ -53,6 +58,7 @@ final class Linking { let platform: DeclarationPlatform let session: SourceResolutionSession let directPins: [ComponentKey: SourceRevision] + let retainedLedger: ResolvedLedger? let budget = LinkBudget() var documents: [GroupIdentity: LinkingDocument] = [:] var nonGit = Set() @@ -64,13 +70,34 @@ final class Linking { init( document: DeclarationDocument, store: StateStore, platform: DeclarationPlatform, - session: SourceResolutionSession, directPins: [ComponentKey: SourceRevision] + session: SourceResolutionSession, directPins: [ComponentKey: SourceRevision], + retainedLedger: ResolvedLedger? ) { self.document = document self.store = store self.platform = platform self.session = session self.directPins = directPins + self.retainedLedger = retainedLedger + } + + /// Direct artifact pins use the artifact digest, independently of every other index member. + /// The caller supplies the admitted ledger closure; absence never means refresh the index. + func retainedArtifact(key: ComponentKey, source: String) throws -> LedgerResource? { + guard let pin = directPins[key], pin.revision.hasPrefix("sha256:") else { return nil } + guard let ledger = retainedLedger else { + throw CoreError.invalidState("missing pinned artifact closure") + } + for resource in ledger.resources.sorted(by: { $0.key < $1.key }).map(\.value) { + try budget.step() + guard resource.kind == .artifact, resource.artifact?.digest == pin.revision, + let origin = ledger.sources[resource.source], origin.kind == .wellKnown, + origin.revision == pin.revision, let transport = origin.transport, + try SourceDeclaration(kind: .wellKnown, location: transport).transportIdentity() == source + else { continue } + return resource + } + throw CoreError.invalidState("missing pinned artifact resource for source") } func solve(preserving pins: [String: SourceRevision]) throws -> LinkedComponents { diff --git a/Sources/Components/Expansion.swift b/Sources/Components/Expansion.swift index 4043763..ef573a4 100644 --- a/Sources/Components/Expansion.swift +++ b/Sources/Components/Expansion.swift @@ -14,7 +14,12 @@ final class Expansion { var active: [GroupIdentity] = [] var nextOccurrence = 0 var referenceParent: Int? - var indexes: [String: [SnapshotIndexSkill]] = [:] + private struct IndexRequest: Hashable { + let source: String + let names: [String]? + let exclude: [String] + } + private var indexes: [IndexRequest: [SnapshotIndexSkill]] = [:] var values = ManifestExpansionBudget() init(linking: Linking, choices: [String: SourceRevision], emit: Bool) { @@ -387,26 +392,63 @@ final class Expansion { context: LinkingDocument, group: String?, condition: DeclarationCondition, chain: [SourceSpan], position: SourceMapEntry?, dependencies: [SourceSnapshotID] ) throws { - if indexes[address.id] == nil { indexes[address.id] = try SkillSnapshotReader.index(source) } - let available = indexes[address.id]! - let names: [String] + let requested: [String]? switch selection.select { - case .all: names = available.map(\.name) - case .names(let requested): names = requested + case .all: requested = nil + case .names(let names): requested = names.map(PathSafety.sanitizeName) } - for name in names where !(selection.exclude ?? []).contains(name) { - let location = chain + (position.map { [$0.span] + $0.origins } ?? []) - guard let artifact = available.first(where: { $0.name == name }) else { - throw LinkError.missing("skill '\(name)'", location) + let excluded = Set((selection.exclude ?? []).map(PathSafety.sanitizeName)) + var overrides: [String: SkillOverride] = [:] + for (name, override) in selection.overrides ?? [:] { + let canonical = PathSafety.sanitizeName(name) + guard overrides[canonical] == nil else { + throw LinkError.invalid("duplicate canonical skill override: \(canonical)", chain) } - let override = selection.overrides?[name] + overrides[canonical] = override + } + var retained: [String: LedgerResource] = [:] + for candidate in linking.directPins.keys.sorted(by: { $0.name < $1.name }) { + try linking.budget.step() + guard candidate.kind == .skills, candidate.source == context.view.snapshot.source, + candidate.root == context.view.discoveryPath, candidate.group == group, + !excluded.contains(candidate.name), requested?.contains(candidate.name) ?? true, + let resource = try linking.retainedArtifact(key: candidate, source: address.id) + else { continue } + retained[candidate.name] = resource + } + let freshNames = requested.map { $0.filter { retained[$0] == nil && !excluded.contains($0) } } + let request = IndexRequest( + source: address.id, names: freshNames?.sorted(), + exclude: excluded.union(retained.keys).sorted()) + if indexes[request] == nil { + indexes[request] = + try freshNames == [] + ? [] : SkillSnapshotReader.index(source, names: request.names, exclude: request.exclude) + } + let available = indexes[request]! + let names = requested ?? (available.map(\.name) + retained.keys).sorted() + for name in names where !excluded.contains(name) { + let location = chain + (position.map { [$0.span] + $0.origins } ?? []) + let override = overrides[name] let mode = override?.mode ?? selection.mode ?? .link guard mode != .edit else { throw LinkError.invalid("edit requires an actual local skill with no requirement", location) } - let view = try linking.session.fileSnapshot( - source: address.id, revision: artifact.artifact.digest, - files: artifact.files) + let view: SourceSnapshot + let artifact: LockedArtifact + if let resource = retained[name] { + artifact = resource.artifact! + view = try linking.session.artifactSnapshot( + source: address.id, resource: resource, objects: linking.retainedLedger!.contentObjects) + } else { + guard let current = available.first(where: { $0.name == name }) else { + throw LinkError.missing("skill '\(name)'", location) + } + artifact = current.artifact + view = try linking.session.fileSnapshot( + source: address.id, revision: artifact.digest, + files: current.files, executableFlags: current.executableFlags) + } try linking.budget.snapshot(view.snapshot) guard let skill = try SkillSnapshotReader.read(view).first, PathSafety.sanitizeName(skill.name) == name @@ -426,7 +468,7 @@ final class Expansion { resources: [ LinkedResource( snapshot: view.snapshot, path: skill.path, hash: skill.hash, - executableFlags: skill.executableFlags, artifact: artifact.artifact) + executableFlags: skill.executableFlags, artifact: artifact) ], chain: chain, position: position, dependencies: dependencies + [view.snapshot]) } diff --git a/Tests/ComponentsTests/ArtifactLinkingTests.swift b/Tests/ComponentsTests/ArtifactLinkingTests.swift new file mode 100644 index 0000000..0155be5 --- /dev/null +++ b/Tests/ComponentsTests/ArtifactLinkingTests.swift @@ -0,0 +1,247 @@ +import AgentsCore +import AgentsManifest +import Foundation +import Testing + +@testable import Components + +@Suite("Indexed component resources", .serialized) +struct ArtifactLinkingTests { + @Test func nestedArtifactFilesAreScopedAndContained() throws { + let fixture = try LinkFixture() + var borrowed: URL? + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let view = try session.fileSnapshot( + source: "https://example.invalid", revision: "fixture", + files: [ + "SKILL.md": Data("skill".utf8), "references/context.md": Data("context".utf8), + "scripts/run": Data("script".utf8), + ], executableFlags: ["scripts/run": true]) + borrowed = view.root + #expect(try Data(contentsOf: view.resource("references/context.md")) == Data("context".utf8)) + #expect(try FileHash.executableFlags(view.root)["scripts/run"] == true) + #expect(throws: CoreError.self) { + try session.fileSnapshot( + source: "https://example.invalid", revision: "unsafe", + files: ["../escape": Data()]) + } + } + #expect(!FileManager.default.fileExists(atPath: try #require(borrowed).path)) + } + + @Test(arguments: [InstallMode.copy, .link]) + func selectedIndexDownloadsAndRetainedClosuresAreIndependent(_ mode: InstallMode) throws { + let fixture = try LinkFixture() + let web = fixture.root.appendingPathComponent("web") + try FileManager.default.createDirectory(at: web, withIntermediateDirectories: true) + let server = try IndexHTTPServer(root: web) + defer { server.stop() } + let oldAlpha = try archive("alpha", body: "old alpha", fixture: fixture, web: web) + let oldBeta = try archive("beta", body: "old beta", fixture: fixture, web: web) + try index([("alpha", oldAlpha), ("beta", oldBeta)], fixture: fixture, web: web) + let document = try fixture.document( + """ + version: 1 + sources: {web: {index: '\(server.url)'}} + components: [{kind: skills, source: web, select: [alpha, beta], mode: \(mode.rawValue)}] + """) + func freeze(pins: [ComponentKey: SourceRevision] = [:], previous: ResolvedLedger? = nil) throws + -> ResolvedLedger + { + try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS, + directPins: pins, retaining: previous + ) { graph, session in + try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: [ + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: ".") + ]), limits: .standard) + } + } + let original = try freeze() + let previous = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(original, limits: .standard), limits: .standard) + let beta = try #require(previous.components.values.first { $0.name == "beta" }) + #expect(previous.sources[beta.source]?.revision == oldBeta) + let betaResourceID = try #require(beta.resources.first) + let betaResource = try #require(previous.resources[betaResourceID]) + #expect(betaResource.entries.contains { $0.path == "references/context.md" }) + #expect(betaResource.entries.contains { $0.path == "scripts/run" && $0.executable }) + let key = ComponentKey( + source: "local:" + fixture.project.path, root: ".", group: nil, + kind: .skills, name: "beta") + let newAlpha = try archive("alpha", body: "new alpha", fixture: fixture, web: web) + // The protected member disappears from the index and its exact download is unavailable. + try FileManager.default.removeItem(at: web.appendingPathComponent("beta.zip")) + try index([("alpha", newAlpha)], fixture: fixture, web: web) + let next = try freeze(pins: [key: .init(revision: oldBeta)], previous: previous) + let retained = try #require(next.components.values.first { $0.name == "beta" }) + #expect(retained == beta) + let retainedResourceID = try #require(retained.resources.first) + #expect(next.resources[retainedResourceID] == betaResource) + let alpha = try #require(next.components.values.first { $0.name == "alpha" }) + #expect(next.sources[alpha.source]?.revision == newAlpha) + let nested = try #require( + betaResource.entries.first { $0.path == "references/context.md" }?.object) + #expect(next.contentObjects[nested] == Data("old beta context".utf8)) + #expect(throws: LinkError.self) { try freeze(pins: [key: .init(revision: oldBeta)]) } + // A different advertised artifact must not be fetched for the protected member. + try index( + [("alpha", newAlpha), ("beta", "sha256:" + String(repeating: "a", count: 64))], + fixture: fixture, web: web) + let advertised = try freeze(pins: [key: .init(revision: oldBeta)], previous: previous) + #expect(advertised.components.values.first { $0.name == "beta" } == beta) + var replay = next + #if os(macOS) + let platform = "macos" + #else + let platform = "linux" + #endif + replay.lowerings = replay.components.sorted { $0.key < $1.key }.map { id, component in + .init( + id: component.name, format: "agents/skill@1", inputs: [id], + resources: component.resources, deployments: [], + layout: .init(object: ["name": .init(component.name)]), platform: platform, artifacts: []) + } + replay = try LedgerReplay.prepareLowerings( + replay, store: fixture.store, + roots: ["project": fixture.project], limits: .standard) + replay = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(replay, limits: .standard), limits: .standard) + server.stop() + try FileManager.default.removeItem(at: web) + try LedgerReplay.withReplay( + replay, store: fixture.store, roots: ["project": fixture.project], limits: .standard + ) { artifacts in + let betaTree = try #require(artifacts.first { $0.name == "beta" }?.tree) + #expect( + try Data(contentsOf: betaTree.appendingPathComponent("references/context.md")) + == Data("old beta context".utf8)) + #expect(try FileHash.executableFlags(betaTree)["scripts/run"] == true) + } + // A wholly retained named selection works without an index or server. + let offline = try fixture.document( + """ + version: 1 + sources: {web: {index: '\(server.url)'}} + components: [{kind: skills, source: web, select: [beta], mode: copy}] + """) + try ComponentLinker.withLinkedComponents( + document: offline, store: fixture.store, platform: .macOS, + directPins: [key: .init(revision: oldBeta)], retaining: previous + ) { graph, session in + #expect(graph.components.count == 1) + let resource = try #require(graph.components.first?.resources.first) + #expect( + try FileHash.folderHash(session.resource(snapshot: resource.snapshot, path: resource.path)) + == String(betaResource.hash.dropFirst(7))) + } + let rebound = try fixture.document( + """ + version: 1 + sources: {web: {index: '\(server.url)/other'}} + components: [{kind: skills, source: web, select: [beta], mode: copy}] + """) + #expect(throws: LinkError.self) { + try ComponentLinker.withLinkedComponents( + document: rebound, store: fixture.store, platform: .macOS, + directPins: [key: .init(revision: oldBeta)], retaining: previous + ) { _, _ in } + } + var corrupt = previous + corrupt.resources[betaResourceID]?.hash = "sha256:" + String(repeating: "0", count: 64) + #expect(throws: LinkError.self) { + try ComponentLinker.withLinkedComponents( + document: offline, store: fixture.store, platform: .macOS, + directPins: [key: .init(revision: oldBeta)], retaining: corrupt + ) { _, _ in } + } + } + + private func archive(_ name: String, body: String, fixture: LinkFixture, web: URL) throws + -> String + { + let root = fixture.root.appendingPathComponent(name) + try fixture.write( + "---\nname: \(name)\ndescription: Fixture\n---\n\(body)\n", to: "SKILL.md", base: root) + try fixture.write(body + " context", to: "references/context.md", base: root) + try fixture.write("fixture script", to: "scripts/run", base: root) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: root.appendingPathComponent("scripts/run").path) + let zip = web.appendingPathComponent(name + ".zip") + if FileManager.default.fileExists(atPath: zip.path) { + try FileManager.default.removeItem(at: zip) + } + try ProcessRunner.run( + "/usr/bin/env", arguments: ["zip", "-qr", zip.path, "."], workingDirectory: root) + return "sha256:" + (try FileHash.sha256Hex(file: zip)) + } + + private func index(_ members: [(String, String)], fixture: LinkFixture, web: URL) throws { + let entries = members.map { name, digest in + [ + "name": name, "description": "Fixture", "type": "archive", "url": "/\(name).zip", + "digest": digest, + ] + } + let bytes = try JSONSerialization.data(withJSONObject: [ + "$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json", "skills": entries, + ]) + try fixture.write( + String(decoding: bytes, as: UTF8.self), to: ".well-known/agent-skills/index.json", base: web) + } +} + +private final class IndexHTTPServer { + private let process = Process() + private let output = Pipe() + let url: String + + init(root: URL) throws { + process.executableURL = URL(fileURLWithPath: "/usr/bin/perl") + process.arguments = [ + "-e", + #""" + use IO::Socket::INET; + alarm 120; + my $root = shift; + my $server = IO::Socket::INET->new(LocalAddr => '127.0.0.1', LocalPort => 0, Listen => 8, Proto => 'tcp') or die $!; + $| = 1; print $server->sockport, "\n"; + while (my $client = $server->accept()) { + my $request = <$client>; + my ($path) = $request =~ m{^GET (/[^ ]*) HTTP/}; + while (my $line = <$client>) { last if $line eq "\r\n"; } + my $bytes = ''; my $status = '404 Not Found'; + if (defined($path) && $path !~ /\.\./ && open(my $file, '<', "$root$path")) { + binmode $file; local $/; $bytes = <$file>; close $file; $status = '200 OK'; + } + print $client "HTTP/1.1 $status\r\nContent-Length: ", length($bytes), "\r\nConnection: close\r\n\r\n", $bytes; + close $client; + } + """#, root.path, + ] + process.standardOutput = output + try process.run() + output.fileHandleForWriting.closeFile() + var bytes = Data() + while let byte = try output.fileHandleForReading.read(upToCount: 1), !byte.isEmpty { + if byte == Data([10]) { break } + bytes.append(byte) + } + guard let port = Int(String(decoding: bytes, as: UTF8.self)) else { + process.waitUntilExit() + try? output.fileHandleForReading.close() + throw CoreError.invalidState("fixture listener unavailable") + } + url = "http://127.0.0.1:\(port)" + } + + func stop() { + if process.isRunning { + process.terminate() + process.waitUntilExit() + } + try? output.fileHandleForReading.close() + } +} From eae5de99168d49c0532e5ca8e6447f327476d22a Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:57:40 +0800 Subject: [PATCH 085/171] feat: expose bounded MCP connection tests --- Documentation/Architecture/Package.md | 2 +- Package.swift | 2 + .../MCPConnectionOperations.swift | 402 ++++++++++++++++++ .../MCPConnectionResources.swift | 134 ++++++ .../MCPConnectionOperationsTests.swift | 288 +++++++++++++ Tests/MCPTestProcess/main.swift | 7 +- 6 files changed, 833 insertions(+), 2 deletions(-) create mode 100644 Sources/AgentsUpdates/MCPConnectionOperations.swift create mode 100644 Sources/AgentsUpdates/MCPConnectionResources.swift create mode 100644 Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 1c1d5bf..1b2de2b 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -14,7 +14,7 @@ AgentsManifest → AgentsCore, TreeSitterYAML, TreeSitter, Yams AgentsSkills → AgentsCore, AgentsManifest, Yams AgentsInstructions → AgentsCore, AgentsManifest, Markdown Components → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, NativeDocuments, MCP -AgentsUpdates → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions +AgentsUpdates → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, Components NativeDocuments → AgentsCore, TOMLSemantics, TreeSitterTOML, TreeSitter TOMLSemantics → Foundation TreeSitterTOML → (vendored C grammar) diff --git a/Package.swift b/Package.swift index b1ab333..cc853c9 100644 --- a/Package.swift +++ b/Package.swift @@ -67,6 +67,7 @@ let package = Package( name: "AgentsUpdates", dependencies: [ "AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions", "CPlatform", + "Components", ]), .target( name: "Components", @@ -114,6 +115,7 @@ let package = Package( name: "AgentsUpdatesTests", dependencies: [ "AgentsUpdates", "AgentsManifest", "StateTestProcess", "StateTestSupport", "CPlatform", + "MCPTestProcess", ]), .testTarget( name: "AgentsSkillsTests", diff --git a/Sources/AgentsUpdates/MCPConnectionOperations.swift b/Sources/AgentsUpdates/MCPConnectionOperations.swift new file mode 100644 index 0000000..b9bc872 --- /dev/null +++ b/Sources/AgentsUpdates/MCPConnectionOperations.swift @@ -0,0 +1,402 @@ +import AgentsCore +import Components +import Foundation + +public enum MCPConnectionPreparationError: String, Error, Sendable { + case invalidSelection, invalidConfiguration, invalidResource, resourceChanged +} + +/// Fixed selected input; it neither resolves sources nor looks up a component by +/// name. Literal configuration and captured resource bytes have no debug dump. +public struct MCPConnectionSnapshot: Sendable, CustomStringConvertible, + CustomDebugStringConvertible, CustomReflectable +{ + public let id: UUID + public let selectionID: String + fileprivate let inputBytes: Int + fileprivate let transport: MCPTransportDeclaration + fileprivate let directory: MCPConnectionResource? + fileprivate let executable: MCPConnectionResource? + public var description: String { "" } + public var debugDescription: String { description } + public var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } +} + +public struct MCPConnectionDescription: Codable, Sendable, Equatable { + public enum Transport: String, Codable, Sendable { case stdio, streamableHTTP, sse } + public let snapshotID: UUID + public let transport: Transport + public let startsOwnedProcess: Bool + public let requiredBindings: [String] + public let environmentBindings: [String] +} + +/// Protocol time excludes the separately bounded owned cleanup. The total timer +/// also includes synchronous binding and per-test resource materialization. +public struct MCPConnectionTestOptions: Sendable { + fileprivate var limits = MCPConnectionLimits() + public var clientName = "agents-tools" + public var clientVersion = "1" + public var totalTimeout: TimeInterval { + get { limits.totalTimeout } + set { limits.totalTimeout = newValue } + } + public var requestTimeout: TimeInterval { + get { limits.requestTimeout } + set { limits.requestTimeout = newValue } + } + public var maximumTools: Int { + get { limits.tools } + set { limits.tools = newValue } + } + public var maximumPages: Int { + get { limits.pages } + set { limits.pages = newValue } + } + public init() {} +} + +public struct MCPConnectionTestResult: Codable, Sendable, Equatable { + public enum Outcome: String, Codable, Sendable { + case discovered + /// Handshake succeeded; the server did not advertise tools discovery. + case noTools + case incomplete, failed + } + public enum Issue: String, Error, Codable, Sendable { + case invalidInput, bindingUnavailable, invalidBinding, resourceChanged + case connectionFailed, connectionClosed, protocolError, unsupportedVersion + case authenticationRequired, forbidden, authorityChanged, sessionExpired + case messageLimit, receiveLimit, sendLimit, stderrLimit, queueLimit + case pageLimit, toolLimit, textLimit, redirectLimit, resumeLimit, cursorCycle + case timeout, cancelled, cleanupFailed + } + public struct Tool: Codable, Sendable, Equatable { + public let name: String + public let title: String? + public let description: String? + } + public let snapshotID: UUID + public let startedAt: Date + public let finishedAt: Date + /// Monotonic elapsed time, including owned cleanup. + public let elapsed: TimeInterval + public let transport: MCPConnectionDescription.Transport + public let outcome: Outcome + public let issue: Issue? + public let negotiatedVersion: String? + public let tools: [Tool] + public let cleanupComplete: Bool +} + +public enum MCPConnectionOperations { + /// Call within the source borrowing scope after selecting an exact payload. + /// Resource handles already captured that scope's bytes; no lock survives here. + public static func snapshot( + selectionID: String, transport: MCPTransportDeclaration, + workingDirectory: MCPConnectionResource? = nil, executable: MCPConnectionResource? = nil + ) throws -> MCPConnectionSnapshot { + guard !selectionID.isEmpty, selectionID.utf8.count <= 4096, !selectionID.utf8.contains(0) else { + throw MCPConnectionPreparationError.invalidSelection + } + var remaining = MCPConnectionLimits().inputBytes + func charge(_ text: String) throws { + guard !text.utf8.contains(0), text.utf8.count < remaining else { + throw MCPConnectionPreparationError.invalidConfiguration + } + remaining -= text.utf8.count + 1 + } + func chargeBinding(_ binding: RuntimeBinding) throws { + switch binding { + case .environment(let name), .secret(let name): + guard !name.isEmpty else { throw MCPConnectionPreparationError.invalidConfiguration } + case .literal: break + } + try charge(binding.text) + } + switch transport { + case .stdio(let run): + guard workingDirectory?.directory == true, + !run.executable.isEmpty, run.executable.contains("/") == (executable != nil), + executable?.directory != true + else { throw MCPConnectionPreparationError.invalidConfiguration } + try charge(run.executable) + for argument in run.arguments { try charge(argument) } + for (key, binding) in run.environment { + guard !key.isEmpty, !key.contains("=") else { + throw MCPConnectionPreparationError.invalidConfiguration + } + try charge(key) + try chargeBinding(binding) + } + case .streamableHTTP(let url, let headers), .sse(let url, let headers): + guard workingDirectory == nil, executable == nil, + let parsed = URL(string: url), + ["http", "https"].contains(parsed.scheme?.lowercased() ?? ""), + parsed.host?.isEmpty == false, parsed.user == nil, parsed.password == nil, + parsed.fragment == nil + else { throw MCPConnectionPreparationError.invalidConfiguration } + try charge(url) + let token = Set( + "!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".utf8) + let reserved = Set([ + "host", "content-length", "transfer-encoding", "connection", "content-type", "accept", + "mcp-session-id", "mcp-protocol-version", "last-event-id", + ]) + var names = Set() + for (key, binding) in headers { + guard !key.isEmpty, key.utf8.allSatisfy({ token.contains($0) }), + !reserved.contains(key.lowercased()), names.insert(key.lowercased()).inserted + else { + throw MCPConnectionPreparationError.invalidConfiguration + } + try charge(key) + try chargeBinding(binding) + if case .literal(let value) = binding, + !value.utf8.allSatisfy({ $0 == 9 || ($0 >= 32 && $0 != 127) }) + { + throw MCPConnectionPreparationError.invalidConfiguration + } + } + } + let bytes = (workingDirectory?.byteCount ?? 0) + (executable?.byteCount ?? 0) + guard bytes <= LedgerLimits.standard.resourceBytes else { + throw MCPConnectionPreparationError.invalidResource + } + return MCPConnectionSnapshot( + id: UUID(), selectionID: selectionID, + inputBytes: MCPConnectionLimits().inputBytes - remaining, + transport: transport, + directory: workingDirectory, executable: executable) + } + + /// Pure metadata projection: no filesystem, provider, process or network access. + public static func describe(_ snapshot: MCPConnectionSnapshot) -> MCPConnectionDescription { + let bindings = snapshot.transport.bindings.values + return MCPConnectionDescription( + snapshotID: snapshot.id, transport: snapshot.transport.kind, + startsOwnedProcess: snapshot.transport.kind == .stdio, + requiredBindings: Set( + bindings.compactMap { if case .secret(let name) = $0 { name } else { nil } } + ).sorted(), + environmentBindings: Set( + bindings.compactMap { if case .environment(let name) = $0 { name } else { nil } } + ).sorted()) + } + + /// Tests only this selected value, never a refreshed source or matching name. + /// The sole shared provider must obey its bounded synchronous data contract. + public static func test( + _ snapshot: MCPConnectionSnapshot, options: MCPConnectionTestOptions = .init(), + environment: RuntimeEnvironment, bindings provider: any RuntimeBindingProvider + ) async -> MCPConnectionTestResult { + let started = Date() + let clock = ContinuousClock.now + var workspace: URL? + var tools: [MCPConnectionTestResult.Tool] = [] + var version: String? + var outcome = MCPConnectionTestResult.Outcome.failed + var issue: MCPConnectionTestResult.Issue? + var clean = true + do { + guard + [options.totalTimeout, options.requestTimeout].allSatisfy({ + $0.isFinite && $0 > 0 && $0 < Double(Int64.max) / 1_000_000_000 + }), options.maximumTools > 0, options.maximumPages > 0 + else { + throw MCPConnectionTestResult.Issue.invalidInput + } + guard !options.clientName.isEmpty, !options.clientVersion.isEmpty, + [options.clientName, options.clientVersion].allSatisfy({ + !$0.utf8.contains(0) && $0.utf8.count <= options.limits.textBytes + }) + else { throw MCPConnectionTestResult.Issue.invalidInput } + try Task.checkCancellation() + try snapshot.directory?.revalidate() + try snapshot.executable?.revalidate() + let description = describe(snapshot) + var remaining = options.limits.inputBytes - snapshot.inputBytes + for (key, value) in environment.environment { + guard !key.isEmpty, !key.contains("="), !key.utf8.contains(0), !value.utf8.contains(0), + key.utf8.count < remaining + else { throw MCPConnectionTestResult.Issue.invalidInput } + remaining -= key.utf8.count + 1 + guard value.utf8.count < remaining else { throw MCPConnectionTestResult.Issue.invalidInput } + remaining -= value.utf8.count + 1 + } + for name in description.environmentBindings { + guard environment.environment[name] != nil else { + throw MCPConnectionTestResult.Issue.bindingUnavailable + } + } + var secrets: [String: String] = [:] + for name in description.requiredBindings { + try Task.checkCancellation() + let data: Data + do { + data = try provider.value(for: name, environment: environment) + } catch is CancellationError { + throw CancellationError() + } catch { throw MCPConnectionTestResult.Issue.bindingUnavailable } + guard data.count < remaining, let value = String(data: data, encoding: .utf8), + !value.utf8.contains(0) + else { throw MCPConnectionTestResult.Issue.invalidBinding } + remaining -= data.count + 1 + secrets[name] = value + } + var privateValues = + Array(environment.environment.values) + Array(secrets.values) + + [options.clientName, options.clientVersion] + func resolve(_ binding: RuntimeBinding, header: Bool) throws -> String { + let value: String + switch binding { + case .literal(let text): value = text + case .environment(let name): + guard let text = environment.environment[name] else { + throw MCPConnectionTestResult.Issue.bindingUnavailable + } + value = text + case .secret(let name): value = secrets[name]! + } + guard !value.utf8.contains(0), + !header || value.utf8.allSatisfy({ $0 == 9 || ($0 >= 32 && $0 != 127) }) + else { + throw MCPConnectionTestResult.Issue.invalidBinding + } + privateValues.append(value) + if header { + privateValues += value.split(whereSeparator: { $0.isWhitespace }).map(String.init) + } + return value + } + let input: MCPConnectionInput + switch snapshot.transport { + case .stdio(let run): + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + "agents-mcp-test-" + UUID().uuidString) + try FileManager.default.createDirectory( + at: directory, withIntermediateDirectories: false, + attributes: [.posixPermissions: 0o700]) + workspace = directory + let cwd = try snapshot.directory!.materialize(in: directory, name: "cwd") + let executable = + try snapshot.executable?.materialize(in: directory, name: "executable") + .path ?? run.executable + var values = environment.environment + for key in run.environment.keys.sorted() { + values[key] = try resolve(run.environment[key]!, header: false) + } + try snapshot.directory?.revalidate() + try snapshot.executable?.revalidate() + privateValues += + run.arguments + [run.executable, executable, directory.path, cwd.path] + + (snapshot.directory?.sensitivePaths ?? []) + (snapshot.executable?.sensitivePaths ?? []) + input = .stdio( + .init( + executable: executable, arguments: run.arguments, directory: cwd, environment: values)) + case .streamableHTTP(let endpoint, let headers), .sse(let endpoint, let headers): + var values: [String: String] = [:] + for key in headers.keys.sorted() { values[key] = try resolve(headers[key]!, header: true) } + privateValues.append(endpoint) + if let url = URL(string: endpoint) { + privateValues += + URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.compactMap(\.value) + ?? [] + } + if snapshot.transport.kind == .sse { + input = .legacySSE(URL(string: endpoint)!, headers: values) + } else { + input = .streamableHTTP(URL(string: endpoint)!, headers: values) + } + } + try Task.checkCancellation() + let elapsed = clock.duration(to: .now) + let spent = Double(elapsed.components.seconds) + Double(elapsed.components.attoseconds) / 1e18 + guard spent < options.totalTimeout else { throw MCPConnectionTestResult.Issue.timeout } + var limits = options.limits + limits.totalTimeout -= spent + let result = await MCPConnectionRunner.run( + input, client: .init(name: options.clientName, version: options.clientVersion), + limits: limits) + clean = result.cleanupComplete + version = result.negotiatedVersion + switch result.status { + case .discovered: outcome = .discovered + case .noTools: outcome = .noTools + case .incomplete(let error): + outcome = .incomplete + issue = .init(rawValue: error.rawValue) + case .failed(let error): + outcome = .failed + issue = .init(rawValue: error.rawValue) + } + let redactions = Set(privateValues.filter { !$0.isEmpty }).sorted { $0.count > $1.count } + let expression = try NSRegularExpression( + pattern: redactions.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|")) + func redact(_ value: String) -> String { + let text = + redactions.isEmpty + ? value + : expression.stringByReplacingMatches( + in: value, range: NSRange(value.startIndex..., in: value), withTemplate: "[redacted]") + let filtered = String( + text.unicodeScalars.filter { !CharacterSet.controlCharacters.contains($0) }) + var bytes = Data(filtered.utf8.prefix(options.limits.textBytes)) + // A byte cap may split the last Unicode scalar; remove only that suffix. + while String(data: bytes, encoding: .utf8) == nil { bytes.removeLast() } + return String(decoding: bytes, as: UTF8.self) + } + tools = result.tools.map { + .init( + name: redact($0.name), title: $0.title.map(redact), + description: $0.description.map(redact)) + } + } catch is CancellationError { + issue = .cancelled + } catch is MCPConnectionPreparationError { + issue = .resourceChanged + } catch let error as MCPConnectionTestResult.Issue { + issue = error + } catch { + issue = .invalidInput + } + if let workspace { + do { try FileManager.default.removeItem(at: workspace) } catch { clean = false } + } + if !clean { + outcome = .failed + issue = .cleanupFailed + } + let elapsed = clock.duration(to: .now) + return MCPConnectionTestResult( + snapshotID: snapshot.id, startedAt: started, finishedAt: Date(), + elapsed: Double(elapsed.components.seconds) + Double(elapsed.components.attoseconds) / 1e18, + transport: snapshot.transport.kind, outcome: outcome, + issue: issue, + negotiatedVersion: version, tools: tools, cleanupComplete: clean) + } +} + +extension RuntimeBinding { + fileprivate var text: String { + switch self { + case .literal(let text), .environment(let text), .secret(let text): text + } + } +} + +extension MCPTransportDeclaration { + fileprivate var bindings: [String: RuntimeBinding] { + switch self { + case .stdio(let run): run.environment + case .streamableHTTP(_, let headers), .sse(_, let headers): headers + } + } + fileprivate var kind: MCPConnectionDescription.Transport { + switch self { + case .stdio: .stdio + case .streamableHTTP: .streamableHTTP + case .sse: .sse + } + } +} diff --git a/Sources/AgentsUpdates/MCPConnectionResources.swift b/Sources/AgentsUpdates/MCPConnectionResources.swift new file mode 100644 index 0000000..97304b6 --- /dev/null +++ b/Sources/AgentsUpdates/MCPConnectionResources.swift @@ -0,0 +1,134 @@ +import AgentsCore +import Foundation + +/// A fixed source resource or explicitly live local path. Capture borrowed source +/// resources before their read scope ends; no borrowed URL is retained. +public struct MCPConnectionResource: Sendable, CustomStringConvertible, + CustomDebugStringConvertible, CustomReflectable +{ + private enum Storage: Sendable { + case live(URL, Identity) + case captured(LedgerResource, [String: Data], [String: Bool]) + } + private struct Identity: Equatable, Sendable { + let device: UInt64 + let inode: UInt64 + let targetDevice: UInt64 + let targetInode: UInt64 + let realPath: String + } + private let storage: Storage + let directory: Bool + let byteCount: Int + var sensitivePaths: [String] { + if case .live(let url, let identity) = storage { return [url.path, identity.realPath] } + return [] + } + public var description: String { "" } + public var debugDescription: String { description } + public var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } + + /// Live directories preserve live content semantics; their physical identity is + /// checked again immediately before starting the connection. + public static func live(_ url: URL) throws -> Self { + do { + guard url.isFileURL else { throw MCPConnectionPreparationError.invalidResource } + let url = url.standardizedFileURL + let identity = try identity(url) + let attributes = try FileManager.default.attributesOfItem(atPath: identity.realPath) + let directory = attributes[.type] as? FileAttributeType == .typeDirectory + guard directory || attributes[.type] as? FileAttributeType == .typeRegular else { + throw MCPConnectionPreparationError.invalidResource + } + return Self(storage: .live(url, identity), directory: directory, byteCount: 0) + } catch { throw MCPConnectionPreparationError.invalidResource } + } + + /// Reads only the selected resource and its contained symlink support. The + /// expected hash comes from the caller's exact linked/frozen selection. + public static func capture( + sourceRoot: URL, path: String, expectedHash: String, + expectedExecutableFiles: [String: Bool] + ) throws -> Self { + do { + let view = try SourceSnapshot( + snapshot: .init(source: "selected", revision: expectedHash), pin: nil, root: sourceRoot) + let url = try view.resource(path) + try view.validateResourceTree(url) + let captured = try LedgerResources.capture( + url, embed: true, limits: .standard, sourceRoot: sourceRoot) + guard captured.hash == expectedHash, captured.flags == expectedExecutableFiles else { + throw MCPConnectionPreparationError.resourceChanged + } + let resource = LedgerResource( + kind: .embedded, source: "selected", path: try view.relativePath(url), + hash: captured.hash, entries: captured.entries, support: captured.support) + let type = + try FileManager.default.attributesOfItem( + atPath: url.resolvingSymlinksInPath().path)[.type] as? FileAttributeType + let directory = type == .typeDirectory + guard directory || type == .typeRegular else { + throw MCPConnectionPreparationError.invalidResource + } + let count = (captured.entries + captured.support).reduce(0) { $0 + ($1.byteCount ?? 0) } + return Self( + storage: .captured(resource, captured.objects, expectedExecutableFiles), + directory: directory, byteCount: count) + } catch is CancellationError { + throw CancellationError() + } catch let error as MCPConnectionPreparationError { + throw error + } catch { throw MCPConnectionPreparationError.invalidResource } + } + + func materialize(in workspace: URL, name: String) throws -> URL { + switch storage { + case .live(let url, _): + try revalidate() + return url + case .captured(let resource, let objects, let expectedFlags): + let destination = workspace.appendingPathComponent(name) + try LedgerResources.materialize(resource, objects: objects, at: destination) + let file = + resource.support.isEmpty + ? destination : try PathSafety.resolvedChild(base: destination, subpath: resource.path) + let hash = try directory ? FileHash.folderHash(file) : FileHash.sha256Hex(file: file) + let flags: [String: Bool] + if directory { + flags = try FileHash.executableFlags(file) + } else { + let mode = try FileManager.default.attributesOfItem(atPath: file.path)[.posixPermissions] + flags = [".": ((mode as? NSNumber)?.intValue ?? 0) & 0o111 != 0] + } + guard "sha256:" + hash == resource.hash, flags == expectedFlags else { + throw MCPConnectionPreparationError.resourceChanged + } + return file + } + } + + func revalidate() throws { + if case .live(let url, let expected) = storage { + do { + guard try Self.identity(url) == expected else { + throw MCPConnectionPreparationError.resourceChanged + } + } catch { throw MCPConnectionPreparationError.resourceChanged } + } + } + + private static func identity(_ url: URL) throws -> Identity { + let attributes = try FileManager.default.attributesOfItem(atPath: url.path) + let real = url.resolvingSymlinksInPath().standardizedFileURL + let target = try FileManager.default.attributesOfItem(atPath: real.path) + guard let device = attributes[.systemNumber] as? NSNumber, + let inode = attributes[.systemFileNumber] as? NSNumber, + let targetDevice = target[.systemNumber] as? NSNumber, + let targetInode = target[.systemFileNumber] as? NSNumber + else { throw MCPConnectionPreparationError.resourceChanged } + return Identity( + device: device.uint64Value, inode: inode.uint64Value, + targetDevice: targetDevice.uint64Value, targetInode: targetInode.uint64Value, + realPath: real.path) + } +} diff --git a/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift b/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift new file mode 100644 index 0000000..0808dc0 --- /dev/null +++ b/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift @@ -0,0 +1,288 @@ +import AgentsCore +import AgentsUpdates +import Foundation +import Testing + +private final class MCPFacadeBundle: NSObject {} + +/// Only the call list mutates, under lock; values are immutable fixture input. +private final class MCPBindingSpy: RuntimeBindingProvider, @unchecked Sendable { + private let lock = NSLock() + private var names: [String] = [] + let values: [String: Data] + let delay: TimeInterval + init(_ values: [String: Data] = [:], delay: TimeInterval = 0) { + self.values = values + self.delay = delay + } + var calls: [String] { lock.withLock { names } } + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + lock.withLock { names.append(binding) } + if delay > 0 { Thread.sleep(forTimeInterval: delay) } + guard let value = values[binding] else { throw MCPConnectionPreparationError.invalidSelection } + return value + } +} + +private struct MCPRemovingDirectoryProvider: RuntimeBindingProvider { + let directory: URL + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + try FileManager.default.removeItem(at: directory) + return Data("unused-after-path-removal".utf8) + } +} + +private final class MCPFacadeFixture { + let root: URL + let observation: URL + let environment: RuntimeEnvironment + static var executable: URL { + var directory = Bundle(for: MCPFacadeBundle.self).bundleURL + for _ in 0..<8 { + let candidate = directory.appendingPathComponent("MCPTestProcess") + if FileManager.default.isExecutableFile(atPath: candidate.path) { return candidate } + directory.deleteLastPathComponent() + } + return directory.appendingPathComponent("MCPTestProcess") + } + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "mcp-facade-" + UUID().uuidString) + observation = root.appendingPathComponent("observed") + environment = RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: [ + "PATH": Self.executable.deletingLastPathComponent().path + ":/usr/bin:/bin", + "SELECTED_ENV": "environment-canary", + ]) + try FileManager.default.createDirectory(at: observation, withIntermediateDirectories: true) + try FileManager.default.createDirectory( + at: root.appendingPathComponent(".agent"), withIntermediateDirectories: true) + try Data("untouched declaration".utf8).write( + to: root.appendingPathComponent(".agent/agents.yaml")) + try Data("untouched ledger".utf8).write( + to: root.appendingPathComponent(".agent/agents.resolved")) + } + func snapshot( + _ mode: String = "normal", selection: String = "source-a/same-name", + values: [String: RuntimeBinding] = [:] + ) throws -> MCPConnectionSnapshot { + try MCPConnectionOperations.snapshot( + selectionID: selection, + transport: .stdio( + .init( + executable: "MCPTestProcess", arguments: [mode, observation.path], environment: values)), + workingDirectory: .live(root)) + } + func text(_ path: String) -> String? { + try? String(contentsOf: observation.appendingPathComponent(path), encoding: .utf8) + } + func waitFor(_ predicate: () -> Bool) async -> Bool { + let deadline = ContinuousClock.now + .seconds(3) + while !predicate() { + if ContinuousClock.now >= deadline { return false } + try? await Task.sleep(for: .milliseconds(2)) + } + return true + } + func unchanged() throws { + #expect( + try String(contentsOf: root.appendingPathComponent(".agent/agents.yaml"), encoding: .utf8) + == "untouched declaration") + #expect( + try String(contentsOf: root.appendingPathComponent(".agent/agents.resolved"), encoding: .utf8) + == "untouched ledger") + } + deinit { try? FileManager.default.removeItem(at: root) } +} + +@Suite(.serialized) struct MCPConnectionOperationsTests { + @Test func describeIsPureAndExactSelectionUsesOnlyNecessaryBindings() async throws { + let fixture = try MCPFacadeFixture() + let spy = MCPBindingSpy(["wanted": Data("provider-canary".utf8)]) + let selected = try fixture.snapshot( + "facade", + values: [ + "FACADE_SECRET": .secret("wanted"), "SECOND_SECRET": .secret("wanted"), + "FACADE_LITERAL": .literal("literal-canary"), "FACADE_ENV": .environment("SELECTED_ENV"), + ]) + let other = try fixture.snapshot( + "wrong-version", selection: "source-b/same-name", values: ["UNUSED": .secret("unused")]) + let before = try FileManager.default.contentsOfDirectory(atPath: fixture.root.path).sorted() + let description = MCPConnectionOperations.describe(selected) + #expect(description.snapshotID == selected.id && selected.id != other.id) + #expect(description.startsOwnedProcess) + #expect(description.requiredBindings == ["wanted"]) + #expect(description.environmentBindings == ["SELECTED_ENV"]) + #expect(spy.calls.isEmpty && fixture.text("pid") == nil) + #expect( + try FileManager.default.contentsOfDirectory(atPath: fixture.root.path).sorted() == before) + #expect(Mirror(reflecting: selected).children.isEmpty) + #expect(!String(reflecting: selected).contains("literal-canary")) + let result = await MCPConnectionOperations.test( + selected, environment: fixture.environment, bindings: spy) + #expect(result.snapshotID == selected.id) + #expect(result.outcome == .discovered && result.issue == nil) + #expect(result.cleanupComplete && result.startedAt <= result.finishedAt) + #expect(result.elapsed >= 0 && result.transport == .stdio) + #expect(result.tools.map(\.name) == ["first", "second"]) + #expect(spy.calls == ["wanted"]) + let encoded = String(decoding: try JSONEncoder().encode(result), as: UTF8.self) + for secret in ["provider-canary", "literal-canary", "environment-canary", fixture.root.path] { + #expect(!encoded.contains(secret)) + } + #expect(result.tools.allSatisfy { $0.description?.contains("[redacted]") == true }) + let pid = try #require(Int32(fixture.text("pid") ?? "")) + #expect(kill(pid, 0) == -1 && errno == ESRCH) + try fixture.unchanged() + } + + @Test func invalidOptionsAndUnavailableEnvironmentDoNotConsultProvider() async throws { + let fixture = try MCPFacadeFixture() + let spy = MCPBindingSpy() + let snapshot = try fixture.snapshot(values: ["TOKEN": .secret("unused")]) + var options = MCPConnectionTestOptions() + options.totalTimeout = .infinity + let invalid = await MCPConnectionOperations.test( + snapshot, options: options, environment: fixture.environment, bindings: spy) + #expect(invalid.issue == .invalidInput && invalid.cleanupComplete) + let missing = try fixture.snapshot(values: [ + "TOKEN": .secret("unused"), "MISSING": .environment("MISSING"), + ]) + let unavailable = await MCPConnectionOperations.test( + missing, environment: fixture.environment, bindings: spy) + #expect(unavailable.issue == .bindingUnavailable && unavailable.cleanupComplete) + #expect(spy.calls.isEmpty && fixture.text("pid") == nil) + let cancelled = Task { [environment = fixture.environment] in + withUnsafeCurrentTask { $0?.cancel() } + return await MCPConnectionOperations.test( + snapshot, environment: environment, bindings: spy) + } + #expect(await cancelled.value.issue == .cancelled) + #expect(spy.calls.isEmpty) + // This bounded synchronous provider deliberately consumes the total budget. + let slow = MCPBindingSpy(["unused": Data("deadline-canary".utf8)], delay: 0.03) + options.totalTimeout = 0.001 + let expired = await MCPConnectionOperations.test( + snapshot, options: options, environment: fixture.environment, bindings: slow) + #expect(expired.issue == .timeout && expired.cleanupComplete) + #expect(slow.calls == ["unused"] && fixture.text("pid") == nil) + try fixture.unchanged() + } + + @Test func invalidHeaderBindingsFailBeforeNetworkWithoutLeakingValues() async throws { + let fixture = try MCPFacadeFixture() + let snapshot = try MCPConnectionOperations.snapshot( + selectionID: "fixed-remote", + transport: .streamableHTTP( + url: "http://127.0.0.1:1/mcp", headers: ["Authorization": .secret("token")])) + let spy = MCPBindingSpy(["token": Data("credential-canary\r\nInjected: value".utf8)]) + let result = await MCPConnectionOperations.test( + snapshot, environment: fixture.environment, bindings: spy) + #expect(result.issue == .invalidBinding && result.cleanupComplete) + #expect(spy.calls == ["token"]) + #expect( + !String(decoding: try JSONEncoder().encode(result), as: UTF8.self).contains( + "credential-canary")) + #expect(throws: MCPConnectionPreparationError.invalidConfiguration) { + try MCPConnectionOperations.snapshot( + selectionID: "invalid", + transport: .sse(url: "http://127.0.0.1/mcp", headers: ["bad\nkey": .secret("unused")])) + } + for headers: [String: RuntimeBinding] in [ + ["MCP-Session-ID": .secret("unused")], + ["Authorization": .secret("one"), "authorization": .secret("two")], + ["Authorization": .secret("")], + ] { + #expect(throws: MCPConnectionPreparationError.invalidConfiguration) { + try MCPConnectionOperations.snapshot( + selectionID: "invalid", transport: .sse(url: "http://127.0.0.1/mcp", headers: headers)) + } + } + try fixture.unchanged() + } + + @Test func capturedBorrowedResourcesSurviveCancellationUntilOwnedCleanup() async throws { + let fixture = try MCPFacadeFixture() + let borrowed = fixture.root.appendingPathComponent("borrowed") + try FileManager.default.createDirectory(at: borrowed, withIntermediateDirectories: false) + let tool = borrowed.appendingPathComponent("tool") + try FileManager.default.copyItem(at: MCPFacadeFixture.executable, to: tool) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: tool.path) + let content = borrowed.appendingPathComponent("content") + try FileManager.default.createDirectory(at: content, withIntermediateDirectories: false) + try Data("required-support".utf8).write(to: content.appendingPathComponent("support")) + let directoryLink = borrowed.appendingPathComponent("cwd") + try FileManager.default.createSymbolicLink( + atPath: directoryLink.path, withDestinationPath: "content") + let executable = try MCPConnectionResource.capture( + sourceRoot: borrowed, path: "tool", + expectedHash: "sha256:" + FileHash.sha256Hex(file: tool), expectedExecutableFiles: [".": true] + ) + let cwd = try MCPConnectionResource.capture( + sourceRoot: borrowed, path: "cwd", + expectedHash: "sha256:" + FileHash.folderHash(directoryLink), + expectedExecutableFiles: FileHash.executableFlags(directoryLink)) + let snapshot = try MCPConnectionOperations.snapshot( + selectionID: "fixed-source/entry", + transport: .stdio( + .init(executable: "./tool", arguments: ["stubborn", fixture.observation.path])), + workingDirectory: cwd, executable: executable) + try FileManager.default.removeItem(at: borrowed) + let spy = MCPBindingSpy() + let task = Task { [environment = fixture.environment] in + await MCPConnectionOperations.test(snapshot, environment: environment, bindings: spy) + } + let ready = await fixture.waitFor { fixture.text("stubborn-ready") != nil } + #expect(ready) + let records = (fixture.text("wire.jsonl") ?? "").split(separator: "\n").compactMap { + (try? JSONSerialization.jsonObject(with: Data($0.utf8))) as? [String: Any] + } + let staged = records.first?["cwd"] as? String + if let staged { + #expect(FileManager.default.fileExists(atPath: staged + "/support")) + #expect(!staged.hasPrefix(borrowed.path)) + } else { + Issue.record("Missing owned resource working directory") + } + task.cancel() + let result = await task.value + #expect(result.issue == .cancelled && result.cleanupComplete) + #expect(result.outcome == .incomplete) + if let staged { #expect(!FileManager.default.fileExists(atPath: staged)) } + let pid = try #require(Int32(fixture.text("pid") ?? "")) + #expect(kill(pid, 0) == -1 && errno == ESRCH) + #expect(spy.calls.isEmpty) + try fixture.unchanged() + } + + @Test func replacedLiveDirectoryRequiresNewSnapshotBeforeBinding() async throws { + let fixture = try MCPFacadeFixture() + let live = fixture.root.appendingPathComponent("live") + try FileManager.default.createDirectory(at: live, withIntermediateDirectories: false) + let snapshot = try MCPConnectionOperations.snapshot( + selectionID: "live-entry", + transport: .stdio( + .init( + executable: "MCPTestProcess", arguments: ["normal", fixture.observation.path], + environment: ["TOKEN": .secret("unused")])), workingDirectory: .live(live)) + try FileManager.default.moveItem(at: live, to: fixture.root.appendingPathComponent("old-live")) + try FileManager.default.createDirectory(at: live, withIntermediateDirectories: false) + let spy = MCPBindingSpy() + let result = await MCPConnectionOperations.test( + snapshot, environment: fixture.environment, bindings: spy) + #expect(result.issue == .resourceChanged && result.cleanupComplete) + #expect(spy.calls.isEmpty && fixture.text("pid") == nil) + let selected = try MCPConnectionOperations.snapshot( + selectionID: "live-entry", + transport: .stdio( + .init(executable: "MCPTestProcess", environment: ["TOKEN": .secret("remove-directory")])), + workingDirectory: .live(live)) + let removedDuringBinding = await MCPConnectionOperations.test( + selected, environment: fixture.environment, + bindings: MCPRemovingDirectoryProvider(directory: live)) + #expect(removedDuringBinding.issue == .resourceChanged && removedDuringBinding.cleanupComplete) + #expect(!FileManager.default.fileExists(atPath: live.path) && fixture.text("pid") == nil) + try fixture.unchanged() + } +} diff --git a/Tests/MCPTestProcess/main.swift b/Tests/MCPTestProcess/main.swift index 3b117b0..9196d65 100644 --- a/Tests/MCPTestProcess/main.swift +++ b/Tests/MCPTestProcess/main.swift @@ -189,7 +189,12 @@ while true { let cursor = (message["params"] as? [String: Any])?["cursor"] as? String let tool: [String: Any] = [ "name": cursor == nil ? "first" : "second", - "description": scenario == "long-text" ? String(repeating: "x", count: 17) : "fixture", + "description": scenario == "long-text" + ? String(repeating: "x", count: 17) + : scenario == "facade" + ? ["FACADE_SECRET", "FACADE_LITERAL", "FACADE_ENV"].map { + ProcessInfo.processInfo.environment[$0] ?? "absent" + }.joined(separator: " ") : "fixture", "inputSchema": ["type": "object"], ] var result: [String: Any] = ["tools": [tool]] From 20aa77d402b8f4d4734b50da76443d9bc4cba01b Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:58:53 +0800 Subject: [PATCH 086/171] fix: retain artifact pins within their source index --- Sources/Components/ComponentLinker.swift | 44 +++++++++++ Sources/Components/Expansion.swift | 9 ++- .../ArtifactLinkingTests.swift | 77 +++++++++++++++++++ 3 files changed, 128 insertions(+), 2 deletions(-) diff --git a/Sources/Components/ComponentLinker.swift b/Sources/Components/ComponentLinker.swift index a66c126..01e9042 100644 --- a/Sources/Components/ComponentLinker.swift +++ b/Sources/Components/ComponentLinker.swift @@ -81,6 +81,50 @@ final class Linking { self.retainedLedger = retainedLedger } + /// An implicit selection admits only members owned by its recorded index. The component key + /// identifies the declaring context; resource lookup still verifies the applicable exact pin. + func artifactBelongsToIndex(key: ComponentKey, source: String) throws -> Bool { + guard let pin = directPins[key], pin.revision.hasPrefix("sha256:") else { return false } + guard let ledger = retainedLedger else { + throw CoreError.invalidState("missing pinned artifact closure") + } + var recorded = false + for component in ledger.components.sorted(by: { $0.key < $1.key }).map(\.value) { + try budget.step() + guard component.kind == key.kind.rawValue, component.root == key.root, + component.group == key.group, PathSafety.sanitizeName(component.name) == key.name, + try retainedSourceIdentity(component.declaringSource, ledger: ledger) == key.source + else { continue } + recorded = true + if try retainedSourceIdentity(component.source, ledger: ledger) == source { return true } + } + guard recorded else { throw CoreError.invalidState("missing pinned artifact component") } + return false + } + + private func retainedSourceIdentity(_ id: String, ledger: ResolvedLedger) throws -> String { + try budget.step() + guard let source = ledger.sources[id] else { + throw CoreError.invalidState("missing retained source") + } + if let container = source.container { + return try retainedSourceIdentity(container, ledger: ledger) + (source.namespace ?? "") + } + let location: String + if let authored = source.location { + location = try authored.resolve(roots: [ + "project": store.environment.projectDirectory, "home": store.environment.homeDirectory, + "state": store.directory, + ]).path + } else if let transport = source.transport { + location = transport + } else { + throw CoreError.invalidState("missing retained source coordinates") + } + return try SourceDeclaration(kind: source.kind, location: location).identity( + environment: store.environment) + } + /// Direct artifact pins use the artifact digest, independently of every other index member. /// The caller supplies the admitted ledger closure; absence never means refresh the index. func retainedArtifact(key: ComponentKey, source: String) throws -> LedgerResource? { diff --git a/Sources/Components/Expansion.swift b/Sources/Components/Expansion.swift index ef573a4..9eead3d 100644 --- a/Sources/Components/Expansion.swift +++ b/Sources/Components/Expansion.swift @@ -411,9 +411,14 @@ final class Expansion { try linking.budget.step() guard candidate.kind == .skills, candidate.source == context.view.snapshot.source, candidate.root == context.view.discoveryPath, candidate.group == group, - !excluded.contains(candidate.name), requested?.contains(candidate.name) ?? true, - let resource = try linking.retainedArtifact(key: candidate, source: address.id) + !excluded.contains(candidate.name), requested?.contains(candidate.name) ?? true else { continue } + if requested == nil, try !linking.artifactBelongsToIndex(key: candidate, source: address.id) { + continue + } + guard let resource = try linking.retainedArtifact(key: candidate, source: address.id) else { + continue + } retained[candidate.name] = resource } let freshNames = requested.map { $0.filter { retained[$0] == nil && !excluded.contains($0) } } diff --git a/Tests/ComponentsTests/ArtifactLinkingTests.swift b/Tests/ComponentsTests/ArtifactLinkingTests.swift index 0155be5..2fc313e 100644 --- a/Tests/ComponentsTests/ArtifactLinkingTests.swift +++ b/Tests/ComponentsTests/ArtifactLinkingTests.swift @@ -159,6 +159,80 @@ struct ArtifactLinkingTests { } } + @Test(arguments: [InstallScope.project, .user]) + func retainedAllMembersBelongToTheirRecordedIndexes(_ scope: InstallScope) throws { + let fixture = try LinkFixture() + let store = StateStore(scope: scope, environment: fixture.environment) + let packageRoot = scope == .project ? fixture.project : store.directory + let webA = fixture.root.appendingPathComponent("web-a") + let webB = fixture.root.appendingPathComponent("web-b") + for web in [webA, webB] { + try FileManager.default.createDirectory(at: web, withIntermediateDirectories: true) + } + let serverA = try IndexHTTPServer(root: webA) + defer { serverA.stop() } + let serverB = try IndexHTTPServer(root: webB) + defer { serverB.stop() } + let alphaDigest = try archive("alpha", body: "alpha original", fixture: fixture, web: webA) + let betaDigest = try archive("beta", body: "beta original", fixture: fixture, web: webB) + try index([("alpha", alphaDigest)], fixture: fixture, web: webA) + try index([("beta", betaDigest)], fixture: fixture, web: webB) + let document = try fixture.document( + """ + version: 1 + sources: {a: {index: '\(serverA.url)'}, b: {index: '\(serverB.url)'}} + components: [{kind: skills, source: a}, {kind: skills, source: b}] + """) + func freeze(pins: [ComponentKey: SourceRevision] = [:], previous: ResolvedLedger? = nil) throws + -> ResolvedLedger + { + try ComponentLinker.withLinkedComponents( + document: document, store: store, platform: .macOS, + directPins: pins, retaining: previous + ) { graph, session in + try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: [ + "local:" + packageRoot.path: .init( + kind: .registered, root: scope == .project ? "project" : "state", path: ".") + ]), limits: .standard) + } + } + let previous = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(freeze(), limits: .standard), limits: .standard) + func key(_ name: String) -> ComponentKey { + .init( + source: "local:" + packageRoot.path, root: ".", group: nil, kind: .skills, name: name) + } + let pins: [ComponentKey: SourceRevision] = [ + key("alpha"): .init(revision: alphaDigest), key("beta"): .init(revision: betaDigest), + ] + // Membership comes from each pin's recorded index, even after its download disappears. + try FileManager.default.removeItem(at: webA.appendingPathComponent("alpha.zip")) + try FileManager.default.removeItem(at: webB.appendingPathComponent("beta.zip")) + try index([], fixture: fixture, web: webA) + try index([], fixture: fixture, web: webB) + let retained = try freeze(pins: pins, previous: previous) + #expect(retained.components == previous.components) + #expect(retained.resources == previous.resources) + #expect(retained.contentObjects == previous.contentObjects) + let freshAlpha = try archive("alpha", body: "alpha fresh", fixture: fixture, web: webA) + try index([("alpha", freshAlpha)], fixture: fixture, web: webA) + let mixed = try freeze(pins: [key("beta"): .init(revision: betaDigest)], previous: previous) + let beta = try #require(previous.components.values.first { $0.name == "beta" }) + #expect(mixed.components.values.first { $0.name == "beta" } == beta) + for id in beta.resources { #expect(mixed.resources[id] == previous.resources[id]) } + let alpha = try #require(mixed.components.values.first { $0.name == "alpha" }) + #expect(mixed.sources[alpha.source]?.revision == freshAlpha) + var missingPin = pins + missingPin[key("alpha")] = .init(revision: "sha256:" + String(repeating: "0", count: 64)) + #expect(throws: LinkError.self) { try freeze(pins: missingPin, previous: previous) } + var corrupt = previous + let betaResource = try #require(beta.resources.first) + corrupt.resources[betaResource]?.hash = "sha256:" + String(repeating: "0", count: 64) + #expect(throws: LinkError.self) { try freeze(pins: pins, previous: corrupt) } + } + private func archive(_ name: String, body: String, fixture: LinkFixture, web: URL) throws -> String { @@ -204,6 +278,9 @@ private final class IndexHTTPServer { "-e", #""" use IO::Socket::INET; + use POSIX qw(SIG_SETMASK sigprocmask); + # The fixture's deadline and termination signals must be deliverable. + sigprocmask(SIG_SETMASK, POSIX::SigSet->new()) or die "sigprocmask: $!"; alarm 120; my $root = shift; my $server = IO::Socket::INET->new(LocalAddr => '127.0.0.1', LocalPort => 0, Listen => 8, Proto => 'tcp') or die $!; From e15c77dc9cd98c33d0300cd71935622e86002f7a Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:03:01 +0800 Subject: [PATCH 087/171] feat: coordinate registered native component targets --- Sources/AgentsCore/FileTransaction.swift | 19 + .../AgentsCore/NativeTargetCoordination.swift | 403 ++++++++++++++++-- .../AgentsCore/PrivateMaterialization.swift | 57 ++- Sources/AgentsCore/TransactionJournal.swift | 17 +- Sources/AgentsCore/TransactionPaths.swift | 30 +- .../RegisteredNativeTargetTests.swift | 272 +++++++++++- .../PrivateMaterializationProbe.swift | 8 +- 7 files changed, 744 insertions(+), 62 deletions(-) diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 2277526..9fcdc03 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -67,6 +67,19 @@ package final class FileTransaction { url, parent: destination.deletingLastPathComponent(), store: store) case .data, .prepared: break } + if let route = NativeTargetRoute.targetRoute(path) { + let requiredKind: mode_t = route.isContainer ? S_IFDIR : S_IFREG + if route.isContainer, case .data = source { + throw CoreError.unsafePath("registered native container requires a directory") + } + guard expectation.kind == nil || expectation.kind == requiredKind else { + throw CoreError.unsafePath("registered native target has the wrong object kind") + } + if case .link = source { + throw CoreError.unsafePath("registered native targets cannot be symbolic links") + } + expectation.kind = requiredKind + } if security.preimage == .privateMaterialization { guard case .data(let data) = source else { throw CoreError.invalidState("sensitive replacement requires private byte construction") @@ -197,6 +210,12 @@ package final class FileTransaction { throw CoreError.invalidState("duplicate transaction destination") } let evidence = try expecting ?? TargetPrecondition(destination) + if let route = NativeTargetRoute.targetRoute(path), let snapshot = evidence.snapshot { + let requiredKind: mode_t = route.isContainer ? S_IFDIR : S_IFREG + guard snapshot.identity.kind == requiredKind else { + throw CoreError.unsafePath("registered native preimage has the wrong object kind") + } + } guard evidence.url.path == destination.standardizedFileURL.path else { throw CoreError.invalidState("precondition belongs to another target") } diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index 3101b64..0ac6f4d 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -2,7 +2,7 @@ import CPlatform import Foundation /// Closed physical routes; regional ownership and rendering belong to the native adapter. -package enum NativeTargetRoute: String, Codable, Sendable, CaseIterable { +enum FixedNativeTargetRoute: String, Codable, Sendable, CaseIterable { case claudeMCPProject = "claude.mcp.project" case claudeMCPLocal = "claude.mcp.local" case claudeMCPUser = "claude.mcp.user" @@ -17,10 +17,20 @@ package enum NativeTargetRoute: String, Codable, Sendable, CaseIterable { case openCodeMCPUserJSON = "opencode.mcp.user.json" case openCodeMCPUserJSONC = "opencode.mcp.user.jsonc" + case claudeSettingsProject = "claude.settings.project" + case claudeSettingsUser = "claude.settings.user" + case codexHooksProject = "codex.hooks.project" + case codexHooksUser = "codex.hooks.user" + case cursorHooksProject = "cursor.hooks.project" + case cursorHooksUser = "cursor.hooks.user" + case geminiIgnoreProject = "gemini.ignore.project" + case cursorIgnoreProject = "cursor.ignore.project" + var shared: Bool { switch self { case .claudeMCPLocal, .claudeMCPUser, .codexMCPUser, .geminiMCPUser, .cursorMCPUser, - .openCodeMCPUserJSON, .openCodeMCPUserJSONC: + .openCodeMCPUserJSON, .openCodeMCPUserJSONC, .claudeSettingsUser, .codexHooksUser, + .cursorHooksUser: true default: false } @@ -42,6 +52,10 @@ package enum NativeTargetRoute: String, Codable, Sendable, CaseIterable { var metadata: String { root == Self.globalRoot ? Self.metadataRoot : root + "-metadata" } var basename: String { switch self { + case .claudeSettingsProject, .claudeSettingsUser: "settings.json" + case .codexHooksProject, .codexHooksUser, .cursorHooksProject, .cursorHooksUser: "hooks.json" + case .geminiIgnoreProject: ".geminiignore" + case .cursorIgnoreProject: ".cursorignore" case .claudeMCPProject: ".mcp.json" case .claudeMCPLocal, .claudeMCPUser: ".claude.json" case .codexMCPProject, .codexMCPUser: "config.toml" @@ -54,7 +68,8 @@ package enum NativeTargetRoute: String, Codable, Sendable, CaseIterable { static var sharedRoutes: [Self] { [ .claudeMCPLocal, .codexMCPUser, .geminiMCPUser, .cursorMCPUser, - .openCodeMCPUserJSON, .openCodeMCPUserJSONC, + .openCodeMCPUserJSON, .openCodeMCPUserJSONC, .claudeSettingsUser, .codexHooksUser, + .cursorHooksUser, ] } static func targetRoute(_ path: String) -> Self? { @@ -79,6 +94,17 @@ package enum NativeTargetRoute: String, Codable, Sendable, CaseIterable { return URL(fileURLWithPath: value).standardizedFileURL } switch self { + case .claudeSettingsProject: + return try Self.absoluteDirectory(environment.projectDirectory).appendingPathComponent( + ".claude") + case .claudeSettingsUser: + return try override("CLAUDE_CONFIG_DIR") ?? home().appendingPathComponent(".claude") + case .codexHooksProject: return try Self.codexMCPProject.logicalDirectory(environment) + case .codexHooksUser: return try Self.codexMCPUser.logicalDirectory(environment) + case .cursorHooksProject: return try Self.cursorMCPProject.logicalDirectory(environment) + case .cursorHooksUser: return try Self.cursorMCPUser.logicalDirectory(environment) + case .geminiIgnoreProject, .cursorIgnoreProject: + return try Self.absoluteDirectory(environment.projectDirectory) case .claudeMCPProject: return try Self.absoluteDirectory(environment.projectDirectory) case .claudeMCPLocal, .claudeMCPUser: @@ -114,7 +140,7 @@ package enum NativeTargetRoute: String, Codable, Sendable, CaseIterable { .appendingPathComponent("opencode") } } - private static func absoluteDirectory(_ url: URL) throws -> URL { + static func absoluteDirectory(_ url: URL) throws -> URL { guard url.isFileURL, url.path.hasPrefix("/"), !url.path.contains("\0") else { throw CoreError.unsafePath("registered native root must be an absolute filesystem directory") } @@ -128,6 +154,248 @@ package enum NativeTargetRoute: String, Codable, Sendable, CaseIterable { } } +/// A closed loader recipe. Named routes carry only validated native member names; +/// runtime directories remain owned by the recipe and explicit environment. +package struct NativeTargetRoute: RawRepresentable, Hashable, Codable, Sendable { + package enum Member: String, Codable, Sendable { + case claudeCommand, claudeAgent, claudeSkillPlugin + case codexAgent, geminiCommand, geminiAgent, geminiExtension + case cursorCommand, cursorAgent, cursorLocalPlugin + } + package let rawValue: String + private let fixed: FixedNativeTargetRoute? + private let member: Member? + private let memberScope: InstallScope? + private let name: String? + + private init(_ fixed: FixedNativeTargetRoute) { + self.fixed = fixed + member = nil + memberScope = nil + name = nil + rawValue = fixed.rawValue + } + package init?(rawValue: String) { + if let fixed = FixedNativeTargetRoute(rawValue: rawValue) { + self.init(fixed) + return + } + let parts = rawValue.split(separator: ":", maxSplits: 2, omittingEmptySubsequences: false) + guard parts.count == 3, let member = Member(rawValue: String(parts[0])), + let scope = InstallScope(rawValue: String(parts[1])), + let value = try? Self.named(member, scope: scope, name: String(parts[2])) + else { return nil } + self = value + } + /// `name` is the adapter's exact extension-free name, including command subdirectories. + package static func named(_ member: Member, scope: InstallScope, name: String) throws -> Self { + let parts = name.split(separator: "/", omittingEmptySubsequences: false) + guard (member.rawValue + ":" + scope.rawValue + ":" + name).utf8.count <= 4096, + !parts.isEmpty, + parts.allSatisfy({ + !$0.isEmpty && $0 != "." && $0 != ".." + && !$0.contains("\\") && !$0.contains("\0") && !$0.contains(":") + && !$0.hasPrefix(".agents-") + }), + member == .claudeCommand || member == .geminiCommand || parts.count == 1, + !(member == .cursorCommand && scope != .project), + !([Member.cursorLocalPlugin, .geminiExtension].contains(member) && scope != .user) + else { throw CoreError.unsafePath("unregistered native member or scope") } + return Self(member: member, scope: scope, name: name) + } + /// Accepts the adapter-owned relative file path, never an absolute destination. + package static func file(_ member: Member, scope: InstallScope, relativePath: String) throws + -> Self + { + let suffix: String + switch member { + case .claudeCommand, .claudeAgent, .cursorCommand, .cursorAgent, .geminiAgent: suffix = ".md" + case .codexAgent, .geminiCommand: suffix = ".toml" + default: throw CoreError.unsafePath("native container requires its registered bundle name") + } + guard relativePath.hasSuffix(suffix) else { + throw CoreError.unsafePath("native member has the wrong filename extension") + } + return try named(member, scope: scope, name: String(relativePath.dropLast(suffix.count))) + } + private init(member: Member, scope: InstallScope, name: String) { + fixed = nil + self.member = member + memberScope = scope + self.name = name + rawValue = member.rawValue + ":" + scope.rawValue + ":" + name + } + package init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + guard let route = Self(rawValue: try container.decode(String.self)) else { + throw CoreError.invalidState("unregistered native route") + } + self = route + } + package func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(rawValue) + } + package static let claudeMCPProject = Self(.claudeMCPProject) + package static let claudeMCPLocal = Self(.claudeMCPLocal) + package static let claudeMCPUser = Self(.claudeMCPUser) + package static let codexMCPProject = Self(.codexMCPProject) + package static let codexMCPUser = Self(.codexMCPUser) + package static let geminiMCPProject = Self(.geminiMCPProject) + package static let geminiMCPUser = Self(.geminiMCPUser) + package static let cursorMCPProject = Self(.cursorMCPProject) + package static let cursorMCPUser = Self(.cursorMCPUser) + package static let openCodeMCPProjectJSON = Self(.openCodeMCPProjectJSON) + package static let openCodeMCPProjectJSONC = Self(.openCodeMCPProjectJSONC) + package static let openCodeMCPUserJSON = Self(.openCodeMCPUserJSON) + package static let openCodeMCPUserJSONC = Self(.openCodeMCPUserJSONC) + package static let claudeSettingsProject = Self(.claudeSettingsProject) + package static let claudeSettingsUser = Self(.claudeSettingsUser) + package static let codexHooksProject = Self(.codexHooksProject) + package static let codexHooksUser = Self(.codexHooksUser) + package static let cursorHooksProject = Self(.cursorHooksProject) + package static let cursorHooksUser = Self(.cursorHooksUser) + package static let geminiIgnoreProject = Self(.geminiIgnoreProject) + package static let cursorIgnoreProject = Self(.cursorIgnoreProject) + package static var allCases: [Self] { FixedNativeTargetRoute.allCases.map(Self.init) } + static var mcpRoutes: [Self] { allCases.filter { $0.rawValue.contains(".mcp.") } } + static var sharedRoutes: [Self] { + FixedNativeTargetRoute.sharedRoutes.filter { $0.rawValue.contains(".mcp.") }.map(Self.init) + } + static let projectRoot = FixedNativeTargetRoute.projectRoot + static let globalRoot = FixedNativeTargetRoute.globalRoot + static let metadataRoot = FixedNativeTargetRoute.metadataRoot + package static func == (lhs: Self, rhs: Self) -> Bool { + lhs.rawValue.utf8.elementsEqual(rhs.rawValue.utf8) + } + package func hash(into hasher: inout Hasher) { + for byte in rawValue.utf8 { hasher.combine(byte) } + } + package var shared: Bool { fixed?.shared ?? (memberScope == .user) } + var isNamed: Bool { member != nil } + package var isContainer: Bool { + member.map { [.claudeSkillPlugin, .cursorLocalPlugin, .geminiExtension].contains($0) } ?? false + } + func permits(_ scope: InstallScope) -> Bool { + if let memberScope { return memberScope == scope } + if rawValue.contains(".mcp.") { return shared || scope == .project } + return shared ? scope == .user : scope == .project + } + /// Known readers are a lower bound; plugin/custom-root exclusivity needs reader evidence. + package var knownReaders: Set { + if fixed == .claudeSettingsProject || fixed == .claudeSettingsUser || member == .claudeAgent { + return [.claudeCode, .cursor] + } + let prefix = rawValue.lowercased() + if prefix.hasPrefix("claude") { return [.claudeCode] } + if prefix.hasPrefix("codex") { return [.codex] } + if prefix.hasPrefix("gemini") { return [.geminiCLI] } + if prefix.hasPrefix("cursor") { return [.cursor] } + return [.opencode] + } + var root: String { + fixed?.root ?? "native-member-" + rawValue.utf8.map { String(format: "%02x", $0) }.joined() + } + var metadata: String { fixed?.metadata ?? root + "-metadata" } + var basename: String { + if let fixed { return fixed.basename } + let suffix: String + switch member! { + case .claudeCommand, .claudeAgent, .cursorCommand, .cursorAgent, .geminiAgent: suffix = ".md" + case .codexAgent, .geminiCommand: suffix = ".toml" + default: suffix = "" + } + return String(name!.split(separator: "/").last!) + suffix + } + private static func routeRoot(_ key: String) -> Self? { + if let fixed = FixedNativeTargetRoute.allCases.first(where: { $0.root == key }) { + return Self(fixed) + } + guard key.hasPrefix("native-member-") else { return nil } + let hex = Array(key.dropFirst("native-member-".count).utf8) + guard hex.count.isMultiple(of: 2), hex.count <= 8192 else { return nil } + var bytes: [UInt8] = [] + for index in stride(from: 0, to: hex.count, by: 2) { + guard let byte = UInt8(String(decoding: hex[index...index + 1], as: UTF8.self), radix: 16) + else { return nil } + bytes.append(byte) + } + guard let raw = String(bytes: bytes, encoding: .utf8), let route = Self(rawValue: raw), + route.root == key + else { return nil } + return route + } + static func targetRoute(_ path: String) -> Self? { + routeRoot(String(path.split(separator: "/").first ?? "")) + } + static func sharedRoute(_ path: String) -> Self? { + targetRoute(path).flatMap { $0.shared ? $0 : nil } + } + static func metadataRoute(_ path: String) -> Self? { + let key = String(path.split(separator: "/").first ?? "") + if key == metadataRoot { return .claudeMCPLocal } + guard key.hasSuffix("-metadata"), + let route = routeRoot(String(key.dropLast("-metadata".count))), route.shared + else { return nil } + return route + } + func logicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + if let fixed { return try fixed.logicalDirectory(environment) } + let base: URL + switch member! { + case .claudeCommand, .claudeAgent, .claudeSkillPlugin: + base = try (memberScope == .project ? Self.claudeSettingsProject : .claudeSettingsUser) + .logicalDirectory(environment) + case .codexAgent: + base = try (memberScope == .project ? Self.codexMCPProject : .codexMCPUser).logicalDirectory( + environment) + case .geminiCommand, .geminiAgent, .geminiExtension: + base = try (memberScope == .project ? Self.geminiMCPProject : .geminiMCPUser) + .logicalDirectory(environment) + case .cursorCommand, .cursorAgent, .cursorLocalPlugin: + base = try (memberScope == .project ? Self.cursorMCPProject : .cursorMCPUser) + .logicalDirectory(environment) + } + let container: String + switch member! { + case .claudeCommand, .geminiCommand, .cursorCommand: container = "commands" + case .claudeAgent, .codexAgent, .geminiAgent, .cursorAgent: container = "agents" + case .claudeSkillPlugin: container = "skills" + case .cursorLocalPlugin: container = "plugins/local" + case .geminiExtension: container = "extensions" + } + let nested = name!.split(separator: "/").dropLast().map(String.init) + var result = base.resolvingSymlinksInPath() + let ancestry = try DirectoryAccessEvidence.capture(at: result) + var opened = + ancestry.directories.count == result.pathComponents.count + ? try DirectoryHandle(at: result) : nil + for part in container.split(separator: "/").map(String.init) + nested { + result.appendPathComponent(part) + if let parent = opened, try parent.info(part) != nil { + opened = try parent.child(part) + } else { + opened = nil + } + } + return result + } + fileprivate func userCounterpart() throws -> Self? { + guard memberScope == .project, let member, member != .cursorCommand else { return nil } + return try Self.named(member, scope: .user, name: name!) + } + func physicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + let logical = try logicalDirectory(environment) + return isNamed ? logical : logical.resolvingSymlinksInPath() + } + static func globalLogicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + try claudeMCPLocal.logicalDirectory(environment) + } + static func globalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + try globalLogicalDirectory(environment).resolvingSymlinksInPath() + } +} + /// Pathname authorization is checked separately. Neither route nor caller participates here. struct SharedResourceIdentity: Codable, Equatable, Comparable { let parent: FileObjectIdentity @@ -137,11 +405,17 @@ struct SharedResourceIdentity: Codable, Equatable, Comparable { "\(parent.device):\(parent.inode):\(parent.kind):\(basename.utf8.count):\(basename)" } var directoryName: String { FileHash.sha256Hex(data: Data(orderingKey.utf8)) } - static func < (lhs: Self, rhs: Self) -> Bool { lhs.orderingKey < rhs.orderingKey } + static func == (lhs: Self, rhs: Self) -> Bool { + lhs.parent == rhs.parent && lhs.basename.utf8.elementsEqual(rhs.basename.utf8) + } + static func < (lhs: Self, rhs: Self) -> Bool { + lhs.orderingKey.utf8.lexicographicallyPrecedes(rhs.orderingKey.utf8) + } func validate() throws { guard parent.isDirectory, - NativeTargetRoute.sharedRoutes.contains(where: { $0.basename == basename }) + !basename.isEmpty, basename != ".", basename != "..", + !basename.contains("/"), !basename.contains("\\"), !basename.contains("\0") else { throw CoreError.invalidState("unregistered shared transaction resource") } @@ -172,9 +446,9 @@ final class SharedResource { init(store: StateStore, route: NativeTargetRoute = .claudeMCPLocal, create: Bool) throws { guard route.shared else { throw CoreError.invalidState("project route has no shared resource") } - self.route = NativeTargetRoute.sharedRoutes.first { $0.root == route.root }! + self.route = NativeTargetRoute.targetRoute(route.root)! authorizedRoot = try route.logicalDirectory(store.environment) - let url = authorizedRoot.resolvingSymlinksInPath() + let url = try route.physicalDirectory(store.environment) parent = try DirectoryHandle(at: url, create: create) ancestry = try DirectoryAccessEvidence.capture(at: url) identity = SharedResourceIdentity(parent: try parent.objectIdentity, basename: route.basename) @@ -349,7 +623,7 @@ struct AbsentSharedRoot { init?(store: StateStore, route: NativeTargetRoute) throws { logical = try route.logicalDirectory(store.environment) - physical = logical.resolvingSymlinksInPath() + physical = try route.physicalDirectory(store.environment) ancestry = try DirectoryAccessEvidence.capture(at: physical) guard ancestry.directories.count < physical.pathComponents.count else { return nil } self.route = route @@ -372,6 +646,8 @@ final class TransactionLockContext { private static let threadKey = "agents.core.transaction-lock-context" let scopeURL: URL let resources: [SharedResource] + let admissions: [SharedResource] + let requestedRoutes: Set let writable: Bool let requestedShared: Bool let absentRoots: [AbsentSharedRoot] @@ -381,10 +657,13 @@ final class TransactionLockContext { init( store: StateStore, resources: [SharedResource], writable: Bool, requestedShared: Bool, - absentRoots: [AbsentSharedRoot] = [] + absentRoots: [AbsentSharedRoot] = [], admissions: [SharedResource] = [], + requestedRoutes: Set = [] ) { scopeURL = store.directory.standardizedFileURL self.resources = resources + self.admissions = admissions.isEmpty ? resources : admissions + self.requestedRoutes = requestedRoutes self.writable = writable self.requestedShared = requestedShared self.absentRoots = absentRoots @@ -456,9 +735,10 @@ final class TransactionLockContext { } func resource(for route: NativeTargetRoute) throws -> SharedResource { - guard let resource = resources.first(where: { $0.route.root == route.root }) else { + guard let resource = admissions.first(where: { $0.route.root == route.root }) else { throw CoreError.invalidState("shared target is outside the held request footprint") } + try resource.validate() return try self.resource(resource.identity) } @@ -490,19 +770,40 @@ final class TransactionLockContext { extension StateStore { package func nativeTarget(for route: NativeTargetRoute) throws -> MaterializationTarget { - guard route.shared || scope == .project else { + guard route.permits(scope) else { throw CoreError.unsafePath("project native targets require their project scope") } - let logical = try route.logicalDirectory(environment) + if let counterpart = try route.userCounterpart(), + try route.physicalDirectory(environment).path.utf8.elementsEqual( + counterpart.physicalDirectory(environment).path.utf8) + { + throw CoreError.unsafePath("project native target coincides with a registered user target") + } + var canonical = route let parent: URL if route.shared, let context = TransactionLockContext.current(self) { parent = try context.targetDirectory(for: route) + if try context.absentRoot(for: route) == nil { + canonical = try context.resource(for: route).route + } } else { - parent = logical.resolvingSymlinksInPath() + parent = try route.physicalDirectory(environment) + } + if !route.shared, let context = TransactionLockContext.current(self) { + for candidate in context.requestedRoutes.filter({ !$0.shared && $0.permits(scope) }).sorted( + by: { + $0.rawValue.utf8.lexicographicallyPrecedes($1.rawValue.utf8) + }) where candidate.basename.utf8.elementsEqual(route.basename.utf8) + { + if try candidate.physicalDirectory(environment).path.utf8.elementsEqual(parent.path.utf8) { + canonical = candidate + break + } + } } return MaterializationTarget( url: parent.appendingPathComponent(route.basename), - path: route.root + "/" + route.basename, scope: directory) + path: canonical.root + "/" + canonical.basename, scope: directory) } /// Acquire the union before the scope lock. Re-admission never replays a delivered callback. @@ -513,34 +814,28 @@ extension StateStore { if TransactionLockContext.isHeld { throw CoreError.invalidState("nested scope lock acquisition") } + guard routes.allSatisfy({ $0.permits(scope) }) else { + throw CoreError.unsafePath("registered native request belongs to another scope") + } while true { let before = try pendingCoordinationJournal(diagnosing: !writable) var resources: [SharedResource] = [] var absentRoots: [AbsentSharedRoot] = [] let pending = before?.footprint ?? [] - var requested = Set( - routes.filter(\.shared).map { route in - NativeTargetRoute.sharedRoutes.first { $0.root == route.root }! + var admissions: [SharedResource] = [] + let recoveryRoutes = Set( + (before?.roots.keys.map { $0 } ?? []).compactMap { + NativeTargetRoute.sharedRoute($0) ?? NativeTargetRoute.metadataRoute($0) }) - for identity in pending { - try identity.validate() - guard - let route = NativeTargetRoute.sharedRoutes.first(where: { - $0.basename == identity.basename - }) - else { - throw CoreError.invalidState("unregistered shared recovery resource") - } - requested.insert(route) - } - // Validate every original recovery domain before creating any newly requested metadata. + var requested = Set(routes.filter(\.shared).map { NativeTargetRoute.targetRoute($0.root)! }) + requested.formUnion(recoveryRoutes) let ordered = requested.sorted { left, right in - let leftPending = pending.contains { $0.basename == left.basename } - let rightPending = pending.contains { $0.basename == right.basename } + let leftPending = recoveryRoutes.contains(left) + let rightPending = recoveryRoutes.contains(right) return leftPending == rightPending ? left.rawValue < right.rawValue : leftPending } for route in ordered { - let recovering = pending.contains { $0.basename == route.basename } + let recovering = recoveryRoutes.contains(route) if !writable, !recovering, let absent = try AbsentSharedRoot(store: self, route: route) { absentRoots.append(absent) continue @@ -564,13 +859,19 @@ extension StateStore { "shared recovery requires the original runtime context and coordination lock") } } + admissions.append(resource) if !resources.contains(where: { $0.identity == resource.identity }) { resources.append(resource) } } + guard pending.allSatisfy({ identity in resources.contains { $0.identity == identity } }) + else { + throw CoreError.invalidState("shared recovery footprint has no registered runtime resource") + } let context = TransactionLockContext( store: self, resources: resources.sorted { $0.identity < $1.identity }, writable: writable, - requestedShared: routes.contains(where: \.shared), absentRoots: absentRoots) + requestedShared: routes.contains(where: \.shared), absentRoots: absentRoots, + admissions: admissions, requestedRoutes: routes) func locked(_ index: Int) throws -> T? { if index < context.resources.count { let resource = context.resources[index] @@ -648,6 +949,7 @@ extension StateStore { guard let directory else { throw CoreError.invalidState("missing transaction scope") } try context.validate(journal, scope: directory) } + for admission in context.admissions { try admission.validate() } for resource in context.resources { if journal?.finalized != true && (context.writable || journal == nil) { try resource.inspect(journal: journal, scope: directory?.identity ?? "") @@ -667,3 +969,36 @@ extension Optional where Wrapped == TransactionLockContext { return try context.resource(identity) } } + +/// Descriptor-derived physical file key. Absence deliberately has no fabricated key. +package struct NativeTargetIdentity: Hashable, Sendable { + package let device: UInt64 + package let inode: UInt64 + package let kind: UInt32 + package let basename: String + package static func == (lhs: Self, rhs: Self) -> Bool { + lhs.device == rhs.device && lhs.inode == rhs.inode && lhs.kind == rhs.kind + && lhs.basename.utf8.elementsEqual(rhs.basename.utf8) + } + package func hash(into hasher: inout Hasher) { + hasher.combine(device) + hasher.combine(inode) + hasher.combine(kind) + for byte in basename.utf8 { hasher.combine(byte) } + } +} + +extension StateStore { + package func nativeTargetIdentity(for route: NativeTargetRoute) throws -> NativeTargetIdentity? { + let target = try nativeTarget(for: route) + let parent = target.url.deletingLastPathComponent() + let evidence = try DirectoryAccessEvidence.capture(at: parent) + guard evidence.directories.count == parent.pathComponents.count else { return nil } + let descriptor = try DirectoryHandle(at: parent) + let identity = try descriptor.objectIdentity + try evidence.validate(at: parent) + return NativeTargetIdentity( + device: identity.device, inode: identity.inode, + kind: UInt32(identity.kind), basename: target.url.lastPathComponent) + } +} diff --git a/Sources/AgentsCore/PrivateMaterialization.swift b/Sources/AgentsCore/PrivateMaterialization.swift index f513fb5..2fc02cf 100644 --- a/Sources/AgentsCore/PrivateMaterialization.swift +++ b/Sources/AgentsCore/PrivateMaterialization.swift @@ -114,6 +114,9 @@ extension StateStore { _ target: MaterializationTarget, changingAccess: Bool = false, requiringReceiptForExistingTarget: Bool = false, expecting generation: UUID? = nil ) throws -> PreparedPrivateMaterialization { + if NativeTargetRoute.targetRoute(target.path)?.isContainer == true { + throw CoreError.invalidState("private materialization requires a registered regular file") + } guard target.scope.path == directory.path, try TransactionPaths(store: self).path(for: target.url) == target.path else { throw CoreError.invalidState("materialization target belongs to another scope") } @@ -198,7 +201,15 @@ struct MaterializationReceipts: Codable { guard version == 1 else { throw CoreError.invalidState("unsupported materialization receipt") } for (path, record) in targets { let paths = TransactionPaths(store: store) - let parts = try paths.components(path) + let parts: (root: String, descendants: [String]) + if let route = NativeTargetRoute.sharedRoute(path) { + guard path.utf8.elementsEqual((route.root + "/" + route.basename).utf8) else { + throw CoreError.invalidState("invalid physical receipt target") + } + parts = (route.root, [route.basename]) + } else { + parts = try paths.components(path) + } guard (parts.root.hasPrefix("instructions-") && parts.root != "instructions-authoring") || NativeTargetRoute.targetRoute(parts.root) != nil @@ -260,17 +271,49 @@ extension StateStore { let evidenceWithAccess = try evidence.capturingAccess() let access = try directory.requirePrivateAccess(url.lastPathComponent) do { - let records = try Self.decode( + var records = try Self.decode( directory.read(url.lastPathComponent), as: MaterializationReceipts.self) try records.validate(store: self) - if let resource, - Set(records.targets.keys) != [resource.route.root + "/" + resource.identity.basename] - { - throw CoreError.invalidState("shared receipt must identify its physical file") + if let resource { + guard records.targets.count == 1, let (key, record) = records.targets.first, + let recorded = NativeTargetRoute.sharedRoute(key), + recorded.basename.utf8.elementsEqual(resource.identity.basename.utf8), + record.rootIdentity.utf8.elementsEqual(resource.identity.orderingKey.utf8) + else { throw CoreError.invalidState("shared receipt must identify its physical file") } + records.targets = [resource.route.root + "/" + resource.identity.basename: record] + } + if !shared { + var candidates = TransactionLockContext.current(self)?.requestedRoutes ?? [] + if let route = NativeTargetRoute.targetRoute(path) { candidates.insert(route) } + for route in candidates.filter({ !$0.shared }).sorted(by: { + $0.rawValue.utf8.lexicographicallyPrecedes($1.rawValue.utf8) + }) { + let target = try nativeTarget(for: route) + let parentURL = target.url.deletingLastPathComponent() + let ancestry = try DirectoryAccessEvidence.capture(at: parentURL) + guard ancestry.directories.count == parentURL.pathComponents.count else { continue } + let parent = try DirectoryHandle(at: parentURL) + let identity = try parent.identity + let matches = records.targets.filter { key, record in + NativeTargetRoute.targetRoute(key)?.shared == false + && key.split(separator: "/").last.map(String.init)?.utf8.elementsEqual( + route.basename.utf8) == true + && record.rootIdentity == identity + } + guard matches.count <= 1 else { + throw CoreError.invalidState("ambiguous physical materialization receipts") + } + if let (old, record) = matches.first { + records.targets.removeValue(forKey: old) + records.targets[target.path] = record + } + try ancestry.validate(at: parentURL) + } } for (key, record) in records.targets { guard shared == (NativeTargetRoute.sharedRoute(key) != nil), - !shared || record.rootIdentity == resource?.identity.orderingKey + !shared + || record.rootIdentity.utf8.elementsEqual((resource?.identity.orderingKey ?? "").utf8) else { throw CoreError.invalidState("receipt belongs to another physical resource") } } try evidence.validate() diff --git a/Sources/AgentsCore/TransactionJournal.swift b/Sources/AgentsCore/TransactionJournal.swift index 61f9816..aef0b43 100644 --- a/Sources/AgentsCore/TransactionJournal.swift +++ b/Sources/AgentsCore/TransactionJournal.swift @@ -22,8 +22,7 @@ struct TransactionJournal: Codable { var finalized = false func validateCoordination() throws { - guard footprint.count <= NativeTargetRoute.sharedRoutes.count, - zip(footprint, footprint.dropFirst()).allSatisfy({ $0 < $1 }) + guard zip(footprint, footprint.dropFirst()).allSatisfy({ $0 < $1 }) else { throw CoreError.invalidState("unregistered shared transaction footprint") } @@ -44,13 +43,15 @@ struct TransactionJournal: Codable { roots.keys.compactMap { key in (NativeTargetRoute.sharedRoute(key) ?? NativeTargetRoute.metadataRoute(key))?.root }) - let footprintRoots = Set( - footprint.compactMap { identity in - NativeTargetRoute.sharedRoutes.first { $0.basename == identity.basename }?.root + let routes = sharedRoots.compactMap(NativeTargetRoute.sharedRoute) + guard sharedRoots.count == routes.count, sharedRoots.count == footprint.count, + routes.allSatisfy({ route in + footprint.contains { $0.basename.utf8.elementsEqual(route.basename.utf8) } + }), + footprint.allSatisfy({ identity in + routes.contains { $0.basename.utf8.elementsEqual(identity.basename.utf8) } }) - guard sharedRoots == footprintRoots, footprintRoots.count == footprint.count else { - throw CoreError.invalidState("journal roots contradict shared footprint") - } + else { throw CoreError.invalidState("journal roots contradict shared footprint") } } } diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index 8facf22..9874e4c 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -29,14 +29,26 @@ struct TransactionPaths { } } } - let nativeRoutes = NativeTargetRoute.allCases.sorted { $0.shared && !$1.shared } - for route in nativeRoutes where route.shared || store.scope == .project { - guard destination.lastPathComponent == route.basename else { continue } - let registered = try route.logicalDirectory(store.environment).resolvingSymlinksInPath() + let admitted = + Array(TransactionLockContext.current(store)?.requestedRoutes ?? []) + + (TransactionLockContext.current(store)?.admissions.map(\.route) ?? []) + let nativeRoutes = Array(Set(admitted + NativeTargetRoute.allCases)).sorted { + if $0.shared != $1.shared { return $0.shared } + if admitted.contains($0) != admitted.contains($1) { return admitted.contains($0) } + return $0.shared == $1.shared ? $0.rawValue < $1.rawValue : $0.shared + } + for route in nativeRoutes where route.shared || route.permits(store.scope) { + guard destination.lastPathComponent.utf8.elementsEqual(route.basename.utf8) else { continue } + let registered = try route.physicalDirectory(store.environment) .appendingPathComponent(route.basename) - guard registered == destination.standardizedFileURL else { continue } + guard registered.path.utf8.elementsEqual(destination.standardizedFileURL.path.utf8) else { + continue + } + guard route.permits(store.scope) else { + throw CoreError.unsafePath("native target belongs to another scope") + } let target = try store.nativeTarget(for: route) - if target.url == destination.standardizedFileURL { + if target.url.path.utf8.elementsEqual(destination.standardizedFileURL.path.utf8) { if route.shared { guard let context = TransactionLockContext.current(store) else { throw CoreError.invalidState("shared target requires its held footprint") @@ -94,7 +106,7 @@ struct TransactionPaths { ? store.environment.projectDirectory : store.environment.homeDirectory url = base.resolvingSymlinksInPath().appendingPathComponent(store.directory.lastPathComponent) } else if let route = NativeTargetRoute.targetRoute(key) { - guard route.shared || store.scope == .project else { + guard route.permits(store.scope) else { throw CoreError.unsafePath("project native targets require their project scope") } if route.shared { @@ -103,7 +115,7 @@ struct TransactionPaths { } url = try context.targetDirectory(for: route) } else { - url = try route.logicalDirectory(store.environment).resolvingSymlinksInPath() + url = try route.physicalDirectory(store.environment) } } else if let route = NativeTargetRoute.metadataRoute(key) { guard let context = TransactionLockContext.current(store), @@ -190,7 +202,7 @@ struct TransactionPaths { throw CoreError.unsafePath("unmanaged state transaction path") } } else if let route = NativeTargetRoute.targetRoute(key) { - guard route.shared || store.scope == .project, descendants == [route.basename] else { + guard route.permits(store.scope), descendants == [route.basename] else { throw CoreError.unsafePath("unregistered native target") } } else if NativeTargetRoute.metadataRoute(key) != nil { diff --git a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift index 78389e3..e704c9e 100644 --- a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift +++ b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift @@ -186,7 +186,7 @@ struct RegisteredNativeTargetTests { } #endif - @Test(arguments: NativeTargetRoute.allCases) + @Test(arguments: NativeTargetRoute.mcpRoutes) func registeredFilesPublishPrivatelyAndRetainTheirReceipt(_ route: NativeTargetRoute) throws { let fixture = try NativeRouteFixture() let expected: [NativeTargetRoute: String] = [ @@ -580,3 +580,273 @@ extension Optional where Wrapped == TransactionLockContext { try #require(self).resource(for: route) } } + +extension RegisteredNativeTargetTests { + private static var componentFiles: [NativeTargetRoute] { + var result: [NativeTargetRoute] = [ + .claudeSettingsProject, .claudeSettingsUser, + .codexHooksProject, .codexHooksUser, .cursorHooksProject, .cursorHooksUser, + .geminiIgnoreProject, .cursorIgnoreProject, + ] + for member in [ + NativeTargetRoute.Member.claudeCommand, .claudeAgent, .codexAgent, + .geminiCommand, .geminiAgent, .cursorCommand, .cursorAgent, + ] { + for scope in [InstallScope.project, .user] { + if let route = try? NativeTargetRoute.named(member, scope: scope, name: "example") { + result.append(route) + } + } + } + return result + } + + @Test(arguments: componentFiles) + func componentFilesRetainPrivateGenerationOnOrdinarySiblingEdit(_ route: NativeTargetRoute) throws + { + let fixture = try NativeRouteFixture() + let store = StateStore( + scope: route.shared ? .user : .project, environment: fixture.store.environment) + try store.withLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + let transaction = FileTransaction(store: store) + try transaction.replacePrivate( + store.preparePrivateMaterialization(target), provider: NativeRouteBindings() + ) { + _ in Data("bound region; unmanaged sibling".utf8) + } + try transaction.commit() + let before = try #require(try store.materializationReceipt(for: target)) + let ordinary = FileTransaction(store: store) + try ordinary.replace(target.url, with: .data(Data("bound region; edited sibling".utf8))) + try ordinary.commit() + let after = try #require(try store.materializationReceipt(for: target)) + #expect(before.generation != after.generation) + _ = try DirectoryHandle(at: target.url.deletingLastPathComponent()).requirePrivateAccess( + target.url.lastPathComponent) + } + try store.withReadLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + let receipt = try store.materializationReceipt(for: target) + #expect(receipt != nil) + } + } + + @Test func componentRouteBoundariesAndPureFreshHomePreview() throws { + let fixture = try NativeRouteFixture() + var environment = fixture.store.environment + environment.homeDirectory = fixture.root.appendingPathComponent("fresh-home") + environment.environment = [:] + let store = StateStore(scope: .user, environment: environment) + let routes = try Set([ + NativeTargetRoute.named(.claudeCommand, scope: .user, name: "team/check"), + .named(.geminiExtension, scope: .user, name: "example"), + .named(.cursorLocalPlugin, scope: .user, name: "example"), + ]) + let before = try FileSnapshot.read(at: fixture.root) + try store.withReadLock(footprint: routes) { + for route in routes { + #expect(try store.nativeTargetIdentity(for: route) == nil) + let target = try store.nativeTarget(for: route) + #expect(target.url.path.hasPrefix(environment.homeDirectory.path + "/")) + #expect(try store.materializationReceipt(for: target) == nil) + } + } + #expect(try FileSnapshot.read(at: fixture.root) == before) + for name in [ + "", ".", "..", "../escape", "/escape", "a//b", "a/../b", "a\\b", ".agents-native", + "a/.agents-native/b", ".agents-temporary", + ] { + #expect(throws: CoreError.self) { + try NativeTargetRoute.named(.claudeCommand, scope: .user, name: name) + } + } + #expect(throws: CoreError.self) { + try NativeTargetRoute.named(.cursorCommand, scope: .user, name: "example") + } + #expect(throws: CoreError.self) { + try NativeTargetRoute.named(.geminiExtension, scope: .project, name: "example") + } + #expect(throws: CoreError.self) { try fixture.store.nativeTarget(for: .claudeSettingsUser) } + let beforeRefusal = try FileSnapshot.read(at: fixture.root) + #expect(throws: CoreError.self) { + try fixture.store.withLock(footprint: [.claudeSettingsUser]) { + _ = Issue.record("wrong-scope request must be refused before callback") + } + } + #expect(try FileSnapshot.read(at: fixture.root) == beforeRefusal) + var collidingEnvironment = fixture.store.environment + collidingEnvironment.environment["CLAUDE_CONFIG_DIR"] = + fixture.root.appendingPathComponent(".claude").path + let colliding = StateStore(scope: .project, environment: collidingEnvironment) + #expect(throws: CoreError.self) { + try colliding.nativeTarget(for: .named(.claudeAgent, scope: .project, name: "example")) + } + #expect(try FileSnapshot.read(at: fixture.root) == beforeRefusal) + let linkParent = fixture.config.appendingPathComponent("commands") + try FileManager.default.createSymbolicLink(at: linkParent, withDestinationURL: fixture.root) + let user = StateStore(scope: .user, environment: fixture.store.environment) + #expect(throws: CoreError.self) { + try user.nativeTarget(for: .named(.claudeCommand, scope: .user, name: "escape")) + } + #expect(NativeTargetRoute.claudeSettingsUser.knownReaders == [.claudeCode, .cursor]) + let fileRoute = try NativeTargetRoute.file( + .claudeCommand, scope: .user, relativePath: "team/check.md") + let namedRoute = try NativeTargetRoute.named(.claudeCommand, scope: .user, name: "team/check") + #expect(fileRoute == namedRoute) + #expect(throws: CoreError.self) { + try NativeTargetRoute.file(.claudeCommand, scope: .user, relativePath: "team/check.toml") + } + } + + @Test func aliasedComponentKindsShareIdentityAndSensitiveReceiptAcrossHomes() throws { + let fixture = try NativeRouteFixture() + var environment = fixture.store.environment + environment.environment["GEMINI_CLI_HOME"] = fixture.root.path + environment.environment["CLAUDE_CONFIG_DIR"] = + fixture.root.appendingPathComponent(".gemini").path + let a = StateStore(scope: .user, environment: environment) + environment.homeDirectory = fixture.root.appendingPathComponent("other-home") + let b = StateStore(scope: .project, environment: environment) + let routes: Set = [.claudeSettingsUser, .geminiMCPUser, .cursorHooksUser] + var identity: NativeTargetIdentity? + try a.withLock(footprint: routes) { + let first = try a.nativeTarget(for: .claudeSettingsUser) + let second = try a.nativeTarget(for: .geminiMCPUser) + #expect(first.path == second.path) + identity = try a.nativeTargetIdentity(for: .claudeSettingsUser) + #expect(identity == (try a.nativeTargetIdentity(for: .geminiMCPUser))) + #expect(identity != (try a.nativeTargetIdentity(for: .cursorHooksUser))) + let transaction = FileTransaction(store: a) + try transaction.replacePrivate( + a.preparePrivateMaterialization(first), provider: NativeRouteBindings() + ) { _ in Data("bound; sibling".utf8) } + try transaction.commit() + } + try b.withLock(footprint: [.geminiMCPUser]) { + let target = try b.nativeTarget(for: .geminiMCPUser) + #expect(identity == (try b.nativeTargetIdentity(for: .geminiMCPUser))) + let previous = try #require(try b.materializationReceipt(for: target)) + let transaction = FileTransaction(store: b) + try transaction.replace(target.url, with: .data(Data("bound; changed sibling".utf8))) + try transaction.commit() + #expect(try b.materializationReceipt(for: target)?.generation != previous.generation) + } + try a.withReadLock(footprint: [.claudeSettingsUser]) { + let target = try a.nativeTarget(for: .claudeSettingsUser) + let receipt = try a.materializationReceipt(for: target) + #expect(receipt != nil) + } + } +} + +extension RegisteredNativeTargetTests { + @Test(arguments: ["shared.1.reservation.halfWritten", "entry.0.applied", "journal.finalized"]) + func namedFilesWithEqualBasenamesRecoverThroughTheirClosedRoots(_ point: String) throws { + let fixture = try NativeRouteFixture() + let routes = try [ + NativeTargetRoute.named(.claudeAgent, scope: .user, name: "example"), + .named(.cursorAgent, scope: .user, name: "example"), + ] + let store = StateStore(scope: .user, environment: fixture.store.environment) + let child = try stateTestProcess( + root: fixture.root, + arguments: [ + "shared-install", point, "--native-routes", routes.map(\.rawValue).joined(separator: ","), + "--shared-config", fixture.config.path, "--scope", "user", + ]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let before = try FileSnapshot.read(at: fixture.root) + try store.withReadLock( + onPendingRecovery: { + let diagnosis = FileTransaction.recoveryDiagnostic(store: store) + #expect(!diagnosis.requiresOwner) + }, { _ = Issue.record("expected pending named targets") }) + #expect(try FileSnapshot.read(at: fixture.root) == before) + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + try store.withReadLock(footprint: Set(routes)) { + for route in routes { + let target = try store.nativeTarget(for: route) + let receipt = try store.materializationReceipt(for: target) + #expect((receipt != nil) == (point == "journal.finalized")) + } + } + } + + @Test(arguments: [ + NativeTargetRoute.Member.claudeSkillPlugin, .cursorLocalPlugin, .geminiExtension, + ]) + func registeredBundleContainersPublishAndDeleteWithoutInstallerAuthority( + _ member: NativeTargetRoute.Member + ) throws { + let fixture = try NativeRouteFixture() + let store = StateStore(scope: .user, environment: fixture.store.environment) + let route = try NativeTargetRoute.named(member, scope: .user, name: "example") + let payload = fixture.root.appendingPathComponent("bundle") + try FileManager.default.createDirectory(at: payload, withIntermediateDirectories: true) + try Data("native manifest fixture".utf8).write( + to: payload.appendingPathComponent("manifest.json")) + try store.withLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + #expect(throws: CoreError.self) { try store.preparePrivateMaterialization(target) } + #expect(throws: CoreError.self) { + let invalid = FileTransaction(store: store) + try invalid.replace(target.url, with: .data(Data("wrong kind".utf8))) + } + let transaction = FileTransaction(store: store) + try transaction.replace(target.url, with: .copy(payload)) + try transaction.commit() + #expect( + try Data(contentsOf: target.url.appendingPathComponent("manifest.json")) + == Data("native manifest fixture".utf8)) + #expect(throws: CoreError.self) { + let outside = fixture.root.appendingPathComponent("outside-native-root") + try FileTransaction(store: store).replace(outside, with: .copy(payload)) + } + let removal = FileTransaction(store: store) + try removal.delete(target.url) + try removal.commit() + #expect(!FileManager.default.fileExists(atPath: target.url.path)) + } + } +} + +extension RegisteredNativeTargetTests { + @Test func projectAliasesPreserveWholeFileSensitivityAcrossComponentKinds() throws { + let fixture = try NativeRouteFixture() + let store = fixture.store + let claude = try NativeTargetRoute.named(.claudeAgent, scope: .project, name: "example") + let cursor = try NativeTargetRoute.named(.cursorAgent, scope: .project, name: "example") + try FileManager.default.createDirectory( + at: fixture.root.appendingPathComponent(".claude"), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: fixture.root.appendingPathComponent(".cursor"), + withDestinationURL: fixture.root.appendingPathComponent(".claude")) + try store.withLock(footprint: [claude, cursor]) { + let a = try store.nativeTarget(for: claude) + let b = try store.nativeTarget(for: cursor) + #expect(a.path == b.path) + let transaction = FileTransaction(store: store) + try transaction.replacePrivate( + store.preparePrivateMaterialization(a), provider: NativeRouteBindings() + ) { _ in Data("private sibling; first region".utf8) } + try transaction.commit() + } + try store.withLock(footprint: [cursor]) { + let target = try store.nativeTarget(for: cursor) + let before = try #require(try store.materializationReceipt(for: target)) + let transaction = FileTransaction(store: store) + try transaction.replace(target.url, with: .data(Data("private sibling; changed region".utf8))) + try transaction.commit() + #expect(try store.materializationReceipt(for: target)?.generation != before.generation) + } + try store.withReadLock(footprint: [claude]) { + let target = try store.nativeTarget(for: claude) + let receipt = try store.materializationReceipt(for: target) + #expect(receipt != nil) + } + } +} diff --git a/Tests/StateTestProcess/PrivateMaterializationProbe.swift b/Tests/StateTestProcess/PrivateMaterializationProbe.swift index 5a72c72..ac19ae5 100644 --- a/Tests/StateTestProcess/PrivateMaterializationProbe.swift +++ b/Tests/StateTestProcess/PrivateMaterializationProbe.swift @@ -114,9 +114,11 @@ func sharedMaterializationProbe( try transaction.replace(target.url, with: .data(Data("secret sibling; edited region".utf8))) } } - try transaction.replace( - store.environment.projectDirectory.appendingPathComponent("old-data/AGENTS.md"), - with: .data(Data("ordinary after".utf8))) + if store.scope == .project { + try transaction.replace( + store.environment.projectDirectory.appendingPathComponent("old-data/AGENTS.md"), + with: .data(Data("ordinary after".utf8))) + } try transaction.commit() } } From d32ec8a3777f4a0f37ccbef6aa3bf1ad85e06059 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:18:44 +0800 Subject: [PATCH 088/171] test: use portable archive fixtures for indexed sources --- .../ComponentsTests/ArtifactLinkingTests.swift | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Tests/ComponentsTests/ArtifactLinkingTests.swift b/Tests/ComponentsTests/ArtifactLinkingTests.swift index 2fc313e..ee07390 100644 --- a/Tests/ComponentsTests/ArtifactLinkingTests.swift +++ b/Tests/ComponentsTests/ArtifactLinkingTests.swift @@ -73,7 +73,7 @@ struct ArtifactLinkingTests { kind: .skills, name: "beta") let newAlpha = try archive("alpha", body: "new alpha", fixture: fixture, web: web) // The protected member disappears from the index and its exact download is unavailable. - try FileManager.default.removeItem(at: web.appendingPathComponent("beta.zip")) + try FileManager.default.removeItem(at: web.appendingPathComponent("beta.tar.gz")) try index([("alpha", newAlpha)], fixture: fixture, web: web) let next = try freeze(pins: [key: .init(revision: oldBeta)], previous: previous) let retained = try #require(next.components.values.first { $0.name == "beta" }) @@ -208,8 +208,8 @@ struct ArtifactLinkingTests { key("alpha"): .init(revision: alphaDigest), key("beta"): .init(revision: betaDigest), ] // Membership comes from each pin's recorded index, even after its download disappears. - try FileManager.default.removeItem(at: webA.appendingPathComponent("alpha.zip")) - try FileManager.default.removeItem(at: webB.appendingPathComponent("beta.zip")) + try FileManager.default.removeItem(at: webA.appendingPathComponent("alpha.tar.gz")) + try FileManager.default.removeItem(at: webB.appendingPathComponent("beta.tar.gz")) try index([], fixture: fixture, web: webA) try index([], fixture: fixture, web: webB) let retained = try freeze(pins: pins, previous: previous) @@ -243,19 +243,19 @@ struct ArtifactLinkingTests { try fixture.write("fixture script", to: "scripts/run", base: root) try FileManager.default.setAttributes( [.posixPermissions: 0o755], ofItemAtPath: root.appendingPathComponent("scripts/run").path) - let zip = web.appendingPathComponent(name + ".zip") - if FileManager.default.fileExists(atPath: zip.path) { - try FileManager.default.removeItem(at: zip) + let archive = web.appendingPathComponent(name + ".tar.gz") + if FileManager.default.fileExists(atPath: archive.path) { + try FileManager.default.removeItem(at: archive) } try ProcessRunner.run( - "/usr/bin/env", arguments: ["zip", "-qr", zip.path, "."], workingDirectory: root) - return "sha256:" + (try FileHash.sha256Hex(file: zip)) + "/usr/bin/env", arguments: ["tar", "-czf", archive.path, "."], workingDirectory: root) + return "sha256:" + (try FileHash.sha256Hex(file: archive)) } private func index(_ members: [(String, String)], fixture: LinkFixture, web: URL) throws { let entries = members.map { name, digest in [ - "name": name, "description": "Fixture", "type": "archive", "url": "/\(name).zip", + "name": name, "description": "Fixture", "type": "archive", "url": "/\(name).tar.gz", "digest": digest, ] } From 7c547b0008f46b46fab0e56b17706ea0c291e8ef Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:18:44 +0800 Subject: [PATCH 089/171] feat: decode typed native component contributions --- .../Adapters/OpenCodeComponents.swift | 72 +-- .../NativeComponentContribution.swift | 195 ++++++++ .../NativeComponentDecodingV1.swift | 440 ++++++++++++++++++ .../Components/NativeComponentLayoutsV1.swift | 47 +- .../Components/NativeComponentLowering.swift | 40 ++ Sources/Components/NativeProgramV1.swift | 36 +- .../NativeComponentTests.swift | 332 ++++++++++++- 7 files changed, 1098 insertions(+), 64 deletions(-) create mode 100644 Sources/Components/NativeComponentContribution.swift create mode 100644 Sources/Components/NativeComponentDecodingV1.swift diff --git a/Sources/Components/Adapters/OpenCodeComponents.swift b/Sources/Components/Adapters/OpenCodeComponents.swift index bd2c5a5..1c0b757 100644 --- a/Sources/Components/Adapters/OpenCodeComponents.swift +++ b/Sources/Components/Adapters/OpenCodeComponents.swift @@ -6,40 +6,14 @@ extension OpenCodeAdapter { -> [ReplayedArtifact] { switch input.record.kind { - case "command": - try input.noParameters() - var fields = try input.checkedNative(["agent": .string, "subagent": .boolean]) - fields["description"] = .init(try input.text("description")) - fields["template"] = .init(try input.prompt()) - return try input.emitted( - lowering, - input.envelope( - route: .openCodeConfig, - keys: ["commands", input.record.name], value: .init(object: fields))) - case "subagent": - guard input.fields["tools"] == nil else { - throw input.issue( - ["tools"], .unsupported, - "OpenCode agent schema has permissions rather than a tool allowlist") - } - var fields = try input.checkedNative(["hidden": .boolean, "disabled": .boolean]) - fields["system"] = .init(try input.prompt()) - fields["description"] = .init(try input.text("description")) - fields["mode"] = .init("subagent") - if let model = input.fields["model"]?.text { - guard model.range(of: #"^[^/#]+/[^#]+(?:#[^#]+)?$"#, options: .regularExpression) != nil - else { - throw input.issue( - ["model"], .invalid, "native model selection requires provider/model syntax") - } - try input.literal(model, field: ["model"]) - fields["model"] = .init(model) - } + case "command", "subagent": + let fields = try definition(input, prompt: input.prompt()) return try input.emitted( lowering, input.envelope( route: .openCodeConfig, - keys: ["agents", input.record.name], value: .init(object: fields))) + keys: [input.record.kind == "command" ? "commands" : "agents", input.record.name], + value: .init(object: fields))) case "permissions": _ = try input.checkedNative([:]) let rules = try (input.fields["rules"]?.array ?? []).enumerated().map { @@ -71,4 +45,42 @@ extension OpenCodeAdapter { throw input.issue(["kind"], .invalid, "component does not match this concrete native profile") } } + + /// Renderer and contribution decoder share the definition fields. A file-backed prompt body + /// reaches the decoder through its sealed artifact; no source path is rediscovered there. + static func definition(_ input: ComponentRenderInput, prompt: String) throws -> [String: + LedgerValue] + { + try input.literal(prompt, field: ["prompt"], prompt: input.record.kind == "command") + if input.record.kind == "command" { + try input.noParameters() + var fields = try input.checkedNative(["agent": .string, "subagent": .boolean]) + fields["description"] = .init(try input.text("description")) + fields["template"] = .init(prompt) + return fields + } + guard input.record.kind == "subagent" else { + throw input.issue(["kind"], .invalid, "component is not an OpenCode definition") + } + guard input.fields["tools"] == nil else { + throw input.issue( + ["tools"], .unsupported, + "OpenCode agent schema has permissions rather than a tool allowlist") + } + var fields = try input.checkedNative(["hidden": .boolean, "disabled": .boolean]) + fields["system"] = .init(prompt) + fields["description"] = .init(try input.text("description")) + fields["mode"] = .init("subagent") + if let model = input.fields["model"]?.text { + guard model.range(of: #"^[^/#]+/[^#]+(?:#[^#]+)?$"#, options: .regularExpression) != nil + else { + throw input.issue( + ["model"], .invalid, "native model selection requires provider/model syntax") + } + try input.literal(model, field: ["model"]) + fields["model"] = .init(model) + } + return fields + } + } diff --git a/Sources/Components/NativeComponentContribution.swift b/Sources/Components/NativeComponentContribution.swift new file mode 100644 index 0000000..59e1179 --- /dev/null +++ b/Sources/Components/NativeComponentContribution.swift @@ -0,0 +1,195 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// One frozen logical owner. Physical reader union and native ownership observations belong to E. +package struct NativeComponentContribution { + package let format: String + package let request: NativeComponentRequest + package let component: String + package let kind: DeclaredComponentKind + package let name: String + package let occurrences: [Int] + package let recipients: [AgentID] + package let knownReaders: [AgentID] + package let resources: [String: LedgerResource] + package let outputs: [NativeComponentOutput] +} + +/// These are the concrete current native surfaces, not caller-programmable document edits. +package struct NativeComponentOutput { + package let route: NativeComponentRoute + package let content: Content + + package enum Content { + /// Whole UTF8 file, with no executable bit. The relative name is admitted under the route by D. + case file(path: String, bytes: Data) + case member(NativeComponentMember, NativeComponentValue) + /// One owned array occurrence. Preserve ordering; equal unmanaged occurrences confer no authority. + case hook(NativeComponentHook) + /// Last-match native tool/resource rules, appended in their declared order. + case orderedPermissions([NativeComponentPermission]) + /// Native deny/ask/allow categories, not a portable ordered policy. + case claudePermissions(NativeClaudePermissions) + /// Ordered lines for E's existing managed ignore block, not independent line ownership. + case ignore([String]) + /// One generated Claude plugin manifest and its coupled registered plugin directory. + case generatedLSPPlugin(directory: String, manifestPath: String, manifest: NativeComponentValue) + /// Complete opaque frozen tree. Entries retain file kinds, symlinks and executable bits. + case nativePlugin(directory: String, resource: String, manifest: String) + } +} + +package enum NativeComponentMember { + case openCodeCommand(String) + case openCodeAgent(String) + case openCodeLSP(String) + /// The config_file points at the coupled codexAgent file output of this same owner. + case codexAgent(String) + + package var keys: [String] { + switch self { + case .openCodeCommand(let name): ["commands", name] + case .openCodeAgent(let name): ["agents", name] + case .openCodeLSP(let name): ["lsp", name] + case .codexAgent(let name): ["agents", name] + } + } +} + +package struct NativeComponentHook { + package enum Layout: Equatable { + /// An event array contains groups with matcher/sequential metadata and a hooks array. + case group + /// Cursor's event array contains handlers directly; the root must have version = 1. + case cursorVersion1 + } + package let event: String + package let layout: Layout + package let value: NativeComponentValue + package var keys: [String] { ["hooks", event] } +} + +package struct NativeComponentPermission { + package enum Effect: String { case allow, ask, deny } + package let tool: String + package let resource: String + package let effect: Effect +} + +package struct NativeClaudePermissions { + /// nil differs from a supplied empty category. E must preserve that distinction. + package let allow: [String]? + package let ask: [String]? + package let deny: [String]? + package let defaultMode: String? +} + +/// Slots identify only actual native program positions. They never address arbitrary settings data. +package enum NativeComponentSlot: Equatable { + case executable + case argument(Int) + case environment(String) + case workingDirectory +} + +package struct NativeComponentBindingPlacement { + package let slot: NativeComponentSlot + package let binding: RuntimeBinding +} + +package struct NativeComponentResourcePlacement { + package let slot: NativeComponentSlot + package let resource: String +} + +/// A decoder-created native value. Its symbolic payload cannot be mutated or constructed by E. +package struct NativeComponentValue { + package let bindings: [NativeComponentBindingPlacement] + package let resourcePlacements: [NativeComponentResourcePlacement] + private let envelope: LedgerValue + private let requiresProgramConversion: Bool + private let manifestProjection: Bool + + init( + envelope: LedgerValue, bindings: [NativeComponentBindingPlacement], + resourcePlacements: [NativeComponentResourcePlacement], requiresProgramConversion: Bool, + manifestProjection: Bool + ) { + self.envelope = envelope + self.bindings = bindings + self.resourcePlacements = resourcePlacements + self.requiresProgramConversion = requiresProgramConversion + self.manifestProjection = manifestProjection + } + + /// Invoke only in E/D's private render closure. Core values and final admitted paths are inputs; + /// this operation never invokes a provider, writes a file or persists materialized bindings. + package func stagedValue( + bindings: RuntimeBindingValues, environment: RuntimeEnvironment, + resourcePaths: [String: String], budget: NativeDocumentBudget, + codexCommandShell: NativeProgramV1.CommandShell? = nil, + cursorCommandShell: NativeProgramV1.CommandShell? = nil + ) throws -> NativeValue { + if requiresProgramConversion { + let converted = try NativeProgramV1.stagedValue( + envelope, bindings: bindings, environment: environment, resourcePaths: resourcePaths, + budget: budget, codexCommandShell: codexCommandShell, + cursorCommandShell: cursorCommandShell) + if manifestProjection { + guard case .object(let files) = converted, + let manifest = files[".claude-plugin/plugin.json"] + else { + throw CoreError.invalidState("missing staged native plugin manifest") + } + return manifest + } + return converted + } + return try literalValue(envelope.object!["value"]!, budget: budget, depth: 0) + } + + /// A key member with no program can be prepared without requesting any runtime values. + package func referenceValue(budget: NativeDocumentBudget) throws -> NativeValue { + guard !requiresProgramConversion else { + let fields = envelope.object! + throw NativeComponentIssue( + request: .init( + surface: NativeClientSurface(rawValue: fields["surface"]!.text!)!, + scope: InstallScope(rawValue: fields["scope"]!.text!)!), + kind: fields["kind"]!.text!, component: fields["name"]!.text!, field: ["value"], + reason: .integrationRequired, detail: "private staged native program conversion is required" + ) + } + return try literalValue(envelope.object!["value"]!, budget: budget, depth: 0) + } + + private func literalValue(_ value: LedgerValue, budget: NativeDocumentBudget, depth: Int) throws + -> NativeValue + { + try budget.node(depth: depth) + try budget.step() + switch value.kind { + case .string, .literal, .decimal: + try budget.allocate(value.text!.utf8.count, stage: "native component string") + try budget.step(value.text!.utf8.count) + if value.kind == .decimal { return .decimal(value.text!) } + return .string(value.text!) + case .integer: return .integer(value.integer!) + case .boolean: return .boolean(value.boolean!) + case .null: return .null + case .array: + return .array(try value.array!.map { try literalValue($0, budget: budget, depth: depth + 1) }) + case .object: + var result: [String: NativeValue] = [:] + for (key, child) in value.object!.sorted(by: { $0.key < $1.key }) { + try budget.allocate(key.utf8.count, stage: "native component key") + try budget.step(key.utf8.count) + result[key] = try literalValue(child, budget: budget, depth: depth + 1) + } + return .object(result) + case .environment, .secret: + throw CoreError.invalidState("symbolic value outside a native component program") + } + } +} diff --git a/Sources/Components/NativeComponentDecodingV1.swift b/Sources/Components/NativeComponentDecodingV1.swift new file mode 100644 index 0000000..7c8db8d --- /dev/null +++ b/Sources/Components/NativeComponentDecodingV1.swift @@ -0,0 +1,440 @@ +import AgentsCore +import Foundation +import NativeDocuments + +extension NativeComponentLayoutsV1 { + /// Decode exactly one sealed lowering's replay artifacts. Call inside LedgerReplay's closure: + /// the ledger has passed Core admission, bundle trees are borrowed there, and replay verifies + /// source bytes and executable bits. This is not a second whole-ledger admission operation. + /// Sealing authenticates file bodies without introducing another native file parser in E. + package static func contribution( + _ lowering: LockedLowering, ledger: ResolvedLedger, artifacts: [ReplayedArtifact], + limits: LedgerLimits + ) throws -> NativeComponentContribution { + guard ledger.lowerings.filter({ $0.id == lowering.id }) == [lowering], + !lowering.artifacts.isEmpty, artifacts.count == lowering.artifacts.count, + let component = lowering.inputs.first, ledger.components[component]?.payload.object != nil + else { throw CoreError.invalidState("unsealed or mismatched native component lowering") } + let input = try input(lowering, ledger: ledger, limits: limits) + let decoder = NativeComponentDecoderV1(input: input) + try decoder.admit(lowering.layout) + if ["hook", "lspServer"].contains(input.record.kind) { + try NativeProgramV1.validateFrozenRun(input) + } + guard artifacts.first?.kind == .ownedValues, + artifacts.first?.name == lowering.id, + (input.record.kind == "plugin" && artifacts.count == 2 + && artifacts[1].kind == .tree && artifacts[1].name == lowering.id + "/bundle") + || (input.record.kind != "plugin" && artifacts.count == 1) + else { throw decoder.invalid() } + for artifact in artifacts { + guard artifact.location == nil else { throw decoder.invalid() } + if let value = artifact.values { try decoder.admit(value) } + } + guard try artifacts.map({ try $0.digest(limits: limits) }) == lowering.artifacts, + artifacts[0].name == lowering.id, artifacts[0].kind == .ownedValues, + let envelope = artifacts[0].values + else { throw decoder.invalid() } + let envelopes: [LedgerValue] + if input.request.surface == .codexCLI, input.record.kind == "subagent" { + guard let pair = envelope.array, pair.count == 2 else { throw decoder.invalid() } + envelopes = pair + } else { + guard envelope.kind == .object else { throw decoder.invalid() } + envelopes = [envelope] + } + let outputs = try envelopes.enumerated().map { + try decoder.output($0.element, index: $0.offset) + } + // Reuse the production semantic validators for all programmable regional outputs. No native + // event/field tables are copied into the decoder or importer. File bodies are pinned by seal. + if ["hook", "permissions", "lspServer"].contains(input.record.kind) { + let expected: [ReplayedArtifact] + switch input.request.surface { + case .claudeCode: expected = try ClaudeAdapter.components(lowering, input) + case .codexCLI: expected = try CodexAdapter.components(lowering, input) + case .geminiCLI: expected = try GeminiAdapter.components(lowering, input) + case .openCodeCLI: expected = try OpenCodeAdapter.components(lowering, input) + case .cursorEditor, .cursorCLI, .cursorCloud: + expected = try CursorAdapter.components(lowering, input) + } + guard expected.count == 1, expected[0].values == envelope else { throw decoder.invalid() } + } + if input.record.kind == "plugin" { + guard artifacts.count == 2, artifacts[1].name == lowering.id + "/bundle", + artifacts[1].kind == .tree, artifacts[1].tree != nil, + artifacts[1].bytes == nil, artifacts[1].values == nil + else { throw decoder.invalid() } + let resource = ledger.resources[lowering.resources[0]]! + let entries = resource.entries.map { entry in + var entry = entry + entry.object = nil + return entry + } + guard + lowering.artifacts[1].hash + == (try ResolvedLedgerCodec.digest( + NativeComponentTreeDigestV1(content: resource.hash, entries: entries))) + else { + throw decoder.invalid(["resources"]) + } + } else { + guard artifacts.count == 1 else { throw decoder.invalid() } + } + let kind = DeclaredComponentKind(rawValue: input.record.kind)! + return .init( + format: lowering.format, request: input.request, component: input.component, kind: kind, + name: input.record.name, occurrences: input.occurrences, + recipients: [input.request.surface.agent], + knownReaders: CapabilityRegistry.componentReaders(input.request, kind: kind) + .sorted { $0.rawValue < $1.rawValue }, + resources: lowering.resources.reduce(into: [:]) { $0[$1] = ledger.resources[$1]! }, + outputs: outputs) + } +} + +private struct NativeComponentTreeDigestV1: Encodable { + let content: String + let entries: [LedgerEntry] +} + +private struct NativeComponentDecoderV1 { + let input: ComponentRenderInput + func invalid(_ field: [String] = ["output"]) -> NativeComponentIssue { + input.issue(field, .invalid, "invalid sealed native component contribution") + } + + /// Charge decoded values before validation, equality, hashing, copying or staging. + func admit(_ value: LedgerValue, depth: Int = 0) throws { + try input.budget.node(depth: depth) + try input.budget.step() + if let text = value.text { + try input.budget.allocate(text.utf8.count, stage: "native contribution string") + try input.budget.step(text.utf8.count) + guard !text.utf8.contains(0) else { throw invalid() } + if value.kind == .decimal, + text.range( + of: #"\A-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\z"#, + options: .regularExpression) == nil + { + throw invalid(["value"]) + } + } + for child in value.array ?? [] { try admit(child, depth: depth + 1) } + for (key, child) in value.object ?? [:] { + try input.budget.allocate(key.utf8.count, stage: "native contribution key") + try input.budget.step(key.utf8.count) + guard !key.utf8.contains(0) else { throw invalid() } + try admit(child, depth: depth + 1) + } + // Children have already been bounded; validate this node's tag without recursive validation. + var node = value + if node.array != nil { node.array = [] } + if node.object != nil { node.object = [:] } + try node.validate() + } + + func text(_ value: LedgerValue?) throws -> String { + guard value?.kind == .string, let text = value?.text else { throw invalid() } + return text + } + func strings(_ value: LedgerValue?) throws -> [String] { + guard let items = value?.array else { throw invalid() } + return try items.map { try text($0) } + } + + func output(_ envelope: LedgerValue, index: Int) throws -> NativeComponentOutput { + let kind = DeclaredComponentKind(rawValue: input.record.kind)! + guard let fields = envelope.object, + Set(fields.keys).subtracting(["path", "rootRequirements"]) == [ + "route", "surface", "scope", "kind", "name", "component", "occurrences", + "recipients", "knownReaders", "keys", "selection", "value", + ], + fields["surface"] == .init(input.request.surface.rawValue), + fields["scope"] == .init(input.request.scope.rawValue), + fields["kind"] == .init(input.record.kind), fields["name"] == .init(input.record.name), + fields["component"] == .init(input.component), + fields["occurrences"] == .init(array: input.occurrences.map { .init(integer: $0) }), + fields["recipients"] == LedgerPayload.strings([input.request.surface.agent.rawValue]), + fields["knownReaders"] + == LedgerPayload.strings( + CapabilityRegistry.componentReaders(input.request, kind: kind).map(\.rawValue).sorted()), + let route = NativeComponentRoute(rawValue: try text(fields["route"])), + let value = fields["value"] + else { throw invalid(["identity"]) } + let keys = try strings(fields["keys"]) + let selection = try text(fields["selection"]) + let path = try fields["path"].map { try text($0) } + if let path { + do { + guard path != ".", try PathSafety.sanitizeSubpath(path) == path else { + throw invalid(["path"]) + } + } catch { throw invalid(["path"]) } + } + if selection != "cursorHook", fields["rootRequirements"] != nil { throw invalid() } + let content: NativeComponentOutput.Content + switch selection { + case "file": + guard keys.isEmpty, let path, [.command, .subagent].contains(kind), index == 0, + value.kind == .string + else { throw invalid() } + let expectedRoute: NativeComponentRoute + let suffix: String + switch (input.request.surface, kind) { + case (.claudeCode, .command): + expectedRoute = .claudeCommand + suffix = ".md" + case (.claudeCode, .subagent): + expectedRoute = .claudeAgent + suffix = ".md" + case (.geminiCLI, .command): + expectedRoute = .geminiCommand + suffix = ".toml" + case (.geminiCLI, .subagent): + expectedRoute = .geminiAgent + suffix = ".md" + case (.codexCLI, .subagent): + expectedRoute = .codexAgent + suffix = ".toml" + case (.cursorEditor, .command): + expectedRoute = .cursorCommand + suffix = ".md" + case (.cursorEditor, .subagent), (.cursorCLI, .subagent): + expectedRoute = .cursorAgent + suffix = ".md" + default: throw invalid(["route"]) + } + let nested = + (input.request.surface == .claudeCode && kind == .command) + || (input.request.surface == .geminiCLI && kind == .command) + || (input.request.surface == .codexCLI && kind == .subagent) + let name = try nested ? input.relativeName() : input.filename() + guard route == expectedRoute, path == name + suffix else { throw invalid(["path"]) } + let text = try text(value) + try input.budget.allocate(text.utf8.count, stage: "native contribution file") + content = .file(path: path, bytes: Data(text.utf8)) + case "key", "lsp": + guard path == nil, value.kind == .object else { throw invalid() } + let member: NativeComponentMember + switch (input.request.surface, kind, selection) { + case (.openCodeCLI, .command, "key"): + member = .openCodeCommand(input.record.name) + guard value.object?["template"]?.kind == .string, + value.object?["description"]?.kind == .string + else { throw invalid() } + case (.openCodeCLI, .subagent, "key"): + member = .openCodeAgent(input.record.name) + guard value.object?["system"]?.kind == .string, + value.object?["description"]?.kind == .string, + value.object?["mode"] == .init("subagent") + else { throw invalid() } + case (.openCodeCLI, .lspServer, "lsp"): member = .openCodeLSP(input.record.name) + case (.codexCLI, .subagent, "key"): + member = .codexAgent(input.record.name) + guard index == 1, + value + == .init(object: [ + "description": input.fields["description"]!, + "config_file": .init("./agents/" + input.record.name + ".toml"), + ]) + else { throw invalid() } + default: throw invalid(["route"]) + } + guard keys == member.keys, + route == (input.request.surface == .codexCLI ? .codexConfig : .openCodeConfig) + else { throw invalid(["route"]) } + if input.request.surface == .openCodeCLI, kind == .command || kind == .subagent { + let body = try text(value.object?[kind == .command ? "template" : "system"]) + guard value == .init(object: try OpenCodeAdapter.definition(input, prompt: body)) else { + throw invalid(["value"]) + } + } + content = .member(member, try template(envelope, selection: selection)) + case "hookGroup", "cursorHook": + guard kind == .hook, path == nil, keys.count == 2, keys[0] == "hooks", + keys[1] == input.fields["event"]?.object?["native"]?.text + else { throw invalid() } + let expected: NativeComponentRoute + switch input.request.surface { + case .claudeCode: expected = .claudeSettings + case .codexCLI: expected = .codexHooks + case .geminiCLI: expected = .geminiSettings + case .cursorEditor, .cursorCLI, .cursorCloud: expected = .cursorHooks + default: throw invalid(["route"]) + } + guard route == expected, (selection == "cursorHook") == (expected == .cursorHooks) else { + throw invalid(["route"]) + } + if selection == "cursorHook" { + guard fields["rootRequirements"] == .init(object: ["version": .init(integer: 1)]) else { + throw invalid() + } + } + content = .hook( + .init( + event: keys[1], layout: selection == "cursorHook" ? .cursorVersion1 : .group, + value: try template(envelope, selection: selection))) + case "orderedAppend": + guard kind == .permissions, input.request.surface == .openCodeCLI, + route == .openCodeConfig, path == nil, keys == ["permissions"], let rules = value.array + else { throw invalid() } + content = .orderedPermissions( + try rules.map { rule in + guard let fields = rule.object, Set(fields.keys) == ["action", "resource", "effect"], + let effect = NativeComponentPermission.Effect(rawValue: try text(fields["effect"])) + else { throw invalid() } + return .init( + tool: try text(fields["action"]), resource: try text(fields["resource"]), effect: effect + ) + }) + case "nativePolicy": + guard kind == .permissions, input.request.surface == .claudeCode, + route == .claudeSettings, path == nil, keys == ["permissions"], let policy = value.object, + Set(policy.keys).isSubset(of: ["allow", "ask", "deny", "defaultMode"]) + else { throw invalid() } + content = .claudePermissions( + .init( + allow: try policy["allow"].map { try strings($0) }, + ask: try policy["ask"].map { try strings($0) }, + deny: try policy["deny"].map { try strings($0) }, + defaultMode: try policy["defaultMode"].map { try text($0) })) + case "managedIgnore": + guard kind == .ignore, path == nil, keys.isEmpty, + (input.request.surface == .geminiCLI && route == .geminiIgnore) + || (input.request.surface == .cursorEditor && route == .cursorIgnore), + value == LedgerPayload.strings(try NativeIgnoreLayoutV1.patterns(input)) + else { throw invalid() } + content = .ignore(try strings(value)) + case "generatedPlugin": + guard kind == .lspServer, input.request.surface == .claudeCode, + route == .claudeSkillPlugin, path == input.record.name, keys.isEmpty, + Set(value.object?.keys.map { $0 } ?? []) == [".claude-plugin/plugin.json"] + else { throw invalid() } + _ = try input.filename() + content = .generatedLSPPlugin( + directory: input.record.name, manifestPath: ".claude-plugin/plugin.json", + manifest: try template(envelope, selection: selection)) + case "nativePlugin": + guard kind == .plugin, input.fields["mode"] == .init("native"), + path == input.record.name, keys.isEmpty, input.record.resources.count == 1, + let resource = input.record.resources.first, + let frozen = input.ledger.resources[resource], + input.record.recipients == [input.request.surface.agent] + else { throw invalid() } + let manifest: String + switch (input.request.surface, input.request.scope, route) { + case (.claudeCode, _, .claudeSkillPlugin): manifest = ".claude-plugin/plugin.json" + case (.cursorEditor, .user, .cursorLocalPlugin): manifest = ".cursor-plugin/plugin.json" + case (.geminiCLI, .user, .geminiExtension): manifest = "gemini-extension.json" + default: throw invalid(["route"]) + } + guard frozen.entries.contains(where: { $0.path == manifest && $0.kind == .file }), + value == .init(object: ["resource": .init(resource), "manifest": .init(manifest)]) + else { throw invalid(["resources"]) } + _ = try input.filename() + content = .nativePlugin(directory: input.record.name, resource: resource, manifest: manifest) + default: throw invalid(["selection"]) + } + return .init(route: route, content: content) + } + + func template(_ envelope: LedgerValue, selection: String) throws -> NativeComponentValue { + let value = envelope.object!["value"]! + var bindings: [NativeComponentBindingPlacement] = [] + var resources: [NativeComponentResourcePlacement] = [] + func string(_ value: LedgerValue, slot: NativeComponentSlot, resource: Bool = false) throws { + switch value.kind { + case .string, .literal: break + case .environment: + guard let name = value.text, !name.isEmpty else { + throw invalid(["bindings"]) + } + bindings.append(.init(slot: slot, binding: .environment(name))) + case .secret: + guard let name = value.text, !name.isEmpty else { throw invalid(["bindings"]) } + bindings.append(.init(slot: slot, binding: .secret(name))) + case .object where resource: + guard Set(value.object!.keys) == ["resource"], + let id = value.object?["resource"], id.kind == .string, + input.record.resources.contains(id.text!), input.ledger.resources[id.text!] != nil + else { throw invalid(["resources"]) } + resources.append(.init(slot: slot, resource: id.text!)) + default: throw invalid(["bindings"]) + } + } + func environment(_ value: LedgerValue?) throws { + guard let value else { return } + guard let fields = value.object else { throw invalid(["bindings"]) } + for (key, item) in fields.sorted(by: { $0.key < $1.key }) { + guard !key.isEmpty, !key.contains("="), + !["hookGroup", "cursorHook"].contains(selection) || MCPReferenceSyntax.isName(key) + else { throw invalid(["bindings"]) } + try string(item, slot: .environment(key)) + } + } + let program: [String: LedgerValue]? + if selection == "hookGroup" { + program = value.object?["hooks"]?.array?.first?.object?["command"]?.object?["program"]?.object + } else if selection == "cursorHook" { + program = value.object?["command"]?.object?["program"]?.object + } else { + program = nil + } + if selection == "hookGroup" || selection == "cursorHook" { + guard let program, + Set(program.keys).isSubset(of: [ + "executable", "arguments", "environment", "workingDirectory", + ]), + let executable = program["executable"], let arguments = program["arguments"]?.array + else { throw invalid(["program"]) } + try string(executable, slot: .executable, resource: true) + for (index, item) in arguments.enumerated() { try string(item, slot: .argument(index)) } + try environment(program["environment"]) + if let cwd = program["workingDirectory"] { + guard cwd.kind == .object else { throw invalid(["resources"]) } + try string(cwd, slot: .workingDirectory, resource: true) + } + } else if selection == "lsp" || selection == "generatedPlugin" { + let config: [String: LedgerValue]? + if selection == "generatedPlugin" { + config = + value.object?[".claude-plugin/plugin.json"]?.object?["lspServers"]?.object?[ + input.record.name]?.object + } else { + config = value.object + } + guard let config else { throw invalid(["program"]) } + if selection == "lsp" { + guard let command = config["command"]?.array, let executable = command.first else { + throw invalid(["program"]) + } + try string(executable, slot: .executable, resource: true) + for (index, item) in command.dropFirst().enumerated() { + try string(item, slot: .argument(index)) + } + } else { + guard let executable = config["command"] else { throw invalid(["program"]) } + try string(executable, slot: .executable, resource: true) + } + try environment(config["env"]) + } else { + func literal(_ value: LedgerValue) throws { + guard value.kind != .environment, value.kind != .secret else { throw invalid(["bindings"]) } + for item in value.array ?? [] { try literal(item) } + for item in value.object?.values ?? [:].values { try literal(item) } + } + try literal(value) + } + func symbolicCount(_ value: LedgerValue) -> Int { + if value.kind == .environment || value.kind == .secret { return 1 } + return (value.array ?? []).reduce(0) { $0 + symbolicCount($1) } + + (value.object?.values ?? [:].values).reduce(0) { $0 + symbolicCount($1) } + } + guard symbolicCount(value) == bindings.count else { throw invalid(["bindings"]) } + return .init( + envelope: envelope, bindings: bindings, resourcePlacements: resources, + requiresProgramConversion: ["hookGroup", "cursorHook", "lsp", "generatedPlugin"].contains( + selection), manifestProjection: selection == "generatedPlugin") + } +} diff --git a/Sources/Components/NativeComponentLayoutsV1.swift b/Sources/Components/NativeComponentLayoutsV1.swift index eb072c8..f70fe83 100644 --- a/Sources/Components/NativeComponentLayoutsV1.swift +++ b/Sources/Components/NativeComponentLayoutsV1.swift @@ -32,17 +32,41 @@ package enum NativeComponentLayoutsV1 { _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL], limits: LedgerLimits, surface: NativeClientSurface ) throws -> [ReplayedArtifact] { + let input = try input(lowering, ledger: ledger, resources: resources, limits: limits) + let record = input.record + let declared = input.request.surface + guard format(declared) == format(surface) else { + throw CoreError.invalidState("invalid version 1 native component renderer") + } + if record.kind == "plugin" { return try NativePluginLayoutV1.render(lowering, input) } + switch declared { + case .geminiCLI: return try GeminiAdapter.components(lowering, input) + case .openCodeCLI: return try OpenCodeAdapter.components(lowering, input) + case .codexCLI: return try CodexAdapter.components(lowering, input) + case .cursorEditor, .cursorCLI, .cursorCloud: + return try CursorAdapter.components(lowering, input) + case .claudeCode: return try ClaudeAdapter.components(lowering, input) + } + } + + static func input( + _ lowering: LockedLowering, ledger: ResolvedLedger, resources: [String: URL]? = nil, + limits: LedgerLimits + ) throws -> ComponentRenderInput { func invalid() -> CoreError { .invalidState("invalid version 1 native component layout") } - guard let layout = lowering.layout.object, + guard lowering.layout.kind == .object, let layout = lowering.layout.object, Set(layout.keys) == ["surface", "scope", "occurrences"], + layout["surface"]?.kind == .string, let declared = layout["surface"]?.text.flatMap(NativeClientSurface.init(rawValue:)), - format(declared) == format(surface), + layout["scope"]?.kind == .string, let scope = layout["scope"]?.text.flatMap(InstallScope.init(rawValue:)), lowering.format == format(declared), lowering.inputs.count == 1, let component = lowering.inputs.first, let record = ledger.components[component], + record.payload.kind == .object, + ledger.sources[record.source] != nil, ledger.sources[record.declaringSource] != nil, + record.resources.allSatisfy({ ledger.resources[$0] != nil }), lowering.resources == record.resources, - record.resources.allSatisfy({ resources[$0] != nil }), - let items = layout["occurrences"]?.array, + layout["occurrences"]?.kind == .array, let items = layout["occurrences"]?.array, items.allSatisfy({ $0.kind == .integer }), !items.isEmpty else { throw invalid() } let occurrences = items.compactMap(\.integer) @@ -59,16 +83,11 @@ package enum NativeComponentLayoutsV1 { let input = ComponentRenderInput( record: record, component: component, request: .init(surface: declared, scope: scope), occurrences: occurrences, - resources: resources, ledger: ledger, limits: limits) - try input.validateProfile() - if record.kind == "plugin" { return try NativePluginLayoutV1.render(lowering, input) } - switch declared { - case .geminiCLI: return try GeminiAdapter.components(lowering, input) - case .openCodeCLI: return try OpenCodeAdapter.components(lowering, input) - case .codexCLI: return try CodexAdapter.components(lowering, input) - case .cursorEditor, .cursorCLI, .cursorCloud: - return try CursorAdapter.components(lowering, input) - case .claudeCode: return try ClaudeAdapter.components(lowering, input) + resources: resources ?? [:], ledger: ledger, limits: limits) + if let resources, !record.resources.allSatisfy({ resources[$0] != nil }) { + throw invalid() } + try input.validateProfile() + return input } } diff --git a/Sources/Components/NativeComponentLowering.swift b/Sources/Components/NativeComponentLowering.swift index 9ebcc6f..c70e2c7 100644 --- a/Sources/Components/NativeComponentLowering.swift +++ b/Sources/Components/NativeComponentLowering.swift @@ -31,6 +31,18 @@ package enum NativeComponentRoute: String { case cursorCommand, cursorAgent, cursorIgnore case claudeSkillPlugin, cursorLocalPlugin, geminiExtension case claudeCommand, claudeAgent, claudeSettings, cursorHooks + + /// Structured shared documents only. Whole files, ignore blocks and plugin trees have their + /// concrete content shape on NativeComponentOutput and do not use a shared-document editor. + package var documentFormat: NativeDocumentFormat? { + switch self { + case .claudeSettings, .codexHooks, .cursorHooks: .json + case .codexConfig: .toml + case .geminiSettings: .jsonc(trailingCommas: false) + case .openCodeConfig: .jsonc(trailingCommas: true) + default: nil + } + } } package enum NativeComponentLowering { @@ -130,8 +142,36 @@ struct ComponentRenderInput { try budget.step(key.utf8.count) try admit(item, depth: depth + 1) } + var node = value + if node.array != nil { node.array = [] } + if node.object != nil { node.object = [:] } + try node.validate() } try admit(record.payload, depth: 0) + guard fields["name"] == .init(record.name) else { + throw issue(["name"], .invalid, "frozen payload and component identity do not match") + } + for key in ["model", "matcher", "description", "purpose", "mode"] where fields[key] != nil { + guard fields[key]?.kind == .string else { + throw issue([key], .invalid, "frozen native field requires a string") + } + } + for key in ["tools", "patterns"] where fields[key] != nil { + guard let values = fields[key]?.array, values.allSatisfy({ $0.kind == .string }) else { + throw issue([key], .invalid, "frozen native field requires strings") + } + } + if let timeout = fields["timeoutSeconds"] { + guard timeout.kind == .integer, timeout.integer.map({ $0 > 0 }) == true else { + throw issue(["timeoutSeconds"], .invalid, "frozen native timeout requires positive seconds") + } + } + if let native = fields["native"] { + guard let clients = native.object, + clients[request.surface.agent.rawValue] == nil + || clients[request.surface.agent.rawValue]?.kind == .object + else { throw issue(["native"], .invalid, "frozen native configuration requires objects") } + } guard record.recipients.contains(request.surface.agent) else { throw issue(["recipients"], .invalid, "component does not target this recipient") } diff --git a/Sources/Components/NativeProgramV1.swift b/Sources/Components/NativeProgramV1.swift index b25311e..064c190 100644 --- a/Sources/Components/NativeProgramV1.swift +++ b/Sources/Components/NativeProgramV1.swift @@ -9,6 +9,32 @@ package enum NativeProgramV1 { /// of the applying process's environment. Gemini's pinned Unix runner selects bash itself. package enum CommandShell { case posix } + /// Frozen program shape is still the typed declaration's run, not native settings data. + static func validateFrozenRun(_ input: ComponentRenderInput) throws { + guard let run = input.fields["run"]?.object, + Set(run.keys).subtracting(["workingDirectory"]) == [ + "executable", "arguments", "environment", + ], + run["executable"]?.kind == .string, run["executable"]?.text?.isEmpty == false, + let arguments = run["arguments"]?.array, arguments.allSatisfy({ $0.kind == .string }), + let environment = run["environment"]?.object, + environment.allSatisfy({ + !$0.key.isEmpty && !$0.key.contains("=") && !$0.key.utf8.contains(0) + && [.literal, .environment, .secret].contains($0.value.kind) + && ($0.value.kind == .literal || $0.value.text?.isEmpty == false) + }) + else { throw input.issue(["run"], .invalid, "invalid frozen typed native program") } + if let cwd = run["workingDirectory"] { + guard let fields = cwd.object, Set(fields.keys).isSubset(of: ["path", "source"]), + fields["path"]?.kind == .string, fields["path"]?.text?.isEmpty == false, + fields["source"] == nil || fields["source"]?.kind == .string + else { + throw input.issue( + ["run", "workingDirectory"], .invalid, "invalid frozen directory resource") + } + } + } + static func executable(_ run: [String: LedgerValue], input: ComponentRenderInput) throws -> LedgerValue { @@ -40,9 +66,8 @@ package enum NativeProgramV1 { } } - /// E calls this only inside its private render closure, with the already obtained Core values. - /// This converts hookGroup/LSP intentions emitted by the concrete versioned profiles. - package static func stagedValue( + /// The strict contribution decoder supplies the envelope; package callers use its typed value. + static func stagedValue( _ envelope: LedgerValue, bindings: RuntimeBindingValues, environment: RuntimeEnvironment, resourcePaths: [String: String], budget: NativeDocumentBudget, codexCommandShell: CommandShell? = nil, cursorCommandShell: CommandShell? = nil @@ -145,7 +170,8 @@ package enum NativeProgramV1 { var words: [String] = [] if let cwd = run["workingDirectory"] { // Working directories are frozen resources; original authored paths never become native paths. - guard let resource = cwd.object?["resource"]?.text, let final = resourcePaths[resource] + guard let resource = cwd.object?["resource"]?.text, let final = resourcePaths[resource], + !final.isEmpty else { throw issue( ["run", "workingDirectory"], "final registered directory placement is required") @@ -229,6 +255,8 @@ package enum NativeProgramV1 { case .object: var fields: [String: NativeValue] = [:] for (key, value) in value.object!.sorted(by: { $0.key < $1.key }) { + try budget.allocate(key.utf8.count, stage: "native program key") + try budget.step(key.utf8.count) fields[key] = try convert(value, path: path + [key], depth: depth + 1) } return .object(fields) diff --git a/Tests/ComponentsTests/NativeComponentTests.swift b/Tests/ComponentsTests/NativeComponentTests.swift index 8d8c5b1..212d6cc 100644 --- a/Tests/ComponentsTests/NativeComponentTests.swift +++ b/Tests/ComponentsTests/NativeComponentTests.swift @@ -72,6 +72,27 @@ struct NativeComponentTests { try replay(ledger, fixture) { output in let envelopes = try #require(output[0].values?.array) #expect(envelopes.count == 2) + let contribution = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: output, limits: .standard) + #expect(contribution.occurrences == linked[0].origins.map(\.occurrence)) + #expect(contribution.outputs.count == 2) + guard case .file(let path, let bytes) = contribution.outputs[0].content, + case .member(let member, let registration) = contribution.outputs[1].content + else { + Issue.record("missing coupled typed role outputs") + return + } + #expect(path == "researcher.toml") + #expect(member.keys == ["agents", "researcher"]) + #expect(contribution.outputs.map(\.route) == [.codexAgent, .codexConfig]) + #expect(contribution.outputs[1].route.documentFormat == .toml) + #expect( + try registration.referenceValue(budget: budget()) + == .object([ + "description": .string("Research-focused role."), + "config_file": .string("./agents/researcher.toml"), + ])) + #expect(bytes == Data(try #require(envelopes[0].object?["value"]?.text).utf8)) let text = try #require(envelopes[0].object?["value"]?.text) let doc = try NativeDocument(bytes: Data(text.utf8), format: .toml, budget: budget()) #expect( @@ -153,13 +174,19 @@ struct NativeComponentTests { let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) #expect(!String(decoding: encoded, as: UTF8.self).contains("private staged fixture")) try replay(ledger, fixture) { output in - let envelope = try #require(output[0].values) + let contribution = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: output, limits: .standard) + guard case .hook(let concreteHook) = contribution.outputs[0].content else { + Issue.record("missing typed native group") + return + } + #expect( + concreteHook.value.resourcePlacements.map(\.slot) == [.executable, .workingDirectory]) let placements = Dictionary( uniqueKeysWithValues: frozen.ledger.components.values.first!.resources.enumerated().map { ($0.element, $0.offset == 0 ? "/registered/scripts/check" : "/registered/working") }) - let native = try NativeProgramV1.stagedValue( - envelope, + let native = try concreteHook.value.stagedValue( bindings: RuntimeBindingValues(["fixture/token": Data("private staged fixture".utf8)]), environment: fixture.environment, resourcePaths: placements, budget: budget(), codexCommandShell: .posix) @@ -203,8 +230,20 @@ struct NativeComponentTests { let environment = RuntimeEnvironment( projectDirectory: fixture.project, homeDirectory: fixture.home, environment: ["SOURCE": "fixture value"]) - let value = try NativeProgramV1.stagedValue( - envelope, bindings: RuntimeBindingValues([:]), environment: environment, resourcePaths: [:], + let contribution = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: output, limits: .standard) + guard case .member(let member, let template) = contribution.outputs[0].content else { + Issue.record("missing typed LSP member") + return + } + #expect(member.keys == ["lsp", "fixture"]) + #expect(template.bindings.count == 1) + #expect(template.bindings[0].slot == .environment("TOKEN")) + #expect(template.bindings[0].binding == .environment("SOURCE")) + #expect(template.resourcePlacements.isEmpty) + #expect(throws: NativeComponentIssue.self) { try template.referenceValue(budget: budget()) } + let value = try template.stagedValue( + bindings: RuntimeBindingValues([:]), environment: environment, resourcePaths: [:], budget: budget()) #expect( value @@ -217,6 +256,28 @@ struct NativeComponentTests { ]), "extensions": .array([.string(".fixture")]), ])) + var corrupted = ledger + let component = try #require(ledger.lowerings[0].inputs.first) + var payload = try #require(corrupted.components[component]?.payload.object) + payload["initializationOptions"] = .init(object: [ + "hidden": .init("fixture/hidden", kind: .secret) + ]) + corrupted.components[component]?.payload = .init(object: payload) + var changed = output + var fields = try #require(envelope.object) + var native = try #require(fields["value"]?.object) + native["initialization"] = payload["initializationOptions"] + fields["value"] = .init(object: native) + changed[0].values = .init(object: fields) + corrupted.lowerings[0].artifacts = try changed.map { try $0.digest(limits: .standard) } + do { + _ = try NativeComponentLayoutsV1.contribution( + corrupted.lowerings[0], ledger: corrupted, artifacts: changed, limits: .standard) + Issue.record("accepted a symbolic binding inside arbitrary native data") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["bindings"]) + #expect(!issue.description.contains("fixture/hidden")) + } } } @@ -243,6 +304,27 @@ struct NativeComponentTests { try FileManager.default.removeItem(at: fixture.project) try replay(ResolvedLedgerCodec.decode(bytes, limits: .standard), fixture) { output in #expect(output[0].values?.object?["route"]?.text == "claudeSkillPlugin") + let contribution = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: output, limits: .standard) + guard + case .nativePlugin(let directory, let resource, let manifest) = contribution.outputs[0] + .content + else { + Issue.record("missing typed frozen plugin") + return + } + #expect(directory == "fixture-plugin") + #expect(manifest == ".claude-plugin/plugin.json") + let entry = try #require( + contribution.resources[resource]?.entries.first { $0.path == "scripts/check" }) + #expect(entry.executable) + var mismatchedResource = ledger + mismatchedResource.resources[resource]?.hash = "sha256:" + String(repeating: "0", count: 64) + #expect(throws: NativeComponentIssue.self) { + try NativeComponentLayoutsV1.contribution( + mismatchedResource.lowerings[0], ledger: mismatchedResource, artifacts: output, + limits: .standard) + } let root = try #require(output[1].tree) #expect( try String(contentsOf: root.appendingPathComponent("commands/review.md"), encoding: .utf8) @@ -317,6 +399,13 @@ struct NativeComponentTests { ledger.lowerings = [try lower(linked[0], frozen, surface: surface)] ledger = try prepared(ledger, fixture) try replay(ledger, fixture) { output in + let contribution = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: output, limits: .standard) + guard case .ignore(let patterns) = contribution.outputs[0].content else { + Issue.record("missing typed context ignore block") + return + } + #expect(patterns == ["private/**", "!private/public.txt"]) #expect(output[0].values?.object?["selection"]?.text == "managedIgnore") #expect( output[0].values?.object?["value"] @@ -396,6 +485,29 @@ struct NativeComponentTests { try replay(ledger, fixture) { output in #expect(output[0].values?.object?["value"]?.text == "Review source.\n") #expect(output[0].values?.object?["route"]?.text == "cursorCommand") + for (name, reason) in [ + ("../escape", NativeAdapterIssue.Reason.invalid), ("nested/review", .unverified), + ] { + var corrupted = ledger + let owner = try #require(corrupted.lowerings[0].inputs.first) + corrupted.components[owner]?.name = name + var payload = try #require(corrupted.components[owner]?.payload.object) + payload["name"] = .init(name) + corrupted.components[owner]?.payload = .init(object: payload) + var fields = try #require(output[0].values?.object) + fields["name"] = .init(name) + fields["path"] = .init(name + ".md") + var artifacts = output + artifacts[0].values = .init(object: fields) + corrupted.lowerings[0].artifacts = try artifacts.map { try $0.digest(limits: .standard) } + do { + _ = try NativeComponentLayoutsV1.contribution( + corrupted.lowerings[0], ledger: corrupted, artifacts: artifacts, limits: .standard) + Issue.record("accepted an unadmitted native filename") + } catch let issue as NativeComponentIssue { + #expect(issue.reason == reason) + } + } } try fixture.write( #"{"name":"extension-fixture","version":"1.0.0"}"#, to: "extension/gemini-extension.json", @@ -608,17 +720,30 @@ struct NativeComponentTests { #expect(!String(decoding: encoded, as: UTF8.self).contains("staged hook value")) try replay(ledger, fixture) { output in let envelope = try #require(output[0].values) + let contribution = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: output, limits: .standard) + guard case .hook(let hook) = contribution.outputs[0].content else { + Issue.record("missing typed native hook") + return + } + #expect( + hook.keys == ["hooks", surface == .claudeCode ? "PreToolUse" : "beforeShellExecution"]) + #expect(hook.layout == (surface == .claudeCode ? .group : .cursorVersion1)) + #expect(contribution.recipients == [surface.agent]) + #expect( + contribution.knownReaders == (surface == .claudeCode ? [.claudeCode, .cursor] : [.cursor])) + #expect(hook.value.bindings.count == 1) if surface == .cursorEditor { #expect(envelope.object?["rootRequirements"]?.object?["version"]?.integer == 1) #expect(envelope.object?["value"]?.object?["matcher"]?.text == "curl|wget") #expect(throws: NativeComponentIssue.self) { - try NativeProgramV1.stagedValue( - envelope, bindings: .init([:]), environment: fixture.environment, resourcePaths: [:], + try hook.value.stagedValue( + bindings: .init([:]), environment: fixture.environment, resourcePaths: [:], budget: budget()) } } - let native = try NativeProgramV1.stagedValue( - envelope, bindings: .init(["fixture/hook": Data("staged hook value".utf8)]), + let native = try hook.value.stagedValue( + bindings: .init(["fixture/hook": Data("staged hook value".utf8)]), environment: fixture.environment, resourcePaths: [:], budget: budget(), cursorCommandShell: .posix) guard case .object(let object) = native else { @@ -716,12 +841,29 @@ struct NativeComponentTests { #expect(envelope.object?["selection"]?.text == "generatedPlugin") #expect(envelope.object?["route"]?.text == "claudeSkillPlugin") let id = try #require(frozen.ledger.components.values.first?.resources.first) - let materialized = try NativeProgramV1.stagedValue( - envelope, bindings: .init(["fixture/lsp": Data("staged LSP value".utf8)]), + let contribution = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: output, limits: .standard) + guard + case .generatedLSPPlugin(let directory, let manifestPath, let value) = contribution.outputs[ + 0 + ].content + else { + Issue.record("missing typed generated plugin") + return + } + #expect(directory == "fixture-lsp") + #expect(manifestPath == ".claude-plugin/plugin.json") + #expect(value.bindings.count == 1) + #expect(value.bindings[0].slot == .environment("TOKEN")) + #expect(value.bindings[0].binding == .secret("fixture/lsp")) + #expect(value.resourcePlacements.count == 1) + #expect(value.resourcePlacements[0].slot == .executable) + #expect(value.resourcePlacements[0].resource == id) + let materialized = try value.stagedValue( + bindings: .init(["fixture/lsp": Data("staged LSP value".utf8)]), environment: fixture.environment, resourcePaths: [id: "/registered/bin/server"], budget: budget()) - guard case .object(let files) = materialized, - case .object(let manifest) = files[".claude-plugin/plugin.json"], + guard case .object(let manifest) = materialized, case .object(let servers) = manifest["lspServers"], case .object(let config) = servers["fixture-lsp"] else { @@ -741,8 +883,8 @@ struct NativeComponentTests { #expect(config["env"] == .object(["TOKEN": .string("staged LSP value")])) for invalid in [Data([0xff]), Data([0]), Data("${CLAUDE_PLUGIN_ROOT}".utf8)] { do { - _ = try NativeProgramV1.stagedValue( - envelope, bindings: .init(["fixture/lsp": invalid]), environment: fixture.environment, + _ = try value.stagedValue( + bindings: .init(["fixture/lsp": invalid]), environment: fixture.environment, resourcePaths: [id: "/registered/bin/server"], budget: budget()) Issue.record("accepted a nonliteral staged native value") } catch let issue as NativeComponentIssue { @@ -1093,6 +1235,155 @@ struct NativeComponentTests { } } + @Test func strictContributionRejectsForgedIdentityRoutesSlotsAndUnsealedOutput() throws { + let fixture = try LinkFixture() + try fixture.write("#!/bin/sh\n# never executed\n", to: "scripts/check", base: fixture.project) + let item: [String: Any] = [ + "kind": "hook", "name": "guard", "agents": ["claude-code"], + "event": ["native": "PreToolUse"], + "run": [ + "executable": "./scripts/check", "environment": ["TOKEN": ["secret": "fixture/token"]], + ], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .claudeCode)] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { artifacts in + let original = try #require(artifacts[0].values?.object) + var wrongOwner = original + wrongOwner["component"] = .init("unrelated-owner") + var wrongOccurrence = original + wrongOccurrence["occurrences"] = .init(array: [.init(integer: 999)]) + var wrongReaders = original + wrongReaders["knownReaders"] = LedgerPayload.strings(["claude-code"]) + var wrongRoute = original + wrongRoute["route"] = .init("cursorHooks") + var extra = original + extra["arbitraryPatch"] = .init("SENSITIVE_CORRUPTION") + var wrongBinding = original + var value = try #require(original["value"]?.object) + var hook = try #require(value["hooks"]?.array?.first?.object) + var program = try #require(hook["command"]?.object?["program"]?.object) + program["environment"] = .init(object: ["TOKEN": .init("SENSITIVE_CORRUPTION", kind: .secret)] + ) + hook["command"] = .init(object: ["program": .init(object: program)]) + value["hooks"] = .init(array: [.init(object: hook)]) + wrongBinding["value"] = .init(object: value) + var wrongResource = original + program["executable"] = .init(object: ["resource": .init("foreign-resource")]) + hook["command"] = .init(object: ["program": .init(object: program)]) + value["hooks"] = .init(array: [.init(object: hook)]) + wrongResource["value"] = .init(object: value) + for fields in [ + wrongOwner, wrongOccurrence, wrongReaders, wrongRoute, extra, wrongBinding, wrongResource, + ] { + var changed = artifacts + changed[0].values = .init(object: fields) + var resealed = ledger + // Even a supplied new digest cannot turn arbitrary metadata/slots into the frozen profile. + resealed.lowerings[0].artifacts = try changed.map { try $0.digest(limits: .standard) } + do { + _ = try NativeComponentLayoutsV1.contribution( + resealed.lowerings[0], ledger: resealed, artifacts: changed, limits: .standard) + Issue.record("accepted forged native component output") + } catch let issue as NativeComponentIssue { + #expect(issue.reason == .invalid) + #expect(!issue.description.contains("SENSITIVE_CORRUPTION")) + } + } + var invalidProgram = ledger + let owner = try #require(invalidProgram.lowerings[0].inputs.first) + var payload = try #require(invalidProgram.components[owner]?.payload.object) + var run = try #require(payload["run"]?.object) + run["executable"] = .init("SENSITIVE_CORRUPTION", kind: .secret) + payload["run"] = .init(object: run) + invalidProgram.components[owner]?.payload = .init(object: payload) + do { + _ = try NativeComponentLayoutsV1.contribution( + invalidProgram.lowerings[0], ledger: invalidProgram, artifacts: artifacts, + limits: .standard) + Issue.record("accepted a non-string frozen executable") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["run"]) + #expect(!issue.description.contains("SENSITIVE_CORRUPTION")) + } + var unsealed = ledger + unsealed.lowerings[0].artifacts = [] + #expect(throws: CoreError.self) { + try NativeComponentLayoutsV1.contribution( + unsealed.lowerings[0], ledger: unsealed, artifacts: artifacts, limits: .standard) + } + #expect(throws: NativeComponentIssue.self) { + var changed = artifacts + changed[0].values = .init(object: wrongOwner) + return try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: changed, limits: .standard) + } + var oversized = artifacts + var large = original + large["value"] = .init(String(repeating: "x", count: 8192)) + oversized[0].values = .init(object: large) + var limits = LedgerLimits.standard + limits.encodedBytes = 4096 + #expect(throws: NativeDocumentBudget.Failure.self) { + try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: oversized, limits: limits) + } + } + } + + @Test func strictContributionKeepsOrderedPolicyAndCategoryOwnershipDistinct() throws { + let fixture = try LinkFixture() + let items: [[String: Any]] = [ + [ + "kind": "permissions", "name": "ordered", "agents": ["opencode"], + "rules": [ + ["effect": "deny", "operation": ["tool": "read"], "pattern": "*"], + ["effect": "allow", "operation": ["tool": "read"], "pattern": "public/**"], + ], + ], + [ + "kind": "permissions", "name": "categories", "agents": ["claude-code"], "rules": [], + "native": [ + "claude-code": ["allow": [], "deny": ["Read(private/**)"], "defaultMode": "plan"] + ], + ], + ] + let (linked, frozen) = try freeze(items, fixture) + var ledger = frozen.ledger + ledger.lowerings = try linked.enumerated().map { + try lower( + $0.element, frozen, surface: $0.offset == 0 ? .openCodeCLI : .claudeCode, + id: "policy-" + String($0.offset)) + } + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { artifacts in + let ordered = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: [artifacts[0]], limits: .standard) + guard case .orderedPermissions(let rules) = ordered.outputs[0].content else { + Issue.record("missing typed ordered policy") + return + } + #expect(rules.map(\.tool) == ["read", "read"]) + #expect(rules.map(\.resource) == ["*", "public/**"]) + #expect(rules.map(\.effect) == [.deny, .allow]) + #expect(ordered.outputs[0].route.documentFormat == .jsonc(trailingCommas: true)) + let categorized = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[1], ledger: ledger, artifacts: [artifacts[1]], limits: .standard) + guard case .claudePermissions(let policy) = categorized.outputs[0].content else { + Issue.record("missing typed categorized policy") + return + } + #expect(policy.allow == []) + #expect(policy.ask == nil) + #expect(policy.deny == ["Read(private/**)"]) + #expect(policy.defaultMode == "plan") + #expect(ordered.component != categorized.component) + #expect(ordered.occurrences != categorized.occurrences) + } + } + private var platform: DeclarationPlatform { #if os(macOS) .macOS @@ -1145,7 +1436,16 @@ struct NativeComponentTests { ) throws { try LedgerReplay.withReplay( ledger, store: fixture.store, roots: [:], limits: .standard, - renderers: NativeComponentLayoutsV1.renderers(limits: .standard), body) + renderers: NativeComponentLayoutsV1.renderers(limits: .standard) + ) { artifacts in + for lowering in ledger.lowerings { + let names = Set(lowering.artifacts.map(\.name)) + _ = try NativeComponentLayoutsV1.contribution( + lowering, ledger: ledger, artifacts: artifacts.filter { names.contains($0.name) }, + limits: .standard) + } + try body(artifacts) + } } private func budget() -> NativeDocumentBudget { .init( From ae464cf528e862ee351e591cfba2d4641e963629 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:23:13 +0800 Subject: [PATCH 090/171] feat: expose immutable lifecycle inspection and outcomes --- Documentation/Architecture/Updates.md | 77 ++++ Sources/AgentsCore/LedgerStateStore.swift | 3 + Sources/AgentsCore/TransactionOutcome.swift | 2 + Sources/AgentsCore/WatchOperations.swift | 33 +- .../AgentsUpdates/ComponentDiscovery.swift | 92 ++++ Sources/AgentsUpdates/ScopeInspection.swift | 289 ++++++++++++ .../SourceImportOperations.swift | 263 +++++++++++ Sources/AgentsUpdates/UpdateCompletion.swift | 83 ++++ Sources/AgentsUpdates/UpdateModels.swift | 1 + Sources/AgentsUpdates/UpdateOperations.swift | 14 +- Sources/AgentsUpdates/UpdatePlan.swift | 241 ++++++++-- Sources/AgentsUpdates/UpdateReporting.swift | 12 +- Sources/AgentsUpdates/UpdateRequest.swift | 8 +- Sources/Components/ArtifactAggregation.swift | 135 +++++- .../Components/DeploymentConstruction.swift | 21 +- Sources/Components/LedgerImpact.swift | 70 ++- .../IndexedArtifactLifecycleTests.swift | 40 ++ .../LifecycleCompositionTests.swift | 15 +- .../PublicInspectionTests.swift | 412 ++++++++++++++++++ .../UpdateTransactionTests.swift | 41 +- 20 files changed, 1774 insertions(+), 78 deletions(-) create mode 100644 Sources/AgentsUpdates/ComponentDiscovery.swift create mode 100644 Sources/AgentsUpdates/ScopeInspection.swift create mode 100644 Sources/AgentsUpdates/SourceImportOperations.swift create mode 100644 Sources/AgentsUpdates/UpdateCompletion.swift create mode 100644 Tests/AgentsUpdatesTests/PublicInspectionTests.swift diff --git a/Documentation/Architecture/Updates.md b/Documentation/Architecture/Updates.md index aff11f5..62e1e3e 100644 --- a/Documentation/Architecture/Updates.md +++ b/Documentation/Architecture/Updates.md @@ -125,3 +125,80 @@ renderCompletion(receipt) `render` and `renderCompletion` belong to the consumer. Completion is reported only after the closure returns. + +## Public Inspection and Interactive Consumers + +`UpdateOperations.inspect` captures the Manifest document (including typed values, +source maps and NodeIDs), complete declaration, v2 source/component/occurrence/group +and resource descriptions, deployments, watch state and recovery diagnostics under +one admitted read footprint. Public record IDs join these immutable descriptions; +logical selections remain independent of revisions and temporary directories. +The report excludes retained content objects and complete native file bytes. +Deployment drift compares owned content or validates the physical private receipt. +An unverified observation is explicit. `readLocations` contains actual state, +source, retained resource and deployment URLs, including missing leaves. + +A pending journal returns recovery diagnostics without reading inconsistent +configuration. Inspection does not recover, resolve sources, call a provider or +create persistent files. It is suitable for App refresh and filesystem invalidation. + +Pass a component's `selection` in `UpdateRequest.selections` to update or remove +that logical component. An occurrence selects that contribution when it is the +sole contribution; a coalesced component requires complete-component selection or +a typed declaration-reference edit. The captured document/ledger generation is +revalidated before linking. Bare names that match multiple logical components +report ambiguity. Unselected components keep their recorded projection and pins. + +`UpdateOperations.discover` resolves an explicit complete declaration, including +exported groups, in B's temporary source session without native lowering. It +returns symbolic descriptions, all exact source revisions, stable identities and +actual local read locations. `ComponentDiscovery.updateRequest()` carries the +captured declaration identity and discovered graph fingerprint into preparation; +a changed source fails before callback delivery. File enumeration and native input +conversion remain with their domain/import owners. + +`SourceImportOperations.inspect` consumes an explicit existing importer profile, +root, document, selection and supplied resource locations. Its immutable report +preserves producer coordinates, pins/integrity, ordered sources, selections, +bindings, unconverted diagnostics, resource preservation obligations and foreign +deployment claims. `updateRequest(in:)` merges admitted canonical intent into the +captured scope declaration. Preparation rereads the same inputs, compares the +proposal, captures their private freshness evidence and validates it again around +publication. Unresolved conversion/binding diagnostics stop submission; foreign +claims do not establish ownership. Input content that would overwrite its own +local authoring source requires independent preservation before submission. + +Pass D's `RuntimeBindingProvider` as `bindingProvider:` to public +`withPreparedUpdate`, `perform` or full `restore`. Preparation and preview never +call it. The provider resolves bounded data only during private staging. Native +reports separate intended recipients from the verified physical object's reader +union and retain sensitivity from an existing shared receipt, including when the +selected change has no bindings. + +`UpdateOperations.perform` returns `UpdateCompletion` after the whole synchronous +operation and outer cleanup have returned. It preserves the result/error and +`unchanged`, `rolledBack`, `committed` or `recoveryRequired` disposition, reports +recovery before callback delivery, and includes pending recovery/cleanup evidence. +A durable commit remains committed when cleanup is pending. Render the disposition +before deciding whether to retry. The terminal value is Sendable when its consumer +result is Sendable; the prepared handle is always invalidated before it returns. + +```swift +let displayed = try UpdateOperations.preview(request, environment: environment) +let completion = UpdateOperations.perform(request, environment: environment, + bindingProvider: bindings +) { prepared in + try prepared.apply(ifUnchangedFrom: displayed.displayedFingerprint) +} +``` + +The closure runs on one thread and must not await. A UI may await the completed +operation's result, refresh a changed candidate and reprepare for confirmation. +Agents CLI restores the full scope once with `UpdateOperations.restore`; domain +consumers continue using their restricted lifecycle methods. + +Watch consumers can pass a displayed `WatchStatus` to `WatchOperations.seen`. +The existing writer revalidates both normalized source identity and the exact Git +commit or artifact digest map before retention and watch-state publication. A +redirected alias or changed content requires refresh. Status and diff never deploy +configuration. diff --git a/Sources/AgentsCore/LedgerStateStore.swift b/Sources/AgentsCore/LedgerStateStore.swift index d6c41b1..c189a33 100644 --- a/Sources/AgentsCore/LedgerStateStore.swift +++ b/Sources/AgentsCore/LedgerStateStore.swift @@ -45,6 +45,9 @@ extension StateStore { roots["instructions-" + agent.rawValue] = file.deletingLastPathComponent() } } + for route in NativeTargetRoute.allCases { + roots[route.root] = try? route.logicalDirectory(environment).resolvingSymlinksInPath() + } return roots } diff --git a/Sources/AgentsCore/TransactionOutcome.swift b/Sources/AgentsCore/TransactionOutcome.swift index 64142c2..08fe292 100644 --- a/Sources/AgentsCore/TransactionOutcome.swift +++ b/Sources/AgentsCore/TransactionOutcome.swift @@ -6,5 +6,7 @@ package final class TransactionOutcome { package var disposition: Disposition = .unchanged var journalID: UUID? + package var publicationStarted: Bool { journalID != nil } + package init() {} } diff --git a/Sources/AgentsCore/WatchOperations.swift b/Sources/AgentsCore/WatchOperations.swift index 00290e0..573aca1 100644 --- a/Sources/AgentsCore/WatchOperations.swift +++ b/Sources/AgentsCore/WatchOperations.swift @@ -107,7 +107,9 @@ public struct WatchOperations: Sendable { @discardableResult public func seen( - _ source: String, revision: String? = nil, scope: InstallScope = .project, + _ source: String, revision: String? = nil, ifCurrentIs expected: WatchSeen? = nil, + ifSourceIs expectedSource: String? = nil, + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> WatchChange { let store = StateStore(scope: scope, environment: environment) @@ -119,13 +121,30 @@ public struct WatchOperations: Sendable { let alias = try subscription(source, declaration: declaration, environment: environment) let declared = declaration.sources[alias]! let id = try declared.identity(environment: environment) - let current = try acknowledge(declared, revision: revision, store: store) + guard expectedSource == nil || expectedSource == id else { + throw CoreError.invalidState("watch source changed; refresh before acknowledging") + } + let current = try acknowledge(declared, revision: revision, expected: expected, store: store) + guard expected == nil || expected == current else { + throw CoreError.invalidState("watch content changed; refresh before acknowledging") + } watch.sources[id] = WatchSourceState(seen: current) try commit(nil, watch: watch, lock: lock, store: store, baseline: baseline) return WatchChange(alias: alias, sourceID: id, seen: current) } } + /// Acknowledges exactly the displayed source/content pair, revalidated under the writer lock. + @discardableResult + public func seen( + _ status: WatchStatus, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> WatchChange { + try seen( + status.alias, ifCurrentIs: status.current, ifSourceIs: status.sourceID, + scope: scope, environment: environment) + } + /// Removes only the subscription and baseline. Source declarations and installations remain. @discardableResult public func remove( @@ -198,12 +217,15 @@ public struct WatchOperations: Sendable { } private func acknowledge( - _ source: SourceDeclaration, revision: String?, store: StateStore + _ source: SourceDeclaration, revision: String?, expected: WatchSeen? = nil, store: StateStore ) throws -> WatchSeen { let cache = SourceCache(store: store, checkpoint: checkpoint) let id = try source.identity(environment: store.environment) if source.kind != .wellKnown { let head = try cache.watchRevision(source, revision: revision) + guard expected == nil || expected == .revision(head) else { + throw CoreError.invalidState("watch content changed; refresh before acknowledging") + } try checkpoint("watch.mirror.fetched") try cache.retainWatchRevision(sourceID: id, source: source.location, revision: head) return .revision(head) @@ -212,6 +234,11 @@ public struct WatchOperations: Sendable { throw CoreError.invalidSource("well-known subscriptions do not accept Git revisions") } let artifacts = try artifacts(source) + let current = WatchSeen.artifacts( + Dictionary(uniqueKeysWithValues: artifacts.map { ($0.name, $0.artifact.digest) })) + guard expected == nil || expected == current else { + throw CoreError.invalidState("watch content changed; refresh before acknowledging") + } let root = FileManager.default.temporaryDirectory.appendingPathComponent( "agents-watch-" + UUID().uuidString) try FileSystem.createDirectory(at: root) diff --git a/Sources/AgentsUpdates/ComponentDiscovery.swift b/Sources/AgentsUpdates/ComponentDiscovery.swift new file mode 100644 index 0000000..3589be0 --- /dev/null +++ b/Sources/AgentsUpdates/ComponentDiscovery.swift @@ -0,0 +1,92 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation + +/// A complete explicit selection graph resolved in a temporary source session, before deployment. +public struct ComponentDiscovery: Sendable { + public let components: [ComponentInspection] + public let sourceRevisions: [String: [String]] + public let fingerprint: String + public let readLocations: [URL] + private let declaration: Declaration + private let declarationDigest: String + + /// Carries both the captured scope and exact discovered content into ordinary preparation. + public func updateRequest() -> UpdateRequest { + var request = UpdateRequest( + operation: .declaration(declaration), + expectedDeclarationDigest: declarationDigest) + request.expectedDiscoveryFingerprint = fingerprint + return request + } + + init( + components: [ComponentInspection], sourceRevisions: [String: [String]], fingerprint: String, + readLocations: [URL], declaration: Declaration, declarationDigest: String + ) { + self.components = components + self.sourceRevisions = sourceRevisions + self.fingerprint = fingerprint + self.readLocations = readLocations + self.declaration = declaration + self.declarationDigest = declarationDigest + } +} + +extension UpdateOperations { + /// Resolves authored selections and exported groups for every linked family. It neither lowers + /// native output nor executes source code, calls a binding provider, retains caches or recovers. + public static func discover( + _ declaration: Declaration, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> ComponentDiscovery { + let store = StateStore(scope: scope, environment: environment) + return try store.withReadLock { + let baseline = try StatePrecondition(store: store) + let previous = try store.readDeclaration(prepared: baseline) + _ = try store.readLedger(prepared: baseline) + _ = try store.readWatch(prepared: baseline) + let original = try store.declarationDocument(prepared: baseline) + let change = try store.planDeclaration(declaration, replacing: previous, prepared: baseline) + let document = try DeclarationDocument( + bytes: change.map { Array($0.bytes) } ?? original?.bytes ?? Array("version: 1\n".utf8), + identity: DocumentIdentity(store.declarationURL.path)) + #if os(macOS) + let platform = DeclarationPlatform.macOS + #else + let platform = DeclarationPlatform.linux + #endif + return try ComponentLinker.withLinkedComponents( + document: document, store: store, platform: platform + ) { linked, session in + let frozen = try LedgerFreeze.freezeWithSources( + linked, session: session, + locations: .init( + sources: UpdatePlan.sourceLocations(linked, declaration: declaration, store: store)), + limits: .standard) + let ledger = frozen.ledger + let fingerprint = try LedgerImpact.discoveryFingerprint(ledger, roots: store.ledgerRoots) + let components = try componentInspections( + ledger, roots: store.ledgerRoots, + generation: ResolvedLedgerCodec.digest(ledger)) + var revisions: [String: [String]] = [:] + var locations = [store.declarationURL, store.resolvedURL, store.watchURL] + for id in ledger.sources.keys.sorted() { + let identity = try ledger.sourceIdentity(id, roots: store.ledgerRoots) + revisions[identity, default: []].append(ledger.sources[id]!.revision) + if let location = ledger.sources[id]!.location { + locations.append(try location.resolve(roots: store.ledgerRoots)) + } + } + for key in revisions.keys { revisions[key] = Array(Set(revisions[key]!)).sorted() } + try baseline.validate() + return ComponentDiscovery( + components: components, sourceRevisions: revisions, + fingerprint: fingerprint, + readLocations: Array(Set(locations)).sorted { $0.path < $1.path }, + declaration: declaration, declarationDigest: original?.digest ?? "absent") + } + } + } +} diff --git a/Sources/AgentsUpdates/ScopeInspection.swift b/Sources/AgentsUpdates/ScopeInspection.swift new file mode 100644 index 0000000..c84f870 --- /dev/null +++ b/Sources/AgentsUpdates/ScopeInspection.swift @@ -0,0 +1,289 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import Components +import Foundation + +/// A logical identity independent of revision, resources and temporary extraction paths. +public struct ComponentSelection: Hashable, Sendable { + public let identity: String + /// An occurrence selection is checked against the inspection generation before use. + public let occurrence: Int? + public let generation: String +} + +public struct ComponentInspection: Sendable { + public let record: String + public let sourceRecord: String + public let declaringSourceRecord: String + public let selection: ComponentSelection + public let kind: DeclaredComponentKind + public let name: String + public let source: String + public let declaringSource: String + public let root: String + public let group: String? + public let revision: String? + public let version: String? + /// Frozen symbolic configuration. Binding slots are objects with `environment` or `secret` keys. + public let configuration: NativeValue + public let conditions: [DeclarationCondition] + public let recipients: [AgentID] + public let chatGPT: Bool + public let resources: [String] + public let occurrences: [OccurrenceInspection] +} + +public struct OccurrenceInspection: Sendable { + public let declaringSourceRecord: String + public let dependencyRecords: [String] + public let selection: ComponentSelection + public let declaringSource: String + public let manifestPath: String + public let reference: Int? + public let dependencies: [String] + public let condition: DeclarationCondition + public let recipients: [AgentID] + public let consumerEditable: Bool +} + +public struct SourceInspection: Sendable { + public let record: String + public let identity: String + public let kind: SourceKind + public let revision: String + public let version: String? + public let container: String? + public let namespace: String? + public let location: URL? + public let uses: [SourceInspectionUse] +} + +public struct SourceInspectionUse: Sendable { + public let root: String + public let requirement: SourceRequirement? +} + +public struct GroupInspection: Sendable { + public let sourceRecord: String + public let id: Int + public let parent: Int? + public let source: String + public let root: String + public let name: String + public let requirement: SourceRequirement? + public let manifestHash: String + public let children: [Int] +} + +public struct ResourceInspection: Sendable { + public let sourceRecord: String + public let identity: String + public let source: String + public let path: String + public let hash: String + public let kind: String + public let location: URL? + public let entries: [ResourceEntryInspection] + public let support: [ResourceEntryInspection] +} + +public struct ResourceEntryInspection: Sendable { + public let path: String + public let kind: String + public let executable: Bool + public let link: String? + public let byteCount: Int? +} + +public struct DeploymentInspection: Sendable { + public enum Status: String, Sendable { case current, missing, drifted, unverified } + public let identity: String + public let location: URL + public let format: String + public let owners: [String] + public let ownerRecords: [String] + public let recipients: [AgentID] + public let ownership: String + public let effectiveReaders: [AgentID]? + public let privateMaterialization: Bool + public let status: Status + /// Fixed diagnostics never contain native sibling bytes or provider values. + public let diagnostic: String? +} + +public struct RecoveryInspection: Sendable { + public let pending: Bool + public let requiresOwner: Bool + public let diagnostic: String? +} + +/// One read generation. No native bytes, retained content objects, provider calls or recovery. +public struct ScopeInspection: Sendable { + public let scope: InstallScope + public let document: DeclarationDocument? + public let declaration: Declaration? + public let generation: String? + public let sources: [SourceInspection] + public let components: [ComponentInspection] + public let groups: [GroupInspection] + public let resources: [ResourceInspection] + public let deployments: [DeploymentInspection] + public let watch: WatchState? + public let recovery: RecoveryInspection + /// Actual state, source and deployment paths, including absent leaves for directory watching. + public let readLocations: [URL] +} + +extension UpdateOperations { + public static func inspect( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> ScopeInspection { + let store = StateStore(scope: scope, environment: environment) + var admitted = Set() + let stateLocations = [store.declarationURL, store.resolvedURL, store.watchURL] + while true { + do { + return try store.withReadLock( + onPendingRecovery: { + let diagnostic = FileTransaction.recoveryDiagnostic(store: store) + return ScopeInspection( + scope: scope, document: nil, declaration: nil, generation: nil, + sources: [], components: [], groups: [], resources: [], deployments: [], watch: nil, + recovery: .init( + pending: true, requiresOwner: diagnostic.requiresOwner, + diagnostic: diagnostic.message), + readLocations: stateLocations) + }, footprint: admitted, + { + let baseline = try StatePrecondition(store: store) + let document = try store.declarationDocument(prepared: baseline) + let declaration = try store.readDeclaration(prepared: baseline) + let ledger = try store.readLedger(prepared: baseline) + let routes = try DeploymentConstruction.routes(ledger) + guard routes.isSubset(of: admitted) else { throw RequiredRoutes(routes: routes) } + let watch = try store.readWatch(prepared: baseline) + let generation = try ResolvedLedgerCodec.digest([ + ResolvedLedgerCodec.digest(ledger), document?.digest ?? "absent", + ]) + let roots = store.ledgerRoots + func source(_ id: String) throws -> String { + try ledger.sourceIdentity(id, roots: roots) + } + let sources = try ledger.sources.keys.sorted().map { id in + let s = ledger.sources[id]! + return SourceInspection( + record: id, identity: try source(id), kind: s.kind, revision: s.revision, + version: s.version, + container: try s.container.map(source), namespace: s.namespace, + location: try s.location?.resolve(roots: roots), + uses: ledger.sourceUses.filter { $0.source == id }.map { + .init(root: $0.root, requirement: $0.requirement) + }) + } + let components = try componentInspections(ledger, roots: roots, generation: generation) + func entry(_ e: LedgerEntry) -> ResourceEntryInspection { + .init( + path: e.path, kind: e.kind.rawValue, executable: e.executable, + link: e.link, byteCount: e.byteCount) + } + let resources = try ledger.resources.keys.sorted().map { id in + let r = ledger.resources[id]! + return ResourceInspection( + sourceRecord: r.source, identity: id, source: try source(r.source), path: r.path, + hash: r.hash, + kind: r.kind.rawValue, + location: try ArtifactAggregation.resourceDestination( + id, ledger: ledger, store: store), + entries: r.entries.map(entry), support: r.support.map(entry)) + } + let deployments = try ledger.deployments.map { d in + let url = try d.target.resolve(roots: roots) + let observed = try ArtifactAggregation.inspectDeployment( + d, ledger: ledger, store: store) + let exposure = try ArtifactAggregation.nativeExposure(d, ledger: ledger, store: store) + return DeploymentInspection( + identity: d.id, location: url, format: d.route, + owners: try d.owners.map { + try LedgerImpact.identity(ledger.components[$0]!, ledger: ledger, roots: roots) + }, + ownerRecords: d.owners, recipients: d.recipients, ownership: d.ownership.rawValue, + effectiveReaders: exposure.readers, privateMaterialization: exposure.sensitive, + status: DeploymentInspection.Status(rawValue: observed.status)!, + diagnostic: observed.diagnostic) + } + let groups = try ledger.groups.map { g in + GroupInspection( + sourceRecord: g.source, id: g.id, parent: g.parent, source: try source(g.source), + root: g.root, + name: g.name, requirement: g.requirement, manifestHash: g.manifestHash, + children: g.children) + } + var paths = + stateLocations + sources.compactMap(\.location) + resources.compactMap(\.location) + + deployments.map(\.location) + for declaration in declaration.sources.values where declaration.kind == .local { + let environment = declaration.environment?.runtime ?? environment + let id = try declaration.identity(environment: environment) + if id.hasPrefix("local:") { + paths.append(URL(fileURLWithPath: String(id.dropFirst(6)))) + } + } + try baseline.validate() + return ScopeInspection( + scope: scope, document: document, declaration: declaration, generation: generation, + sources: sources, components: components, groups: groups, resources: resources, + deployments: deployments, watch: watch, + recovery: .init(pending: false, requiresOwner: false, diagnostic: nil), + readLocations: Array(Set(paths)).sorted { $0.path < $1.path }) + }) + } catch let required as RequiredRoutes { admitted.formUnion(required.routes) } + } + } + + static func componentInspections( + _ ledger: ResolvedLedger, roots: [String: URL], generation: String + ) throws -> [ComponentInspection] { + func source(_ id: String) throws -> String { try ledger.sourceIdentity(id, roots: roots) } + func condition(_ c: LedgerCondition) -> DeclarationCondition { + .init( + agents: c.agents, scopes: c.scopes, + platforms: c.platforms?.compactMap(DeclarationPlatform.init(rawValue:))) + } + return try ledger.components.keys.sorted().map { id in + let c = ledger.components[id]! + let identity = try LedgerImpact.identity(c, ledger: ledger, roots: roots) + return ComponentInspection( + record: id, sourceRecord: c.source, declaringSourceRecord: c.declaringSource, + selection: .init(identity: identity, occurrence: nil, generation: generation), + kind: DeclaredComponentKind(rawValue: c.kind)!, name: c.name, + source: try source(c.source), declaringSource: try source(c.declaringSource), + root: c.root, group: c.group, revision: c.revision, version: c.version, + configuration: symbolicValue(c.payload), conditions: c.conditions.map(condition), + recipients: c.recipients, chatGPT: c.chatGPT, resources: c.resources, + occurrences: try ledger.occurrences.filter { $0.component == id }.map { o in + .init( + declaringSourceRecord: o.declaringSource, dependencyRecords: o.dependencies, + selection: .init(identity: identity, occurrence: o.id, generation: generation), + declaringSource: try source(o.declaringSource), manifestPath: o.manifestPath, + reference: o.reference, dependencies: try o.dependencies.map(source), + condition: condition(o.condition), recipients: o.recipients, + consumerEditable: o.consumerEditable) + }) + } + } + + private static func symbolicValue(_ value: LedgerValue) -> NativeValue { + switch value.kind { + case .environment: return .object(["environment": .string(value.text!)]) + case .secret: return .object(["secret": .string(value.text!)]) + case .string, .literal: return .string(value.text!) + case .integer: return .integer(value.integer!) + case .decimal: return .decimal(value.text!) + case .boolean: return .boolean(value.boolean!) + case .null: return .null + case .array: return .array(value.array!.map(symbolicValue)) + case .object: return .object(value.object!.mapValues(symbolicValue)) + } + } +} diff --git a/Sources/AgentsUpdates/SourceImportOperations.swift b/Sources/AgentsUpdates/SourceImportOperations.swift new file mode 100644 index 0000000..46a8c73 --- /dev/null +++ b/Sources/AgentsUpdates/SourceImportOperations.swift @@ -0,0 +1,263 @@ +import AgentsCore +import Components +import Foundation + +public struct ImportSourceInspection: Sendable { + public let alias: String + public let document: String + public let pointer: String + public let declaration: SourceDeclaration? + public let commit: String? + public let version: String? + public let integrityKind: String? + public let integrity: String? + public let requestedRef: String? + public let resolvedRef: String? + public let resolvedURL: String? + public let developmentOnly: Bool + public let producerPath: String? + public let producerIdentity: String? + public let registry: String? +} + +public struct ImportComponentInspection: Sendable { + public let document: String + public let pointer: String + public let declaration: ComponentDeclaration +} + +public struct ImportDiagnosticInspection: Sendable { + public let code: String + public let document: String + public let pointer: String + public let span: SourceSpan? + public let message: String +} + +public struct ImportResourceInspection: Sendable { + public let sourceAlias: String + public let producerName: String + public let path: String? + public let hash: String? + public let integrityKind: String? + public let integrity: String? + public let executableFlags: [String: Bool] + public let requiresStandaloneSource: Bool + public let selected: Bool +} + +/// Producer claims remain evidence; they never grant ownership of an existing target. +public struct ImportDeploymentInspection: Sendable { + public let document: String + public let pointer: String + public let sourceAlias: String? + public let agent: String? + public let scope: String? + public let directory: String? + public let files: [String] +} + +public struct ImportBindingInspection: Sendable { + public let document: String + public let pointer: String + public let reason: String + public let environmentVariable: String? +} + +public struct ImportSelectionInspection: Sendable { + public let document: String + public let pointer: String + public let sourceAlias: String? + public let kind: String + public let values: [String] + public let automatic: Bool + public let developmentOnly: Bool +} + +public struct ImportOrderedSourceInspection: Sendable { + public let document: String + public let pointer: String + public let alias: String + public let identity: String + public let transport: String + public let registry: String? + public let requestedRef: String? + public let skillsPath: String + public let rulesPath: String + public let skills: [String]? + public let rules: [String]? +} + +public struct SourceImportInspection: Sendable { + public let format: String + public let producerRevision: String + public let specificationStatus: String + public let sources: [ImportSourceInspection] + public let components: [ImportComponentInspection] + public let diagnostics: [ImportDiagnosticInspection] + public let resources: [ImportResourceInspection] + public let deployments: [ImportDeploymentInspection] + public let bindings: [ImportBindingInspection] + public let selections: [ImportSelectionInspection] + public let orderedSources: [ImportOrderedSourceInspection] + public let readLocations: [URL] + private let preparation: ImportPreparation + + /// Merges selected canonical intent into the same captured full declaration. Unconverted + /// semantics and required bindings must be resolved by another explicit input selection. + public func updateRequest(in inspection: ScopeInspection) throws -> UpdateRequest { + guard !inspection.recovery.pending, var declaration = inspection.declaration else { + throw CoreError.invalidState("inspect the committed scope before preparing an import") + } + guard diagnostics.isEmpty, bindings.isEmpty else { + throw CoreError.invalidState( + "import has unresolved conversion diagnostics or binding requirements") + } + guard + !preparation.proposal.resources.contains(where: { + $0.selected && $0.producerIntegrity != nil && $0.observedHash == nil + }) + else { + throw CoreError.invalidState( + "import requires verified captured content for the producer integrity claim") + } + for source in preparation.proposal.sources { + guard let imported = source.declaration else { + throw CoreError.invalidState("import lacks exact canonical source coordinates") + } + if let existing = declaration.sources[source.alias], existing != imported { + throw CoreError.invalidState( + "import source alias conflicts with the captured declaration: " + source.alias) + } + declaration.sources[source.alias] = imported + } + for component in preparation.proposal.components + where !declaration.components.contains(component.declaration) { + declaration.components.append(component.declaration) + } + var request = UpdateRequest( + operation: .declaration(declaration), + expectedDeclarationDigest: inspection.document?.digest ?? "absent") + request.importPreparation = preparation + return request + } + + init(_ proposal: SourceImportProposal, preparation: ImportPreparation) { + self.preparation = preparation + format = proposal.profile.rawValue + producerRevision = proposal.profile.producerRevision + specificationStatus = proposal.profile.specificationStatus + sources = proposal.sources.map { s in + .init( + alias: s.alias, document: s.origin.document, pointer: s.origin.pointer, + declaration: s.declaration, commit: s.pin.commit, version: s.pin.version, + integrityKind: s.pin.integrity?.kind.rawValue, integrity: s.pin.integrity?.value, + requestedRef: s.requestedRef, resolvedRef: s.resolvedRef, resolvedURL: s.resolvedURL, + developmentOnly: s.developmentOnly, producerPath: s.producerPath, + producerIdentity: s.producerIdentity, registry: s.registry) + } + components = proposal.components.map { + .init( + document: $0.origin.document, + pointer: $0.origin.pointer, declaration: $0.declaration) + } + diagnostics = proposal.diagnostics.map { + .init( + code: $0.code.rawValue, + document: $0.location.document, pointer: $0.location.pointer, span: $0.location.span, + message: $0.message) + } + resources = proposal.resources.map { + .init( + sourceAlias: $0.sourceAlias, + producerName: $0.producerName, path: $0.path, hash: $0.observedHash, + integrityKind: $0.producerIntegrity?.kind.rawValue, integrity: $0.producerIntegrity?.value, + executableFlags: $0.executableFlags, requiresStandaloneSource: $0.requiresStandaloneSource, + selected: $0.selected) + } + deployments = proposal.deployments.map { + .init( + document: $0.origin.document, + pointer: $0.origin.pointer, sourceAlias: $0.sourceAlias, agent: $0.agent, scope: $0.scope, + directory: $0.installDirectory, files: $0.files) + } + bindings = proposal.bindings.map { + .init( + document: $0.location.document, + pointer: $0.location.pointer, reason: $0.reason, environmentVariable: $0.environmentVariable + ) + } + selections = proposal.selections.map { + .init( + document: $0.origin.document, + pointer: $0.origin.pointer, sourceAlias: $0.sourceAlias, kind: $0.kind.rawValue, + values: $0.values, automatic: $0.automatic, developmentOnly: $0.developmentOnly) + } + orderedSources = proposal.orderedSources.map { + .init( + document: $0.origin.document, + pointer: $0.origin.pointer, alias: $0.alias, identity: $0.identity, transport: $0.transport, + registry: $0.registry, requestedRef: $0.requestedRef, skillsPath: $0.skillsPath, + rulesPath: $0.rulesPath, skills: $0.skills, rules: $0.rules) + } + readLocations = preparation.locations + } +} + +package struct ImportPreparation: Sendable { + let input: SourceImportInput + let proposal: SourceImportProposal + let documentFingerprint: String + let locations: [URL] + + func capture() throws -> [TargetPrecondition] { + let document = try PathSafety.resolvedChild(base: input.root, subpath: input.document) + let evidence = try TargetPrecondition(document) + let inputs = try locations.map { try TargetPrecondition($0) } + guard try evidence.displayEvidence(includeContent: true) == documentFingerprint, + try SourceImport.preview(input) == proposal + else { throw CoreError.invalidState("import inputs changed; refresh the import inspection") } + try evidence.validate() + for input in inputs { try input.validate() } + return inputs + } +} + +public enum SourceImportOperations { + /// Explicit pinned profile names are the importer owner's existing raw values. No ambient + /// config discovery, execution, network access, deployment adoption or write occurs. + public static func inspect( + format: String, root: URL, document: String, selection: Set? = nil, + sourceDeclarations: [String: SourceDeclaration] = [:], installedSkills: [String: String] = [:] + ) throws -> SourceImportInspection { + guard let profile = SourceImportProfile(rawValue: format) else { + throw CoreError.invalidSource("unknown source import profile") + } + let input = SourceImportInput( + profile: profile, root: root, document: document, + selection: selection, sourceDeclarations: sourceDeclarations, installedSkills: installedSkills + ) + let url = try PathSafety.resolvedChild(base: root, subpath: document) + let evidence = try TargetPrecondition(url) + let fingerprint = try evidence.displayEvidence(includeContent: true) + let proposal = try SourceImport.preview(input) + var locations = [url] + for path in installedSkills.values { + locations.append(try PathSafety.resolvedChild(base: root, subpath: path)) + } + for source in proposal.sources.compactMap(\.declaration) where source.kind == .local { + let environment = + source.environment?.runtime ?? RuntimeEnvironment(projectDirectory: root, environment: [:]) + let identity = try source.identity(environment: environment) + if identity.hasPrefix("local:") { + locations.append(URL(fileURLWithPath: String(identity.dropFirst(6)))) + } + } + let preparation = ImportPreparation( + input: input, proposal: proposal, + documentFingerprint: fingerprint, + locations: Array(Set(locations)).sorted { $0.path < $1.path }) + _ = try preparation.capture() + return SourceImportInspection(proposal, preparation: preparation) + } +} diff --git a/Sources/AgentsUpdates/UpdateCompletion.swift b/Sources/AgentsUpdates/UpdateCompletion.swift new file mode 100644 index 0000000..f51b290 --- /dev/null +++ b/Sources/AgentsUpdates/UpdateCompletion.swift @@ -0,0 +1,83 @@ +import AgentsCore + +/// The outer operation's disposition after writer-lock recovery and cleanup have returned. +public enum UpdateTerminalDisposition: String, Sendable { + case unchanged, rolledBack, committed, recoveryRequired +} + +public struct UpdateCompletion { + public let result: Result + public let disposition: UpdateTerminalDisposition + public let recoveredBeforePreparation: Bool + public let recovery: RecoveryInspection +} + +extension UpdateCompletion: Sendable where Value: Sendable {} + +extension UpdateOperations { + /// Returns only after the synchronous closure, source lifetime and outer scope cleanup end. + /// UI consumers reprepare and compare the displayed fingerprint inside this closure. + public static func perform( + _ request: UpdateRequest = UpdateRequest(), scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), + bindingProvider: (any RuntimeBindingProvider)? = nil, + _ body: (PreparedUpdate) throws -> Value + ) -> UpdateCompletion { + perform( + request, scope: scope, environment: environment, bindingProvider: bindingProvider, + checkpoint: { _ in }, body) + } + + package static func perform( + _ request: UpdateRequest = UpdateRequest(), scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), + bindingProvider: (any RuntimeBindingProvider)? = nil, + checkpoint: @escaping (String) throws -> Void, + _ body: (PreparedUpdate) throws -> Value + ) -> UpdateCompletion { + var disposition = UpdateTerminalDisposition.unchanged + var delivered = false + var recovered = false + let result = Result { + do { + return try prepare( + request, scope: scope, environment: environment, checkpoint: checkpoint, + provider: bindingProvider ?? RequiredBindingProvider(), + completion: { outcome in + switch outcome.disposition { + case .committed: disposition = .committed + case .recoveryRequired: disposition = .recoveryRequired + case .unchanged: disposition = outcome.publicationStarted ? .rolledBack : .unchanged + } + } + ) { update in + delivered = true + return try body(update) + } + } catch { + let underlying = (error as? UpdateApplyError)?.underlyingError ?? error + if !delivered, case CoreError.transactionRecovered = underlying { recovered = true } + throw error + } + } + let store = StateStore(scope: scope, environment: environment) + let recovery: RecoveryInspection + do { + recovery = try store.withReadLock( + onPendingRecovery: { + let diagnostic = FileTransaction.recoveryDiagnostic(store: store) + return .init( + pending: true, requiresOwner: diagnostic.requiresOwner, diagnostic: diagnostic.message) + }, { .init(pending: false, requiresOwner: false, diagnostic: nil) }) + } catch { + // Failure to inspect cleanup is itself material; do not downgrade it to success. + recovery = .init( + pending: true, requiresOwner: true, + diagnostic: "recovery or cleanup could not be verified; retain this scope for diagnosis") + } + if recovery.pending, disposition != .committed { disposition = .recoveryRequired } + return UpdateCompletion( + result: result, disposition: disposition, + recoveredBeforePreparation: recovered, recovery: recovery) + } +} diff --git a/Sources/AgentsUpdates/UpdateModels.swift b/Sources/AgentsUpdates/UpdateModels.swift index db45b9b..bfb3a38 100644 --- a/Sources/AgentsUpdates/UpdateModels.swift +++ b/Sources/AgentsUpdates/UpdateModels.swift @@ -48,6 +48,7 @@ public struct ComponentUpdateChange: Codable, Sendable, Equatable { public let ownership: String public let resources: [ComponentResourceInfo] public let requiredBindings: [String] + public let effectiveReaders: [AgentID] public let privateMaterialization: Bool public let permissionChange: ComponentPermissionChange? public let symbolicBefore: String? diff --git a/Sources/AgentsUpdates/UpdateOperations.swift b/Sources/AgentsUpdates/UpdateOperations.swift index f676cb7..81022de 100644 --- a/Sources/AgentsUpdates/UpdateOperations.swift +++ b/Sources/AgentsUpdates/UpdateOperations.swift @@ -39,10 +39,12 @@ public enum UpdateOperations { public static func withPreparedUpdate( _ request: UpdateRequest = UpdateRequest(), scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + bindingProvider: (any RuntimeBindingProvider)? = nil, _ body: (PreparedUpdate) throws -> Result ) throws -> Result { - try withPreparedUpdate( - request, scope: scope, environment: environment, checkpoint: { _ in }, body) + try prepare( + request, scope: scope, environment: environment, checkpoint: { _ in }, + provider: bindingProvider ?? RequiredBindingProvider(), body) } package static func withPreparedUpdate( @@ -59,10 +61,12 @@ public enum UpdateOperations { package static func prepare( _ request: UpdateRequest, scope: InstallScope, environment: RuntimeEnvironment, checkpoint: @escaping (String) throws -> Void, provider: any RuntimeBindingProvider, + completion: ((TransactionOutcome) -> Void)? = nil, _ body: (PreparedUpdate) throws -> Result ) throws -> Result { let store = StateStore(scope: scope, environment: environment) let outcome = TransactionOutcome() + defer { completion?(outcome) } var delivered = false var returned = false var admitted = Set() @@ -115,10 +119,12 @@ public enum UpdateOperations { } public static func restore( - scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + bindingProvider: (any RuntimeBindingProvider)? = nil ) throws -> UpdateApplyResult { try withPreparedUpdate( - UpdateRequest(operation: .restore), scope: scope, environment: environment + UpdateRequest(operation: .restore), scope: scope, environment: environment, + bindingProvider: bindingProvider ) { try $0.apply() } } } diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 6eb5976..1a6ffbd 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -28,8 +28,11 @@ final class UpdatePlan { checkpoint: @escaping (String) throws -> Void, provider: any RuntimeBindingProvider, _ body: (UpdatePlan) throws -> T ) throws -> T { + var request = request + let importInputs = try request.importPreparation?.capture() ?? [] let baseline = try StatePrecondition(store: store) let previous = try store.readLedger(prepared: baseline) + try resolveSelection(&request, ledger: previous, store: store, baseline: baseline) let restoringRequest: Bool if case .restore = request.operation { restoringRequest = true @@ -68,7 +71,8 @@ final class UpdatePlan { restoring = false try LedgerImpact.requireEditable( previous, kinds: request.kinds ?? Set(DeclaredComponentKind.allCases), - names: Set(request.names), roots: store.ledgerRoots) + names: Set(request.names), roots: store.ledgerRoots, + selectedIdentities: request.selectedIdentities) candidate = try removing(request, from: declaration, ledger: previous, store: store) change = try store.planDeclaration(candidate, replacing: declaration, prepared: baseline) } @@ -98,7 +102,11 @@ final class UpdatePlan { bytes: Array("version: 1\n".utf8), identity: DocumentIdentity(store.declarationURL.path)) } let updating: Bool - if case .update = request.operation { updating = true } else { updating = false } + if case .update = request.operation { + updating = true + } else { + updating = request.expectedDiscoveryFingerprint != nil + } let removing: Bool if case .remove = request.operation { removing = true } else { removing = false } if removing || (updating && !request.names.isEmpty), request.kinds?.contains(.skills) ?? true { @@ -140,7 +148,7 @@ final class UpdatePlan { let impact = try LedgerImpact( ledger: previous, roots: store.ledgerRoots, kinds: request.kinds ?? Set(DeclaredComponentKind.allCases), names: Set(request.names), - updating: updating) + updating: updating, selectedIdentities: request.selectedIdentities) #if os(macOS) let platform = DeclarationPlatform.macOS #else @@ -163,36 +171,7 @@ final class UpdatePlan { "automatic skill selection changed during discovery; retry the command") } } - var locations: [String: LedgerLocation] = [:] - let packageRoot = - store.scope == .project ? store.environment.projectDirectory : store.directory - for evidence in linked.sourceSnapshots + linked.declaringSnapshots - where evidence.container == nil && evidence.snapshot.source.hasPrefix("local:") { - let path = String(evidence.snapshot.source.dropFirst(6)) - if path == packageRoot.path { - locations[evidence.snapshot.source] = .init( - kind: .registered, root: store.scope == .project ? "project" : "state", path: ".") - } else if let authored = try candidate.sources.values.first(where: { - try $0.identity(environment: store.environment) == evidence.snapshot.source - }), - !authored.location.hasPrefix("/") - { - if authored.location == "~" || authored.location.hasPrefix("~/") { - locations[evidence.snapshot.source] = .init( - kind: .authoringRelative, root: "home", - path: authored.location == "~" ? "." : String(authored.location.dropFirst(2))) - } else if authored.environment?.projectDirectory.path - == store.environment.projectDirectory.path || authored.environment == nil - { - locations[evidence.snapshot.source] = .init( - kind: .authoringRelative, root: "project", path: authored.location) - } else { - locations[evidence.snapshot.source] = .init(kind: .absolute, path: path) - } - } else { - locations[evidence.snapshot.source] = .init(kind: .absolute, path: path) - } - } + let locations = try sourceLocations(linked, declaration: candidate, store: store) for component in linked.components { if case .skill(let skill, .copy, _) = component.payload { try DeploymentConstruction.validateCopiedSkill( @@ -201,15 +180,21 @@ final class UpdatePlan { } let frozen = try LedgerFreeze.freezeWithSources( linked, session: session, locations: .init(sources: locations), limits: .standard) + if let expected = request.expectedDiscoveryFingerprint, + expected != (try LedgerImpact.discoveryFingerprint(frozen.ledger, roots: store.ledgerRoots)) + { + throw CoreError.invalidState("discovered source content changed; refresh discovery") + } let native = try DeploymentConstruction.lowerNative( linked: linked, frozen: frozen, scope: store.scope, platform: platform) let routes = try DeploymentConstruction.routes(native).union( DeploymentConstruction.routes(previous)) guard routes.isSubset(of: admitted) else { throw RequiredRoutes(routes: routes) } - if let kinds = request.kinds { + if request.kinds != nil || !request.names.isEmpty || request.selectedIdentities != nil { + let kinds = request.kinds ?? Set(DeclaredComponentKind.allCases) try LedgerImpact.requireProtected( previous: previous, next: native, kinds: kinds, names: Set(request.names), - roots: store.ledgerRoots) + roots: store.ledgerRoots, selectedIdentities: request.selectedIdentities) } let complete = try DeploymentConstruction.complete( native, linked: linked, store: store, previous: previous, platform: platform) @@ -228,7 +213,7 @@ final class UpdatePlan { request: request, store: store, baseline: baseline, previous: previous, next: next, watch: watch, change: change, artifacts: artifacts, resources: resources, workspace: workspace, - decisionInputs: complete.inputs, originalInputs: originals, + decisionInputs: complete.inputs, originalInputs: originals + importInputs, checkpoint: checkpoint, provider: provider)) } } @@ -254,6 +239,26 @@ final class UpdatePlan { ledger: next, previous: previous, artifacts: artifacts, resources: resources, workspace: workspace, store: store, replace: request.replace, changingAccess: request.changingAccess, kinds: request.kinds) + if let imported = request.importPreparation { + for resource in imported.proposal.resources + where resource.selected && resource.requiresStandaloneSource { + guard + let source = imported.proposal.sources.first(where: { $0.alias == resource.sourceAlias })? + .declaration, + source.kind == .local + else { continue } + let sourceEnvironment = source.environment?.runtime ?? store.environment + let identity = try source.identity(environment: sourceEnvironment) + let root = URL(fileURLWithPath: String(identity.dropFirst(6))) + if aggregation.changes.contains(where: { + PathSafety.isContained(root, in: $0.url) || PathSafety.isContained($0.url, in: root) + }) { + throw CoreError.invalidState( + "import requires an independent authoring source before replacing its installed content" + ) + } + } + } self.next = aggregation.ledger try self.next.validate() let lockMissing = try baseline.bytes(for: store.resolvedURL) == nil @@ -262,7 +267,8 @@ final class UpdatePlan { let allResults = try UpdateReporting.skills( previous: previous, next: self.next, resources: resources, changes: aggregation.changes, store: store, lockMissing: lockMissing, - included: request.kinds == nil || request.kinds!.contains(.skills)) + included: request.kinds == nil || request.kinds!.contains(.skills), + selectedIdentities: request.selectedIdentities) let results = request.names.isEmpty ? allResults : allResults.filter { request.names.contains($0.skill) } receipts = results.flatMap(\.installed) @@ -302,6 +308,7 @@ final class UpdatePlan { let scope: InstallScope let kinds: [String]? let names: [String] + let selectedIdentities: [String]? let replace: Bool let changingAccess: Bool let candidate: ResolvedLedger @@ -312,7 +319,8 @@ final class UpdatePlan { let fingerprint = try ResolvedLedgerCodec.digest( Fingerprint( operation: operation, scope: store.scope, kinds: request.kinds?.map(\.rawValue).sorted(), - names: request.names.sorted(), replace: request.replace, + names: request.names.sorted(), selectedIdentities: request.selectedIdentities?.sorted(), + replace: request.replace, changingAccess: request.changingAccess, candidate: self.next, baseline: previous, declaration: try (change?.bytes ?? baseline.bytes(for: store.declarationURL)).map { @@ -327,7 +335,16 @@ final class UpdatePlan { hasChanges: self.next != previous || change != nil || aggregation.changes.contains(where: \.changed), displayedFingerprint: fingerprint, - components: try aggregation.changes.filter(\.native).map { change in + components: try aggregation.changes.filter { change in + guard change.native else { return false } + guard let identities = request.selectedIdentities else { return true } + return try change.deployment.owners.contains { owner in + let ledger = finalNext.components[owner] == nil ? previous : finalNext + return try identities.contains( + LedgerImpact.identity( + ledger.components[owner]!, ledger: ledger, roots: store.ledgerRoots)) + } + }.map { change in let owner = change.deployment.owners[0] let ledger = finalNext.components[owner] == nil ? previous : finalNext let component = ledger.components[owner]! @@ -342,7 +359,7 @@ final class UpdatePlan { uniqueKeysWithValues: resource.entries.filter { $0.kind == .file }.map { ($0.path, $0.executable) })) - }, requiredBindings: change.requiredBindings, + }, requiredBindings: change.requiredBindings, effectiveReaders: change.effectiveReaders, privateMaterialization: change.privateMaterialization, permissionChange: change.accessChange.map { access in ComponentPermissionChange( @@ -396,6 +413,111 @@ final class UpdatePlan { } } + static func sourceLocations( + _ linked: LinkedComponents, declaration: Declaration, store: StateStore + ) throws -> [String: LedgerLocation] { + var locations: [String: LedgerLocation] = [:] + let packageRoot = + store.scope == .project ? store.environment.projectDirectory : store.directory + for evidence in linked.sourceSnapshots + linked.declaringSnapshots + where evidence.container == nil && evidence.snapshot.source.hasPrefix("local:") { + let path = String(evidence.snapshot.source.dropFirst(6)) + if path == packageRoot.path { + locations[evidence.snapshot.source] = .init( + kind: .registered, root: store.scope == .project ? "project" : "state", path: ".") + } else if let authored = try declaration.sources.values.first(where: { + try $0.identity(environment: store.environment) == evidence.snapshot.source + }), + !authored.location.hasPrefix("/") + { + if authored.location == "~" || authored.location.hasPrefix("~/") { + locations[evidence.snapshot.source] = .init( + kind: .authoringRelative, root: "home", + path: authored.location == "~" ? "." : String(authored.location.dropFirst(2))) + } else if authored.environment?.projectDirectory.path + == store.environment.projectDirectory.path || authored.environment == nil + { + locations[evidence.snapshot.source] = .init( + kind: .authoringRelative, root: "project", path: authored.location) + } else { + locations[evidence.snapshot.source] = .init(kind: .absolute, path: path) + } + } else { + locations[evidence.snapshot.source] = .init(kind: .absolute, path: path) + } + } + return locations + } + + private static func resolveSelection( + _ request: inout UpdateRequest, ledger: ResolvedLedger, store: StateStore, + baseline: StatePrecondition + ) throws { + let kinds = request.kinds ?? Set(DeclaredComponentKind.allCases) + func name(_ c: LedgerComponent) -> String { + c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name + } + if request.selections.isEmpty { + for requested in request.names { + let matches = try ledger.components.values.filter { + kinds.contains(DeclaredComponentKind(rawValue: $0.kind)!) && name($0) == requested + }.map { try LedgerImpact.identity($0, ledger: ledger, roots: store.ledgerRoots) } + guard Set(matches).count <= 1 else { + throw CoreError.invalidState( + "component name is ambiguous; select a component from inspection: " + requested) + } + } + return + } + guard request.names.isEmpty else { + throw CoreError.invalidState("use names or precise selections, not both") + } + switch request.operation { + case .update, .remove: break + default: throw CoreError.invalidState("precise selection applies to update or removal") + } + let documentDigest = + try baseline.bytes(for: store.declarationURL).map { "sha256:" + FileHash.sha256Hex(data: $0) } + ?? "absent" + let generation = try ResolvedLedgerCodec.digest([ + ResolvedLedgerCodec.digest(ledger), documentDigest, + ]) + var selected = Set() + var names = Set() + var selectedKinds = Set() + for selection in request.selections { + guard selection.generation == generation else { + throw CoreError.invalidState("inspection changed; refresh component selection") + } + let entries = try ledger.components.filter { + try LedgerImpact.identity($0.value, ledger: ledger, roots: store.ledgerRoots) + == selection.identity + } + guard let entry = entries.first, + kinds.contains(DeclaredComponentKind(rawValue: entry.value.kind)!) + else { + throw CoreError.notFound("selected component") + } + if let occurrence = selection.occurrence { + let occurrences = ledger.occurrences.filter { entries[$0.component] != nil } + guard occurrences.contains(where: { $0.id == occurrence }) else { + throw CoreError.notFound("selected occurrence") + } + guard occurrences.count == 1 else { + throw CoreError.invalidState( + "this component has multiple contributions; select the complete component or edit its declaration reference" + ) + } + } + selected.insert(selection.identity) + names.insert(name(entry.value)) + selectedKinds.insert(DeclaredComponentKind(rawValue: entry.value.kind)!) + } + request.selectedIdentities = selected + request.names = names.sorted() + request.kinds = selectedKinds + } + private static func removing( _ request: UpdateRequest, from declaration: Declaration, ledger: ResolvedLedger, store: StateStore @@ -412,7 +534,30 @@ final class UpdatePlan { return [] }) var instructionReferences = Set() - if kinds.contains(.instructions) { + if kinds.contains(.instructions), let identities = request.selectedIdentities { + let sections = declaration.components.flatMap { component -> [SectionDeclaration] in + guard case .instructions(let selection) = component else { return [] } + return selection.sectionReferences + + selection.prompts.flatMap { $0.prompt.sectionReferences } + } + for section in sections { + let source: String + if let alias = section.source, alias != "." { + guard let declaration = declaration.sources[alias] else { continue } + source = try declaration.identity(environment: store.environment) + } else { + source = "local:" + store.environment.projectDirectory.resolvingSymlinksInPath().path + } + if try ledger.components.values.contains(where: { c in + try c.kind == "instructions" && c.name == section.name + && ledger.sourceIdentity(c.source, roots: store.ledgerRoots) == source + && identities.contains( + LedgerImpact.identity(c, ledger: ledger, roots: store.ledgerRoots)) + }) { + instructionReferences.insert(section.reference) + } + } + } else if kinds.contains(.instructions) { for name in names { let exact = references.filter { $0 == name } let matches = @@ -427,6 +572,16 @@ final class UpdatePlan { result.components = declaration.components.compactMap { component in switch component { case .skills(let alias, var selection) where kinds.contains(.skills): + if let identities = request.selectedIdentities { + let source = try? declaration.sources[alias]?.identity(environment: store.environment) + let matches = ledger.components.values.contains { c in + c.kind == "skills" + && (try? ledger.sourceIdentity(c.source, roots: store.ledgerRoots)) == source + && (try? LedgerImpact.identity(c, ledger: ledger, roots: store.ledgerRoots)).map( + identities.contains) == true + } + if !matches { return component } + } if case .all = selection.select { selection.exclude = Array(Set(selection.exclude ?? []).union(names)).sorted() } else if case .names(let selected) = selection.select { @@ -440,7 +595,9 @@ final class UpdatePlan { var original = selection for name in names { let current = ledger.components.values.first { - $0.name == name && $0.kind == "skills" + $0.kind == "skills" && PathSafety.sanitizeName($0.name) == name + && (try? ledger.sourceIdentity($0.source, roots: store.ledgerRoots)) + == (try? declaration.sources[alias]?.identity(environment: store.environment)) } var overrides = original.overrides ?? [:] overrides[name] = SkillOverride( diff --git a/Sources/AgentsUpdates/UpdateReporting.swift b/Sources/AgentsUpdates/UpdateReporting.swift index 8d93edf..481785a 100644 --- a/Sources/AgentsUpdates/UpdateReporting.swift +++ b/Sources/AgentsUpdates/UpdateReporting.swift @@ -8,7 +8,8 @@ import Foundation enum UpdateReporting { static func skills( previous: ResolvedLedger, next: ResolvedLedger, resources: [String: URL], - changes: [AggregatedChange], store: StateStore, lockMissing: Bool, included: Bool + changes: [AggregatedChange], store: StateStore, lockMissing: Bool, included: Bool, + selectedIdentities: Set? = nil ) throws -> [UpdateResult] { guard included else { return [] } struct Item { @@ -20,6 +21,12 @@ enum UpdateReporting { var result: [String: Item] = [:] for component in ledger.components.values where component.kind == "skills" && !component.recipients.isEmpty { + if let selectedIdentities, + !selectedIdentities.contains( + try LedgerImpact.identity(component, ledger: ledger, roots: store.ledgerRoots)) + { + continue + } guard let id = component.resources.first, let resource = ledger.resources[id] else { continue } @@ -80,6 +87,9 @@ enum UpdateReporting { let retained = members.contains { new?.installs[$0.agent.rawValue] != nil } let oldFiles = try entries(URL(fileURLWithPath: target)) var newFiles = try retained ? content.map(entries) ?? [:] : [:] + if !retained, changes.contains(where: { $0.url.path == target && !$0.changed }) { + newFiles = oldFiles + } if let change = changes.first(where: { $0.url.path == target }), let destination = change.afterLink { diff --git a/Sources/AgentsUpdates/UpdateRequest.swift b/Sources/AgentsUpdates/UpdateRequest.swift index 438765a..c08f35a 100644 --- a/Sources/AgentsUpdates/UpdateRequest.swift +++ b/Sources/AgentsUpdates/UpdateRequest.swift @@ -11,7 +11,11 @@ public enum UpdateOperation: Sendable { /// Selection constrains application and protects the recorded semantics of every other domain. public struct UpdateRequest: Sendable { + package var importPreparation: ImportPreparation? + package var expectedDiscoveryFingerprint: String? package var automaticSkill: (source: String, name: String)? + package var selectedIdentities: Set? + public var selections: [ComponentSelection] public var operation: UpdateOperation public var kinds: Set? public var names: [String] @@ -23,9 +27,11 @@ public struct UpdateRequest: Sendable { public init( operation: UpdateOperation = .update, kinds: Set? = nil, - names: [String] = [], agents: [AgentID]? = nil, replace: Bool = false, + names: [String] = [], selections: [ComponentSelection] = [], agents: [AgentID]? = nil, + replace: Bool = false, changingAccess: Bool = false, expectedDeclarationDigest: String? = nil ) { + self.selections = selections self.operation = operation self.kinds = kinds self.names = names diff --git a/Sources/Components/ArtifactAggregation.swift b/Sources/Components/ArtifactAggregation.swift index 2b4df3e..a724532 100644 --- a/Sources/Components/ArtifactAggregation.swift +++ b/Sources/Components/ArtifactAggregation.swift @@ -12,6 +12,7 @@ package struct AggregatedChange { package let native: Bool package var afterLink: URL? = nil package var accessChange: PrivateAccessChange? = nil + package var effectiveReaders: [AgentID] = [] package var privateMaterialization = false package var requiredBindings: [String] = [] package var symbolicBefore: LedgerValue? = nil @@ -256,12 +257,17 @@ package final class ArtifactAggregation: PreparedEvidence { } private func resourceDestination(_ id: String, in selected: ResolvedLedger? = nil) throws -> URL { - let ledger = selected ?? self.ledger + try Self.resourceDestination(id, ledger: selected ?? ledger, store: store) + } + + package static func resourceDestination(_ id: String, ledger: ResolvedLedger, store: StateStore) + throws -> URL + { guard let resource = ledger.resources[id] else { throw CoreError.invalidState("missing deployment resource") } if let location = resource.location { return try location.resolve(roots: store.ledgerRoots) } - if let root = try gitDestination(resource, ledger: ledger) { + if let root = try gitDestination(resource, ledger: ledger, store: store) { return root.appendingPathComponent(resource.path) } let base = store.cacheDirectory.appendingPathComponent( @@ -270,6 +276,12 @@ package final class ArtifactAggregation: PreparedEvidence { } private func gitDestination(_ resource: LedgerResource, ledger: ResolvedLedger) throws -> URL? { + try Self.gitDestination(resource, ledger: ledger, store: store) + } + + private static func gitDestination( + _ resource: LedgerResource, ledger: ResolvedLedger, store: StateStore + ) throws -> URL? { guard resource.kind == .git else { return nil } var sourceID = resource.source while let parent = ledger.sources[sourceID]?.container { sourceID = parent } @@ -298,7 +310,7 @@ package final class ArtifactAggregation: PreparedEvidence { return } let document = try NativeDocument( - bytes: capture.bytes ?? Data("{}\n".utf8), + bytes: capture.bytes ?? Data((descriptor.documentFormat == .toml ? "" : "{}\n").utf8), format: descriptor.documentFormat, budget: NativeDocumentBudget( limits: .init( @@ -317,7 +329,12 @@ package final class ArtifactAggregation: PreparedEvidence { } let oldByName = Dictionary(old.map { ($0.name, $0) }, uniquingKeysWith: { first, _ in first }) let names = Set(desired.keys).union(oldByName.keys).sorted() - let sensitive = (old + contributions.map(\.1)).contains { + let effectiveReaders = Array( + (old + contributions.map(\.1)).reduce(into: Set()) { + $0.formUnion($1.descriptor.knownReaders) + } + ).sorted { $0.rawValue < $1.rawValue } + let hasBindings = (old + contributions.map(\.1)).contains { $0.bindings.contains { !$0.reference } } let target: MaterializationTarget @@ -326,6 +343,7 @@ package final class ArtifactAggregation: PreparedEvidence { } else { target = try store.nativeTarget(for: DeploymentConstruction.route(old[0])) } + let sensitive = try hasBindings || store.materializationReceipt(for: target) != nil let privatePlan = try sensitive ? store.preparePrivateMaterialization( @@ -371,7 +389,9 @@ package final class ArtifactAggregation: PreparedEvidence { // Symbolic placeholders never leave the private plan. A staged literal render consumes // all regions together after Core has verified private staging and resolved bindings. let preview = try document.prepare(edits(nil)) - let changed = preview.bytes != (capture.bytes ?? Data("{}\n".utf8)) + let changed = + preview.bytes + != (capture.bytes ?? Data((descriptor.documentFormat == .toml ? "" : "{}\n").utf8)) if let privatePlan { let bindings = Set( contributions.flatMap { @@ -407,7 +427,8 @@ package final class ArtifactAggregation: PreparedEvidence { changes.append( .init( deployment: deployment, url: url, before: nil, after: nil, changed: changed || sensitive, - native: true, accessChange: privatePlan?.accessChange, privateMaterialization: sensitive, + native: true, accessChange: privatePlan?.accessChange, effectiveReaders: effectiveReaders, + privateMaterialization: sensitive, requiredBindings: contribution.bindings.filter { !$0.reference }.map { switch $0.binding { case .environment(let name), .secret(let name): name @@ -428,6 +449,7 @@ package final class ArtifactAggregation: PreparedEvidence { .init( deployment: prior, url: url, before: nil, after: nil, changed: removed, native: true, accessChange: privatePlan?.accessChange, + effectiveReaders: effectiveReaders, privateMaterialization: sensitive, symbolicBefore: old.value)) } @@ -436,12 +458,19 @@ package final class ArtifactAggregation: PreparedEvidence { private func nativeValue( _ contribution: NativeMCPContribution, values: RuntimeBindingValues?, ledger: ResolvedLedger + ) throws -> NativeValue { + try Self.nativeValue(contribution, values: values, ledger: ledger, store: store) + } + + private static func nativeValue( + _ contribution: NativeMCPContribution, values: RuntimeBindingValues?, ledger: ResolvedLedger, + store: StateStore ) throws -> NativeValue { func convert(_ value: LedgerValue, path: [MCPValueStep]) throws -> NativeValue { if let resource = contribution.resourcePlacements.first(where: { $0.path == path }), ledger.resources[resource.resource] != nil { - let destination = try resourceDestination(resource.resource, in: ledger) + let destination = try resourceDestination(resource.resource, ledger: ledger, store: store) return .string(destination.path) } switch value.kind { @@ -549,3 +578,95 @@ extension Dictionary { try [Key: T](uniqueKeysWithValues: map { (key, value) in (key, try transform(key, value)) }) } } + +extension ArtifactAggregation { + package static func nativeExposure( + _ deployment: LedgerDeployment, ledger: ResolvedLedger, store: StateStore + ) throws -> (readers: [AgentID]?, sensitive: Bool) { + guard deployment.ownership == .ownedValues else { return (nil, false) } + let path = try deployment.target.resolve(roots: store.ledgerRoots).path + var readers = Set() + var sensitive = false + for lowering in ledger.lowerings where lowering.format.hasSuffix("-mcp@1") { + let c = try MCPLayoutV1.contribution(lowering, ledger: ledger) + let target = try store.nativeTarget(for: DeploymentConstruction.route(c)) + if target.url.path == path { + readers.formUnion(c.descriptor.knownReaders) + sensitive = + try sensitive || c.bindings.contains(where: { !$0.reference }) + || store.materializationReceipt(for: target) != nil + } + } + return (readers.isEmpty ? nil : readers.sorted { $0.rawValue < $1.rawValue }, sensitive) + } + + /// Observes only the owned region. Private receipts validate the entire physical preimage. + package static func inspectDeployment( + _ deployment: LedgerDeployment, ledger: ResolvedLedger, store: StateStore + ) throws -> (status: String, diagnostic: String?) { + let url = try deployment.target.resolve(roots: store.ledgerRoots) + guard FileManager.default.fileExists(atPath: url.path) else { + return ("missing", "managed target is missing") + } + do { + if deployment.route == "agents/skill@1" { + let expected = deployment.expectedHash + let hash = "sha256:" + (try FileHash.folderHash(url)) + let flags = try FileHash.executableFlags(url) + let resources = deployment.owners.flatMap { ledger.components[$0]?.resources ?? [] } + let expectedFlags = resources.first.flatMap { ledger.resources[$0] }.map { + Dictionary( + uniqueKeysWithValues: $0.entries.filter { $0.kind == .file }.map { + ($0.path, $0.executable) + }) + } + return hash == expected && (expectedFlags == nil || expectedFlags == flags) + ? ("current", nil) : ("drifted", "managed skill content or executable mode changed") + } + if deployment.ownership == .ownedValues, + let lowering = ledger.lowerings.first(where: { $0.deployments.contains(deployment.id) }), + lowering.format.hasSuffix("-mcp@1") + { + let c = try MCPLayoutV1.contribution(lowering, ledger: ledger) + let target = try store.nativeTarget(for: DeploymentConstruction.route(c)) + if try store.materializationReceipt(for: target) != nil { return ("current", nil) } + if c.bindings.contains(where: { !$0.reference }) { + return ( + "unverified", + "native materialization needs its private receipt or resource placement evidence" + ) + } + let document = try NativeDocument( + bytes: FileSystem.read(at: url), format: c.descriptor.documentFormat, + budget: NativeDocumentBudget( + limits: .init( + storage: LedgerLimits.standard.resourceBytes, + work: LedgerLimits.standard.encodedBytes, nodes: LedgerLimits.standard.nodes, + depth: LedgerLimits.standard.depth, uninterruptedBytes: LedgerLimits.standard.keyBytes + ))) + let region = try c.descriptor.region( + server: c.name, + nativeProjectKey: c.descriptor.request.scope == .local + ? store.nativeTarget(for: .claudeMCPProject).url.deletingLastPathComponent().path : nil) + guard let observed = try document.read(region) else { + return ("missing", "managed native region is missing") + } + return try observed.value == nativeValue(c, values: nil, ledger: ledger, store: store) + ? ("current", nil) : ("drifted", "managed native region changed") + } + let bytes = try FileSystem.read(at: url) + let hash = + deployment.ownership == .importBlock + ? try InstructionTargets.ownedImportBytes(bytes).map { + "sha256:" + FileHash.sha256Hex(data: $0) + } + : "sha256:" + FileHash.sha256Hex(data: bytes) + return hash == deployment.expectedHash + ? ("current", nil) : ("drifted", "managed instructions changed") + } catch { + return ( + "unverified", "managed target could not be verified; inspect ownership, format and access" + ) + } + } +} diff --git a/Sources/Components/DeploymentConstruction.swift b/Sources/Components/DeploymentConstruction.swift index 5ab1f22..1ff1511 100644 --- a/Sources/Components/DeploymentConstruction.swift +++ b/Sources/Components/DeploymentConstruction.swift @@ -30,15 +30,22 @@ package enum DeploymentConstruction { } package static func route(_ contribution: NativeMCPContribution) throws -> NativeTargetRoute { - guard contribution.descriptor.request.surface == .claudeCode else { + let project = contribution.descriptor.request.scope == .project + switch contribution.descriptor.request.surface { + case .claudeCode: + switch contribution.descriptor.request.scope { + case .project: return .claudeMCPProject + case .local: return .claudeMCPLocal + case .user: return .claudeMCPUser + } + case .codexCLI: return project ? .codexMCPProject : .codexMCPUser + case .geminiCLI: return project ? .geminiMCPProject : .geminiMCPUser + case .cursorEditor: return project ? .cursorMCPProject : .cursorMCPUser + case .openCodeCLI: return project ? .openCodeMCPProjectJSON : .openCodeMCPUserJSON + case .cursorCLI, .cursorCloud: throw NativeAdapterIssue( request: contribution.descriptor.request, component: contribution.name, field: ["route"], - reason: .integrationRequired, detail: "Core registered route is pending integration") - } - switch contribution.descriptor.request.scope { - case .project: return .claudeMCPProject - case .local: return .claudeMCPLocal - case .user: return .claudeMCPUser + reason: .integrationRequired, detail: "this surface has no accepted registered route") } } diff --git a/Sources/Components/LedgerImpact.swift b/Sources/Components/LedgerImpact.swift index 7750e1f..366b816 100644 --- a/Sources/Components/LedgerImpact.swift +++ b/Sources/Components/LedgerImpact.swift @@ -3,15 +3,58 @@ import Foundation /// Selection and protection are projections of the recorded graph, never of mutable producers. package struct LedgerImpact { + package static func identity( + _ c: LedgerComponent, ledger: ResolvedLedger, roots: [String: URL] + ) throws -> String { + try ResolvedLedgerCodec.digest([ + ledger.sourceIdentity(c.declaringSource, roots: roots), + ledger.sourceIdentity(c.source, roots: roots), c.root, c.group ?? "", c.kind, + c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name, + ]) + } + + package static func discoveryFingerprint(_ ledger: ResolvedLedger, roots: [String: URL]) throws + -> String + { + struct Component: Encodable { + let identity: String + let revision: String? + let payload: LedgerValue + let conditions: [LedgerCondition] + let recipients: [AgentID] + let resources: [String] + } + let components = try ledger.components.values.map { c in + Component( + identity: try identity(c, ledger: ledger, roots: roots), revision: c.revision, + payload: c.payload, conditions: c.conditions, recipients: c.recipients, + resources: c.resources.map { ledger.resources[$0]!.hash }) + }.sorted { + if $0.identity != $1.identity { return $0.identity < $1.identity } + return try ResolvedLedgerCodec.digest($0) < ResolvedLedgerCodec.digest($1) + } + let sources = try ledger.sources.keys.map { id in + [try ledger.sourceIdentity(id, roots: roots), ledger.sources[id]!.revision] + }.sorted { $0.lexicographicallyPrecedes($1) } + return try ResolvedLedgerCodec.digest([ + ResolvedLedgerCodec.digest(components), ResolvedLedgerCodec.digest(sources), + ResolvedLedgerCodec.digest(ledger.groups.map(\.manifestHash)), + ]) + } + package let pins: [String: SourceRevision] package let directPins: [ComponentKey: SourceRevision] package init( ledger: ResolvedLedger, roots: [String: URL], kinds: Set, - names: Set, updating: Bool + names: Set, updating: Bool, selectedIdentities: Set? = nil ) throws { func selected(_ c: LedgerComponent) -> Bool { - kinds.contains(DeclaredComponentKind(rawValue: c.kind)!) + if let selectedIdentities { + return (try? Self.identity(c, ledger: ledger, roots: roots)).map( + selectedIdentities.contains) == true + } + return kinds.contains(DeclaredComponentKind(rawValue: c.kind)!) && (names.isEmpty || names.contains(c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name)) } @@ -48,7 +91,7 @@ package struct LedgerImpact { package static func requireProtected( previous: ResolvedLedger, next: ResolvedLedger, kinds: Set, - names: Set = [], roots: [String: URL] + names: Set = [], roots: [String: URL], selectedIdentities: Set? = nil ) throws { struct Projection: Encodable { let component: LedgerComponent @@ -58,10 +101,16 @@ package struct LedgerImpact { func streams(_ ledger: ResolvedLedger) throws -> [String: [String]] { var result: [String: [String]] = [:] for occurrence in ledger.occurrences { - guard var c = ledger.components[occurrence.component], - !kinds.contains(DeclaredComponentKind(rawValue: c.kind)!) - || (!names.isEmpty - && !names.contains(c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name)) + guard var c = ledger.components[occurrence.component] else { continue } + let selected = try selectedIdentities.map { + try $0.contains(identity(c, ledger: ledger, roots: roots)) + } + guard + selected == false + || (selected == nil + && (!kinds.contains(DeclaredComponentKind(rawValue: c.kind)!) + || (!names.isEmpty + && !names.contains(c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name)))) else { continue } func sourceChain(_ id: String) throws -> [LedgerSource] { var result: [LedgerSource] = [] @@ -163,10 +212,15 @@ package struct LedgerImpact { package static func requireEditable( _ ledger: ResolvedLedger, kinds: Set, names: Set, - roots: [String: URL] + roots: [String: URL], selectedIdentities: Set? = nil ) throws { for occurrence in ledger.occurrences where !occurrence.consumerEditable { let c = ledger.components[occurrence.component]! + if let selectedIdentities, + !selectedIdentities.contains(try identity(c, ledger: ledger, roots: roots)) + { + continue + } if kinds.contains(DeclaredComponentKind(rawValue: c.kind)!), names.contains(c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name) { diff --git a/Tests/AgentsSkillsTests/IndexedArtifactLifecycleTests.swift b/Tests/AgentsSkillsTests/IndexedArtifactLifecycleTests.swift index 26143aa..d9722ce 100644 --- a/Tests/AgentsSkillsTests/IndexedArtifactLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/IndexedArtifactLifecycleTests.swift @@ -185,3 +185,43 @@ private final class ArtifactHTTPServer { try? output.fileHandleForReading.close() } } + +extension IndexedArtifactLifecycleTests { + @Test func acknowledgmentRevalidatesTheDisplayedArtifactDigests() throws { + let fixture = try SkillFixture() + let web = fixture.root.appendingPathComponent("watch-web") + try FileManager.default.createDirectory(at: web, withIntermediateDirectories: true) + let server = try ArtifactHTTPServer(root: web) + defer { server.stop() } + func publish(_ body: String) throws { + let bytes = Data("---\nname: watched\ndescription: Watch\n---\n\(body)\n".utf8) + try bytes.write(to: web.appendingPathComponent("watched.md")) + let index = web.appendingPathComponent(".well-known/agent-skills/index.json") + try FileManager.default.createDirectory( + at: index.deletingLastPathComponent(), withIntermediateDirectories: true) + try JSONSerialization.data(withJSONObject: [ + "$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json", + "skills": [ + [ + "name": "watched", "description": "Watch", "type": "skill-md", "url": "/watched.md", + "digest": "sha256:" + FileHash.sha256Hex(data: bytes), + ] + ], + ]).write(to: index) + } + try publish("original") + let watch = SkillOperations.watchOperations() + _ = try watch.add(server.url, alias: "watched", environment: fixture.environment) + let displayed = try #require(watch.status(environment: fixture.environment).first) + let baseline = try Data(contentsOf: fixture.store().watchURL) + try publish("advanced") + #expect(throws: (any Error).self) { + try watch.seen(displayed, environment: fixture.environment) + } + #expect(try Data(contentsOf: fixture.store().watchURL) == baseline) + let current = try #require(watch.status(environment: fixture.environment).first) + _ = try watch.seen(current, environment: fixture.environment) + #expect(try fixture.store().loadWatch().sources[current.sourceID]?.seen == current.current) + #expect(try fixture.store().loadLedger().components.isEmpty) + } +} diff --git a/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift b/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift index 7192c5a..495c4b7 100644 --- a/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift +++ b/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift @@ -4,6 +4,7 @@ import AgentsManifest import AgentsSkills import Foundation import StateTestSupport +import Synchronization import Testing @testable import AgentsUpdates @@ -171,11 +172,17 @@ struct LifecycleCompositionTests { } private final class FixtureBindings: RuntimeBindingProvider { - var calls = 0 - var value = "private literal sentinel" + private let state = Mutex((calls: 0, value: "private literal sentinel")) + var calls: Int { state.withLock { $0.calls } } + var value: String { + get { state.withLock { $0.value } } + set { state.withLock { $0.value = newValue } } + } func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { - calls += 1 - return Data(value.utf8) + state.withLock { + $0.calls += 1 + return Data($0.value.utf8) + } } } diff --git a/Tests/AgentsUpdatesTests/PublicInspectionTests.swift b/Tests/AgentsUpdatesTests/PublicInspectionTests.swift new file mode 100644 index 0000000..318bef4 --- /dev/null +++ b/Tests/AgentsUpdatesTests/PublicInspectionTests.swift @@ -0,0 +1,412 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +@Suite("Public rich lifecycle consumers") +struct PublicInspectionTests { + @Test func coherentInspectionCarriesDocumentGraphAndActualLocationsWithoutWrites() throws { + let f = try UpdateFixture() + try f.declare(agents: [.claudeCode]) + var declaration = try f.store.loadDeclaration() + declaration.components.append( + .mcpServer( + name: "metadata", transport: .stdio(.init(executable: "never-run")), agents: [.claudeCode])) + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + let before = try FileHash.folderHash(f.root) + let snapshot = try UpdateOperations.inspect(environment: f.environment) + #expect(try snapshot.document?.digest == f.store.loadManifest()?.digest) + #expect(snapshot.declaration == declaration) + #expect(snapshot.components.count == 4) + #expect(snapshot.components.allSatisfy { !$0.occurrences.isEmpty }) + #expect( + snapshot.components.allSatisfy { + !$0.selection.identity.contains(f.store.cacheDirectory.path) + }) + #expect(snapshot.sources.contains { $0.identity == "local:" + f.repo.path }) + #expect(snapshot.resources.allSatisfy { $0.location != nil }) + #expect(snapshot.readLocations.contains(f.store.watchURL)) + #expect(snapshot.readLocations.contains(f.root.appendingPathComponent(".mcp.json"))) + #expect(snapshot.deployments.allSatisfy { $0.status == .current }) + #expect(!snapshot.recovery.pending) + #expect(try FileHash.folderHash(f.root) == before) + try f.write("external drift", to: f.target(.claudeCode).appendingPathComponent("SKILL.md")) + let drift = try UpdateOperations.inspect(environment: f.environment) + #expect(drift.deployments.contains { $0.format == "agents/skill@1" && $0.status == .drifted }) + #expect(drift.generation == snapshot.generation) + } + + @Test func producerGroupInspectionPreservesRecordedJoinsAndProvenance() throws { + let f = try UpdateFixture() + try f.write( + """ + version: 1 + groups: + tools: + components: [{kind: mcpServer, name: group-tool, transport: {kind: stdio, executable: never-run}, agents: [claude-code]}] + exports: [tools] + """, to: f.repo.appendingPathComponent(".agent/agents.yaml")) + try f.commit() + try f.write( + """ + version: 1 + sources: {producer: {path: \(f.repo.path)}} + uses: [{source: producer, group: tools}] + """, to: f.store.declarationURL) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + let group = try #require(snapshot.groups.first) + let component = try #require(snapshot.components.first) + let occurrence = try #require(component.occurrences.first) + let sourceRecords = Set(snapshot.sources.map(\.record)) + #expect(snapshot.groups.count == 1) + #expect(group.name == "tools") + #expect(sourceRecords.contains(group.sourceRecord)) + #expect(sourceRecords.contains(component.sourceRecord)) + #expect(sourceRecords.contains(component.declaringSourceRecord)) + #expect(occurrence.reference == group.id) + #expect(occurrence.manifestPath == ".agent/agents.yaml") + #expect(!occurrence.consumerEditable) + #expect(occurrence.dependencyRecords.allSatisfy(sourceRecords.contains)) + #expect(component.recipients == [.claudeCode]) + #expect(snapshot.deployments.first?.ownerRecords == [component.record]) + #expect(snapshot.deployments.first?.status == .current) + #expect(throws: (any Error).self) { + try UpdateOperations.preview( + .init(operation: .remove, selections: [component.selection]), environment: f.environment) + } + } + + @Test func preciseSelectionRemovesOneOfEqualNamesAndRejectsStaleOccurrence() throws { + let f = try UpdateFixture() + let a = f.root.appendingPathComponent("a") + let b = f.root.appendingPathComponent("b") + for root in [a, b] { + try f.write( + "---\nname: same\ndescription: Example\n---\nvalue\n", + to: root.appendingPathComponent("same/SKILL.md")) + } + try f.store.save( + declaration: Declaration( + sources: [ + "a": .init(kind: .local, location: a.path), "b": .init(kind: .local, location: b.path), + ], + components: [ + .skills(source: "a", .init(select: .all, agents: [.codex], mode: .copy)), + .skills(source: "b", .init(select: .all, agents: [.claudeCode], mode: .copy)), + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let inspected = try UpdateOperations.inspect(environment: f.environment) + let selected = try #require(inspected.components.first { $0.source == "local:" + a.path }) + #expect(throws: (any Error).self) { + try UpdateOperations.preview( + .init(operation: .remove, kinds: [.skills], names: ["same"]), environment: f.environment) + } + let request = UpdateRequest(operation: .remove, selections: [selected.occurrences[0].selection]) + let preview = try UpdateOperations.preview(request, environment: f.environment) + #expect(preview.skills.count == 1) + #expect(preview.skills[0].sourceIdentity == "local:" + a.path) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let remaining = try UpdateOperations.inspect(environment: f.environment) + #expect(remaining.components.count == 1) + #expect(remaining.components[0].source == "local:" + b.path) + #expect(remaining.deployments.allSatisfy { $0.status == .current }) + #expect(throws: (any Error).self) { + try UpdateOperations.preview(request, environment: f.environment) + } + } + + @Test func preciseInstructionSelectionPreservesAnEqualNameFromAnotherSource() throws { + let f = try UpdateFixture() + let a = f.root.appendingPathComponent("instructions-a") + let b = f.root.appendingPathComponent("instructions-b") + for root in [a, b] { + try f.write( + "---\ndescription: Same name\n---\n# \(root.lastPathComponent)\n", + to: root.appendingPathComponent("instructions/rules.md")) + } + try f.store.save( + declaration: Declaration( + sources: [ + "a": .init(kind: .local, location: a.path), "b": .init(kind: .local, location: b.path), + ], + components: [ + .instructions(.init(agents: [.claudeCode], sections: ["a:rules"])), + .instructions(.init(agents: [.claudeCode], sections: ["b:rules"])), + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + let selected = try #require(snapshot.components.first { $0.source == "local:" + a.path }) + let request = UpdateRequest(operation: .remove, selections: [selected.selection]) + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let remaining = try UpdateOperations.inspect(environment: f.environment) + #expect(remaining.components.count == 1) + #expect(remaining.components[0].source == "local:" + b.path) + #expect(remaining.deployments.allSatisfy { $0.status == .current }) + } + + @Test(arguments: AgentID.allCases) + func registeredMCPRouteAppliesAndColdRestoresWithoutRunningClient(_ agent: AgentID) throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .mcpServer( + name: "quoted.server", + transport: .stdio(.init(executable: "never-run", arguments: ["fixed"])), agents: [agent]) + ]), ledger: ResolvedLedger()) + let preview = try f.preview() + #expect(preview.components.count == 1) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + let deployed = try #require(snapshot.deployments.first) + #expect(deployed.status == .current) + let bytes = try Data(contentsOf: deployed.location) + let locked = try Data(contentsOf: f.store.resolvedURL) + try FileManager.default.removeItem(at: deployed.location) + _ = try UpdateOperations.restore(environment: f.environment) + #expect(try Data(contentsOf: deployed.location) == bytes) + #expect(try Data(contentsOf: f.store.resolvedURL) == locked) + } + + @Test func publicProviderAndOuterTerminalRetainPrivateBoundary() throws { + struct Provider: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + Data("private-canary".utf8) + } + } + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .mcpServer( + name: "private", + transport: .stdio( + .init(executable: "never-run", environment: ["TOKEN": .secret("token")])), + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + try FileManager.default.createDirectory( + at: f.root.appendingPathComponent("configured-claude"), withIntermediateDirectories: true) + let preview = try f.preview() + #expect( + !String(decoding: try JSONEncoder().encode(preview), as: UTF8.self).contains("private-canary") + ) + let completion = UpdateOperations.perform( + environment: f.environment, bindingProvider: Provider() + ) { update in + try update.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + _ = try completion.result.get() + #expect(completion.disposition == .committed) + #expect(!completion.recovery.pending) + #expect( + !String(decoding: try Data(contentsOf: f.store.resolvedURL), as: UTF8.self).contains( + "private-canary")) + let snapshot = try UpdateOperations.inspect(environment: f.environment) + #expect(snapshot.deployments.allSatisfy { $0.status == .current }) + struct Cancelled: Error {} + let cancelled: UpdateCompletion = UpdateOperations.perform(environment: f.environment) { + _ in throw Cancelled() + } + #expect(cancelled.disposition == .unchanged) + #expect(throws: Cancelled.self) { try cancelled.result.get() } + } + + @Test func watchAcknowledgmentRejectsUndisplayedHead() throws { + let f = try UpdateFixture() + try f.declare() + let watch = SkillOperations.watchOperations() + _ = try watch.add("fixture", environment: f.environment) + let displayed = try #require(watch.status(environment: f.environment).first) + let previous = try f.store.loadWatch() + try f.advance() + #expect(throws: (any Error).self) { + try watch.seen(displayed, environment: f.environment) + } + #expect(try f.store.loadWatch() == previous) + let current = try #require(watch.status(environment: f.environment).first) + _ = try watch.seen(current, environment: f.environment) + #expect(try f.store.loadWatch().sources[current.sourceID]?.seen == current.current) + } + @Test func discoveryRetainsExactEvidenceAndRejectsAChangedSource() throws { + let f = try UpdateFixture() + try f.declare(agents: [.claudeCode]) + let declaration = try f.store.loadDeclaration() + let before = try FileHash.folderHash(f.root) + let discovery = try UpdateOperations.discover(declaration, environment: f.environment) + #expect(!discovery.components.isEmpty) + #expect( + discovery.sourceRevisions.values.flatMap { $0 }.contains(try f.git(["rev-parse", "HEAD"]))) + #expect(try FileHash.folderHash(f.root) == before) + #expect(discovery.readLocations.contains { $0.path == f.repo.path }) + let request = discovery.updateRequest() + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let current = try UpdateOperations.discover(declaration, environment: f.environment) + try f.advance() + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(current.updateRequest(), environment: f.environment) { + _ in + Issue.record("changed discovery must fail before delivering the handle") + } + } + } + + @Test func watchAcknowledgmentRejectsAnAliasRedirectEvenWithTheSameCommit() throws { + let f = try UpdateFixture() + try f.declare() + let watch = SkillOperations.watchOperations() + _ = try watch.add("fixture", environment: f.environment) + let displayed = try #require(watch.status(environment: f.environment).first) + let other = f.root.appendingPathComponent("another-source") + try FileManager.default.copyItem(at: f.repo, to: other) + var declaration = try f.store.loadDeclaration() + declaration.sources["fixture"]?.location = other.path + try f.store.save(declaration: declaration, ledger: f.store.loadLedger()) + let before = try Data(contentsOf: f.store.watchURL) + #expect(throws: (any Error).self) { try watch.seen(displayed, environment: f.environment) } + #expect(try Data(contentsOf: f.store.watchURL) == before) + } + +} + +extension PublicInspectionTests { + @Test func importedAuthoringContentUsesProductionFreezeAndInputFreshness() throws { + let f = try UpdateFixture() + let input = f.root.appendingPathComponent("producer") + let document = input.appendingPathComponent("apm.yml") + let skill = input.appendingPathComponent(".apm/skills/review/SKILL.md") + try f.write("name: example\nversion: '1.0.0'\n", to: document) + try f.write("---\nname: review\ndescription: Review\n---\n# Review\n", to: skill) + let before = try FileHash.folderHash(f.root) + let proposal = try SourceImportOperations.inspect( + format: "apmManifest", root: input, document: "apm.yml") + #expect(proposal.diagnostics.isEmpty) + #expect(proposal.components.count == 1) + #expect(proposal.resources.first?.requiresStandaloneSource == true) + #expect(try FileHash.folderHash(f.root) == before) + let scope = try UpdateOperations.inspect(environment: f.environment) + let request = try proposal.updateRequest(in: scope) + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let installed = try UpdateOperations.inspect(environment: f.environment) + #expect(installed.components.first?.name == "review") + #expect(installed.deployments.allSatisfy { $0.status == .current }) + let newProposal = try SourceImportOperations.inspect( + format: "apmManifest", root: input, document: "apm.yml") + let newRequest = try newProposal.updateRequest(in: installed) + try f.write("---\nname: review\ndescription: Review\n---\n# Changed\n", to: skill) + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(newRequest, environment: f.environment) { _ in + Issue.record("stale imported resources must fail before delivering the handle") + } + } + let target = try #require(installed.deployments.first?.location) + let bytes = try Data(contentsOf: target.appendingPathComponent("SKILL.md")) + try FileManager.default.removeItem(at: input) + try FileManager.default.removeItem(at: f.store.cacheDirectory) + for deployment in installed.deployments { + try FileManager.default.removeItem(at: deployment.location) + } + _ = try UpdateOperations.restore(environment: f.environment) + #expect(try Data(contentsOf: target.appendingPathComponent("SKILL.md")) == bytes) + } + + @Test func importInputChangesDuringCallbackPreventPublication() throws { + let f = try UpdateFixture() + let input = f.root.appendingPathComponent("producer") + let document = input.appendingPathComponent("apm.yml") + try f.write("name: example\nversion: '1.0.0'\n", to: document) + try f.write( + "---\nname: review\ndescription: Review\n---\n# Review\n", + to: input.appendingPathComponent(".apm/skills/review/SKILL.md")) + let proposal = try SourceImportOperations.inspect( + format: "apmManifest", root: input, document: "apm.yml") + let request = try proposal.updateRequest( + in: UpdateOperations.inspect(environment: f.environment)) + let result = UpdateOperations.perform(request, environment: f.environment) { update in + try f.write("name: changed\n", to: document) + return try update.apply() + } + #expect(result.disposition == .unchanged) + #expect(throws: UpdateApplyError.self) { try result.result.get() } + #expect(!FileManager.default.fileExists(atPath: f.store.resolvedURL.path)) + } + @Test func importPreservesUnconvertedAndBindingDiagnostics() throws { + let f = try UpdateFixture() + let input = f.root.appendingPathComponent("producer") + try f.write( + "name: example\nversion: '1.0.0'\nscripts: {start: never-run}\n", + to: input.appendingPathComponent("apm.yml")) + let report = try SourceImportOperations.inspect( + format: "apmManifest", root: input, document: "apm.yml") + #expect(!report.diagnostics.isEmpty) + #expect(report.diagnostics.allSatisfy { !$0.document.isEmpty && !$0.message.isEmpty }) + #expect(throws: (any Error).self) { + try report.updateRequest(in: UpdateOperations.inspect(environment: f.environment)) + } + } + + @Test func ordinarySiblingUpdateKeepsTheWholeSharedFilePrivate() throws { + struct Provider: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + Data("shared-canary".utf8) + } + } + let f = try UpdateFixture() + try FileManager.default.createDirectory( + at: f.root.appendingPathComponent("configured-claude"), withIntermediateDirectories: true) + try f.store.save( + declaration: Declaration(components: [ + .mcpServer( + name: "private", + transport: .stdio( + .init(executable: "never-run", environment: ["TOKEN": .secret("token")])), + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + environment: f.environment, bindingProvider: Provider() + ) { try $0.apply() } + let user = StateStore(scope: .user, environment: f.environment) + try user.save( + declaration: Declaration(components: [ + .mcpServer( + name: "ordinary", transport: .stdio(.init(executable: "never-run")), agents: [.claudeCode] + ) + ]), ledger: ResolvedLedger()) + let preview = try UpdateOperations.preview(scope: .user, environment: f.environment) + #expect(preview.components.allSatisfy { $0.privateMaterialization }) + #expect( + !String(decoding: try JSONEncoder().encode(preview), as: UTF8.self).contains("shared-canary")) + _ = try UpdateOperations.withPreparedUpdate(scope: .user, environment: f.environment) { + try $0.apply() + } + let target = try #require( + UpdateOperations.inspect(scope: .user, environment: f.environment).deployments.first?.location + ) + #expect(String(decoding: try Data(contentsOf: target), as: UTF8.self).contains("shared-canary")) + let mode = + try FileManager.default.attributesOfItem(atPath: target.path)[.posixPermissions] as? NSNumber + #expect(mode?.intValue == 0o600) + #expect( + try UpdateOperations.inspect(environment: f.environment).deployments.allSatisfy { + $0.status == .current + }) + try FileManager.default.removeItem(at: target) + _ = try UpdateOperations.restore(environment: f.environment, bindingProvider: Provider()) + #expect(String(decoding: try Data(contentsOf: target), as: UTF8.self).contains("shared-canary")) + } + +} diff --git a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift index db107a5..cfb4a14 100644 --- a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift +++ b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift @@ -50,6 +50,32 @@ struct UpdateTransactionTests { #expect(try !fixture.preview().hasChanges) } + @Test(arguments: [false, true]) + func outerTerminalReportsTheDurablePublication(_ committed: Bool) throws { + let fixture = try UpdateFixture() + try fixture.install() + let before = try fixture.snapshot() + try fixture.advance() + let point = + committed + ? TransactionCheckpoint.phase(.committed).name + : TransactionCheckpoint.phase(.preparing).name + var interrupted = false + let result = UpdateOperations.perform( + environment: fixture.environment, + checkpoint: { step in + if step == point { + interrupted = true + throw CoreError.invalidState("terminal fixture failure") + } + }, { try $0.apply() }) + #expect(interrupted) + #expect(result.disposition == (committed ? .committed : .rolledBack)) + #expect(!result.recovery.pending) + #expect(throws: UpdateApplyError.self) { try result.result.get() } + if !committed { #expect(try fixture.snapshot() == before) } + } + @Test(arguments: [ "between-kinds", TransactionCheckpoint.phase(.preparing).name, TransactionCheckpoint.persisted(.applying, .entry(0, .publishing), .renamed).name, @@ -120,8 +146,21 @@ struct UpdateTransactionTests { #expect(throws: CoreError.recoveryPending(TransactionRecoveryDiagnostic.pendingMessage)) { try fixture.preview() } + let inspection = try UpdateOperations.inspect(environment: fixture.environment) + #expect(inspection.recovery.pending) + #expect(inspection.components.isEmpty) + var delivered = false + let recovered: UpdateCompletion = UpdateOperations.perform( + environment: fixture.environment + ) { _ in + delivered = true + } + #expect(!delivered) + #expect(recovered.recoveredBeforePreparation) + #expect(recovered.disposition == .unchanged) + #expect(!recovered.recovery.pending) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.apply() + try recovered.result.get() } let committed = committedPoints.contains(checkpoint) if !committed { #expect(try fixture.snapshot() == before) } From 3ae66cc874e1d7008c1067609bf584612a01ec82 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:32:50 +0800 Subject: [PATCH 091/171] refactor: keep manifest schema with its validation owner --- Documentation/Architecture/Package.md | 2 +- Documentation/Reference/Manifest.md | 33 ++++--------------- Package.swift | 2 +- .../ManifestSchemaResource.swift | 14 -------- .../SchemaResourceTests.swift | 16 --------- 5 files changed, 9 insertions(+), 58 deletions(-) delete mode 100644 Sources/AgentsManifest/ManifestSchemaResource.swift delete mode 100644 Tests/AgentsManifestTests/SchemaResourceTests.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 1c1d5bf..34a17e2 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -42,7 +42,7 @@ The frontend reads `.agent/agents.yaml` or the user scope’s `agents.yaml` and produces complete syntax-independent IR and typed declarations. Admission checks UTF-8 and unsupported raw line separators before parsing. Tree-sitter supplies concrete byte ranges under an enforced parser work policy; bounded CST admission -precedes public Yams ordered-node composition. The bundled schema owns field +precedes public Yams ordered-node composition. The source schema owns field shapes and generates finite runtime constraints and reference help. Core scalar resolution preserves string values, integer kind and exact decimal payloads. diff --git a/Documentation/Reference/Manifest.md b/Documentation/Reference/Manifest.md index 5fe56ad..7467d26 100644 --- a/Documentation/Reference/Manifest.md +++ b/Documentation/Reference/Manifest.md @@ -22,7 +22,7 @@ uses: [{group: checks}] exports: [checks] ``` -The distributed [JSON schema](../../Sources/AgentsManifest/Resources/agents.schema.json) +The source [JSON schema](../../Sources/AgentsManifest/Resources/agents.schema.json) is the field-shape owner. [Generated field help](ManifestSchema.md) lists supported shapes, field descriptions, examples and schema-owned collection bounds. The finite compiler rejects unsupported validation keywords, values and combinations; its generated @@ -36,31 +36,6 @@ resolve sources, access resources or execute component programs. Git requirements also apply to local Git repositories declared with `path`; their local source identity and declaring environment remain unchanged. -## Public Schema Resource - -Consumers importing `AgentsManifest` can obtain the bundled schema for offline -editor association or export: - -```swift -import AgentsManifest - -let bytes: [UInt8] = try ManifestSchemaResource.encodedJSON() -``` - -The API returns the exact resource bytes, including descriptions, examples and -`x-agents-*` scalar annotations. It reads no declaration or scope state and uses -no network. All schema references are bundled; the schema identifier is not a -download requirement. Executable distributions must include the Swift package's -resource bundle. A missing or unreadable schema file throws an I/O error; -consumers do not need a checkout or a build-directory path. - -The schema supplies completion, field help and structural validation. Core -diagnostics remain authoritative for YAML admission, scalar kinds, numeric -identity and domain relationships. General JSON Schema treats `1.0` as a -mathematical integer and cannot preserve decimal lexical identity. Saving a -manifest must preserve its YAML text rather than convert it through JSON numbers -or enable schema-driven format conversion. - ## Values and Ordering Sources, groups, components, uses, exports, prompt sections and named ChatGPT @@ -78,6 +53,10 @@ Every decimal is written as `!!float ""`; integer-shaped payloads, negative zero, exponent spelling and trailing zeroes retain identity. This tag is permitted only on NativeValue scalars. `<<` is an ordinary data key. +Core diagnostics are authoritative for YAML admission, scalar kinds, numeric +identity and domain relationships. General JSON Schema treats `1.0` as a +mathematical integer and cannot preserve decimal lexical identity. + UTF-8, a leading BOM, LF/CRLF, block and flow collections and all ordinary scalar styles are supported. Raw NEL, line separator and paragraph separator characters are rejected before either parser; use double-quoted escapes `\u0085`, @@ -90,6 +69,8 @@ directives, complex keys, multiple documents and other tags are rejected. `sources.team` maps to `/sources/0`, its key to `/sources/0/name`, and nested group components to `/groups/0/components/...`. Handles belong to one digest. `ManifestEdit` accepts Core domain values and prepares bytes without writing. +Agents App uses these document and edit APIs for configuration editing. Save +operations preserve YAML text and scalar identity through the prepared edits. No-op changes return exact bytes. Changed fields and collection entries preserve unrelated bytes. Adjacent leading comments and same-line trailing comments belong diff --git a/Package.swift b/Package.swift index b1ab333..2b6005a 100644 --- a/Package.swift +++ b/Package.swift @@ -51,7 +51,7 @@ let package = Package( dependencies: [ "AgentsCore", "TreeSitterYAML", "Yams", .product(name: "TreeSitter", package: "tree-sitter"), - ], resources: [.copy("Resources/agents.schema.json")]), + ], exclude: ["Resources/agents.schema.json"]), .target( name: "AgentsCore", dependencies: ["CPlatform", .product(name: "Crypto", package: "swift-crypto")] diff --git a/Sources/AgentsManifest/ManifestSchemaResource.swift b/Sources/AgentsManifest/ManifestSchemaResource.swift deleted file mode 100644 index e122be7..0000000 --- a/Sources/AgentsManifest/ManifestSchemaResource.swift +++ /dev/null @@ -1,14 +0,0 @@ -import Foundation - -/// The bundled field schema shared by manifest validation, generated help and editor clients. -public enum ManifestSchemaResource { - /// Returns the resource's exact JSON bytes, including its scalar annotations, without reading - /// a declaration or accessing a scope or network. Consumers must distribute the package's - /// resource bundle with their executable. A missing or unreadable schema file throws an I/O error. - public static func encodedJSON() throws -> [UInt8] { - guard let url = Bundle.module.url(forResource: "agents.schema", withExtension: "json") else { - throw CocoaError(.fileReadNoSuchFile) - } - return try Array(Data(contentsOf: url)) - } -} diff --git a/Tests/AgentsManifestTests/SchemaResourceTests.swift b/Tests/AgentsManifestTests/SchemaResourceTests.swift deleted file mode 100644 index 6cc65b2..0000000 --- a/Tests/AgentsManifestTests/SchemaResourceTests.swift +++ /dev/null @@ -1,16 +0,0 @@ -import AgentsManifest -import Foundation -import Testing - -@Suite("Manifest schema resource") -struct SchemaResourceTests { - @Test func exportedBytesMatchTheCanonicalResource() throws { - let resource = URL(fileURLWithPath: #filePath) - .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() - .appendingPathComponent("Sources/AgentsManifest/Resources/agents.schema.json") - let expected = try Data(contentsOf: resource) - let exported = try ManifestSchemaResource.encodedJSON() - #expect(exported == Array(expected)) - _ = try JSONSerialization.jsonObject(with: Data(exported)) - } -} From b3ce7cb5294582fe1b678d5ca78dea61a045e6df Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:45:07 +0800 Subject: [PATCH 092/171] fix: redact normalized MCP tool descriptions --- .../MCPConnectionOperations.swift | 19 +++++++++++++------ .../MCPConnectionOperationsTests.swift | 19 +++++++++++++++---- Tests/MCPTestProcess/main.swift | 4 +++- 3 files changed, 31 insertions(+), 11 deletions(-) diff --git a/Sources/AgentsUpdates/MCPConnectionOperations.swift b/Sources/AgentsUpdates/MCPConnectionOperations.swift index b9bc872..4e2e547 100644 --- a/Sources/AgentsUpdates/MCPConnectionOperations.swift +++ b/Sources/AgentsUpdates/MCPConnectionOperations.swift @@ -330,18 +330,25 @@ public enum MCPConnectionOperations { outcome = .failed issue = .init(rawValue: error.rawValue) } - let redactions = Set(privateValues.filter { !$0.isEmpty }).sorted { $0.count > $1.count } + func withoutControls(_ value: String) -> String { + String(value.unicodeScalars.filter { !CharacterSet.controlCharacters.contains($0) }) + } + // Match the final text projection, including private values containing + // controls. No character removal may join text after this masking pass. + let redactions = Set(privateValues.map(withoutControls).filter { !$0.isEmpty }).sorted { + $0.count > $1.count + } let expression = try NSRegularExpression( pattern: redactions.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|")) func redact(_ value: String) -> String { + let filtered = withoutControls(value) let text = redactions.isEmpty - ? value + ? filtered : expression.stringByReplacingMatches( - in: value, range: NSRange(value.startIndex..., in: value), withTemplate: "[redacted]") - let filtered = String( - text.unicodeScalars.filter { !CharacterSet.controlCharacters.contains($0) }) - var bytes = Data(filtered.utf8.prefix(options.limits.textBytes)) + in: filtered, range: NSRange(filtered.startIndex..., in: filtered), + withTemplate: "[redacted]") + var bytes = Data(text.utf8.prefix(options.limits.textBytes)) // A byte cap may split the last Unicode scalar; remove only that suffix. while String(data: bytes, encoding: .utf8) == nil { bytes.removeLast() } return String(decoding: bytes, as: UTF8.self) diff --git a/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift b/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift index 0808dc0..15e81c0 100644 --- a/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift +++ b/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift @@ -99,12 +99,15 @@ private final class MCPFacadeFixture { @Suite(.serialized) struct MCPConnectionOperationsTests { @Test func describeIsPureAndExactSelectionUsesOnlyNecessaryBindings() async throws { let fixture = try MCPFacadeFixture() - let spy = MCPBindingSpy(["wanted": Data("provider-canary".utf8)]) + let spy = MCPBindingSpy([ + "wanted": Data("provider-canary".utf8), "controlled": Data("control-\ncanary".utf8), + ]) let selected = try fixture.snapshot( "facade", values: [ "FACADE_SECRET": .secret("wanted"), "SECOND_SECRET": .secret("wanted"), "FACADE_LITERAL": .literal("literal-canary"), "FACADE_ENV": .environment("SELECTED_ENV"), + "FACADE_CONTROLLED": .secret("controlled"), ]) let other = try fixture.snapshot( "wrong-version", selection: "source-b/same-name", values: ["UNUSED": .secret("unused")]) @@ -112,7 +115,7 @@ private final class MCPFacadeFixture { let description = MCPConnectionOperations.describe(selected) #expect(description.snapshotID == selected.id && selected.id != other.id) #expect(description.startsOwnedProcess) - #expect(description.requiredBindings == ["wanted"]) + #expect(description.requiredBindings == ["controlled", "wanted"]) #expect(description.environmentBindings == ["SELECTED_ENV"]) #expect(spy.calls.isEmpty && fixture.text("pid") == nil) #expect( @@ -126,12 +129,20 @@ private final class MCPFacadeFixture { #expect(result.cleanupComplete && result.startedAt <= result.finishedAt) #expect(result.elapsed >= 0 && result.transport == .stdio) #expect(result.tools.map(\.name) == ["first", "second"]) - #expect(spy.calls == ["wanted"]) + #expect(spy.calls == ["controlled", "wanted"]) let encoded = String(decoding: try JSONEncoder().encode(result), as: UTF8.self) - for secret in ["provider-canary", "literal-canary", "environment-canary", fixture.root.path] { + for secret in [ + "provider-canary", "control-canary", "literal-canary", "environment-canary", + fixture.root.path, + ] { #expect(!encoded.contains(secret)) } #expect(result.tools.allSatisfy { $0.description?.contains("[redacted]") == true }) + #expect( + result.tools.allSatisfy { + $0.description?.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) + == false + }) let pid = try #require(Int32(fixture.text("pid") ?? "")) #expect(kill(pid, 0) == -1 && errno == ESRCH) try fixture.unchanged() diff --git a/Tests/MCPTestProcess/main.swift b/Tests/MCPTestProcess/main.swift index 9196d65..7cf726b 100644 --- a/Tests/MCPTestProcess/main.swift +++ b/Tests/MCPTestProcess/main.swift @@ -192,8 +192,10 @@ while true { "description": scenario == "long-text" ? String(repeating: "x", count: 17) : scenario == "facade" - ? ["FACADE_SECRET", "FACADE_LITERAL", "FACADE_ENV"].map { + ? ["FACADE_SECRET", "FACADE_LITERAL", "FACADE_ENV", "FACADE_CONTROLLED"].map { ProcessInfo.processInfo.environment[$0] ?? "absent" + }.map { value in + value + " " + value.replacingOccurrences(of: "-", with: "-\n") }.joined(separator: " ") : "fixture", "inputSchema": ["type": "object"], ] From c7f4532239fea288a9de040edd21c0d395e2cd43 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:01:48 +0800 Subject: [PATCH 093/171] feat: import native component declarations and provenance --- .../Components/Import/ImportFrontmatter.swift | 18 +- .../Import/NativeCatalogImport.swift | 164 ++++++ .../Import/NativeContainerImport.swift | 355 +++++++++++++ .../Import/NativeExecutableMembers.swift | 239 +++++++++ .../Components/Import/NativeImportInput.swift | 341 ++++++++++++ .../Import/NativeImportSemantics.swift | 32 ++ .../Import/NativeMemberImport.swift | 133 +++++ .../Import/NativeSourceImport.swift | 486 ++++++++++++++++++ Sources/Components/Import/SourceImport.swift | 6 + .../Import/SourceImportProposal.swift | 54 +- .../Components/Import/YAMLSourceImport.swift | 12 +- Tests/ComponentsTests/ImportNativeTests.swift | 339 ++++++++++++ .../ComponentsTests/ImportProfileTests.swift | 36 ++ 13 files changed, 2207 insertions(+), 8 deletions(-) create mode 100644 Sources/Components/Import/NativeCatalogImport.swift create mode 100644 Sources/Components/Import/NativeContainerImport.swift create mode 100644 Sources/Components/Import/NativeExecutableMembers.swift create mode 100644 Sources/Components/Import/NativeImportInput.swift create mode 100644 Sources/Components/Import/NativeImportSemantics.swift create mode 100644 Sources/Components/Import/NativeMemberImport.swift create mode 100644 Sources/Components/Import/NativeSourceImport.swift create mode 100644 Tests/ComponentsTests/ImportNativeTests.swift diff --git a/Sources/Components/Import/ImportFrontmatter.swift b/Sources/Components/Import/ImportFrontmatter.swift index 4635c28..738ea7d 100644 --- a/Sources/Components/Import/ImportFrontmatter.swift +++ b/Sources/Components/Import/ImportFrontmatter.swift @@ -9,11 +9,20 @@ enum ImportFrontmatter { _ bytes: Data, document: String, converted: Set, profile: SourceImportProfile, limits: SourceImportLimits ) throws -> (diagnostics: [SourceImportDiagnostic], bindings: [ImportBindingRequirement]) { + let parsed = try read(bytes, document: document, limits: limits) + var diagnostics = ImportDiagnostics(proposal: .init(profile: profile)) + parsed.header?.unknown(converted, into: &diagnostics) + return (diagnostics.proposal.diagnostics, diagnostics.proposal.bindings) + } + + static func read(_ bytes: Data, document: String, limits: SourceImportLimits) throws + -> (header: ImportYAML?, body: Data) + { let source = Array(bytes) let bom = source.starts(with: [0xEF, 0xBB, 0xBF]) ? 3 : 0 guard source.count >= bom + 4, Array(source[bom..<(bom + 3)]) == [45, 45, 45], [10, 13].contains(source[bom + 3]) - else { return ([], []) } + else { return (nil, bytes) } var index = bom + 3 if source[index] == 13 { index += 1 } if index < source.count, source[index] == 10 { index += 1 } @@ -36,9 +45,10 @@ enum ImportFrontmatter { let root = ImportYAML(reader: reader, node: reader.root, pointer: "/frontmatter") try ImportYAML.check(reader.root, limits: limits) guard root.pairs != nil else { throw ImportReadFailure.invalid } - var diagnostics = ImportDiagnostics(proposal: .init(profile: profile)) - root.unknown(converted, into: &diagnostics) - return (diagnostics.proposal.diagnostics, diagnostics.proposal.bindings) + var bodyStart = index + if bodyStart < source.count, source[bodyStart] == 13 { bodyStart += 1 } + if bodyStart < source.count, source[bodyStart] == 10 { bodyStart += 1 } + return (root, Data(source[bodyStart...])) } if index < source.count, source[index] == 13 { index += 1 } if index < source.count, source[index] == 10 { index += 1 } diff --git a/Sources/Components/Import/NativeCatalogImport.swift b/Sources/Components/Import/NativeCatalogImport.swift new file mode 100644 index 0000000..57409ee --- /dev/null +++ b/Sources/Components/Import/NativeCatalogImport.swift @@ -0,0 +1,164 @@ +import AgentsCore +import Foundation + +/// Catalog entries are coordinates only. Resolution, selection and fetching stay with B. +enum NativeCatalogImport { + static func read( + _ input: SourceImportInput, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + let parsed = try NativeImportDocument(input, format: .json, limits: limits) + NativeImportInput.unknown( + parsed.fields, allowed: ["name", "plugins"], at: parsed.location(), + into: &diagnostics) + guard let catalogName = parsed.fields["name"]?.importString, + NativeImportInput.name(catalogName), + parsed.fields["owner"]?.importObject?["name"]?.importString?.isEmpty == false, + case .array(let entries) = parsed.fields["plugins"] + else { + throw ImportReadFailure.invalid + } + guard let selection = input.selection else { + diagnostics.add( + .unconverted, parsed.location(["plugins"]), + "Catalog coordinates require an explicit entry selection; no catalog is installed or resolved." + ) + return + } + let suffix = ".claude-plugin/marketplace.json" + guard input.document == suffix || input.document.hasSuffix("/" + suffix) else { + throw ImportReadFailure.invalid + } + let root = input.document == suffix ? "." : String(input.document.dropLast(suffix.count + 1)) + var counts: [String: Int] = [:] + for value in entries { + if let name = value.importObject?["name"]?.importString { counts[name, default: 0] += 1 } + } + var selected: Set = [] + for (index, value) in entries.enumerated() { + let origin = parsed.location(["plugins"]).appending(String(index)) + guard let fields = value.importObject, let name = fields["name"]?.importString, + NativeImportInput.name(name) + else { + NativeImportInput.unconverted(value, at: origin, into: &diagnostics) + continue + } + guard selection.contains(name) else { continue } + if counts[name, default: 0] > 1 { + diagnostics.add( + .ambiguousSource, origin, + "Catalog selection has multiple declarations; no source is chosen.") + continue + } + guard selected.insert(name).inserted else { + diagnostics.add( + .ambiguousSource, origin, "Selected catalog name has multiple declarations.") + continue + } + NativeImportInput.unknown( + fields, + allowed: [ + "name", "source", "version", "description", "author", "homepage", "keywords", "category", + "tags", "strict", + ], at: origin, into: &diagnostics) + if let strict = fields["strict"], strict != .boolean(true) { + NativeImportInput.unconverted(strict, at: origin.appending("strict"), into: &diagnostics) + continue + } + for key in ["version", "description", "author", "homepage", "keywords", "category", "tags"] + where fields[key] != nil { + NativeImportInput.unconverted(fields[key]!, at: origin.appending(key), into: &diagnostics) + } + let declaration: SourceDeclaration + var exact: String? + var requested: String? + var path: String? + if let local = fields["source"]?.importString { + let relative = try NativeSourceImport.nativePath(local, container: root) + let location = root == "." ? relative : root + "/" + relative + declaration = .init( + kind: .local, location: location, + environment: .init(projectDirectory: input.root, homeDirectory: input.root)) + diagnostics.add( + .incompletePin, origin, + "Local catalog entry needs explicit content capture; a version label is not an exact content pin." + ) + } else if let source = fields["source"]?.importObject { + NativeImportInput.unknown( + source, allowed: ["source", "repo", "url", "ref", "sha", "path"], + at: origin.appending("source"), into: &diagnostics) + let location: String + if source["source"] == .string("github"), let repo = source["repo"]?.importString, + repo.split(separator: "/", omittingEmptySubsequences: false).count == 2, + repo.split(separator: "/", omittingEmptySubsequences: false).allSatisfy({ + $0.range(of: #"^[A-Za-z0-9._-]+$"#, options: .regularExpression) != nil + }) + { + location = "https://github.com/" + repo + } else if [NativeValue.string("url"), .string("git-subdir")].contains( + source["source"] ?? .null), + let url = source["url"]?.importString + { + guard ImportInput.safeLocator(url) else { + diagnostics.binding(origin.appending("source")) + continue + } + location = url + } else { + NativeImportInput.unconverted( + fields["source"]!, at: origin.appending("source"), into: &diagnostics) + continue + } + exact = ImportInput.hex(source["sha"]?.importString, count: 40) + requested = source["ref"]?.importString + if source["source"] == .string("git-subdir") { + guard let raw = source["path"]?.importString else { + diagnostics.add( + .invalidInput, origin.appending("source/path"), + "Git subdirectory source requires an explicit path.") + continue + } + path = try NativeSourceImport.nativePath(raw, container: root) + } else if source["path"] != nil { + NativeImportInput.unconverted( + source["path"]!, at: origin.appending("source/path"), into: &diagnostics) + continue + } + declaration = .init( + kind: .git, location: location, requirement: exact.map(SourceRequirement.revision), + path: path) + guard (try? declaration.transportIdentity()) != nil else { + diagnostics.add( + .invalidInput, origin, "Catalog Git coordinate is not a valid canonical source.") + continue + } + if exact == nil { + diagnostics.add( + .incompletePin, origin, + "Catalog ref/version is requested provenance; no resolved commit is invented or fetched." + ) + } + } else { + NativeImportInput.unconverted( + fields["source"] ?? .null, at: origin.appending("source"), into: &diagnostics) + continue + } + let alias = "catalog-\(index)" + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: origin, declaration: declaration, + pin: .init(commit: exact), requestedRef: requested, producerPath: path, + producerIdentity: name)) + NativeImportInput.emit( + .plugin( + name: name, path: ".", source: alias, mode: .components, agents: [.claudeCode]), + selector: .plugin(name: name), origin: origin, container: root, profile: input.profile, + into: &diagnostics) + } + if !selection.isSubset(of: selected) { + diagnostics.add( + .invalidInput, parsed.location(["plugins"]), + "A selected catalog entry is absent or invalid.") + } + } +} diff --git a/Sources/Components/Import/NativeContainerImport.swift b/Sources/Components/Import/NativeContainerImport.swift new file mode 100644 index 0000000..def4d37 --- /dev/null +++ b/Sources/Components/Import/NativeContainerImport.swift @@ -0,0 +1,355 @@ +import AgentsCore +import Foundation + +/// Container discovery uses producer roots, never the parser's working directory. +enum NativeContainerImport { + static func read( + _ input: SourceImportInput, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + let suffix: String + switch input.profile { + case .claudePluginV1: suffix = ".claude-plugin/plugin.json" + case .cursorPluginV1: suffix = ".cursor-plugin/plugin.json" + default: suffix = "gemini-extension.json" + } + guard input.document == suffix || input.document.hasSuffix("/" + suffix) else { + diagnostics.add( + .invalidInput, .init(document: input.document, pointer: ""), + "Manifest location does not match the selected native container profile.") + return + } + let root = input.document == suffix ? "." : String(input.document.dropLast(suffix.count + 1)) + let parsed = try NativeImportDocument(input, format: .json, limits: limits) + guard let name = parsed.fields["name"]?.importString, NativeImportInput.name(name) else { + throw ImportReadFailure.invalid + } + let snapshot = try ImportInput.snapshot(input.root) + try parsed.admission.resource(try snapshot.resource(root), snapshot: snapshot) + let agent = NativeImportInput.agent(input.profile) + let alias = NativeImportInput.source( + input, root: root, origin: parsed.location(), into: &diagnostics) + let metadata: Set = ["name", "version"] + let members: Set = + agent == .geminiCLI + ? ["mcpServers", "contextFileName"] + : ["commands", "agents", "skills", "hooks", "mcpServers", "lspServers", "rules"] + NativeImportInput.unknown( + parsed.fields, allowed: metadata.union(members), at: parsed.location(), into: &diagnostics) + if agent == .geminiCLI, parsed.fields["version"]?.importString?.isEmpty != false { + diagnostics.add( + .invalidInput, parsed.location(["version"]), "Native extension requires a version string.") + return + } + // A container contributes typed children; .native selection/registration belongs to B/F. + // Unknown/dependency fields are already diagnosed rather than becoming opaque payloads. + for (field, kind, folder) in [ + ("commands", DeclaredComponentKind.command, "commands"), + ("agents", .subagent, "agents"), ("skills", .skills, "skills"), + ] { + let supplied = parsed.fields[field] + if agent == .geminiCLI, supplied != nil { + NativeImportInput.unconverted(supplied!, at: parsed.location([field]), into: &diagnostics) + continue + } + var paths: [String] = [] + var explicitPaths: Set = [] + // Cursor explicit paths replace default discovery. Claude paths add to defaults. + if agent != .cursor || supplied == nil { paths.append(folder) } + if let supplied { + if let path = supplied.importString { + let relative = try componentPath(path, agent: agent) + explicitPaths.insert(relative) + paths.append(relative) + } else if let list = supplied.importStrings { + let relative = try list.map { try componentPath($0, agent: agent) } + explicitPaths.formUnion(relative) + paths += relative + } else { + NativeImportInput.unconverted(supplied, at: parsed.location([field]), into: &diagnostics) + } + } + var seen: Set = [] + for path in paths where seen.insert(path).inserted { + try discover( + path, kind: kind, root: root, input: input, limits: limits, into: &diagnostics, + admission: parsed.admission, + requiredOrigin: explicitPaths.contains(path) ? parsed.location([field]) : nil) + } + } + var mcpSources: [(NativeValue, NativeImportDocument, [String])] = [] + let mcpDefault = agent == .cursor ? "mcp.json" : ".mcp.json" + if agent != .geminiCLI, agent != .cursor || parsed.fields["mcpServers"] == nil, + let document = try optionalDocument( + mcpDefault, root: root, input: input, limits: limits, admission: parsed.admission) + { + NativeImportInput.unknown( + document.fields, allowed: ["mcpServers"], at: document.location(), into: &diagnostics) + if let map = document.fields["mcpServers"] { + mcpSources.append((map, document, ["mcpServers"])) + } else { + NativeImportInput.unconverted( + .object(document.fields), at: document.location(), into: &diagnostics) + } + } + if let declared = parsed.fields["mcpServers"] { + try configurations( + declared, field: "mcpServers", parsed: parsed, root: root, limits: limits, + into: &mcpSources, diagnostics: &diagnostics) + } + // The producer loads defaults then declarations; later duplicate names replace earlier ones. + var winners: [String: (NativeValue, NativeImportDocument, [String])] = [:] + for (value, document, keys) in mcpSources { + guard let fields = value.importObject else { throw ImportReadFailure.invalid } + for (name, entry) in fields { + if let previous = winners[name] { + diagnostics.add( + .unconverted, previous.1.location(previous.2 + [name]), + "Later native MCP declaration replaces this earlier source member.") + } + winners[name] = (entry, document, keys) + } + } + for name in winners.keys.sorted() { + let winner = winners[name]! + try NativeSourceImport.mcp( + .object([name: winner.0]), parsed: winner.1, keys: winner.2, + container: root, limits: limits, into: &diagnostics) + } + var observed: Set = [] + for (_, document, _) in mcpSources + where document.input.document != input.document + && observed.insert(document.input.document).inserted + { + let relative = + root == "." + ? document.input.document : String(document.input.document.dropFirst(root.count + 1)) + let rewrite = diagnostics.proposal.bindings.contains { + $0.location.document == document.input.document + } + try NativeImportInput.resource( + relative, root: root, input: input, origin: document.location(), limits: limits, + rewrite: rewrite, into: &diagnostics, admission: parsed.admission) + } + var lspSources: [(NativeValue, NativeImportDocument, [String])] = [] + if agent == .claudeCode, + let document = try optionalDocument( + ".lsp.json", root: root, input: input, limits: limits, admission: parsed.admission) + { + lspSources.append((.object(document.fields), document, [])) + } + if let value = parsed.fields["lspServers"] { + try configurations( + value, field: "lspServers", parsed: parsed, root: root, limits: limits, into: &lspSources, + diagnostics: &diagnostics) + } + var lspWinners: [String: (NativeValue, NativeImportDocument, [String])] = [:] + for (value, document, keys) in lspSources { + for (name, entry) in value.importObject ?? [:] { lspWinners[name] = (entry, document, keys) } + } + for name in lspWinners.keys.sorted() { + let entry = lspWinners[name]! + try NativeSourceImport.lsp( + .object([name: entry.0]), parsed: entry.1, keys: entry.2, container: root, limits: limits, + into: &diagnostics) + } + var hookSources: [(NativeValue, NativeImportDocument, [String])] = [] + if agent != .cursor || parsed.fields["hooks"] == nil, + let document = try optionalDocument( + "hooks/hooks.json", root: root, input: input, limits: limits, admission: parsed.admission), + let value = document.fields["hooks"] + { + NativeImportInput.unknown( + document.fields, allowed: ["hooks"], at: document.location(), into: &diagnostics) + hookSources.append((value, document, ["hooks"])) + } + if let value = parsed.fields["hooks"] { + try configurations( + value, field: "hooks", parsed: parsed, root: root, limits: limits, into: &hookSources, + diagnostics: &diagnostics) + } + for (value, document, keys) in hookSources { + try NativeSourceImport.hooks( + value, parsed: document, keys: keys, container: root, limits: limits, into: &diagnostics) + } + for (_, document, _) in lspSources + hookSources + where document.input.document != input.document + && observed.insert(document.input.document).inserted + { + let path = + root == "." + ? document.input.document : String(document.input.document.dropFirst(root.count + 1)) + let rewrite = diagnostics.proposal.bindings.contains { + $0.location.document == document.input.document + } + try NativeImportInput.resource( + path, root: root, input: input, origin: document.location(), limits: limits, + rewrite: rewrite, into: &diagnostics, admission: parsed.admission) + } + for field in ["rules", "contextFileName"] where parsed.fields[field] != nil { + NativeImportInput.unconverted( + parsed.fields[field]!, at: parsed.location([field]), into: &diagnostics) + } + // Record the actual manifest, not a raw original bundle containing credential literals. + let rewrite = diagnostics.proposal.bindings.contains { $0.location.document == input.document } + try NativeImportInput.resource( + suffix, root: root, input: input, origin: parsed.location(), limits: limits, rewrite: rewrite, + into: &diagnostics, admission: parsed.admission) + if diagnostics.proposal.components.isEmpty { + diagnostics.add( + .unconverted, parsed.location(), + "No typed child was converted; native container preservation/registration remains an explicit B/F operation." + ) + } + _ = alias + } + + private static func componentPath(_ path: String, agent: AgentID) throws -> String { + if agent == .claudeCode, !path.hasPrefix("./"), path != "." { + throw CoreError.unsafePath("native component path") + } + return try NativeSourceImport.nativePath(path, container: ".") + } + + private static func configurations( + _ value: NativeValue, field: String, parsed: NativeImportDocument, + root: String, limits: SourceImportLimits, + into sources: inout [(NativeValue, NativeImportDocument, [String])], + diagnostics: inout ImportDiagnostics + ) throws { + if let path = value.importString { + let relative = try componentPath(path, agent: NativeImportInput.agent(parsed.input.profile)) + guard + let document = try optionalDocument( + relative, root: root, input: parsed.input, limits: limits, admission: parsed.admission) + else { + diagnostics.add( + .missingResource, parsed.location([field]), "Explicit native component file is absent.") + return + } + guard + let fields = field == "lspServers" + ? NativeValue.object(document.fields) : document.fields[field] + else { + NativeImportInput.unconverted( + .object(document.fields), at: document.location(), into: &diagnostics) + return + } + if field != "lspServers" { + NativeImportInput.unknown( + document.fields, allowed: [field], + at: document.location(), into: &diagnostics) + } + sources.append((fields, document, [field])) + } else if case .array(let entries) = value { + for entry in entries { + try configurations( + entry, field: field, parsed: parsed, root: root, limits: limits, into: &sources, + diagnostics: &diagnostics) + } + } else if value.importObject != nil, NativeImportInput.agent(parsed.input.profile) != .cursor { + sources.append((value, parsed, [field])) + } else { + NativeImportInput.unconverted(value, at: parsed.location([field]), into: &diagnostics) + } + } + + private static func optionalDocument( + _ path: String, root: String, input: SourceImportInput, + limits: SourceImportLimits, admission: NativeImportBudget + ) throws -> NativeImportDocument? { + let relative = root == "." ? path : root + "/" + path + let snapshot = try ImportInput.snapshot(input.root) + let url = try snapshot.resource(relative) + guard FileManager.default.fileExists(atPath: url.path) else { return nil } + return try NativeImportDocument( + .init(profile: input.profile, root: input.root, document: relative), format: .json, + limits: limits, admission: admission) + } + + private static func discover( + _ path: String, kind: DeclaredComponentKind, root: String, + input: SourceImportInput, limits: SourceImportLimits, into diagnostics: inout ImportDiagnostics, + admission: NativeImportBudget, requiredOrigin: ImportLocation? + ) throws { + let snapshot = try ImportInput.snapshot(input.root) + let relative = root == "." ? path : root + (path == "." ? "" : "/" + path) + let url = try snapshot.resource(relative) + var directory: ObjCBool = false + guard FileManager.default.fileExists(atPath: url.path, isDirectory: &directory) else { + if let requiredOrigin { + diagnostics.add(.missingResource, requiredOrigin, "Explicit native member path is absent.") + } + return + } + var files: [String] = [] + if directory.boolValue { + guard let iterator = FileManager.default.enumerator(at: url, includingPropertiesForKeys: nil) + else { throw ImportReadFailure.invalid } + for case let file as URL in iterator { + try Task.checkCancellation() + guard files.count < limits.resourceEntries else { throw ImportReadFailure.invalid } + let location = try snapshot.relativePath(file) + let attributes = try FileManager.default.attributesOfItem(atPath: file.path) + guard attributes[.type] as? FileAttributeType != .typeSymbolicLink else { + diagnostics.add( + .unconverted, .init(document: location, pointer: ""), + "Native member discovery through a link requires explicit contained support closure.") + iterator.skipDescendants() + continue + } + if attributes[.type] as? FileAttributeType == .typeRegular { files.append(location) } + } + } else { + files = [relative] + } + for file in files.sorted() { + if kind == .skills { + guard URL(fileURLWithPath: file).lastPathComponent == "SKILL.md" else { continue } + let skillPath = (file as NSString).deletingLastPathComponent + let content = try ImportSkillContent.read(skillPath, input: input, limits: limits) + diagnostics.proposal.diagnostics += content.diagnostics + diagnostics.proposal.bindings += content.bindings + if !content.bindings.isEmpty { continue } + let alias = "native-skill-" + String(diagnostics.proposal.sources.count) + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: .init(document: file, pointer: ""), + declaration: .init( + kind: .local, location: skillPath, + environment: .init(projectDirectory: input.root, homeDirectory: input.root)), + pin: .init(), requestedRef: nil, producerPath: skillPath)) + NativeImportInput.emit( + .skills( + source: alias, + .init( + select: .names([content.skill.name]), + agents: [NativeImportInput.agent(input.profile)], condition: content.skill.condition)), + selector: .skill(name: content.skill.name), + origin: .init(document: file, pointer: "/frontmatter"), container: root, + profile: input.profile, into: &diagnostics, admission: admission) + diagnostics.proposal.resources.append( + .init( + origin: .init(document: file, pointer: ""), sourceAlias: alias, + producerName: content.skill.name, path: ".", producerIntegrity: nil, + observedHash: content.hash, + executableFlags: content.flags, requiresStandaloneSource: true, kind: .skills)) + } else { + let ext = URL(fileURLWithPath: file).pathExtension + let allowed = + NativeImportInput.agent(input.profile) == .geminiCLI && kind == .command + ? ["toml"] : ["md", "mdc", "markdown", "txt"] + guard allowed.contains(ext) else { + diagnostics.add( + .unconverted, .init(document: file, pointer: ""), + "Native directory file has no converted member format.") + continue + } + try NativeMemberImport.read( + .init(profile: input.profile, root: input.root, document: file), container: root, + kind: kind, limits: limits, into: &diagnostics, admission: admission, + discoveryRoot: relative) + } + } + } +} diff --git a/Sources/Components/Import/NativeExecutableMembers.swift b/Sources/Components/Import/NativeExecutableMembers.swift new file mode 100644 index 0000000..5914482 --- /dev/null +++ b/Sources/Components/Import/NativeExecutableMembers.swift @@ -0,0 +1,239 @@ +import AgentsCore +import Foundation + +extension NativeSourceImport { + static func hooks( + _ value: NativeValue, parsed: NativeImportDocument, keys: [String], + container: String, limits: SourceImportLimits, into diagnostics: inout ImportDiagnostics + ) throws { + let agent = NativeImportInput.agent(parsed.input.profile) + guard [.claudeCode, .cursor].contains(agent), let events = value.importObject else { + NativeImportInput.unconverted(value, at: parsed.location(keys), into: &diagnostics) + return + } + let admitted = + agent == .claudeCode + ? NativeDocumentedHooksV1.claudeEvents : NativeDocumentedHooksV1.cursorEvents + for event in events.keys.sorted() { + let location = parsed.location(keys + [event]) + guard admitted.contains(event), case .array(let groups) = events[event] else { + NativeImportInput.unconverted(events[event]!, at: location, into: &diagnostics) + continue + } + for (groupIndex, group) in groups.enumerated() { + let groupLocation = location.appending(String(groupIndex)) + let handlers: [NativeValue] + let matcher: String? + if agent == .claudeCode { + guard let fields = group.importObject, + Set(fields.keys).isSubset(of: ["matcher", "hooks"]), + case .array(let values) = fields["hooks"], + fields["matcher"] == nil || fields["matcher"]?.importString != nil + else { + NativeImportInput.unconverted(group, at: groupLocation, into: &diagnostics) + continue + } + handlers = values + matcher = fields["matcher"]?.importString + } else { + handlers = [group] + matcher = group.importObject?["matcher"]?.importString + } + if let matcher, + !NativeDocumentedHooksV1.admittedMatcher(matcher) + || (agent == .claudeCode + && NativeDocumentedHooksV1.claudeWithoutMatcher.contains(event)) + || (agent == .cursor && !NativeDocumentedHooksV1.cursorMatcherEvents.contains(event)) + { + diagnostics.add( + .unconverted, groupLocation, + "F's native event/matcher contract cannot preserve this matcher.") + continue + } + for (handlerIndex, handler) in handlers.enumerated() { + let origin = groupLocation.appending("hooks/\(handlerIndex)") + guard let fields = handler.importObject else { + NativeImportInput.unconverted(handler, at: origin, into: &diagnostics) + continue + } + let allowed: Set = + agent == .cursor + ? ["type", "command", "timeout", "matcher"] : ["type", "command", "timeout"] + NativeImportInput.unknown(fields, allowed: allowed, at: origin, into: &diagnostics) + guard Set(fields.keys).isSubset(of: allowed), + fields["type"] == nil || fields["type"] == .string("command"), + let command = fields["command"]?.importString, !command.isEmpty + else { + diagnostics.add( + .unconverted, origin, + "Native non-command handler or extra execution policy has no equivalent executable conversion." + ) + continue + } + // A single executable token needs no shell splitting or inferred interpreter. + guard command.range(of: #"^[A-Za-z0-9_./-]+$"#, options: .regularExpression) != nil else { + diagnostics.add( + .unconverted, origin.appending("command"), + "Native shell syntax is not parsed or rewritten into argv.") + continue + } + var timeout: Int? + if let value = fields["timeout"] { + guard case .integer(let seconds) = value, seconds > 0, + !(agent == .claudeCode && event == "SessionEnd" && seconds > 60) + else { + NativeImportInput.unconverted( + value, at: origin.appending("timeout"), into: &diagnostics) + continue + } + timeout = seconds + } + var executable = command + if command.hasPrefix("./") { + executable = try nativePath(command, container: container) + try NativeImportInput.resource( + executable, root: container, input: parsed.input, origin: origin, + limits: limits, into: &diagnostics, admission: parsed.admission) + } else if command.contains("/") { + diagnostics.add( + .unconverted, origin, + "Native hook outside its explicit root needs a selected authoring resource.") + continue + } + let identity = event + "\0" + (matcher ?? "") + "\0" + executable + let base = event + "-" + FileHash.sha256Hex(data: Data(identity.utf8)) + let occurrence = parsed.admission.memberOccurrences[base, default: 0] + 1 + parsed.admission.memberOccurrences[base] = occurrence + let name = base + (occurrence == 1 ? "" : "-\(occurrence)") + NativeImportInput.emit( + .hook( + name: name, event: .native(event), run: .init(executable: executable), + matcher: matcher, timeoutSeconds: timeout, agents: [agent]), + selector: .hook(name: name), + origin: origin, container: container, profile: parsed.input.profile, into: &diagnostics, + admission: parsed.admission) + } + } + } + } + + static func lsp( + _ value: NativeValue, parsed: NativeImportDocument, keys: [String], + container: String, limits: SourceImportLimits, into diagnostics: inout ImportDiagnostics + ) throws { + let agent = NativeImportInput.agent(parsed.input.profile) + guard [.claudeCode, .opencode].contains(agent), let servers = value.importObject else { + NativeImportInput.unconverted(value, at: parsed.location(keys), into: &diagnostics) + return + } + for (index, name) in servers.keys.sorted().enumerated() { + let origin = parsed.location( + keys + [name], display: keys.map { "/" + $0 }.joined() + "/member[\(index)]") + guard NativeImportInput.name(name), let fields = servers[name]?.importObject else { + NativeImportInput.unconverted(servers[name]!, at: origin, into: &diagnostics) + continue + } + let allowed: Set = + agent == .claudeCode + ? ["command", "args", "env", "extensionToLanguage", "initializationOptions"] + : ["command", "env", "extensions", "disabled", "initialization"] + NativeImportInput.unknown(fields, allowed: allowed, at: origin, into: &diagnostics) + guard Set(fields.keys).isSubset(of: allowed) else { continue } + let executable: String + let arguments: [String] + var languages: [String: String] = [:] + var native: NativeConfiguration = [:] + if agent == .claudeCode { + guard let command = fields["command"]?.importString, + let mapping = fields["extensionToLanguage"]?.importObject, !mapping.isEmpty, + mapping.allSatisfy({ $0.key.hasPrefix(".") && $0.value.importString?.isEmpty == false }), + fields["args"] == nil || fields["args"]?.importStrings != nil + else { + diagnostics.add( + .invalidInput, origin, "Native LSP command/language mapping is malformed.") + continue + } + executable = command + arguments = fields["args"]?.importStrings ?? [] + languages = mapping.mapValues { $0.importString! } + } else { + guard let argv = fields["command"]?.importStrings, let command = argv.first, + !command.isEmpty, + fields["extensions"] == nil || MCPNativeField.strings.accepts(fields["extensions"]!), + fields["disabled"] == nil || MCPNativeField.boolean.accepts(fields["disabled"]!) + else { + diagnostics.add(.invalidInput, origin, "Native LSP argv/extensions are malformed.") + continue + } + executable = command + arguments = Array(argv.dropFirst()) + for key in ["extensions", "disabled"] where fields[key] != nil { + native[agent.rawValue, default: [:]][key] = fields[key] + } + } + guard !executable.isEmpty, !executable.contains("\0"), !executable.contains("${"), + !arguments.contains(where: { + $0.contains("${") || ($0.contains("://") && !ImportInput.safeLocator($0)) + }) + else { + diagnostics.add( + .unconverted, origin, + "Native LSP interpolation/arguments require explicit resource or binding conversion.") + continue + } + var credentialArgument = false + for (index, argument) in arguments.enumerated() { + let flag = argument.split(separator: "=", maxSplits: 1).first.map(String.init) ?? argument + if ImportInput.credentialField(flag) { + diagnostics.binding(origin.appending("args/\(index)")) + credentialArgument = true + } + } + if credentialArgument { + diagnostics.add( + .unconverted, origin, "Native LSP credential arguments require symbolic reconstruction.") + continue + } + let optionsKey = agent == .claudeCode ? "initializationOptions" : "initialization" + let options = fields[optionsKey]?.importObject ?? [:] + if fields[optionsKey] != nil && fields[optionsKey]?.importObject == nil { + diagnostics.add( + .invalidInput, origin.appending(optionsKey), + "Native initialization options require an object.") + continue + } + if NativeImportInput.sensitive( + .object(options), at: origin.appending(optionsKey), into: &diagnostics) + { + diagnostics.add( + .unconverted, origin, + "Native initialization data contains literal credential slots without a typed binding representation." + ) + continue + } + let environment = try NativeImportInput.bindings( + fields["env"], at: origin.appending("env"), into: &diagnostics, + profile: parsed.input.profile) + var program = executable + if executable.hasPrefix("./") { + program = try nativePath(executable, container: container) + try NativeImportInput.resource( + program, root: container, input: parsed.input, origin: origin, + limits: limits, into: &diagnostics, admission: parsed.admission) + } else if executable.contains("/") { + diagnostics.add( + .unconverted, origin, + "Native LSP executable outside its source requires a selected resource.") + continue + } + NativeImportInput.emit( + .lspServer( + name: name, + run: .init(executable: program, arguments: arguments, environment: environment), + languages: languages, initializationOptions: options, agents: [agent], native: native), + selector: .lspServer(name: name), + origin: origin, container: container, profile: parsed.input.profile, into: &diagnostics, + admission: parsed.admission) + } + } +} diff --git a/Sources/Components/Import/NativeImportInput.swift b/Sources/Components/Import/NativeImportInput.swift new file mode 100644 index 0000000..6a6dc97 --- /dev/null +++ b/Sources/Components/Import/NativeImportInput.swift @@ -0,0 +1,341 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// An operation-local reader. Native bytes and parser observations never enter the proposal. +struct NativeImportDocument { + let input: SourceImportInput + let bytes: Data + let document: NativeDocument + let fields: [String: NativeValue] + let admission: NativeImportBudget + + init( + _ input: SourceImportInput, format: NativeDocumentFormat, limits: SourceImportLimits, + admission: NativeImportBudget? = nil + ) throws { + let bytes = try ImportInput.bytes(input, limits: limits) + let admission = try admission ?? NativeImportBudget(limits) + try admission.document(bytes, path: input.document) + let budget = admission.parser + do { + let document = try NativeDocument(bytes: bytes, format: format, budget: budget) + guard let observation = try document.read(.init(keys: [])), + observation.projectionFailure == nil, case .object(let fields) = observation.value + else { throw ImportReadFailure.invalid } + self.input = input + self.bytes = bytes + self.document = document + self.fields = fields + self.admission = admission + } catch NativeDocumentError.cancelled { + throw CancellationError() + } catch NativeDocumentError.invalidDocument(_, let range) { + throw ImportLocatedFailure( + location: .init( + document: input.document, pointer: "", + span: range.map { importSpan(bytes, document: input.document, range: $0) })) + } + } + + func location(_ keys: [String] = [], display: String? = nil) -> ImportLocation { + let observation = try? document.read(.init(keys: keys)) + var range = observation?.valueRange ?? observation?.entryRanges.first + if range == nil, let fields = observation?.value?.importObject { + for key in fields.keys.sorted() { + if let found = (try? document.read(.init(keys: keys + [key])))?.valueRange { + range = found + break + } + } + } + return .init( + document: input.document, pointer: display ?? keys.map { "/" + $0 }.joined(), + span: range.map { importSpan(bytes, document: input.document, range: $0) }) + } +} + +enum NativeImportInput { + static func agent(_ profile: SourceImportProfile) -> AgentID { + switch profile { + case .codexConfigV1: .codex + case .cursorMCPV1, .cursorPluginV1, .cursorCommandV1, .cursorAgentV1, .cursorIgnoreV1: .cursor + case .geminiSettingsV1, .geminiExtensionV1, .geminiCommandV1, .geminiAgentV1, .geminiIgnoreV1: + .geminiCLI + case .openCodeConfigV2, .openCodeCommandV2, .openCodeAgentV2: .opencode + default: .claudeCode + } + } + + static func name(_ text: String) -> Bool { + ImportInput.name(text) && !text.contains("://") + } + + static func unknown( + _ fields: [String: NativeValue], allowed: Set, at origin: ImportLocation, + into diagnostics: inout ImportDiagnostics + ) { + for (index, key) in fields.keys.sorted().enumerated() where !allowed.contains(key) { + let location = origin.appending("member[\(index)]") + if ImportInput.credentialField(key) { diagnostics.binding(location) } + unconverted(fields[key]!, at: location, into: &diagnostics) + } + } + + static func unconverted( + _ value: NativeValue, at location: ImportLocation, + into diagnostics: inout ImportDiagnostics + ) { + diagnostics.add( + .unconverted, location, + "Native field requires an explicit semantic conversion; it is not imported.") + switch value { + case .object(let fields): + for (index, key) in fields.keys.sorted().enumerated() { + let child = location.appending("member[\(index)]") + if ImportInput.credentialField(key) { diagnostics.binding(child) } + unconverted(fields[key]!, at: child, into: &diagnostics) + } + case .array(let values): + for (index, value) in values.enumerated() { + unconverted(value, at: location.appending(String(index)), into: &diagnostics) + } + case .string(let text) where text.contains("://") && !ImportInput.safeLocator(text): + diagnostics.binding(location) + default: break + } + } + + static func sensitive( + _ value: NativeValue, at location: ImportLocation, into diagnostics: inout ImportDiagnostics + ) -> Bool { + var found = false + if let fields = value.importObject { + for (index, key) in fields.keys.sorted().enumerated() { + let item = location.appending("member[\(index)]") + if ImportInput.credentialField(key) { + diagnostics.binding(item) + found = true + } + if sensitive(fields[key]!, at: item, into: &diagnostics) { found = true } + } + } else if case .array(let values) = value { + for (index, value) in values.enumerated() { + if sensitive(value, at: location.appending(String(index)), into: &diagnostics) { + found = true + } + } + } else if let string = value.importString, string.contains("://"), + !ImportInput.safeLocator(string) + { + diagnostics.binding(location) + found = true + } + return found + } + + static func binding( + _ location: ImportLocation, environment: String? = nil, + into diagnostics: inout ImportDiagnostics + ) -> RuntimeBinding { + let key = + "import-" + FileHash.sha256Hex(data: Data((location.document + "\0" + location.pointer).utf8)) + diagnostics.binding(location, environmentVariable: environment) + if let index = diagnostics.proposal.bindings.firstIndex(where: { $0.location == location }) { + diagnostics.proposal.bindings[index].key = key + } + return environment.map(RuntimeBinding.environment) ?? .secret(key) + } + + static func bindings( + _ value: NativeValue?, at location: ImportLocation, symbolic: Bool = false, + into diagnostics: inout ImportDiagnostics, profile: SourceImportProfile? = nil + ) throws -> [String: RuntimeBinding] { + guard let value else { return [:] } + guard case .object(let fields) = value else { throw ImportReadFailure.invalid } + var result: [String: RuntimeBinding] = [:] + for (index, key) in fields.keys.sorted().enumerated() { + let item = location.appending("member[\(index)]") + guard name(key), let text = fields[key]?.importString else { throw ImportReadFailure.invalid } + if symbolic { + guard MCPReferenceSyntax.isName(text) + else { throw ImportReadFailure.invalid } + result[key] = binding(item, environment: text, into: &diagnostics) + } else { + var reference: String? + if let profile { + let client = agent(profile) + if [.claudeCode, .geminiCLI].contains(client), text.hasPrefix("${"), text.hasSuffix("}") { + reference = String(text.dropFirst(2).dropLast()) + } else if client == .opencode, text.hasPrefix("{env:"), text.hasSuffix("}") { + reference = String(text.dropFirst(5).dropLast()) + } + } + if let reference, + MCPReferenceSyntax.isName(reference) + { + result[key] = binding(item, environment: reference, into: &diagnostics) + } else if text.contains("${") || text.contains("{env:") || text.contains("{file:") { + diagnostics.binding(item) + diagnostics.add( + .unconverted, item, + "Native interpolation is not a single admitted symbolic environment reference.") + throw ImportReadFailure.invalid + } else { + result[key] = binding(item, into: &diagnostics) + } + } + } + return result + } + + static func source( + _ input: SourceImportInput, root: String, origin: ImportLocation, + into diagnostics: inout ImportDiagnostics + ) -> String { + let alias = "native-input" + if !diagnostics.proposal.sources.contains(where: { $0.alias == alias }) { + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: origin, + declaration: .init( + kind: .local, location: root, + environment: .init(projectDirectory: input.root, homeDirectory: input.root)), + pin: .init(), requestedRef: nil, producerPath: root)) + } + return alias + } + + static func emit( + _ declaration: ComponentDeclaration, selector: ComponentReferenceDeclaration, + origin: ImportLocation, container: String, profile: SourceImportProfile, + into diagnostics: inout ImportDiagnostics, admission: NativeImportBudget? = nil + ) { + let member = ImportMemberCoordinate( + containerRoot: container, selector: selector, + profile: profile, formatVersion: 1) + guard admission?.ambiguousMembers.contains(member) != true, + !diagnostics.proposal.components.contains(where: { $0.member == member }) + else { + diagnostics.proposal.components.removeAll { $0.member == member } + admission?.ambiguousMembers.append(member) + diagnostics.add( + .ambiguousSource, origin, "Two native declarations have the same typed member identity.") + return + } + diagnostics.proposal.components.append( + .init(origin: origin, declaration: declaration, member: member)) + } + + static func resource( + _ path: String, root: String, input: SourceImportInput, + origin: ImportLocation, limits: SourceImportLimits, rewrite: Bool = false, + into diagnostics: inout ImportDiagnostics, admission: NativeImportBudget? = nil + ) throws { + let root = try ImportInput.path(root) + let path = try ImportInput.path(path) + let relative = root == "." ? path : root + (path == "." ? "" : "/" + path) + let snapshot = try ImportInput.snapshot(input.root) + let url = try snapshot.resource(relative) + try admission?.resource(url, snapshot: snapshot) + let needsRewrite = + rewrite + || diagnostics.proposal.bindings.contains { + $0.location.document == relative || $0.location.document.hasPrefix(relative + "/") + || relative == "." + } + let frozen = try LedgerResources.capture( + url, embed: false, + limits: .init( + encodedBytes: limits.resourceBytes, depth: limits.depth, nodes: limits.nodes, + objectBytes: limits.resourceBytes, entries: limits.resourceEntries, + keyBytes: limits.resourceBytes, resourceBytes: limits.resourceBytes), + sourceRoot: try snapshot.resource(root)) + for entry in frozen.support { + let supportPath = root == "." ? entry.path : root + "/" + entry.path + try admission?.resource(try snapshot.resource(supportPath), snapshot: snapshot) + } + let alias = source(input, root: root, origin: origin, into: &diagnostics) + diagnostics.proposal.resources.append( + .init( + origin: origin, sourceAlias: alias, + producerName: url.lastPathComponent, path: path, producerIntegrity: nil, + observedHash: needsRewrite ? nil : frozen.hash, executableFlags: frozen.flags, + requiresStandaloneSource: true, requiresBindingRewrite: needsRewrite)) + // Support targets remain separate resources relative to the same native-format root. + for entry in frozen.support where entry.kind == .file { + diagnostics.proposal.resources.append( + .init( + origin: origin, sourceAlias: alias, + producerName: URL(fileURLWithPath: entry.path).lastPathComponent, path: entry.path, + producerIntegrity: nil, observedHash: nil, + executableFlags: [entry.path: entry.executable], + requiresStandaloneSource: true, requiresBindingRewrite: needsRewrite)) + } + } +} + +/// Shared only within one bounded import operation; no bytes or state escape in a proposal. +final class NativeImportBudget { + let parser: NativeDocumentBudget + private let limits: SourceImportLimits + private var documentBytes: Int + private var resourceBytes: Int + private var entries: Int + var ambiguousMembers: [ImportMemberCoordinate] = [] + var memberOccurrences: [String: Int] = [:] + private var documents: Set = [] + private var resources: Set = [] + + init(_ limits: SourceImportLimits) throws { + guard limits.documentBytes >= 0, limits.documentBytes <= (Int.max - 1024) / 64, + limits.resourceBytes >= 0, limits.resourceEntries > 0, limits.depth > 0, limits.nodes > 0 + else { throw ImportReadFailure.invalid } + self.limits = limits + documentBytes = limits.documentBytes + resourceBytes = limits.resourceBytes + entries = limits.resourceEntries + parser = .init( + limits: .init( + storage: limits.documentBytes * 32 + 1024, + work: limits.documentBytes * 64 + 1024, nodes: limits.nodes, depth: limits.depth, + uninterruptedBytes: limits.documentBytes)) + } + + func document(_ bytes: Data, path: String) throws { + if documents.insert(path).inserted { + guard bytes.count <= documentBytes else { throw ImportReadFailure.invalid } + documentBytes -= bytes.count + } + } + + func resource(_ url: URL, snapshot: SourceSnapshot) throws { + func admit(_ file: URL) throws { + try Task.checkCancellation() + let path = try snapshot.relativePath(file) + guard !resources.contains(path) else { return } + guard entries > 0, path.split(separator: "/").count <= limits.depth else { + throw ImportReadFailure.invalid + } + let info = try FileManager.default.attributesOfItem(atPath: file.path) + if info[.type] as? FileAttributeType == .typeRegular { + guard let size = (info[.size] as? NSNumber)?.intValue, size >= 0, size <= resourceBytes + else { throw ImportReadFailure.invalid } + resourceBytes -= size + } else if ![FileAttributeType.typeDirectory, .typeSymbolicLink].contains( + info[.type] as? FileAttributeType ?? .typeUnknown) + { + throw ImportReadFailure.invalid + } + resources.insert(path) + entries -= 1 + } + try admit(url) + let info = try FileManager.default.attributesOfItem(atPath: url.path) + if info[.type] as? FileAttributeType == .typeDirectory { + guard let walk = FileManager.default.enumerator(at: url, includingPropertiesForKeys: nil) + else { throw ImportReadFailure.invalid } + for case let file as URL in walk { try admit(file) } + } + } +} diff --git a/Sources/Components/Import/NativeImportSemantics.swift b/Sources/Components/Import/NativeImportSemantics.swift new file mode 100644 index 0000000..83eb715 --- /dev/null +++ b/Sources/Components/Import/NativeImportSemantics.swift @@ -0,0 +1,32 @@ +import AgentsCore + +/// Reuses F's finite conversion/validation rather than maintaining another native field table. +enum NativeImportSemantics { + static func mcp( + name: String, transport: MCPTransportDeclaration, + native: [String: NativeValue], profile: SourceImportProfile, resources: [String] + ) throws { + let surface: NativeClientSurface + switch NativeImportInput.agent(profile) { + case .claudeCode: surface = .claudeCode + case .codex: surface = .codexCLI + case .geminiCLI: surface = .geminiCLI + case .cursor: surface = .cursorEditor + case .opencode: surface = .openCodeCLI + } + // These field converters do not consume scope or produce a deployment. Project is an + // error-context value only; no scope, route or ownership is returned by the importer. + let descriptor = try CapabilityRegistry.mcp( + .init(surface: surface, scope: .project), component: name) + let input = MCPInput( + descriptor: descriptor, name: name, transport: transport, native: native, resources: resources + ) + switch surface { + case .claudeCode: _ = try ClaudeAdapter.mcp(input) + case .codexCLI: _ = try CodexAdapter.mcp(input) + case .geminiCLI: _ = try GeminiAdapter.mcp(input) + case .cursorEditor, .cursorCLI, .cursorCloud: _ = try CursorAdapter.mcp(input) + case .openCodeCLI: _ = try OpenCodeAdapter.mcp(input) + } + } +} diff --git a/Sources/Components/Import/NativeMemberImport.swift b/Sources/Components/Import/NativeMemberImport.swift new file mode 100644 index 0000000..d3e3dc9 --- /dev/null +++ b/Sources/Components/Import/NativeMemberImport.swift @@ -0,0 +1,133 @@ +import AgentsCore +import Foundation + +/// Native file bodies share the package-owned bounded YAML/TOML readers. +enum NativeMemberImport { + static func read( + _ input: SourceImportInput, container: String, + kind explicitKind: DeclaredComponentKind? = nil, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics, admission supplied: NativeImportBudget? = nil, + discoveryRoot: String? = nil + ) throws { + let admission = try supplied ?? NativeImportBudget(limits) + let agent = NativeImportInput.agent(input.profile) + let isAgent = + explicitKind == .subagent + || [.claudeAgentV1, .geminiAgentV1, .openCodeAgentV2, .cursorAgentV1].contains(input.profile) + let bytes = try ImportInput.bytes(input, limits: limits) + try admission.document(bytes, path: input.document) + let file = URL(fileURLWithPath: input.document) + let stem = (input.document as NSString).deletingPathExtension + let fallback = + discoveryRoot.map { + stem.hasPrefix($0 + "/") + ? String(stem.dropFirst($0.count + 1)) : file.deletingPathExtension().lastPathComponent + } ?? file.deletingPathExtension().lastPathComponent + var origin = ImportLocation(document: input.document, pointer: "") + var name = fallback + let body: String + let description: String + var model: String? + var tools: [String]? + if input.profile == .geminiCommandV1 || (!isAgent && agent == .geminiCLI) { + let parsed = try NativeImportDocument( + input, format: .toml, limits: limits, admission: admission) + origin = parsed.location() + NativeImportInput.unknown( + parsed.fields, allowed: ["description", "prompt"], at: origin, into: &diagnostics) + guard Set(parsed.fields.keys).isSubset(of: ["description", "prompt"]), + let prompt = parsed.fields["prompt"]?.importString, + parsed.fields["description"] == nil || parsed.fields["description"]?.importString != nil + else { + diagnostics.add( + .invalidInput, origin, "Native command requires its fixed prompt/description fields.") + return + } + body = prompt + description = parsed.fields["description"]?.importString ?? "" + } else { + let parsed = try ImportFrontmatter.read(bytes, document: input.document, limits: limits) + guard let text = String(data: parsed.body, encoding: .utf8) else { + throw ImportReadFailure.invalid + } + // Gemini's native agent loader trims its body; the proposal represents that loaded value. + body = + agent == .geminiCLI && isAgent ? text.trimmingCharacters(in: .whitespacesAndNewlines) : text + let converted: Set = + isAgent ? ["name", "description", "model", "tools"] : ["description"] + parsed.header?.unknown(converted, into: &diagnostics) + let unknown = Set(parsed.header?.pairs?.map(\.0) ?? []).subtracting(converted) + guard unknown.isEmpty else { return } + if let header = parsed.header { + origin = header.location + guard + header.validate( + strings: isAgent ? ["name", "description", "model"] : ["description"], + into: &diagnostics) + else { return } + if isAgent { + name = header["name"]?.string ?? name + model = header["model"]?.string + if let value = header["tools"] { + if let values = value.strings { + tools = values + } else if let value = value.string, agent == .claudeCode { + tools = value.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) } + } else { + diagnostics.add( + .invalidInput, value.location, + "Native tool selection cannot be represented as a string list.") + return + } + } + } + } + description = parsed.header?["description"]?.string ?? "" + if isAgent, + description.isEmpty + || ([AgentID.claudeCode, .geminiCLI].contains(agent) && parsed.header?["name"] == nil) + { + diagnostics.add( + .invalidInput, origin, "Native agent requires its producer name and description.") + return + } + if !isAgent, agent == .claudeCode, + body.contains("$ARGUMENTS") + || body.range(of: #"\$[0-9]+"#, options: .regularExpression) != nil + { + diagnostics.add( + .unconverted, origin, + "Native command substitutions need explicit parameter conversion; no prompt parameters are guessed." + ) + return + } + } + guard + name.split(separator: "/", omittingEmptySubsequences: false).allSatisfy({ + NativeImportInput.name(String($0)) + }) + else { + diagnostics.add( + .invalidInput, origin, "Native member name is not an admitted component identifier.") + return + } + if isAgent { + NativeImportInput.emit( + .subagent( + name: name, description: description, prompt: .literal(body), + model: model, tools: tools, agents: [agent]), selector: .subagent(name: name), + origin: origin, container: container, profile: input.profile, into: &diagnostics, + admission: admission) + } else { + NativeImportInput.emit( + .command(name: name, description: description, prompt: .literal(body), agents: [agent]), + selector: .command(name: name), origin: origin, container: container, + profile: input.profile, into: &diagnostics, admission: admission) + } + let relative = + container == "." ? input.document : String(input.document.dropFirst(container.count + 1)) + try NativeImportInput.resource( + relative, root: container, input: input, origin: origin, limits: limits, into: &diagnostics, + admission: admission) + } +} diff --git a/Sources/Components/Import/NativeSourceImport.swift b/Sources/Components/Import/NativeSourceImport.swift new file mode 100644 index 0000000..ae5e342 --- /dev/null +++ b/Sources/Components/Import/NativeSourceImport.swift @@ -0,0 +1,486 @@ +import AgentsCore +import Foundation +import NativeDocuments + +enum NativeSourceImport { + static func read( + _ input: SourceImportInput, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + switch input.profile { + case .geminiIgnoreV1, .cursorIgnoreV1: + let bytes = try ImportInput.bytes(input, limits: limits) + guard let text = String(data: bytes, encoding: .utf8), !text.contains("\0") else { + throw ImportReadFailure.invalid + } + let patterns = text.components(separatedBy: .newlines).filter { !$0.isEmpty } + let origin = ImportLocation(document: input.document, pointer: "") + NativeImportInput.emit( + .ignore( + name: "native-context", patterns: patterns, + agents: [NativeImportInput.agent(input.profile)]), + selector: .ignore(name: "native-context"), origin: origin, container: ".", + profile: input.profile, into: &diagnostics) + try NativeImportInput.resource( + input.document, root: ".", input: input, origin: origin, limits: limits, into: &diagnostics) + case .claudePluginV1, .cursorPluginV1, .geminiExtensionV1: + try NativeContainerImport.read(input, limits: limits, into: &diagnostics) + case .claudeMarketplaceV1: + try NativeCatalogImport.read(input, limits: limits, into: &diagnostics) + case .claudeCommandV1, .claudeAgentV1, .geminiCommandV1, .geminiAgentV1, + .openCodeCommandV2, .openCodeAgentV2, .cursorCommandV1, .cursorAgentV1: + try NativeMemberImport.read(input, container: ".", limits: limits, into: &diagnostics) + default: + let format: NativeDocumentFormat = + input.profile == .codexConfigV1 ? .toml : .jsonc(trailingCommas: true) + let parsed = try NativeImportDocument(input, format: format, limits: limits) + let root = "." + _ = NativeImportInput.source(input, root: root, origin: parsed.location(), into: &diagnostics) + let wrapper = + input.profile == .codexConfigV1 + ? "mcp_servers" : input.profile == .openCodeConfigV2 ? "mcp" : "mcpServers" + if let value = parsed.fields[wrapper] { + if input.profile == .openCodeConfigV2 { + guard let fields = value.importObject else { throw ImportReadFailure.invalid } + NativeImportInput.unknown( + fields, allowed: ["servers"], at: parsed.location([wrapper]), into: &diagnostics) + if let servers = fields["servers"] { + try mcp( + servers, parsed: parsed, keys: [wrapper, "servers"], container: root, + limits: limits, into: &diagnostics) + } + } else { + try mcp( + value, parsed: parsed, keys: [wrapper], container: root, limits: limits, + into: &diagnostics) + } + } + var converted: Set = [wrapper, "$schema"] + if input.profile == .openCodeConfigV2 { + for (key, kind) in [("commands", "command"), ("agents", "subagent")] + where parsed.fields[key] != nil { + try openCodeMembers( + parsed.fields[key]!, kind: kind, parsed: parsed, key: key, into: &diagnostics) + converted.insert(key) + } + if let value = parsed.fields["permissions"] { + permissions(value, parsed: parsed, into: &diagnostics) + converted.insert("permissions") + } + } + if input.profile == .codexConfigV1, let agents = parsed.fields["agents"] { + try codexAgents(agents, parsed: parsed, limits: limits, into: &diagnostics) + converted.insert("agents") + } + if let value = parsed.fields["hooks"] { + try hooks( + value, parsed: parsed, keys: ["hooks"], container: root, limits: limits, + into: &diagnostics) + converted.insert("hooks") + } + if input.profile == .openCodeConfigV2, let value = parsed.fields["lsp"] { + try lsp( + value, parsed: parsed, keys: ["lsp"], container: root, limits: limits, into: &diagnostics) + converted.insert("lsp") + } + if input.profile == .claudeSettingsV1, let value = parsed.fields["permissions"] { + if let fields = value.importObject, + Set(fields.keys).isSubset(of: ["allow", "ask", "deny"]), + fields.values.allSatisfy(MCPNativeField.strings.accepts) + { + NativeImportInput.emit( + .permissions( + name: "native-policy", rules: [], agents: [.claudeCode], + native: [AgentID.claudeCode.rawValue: fields]), + selector: .permissions(name: "native-policy"), origin: parsed.location(["permissions"]), + container: root, + profile: input.profile, into: &diagnostics, admission: parsed.admission) + } else { + NativeImportInput.unconverted( + value, at: parsed.location(["permissions"]), into: &diagnostics) + } + converted.insert("permissions") + } + NativeImportInput.unknown( + parsed.fields, allowed: converted, at: parsed.location(), into: &diagnostics) + let privateInput = diagnostics.proposal.bindings.contains { + $0.location.document == input.document + } + try NativeImportInput.resource( + input.document, root: root, input: input, origin: parsed.location(), + limits: limits, rewrite: privateInput, into: &diagnostics, admission: parsed.admission) + } + } + + static func mcp( + _ value: NativeValue, parsed: NativeImportDocument, keys: [String], + container: String, limits: SourceImportLimits, into diagnostics: inout ImportDiagnostics + ) throws { + guard case .object(let servers) = value else { throw ImportReadFailure.invalid } + let agent = NativeImportInput.agent(parsed.input.profile) + for (index, name) in servers.keys.sorted().enumerated() { + try Task.checkCancellation() + if ![SourceImportProfile.claudePluginV1, .cursorPluginV1, .geminiExtensionV1].contains( + parsed.input.profile), + !(parsed.input.selection?.contains(name) ?? true) + { + continue + } + let originalNames = + (try parsed.document.read(.init(keys: keys)))?.value?.importObject?.keys.sorted() + ?? servers.keys.sorted() + let originalIndex = originalNames.firstIndex(of: name) ?? index + let location = parsed.location( + keys + [name], display: keys.map { "/" + $0 }.joined() + "/member[\(originalIndex)]") + guard NativeImportInput.name(name), case .object(let fields) = servers[name] else { + NativeImportInput.unconverted(servers[name]!, at: location, into: &diagnostics) + continue + } + do { + guard + ["type", "url", "httpUrl", "cwd"].allSatisfy({ + fields[$0] == nil || fields[$0]?.importString != nil + }) + else { throw ImportReadFailure.invalid } + var allowed: Set = ["command", "args", "env", "type", "url", "headers"] + if agent == .codex { + allowed = [ + "command", "args", "env", "cwd", "env_vars", "url", "http_headers", "env_http_headers", + ] + } + if agent == .geminiCLI { + allowed.insert("cwd") + allowed.insert("httpUrl") + } + if agent == .opencode { + allowed = [ + "type", "command", "environment", "cwd", "url", "headers", "codemode", "oauth", + ] + } + let extra = fields.filter { !allowed.contains($0.key) } + for (index, key) in extra.keys.sorted().enumerated() where ImportInput.credentialField(key) + { + diagnostics.binding(location.appending("native/member[\(index)]")) + } + let transport: MCPTransportDeclaration + let explicit = fields["type"]?.importString + var native: NativeConfiguration = extra.isEmpty ? [:] : [agent.rawValue: extra] + if agent == .opencode, fields["codemode"] != nil { + guard case .boolean = fields["codemode"]! else { throw ImportReadFailure.invalid } + native[agent.rawValue, default: [:]]["codemode"] = fields["codemode"] + } + if agent == .opencode, let oauth = fields["oauth"], oauth != .boolean(false) { + NativeImportInput.unconverted(oauth, at: location.appending("oauth"), into: &diagnostics) + continue + } + if let url = fields["url"]?.importString ?? fields["httpUrl"]?.importString { + guard fields["command"] == nil, ImportInput.safeLocator(url), + let address = URLComponents(string: url), ["https", "http"].contains(address.scheme), + address.host != nil + else { + if !ImportInput.safeLocator(url) { diagnostics.binding(location.appending("url")) } + throw ImportReadFailure.invalid + } + let inappropriate: Set = ["args", "env", "env_vars", "environment", "cwd"] + if !Set(fields.keys).isDisjoint(with: inappropriate) { + for key in inappropriate where fields[key] != nil { + NativeImportInput.unconverted( + fields[key]!, at: location.appending(key), into: &diagnostics) + } + continue + } + if agent == .opencode, fields["codemode"] == nil { + native[agent.rawValue, default: [:]]["codemode"] = .boolean(true) + } + let headerKey = agent == .codex ? "http_headers" : "headers" + var headers = try NativeImportInput.bindings( + fields[headerKey], at: location.appending(headerKey), into: &diagnostics, + profile: parsed.input.profile) + if agent == .codex { + let refs = try NativeImportInput.bindings( + fields["env_http_headers"], at: location.appending("env_http_headers"), + symbolic: true, into: &diagnostics, profile: parsed.input.profile) + guard Set(headers.keys).isDisjoint(with: refs.keys) else { + throw ImportReadFailure.invalid + } + headers.merge(refs) { first, _ in first } + } + if agent == .codex || (agent == .opencode && explicit == "remote") || explicit == "http" + || fields["httpUrl"] != nil + { + transport = .streamableHTTP(url: url, headers: headers) + } else if agent == .claudeCode || agent == .geminiCLI, explicit == "sse" { + transport = .sse(url: url, headers: headers) + } else { + diagnostics.add( + .unconverted, location, + "Native remote transport is not fixed by this input; no HTTP/SSE transport is guessed." + ) + continue + } + } else { + guard explicit == nil || explicit == (agent == .opencode ? "local" : "stdio") else { + throw ImportReadFailure.invalid + } + if fields["headers"] != nil || fields["http_headers"] != nil + || fields["env_http_headers"] != nil + { + for key in ["headers", "http_headers", "env_http_headers"] where fields[key] != nil { + _ = try NativeImportInput.bindings( + fields[key], at: location.appending(key), into: &diagnostics) + NativeImportInput.unconverted( + fields[key]!, at: location.appending(key), into: &diagnostics) + } + continue + } + var executable: String + var arguments: [String] + if agent == .opencode { + guard let argv = fields["command"]?.importStrings, let first = argv.first, + !first.isEmpty + else { throw ImportReadFailure.invalid } + executable = first + arguments = Array(argv.dropFirst()) + } else { + guard let command = fields["command"]?.importString, !command.isEmpty else { + throw ImportReadFailure.invalid + } + executable = command + guard fields["args"] == nil || fields["args"]?.importStrings != nil else { + throw ImportReadFailure.invalid + } + arguments = fields["args"]?.importStrings ?? [] + } + guard !executable.contains("\0"), !arguments.contains(where: { $0.contains("\0") }) else { + throw ImportReadFailure.invalid + } + var unrepresentableArgument = false + for (offset, argument) in arguments.enumerated() { + let flag = + argument.hasPrefix("--") + ? String(argument.dropFirst(2).split(separator: "=", maxSplits: 1).first ?? "") : "" + if ImportInput.credentialField(flag) + || (argument.contains("://") && !ImportInput.safeLocator(argument)) + { + diagnostics.binding(location.appending("args/\(offset)")) + diagnostics.add( + .unconverted, location.appending("args/\(offset)"), + "Secret arguments require a typed argument binding slot; the argument literal is not retained." + ) + unrepresentableArgument = true + } + if argument.contains("${CLAUDE_PLUGIN_ROOT}") || argument.contains("${extensionPath}") { + diagnostics.add( + .unconverted, location.appending("args/\(offset)"), + "Native argument resource substitution has no typed canonical argument-resource slot; no extraction path is substituted." + ) + unrepresentableArgument = true + } + } + if unrepresentableArgument { continue } + let environmentKey = agent == .opencode ? "environment" : "env" + var environment = try NativeImportInput.bindings( + fields[environmentKey], at: location.appending(environmentKey), into: &diagnostics, + profile: parsed.input.profile) + if agent == .codex, let value = fields["env_vars"] { + guard let variables = value.importStrings else { throw ImportReadFailure.invalid } + for (offset, variable) in variables.enumerated() { + guard + variable.range(of: #"^[A-Za-z_][A-Za-z0-9_]*$"#, options: .regularExpression) + != nil, + environment[variable] == nil + else { throw ImportReadFailure.invalid } + environment[variable] = NativeImportInput.binding( + location.appending("env_vars/\(offset)"), environment: variable, into: &diagnostics) + } + } + var cwd: ResourceDeclaration? + if let value = fields["cwd"] { + guard [.codex, .geminiCLI, .opencode].contains(agent), + let authoredPath = value.importString + else { throw ImportReadFailure.invalid } + let path = try nativePath(authoredPath, container: container) + try NativeImportInput.resource( + path, root: container, input: parsed.input, origin: location.appending("cwd"), + limits: limits, into: &diagnostics, admission: parsed.admission) + cwd = .init(path: path, source: "native-input") + } + if parsed.input.profile == .claudePluginV1, executable.hasPrefix("${CLAUDE_PLUGIN_ROOT}/") + { + executable = "./" + executable.dropFirst("${CLAUDE_PLUGIN_ROOT}/".count) + } else if parsed.input.profile == .geminiExtensionV1, + executable.hasPrefix("${extensionPath}/") + { + executable = "./" + executable.dropFirst("${extensionPath}/".count) + } + if executable.hasPrefix("./") { + let path = try nativePath(executable, container: container) + try NativeImportInput.resource( + path, root: container, input: parsed.input, origin: location.appending("command"), + limits: limits, into: &diagnostics, admission: parsed.admission) + executable = path + } else if executable.contains("/") { + diagnostics.add( + .unconverted, location.appending("command"), + "Native executable outside the explicit container requires a caller-selected resource; no host executable is read." + ) + continue + } + transport = .stdio( + .init( + executable: executable, arguments: arguments, environment: environment, + workingDirectory: cwd)) + } + var resourceCoordinates: [String] = [] + if case .stdio(let run) = transport { + if run.executable.contains("/") { resourceCoordinates.append(run.executable) } + if let cwd = run.workingDirectory { resourceCoordinates.append(cwd.path) } + } + try NativeImportSemantics.mcp( + name: name, transport: transport, native: native[agent.rawValue] ?? [:], + profile: parsed.input.profile, resources: resourceCoordinates) + if let bearer = extra["bearer_token_env_var"]?.importString { + _ = NativeImportInput.binding( + location.appending("bearer_token_env_var"), environment: bearer, into: &diagnostics) + } + NativeImportInput.emit( + .mcpServer(name: name, transport: transport, agents: [agent], native: native), + selector: .mcpServer(name: name), origin: location, container: container, + profile: parsed.input.profile, into: &diagnostics) + } catch let issue as NativeAdapterIssue { + diagnostics.add( + issue.reason == .invalid ? .invalidInput : .unconverted, location, + "F's fixed native field profile cannot admit this member; its field/default semantics are not converted." + ) + } catch is CancellationError { throw CancellationError() } catch CoreError.unsafePath { + diagnostics.add(.unsafePath, location, "Native resource escapes its format-owned root.") + } catch { + diagnostics.add( + .invalidInput, location, + "Native MCP member is malformed or its resource is missing; no partial server is imported." + ) + } + } + } + + static func nativePath(_ path: String, container: String) throws -> String { + guard !path.hasPrefix("/"), !path.hasPrefix("~"), !path.contains("://"), + !path.split(separator: "/").contains("..") + else { throw CoreError.unsafePath("native resource") } + return try ImportInput.path(path) + } + + private static func openCodeMembers( + _ value: NativeValue, kind: String, + parsed: NativeImportDocument, key: String, into diagnostics: inout ImportDiagnostics + ) throws { + guard case .object(let entries) = value else { throw ImportReadFailure.invalid } + for (index, name) in entries.keys.sorted().enumerated() { + let origin = parsed.location([key, name], display: "/\(key)/member[\(index)]") + guard NativeImportInput.name(name), let fields = entries[name]?.importObject else { + NativeImportInput.unconverted(entries[name]!, at: origin, into: &diagnostics) + continue + } + let bodyKey = kind == "command" ? "template" : "system" + let allowed: Set = + kind == "command" + ? ["template", "description"] : ["system", "description", "mode", "model"] + NativeImportInput.unknown(fields, allowed: allowed, at: origin, into: &diagnostics) + guard Set(fields.keys).isSubset(of: allowed), let body = fields[bodyKey]?.importString, + fields["description"] == nil || fields["description"]?.importString != nil, + fields["model"] == nil || fields["model"]?.importString != nil, + kind == "command" || fields["mode"] == .string("subagent") + else { + NativeImportInput.unconverted(entries[name]!, at: origin, into: &diagnostics) + continue + } + let description = fields["description"]?.importString ?? "" + if kind == "command" { + NativeImportInput.emit( + .command( + name: name, description: description, prompt: .literal(body), agents: [.opencode]), + selector: .command(name: name), origin: origin, container: ".", + profile: parsed.input.profile, into: &diagnostics) + } else { + NativeImportInput.emit( + .subagent( + name: name, description: description, prompt: .literal(body), + model: fields["model"]?.importString, agents: [.opencode]), + selector: .subagent(name: name), origin: origin, container: ".", + profile: parsed.input.profile, into: &diagnostics) + } + } + } + + private static func permissions( + _ value: NativeValue, parsed: NativeImportDocument, + into diagnostics: inout ImportDiagnostics + ) { + guard case .array(let entries) = value else { + NativeImportInput.unconverted(value, at: parsed.location(["permissions"]), into: &diagnostics) + return + } + var rules: [PermissionRuleDeclaration] = [] + for (index, entry) in entries.enumerated() { + guard let fields = entry.importObject, Set(fields.keys) == ["action", "resource", "effect"], + let action = fields["action"]?.importString, + let resource = fields["resource"]?.importString, + let effect = fields["effect"]?.importString, ["allow", "ask", "deny"].contains(effect) + else { + NativeImportInput.unconverted( + entry, at: parsed.location(["permissions"]).appending(String(index)), into: &diagnostics) + return + } + switch effect { + case "allow": rules.append(.allow(.tool(action), resource)) + case "ask": rules.append(.ask(.tool(action), resource)) + default: rules.append(.deny(.tool(action), resource)) + } + } + NativeImportInput.emit( + .permissions(name: "native-policy", rules: rules, agents: [.opencode]), + selector: .permissions(name: "native-policy"), origin: parsed.location(["permissions"]), + container: ".", profile: parsed.input.profile, into: &diagnostics) + } + + private static func codexAgents( + _ value: NativeValue, parsed: NativeImportDocument, + limits: SourceImportLimits, into diagnostics: inout ImportDiagnostics + ) throws { + guard case .object(let agents) = value else { throw ImportReadFailure.invalid } + for (index, name) in agents.keys.sorted().enumerated() { + let origin = parsed.location(["agents", name], display: "/agents/member[\(index)]") + guard NativeImportInput.name(name), let fields = agents[name]?.importObject, + Set(fields.keys).isSubset(of: ["description", "config_file"]), + let description = fields["description"]?.importString, + let file = fields["config_file"]?.importString + else { + NativeImportInput.unconverted(agents[name]!, at: origin, into: &diagnostics) + continue + } + // Codex role paths are relative to the declaring config directory, unlike plugin paths. + let parent = (parsed.input.document as NSString).deletingLastPathComponent + let relative = try nativePath(file, container: parent) + let path = parent.isEmpty ? relative : parent + "/" + relative + var request = parsed.input + request = .init(profile: request.profile, root: request.root, document: path) + let role = try NativeImportDocument( + request, format: .toml, limits: limits, admission: parsed.admission) + NativeImportInput.unknown( + role.fields, allowed: ["developer_instructions", "model"], at: role.location(), + into: &diagnostics) + guard Set(role.fields.keys).isSubset(of: ["developer_instructions", "model"]), + let body = role.fields["developer_instructions"]?.importString + else { continue } + NativeImportInput.emit( + .subagent( + name: name, description: description, prompt: .literal(body), + model: role.fields["model"]?.importString, agents: [.codex]), + selector: .subagent(name: name), origin: role.location(["developer_instructions"]), + container: ".", profile: parsed.input.profile, into: &diagnostics) + try NativeImportInput.resource( + path, root: ".", input: parsed.input, origin: role.location(), limits: limits, + into: &diagnostics, admission: parsed.admission) + } + } +} diff --git a/Sources/Components/Import/SourceImport.swift b/Sources/Components/Import/SourceImport.swift index 5844194..47407e7 100644 --- a/Sources/Components/Import/SourceImport.swift +++ b/Sources/Components/Import/SourceImport.swift @@ -47,6 +47,12 @@ package enum SourceImport { case .rulesyncSourcesV1, .rulesyncNpmV1: try RulesyncSourceImport.read( ImportInput.document(input, limits: limits), input: input, into: &diagnostics) + case .claudeSettingsV1, .codexConfigV1, .cursorMCPV1, .geminiSettingsV1, .openCodeConfigV2, + .claudePluginV1, .cursorPluginV1, .geminiExtensionV1, .claudeMarketplaceV1, + .claudeCommandV1, .claudeAgentV1, .geminiCommandV1, .geminiAgentV1, + .openCodeCommandV2, .openCodeAgentV2, .cursorCommandV1, .cursorAgentV1, .geminiIgnoreV1, + .cursorIgnoreV1: + try NativeSourceImport.read(input, limits: limits, into: &diagnostics) case .vercelProjectV2, .vercelUserV3: try VercelSourceImport.read( ImportInput.document(input, limits: limits), input: input, limits: limits, diff --git a/Sources/Components/Import/SourceImportProposal.swift b/Sources/Components/Import/SourceImportProposal.swift index d953944..2397e50 100644 --- a/Sources/Components/Import/SourceImportProposal.swift +++ b/Sources/Components/Import/SourceImportProposal.swift @@ -1,19 +1,36 @@ import AgentsCore import Foundation -/// Each profile describes one producer format at an inspected release, not a format guess. +/// Fixed input formats grounded in upstream source revisions or producer documentation. package enum SourceImportProfile: String, Sendable { case rulesyncSourcesV1, rulesyncNpmV1, vercelProjectV2, vercelUserV3 case apmManifest, apmLock, rulesyncConfig, rulesyncGitHubV1, rulesyncAPMV1 + case claudeSettingsV1, codexConfigV1, cursorMCPV1, geminiSettingsV1, openCodeConfigV2 + case claudePluginV1, cursorPluginV1, geminiExtensionV1, claudeMarketplaceV1 + case claudeCommandV1, claudeAgentV1, geminiCommandV1, geminiAgentV1 + case openCodeCommandV2, openCodeAgentV2, cursorCommandV1, cursorAgentV1 + case geminiIgnoreV1, cursorIgnoreV1 package var specificationStatus: String { switch self { case .apmManifest, .apmLock: "APM working-draft profile; schema amendments are unratified" - default: "Pinned producer implementation format" + case .rulesyncSourcesV1, .rulesyncNpmV1, .rulesyncConfig, .rulesyncGitHubV1, .rulesyncAPMV1, + .vercelProjectV2, .vercelUserV3: + "Pinned producer implementation format" + case .codexConfigV1: "Pinned Codex source format" + case .geminiSettingsV1, .geminiExtensionV1, .geminiCommandV1, .geminiAgentV1, .geminiIgnoreV1: + "Pinned Gemini CLI source format" + case .openCodeConfigV2, .openCodeCommandV2, .openCodeAgentV2: + "Pinned OpenCode source format" + case .claudeSettingsV1, .claudePluginV1, .claudeMarketplaceV1, .claudeCommandV1, .claudeAgentV1: + "Documented Claude Code format (https://code.claude.com/docs); upstream source revision unavailable" + case .cursorMCPV1, .cursorPluginV1, .cursorCommandV1, .cursorAgentV1, .cursorIgnoreV1: + "Documented Cursor format (https://cursor.com/docs); upstream source revision unavailable" } } - package var producerRevision: String { + /// Exact upstream source revision when available. Documentation-only profiles have no commit. + package var producerRevision: String? { switch self { case .rulesyncSourcesV1, .rulesyncNpmV1, .rulesyncConfig, .rulesyncGitHubV1, .rulesyncAPMV1: "fbe4fe58334cab4e84b87f20d730d6450a35e0f7" @@ -21,6 +38,15 @@ package enum SourceImportProfile: String, Sendable { "787a97cc52fbbcc344374e1567b2a1e5b8adf441" case .vercelProjectV2, .vercelUserV3: "e781cb4d07433dfe1d19e924ed45cc61738c55ec" + case .codexConfigV1: + "092d3acd6bec3e3a14bdc7e7a2810ab628ab759d" + case .geminiSettingsV1, .geminiExtensionV1, .geminiCommandV1, .geminiAgentV1, .geminiIgnoreV1: + "5a5c7180ff3f0a02511f54b54db7f228d4982a30" + case .openCodeConfigV2, .openCodeCommandV2, .openCodeAgentV2: + "fedc6f208aa2bd54c1019227214568083f6380ad" + case .claudeSettingsV1, .claudePluginV1, .claudeMarketplaceV1, .claudeCommandV1, .claudeAgentV1, + .cursorMCPV1, .cursorPluginV1, .cursorCommandV1, .cursorAgentV1, .cursorIgnoreV1: + nil } } } @@ -52,6 +78,8 @@ package struct ImportBindingRequirement: Equatable, Sendable { package let reason: String /// Symbolic producer binding only; the process environment is never read. package var environmentVariable: String? = nil + /// Identifier used by RuntimeBinding.secret; the literal remains outside the proposal. + package var key: String? = nil } package struct ImportPin: Equatable, Sendable { @@ -105,9 +133,18 @@ package struct ImportedSource: Equatable, Sendable { } } +package struct ImportMemberCoordinate: Equatable, Sendable { + package let containerRoot: String + package let selector: ComponentReferenceDeclaration + package let profile: SourceImportProfile + package let formatVersion: Int +} + package struct ImportedComponent: Equatable, Sendable { + /// The original producer document, including inline declarations and referenced files. package let origin: ImportLocation package let declaration: ComponentDeclaration + package var member: ImportMemberCoordinate? = nil } /// This is a preservation intention, not a retained object or an adoption receipt. E must freeze @@ -124,12 +161,23 @@ package struct ImportResourceProposal: Equatable, Sendable { package let requiresStandaloneSource: Bool package var kind: DeclaredComponentKind? = nil package var selected = true + /// E must reconstruct symbolic fields and keep the original freshness preimage private. + package var requiresBindingRewrite = false +} + +/// Producer package identity is provenance, not a component, source pin or deployment choice. +package struct ImportPackageMetadata: Equatable, Sendable { + package let name: String + package let version: String + package let nameLocation: ImportLocation + package let versionLocation: ImportLocation } /// Canonical intent and evidence only. Raw documents and literal credentials never escape parsing. /// Application, target ownership and adoption belong to the shared import lifecycle. package struct SourceImportProposal: Equatable, Sendable { package let profile: SourceImportProfile + package var packageMetadata: ImportPackageMetadata? = nil package var sources: [ImportedSource] = [] package var components: [ImportedComponent] = [] package var resources: [ImportResourceProposal] = [] diff --git a/Sources/Components/Import/YAMLSourceImport.swift b/Sources/Components/Import/YAMLSourceImport.swift index 9a35e3e..54a8360 100644 --- a/Sources/Components/Import/YAMLSourceImport.swift +++ b/Sources/Components/Import/YAMLSourceImport.swift @@ -214,7 +214,17 @@ enum YAMLSourceImport { return } } - for field in ["name", "version"] { root[field]!.unconverted(into: &diagnostics) } + let name = root["name"]! + let version = root["version"]! + for field in [name, version] + where field.string!.contains("://") && !ImportInput.safeLocator(field.string!) { + diagnostics.binding(field.location) + field.unconverted(into: &diagnostics) + return + } + diagnostics.proposal.packageMetadata = .init( + name: name.string!, version: version.string!, + nameLocation: name.location, versionLocation: version.location) root.unknown( [ "$schema", "name", "version", "target", "targets", "includes", "dependencies", diff --git a/Tests/ComponentsTests/ImportNativeTests.swift b/Tests/ComponentsTests/ImportNativeTests.swift new file mode 100644 index 0000000..440c999 --- /dev/null +++ b/Tests/ComponentsTests/ImportNativeTests.swift @@ -0,0 +1,339 @@ +import AgentsCore +import Components +import Foundation +import Testing + +struct ImportNativeTests { + @Test(arguments: [ + SourceImportProfile.claudeSettingsV1, .codexConfigV1, .cursorMCPV1, .geminiSettingsV1, + .openCodeConfigV2, + ]) + func fiveNativeMCPProfilesKeepArgvBindingsAndOriginalLocations(_ profile: SourceImportProfile) + throws + { + let fixture = try NativeImportFixture() + let file: String + let text: String + switch profile { + case .codexConfigV1: + file = "config.toml" + text = + "[mcp_servers.review]\ncommand='review-server'\nargs=['--read-only']\nenv_vars=['PUBLIC_TOKEN']\n[mcp_servers.review.env]\nTOKEN='NATIVE_SECRET_CANARY'\n" + case .openCodeConfigV2: + file = "opencode.jsonc" + text = + #"{"mcp":{"servers":{"review":{"type":"local","command":["review-server","--read-only"],"environment":{"TOKEN":"NATIVE_SECRET_CANARY"}}}}}"# + default: + file = "settings.json" + text = + #"{"mcpServers":{"review":{"command":"review-server","args":["--read-only"],"env":{"TOKEN":"NATIVE_SECRET_CANARY"}}}}"# + } + try fixture.write(file, text) + let before = try fixture.hash() + let result = try SourceImport.preview(fixture.input(profile, file)) + let item = try #require(result.components.first) + guard case .mcpServer(let name, .stdio(let run), let agents, _, _) = item.declaration else { + Issue.record("Expected typed stdio member") + return + } + #expect(name == "review") + #expect(run.executable == "review-server") + #expect(run.arguments == ["--read-only"]) + #expect(agents?.count == 1) + if case .secret(let key) = run.environment["TOKEN"] { + #expect(result.bindings.contains { $0.key == key }) + } else { + Issue.record("Literal credential must be symbolic") + } + if profile == .codexConfigV1 { + #expect(run.environment["PUBLIC_TOKEN"] == .environment("PUBLIC_TOKEN")) + } + #expect(item.member?.selector == .mcpServer(name: "review")) + #expect(item.member?.containerRoot == ".") + #expect(item.origin.document == file) + #expect(item.origin.span?.start != nil) + #expect(result.resources.last?.requiresBindingRewrite == true) + #expect(result.resources.last?.observedHash == nil) + #expect(!String(reflecting: result).contains("NATIVE_SECRET_CANARY")) + #expect(try fixture.hash() == before) + } + + @Test func nativeProfileProvenanceUsesUpstreamSourcesAndHonestDocumentationStatus() { + #expect( + SourceImportProfile.codexConfigV1.producerRevision + == "092d3acd6bec3e3a14bdc7e7a2810ab628ab759d") + #expect( + SourceImportProfile.geminiExtensionV1.producerRevision + == "5a5c7180ff3f0a02511f54b54db7f228d4982a30") + #expect( + SourceImportProfile.openCodeConfigV2.producerRevision + == "fedc6f208aa2bd54c1019227214568083f6380ad") + for profile in [ + SourceImportProfile.claudeSettingsV1, .claudePluginV1, .claudeMarketplaceV1, + .claudeCommandV1, .claudeAgentV1, .cursorMCPV1, .cursorPluginV1, .cursorCommandV1, + .cursorAgentV1, .cursorIgnoreV1, + ] { + #expect(profile.producerRevision == nil) + #expect(profile.specificationStatus.contains("Documented")) + #expect(profile.specificationStatus.contains("upstream source revision unavailable")) + } + } + + @Test func claudeContainerPreservesTypedChildrenRootsExecutableClosureAndSecrets() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"review-bundle","version":"1","mcpServers":{"review":{"command":"${CLAUDE_PLUGIN_ROOT}/bin/server","env":{"TOKEN":"NATIVE_SECRET_CANARY"}}}}"# + ) + try fixture.write("bundle/bin/server", "#!/bin/sh\nexit 0\n", executable: true) + try fixture.write( + "bundle/commands/check.md", "---\ndescription: Check changes\n---\nReview the change.\n") + try fixture.write( + "bundle/agents/reviewer.md", + "---\nname: reviewer\ndescription: Review changes\n---\nReview carefully.\n") + try fixture.write( + "bundle/skills/audit/SKILL.md", "---\nname: audit\ndescription: Audit changes\n---\nAudit.\n") + try fixture.write( + "bundle/.lsp.json", + #"{"swift":{"command":"swift-lsp","extensionToLanguage":{".swift":"swift"}}}"#) + try fixture.write( + "bundle/hooks/hooks.json", + #"{"hooks":{"PreToolUse":[{"matcher":"Read","hooks":[{"type":"command","command":"./bin/server"}]}]}}"# + ) + var input = fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json") + input.selection = [] // Member all/none is B's operation, not container parsing. + let before = try fixture.hash() + let result = try SourceImport.preview(input) + #expect( + Set(result.components.map(\.declaration.kind)) == [ + .command, .subagent, .skills, .mcpServer, .lspServer, .hook, + ]) + #expect(result.components.allSatisfy { $0.member?.containerRoot == "bundle" }) + #expect( + result.components.first { $0.declaration.kind == .command }?.origin.document + == "bundle/commands/check.md") + #expect( + result.components.first { $0.declaration.kind == .lspServer }?.origin.document + == "bundle/.lsp.json") + #expect( + result.resources.contains { + $0.path == "bin/server" && $0.executableFlags["."] == true && $0.requiresStandaloneSource + }) + #expect(!result.resources.contains { $0.sourceAlias == "native-input" && $0.path == "." }) + #expect( + result.resources.first { $0.path == ".claude-plugin/plugin.json" }?.requiresBindingRewrite + == true) + #expect(!String(reflecting: result).contains("NATIVE_SECRET_CANARY")) + #expect(try fixture.hash() == before) + } + + @Test func cursorReplacementAndGeminiCommandNamespaceKeepProducerMeaning() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "cursor/.cursor-plugin/plugin.json", #"{"name":"review","commands":"custom"}"#) + try fixture.write("cursor/commands/ignored.md", "Default must not be selected\n") + try fixture.write("cursor/custom/selected.txt", "Selected prompt\n") + let cursor = try SourceImport.preview( + fixture.input(.cursorPluginV1, "cursor/.cursor-plugin/plugin.json")) + #expect(cursor.components.map(\.member?.selector) == [.command(name: "selected")]) + try fixture.write("extension/gemini-extension.json", #"{"name":"review","version":"1"}"#) + try fixture.write( + "extension/commands/gcs/sync.toml", "description='Sync'\nprompt='Sync {{args}}'\n") + let gemini = try SourceImport.preview( + fixture.input(.geminiExtensionV1, "extension/gemini-extension.json")) + #expect(gemini.components.first?.member?.selector == .command(name: "gcs/sync")) + #expect(gemini.components.first?.origin.document == "extension/commands/gcs/sync.toml") + } + + @Test func codexRoleRelativeFileAndOpenCodeOrderedPolicyBecomeTypedIntent() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "codex/config.toml", + "[agents.review]\ndescription='Review'\nconfig_file='./roles/review.toml'\n") + try fixture.write( + "codex/roles/review.toml", "developer_instructions='Review carefully'\nmodel='model-id'\n") + let codex = try SourceImport.preview(fixture.input(.codexConfigV1, "codex/config.toml")) + #expect(codex.components.first?.origin.document == "codex/roles/review.toml") + #expect(codex.resources.contains { $0.path == "codex/roles/review.toml" }) + try fixture.write( + "opencode.jsonc", + #"{"commands":{"review":{"description":"Review","template":"Review $ARGUMENTS"}},"agents":{"reviewer":{"description":"Reviewer","mode":"subagent","system":"Review","model":"provider/model"}},"permissions":[{"action":"read","resource":"*","effect":"deny"},{"action":"read","resource":"safe/*","effect":"allow"}]}"# + ) + let opencode = try SourceImport.preview(fixture.input(.openCodeConfigV2, "opencode.jsonc")) + #expect( + Set(opencode.components.map(\.declaration.kind)) == [.command, .subagent, .permissions]) + guard case .permissions(_, let rules, _, _, _) = opencode.components.last?.declaration else { + Issue.record("Expected native ordered policy") + return + } + #expect(rules == [.deny(.tool("read"), "*"), .allow(.tool("read"), "safe/*")]) + } + + @Test func selectedCatalogCoordinatesKeepExactPinsAndNeverExecuteCommandSources() throws { + let fixture = try NativeImportFixture() + let commit = String(repeating: "a", count: 40) + try fixture.write( + "catalog/.claude-plugin/marketplace.json", + """ + {"name":"catalog","owner":{"name":"owner"},"plugins":[ + {"name":"pinned","source":{"source":"github","repo":"acme/review","ref":"main","sha":"\(commit)"}}, + {"name":"mutable","source":{"source":"url","url":"https://example.test/repo.git","ref":"main"}}, + {"name":"command","source":{"source":"command","command":"touch SHOULD_NOT_EXIST"}}]} + """) + var input = fixture.input(.claudeMarketplaceV1, "catalog/.claude-plugin/marketplace.json") + let unselected = try SourceImport.preview(input) + #expect(unselected.sources.isEmpty) + input.selection = ["pinned", "mutable", "command"] + let before = try fixture.hash() + let result = try SourceImport.preview(input) + #expect(result.sources.map(\.pin.commit) == [commit, nil]) + #expect(result.sources.first?.declaration?.requirement == .revision(commit)) + #expect(result.sources.first?.requestedRef == "main") + #expect(result.diagnostics.contains { $0.code == .incompletePin }) + #expect(result.diagnostics.contains { $0.code == .unconverted }) + #expect( + !FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("SHOULD_NOT_EXIST").path)) + #expect(try fixture.hash() == before) + } + + @Test func nativeRefusalsAreLocatedValueFreeAndPreserveAllInputBytes() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "settings.json", + #"{"mcpServers":{"bad":{"command":"tool","args":["--token=NATIVE_SECRET_CANARY"]}},"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"echo a | sed b"}]}]},"future":{"token":"NATIVE_SECRET_CANARY"}}"# + ) + let before = try fixture.hash() + let result = try SourceImport.preview(fixture.input(.claudeSettingsV1, "settings.json")) + #expect(result.components.isEmpty) + #expect(!result.bindings.isEmpty) + #expect( + result.diagnostics.contains { + $0.code == .unconverted && $0.location.document == "settings.json" + }) + #expect(!String(reflecting: result).contains("NATIVE_SECRET_CANARY")) + #expect(try fixture.hash() == before) + try fixture.write("duplicate.json", #"{"mcpServers":{},"mcpServers":{}}"#) + let duplicate = try SourceImport.preview(fixture.input(.claudeSettingsV1, "duplicate.json")) + #expect(duplicate.components.isEmpty) + #expect(duplicate.diagnostics.last?.code == .invalidInput) + try fixture.write( + "bundle/.claude-plugin/plugin.json", #"{"name":"bundle","commands":"./../outside"}"#) + let traversal = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(traversal.diagnostics.last?.code == .unsafePath) + var limits = SourceImportLimits() + limits.documentBytes = 8 + #expect( + try SourceImport.preview(fixture.input(.claudeSettingsV1, "settings.json"), limits: limits) + .components.isEmpty) + } + + @Test func nativeIgnoreAndCatalogSubdirectoryPreserveFormatCoordinates() throws { + let fixture = try NativeImportFixture() + try fixture.write(".geminiignore", "build/\n!important.txt\n") + let ignored = try SourceImport.preview(fixture.input(.geminiIgnoreV1, ".geminiignore")) + guard case .ignore(_, let patterns, _, _, _, _) = ignored.components.first?.declaration else { + Issue.record("Expected context exclusion patterns") + return + } + #expect(patterns == ["build/", "!important.txt"]) + let commit = String(repeating: "b", count: 40) + try fixture.write( + ".claude-plugin/marketplace.json", + """ + {"name":"catalog","owner":{"name":"owner"},"plugins":[ + {"name":"nested","source":{"source":"git-subdir","url":"https://example.test/repo.git","path":"plugins/review","sha":"\(commit)"}}]} + """) + var input = fixture.input(.claudeMarketplaceV1, ".claude-plugin/marketplace.json") + input.selection = ["nested"] + let result = try SourceImport.preview(input) + #expect(result.sources.first?.declaration?.path == "plugins/review") + #expect(result.sources.first?.pin.commit == commit) + guard case .plugin(_, let path, _, _, _, _, _, _, _) = result.components.first?.declaration + else { + Issue.record("Expected selected catalog plugin") + return + } + #expect(path == ".") + } + + @Test func optionalNativeDescriptionsAndReferencedUnknownFieldsStayVisible() throws { + let fixture = try NativeImportFixture() + try fixture.write("command.toml", "prompt='Review {{args}}'\n") + let command = try SourceImport.preview(fixture.input(.geminiCommandV1, "command.toml")) + #expect(command.components.count == 1) + try fixture.write("opencode.jsonc", #"{"commands":{"review":{"template":"Review"}}}"#) + let opencode = try SourceImport.preview(fixture.input(.openCodeConfigV2, "opencode.jsonc")) + #expect(opencode.components.count == 1) + try fixture.write("bundle/.claude-plugin/plugin.json", #"{"name":"bundle"}"#) + try fixture.write( + "bundle/.mcp.json", #"{"mcpServers":{},"future":{"token":"NATIVE_SECRET_CANARY"}}"#) + let bundle = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect( + bundle.diagnostics.contains { + $0.code == .unconverted && $0.location.document == "bundle/.mcp.json" + }) + #expect(!bundle.bindings.isEmpty) + #expect(bundle.resources.contains { $0.path == ".mcp.json" && $0.requiresBindingRewrite }) + #expect(!String(reflecting: bundle).contains("NATIVE_SECRET_CANARY")) + } + + @Test func missingExplicitContainerMembersAreLocatedWhileOptionalDefaultsStayOptional() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "bundle/.cursor-plugin/plugin.json", #"{"name":"bundle","commands":"missing"}"#) + let missing = try SourceImport.preview( + fixture.input(.cursorPluginV1, "bundle/.cursor-plugin/plugin.json")) + #expect(missing.components.isEmpty) + #expect( + missing.diagnostics.contains { + $0.code == .missingResource && $0.location.document == "bundle/.cursor-plugin/plugin.json" + && $0.location.pointer == "/commands" && $0.location.span != nil + }) + try fixture.write("bundle/.cursor-plugin/plugin.json", #"{"name":"bundle"}"#) + let defaults = try SourceImport.preview( + fixture.input(.cursorPluginV1, "bundle/.cursor-plugin/plugin.json")) + #expect(!defaults.diagnostics.contains { $0.code == .missingResource }) + } + + @Test func typedMembersStayStableWhenCallerMovesTheInputRoot() throws { + let one = try NativeImportFixture() + let two = try NativeImportFixture() + for fixture in [one, two] { + try fixture.write("bundle/.cursor-plugin/plugin.json", #"{"name":"bundle"}"#) + try fixture.write("bundle/commands/review.md", "Review\n") + } + let a = try SourceImport.preview( + one.input(.cursorPluginV1, "bundle/.cursor-plugin/plugin.json")) + let b = try SourceImport.preview( + two.input(.cursorPluginV1, "bundle/.cursor-plugin/plugin.json")) + #expect(a.components.map(\.member) == b.components.map(\.member)) + #expect(a.components.map(\.origin) == b.components.map(\.origin)) + #expect(a.resources.map(\.observedHash) == b.resources.map(\.observedHash)) + } +} + +private final class NativeImportFixture { + let root: URL + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "native-import-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + deinit { do { try FileManager.default.removeItem(at: root) } catch { Issue.record(error) } } + func write(_ path: String, _ text: String, executable: Bool = false) throws { + let file = root.appendingPathComponent(path) + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: file) + if executable { + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: file.path) + } + } + func input(_ profile: SourceImportProfile, _ path: String) -> SourceImportInput { + .init(profile: profile, root: root, document: path) + } + func hash() throws -> String { try FileHash.folderHash(root) } +} diff --git a/Tests/ComponentsTests/ImportProfileTests.swift b/Tests/ComponentsTests/ImportProfileTests.swift index 643c3d8..bb35382 100644 --- a/Tests/ComponentsTests/ImportProfileTests.swift +++ b/Tests/ComponentsTests/ImportProfileTests.swift @@ -28,6 +28,42 @@ struct ImportProfileTests { #expect(rulesync.components.isEmpty) } + @Test func apmPackageIdentityIsLocatedMetadataAndDoesNotBlockAuthoringContent() throws { + let fixture = try ImportProfileFixture() + // APM permits a manifest with only its required package identity fields. + try fixture.write("apm.yml", "name: example\nversion: '1.0.0'\n") + try fixture.write( + ".apm/skills/review/SKILL.md", + "---\nname: review\ndescription: Review\n---\n# Review\n") + let before = try fixture.hash() + let proposal = try SourceImport.preview(fixture.input(.apmManifest, "apm.yml")) + #expect(proposal.diagnostics.isEmpty) + #expect(proposal.bindings.isEmpty) + #expect(proposal.components.count == 1) + #expect(proposal.resources.first?.requiresStandaloneSource == true) + let metadata = try #require(proposal.packageMetadata) + #expect(metadata.name == "example") + #expect(metadata.version == "1.0.0") + #expect(metadata.nameLocation.document == "apm.yml") + #expect(metadata.nameLocation.span?.line == 1) + #expect(metadata.versionLocation.span?.line == 2) + #expect(proposal.profile.producerRevision == "787a97cc52fbbcc344374e1567b2a1e5b8adf441") + #expect(try fixture.hash() == before) + + try fixture.write("apm.yml", "name: example\nversion: '1.0.0'\nscripts: {start: never-run}\n") + let unresolved = try SourceImport.preview(fixture.input(.apmManifest, "apm.yml")) + #expect(unresolved.packageMetadata == metadata) + #expect( + unresolved.diagnostics.contains { $0.code == .unconverted && $0.location.span?.line == 3 }) + #expect(!String(reflecting: unresolved).contains("never-run")) + + try fixture.write("apm.yml", "name: https://user:METADATA_SECRET@host.test\nversion: '1.0.0'\n") + let privateMetadata = try SourceImport.preview(fixture.input(.apmManifest, "apm.yml")) + #expect(privateMetadata.packageMetadata == nil) + #expect(!privateMetadata.bindings.isEmpty) + #expect(!String(reflecting: privateMetadata).contains("METADATA_SECRET")) + } + @Test func apmCompositionNeedsMatchingCoordinatesAndCapturesExplicitContentHonestly() throws { let fixture = try ImportProfileFixture() try fixture.write( From de2330da3a87ac3b81d4401479d588c607a68c87 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:07:58 +0800 Subject: [PATCH 094/171] fix: preserve native target authority and object kinds --- .../AgentsCore/NativeTargetCoordination.swift | 180 +++++++++++++----- Sources/AgentsCore/TransactionPaths.swift | 46 ++--- .../AgentsCore/TransactionPublication.swift | 6 +- Sources/AgentsCore/TransactionSession.swift | 6 +- .../RegisteredNativeTargetTests.swift | 149 +++++++++++++++ 5 files changed, 309 insertions(+), 78 deletions(-) diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index 0ac6f4d..8285a06 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -84,7 +84,9 @@ enum FixedNativeTargetRoute: String, Codable, Sendable, CaseIterable { return sharedRoutes.first { $0.metadata == key } } - func logicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + func logicalDirectory(_ environment: RuntimeEnvironment, validateExistingOverride: Bool = true) + throws -> URL + { func home() throws -> URL { try Self.absoluteDirectory(environment.homeDirectory) } func override(_ key: String) throws -> URL? { guard let value = environment.environment[key], !value.isEmpty else { return nil } @@ -100,7 +102,9 @@ enum FixedNativeTargetRoute: String, Codable, Sendable, CaseIterable { case .claudeSettingsUser: return try override("CLAUDE_CONFIG_DIR") ?? home().appendingPathComponent(".claude") case .codexHooksProject: return try Self.codexMCPProject.logicalDirectory(environment) - case .codexHooksUser: return try Self.codexMCPUser.logicalDirectory(environment) + case .codexHooksUser: + return try Self.codexMCPUser.logicalDirectory( + environment, validateExistingOverride: validateExistingOverride) case .cursorHooksProject: return try Self.cursorMCPProject.logicalDirectory(environment) case .cursorHooksUser: return try Self.cursorMCPUser.logicalDirectory(environment) case .geminiIgnoreProject, .cursorIgnoreProject: @@ -114,7 +118,7 @@ enum FixedNativeTargetRoute: String, Codable, Sendable, CaseIterable { ".codex") case .codexMCPUser: if let root = try override("CODEX_HOME") { - _ = try DirectoryHandle(at: root.resolvingSymlinksInPath()) + if validateExistingOverride { _ = try DirectoryHandle(at: root.resolvingSymlinksInPath()) } return root } return try home().appendingPathComponent(".codex") @@ -157,7 +161,7 @@ enum FixedNativeTargetRoute: String, Codable, Sendable, CaseIterable { /// A closed loader recipe. Named routes carry only validated native member names; /// runtime directories remain owned by the recipe and explicit environment. package struct NativeTargetRoute: RawRepresentable, Hashable, Codable, Sendable { - package enum Member: String, Codable, Sendable { + package enum Member: String, Codable, Sendable, CaseIterable { case claudeCommand, claudeAgent, claudeSkillPlugin case codexAgent, geminiCommand, geminiAgent, geminiExtension case cursorCommand, cursorAgent, cursorLocalPlugin @@ -339,38 +343,117 @@ package struct NativeTargetRoute: RawRepresentable, Hashable, Codable, Sendable else { return nil } return route } - func logicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { - if let fixed { return try fixed.logicalDirectory(environment) } - let base: URL + func rootAuthority(_ environment: RuntimeEnvironment, validateExistingOverride: Bool = true) + throws -> NativeRootAuthority + { + if let fixed { + return NativeRootAuthority( + loader: try fixed.logicalDirectory( + environment, validateExistingOverride: validateExistingOverride), descendants: []) + } + let base: FixedNativeTargetRoute switch member! { case .claudeCommand, .claudeAgent, .claudeSkillPlugin: - base = try (memberScope == .project ? Self.claudeSettingsProject : .claudeSettingsUser) - .logicalDirectory(environment) + base = memberScope == .project ? .claudeSettingsProject : .claudeSettingsUser case .codexAgent: - base = try (memberScope == .project ? Self.codexMCPProject : .codexMCPUser).logicalDirectory( - environment) + base = memberScope == .project ? .codexMCPProject : .codexMCPUser case .geminiCommand, .geminiAgent, .geminiExtension: - base = try (memberScope == .project ? Self.geminiMCPProject : .geminiMCPUser) - .logicalDirectory(environment) + base = memberScope == .project ? .geminiMCPProject : .geminiMCPUser case .cursorCommand, .cursorAgent, .cursorLocalPlugin: - base = try (memberScope == .project ? Self.cursorMCPProject : .cursorMCPUser) - .logicalDirectory(environment) + base = memberScope == .project ? .cursorMCPProject : .cursorMCPUser } - let container: String + let container: [String] switch member! { - case .claudeCommand, .geminiCommand, .cursorCommand: container = "commands" - case .claudeAgent, .codexAgent, .geminiAgent, .cursorAgent: container = "agents" - case .claudeSkillPlugin: container = "skills" - case .cursorLocalPlugin: container = "plugins/local" - case .geminiExtension: container = "extensions" - } - let nested = name!.split(separator: "/").dropLast().map(String.init) - var result = base.resolvingSymlinksInPath() + case .claudeCommand, .geminiCommand, .cursorCommand: container = ["commands"] + case .claudeAgent, .codexAgent, .geminiAgent, .cursorAgent: container = ["agents"] + case .claudeSkillPlugin: container = ["skills"] + case .cursorLocalPlugin: container = ["plugins", "local"] + case .geminiExtension: container = ["extensions"] + } + return NativeRootAuthority( + loader: try base.logicalDirectory( + environment, validateExistingOverride: validateExistingOverride), + descendants: container + name!.split(separator: "/").dropLast().map(String.init)) + } + func logicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + try rootAuthority(environment).logicalDirectory + } + func physicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + try rootAuthority(environment).physicalDirectory() + } + + /// Detect closed user slots without creating a root or granting publication authority. + static func userRoute(at destination: URL, environment: RuntimeEnvironment) throws -> Self? { + let target = destination.deletingLastPathComponent().resolvingSymlinksInPath() + .appendingPathComponent(destination.lastPathComponent) + func matches(_ route: Self) throws -> Bool { + guard route.basename.utf8.elementsEqual(target.lastPathComponent.utf8) else { return false } + let authority = try route.rootAuthority(environment, validateExistingOverride: false) + let planned = authority.plannedPhysicalDirectory + let targetParent = target.deletingLastPathComponent() + if planned.path.utf8.elementsEqual(targetParent.path.utf8) { + _ = try authority.physicalDirectory() + return true + } + if planned.resolvingSymlinksInPath().path.utf8.elementsEqual(targetParent.path.utf8) { + _ = try authority.physicalDirectory() + return true + } + // Unselected, disjoint roots do not impose access requirements on this target. + // Openable aliases still compare by descriptor identity, including bind aliases. + guard let candidate = try? DirectoryHandle(at: planned), + let parent = try? DirectoryHandle(at: targetParent), + try candidate.objectIdentity == parent.objectIdentity + else { return false } + _ = try authority.physicalDirectory() + return true + } + for route in allCases + where route.shared && route.basename.utf8.elementsEqual(target.lastPathComponent.utf8) { + if try matches(route) { return route } + } + for member in Member.allCases { + guard let probe = try? named(member, scope: .user, name: "probe") else { continue } + let suffix = String(probe.basename.dropFirst("probe".count)) + guard target.lastPathComponent.hasSuffix(suffix) else { continue } + let authority = try probe.rootAuthority(environment, validateExistingOverride: false) + let prefix = authority.plannedPhysicalDirectory.path + "/" + let bytes = Array(target.path.utf8) + let relative = + bytes.starts(with: prefix.utf8) + ? String(decoding: bytes.dropFirst(prefix.utf8.count), as: UTF8.self) + : target.lastPathComponent + let candidate = + probe.isContainer + ? try? named(member, scope: .user, name: relative) + : try? file(member, scope: .user, relativePath: relative) + if let candidate, try matches(candidate) { return candidate } + } + return nil + } + static func globalLogicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + try claudeMCPLocal.logicalDirectory(environment) + } + static func globalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + try globalLogicalDirectory(environment).resolvingSymlinksInPath() + } +} + +/// The configured loader boundary may be an admitted alias. Every descendant is no-follow. +struct NativeRootAuthority { + let loader: URL + let descendants: [String] + var logicalDirectory: URL { descendants.reduce(loader) { $0.appendingPathComponent($1) } } + var plannedPhysicalDirectory: URL { + descendants.reduce(loader.resolvingSymlinksInPath()) { $0.appendingPathComponent($1) } + } + func physicalDirectory() throws -> URL { + var result = loader.resolvingSymlinksInPath() let ancestry = try DirectoryAccessEvidence.capture(at: result) var opened = ancestry.directories.count == result.pathComponents.count ? try DirectoryHandle(at: result) : nil - for part in container.split(separator: "/").map(String.init) + nested { + for part in descendants { result.appendPathComponent(part) if let parent = opened, try parent.info(part) != nil { opened = try parent.child(part) @@ -380,20 +463,6 @@ package struct NativeTargetRoute: RawRepresentable, Hashable, Codable, Sendable } return result } - fileprivate func userCounterpart() throws -> Self? { - guard memberScope == .project, let member, member != .cursorCommand else { return nil } - return try Self.named(member, scope: .user, name: name!) - } - func physicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { - let logical = try logicalDirectory(environment) - return isNamed ? logical : logical.resolvingSymlinksInPath() - } - static func globalLogicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { - try claudeMCPLocal.logicalDirectory(environment) - } - static func globalDirectory(_ environment: RuntimeEnvironment) throws -> URL { - try globalLogicalDirectory(environment).resolvingSymlinksInPath() - } } /// Pathname authorization is checked separately. Neither route nor caller participates here. @@ -440,15 +509,15 @@ final class SharedResource { let ancestry: DirectoryAccessEvidence let metadataAccess: FileAccessEvidence? let metadataAncestry: DirectoryAccessEvidence? - let authorizedRoot: URL + let authority: NativeRootAuthority private var lockDescriptor: Int32? private var lockAccess: FileAccessEvidence? init(store: StateStore, route: NativeTargetRoute = .claudeMCPLocal, create: Bool) throws { guard route.shared else { throw CoreError.invalidState("project route has no shared resource") } self.route = NativeTargetRoute.targetRoute(route.root)! - authorizedRoot = try route.logicalDirectory(store.environment) - let url = try route.physicalDirectory(store.environment) + authority = try route.rootAuthority(store.environment) + let url = try authority.physicalDirectory() parent = try DirectoryHandle(at: url, create: create) ancestry = try DirectoryAccessEvidence.capture(at: url) identity = SharedResourceIdentity(parent: try parent.objectIdentity, basename: route.basename) @@ -488,7 +557,7 @@ final class SharedResource { } try ancestry.validate(at: parent.url) guard - try DirectoryHandle(at: authorizedRoot.resolvingSymlinksInPath()).objectIdentity + try DirectoryHandle(at: authority.physicalDirectory()).objectIdentity == identity.parent, try DirectoryHandle(at: parent.url).objectIdentity == identity.parent else { @@ -617,20 +686,20 @@ final class SharedResource { /// a writer must create and open the real parent before deriving its coordination domain. struct AbsentSharedRoot { let route: NativeTargetRoute - let logical: URL + let authority: NativeRootAuthority let physical: URL let ancestry: DirectoryAccessEvidence init?(store: StateStore, route: NativeTargetRoute) throws { - logical = try route.logicalDirectory(store.environment) - physical = try route.physicalDirectory(store.environment) + authority = try route.rootAuthority(store.environment) + physical = try authority.physicalDirectory() ancestry = try DirectoryAccessEvidence.capture(at: physical) guard ancestry.directories.count < physical.pathComponents.count else { return nil } self.route = route } func remainsAbsent() throws -> Bool { - guard logical.resolvingSymlinksInPath().path == physical.path else { + guard try authority.physicalDirectory().path.utf8.elementsEqual(physical.path.utf8) else { throw CoreError.invalidState("registered native root changed during inspection") } let current = try DirectoryAccessEvidence.capture(at: physical) @@ -769,15 +838,21 @@ final class TransactionLockContext { } extension StateStore { + func requireProjectNativeAuthority(at destination: URL) throws { + if scope == .project, + try NativeTargetRoute.userRoute(at: destination, environment: environment) != nil + { + throw CoreError.unsafePath("project target coincides with a registered shared user target") + } + } + package func nativeTarget(for route: NativeTargetRoute) throws -> MaterializationTarget { guard route.permits(scope) else { throw CoreError.unsafePath("project native targets require their project scope") } - if let counterpart = try route.userCounterpart(), - try route.physicalDirectory(environment).path.utf8.elementsEqual( - counterpart.physicalDirectory(environment).path.utf8) - { - throw CoreError.unsafePath("project native target coincides with a registered user target") + if !route.shared, route.isNamed { + let target = try route.physicalDirectory(environment).appendingPathComponent(route.basename) + try requireProjectNativeAuthority(at: target) } var canonical = route let parent: URL @@ -817,6 +892,7 @@ extension StateStore { guard routes.allSatisfy({ $0.permits(scope) }) else { throw CoreError.unsafePath("registered native request belongs to another scope") } + for route in routes where !route.shared && route.isNamed { _ = try nativeTarget(for: route) } while true { let before = try pendingCoordinationJournal(diagnosing: !writable) var resources: [SharedResource] = [] diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index 9874e4c..21e6ff4 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -10,25 +10,6 @@ struct TransactionPaths { store.scope == .project ? store.environment.projectDirectory : store.environment.homeDirectory let physicalState = base.resolvingSymlinksInPath().appendingPathComponent( store.directory.lastPathComponent) - if store.scope == .project { - let relative = PathSafety.relativePath( - destination.path, to: base.resolvingSymlinksInPath().path) - if InstructionLocations.isProjectTarget(relative) { - return "instructions-project/" + relative - } - if isAuthoringFile(relative.split(separator: "/").map(String.init)) { - return "instructions-authoring/" + relative - } - } else { - for agent in AgentID.allCases { - if let file = InstructionLocations.file( - for: agent, scope: .user, environment: store.environment), - InstructionLocations.physical(file) == destination.standardizedFileURL - { - return "instructions-" + agent.rawValue + "/" + file.lastPathComponent - } - } - } let admitted = Array(TransactionLockContext.current(store)?.requestedRoutes ?? []) + (TransactionLockContext.current(store)?.admissions.map(\.route) ?? []) @@ -55,9 +36,30 @@ struct TransactionPaths { } _ = try context.targetDirectory(for: route) } + if !route.shared { try store.requireProjectNativeAuthority(at: target.url) } return target.path } } + try store.requireProjectNativeAuthority(at: destination) + if store.scope == .project { + let relative = PathSafety.relativePath( + destination.path, to: base.resolvingSymlinksInPath().path) + if InstructionLocations.isProjectTarget(relative) { + return "instructions-project/" + relative + } + if isAuthoringFile(relative.split(separator: "/").map(String.init)) { + return "instructions-authoring/" + relative + } + } else { + for agent in AgentID.allCases { + if let file = InstructionLocations.file( + for: agent, scope: .user, environment: store.environment), + InstructionLocations.physical(file) == destination.standardizedFileURL + { + return "instructions-" + agent.rawValue + "/" + file.lastPathComponent + } + } + } var matchingInstallation = false for agent in AgentID.allCases { let logical = AgentRegistry.installSkillsDirectory( @@ -145,11 +147,11 @@ struct TransactionPaths { return url } - func nativeRootAuthorities(_ keys: Set) throws -> [String: URL] { - var result: [String: URL] = [:] + func nativeRootAuthorities(_ keys: Set) throws -> [String: NativeRootAuthority] { + var result: [String: NativeRootAuthority] = [:] for key in keys { if let route = NativeTargetRoute.targetRoute(key), !route.shared { - result[key] = try route.logicalDirectory(store.environment) + result[key] = try route.rootAuthority(store.environment) } } return result diff --git a/Sources/AgentsCore/TransactionPublication.swift b/Sources/AgentsCore/TransactionPublication.swift index 85d3902..76ead71 100644 --- a/Sources/AgentsCore/TransactionPublication.swift +++ b/Sources/AgentsCore/TransactionPublication.swift @@ -131,8 +131,12 @@ extension TransactionSession { guard PathSafety.isContained(url.resolvingSymlinksInPath(), in: root) else { throw CoreError.unsafePath("prepared content escapes transaction staging") } - expectation = try FileTransaction.copyExpectation( + let produced = try FileTransaction.copyExpectation( url, hash: expectation.hash, flags: expectation.executableFlags) + guard expectation.kind == nil || expectation.kind == produced.kind else { + throw CoreError.invalidState("prepared content type contradicts registered target") + } + expectation = produced try emit(.stage(index, .workPrepared)) try copy(url, named: name, index: index, container: container) } diff --git a/Sources/AgentsCore/TransactionSession.swift b/Sources/AgentsCore/TransactionSession.swift index 4f94645..8cbfc90 100644 --- a/Sources/AgentsCore/TransactionSession.swift +++ b/Sources/AgentsCore/TransactionSession.swift @@ -8,7 +8,7 @@ final class TransactionSession { let checkpoint: (String) throws -> Void let resources: [SharedResource] /// Logical project-root authorization is checked separately from opened physical parents. - private let nativeRoots: [String: URL] + private let nativeRoots: [String: NativeRootAuthority] /// Devices whose atomic renames passed a probe during this session only; `st_dev` values /// can be reused by another filesystem after an unmount. var capableDevices: Set = [] @@ -16,7 +16,7 @@ final class TransactionSession { init( journal: TransactionJournal, directory: DirectoryHandle, parents: [DirectoryHandle], checkpoint: @escaping (String) throws -> Void, resources: [SharedResource] = [], - nativeRoots: [String: URL] = [:] + nativeRoots: [String: NativeRootAuthority] = [:] ) { self.journal = journal self.directory = directory @@ -90,7 +90,7 @@ final class TransactionSession { if !resources.isEmpty { try requireScope() } if let route = NativeTargetRoute.targetRoute(journal.entries[index].path), !route.shared { guard let logical = nativeRoots[route.root], - try DirectoryHandle(at: logical.resolvingSymlinksInPath()).identity + try DirectoryHandle(at: logical.physicalDirectory()).identity == journal.roots[route.root] else { throw conflict(index, "registered native root changed after preparation") diff --git a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift index e704c9e..8d7fcfb 100644 --- a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift +++ b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift @@ -850,3 +850,152 @@ extension RegisteredNativeTargetTests { } } } + +extension RegisteredNativeTargetTests { + @Test func crossFamilyProjectAliasCannotBypassPrivateUserAgent() throws { + let fixture = try NativeRouteFixture() + let user = StateStore(scope: .user, environment: fixture.store.environment) + let userRoute = try NativeTargetRoute.named(.cursorAgent, scope: .user, name: "example") + var targetURL: URL! + var receiptURL: URL! + try user.withLock(footprint: [userRoute]) { + let target = try user.nativeTarget(for: userRoute) + targetURL = target.url + let transaction = FileTransaction(store: user) + try transaction.replacePrivate( + user.preparePrivateMaterialization(target), provider: NativeRouteBindings() + ) { + _ in Data("private user agent".utf8) + } + try transaction.commit() + receiptURL = try user.materializationReceipts(for: target.path).url + } + let receipt = try Data(contentsOf: receiptURL) + try FileManager.default.createSymbolicLink( + at: fixture.root.appendingPathComponent(".claude"), + withDestinationURL: user.environment.homeDirectory.appendingPathComponent(".cursor")) + let projectRoute = try NativeTargetRoute.named(.claudeAgent, scope: .project, name: "example") + #expect(throws: CoreError.self) { + try fixture.store.withLock(footprint: [projectRoute]) { + let target = try fixture.store.nativeTarget(for: projectRoute) + let transaction = FileTransaction(store: fixture.store) + try transaction.replace(target.url, with: .data(Data("ordinary project edit".utf8))) + try transaction.commit() + } + } + #expect(try Data(contentsOf: targetURL) == Data("private user agent".utf8)) + #expect(try Data(contentsOf: receiptURL) == receipt) + try user.withReadLock(footprint: [userRoute]) { + let target = try user.nativeTarget(for: userRoute) + let privateReceipt = try user.materializationReceipt(for: target) + #expect(privateReceipt != nil) + } + } + + @Test(arguments: [InstallScope.project, .user]) + func namedLoaderAliasRedirectStopsPublication(_ scope: InstallScope) throws { + let fixture = try NativeRouteFixture() + let a = fixture.root.appendingPathComponent("loader-a") + let b = fixture.root.appendingPathComponent("loader-b") + for url in [a, b] { + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + } + let alias = fixture.root.appendingPathComponent(scope == .project ? ".claude" : "loader-alias") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: a) + var environment = fixture.store.environment + if scope == .user { environment.environment["CLAUDE_CONFIG_DIR"] = alias.path } + let store = StateStore(scope: scope, environment: environment) + let route = try NativeTargetRoute.named(.claudeAgent, scope: scope, name: "example") + #expect(throws: CoreError.self) { + try store.withLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + let transaction = FileTransaction(store: store) { point in + if point == "stage.0.writeCreated" { + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: b) + } + } + try transaction.replace(target.url, with: .data(Data("stale authority".utf8))) + try transaction.commit() + } + } + for url in [a, b] { + #expect( + !FileManager.default.fileExists( + atPath: url.appendingPathComponent("agents/example.md").path)) + } + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: a) + if FileManager.default.fileExists( + atPath: store.directory.appendingPathComponent("transaction.json").path) + { + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { + try store.withLock {} + } + } + } + + @Test(arguments: [false, true]) + func preparedNativeOutputMustRetainRegisteredKind(_ container: Bool) throws { + let fixture = try NativeRouteFixture() + let route = try NativeTargetRoute.named( + container ? .claudeSkillPlugin : .claudeAgent, scope: .project, name: "example") + try fixture.store.withLock(footprint: [route]) { + let target = try fixture.store.nativeTarget(for: route) + try FileManager.default.createDirectory( + at: target.url.deletingLastPathComponent(), withIntermediateDirectories: true) + if container { + try FileManager.default.createDirectory(at: target.url, withIntermediateDirectories: false) + try Data("existing member".utf8).write(to: target.url.appendingPathComponent("member")) + } else { + try Data("existing native file".utf8).write(to: target.url) + } + let before = try FileSnapshot.read(at: target.url) + let transaction = FileTransaction(store: fixture.store) + try transaction.replace( + target.url, + with: .prepared { work in + let output = work.appendingPathComponent("output") + if container { + try Data("wrong kind".utf8).write(to: output) + } else { + try FileManager.default.createDirectory(at: output, withIntermediateDirectories: false) + } + return output + }) + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(try FileSnapshot.read(at: target.url) == before) + } + } + + @Test(arguments: ["AGENTS", "GEMINI"]) + func admittedNativeInstructionBasenameKeepsItsNativeReceipt(_ name: String) throws { + let fixture = try NativeRouteFixture() + // An unrelated user command alias does not authorize or restrict this project agent. + try FileManager.default.createSymbolicLink( + at: fixture.config.appendingPathComponent("commands"), withDestinationURL: fixture.root) + let route = try NativeTargetRoute.named(.claudeAgent, scope: .project, name: name) + try fixture.store.withLock(footprint: [route]) { + let target = try fixture.store.nativeTarget(for: route) + #expect(try TransactionPaths(store: fixture.store).path(for: target.url) == target.path) + let transaction = FileTransaction(store: fixture.store) + try transaction.replacePrivate( + fixture.store.preparePrivateMaterialization(target), provider: NativeRouteBindings() + ) { + _ in Data("native private sibling".utf8) + } + try transaction.commit() + let before = try #require(try fixture.store.materializationReceipt(for: target)) + let edit = FileTransaction(store: fixture.store) + try edit.replace(target.url, with: .data(Data("native private sibling; edit".utf8))) + try edit.commit() + #expect( + try fixture.store.materializationReceipt(for: target)?.generation != before.generation) + } + try fixture.store.withReadLock { + let instruction = fixture.root.appendingPathComponent("notes/" + name + ".md") + let path = try TransactionPaths(store: fixture.store).path(for: instruction) + #expect(path == "instructions-project/notes/" + name + ".md") + } + } +} From 360867fafdecadbf59f36e7df603e422a3dc6e21 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:27:08 +0800 Subject: [PATCH 095/171] feat: share native input validation and preserve resource links --- .../Adapters/ClaudeComponents.swift | 21 +- .../Adapters/CursorComponents.swift | 3 +- .../Adapters/GeminiComponents.swift | 7 +- Sources/Components/FrozenNativeIdentity.swift | 84 +++++- .../Components/NativeComponentFieldsV1.swift | 268 ++++++++++++++++++ Sources/Components/NativeLSPLayoutV1.swift | 6 +- Sources/Components/NativePluginFieldsV1.swift | 132 ++++++--- Sources/Components/NativePluginLayoutV1.swift | 11 - .../NativeComponentFieldsTests.swift | 176 ++++++++++++ .../NativeComponentTests.swift | 32 ++- 10 files changed, 652 insertions(+), 88 deletions(-) create mode 100644 Sources/Components/NativeComponentFieldsV1.swift create mode 100644 Tests/ComponentsTests/NativeComponentFieldsTests.swift diff --git a/Sources/Components/Adapters/ClaudeComponents.swift b/Sources/Components/Adapters/ClaudeComponents.swift index fed965f..9dcbb7f 100644 --- a/Sources/Components/Adapters/ClaudeComponents.swift +++ b/Sources/Components/Adapters/ClaudeComponents.swift @@ -8,13 +8,8 @@ extension ClaudeAdapter { switch input.record.kind { case "command": try input.noParameters() - var fields = try input.checkedNative([ - "argument-hint": .string, "allowed-tools": .strings, - "disallowed-tools": .strings, "when_to_use": .string, - "disable-model-invocation": .boolean, "user-invocable": .boolean, - "model": .string, "context": .oneOf(["fork"]), "agent": .string, - "background": .boolean, "effort": .oneOf(["low", "medium", "high", "xhigh", "max"]), - ]) + var fields = try input.checkedNative( + NativeComponentFieldsV1.markdownRules(.claudeCode, kind: "command")) for key in ["agent", "background"] where fields[key] != nil && fields["context"]?.text != "fork" { throw input.issue( @@ -29,16 +24,8 @@ extension ClaudeAdapter { route: .claudeCommand, path: name + ".md", selection: "file", value: .init(try input.frontmatter(fields, body: input.prompt())))) case "subagent": - var fields = try input.checkedNative([ - "disallowedTools": .strings, - "permissionMode": .oneOf([ - "default", "manual", "acceptEdits", "auto", "dontAsk", "bypassPermissions", "plan", - ]), - "maxTurns": .positiveInteger, "skills": .strings, - "memory": .oneOf(["user", "project", "local"]), "background": .boolean, - "omitClaudeMd": .boolean, "isolation": .oneOf(["worktree"]), - "effort": .oneOf(["low", "medium", "high", "xhigh", "max"]), - ]) + var fields = try input.checkedNative( + NativeComponentFieldsV1.markdownRules(.claudeCode, kind: "subagent")) let name = try input.filename() guard name.count <= 256, !name.contains(":") else { throw input.issue( diff --git a/Sources/Components/Adapters/CursorComponents.swift b/Sources/Components/Adapters/CursorComponents.swift index 4585053..5c87e8f 100644 --- a/Sources/Components/Adapters/CursorComponents.swift +++ b/Sources/Components/Adapters/CursorComponents.swift @@ -25,7 +25,8 @@ extension CursorAdapter { ["tools"], .unverified, "the documented subagent schema does not establish a tool allowlist") } - var fields = try input.checkedNative(["readonly": .boolean, "is_background": .boolean]) + var fields = try input.checkedNative( + NativeComponentFieldsV1.markdownRules(.cursorEditor, kind: "subagent")) let name = try input.filename() fields["name"] = .init(name) fields["description"] = .init(try input.text("description")) diff --git a/Sources/Components/Adapters/GeminiComponents.swift b/Sources/Components/Adapters/GeminiComponents.swift index 28393e8..b9b5bd2 100644 --- a/Sources/Components/Adapters/GeminiComponents.swift +++ b/Sources/Components/Adapters/GeminiComponents.swift @@ -18,9 +18,8 @@ extension GeminiAdapter { route: .geminiCommand, path: name + ".toml", selection: "file", value: .init(file))) case "subagent": - let native = try input.checkedNative([ - "max_turns": .positiveInteger, "timeout_mins": .positiveInteger, - ]) + let native = try input.checkedNative( + NativeComponentFieldsV1.markdownRules(.geminiCLI, kind: "subagent")) let name = try input.filename() guard name.range(of: #"^[a-z0-9_-]+$"#, options: .regularExpression) != nil else { throw input.issue(["name"], .invalid, "Gemini agent names must be lowercase slugs") @@ -69,7 +68,7 @@ extension GeminiAdapter { } extension GeminiAdapter { - private static func validAgentTool(_ name: String) -> Bool { + static func validAgentTool(_ name: String) -> Bool { let builtins: Set = [ "activate_skill", "ask_user", diff --git a/Sources/Components/FrozenNativeIdentity.swift b/Sources/Components/FrozenNativeIdentity.swift index 63a695e..0c7c567 100644 --- a/Sources/Components/FrozenNativeIdentity.swift +++ b/Sources/Components/FrozenNativeIdentity.swift @@ -7,6 +7,8 @@ enum FrozenNativeIdentity { agent: AgentID, scope: InstallScope ) throws -> (id: String, occurrences: [Int]) { let ledger = frozen.ledger + try ResolvedLedgerCodec.checkModel(ledger, limits: .standard) + try ledger.validate() let sourceIDs = frozen.sources func invalid(_ detail: String) -> CoreError { .invalidState(detail) } guard linked.recipients.contains(agent), case .declaration(let declaration) = linked.payload, @@ -44,17 +46,9 @@ enum FrozenNativeIdentity { for (resource, frozen) in zip(linked.resources, record.resources) { guard let item = ledger.resources[frozen], item.path == resource.path, item.source == sourceIDs[resource.snapshot], item.artifact == resource.artifact, - item.hash == resource.hash + item.hash == resource.hash, try ResolvedLedgerCodec.digest(item) == frozen else { throw invalid("linked resource and frozen evidence do not match") } - let flags: [String: Bool] - if item.entries.count == 1, item.entries[0].kind == .file, item.entries[0].path == "." { - flags = [resource.path: item.entries[0].executable] - } else { - flags = Dictionary( - uniqueKeysWithValues: item.entries.filter { $0.kind == .file }.map { - ($0.path, $0.executable) - }) - } + let flags = try executableFlags(item) guard resource.executableFlags.isEmpty || resource.executableFlags == flags else { throw invalid("linked executable flags and frozen resource do not match") } @@ -68,4 +62,74 @@ enum FrozenNativeIdentity { } return (id, selected.map(\.id)) } + + /// FileHash follows the selected root directory link, but does not follow links inside + /// that directory. Supporting entries use source-root coordinates, unlike selected entries. + private static func executableFlags(_ resource: LedgerResource) throws -> [String: Bool] { + guard let root = resource.entries.first(where: { $0.path == "." }) else { + throw CoreError.invalidState("missing selected resource root") + } + if root.kind == .file { return [resource.path: root.executable] } + if root.kind == .directory { + return Dictionary( + uniqueKeysWithValues: resource.entries.filter { $0.kind == .file }.map { + ($0.path, $0.executable) + }) + } + // Core's ledger admission validates containment, ancestors, link cycles and support. + // This traversal only projects the selected referent's executable flags. + var entries = Dictionary(uniqueKeysWithValues: resource.support.map { ($0.path, $0) }) + for original in resource.entries { + var entry = original + entry.path = original.path == "." ? resource.path : resource.path + "/" + original.path + entries[entry.path] = entry + } + let parents = resource.path.split(separator: "/").dropLast() + for count in 1..<(parents.count + 1) { + let ancestor = parents.prefix(count).joined(separator: "/") + if entries[ancestor] == nil { + entries[ancestor] = .init(path: ancestor, kind: .directory, executable: false) + } + } + var path: [String] = [] + var pending = resource.path.split(separator: "/").map(String.init).reversed().map { $0 } + var remainingWork = LedgerLimits.standard.encodedBytes + while let part = pending.popLast() { + guard remainingWork > 0 else { + throw CoreError.invalidState("resource projection work budget") + } + remainingWork -= 1 + if part == "." { continue } + if part == ".." { + guard !path.isEmpty else { throw CoreError.invalidState("invalid resource referent") } + path.removeLast() + continue + } + path.append(part) + let coordinate = path.joined(separator: "/") + guard let entry = entries[coordinate] else { + throw CoreError.invalidState("missing resource referent evidence") + } + if entry.kind == .symlink { + guard let link = entry.link, link.utf8.count <= remainingWork else { + throw CoreError.invalidState("invalid resource referent evidence") + } + remainingWork -= link.utf8.count + path.removeLast() + pending += link.split(separator: "/").reversed().map(String.init) + } + } + let target = path.isEmpty ? "." : path.joined(separator: "/") + guard entries[target]?.kind == .directory else { + throw CoreError.invalidState("selected native resource link is not a directory") + } + let prefix = target == "." ? "" : target + "/" + var flags: [String: Bool] = [:] + for entry in entries.values where entry.kind == .file && entry.path.hasPrefix(prefix) { + let relative = String(entry.path.dropFirst(prefix.count)) + flags[relative] = entry.executable + } + return flags + } + } diff --git a/Sources/Components/NativeComponentFieldsV1.swift b/Sources/Components/NativeComponentFieldsV1.swift new file mode 100644 index 0000000..ed51120 --- /dev/null +++ b/Sources/Components/NativeComponentFieldsV1.swift @@ -0,0 +1,268 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// Structural semantic failures contain no imported field values or machine paths. +package struct NativeComponentFieldIssue: Error { + package let field: [String] + package let reason: NativeAdapterIssue.Reason + package let detail: String +} + +/// Finite native field semantics shared by rendering and parsed source input. +/// Callers own syntax, source locations, aggregate admission and source capture. +package enum NativeComponentFieldsV1 { + static func markdownRules(_ surface: NativeClientSurface, kind: String) -> [String: + MCPNativeField] + { + switch (surface, kind) { + case (.claudeCode, "command"): + return [ + "argument-hint": .string, "allowed-tools": .strings, + "disallowed-tools": .strings, "when_to_use": .string, + "disable-model-invocation": .boolean, "user-invocable": .boolean, + "model": .string, "context": .oneOf(["fork"]), "agent": .string, + "background": .boolean, "effort": .oneOf(["low", "medium", "high", "xhigh", "max"]), + ] + case (.claudeCode, "subagent"): + return [ + "disallowedTools": .strings, + "permissionMode": .oneOf([ + "default", "manual", "acceptEdits", "auto", "dontAsk", "bypassPermissions", "plan", + ]), + "maxTurns": .positiveInteger, "skills": .strings, + "memory": .oneOf(["user", "project", "local"]), "background": .boolean, + "omitClaudeMd": .boolean, "isolation": .oneOf(["worktree"]), + "effort": .oneOf(["low", "medium", "high", "xhigh", "max"]), + ] + case (.cursorEditor, "subagent"): return ["readonly": .boolean, "is_background": .boolean] + case (.geminiCLI, "subagent"): + return [ + "max_turns": .positiveInteger, "timeout_mins": .positiveInteger, + ] + default: return [:] + } + } +} + +extension NativeComponentFieldsV1 { + /// Applicable default coordinates beneath the explicitly selected producer container. + /// Explicit Claude commands/agents replace discovery; skills add and configs merge. + /// Cursor explicit component fields replace default discovery for that component. + package static func pluginDefaults( + surface: NativeClientSurface, explicitFields: Set + ) throws -> [String: String] { + let defaults: [String: String] + switch surface { + case .claudeCode: + defaults = [ + "commands": "commands", "agents": "agents", "skills": "skills", + "hooks": "hooks/hooks.json", "mcpServers": ".mcp.json", "lspServers": ".lsp.json", + ] + return defaults.filter { + !["commands", "agents"].contains($0.key) || !explicitFields.contains($0.key) + } + case .cursorEditor: + defaults = [ + "commands": "commands", "agents": "agents", "skills": "skills", "rules": "rules", + "hooks": "hooks/hooks.json", "mcpServers": "mcp.json", + ] + return defaults.filter { !explicitFields.contains($0.key) } + default: + throw failure([], .unverified, "native plugin defaults are not established for this surface") + } + } + + /// Values are already parsed. Resource entries/documents are relative to the producer's + /// explicit container root; they convey presence and kind, never deployment ownership. + package static func plugin( + surface: NativeClientSurface, fields: [String: NativeValue], + entries: [LedgerEntry], documents: [String: NativeValue], budget: NativeDocumentBudget + ) throws -> [String: NativeValue] { + guard surface == .claudeCode || surface == .cursorEditor else { + throw failure([], .unverified, "this container profile has no shared parsed-field contract") + } + try admit(.object(fields), budget: budget) + try budget.step(entries.count) + var coordinates = Set() + for entry in entries { + try budget.allocate(entry.path.utf8.count, stage: "native resource coordinate") + try budget.step(entry.path.utf8.count) + guard (try? PathSafety.sanitizeSubpath(entry.path)) == entry.path, + coordinates.insert(entry.path).inserted + else { + throw failure([], .invalid, "native resource coordinates must be unique and contained") + } + } + for (path, value) in documents { + try budget.allocate(path.utf8.count, stage: "native document coordinate") + try admit(value, budget: budget) + } + let validator = NativePluginFieldsV1( + surface: surface, entries: entries, budget: budget, documents: documents) + try validator.validate(fields) + return fields + } + + /// One native Claude/OpenCode LSP entry, without launch or placeholder expansion. Native + /// placeholders remain source syntax; G must convert bindings before canonical capture. + package static func lsp( + surface: NativeClientSurface, fields: [String: NativeValue], budget: NativeDocumentBudget + ) throws -> [String: NativeValue] { + try admit(.object(fields), budget: budget) + switch surface { + case .claudeCode: + try NativePluginFieldsV1(surface: surface, entries: [], budget: budget, documents: [:]) + .lsp(.object(fields), field: []) + case .openCodeCLI: + // A disabled built-in entry has no explicit executable to project into a declaration. + if fields == ["disabled": .boolean(true)] { return fields } + var rules = NativeLSPLayoutV1.openCodeNativeFields + rules["command"] = .strings + rules["env"] = .object + rules["initialization"] = .object + guard fields["command"] != nil else { + throw failure(["command"], .invalid, "native LSP server entry requires command argv") + } + for (index, item) in fields.sorted(by: { $0.key < $1.key }).enumerated() { + guard let rule = rules[item.key] else { + throw failure( + [String(index)], .unverified, "native LSP field is outside the finite profile") + } + guard rule.accepts(item.value) else { + throw failure([item.key], .invalid, "native LSP field has an invalid type or range") + } + if item.key == "env", case .object(let values) = item.value, + !values.values.allSatisfy({ if case .string = $0 { true } else { false } }) + { + throw failure(["env"], .invalid, "native LSP environment requires string values") + } + } + default: + throw failure([], .unverified, "this surface has no shared native LSP input contract") + } + return fields + } + + /// A finite command/subagent frontmatter object. Name is the source member coordinate, + /// used only by schemas that permit a filename fallback. inPlugin is the actual source + /// registration context, not inferred from the desired deployment scope. No fields are dropped. + package static func markdown( + surface: NativeClientSurface, kind: DeclaredComponentKind, name: String, + fields: [String: NativeValue], inPlugin: Bool, budget: NativeDocumentBudget + ) throws -> [String: NativeValue] { + guard [.claudeCode, .cursorEditor, .geminiCLI].contains(surface), + kind == .command || kind == .subagent, + !(surface == .geminiCLI && kind == .command) + else { throw failure([], .unverified, "native Markdown input is outside this finite profile") } + try admit(.object(fields), budget: budget) + try budget.allocate(name.utf8.count, stage: "native member coordinate") + try budget.step(name.utf8.count) + if kind == .command { + guard name != ".", !name.isEmpty, + (try? PathSafety.sanitizeSubpath(name)) == name + else { + throw failure( + ["name"], .invalid, "native command requires an exact contained relative name") + } + if surface == .cursorEditor, name.contains("/") { + throw failure( + ["name"], .unverified, "nested command discovery is not established for this profile") + } + } + + var rules = markdownRules(surface, kind: kind.rawValue) + if kind == .subagent { + rules["name"] = .string + rules["description"] = .string + rules["model"] = .string + if surface != .cursorEditor { rules["tools"] = .strings } + } else if surface == .claudeCode { + rules["description"] = .string + } + for (index, item) in fields.sorted(by: { $0.key < $1.key }).enumerated() { + guard let rule = rules[item.key] else { + throw failure( + [String(index)], .unverified, "native frontmatter field has no verified projection") + } + // The native source format also admits comma-separated tools. Preserve its source + // spelling for G's canonical projection rather than guessing tool-pattern tokenization. + if surface == .claudeCode, kind == .subagent, item.key == "tools", + case .string = item.value + { + continue + } + guard rule.accepts(item.value) else { + throw failure([item.key], .invalid, "native frontmatter field has an invalid type or range") + } + } + if inPlugin, surface == .claudeCode, kind == .subagent, fields["permissionMode"] != nil { + throw failure( + ["permissionMode"], .unsupported, + "native plugin agents ignore this field; standalone policy projection would change meaning") + } + if surface == .claudeCode, kind == .command { + for key in ["agent", "background"] + where fields[key] != nil && fields["context"] != .string("fork") { + throw failure([key], .unsupported, "native command field requires context fork") + } + } + if kind == .subagent { + if surface != .cursorEditor { + guard case .string(let description) = fields["description"], !description.isEmpty, + fields["name"] != nil + else { throw failure([], .invalid, "native agent requires name and nonempty description") } + } + let effective: String + if case .string(let supplied) = fields["name"] { + effective = supplied + } else { + effective = name + } + guard !effective.isEmpty, !effective.contains("/"), !effective.contains("\\"), + effective != ".", effective != "..", !effective.utf8.contains(0) + else { throw failure(["name"], .invalid, "native agent requires a contained filename") } + if surface == .claudeCode, effective.count > 256 || effective.contains(":") { + throw failure(["name"], .invalid, "native agent name exceeds its native domain") + } + if surface == .geminiCLI { + guard effective.range(of: #"^[a-z0-9_-]+$"#, options: .regularExpression) != nil else { + throw failure(["name"], .invalid, "native agent requires a lowercase slug") + } + if case .array(let tools) = fields["tools"] { + guard + tools.allSatisfy({ + if case .string(let tool) = $0 { return GeminiAdapter.validAgentTool(tool) } + return false + }) + else { throw failure(["tools"], .invalid, "native tool is outside the pinned schema") } + } + } + } + return fields + } + + private static func failure( + _ field: [String], _ reason: NativeAdapterIssue.Reason, _ detail: String + ) -> NativeComponentFieldIssue { .init(field: field, reason: reason, detail: detail) } + + private static func admit(_ value: NativeValue, budget: NativeDocumentBudget, depth: Int = 0) + throws + { + try budget.node(depth: depth) + switch value { + case .string(let text), .decimal(let text): + try budget.allocate(text.utf8.count, stage: "native parsed value") + try budget.step(text.utf8.count) + case .array(let values): + for child in values { try admit(child, budget: budget, depth: depth + 1) } + case .object(let fields): + for (key, child) in fields { + try budget.allocate(key.utf8.count, stage: "native parsed key") + try budget.step(key.utf8.count) + try admit(child, budget: budget, depth: depth + 1) + } + default: break + } + } +} diff --git a/Sources/Components/NativeLSPLayoutV1.swift b/Sources/Components/NativeLSPLayoutV1.swift index 88deacb..74c80c7 100644 --- a/Sources/Components/NativeLSPLayoutV1.swift +++ b/Sources/Components/NativeLSPLayoutV1.swift @@ -1,6 +1,10 @@ import AgentsCore enum NativeLSPLayoutV1 { + static let openCodeNativeFields: [String: MCPNativeField] = [ + "extensions": .strings, "disabled": .boolean, + ] + static func claude(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws -> [ReplayedArtifact] { @@ -78,7 +82,7 @@ enum NativeLSPLayoutV1 { "native extensions do not encode extension-to-language IDs; runtime equivalence is not established" ) } - var fields = try input.checkedNative(["extensions": .strings, "disabled": .boolean]) + var fields = try input.checkedNative(openCodeNativeFields) guard let run = input.fields["run"]?.object else { throw input.issue(["run"], .invalid, "missing frozen LSP executable") } diff --git a/Sources/Components/NativePluginFieldsV1.swift b/Sources/Components/NativePluginFieldsV1.swift index 55e485c..b1b9030 100644 --- a/Sources/Components/NativePluginFieldsV1.swift +++ b/Sources/Components/NativePluginFieldsV1.swift @@ -5,10 +5,64 @@ import NativeDocuments /// Validates documented native container fields against the frozen bundle. Native source /// bytes and discovery precedence are preserved; this is not decomposition or installation. struct NativePluginFieldsV1 { - let input: ComponentRenderInput - let resource: LedgerResource - let root: URL - var claude: Bool { input.request.surface == .claudeCode } + let surface: NativeClientSurface + let entries: [LedgerEntry] + let budget: NativeDocumentBudget + let readJSON: (String, [String]) throws -> NativeValue + let issue: ([String], String, NativeAdapterIssue.Reason) -> Error + var claude: Bool { surface == .claudeCode } + + init(input: ComponentRenderInput, resource: LedgerResource, root: URL) { + surface = input.request.surface + entries = resource.entries + budget = input.budget + issue = { input.issue(["manifest"] + $0, $2, $1) } + readJSON = { relative, field in + try input.budget.step(resource.entries.count) + guard let entry = resource.entries.first(where: { $0.path == relative }), + entry.kind == .file, let size = entry.byteCount, size <= input.limits.resourceBytes + else { + throw input.issue( + ["manifest"] + field, .invalid, "native JSON resource is not a bounded frozen file") + } + try input.budget.allocate(size, stage: "native plugin JSON") + try input.budget.step(size) + let bytes = try Data(contentsOf: PathSafety.resolvedChild(base: root, subpath: relative)) + guard bytes.count == size else { + throw input.issue(["manifest"] + field, .invalid, "native JSON resource size changed") + } + do { + let document = try NativeDocument(bytes: bytes, format: .json, budget: input.budget) + guard let value = try document.read(.init(keys: []))?.value else { + throw input.issue( + ["manifest"] + field, .invalid, "native JSON resource has no root value") + } + return value + } catch NativeDocumentError.invalidDocument { + throw input.issue(["manifest"] + field, .invalid, "native JSON resource is malformed") + } + } + } + + init( + surface: NativeClientSurface, entries: [LedgerEntry], budget: NativeDocumentBudget, + documents: [String: NativeValue] + ) { + self.surface = surface + self.entries = entries + self.budget = budget + issue = { NativeComponentFieldIssue(field: $0, reason: $2, detail: $1) } + readJSON = { relative, field in + guard entries.contains(where: { $0.path == relative && $0.kind == .file }), + let value = documents[relative] + else { + throw NativeComponentFieldIssue( + field: field, reason: .invalid, detail: "referenced native JSON document was not supplied" + ) + } + return value + } + } static func validClaudeName(_ name: String) -> Bool { !name.isEmpty && name.unicodeScalars.allSatisfy { @@ -20,9 +74,9 @@ struct NativePluginFieldsV1 { } func fail(_ path: [String], _ detail: String, _ reason: NativeAdapterIssue.Reason = .invalid) - -> NativeComponentIssue + -> Error { - input.issue(["manifest"] + path, reason, detail) + issue(path, detail, reason) } func text(_ value: NativeValue, _ path: [String]) throws -> String { @@ -58,10 +112,10 @@ struct NativePluginFieldsV1 { else { throw CoreError.invalidState("invalid path") } } catch { throw fail(field, "native component path must remain inside its frozen plugin root") } if relative == ".", kind != .file, suffix == nil { return relative } - try input.budget.step(resource.entries.count) - guard let entry = resource.entries.first(where: { $0.path == relative }) else { - try input.budget.step(resource.entries.count) - if resource.entries.contains(where: { + try budget.step(entries.count) + guard let entry = entries.first(where: { $0.path == relative }) else { + try budget.step(entries.count) + if entries.contains(where: { $0.kind == .symlink && relative.hasPrefix($0.path + "/") }) { throw fail( @@ -94,25 +148,7 @@ struct NativePluginFieldsV1 { } func json(_ relative: String, field: [String]) throws -> NativeValue { - try input.budget.step(resource.entries.count) - guard let entry = resource.entries.first(where: { $0.path == relative }), entry.kind == .file, - let size = entry.byteCount, size <= input.limits.resourceBytes - else { - throw fail(field, "native JSON resource is not a bounded frozen file") - } - try input.budget.allocate(size, stage: "native plugin JSON") - try input.budget.step(size) - let bytes = try Data(contentsOf: PathSafety.resolvedChild(base: root, subpath: relative)) - guard bytes.count == size else { throw fail(field, "native JSON resource size changed") } - do { - let document = try NativeDocument(bytes: bytes, format: .json, budget: input.budget) - guard let value = try document.read(.init(keys: []))?.value else { - throw fail(field, "native JSON resource has no root value") - } - return value - } catch NativeDocumentError.invalidDocument { - throw fail(field, "native JSON resource is malformed") - } + try readJSON(relative, field) } func validate(_ fields: [String: NativeValue]) throws { @@ -130,8 +166,17 @@ struct NativePluginFieldsV1 { "Cursor native plugin name must be a lowercase alphanumeric/hyphen/period identifier") } } + if !claude, case .string(let version) = fields["version"] { + do { + guard try SourceRequirement.exact(version).canonicalized() == .exact(version) else { + throw fail(["version"], "native plugin version must be canonical SemVer") + } + } catch { + throw fail(["version"], "native plugin version must be canonical SemVer") + } + } for (key, value) in fields.sorted(by: { $0.key < $1.key }) { - try input.budget.step() + try budget.step() switch key { case "name", "version", "description", "homepage", "repository", "license": _ = try text(value, [key]) @@ -202,19 +247,20 @@ struct NativePluginFieldsV1 { } } // Native defaults retain their own merge/replacement behavior. They are not rewritten. - try input.budget.step(resource.entries.count * 3) - for (file, field) in claude - ? [("hooks/hooks.json", "hooks"), (".mcp.json", "mcpServers"), (".lsp.json", "lspServers")] - : [("hooks/hooks.json", "hooks"), ("mcp.json", "mcpServers")] - where resource.entries.contains(where: { $0.path == file }) { - if !claude, fields[field] != nil { continue } + let defaults = try NativeComponentFieldsV1.pluginDefaults( + surface: surface, explicitFields: Set(fields.keys)) + try budget.step(entries.count * 3) + for field in claude ? ["hooks", "mcpServers", "lspServers"] : ["hooks", "mcpServers"] { + guard let file = defaults[field], entries.contains(where: { $0.path == file }) else { + continue + } let value = try json(file, field: [field, "default"]) try configuration(value, field: field, wrapped: true) } } func configurations(_ value: NativeValue, field: String) throws { - try input.budget.step() + try budget.step() if case .array(let values) = value { guard claude || field == "mcpServers" else { throw fail([field], "native hooks do not accept an array of configuration sources") @@ -298,7 +344,7 @@ struct NativePluginFieldsV1 { func hooks(_ events: [String: NativeValue]) throws { for (event, value) in events { - try input.budget.step() + try budget.step() guard (claude ? NativeDocumentedHooksV1.claudeEvents : NativeDocumentedHooksV1.cursorEvents) .contains(event), case .array(let entries) = value @@ -337,7 +383,7 @@ struct NativePluginFieldsV1 { } func handlerFields(_ value: NativeValue, event: String) throws { - try input.budget.step() + try budget.step() guard case .object(let handler) = value else { throw fail(["hooks", event], "native handler requires an object") } @@ -493,7 +539,7 @@ struct NativePluginFieldsV1 { } func lsp(_ value: NativeValue, field: [String]) throws { - try input.budget.step() + try budget.step() guard case .object(let config) = value, let command = config["command"], case .object(let languages) = config["extensionToLanguage"], !languages.isEmpty else { @@ -533,7 +579,7 @@ struct NativePluginFieldsV1 { } func mcp(_ value: NativeValue, field: [String]) throws { - try input.budget.step() + try budget.step() guard case .object(let server) = value, (server["command"] == nil) != (server["url"] == nil) else { throw fail(field, "native MCP needs exactly one command or URL") @@ -563,7 +609,7 @@ struct NativePluginFieldsV1 { } func variables(_ value: NativeValue, field: [String], root: Bool = false) throws { - try input.budget.step() + try budget.step() guard case .object(let schema) = value else { throw fail(field, "native variables require a schema object") } @@ -610,7 +656,7 @@ struct NativePluginFieldsV1 { throw fail(["userConfig"], "native userConfig requires an object") } for (name, value) in entries { - try input.budget.step() + try budget.step() let field = ["userConfig", name] guard MCPReferenceSyntax.isName(name), case .object(let option) = value, case .string(let type) = option["type"], diff --git a/Sources/Components/NativePluginLayoutV1.swift b/Sources/Components/NativePluginLayoutV1.swift index 070d317..cf01c9a 100644 --- a/Sources/Components/NativePluginLayoutV1.swift +++ b/Sources/Components/NativePluginLayoutV1.swift @@ -87,17 +87,6 @@ enum NativePluginLayoutV1 { throw input.issue( ["name"], .invalid, "native manifest name does not match the frozen component") } - if input.request.surface == .cursorEditor, case .string(let version) = manifestFields["version"] - { - do { - guard try SourceRequirement.exact(version).canonicalized() == .exact(version) else { - throw CoreError.invalidState("invalid native version") - } - } catch { - throw input.issue( - ["manifest", "version"], .invalid, "native plugin version must be canonical SemVer") - } - } if input.request.surface == .geminiCLI { guard name.range(of: #"^[a-zA-Z0-9-]+$"#, options: .regularExpression) != nil else { throw input.issue( diff --git a/Tests/ComponentsTests/NativeComponentFieldsTests.swift b/Tests/ComponentsTests/NativeComponentFieldsTests.swift new file mode 100644 index 0000000..6ed9824 --- /dev/null +++ b/Tests/ComponentsTests/NativeComponentFieldsTests.swift @@ -0,0 +1,176 @@ +import AgentsCore +import Foundation +import NativeDocuments +import Testing + +@testable import Components + +@Suite("Parsed native component semantics") +struct NativeComponentFieldsTests { + private func budget(_ nodes: Int = 10000) -> NativeDocumentBudget { + .init( + limits: .init( + storage: 1_000_000, work: 1_000_000, nodes: nodes, depth: 64, uninterruptedBytes: 1_000_000) + ) + } + + @Test func parsedFrontmatterKeepsNativeFieldsAndRejectsIgnoredIntent() throws { + let fields: [String: NativeValue] = [ + "name": .string("auditor"), "description": .string("Inspect source."), + "permissionMode": .string("plan"), "maxTurns": .integer(3), + "tools": .array([.string("Read")]), "disallowedTools": .array([.string("Write")]), + ] + #expect( + try NativeComponentFieldsV1.markdown( + surface: .claudeCode, kind: .subagent, name: "auditor", fields: fields, inPlugin: false, + budget: budget()) + == fields) + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.markdown( + surface: .claudeCode, kind: .subagent, name: "auditor", fields: fields, + inPlugin: true, budget: budget()) + } + var commaTools = fields + commaTools["tools"] = .string("Read, Grep") + #expect( + try NativeComponentFieldsV1.markdown( + surface: .claudeCode, kind: .subagent, name: "auditor", fields: commaTools, inPlugin: false, + budget: budget()) == commaTools) + var unknown = fields + unknown["permissionmode"] = .string("value-canary") + do { + _ = try NativeComponentFieldsV1.markdown( + surface: .claudeCode, kind: .subagent, name: "auditor", fields: unknown, inPlugin: false, + budget: budget()) + Issue.record("silently ignored unknown native field") + } catch let issue as NativeComponentFieldIssue { + #expect(issue.reason == .unverified) + #expect(!issue.detail.contains("value-canary")) + } + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.markdown( + surface: .claudeCode, kind: .command, name: "review", + fields: ["background": .boolean(true)], inPlugin: false, budget: budget()) + } + #expect( + try NativeComponentFieldsV1.markdown( + surface: .claudeCode, kind: .command, name: "team/review", fields: [:], + inPlugin: false, budget: budget() + ).isEmpty) + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.markdown( + surface: .cursorEditor, kind: .command, name: "team/review", fields: [:], + inPlugin: false, budget: budget()) + } + let cursor: [String: NativeValue] = [ + "readonly": .boolean(true), "is_background": .boolean(true), + ] + #expect( + try NativeComponentFieldsV1.markdown( + surface: .cursorEditor, kind: .subagent, name: "auditor", fields: cursor, inPlugin: false, + budget: budget()) + == cursor) + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.markdown( + surface: .cursorEditor, kind: .subagent, name: "auditor", + fields: ["tools": .array([.string("Read")])], inPlugin: false, budget: budget()) + } + } + + @Test func parsedLSPPreservesArbitraryInitializationAndRejectsUnknownFields() throws { + let fields: [String: NativeValue] = [ + "command": .string("source-lsp"), + "extensionToLanguage": .object([".source": .string("source")]), + "transport": .string("socket"), "requestTimeout": .integer(100), + "initializationOptions": .object([ + "deep": .array([.null, .boolean(true), .string("${kept}\0data")]) + ]), + ] + #expect( + try NativeComponentFieldsV1.lsp(surface: .claudeCode, fields: fields, budget: budget()) + == fields) + var unknown = fields + unknown["cwd"] = .string("value-canary") + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.lsp(surface: .claudeCode, fields: unknown, budget: budget()) + } + var invalid = fields + invalid["requestTimeout"] = .integer(0) + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.lsp(surface: .claudeCode, fields: invalid, budget: budget()) + } + } + + @Test func parsedOpenCodeLSPRetainsNativeEntrySemantics() throws { + let fields: [String: NativeValue] = [ + "command": .array([.string("source-lsp"), .string("--stdio")]), + "extensions": .array([.string(".source")]), + "env": .object(["SOURCE": .string("{env:SOURCE}")]), + "initialization": .object(["any": .array([.null, .integer(7)])]), + ] + #expect( + try NativeComponentFieldsV1.lsp( + surface: .openCodeCLI, fields: fields, budget: budget()) == fields) + let disabled: [String: NativeValue] = ["disabled": .boolean(true)] + #expect( + try NativeComponentFieldsV1.lsp( + surface: .openCodeCLI, fields: disabled, budget: budget()) == disabled) + var invalid = fields + invalid["env"] = .object(["SOURCE": .integer(7)]) + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.lsp(surface: .openCodeCLI, fields: invalid, budget: budget()) + } + } + + @Test func parsedPluginUsesProducerRootAndMergeDefaults() throws { + let claudeDefaults = try NativeComponentFieldsV1.pluginDefaults( + surface: .claudeCode, explicitFields: ["commands", "agents", "skills", "hooks"]) + #expect(claudeDefaults["commands"] == nil && claudeDefaults["agents"] == nil) + #expect(claudeDefaults["skills"] == "skills" && claudeDefaults["hooks"] == "hooks/hooks.json") + let cursorDefaults = try NativeComponentFieldsV1.pluginDefaults( + surface: .cursorEditor, explicitFields: ["commands", "skills", "hooks"]) + #expect(cursorDefaults["commands"] == nil && cursorDefaults["skills"] == nil) + #expect(cursorDefaults["hooks"] == nil && cursorDefaults["mcpServers"] == "mcp.json") + let entries: [LedgerEntry] = [ + .init(path: ".", kind: .directory, executable: false), + .init(path: "commands/review.md", kind: .file, executable: false), + .init(path: "hooks/hooks.json", kind: .file, executable: false), + ] + let valid: [String: NativeValue] = [ + "name": .string("fixture"), "commands": .string("./commands/review.md"), + "hooks": .object([:]), + ] + let badDefault: NativeValue = .object(["hooks": .object(["invented": .array([])])]) + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.plugin( + surface: .claudeCode, fields: valid, + entries: entries, documents: ["hooks/hooks.json": badDefault], budget: budget()) + } + let emptyHooks: NativeValue = .object(["hooks": .object([:])]) + #expect( + try NativeComponentFieldsV1.plugin( + surface: .claudeCode, fields: valid, + entries: entries, documents: ["hooks/hooks.json": emptyHooks], budget: budget()) == valid) + // Cursor explicit hooks replace its default; an absent explicit file still fails. + let cursor: [String: NativeValue] = [ + "name": .string("fixture"), "hooks": .string("chosen.json"), + ] + let cursorEntries = entries + [.init(path: "chosen.json", kind: .file, executable: false)] + #expect( + try NativeComponentFieldsV1.plugin( + surface: .cursorEditor, fields: cursor, + entries: cursorEntries, + documents: ["chosen.json": .object(["version": .integer(1), "hooks": .object([:])])], + budget: budget()) == cursor) + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.plugin( + surface: .cursorEditor, fields: cursor, + entries: entries, documents: [:], budget: budget()) + } + #expect(throws: (any Error).self) { + try NativeComponentFieldsV1.plugin( + surface: .claudeCode, fields: valid, + entries: entries, documents: ["hooks/hooks.json": emptyHooks], budget: budget(1)) + } + } +} diff --git a/Tests/ComponentsTests/NativeComponentTests.swift b/Tests/ComponentsTests/NativeComponentTests.swift index 212d6cc..ba2aaea 100644 --- a/Tests/ComponentsTests/NativeComponentTests.swift +++ b/Tests/ComponentsTests/NativeComponentTests.swift @@ -157,22 +157,52 @@ struct NativeComponentTests { [.posixPermissions: 0o755], ofItemAtPath: fixture.project.appendingPathComponent("scripts/check").path) try fixture.write("data", to: "working/data", base: fixture.project) + try fixture.write("executable support", to: "working/check", base: fixture.project) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: fixture.project.appendingPathComponent("working/check").path) + try FileManager.default.createDirectory( + at: fixture.project.appendingPathComponent("links"), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: fixture.project.appendingPathComponent("redirect").path, + withDestinationPath: "working") + try FileManager.default.createSymbolicLink( + atPath: fixture.project.appendingPathComponent("links/working-alias").path, + withDestinationPath: "../redirect") let item: [String: Any] = [ "kind": "hook", "name": "check", "event": ["native": "SessionStart"], "run": [ "executable": "./scripts/check", "arguments": ["a'b", "$(never-execute)", surface == .geminiCLI ? "plain" : "$ordinary"], - "workingDirectory": ["path": "working"], + "workingDirectory": ["path": "links/working-alias"], "environment": ["TOKEN": ["secret": "fixture/token"]], ], "matcher": "startup", "timeoutSeconds": 7, "agents": [surface.agent.rawValue], ] let (linked, frozen) = try freeze([item], fixture) + let cwdID = try #require(frozen.ledger.components.values.first?.resources.last) + let cwd = try #require(frozen.ledger.resources[cwdID]) + #expect(cwd.entries.first?.kind == .symlink) + #expect(cwd.support.first(where: { $0.path == "working/check" })?.executable == true) + for remove in [false, true] { + var corrupted = frozen + if remove { + corrupted.ledger.resources[cwdID]!.support.removeAll { $0.path == "working/check" } + } else { + let index = try #require(cwd.support.firstIndex(where: { $0.path == "working/check" })) + corrupted.ledger.resources[cwdID]!.support[index].executable = false + } + #expect(throws: NativeComponentIssue.self) { + try lower(linked[0], corrupted, surface: surface) + } + } var ledger = frozen.ledger ledger.lowerings = [try lower(linked[0], frozen, surface: surface)] ledger = try prepared(ledger, fixture) let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) #expect(!String(decoding: encoded, as: UTF8.self).contains("private staged fixture")) + ledger = try ResolvedLedgerCodec.decode(encoded, limits: .standard) + try FileManager.default.removeItem(at: fixture.project) try replay(ledger, fixture) { output in let contribution = try NativeComponentLayoutsV1.contribution( ledger.lowerings[0], ledger: ledger, artifacts: output, limits: .standard) From c986ea8484c2d59013850cd598d0ccfd8ca18ca2 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:27:09 +0800 Subject: [PATCH 096/171] fix: resolve local sources at their declared root --- .../AgentsCore/SourceResolutionSession.swift | 12 +++- Tests/ComponentsTests/SnapshotTests.swift | 68 +++++++++++++++++++ 2 files changed, 77 insertions(+), 3 deletions(-) diff --git a/Sources/AgentsCore/SourceResolutionSession.swift b/Sources/AgentsCore/SourceResolutionSession.swift index 55f8b8c..ce619b9 100644 --- a/Sources/AgentsCore/SourceResolutionSession.swift +++ b/Sources/AgentsCore/SourceResolutionSession.swift @@ -352,10 +352,16 @@ package final class SourceResolutionSession { package func isGitSource(_ source: SourceDeclaration) throws -> Bool { guard source.kind == .local else { return source.kind == .git } let local = source.localURL(environment: store.environment) - return - (try? ProcessRunner.git( - ["-C", local.path, "rev-parse", "--git-dir"], + // Validate this directory's metadata, including worktree gitfiles, without ancestor discovery. + for path in [".git", "."] { + if (try? ProcessRunner.git( + ["--no-optional-locks", "-C", local.path, "rev-parse", "--resolve-git-dir", path], operation: .findRepositoryRoot, source: source.location)) != nil + { + return true + } + } + return false } private func localEnvironment(for source: SourceDeclaration) -> SourceEnvironment? { diff --git a/Tests/ComponentsTests/SnapshotTests.swift b/Tests/ComponentsTests/SnapshotTests.swift index cb1641e..5503114 100644 --- a/Tests/ComponentsTests/SnapshotTests.swift +++ b/Tests/ComponentsTests/SnapshotTests.swift @@ -7,6 +7,74 @@ import Testing @Suite("Exact component snapshots", .serialized) struct SnapshotTests { + @Test func localDirectoryBeneathRepositoryKeepsItsOwnContent() throws { + let fixture = try LinkFixture() + try fixture.initialize(fixture.project) + try fixture.write("Parent repository", to: "README.md", base: fixture.project) + try fixture.commit(fixture.project) + let content = fixture.project.appendingPathComponent("content") + try fixture.skill("demo", at: content) + let source = SourceDeclaration(kind: .local, location: "./content") + let before = try FileHash.folderHash(fixture.project) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + #expect(try !session.isGitSource(source)) + let view = try session.localSnapshot(source) + #expect(view.pin == nil) + #expect(try SkillSnapshotReader.read(view).map(\.name) == ["demo"]) + } + let graph = try fixture.link( + """ + version: 1 + sources: {local: {path: ./content}} + components: [{kind: skills, source: local, select: all}] + """) + #expect(graph.components.map(\.key.name) == ["demo"]) + #expect(try FileHash.folderHash(fixture.project) == before) + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } + + @Test(arguments: ["repository", "worktree", "bare"]) + func localRepositoryKindsPreserveExplicitDiscoveryRoot(_ kind: String) throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("selected", at: repository.appendingPathComponent("packages/content")) + try fixture.skill("root-only", at: repository) + let revision = try fixture.commit(repository) + let location: URL + switch kind { + case "worktree": + location = fixture.root.appendingPathComponent("worktree") + try fixture.git(repository, ["worktree", "add", "--detach", location.path]) + case "bare": + location = fixture.root.appendingPathComponent("bare") + try fixture.git( + repository, ["clone", "--bare", "--no-local", repository.path, location.path]) + try fixture.git(location, ["config", "maintenance.auto", "false"]) + try fixture.git(location, ["config", "gc.auto", "0"]) + default: location = repository + } + let source = SourceDeclaration( + kind: .local, location: location.path, path: "packages/content") + var borrowed: URL? + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + #expect(try session.isGitSource(source)) + if kind == "bare" { + #expect( + try !session.isGitSource( + SourceDeclaration( + kind: .local, location: location.appendingPathComponent("objects").path))) + } + let pin = try #require(session.candidates(for: source, requirements: [nil]).first) + #expect(pin.revision == revision) + let view = try session.snapshot(source, at: pin) + borrowed = view.root + #expect(try SkillSnapshotReader.read(view).map(\.name) == ["selected"]) + } + #expect(!FileManager.default.fileExists(atPath: try #require(borrowed).path)) + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } + @Test func frozenCatalogAndScopedLifetime() throws { let fixture = try LinkFixture() let repository = fixture.root.appendingPathComponent("repository") From 5dbc16853dbab7a32e4f8197965ea8cb214fe8d5 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:09:09 +0800 Subject: [PATCH 097/171] fix: preserve native import selection and binding semantics --- .../Import/NativeContainerImport.swift | 6 +- .../Import/NativeExecutableMembers.swift | 16 +- .../Components/Import/NativeImportInput.swift | 55 +++++- .../Import/NativeSourceImport.swift | 44 +++-- Tests/ComponentsTests/ImportNativeTests.swift | 181 ++++++++++++++++++ 5 files changed, 281 insertions(+), 21 deletions(-) diff --git a/Sources/Components/Import/NativeContainerImport.swift b/Sources/Components/Import/NativeContainerImport.swift index def4d37..8e136f5 100644 --- a/Sources/Components/Import/NativeContainerImport.swift +++ b/Sources/Components/Import/NativeContainerImport.swift @@ -100,6 +100,8 @@ enum NativeContainerImport { // The producer loads defaults then declarations; later duplicate names replace earlier ones. var winners: [String: (NativeValue, NativeImportDocument, [String])] = [:] for (value, document, keys) in mcpSources { + try NativeSourceImport.classifyMembers( + value, parsed: document, keys: keys, into: &diagnostics) guard let fields = value.importObject else { throw ImportReadFailure.invalid } for (name, entry) in fields { if let previous = winners[name] { @@ -145,6 +147,8 @@ enum NativeContainerImport { } var lspWinners: [String: (NativeValue, NativeImportDocument, [String])] = [:] for (value, document, keys) in lspSources { + try NativeSourceImport.classifyMembers( + value, parsed: document, keys: keys, into: &diagnostics) for (name, entry) in value.importObject ?? [:] { lspWinners[name] = (entry, document, keys) } } for name in lspWinners.keys.sorted() { @@ -240,7 +244,7 @@ enum NativeContainerImport { document.fields, allowed: [field], at: document.location(), into: &diagnostics) } - sources.append((fields, document, [field])) + sources.append((fields, document, field == "lspServers" ? [] : [field])) } else if case .array(let entries) = value { for entry in entries { try configurations( diff --git a/Sources/Components/Import/NativeExecutableMembers.swift b/Sources/Components/Import/NativeExecutableMembers.swift index 5914482..fdf1a10 100644 --- a/Sources/Components/Import/NativeExecutableMembers.swift +++ b/Sources/Components/Import/NativeExecutableMembers.swift @@ -90,9 +90,10 @@ extension NativeSourceImport { } var executable = command if command.hasPrefix("./") { - executable = try nativePath(command, container: container) + let path = try nativePath(command, container: container) + executable = path.contains("/") ? path : "./" + path try NativeImportInput.resource( - executable, root: container, input: parsed.input, origin: origin, + path, root: container, input: parsed.input, origin: origin, limits: limits, into: &diagnostics, admission: parsed.admission) } else if command.contains("/") { diagnostics.add( @@ -126,9 +127,9 @@ extension NativeSourceImport { NativeImportInput.unconverted(value, at: parsed.location(keys), into: &diagnostics) return } - for (index, name) in servers.keys.sorted().enumerated() { - let origin = parsed.location( - keys + [name], display: keys.map { "/" + $0 }.joined() + "/member[\(index)]") + try classifyMembers(value, parsed: parsed, keys: keys, into: &diagnostics) + for name in servers.keys.sorted() { + let origin = try parsed.memberLocation(keys, name: name) guard NativeImportInput.name(name), let fields = servers[name]?.importObject else { NativeImportInput.unconverted(servers[name]!, at: origin, into: &diagnostics) continue @@ -216,9 +217,10 @@ extension NativeSourceImport { profile: parsed.input.profile) var program = executable if executable.hasPrefix("./") { - program = try nativePath(executable, container: container) + let path = try nativePath(executable, container: container) + program = path.contains("/") ? path : "./" + path try NativeImportInput.resource( - program, root: container, input: parsed.input, origin: origin, + path, root: container, input: parsed.input, origin: origin, limits: limits, into: &diagnostics, admission: parsed.admission) } else if executable.contains("/") { diagnostics.add( diff --git a/Sources/Components/Import/NativeImportInput.swift b/Sources/Components/Import/NativeImportInput.swift index 6a6dc97..942c31c 100644 --- a/Sources/Components/Import/NativeImportInput.swift +++ b/Sources/Components/Import/NativeImportInput.swift @@ -38,6 +38,15 @@ struct NativeImportDocument { } } + /// Winner subsets retain coordinates from the complete original producer map. + func memberLocation(_ keys: [String], name: String) throws -> ImportLocation { + guard let fields = (try document.read(.init(keys: keys)))?.value?.importObject, + let index = fields.keys.sorted().firstIndex(of: name) + else { throw ImportReadFailure.invalid } + return location( + keys + [name], display: keys.map { "/" + $0 }.joined() + "/member[\(index)]") + } + func location(_ keys: [String] = [], display: String? = nil) -> ImportLocation { let observation = try? document.read(.init(keys: keys)) var range = observation?.valueRange ?? observation?.entryRanges.first @@ -149,6 +158,7 @@ enum NativeImportInput { static func bindings( _ value: NativeValue?, at location: ImportLocation, symbolic: Bool = false, + literalsOnly: Bool = false, into diagnostics: inout ImportDiagnostics, profile: SourceImportProfile? = nil ) throws -> [String: RuntimeBinding] { guard let value else { return [:] } @@ -160,7 +170,8 @@ enum NativeImportInput { if symbolic { guard MCPReferenceSyntax.isName(text) else { throw ImportReadFailure.invalid } - result[key] = binding(item, environment: text, into: &diagnostics) + result[key] = + literalsOnly ? .environment(text) : binding(item, environment: text, into: &diagnostics) } else { var reference: String? if let profile { @@ -174,7 +185,9 @@ enum NativeImportInput { if let reference, MCPReferenceSyntax.isName(reference) { - result[key] = binding(item, environment: reference, into: &diagnostics) + result[key] = + literalsOnly + ? .environment(reference) : binding(item, environment: reference, into: &diagnostics) } else if text.contains("${") || text.contains("{env:") || text.contains("{file:") { diagnostics.binding(item) diagnostics.add( @@ -189,6 +202,44 @@ enum NativeImportInput { return result } + /// Classifies native credential slots before selection/precedence. No member is emitted and + /// no referenced resource is read. Explicit symbolic references do not contain literal secrets. + static func preservationBindings( + _ fields: [String: NativeValue], at location: ImportLocation, + profile: SourceImportProfile, into diagnostics: inout ImportDiagnostics + ) { + let maps: Set = ["env", "environment", "headers", "http_headers", "env_http_headers"] + for field in maps.sorted() where fields[field] != nil { + do { + _ = try bindings( + fields[field], at: location.appending(field), + symbolic: field == "env_http_headers" && agent(profile) == .codex, + literalsOnly: true, into: &diagnostics, + profile: field == "env_http_headers" && agent(profile) != .codex ? nil : profile) + } catch { + diagnostics.binding(location.appending(field)) + diagnostics.add( + .invalidInput, location.appending(field), + "Native binding values cannot be admitted for preservation.") + } + } + _ = sensitive( + .object(fields.filter { !maps.contains($0.key) }), at: location, into: &diagnostics) + let argv = + fields["args"]?.importStrings ?? fields["command"]?.importStrings.map { + Array($0.dropFirst()) + } ?? [] + for (index, argument) in argv.enumerated() { + let flag = String(argument.split(separator: "=", maxSplits: 1).first ?? "") + if ImportInput.credentialField(flag) + || (argument.contains("://") && !ImportInput.safeLocator(argument)) + { + let coordinate = fields["args"] != nil ? "args/\(index)" : "command/\(index + 1)" + diagnostics.binding(location.appending(coordinate)) + } + } + } + static func source( _ input: SourceImportInput, root: String, origin: ImportLocation, into diagnostics: inout ImportDiagnostics diff --git a/Sources/Components/Import/NativeSourceImport.swift b/Sources/Components/Import/NativeSourceImport.swift index ae5e342..3fe00e2 100644 --- a/Sources/Components/Import/NativeSourceImport.swift +++ b/Sources/Components/Import/NativeSourceImport.swift @@ -112,13 +112,32 @@ enum NativeSourceImport { } } + /// A full parsed map is classified even when only a subset contributes canonical members. + static func classifyMembers( + _ value: NativeValue, parsed: NativeImportDocument, keys: [String], + into diagnostics: inout ImportDiagnostics + ) throws { + guard let members = value.importObject else { throw ImportReadFailure.invalid } + for name in members.keys.sorted() { + try Task.checkCancellation() + let origin = try parsed.memberLocation(keys, name: name) + if let fields = members[name]?.importObject { + NativeImportInput.preservationBindings( + fields, at: origin, profile: parsed.input.profile, into: &diagnostics) + } else { + _ = NativeImportInput.sensitive(members[name]!, at: origin, into: &diagnostics) + } + } + } + static func mcp( _ value: NativeValue, parsed: NativeImportDocument, keys: [String], container: String, limits: SourceImportLimits, into diagnostics: inout ImportDiagnostics ) throws { guard case .object(let servers) = value else { throw ImportReadFailure.invalid } + try classifyMembers(value, parsed: parsed, keys: keys, into: &diagnostics) let agent = NativeImportInput.agent(parsed.input.profile) - for (index, name) in servers.keys.sorted().enumerated() { + for name in servers.keys.sorted() { try Task.checkCancellation() if ![SourceImportProfile.claudePluginV1, .cursorPluginV1, .geminiExtensionV1].contains( parsed.input.profile), @@ -126,12 +145,7 @@ enum NativeSourceImport { { continue } - let originalNames = - (try parsed.document.read(.init(keys: keys)))?.value?.importObject?.keys.sorted() - ?? servers.keys.sorted() - let originalIndex = originalNames.firstIndex(of: name) ?? index - let location = parsed.location( - keys + [name], display: keys.map { "/" + $0 }.joined() + "/member[\(originalIndex)]") + let location = try parsed.memberLocation(keys, name: name) guard NativeImportInput.name(name), case .object(let fields) = servers[name] else { NativeImportInput.unconverted(servers[name]!, at: location, into: &diagnostics) continue @@ -169,9 +183,13 @@ enum NativeSourceImport { guard case .boolean = fields["codemode"]! else { throw ImportReadFailure.invalid } native[agent.rawValue, default: [:]]["codemode"] = fields["codemode"] } - if agent == .opencode, let oauth = fields["oauth"], oauth != .boolean(false) { - NativeImportInput.unconverted(oauth, at: location.appending("oauth"), into: &diagnostics) - continue + if agent == .opencode, let oauth = fields["oauth"] { + guard oauth == .boolean(false) else { + NativeImportInput.unconverted( + oauth, at: location.appending("oauth"), into: &diagnostics) + continue + } + native[agent.rawValue, default: [:]]["oauth"] = oauth } if let url = fields["url"]?.importString ?? fields["httpUrl"]?.importString { guard fields["command"] == nil, ImportInput.safeLocator(url), @@ -318,7 +336,7 @@ enum NativeSourceImport { try NativeImportInput.resource( path, root: container, input: parsed.input, origin: location.appending("command"), limits: limits, into: &diagnostics, admission: parsed.admission) - executable = path + executable = path.contains("/") ? path : "./" + path } else if executable.contains("/") { diagnostics.add( .unconverted, location.appending("command"), @@ -375,7 +393,9 @@ enum NativeSourceImport { parsed: NativeImportDocument, key: String, into diagnostics: inout ImportDiagnostics ) throws { guard case .object(let entries) = value else { throw ImportReadFailure.invalid } + try classifyMembers(value, parsed: parsed, keys: [key], into: &diagnostics) for (index, name) in entries.keys.sorted().enumerated() { + guard parsed.input.selection?.contains(name) ?? true else { continue } let origin = parsed.location([key, name], display: "/\(key)/member[\(index)]") guard NativeImportInput.name(name), let fields = entries[name]?.importObject else { NativeImportInput.unconverted(entries[name]!, at: origin, into: &diagnostics) @@ -448,7 +468,9 @@ enum NativeSourceImport { limits: SourceImportLimits, into diagnostics: inout ImportDiagnostics ) throws { guard case .object(let agents) = value else { throw ImportReadFailure.invalid } + try classifyMembers(value, parsed: parsed, keys: ["agents"], into: &diagnostics) for (index, name) in agents.keys.sorted().enumerated() { + guard parsed.input.selection?.contains(name) ?? true else { continue } let origin = parsed.location(["agents", name], display: "/agents/member[\(index)]") guard NativeImportInput.name(name), let fields = agents[name]?.importObject, Set(fields.keys).isSubset(of: ["description", "config_file"]), diff --git a/Tests/ComponentsTests/ImportNativeTests.swift b/Tests/ComponentsTests/ImportNativeTests.swift index 440c999..e9b8987 100644 --- a/Tests/ComponentsTests/ImportNativeTests.swift +++ b/Tests/ComponentsTests/ImportNativeTests.swift @@ -298,6 +298,187 @@ struct ImportNativeTests { #expect(!defaults.diagnostics.contains { $0.code == .missingResource }) } + @Test func preservedMCPDocumentsClassifyExcludedAndReplacedBindings() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "settings.json", + #"{"mcpServers":{"clean":{"command":"tool"},"private":{"command":"tool","env":{"CUSTOM":"EXCLUDED_SECRET"}}}}"# + ) + var input = fixture.input(.claudeSettingsV1, "settings.json") + input.selection = ["clean"] + let before = try fixture.hash() + let selected = try SourceImport.preview(input) + #expect(selected.components.count == 1) + #expect(selected.bindings.contains { $0.location.pointer.contains("member[1]/env") }) + #expect(selected.resources.allSatisfy { $0.requiresBindingRewrite && $0.observedHash == nil }) + #expect(!String(reflecting: selected).contains("EXCLUDED_SECRET")) + #expect(try fixture.hash() == before) + #expect(selected.components.first?.member?.selector == .mcpServer(name: "clean")) + try fixture.write( + "settings.json", + #"{"mcpServers":{"clean":{"command":"tool","env":{}},"private":{"command":"tool","env":{"CUSTOM":"${OPTIONAL_TOKEN}"}}}}"# + ) + let symbolic = try SourceImport.preview(input) + #expect(symbolic.components.count == 1) + #expect(symbolic.bindings.isEmpty) + #expect(symbolic.resources.allSatisfy { !$0.requiresBindingRewrite && $0.observedHash != nil }) + try fixture.write( + "settings.json", + #"{"mcpServers":{"clean":{"command":"tool"},"private":{"command":"tool","env_http_headers":{"CUSTOM":"EXCLUDED_HEADER_SECRET"}}}}"# + ) + let foreignField = try SourceImport.preview(input) + #expect(!foreignField.bindings.isEmpty) + #expect( + foreignField.resources.allSatisfy { $0.requiresBindingRewrite && $0.observedHash == nil }) + #expect(!String(reflecting: foreignField).contains("EXCLUDED_HEADER_SECRET")) + + try fixture.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"bundle","mcpServers":{"same":{"command":"winning-tool"}}}"#) + try fixture.write( + "bundle/.mcp.json", + #"{"mcpServers":{"same":{"command":"old-tool","env":{"CUSTOM":"REPLACED_SECRET"}}}}"#) + let bundleBefore = try fixture.hash() + let replaced = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(replaced.components.count == 1) + #expect(replaced.bindings.contains { $0.location.document == "bundle/.mcp.json" }) + #expect( + replaced.resources.contains { + $0.path == ".mcp.json" && $0.requiresBindingRewrite && $0.observedHash == nil + }) + #expect(!String(reflecting: replaced).contains("REPLACED_SECRET")) + #expect(try fixture.hash() == bundleBefore) + } + + @Test func rootRelativeExecutablesRemainResourcesAcrossNativeKinds() throws { + let fixture = try NativeImportFixture() + try fixture.write( + ".claude-plugin/plugin.json", + #"{"name":"bundle","mcpServers":{"mcp":{"command":"./server"}},"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"./server"}]}]}}"# + ) + try fixture.write( + ".lsp.json", #"{"lsp":{"command":"./server","extensionToLanguage":{".x":"x"}}}"#) + try fixture.write("server", "#!/bin/sh\nexit 0\n", executable: true) + let before = try fixture.hash() + let result = try SourceImport.preview( + fixture.input(.claudePluginV1, ".claude-plugin/plugin.json")) + var executables: [String] = [] + for item in result.components { + switch item.declaration { + case .mcpServer(_, .stdio(let run), _, _, _), .hook(_, _, let run, _, _, _, _, _), + .lspServer(_, let run, _, _, _, _, _): + executables.append(run.executable) + default: Issue.record("Unexpected member") + } + } + #expect(executables == ["./server", "./server", "./server"]) + #expect(result.resources.contains { $0.path == "server" && $0.executableFlags["."] == true }) + #expect(try fixture.hash() == before) + } + + @Test func lspBindingsKeepOriginalMapCoordinatesThroughPrecedence() throws { + let fixture = try NativeImportFixture() + try fixture.write("bundle/.claude-plugin/plugin.json", #"{"name":"bundle"}"#) + try fixture.write( + "bundle/.lsp.json", + """ + {"a":{"command":"a-lsp","extensionToLanguage":{".a":"a"},"env":{"CUSTOM":"LSP_A_SECRET"}}, + "b":{"command":"b-lsp","extensionToLanguage":{".b":"b"},"env":{"CUSTOM":"LSP_B_SECRET"}}} + """) + func keys(_ result: SourceImportProposal) -> [String] { + result.components.compactMap { + if case .lspServer(_, let run, _, _, _, _, _) = $0.declaration, + case .secret(let key) = run.environment["CUSTOM"] + { + return key + } + return nil + } + } + let original = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(Set(keys(original)).count == 2) + #expect(Set(original.components.map(\.origin.pointer)) == ["/member[0]", "/member[1]"]) + #expect(Set(original.components.compactMap { $0.origin.span?.line }) == [1, 2]) + try fixture.write( + "bundle/.claude-plugin/plugin.json", #"{"name":"bundle","lspServers":"./override.json"}"#) + try fixture.write( + "bundle/override.json", + #"{"a":{"command":"new-lsp","extensionToLanguage":{".a":"a"},"env":{"CUSTOM":"NEW_LSP_SECRET"}}}"# + ) + let replaced = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(Set(keys(replaced)).count == 2) + #expect(Set(replaced.bindings.compactMap(\.key)).count == 3) + #expect( + replaced.components.contains { + $0.origin.document == "bundle/.lsp.json" && $0.origin.pointer == "/member[1]" + }) + #expect( + replaced.components.contains { + $0.origin.document == "bundle/override.json" && $0.origin.pointer == "/member[0]" + && $0.origin.span != nil + }) + #expect( + replaced.resources.filter { $0.path == ".lsp.json" || $0.path == "override.json" }.allSatisfy + { $0.requiresBindingRewrite && $0.observedHash == nil }) + #expect(!String(reflecting: replaced).contains("LSP_B_SECRET")) + } + + @Test func openCodeExplicitOAuthDisableSurvivesTypedImport() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "opencode.jsonc", + #"{"mcp":{"servers":{"review":{"type":"remote","url":"https://example.test/mcp","oauth":false}}}}"# + ) + let result = try SourceImport.preview(fixture.input(.openCodeConfigV2, "opencode.jsonc")) + guard + case .mcpServer(_, .streamableHTTP, _, _, let native) = result.components.first?.declaration + else { + Issue.record("Expected remote MCP") + return + } + #expect(native[AgentID.opencode.rawValue]?["oauth"] == .boolean(false)) + #expect(result.diagnostics.isEmpty) + } + + @Test func nativeConfigurationMemberSelectionHonorsEmptyAndNarrowNames() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "opencode.jsonc", + #"{"commands":{"other":{"template":"Other"},"selected":{"template":"Selected"}},"agents":{"other":{"system":"Other","mode":"subagent"},"selected":{"system":"Selected","mode":"subagent"}}}"# + ) + try fixture.write( + "config.toml", + "[agents.other]\ndescription='Other'\nconfig_file='other.toml'\n[agents.selected]\ndescription='Selected'\nconfig_file='selected.toml'\n" + ) + try fixture.write("other.toml", "developer_instructions='Other'\n") + try fixture.write("selected.toml", "developer_instructions='Selected'\n") + let selections: [Set?] = [nil, [], ["selected"]] + for selection in selections { + var openCode = fixture.input(.openCodeConfigV2, "opencode.jsonc") + var codex = fixture.input(.codexConfigV1, "config.toml") + openCode.selection = selection + codex.selection = selection + let a = try SourceImport.preview(openCode) + let b = try SourceImport.preview(codex) + #expect(a.components.count == (selection == nil ? 4 : selection!.isEmpty ? 0 : 2)) + #expect(b.components.count == (selection == nil ? 2 : selection!.isEmpty ? 0 : 1)) + if selection == ["selected"] { + #expect( + a.components.compactMap { $0.member?.selector } == [ + .command(name: "selected"), .subagent(name: "selected"), + ]) + #expect(b.components.first?.member?.selector == .subagent(name: "selected")) + } + } + try FileManager.default.removeItem(at: fixture.root.appendingPathComponent("other.toml")) + var narrow = fixture.input(.codexConfigV1, "config.toml") + narrow.selection = ["selected"] + #expect(try SourceImport.preview(narrow).components.count == 1) + } + @Test func typedMembersStayStableWhenCallerMovesTheInputRoot() throws { let one = try NativeImportFixture() let two = try NativeImportFixture() From 3b2f8f68670e2e303319a978d57b1622220de1a6 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:09:10 +0800 Subject: [PATCH 098/171] fix: retain root authority and transaction terminal evidence --- Sources/AgentsCore/FileLock.swift | 11 +- Sources/AgentsCore/FileTransaction.swift | 27 +- .../AgentsCore/NativeTargetCoordination.swift | 57 +++- Sources/AgentsCore/StateStore.swift | 91 ++++-- Sources/AgentsCore/TransactionOutcome.swift | 24 +- Sources/AgentsCore/TransactionPaths.swift | 27 +- .../AgentsCore/TransactionPublication.swift | 2 +- Sources/AgentsCore/TransactionRecovery.swift | 104 +++--- Sources/AgentsCore/TransactionSession.swift | 7 +- Sources/AgentsCore/UpdatePreconditions.swift | 111 +++++++ Tests/AgentsCoreTests/PublicationTests.swift | 10 +- .../RegisteredNativeTargetTests.swift | 41 +++ .../StateTransactionTests.swift | 295 +++++++++++++++++- Tests/StateTestProcess/main.swift | 7 +- 14 files changed, 706 insertions(+), 108 deletions(-) diff --git a/Sources/AgentsCore/FileLock.swift b/Sources/AgentsCore/FileLock.swift index 8d09fac..5a57208 100644 --- a/Sources/AgentsCore/FileLock.swift +++ b/Sources/AgentsCore/FileLock.swift @@ -35,8 +35,17 @@ package enum FileLock { let parent = try DirectoryHandle(at: url.deletingLastPathComponent(), create: true) { try checkpoint(ancestryCheckpoint($0)) } + return try withDescriptor(in: parent, name: url.lastPathComponent, checkpoint: checkpoint, body) + } + + /// The caller pins and authorizes the existing parent; no absolute ancestry is created. + static func withDescriptor( + in parent: DirectoryHandle, name: String, checkpoint: (String) throws -> Void = { _ in }, + _ body: (Int32) throws -> T + ) throws -> T { + let url = parent.url.appendingPathComponent(name) let descriptor = openat( - parent.descriptor, url.lastPathComponent, O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC, + parent.descriptor, name, O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC, S_IRUSR | S_IWUSR) guard descriptor >= 0 else { throw FileSystem.posixError( diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 9fcdc03..9b542ac 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -36,6 +36,7 @@ package final class FileTransaction { private let checkpoint: (String) throws -> Void private let outcome: TransactionOutcome private var requests: [Request] = [] + private var skillInitialization: SkillInitializationTarget? private var receiptStates: [String: MaterializationReceiptState] = [:] private var receiptIndices: [Int: MaterializationReceiptState] = [:] private var unchanged: [any PreparedEvidence] = [] @@ -97,6 +98,20 @@ package final class FileTransaction { } } + /// Admits only this explicit, absent local authoring file to the ordinary journal. + package func initializeSkill(_ target: SkillInitializationTarget, bytes: Data) throws { + guard target.scope.path.utf8.elementsEqual(store.directory.path.utf8), + let context = TransactionLockContext.current(store), context.projectRootDirectory != nil + else { + throw CoreError.invalidState("skill initialization requires its observed existing parent") + } + try context.requireWriterScope() + try target.evidence.validate() + skillInitialization = target + defer { skillInitialization = nil } + try replace(target.file, with: .data(bytes), expecting: target.evidence) + } + package func delete(_ destination: URL, expecting: TargetPrecondition? = nil) throws { let (path, evidence, security) = try request(destination, expecting: expecting) requests.append( @@ -194,7 +209,8 @@ package final class FileTransaction { private func request(_ destination: URL, expecting: TargetPrecondition?) throws -> ( path: String, evidence: TargetPrecondition, security: TransactionSecurity ) { - let path = try TransactionPaths(store: store).path(for: destination) + let path = try TransactionPaths(store: store).path( + for: destination, skillInitialization: skillInitialization) guard path != "state/" + MaterializationReceipts.fileName else { throw CoreError.unsafePath("materialization receipts are transaction-owned") } @@ -317,15 +333,16 @@ package final class FileTransaction { try session.emit(.preconditions) try validateUnchanged() try session.validatePreimages() - outcome.disposition = .recoveryRequired + outcome.requireRecovery() for index in session.journal.entries.indices { try session.publish(index) } try validateUnchanged() try session.sealDisposal() try session.emit(.commitValidated) try session.finish(.committed) - outcome.disposition = .committed + outcome.recordTerminal(.committed) try session.emit(.phase(.committed)) try session.dispose() + outcome.recoveryPending = false } catch { // Recovery names its checkpoints under `recovery.`, apart from the failed commit's. do { @@ -333,7 +350,7 @@ package final class FileTransaction { try self.checkpoint("recovery." + $0) } } catch { - outcome.disposition = .recoveryRequired + outcome.requireRecovery() } throw error } @@ -422,7 +439,7 @@ package final class FileTransaction { let session = TransactionSession( journal: journal, directory: directory, parents: parents, checkpoint: checkpoint, resources: resources, - nativeRoots: try paths.nativeRootAuthorities(Set(journal.roots.keys))) + nativeRoots: try paths.nativeRootAuthorities(Set(journal.roots.keys)), outcome: outcome) try session.validateRecords(store: store) return session } diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index 8285a06..284c31b 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -417,12 +417,30 @@ package struct NativeTargetRoute: RawRepresentable, Hashable, Codable, Sendable let suffix = String(probe.basename.dropFirst("probe".count)) guard target.lastPathComponent.hasSuffix(suffix) else { continue } let authority = try probe.rootAuthority(environment, validateExistingOverride: false) - let prefix = authority.plannedPhysicalDirectory.path + "/" - let bytes = Array(target.path.utf8) - let relative = - bytes.starts(with: prefix.utf8) - ? String(decoding: bytes.dropFirst(prefix.utf8.count), as: UTF8.self) - : target.lastPathComponent + let container = authority.plannedPhysicalDirectory + var ancestor = target.deletingLastPathComponent() + var relativeParts = [target.lastPathComponent] + let containerIdentity = try? DirectoryHandle(at: container).objectIdentity + while ancestor.path != "/" { + if let containerIdentity, + let opened = try? DirectoryHandle(at: ancestor), + try opened.objectIdentity == containerIdentity + { + break + } + relativeParts.insert(ancestor.lastPathComponent, at: 0) + ancestor.deleteLastPathComponent() + } + let relative: String + if ancestor.path != "/" { + // Descriptor-equivalent container aliases retain the entire validated nested name. + relative = relativeParts.joined(separator: "/") + } else { + let prefix = container.path + "/" + let bytes = Array(target.path.utf8) + guard bytes.starts(with: prefix.utf8) else { continue } + relative = String(decoding: bytes.dropFirst(prefix.utf8.count), as: UTF8.self) + } let candidate = probe.isContainer ? try? named(member, scope: .user, name: relative) @@ -513,12 +531,21 @@ final class SharedResource { private var lockDescriptor: Int32? private var lockAccess: FileAccessEvidence? - init(store: StateStore, route: NativeTargetRoute = .claudeMCPLocal, create: Bool) throws { + init( + store: StateStore, route: NativeTargetRoute = .claudeMCPLocal, create: Bool, + existingRoot: ExistingProjectRoot? = nil, projectRoot: DirectoryHandle? = nil + ) throws { guard route.shared else { throw CoreError.invalidState("project route has no shared resource") } self.route = NativeTargetRoute.targetRoute(route.root)! authority = try route.rootAuthority(store.environment) let url = try authority.physicalDirectory() - parent = try DirectoryHandle(at: url, create: create) + if let existingRoot, let projectRoot, + let anchored = try existingRoot.descendant(at: url, from: projectRoot, create: create) + { + parent = anchored + } else { + parent = try DirectoryHandle(at: url, create: create) + } ancestry = try DirectoryAccessEvidence.capture(at: url) identity = SharedResourceIdentity(parent: try parent.objectIdentity, basename: route.basename) func child(_ parent: DirectoryHandle, _ name: String) throws -> DirectoryHandle? { @@ -720,6 +747,8 @@ final class TransactionLockContext { let writable: Bool let requestedShared: Bool let absentRoots: [AbsentSharedRoot] + var existingProjectRoot: ExistingProjectRoot? + var projectRootDirectory: DirectoryHandle? private var scopeDirectory: DirectoryHandle? private var scopeDescriptor: Int32? private var scopeLockIdentity: FileObjectIdentity? @@ -776,6 +805,7 @@ final class TransactionLockContext { } func validateScope() throws { + try existingProjectRoot?.validate() guard let directory = scopeDirectory else { return } var info = stat() guard let descriptor = scopeDescriptor, let identity = scopeLockIdentity, @@ -884,8 +914,11 @@ extension StateStore { /// Acquire the union before the scope lock. Re-admission never replays a delivered callback. func withCoordination( routes: Set, writable: Bool, - checkpoint: (String) throws -> Void = { _ in }, _ body: () throws -> T + checkpoint: (String) throws -> Void = { _ in }, + existingRoot: ExistingProjectRoot? = nil, projectRoot: DirectoryHandle? = nil, + _ body: () throws -> T ) throws -> T { + try existingRoot?.validate() if TransactionLockContext.isHeld { throw CoreError.invalidState("nested scope lock acquisition") } @@ -918,7 +951,9 @@ extension StateStore { } let resource: SharedResource do { - resource = try SharedResource(store: self, route: route, create: writable && !recovering) + resource = try SharedResource( + store: self, route: route, create: writable && !recovering, + existingRoot: existingRoot, projectRoot: projectRoot) } catch { if recovering { throw CoreError.invalidState( @@ -948,6 +983,8 @@ extension StateStore { store: self, resources: resources.sorted { $0.identity < $1.identity }, writable: writable, requestedShared: routes.contains(where: \.shared), absentRoots: absentRoots, admissions: admissions, requestedRoutes: routes) + context.existingProjectRoot = existingRoot + context.projectRootDirectory = projectRoot func locked(_ index: Int) throws -> T? { if index < context.resources.count { let resource = context.resources[index] diff --git a/Sources/AgentsCore/StateStore.swift b/Sources/AgentsCore/StateStore.swift index 1bd580d..f975512 100644 --- a/Sources/AgentsCore/StateStore.swift +++ b/Sources/AgentsCore/StateStore.swift @@ -82,9 +82,14 @@ public struct StateStore: Sendable { package func withLock( createIfMissing: Bool = true, checkpoint: @escaping (String) throws -> Void = { _ in }, outcome: TransactionOutcome? = nil, footprint: Set = [], + existingRoot: ExistingProjectRoot? = nil, _ body: () throws -> T ) throws -> T { - try withCoordination(routes: footprint, writable: true, checkpoint: checkpoint) { + let root = try existingRoot?.open(for: self) + return try withCoordination( + routes: footprint, writable: true, checkpoint: checkpoint, + existingRoot: existingRoot, projectRoot: root + ) { try withScopeLock( createIfMissing: createIfMissing, checkpoint: checkpoint, outcome: outcome, body) } @@ -113,42 +118,62 @@ public struct StateStore: Sendable { let base = scope == .project ? environment.projectDirectory : environment.homeDirectory let physicalDirectory = base.resolvingSymlinksInPath().appendingPathComponent( directory.lastPathComponent) - return try FileLock.withDescriptor( - at: physicalDirectory.appendingPathComponent(".agents.lock"), - checkpoint: { try checkpoint("scope." + $0) }, - { descriptor in - guard let context = TransactionLockContext.current(self), - let scopeDirectory = try openDirectoryIfPresent() - else { - throw CoreError.invalidState("missing scope lock admission") - } - try context.bindScope(scopeDirectory, descriptor: descriptor) - try verifyCoordinationAdmission() - let recovered = try FileTransaction.recover( - store: self, outcome: outcome, checkpoint: checkpoint) - _ = try readWatch() - let cache = SourceCache(store: self, checkpoint: checkpoint) - let referencesRecovered = try cache.recoverWatchReferences() - if recovered || referencesRecovered { - throw CoreError.transactionRecovered(directory.path) + func locked(_ body: (Int32) throws -> T) throws -> T { + if let context = TransactionLockContext.current(self), + let root = context.projectRootDirectory + { + try context.existingProjectRoot?.validate() + let name = directory.lastPathComponent + if try root.info(name) == nil { + try root.makeDirectory(name) { + try checkpoint("scope." + FileLock.ancestryCheckpoint(.created(depth: 0))) + } + try checkpoint("scope." + FileLock.ancestryCheckpoint(.synced(depth: 0))) } - let result: T + let parent = try root.child(name) + try context.existingProjectRoot?.validate() + return try FileLock.withDescriptor( + in: parent, name: ".agents.lock", checkpoint: { try checkpoint("scope." + $0) }, body) + } + return try FileLock.withDescriptor( + at: physicalDirectory.appendingPathComponent(".agents.lock"), + checkpoint: { try checkpoint("scope." + $0) }, body) + } + return try locked { descriptor in + guard let context = TransactionLockContext.current(self), + let scopeDirectory = try openDirectoryIfPresent() + else { + throw CoreError.invalidState("missing scope lock admission") + } + try context.bindScope(scopeDirectory, descriptor: descriptor) + try verifyCoordinationAdmission() + let recovered = try FileTransaction.recover( + store: self, outcome: outcome, checkpoint: checkpoint) + _ = try readWatch() + let cache = SourceCache(store: self, checkpoint: checkpoint) + let referencesRecovered = try cache.recoverWatchReferences() + if recovered || referencesRecovered { + throw CoreError.transactionRecovered(directory.path) + } + let result: T + do { + result = try body() + try context.validateScope() + } catch { + // A handled failure can finish rollback now. A killed process leaves the marker + // for the next access, which must recover the journal before releasing any ref. do { - result = try body() + _ = try FileTransaction.recover(store: self, outcome: outcome) + _ = try SourceCache(store: self).recoverWatchReferences() } catch { - // A handled failure can finish rollback now. A killed process leaves the marker - // for the next access, which must recover the journal before releasing any ref. - do { - _ = try FileTransaction.recover(store: self, outcome: outcome) - _ = try SourceCache(store: self).recoverWatchReferences() - } catch { - outcome?.disposition = .recoveryRequired - } - throw error + outcome?.requireRecovery() } - _ = try cache.recoverWatchReferences() - return result - }) + throw error + } + _ = try cache.recoverWatchReferences() + try context.validateScope() + return result + } } /// Only the supplied scope root may resolve through links; state and cache ancestry may not. diff --git a/Sources/AgentsCore/TransactionOutcome.swift b/Sources/AgentsCore/TransactionOutcome.swift index 08fe292..41e2ba2 100644 --- a/Sources/AgentsCore/TransactionOutcome.swift +++ b/Sources/AgentsCore/TransactionOutcome.swift @@ -3,10 +3,30 @@ import Foundation /// Tracks the generation established by its own journal, not preparatory cache publications. package final class TransactionOutcome { package enum Disposition { case unchanged, committed, recoveryRequired } - package var disposition: Disposition = .unchanged + private var reportedDisposition: Disposition = .unchanged + package var disposition: Disposition { + get { terminal == .committed ? .committed : reportedDisposition } + set { + reportedDisposition = newValue + if newValue == .recoveryRequired { recoveryPending = true } + } + } + package enum Terminal { case committed, rolledBack } + package private(set) var terminal: Terminal? + package var recoveryPending = false var journalID: UUID? + package var publicationStarted = false - package var publicationStarted: Bool { journalID != nil } + func recordTerminal(_ phase: TransactionJournal.Phase) { + guard phase == .committed || phase == .rolledBack else { return } + terminal = phase == .committed ? .committed : .rolledBack + disposition = phase == .committed ? .committed : .unchanged + } + + func requireRecovery() { + recoveryPending = true + if terminal == nil { disposition = .recoveryRequired } + } package init() {} } diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index 21e6ff4..5f25b8b 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -5,7 +5,9 @@ import Foundation struct TransactionPaths { let store: StateStore - func path(for destination: URL) throws -> String { + func path(for destination: URL, skillInitialization: SkillInitializationTarget? = nil) throws + -> String + { let base = store.scope == .project ? store.environment.projectDirectory : store.environment.homeDirectory let physicalState = base.resolvingSymlinksInPath().appendingPathComponent( @@ -41,6 +43,14 @@ struct TransactionPaths { } } try store.requireProjectNativeAuthority(at: destination) + if let initialization = skillInitialization, + initialization.scope.path.utf8.elementsEqual(store.directory.path.utf8), + initialization.file.path.utf8.elementsEqual(destination.standardizedFileURL.path.utf8) + { + let path = "skill-authoring/" + initialization.descendants.joined(separator: "/") + _ = try components(path) + return path + } if store.scope == .project { let relative = PathSafety.relativePath( destination.path, to: base.resolvingSymlinksInPath().path) @@ -97,7 +107,15 @@ struct TransactionPaths { _ key: String, create: Bool = false, checkpoint: (DirectoryHandle.AncestryStep) throws -> Void = { _ in } ) throws -> DirectoryHandle { - try DirectoryHandle(at: rootURL(key), create: create, checkpoint: checkpoint) + let url = try rootURL(key) + if let context = TransactionLockContext.current(store), let root = context.projectRootDirectory, + let observation = context.existingProjectRoot, + let anchored = try observation.descendant( + at: url, from: root, create: create, checkpoint: checkpoint) + { + return anchored + } + return try DirectoryHandle(at: url, create: create, checkpoint: checkpoint) } func rootURL(_ key: String) throws -> URL { @@ -126,6 +144,8 @@ struct TransactionPaths { throw CoreError.invalidState("shared metadata directory is missing") } url = metadata.url + } else if key == "skill-authoring", store.scope == .project { + url = store.environment.projectDirectory.resolvingSymlinksInPath() } else if key == "instructions-project" || key == "instructions-authoring", store.scope == .project { @@ -211,6 +231,9 @@ struct TransactionPaths { guard descendants == ["receipt"] else { throw CoreError.unsafePath("unregistered shared transaction metadata") } + } else if key == "skill-authoring", store.scope == .project { + guard (1...2).contains(descendants.count), descendants.last == "SKILL.md" + else { throw CoreError.unsafePath("invalid local skill authoring path") } } else if key == "instructions-project", store.scope == .project { guard InstructionLocations.isProjectTarget(descendants.joined(separator: "/")) else { throw CoreError.unsafePath("unmanaged project instruction path") diff --git a/Sources/AgentsCore/TransactionPublication.swift b/Sources/AgentsCore/TransactionPublication.swift index 76ead71..4380769 100644 --- a/Sources/AgentsCore/TransactionPublication.swift +++ b/Sources/AgentsCore/TransactionPublication.swift @@ -215,7 +215,7 @@ extension TransactionSession { try advance(index, to: .publishing) try requirePreimage(index) try emit(.publication(index, .validated)) - if entry.security.isPrivate { try requirePreimage(index) } + try requirePreimage(index) try grantDirectoryPermissions(index, layout: layout, purpose: .publicationGrant) if entry.action == .install { let exchange = entry.preimage != nil diff --git a/Sources/AgentsCore/TransactionRecovery.swift b/Sources/AgentsCore/TransactionRecovery.swift index 8d2d6b8..4aca362 100644 --- a/Sources/AgentsCore/TransactionRecovery.swift +++ b/Sources/AgentsCore/TransactionRecovery.swift @@ -13,6 +13,17 @@ extension FileTransaction { package static func recover( store: StateStore, outcome: TransactionOutcome? = nil, checkpoint: @escaping (String) throws -> Void = { _ in } + ) throws -> Bool { + do { + return try recoverJournal(store: store, outcome: outcome, checkpoint: checkpoint) + } catch { + outcome?.requireRecovery() + throw error + } + } + + private static func recoverJournal( + store: StateStore, outcome: TransactionOutcome?, checkpoint: @escaping (String) throws -> Void ) throws -> Bool { guard let directory = try store.openDirectoryIfPresent() else { return false } let primary = TransactionJournal.fileName @@ -25,9 +36,14 @@ extension FileTransaction { if journal.finalized { try validateRecoveryCoordination(journal, store: store, directory: directory) try directory.syncFile(incomplete) + if outcome?.journalID == journal.id { + outcome?.recordTerminal(journal.phase) + outcome?.recoveryPending = true + } try cleanupFinalized(journal, store: store, directory: directory, checkpoint: checkpoint) if outcome?.journalID == journal.id { - outcome?.disposition = journal.phase == .committed ? .committed : .unchanged + outcome?.recordTerminal(journal.phase) + outcome?.recoveryPending = false } return true } @@ -35,7 +51,10 @@ extension FileTransaction { try validateRecoveryCoordination(journal, store: store, directory: directory) try finalizeReservationConstruction( journal, store: store, directory: directory, checkpoint: checkpoint) - if outcome?.journalID == journal.id { outcome?.disposition = .unchanged } + if outcome?.journalID == journal.id { + outcome?.recordTerminal(.rolledBack) + outcome?.recoveryPending = false + } return true } } @@ -44,51 +63,56 @@ extension FileTransaction { try directory.remove(incomplete) return true } - var recoveredID: UUID? - do { - let journal = try readJournal(directory.read(primary)) - recoveredID = journal.id - try validateRecoveryCoordination(journal, store: store, directory: directory) - if journal.isReservationOnly { - try finalizeReservationConstruction( - journal, store: store, directory: directory, checkpoint: checkpoint) - if outcome?.journalID == journal.id { outcome?.disposition = .unchanged } - return true - } - if journal.finalized { - try directory.syncFile(primary) - try cleanupFinalized(journal, store: store, directory: directory, checkpoint: checkpoint) - if outcome?.journalID == journal.id { - outcome?.disposition = journal.phase == .committed ? .committed : .unchanged - } - return true - } - let session = try recoverySession( + let journal = try readJournal(directory.read(primary)) + try validateRecoveryCoordination(journal, store: store, directory: directory) + if journal.isReservationOnly { + try finalizeReservationConstruction( journal, store: store, directory: directory, checkpoint: checkpoint) - // Validate the incomplete next generation before any recovery mutation. - if try directory.info(incomplete) != nil { _ = try directory.read(incomplete) } - // Any observed journal may have been renamed without its directory barrier. Persist it - // before granting permissions, renaming objects or deleting any resource, including on retry. + if outcome?.journalID == journal.id { + outcome?.recordTerminal(.rolledBack) + outcome?.recoveryPending = false + } + return true + } + if journal.finalized { try directory.syncFile(primary) - try session.emit(.journalSynced) - if journal.phase == .applying { try session.rollback() } - if session.journal.phase == .applying || session.journal.phase == .preparing { - try session.sealDisposal() - try session.finish(.rolledBack) - try session.emit(.phase(.rolledBack)) + if outcome?.journalID == journal.id { + outcome?.recordTerminal(journal.phase) + outcome?.recoveryPending = true } - try session.revalidateDisposal() + try cleanupFinalized(journal, store: store, directory: directory, checkpoint: checkpoint) if outcome?.journalID == journal.id { - outcome?.disposition = session.journal.phase == .committed ? .committed : .unchanged + outcome?.recordTerminal(journal.phase) + outcome?.recoveryPending = false } return true - } catch { - // An unreadable journal cannot prove an unchanged or committed outcome. - if recoveredID == nil || outcome?.journalID == recoveredID { - outcome?.disposition = .recoveryRequired - } - throw error } + if outcome?.journalID == journal.id { + // Stabilize the observed terminal before reconstructing data that disposal may reject. + try directory.syncFile(primary) + outcome?.recordTerminal(journal.phase) + if journal.phase == .applying { outcome?.publicationStarted = true } + outcome?.recoveryPending = true + } + let session = try recoverySession( + journal, store: store, directory: directory, checkpoint: checkpoint) + // Validate the incomplete next generation before any recovery mutation. + if try directory.info(incomplete) != nil { _ = try directory.read(incomplete) } + // Any observed journal may have been renamed without its directory barrier. Persist it + // before granting permissions, renaming objects or deleting any resource, including on retry. + if outcome?.journalID != journal.id { try directory.syncFile(primary) } + try session.emit(.journalSynced) + if journal.phase == .applying { try session.rollback() } + if session.journal.phase == .applying || session.journal.phase == .preparing { + try session.sealDisposal() + try session.finish(.rolledBack) + if outcome?.journalID == journal.id { outcome?.recordTerminal(.rolledBack) } + try session.emit(.phase(.rolledBack)) + } + if outcome?.journalID == journal.id { outcome?.recordTerminal(session.journal.phase) } + try session.revalidateDisposal() + if outcome?.journalID == journal.id { outcome?.recoveryPending = false } + return true } package static func recoveryDiagnostic(store: StateStore) -> TransactionRecoveryDiagnostic { diff --git a/Sources/AgentsCore/TransactionSession.swift b/Sources/AgentsCore/TransactionSession.swift index 8cbfc90..3322ee5 100644 --- a/Sources/AgentsCore/TransactionSession.swift +++ b/Sources/AgentsCore/TransactionSession.swift @@ -7,6 +7,7 @@ final class TransactionSession { let parents: [DirectoryHandle] let checkpoint: (String) throws -> Void let resources: [SharedResource] + private let outcome: TransactionOutcome? /// Logical project-root authorization is checked separately from opened physical parents. private let nativeRoots: [String: NativeRootAuthority] /// Devices whose atomic renames passed a probe during this session only; `st_dev` values @@ -16,7 +17,7 @@ final class TransactionSession { init( journal: TransactionJournal, directory: DirectoryHandle, parents: [DirectoryHandle], checkpoint: @escaping (String) throws -> Void, resources: [SharedResource] = [], - nativeRoots: [String: NativeRootAuthority] = [:] + nativeRoots: [String: NativeRootAuthority] = [:], outcome: TransactionOutcome? = nil ) { self.journal = journal self.directory = directory @@ -24,6 +25,7 @@ final class TransactionSession { self.checkpoint = checkpoint self.resources = resources self.nativeRoots = nativeRoots + self.outcome = outcome } func emit(_ point: TransactionCheckpoint) throws { try checkpoint(point.name) } @@ -57,6 +59,7 @@ final class TransactionSession { journal.entries[index].progress = next journal.entries[index].conflict = nil try persist(.entry(index, next)) + if next == .publishing { outcome?.publicationStarted = true } try emit(.progress(index, next)) } @@ -87,7 +90,7 @@ final class TransactionSession { } func requireParent(_ index: Int) throws { - if !resources.isEmpty { try requireScope() } + try requireScope() if let route = NativeTargetRoute.targetRoute(journal.entries[index].path), !route.shared { guard let logical = nativeRoots[route.root], try DirectoryHandle(at: logical.physicalDirectory()).identity diff --git a/Sources/AgentsCore/UpdatePreconditions.swift b/Sources/AgentsCore/UpdatePreconditions.swift index 6314ffb..24b9c30 100644 --- a/Sources/AgentsCore/UpdatePreconditions.swift +++ b/Sources/AgentsCore/UpdatePreconditions.swift @@ -169,3 +169,114 @@ struct TargetAccessPrecondition: Equatable { } } } + +/// An existing selected project, captured without creating lock or state ancestry. +/// Passing this observation never grants authority outside registered transaction targets. +public struct ExistingProjectRoot: Sendable { + public let directory: URL + private let identity: FileObjectIdentity + + fileprivate init(directory: URL) throws { + self.directory = directory.standardizedFileURL + identity = try DirectoryHandle(at: directory.resolvingSymlinksInPath()).objectIdentity + } + + func validate() throws { + guard try DirectoryHandle(at: directory.resolvingSymlinksInPath()).objectIdentity == identity + else { throw CoreError.invalidState("selected project root changed") } + } + + /// Returns nil for a separately registered external loader; selected-root descendants + /// are opened from the pinned descriptor and never recreate the selected pathname. + func descendant( + at url: URL, from root: DirectoryHandle, create: Bool, + checkpoint: (DirectoryHandle.AncestryStep) throws -> Void = { _ in } + ) throws -> DirectoryHandle? { + try validate() + let prefix = Array(root.url.path.utf8) + let bytes = Array(url.path.utf8) + guard bytes == prefix || bytes.starts(with: prefix + [47]) else { return nil } + let relative = String( + decoding: bytes.dropFirst(min(prefix.count + 1, bytes.count)), as: UTF8.self) + let parts = relative.split(separator: "/").map(String.init) + var current = root + for (index, name) in parts.enumerated() { + if create { + let depth = parts.count - index - 1 + if try current.info(name) == nil { + try current.makeDirectory(name) { try checkpoint(.created(depth: depth)) } + try checkpoint(.synced(depth: depth)) + } else { + try current.sync() + } + } + current = try current.child(name) + try validate() + } + return current + } + + func open(for store: StateStore) throws -> DirectoryHandle { + guard store.scope == .project, + directory.path.utf8.elementsEqual( + store.environment.projectDirectory.standardizedFileURL.path.utf8) + else { throw CoreError.invalidState("project observation belongs to another scope") } + try validate() + let opened = try DirectoryHandle(at: directory.resolvingSymlinksInPath()) + guard try opened.objectIdentity == identity else { + throw CoreError.invalidState("selected project root changed during admission") + } + return opened + } +} + +extension StateStore { + public func captureExistingProjectRoot() throws -> ExistingProjectRoot { + guard scope == .project else { + throw CoreError.invalidState("existing project root requires project scope") + } + return try ExistingProjectRoot(directory: environment.projectDirectory) + } +} + +/// Exact, absent authoring file owned by one explicit local skill initialization. +package struct SkillInitializationTarget { + package let file: URL + let scope: URL + let descendants: [String] + let evidence: TargetPrecondition + + fileprivate init(store: StateStore, name: String?, selectedDirectory: String? = nil) throws { + guard store.scope == .project, + name == nil || (name == PathSafety.sanitizeName(name!) && !name!.contains("/")), + selectedDirectory.map({ + !$0.isEmpty && $0 != "." && $0 != ".." && !$0.contains("/") + && !$0.contains("\\") && !$0.contains("\0") + }) ?? true + else { throw CoreError.unsafePath("invalid local skill initialization target") } + scope = store.directory + descendants = ((selectedDirectory ?? name).map { [$0] } ?? []) + ["SKILL.md"] + file = descendants.reduce(store.environment.projectDirectory.resolvingSymlinksInPath()) { + $0.appendingPathComponent($1) + } + evidence = try TargetPrecondition(file) + guard evidence.snapshot == nil else { + throw CoreError.invalidSkill("skill file already exists") + } + } +} + +extension StateStore { + package func skillInitializationTarget(named name: String? = nil) throws + -> SkillInitializationTarget + { + try SkillInitializationTarget(store: self, name: name) + } + + /// Preserves an explicitly selected directory spelling below the observed existing parent. + package func skillInitializationTarget(inChildDirectory directory: String) throws + -> SkillInitializationTarget + { + try SkillInitializationTarget(store: self, name: nil, selectedDirectory: directory) + } +} diff --git a/Tests/AgentsCoreTests/PublicationTests.swift b/Tests/AgentsCoreTests/PublicationTests.swift index 1f8ad56..2c79f7e 100644 --- a/Tests/AgentsCoreTests/PublicationTests.swift +++ b/Tests/AgentsCoreTests/PublicationTests.swift @@ -801,7 +801,15 @@ final class PublicationFixture { guard case CoreError.invalidState(let reason) = error else { return false } return reason.contains(expected) } - #expect(outcome.disposition == .recoveryRequired) + let terminal = try #require(try lastJournal()).phase + #expect(outcome.recoveryPending) + if terminal == .committed { + #expect(outcome.disposition == .committed && outcome.terminal == .committed) + } else if terminal == .rolledBack { + #expect(outcome.disposition == .unchanged && outcome.terminal == .rolledBack) + } else { + #expect(outcome.disposition == .recoveryRequired && outcome.terminal == nil) + } let diagnostic = FileTransaction.recoveryDiagnostic(store: store) #expect(diagnostic.requiresOwner) #expect(diagnostic.message.contains("owner action")) diff --git a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift index 8d7fcfb..fc59f84 100644 --- a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift +++ b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift @@ -892,6 +892,47 @@ extension RegisteredNativeTargetTests { } } + @Test func nestedProjectAliasCannotBypassPrivateUserCommand() throws { + let fixture = try NativeRouteFixture() + let user = StateStore(scope: .user, environment: fixture.store.environment) + let userRoute = try NativeTargetRoute.named(.claudeCommand, scope: .user, name: "team/example") + var targetURL: URL! + var receiptURL: URL! + try user.withLock(footprint: [userRoute]) { + let target = try user.nativeTarget(for: userRoute) + targetURL = target.url + let transaction = FileTransaction(store: user) + try transaction.replacePrivate( + user.preparePrivateMaterialization(target), provider: NativeRouteBindings() + ) { + _ in Data("private user agent".utf8) + } + try transaction.commit() + receiptURL = try user.materializationReceipts(for: target.path).url + } + let receipt = try Data(contentsOf: receiptURL) + try FileManager.default.createSymbolicLink( + at: fixture.root.appendingPathComponent(".claude"), + withDestinationURL: user.environment.homeDirectory.appendingPathComponent(".claude")) + let projectRoute = try NativeTargetRoute.named( + .claudeCommand, scope: .project, name: "team/example") + #expect(throws: CoreError.self) { + try fixture.store.withLock(footprint: [projectRoute]) { + let target = try fixture.store.nativeTarget(for: projectRoute) + let transaction = FileTransaction(store: fixture.store) + try transaction.replace(target.url, with: .data(Data("ordinary project edit".utf8))) + try transaction.commit() + } + } + #expect(try Data(contentsOf: targetURL) == Data("private user agent".utf8)) + #expect(try Data(contentsOf: receiptURL) == receipt) + try user.withReadLock(footprint: [userRoute]) { + let target = try user.nativeTarget(for: userRoute) + let privateReceipt = try user.materializationReceipt(for: target) + #expect(privateReceipt != nil) + } + } + @Test(arguments: [InstallScope.project, .user]) func namedLoaderAliasRedirectStopsPublication(_ scope: InstallScope) throws { let fixture = try NativeRouteFixture() diff --git a/Tests/AgentsCoreTests/StateTransactionTests.swift b/Tests/AgentsCoreTests/StateTransactionTests.swift index e680dc3..fa147eb 100644 --- a/Tests/AgentsCoreTests/StateTransactionTests.swift +++ b/Tests/AgentsCoreTests/StateTransactionTests.swift @@ -145,6 +145,8 @@ final class TransactionFixture { deinit { removeTemporaryDirectory(root) } func commit(checkpoint: @escaping (String) throws -> Void) throws { try store.withLock { + var ledger = ResolvedLedger() + ledger.sources["local:/new"] = LedgerSource(kind: .local, revision: "live") let transaction = FileTransaction(store: store, checkpoint: checkpoint) try transaction.replace( root.appendingPathComponent(".agents/skills/target"), @@ -154,7 +156,7 @@ final class TransactionFixture { try transaction.replace( store.resolvedURL, with: .data( - StateStore.encode(ResolvedState(sources: ["local:/new": LockedSource(kind: .local)])))) + StateStore.encode(ledger))) try transaction.delete(root.appendingPathComponent(".agent/cache/artifact-content/pruned")) try transaction.replace( root.appendingPathComponent(".claude/skills/created"), @@ -175,7 +177,7 @@ final class TransactionFixture { contentsOf: root.appendingPathComponent(".agents/skills/target/SKILL.md"), encoding: .utf8) == (committed ? "new" : "target")) #expect(try store.loadDeclaration().agents == (committed ? [.codex] : nil)) - #expect(try store.loadResolved().sources.isEmpty == !committed) + #expect(try store.loadLedger().sources.isEmpty == !committed) #expect( FileManager.default.fileExists( atPath: root.appendingPathComponent(".claude/skills/created/SKILL.md").path) == committed) @@ -615,11 +617,9 @@ extension StateTransactionTests { } try transaction.replace( store.declarationURL, with: .data(manifestText("defaultAgents: [\"codex\"]\n"))) - try transaction.replace( - store.resolvedURL, - with: .data( - StateStore.encode( - ResolvedState(sources: ["local:/new": LockedSource(kind: .local)])))) + var ledger = ResolvedLedger() + ledger.sources["local:/new"] = LedgerSource(kind: .local, revision: "live") + try transaction.replace(store.resolvedURL, with: .data(StateStore.encode(ledger))) try transaction.commit() } } @@ -633,3 +633,284 @@ extension StateTransactionTests { #expect(try store.loadDeclaration().agents == nil) } } + +extension StateTransactionTests { + @Test(arguments: [false, true]) + func observedProjectCannotBeRecreatedOrReplacedBeforeAdmission(_ replace: Bool) throws { + let parent = try temporaryDirectory() + defer { removeTemporaryDirectory(parent) } + let project = parent.appendingPathComponent("project") + let moved = parent.appendingPathComponent("moved") + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: false) + let store = StateStore( + scope: .project, environment: RuntimeEnvironment(projectDirectory: project)) + let before = try FileSnapshot.read(at: parent) + let observed = try store.captureExistingProjectRoot() + #expect(try FileSnapshot.read(at: parent) == before) + try FileManager.default.moveItem(at: project, to: moved) + if replace { + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: false) + } + #expect(throws: (any Error).self) { + try store.withLock(existingRoot: observed) { Issue.record("stale root admitted") } + } + #expect(!FileManager.default.fileExists(atPath: project.appendingPathComponent(".agent").path)) + #expect(!FileManager.default.fileExists(atPath: moved.appendingPathComponent(".agent").path)) + #expect(FileManager.default.fileExists(atPath: project.path) == replace) + } + + @Test(arguments: [false, true]) + func observedProjectMovementStopsPublication(_ replace: Bool) throws { + let parent = try temporaryDirectory() + defer { removeTemporaryDirectory(parent) } + let project = parent.appendingPathComponent("project") + let moved = parent.appendingPathComponent("moved") + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: false) + let target = project.appendingPathComponent("AGENTS.md") + try Data("preimage".utf8).write(to: target) + let store = StateStore( + scope: .project, environment: RuntimeEnvironment(projectDirectory: project)) + let observed = try store.captureExistingProjectRoot() + let outcome = TransactionOutcome() + #expect(throws: (any Error).self) { + try store.withLock(outcome: outcome, existingRoot: observed) { + let transaction = FileTransaction(store: store, outcome: outcome) { point in + if point == TransactionCheckpoint.publication(0, .validated).name { + try FileManager.default.moveItem(at: project, to: moved) + if replace { + try FileManager.default.createDirectory( + at: project, withIntermediateDirectories: false) + } + } + } + try transaction.replace(target, with: .data(Data("replacement".utf8))) + try transaction.commit() + } + } + #expect( + try Data(contentsOf: moved.appendingPathComponent("AGENTS.md")) == Data("preimage".utf8)) + #expect( + !FileManager.default.fileExists(atPath: project.appendingPathComponent("AGENTS.md").path)) + #expect(FileManager.default.fileExists(atPath: project.path) == replace) + #expect(outcome.publicationStarted && outcome.recoveryPending) + #expect(outcome.disposition == .recoveryRequired) + if replace { try FileManager.default.removeItem(at: project) } + try FileManager.default.moveItem(at: moved, to: project) + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + #expect(try Data(contentsOf: target) == Data("preimage".utf8)) + } + + @Test(arguments: [false, true]) + func terminalEvidenceSurvivesFailedDisposalRecovery(_ committed: Bool) throws { + let fixture = try TransactionFixture() + let parent = fixture.root.appendingPathComponent(".agents/skills") + let displaced = fixture.root.appendingPathComponent("displaced-skills") + let outcome = TransactionOutcome() + let stop = + committed + ? TransactionCheckpoint.phase(.committed).name + : TransactionCheckpoint.progress(0, .applied).name + #expect(throws: CoreError.invalidState("interrupted transaction")) { + try fixture.store.withLock(outcome: outcome) { + let transaction = FileTransaction(store: fixture.store, outcome: outcome) { point in + if point == stop { + try FileManager.default.moveItem(at: parent, to: displaced) + throw CoreError.invalidState("interrupted transaction") + } + } + try transaction.replace( + parent.appendingPathComponent("target"), + with: .copy(fixture.root.appendingPathComponent("new"))) + try transaction.commit() + } + } + #expect(outcome.publicationStarted && outcome.recoveryPending) + #expect(outcome.disposition == (committed ? .committed : .recoveryRequired)) + #expect(outcome.terminal == (committed ? .committed : nil)) + #expect( + try Data(contentsOf: displaced.appendingPathComponent("target/SKILL.md")) == Data("new".utf8)) + #expect( + FileManager.default.fileExists( + atPath: fixture.store.directory.appendingPathComponent(TransactionJournal.fileName).path)) + let nextOperation = TransactionOutcome() + #expect(throws: (any Error).self) { + try fixture.store.withLock(outcome: nextOperation) { + Issue.record("pending recovery admitted a new operation") + } + } + #expect(!nextOperation.publicationStarted && nextOperation.terminal == nil) + #expect(nextOperation.disposition == .recoveryRequired && nextOperation.recoveryPending) + try FileManager.default.moveItem(at: displaced, to: parent) + #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { + try fixture.store.withLock(outcome: outcome) {} + } + #expect(outcome.terminal == (committed ? .committed : .rolledBack)) + #expect(!outcome.recoveryPending) + #expect( + try Data(contentsOf: parent.appendingPathComponent("target/SKILL.md")) + == Data((committed ? "new" : "target").utf8)) + } + + @Test func stagingRollbackDoesNotClaimPublication() throws { + let fixture = try TransactionFixture() + let outcome = TransactionOutcome() + try fixture.store.withLock(outcome: outcome) { + let transaction = FileTransaction(store: fixture.store, outcome: outcome) { point in + if point == TransactionCheckpoint.stage(0, .constructed).name { + throw CoreError.invalidState("stop staging") + } + } + try transaction.replace( + fixture.root.appendingPathComponent("AGENTS.md"), with: .data(Data("new".utf8))) + #expect(throws: CoreError.invalidState("stop staging")) { try transaction.commit() } + } + #expect(!outcome.publicationStarted && !outcome.recoveryPending) + #expect(outcome.terminal == .rolledBack && outcome.disposition == .unchanged) + #expect( + try Data(contentsOf: fixture.root.appendingPathComponent("AGENTS.md")) + == Data("old instructions".utf8)) + } +} + +extension StateTransactionTests { + @Test(arguments: [false, true]) + func localSkillInitializationUsesTheSameJournalAtAnExistingAnchor(_ named: Bool) throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) + let before = try FileSnapshot.read(at: root) + let observation = try store.captureExistingProjectRoot() + let target = try store.skillInitializationTarget(named: named ? "new-skill" : nil) + #expect(try FileSnapshot.read(at: root) == before) + let outcome = TransactionOutcome() + try store.withLock(outcome: outcome, existingRoot: observation) { + #expect(throws: CoreError.self) { + try FileTransaction(store: store).replace(target.file, with: .data(Data("unadmitted".utf8))) + } + let transaction = FileTransaction(store: store, outcome: outcome) + try transaction.initializeSkill(target, bytes: Data("skill template".utf8)) + try transaction.commit() + } + #expect(outcome.terminal == .committed && !outcome.recoveryPending) + #expect(try Data(contentsOf: target.file) == Data("skill template".utf8)) + #expect(throws: CoreError.self) { + try store.skillInitializationTarget(named: named ? "new-skill" : nil) + } + for name in ["../escape", ".", "a/b", "UPPER"] { + #expect(throws: CoreError.self) { try store.skillInitializationTarget(named: name) } + } + } + + @Test func localSkillInitializationRollbackRetainsTheRecordedAbsence() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) + let observed = try store.captureExistingProjectRoot() + let target = try store.skillInitializationTarget(named: "new-skill") + let outcome = TransactionOutcome() + try store.withLock(outcome: outcome, existingRoot: observed) { + let transaction = FileTransaction(store: store, outcome: outcome) { point in + if point == TransactionCheckpoint.publication(0, .created).name { + throw CoreError.invalidState("skill publication interrupted") + } + } + try transaction.initializeSkill(target, bytes: Data("template".utf8)) + #expect(throws: CoreError.invalidState("skill publication interrupted")) { + try transaction.commit() + } + } + #expect( + outcome.publicationStarted && outcome.terminal == .rolledBack && !outcome.recoveryPending) + #expect(!FileManager.default.fileExists(atPath: target.file.path)) + #expect( + !FileManager.default.fileExists( + atPath: store.directory.appendingPathComponent(TransactionJournal.fileName).path)) + } +} + +extension StateTransactionTests { + @Test func localSkillInitializationCannotFollowAChildLink() throws { + let parent = try temporaryDirectory() + defer { removeTemporaryDirectory(parent) } + let root = parent.appendingPathComponent("project") + let outside = parent.appendingPathComponent("outside") + for directory in [root, outside] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + } + try FileManager.default.createSymbolicLink( + at: root.appendingPathComponent("linked"), withDestinationURL: outside) + let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) + let observed = try store.captureExistingProjectRoot() + let target = try store.skillInitializationTarget(named: "linked") + #expect(throws: (any Error).self) { + try store.withLock(existingRoot: observed) { + let transaction = FileTransaction(store: store) + try transaction.initializeSkill(target, bytes: Data("template".utf8)) + try transaction.commit() + } + } + #expect( + !FileManager.default.fileExists(atPath: outside.appendingPathComponent("SKILL.md").path)) + } +} + +extension StateTransactionTests { + @Test func explicitlySelectedLocalDirectoryRetainsItsExactSpelling() throws { + let parent = try temporaryDirectory() + defer { removeTemporaryDirectory(parent) } + let store = StateStore( + scope: .project, environment: RuntimeEnvironment(projectDirectory: parent)) + let observed = try store.captureExistingProjectRoot() + let target = try store.skillInitializationTarget(inChildDirectory: "Selected Skill") + try store.withLock(existingRoot: observed) { + let transaction = FileTransaction(store: store) + try transaction.initializeSkill(target, bytes: Data("template".utf8)) + try transaction.commit() + } + #expect(target.file.deletingLastPathComponent().lastPathComponent == "Selected Skill") + #expect(try Data(contentsOf: target.file) == Data("template".utf8)) + for name in ["", ".", "..", "../outside", "a/b", "a\\b"] { + #expect(throws: CoreError.self) { + try store.skillInitializationTarget(inChildDirectory: name) + } + } + } +} + +extension StateTransactionTests { + @Test func durableRollbackTerminalSurvivesLossOfScopeReachability() throws { + let fixture = try TransactionFixture() + let moved = fixture.root.deletingLastPathComponent().appendingPathComponent( + fixture.root.lastPathComponent + "-moved") + defer { removeTemporaryDirectory(moved) } + let observed = try fixture.store.captureExistingProjectRoot() + let outcome = TransactionOutcome() + #expect(throws: CoreError.invalidState("stop publication")) { + try fixture.store.withLock(outcome: outcome, existingRoot: observed) { + let transaction = FileTransaction(store: fixture.store, outcome: outcome) { point in + if point == TransactionCheckpoint.publication(0, .exchanged).name { + throw CoreError.invalidState("stop publication") + } + if point == "recovery." + TransactionCheckpoint.phase(.rolledBack).name { + try FileManager.default.moveItem(at: fixture.root, to: moved) + throw CoreError.invalidState("scope moved after durable rollback") + } + } + try transaction.replace( + fixture.root.appendingPathComponent("AGENTS.md"), with: .data(Data("replacement".utf8))) + try transaction.commit() + } + } + #expect( + outcome.publicationStarted && outcome.terminal == .rolledBack && outcome.recoveryPending) + #expect( + try Data(contentsOf: moved.appendingPathComponent("AGENTS.md")) + == Data("old instructions".utf8)) + #expect(!FileManager.default.fileExists(atPath: fixture.root.path)) + try FileManager.default.moveItem(at: moved, to: fixture.root) + #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { + try fixture.store.withLock(outcome: outcome) {} + } + #expect(outcome.terminal == .rolledBack && !outcome.recoveryPending) + } +} diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index f5fae95..8d06651 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -393,10 +393,9 @@ if arguments[2].hasPrefix("ledger-") { .appendingPathComponent("target"), with: .copy(root.appendingPathComponent("new"))) try transaction.replace( store.declarationURL, with: .data(manifestText("defaultAgents: [\"codex\"]\n"))) - try transaction.replace( - store.resolvedURL, - with: .data( - StateStore.encode(ResolvedState(sources: ["local:/new": LockedSource(kind: .local)])))) + var ledger = ResolvedLedger() + ledger.sources["local:/new"] = LedgerSource(kind: .local, revision: "live") + try transaction.replace(store.resolvedURL, with: .data(StateStore.encode(ledger))) try transaction.delete(store.cacheDirectory.appendingPathComponent("artifact-content/pruned")) try transaction.replace( AgentRegistry.installSkillsDirectory( From 8a036c0d638ed9c4b3adab2859614d98a5d40e34 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:30:00 +0800 Subject: [PATCH 099/171] feat: compose native component updates and source imports --- Documentation/Architecture/Updates.md | 25 + Sources/AgentsManifest/YAMLPatches.swift | 13 +- .../AgentsUpdates/InstructionOperations.swift | 13 +- .../SourceImportOperations.swift | 24 +- Sources/AgentsUpdates/UpdatePlan.swift | 5 +- Sources/Components/ArtifactAggregation.swift | 855 +++++++++++++++--- .../Components/DeploymentConstruction.swift | 124 ++- Sources/Components/LedgerImpact.swift | 4 +- Sources/Components/LedgerReplay.swift | 33 +- .../IntegratedConsumerRegressionTests.swift | 114 +++ .../NativeCompositionIntegrationTests.swift | 334 +++++++ .../PublicInspectionTests.swift | 1 + .../UpdateTransactionTests.swift | 39 + 13 files changed, 1436 insertions(+), 148 deletions(-) create mode 100644 Tests/AgentsUpdatesTests/IntegratedConsumerRegressionTests.swift create mode 100644 Tests/AgentsUpdatesTests/NativeCompositionIntegrationTests.swift diff --git a/Documentation/Architecture/Updates.md b/Documentation/Architecture/Updates.md index 62e1e3e..cf48269 100644 --- a/Documentation/Architecture/Updates.md +++ b/Documentation/Architecture/Updates.md @@ -202,3 +202,28 @@ The existing writer revalidates both normalized source identity and the exact Gi commit or artifact digest map before retention and watch-state publication. A redirected alias or changed content requires refresh. Status and diff never deploy configuration. + +Concrete native contributions are decoded from their sealed F artifacts inside +replay's resource lifetime. Composition resolves D's closed routes and descriptor +physical identities before grouping logical owners. A shared document receives +one regional preparation, including protected MCP and native component siblings. +Reader and sensitivity evidence covers the physical object; selection controls +which runtime bindings may be requested. Ordinary changes preserve an unselected +private region using its verified receipt, without replaying its provider. + +Public prompt export renders locked sections in their recorded order and retains +producer append resources. A recorded consumer `localAppend` is read from its +current contained file only during export. Update, install and locked recovery do +not read that mutable consumer file. + +`SourceImportInspection.producerRevision` is optional. Documentation-backed native +profiles retain an unavailable upstream revision as `nil`; their +`specificationStatus` remains available. Import requests rebase producer-local +source coordinates into the captured declaration while retaining the proposal's +input freshness evidence and conversion/binding diagnostics. + +A consumer presenting authored YAML occurrences can use the captured document's +`node(at:)`, verify `editability(of:)`, and submit a typed `ManifestEdit` through +`UpdateRequest.operation.edit`, with `expectedDeclarationDigest`. This addresses +the selected authored node; it does not infer a producer child's ownership from a +recorded occurrence index. The node and expected digest reject stale reuse. diff --git a/Sources/AgentsManifest/YAMLPatches.swift b/Sources/AgentsManifest/YAMLPatches.swift index 3b40177..c8014ab 100644 --- a/Sources/AgentsManifest/YAMLPatches.swift +++ b/Sources/AgentsManifest/YAMLPatches.swift @@ -34,7 +34,9 @@ struct YAMLPatches { let shifted = raw.components(separatedBy: newline).map { line in line.hasPrefix(oldIndent) ? newIndent + line.dropFirst(oldIndent.count) : line }.joined(separator: newline) - insertion = insertion.map { SourcePatch(range: $0.range, replacement: Array(shifted.utf8)) } + insertion = insertion.map { + SourcePatch(range: $0.range, replacement: movedEntry(shifted, at: $0.range.lowerBound)) + } } else if !carried.isEmpty { let rendered = YAMLWriter.flow(value) let prefix = newline + carried.map { " " + $0 + newline }.joined() + " " @@ -88,7 +90,8 @@ struct YAMLPatches { } return [ SourcePatch(range: range, replacement: []), - SourcePatch(range: offset.. [UInt8] { + let prefix = offset > 0 && bytes[offset - 1] != 10 ? newline : "" + let suffix = offset < bytes.count && !text.hasSuffix(newline) ? newline : "" + return Array((prefix + text + suffix).utf8) + } + private func blockEntry(_ text: String, at offset: Int) -> [UInt8] { let prefix = offset > 0 && bytes[offset - 1] != 10 ? newline : "" let suffix = offset == bytes.count && bytes.last != 10 ? "" : newline diff --git a/Sources/AgentsUpdates/InstructionOperations.swift b/Sources/AgentsUpdates/InstructionOperations.swift index 59c5132..b890213 100644 --- a/Sources/AgentsUpdates/InstructionOperations.swift +++ b/Sources/AgentsUpdates/InstructionOperations.swift @@ -176,13 +176,14 @@ extension InstructionOperations { return try store.withReadLock { _ = try store.readDeclaration() let ledger = try store.readLedger() - return try LedgerReplay.withReplay( + guard let lowering = ledger.lowerings.first(where: { $0.id == "prompt:" + name }) else { + throw InstructionError.emptyPrompt + } + return try LedgerReplay.withLockedResources( ledger, store: store, roots: store.ledgerRoots, limits: .standard - ) { artifacts in - guard let bytes = artifacts.first(where: { $0.name == "prompt:" + name })?.bytes else { - throw InstructionError.emptyPrompt - } - return bytes + ) { _, resources, _ in + try LedgerReplay.exportPrompt( + lowering, ledger: ledger, resources: resources, roots: store.ledgerRoots) } } } diff --git a/Sources/AgentsUpdates/SourceImportOperations.swift b/Sources/AgentsUpdates/SourceImportOperations.swift index 46a8c73..f4e2d69 100644 --- a/Sources/AgentsUpdates/SourceImportOperations.swift +++ b/Sources/AgentsUpdates/SourceImportOperations.swift @@ -90,7 +90,7 @@ public struct ImportOrderedSourceInspection: Sendable { public struct SourceImportInspection: Sendable { public let format: String - public let producerRevision: String + public let producerRevision: String? public let specificationStatus: String public let sources: [ImportSourceInspection] public let components: [ImportComponentInspection] @@ -122,12 +122,26 @@ public struct SourceImportInspection: Sendable { "import requires verified captured content for the producer integrity claim") } for source in preparation.proposal.sources { - guard let imported = source.declaration else { + guard var imported = source.declaration else { throw CoreError.invalidState("import lacks exact canonical source coordinates") } - if let existing = declaration.sources[source.alias], existing != imported { - throw CoreError.invalidState( - "import source alias conflicts with the captured declaration: " + source.alias) + if imported.kind == .local { + let identity = try imported.identity( + environment: RuntimeEnvironment( + projectDirectory: preparation.input.root, homeDirectory: preparation.input.root, + environment: [:])) + imported.location = String(identity.dropFirst("local:".count)) + imported.environment = nil + } + if let existing = declaration.sources[source.alias] { + let oldIdentity = try existing.identity(environment: RuntimeEnvironment(environment: [:])) + let newIdentity = try imported.identity(environment: RuntimeEnvironment(environment: [:])) + guard existing.kind == imported.kind, existing.requirement == imported.requirement, + existing.path == imported.path, oldIdentity == newIdentity + else { + throw CoreError.invalidState( + "import source alias conflicts with the captured declaration: " + source.alias) + } } declaration.sources[source.alias] = imported } diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 1a6ffbd..64e0c07 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -156,7 +156,7 @@ final class UpdatePlan { #endif return try ComponentLinker.withLinkedComponents( document: document, store: store, platform: platform, - preserving: impact.pins, directPins: impact.directPins + preserving: impact.pins, directPins: impact.directPins, retaining: previous ) { linked, session in if let expected = request.automaticSkill { guard @@ -238,7 +238,8 @@ final class UpdatePlan { aggregation = try ArtifactAggregation( ledger: next, previous: previous, artifacts: artifacts, resources: resources, workspace: workspace, store: store, replace: request.replace, - changingAccess: request.changingAccess, kinds: request.kinds) + changingAccess: request.changingAccess, kinds: request.kinds, + names: Set(request.names), selectedIdentities: request.selectedIdentities) if let imported = request.importPreparation { for resource in imported.proposal.resources where resource.selected && resource.requiresStandaloneSource { diff --git a/Sources/Components/ArtifactAggregation.swift b/Sources/Components/ArtifactAggregation.swift index a724532..917ab1a 100644 --- a/Sources/Components/ArtifactAggregation.swift +++ b/Sources/Components/ArtifactAggregation.swift @@ -27,6 +27,9 @@ package final class ArtifactAggregation: PreparedEvidence { private let store: StateStore private let resources: [String: URL] private let replace: Bool + private let selectedKinds: Set? + private let selectedNames: Set + private let selectedIdentities: Set? private var unownedInstructions: [String] = [] private var unownedSkills: [String] = [] private var targets: [String: TargetPrecondition] = [:] @@ -37,17 +40,22 @@ package final class ArtifactAggregation: PreparedEvidence { private var privateWrites: [(PreparedPrivateMaterialization, Set, (RuntimeBindingValues) throws -> Data)] = [] private var resourceEvidence: [TargetPrecondition] = [] + private var physicalPaths: [NativeTargetIdentity: String] = [:] package init( ledger: ResolvedLedger, previous: ResolvedLedger, artifacts: [ReplayedArtifact], resources: [String: URL], workspace: URL, store: StateStore, replace: Bool, changingAccess: Bool, - kinds: Set? = nil + kinds: Set? = nil, names: Set = [], + selectedIdentities: Set? = nil ) throws { self.ledger = ledger self.store = store self.resources = resources self.replace = replace + selectedKinds = kinds + selectedNames = names + self.selectedIdentities = selectedIdentities for (id, file) in resources where ledger.resources[id]?.kind != .liveEdit { resourceEvidence.append(try TargetPrecondition(file)) } @@ -104,24 +112,73 @@ package final class ArtifactAggregation: PreparedEvidence { } var native: [String: [(LockedLowering, NativeMCPContribution, MaterializationTarget)]] = [:] for lowering in ledger.lowerings - where lowering.format.hasSuffix("-mcp@1") && (kinds == nil || kinds!.contains(.mcpServer)) { + where lowering.format.hasSuffix("-mcp@1") { let contribution = try MCPLayoutV1.contribution(lowering, ledger: ledger) - let route = try DeploymentConstruction.route(contribution) + let route = try DeploymentConstruction.physicalRoute( + DeploymentConstruction.route(contribution), ledger: previous, store: store) let target = try store.nativeTarget(for: route) - native[target.url.path, default: []].append((lowering, contribution, target)) + native[try physicalPath(route), default: []].append((lowering, contribution, target)) } // Removed native regions still participate in the same physical aggregation. for lowering in previous.lowerings - where lowering.format.hasSuffix("-mcp@1") && (kinds == nil || kinds!.contains(.mcpServer)) { + where lowering.format.hasSuffix("-mcp@1") { let c = try MCPLayoutV1.contribution(lowering, ledger: previous) - let target = try store.nativeTarget(for: DeploymentConstruction.route(c)) - if native[target.url.path] == nil { native[target.url.path] = [] } + let path = try physicalPath( + DeploymentConstruction.physicalRoute( + DeploymentConstruction.route(c), ledger: previous, store: store)) + if native[path] == nil { native[path] = [] } } - for path in native.keys.sorted() { - try prepareNative( - path: path, contributions: native[path]!, previous: previous, - changingAccess: changingAccess) - byPath.removeValue(forKey: path) + let currentComponents = try componentOutputs(ledger, artifacts: artifacts, routing: previous) + try LedgerReplay.withLockedResources(previous, store: store, roots: roots, limits: .standard) { + oldArtifacts, _, _ in + let oldComponents = try componentOutputs( + previous, + artifacts: Dictionary(uniqueKeysWithValues: oldArtifacts.map { ($0.name, $0) }), + routing: previous) + for path in Set(native.keys).union(currentComponents.keys).union(oldComponents.keys).sorted() + { + let next = currentComponents[path] ?? [] + let old = oldComponents[path] ?? [] + let entries = next + old + if let first = entries.first { + switch first.output.content { + case .file, .nativePlugin, .generatedLSPPlugin: + guard native[path] == nil else { + throw CoreError.invalidState("whole native object overlaps a shared document") + } + if try entries.contains(where: { + try isSelected( + $0.contribution.component, + in: ledger.components[$0.contribution.component] == nil ? previous : ledger) + }) { + try prepareWholeNative( + path: path, next: next, old: old, previous: previous, + artifacts: artifacts, workspace: workspace) + } else { + for entry in next { + try record( + entry, previous: previous, changed: false, + readers: entry.contribution.knownReaders, ownership: .generated) + } + } + case .ignore: + guard native[path] == nil else { + throw CoreError.invalidState("ignore block overlaps a structured document") + } + try prepareIgnore(path: path, next: next, old: old, previous: previous) + default: + try prepareNative( + path: path, contributions: native[path] ?? [], previous: previous, + changingAccess: changingAccess, components: next, oldComponents: old) + } + } else { + try prepareNative( + path: path, contributions: native[path] ?? [], previous: previous, + changingAccess: changingAccess) + } + native[path] = native[path] ?? [] + byPath.removeValue(forKey: path) + } } for path in Set(byPath.keys).union(previousByPath.keys).sorted() where native[path] == nil { let url = URL(fileURLWithPath: path) @@ -293,9 +350,327 @@ package final class ArtifactAggregation: PreparedEvidence { revision: source.revision) } + private func physicalPath(_ requested: NativeTargetRoute) throws -> String { + let route = try DeploymentConstruction.physicalRoute(requested, ledger: ledger, store: store) + let target = try store.nativeTarget(for: route) + guard let identity = try store.nativeTargetIdentity(for: route) else { return target.url.path } + if let path = physicalPaths[identity] { + if path != target.url.path { resourceEvidence.append(try TargetPrecondition(target.url)) } + return path + } + physicalPaths[identity] = target.url.path + return target.url.path + } + + private func isSelected(_ id: String, in selected: ResolvedLedger) throws -> Bool { + guard let c = selected.components[id] else { return false } + if let selectedIdentities { + return try selectedIdentities.contains( + LedgerImpact.identity(c, ledger: selected, roots: store.ledgerRoots)) + } + return (selectedKinds?.contains(DeclaredComponentKind(rawValue: c.kind)!) ?? true) + && (selectedNames.isEmpty + || selectedNames.contains(c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name)) + } + + private struct ComponentOutputEntry { + let lowering: LockedLowering + let contribution: NativeComponentContribution + let output: NativeComponentOutput + let target: MaterializationTarget + let index: Int + var id: String { lowering.id + ":" + String(index) } + } + + private func componentOutputs( + _ selected: ResolvedLedger, artifacts: [String: ReplayedArtifact], routing: ResolvedLedger + ) throws -> [String: [ComponentOutputEntry]] { + var result: [String: [ComponentOutputEntry]] = [:] + for lowering in selected.lowerings where lowering.format.hasSuffix("-components@1") { + let contribution = try NativeComponentLayoutsV1.contribution( + lowering, ledger: selected, + artifacts: try lowering.artifacts.map { digest in + guard let artifact = artifacts[digest.name] else { + throw CoreError.invalidState("missing sealed native output") + } + return artifact + }, limits: .standard) + for (index, output) in contribution.outputs.enumerated() { + let route = try DeploymentConstruction.physicalRoute( + DeploymentConstruction.route(output, request: contribution.request), + ledger: selected.deployments.contains(where: { $0.route.hasPrefix("agents/opencode-") }) + ? selected : routing, store: store) + let target = try store.nativeTarget(for: route) + result[try physicalPath(route), default: []].append( + .init( + lowering: lowering, contribution: contribution, + output: output, target: target, index: index)) + } + } + return result + } + + private func location(_ target: MaterializationTarget) -> LedgerLocation { + for (key, root) in [ + ("project", store.environment.projectDirectory), ("home", store.environment.homeDirectory), + ] { + let root = root.resolvingSymlinksInPath().standardizedFileURL + if PathSafety.isContained(target.url, in: root) { + return .init( + kind: .registered, root: key, + path: String(target.url.path.dropFirst(root.path.count + 1))) + } + } + return .init(kind: .absolute, path: target.url.path) + } + + private func record( + _ entry: ComponentOutputEntry, previous: ResolvedLedger, changed: Bool, + readers: [AgentID], privatePlan: PreparedPrivateMaterialization? = nil, + bindings: [String] = [], ownership: LedgerDeployment.Ownership = .ownedValues + ) throws { + let identity = try LedgerImpact.identity( + ledger.components[entry.contribution.component]!, ledger: ledger, roots: store.ledgerRoots) + let oldComponent = try previous.components.values.first { + try LedgerImpact.identity($0, ledger: previous, roots: store.ledgerRoots) == identity + } + let deployment = LedgerDeployment( + id: entry.id, target: location(entry.target), route: entry.lowering.format, + owners: [entry.contribution.component], recipients: entry.contribution.recipients, + ownership: ownership, expectedHash: entry.lowering.artifacts[0].hash, + created: previous.deployments.first { + $0.route == entry.lowering.format + && (try? $0.target.resolve(roots: store.ledgerRoots).path) == entry.target.url.path + }?.created ?? !FileManager.default.fileExists(atPath: entry.target.url.path)) + ledger.deployments.removeAll { $0.id == entry.id } + ledger.deployments.append(deployment) + if let i = ledger.lowerings.firstIndex(where: { $0.id == entry.lowering.id }) { + if !ledger.lowerings[i].deployments.contains(entry.id) { + ledger.lowerings[i].deployments.append(entry.id) + } + } + changes.append( + .init( + deployment: deployment, url: entry.target.url, before: nil, after: nil, + changed: changed, native: true, accessChange: privatePlan?.accessChange, + effectiveReaders: readers, + privateMaterialization: privatePlan != nil, requiredBindings: bindings, + symbolicBefore: oldComponent?.payload, + symbolicAfter: ledger.components[entry.contribution.component]?.payload)) + } + + private func componentValue( + _ value: NativeComponentValue, values: RuntimeBindingValues?, + selected: ResolvedLedger + ) throws -> NativeValue { + guard let values else { return try value.referenceValue(budget: nativeBudget()) } + let paths = try selected.resources.keys.reduce(into: [String: String]()) { + $0[$1] = try Self.resourceDestination($1, ledger: selected, store: store).path + } + return try value.stagedValue( + bindings: values, environment: store.environment, + resourcePaths: paths, + budget: NativeDocumentBudget( + limits: .init( + storage: LedgerLimits.standard.resourceBytes, + work: LedgerLimits.standard.encodedBytes, nodes: LedgerLimits.standard.nodes, + depth: LedgerLimits.standard.depth, uninterruptedBytes: LedgerLimits.standard.keyBytes)), + codexCommandShell: .posix, cursorCommandShell: .posix) + } + + private func prepareWholeNative( + path: String, next: [ComponentOutputEntry], old: [ComponentOutputEntry], + previous: ResolvedLedger, artifacts: [String: ReplayedArtifact], workspace: URL + ) throws { + guard let target = (next.first ?? old.first)?.target else { return } + let capture = try TargetPrecondition(target.url).capturingPublicationAccess() + targets[path] = capture + fingerprints.append(try capture.displayEvidence(includeContent: false)) + var physicalReaders = Set((next + old).flatMap { $0.contribution.knownReaders }) + for entry in next + old { + physicalReaders.formUnion( + try DeploymentConstruction.route(entry.output, request: entry.contribution.request) + .knownReaders) + } + let readers = physicalReaders.sorted { $0.rawValue < $1.rawValue } + guard next.count <= 1, old.count <= 1 else { + throw CoreError.invalidState("conflicting native whole-object owners") + } + func source(_ entry: ComponentOutputEntry) throws -> FileTransaction.Source { + switch entry.output.content { + case .file(_, let bytes): return .data(bytes) + case .nativePlugin(_, let resource, _): + guard let artifact = artifacts[entry.lowering.id + "/bundle"], let tree = artifact.tree, + ledger.resources[resource] != nil + else { throw CoreError.invalidState("missing frozen native container") } + return .copy(tree) + case .generatedLSPPlugin(_, let manifestPath, let manifest): + guard manifest.bindings.isEmpty else { + throw CoreError.invalidState( + "native private container materialization requires the Core tree construction interface" + ) + } + let tree = workspace.appendingPathComponent( + "native-tree-" + FileHash.sha256Hex(data: Data(entry.id.utf8))) + let file = try PathSafety.resolvedChild(base: tree, subpath: manifestPath) + try FileSystem.createDirectory(at: file.deletingLastPathComponent()) + let document = try NativeDocument( + bytes: Data("{}".utf8), format: .json, budget: nativeBudget()) + let observation = try document.read(.init(keys: []))! + let bytes = try document.prepare([ + .put( + region: .init(keys: []), expected: .owned(observation), + value: componentValue(manifest, values: nil, selected: ledger)) + ]).bytes + try bytes.write(to: file) + return .copy(tree) + default: throw CoreError.invalidState("native whole-object content has a regional shape") + } + } + let exists = FileManager.default.fileExists(atPath: path) + if exists { + guard let old = old.first, + let deployment = previous.deployments.first(where: { $0.id == old.id }) + else { + throw CoreError.invalidState("native target contains unmanaged content") + } + switch old.output.content { + case .file(_, let bytes): + guard try Data(contentsOf: target.url) == bytes else { + throw CoreError.invalidState("owned native file drifted") + } + case .nativePlugin(_, let resource, _): + let observed = try LedgerResources.capture(target.url, embed: false, limits: .standard) + guard observed.hash == previous.resources[resource]?.hash, + observed.entries.map(\.executable) + == previous.resources[resource]?.entries.map(\.executable) + else { throw CoreError.invalidState("owned native tree drifted") } + case .generatedLSPPlugin(_, let manifestPath, let manifest): + let captured = try LedgerResources.capture(target.url, embed: false, limits: .standard) + let expectedPaths = Set([ + manifestPath, (manifestPath as NSString).deletingLastPathComponent, + ]) + guard captured.entries.allSatisfy({ expectedPaths.contains($0.path) && !$0.executable }) + else { + throw CoreError.invalidState("generated native container has unmanaged members") + } + let current = try NativeDocument( + bytes: Data(contentsOf: target.url.appendingPathComponent(manifestPath)), format: .json, + budget: nativeBudget()) + guard + try current.read(.init(keys: []))?.value + == componentValue(manifest, values: nil, selected: previous), + deployment.ownership == .generated + else { throw CoreError.invalidState("owned generated native tree drifted") } + default: throw CoreError.invalidState("invalid whole-object ownership") + } + } + if let entry = next.first { + let desired = try source(entry) + let changed: Bool + switch desired { + case .data(let bytes): changed = try !exists || Data(contentsOf: target.url) != bytes + case .copy(let tree): + changed = try !exists || FileHash.folderHash(target.url) != FileHash.folderHash(tree) + default: throw CoreError.invalidState("invalid native whole-object source") + } + if changed { writes[path] = desired } + try record( + entry, previous: previous, changed: changed, readers: readers, ownership: .generated) + } else if let entry = old.first, + let deployment = previous.deployments.first(where: { $0.id == entry.id }) + { + if exists { deletes.insert(path) } + changes.append( + .init( + deployment: deployment, url: target.url, before: nil, after: nil, + changed: exists, native: true, effectiveReaders: readers, + symbolicBefore: previous.components[entry.contribution.component]?.payload)) + } + } + + private func prepareIgnore( + path: String, next: [ComponentOutputEntry], old: [ComponentOutputEntry], + previous: ResolvedLedger + ) throws { + let url = URL(fileURLWithPath: path) + let capture = try TargetPrecondition.readingFile(url) + targets[path] = try capture.evidence.capturingPublicationAccess() + fingerprints.append(try capture.evidence.displayEvidence(includeContent: false)) + let opening = "# >>> agents context ignore v1\n" + let closing = "# <<< agents context ignore v1\n" + func block(_ entries: [ComponentOutputEntry]) throws -> String { + let lines = try entries.flatMap { entry -> [String] in + guard case .ignore(let lines) = entry.output.content else { + throw CoreError.invalidState("incompatible ignore owners") + } + return lines + } + return entries.isEmpty ? "" : opening + lines.joined(separator: "\n") + "\n" + closing + } + let before = capture.bytes ?? Data() + guard let text = String(data: before, encoding: .utf8) else { + throw CoreError.invalidState("ignore document is not UTF8") + } + let starts = text.components(separatedBy: opening).count - 1 + let ends = text.components(separatedBy: closing).count - 1 + guard starts == ends, starts <= 1 else { + throw CoreError.invalidState("ambiguous managed ignore block") + } + let after: String + let desired = try block(next) + if let start = text.range(of: opening), let end = text.range(of: closing), + start.lowerBound < end.upperBound + { + let range = start.lowerBound.. + let symbolic: LedgerValue + let render: (RuntimeBindingValues?) throws -> NativeValue + } + private func prepareNative( path: String, contributions: [(LockedLowering, NativeMCPContribution, MaterializationTarget)], - previous: ResolvedLedger, changingAccess: Bool + previous: ResolvedLedger, changingAccess: Bool, + components: [ComponentOutputEntry] = [], oldComponents: [ComponentOutputEntry] = [] ) throws { let url = URL(fileURLWithPath: path) let capture = try TargetPrecondition.readingFile(url) @@ -304,158 +679,258 @@ package final class ArtifactAggregation: PreparedEvidence { let old = try previous.lowerings.filter { $0.format.hasSuffix("-mcp@1") }.compactMap { lowering -> NativeMCPContribution? in let c = try MCPLayoutV1.contribution(lowering, ledger: previous) - return try store.nativeTarget(for: DeploymentConstruction.route(c)).url.path == path ? c : nil + return try physicalPath( + DeploymentConstruction.physicalRoute( + DeploymentConstruction.route(c), ledger: previous, store: store)) == path ? c : nil } - guard let descriptor = contributions.first?.1.descriptor ?? old.first?.descriptor else { - return + let priorTarget = try old.first.map { + try store.nativeTarget( + for: DeploymentConstruction.physicalRoute( + DeploymentConstruction.route($0), ledger: previous, store: store)) } + guard + let target = contributions.first?.2 ?? components.first?.target ?? oldComponents.first?.target + ?? priorTarget + else { return } + let format = + components.first?.output.route.documentFormat ?? oldComponents.first?.output.route + .documentFormat + ?? contributions.first?.1.descriptor.documentFormat ?? old.first!.descriptor.documentFormat let document = try NativeDocument( - bytes: capture.bytes ?? Data((descriptor.documentFormat == .toml ? "" : "{}\n").utf8), - format: descriptor.documentFormat, - budget: NativeDocumentBudget( - limits: .init( - storage: LedgerLimits.standard.resourceBytes, work: LedgerLimits.standard.encodedBytes, - nodes: LedgerLimits.standard.nodes, depth: LedgerLimits.standard.depth, - uninterruptedBytes: LedgerLimits.standard.keyBytes))) - var desired: [String: NativeMCPContribution] = [:] - for (_, c, _) in contributions { - if let prior = desired[c.name], - prior.value != c.value || prior.bindings != c.bindings - || prior.resourcePlacements != c.resourcePlacements - { - throw CoreError.invalidState("conflicting native region contributions") + bytes: capture.bytes ?? Data((format == .toml ? "" : "{}\n").utf8), + format: format, budget: nativeBudget()) + func names(_ bindings: [NativeComponentBindingPlacement]) -> Set { + Set( + bindings.compactMap { + switch $0.binding { + case .environment(let n), .secret(let n): n + case .literal: nil + } + }) + } + func mcp(_ c: NativeMCPContribution, selected: ResolvedLedger) throws -> NativeRegionOwner? { + let region = try c.descriptor.region( + server: c.name, + nativeProjectKey: c.descriptor.request.scope == .local + ? try store.nativeTarget(for: .claudeMCPProject).url.deletingLastPathComponent().path + : nil) + let key = try ResolvedLedgerCodec.digest(c.descriptor.request.scope.rawValue + ":" + c.name) + if try !isSelected(c.component, in: selected) { + guard let observed = try document.read(region)?.value else { return nil } + return .init( + key: key, region: region, bindings: [], symbolic: c.value, render: { _ in observed }) } - desired[c.name] = c + let bindings = Set( + c.bindings.filter { !$0.reference }.compactMap { + switch $0.binding { + case .environment(let n), .secret(let n): n + case .literal: nil + } + }) + return .init( + key: key, region: region, bindings: bindings, symbolic: c.value, + render: { try self.nativeValue(c, values: $0, ledger: selected) }) } - let oldByName = Dictionary(old.map { ($0.name, $0) }, uniquingKeysWith: { first, _ in first }) - let names = Set(desired.keys).union(oldByName.keys).sorted() - let effectiveReaders = Array( - (old + contributions.map(\.1)).reduce(into: Set()) { - $0.formUnion($1.descriptor.knownReaders) + func regional(_ entry: ComponentOutputEntry, selected: ResolvedLedger) throws + -> [NativeRegionOwner] + { + func region( + _ keys: [String], symbolic: LedgerValue, + bindings: Set = [], render: @escaping (RuntimeBindingValues?) throws -> NativeValue + ) throws -> NativeRegionOwner { + .init( + key: try ResolvedLedgerCodec.digest(keys), region: .init(keys: keys), bindings: bindings, + symbolic: symbolic, render: render) + } + switch entry.output.content { + case .member(let member, let value): + if try !isSelected(entry.contribution.component, in: selected) { + guard let observed = try document.read(.init(keys: member.keys))?.value else { return [] } + return [ + try region( + member.keys, symbolic: selected.components[entry.contribution.component]!.payload, + render: { _ in observed }) + ] + } + return [ + try region( + member.keys, symbolic: selected.components[entry.contribution.component]!.payload, + bindings: names(value.bindings), + render: { try self.componentValue(value, values: $0, selected: selected) }) + ] + case .claudePermissions(let policy): + var values: [(String, NativeValue)] = [] + for (key, strings) in [("allow", policy.allow), ("ask", policy.ask), ("deny", policy.deny)] + { + if let strings { values.append((key, .array(strings.map(NativeValue.string)))) } + } + if let mode = policy.defaultMode { values.append(("defaultMode", .string(mode))) } + return try values.map { key, value in + try region( + ["permissions", key], + symbolic: selected.components[entry.contribution.component]!.payload, + render: { _ in value }) + } + case .hook, .orderedPermissions: + throw CoreError.invalidState( + "native occurrence publication requires durable occurrence ownership and append support" + ) + default: + throw CoreError.invalidState("whole native content cannot be prepared as a shared region") } - ).sorted { $0.rawValue < $1.rawValue } - let hasBindings = (old + contributions.map(\.1)).contains { - $0.bindings.contains { !$0.reference } } - let target: MaterializationTarget - if let provided = contributions.first?.2 { - target = provided - } else { - target = try store.nativeTarget(for: DeploymentConstruction.route(old[0])) + let desiredItems = + try contributions.compactMap { try mcp($0.1, selected: ledger) } + + components.flatMap { try regional($0, selected: ledger) } + let oldItems = + try old.compactMap { try mcp($0, selected: previous) } + + oldComponents.flatMap { try regional($0, selected: previous) } + func keyed(_ items: [NativeRegionOwner]) throws -> [String: NativeRegionOwner] { + var result: [String: NativeRegionOwner] = [:] + for item in items { + if let existing = result[item.key], try existing.render(nil) != item.render(nil) { + throw CoreError.invalidState("conflicting native physical region owners") + } + result[item.key] = item + } + return result } - let sensitive = try hasBindings || store.materializationReceipt(for: target) != nil + let desired = try keyed(desiredItems) + let prior = try keyed(oldItems) + let keys = Set(desired.keys).union(prior.keys).sorted() + func componentBindings(_ entries: [ComponentOutputEntry]) -> Bool { + entries.contains { entry in + switch entry.output.content { + case .member(_, let value): !value.bindings.isEmpty + case .hook(let hook): !hook.value.bindings.isEmpty + case .generatedLSPPlugin(_, _, let value): !value.bindings.isEmpty + default: false + } + } + } + let recordedOldBindings = + old.contains { $0.bindings.contains { !$0.reference } } || componentBindings(oldComponents) + let sensitiveBindings = + recordedOldBindings + || contributions.contains { $0.1.bindings.contains { !$0.reference } } + || componentBindings(components) + let sensitive = try sensitiveBindings || store.materializationReceipt(for: target) != nil let privatePlan = try sensitive ? store.preparePrivateMaterialization( target, changingAccess: changingAccess, - requiringReceiptForExistingTarget: old.contains { $0.bindings.contains { !$0.reference } }) - : nil + requiringReceiptForExistingTarget: recordedOldBindings) : nil var expected: [String: NativeExpectedRegion] = [:] - for name in names { - let region = try descriptor.region( - server: name, - nativeProjectKey: descriptor.request.scope == .local - ? try store.nativeTarget(for: .claudeMCPProject).url.deletingLastPathComponent().path - : nil) + for key in keys { + let region = (desired[key] ?? prior[key])!.region if let observation = try document.read(region) { - guard let prior = oldByName[name] else { + guard let old = prior[key] else { throw NativeDocumentError.ownershipMismatch(region) } + if old.bindings.isEmpty, try observation.value != old.render(nil) { throw NativeDocumentError.ownershipMismatch(region) } - if !prior.bindings.contains(where: { !$0.reference }) { - guard observation.value == (try nativeValue(prior, values: nil, ledger: previous)) else { - throw NativeDocumentError.ownershipMismatch(region) - } - } - expected[name] = .owned(observation) + expected[key] = .owned(observation) } else { - expected[name] = .absent + expected[key] = .absent } } func edits(_ values: RuntimeBindingValues?) throws -> [NativeRegionEdit] { - try names.map { name in - let region = try descriptor.region( - server: name, - nativeProjectKey: descriptor.request.scope == .local - ? try self.store.nativeTarget(for: .claudeMCPProject).url.deletingLastPathComponent() - .path : nil) - if let c = desired[name] { - return .put( - region: region, expected: expected[name]!, - value: try self.nativeValue(c, values: values, ledger: self.ledger)) + try keys.compactMap { key in + if let next = desired[key] { + return .put(region: next.region, expected: expected[key]!, value: try next.render(values)) } - return .remove(region: region, expected: expected[name]!) + if case .absent = expected[key] { return nil } + return .remove(region: prior[key]!.region, expected: expected[key]!) } } - // Symbolic placeholders never leave the private plan. A staged literal render consumes - // all regions together after Core has verified private staging and resolved bindings. let preview = try document.prepare(edits(nil)) - let changed = - preview.bytes - != (capture.bytes ?? Data((descriptor.documentFormat == .toml ? "" : "{}\n").utf8)) + let changed = preview.bytes != (capture.bytes ?? Data((format == .toml ? "" : "{}\n").utf8)) + let bindings = desiredItems.reduce(into: Set()) { $0.formUnion($1.bindings) } if let privatePlan { - let bindings = Set( - contributions.flatMap { - $0.1.bindings.filter { !$0.reference }.map { placement in - switch placement.binding { - case .environment(let n), .secret(let n): n - case .literal: "" - } - } - }) - privateWrites.append( - (privatePlan, bindings, { values in try document.prepare(edits(values)).bytes })) + privateWrites.append((privatePlan, bindings, { try document.prepare(edits($0)).bytes })) } else if changed { writes[path] = .data(preview.bytes) } + var readers = Set((old + contributions.map(\.1)).flatMap { $0.descriptor.knownReaders }) + readers.formUnion((components + oldComponents).flatMap { $0.contribution.knownReaders }) + for entry in components + oldComponents { + readers.formUnion( + try DeploymentConstruction.route(entry.output, request: entry.contribution.request) + .knownReaders) + } + let effectiveReaders = readers.sorted { $0.rawValue < $1.rawValue } for (lowering, contribution, _) in contributions { - let id = lowering.id let deployment = LedgerDeployment( - id: id, - target: .init( - kind: .registered, root: String(target.path.split(separator: "/")[0]), - path: url.lastPathComponent), - route: lowering.format, owners: [contribution.component], - recipients: contribution.recipients, - ownership: .ownedValues, expectedHash: try ResolvedLedgerCodec.digest(contribution.value), - created: previous.deployments.first(where: { $0.id == id })?.created + id: lowering.id, target: location(target), route: lowering.format, + owners: [contribution.component], recipients: contribution.recipients, + ownership: .ownedValues, + expectedHash: try ResolvedLedgerCodec.digest(contribution.value), + created: previous.deployments.first { $0.id == lowering.id }?.created ?? (capture.bytes == nil)) - ledger.deployments.removeAll { $0.id == id } + ledger.deployments.removeAll { $0.id == lowering.id } ledger.deployments.append(deployment) if let i = ledger.lowerings.firstIndex(where: { $0.id == lowering.id }) { - ledger.lowerings[i].deployments = [id] + ledger.lowerings[i].deployments = [lowering.id] } changes.append( .init( deployment: deployment, url: url, before: nil, after: nil, changed: changed || sensitive, native: true, accessChange: privatePlan?.accessChange, effectiveReaders: effectiveReaders, privateMaterialization: sensitive, - requiredBindings: contribution.bindings.filter { !$0.reference }.map { + requiredBindings: contribution.bindings.filter { !$0.reference }.compactMap { switch $0.binding { - case .environment(let name), .secret(let name): name - case .literal: "" + case .environment(let n), .secret(let n): n + case .literal: nil } - }.sorted(), symbolicBefore: oldByName[contribution.name]?.value, + }.sorted(), + symbolicBefore: old.first { $0.name == contribution.name }?.value, symbolicAfter: contribution.value)) } - for name in Set(oldByName.keys).subtracting(desired.keys).sorted() { - let old = oldByName[name]! - if let prior = previous.deployments.first(where: { - $0.ownership == .ownedValues && $0.owners.contains(old.component) - && (try? $0.target.resolve(roots: store.ledgerRoots).path) == path - }) { - let removed: Bool - if case .absent = expected[name] { removed = false } else { removed = true } - changes.append( - .init( - deployment: prior, url: url, before: nil, after: nil, changed: removed, - native: true, accessChange: privatePlan?.accessChange, - effectiveReaders: effectiveReaders, - privateMaterialization: sensitive, - symbolicBefore: old.value)) + for entry in components { + let ownBindings: [String] + if case .member(_, let value) = entry.output.content { + ownBindings = Array(names(value.bindings)).sorted() + } else { + ownBindings = [] + } + try record( + entry, previous: previous, changed: changed || sensitive, readers: effectiveReaders, + privatePlan: privatePlan, bindings: ownBindings) + } + for deployment in previous.deployments + where (try? deployment.target.resolve(roots: store.ledgerRoots).path) == path { + let oldOwners = try Set( + deployment.owners.map { + try LedgerImpact.identity( + previous.components[$0]!, ledger: previous, roots: store.ledgerRoots) + }) + let retained = try ledger.deployments.contains { next in + guard next.route == deployment.route, + (try? next.target.resolve(roots: store.ledgerRoots).path) == path + else { return false } + return try Set( + next.owners.map { + try LedgerImpact.identity( + ledger.components[$0]!, ledger: ledger, roots: store.ledgerRoots) + }) == oldOwners } + if retained { continue } + changes.append( + .init( + deployment: deployment, url: url, before: nil, after: nil, changed: changed, + native: true, accessChange: privatePlan?.accessChange, effectiveReaders: effectiveReaders, + privateMaterialization: sensitive, + symbolicBefore: previous.components[deployment.owners[0]]?.payload)) } } + private func nativeBudget() -> NativeDocumentBudget { + NativeDocumentBudget( + limits: .init( + storage: LedgerLimits.standard.resourceBytes, + work: LedgerLimits.standard.encodedBytes, nodes: LedgerLimits.standard.nodes, + depth: LedgerLimits.standard.depth, uninterruptedBytes: LedgerLimits.standard.keyBytes)) + } + private func nativeValue( _ contribution: NativeMCPContribution, values: RuntimeBindingValues?, ledger: ResolvedLedger ) throws -> NativeValue { @@ -583,13 +1058,28 @@ extension ArtifactAggregation { package static func nativeExposure( _ deployment: LedgerDeployment, ledger: ResolvedLedger, store: StateStore ) throws -> (readers: [AgentID]?, sensitive: Bool) { - guard deployment.ownership == .ownedValues else { return (nil, false) } + guard deployment.ownership == .ownedValues || deployment.route.hasSuffix("-components@1") else { + return (nil, false) + } let path = try deployment.target.resolve(roots: store.ledgerRoots).path + var identities = Set() + for route in try DeploymentConstruction.routes(ledger) { + let target = try store.nativeTarget(for: route) + if target.url.path == path, let identity = try store.nativeTargetIdentity(for: route) { + identities.insert(identity) + } + } + func matches(_ route: NativeTargetRoute, _ target: MaterializationTarget) throws -> Bool { + if target.url.path == path { return true } + return try store.nativeTargetIdentity(for: route).map(identities.contains) ?? false + } var readers = Set() var sensitive = false for lowering in ledger.lowerings where lowering.format.hasSuffix("-mcp@1") { let c = try MCPLayoutV1.contribution(lowering, ledger: ledger) - let target = try store.nativeTarget(for: DeploymentConstruction.route(c)) + let target = try store.nativeTarget( + for: DeploymentConstruction.physicalRoute( + DeploymentConstruction.route(c), ledger: ledger, store: store)) if target.url.path == path { readers.formUnion(c.descriptor.knownReaders) sensitive = @@ -597,6 +1087,28 @@ extension ArtifactAggregation { || store.materializationReceipt(for: target) != nil } } + func hasBinding(_ value: LedgerValue) -> Bool { + value.kind == .secret || value.kind == .environment + || (value.array ?? []).contains(where: hasBinding) + || (value.object?.values ?? [:].values).contains(where: hasBinding) + } + for lowering in ledger.lowerings where lowering.format.hasSuffix("-components@1") { + let input = try NativeComponentLayoutsV1.input(lowering, ledger: ledger, limits: .standard) + var selected = ledger + selected.lowerings = [lowering] + for route in try DeploymentConstruction.routes(selected) { + let target = try store.nativeTarget(for: route) + if try matches(route, target) { + readers.formUnion( + CapabilityRegistry.componentReaders( + input.request, kind: DeclaredComponentKind(rawValue: input.record.kind)!)) + readers.formUnion(route.knownReaders) + sensitive = + try sensitive || hasBinding(input.record.payload) + || store.materializationReceipt(for: target) != nil + } + } + } return (readers.isEmpty ? nil : readers.sorted { $0.rawValue < $1.rawValue }, sensitive) } @@ -628,7 +1140,9 @@ extension ArtifactAggregation { lowering.format.hasSuffix("-mcp@1") { let c = try MCPLayoutV1.contribution(lowering, ledger: ledger) - let target = try store.nativeTarget(for: DeploymentConstruction.route(c)) + let target = try store.nativeTarget( + for: DeploymentConstruction.physicalRoute( + DeploymentConstruction.route(c), ledger: ledger, store: store)) if try store.materializationReceipt(for: target) != nil { return ("current", nil) } if c.bindings.contains(where: { !$0.reference }) { return ( @@ -654,6 +1168,105 @@ extension ArtifactAggregation { return try observed.value == nativeValue(c, values: nil, ledger: ledger, store: store) ? ("current", nil) : ("drifted", "managed native region changed") } + if deployment.route.hasSuffix("-components@1"), + let lowering = ledger.lowerings.first(where: { $0.deployments.contains(deployment.id) }) + { + return try LedgerReplay.withLockedResources( + ledger, store: store, roots: store.ledgerRoots, limits: .standard + ) { + artifacts, _, _ in + let table = Dictionary(uniqueKeysWithValues: artifacts.map { ($0.name, $0) }) + let contribution = try NativeComponentLayoutsV1.contribution( + lowering, ledger: ledger, + artifacts: try lowering.artifacts.map { item in + guard let artifact = table[item.name] else { + throw CoreError.invalidState("missing sealed native output") + } + return artifact + }, limits: .standard) + guard + let index = contribution.outputs.indices.first(where: { + lowering.id + ":" + String($0) == deployment.id + }) + else { + throw CoreError.invalidState("missing native deployment output") + } + let output = contribution.outputs[index] + let target = try store.nativeTarget( + for: DeploymentConstruction.physicalRoute( + DeploymentConstruction.route(output, request: contribution.request), ledger: ledger, + store: store)) + if try store.materializationReceipt(for: target) != nil { return ("current", nil) } + let budget = NativeDocumentBudget( + limits: .init( + storage: LedgerLimits.standard.resourceBytes, + work: LedgerLimits.standard.encodedBytes, nodes: LedgerLimits.standard.nodes, + depth: LedgerLimits.standard.depth, uninterruptedBytes: LedgerLimits.standard.keyBytes + )) + let matches: Bool + switch output.content { + case .file(_, let bytes): matches = try Data(contentsOf: url) == bytes + case .member(let member, let value): + let document = try NativeDocument( + bytes: Data(contentsOf: url), format: output.route.documentFormat!, budget: budget) + matches = + try document.read(.init(keys: member.keys))?.value + == value.referenceValue(budget: budget) + case .claudePermissions(let policy): + let document = try NativeDocument( + bytes: Data(contentsOf: url), format: .json, budget: budget) + var expected: [(String, NativeValue)] = [] + for (key, strings) in [ + ("allow", policy.allow), ("ask", policy.ask), ("deny", policy.deny), + ] { + if let strings { expected.append((key, .array(strings.map(NativeValue.string)))) } + } + if let mode = policy.defaultMode { expected.append(("defaultMode", .string(mode))) } + matches = try expected.allSatisfy { + try document.read(.init(keys: ["permissions", $0.0]))?.value == $0.1 + } + case .nativePlugin(_, let resource, _): + let observed = try LedgerResources.capture(url, embed: false, limits: .standard) + matches = + observed.hash == ledger.resources[resource]?.hash + && observed.entries.map(\.executable) + == ledger.resources[resource]?.entries.map(\.executable) + case .ignore: + var patterns: [String] = [] + for candidate in ledger.lowerings where candidate.format.hasSuffix("-components@1") { + let other = try NativeComponentLayoutsV1.contribution( + candidate, ledger: ledger, + artifacts: try candidate.artifacts.map { item in + guard let artifact = table[item.name] else { + throw CoreError.invalidState("missing sealed native output") + } + return artifact + }, limits: .standard) + for output in other.outputs { + let target = try store.nativeTarget( + for: DeploymentConstruction.physicalRoute( + DeploymentConstruction.route(output, request: other.request), ledger: ledger, + store: store)) + if target.url.path == url.path, case .ignore(let lines) = output.content { + patterns += lines + } + } + } + let text = try String(contentsOf: url, encoding: .utf8) + let opening = "# >>> agents context ignore v1\n" + let closing = "# <<< agents context ignore v1\n" + matches = + text.components(separatedBy: opening).count == 2 + && text.components(separatedBy: closing).count == 2 + && text.contains(opening + patterns.joined(separator: "\n") + "\n" + closing) + case .generatedLSPPlugin, .hook, .orderedPermissions: + return ( + "unverified", "native ownership observation requires the integrated regional evidence" + ) + } + return matches ? ("current", nil) : ("drifted", "managed native contribution changed") + } + } let bytes = try FileSystem.read(at: url) let hash = deployment.ownership == .importBlock diff --git a/Sources/Components/DeploymentConstruction.swift b/Sources/Components/DeploymentConstruction.swift index 1ff1511..e444032 100644 --- a/Sources/Components/DeploymentConstruction.swift +++ b/Sources/Components/DeploymentConstruction.swift @@ -24,11 +24,116 @@ package enum DeploymentConstruction { var result = Set() for lowering in ledger.lowerings where lowering.format.hasSuffix("-mcp@1") { let contribution = try MCPLayoutV1.contribution(lowering, ledger: ledger) - result.insert(try route(contribution)) + let route = try route(contribution) + result.insert(route) + if contribution.descriptor.request.surface == .openCodeCLI { + result.insert( + contribution.descriptor.request.scope == .project + ? .openCodeMCPProjectJSONC : .openCodeMCPUserJSONC) + } + } + for lowering in ledger.lowerings where lowering.format.hasSuffix("-components@1") { + let input = try NativeComponentLayoutsV1.input(lowering, ledger: ledger, limits: .standard) + let scope = input.request.scope + let name = input.record.name + switch (input.request.surface, input.record.kind) { + case (.claudeCode, "command"): + result.insert(try .named(.claudeCommand, scope: scope, name: name)) + case (.claudeCode, "subagent"): + result.insert(try .named(.claudeAgent, scope: scope, name: name)) + case (.claudeCode, "lspServer"), (.claudeCode, "plugin"): + result.insert(try .named(.claudeSkillPlugin, scope: scope, name: name)) + case (.claudeCode, _): + result.insert(scope == .project ? .claudeSettingsProject : .claudeSettingsUser) + case (.codexCLI, "subagent"): + result.insert(try .named(.codexAgent, scope: scope, name: name)) + result.insert(scope == .project ? .codexMCPProject : .codexMCPUser) + case (.codexCLI, _): result.insert(scope == .project ? .codexHooksProject : .codexHooksUser) + case (.geminiCLI, "command"): + result.insert(try .named(.geminiCommand, scope: scope, name: name)) + case (.geminiCLI, "subagent"): + result.insert(try .named(.geminiAgent, scope: scope, name: name)) + case (.geminiCLI, "plugin"): + result.insert(try .named(.geminiExtension, scope: scope, name: name)) + case (.geminiCLI, "ignore"): result.insert(.geminiIgnoreProject) + case (.geminiCLI, _): result.insert(scope == .project ? .geminiMCPProject : .geminiMCPUser) + case (.cursorEditor, "command"): + result.insert(try .named(.cursorCommand, scope: scope, name: name)) + case (.cursorEditor, "subagent"): + result.insert(try .named(.cursorAgent, scope: scope, name: name)) + case (.cursorEditor, "plugin"): + result.insert(try .named(.cursorLocalPlugin, scope: scope, name: name)) + case (.cursorEditor, "ignore"): result.insert(.cursorIgnoreProject) + case (.cursorEditor, _): + result.insert(scope == .project ? .cursorHooksProject : .cursorHooksUser) + case (.openCodeCLI, _): + result.insert(scope == .project ? .openCodeMCPProjectJSON : .openCodeMCPUserJSON) + result.insert(scope == .project ? .openCodeMCPProjectJSONC : .openCodeMCPUserJSONC) + default: throw CoreError.invalidState("native surface has no integrated closed route") + } } return result } + package static func physicalRoute( + _ route: NativeTargetRoute, ledger: ResolvedLedger, store: StateStore + ) throws -> NativeTargetRoute { + let alternate: NativeTargetRoute + if route == .openCodeMCPProjectJSON { + alternate = .openCodeMCPProjectJSONC + } else if route == .openCodeMCPUserJSON { + alternate = .openCodeMCPUserJSONC + } else { + return route + } + let recorded = ledger.deployments.filter { $0.route.hasPrefix("agents/opencode-") } + let names = Set(recorded.map { ($0.target.path as NSString).lastPathComponent }) + if names.contains("opencode.jsonc"), !names.contains("opencode.json") { return alternate } + if names.contains("opencode.json"), !names.contains("opencode.jsonc") { return route } + let json = try store.nativeTarget(for: route) + let jsonc = try store.nativeTarget(for: alternate) + let hasJSON = FileManager.default.fileExists(atPath: json.url.path) + let hasJSONC = FileManager.default.fileExists(atPath: jsonc.url.path) + guard !(hasJSON && hasJSONC) else { + throw CoreError.invalidState( + "multiple OpenCode configuration files require an explicit native target decision") + } + return hasJSONC ? alternate : route + } + + package static func route(_ output: NativeComponentOutput, request: NativeComponentRequest) throws + -> NativeTargetRoute + { + let project = request.scope == .project + let path: String + switch output.content { + case .file(let name, _): path = name + case .generatedLSPPlugin(let directory, _, _), .nativePlugin(let directory, _, _): + path = directory + default: path = "" + } + switch output.route { + case .claudeCommand: return try .file(.claudeCommand, scope: request.scope, relativePath: path) + case .claudeAgent: return try .file(.claudeAgent, scope: request.scope, relativePath: path) + case .codexAgent: return try .file(.codexAgent, scope: request.scope, relativePath: path) + case .geminiCommand: return try .file(.geminiCommand, scope: request.scope, relativePath: path) + case .geminiAgent: return try .file(.geminiAgent, scope: request.scope, relativePath: path) + case .cursorCommand: return try .file(.cursorCommand, scope: request.scope, relativePath: path) + case .cursorAgent: return try .file(.cursorAgent, scope: request.scope, relativePath: path) + case .claudeSkillPlugin: return try .named(.claudeSkillPlugin, scope: request.scope, name: path) + case .cursorLocalPlugin: return try .named(.cursorLocalPlugin, scope: request.scope, name: path) + case .geminiExtension: return try .named(.geminiExtension, scope: request.scope, name: path) + case .claudeSettings: return project ? .claudeSettingsProject : .claudeSettingsUser + case .codexHooks: return project ? .codexHooksProject : .codexHooksUser + case .cursorHooks: return project ? .cursorHooksProject : .cursorHooksUser + case .geminiIgnore: return .geminiIgnoreProject + case .cursorIgnore: return .cursorIgnoreProject + case .geminiSettings: return project ? .geminiMCPProject : .geminiMCPUser + case .codexConfig: return project ? .codexMCPProject : .codexMCPUser + case .openCodeConfig: return project ? .openCodeMCPProjectJSON : .openCodeMCPUserJSON + } + } + package static func route(_ contribution: NativeMCPContribution) throws -> NativeTargetRoute { let project = contribution.descriptor.request.scope == .project switch contribution.descriptor.request.surface { @@ -56,14 +161,6 @@ package enum DeploymentConstruction { var ledger = frozen.ledger for component in linked.components { guard case .declaration = component.payload else { continue } - guard component.key.kind == .mcpServer else { - if !component.recipients.isEmpty { - throw CoreError.invalidState( - "\(component.key.kind.rawValue)/\(component.key.name): production adapter integration is pending" - ) - } - continue - } for agent in component.recipients.sorted(by: { $0.rawValue < $1.rawValue }) { let surface: NativeClientSurface switch agent { @@ -73,6 +170,15 @@ package enum DeploymentConstruction { case .geminiCLI: surface = .geminiCLI case .opencode: surface = .openCodeCLI } + if component.key.kind != .mcpServer { + ledger.lowerings.append( + try NativeComponentLowering.lower( + component, frozen: frozen, + request: .init(surface: surface, scope: scope), + id: "native:" + String(component.origins[0].occurrence) + ":" + agent.rawValue, + platform: platform)) + continue + } var contribution = try NativeMCPLowering.lower( component, frozen: frozen, request: .init(surface: surface, scope: scope == .user ? .user : .project)) diff --git a/Sources/Components/LedgerImpact.swift b/Sources/Components/LedgerImpact.swift index 366b816..b2a349f 100644 --- a/Sources/Components/LedgerImpact.swift +++ b/Sources/Components/LedgerImpact.swift @@ -77,7 +77,9 @@ package struct LedgerImpact { } var direct: [ComponentKey: SourceRevision] = [:] for c in ledger.components.values where !updating || !selected(c) { - guard c.group == nil, let revision = c.revision else { continue } + guard c.group == nil else { continue } + let artifact = c.resources.compactMap { ledger.resources[$0]?.artifact?.digest }.first + guard let revision = artifact ?? c.revision else { continue } direct[ ComponentKey( source: try ledger.sourceIdentity(c.declaringSource, roots: roots), root: c.root, diff --git a/Sources/Components/LedgerReplay.swift b/Sources/Components/LedgerReplay.swift index 200803b..25d8a11 100644 --- a/Sources/Components/LedgerReplay.swift +++ b/Sources/Components/LedgerReplay.swift @@ -77,6 +77,7 @@ package enum LedgerReplay { "agents/claude-import@1": { try forwarding($0, $1, $2, outputBytes: outputBytes) }, "agents/chatgpt@1": { try chatGPT($0, $1, $2, outputBytes: outputBytes) }, ].merging(MCPLayoutV1.renderers) { existing, _ in existing } + .merging(NativeComponentLayoutsV1.renderers(limits: .standard)) { existing, _ in existing } } package static func withReplay( @@ -304,9 +305,29 @@ package enum LedgerReplay { ] } + package static func exportPrompt( + _ lowering: LockedLowering, ledger: ResolvedLedger, resources: [String: URL], + roots: [String: URL] + ) throws -> Data { + let locations = try lowering.inputs.compactMap { + try ledger.components[$0]?.payload.object?["localAppend"].map { + try LedgerLocation(ledgerValue: $0) + } + } + let paths = try Set(locations.map { try $0.resolve(roots: roots) }) + guard paths.count <= 1 else { + throw CoreError.invalidState("prompt has conflicting consumer append locations") + } + let append = try locations.first.map { try $0.readContainedFile(roots: roots) } + return try chatGPT( + lowering, ledger, resources, outputBytes: LedgerLimits.standard.resourceBytes, + consumerAppend: append + ).first!.bytes! + } + private static func chatGPT( _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL], - outputBytes: Int + outputBytes: Int, consumerAppend: Data? = nil ) throws -> [ReplayedArtifact] { guard let count = lowering.layout.object?["sectionCount"]?.integer, count > 0, count <= lowering.resources.count, lowering.resources.count <= count + 1, @@ -316,10 +337,18 @@ package enum LedgerReplay { guard let file = resources[id] else { throw CoreError.invalidState("missing prompt section") } return try FileSystem.read(at: file) } - let append = try lowering.resources.dropFirst(count).first.map { id in + var append = try lowering.resources.dropFirst(count).first.map { id in guard let file = resources[id] else { throw CoreError.invalidState("missing prompt append") } return try FileSystem.read(at: file) } + if let consumerAppend, !consumerAppend.isEmpty { + if append?.isEmpty == false { + append!.append(Data("\n".utf8)) + append!.append(consumerAppend) + } else { + append = consumerAppend + } + } return [ .init( name: name, kind: .file, diff --git a/Tests/AgentsUpdatesTests/IntegratedConsumerRegressionTests.swift b/Tests/AgentsUpdatesTests/IntegratedConsumerRegressionTests.swift new file mode 100644 index 0000000..e153bcf --- /dev/null +++ b/Tests/AgentsUpdatesTests/IntegratedConsumerRegressionTests.swift @@ -0,0 +1,114 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +struct IntegratedConsumerRegressionTests { + @Test func preciseRootMCPRemovalPreservesUnrelatedYAML() throws { + let f = try UpdateFixture() + try f.write( + """ + # Keep this declaration comment. + version: 1 + components: + - kind: mcpServer + name: first + transport: {kind: stdio, executable: never-run} + agents: [claude-code] + # Keep the remaining component comment. + - kind: mcpServer + name: second + transport: {kind: stdio, executable: never-run} + agents: [claude-code] + """, to: f.store.declarationURL) + _ = try f.apply() + let inspected = try UpdateOperations.inspect(environment: f.environment) + let selected = try #require(inspected.components.first { $0.name == "first" }) + let request = UpdateRequest(operation: .remove, selections: [selected.selection]) + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let after = try UpdateOperations.inspect(environment: f.environment) + #expect(after.components.map(\.name) == ["second"]) + let text = try String(contentsOf: f.store.declarationURL, encoding: .utf8) + #expect(text.contains("# Keep this declaration comment.")) + #expect(text.contains("# Keep the remaining component comment.")) + } + + @Test func publicPromptUsesCurrentConsumerAppendAndLockedSectionOrder() throws { + let f = try UpdateFixture() + try f.declare(agents: [.claudeCode]) + var declaration = try f.store.loadDeclaration() + for index in declaration.components.indices { + if case .instructions(var selection) = declaration.components[index] { + selection.prompts[0].prompt.append = "append.md" + declaration.components[index] = .instructions(selection) + } + } + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() // An absent consumer file must not prevent publication. + try f.write("First appendix", to: f.root.appendingPathComponent("append.md")) + let first = try InstructionOperations.renderChatGPT( + prompt: "weekly", environment: f.environment) + try f.write("Current appendix", to: f.root.appendingPathComponent("append.md")) + let before = try FileHash.folderHash(f.root) + let current = try InstructionOperations.renderChatGPT( + prompt: "weekly", environment: f.environment) + #expect(String(decoding: first, as: UTF8.self).contains("First appendix")) + #expect(String(decoding: current, as: UTF8.self).contains("Current appendix")) + #expect(!String(decoding: current, as: UTF8.self).contains("First appendix")) + #expect(try FileHash.folderHash(f.root) == before) + } +} + +extension IntegratedConsumerRegressionTests { + @Test func documentedNativeImportKeepsUnavailableUpstreamRevisionNil() throws { + let f = try UpdateFixture() + let input = f.root.appendingPathComponent("native-input") + try f.write("{}", to: input.appendingPathComponent("settings.json")) + let before = try FileHash.folderHash(f.root) + let report = try SourceImportOperations.inspect( + format: "claudeSettingsV1", root: input, document: "settings.json") + #expect(report.producerRevision == nil) + #expect(report.specificationStatus.contains("Documented Claude Code format")) + #expect(try FileHash.folderHash(f.root) == before) + } +} + +extension IntegratedConsumerRegressionTests { + @Test func authoredNodeRemovalSelectsOneDirectOccurrenceAndRejectsReuse() throws { + let f = try UpdateFixture() + try f.write( + """ + # Keep authored occurrence order. + version: 1 + components: + - {kind: mcpServer, name: repeated, transport: {kind: stdio, executable: first}, agents: [claude-code]} + - {kind: mcpServer, name: repeated, transport: {kind: stdio, executable: second}, agents: [gemini-cli]} + """, to: f.store.declarationURL) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + let document = try #require(snapshot.document) + let node = try #require(document.node(at: "/components/1")) + #expect(document.editability(of: node) == .direct) + let request = UpdateRequest( + operation: .edit([.removeComponent(node)]), expectedDeclarationDigest: document.digest) + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let remaining = try UpdateOperations.inspect(environment: f.environment) + #expect(remaining.components.count == 1) + #expect(remaining.components[0].recipients == [.claudeCode]) + #expect( + try String(contentsOf: f.store.declarationURL, encoding: .utf8).contains( + "# Keep authored occurrence order.")) + #expect(throws: (any Error).self) { + try UpdateOperations.preview(request, environment: f.environment) + } + } +} diff --git a/Tests/AgentsUpdatesTests/NativeCompositionIntegrationTests.swift b/Tests/AgentsUpdatesTests/NativeCompositionIntegrationTests.swift new file mode 100644 index 0000000..5176dbe --- /dev/null +++ b/Tests/AgentsUpdatesTests/NativeCompositionIntegrationTests.swift @@ -0,0 +1,334 @@ +import AgentsCore +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +struct NativeCompositionIntegrationTests { + @Test(arguments: [AgentID.claudeCode, .geminiCLI, .cursor, .opencode]) + func concreteCommandLifecycleUsesPublicOperations(_ agent: AgentID) throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .command( + name: "review", description: agent == .cursor ? "" : "Review sources", + prompt: .literal("Review exact sources."), agents: [agent]) + ]), ledger: ResolvedLedger()) + let before = try FileHash.folderHash(f.root) + let preview = try f.preview() + #expect(preview.components.first?.kind == "command") + #expect(try FileHash.folderHash(f.root) == before) + _ = try UpdateOperations.withPreparedUpdate(environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let inspection = try UpdateOperations.inspect(environment: f.environment) + let deployment = try #require(inspection.deployments.first) + #expect(deployment.status == .current) + let bytes = try Data(contentsOf: deployment.location) + #expect(String(decoding: bytes, as: UTF8.self).contains("Review exact sources.")) + try FileManager.default.removeItem(at: deployment.location) + _ = try UpdateOperations.restore(environment: f.environment) + #expect(try Data(contentsOf: deployment.location) == bytes) + let current = try UpdateOperations.inspect(environment: f.environment) + let selection = try #require(current.components.first?.selection) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [selection]), environment: f.environment + ) { try $0.apply() } + #expect(try UpdateOperations.inspect(environment: f.environment).components.isEmpty) + } + + @Test func codexRoleAndMCPShareOnePhysicalDocumentWithoutLosingSiblings() throws { + let f = try UpdateFixture() + let config = f.root.appendingPathComponent(".codex/config.toml") + try f.write("# Preserve this native setting.\ntheme = 'fixture'\n", to: config) + try f.store.save( + declaration: Declaration(components: [ + .subagent( + name: "researcher", description: "Research sources", prompt: .literal("Read sources."), + agents: [.codex]), + .mcpServer(name: "db", transport: .stdio(.init(executable: "never-run")), agents: [.codex]), + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let contents = try String(contentsOf: config, encoding: .utf8) + #expect(contents.hasPrefix("# Preserve this native setting.\ntheme = 'fixture'\n")) + #expect(contents.contains("researcher")) + #expect(contents.contains("db")) + let inspection = try UpdateOperations.inspect(environment: f.environment) + #expect(inspection.deployments.filter { $0.location == config }.count == 2) + let role = try #require(inspection.components.first { $0.kind == .subagent }) + let request = UpdateRequest(operation: .remove, selections: [role.selection]) + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let after = try String(contentsOf: config, encoding: .utf8) + #expect(after.contains("theme = 'fixture'")) + #expect(after.contains("db")) + #expect(!after.contains("researcher")) + #expect( + !FileManager.default.fileExists( + atPath: f.root.appendingPathComponent(".codex/agents/researcher.toml").path)) + } + + @Test func nativePermissionCategoriesPreserveUnselectedCategoriesAndSettings() throws { + let f = try UpdateFixture() + let settings = f.root.appendingPathComponent(".claude/settings.json") + try f.write("{\"telemetry\":false,\"permissions\":{\"deny\":[\"Bash(rm *)\"]}}", to: settings) + try f.store.save( + declaration: Declaration(components: [ + .permissions( + name: "read", rules: [], agents: [.claudeCode], + native: ["claude-code": ["allow": .array([.string("Read")])]]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let value = try JSONSerialization.jsonObject(with: Data(contentsOf: settings)) as? [String: Any] + #expect(value?["telemetry"] as? Bool == false) + #expect((value?["permissions"] as? [String: Any])?["deny"] as? [String] == ["Bash(rm *)"]) + let inspected = try UpdateOperations.inspect(environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(inspected.components.first?.selection)]), + environment: f.environment + ) { try $0.apply() } + let after = try JSONSerialization.jsonObject(with: Data(contentsOf: settings)) as? [String: Any] + #expect((after?["permissions"] as? [String: Any])?["allow"] == nil) + #expect((after?["permissions"] as? [String: Any])?["deny"] as? [String] == ["Bash(rm *)"]) + } + + @Test(arguments: [AgentID.geminiCLI, .cursor]) + func ignoreBlockPreservesUnmanagedPatternsThroughRemoval(_ agent: AgentID) throws { + let f = try UpdateFixture() + let file = f.root.appendingPathComponent(agent == .cursor ? ".cursorignore" : ".geminiignore") + let custom = "# Preserve user patterns.\nuser-local\n" + try f.write(custom, to: file) + try f.store.save( + declaration: Declaration(components: [ + .ignore(name: "generated", patterns: ["build", "!build/keep"], agents: [agent]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + #expect(try String(contentsOf: file, encoding: .utf8).hasPrefix(custom)) + let current = try UpdateOperations.inspect(environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(current.components.first?.selection)]), + environment: f.environment + ) { try $0.apply() } + #expect(try String(contentsOf: file, encoding: .utf8) == custom) + } +} + +extension NativeCompositionIntegrationTests { + @Test func opaqueNativePluginRetainsItsWholeFrozenTreeAndExecutionBits() throws { + let f = try UpdateFixture() + let source = f.root.appendingPathComponent("plugin-source") + let tree = source.appendingPathComponent("plugins/demo-plugin") + try f.write( + "{\"name\":\"demo-plugin\",\"version\":\"1.0.0\"}", + to: tree.appendingPathComponent(".claude-plugin/plugin.json")) + try f.write("#!/bin/sh\n# Never executed.\n", to: tree.appendingPathComponent("scripts/check")) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: tree.appendingPathComponent("scripts/check").path) + try f.store.save( + declaration: Declaration( + sources: ["producer": .init(kind: .local, location: source.path)], + components: [ + .plugin( + name: "demo-plugin", path: "plugins/demo-plugin", source: "producer", mode: .native, + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + let deployment = try #require(snapshot.deployments.first) + #expect(deployment.status == .current) + let hash = try FileHash.folderHash(deployment.location) + let flags = try FileHash.executableFlags(deployment.location) + try FileManager.default.removeItem(at: source) + try FileManager.default.removeItem(at: f.store.cacheDirectory) + try FileManager.default.removeItem(at: deployment.location) + _ = try UpdateOperations.restore(environment: f.environment) + #expect(try FileHash.folderHash(deployment.location) == hash) + #expect(try FileHash.executableFlags(deployment.location) == flags) + try f.write("Unmanaged child", to: deployment.location.appendingPathComponent("user-child")) + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(snapshot.components.first?.selection)]), + environment: f.environment + ) { try $0.apply() } + } + #expect( + try String( + contentsOf: deployment.location.appendingPathComponent("user-child"), encoding: .utf8) + == "Unmanaged child") + } + + @Test func normalLSPProgramUsesProductionStagedConversion() throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .lspServer( + name: "language", run: .init(executable: "never-run"), languages: [:], agents: [.opencode] + ) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + #expect(snapshot.deployments.allSatisfy { $0.status == .current }) + } +} + +extension NativeCompositionIntegrationTests { + @Test(arguments: [false, true]) + func createdNativeContainerPruningPreservesPreexistingContainers(_ existingContainer: Bool) throws + { + let f = try UpdateFixture() + let config = f.root.appendingPathComponent("opencode.json") + if existingContainer { try f.write("{\"commands\":{},\"userSetting\":false}", to: config) } + try f.store.save( + declaration: Declaration(components: [ + .command( + name: "review", description: "Review", prompt: .literal("Review sources."), + agents: [.opencode]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(snapshot.components.first?.selection)]), + environment: f.environment + ) { try $0.apply() } + let object = try JSONSerialization.jsonObject(with: Data(contentsOf: config)) as? [String: Any] + #expect((object?["commands"] != nil) == existingContainer) + if existingContainer { #expect(object?["userSetting"] as? Bool == false) } + } + + @Test func normalHookPreservesExistingUnmanagedOccurrence() throws { + let f = try UpdateFixture() + let config = f.root.appendingPathComponent(".claude/settings.json") + try f.write( + "{\"hooks\":{\"SessionStart\":[{\"hooks\":[{\"type\":\"command\",\"command\":\"user-hook\"}]}]}}", + to: config) + try f.store.save( + declaration: Declaration(components: [ + .hook( + name: "check", event: .native("SessionStart"), run: .init(executable: "never-run"), + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let text = try String(contentsOf: config, encoding: .utf8) + #expect(text.contains("user-hook")) + #expect(text.contains("never-run")) + } +} + +extension NativeCompositionIntegrationTests { + @Test(arguments: AgentID.allCases, [InstallScope.project, .user]) + func concreteSubagentUsesRegisteredScopeAndColdRestore(_ agent: AgentID, _ scope: InstallScope) + throws + { + let f = try UpdateFixture(scope: scope) + try f.store.save( + declaration: Declaration(components: [ + .subagent( + name: "researcher", description: "Research exact sources", + prompt: .literal("Read exact sources."), agents: [agent]) + ]), ledger: ResolvedLedger()) + let preview = try f.preview() + _ = try UpdateOperations.withPreparedUpdate(scope: scope, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let snapshot = try UpdateOperations.inspect(scope: scope, environment: f.environment) + #expect(!snapshot.deployments.isEmpty) + #expect(snapshot.deployments.allSatisfy { $0.status == .current }) + let before = try snapshot.deployments.map { try Data(contentsOf: $0.location) } + let locked = try Data(contentsOf: f.store.resolvedURL) + for deployment in snapshot.deployments { + try FileManager.default.removeItem(at: deployment.location) + } + _ = try UpdateOperations.restore(scope: scope, environment: f.environment) + #expect(try snapshot.deployments.map { try Data(contentsOf: $0.location) } == before) + #expect(try Data(contentsOf: f.store.resolvedURL) == locked) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(snapshot.components.first?.selection)]), + scope: scope, environment: f.environment + ) { try $0.apply() } + #expect( + try UpdateOperations.inspect(scope: scope, environment: f.environment).components.isEmpty) + } +} + +extension NativeCompositionIntegrationTests { + @Test func ordinaryRoleEditPreservesAnUnselectedPrivateMCPRegionWithoutProviderReplay() throws { + struct InitialBindings: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + Data("private-native-sibling-canary".utf8) + } + } + struct NoReplay: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + throw CoreError.invalidState("unselected provider was replayed") + } + } + let f = try UpdateFixture() + func declaration(_ body: String) -> Declaration { + Declaration(components: [ + .mcpServer( + name: "private", + transport: .stdio( + .init(executable: "never-run", environment: ["TOKEN": .secret("token")])), + agents: [.codex]), + .subagent( + name: "researcher", description: "Research sources", prompt: .literal(body), + agents: [.codex]), + ]) + } + try f.store.save(declaration: declaration("Before."), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + environment: f.environment, bindingProvider: InitialBindings() + ) { try $0.apply() } + let request = UpdateRequest(operation: .declaration(declaration("After.")), kinds: [.subagent]) + let preview = try UpdateOperations.preview(request, environment: f.environment) + #expect( + !String(decoding: try JSONEncoder().encode(preview), as: UTF8.self).contains( + "private-native-sibling-canary")) + _ = try UpdateOperations.withPreparedUpdate( + request, environment: f.environment, bindingProvider: NoReplay() + ) { try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) } + let config = f.root.appendingPathComponent(".codex/config.toml") + #expect( + try String(contentsOf: config, encoding: .utf8).contains("private-native-sibling-canary")) + let mode = + try FileManager.default.attributesOfItem(atPath: config.path)[.posixPermissions] as? NSNumber + #expect((mode?.intValue ?? 0) & 0o777 == 0o600) + #expect( + try UpdateOperations.inspect(environment: f.environment).deployments.allSatisfy { + $0.status == .current + }) + } +} + +extension NativeCompositionIntegrationTests { + @Test func existingOpenCodeJSONCIsOneRecordedPhysicalTargetForMCPAndCommands() throws { + let f = try UpdateFixture() + let config = f.root.appendingPathComponent("opencode.jsonc") + try f.write("// User comment\n{\"userSetting\":true,}\n", to: config) + try f.store.save( + declaration: Declaration(components: [ + .command( + name: "review", description: "Review", prompt: .literal("Review sources."), + agents: [.opencode]), + .mcpServer( + name: "db", transport: .stdio(.init(executable: "never-run")), agents: [.opencode]), + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + #expect(snapshot.deployments.allSatisfy { $0.location == config && $0.status == .current }) + #expect( + !FileManager.default.fileExists(atPath: f.root.appendingPathComponent("opencode.json").path)) + let bytes = try Data(contentsOf: config) + #expect(String(decoding: bytes, as: UTF8.self).hasPrefix("// User comment\n")) + let locked = try Data(contentsOf: f.store.resolvedURL) + try FileManager.default.removeItem(at: config) + _ = try UpdateOperations.restore(environment: f.environment) + let restored = try UpdateOperations.inspect(environment: f.environment) + #expect(restored.deployments.allSatisfy { $0.location == config && $0.status == .current }) + #expect(try Data(contentsOf: f.store.resolvedURL) == locked) + #expect( + !FileManager.default.fileExists(atPath: f.root.appendingPathComponent("opencode.json").path)) + } +} diff --git a/Tests/AgentsUpdatesTests/PublicInspectionTests.swift b/Tests/AgentsUpdatesTests/PublicInspectionTests.swift index 318bef4..97d7439 100644 --- a/Tests/AgentsUpdatesTests/PublicInspectionTests.swift +++ b/Tests/AgentsUpdatesTests/PublicInspectionTests.swift @@ -291,6 +291,7 @@ extension PublicInspectionTests { let before = try FileHash.folderHash(f.root) let proposal = try SourceImportOperations.inspect( format: "apmManifest", root: input, document: "apm.yml") + #expect(!proposal.specificationStatus.isEmpty) #expect(proposal.diagnostics.isEmpty) #expect(proposal.components.count == 1) #expect(proposal.resources.first?.requiresStandaloneSource == true) diff --git a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift index cfb4a14..7ea7da8 100644 --- a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift +++ b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift @@ -276,3 +276,42 @@ private func waitFor(_ name: String, fixture: UpdateFixture, child: Process) thr private func terminate(_ process: Process) { do { try ProcessWait.terminate(process) } catch { Issue.record(error) } } + +extension UpdateTransactionTests { + @Test func combinedNativeFileAndSharedDocumentFaultRollBackTogether() throws { + let fixture = try UpdateFixture() + let config = fixture.root.appendingPathComponent(".codex/config.toml") + let role = fixture.root.appendingPathComponent(".codex/agents/researcher.toml") + try fixture.write("# User setting\ntheme = 'fixture'\n", to: config) + let initial = Declaration(components: [ + .subagent( + name: "researcher", description: "Research sources", prompt: .literal("Before."), + agents: [.codex]), + .mcpServer(name: "db", transport: .stdio(.init(executable: "before")), agents: [.codex]), + ]) + try fixture.store.save(declaration: initial, ledger: ResolvedLedger()) + _ = try fixture.apply() + let files = [fixture.store.declarationURL, fixture.store.resolvedURL, config, role] + let before = try files.map { try Data(contentsOf: $0) } + let next = Declaration(components: [ + .subagent( + name: "researcher", description: "Research sources", prompt: .literal("After."), + agents: [.codex]), + .mcpServer(name: "db", transport: .stdio(.init(executable: "after")), agents: [.codex]), + ]) + var reached = false + let completion = UpdateOperations.perform( + .init(operation: .declaration(next)), environment: fixture.environment, + checkpoint: { step in + if step == TransactionCheckpoint.progress(0, .applied).name { + reached = true + throw CoreError.invalidState("combined native fault fixture") + } + }, { try $0.apply() }) + #expect(reached) + #expect(completion.disposition == .rolledBack) + #expect(!completion.recovery.pending) + #expect(throws: UpdateApplyError.self) { try completion.result.get() } + #expect(try files.map { try Data(contentsOf: $0) } == before) + } +} From 75f978a9b1dc10f5fa234342f8cf39741986a1a6 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:57:54 +0800 Subject: [PATCH 100/171] feat: preserve ordered hook occurrence ownership --- .../NativeComponentContribution.swift | 6 + Sources/NativeDocuments/Model.swift | 31 ++- Sources/NativeDocuments/NativeDocument.swift | 108 +++++++- Sources/NativeDocuments/PatchBuilder.swift | 11 + .../NativeComponentTests.swift | 22 ++ .../OccurrenceInsertionTests.swift | 247 ++++++++++++++++++ 6 files changed, 412 insertions(+), 13 deletions(-) create mode 100644 Tests/NativeDocumentsTests/OccurrenceInsertionTests.swift diff --git a/Sources/Components/NativeComponentContribution.swift b/Sources/Components/NativeComponentContribution.swift index 59e1179..c63c3e4 100644 --- a/Sources/Components/NativeComponentContribution.swift +++ b/Sources/Components/NativeComponentContribution.swift @@ -68,6 +68,12 @@ package struct NativeComponentHook { package let layout: Layout package let value: NativeComponentValue package var keys: [String] { ["hooks", event] } + + /// E supplies the staged value and a fresh array precondition. Ownership comes only from + /// prepare's appendedOccurrences result, never from an equal existing handler. + package func append(value: NativeValue, expected: NativeExpectedRegion) -> NativeRegionEdit { + .append(region: NativeRegion(keys: keys), expected: expected, value: value) + } } package struct NativeComponentPermission { diff --git a/Sources/NativeDocuments/Model.swift b/Sources/NativeDocuments/Model.swift index ca5a014..3e20bbf 100644 --- a/Sources/NativeDocuments/Model.swift +++ b/Sources/NativeDocuments/Model.swift @@ -59,6 +59,9 @@ package struct NativeOccurrenceEvidence: Equatable { /// Fingerprints contain value bytes: secret-bearing matches stay in E/D's private plan, /// while only non-secret semantic evidence may enter a versioned locked layout. package let snapshot: Data? + /// Insertion ownership pins the complete semantic array and its position. Changed arrays + /// require fresh evidence from an authorized same-snapshot prepare, never duplicate reselection. + package let arraySnapshot: Data? package let ordinal: Int? package let previous: Data? package let next: Data? @@ -66,14 +69,18 @@ package struct NativeOccurrenceEvidence: Equatable { self.idKey = idKey self.id = id snapshot = nil + arraySnapshot = nil ordinal = nil previous = nil next = nil } - package init(snapshot: Data, ordinal: Int, previous: Data?, next: Data?) { + package init( + snapshot: Data, ordinal: Int, previous: Data?, next: Data?, arraySnapshot: Data? = nil + ) { idKey = nil id = nil self.snapshot = snapshot + self.arraySnapshot = arraySnapshot self.ordinal = ordinal self.previous = previous self.next = next @@ -87,7 +94,8 @@ package struct NativeOccurrenceEvidence: Equatable { } } return same(a.idKey, b.idKey) && same(a.id, b.id) && a.snapshot == b.snapshot - && a.ordinal == b.ordinal && a.previous == b.previous && a.next == b.next + && a.arraySnapshot == b.arraySnapshot && a.ordinal == b.ordinal && a.previous == b.previous + && a.next == b.next } } @@ -118,21 +126,29 @@ package enum NativeExpectedRegion { package enum NativeRegionEdit { case put(region: NativeRegion, expected: NativeExpectedRegion, value: NativeValue) case remove(region: NativeRegion, expected: NativeExpectedRegion) + /// Appends a distinct occurrence even when an equal unmanaged value exists. The precondition + /// observes the original array, or its absence. Several appends retain caller order. + case append(region: NativeRegion, expected: NativeExpectedRegion, value: NativeValue) /// The caller must hold durable creation authority for this object or array. The observation /// must match the preimage; removal is conditional on emptiness after all descendant edits. /// Unowned comments or ambiguous removal syntax retain the container. case pruneCreatedContainer(region: NativeRegion, observed: NativeObservation) var region: NativeRegion { switch self { - case .put(let r, _, _), .remove(let r, _), .pruneCreatedContainer(let r, _): r + case .put(let r, _, _), .append(let r, _, _), .remove(let r, _), + .pruneCreatedContainer(let r, _): + r } } var expected: NativeExpectedRegion { switch self { - case .put(_, let e, _), .remove(_, let e): e + case .put(_, let e, _), .append(_, let e, _), .remove(_, let e): e case .pruneCreatedContainer(_, let observation): .createdContainer(observation) } } + var isAppend: Bool { + if case .append = self { true } else { false } + } var isConditionalPrune: Bool { if case .pruneCreatedContainer = self { true } else { false } } @@ -143,6 +159,13 @@ package struct PreparedNativeChange { package let changedRegions: [NativeRegion] package let observations: [NativeObservation] package let createdContainers: [NativeRegion] + /// Input edit index associates each inserted owner with its final, rematchable observation. + package let appendedOccurrences: [NativeAppendedOccurrence] +} + +package struct NativeAppendedOccurrence { + package let editIndex: Int + package let observation: NativeObservation } struct Member { diff --git a/Sources/NativeDocuments/NativeDocument.swift b/Sources/NativeDocuments/NativeDocument.swift index e7f8ca2..676ca0a 100644 --- a/Sources/NativeDocuments/NativeDocument.swift +++ b/Sources/NativeDocuments/NativeDocument.swift @@ -79,13 +79,21 @@ package struct NativeDocument { && previous.starts(with: address)) || (edits[index].isConditionalPrune && address.count > previous.count && address.starts(with: previous)) - if !conditionalAncestor + let orderedAppend = + (edit.isAppend && previous.starts(with: address) + && (previous.count > address.count || edits[index].isAppend)) + || (edits[index].isAppend && address.count > previous.count + && address.starts(with: previous)) + if !conditionalAncestor && !orderedAppend && (address.starts(with: previous) || previous.starts(with: address)) { throw NativeDocumentError.unsupportedEdit(.overlappingEdits, edit.region, []) } } let existing = try resolve(edit.region, on: root) + if edit.isAppend, let existing, existing.kind != .array { + throw NativeDocumentError.ownershipMismatch(edit.region) + } if case .createdContainer = edit.expected { if edit.isConditionalPrune { guard let existing, existing.kind == .object || existing.kind == .array else { @@ -115,13 +123,21 @@ package struct NativeDocument { var changed: [NativeRegion] = [] var created: [NativeRegion] = [] var observed: [Int] = [] + var appended: [(editIndex: Int, ordinal: Int)] = [] var removed: [([AddressStep], Int)] = [] try budget.allocate(edits.count, stage: "native edit order") var prunes: [Int] = [] + var appends: [Int] = [] var order: [Int] = [] for index in edits.indices { try budget.step() - if edits[index].isConditionalPrune { prunes.append(index) } else { order.append(index) } + if edits[index].isConditionalPrune { + prunes.append(index) + } else if edits[index].isAppend { + appends.append(index) + } else { + order.append(index) + } } try prunes.sort { try budget.step() @@ -129,6 +145,7 @@ package struct NativeDocument { ? $0 < $1 : addresses[$0].count > addresses[$1].count } try budget.allocate(prunes.count, stage: "conditional prune order") + order.append(contentsOf: appends) order.append(contentsOf: prunes) for editIndex in order { let edit = edits[editIndex] @@ -148,17 +165,31 @@ package struct NativeDocument { if try current.hasComments(old) { continue } } let desired: Node? + var appendedValue: Node? switch edit { - case .put(_, _, let value): + case .put(_, _, let value), .append(_, _, let value): let text = try NativeRenderer(format: format, budget: budget, region: edit.region).render( value) if format == .toml { let parsed = try NativeDocument( bytes: Data(("value = " + text).utf8), format: .toml, budget: budget) - desired = parsed.root.members.first?.node + appendedValue = parsed.root.members.first?.node } else { let parsed = try NativeDocument(bytes: Data(text.utf8), format: .json, budget: budget) - desired = parsed.root + appendedValue = parsed.root + } + if edit.isAppend { + guard let element = appendedValue else { + throw NativeDocumentError.ownershipMismatch(edit.region) + } + if old == nil { try budget.node(depth: effective.steps.count) } + let array = try old?.copy(budget) ?? Node(.array) + try budget.allocate(1, stage: "appended occurrence") + array.elements.append(element) + desired = array + } else { + desired = appendedValue + appendedValue = nil } case .remove, .pruneCreatedContainer: desired = nil @@ -178,6 +209,10 @@ package struct NativeDocument { throw NativeDocumentError.unsupportedEdit(.ambiguousTrivia, edit.region, old.headers) } } + if edit.isAppend && old == nil { + try budget.allocate(effective.steps.count + 1, stage: "created array evidence") + created.append(effective) + } try current.createdObjects(old: old, new: desired, path: effective.steps, into: &created) let expected = try current.root.copy(budget) try current.change( @@ -186,7 +221,9 @@ package struct NativeDocument { var editor = PatchBuilder(document: current, region: effective) let checked: NativeDocument do { - if let old, let desired { + if let appendedValue, old != nil { + try editor.appendOccurrence(appendedValue, path: effective.steps) + } else if let old, let desired { try editor.diff(old, desired: desired, path: effective.steps) } else if let old { try editor.remove(old, path: effective.steps) @@ -219,7 +256,15 @@ package struct NativeDocument { throw NativeDocumentError.unsupportedEdit( .wouldRewriteUnownedStructure, edit.region, editor.patches.map(\.range)) } - if desired != nil { + if edit.isAppend { + var ordinal = old?.elements.count ?? 0 + for (path, _) in removed { + try budget.step(path.reduce(0) { $0 + $1.work }) + if path == addresses[editIndex] { ordinal += 1 } + } + try budget.allocate(1, stage: "insertion identity") + appended.append((editIndex, ordinal)) + } else if desired != nil { observed.append(editIndex) } removed = nextRemoved @@ -233,9 +278,32 @@ package struct NativeDocument { observations.append(try current.observation(node, region: region)) } } + var appendedOccurrences: [NativeAppendedOccurrence] = [] + for insertion in appended { + let index = insertion.editIndex + let parent = try current.region(edits[index].region, at: addresses[index], removed: removed) + guard let array = try current.resolve(parent, on: current.root) else { + throw NativeDocumentError.ownershipMismatch(parent) + } + var ordinal = insertion.ordinal + for (path, _) in removed { + try budget.step(path.reduce(0) { $0 + $1.work }) + if path == addresses[index] { ordinal -= 1 } + } + guard ordinal >= 0 && ordinal < array.elements.count else { + throw NativeDocumentError.ownershipMismatch(parent) + } + let evidence = try current.insertionEvidence(in: array, ordinal: ordinal) + let region = NativeRegion(parent.steps + [.occurrence(evidence)]) + try budget.allocate(region.steps.count + 1, stage: "insertion observation") + appendedOccurrences.append( + NativeAppendedOccurrence( + editIndex: index, + observation: try current.observation(array.elements[ordinal], region: region))) + } return PreparedNativeChange( bytes: current.bytes, changedRegions: changed, observations: observations, - createdContainers: created) + createdContainers: created, appendedOccurrences: appendedOccurrences) } } @@ -288,9 +356,11 @@ package struct NativeDocument { case (.occurrence(let a), .occurrence(let b)): let aSize = (a.idKey?.utf8.count ?? 0) + (a.id?.utf8.count ?? 0) + (a.snapshot?.count ?? 0) + + (a.arraySnapshot?.count ?? 0) + (a.previous?.count ?? 0) + (a.next?.count ?? 0) let bSize = (b.idKey?.utf8.count ?? 0) + (b.id?.utf8.count ?? 0) + (b.snapshot?.count ?? 0) + + (b.arraySnapshot?.count ?? 0) + (b.previous?.count ?? 0) + (b.next?.count ?? 0) try budget.step(aSize + bSize + 1) if a != b { return false } @@ -385,7 +455,9 @@ package struct NativeDocument { } let element = current.elements[i] let next: NativeOccurrenceEvidence - if let key = evidence.idKey, let m = try element.member(key, budget: budget), + if evidence.arraySnapshot != nil { + next = try insertionEvidence(in: current, ordinal: i) + } else if let key = evidence.idKey, let m = try element.member(key, budget: budget), element.members[m].node.kind == .string { next = .init(idKey: key, id: element.members[m].node.text) @@ -423,10 +495,28 @@ package struct NativeDocument { return false } + private func insertionEvidence(in array: Node, ordinal: Int) throws -> NativeOccurrenceEvidence { + .init( + snapshot: try array.elements[ordinal].fingerprint(budget), ordinal: ordinal, + previous: ordinal > 0 ? try array.elements[ordinal - 1].fingerprint(budget) : nil, + next: ordinal + 1 < array.elements.count + ? try array.elements[ordinal + 1].fingerprint(budget) : nil, + arraySnapshot: try array.fingerprint(budget)) + } + func occurrence(_ evidence: NativeOccurrenceEvidence, in node: Node, region: NativeRegion) throws -> Int { guard node.kind == .array else { throw NativeDocumentError.ownershipMismatch(region) } + if let arraySnapshot = evidence.arraySnapshot { + try budget.step(arraySnapshot.count + (evidence.snapshot?.count ?? 0)) + guard let ordinal = evidence.ordinal, let snapshot = evidence.snapshot, + ordinal >= 0 && ordinal < node.elements.count, + try node.fingerprint(budget) == arraySnapshot, + try node.elements[ordinal].fingerprint(budget) == snapshot + else { throw NativeDocumentError.ownershipMismatch(region) } + return ordinal + } var matches: [Int] = [] for (i, element) in node.elements.enumerated() { try budget.step() diff --git a/Sources/NativeDocuments/PatchBuilder.swift b/Sources/NativeDocuments/PatchBuilder.swift index 1e6a05c..67608f9 100644 --- a/Sources/NativeDocuments/PatchBuilder.swift +++ b/Sources/NativeDocuments/PatchBuilder.swift @@ -268,6 +268,17 @@ struct PatchBuilder { } throw NativeDocumentError.ownershipMismatch(region) } + mutating func appendOccurrence(_ value: Node, path: [NativePathStep]) throws { + guard let array = try document.resolve(NativeRegion(path), on: document.root), + array.kind == .array + else { throw NativeDocumentError.ownershipMismatch(region) } + if array.aot { + try appendTables([value], path: path) + } else { + try appendValues([value], in: array) + } + } + private mutating func arrayAssignment(path: [NativePathStep], rendered: String = "[]") throws { guard case .key(let key) = path.last, let parent = try document.resolve(NativeRegion(Array(path.dropLast())), on: document.root) diff --git a/Tests/ComponentsTests/NativeComponentTests.swift b/Tests/ComponentsTests/NativeComponentTests.swift index ba2aaea..74b9bca 100644 --- a/Tests/ComponentsTests/NativeComponentTests.swift +++ b/Tests/ComponentsTests/NativeComponentTests.swift @@ -776,6 +776,28 @@ struct NativeComponentTests { bindings: .init(["fixture/hook": Data("staged hook value".utf8)]), environment: fixture.environment, resourcePaths: [:], budget: budget(), cursorCommandShell: .posix) + let existing = try NativeDocument( + bytes: Data("{\"version\":1,\"privateSibling\":\"keep\"}".utf8), + format: .json, budget: budget()) + let initial = try existing.prepare([hook.append(value: native, expected: .absent)]) + let fresh = try NativeDocument(bytes: initial.bytes, format: .json, budget: budget()) + let arrayRegion = NativeRegion(keys: hook.keys) + let append = hook.append( + value: native, expected: .owned(try #require(try fresh.read(arrayRegion)))) + let owner = try #require(initial.appendedOccurrences.first).observation + let doubled = try fresh.prepare([ + .put(region: owner.region, expected: .owned(owner), value: native), append, + ]) + #expect(doubled.appendedOccurrences.map(\.editIndex) == [1]) + let published = try NativeDocument(bytes: doubled.bytes, format: .json, budget: budget()) + #expect(try published.read(arrayRegion)?.value == .array([native, native])) + #expect(try published.read(.init(keys: ["privateSibling"]))?.value == .string("keep")) + let addedOwner = try #require(doubled.appendedOccurrences.first).observation + let removed = try published.prepare([ + .remove(region: addedOwner.region, expected: .owned(addedOwner)) + ]) + let afterRemoval = try NativeDocument(bytes: removed.bytes, format: .json, budget: budget()) + #expect(try afterRemoval.read(arrayRegion)?.value == .array([native])) guard case .object(let object) = native else { Issue.record("missing native hook") return diff --git a/Tests/NativeDocumentsTests/OccurrenceInsertionTests.swift b/Tests/NativeDocumentsTests/OccurrenceInsertionTests.swift new file mode 100644 index 0000000..88cdb4b --- /dev/null +++ b/Tests/NativeDocumentsTests/OccurrenceInsertionTests.swift @@ -0,0 +1,247 @@ +import AgentsCore +import Foundation +import NativeDocuments +import Testing + +@Suite("Ordered native occurrence insertion") +struct OccurrenceInsertionTests { + @Test func equalUnmanagedHooksRemainDistinctAndOwnersRemoveIndependently() throws { + let source = + #"{"hooks":{"SessionStart":[{"command":"check"},{"command":"check"}]},"other":true}"# + let array = keyRegion("hooks", "SessionStart") + let hook = NativeValue.object(["command": .string("check")]) + let original = try document(source, .json) + let added = try original.prepare([ + .append(region: array, expected: owned(original, array), value: hook), + .append(region: array, expected: owned(original, array), value: hook), + ]) + #expect( + text(added) + == source.replacingOccurrences( + of: "]}", with: ", {\"command\": \"check\"}, {\"command\": \"check\"}]}")) + #expect(added.appendedOccurrences.map(\.editIndex) == [0, 1]) + let first = added.appendedOccurrences[0].observation + let second = added.appendedOccurrences[1].observation + #expect(first.region != second.region) + let live = try NativeDocument(bytes: added.bytes, format: .json, budget: generousBudget()) + #expect(try live.read(first.region)?.value == hook) + #expect(try live.read(second.region)?.value == hook) + let removed = try live.prepare([ + .remove(region: first.region, expected: .owned(first)), + .put(region: second.region, expected: .owned(second), value: hook), + ]) + #expect(removed.observations.count == 1) + let retained = try #require(removed.observations.first) + let fresh = try NativeDocument(bytes: removed.bytes, format: .json, budget: generousBudget()) + // A stale duplicate must not move ownership to the last equal unmanaged occurrence. + #expect(try fresh.read(second.region) == nil) + let restored = try fresh.prepare([ + .remove(region: retained.region, expected: .owned(retained)) + ]) + #expect(text(restored) == source.replacingOccurrences(of: "]}", with: " ]}")) + } + + @Test func appendPreservesJSONCCommentsAndCreatesOnlyMissingContainers() throws { + let source = + "{\n \"hooks\": {\"BeforeAgent\": [\n {\"command\":\"unmanaged\"} // retained\n ]},\n // sibling\n \"other\": 7\n}" + let original = try document(source, .jsonc(trailingCommas: true)) + let array = keyRegion("hooks", "BeforeAgent") + let changed = try original.prepare([ + .append( + region: array, expected: owned(original, array), value: .object(["command": .string("new")]) + ) + ]) + #expect( + text(changed) + == source.replacingOccurrences( + of: "{\"command\":\"unmanaged\"} // retained\n", + with: "{\"command\":\"unmanaged\"}, // retained\n {\"command\": \"new\"}\n")) + let empty = try document("{\"other\":7}", .json) + let created = try empty.prepare([ + .append(region: array, expected: .absent, value: .object(["command": .string("new")])) + ]) + let new = try NativeDocument(bytes: created.bytes, format: .json, budget: generousBudget()) + #expect(try new.read(array)?.occurrences.count == 1) + #expect(try new.read(keyRegion("other"))?.value == .integer(7)) + #expect(created.createdContainers.contains(keyRegion("hooks"))) + #expect(created.createdContainers.contains(array)) + let inserted = try #require(created.appendedOccurrences.first).observation + let removed = try new.prepare([ + .pruneCreatedContainer( + region: keyRegion("hooks"), observed: #require(try new.read(keyRegion("hooks")))), + .pruneCreatedContainer(region: array, observed: #require(try new.read(array))), + .remove(region: inserted.region, expected: .owned(inserted)), + ]) + #expect(text(removed) == "{\"other\":7}") + } + + @Test func tomlOccurrencesAppendWithoutNativeIDsAndPreserveUnrelatedBytes() throws { + for source in [ + "hooks = [{ command = 'keep' }] # retained\nother = 7\n", + "# retained\nother = 7\n[[hooks]]\ncommand = 'keep'\n", + ] { + let original = try document(source) + let array = keyRegion("hooks") + let changed = try original.prepare([ + .append( + region: array, expected: owned(original, array), + value: .object(["command": .string("new")])) + ]) + #expect(text(changed).contains("command = 'keep'")) + #expect(text(changed).contains("# retained\n")) + #expect(text(changed).contains("other = 7\n")) + #expect(!text(changed).contains("id")) + let live = try NativeDocument(bytes: changed.bytes, format: .toml, budget: generousBudget()) + let inserted = try #require(changed.appendedOccurrences.first).observation + let removed = try live.prepare([.remove(region: inserted.region, expected: .owned(inserted))]) + #expect(text(removed) == (source.hasPrefix("#") ? source + "\n\n" : source)) + } + } + + @Test func sameSnapshotRemovalAppendAndRefreshPreserveOrder() throws { + let original = try document(#"{"items":["unmanaged","old","retained"]}"#, .json) + let array = keyRegion("items") + let entries = try #require(try original.read(array)).occurrences + let old = NativeRegion(array.steps + [.occurrence(entries[1])]) + let retained = NativeRegion(array.steps + [.occurrence(entries[2])]) + let changed = try original.prepare([ + .append(region: array, expected: owned(original, array), value: .string("new")), + .remove(region: old, expected: owned(original, old)), + .put(region: retained, expected: owned(original, retained), value: .string("retained")), + .append(region: array, expected: owned(original, array), value: .string("last")), + ]) + let live = try NativeDocument(bytes: changed.bytes, format: .json, budget: generousBudget()) + #expect( + try live.read(array)?.value + == .array([.string("unmanaged"), .string("retained"), .string("new"), .string("last")])) + #expect(changed.appendedOccurrences.map(\.editIndex) == [0, 3]) + #expect( + try live.read(changed.appendedOccurrences[0].observation.region)?.value == .string("new")) + #expect( + try live.read(changed.appendedOccurrences[1].observation.region)?.value == .string("last")) + } + + @Test func appendRetainsIdentityThroughConditionalOccurrencePruning() throws { + let original = try document(#"{"items":[{"payload":{"owned":1}},{"unmanaged":true}]}"#, .json) + let array = keyRegion("items") + let first = try #require(try original.read(array)).occurrences[0] + let selected = NativeRegion(array.steps + [.occurrence(first)]) + let payload = NativeRegion(selected.steps + [.key("payload")]) + let child = NativeRegion(payload.steps + [.key("owned")]) + let changed = try original.prepare([ + .append( + region: array, expected: owned(original, array), value: .object(["new": .boolean(true)])), + .pruneCreatedContainer(region: selected, observed: #require(try original.read(selected))), + .pruneCreatedContainer(region: payload, observed: #require(try original.read(payload))), + .remove(region: child, expected: owned(original, child)), + ]) + let live = try NativeDocument(bytes: changed.bytes, format: .json, budget: generousBudget()) + let inserted = try #require(changed.appendedOccurrences.first).observation + #expect( + try live.read(array)?.value + == .array([ + .object(["unmanaged": .boolean(true)]), .object(["new": .boolean(true)]), + ])) + #expect(try live.read(inserted.region)?.value == .object(["new": .boolean(true)])) + } + + @Test func explicitAppendComposesWithExistingNativeIDInsertion() throws { + let original = try document(#"{"items":[{"id":"existing"}]}"#, .json) + let array = keyRegion("items") + let nativeID = NativeRegion(array.steps + [.occurrence(.init(idKey: "id", id: "named"))]) + let changed = try original.prepare([ + .append(region: array, expected: owned(original, array), value: .string("last")), + .put(region: nativeID, expected: .absent, value: .object(["id": .string("named")])), + ]) + let live = try NativeDocument(bytes: changed.bytes, format: .json, budget: generousBudget()) + let inserted = try #require(changed.appendedOccurrences.first).observation + #expect( + try live.read(array)?.value + == .array([ + .object(["id": .string("existing")]), .object(["id": .string("named")]), .string("last"), + ])) + #expect(try live.read(inserted.region)?.value == .string("last")) + } + + @Test func insertionEvidenceReconstructsWithoutOffsetsAndRejectsCorruption() throws { + let original = try document(#"{"items":["same","same"]}"#, .json) + let array = keyRegion("items") + let changed = try original.prepare([ + .append(region: array, expected: owned(original, array), value: .string("same")) + ]) + let observation = try #require(changed.appendedOccurrences.first).observation + guard case .occurrence(let saved) = observation.region.steps.last else { + Issue.record("missing insertion evidence") + return + } + let snapshot = try #require(saved.snapshot) + let ordinal = try #require(saved.ordinal) + let arraySnapshot = try #require(saved.arraySnapshot) + let retained = NativeOccurrenceEvidence( + snapshot: snapshot, ordinal: ordinal, + previous: saved.previous, next: saved.next, arraySnapshot: arraySnapshot) + let selected = NativeRegion(array.steps + [.occurrence(retained)]) + let live = try NativeDocument(bytes: changed.bytes, format: .json, budget: generousBudget()) + #expect(try live.read(selected)?.value == .string("same")) + let corrupt = NativeOccurrenceEvidence( + snapshot: snapshot, ordinal: ordinal, + previous: saved.previous, next: saved.next, arraySnapshot: Data("corrupt".utf8)) + #expect(try live.read(NativeRegion(array.steps + [.occurrence(corrupt)])) == nil) + } + + @Test func appendSharesTheOperationBudgetAcrossDraftsAndEvidence() throws { + func bounded() -> NativeDocumentBudget { + NativeDocumentBudget( + limits: .init( + storage: 1_000_000, work: 100_000, nodes: 10_000, depth: 30, + uninterruptedBytes: 10_000)) + } + let source = #"{"items":[]}"# + let array = keyRegion("items") + let value = NativeValue.string(String(repeating: "x", count: 2048)) + let single = try document(source, .json, budget: bounded()) + #expect( + try single.prepare([ + .append(region: array, expected: owned(single, array), value: value) + ]).appendedOccurrences.count == 1) + let batch = try document(source, .json, budget: bounded()) + let edits = try (0..<16).map { _ in + NativeRegionEdit.append(region: array, expected: try owned(batch, array), value: value) + } + do { + _ = try batch.prepare(edits) + Issue.record("unbounded cumulative append work") + } catch NativeDocumentError.budgetExceeded {} + #expect(batch.bytes == Data(source.utf8)) + } + + @Test func staleAppendPreimageOrdinaryOverlapAndAmbiguousEvidenceRefuse() throws { + let array = keyRegion("items") + let original = try document(#"{"items":[1,1]}"#, .json) + let changed = try document(#"{"items":[1,1,1]}"#, .json) + #expect(throws: NativeDocumentError.self) { + try changed.prepare([ + .append(region: array, expected: owned(original, array), value: .integer(2)) + ]) + } + #expect(throws: NativeDocumentError.self) { + try original.prepare([ + .put(region: array, expected: owned(original, array), value: .array([])), + .append(region: array, expected: owned(original, array), value: .integer(2)), + ]) + } + let ambiguous = try document(#"{"items":[1,1,1,1,1]}"#, .json) + let evidence = try #require(try ambiguous.read(array)).occurrences[2] + #expect(throws: NativeDocumentError.self) { + try ambiguous.read(NativeRegion(array.steps + [.occurrence(evidence)])) + } + let insertion = try original.prepare([ + .append(region: array, expected: owned(original, array), value: .integer(1)) + ]) + let owner = try #require(insertion.appendedOccurrences.first).observation + let externallyChanged = try document(#"{"items":[1,1,1,1]}"#, .json) + #expect(throws: NativeDocumentError.self) { + try externallyChanged.prepare([.remove(region: owner.region, expected: .owned(owner))]) + } + } +} From 1d86a0b9b0f9fadff50bad82359636f09f96a342 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:57:54 +0800 Subject: [PATCH 101/171] fix: validate imported native fields consistently --- .../Import/NativeContainerImport.swift | 136 ++++++++++-- .../Import/NativeExecutableMembers.swift | 37 +++- .../Components/Import/NativeImportInput.swift | 18 ++ .../Import/NativeImportSemantics.swift | 18 ++ .../Import/NativeMemberImport.swift | 116 +++++++---- Tests/ComponentsTests/ImportNativeTests.swift | 193 +++++++++++++++++- 6 files changed, 454 insertions(+), 64 deletions(-) diff --git a/Sources/Components/Import/NativeContainerImport.swift b/Sources/Components/Import/NativeContainerImport.swift index 8e136f5..5526c86 100644 --- a/Sources/Components/Import/NativeContainerImport.swift +++ b/Sources/Components/Import/NativeContainerImport.swift @@ -29,6 +29,13 @@ enum NativeContainerImport { let agent = NativeImportInput.agent(input.profile) let alias = NativeImportInput.source( input, root: root, origin: parsed.location(), into: &diagnostics) + let surface = NativeImportSemantics.surface(input.profile) + let defaults = + agent == .geminiCLI + ? ["commands": "commands", "agents": "agents", "skills": "skills"] + : try NativeComponentFieldsV1.pluginDefaults( + surface: surface, explicitFields: Set(parsed.fields.keys)) + var documents: [String: NativeImportDocument] = [:] let metadata: Set = ["name", "version"] let members: Set = agent == .geminiCLI @@ -43,9 +50,9 @@ enum NativeContainerImport { } // A container contributes typed children; .native selection/registration belongs to B/F. // Unknown/dependency fields are already diagnosed rather than becoming opaque payloads. - for (field, kind, folder) in [ - ("commands", DeclaredComponentKind.command, "commands"), - ("agents", .subagent, "agents"), ("skills", .skills, "skills"), + for (field, kind) in [ + ("commands", DeclaredComponentKind.command), + ("agents", .subagent), ("skills", .skills), ] { let supplied = parsed.fields[field] if agent == .geminiCLI, supplied != nil { @@ -54,8 +61,7 @@ enum NativeContainerImport { } var paths: [String] = [] var explicitPaths: Set = [] - // Cursor explicit paths replace default discovery. Claude paths add to defaults. - if agent != .cursor || supplied == nil { paths.append(folder) } + if let path = defaults[field] { paths.append(path) } if let supplied { if let path = supplied.importString { let relative = try componentPath(path, agent: agent) @@ -78,11 +84,11 @@ enum NativeContainerImport { } } var mcpSources: [(NativeValue, NativeImportDocument, [String])] = [] - let mcpDefault = agent == .cursor ? "mcp.json" : ".mcp.json" - if agent != .geminiCLI, agent != .cursor || parsed.fields["mcpServers"] == nil, + if let mcpDefault = defaults["mcpServers"], let document = try optionalDocument( mcpDefault, root: root, input: input, limits: limits, admission: parsed.admission) { + documents[mcpDefault] = document NativeImportInput.unknown( document.fields, allowed: ["mcpServers"], at: document.location(), into: &diagnostics) if let map = document.fields["mcpServers"] { @@ -95,7 +101,7 @@ enum NativeContainerImport { if let declared = parsed.fields["mcpServers"] { try configurations( declared, field: "mcpServers", parsed: parsed, root: root, limits: limits, - into: &mcpSources, diagnostics: &diagnostics) + into: &mcpSources, documents: &documents, diagnostics: &diagnostics) } // The producer loads defaults then declarations; later duplicate names replace earlier ones. var winners: [String: (NativeValue, NativeImportDocument, [String])] = [:] @@ -134,16 +140,17 @@ enum NativeContainerImport { rewrite: rewrite, into: &diagnostics, admission: parsed.admission) } var lspSources: [(NativeValue, NativeImportDocument, [String])] = [] - if agent == .claudeCode, + if let lspDefault = defaults["lspServers"], let document = try optionalDocument( - ".lsp.json", root: root, input: input, limits: limits, admission: parsed.admission) + lspDefault, root: root, input: input, limits: limits, admission: parsed.admission) { + documents[lspDefault] = document lspSources.append((.object(document.fields), document, [])) } if let value = parsed.fields["lspServers"] { try configurations( value, field: "lspServers", parsed: parsed, root: root, limits: limits, into: &lspSources, - diagnostics: &diagnostics) + documents: &documents, diagnostics: &diagnostics) } var lspWinners: [String: (NativeValue, NativeImportDocument, [String])] = [:] for (value, document, keys) in lspSources { @@ -158,19 +165,19 @@ enum NativeContainerImport { into: &diagnostics) } var hookSources: [(NativeValue, NativeImportDocument, [String])] = [] - if agent != .cursor || parsed.fields["hooks"] == nil, + if let hookDefault = defaults["hooks"], let document = try optionalDocument( - "hooks/hooks.json", root: root, input: input, limits: limits, admission: parsed.admission), - let value = document.fields["hooks"] + hookDefault, root: root, input: input, limits: limits, admission: parsed.admission) { + documents[hookDefault] = document NativeImportInput.unknown( document.fields, allowed: ["hooks"], at: document.location(), into: &diagnostics) - hookSources.append((value, document, ["hooks"])) + if let value = document.fields["hooks"] { hookSources.append((value, document, ["hooks"])) } } if let value = parsed.fields["hooks"] { try configurations( value, field: "hooks", parsed: parsed, root: root, limits: limits, into: &hookSources, - diagnostics: &diagnostics) + documents: &documents, diagnostics: &diagnostics) } for (value, document, keys) in hookSources { try NativeSourceImport.hooks( @@ -194,6 +201,58 @@ enum NativeContainerImport { NativeImportInput.unconverted( parsed.fields[field]!, at: parsed.location([field]), into: &diagnostics) } + if agent != .geminiCLI { + for (_, document, _) in mcpSources + lspSources + hookSources { + guard document.input.document != input.document else { continue } + let path = + root == "." + ? document.input.document : String(document.input.document.dropFirst(root.count + 1)) + documents[path] = document + } + do { + _ = try NativeComponentFieldsV1.plugin( + surface: surface, fields: parsed.fields, + entries: try inventory(snapshot, root: root, limits: limits), + documents: documents.mapValues { .object($0.fields) }, budget: parsed.admission.parser) + } catch let issue as NativeComponentFieldIssue { + var document = parsed + var keys = issue.field + if let field = issue.field.first { + let sources = + field == "mcpServers" + ? mcpSources : field == "lspServers" ? lspSources : field == "hooks" ? hookSources : [] + let external = sources.filter { $0.1.input.document != input.document } + // The helper does not return a document coordinate. Only a single original + // source can be located uniquely; multiple inputs retain their manifest location. + let declaredPaths = + parsed.fields[field]?.importStrings + ?? parsed.fields[field]?.importString.map { [$0] } + if Set(external.map { $0.1.input.document }).count == 1, let source = external.first, + parsed.fields[field] == nil + || (declaredPaths?.count == 1 + && documents[(try? ImportInput.path(declaredPaths![0])) ?? ""]?.input.document + == source.1.input.document) + { + document = source.1 + keys = source.2 + Array(issue.field.dropFirst().filter { $0 != "default" }) + } + } + NativeImportSemantics.report(issue, at: document.fieldLocation(keys), into: &diagnostics) + } + } + for field in metadata { + if let value = parsed.fields[field] { + _ = NativeImportInput.sensitive(value, at: parsed.location([field]), into: &diagnostics) + } + } + if let options = parsed.fields["userConfig"]?.importObject { + for (name, value) in options { + guard let option = value.importObject, option["sensitive"] == .boolean(true), + let literal = option["default"], literal != .string("") + else { continue } + diagnostics.binding(parsed.fieldLocation(["userConfig", name, "default"])) + } + } // Record the actual manifest, not a raw original bundle containing credential literals. let rewrite = diagnostics.proposal.bindings.contains { $0.location.document == input.document } try NativeImportInput.resource( @@ -208,6 +267,45 @@ enum NativeContainerImport { _ = alias } + private static func inventory( + _ snapshot: SourceSnapshot, root: String, limits: SourceImportLimits + ) throws -> [LedgerEntry] { + let url = try snapshot.resource(root) + var entries: [LedgerEntry] = [] + func append(_ file: URL) throws { + guard entries.count < limits.resourceEntries else { throw ImportReadFailure.invalid } + let path = try snapshot.relativePath(file) + let relative = + path == root ? "." : root == "." ? path : String(path.dropFirst(root.count + 1)) + let info = try FileManager.default.attributesOfItem(atPath: file.path) + let kind: LedgerEntry.Kind + switch info[.type] as? FileAttributeType { + case .typeRegular: kind = .file + case .typeDirectory: kind = .directory + case .typeSymbolicLink: kind = .symlink + default: throw ImportReadFailure.invalid + } + entries.append( + .init( + path: relative, kind: kind, + link: kind == .symlink + ? try FileManager.default.destinationOfSymbolicLink(atPath: file.path) : nil, + executable: kind == .file + && ((info[.posixPermissions] as? NSNumber)?.intValue ?? 0) & 0o111 != 0, + byteCount: kind == .file ? (info[.size] as? NSNumber)?.intValue : nil)) + } + try append(url) + guard let walk = FileManager.default.enumerator(at: url, includingPropertiesForKeys: nil) else { + throw ImportReadFailure.invalid + } + for case let file as URL in walk { + try Task.checkCancellation() + try append(file) + if entries.last?.kind == .symlink { walk.skipDescendants() } + } + return entries + } + private static func componentPath(_ path: String, agent: AgentID) throws -> String { if agent == .claudeCode, !path.hasPrefix("./"), path != "." { throw CoreError.unsafePath("native component path") @@ -219,6 +317,7 @@ enum NativeContainerImport { _ value: NativeValue, field: String, parsed: NativeImportDocument, root: String, limits: SourceImportLimits, into sources: inout [(NativeValue, NativeImportDocument, [String])], + documents: inout [String: NativeImportDocument], diagnostics: inout ImportDiagnostics ) throws { if let path = value.importString { @@ -231,6 +330,7 @@ enum NativeContainerImport { .missingResource, parsed.location([field]), "Explicit native component file is absent.") return } + documents[relative] = document guard let fields = field == "lspServers" ? NativeValue.object(document.fields) : document.fields[field] @@ -249,7 +349,7 @@ enum NativeContainerImport { for entry in entries { try configurations( entry, field: field, parsed: parsed, root: root, limits: limits, into: &sources, - diagnostics: &diagnostics) + documents: &documents, diagnostics: &diagnostics) } } else if value.importObject != nil, NativeImportInput.agent(parsed.input.profile) != .cursor { sources.append((value, parsed, [field])) @@ -352,7 +452,7 @@ enum NativeContainerImport { try NativeMemberImport.read( .init(profile: input.profile, root: input.root, document: file), container: root, kind: kind, limits: limits, into: &diagnostics, admission: admission, - discoveryRoot: relative) + discoveryRoot: relative, inPlugin: true) } } } diff --git a/Sources/Components/Import/NativeExecutableMembers.swift b/Sources/Components/Import/NativeExecutableMembers.swift index fdf1a10..0eddc0e 100644 --- a/Sources/Components/Import/NativeExecutableMembers.swift +++ b/Sources/Components/Import/NativeExecutableMembers.swift @@ -134,16 +134,31 @@ extension NativeSourceImport { NativeImportInput.unconverted(servers[name]!, at: origin, into: &diagnostics) continue } - let allowed: Set = - agent == .claudeCode - ? ["command", "args", "env", "extensionToLanguage", "initializationOptions"] - : ["command", "env", "extensions", "disabled", "initialization"] - NativeImportInput.unknown(fields, allowed: allowed, at: origin, into: &diagnostics) - guard Set(fields.keys).isSubset(of: allowed) else { continue } - let executable: String + do { + _ = try NativeComponentFieldsV1.lsp( + surface: NativeImportSemantics.surface(parsed.input.profile), fields: fields, + budget: parsed.admission.parser) + } catch let issue as NativeComponentFieldIssue { + let path = issue.field.enumerated().map { index, key in + index == 0 && Int(key) != nil ? fields.keys.sorted()[Int(key)!] : key + } + NativeImportSemantics.report( + issue, at: parsed.fieldLocation(keys + [name] + path), into: &diagnostics) + continue + } + var executable: String let arguments: [String] var languages: [String: String] = [:] - var native: NativeConfiguration = [:] + let converted: Set = [ + "command", "args", "env", "extensionToLanguage", "initializationOptions", "initialization", + ] + let extras = fields.filter { !converted.contains($0.key) } + var native: NativeConfiguration = extras.isEmpty ? [:] : [agent.rawValue: extras] + var classification = ImportDiagnostics(proposal: .init(profile: parsed.input.profile)) + if NativeImportInput.sensitive(.object(extras), at: origin, into: &classification) { + diagnostics.add(.unconverted, origin, "Native LSP extras require symbolic reconstruction.") + continue + } if agent == .claudeCode { guard let command = fields["command"]?.importString, let mapping = fields["extensionToLanguage"]?.importObject, !mapping.isEmpty, @@ -163,7 +178,8 @@ extension NativeSourceImport { fields["extensions"] == nil || MCPNativeField.strings.accepts(fields["extensions"]!), fields["disabled"] == nil || MCPNativeField.boolean.accepts(fields["disabled"]!) else { - diagnostics.add(.invalidInput, origin, "Native LSP argv/extensions are malformed.") + diagnostics.add( + .unconverted, origin, "Native LSP entry has no executable declaration to convert.") continue } executable = command @@ -172,6 +188,9 @@ extension NativeSourceImport { native[agent.rawValue, default: [:]][key] = fields[key] } } + if parsed.input.profile == .claudePluginV1, executable.hasPrefix("${CLAUDE_PLUGIN_ROOT}/") { + executable = "./" + executable.dropFirst("${CLAUDE_PLUGIN_ROOT}/".count) + } guard !executable.isEmpty, !executable.contains("\0"), !executable.contains("${"), !arguments.contains(where: { $0.contains("${") || ($0.contains("://") && !ImportInput.safeLocator($0)) diff --git a/Sources/Components/Import/NativeImportInput.swift b/Sources/Components/Import/NativeImportInput.swift index 942c31c..0c873c1 100644 --- a/Sources/Components/Import/NativeImportInput.swift +++ b/Sources/Components/Import/NativeImportInput.swift @@ -47,6 +47,24 @@ struct NativeImportDocument { keys + [name], display: keys.map { "/" + $0 }.joined() + "/member[\(index)]") } + /// Structural helper paths are resolved against original syntax, with value-free ordinals. + func fieldLocation(_ keys: [String]) -> ImportLocation { + var prefix: [String] = [] + var display = "" + for key in keys { + let value = try? document.read(.init(keys: prefix))?.value + if let map = value?.importObject, let index = map.keys.sorted().firstIndex(of: key) { + display += "/member[\(index)]" + } else if case .array = value, Int(key) != nil { + display += "/" + key + } else { + return location(prefix, display: display) + } + prefix.append(key) + } + return location(keys, display: display) + } + func location(_ keys: [String] = [], display: String? = nil) -> ImportLocation { let observation = try? document.read(.init(keys: keys)) var range = observation?.valueRange ?? observation?.entryRanges.first diff --git a/Sources/Components/Import/NativeImportSemantics.swift b/Sources/Components/Import/NativeImportSemantics.swift index 83eb715..cad8b0b 100644 --- a/Sources/Components/Import/NativeImportSemantics.swift +++ b/Sources/Components/Import/NativeImportSemantics.swift @@ -1,7 +1,25 @@ import AgentsCore +import NativeDocuments /// Reuses F's finite conversion/validation rather than maintaining another native field table. enum NativeImportSemantics { + static func surface(_ profile: SourceImportProfile) -> NativeClientSurface { + switch NativeImportInput.agent(profile) { + case .claudeCode: return .claudeCode + case .codex: return .codexCLI + case .geminiCLI: return .geminiCLI + case .cursor: return .cursorEditor + case .opencode: return .openCodeCLI + } + } + + static func report( + _ issue: NativeComponentFieldIssue, at location: ImportLocation, + into diagnostics: inout ImportDiagnostics + ) { + diagnostics.add(issue.reason == .invalid ? .invalidInput : .unconverted, location, issue.detail) + } + static func mcp( name: String, transport: MCPTransportDeclaration, native: [String: NativeValue], profile: SourceImportProfile, resources: [String] diff --git a/Sources/Components/Import/NativeMemberImport.swift b/Sources/Components/Import/NativeMemberImport.swift index d3e3dc9..19789f5 100644 --- a/Sources/Components/Import/NativeMemberImport.swift +++ b/Sources/Components/Import/NativeMemberImport.swift @@ -1,5 +1,7 @@ import AgentsCore +import AgentsManifest import Foundation +import NativeDocuments /// Native file bodies share the package-owned bounded YAML/TOML readers. enum NativeMemberImport { @@ -7,7 +9,7 @@ enum NativeMemberImport { _ input: SourceImportInput, container: String, kind explicitKind: DeclaredComponentKind? = nil, limits: SourceImportLimits, into diagnostics: inout ImportDiagnostics, admission supplied: NativeImportBudget? = nil, - discoveryRoot: String? = nil + discoveryRoot: String? = nil, inPlugin: Bool = false ) throws { let admission = try supplied ?? NativeImportBudget(limits) let agent = NativeImportInput.agent(input.profile) @@ -29,6 +31,7 @@ enum NativeMemberImport { let description: String var model: String? var tools: [String]? + var native: NativeConfiguration = [:] if input.profile == .geminiCommandV1 || (!isAgent && agent == .geminiCLI) { let parsed = try NativeImportDocument( input, format: .toml, limits: limits, admission: admission) @@ -46,51 +49,70 @@ enum NativeMemberImport { body = prompt description = parsed.fields["description"]?.importString ?? "" } else { - let parsed = try ImportFrontmatter.read(bytes, document: input.document, limits: limits) + let parsed = + try agent == .cursor && !isAgent && !inPlugin + ? (header: Optional.none, body: bytes) + : ImportFrontmatter.read(bytes, document: input.document, limits: limits) guard let text = String(data: parsed.body, encoding: .utf8) else { throw ImportReadFailure.invalid } // Gemini's native agent loader trims its body; the proposal represents that loaded value. body = agent == .geminiCLI && isAgent ? text.trimmingCharacters(in: .whitespacesAndNewlines) : text - let converted: Set = - isAgent ? ["name", "description", "model", "tools"] : ["description"] - parsed.header?.unknown(converted, into: &diagnostics) - let unknown = Set(parsed.header?.pairs?.map(\.0) ?? []).subtracting(converted) - guard unknown.isEmpty else { return } + var fields: [String: NativeValue] = [:] if let header = parsed.header { origin = header.location - guard - header.validate( - strings: isAgent ? ["name", "description", "model"] : ["description"], - into: &diagnostics) - else { return } - if isAgent { - name = header["name"]?.string ?? name - model = header["model"]?.string - if let value = header["tools"] { - if let values = value.strings { - tools = values - } else if let value = value.string, agent == .claudeCode { - tools = value.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) } - } else { - diagnostics.add( - .invalidInput, value.location, - "Native tool selection cannot be represented as a string list.") - return - } - } - } + fields = try nativeValue(header).importObject! } - description = parsed.header?["description"]?.string ?? "" - if isAgent, - description.isEmpty - || ([AgentID.claudeCode, .geminiCLI].contains(agent) && parsed.header?["name"] == nil) - { + // All original frontmatter participates in preservation admission, even on refusal. + if NativeImportInput.sensitive(.object(fields), at: origin, into: &diagnostics) { diagnostics.add( - .invalidInput, origin, "Native agent requires its producer name and description.") + .unconverted, origin, + "Native frontmatter credential slots require symbolic reconstruction.") return } + if agent != .opencode { + do { + fields = try NativeComponentFieldsV1.markdown( + surface: NativeImportSemantics.surface(input.profile), + kind: isAgent ? .subagent : .command, name: fallback, fields: fields, + inPlugin: inPlugin, budget: admission.parser) + } catch let issue as NativeComponentFieldIssue { + let location = + parsed.header.flatMap { header in + issue.field.first.flatMap { field in + Int(field).flatMap { + header.pairs?.indices.contains($0) == true + ? header.pairs?.sorted { $0.0 < $1.0 }[$0].1 : nil + } + ?? header[field] + } + }?.location ?? origin + NativeImportSemantics.report(issue, at: location, into: &diagnostics) + return + } + } else { + let converted: Set = + isAgent ? ["name", "description", "model", "tools"] : ["description"] + NativeImportInput.unknown(fields, allowed: converted, at: origin, into: &diagnostics) + guard Set(fields.keys).isSubset(of: converted) else { return } + } + name = fields["name"]?.importString ?? name + model = fields["model"]?.importString + if let value = fields["tools"] { + if let values = value.importStrings { + tools = values + } else if let text = value.importString, agent == .claudeCode { + tools = text.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) } + } else { + throw ImportReadFailure.invalid + } + } + description = fields["description"]?.importString ?? "" + let converted: Set = + isAgent ? ["name", "description", "model", "tools"] : ["description"] + let extras = fields.filter { !converted.contains($0.key) } + if !extras.isEmpty { native[agent.rawValue] = extras } if !isAgent, agent == .claudeCode, body.contains("$ARGUMENTS") || body.range(of: #"\$[0-9]+"#, options: .regularExpression) != nil @@ -115,12 +137,15 @@ enum NativeMemberImport { NativeImportInput.emit( .subagent( name: name, description: description, prompt: .literal(body), - model: model, tools: tools, agents: [agent]), selector: .subagent(name: name), + model: model, tools: tools, agents: [agent], native: native), + selector: .subagent(name: name), origin: origin, container: container, profile: input.profile, into: &diagnostics, admission: admission) } else { NativeImportInput.emit( - .command(name: name, description: description, prompt: .literal(body), agents: [agent]), + .command( + name: name, description: description, prompt: .literal(body), agents: [agent], + native: native), selector: .command(name: name), origin: origin, container: container, profile: input.profile, into: &diagnostics, admission: admission) } @@ -130,4 +155,23 @@ enum NativeMemberImport { relative, root: container, input: input, origin: origin, limits: limits, into: &diagnostics, admission: admission) } + + private static func nativeValue(_ yaml: ImportYAML) throws -> NativeValue { + if let pairs = yaml.pairs { + return .object( + try pairs.map { ($0.0, try nativeValue($0.1)) }.reduce(into: [:]) { $0[$1.0] = $1.1 }) + } + if let items = yaml.items { return .array(try items.map { try nativeValue($0) }) } + if let text = yaml.string { return .string(text) } + if let value = yaml.boolean { return .boolean(value) } + if let value = yaml.integer { return .integer(value) } + if let scalar = yaml.node.scalar { + if scalar.decimalTag || YAMLScalar.classify(scalar.text) == .decimal { + // Decimal spelling stays private until the finite field validator admits its domain. + return .decimal(scalar.text) + } + if YAMLScalar.classify(scalar.text) == .null { return .null } + } + throw ImportLocatedFailure(location: yaml.location) + } } diff --git a/Tests/ComponentsTests/ImportNativeTests.swift b/Tests/ComponentsTests/ImportNativeTests.swift index e9b8987..79c0c7f 100644 --- a/Tests/ComponentsTests/ImportNativeTests.swift +++ b/Tests/ComponentsTests/ImportNativeTests.swift @@ -358,7 +358,8 @@ struct ImportNativeTests { #"{"name":"bundle","mcpServers":{"mcp":{"command":"./server"}},"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"./server"}]}]}}"# ) try fixture.write( - ".lsp.json", #"{"lsp":{"command":"./server","extensionToLanguage":{".x":"x"}}}"#) + ".lsp.json", + #"{"lsp":{"command":"${CLAUDE_PLUGIN_ROOT}/server","extensionToLanguage":{".x":"x"}}}"#) try fixture.write("server", "#!/bin/sh\nexit 0\n", executable: true) let before = try fixture.hash() let result = try SourceImport.preview( @@ -479,6 +480,196 @@ struct ImportNativeTests { #expect(try SourceImport.preview(narrow).components.count == 1) } + @Test func sharedMarkdownFieldsKeepNativeIntentAndActualRegistrationContext() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "auditor.md", + "---\nname: auditor\ndescription: Inspect source\npermissionMode: plan\nmaxTurns: 3\n---\nInspect carefully.\n" + ) + let standalone = try SourceImport.preview(fixture.input(.claudeAgentV1, "auditor.md")) + guard case .subagent(_, _, _, _, _, _, _, let native) = standalone.components.first?.declaration + else { + Issue.record("Expected standalone agent") + return + } + #expect(native[AgentID.claudeCode.rawValue]?["permissionMode"] == .string("plan")) + #expect(native[AgentID.claudeCode.rawValue]?["maxTurns"] == .integer(3)) + try fixture.write("bundle/.claude-plugin/plugin.json", #"{"name":"bundle"}"#) + try fixture.write( + "bundle/agents/auditor.md", + "---\nname: auditor\ndescription: Inspect source\npermissionMode: plan\n---\nInspect.\n") + let plugin = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(!plugin.components.contains { $0.declaration.kind == .subagent }) + #expect( + plugin.diagnostics.contains { + $0.code == .unconverted && $0.location.document == "bundle/agents/auditor.md" + && $0.location.span?.line == 4 + }) + try fixture.write( + "review.md", + "---\ncontext: fork\nagent: auditor\nbackground: true\nmodel: sonnet\n---\nReview.\n") + let command = try SourceImport.preview(fixture.input(.claudeCommandV1, "review.md")) + guard case .command(_, _, _, _, _, _, let fields) = command.components.first?.declaration else { + Issue.record("Expected native command") + return + } + #expect(fields[AgentID.claudeCode.rawValue]?["context"] == .string("fork")) + #expect(fields[AgentID.claudeCode.rawValue]?["model"] == .string("sonnet")) + try fixture.write("review.md", "---\nbackground: true\n---\nReview.\n") + let refused = try SourceImport.preview(fixture.input(.claudeCommandV1, "review.md")) + #expect(refused.components.isEmpty) + #expect( + refused.diagnostics.contains { $0.code == .unconverted && $0.location.span?.line == 2 }) + try fixture.write( + "review.md", "---\nzzzUnknown: value\ndescription: Review\naaaUnknown: value\n---\nReview.\n") + let unknown = try SourceImport.preview(fixture.input(.claudeCommandV1, "review.md")) + #expect(unknown.components.isEmpty) + #expect(unknown.diagnostics.contains { $0.code == .unconverted && $0.location.span?.line == 4 }) + try fixture.write("review.md", "---\nzzz: 3.5\ndescription: Review\n---\nReview.\n") + let decimalUnknown = try SourceImport.preview(fixture.input(.claudeCommandV1, "review.md")) + #expect(decimalUnknown.components.isEmpty) + #expect( + decimalUnknown.diagnostics.contains { $0.code == .unconverted && $0.location.span?.line == 2 } + ) + let cursorBody = "---\nnot-frontmatter: [this is prompt text\n---\nKeep all bytes.\n" + try fixture.write("review.md", cursorBody) + let cursor = try SourceImport.preview(fixture.input(.cursorCommandV1, "review.md")) + guard case .command(_, _, .literal(let body), _, _, _, _) = cursor.components.first?.declaration + else { + Issue.record("Expected plain Cursor prompt") + return + } + #expect(body == cursorBody) + } + + @Test func sharedLSPFieldsPreserveExtrasBindingsAndRefuseAbsentPrograms() throws { + let fixture = try NativeImportFixture() + try fixture.write("bundle/.claude-plugin/plugin.json", #"{"name":"bundle"}"#) + try fixture.write( + "bundle/.lsp.json", + #"{"source":{"command":"${CLAUDE_PLUGIN_ROOT}/server","extensionToLanguage":{".s":"source"},"transport":"socket","workspaceFolder":"workspace","requestTimeout":4,"settings":{"nested":[true,7]},"initializationOptions":{"feature":true},"env":{"TOKEN":"SHARED_SECRET_CANARY"}}}"# + ) + try fixture.write("bundle/server", "#!/bin/sh\nexit 0\n", executable: true) + let before = try fixture.hash() + let result = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + guard + case .lspServer(_, let run, _, let options, _, _, let native) = result.components.first? + .declaration + else { + Issue.record("Expected native LSP") + return + } + #expect(run.executable == "./server") + #expect(run.workingDirectory == nil) + #expect(options == ["feature": .boolean(true)]) + #expect(native[AgentID.claudeCode.rawValue]?["workspaceFolder"] == .string("workspace")) + #expect( + native[AgentID.claudeCode.rawValue]?["settings"] + == .object(["nested": .array([.boolean(true), .integer(7)])])) + #expect(!String(reflecting: result).contains("SHARED_SECRET_CANARY")) + #expect( + result.resources.contains { + $0.path == ".lsp.json" && $0.requiresBindingRewrite && $0.observedHash == nil + }) + #expect(try fixture.hash() == before) + try fixture.write( + "opencode.json", + #"{"lsp":{"builtin":{"disabled":true},"empty":{"command":[]},"valid":{"command":["source-lsp"],"initialization":{"feature":true}}}}"# + ) + let open = try SourceImport.preview(fixture.input(.openCodeConfigV2, "opencode.json")) + #expect(open.components.map(\.member?.selector) == [.lspServer(name: "valid")]) + #expect(open.diagnostics.filter { $0.code == .unconverted }.count == 2) + try fixture.write( + "bundle/.lsp.json", + #"{"source":{"command":"server","extensionToLanguage":{".s":"source"},"requestTimeout":0}}"#) + let invalid = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(invalid.components.isEmpty) + #expect( + invalid.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == "bundle/.lsp.json" + && $0.location.span != nil + }) + } + + @Test func sharedPluginDefaultsReplaceClaudeCommandsAgentsAndValidateRealDocuments() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"bundle","commands":"./chosen/review.md","agents":"./chosen/auditor.md"}"#) + try fixture.write("bundle/commands/ignored.md", "Ignored default\n") + try fixture.write( + "bundle/agents/ignored.md", "---\nname: ignored\ndescription: Ignored\n---\nIgnored default\n" + ) + try fixture.write("bundle/chosen/review.md", "Chosen command\n") + try fixture.write( + "bundle/chosen/auditor.md", "---\nname: auditor\ndescription: Inspect\n---\nChosen agent\n") + try fixture.write("bundle/hooks/hooks.json", #"{"hooks":{"invented":[]}}"#) + let input = fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json") + let invalidDefault = try SourceImport.preview(input) + #expect( + invalidDefault.components.map(\.member?.selector) == [ + .command(name: "review"), .subagent(name: "auditor"), + ]) + #expect( + invalidDefault.diagnostics.contains { + $0.code == .unconverted && $0.location.document == "bundle/hooks/hooks.json" + }) + try fixture.write("bundle/hooks/hooks.json", #"{"hooks":{}}"#) + let valid = try SourceImport.preview(input) + #expect(valid.diagnostics.isEmpty) + try fixture.write( + "bundle/.claude-plugin/plugin.json", #"{"name":"bundle","agents":"./chosen"}"#) + let wrongKind = try SourceImport.preview(input) + #expect( + wrongKind.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == input.document + }) + } + + @Test func nativeSensitiveDefaultsRequireBindingsBeforeManifestPreservation() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"bundle","userConfig":{"access":{"type":"string","title":"Access","description":"Local binding","sensitive":true,"default":"USER_CONFIG_SECRET_CANARY"}}}"# + ) + let result = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(!result.bindings.isEmpty) + #expect(!String(reflecting: result).contains("USER_CONFIG_SECRET_CANARY")) + #expect( + result.resources.contains { + $0.path == ".claude-plugin/plugin.json" && $0.requiresBindingRewrite + && $0.observedHash == nil + }) + } + + @Test func multiplePluginConfigurationInputsDoNotInventAnErrorDocument() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"bundle","mcpServers":["./first.json","./second.json"]}"#) + try fixture.write("bundle/first.json", #"{"mcpServers":{"same":{"command":"tool"}}}"#) + try fixture.write("bundle/second.json", #"{"mcpServers":{"same":{"command":17}}}"#) + let result = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(result.components.isEmpty) + #expect( + result.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == "bundle/second.json" + }) + #expect( + !result.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == "bundle/first.json" + }) + #expect( + result.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == "bundle/.claude-plugin/plugin.json" + }) + } + @Test func typedMembersStayStableWhenCallerMovesTheInputRoot() throws { let one = try NativeImportFixture() let two = try NativeImportFixture() From cb32cd4a453d0d71c80c047d6b4248120480857a Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:10:28 +0800 Subject: [PATCH 102/171] feat: expose configuration initialization and watch operations --- Documentation/Architecture/Updates.md | 29 ++ Sources/AgentsCore/WatchOperations.swift | 274 +++++++++++++++--- .../InstructionInitialization.swift | 50 ++++ .../InstructionOperations.swift | 37 +-- .../AgentsSkills/SkillInitialization.swift | 78 +++++ Sources/AgentsSkills/SkillOperations.swift | 26 +- .../AgentsUpdates/ComponentDiscovery.swift | 3 +- .../InitializationOperations.swift | 96 ++++++ .../AgentsUpdates/InstructionOperations.swift | 47 ++- Sources/AgentsUpdates/ScopeInspection.swift | 12 +- Sources/AgentsUpdates/UpdateCompletion.swift | 37 ++- Sources/AgentsUpdates/UpdateModels.swift | 3 + Sources/AgentsUpdates/UpdatePlan.swift | 17 ++ .../AgentsUpdates/UpdateReadLocations.swift | 58 ++++ Sources/AgentsUpdates/WatchCompletion.swift | 20 ++ .../InitializationIntegrationTests.swift | 142 +++++++++ .../ReadFootprintIntegrationTests.swift | 62 ++++ .../WatchConfirmationTests.swift | 114 ++++++++ 18 files changed, 998 insertions(+), 107 deletions(-) create mode 100644 Sources/AgentsInstructions/InstructionInitialization.swift create mode 100644 Sources/AgentsSkills/SkillInitialization.swift create mode 100644 Sources/AgentsUpdates/InitializationOperations.swift create mode 100644 Sources/AgentsUpdates/UpdateReadLocations.swift create mode 100644 Sources/AgentsUpdates/WatchCompletion.swift create mode 100644 Tests/AgentsUpdatesTests/InitializationIntegrationTests.swift create mode 100644 Tests/AgentsUpdatesTests/ReadFootprintIntegrationTests.swift create mode 100644 Tests/AgentsUpdatesTests/WatchConfirmationTests.swift diff --git a/Documentation/Architecture/Updates.md b/Documentation/Architecture/Updates.md index cf48269..e70ccae 100644 --- a/Documentation/Architecture/Updates.md +++ b/Documentation/Architecture/Updates.md @@ -197,6 +197,35 @@ operation's result, refresh a changed candidate and reprepare for confirmation. Agents CLI restores the full scope once with `UpdateOperations.restore`; domain consumers continue using their restricted lifecycle methods. +`CombinedUpdateReport.readLocations`, discovery and scope inspection expose durable +state, source, own-instruction, resource and deployment inputs, including absent +leaves introduced by an unsaved declaration. `inspectOwnInstructions` and +`inspectChatGPTExport` pair their results with their owner-computed read locations. +Export reads the consumer appendix at export time; an absent appendix is allowed +while installing, but must exist when explicitly exported. + +Initialization uses a pure `describeInstructionsInitialization` or +`describeProjectSkillInitialization` and then `UpdateOperations.initialize`. +The immutable description contains the exact file/template and captured existing +project identity. `describeSkillInitialization(directory:)` is explicit standalone +authoring and can select a new direct child of an existing parent. Apply holds +that observed root through the lower domain's sole transaction. Registered roots +removed or replaced after description are never recreated. Existing URL-returning +initializers use the same lower writer; consumers needing terminal evidence use +the description/completion API. A committed operation with pending cleanup stays +committed; durable rollback stays rolled back even with pending cleanup. Earlier +recovery failure has unchanged current disposition and pending recovery evidence. +No executing resource or borrowed descriptor outlives the synchronous return. + +`WatchOperations.previewAdd` and `previewRemove` produce immutable confirmation +requests with a stable fingerprint, selected source/content and read locations. +Add resolves Git in disposable storage or uses the existing verified index reader; +preview never retains content, changes scope files or recovers. `apply(preview)` +revalidates scope state and exact content in the existing subscription writer. +`UpdateOperations.performWatch(preview)` returns that writer's outer +`UpdateCompletion` without nesting a transaction. Subscriptions do +not deploy native targets or skills. + Watch consumers can pass a displayed `WatchStatus` to `WatchOperations.seen`. The existing writer revalidates both normalized source identity and the exact Git commit or artifact digest map before retention and watch-state publication. A diff --git a/Sources/AgentsCore/WatchOperations.swift b/Sources/AgentsCore/WatchOperations.swift index 573aca1..766c2fe 100644 --- a/Sources/AgentsCore/WatchOperations.swift +++ b/Sources/AgentsCore/WatchOperations.swift @@ -27,46 +27,36 @@ public struct WatchOperations: Sendable { _ source: String, alias: String? = nil, requirement: SourceRequirement? = nil, path: String? = nil, scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> WatchChange { + try add( + source, alias: alias, requirement: requirement, path: path, scope: scope, + environment: environment, expected: nil, outcome: TransactionOutcome()) + } + + private func add( + _ source: String, alias: String?, requirement: SourceRequirement?, path: String?, + scope: InstallScope, environment: RuntimeEnvironment, expected: WatchMutationPreview?, + outcome: TransactionOutcome ) throws -> WatchChange { let store = StateStore(scope: scope, environment: environment) - return try store.withLock(checkpoint: checkpoint) { + return try store.withLock(checkpoint: checkpoint, outcome: outcome) { let baseline = try StatePrecondition(store: store) let previous = try declarations.read(store, baseline) - var declaration = previous let lock = try store.readLedger(prepared: baseline) var watch = try store.readWatch(prepared: baseline) - var argument = try SourceArgument(source) - guard argument.name == nil else { - throw CoreError.invalidSource("@skill: selects skills; watch subscribes to whole sources") - } - if declaration.sources[argument.location] == nil, - let alias = try declaration.sources.keys.sorted().first(where: { - try declaration.sources[$0]?.identity(environment: environment) == argument.location - }) - { - argument.location = alias - } - let selection = try argument.selection( - in: declaration, requirement: requirement, path: path, environment: environment) - let parsed = selection.source - let id = try parsed.identity(environment: environment) - let existing = try declaration.sources.keys.sorted().first { - try declaration.sources[$0]?.identity(environment: environment) == id + let planned = try planAdd( + source, alias: alias, requirement: requirement, path: path, + declaration: previous, store: store, baseline: baseline) + let (name, id, declared, change) = (planned.alias, planned.id, planned.source, planned.change) + if let expected { + try requireFingerprint( + expected, baseline: baseline, change: change, seen: expected.seen, store: store, + alias: name, sourceID: id, removing: false) } - let name = alias ?? existing ?? declaration.derivedAlias(for: parsed.location) - if let current = declaration.sources[name], - try current.identity(environment: environment) != id - { - throw CoreError.invalidSource("source alias already refers to another source: \(name)") - } - let declared = selection.applied(to: existing.flatMap { declaration.sources[$0] } ?? parsed) - declaration.sources[name] = declared - declaration.watch = Array(Set((declaration.watch ?? []) + [name])).sorted() - try declaration.validate(environment: environment) - let change = try declarations.plan(store, previous, declaration, baseline) - let current = try acknowledge(declared, revision: nil, store: store) + let current = try acknowledge(declared, revision: nil, expected: expected?.seen, store: store) watch.sources[id] = WatchSourceState(seen: current) - try commit(change, watch: watch, lock: lock, store: store, baseline: baseline) + try commit( + change, watch: watch, lock: lock, store: store, baseline: baseline, outcome: outcome) return WatchChange(alias: name, sourceID: id, seen: current) } } @@ -150,9 +140,17 @@ public struct WatchOperations: Sendable { public func remove( _ source: String, scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> WatchChange { + try remove( + source, scope: scope, environment: environment, expected: nil, outcome: TransactionOutcome()) + } + + private func remove( + _ source: String, scope: InstallScope, environment: RuntimeEnvironment, + expected: WatchMutationPreview?, outcome: TransactionOutcome ) throws -> WatchChange { let store = StateStore(scope: scope, environment: environment) - return try store.withLock(checkpoint: checkpoint) { + return try store.withLock(checkpoint: checkpoint, outcome: outcome) { let baseline = try StatePrecondition(store: store) let previous = try declarations.read(store, baseline) var declaration = previous @@ -163,11 +161,200 @@ public struct WatchOperations: Sendable { declaration.watch?.removeAll { $0 == alias } watch.sources.removeValue(forKey: id) let change = try declarations.plan(store, previous, declaration, baseline) - try commit(change, watch: watch, lock: lock, store: store, baseline: baseline) + if let expected { + try requireFingerprint( + expected, baseline: baseline, change: change, seen: nil, store: store, alias: alias, + sourceID: id, removing: true) + } + try commit( + change, watch: watch, lock: lock, store: store, baseline: baseline, outcome: outcome) return WatchChange(alias: alias, sourceID: id, seen: nil) } } + /// Resolves acknowledgment in disposable storage without retaining refs or recovering the scope. + public func previewAdd( + _ source: String, alias: String? = nil, requirement: SourceRequirement? = nil, + path: String? = nil, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> WatchMutationPreview { + let store = StateStore(scope: scope, environment: environment) + return try store.withReadLock { + let baseline = try StatePrecondition(store: store) + let previous = try declarations.read(store, baseline) + _ = try store.readLedger(prepared: baseline) + _ = try store.readWatch(prepared: baseline) + let planned = try planAdd( + source, alias: alias, requirement: requirement, path: path, + declaration: previous, store: store, baseline: baseline) + let seen = try observe(planned.source, store: store) + let fingerprint = try mutationFingerprint( + baseline: baseline, change: planned.change, seen: seen, store: store, alias: planned.alias, + sourceID: planned.id, removing: false) + try baseline.validate() + return WatchMutationPreview( + action: .add(source, alias, requirement, path), store: store, + alias: planned.alias, sourceID: planned.id, seen: seen, displayedFingerprint: fingerprint, + readLocations: mutationReadLocations(store, source: planned.source)) + } + } + + public func previewRemove( + _ source: String, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> WatchMutationPreview { + let store = StateStore(scope: scope, environment: environment) + return try store.withReadLock { + let baseline = try StatePrecondition(store: store) + let previous = try declarations.read(store, baseline) + var declaration = previous + _ = try store.readLedger(prepared: baseline) + _ = try store.readWatch(prepared: baseline) + let alias = try subscription(source, declaration: declaration, environment: environment) + let selected = declaration.sources[alias]! + let id = try selected.identity(environment: environment) + declaration.watch?.removeAll { $0 == alias } + let change = try declarations.plan(store, previous, declaration, baseline) + let fingerprint = try mutationFingerprint( + baseline: baseline, change: change, seen: nil, store: store, alias: alias, sourceID: id, + removing: true) + try baseline.validate() + return WatchMutationPreview( + action: .remove(source), store: store, + alias: alias, sourceID: id, seen: nil, displayedFingerprint: fingerprint, + readLocations: mutationReadLocations(store, source: selected)) + } + } + + /// Revalidates exactly the displayed subscription mutation inside its sole scope writer. + @discardableResult + public func apply(_ preview: WatchMutationPreview) throws -> WatchChange { + try apply(preview, outcome: TransactionOutcome()) + } + + package func apply(_ preview: WatchMutationPreview, outcome: TransactionOutcome) throws + -> WatchChange + { + switch preview.action { + case .add(let source, let alias, let requirement, let path): + return try add( + source, alias: alias, requirement: requirement, path: path, + scope: preview.store.scope, environment: preview.store.environment, expected: preview, + outcome: outcome) + case .remove(let source): + return try remove( + source, scope: preview.store.scope, environment: preview.store.environment, + expected: preview, outcome: outcome) + } + } + + private func mutationReadLocations(_ store: StateStore, source: SourceDeclaration) -> [URL] { + [store.declarationURL, store.resolvedURL, store.watchURL] + + (source.kind == .local ? [source.localURL(environment: store.environment)] : []) + } + + private func mutationFingerprint( + baseline: StatePrecondition, change: DeclarationChange?, + seen: WatchSeen?, store: StateStore, alias: String, sourceID: String, removing: Bool + ) throws -> String { + struct Evidence: Encodable { + let scope: InstallScope + let alias: String + let sourceID: String + let removing: Bool + let state: [String?] + let declaration: String? + let seen: WatchSeen? + } + return try ResolvedLedgerCodec.digest( + Evidence( + scope: store.scope, alias: alias, sourceID: sourceID, removing: removing, + state: [store.declarationURL, store.resolvedURL, store.watchURL].map { + try baseline.bytes(for: $0).map { FileHash.sha256Hex(data: $0) } + }, declaration: change.map { FileHash.sha256Hex(data: $0.bytes) }, seen: seen)) + } + + private func requireFingerprint( + _ preview: WatchMutationPreview, baseline: StatePrecondition, + change: DeclarationChange?, seen: WatchSeen?, store: StateStore, alias: String, + sourceID: String, removing: Bool + ) throws { + guard + try mutationFingerprint( + baseline: baseline, change: change, seen: seen, store: store, alias: alias, + sourceID: sourceID, removing: removing) == preview.displayedFingerprint + else { + throw CoreError.invalidState("subscription changed; refresh before confirming") + } + } + + private func observe(_ source: SourceDeclaration, store: StateStore) throws -> WatchSeen { + if source.kind == .wellKnown { + return .artifacts( + Dictionary( + uniqueKeysWithValues: try artifacts(source).map { ($0.name, $0.artifact.digest) })) + } + let temporary = FileManager.default.temporaryDirectory.appendingPathComponent( + "agents-watch-preview-" + UUID().uuidString) + try FileSystem.createDirectory(at: temporary) + defer { try? FileManager.default.removeItem(at: temporary) } + var source = source + if source.kind == .local { + source.location = source.localURL(environment: store.environment).path + } + let environment = RuntimeEnvironment( + projectDirectory: temporary, homeDirectory: temporary, + environment: store.environment.environment) + return .revision( + try SourceCache(store: StateStore(scope: .project, environment: environment)).watchRevision( + source)) + } + + private struct AddPlan { + let alias: String + let id: String + let source: SourceDeclaration + let change: DeclarationChange? + } + + private func planAdd( + _ source: String, alias: String?, requirement: SourceRequirement?, path: String?, + declaration previous: Declaration, store: StateStore, baseline: StatePrecondition + ) throws -> AddPlan { + let environment = store.environment + var declaration = previous + var argument = try SourceArgument(source) + guard argument.name == nil else { + throw CoreError.invalidSource("@skill: selects skills; watch subscribes to whole sources") + } + if declaration.sources[argument.location] == nil, + let alias = try declaration.sources.keys.sorted().first(where: { + try declaration.sources[$0]?.identity(environment: environment) == argument.location + }) + { + argument.location = alias + } + let selection = try argument.selection( + in: declaration, requirement: requirement, path: path, environment: environment) + let parsed = selection.source + let id = try parsed.identity(environment: environment) + let existing = try declaration.sources.keys.sorted().first { + try declaration.sources[$0]?.identity(environment: environment) == id + } + let name = alias ?? existing ?? declaration.derivedAlias(for: parsed.location) + if let current = declaration.sources[name], + try current.identity(environment: environment) != id + { + throw CoreError.invalidSource("source alias already refers to another source: \(name)") + } + let declared = selection.applied(to: existing.flatMap { declaration.sources[$0] } ?? parsed) + declaration.sources[name] = declared + declaration.watch = Array(Set((declaration.watch ?? []) + [name])).sorted() + try declaration.validate(environment: environment) + let change = try declarations.plan(store, previous, declaration, baseline) + return AddPlan(alias: name, id: id, source: declared, change: change) + } + private func sourceDeclaration( _ input: String, declaration: Declaration, environment: RuntimeEnvironment ) throws -> SourceDeclaration { @@ -201,10 +388,10 @@ public struct WatchOperations: Sendable { /// preimage evidence and also guards the lock that pruning follows. private func commit( _ change: DeclarationChange?, watch: WatchState, lock: ResolvedLedger, store: StateStore, - baseline: StatePrecondition + baseline: StatePrecondition, outcome: TransactionOutcome = TransactionOutcome() ) throws { try watch.validate() - let transaction = FileTransaction(store: store, checkpoint: checkpoint) + let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) transaction.requireUnchanged(since: baseline) try store.stageDeclaration(change, in: transaction, prepared: baseline) try transaction.replace( @@ -462,3 +649,18 @@ private struct WatchUnit: Equatable { } } } + +/// Immutable subscription confirmation; no locks or borrowed resources escape preview. +public struct WatchMutationPreview: Sendable { + fileprivate enum Action: Sendable { + case add(String, String?, SourceRequirement?, String?) + case remove(String) + } + fileprivate let action: Action + package let store: StateStore + public let alias: String + public let sourceID: String + public let seen: WatchSeen? + public let displayedFingerprint: String + public let readLocations: [URL] +} diff --git a/Sources/AgentsInstructions/InstructionInitialization.swift b/Sources/AgentsInstructions/InstructionInitialization.swift new file mode 100644 index 0000000..7dda8a8 --- /dev/null +++ b/Sources/AgentsInstructions/InstructionInitialization.swift @@ -0,0 +1,50 @@ +import AgentsCore +import Foundation + +package struct InstructionInitialization: Sendable { + package let store: StateStore + package let root: ExistingProjectRoot + package let file: URL + package let template: Data + + package init(named name: String, environment: RuntimeEnvironment, validateState: Bool = true) + throws + { + guard Declaration.isInstructionName(name), !name.contains("/") else { + throw CoreError.invalidSource( + "instruction names use lowercase letters, digits and hyphens: \(name)") + } + store = StateStore(scope: .project, environment: environment) + root = try store.captureExistingProjectRoot() + file = root.directory.resolvingSymlinksInPath() + .appendingPathComponent(InstructionSources.ownContainer).appendingPathComponent(name + ".md") + template = Data( + "---\ndescription: Describe what these instructions make the agent do.\n---\n# \(name)\n\nWrite the instructions here.\n" + .utf8) + _ = try Instructions.validateSource(template, id: name) + if validateState { + try store.withReadLock { + _ = try store.declarationBytes() + guard try InstructionTargets.read(file) == nil else { + throw CoreError.invalidSource("instruction file already exists: \(file.path)") + } + } + } + } + + package func apply(outcome: TransactionOutcome, checkpoint: @escaping (String) throws -> Void) + throws -> URL + { + try store.withLock(checkpoint: checkpoint, outcome: outcome, existingRoot: root) { + _ = try store.declarationBytes() + let evidence = try TargetPrecondition(file) + guard try InstructionTargets.read(file) == nil else { + throw CoreError.invalidSource("instruction file already exists: \(file.path)") + } + let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) + try transaction.replace(file, with: .data(template), expecting: evidence) + try transaction.commit() + return file + } + } +} diff --git a/Sources/AgentsInstructions/InstructionOperations.swift b/Sources/AgentsInstructions/InstructionOperations.swift index d528877..a98ccc8 100644 --- a/Sources/AgentsInstructions/InstructionOperations.swift +++ b/Sources/AgentsInstructions/InstructionOperations.swift @@ -31,33 +31,13 @@ public enum InstructionOperations { } /// Creates the project's own `.agent/instructions/.md` with the required front matter, - /// without replacing an existing entry or creating a declaration or lock. + /// without replacing an existing entry or creating a declaration or resolved ledger. @discardableResult 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 store = StateStore(scope: .project, environment: environment) - return try store.withLock { - _ = try store.declarationBytes() - 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)") - } - 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, with: .data(bytes)) - try transaction.commit() - return file - } + try InstructionInitialization(named: name, environment: environment, validateState: false) + .apply(outcome: TransactionOutcome(), checkpoint: { _ in }) } static func operate( @@ -107,3 +87,14 @@ extension InstructionOperations { } } } + +extension InstructionOperations { + /// Includes the absent own container and explicitly selected leaves for file-event invalidation. + package static func ownReadLocations(names: [String] = [], environment: RuntimeEnvironment) + -> [URL] + { + let directory = environment.projectDirectory.resolvingSymlinksInPath() + .appendingPathComponent(InstructionSources.ownContainer) + return [directory] + names.map { directory.appendingPathComponent($0 + ".md") } + } +} diff --git a/Sources/AgentsSkills/SkillInitialization.swift b/Sources/AgentsSkills/SkillInitialization.swift new file mode 100644 index 0000000..25ed8f9 --- /dev/null +++ b/Sources/AgentsSkills/SkillInitialization.swift @@ -0,0 +1,78 @@ +import AgentsCore +import Foundation + +package struct SkillInitialization: Sendable { + package let store: StateStore + package let root: ExistingProjectRoot + package let file: URL + private let resultDirectory: URL + package let template: Data + private let name: String? + private let selectedChild: String? + + package init( + named requestedName: String?, directory: URL, environment: RuntimeEnvironment, + requiresExistingDirectory: Bool = false, validateState: Bool = true + ) throws { + let directory = directory.standardizedFileURL + let canonicalName = requestedName.map(PathSafety.sanitizeName) + resultDirectory = canonicalName.map { directory.appendingPathComponent($0) } ?? directory + var environment = environment + if requiresExistingDirectory || FileManager.default.fileExists(atPath: directory.path) { + environment.projectDirectory = directory + name = canonicalName + selectedChild = nil + } else { + guard canonicalName == nil else { + throw CoreError.unsupported( + "initializing a named skill below a new directory requires admission of both creating levels" + ) + } + environment.projectDirectory = directory.deletingLastPathComponent() + name = nil + selectedChild = directory.lastPathComponent + } + store = StateStore(scope: .project, environment: environment) + root = try store.captureExistingProjectRoot() + let observedDirectory = root.directory.resolvingSymlinksInPath() + file = + (selectedChild ?? name).map { observedDirectory.appendingPathComponent($0) } + .map { $0.appendingPathComponent("SKILL.md") } + ?? root.directory.resolvingSymlinksInPath().appendingPathComponent("SKILL.md") + let title = canonicalName ?? PathSafety.sanitizeName(directory.lastPathComponent) + template = Data( + "---\nname: \(title)\ndescription: Describe when to use this skill\n---\n\n# \(title)\n\nWrite the skill instructions here.\n" + .utf8) + if validateState { + try store.withReadLock { + let target = + try selectedChild.map { try store.skillInitializationTarget(inChildDirectory: $0) } + ?? store.skillInitializationTarget(named: name) + guard target.file == file else { + throw CoreError.invalidState("skill initialization target changed") + } + _ = try store.declarationBytes() + _ = try store.readLedger() + } + } + } + + package func apply(outcome: TransactionOutcome, checkpoint: @escaping (String) throws -> Void) + throws -> URL + { + try store.withLock(checkpoint: checkpoint, outcome: outcome, existingRoot: root) { + _ = try store.declarationBytes() + _ = try store.readLedger() + let target = + try selectedChild.map { try store.skillInitializationTarget(inChildDirectory: $0) } + ?? store.skillInitializationTarget(named: name) + guard target.file == file else { + throw CoreError.invalidState("skill initialization target changed") + } + let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) + try transaction.initializeSkill(target, bytes: template) + try transaction.commit() + return resultDirectory + } + } +} diff --git a/Sources/AgentsSkills/SkillOperations.swift b/Sources/AgentsSkills/SkillOperations.swift index 1093a4e..f1cc26e 100644 --- a/Sources/AgentsSkills/SkillOperations.swift +++ b/Sources/AgentsSkills/SkillOperations.swift @@ -197,28 +197,10 @@ public enum SkillOperations { } public static func initializeSkill(named name: String?, directory: URL) throws -> URL { - let store = StateStore( - scope: .project, environment: RuntimeEnvironment(projectDirectory: directory)) - return try store.withLock(createIfMissing: false) { - _ = try store.readDeclaration() - _ = try store.readResolved() - let name = name.map(PathSafety.sanitizeName) - let root = name.map { directory.appendingPathComponent($0) } ?? directory - let file = root.appendingPathComponent("SKILL.md") - if FileManager.default.fileExists(atPath: file.path) { - try FileSystem.requireWritableFile(at: file) - throw CoreError.invalidSkill("SKILL.md already exists at \(file.path)") - } - try FileSystem.createDirectory(at: root) - let title = name ?? PathSafety.sanitizeName(root.lastPathComponent) - try FileSystem.withAccessErrors(at: file) { - try - "---\nname: \(title)\ndescription: Describe when to use this skill\n---\n\n# \(title)\n\nWrite the skill instructions here.\n" - .write(to: file, atomically: true, encoding: .utf8) - } - try FileSystem.requireWritableFile(at: file) - return root - } + try SkillInitialization( + named: name, directory: directory, environment: RuntimeEnvironment(), validateState: false + ) + .apply(outcome: TransactionOutcome(), checkpoint: { _ in }) } } diff --git a/Sources/AgentsUpdates/ComponentDiscovery.swift b/Sources/AgentsUpdates/ComponentDiscovery.swift index 3589be0..1cf95bf 100644 --- a/Sources/AgentsUpdates/ComponentDiscovery.swift +++ b/Sources/AgentsUpdates/ComponentDiscovery.swift @@ -71,7 +71,8 @@ extension UpdateOperations { ledger, roots: store.ledgerRoots, generation: ResolvedLedgerCodec.digest(ledger)) var revisions: [String: [String]] = [:] - var locations = [store.declarationURL, store.resolvedURL, store.watchURL] + var locations = try readLocations( + declarations: [previous, declaration], ledgers: [ledger], store: store) for id in ledger.sources.keys.sorted() { let identity = try ledger.sourceIdentity(id, roots: store.ledgerRoots) revisions[identity, default: []].append(ledger.sources[id]!.revision) diff --git a/Sources/AgentsUpdates/InitializationOperations.swift b/Sources/AgentsUpdates/InitializationOperations.swift new file mode 100644 index 0000000..6cc74f8 --- /dev/null +++ b/Sources/AgentsUpdates/InitializationOperations.swift @@ -0,0 +1,96 @@ +import AgentsCore +import AgentsInstructions +import AgentsSkills +import Foundation + +/// A pure local authoring request. Its existing root identity is retained through publication. +public struct InitializationDescription: Sendable { + public enum Kind: String, Sendable { case skill, instructions } + public let kind: Kind + public let file: URL + public let template: String + public let existingRoot: URL + public let readLocations: [URL] + private enum Request: Sendable { + case skill(SkillInitialization) + case instructions(InstructionInitialization) + } + private let request: Request + let store: StateStore + + init(skill: SkillInitialization) { + kind = .skill + request = .skill(skill) + store = skill.store + file = skill.file + existingRoot = skill.root.directory + template = String(decoding: skill.template, as: UTF8.self) + readLocations = [existingRoot, file, store.declarationURL, store.resolvedURL, store.watchURL] + } + + init(instructions: InstructionInitialization) { + kind = .instructions + request = .instructions(instructions) + store = instructions.store + file = instructions.file + existingRoot = instructions.root.directory + template = String(decoding: instructions.template, as: UTF8.self) + readLocations = [existingRoot, file, store.declarationURL, store.resolvedURL, store.watchURL] + } + + func apply(outcome: TransactionOutcome, checkpoint: @escaping (String) throws -> Void) throws + -> URL + { + switch request { + case .skill(let skill): return try skill.apply(outcome: outcome, checkpoint: checkpoint) + case .instructions(let instructions): + return try instructions.apply(outcome: outcome, checkpoint: checkpoint) + } + } +} + +extension UpdateOperations { + public static func describeInstructionsInitialization( + named name: String, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> InitializationDescription { + .init(instructions: try InstructionInitialization(named: name, environment: environment)) + } + + /// Creates in a registered project, which must already exist even during description. + public static func describeProjectSkillInitialization( + named name: String? = nil, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> InitializationDescription { + .init( + skill: try SkillInitialization( + named: name, directory: environment.projectDirectory, environment: environment, + requiresExistingDirectory: true)) + } + + /// Explicit standalone authoring. The selected directory may be absent when its immediate parent already exists. + public static func describeSkillInitialization( + named name: String? = nil, directory: URL, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> InitializationDescription { + .init( + skill: try SkillInitialization(named: name, directory: directory, environment: environment)) + } + + /// Returns after all executing resources are released, including on retained journal recovery. + public static func initialize(_ description: InitializationDescription) -> UpdateCompletion { + initialize(description, checkpoint: { _ in }) + } + + package static func initialize( + _ description: InitializationDescription, checkpoint: @escaping (String) throws -> Void + ) -> UpdateCompletion { + let outcome = TransactionOutcome() + var recovered = false + let result = Result { + do { return try description.apply(outcome: outcome, checkpoint: checkpoint) } catch { + if case CoreError.transactionRecovered = error { recovered = true } + throw error + } + } + return completion(result, outcome: outcome, recovered: recovered, store: description.store) + } +} diff --git a/Sources/AgentsUpdates/InstructionOperations.swift b/Sources/AgentsUpdates/InstructionOperations.swift index b890213..1e6d0d6 100644 --- a/Sources/AgentsUpdates/InstructionOperations.swift +++ b/Sources/AgentsUpdates/InstructionOperations.swift @@ -172,19 +172,60 @@ extension InstructionOperations { prompt name: String, scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> Data { + try inspectChatGPTExport(prompt: name, scope: scope, environment: environment).bytes + } + + /// Locked ordered content plus the live consumer appendix, with the actual durable read inputs. + public static func inspectChatGPTExport( + prompt name: String, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> InstructionExportInspection { let store = StateStore(scope: scope, environment: environment) return try store.withReadLock { - _ = try store.readDeclaration() - let ledger = try store.readLedger() + let baseline = try StatePrecondition(store: store) + let declaration = try store.readDeclaration(prepared: baseline) + let ledger = try store.readLedger(prepared: baseline) guard let lowering = ledger.lowerings.first(where: { $0.id == "prompt:" + name }) else { throw InstructionError.emptyPrompt } return try LedgerReplay.withLockedResources( ledger, store: store, roots: store.ledgerRoots, limits: .standard ) { _, resources, _ in - try LedgerReplay.exportPrompt( + let bytes = try LedgerReplay.exportPrompt( lowering, ledger: ledger, resources: resources, roots: store.ledgerRoots) + let paths = try UpdateOperations.readLocations( + declarations: [declaration], ledgers: [ledger], store: store) + try baseline.validate() + return InstructionExportInspection(bytes: bytes, readLocations: paths) } } } + + public static func inspectOwnInstructions( + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> OwnInstructionsInspection { + let store = StateStore(scope: .project, environment: environment) + return try store.withReadLock { + let baseline = try StatePrecondition(store: store) + _ = try store.readDeclaration(prepared: baseline) + let paths = ownReadLocations(environment: environment) + let evidence = try paths.map(TargetPrecondition.init) + let units = try inspectOwn(names: [], environment: environment) + for input in evidence { try input.validate() } + try baseline.validate() + return OwnInstructionsInspection( + units: units, + readLocations: ownReadLocations(names: units.map(\.record.name), environment: environment)) + } + } +} + +public struct InstructionExportInspection: Sendable { + public let bytes: Data + public let readLocations: [URL] +} + +public struct OwnInstructionsInspection: Sendable { + public let units: [InstructionUnit] + public let readLocations: [URL] } diff --git a/Sources/AgentsUpdates/ScopeInspection.swift b/Sources/AgentsUpdates/ScopeInspection.swift index c84f870..a7e3b5e 100644 --- a/Sources/AgentsUpdates/ScopeInspection.swift +++ b/Sources/AgentsUpdates/ScopeInspection.swift @@ -219,16 +219,8 @@ extension UpdateOperations { name: g.name, requirement: g.requirement, manifestHash: g.manifestHash, children: g.children) } - var paths = - stateLocations + sources.compactMap(\.location) + resources.compactMap(\.location) - + deployments.map(\.location) - for declaration in declaration.sources.values where declaration.kind == .local { - let environment = declaration.environment?.runtime ?? environment - let id = try declaration.identity(environment: environment) - if id.hasPrefix("local:") { - paths.append(URL(fileURLWithPath: String(id.dropFirst(6)))) - } - } + let paths = try readLocations( + declarations: [declaration], ledgers: [ledger], store: store) try baseline.validate() return ScopeInspection( scope: scope, document: document, declaration: declaration, generation: generation, diff --git a/Sources/AgentsUpdates/UpdateCompletion.swift b/Sources/AgentsUpdates/UpdateCompletion.swift index f51b290..2ad735f 100644 --- a/Sources/AgentsUpdates/UpdateCompletion.swift +++ b/Sources/AgentsUpdates/UpdateCompletion.swift @@ -35,7 +35,7 @@ extension UpdateOperations { checkpoint: @escaping (String) throws -> Void, _ body: (PreparedUpdate) throws -> Value ) -> UpdateCompletion { - var disposition = UpdateTerminalDisposition.unchanged + var capturedOutcome = TransactionOutcome() var delivered = false var recovered = false let result = Result { @@ -43,13 +43,7 @@ extension UpdateOperations { return try prepare( request, scope: scope, environment: environment, checkpoint: checkpoint, provider: bindingProvider ?? RequiredBindingProvider(), - completion: { outcome in - switch outcome.disposition { - case .committed: disposition = .committed - case .recoveryRequired: disposition = .recoveryRequired - case .unchanged: disposition = outcome.publicationStarted ? .rolledBack : .unchanged - } - } + completion: { capturedOutcome = $0 } ) { update in delivered = true return try body(update) @@ -60,8 +54,24 @@ extension UpdateOperations { throw error } } - let store = StateStore(scope: scope, environment: environment) - let recovery: RecoveryInspection + return completion( + result, outcome: capturedOutcome, recovered: recovered, + store: StateStore(scope: scope, environment: environment)) + } + + static func completion( + _ result: Result, outcome: TransactionOutcome, recovered: Bool, + store: StateStore + ) -> UpdateCompletion { + let disposition: UpdateTerminalDisposition + switch outcome.terminal { + case .committed: disposition = .committed + case .rolledBack: disposition = outcome.publicationStarted ? .rolledBack : .unchanged + case nil: + disposition = + outcome.publicationStarted && outcome.recoveryPending ? .recoveryRequired : .unchanged + } + var recovery: RecoveryInspection do { recovery = try store.withReadLock( onPendingRecovery: { @@ -70,12 +80,15 @@ extension UpdateOperations { pending: true, requiresOwner: diagnostic.requiresOwner, diagnostic: diagnostic.message) }, { .init(pending: false, requiresOwner: false, diagnostic: nil) }) } catch { - // Failure to inspect cleanup is itself material; do not downgrade it to success. recovery = .init( pending: true, requiresOwner: true, diagnostic: "recovery or cleanup could not be verified; retain this scope for diagnosis") } - if recovery.pending, disposition != .committed { disposition = .recoveryRequired } + if outcome.recoveryPending && !recovery.pending { + recovery = .init( + pending: true, requiresOwner: true, + diagnostic: "transaction recovery or cleanup remains pending at the captured scope") + } return UpdateCompletion( result: result, disposition: disposition, recoveredBeforePreparation: recovered, recovery: recovery) diff --git a/Sources/AgentsUpdates/UpdateModels.swift b/Sources/AgentsUpdates/UpdateModels.swift index bfb3a38..d4496c1 100644 --- a/Sources/AgentsUpdates/UpdateModels.swift +++ b/Sources/AgentsUpdates/UpdateModels.swift @@ -1,6 +1,7 @@ import AgentsCore import AgentsInstructions import AgentsSkills +import Foundation public struct CombinedUpdateReport: Codable, Sendable, Equatable { public let scope: InstallScope @@ -10,6 +11,8 @@ public struct CombinedUpdateReport: Codable, Sendable, Equatable { /// Includes normalized state changes and missing-lock reconstruction, even without file diffs. public let hasChanges: Bool public let displayedFingerprint: String + /// Durable inputs and absent leaves used to invalidate this exact preview. + public let readLocations: [URL] public let components: [ComponentUpdateChange] } diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 64e0c07..03ac97f 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -329,6 +329,22 @@ final class UpdatePlan { }, targets: (aggregation.fingerprints + (try decisionInputs.map { try $0.displayEvidence(includeContent: false) })).sorted())) + var readDeclarations: [Declaration] = [] + if case .restore = request.operation { + } else { + readDeclarations.append(try store.readDeclaration(prepared: baseline)) + } + if let change { + readDeclarations.append( + try ManifestProjection.declaration( + of: DeclarationDocument( + bytes: Array(change.bytes), identity: DocumentIdentity(store.declarationURL.path)), + environment: store.environment)) + } + let readPaths = + try UpdateOperations.readLocations( + declarations: readDeclarations, ledgers: [previous, self.next], store: store) + + decisionInputs.map(\.url) let finalNext = self.next report = CombinedUpdateReport( scope: store.scope, skills: publicResults, instructions: instructions, @@ -336,6 +352,7 @@ final class UpdatePlan { hasChanges: self.next != previous || change != nil || aggregation.changes.contains(where: \.changed), displayedFingerprint: fingerprint, + readLocations: Array(Set(readPaths)).sorted { $0.path < $1.path }, components: try aggregation.changes.filter { change in guard change.native else { return false } guard let identities = request.selectedIdentities else { return true } diff --git a/Sources/AgentsUpdates/UpdateReadLocations.swift b/Sources/AgentsUpdates/UpdateReadLocations.swift new file mode 100644 index 0000000..7e8a0b9 --- /dev/null +++ b/Sources/AgentsUpdates/UpdateReadLocations.swift @@ -0,0 +1,58 @@ +import AgentsCore +import AgentsInstructions +import Components +import Foundation + +extension UpdateOperations { + /// Only durable inputs are exposed; replay workspaces and borrowed source URLs stay private. + static func readLocations( + declarations: [Declaration], ledgers: [ResolvedLedger], store: StateStore + ) throws -> [URL] { + var paths = [store.declarationURL, store.resolvedURL, store.watchURL] + for declaration in declarations { + for source in declaration.sources.values where source.kind == .local { + paths.append(source.localURL(environment: source.environment?.runtime ?? store.environment)) + } + func collect(_ components: [ComponentDeclaration]) { + for component in components { + guard case .instructions(let instructions) = component else { continue } + let sections = + instructions.sectionReferences + + instructions.prompts.flatMap { $0.prompt.sectionReferences } + let ownNames = sections.filter { $0.source == nil || $0.source == "." }.map(\.name) + if store.scope == .project { + paths += InstructionOperations.ownReadLocations( + names: ownNames, environment: store.environment) + } + } + } + collect(declaration.components) + for group in declaration.groups { collect(group.components) } + } + for ledger in ledgers { + for source in ledger.sources.values { + if let location = source.location { + paths.append(try location.resolve(roots: store.ledgerRoots)) + } + } + for component in ledger.components.values { + if let value = component.payload.object?["localAppend"] { + paths.append(try LedgerLocation(ledgerValue: value).resolve(roots: store.ledgerRoots)) + } + } + for deployment in ledger.deployments { + paths.append(try deployment.target.resolve(roots: store.ledgerRoots)) + } + for (id, resource) in ledger.resources { + paths.append(try ArtifactAggregation.resourceDestination(id, ledger: ledger, store: store)) + if let source = ledger.sources[resource.source], source.kind == .local, + let location = source.location + { + let root = try location.resolve(roots: store.ledgerRoots) + paths.append(root.appendingPathComponent(try PathSafety.sanitizeSubpath(resource.path))) + } + } + } + return Array(Set(paths.map(\.standardizedFileURL))).sorted { $0.path < $1.path } + } +} diff --git a/Sources/AgentsUpdates/WatchCompletion.swift b/Sources/AgentsUpdates/WatchCompletion.swift new file mode 100644 index 0000000..dc9d80a --- /dev/null +++ b/Sources/AgentsUpdates/WatchCompletion.swift @@ -0,0 +1,20 @@ +import AgentsCore +import AgentsSkills + +extension UpdateOperations { + /// Uses WatchOperations' single subscription writer, then reports its actual outer terminal. + public static func performWatch( + _ preview: WatchMutationPreview, + operations: WatchOperations = SkillOperations.watchOperations() + ) -> UpdateCompletion { + let outcome = TransactionOutcome() + var recovered = false + let result = Result { + do { return try operations.apply(preview, outcome: outcome) } catch { + if case CoreError.transactionRecovered = error { recovered = true } + throw error + } + } + return completion(result, outcome: outcome, recovered: recovered, store: preview.store) + } +} diff --git a/Tests/AgentsUpdatesTests/InitializationIntegrationTests.swift b/Tests/AgentsUpdatesTests/InitializationIntegrationTests.swift new file mode 100644 index 0000000..347d3d4 --- /dev/null +++ b/Tests/AgentsUpdatesTests/InitializationIntegrationTests.swift @@ -0,0 +1,142 @@ +import AgentsInstructions +import AgentsSkills +import Foundation +import Testing + +@testable import AgentsCore +@testable import AgentsUpdates + +@Suite struct InitializationIntegrationTests { + @Test func descriptionsArePureAndCreationUsesExactTemplates() throws { + let f = try UpdateFixture() + let before = try FileSnapshot.read(at: f.root) + let instruction = try UpdateOperations.describeInstructionsInitialization( + named: "own", environment: f.environment) + let skill = try UpdateOperations.describeSkillInitialization( + named: "My Skill", directory: f.root, environment: f.environment) + #expect(try FileSnapshot.read(at: f.root) == before) + #expect(instruction.file == f.root.appendingPathComponent(".agent/instructions/own.md")) + #expect(skill.file == f.root.appendingPathComponent("my-skill/SKILL.md")) + for description in [instruction, skill] { + let completion = UpdateOperations.initialize(description) + #expect(completion.disposition == .committed && !completion.recovery.pending) + _ = try completion.result.get() + #expect(try String(contentsOf: description.file, encoding: .utf8) == description.template) + let duplicate = UpdateOperations.initialize(description) + #expect(duplicate.disposition == .unchanged && !duplicate.recovery.pending) + #expect(throws: (any Error).self) { try duplicate.result.get() } + } + } + + @Test func absentStandaloneDirectoryUsesItsExistingParent() throws { + let f = try UpdateFixture() + let directory = f.root.appendingPathComponent("My Selected Skill") + let description = try UpdateOperations.describeSkillInitialization( + directory: directory, environment: f.environment) + #expect(description.existingRoot.path == f.root.path) + #expect(description.file == directory.appendingPathComponent("SKILL.md")) + #expect(!FileManager.default.fileExists(atPath: directory.path)) + #expect(try UpdateOperations.initialize(description).result.get().path == directory.path) + } + + @Test(arguments: [false, true]) + func missingOrReplacedObservedProjectIsNeverRecreated(_ replace: Bool) throws { + let f = try UpdateFixture() + let selected = f.root.appendingPathComponent("selected") + let moved = f.root.appendingPathComponent("moved") + try FileManager.default.createDirectory(at: selected, withIntermediateDirectories: false) + var environment = f.environment + environment.projectDirectory = selected + let description = try UpdateOperations.describeInstructionsInitialization( + named: "own", environment: environment) + let skill = try UpdateOperations.describeProjectSkillInitialization( + named: "new", environment: environment) + try FileManager.default.moveItem(at: selected, to: moved) + if replace { + try FileManager.default.createDirectory(at: selected, withIntermediateDirectories: false) + } + let completion = UpdateOperations.initialize(description) + #expect(completion.disposition == .unchanged) + let skillCompletion = UpdateOperations.initialize(skill) + #expect(skillCompletion.disposition == .unchanged) + #expect(throws: (any Error).self) { try skillCompletion.result.get() } + if !replace { + #expect(throws: (any Error).self) { + try UpdateOperations.describeProjectSkillInitialization(environment: environment) + } + } + #expect(throws: (any Error).self) { try completion.result.get() } + #expect(FileManager.default.fileExists(atPath: selected.path) == replace) + #expect(!FileManager.default.fileExists(atPath: selected.appendingPathComponent(".agent").path)) + #expect(!FileManager.default.fileExists(atPath: moved.appendingPathComponent(".agent").path)) + } + + @Test(arguments: [false, true]) + func actualPublicationAndFailedRecoveryKeepDistinctOuterOutcomes(_ committed: Bool) throws { + let f = try UpdateFixture() + let description = try UpdateOperations.describeInstructionsInitialization( + named: "own", environment: f.environment) + let parent = description.file.deletingLastPathComponent() + let displaced = f.root.appendingPathComponent("displaced-instructions") + let stop = + committed + ? TransactionCheckpoint.phase(.committed).name + : TransactionCheckpoint.progress(0, .applied).name + let completion = UpdateOperations.initialize(description) { point in + if point == stop { + try FileManager.default.moveItem(at: parent, to: displaced) + throw CoreError.invalidState("fixture publication interruption") + } + } + #expect(completion.disposition == (committed ? .committed : .recoveryRequired)) + #expect(completion.recovery.pending) + #expect(throws: (any Error).self) { try completion.result.get() } + #expect( + try String(contentsOf: displaced.appendingPathComponent("own.md"), encoding: .utf8) + == description.template) + let blocked = UpdateOperations.initialize(description) + #expect(blocked.disposition == .unchanged && blocked.recovery.pending) + #expect(!blocked.recoveredBeforePreparation) + #expect(throws: (any Error).self) { try blocked.result.get() } + try FileManager.default.moveItem(at: displaced, to: parent) + let recovered = UpdateOperations.initialize(description) + #expect(recovered.disposition == .unchanged && recovered.recoveredBeforePreparation) + #expect(!recovered.recovery.pending) + #expect(FileManager.default.fileExists(atPath: description.file.path) == committed) + } + + @Test func rollbackTerminalSurvivesMovedScopeAndPendingDisposal() throws { + let f = try UpdateFixture() + let description = try UpdateOperations.describeInstructionsInitialization( + named: "own", environment: f.environment) + let moved = f.root.deletingLastPathComponent().appendingPathComponent( + f.root.lastPathComponent + "-moved") + let completion = UpdateOperations.initialize(description) { point in + if point == TransactionCheckpoint.publication(0, .created).name { + throw CoreError.invalidState("fixture rollback") + } + if point == "recovery." + TransactionCheckpoint.phase(.rolledBack).name { + try FileManager.default.moveItem(at: f.root, to: moved) + throw CoreError.invalidState("fixture cleanup unavailable") + } + } + #expect(completion.disposition == .rolledBack && completion.recovery.pending) + #expect(!FileManager.default.fileExists(atPath: description.file.path)) + try FileManager.default.moveItem(at: moved, to: f.root) + let recovered = UpdateOperations.initialize(description) + #expect(recovered.recoveredBeforePreparation && !recovered.recovery.pending) + } + + @Test func stagingFailureIsUnchangedWithoutACommittedFile() throws { + let f = try UpdateFixture() + let description = try UpdateOperations.describeSkillInitialization( + named: "new", directory: f.root, environment: f.environment) + let completion = UpdateOperations.initialize(description) { point in + if point == TransactionCheckpoint.stage(0, .constructed).name { + throw CoreError.invalidState("fixture staging failure") + } + } + #expect(completion.disposition == .unchanged && !completion.recovery.pending) + #expect(!FileManager.default.fileExists(atPath: description.file.path)) + } +} diff --git a/Tests/AgentsUpdatesTests/ReadFootprintIntegrationTests.swift b/Tests/AgentsUpdatesTests/ReadFootprintIntegrationTests.swift new file mode 100644 index 0000000..fa0dff8 --- /dev/null +++ b/Tests/AgentsUpdatesTests/ReadFootprintIntegrationTests.swift @@ -0,0 +1,62 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsUpdates +import Foundation +import Testing + +struct ReadFootprintIntegrationTests { + @Test func unsavedDeclarationAndAbsentExportInputsHaveDurableReadLocations() throws { + let f = try UpdateFixture() + try f.declare(agents: [.claudeCode]) + let own = f.root.appendingPathComponent(".agent/instructions/own.md") + let appendix = f.root.appendingPathComponent("future-append.md") + let unused = f.root.appendingPathComponent("future-source") + try f.write("---\ndescription: Own rules.\n---\n# Own\n\nCurrent own rules.", to: own) + var declaration = try f.store.loadDeclaration() + declaration.sources["unused"] = SourceDeclaration(kind: .local, location: unused.path) + for index in declaration.components.indices { + if case .instructions(var selection) = declaration.components[index] { + selection.sectionReferences.append(SectionDeclaration(name: "own")) + selection.prompts[0].prompt.append = "future-append.md" + declaration.components[index] = .instructions(selection) + } + } + let before = try FileHash.folderHash(f.root) + let report = try UpdateOperations.preview( + UpdateRequest(operation: .declaration(declaration)), environment: f.environment) + let discovery = try UpdateOperations.discover(declaration, environment: f.environment) + for locations in [report.readLocations, discovery.readLocations] { + let paths = Set(locations.map(\.path)) + #expect(paths.contains(unused.path)) + #expect(paths.contains(own.path)) + #expect(paths.contains(appendix.path)) + #expect(paths.contains(f.store.declarationURL.path)) + #expect( + !paths.contains { $0.contains("agents-replay-") || $0.contains("agents-resolution-") }) + } + #expect(try FileHash.folderHash(f.root) == before) + _ = try UpdateOperations.withPreparedUpdate( + UpdateRequest(operation: .declaration(declaration)), environment: f.environment + ) { + try $0.apply(ifUnchangedFrom: report.displayedFingerprint) + } + let inspected = try UpdateOperations.inspect(environment: f.environment) + #expect( + Set(inspected.readLocations.map(\.path)).isSuperset(of: [ + unused.path, own.path, appendix.path, + ])) + #expect(throws: (any Error).self) { + try InstructionOperations.inspectChatGPTExport(prompt: "weekly", environment: f.environment) + } + #expect(!FileManager.default.fileExists(atPath: appendix.path)) + try f.write("Live appendix", to: appendix) + let current = try InstructionOperations.inspectChatGPTExport( + prompt: "weekly", environment: f.environment) + #expect(String(decoding: current.bytes, as: UTF8.self).contains("Live appendix")) + #expect(current.readLocations.map(\.path).contains(appendix.path)) + let ownInspection = try InstructionOperations.inspectOwnInstructions(environment: f.environment) + #expect(ownInspection.units.map(\.record.name) == ["own"]) + #expect(ownInspection.readLocations.map(\.path).contains(own.deletingLastPathComponent().path)) + } +} diff --git a/Tests/AgentsUpdatesTests/WatchConfirmationTests.swift b/Tests/AgentsUpdatesTests/WatchConfirmationTests.swift new file mode 100644 index 0000000..cb640b0 --- /dev/null +++ b/Tests/AgentsUpdatesTests/WatchConfirmationTests.swift @@ -0,0 +1,114 @@ +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import Foundation +import Testing + +@testable import AgentsCore + +struct WatchConfirmationTests { + @Test func newSubscriptionPreviewIsPureAndConfirmationUsesTheExactContent() throws { + let f = try UpdateFixture() + let operations = SkillOperations.watchOperations() + let before = try FileHash.folderHash(f.root) + let preview = try operations.previewAdd( + f.repo.path, alias: "watched", environment: f.environment) + let repeated = try operations.previewAdd( + f.repo.path, alias: "watched", environment: f.environment) + #expect(preview.displayedFingerprint == repeated.displayedFingerprint) + #expect(preview.readLocations.map(\.path).contains(f.repo.path)) + #expect(try FileHash.folderHash(f.root) == before) + #expect(!FileManager.default.fileExists(atPath: f.store.directory.path)) + let completion = UpdateOperations.performWatch(preview) + #expect(completion.disposition == .committed && !completion.recovery.pending) + #expect(try completion.result.get().seen == preview.seen) + #expect(try f.store.loadWatch().sources[preview.sourceID]?.seen == preview.seen) + #expect(try f.store.loadDeclaration().watch == ["watched"]) + #expect(!FileManager.default.fileExists(atPath: f.target().path)) + let removal = try operations.previewRemove("watched", environment: f.environment) + let subscribed = try FileHash.folderHash(f.root) + _ = try operations.previewRemove("watched", environment: f.environment) + #expect(try FileHash.folderHash(f.root) == subscribed) + let removed = UpdateOperations.performWatch(removal) + #expect(removed.disposition == .committed && !removed.recovery.pending) + #expect(try removed.result.get().seen == nil) + #expect(try f.store.loadWatch().sources.isEmpty) + #expect(try f.store.loadDeclaration().sources["watched"] != nil) + } + + @Test func upstreamChangesAfterPreviewCannotBeAcknowledged() throws { + let f = try UpdateFixture() + try f.declare() + let operations = SkillOperations.watchOperations() + let preview = try operations.previewAdd("fixture", environment: f.environment) + let before = try f.snapshot() + try f.advance() + let completion = UpdateOperations.performWatch(preview) + #expect(completion.disposition == .unchanged && !completion.recovery.pending) + #expect(throws: (any Error).self) { try completion.result.get() } + #expect(try f.snapshot() == before) + #expect(try f.store.loadWatch().sources.isEmpty) + } + + @Test func declarationEditsAfterPreviewPreventSubscriptionPublication() throws { + let f = try UpdateFixture() + try f.declare() + let operations = SkillOperations.watchOperations() + let preview = try operations.previewAdd("fixture", environment: f.environment) + let edited = + try String(contentsOf: f.store.declarationURL, encoding: .utf8) + "# External edit.\n" + try f.write(edited, to: f.store.declarationURL) + let before = try f.snapshot() + let completion = UpdateOperations.performWatch(preview) + #expect(completion.disposition == .unchanged && !completion.recovery.pending) + #expect(throws: (any Error).self) { try completion.result.get() } + #expect(try f.snapshot() == before) + #expect(try f.store.loadDeclaration().watch == nil) + } + + @Test func removalRejectsAnAcknowledgmentChangedAfterConfirmation() throws { + let f = try UpdateFixture() + let operations = SkillOperations.watchOperations() + _ = try operations.add(f.repo.path, alias: "watched", environment: f.environment) + let preview = try operations.previewRemove("watched", environment: f.environment) + try f.advance() + _ = try operations.seen("watched", environment: f.environment) + let before = try f.snapshot() + let completion = UpdateOperations.performWatch(preview) + #expect(completion.disposition == .unchanged && !completion.recovery.pending) + #expect(throws: (any Error).self) { try completion.result.get() } + #expect(try f.snapshot() == before) + #expect(try f.store.loadDeclaration().watch == ["watched"]) + } + + @Test func committedWatchDisposalFailureHasAnOuterTerminalAndRetainedRecovery() throws { + let f = try UpdateFixture() + let operations = SkillOperations.watchOperations() + let preview = try operations.previewAdd( + f.repo.path, alias: "watched", environment: f.environment) + let displaced = f.root.appendingPathComponent("displaced-watch") + let interrupted = WatchOperations( + discoverSkills: { _ in throw CoreError.invalidState("unexpected discovery") }, + fetchArtifacts: { _ in throw CoreError.invalidState("unexpected artifact fetch") }, + declarations: .manifest, + checkpoint: { [watchURL = f.store.watchURL] point in + if point == TransactionCheckpoint.phase(.committed).name { + try FileManager.default.moveItem(at: watchURL, to: displaced) + throw CoreError.invalidState("fixture disposal interruption") + } + }) + let completion = UpdateOperations.performWatch(preview, operations: interrupted) + #expect(completion.disposition == .committed && completion.recovery.pending) + #expect(throws: (any Error).self) { try completion.result.get() } + #expect(throws: (any Error).self) { + try operations.previewRemove("watched", environment: f.environment) + } + let blocked = UpdateOperations.performWatch(preview) + #expect(blocked.disposition == .unchanged && blocked.recovery.pending) + try FileManager.default.moveItem(at: displaced, to: f.store.watchURL) + let recovered = UpdateOperations.performWatch(preview) + #expect(recovered.disposition == .unchanged && recovered.recoveredBeforePreparation) + #expect(!recovered.recovery.pending) + #expect(try f.store.loadWatch().sources[preview.sourceID]?.seen == preview.seen) + } +} From be414713e7794832466838734472c244410d6f6f Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:10:28 +0800 Subject: [PATCH 103/171] feat: prepare MCP tests from exact component selections --- .../MCPConnectionResources.swift | 61 ++++ .../MCPConnectionSelection.swift | 152 ++++++++++ .../MCPConnectionOperationsTests.swift | 4 +- .../MCPManagedSelectionTests.swift | 268 ++++++++++++++++++ Tests/MCPTestProcess/main.swift | 32 ++- 5 files changed, 514 insertions(+), 3 deletions(-) create mode 100644 Sources/AgentsUpdates/MCPConnectionSelection.swift create mode 100644 Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift diff --git a/Sources/AgentsUpdates/MCPConnectionResources.swift b/Sources/AgentsUpdates/MCPConnectionResources.swift index 97304b6..89084f0 100644 --- a/Sources/AgentsUpdates/MCPConnectionResources.swift +++ b/Sources/AgentsUpdates/MCPConnectionResources.swift @@ -81,6 +81,67 @@ public struct MCPConnectionResource: Sendable, CustomStringConvertible, } catch { throw MCPConnectionPreparationError.invalidResource } } + /// Selected retained closure only; never acquires a source or reads deployed settings. + static func retaining( + _ resource: LedgerResource, objects: [String: Data], gitRoot: URL? + ) throws -> Self { + let workspace = FileManager.default.temporaryDirectory.appendingPathComponent( + "agents-mcp-capture-" + UUID().uuidString) + try FileManager.default.createDirectory( + at: workspace, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + let result = Result { () throws -> Self in + let root: URL + let path: String + if resource.kind == .git { + guard let gitRoot else { throw MCPConnectionPreparationError.invalidResource } + root = gitRoot + path = resource.path + } else { + guard resource.kind == .embedded || resource.kind == .artifact else { + throw MCPConnectionPreparationError.invalidResource + } + let destination = workspace.appendingPathComponent("tree") + var embedded = resource + embedded.kind = .embedded + try LedgerResources.materialize(embedded, objects: objects, at: destination) + root = resource.support.isEmpty ? workspace : destination + path = resource.support.isEmpty ? "tree" : resource.path + } + let view = try SourceSnapshot( + snapshot: .init(source: "selected", revision: resource.hash), pin: nil, root: root) + let file = try view.resource(path) + try view.validateResourceTree(file) + let captured = try LedgerResources.capture( + file, embed: true, limits: .standard, sourceRoot: root) + func metadata(_ entries: [LedgerEntry]) -> [LedgerEntry] { + entries.map { entry in + var entry = entry + entry.object = nil + return entry + } + } + guard captured.hash == resource.hash, + metadata(captured.entries) == metadata(resource.entries), + metadata(captured.support) == metadata(resource.support) + else { throw MCPConnectionPreparationError.resourceChanged } + let type = + try FileManager.default.attributesOfItem(atPath: file.resolvingSymlinksInPath().path)[.type] + as? FileAttributeType + guard type == .typeDirectory || type == .typeRegular else { + throw MCPConnectionPreparationError.invalidResource + } + let retained = LedgerResource( + kind: .embedded, source: "selected", path: path, hash: captured.hash, + entries: captured.entries, support: captured.support) + let count = (captured.entries + captured.support).reduce(0) { $0 + ($1.byteCount ?? 0) } + return Self( + storage: .captured(retained, captured.objects, captured.flags), + directory: type == .typeDirectory, byteCount: count) + } + try FileManager.default.removeItem(at: workspace) + return try result.get() + } + func materialize(in workspace: URL, name: String) throws -> URL { switch storage { case .live(let url, _): diff --git a/Sources/AgentsUpdates/MCPConnectionSelection.swift b/Sources/AgentsUpdates/MCPConnectionSelection.swift new file mode 100644 index 0000000..81fac86 --- /dev/null +++ b/Sources/AgentsUpdates/MCPConnectionSelection.swift @@ -0,0 +1,152 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation + +extension MCPConnectionOperations { + /// Prepares one managed inspection selection without resolving sources, reading + /// native configuration, acquiring bindings or starting the selected program. + /// All read locks and borrowed resource scopes end before this value returns. + public static func snapshot( + selection: ComponentSelection, scope: InstallScope, environment: RuntimeEnvironment + ) throws -> MCPConnectionSnapshot { + let store = StateStore(scope: scope, environment: environment) + do { + return try store.withReadLock { + let baseline = try StatePrecondition(store: store) + let document = try store.declarationDocument(prepared: baseline) + let ledger = try store.readLedger(prepared: baseline) + let generation = try ResolvedLedgerCodec.digest([ + ResolvedLedgerCodec.digest(ledger), document?.digest ?? "absent", + ]) + guard generation == selection.generation else { + throw MCPConnectionPreparationError.invalidSelection + } + let matches = try ledger.components.filter { + try LedgerImpact.identity($0.value, ledger: ledger, roots: store.ledgerRoots) + == selection.identity + } + guard matches.count == 1, let selected = matches.first, + selected.value.kind == DeclaredComponentKind.mcpServer.rawValue + else { throw MCPConnectionPreparationError.invalidSelection } + let occurrences = ledger.occurrences.filter { $0.component == selected.key } + guard !occurrences.isEmpty, + selection.occurrence.map({ id in occurrences.contains { $0.id == id } }) ?? true + else { throw MCPConnectionPreparationError.invalidSelection } + guard selected.value.payload.object?["name"]?.kind == .string, + selected.value.payload.object?["name"]?.text == selected.value.name + else { throw MCPConnectionPreparationError.invalidConfiguration } + let transport = try managedTransport(selected.value.payload) + var remaining = LedgerLimits.standard.resourceBytes + for id in selected.value.resources { + guard let resource = ledger.resources[id] else { + throw MCPConnectionPreparationError.invalidResource + } + for entry in resource.entries + resource.support { + let count = entry.byteCount ?? 0 + guard count >= 0, count <= remaining else { + throw MCPConnectionPreparationError.invalidResource + } + remaining -= count + } + } + var resources = selected.value.resources.makeIterator() + func capture() throws -> MCPConnectionResource { + guard let id = resources.next(), let resource = ledger.resources[id] else { + throw MCPConnectionPreparationError.invalidResource + } + if resource.kind == .liveEdit { + guard let location = resource.location else { + throw MCPConnectionPreparationError.invalidResource + } + return try .live(location.resolve(roots: store.ledgerRoots)) + } + var root: URL? + if resource.kind == .git { + var sourceID = resource.source + while let parent = ledger.sources[sourceID]?.container { sourceID = parent } + guard let source = ledger.sources[sourceID] else { + throw MCPConnectionPreparationError.invalidResource + } + let cache = SourceCache(store: store) + let retained = cache.materializedURL( + sourceID: try ledger.sourceIdentity(sourceID, roots: store.ledgerRoots), + revision: source.revision) + try cache.validatePath(retained) + root = retained + } + return try .retaining(resource, objects: ledger.contentObjects, gitRoot: root) + } + var directory: MCPConnectionResource? + var executable: MCPConnectionResource? + if case .stdio(let run) = transport { + if run.executable.contains("/") { executable = try capture() } + directory = + try run.workingDirectory == nil ? .live(environment.projectDirectory) : capture() + } + guard resources.next() == nil else { throw MCPConnectionPreparationError.invalidResource } + let result = try snapshot( + selectionID: selection.identity, transport: transport, + workingDirectory: directory, executable: executable) + try baseline.validate() + return result + } + } catch is CancellationError { + throw CancellationError() + } catch let error as MCPConnectionPreparationError { + throw error + } catch { throw MCPConnectionPreparationError.invalidSelection } + } + + private static func managedTransport(_ payload: LedgerValue) throws -> MCPTransportDeclaration { + func invalid() -> MCPConnectionPreparationError { .invalidConfiguration } + func string(_ value: LedgerValue?) throws -> String { + guard value?.kind == .string, let text = value?.text else { throw invalid() } + return text + } + func bindings(_ value: LedgerValue?) throws -> [String: RuntimeBinding] { + guard value?.kind == .object, let values = value?.object else { throw invalid() } + return try values.mapValues { item in + guard let text = item.text else { throw invalid() } + switch item.kind { + case .literal: return .literal(text) + case .environment: return .environment(text) + case .secret: return .secret(text) + default: throw invalid() + } + } + } + guard let fields = payload.object?["transport"]?.object else { throw invalid() } + switch try string(fields["kind"]) { + case "stdio": + guard Set(fields.keys) == ["kind", "run"], let run = fields["run"]?.object, + Set(run.keys).subtracting(["workingDirectory"]) == [ + "executable", "arguments", "environment", + ], + run["arguments"]?.kind == .array, let arguments = run["arguments"]?.array + else { throw invalid() } + let cwd: ResourceDeclaration? + if let directory = run["workingDirectory"] { + guard let object = directory.object, Set(object.keys).isSubset(of: ["path", "source"]) + else { + throw invalid() + } + cwd = try .init( + path: string(object["path"]), source: object["source"].map { try string($0) }) + } else { + cwd = nil + } + return try .stdio( + .init( + executable: string(run["executable"]), arguments: arguments.map { try string($0) }, + environment: bindings(run["environment"]), workingDirectory: cwd)) + case "streamableHTTP", "sse": + guard Set(fields.keys) == ["kind", "url", "headers"] else { throw invalid() } + let url = try string(fields["url"]) + let headers = try bindings(fields["headers"]) + return fields["kind"]?.text == "sse" + ? .sse(url: url, headers: headers) : .streamableHTTP(url: url, headers: headers) + default: throw invalid() + } + } +} diff --git a/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift b/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift index 15e81c0..d8f7db0 100644 --- a/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift +++ b/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift @@ -6,7 +6,7 @@ import Testing private final class MCPFacadeBundle: NSObject {} /// Only the call list mutates, under lock; values are immutable fixture input. -private final class MCPBindingSpy: RuntimeBindingProvider, @unchecked Sendable { +final class MCPBindingSpy: RuntimeBindingProvider, @unchecked Sendable { private let lock = NSLock() private var names: [String] = [] let values: [String: Data] @@ -32,7 +32,7 @@ private struct MCPRemovingDirectoryProvider: RuntimeBindingProvider { } } -private final class MCPFacadeFixture { +final class MCPFacadeFixture { let root: URL let observation: URL let environment: RuntimeEnvironment diff --git a/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift b/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift new file mode 100644 index 0000000..496622a --- /dev/null +++ b/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift @@ -0,0 +1,268 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation +import Testing + +@testable import AgentsUpdates + +private struct ManagedMCPFixture { + let fixture: MCPFacadeFixture + let store: StateStore + let producer: URL + var ledger: ResolvedLedger + + init(remote: Bool) throws { + fixture = try MCPFacadeFixture() + store = StateStore(scope: .project, environment: fixture.environment) + producer = fixture.root.appendingPathComponent("producer") + let fm = FileManager.default + try fm.createDirectory( + at: producer.appendingPathComponent(".agent"), withIntermediateDirectories: true) + try fm.createDirectory( + at: producer.appendingPathComponent("cwd"), withIntermediateDirectories: true) + try fm.copyItem(at: MCPFacadeFixture.executable, to: producer.appendingPathComponent("tool")) + try fm.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: producer.appendingPathComponent("tool").path) + try Data("fixed support".utf8).write(to: producer.appendingPathComponent("cwd/support")) + try Data( + """ + version: 1 + groups: + tools: + components: + - kind: mcpServer + name: selected + transport: + kind: stdio + executable: ./tool + arguments: [managed, \(fixture.observation.path)] + workingDirectory: {path: cwd} + environment: {TOKEN: {secret: wanted}} + agents: [] + exports: [tools] + """.utf8 + ).write(to: producer.appendingPathComponent(".agent/agents.yaml")) + let bytes = Data( + """ + version: 1 + sources: {producer: {path: \(producer.path)}} + uses: [{source: producer, group: tools}] + """.utf8) + try bytes.write(to: store.declarationURL) + let document = try DeclarationDocument( + bytes: Array(bytes), identity: DocumentIdentity(store.declarationURL.path)) + let declaration = try ManifestProjection.declaration( + of: document, environment: fixture.environment) + #if os(macOS) + let platform = DeclarationPlatform.macOS + #else + let platform = DeclarationPlatform.linux + #endif + let selectedStore = store + ledger = try ComponentLinker.withLinkedComponents( + document: document, store: selectedStore, platform: platform + ) { linked, session in + try LedgerFreeze.freeze( + linked, session: session, + locations: .init( + sources: UpdatePlan.sourceLocations( + linked, declaration: declaration, store: selectedStore)), limits: .standard) + } + if remote { + let id = try #require(ledger.groups.first?.source) + let revision = String(repeating: "a", count: 40) + ledger.sources[id] = .init( + kind: .git, transport: "https://fixture.invalid/producer.git", revision: revision) + let root = SourceCache(store: store).materializedURL( + sourceID: try ledger.sourceIdentity(id, roots: store.ledgerRoots), revision: revision) + try fm.createDirectory( + at: root.deletingLastPathComponent(), withIntermediateDirectories: true) + try fm.copyItem(at: producer, to: root) + for key in ledger.resources.keys { + ledger.resources[key]!.kind = .git + ledger.resources[key]!.entries = ledger.resources[key]!.entries.map { + var e = $0 + e.object = nil + return e + } + ledger.resources[key]!.support = ledger.resources[key]!.support.map { + var e = $0 + e.object = nil + return e + } + } + ledger.contentObjects = [:] + } + try ResolvedLedgerCodec.encode(ledger, limits: .standard).write(to: store.resolvedURL) + } + func save(_ value: ResolvedLedger) throws { + try ResolvedLedgerCodec.encode(value, limits: .standard).write(to: store.resolvedURL) + } + func inspection() throws -> ComponentInspection { + try #require(UpdateOperations.inspect(environment: fixture.environment).components.first) + } +} + +@Suite(.serialized) struct MCPManagedSelectionTests { + @Test(arguments: [false, true]) + func exactGroupSelectionOwnsResourcesAcrossSourceLossAndConcurrentTests(_ remote: Bool) + async throws + { + let f = try ManagedMCPFixture(remote: remote) + let selected = try f.inspection() + #expect(selected.group == "tools" && selected.kind == .mcpServer) + #expect( + remote ? selected.source == "fixture.invalid/producer" : selected.source.hasPrefix("local:")) + let before = try FileHash.folderHash(f.store.directory) + if remote { try FileManager.default.removeItem(at: f.producer) } + let snapshot = try MCPConnectionOperations.snapshot( + selection: selected.occurrences[0].selection, scope: .project, + environment: f.fixture.environment) + let spy = MCPBindingSpy(["wanted": Data("provider-canary".utf8)]) + #expect(MCPConnectionOperations.describe(snapshot).requiredBindings == ["wanted"]) + #expect(spy.calls.isEmpty) + #expect(try FileManager.default.contentsOfDirectory(atPath: f.fixture.observation.path).isEmpty) + #expect(try FileHash.folderHash(f.store.directory) == before) + if !remote { try FileManager.default.removeItem(at: f.producer) } + if remote { try FileManager.default.removeItem(at: f.store.cacheDirectory) } + let environment = f.fixture.environment + async let first = MCPConnectionOperations.test( + snapshot, environment: environment, bindings: spy) + async let second = MCPConnectionOperations.test( + snapshot, environment: environment, bindings: spy) + let results = await [first, second] + #expect(results.allSatisfy { $0.outcome == .discovered && $0.cleanupComplete }) + #expect(spy.calls == ["wanted", "wanted"]) + let children = try FileManager.default.contentsOfDirectory( + at: f.fixture.observation, includingPropertiesForKeys: nil) + #expect(children.count == 2) + var directories = Set() + for child in children { + let pid = try #require( + Int32(String(contentsOf: child.appendingPathComponent("pid"), encoding: .utf8))) + #expect(kill(pid, 0) == -1 && errno == ESRCH) + let wire = try String(contentsOf: child.appendingPathComponent("wire.jsonl"), encoding: .utf8) + let startup = try #require(wire.split(separator: "\n").first) + let record = try #require( + JSONSerialization.jsonObject(with: Data(startup.utf8)) as? [String: Any]) + let cwd = try #require(record["cwd"] as? String) + directories.insert(cwd) + #expect(!FileManager.default.fileExists(atPath: cwd)) + } + #expect(directories.count == 2) + } + + @Test func staleWrongKindOccurrenceAndAmbiguousSelectionsRefusePreparation() throws { + let f = try ManagedMCPFixture(remote: false) + let selected = try f.inspection() + let environment = f.fixture.environment + let wrong = ComponentSelection( + identity: selected.selection.identity, occurrence: 99999, + generation: selected.selection.generation) + #expect(throws: MCPConnectionPreparationError.invalidSelection) { + try MCPConnectionOperations.snapshot( + selection: wrong, scope: .project, environment: environment) + } + let unknown = ComponentSelection( + identity: "not-the-selected-source", occurrence: nil, + generation: selected.selection.generation) + #expect(throws: MCPConnectionPreparationError.invalidSelection) { + try MCPConnectionOperations.snapshot( + selection: unknown, scope: .project, environment: environment) + } + var ledger = f.ledger + let key = try #require(ledger.components.keys.first) + ledger.components[key]!.kind = "ignore" + try f.save(ledger) + #expect(throws: MCPConnectionPreparationError.invalidSelection) { + try MCPConnectionOperations.snapshot( + selection: selected.selection, scope: .project, environment: environment) + } + let wrongKind = try f.inspection().selection + #expect(throws: MCPConnectionPreparationError.invalidSelection) { + try MCPConnectionOperations.snapshot( + selection: wrongKind, scope: .project, environment: environment) + } + try f.save(f.ledger) + var declaration = try Data(contentsOf: f.store.declarationURL) + declaration.append(Data("\n# changed generation\n".utf8)) + try declaration.write(to: f.store.declarationURL) + #expect(throws: MCPConnectionPreparationError.invalidSelection) { + try MCPConnectionOperations.snapshot( + selection: selected.selection, scope: .project, environment: environment) + } + ledger = f.ledger + ledger.components["duplicate"] = ledger.components[key] + try f.save(ledger) + let ambiguous = try f.inspection().selection + #expect(throws: MCPConnectionPreparationError.invalidSelection) { + try MCPConnectionOperations.snapshot( + selection: ambiguous, scope: .project, environment: environment) + } + #expect(try FileManager.default.contentsOfDirectory(atPath: f.fixture.observation.path).isEmpty) + } + + @Test func defaultLocalContextStaysLiveAndReplacedIdentityRefusesLaunch() async throws { + let f = try ManagedMCPFixture(remote: false) + var ledger = f.ledger + let key = try #require(ledger.components.keys.first) + var payload = ledger.components[key]!.payload.object! + payload["transport"] = .init(object: [ + "kind": .init("stdio"), + "run": .init(object: [ + "executable": .init("MCPTestProcess"), + "arguments": .init(array: [LedgerValue("normal"), .init(f.fixture.observation.path)]), + "environment": .init(object: [:]), + ]), + ]) + ledger.components[key]!.payload = .init(object: payload) + ledger.components[key]!.resources = [] + try f.save(ledger) + let marker = f.fixture.root.appendingPathComponent("live-marker") + try Data("before".utf8).write(to: marker) + let selection = try f.inspection().selection + let snapshot = try MCPConnectionOperations.snapshot( + selection: selection, scope: .project, environment: f.fixture.environment) + try Data("after".utf8).write(to: marker) + let spy = MCPBindingSpy() + let result = await MCPConnectionOperations.test( + snapshot, environment: f.fixture.environment, bindings: spy) + #expect(result.outcome == .discovered && result.cleanupComplete) + let wire = try String( + contentsOf: f.fixture.observation.appendingPathComponent("wire.jsonl"), encoding: .utf8) + let startup = try #require(wire.split(separator: "\n").first) + let record = try #require( + JSONSerialization.jsonObject(with: Data(startup.utf8)) as? [String: Any]) + #expect(record["liveMarker"] as? String == "after") + let displaced = f.fixture.root.appendingPathExtension("displaced") + defer { try? FileManager.default.removeItem(at: displaced) } + try FileManager.default.moveItem(at: f.fixture.root, to: displaced) + try FileManager.default.createDirectory(at: f.fixture.root, withIntermediateDirectories: false) + let stale = await MCPConnectionOperations.test( + snapshot, environment: f.fixture.environment, bindings: spy) + #expect(stale.issue == .resourceChanged && stale.cleanupComplete && spy.calls.isEmpty) + #expect(try FileManager.default.contentsOfDirectory(atPath: f.fixture.root.path).isEmpty) + } + + @Test func changedOrMissingRetainedRemoteBytesNeverRefreshTheSource() throws { + let f = try ManagedMCPFixture(remote: true) + let selected = try f.inspection().selection + let id = try #require(f.ledger.groups.first?.source) + let root = SourceCache(store: f.store).materializedURL( + sourceID: try f.ledger.sourceIdentity(id, roots: f.store.ledgerRoots), + revision: f.ledger.sources[id]!.revision) + try Data("changed retained executable".utf8).write(to: root.appendingPathComponent("tool")) + #expect(throws: (any Error).self) { + try MCPConnectionOperations.snapshot( + selection: selected, scope: .project, environment: f.fixture.environment) + } + try FileManager.default.removeItem(at: root) + #expect(throws: (any Error).self) { + try MCPConnectionOperations.snapshot( + selection: selected, scope: .project, environment: f.fixture.environment) + } + #expect(!FileManager.default.fileExists(atPath: root.path)) + #expect(try FileManager.default.contentsOfDirectory(atPath: f.fixture.observation.path).isEmpty) + } +} diff --git a/Tests/MCPTestProcess/main.swift b/Tests/MCPTestProcess/main.swift index 7cf726b..8f806da 100644 --- a/Tests/MCPTestProcess/main.swift +++ b/Tests/MCPTestProcess/main.swift @@ -9,7 +9,33 @@ import Foundation let arguments = CommandLine.arguments let scenario = arguments.count > 1 ? arguments[1] : "normal" -let root = URL(fileURLWithPath: arguments.count > 2 ? arguments[2] : "/tmp") +let observation = URL(fileURLWithPath: arguments.count > 2 ? arguments[2] : "/tmp") +let root = + scenario == "managed" ? observation.appendingPathComponent(String(getpid())) : observation +if scenario == "managed" { + try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try? Data().write(to: root.appendingPathComponent("ready")) + guard + (try? String( + contentsOfFile: FileManager.default.currentDirectoryPath + "/support", encoding: .utf8)) + == "fixed support" + else { exit(4) } + let deadline = Date().addingTimeInterval(3) + var paired = false + while Date() < deadline { + let ready = + (try? FileManager.default.contentsOfDirectory( + at: observation, includingPropertiesForKeys: nil)) ?? [] + if ready.filter({ + FileManager.default.fileExists(atPath: $0.appendingPathComponent("ready").path) + }).count == 2 { + paired = true + break + } + usleep(1000) + } + guard paired else { exit(3) } +} func record(_ value: [String: Any]) { guard let data = try? JSONSerialization.data(withJSONObject: value) else { return } let file = root.appendingPathComponent("wire.jsonl") @@ -111,6 +137,10 @@ if scenario == "descendant" || scenario == "thread-descendant" { let fd = Int32(ProcessInfo.processInfo.environment["FD_CHECK"] ?? "-1") ?? -1 record([ "startup": true, "cwd": FileManager.default.currentDirectoryPath, + "liveMarker": + (try? String( + contentsOfFile: FileManager.default.currentDirectoryPath + "/live-marker", encoding: .utf8)) + ?? "absent", "environment": ProcessInfo.processInfo.environment["FIXTURE_VALUE"] ?? "absent", "inheritedFD": fd >= 0 && fcntl(fd, F_GETFD) >= 0, ]) From 8f6f31cb04a1f7ab5d38cf4129514980334ce539 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:10:28 +0800 Subject: [PATCH 104/171] feat: retain plugin member identity through resolution --- Sources/AgentsCore/LedgerValidation.swift | 83 +++++ Sources/AgentsCore/ResolvedLedger.swift | 70 +++- Sources/AgentsCore/ResolvedLedgerCodec.swift | 26 +- Sources/AgentsCore/SourceProvenance.swift | 4 +- Sources/Components/ComponentLinker.swift | 6 + Sources/Components/Expansion.swift | 163 +++++---- Sources/Components/LedgerFreeze.swift | 25 +- Sources/Components/LedgerPayload.swift | 2 +- Sources/Components/LinkedComponents.swift | 124 ++++++- Sources/Components/PluginExpansion.swift | 240 +++++++++++++ Tests/ComponentsTests/LedgerReplayTests.swift | 4 +- .../ComponentsTests/PluginLinkingTests.swift | 325 ++++++++++++++++++ 12 files changed, 993 insertions(+), 79 deletions(-) create mode 100644 Sources/Components/PluginExpansion.swift create mode 100644 Tests/ComponentsTests/PluginLinkingTests.swift diff --git a/Sources/AgentsCore/LedgerValidation.swift b/Sources/AgentsCore/LedgerValidation.swift index 760c780..a71de12 100644 --- a/Sources/AgentsCore/LedgerValidation.swift +++ b/Sources/AgentsCore/LedgerValidation.swift @@ -132,6 +132,7 @@ extension ResolvedLedger { try requireSource(component.declaringSource) try requireSource(component.source) try ledgerPath(component.root) + try component.containerRoot.map(ledgerPath) guard DeclaredComponentKind(rawValue: component.kind) != nil, !component.name.isEmpty else { throw CoreError.invalidState("invalid component identity") } @@ -186,6 +187,7 @@ extension ResolvedLedger { for dependency in occurrence.dependencies { try requireSource(dependency) } try validate(occurrence.condition) } + try validatePluginRelations() let deploymentIDs = Set(deployments.map(\.id)) guard deploymentIDs.count == deployments.count else { throw CoreError.invalidState("duplicate deployment") @@ -227,6 +229,87 @@ extension ResolvedLedger { } } + private func validatePluginRelations() throws { + let index = Dictionary(uniqueKeysWithValues: occurrences.map { ($0.id, $0) }) + var children: [Int: [Int]] = [:] + var selectors: [Int: Set] = [:] + var memberOccurrences: [String: [LedgerOccurrence]] = [:] + func exact(_ a: String, _ b: String) -> Bool { a.utf8.elementsEqual(b.utf8) } + func input(_ value: LedgerInputProvenance) throws { + guard !value.format.isEmpty, !value.adapterVersion.isEmpty, + !value.format.contains("\0"), !value.adapterVersion.contains("\0") + else { + throw CoreError.invalidState("invalid native input provenance") + } + } + func narrower(_ child: [T]?, _ parent: [T]?) -> Bool { + guard let parent else { return true } + guard let child else { return false } + return Set(child).isSubset(of: Set(parent)) + } + for occurrence in occurrences { + if let provenance = occurrence.input { try input(provenance) } + guard let member = occurrence.pluginMember else { continue } + guard !member.name.isEmpty, !member.name.contains("\0"), + member.parent >= 0, member.parent < occurrence.id, + let parent = index[member.parent], let expansion = parent.pluginExpansion, + let component = components[occurrence.component], + let container = component.containerRoot, + exact(component.kind, member.kind), exact(component.name, member.name), + exact(component.root, expansion.root), exact(container, expansion.containerRoot), + component.declaringSource == expansion.source, + occurrence.declaringSource == component.declaringSource, + occurrence.dependencies.contains(expansion.source), + occurrence.dependencies.contains(component.source), + expansion.containerRoot == "." + || occurrence.manifestPath.utf8.starts(with: (expansion.containerRoot + "/").utf8), + component.resources.allSatisfy({ resource in + resources[resource].map { occurrence.dependencies.contains($0.source) } ?? false + }), + !occurrence.consumerEditable, occurrence.input != nil, + Set(occurrence.recipients).isSubset(of: Set(parent.recipients)), + narrower(occurrence.condition.agents, parent.condition.agents), + narrower(occurrence.condition.scopes, parent.condition.scopes), + narrower(occurrence.condition.platforms, parent.condition.platforms) + else { throw CoreError.invalidState("invalid plugin member relation") } + let selector = Data((member.kind + "\0" + member.name).utf8) + guard selectors[member.parent, default: []].insert(selector).inserted else { + throw CoreError.invalidState("duplicate plugin member selector") + } + children[member.parent, default: []].append(occurrence.id) + memberOccurrences[occurrence.component, default: []].append(occurrence) + } + for occurrence in occurrences { + guard let expansion = occurrence.pluginExpansion else { continue } + guard let component = components[occurrence.component], component.kind == "plugin", + component.payload.object?["mode"]?.text == "components", + occurrence.dependencies.contains(expansion.source), + expansion.children == (children[occurrence.id] ?? []).sorted() + else { throw CoreError.invalidState("invalid plugin expansion closure") } + try requireSource(expansion.source) + try ledgerPath(expansion.root) + try ledgerPath(expansion.containerRoot) + try ledgerPath(expansion.document) + guard + expansion.containerRoot == "." + || expansion.document.utf8.starts(with: (expansion.containerRoot + "/").utf8) + else { + throw CoreError.invalidState("plugin document outside container") + } + try input(expansion.input) + } + let related = Set(occurrences.filter { $0.pluginMember != nil }.map(\.component)) + for (id, component) in components where component.containerRoot != nil { + guard related.contains(id), let contributions = memberOccurrences[id], + Set(contributions.flatMap(\.recipients)) == Set(component.recipients), + try Set(component.conditions.map { try ResolvedLedgerCodec.bytes($0) }) + == Set(contributions.map { try ResolvedLedgerCodec.bytes($0.condition) }) + else { + throw CoreError.invalidState("container component lacks plugin occurrence") + } + } + } + private func requireSource(_ id: String) throws { guard sources[id] != nil else { throw CoreError.invalidState("dangling ledger source") } } diff --git a/Sources/AgentsCore/ResolvedLedger.swift b/Sources/AgentsCore/ResolvedLedger.swift index d381242..82d24d9 100644 --- a/Sources/AgentsCore/ResolvedLedger.swift +++ b/Sources/AgentsCore/ResolvedLedger.swift @@ -199,6 +199,7 @@ package struct LedgerComponent: Codable, Equatable, Sendable { package var source: String package var root: String package var group: String? + package var containerRoot: String? package var kind: String package var name: String package var revision: String? @@ -210,7 +211,8 @@ package struct LedgerComponent: Codable, Equatable, Sendable { package var resources: [String] package init( - declaringSource: String, source: String, root: String, group: String? = nil, kind: String, + declaringSource: String, source: String, root: String, group: String? = nil, + containerRoot: String? = nil, kind: String, name: String, revision: String? = nil, version: String? = nil, payload: LedgerValue, conditions: [LedgerCondition], recipients: [AgentID], chatGPT: Bool, resources: [String] ) { @@ -218,6 +220,7 @@ package struct LedgerComponent: Codable, Equatable, Sendable { self.root = root self.declaringSource = declaringSource self.group = group + self.containerRoot = containerRoot self.kind = kind self.name = name self.revision = revision @@ -240,11 +243,15 @@ package struct LedgerOccurrence: Codable, Equatable, Sendable { package var condition: LedgerCondition package var recipients: [AgentID] package var consumerEditable: Bool + package var pluginMember: LedgerPluginMember? + package var input: LedgerInputProvenance? + package var pluginExpansion: LedgerPluginExpansion? package init( declaringSource: String, manifestPath: String, id: Int, component: String, reference: Int? = nil, dependencies: [String], condition: LedgerCondition, - recipients: [AgentID], consumerEditable: Bool + recipients: [AgentID], consumerEditable: Bool, pluginMember: LedgerPluginMember? = nil, + input: LedgerInputProvenance? = nil, pluginExpansion: LedgerPluginExpansion? = nil ) { self.id = id self.declaringSource = declaringSource @@ -255,6 +262,65 @@ package struct LedgerOccurrence: Codable, Equatable, Sendable { self.condition = condition self.recipients = recipients self.consumerEditable = consumerEditable + self.pluginMember = pluginMember + self.input = input + self.pluginExpansion = pluginExpansion + } +} + +/// Native conversion provenance; diagnostic pointers never participate in logical identity. +package struct LedgerInputProvenance: Codable, Equatable, Sendable { + package var format: String + package var adapterVersion: String + package var pointer: String? + package init(format: String, adapterVersion: String, pointer: String? = nil) { + self.format = format + self.adapterVersion = adapterVersion + self.pointer = pointer + } +} + +package struct LedgerPluginMember: Codable, Equatable, Sendable { + package var parent: Int + package var kind: String + package var name: String + package init(parent: Int, kind: String, name: String) { + self.parent = parent + self.kind = kind + self.name = name + } + + package static func == (lhs: Self, rhs: Self) -> Bool { + lhs.parent == rhs.parent && lhs.kind.utf8.elementsEqual(rhs.kind.utf8) + && lhs.name.utf8.elementsEqual(rhs.name.utf8) + } +} + +/// Complete ordered direct-member closure, including a successfully expanded empty selection. +package struct LedgerPluginExpansion: Codable, Equatable, Sendable { + package var source: String + package var root: String + package var containerRoot: String + package var document: String + package var input: LedgerInputProvenance + package var children: [Int] + package init( + source: String, root: String, containerRoot: String, document: String, + input: LedgerInputProvenance, children: [Int] + ) { + self.source = source + self.root = root + self.containerRoot = containerRoot + self.document = document + self.input = input + self.children = children + } + + package static func == (lhs: Self, rhs: Self) -> Bool { + lhs.source.utf8.elementsEqual(rhs.source.utf8) && lhs.root.utf8.elementsEqual(rhs.root.utf8) + && lhs.containerRoot.utf8.elementsEqual(rhs.containerRoot.utf8) + && lhs.document.utf8.elementsEqual(rhs.document.utf8) + && lhs.input == rhs.input && lhs.children == rhs.children } } diff --git a/Sources/AgentsCore/ResolvedLedgerCodec.swift b/Sources/AgentsCore/ResolvedLedgerCodec.swift index 657cbeb..da62e59 100644 --- a/Sources/AgentsCore/ResolvedLedgerCodec.swift +++ b/Sources/AgentsCore/ResolvedLedgerCodec.swift @@ -31,7 +31,7 @@ package enum ResolvedLedgerCodec { ) throws -> Data? { try checkModel(ledger, limits: limits) try ledger.validate() - if let existing, try decode(existing, limits: limits) == ledger { return nil } + if let existing, try bytes(decode(existing, limits: limits)) == bytes(ledger) { return nil } return try encode(ledger, limits: limits) } @@ -61,7 +61,20 @@ package enum ResolvedLedgerCodec { var pending = ledger.components.values.map { ($0.payload, 0) } + ledger.lowerings.map { ($0.layout, 0) } - var nodes = 0 + var nodes = ledger.occurrences.count + ledger.groups.count + let ordered = ledger.occurrences.sorted { $0.id < $1.id } + var pluginDepth: [Int: Int] = [:] + for occurrence in ordered { + if let member = occurrence.pluginMember { + let depth = (pluginDepth[member.parent] ?? 0) + 1 + guard depth < limits.depth else { + throw CoreError.invalidState("ledger plugin depth budget") + } + pluginDepth[occurrence.id] = depth + } + nodes += occurrence.pluginExpansion?.children.count ?? 0 + guard nodes <= limits.nodes else { throw CoreError.invalidState("ledger relation budget") } + } while let (value, depth) = pending.popLast() { nodes += 1 guard depth < limits.depth / 2, nodes <= limits.nodes else { @@ -88,6 +101,7 @@ package enum ResolvedLedgerCodec { private indirect enum WireShape { case ledger, source, location, sourceUse, component, condition, occurrence, group case resource, entry, deployment, lowering, value, artifact, requirement, scalar + case pluginMember, input, pluginExpansion case map(WireShape) case list(WireShape) @@ -97,9 +111,10 @@ package enum ResolvedLedgerCodec { case .location: ["root"] case .sourceUse: ["requirement"] case .requirement: ["to"] - case .component: ["group", "revision", "version"] + case .component: ["group", "revision", "version", "containerRoot"] case .condition: ["agents", "scopes", "platforms"] - case .occurrence: ["reference"] + case .occurrence: ["reference", "pluginMember", "input", "pluginExpansion"] + case .input: ["pointer"] case .group: ["parent", "requirement"] case .resource: ["artifact", "location"] case .entry: ["object", "link", "byteCount"] @@ -125,6 +140,9 @@ package enum ResolvedLedgerCodec { case (.component, "payload"), (.lowering, "layout"): .value case (.component, "conditions"): .list(.condition) case (.occurrence, "condition"): .condition + case (.occurrence, "pluginMember"): .pluginMember + case (.occurrence, "input"), (.pluginExpansion, "input"): .input + case (.occurrence, "pluginExpansion"): .pluginExpansion case (.resource, "entries"), (.resource, "support"): .list(.entry) case (.resource, "artifact"): .artifact case (.value, "array"): .list(.value) diff --git a/Sources/AgentsCore/SourceProvenance.swift b/Sources/AgentsCore/SourceProvenance.swift index a59154d..a39acd7 100644 --- a/Sources/AgentsCore/SourceProvenance.swift +++ b/Sources/AgentsCore/SourceProvenance.swift @@ -30,11 +30,12 @@ public struct SourceProvenance: Sendable, Equatable { public let adapterVersion: String public let group: String? public let referenceChain: [SourceSpan] + public let pointer: String? public init( sourceIdentity: String, revision: String? = nil, artifactDigest: String? = nil, relativePath: String, format: String, adapterVersion: String, group: String? = nil, - referenceChain: [SourceSpan] = [] + referenceChain: [SourceSpan] = [], pointer: String? = nil ) { self.sourceIdentity = sourceIdentity self.revision = revision @@ -44,6 +45,7 @@ public struct SourceProvenance: Sendable, Equatable { self.adapterVersion = adapterVersion self.group = group self.referenceChain = referenceChain + self.pointer = pointer } } diff --git a/Sources/Components/ComponentLinker.swift b/Sources/Components/ComponentLinker.swift index 01e9042..38abdd5 100644 --- a/Sources/Components/ComponentLinker.swift +++ b/Sources/Components/ComponentLinker.swift @@ -32,6 +32,7 @@ struct LinkingDocument { let view: SourceSnapshot let manifestPath: String let producer: Bool + var importedSources: [String: SourceSnapshot] = [:] } @@ -273,6 +274,11 @@ final class Linking { id: context.view.snapshot.source, source: nil, contained: context.view, root: context.view.discoveryPath) } + if let view = context.importedSources[alias] { + return SourceAddress( + id: view.snapshot.source, source: nil, contained: view, + root: view.discoveryPath) + } guard let source = context.declaration.sources[alias] else { throw LinkError.missing("source alias '\(alias)'", chain) } diff --git a/Sources/Components/Expansion.swift b/Sources/Components/Expansion.swift index 9eead3d..7e2e221 100644 --- a/Sources/Components/Expansion.swift +++ b/Sources/Components/Expansion.swift @@ -14,6 +14,18 @@ final class Expansion { var active: [GroupIdentity] = [] var nextOccurrence = 0 var referenceParent: Int? + struct PluginFrame { + let parent: Int + let selector: ComponentReferenceDeclaration + let root: String + let containerRoot: String + let origin: ImportLocation + let input: LedgerInputProvenance + let recipients: Set + } + var pluginFrame: PluginFrame? + var pluginDepth = 0 + var pluginChildren: [Int: [Int]] = [:] private struct IndexRequest: Hashable { let source: String let names: [String]? @@ -189,63 +201,77 @@ final class Expansion { } guard emit else { continue } let effective = condition.intersecting(component.condition ?? DeclarationCondition()) - do { - switch component { - case .skills(let alias, let selection): - try skills( - selection, alias: alias, context: context, group: group, - condition: effective, chain: chain, position: position, dependencies: dependencies) - case .instructions(let selection): - for (index, section) in selection.sectionReferences.enumerated() { + try emitComponent( + component, in: context, group: group, condition: effective, + chain: chain, position: position, dependencies: dependencies, pointer: pointer) + } + } + + func emitComponent( + _ component: ComponentDeclaration, in context: LinkingDocument, + group: String?, condition effective: DeclarationCondition, chain: [SourceSpan], + position: SourceMapEntry?, dependencies: [SourceSnapshotID], pointer: String = "" + ) throws { + do { + switch component { + case .skills(let alias, let selection): + try skills( + selection, alias: alias, context: context, group: group, + condition: effective, chain: chain, position: position, dependencies: dependencies) + case .instructions(let selection): + for (index, section) in selection.sectionReferences.enumerated() { + try instruction( + section, prompt: nil, selection: selection, context: context, group: group, + condition: effective, chain: chain, + position: linking.position(at: pointer + "/sections/\(index)", in: context) + ?? position, + dependencies: dependencies) + } + for prompt in selection.prompts { + let promptCondition = effective.intersecting( + prompt.prompt.condition ?? DeclarationCondition()) + for section in prompt.prompt.sectionReferences { try instruction( - section, prompt: nil, selection: selection, context: context, group: group, - condition: effective, chain: chain, - position: linking.position(at: pointer + "/sections/\(index)", in: context) - ?? position, - dependencies: dependencies) - } - for prompt in selection.prompts { - let promptCondition = effective.intersecting( - prompt.prompt.condition ?? DeclarationCondition()) - for section in prompt.prompt.sectionReferences { - try instruction( - section, prompt: prompt.name, selection: selection, context: context, - group: group, condition: promptCondition, chain: chain, position: position, - dependencies: dependencies, append: prompt.prompt.append) - } - } - default: - let resources = try component.resources.map { - try resource($0, context: context, chain: chain) + section, prompt: prompt.name, selection: selection, context: context, + group: group, condition: promptCondition, chain: chain, position: position, + dependencies: dependencies, append: prompt.prompt.append) } - try append( - key: key(component.name!, kind: component.kind, context: context, group: group), - snapshot: context.view.snapshot, pin: context.view.pin, - payload: .declaration(component), - context: context, - group: group, condition: effective, - recipients: effective.recipients( - requested: component.agents ?? context.declaration.defaultAgents, - scope: linking.store.scope, platform: linking.platform), chatGPT: false, - resources: resources, chain: chain, position: position, - dependencies: dependencies + resources.map(\.snapshot)) } - } catch let error as LinkError { throw error } catch { - throw LinkError.invalid( - String(describing: error), chain + (position.map { [$0.span] + $0.origins } ?? [])) + case .plugin: + try plugin( + component, context: context, group: group, condition: effective, + chain: chain, position: position, dependencies: dependencies) + default: + let resources = try component.resources.map { + try resource($0, context: context, chain: chain) + } + try append( + key: key(component.name!, kind: component.kind, context: context, group: group), + snapshot: context.view.snapshot, pin: context.view.pin, + payload: .declaration(try resolvedNativeResources(component, context: context)), + context: context, + group: group, condition: effective, + recipients: effective.recipients( + requested: component.agents ?? context.declaration.defaultAgents, + scope: linking.store.scope, platform: linking.platform), chatGPT: false, + resources: resources, chain: chain, position: position, + dependencies: dependencies + resources.map(\.snapshot)) } + } catch let error as LinkError { throw error } catch { + throw LinkError.invalid( + String(describing: error), chain + (position.map { [$0.span] + $0.origins } ?? [])) } } - private func key( + func key( _ name: String, kind: DeclaredComponentKind, context: LinkingDocument, group: String? ) -> ComponentKey { ComponentKey( - source: context.view.snapshot.source, root: context.view.discoveryPath, - group: group, kind: kind, name: name) + source: context.view.snapshot.source, root: pluginFrame?.root ?? context.view.discoveryPath, + group: group, kind: kind, name: name, containerRoot: pluginFrame?.containerRoot) } - private func selectedView(_ address: SourceAddress, key: ComponentKey?, live: Bool = false) throws + func selectedView(_ address: SourceAddress, key: ComponentKey?, live: Bool = false) throws -> SourceSnapshot { if let contained = address.contained { @@ -287,6 +313,10 @@ final class Expansion { return try linking.view(address, pin: pin)! } + private func canonicalSkillName(_ value: String) -> String { + pluginFrame == nil ? PathSafety.sanitizeName(value) : value + } + private func skills( _ selection: SkillDeclaration, alias: String, context: LinkingDocument, group: String?, condition: DeclarationCondition, @@ -309,12 +339,12 @@ final class Expansion { let requestedNames: [String]? switch selection.select { case .all: requestedNames = nil - case .names(let names): requestedNames = names.map(PathSafety.sanitizeName) + case .names(let names): requestedNames = names.map(canonicalSkillName) } - let excluded = Set((selection.exclude ?? []).map(PathSafety.sanitizeName)) + let excluded = Set((selection.exclude ?? []).map(canonicalSkillName)) var overrides: [String: SkillOverride] = [:] for (name, override) in selection.overrides ?? [:] { - let canonical = PathSafety.sanitizeName(name) + let canonical = canonicalSkillName(name) guard overrides[canonical] == nil else { throw LinkError.invalid("duplicate canonical skill override: \(canonical)", location) } @@ -338,14 +368,14 @@ final class Expansion { } else { let live = selection.mode == .edit let primary = try selectedView(address, key: nil, live: live) - var selected = try members(primary, live: live).map { PathSafety.sanitizeName($0.name) } + var selected = try members(primary, live: live).map { canonicalSkillName($0.name) } for name in overrides.keys.sorted() where !excluded.contains(name) && (selectedMode(name) == .edit) != live { let view = try selectedView( address, key: key(name, kind: .skills, context: context, group: group), live: selectedMode(name) == .edit) if try members(view, live: selectedMode(name) == .edit).contains(where: { - PathSafety.sanitizeName($0.name) == name + canonicalSkillName($0.name) == name }) { selected.append(name) } @@ -361,7 +391,8 @@ final class Expansion { throw LinkError.invalid("edit requires an actual local skill with no requirement", location) } let matches = try members(view, live: mode == .edit).filter { - PathSafety.sanitizeName($0.name) == name + if pluginFrame != nil { return $0.name.utf8.elementsEqual(name.utf8) } + return canonicalSkillName($0.name) == name || PathSafety.sanitizeName(URL(fileURLWithPath: $0.path).lastPathComponent) == name } if matches.isEmpty, requestedNames == nil { continue } @@ -369,7 +400,7 @@ final class Expansion { throw LinkError.missing("skill '\(name)'", location) } let componentKey = key( - PathSafety.sanitizeName(skill.name), kind: .skills, context: context, group: group) + canonicalSkillName(skill.name), kind: .skills, context: context, group: group) let effective = condition.intersecting(skill.condition) let resource = LinkedResource( snapshot: view.snapshot, path: skill.path, @@ -395,12 +426,12 @@ final class Expansion { let requested: [String]? switch selection.select { case .all: requested = nil - case .names(let names): requested = names.map(PathSafety.sanitizeName) + case .names(let names): requested = names.map(canonicalSkillName) } - let excluded = Set((selection.exclude ?? []).map(PathSafety.sanitizeName)) + let excluded = Set((selection.exclude ?? []).map(canonicalSkillName)) var overrides: [String: SkillOverride] = [:] for (name, override) in selection.overrides ?? [:] { - let canonical = PathSafety.sanitizeName(name) + let canonical = canonicalSkillName(name) guard overrides[canonical] == nil else { throw LinkError.invalid("duplicate canonical skill override: \(canonical)", chain) } @@ -456,7 +487,7 @@ final class Expansion { } try linking.budget.snapshot(view.snapshot) guard let skill = try SkillSnapshotReader.read(view).first, - PathSafety.sanitizeName(skill.name) == name + canonicalSkillName(skill.name) == name else { throw LinkError.missing("skill '\(name)'", location) } @@ -552,7 +583,7 @@ final class Expansion { } } - private func resource( + func resource( _ resource: ResourceDeclaration, context: LinkingDocument, chain: [SourceSpan] ) throws -> LinkedResource { let address = try linking.address(resource.source, in: context, chain: chain) @@ -562,7 +593,7 @@ final class Expansion { return try self.resource(resource.path, in: view, chain: chain) } - private func resource(_ resourcePath: String, in view: SourceSnapshot, chain: [SourceSpan]) throws + func resource(_ resourcePath: String, in view: SourceSnapshot, chain: [SourceSpan]) throws -> LinkedResource { let root = try view.directory() @@ -587,7 +618,7 @@ final class Expansion { executableFlags: [path: ((info[.posixPermissions] as? NSNumber)?.intValue ?? 0) & 0o111 != 0]) } - private func append( + func append( key: ComponentKey, snapshot: SourceSnapshotID, pin: SourceRevision? = nil, payload: LinkedPayload, context: LinkingDocument, group: String?, condition: DeclarationCondition, recipients: Set, chatGPT: Bool, @@ -602,13 +633,20 @@ final class Expansion { revision: context.view.pin?.revision, artifactDigest: context.view.snapshot.revision.hasPrefix("sha256:") ? context.view.snapshot.revision : nil, - relativePath: context.manifestPath, format: "yaml", adapterVersion: "1", - group: group, referenceChain: chain) + relativePath: pluginFrame?.origin.document ?? context.manifestPath, + format: pluginFrame?.input.format ?? "yaml", + adapterVersion: pluginFrame?.input.adapterVersion ?? "1", + group: group, referenceChain: chain, pointer: pluginFrame?.origin.pointer) + let recipients = pluginFrame.map { recipients.intersection($0.recipients) } ?? recipients let origin = ContributionOrigin( occurrence: occurrence, provenance: provenance, declaration: position?.span, sourceOrigins: position?.origins ?? [], reference: referenceParent, condition: condition, - recipients: recipients, dependencies: dependencies, consumerEditable: !context.producer) + recipients: recipients, dependencies: dependencies, consumerEditable: !context.producer, + pluginMember: pluginFrame.map { + LinkedPluginMember(parentOccurrence: $0.parent, selector: $0.selector) + }) + if let frame = pluginFrame { pluginChildren[frame.parent, default: []].append(occurrence) } components.append( LinkedComponent( key: key, declaringSnapshot: context.view.snapshot, snapshot: snapshot, pin: pin, @@ -658,6 +696,7 @@ final class Expansion { result.flatMap { component in [component.snapshot] + component.resources.map(\.snapshot) + component.origins.flatMap(\.dependencies) + + component.origins.compactMap { $0.pluginExpansion?.snapshot } } + references.map(\.snapshot)) return LinkedComponents( components: result, references: references, diff --git a/Sources/Components/LedgerFreeze.swift b/Sources/Components/LedgerFreeze.swift index 73eae56..e3b8655 100644 --- a/Sources/Components/LedgerFreeze.swift +++ b/Sources/Components/LedgerFreeze.swift @@ -97,7 +97,7 @@ package enum LedgerFreeze { url, embed: kind != .git, limits: limits, sourceRoot: try session.resource(snapshot: resource.snapshot, path: ".")) let flags = - captured.entries.count == 1 && captured.entries[0].kind == .file + captured.entries.count == 1 && captured.entries[0].kind != .directory ? [resource.path: captured.flags["."] ?? false] : captured.flags guard captured.hash == resource.hash, resource.executableFlags.isEmpty || flags == resource.executableFlags @@ -139,7 +139,8 @@ package enum LedgerFreeze { let record = LedgerComponent( declaringSource: try sourceID(component.declaringSnapshot), source: try sourceID(component.snapshot), root: component.key.root, - group: component.key.group, kind: component.key.kind.rawValue, name: component.key.name, + group: component.key.group, containerRoot: component.key.containerRoot, + kind: component.key.kind.rawValue, name: component.key.name, revision: component.pin?.revision, version: component.pin?.version, payload: payload, conditions: component.conditions.map(LedgerCondition.init), recipients: component.recipients.sorted { $0.rawValue < $1.rawValue }, @@ -154,7 +155,24 @@ package enum LedgerFreeze { reference: origin.reference, dependencies: try origin.dependencies.map(sourceID), condition: LedgerCondition(origin.condition), recipients: origin.recipients.sorted { $0.rawValue < $1.rawValue }, - consumerEditable: origin.consumerEditable)) + consumerEditable: origin.consumerEditable, + pluginMember: origin.pluginMember.map { + let selector = LedgerPayload.reference($0.selector).object! + return LedgerPluginMember( + parent: $0.parentOccurrence, + kind: selector["kind"]!.text!, name: selector["name"]!.text!) + }, + input: origin.provenance.format == "yaml" + ? nil + : LedgerInputProvenance( + format: origin.provenance.format, adapterVersion: origin.provenance.adapterVersion, + pointer: origin.provenance.pointer), + pluginExpansion: try origin.pluginExpansion.map { + LedgerPluginExpansion( + source: try sourceID($0.snapshot), root: $0.root, + containerRoot: $0.containerRoot, document: $0.document, input: $0.input, + children: $0.children) + })) } } ledger.occurrences.sort { $0.id < $1.id } @@ -175,6 +193,7 @@ package enum LedgerFreeze { manifestHash: reference.manifestHash, children: (children[reference.occurrence] ?? []).sorted()) } + try ResolvedLedgerCodec.checkModel(ledger, limits: limits) try ledger.validate() return Result(ledger: ledger, sources: sources) } diff --git a/Sources/Components/LedgerPayload.swift b/Sources/Components/LedgerPayload.swift index 0e8fc6a..6223339 100644 --- a/Sources/Components/LedgerPayload.swift +++ b/Sources/Components/LedgerPayload.swift @@ -166,7 +166,7 @@ enum LedgerPayload { return .init(object: ["action": .init(action), "operation": op, "pattern": .init(pattern)]) } - private static func reference(_ reference: ComponentReferenceDeclaration) -> LedgerValue { + static func reference(_ reference: ComponentReferenceDeclaration) -> LedgerValue { let kind: String let name: String switch reference { diff --git a/Sources/Components/LinkedComponents.swift b/Sources/Components/LinkedComponents.swift index 8dd5c6a..2b10d45 100644 --- a/Sources/Components/LinkedComponents.swift +++ b/Sources/Components/LinkedComponents.swift @@ -10,6 +10,32 @@ package struct ComponentKey: Hashable, Sendable { package let group: String? package let kind: DeclaredComponentKind package let name: String + package let containerRoot: String? + + package init( + source: String, root: String, group: String?, kind: DeclaredComponentKind, + name: String, containerRoot: String? = nil + ) { + self.source = source + self.root = root + self.group = group + self.kind = kind + self.name = name + self.containerRoot = containerRoot + } + + package static func == (lhs: Self, rhs: Self) -> Bool { + lhs.kind == rhs.kind && lhs.source.utf8.elementsEqual(rhs.source.utf8) + && lhs.root.utf8.elementsEqual(rhs.root.utf8) && lhs.name.utf8.elementsEqual(rhs.name.utf8) + && lhs.group.map { Data($0.utf8) } == rhs.group.map { Data($0.utf8) } + && lhs.containerRoot.map { Data($0.utf8) } == rhs.containerRoot.map { Data($0.utf8) } + } + package func hash(into hasher: inout Hasher) { + hasher.combine(kind.rawValue) + for value in [Optional(source), root, group, name, containerRoot] { + hasher.combine(value.map { Data($0.utf8) }) + } + } } /// Exact, relative resource evidence. URLs used while reading never enter this value. @@ -39,12 +65,46 @@ package enum LinkedPayload: Equatable, Sendable { func sameContent(as other: Self) -> Bool { if case .declaration(let lhs) = self, case .declaration(let rhs) = other { - return lhs.comparisonPayload == rhs.comparisonPayload + guard let a = try? ResolvedLedgerCodec.bytes(LedgerPayload.component(lhs.comparisonPayload)), + let b = try? ResolvedLedgerCodec.bytes(LedgerPayload.component(rhs.comparisonPayload)) + else { return false } + return a == b } return self == other } } +package struct LinkedPluginMember: Equatable, Sendable { + package let parentOccurrence: Int + package let selector: ComponentReferenceDeclaration + + package static func == (lhs: Self, rhs: Self) -> Bool { + guard lhs.parentOccurrence == rhs.parentOccurrence, + let a = try? ResolvedLedgerCodec.bytes(LedgerPayload.reference(lhs.selector)), + let b = try? ResolvedLedgerCodec.bytes(LedgerPayload.reference(rhs.selector)) + else { return false } + return a == b + } +} + +package struct LinkedPluginExpansion: Equatable, Sendable { + package let snapshot: SourceSnapshotID + package let root: String + package let containerRoot: String + package let document: String + package let input: LedgerInputProvenance + package var children: [Int] + + package static func == (lhs: Self, rhs: Self) -> Bool { + lhs.snapshot.source.utf8.elementsEqual(rhs.snapshot.source.utf8) + && lhs.snapshot.revision.utf8.elementsEqual(rhs.snapshot.revision.utf8) + && lhs.root.utf8.elementsEqual(rhs.root.utf8) + && lhs.containerRoot.utf8.elementsEqual(rhs.containerRoot.utf8) + && lhs.document.utf8.elementsEqual(rhs.document.utf8) + && lhs.input == rhs.input && lhs.children == rhs.children + } +} + package struct ContributionOrigin: Equatable, Sendable { package let occurrence: Int package let provenance: SourceProvenance @@ -56,6 +116,8 @@ package struct ContributionOrigin: Equatable, Sendable { /// Source variables traversed to reach this contribution, including resource dependencies. package let dependencies: [SourceSnapshotID] package let consumerEditable: Bool + package var pluginMember: LinkedPluginMember? = nil + package var pluginExpansion: LinkedPluginExpansion? = nil } package struct LinkedComponent: Equatable, Sendable { @@ -68,7 +130,7 @@ package struct LinkedComponent: Equatable, Sendable { package var recipients: Set /// ChatGPT is a projection, not an AgentID. Scope/platform constraints still apply. package let chatGPT: Bool - package let resources: [LinkedResource] + package var resources: [LinkedResource] package var origins: [ContributionOrigin] /// Consumer-owned export input. It is not read or retained for installation replay. package var localAppend: LedgerLocation? = nil @@ -120,6 +182,50 @@ package struct LinkedComponents: Equatable, Sendable { }, by: \.key) } var changes = Set() + func relations(_ graph: Self) -> [Int: Data] { + guard + graph.components.contains(where: { + $0.origins.contains { $0.pluginMember != nil || $0.pluginExpansion != nil } + }) + else { return [:] } + let occurrences = Dictionary( + uniqueKeysWithValues: graph.components.flatMap { component in + component.origins.map { ($0.occurrence, component) } + }) + func identity(_ key: ComponentKey) -> LedgerValue { + var fields: [String: LedgerValue] = [ + "source": .init(key.source), "root": .init(key.root), + "kind": .init(key.kind.rawValue), "name": .init(key.name), + ] + fields["group"] = key.group.map { .init($0) } + fields["containerRoot"] = key.containerRoot.map { .init($0) } + return .init(object: fields) + } + var result: [Int: Data] = [:] + for component in graph.components { + for origin in component.origins { + var fields: [String: LedgerValue] = [:] + if let member = origin.pluginMember, let parent = occurrences[member.parentOccurrence] { + fields["parent"] = identity(parent.key) + fields["selector"] = LedgerPayload.reference(member.selector) + } + if let expansion = origin.pluginExpansion { + fields["source"] = .init(expansion.snapshot.source) + fields["revision"] = .init(expansion.snapshot.revision) + fields["root"] = .init(expansion.root) + fields["containerRoot"] = .init(expansion.containerRoot) + fields["children"] = .init( + array: expansion.children.compactMap { occurrences[$0] }.map { identity($0.key) }) + } + if !fields.isEmpty { + result[origin.occurrence] = try? ResolvedLedgerCodec.bytes(LedgerValue(object: fields)) + } + } + } + return result + } + let beforeRelations = relations(previous) + let afterRelations = relations(self) func compare(_ lhs: [LinkedComponent], _ rhs: [LinkedComponent]) { for (a, b) in zip(lhs, rhs) { // Coalescing retains distinct complete clauses; collection order carries no restriction. @@ -128,12 +234,19 @@ package struct LinkedComponents: Equatable, Sendable { ? a.conditions.count == b.conditions.count && a.conditions.allSatisfy { b.conditions.contains($0) } : a.conditions == b.conditions + let aRelations = a.origins.compactMap { beforeRelations[$0.occurrence] }.sorted { + $0.lexicographicallyPrecedes($1) + } + let bRelations = b.origins.compactMap { afterRelations[$0.occurrence] }.sorted { + $0.lexicographicallyPrecedes($1) + } if a.key != b.key || a.snapshot != b.snapshot || a.pin != b.pin || !a.payload.sameContent(as: b.payload) || !sameConditions || a.localAppend != b.localAppend || a.recipients != b.recipients || a.chatGPT != b.chatGPT || a.resources != b.resources || Set(a.origins.flatMap(\.dependencies)) != Set(b.origins.flatMap(\.dependencies)) + || aRelations != bRelations { changes.insert(a.key) changes.insert(b.key) @@ -177,9 +290,12 @@ package struct LinkedComponents: Equatable, Sendable { } } return changes.sorted { lhs, rhs in - [lhs.source, lhs.root, lhs.group ?? "", lhs.kind.rawValue, lhs.name] + [lhs.source, lhs.root, lhs.containerRoot ?? "", lhs.group ?? "", lhs.kind.rawValue, lhs.name] .lexicographicallyPrecedes( - [rhs.source, rhs.root, rhs.group ?? "", rhs.kind.rawValue, rhs.name]) + [ + rhs.source, rhs.root, rhs.containerRoot ?? "", rhs.group ?? "", rhs.kind.rawValue, + rhs.name, + ]) } } diff --git a/Sources/Components/PluginExpansion.swift b/Sources/Components/PluginExpansion.swift new file mode 100644 index 0000000..5fea1f5 --- /dev/null +++ b/Sources/Components/PluginExpansion.swift @@ -0,0 +1,240 @@ +import AgentsCore +import Foundation + +extension Expansion { + func plugin( + _ declaration: ComponentDeclaration, context: LinkingDocument, group: String?, + condition: DeclarationCondition, chain: [SourceSpan], position: SourceMapEntry?, + dependencies: [SourceSnapshotID] + ) throws { + guard + case .plugin( + let name, let path, let alias, let mode, let select, let exclude, + let agents, _, _) = declaration + else { return } + guard active.count + pluginDepth < 64 else { throw LinkError.budget("active references") } + let componentKey = key(name, kind: .plugin, context: context, group: group) + let address = try linking.address(alias, in: context, chain: chain) + let view: SourceSnapshot + if linking.directPins[componentKey] == nil, + let selected = try linking.view(address, pin: choices[address.id]) + { + view = selected + } else { + view = try selectedView(address, key: componentKey) + } + let container = try view.relativePath( + PathSafety.resolvedChild(base: view.directory(), subpath: path)) + let recipients = condition.recipients( + requested: agents ?? context.declaration.defaultAgents, + scope: linking.store.scope, platform: linking.platform) + if mode == .native { + guard recipients.count == 1, select == nil, exclude.isEmpty else { + throw LinkError.invalid("native plugin requires one recipient and no filters", chain) + } + try append( + key: componentKey, snapshot: view.snapshot, pin: view.pin, + payload: .declaration(declaration), context: context, group: group, + condition: condition, recipients: recipients, chatGPT: false, + resources: [resource(path, in: view, chain: chain)], chain: chain, position: position, + dependencies: dependencies + [view.snapshot]) + return + } + let profiles: [(SourceImportProfile, String)] = [ + (.claudePluginV1, ".claude-plugin/plugin.json"), + (.cursorPluginV1, ".cursor-plugin/plugin.json"), + (.geminiExtensionV1, "gemini-extension.json"), + ] + let entries = try profiles.compactMap { profile, suffix -> (SourceImportProfile, String)? in + let document = container == "." ? suffix : container + "/" + suffix + let file = try view.resource(document) + return FileManager.default.fileExists(atPath: file.path) ? (profile, document) : nil + } + guard entries.count == 1, let (profile, document) = entries.first else { + throw LinkError.invalid("plugin requires one supported native container manifest", chain) + } + let proposal = try SourceImport.preview( + .init(profile: profile, root: view.root, document: document)) + if let failure = proposal.diagnostics.first(where: { + ![.unconverted, .credentialBinding].contains($0.code) + }) { + throw LinkError.invalid( + "native plugin \(failure.code.rawValue) at \(failure.location.document)\(failure.location.pointer)", + chain) + } + // G's aliases are read coordinates in the already selected immutable producer tree. + var aliases: [String: SourceSnapshot] = [:] + for source in proposal.sources { + try linking.budget.step() + guard source.declaration?.kind == .local, let path = source.producerPath else { + throw LinkError.invalid("native member has no contained producer coordinates", chain) + } + aliases[source.alias] = try SourceSnapshot( + snapshot: view.snapshot, pin: view.pin, root: view.root, discoveryPath: path, + packageIdentity: view.packageIdentity) + } + let namespace = pluginFrame?.root ?? view.discoveryPath + let input = LedgerInputProvenance( + format: "native/" + profile.rawValue + "@1", adapterVersion: "1") + let parentIndex = components.count + let parent = nextOccurrence + try append( + key: componentKey, snapshot: view.snapshot, pin: view.pin, + payload: .declaration(declaration), context: context, group: group, + condition: condition, recipients: recipients, chatGPT: false, resources: [], + chain: chain, position: position, dependencies: dependencies + [view.snapshot]) + let actualRecipients = components[parentIndex].origins[0].recipients + components[parentIndex].origins[0].pluginExpansion = LinkedPluginExpansion( + snapshot: view.snapshot, root: namespace, containerRoot: container, + document: document, input: input, children: []) + let previous = pluginFrame + pluginDepth += 1 + defer { + pluginFrame = previous + pluginDepth -= 1 + } + let childView = try SourceSnapshot( + snapshot: view.snapshot, pin: view.pin, root: view.root, + discoveryPath: container, packageIdentity: view.packageIdentity) + var childContext = LinkingDocument( + declaration: context.declaration, document: context.document, + view: childView, manifestPath: document, producer: true) + childContext.importedSources = aliases + var documents = Set() + for path in [document] + proposal.components.map({ $0.origin.document }) + + proposal.resources.map({ $0.origin.document }) + where documents.insert(Data(path.utf8)).inserted { + let bytes = try Data(contentsOf: view.resource(path)) + try linking.budget.manifest(view.snapshot, path: path, bytes: bytes.count) + } + let exclusions = try Set( + exclude.map { + try linking.budget.step() + return try ResolvedLedgerCodec.bytes(LedgerPayload.reference($0)) + }) + var resourcesByDocument: [Data: [ImportResourceProposal]] = [:] + for resource in proposal.resources { + try linking.budget.step() + resourcesByDocument[Data(resource.origin.document.utf8), default: []].append(resource) + } + var selectors = Set() + for child in proposal.components { + if child.declaration.kind == .skills { + try linking.budget.step() + } else { + try spendNativeValue(LedgerPayload.component(child.declaration)) + } + guard let coordinate = child.member, + coordinate.containerRoot.utf8.elementsEqual(container.utf8) + else { + throw LinkError.invalid("native member lacks container coordinates", chain) + } + let selector = LedgerPayload.reference(coordinate.selector) + let bytes = try ResolvedLedgerCodec.bytes(selector) + guard selectors.insert(bytes).inserted else { + throw LinkError.invalid("duplicate native member selector", chain) + } + guard select?.contains(child.declaration.kind) ?? true, !exclusions.contains(bytes) + else { continue } + pluginFrame = PluginFrame( + parent: parent, selector: coordinate.selector, + root: namespace, containerRoot: container, origin: child.origin, + input: .init( + format: "native/" + coordinate.profile.rawValue + "@" + String(coordinate.formatVersion), + adapterVersion: "1", + pointer: child.origin.pointer), recipients: actualRecipients) + let condition = condition.intersecting(child.declaration.condition ?? .init()) + let start = components.count + try emitComponent( + child.declaration, in: childContext, group: nil, condition: condition, + chain: chain, + position: child.origin.span.map { + SourceMapEntry(pointer: child.origin.pointer, span: $0, origins: [], defaulted: false) + }, dependencies: dependencies + [view.snapshot]) + // Literal prompt payloads retain their selected safe native input, never a raw bundle. + if [.command, .subagent].contains(child.declaration.kind) { + let selected = (resourcesByDocument[Data(child.origin.document.utf8)] ?? []).filter { + ($0.kind == nil || $0.kind == child.declaration.kind) && !$0.requiresBindingRewrite + } + for entry in selected { + guard let path = entry.path, let source = aliases[entry.sourceAlias] else { + throw LinkError.invalid("native member resource lacks producer coordinates", chain) + } + let resource = try resource(path, in: source, chain: chain) + for index in start.. ComponentDeclaration + { + guard pluginFrame != nil else { return declaration } + func path(_ value: ResourceDeclaration) throws -> ResourceDeclaration { + let address = try linking.address(value.source, in: context, chain: []) + guard let view = address.contained else { + throw LinkError.invalid("unselected native resource", []) + } + return try ResourceDeclaration( + path: view.relativePath( + PathSafety.resolvedChild(base: view.directory(), subpath: value.path))) + } + func run(_ value: ExecutableDeclaration) throws -> ExecutableDeclaration { + var value = value + if value.executable.contains("/") { + value.executable = try path(.init(path: value.executable)).path + } + value.workingDirectory = try value.workingDirectory.map(path) + return value + } + func prompt(_ value: PromptBody) throws -> PromptBody { + if case .file(let resource) = value { return try .file(path(resource)) } + return value + } + switch declaration { + case .mcpServer(let name, .stdio(let invocation), let agents, let condition, let native): + return try .mcpServer( + name: name, transport: .stdio(run(invocation)), agents: agents, + condition: condition, native: native) + case .hook( + let name, let event, let invocation, let matcher, let timeout, let agents, let condition, + let native): + return try .hook( + name: name, event: event, run: run(invocation), matcher: matcher, + timeoutSeconds: timeout, agents: agents, condition: condition, native: native) + case .lspServer( + let name, let invocation, let languages, let options, let agents, let condition, let native): + return try .lspServer( + name: name, run: run(invocation), languages: languages, + initializationOptions: options, agents: agents, condition: condition, native: native) + case .command( + let name, let description, let body, let parameters, let agents, let condition, let native): + return try .command( + name: name, description: description, prompt: prompt(body), + parameters: parameters, agents: agents, condition: condition, native: native) + case .subagent( + let name, let description, let body, let model, let tools, let agents, let condition, + let native): + return try .subagent( + name: name, description: description, prompt: prompt(body), model: model, + tools: tools, agents: agents, condition: condition, native: native) + default: return declaration + } + } +} diff --git a/Tests/ComponentsTests/LedgerReplayTests.swift b/Tests/ComponentsTests/LedgerReplayTests.swift index f549f27..4a04aba 100644 --- a/Tests/ComponentsTests/LedgerReplayTests.swift +++ b/Tests/ComponentsTests/LedgerReplayTests.swift @@ -22,7 +22,7 @@ struct LedgerReplayTests { try fixture.manifest( """ version: 1 - components: [{"kind": "mcpServer", "name": "server", "transport": {"kind": "stdio", "executable": "./bin/server"}}, {"kind": "command", "name": "task", "description": "Task", "prompt": {"file": {"path": "prompts/task.md"}}}, {"kind": "plugin", "name": "vendor", "path": "vendor", "source": "."}] + components: [{"kind": "mcpServer", "name": "server", "transport": {"kind": "stdio", "executable": "./bin/server"}}, {"kind": "command", "name": "task", "description": "Task", "prompt": {"file": {"path": "prompts/task.md"}}}, {"kind": "plugin", "name": "vendor", "path": "vendor", "source": ".", "mode": "native", "agents": ["claude-code"]}] """, at: project) try run("ledger-freeze", root: project) let ledger = try fixture.store.loadLedger(limits: .standard) @@ -185,7 +185,7 @@ struct LedgerResourceClosureTests { atPath: fixture.project.appendingPathComponent("vendor/reference").path, withDestinationPath: "../shared/text") let document = try fixture.document( - "version: 1\ncomponents: [{\"kind\": \"plugin\", \"name\": \"vendor\", \"path\": \"vendor\", \"source\": \".\"}]\n" + "version: 1\ncomponents: [{\"kind\": \"plugin\", \"name\": \"vendor\", \"path\": \"vendor\", \"source\": \".\", \"mode\": \"native\", \"agents\": [\"claude-code\"]}]\n" ) var ledger = try ComponentLinker.withLinkedComponents( document: document, store: fixture.store, platform: .macOS diff --git a/Tests/ComponentsTests/PluginLinkingTests.swift b/Tests/ComponentsTests/PluginLinkingTests.swift new file mode 100644 index 0000000..922e223 --- /dev/null +++ b/Tests/ComponentsTests/PluginLinkingTests.swift @@ -0,0 +1,325 @@ +import AgentsCore +import Components +import Foundation +import Testing + +@Suite("Plugin occurrence linking", .serialized) +struct PluginLinkingTests { + private func container(_ fixture: LinkFixture, _ path: String, at root: URL) throws { + try fixture.write("{\"name\":\"review\"}", to: path + "/.claude-plugin/plugin.json", base: root) + try fixture.write( + "---\ndescription: Review command\n---\nReview carefully\n", + to: path + "/commands/review.md", base: root) + try fixture.write( + "---\nname: review\ndescription: Review skill\nplatforms: [macos]\n---\nBody\n", + to: path + "/skills/review/SKILL.md", base: root) + try fixture.write("shared support", to: path + "/shared/context.md", base: root) + try fixture.write("#!/bin/sh\nexit 0\n", to: path + "/shared/server", base: root) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: root.appendingPathComponent(path + "/shared/server").path) + try FileManager.default.createDirectory( + at: root.appendingPathComponent(path + "/bin"), + withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: root.appendingPathComponent(path + "/bin/server").path, + withDestinationPath: "../shared/server") + try fixture.write( + "{\"mcpServers\":{\"server\":{\"command\":\"${CLAUDE_PLUGIN_ROOT}/bin/server\"}}}", + to: path + "/.mcp.json", base: root) + } + + private func freeze(_ fixture: LinkFixture, _ expression: String) throws -> ResolvedLedger { + try ComponentLinker.withLinkedComponents( + document: fixture.document(expression), + store: fixture.store, platform: .macOS + ) { graph, session in + let locations = Dictionary( + (graph.sourceSnapshots + graph.declaringSnapshots).filter { + $0.source?.kind == .local && $0.container == nil + }.map { + ( + $0.snapshot.source, + LedgerLocation( + kind: .absolute, + path: String($0.snapshot.source.dropFirst("local:".count))) + ) + }, uniquingKeysWith: { first, _ in first }) + return try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: locations), limits: .standard) + } + } + + @Test func multiParentSelectionNamespacesAndRestrictions() throws { + let fixture = try LinkFixture() + try container(fixture, "one", at: fixture.project) + try container(fixture, "two", at: fixture.project) + let expression = """ + version: 1 + defaultAgents: ["claude-code", "codex"] + components: + - {kind: plugin, name: first, path: one, source: ".", agents: ["claude-code"]} + - {kind: plugin, name: repeated, path: one, source: ".", condition: {agents: []}} + - {kind: plugin, name: second, path: two, source: ".", select: [command], exclude: [{kind: command, name: review}]} + - {kind: plugin, name: empty, path: one, source: ".", select: []} + """ + let graph = try fixture.link(expression) + let parents = graph.components.filter { $0.key.kind == .plugin } + #expect(parents.count == 4) + #expect(parents.map { $0.origins[0].pluginExpansion!.children.count } == [3, 3, 0, 0]) + let members = graph.components.filter { $0.key.containerRoot != nil } + #expect(members.count == 6) + #expect(Set(members.map(\.key)).count == 3) + #expect(members.prefix(3).allSatisfy { $0.recipients == [.claudeCode] }) + #expect(members.suffix(3).allSatisfy { $0.recipients.isEmpty }) + #expect(members.allSatisfy { !$0.origins[0].consumerEditable }) + #expect(throws: LinkError.self) { try graph.requireEditable(members[0].key) } + let ledger = try freeze(fixture, expression) + #expect(ledger.occurrences.count == 10) + #expect(ledger.occurrences.filter { $0.pluginExpansion != nil }.count == 4) + #expect(ledger.occurrences.filter { $0.pluginMember != nil }.count == 6) + #expect( + ledger.resources.values.allSatisfy { !$0.path.hasSuffix("plugin.json") && $0.path != "one" }) + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + #expect(try ResolvedLedgerCodec.decode(bytes, limits: .standard) == ledger) + #expect( + ledger.occurrences.filter { $0.pluginMember != nil }.allSatisfy { + $0.input?.format == "native/claudePluginV1@1" + }) + let both = try fixture.link( + """ + version: 1 + components: [{kind: plugin, name: a, path: one, source: "."}, {kind: plugin, name: b, path: two, source: "."}] + """) + #expect(Set(both.components.filter { $0.key.kind == .command }.map(\.key)).count == 2) + } + + @Test func remoteChildrenAndEmptyFreezeKeepExactProducer() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("producer") + try fixture.initialize(repository) + try container(fixture, "plugins/review", at: repository) + let first = try fixture.commit(repository, tag: "1.0.0") + let source = + "sources: {p: {url: \"file://localhost\(repository.path)\", requirement: {exact: \"1.0.0\"}}}" + let expression = + "version: 1\n" + source + + "\ncomponents: [{kind: plugin, name: p, path: plugins/review, source: p}]" + let ledger = try freeze(fixture, expression) + let expansion = try #require(ledger.occurrences.first?.pluginExpansion) + #expect(ledger.sources[expansion.source]?.revision == first) + #expect( + ledger.components.values.filter { $0.containerRoot != nil }.allSatisfy { + $0.declaringSource == expansion.source && $0.source == expansion.source + }) + let executable = try #require(ledger.resources.values.first { $0.path.hasSuffix("bin/server") }) + #expect(!executable.support.isEmpty) + #expect(ledger.resources.values.allSatisfy { $0.kind == .git }) + let mcp = try #require(ledger.components.values.first { $0.kind == "mcpServer" }) + #expect( + mcp.payload.object?["transport"]?.object?["run"]?.object?["executable"]?.text + == "plugins/review/bin/server") + #expect( + !String(decoding: try ResolvedLedgerCodec.encode(ledger, limits: .standard), as: UTF8.self) + .contains("agents-source-")) + let empty = try freeze( + fixture, + "version: 1\n" + source + + "\ncomponents: [{kind: plugin, name: p, path: plugins/review, source: p, select: []}]") + let emptyExpansion = try #require(empty.occurrences.first?.pluginExpansion) + #expect(emptyExpansion.children.isEmpty) + #expect(empty.sources[emptyExpansion.source]?.revision == first) + #expect(empty.resources.isEmpty) + try FileManager.default.removeItem(at: repository) + let decoded = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(ledger, limits: .standard), limits: .standard) + #expect(decoded.occurrences == ledger.occurrences) + } + + @Test func memberIdentityDoesNotInheritDeclaringParentGroup() throws { + let fixture = try LinkFixture() + try container(fixture, "one", at: fixture.project) + let graph = try fixture.link( + """ + version: 1 + groups: + left: {components: [{kind: plugin, name: left, path: one, source: ".", select: [command]}]} + right: {components: [{kind: plugin, name: right, path: one, source: ".", select: [command]}]} + uses: [{group: left}, {group: right}] + """) + let children = graph.components.filter { $0.key.kind == .command } + #expect(children.count == 2) + #expect(Set(children.map(\.key)).count == 1) + #expect(children.allSatisfy { $0.key.group == nil && $0.origins[0].reference != nil }) + #expect(Set(children.map { $0.origins[0].pluginMember!.parentOccurrence }).count == 2) + } + + @Test func selectedMembersKeepIndependentDirectPins() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("producer") + try fixture.initialize(repository) + try container(fixture, "one", at: repository) + let first = try fixture.commit(repository, tag: "1.0.0") + let expression = """ + version: 1 + sources: {p: {url: "file://localhost\(repository.path)", requirement: {from: "1.0.0"}}} + components: [{kind: skills, source: p, select: [review]}, {kind: plugin, name: p, path: one, source: p, select: [mcpServer]}] + """ + let before = try fixture.link(expression) + let direct = try #require(before.components.first { $0.key.kind == .skills }) + try fixture.write("new binary", to: "one/shared/server", base: repository) + try fixture.write( + "---\nname: review\ndescription: Changed\n---\nChanged\n", + to: "one/skills/review/SKILL.md", base: repository) + let second = try fixture.commit(repository, tag: "1.1.0") + let after = try fixture.link(expression, directPins: [direct.key: try #require(direct.pin)]) + #expect(after.components.first { $0.key.kind == .skills }?.snapshot.revision == first) + #expect(after.components.first { $0.key.kind == .mcpServer }?.snapshot.revision == second) + #expect(!after.protectedChanges(from: before, allowing: [.skills]).isEmpty) + } + + @Test func emptyContainerAndExactExclusionSurviveFreeze() throws { + let fixture = try LinkFixture() + try fixture.write( + "{\"name\":\"empty\"}", to: "empty/.claude-plugin/plugin.json", base: fixture.project) + let empty = try freeze( + fixture, "version: 1\ncomponents: [{kind: plugin, name: empty, path: empty, source: \".\"}]") + #expect(empty.occurrences[0].pluginExpansion?.children == []) + #expect(empty.resources.isEmpty) + try fixture.write( + "{\"name\":\"unicode\"}", to: "unicode/.claude-plugin/plugin.json", base: fixture.project) + try fixture.write("Body", to: "unicode/commands/é.md", base: fixture.project) + let base = "version: 1\ncomponents: [{kind: plugin, name: u, path: unicode, source: \".\"" + let graph = try fixture.link(base + "}]") + let command = try #require(graph.components.first { $0.key.kind == .command }) + let name = command.key.name + let other = name.utf8.elementsEqual("é".utf8) ? "e\u{301}" : "é" + let kept = try fixture.link(base + ", exclude: [{kind: command, name: \"\(other)\"}]}]") + #expect(kept.components.contains { $0.key.kind == .command }) + let excluded = try fixture.link(base + ", exclude: [{kind: command, name: \"\(name)\"}]}]") + #expect(excluded.components.count == 1) + let renumbered = try fixture.link( + "version: 1\ncomponents: [{kind: ignore, name: unrelated, patterns: [temp]}, {kind: plugin, name: u, path: unicode, source: \".\"}]" + ) + #expect(renumbered.protectedChanges(from: graph, allowing: [.ignore]).isEmpty) + } + + @Test func unicodeSelectorsRemainDistinctWithinContainer() throws { + let fixture = try LinkFixture() + try fixture.write( + "{\"name\":\"unicode\"}", to: "unicode/.claude-plugin/plugin.json", base: fixture.project) + for (path, name) in [("first", "é"), ("second", "e\u{301}")] { + try fixture.write( + "---\nname: \(name)\ndescription: Agent\n---\nBody\n", + to: "unicode/agents/" + path + ".md", base: fixture.project) + } + let graph = try fixture.link( + "version: 1\ncomponents: [{kind: plugin, name: u, path: unicode, source: \".\"}]") + let members = graph.components.filter { $0.key.kind == .subagent } + #expect(members.count == 2) + #expect(Set(members.map(\.key)).count == 2) + } + + @Test func nativeModeRemainsOpaqueAndBindingBytesStayPrivate() throws { + let fixture = try LinkFixture() + try container(fixture, "one", at: fixture.project) + try fixture.write( + "{\"mcpServers\":{\"server\":{\"command\":\"server\",\"env\":{\"TOKEN\":\"CANARY-plugin-secret\"}}}}", + to: "one/.mcp.json", base: fixture.project) + let ledger = try freeze( + fixture, "version: 1\ncomponents: [{kind: plugin, name: p, path: one, source: \".\"}]") + #expect( + !String(decoding: try ResolvedLedgerCodec.encode(ledger, limits: .standard), as: UTF8.self) + .contains("CANARY-plugin-secret")) + #expect( + ledger.contentObjects.values.allSatisfy { + !String(decoding: $0, as: UTF8.self).contains("CANARY-plugin-secret") + }) + let opaque = try fixture.link( + "version: 1\ncomponents: [{kind: plugin, name: p, path: one, source: \".\", mode: native, agents: [\"claude-code\"]}]" + ) + #expect(opaque.components.count == 1) + #expect(opaque.components[0].origins[0].pluginExpansion == nil) + #expect(opaque.components[0].resources.count == 1) + #expect(throws: (any Error).self) { + _ = try fixture.link( + "version: 1\ncomponents: [{kind: plugin, name: p, path: one, source: \".\", mode: native, agents: [\"claude-code\"], select: []}]" + ) + } + } + + @Test func strictClosureAndByteExactNoOp() throws { + let fixture = try LinkFixture() + try container(fixture, "one", at: fixture.project) + let ledger = try freeze( + fixture, + "version: 1\ncomponents: [{kind: plugin, name: p, path: one, source: \".\"}]") + func refused(_ change: (inout ResolvedLedger) -> Void) { + var value = ledger + change(&value) + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.encode(value, limits: .standard) + } + } + refused { $0.occurrences[0].pluginExpansion!.children.removeLast() } + refused { $0.occurrences[1].pluginMember!.parent = 9 } + refused { $0.occurrences[1].pluginMember!.parent = 1 } + refused { $0.occurrences[1].pluginMember!.kind = "hook" } + refused { $0.occurrences[1].consumerEditable = true } + refused { $0.occurrences[0].pluginExpansion!.containerRoot = "../escape" } + refused { $0.occurrences[0].pluginExpansion!.children.reverse() } + refused { $0.occurrences[0].recipients = [] } + refused { $0.occurrences[0].condition.platforms = [] } + refused { + $0.occurrences[2].component = $0.occurrences[1].component + $0.occurrences[2].pluginMember = $0.occurrences[1].pluginMember + } + refused { $0.occurrences[1].manifestPath = "elsewhere/child.md" } + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + var limits = LedgerLimits.standard + limits.encodedBytes = encoded.count + #expect(try ResolvedLedgerCodec.decode(encoded, limits: limits) == ledger) + limits.encodedBytes -= 1 + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(encoded, limits: limits) + } + var json = try #require( + JSONSerialization.jsonObject(with: ResolvedLedgerCodec.encode(ledger, limits: .standard)) + as? [String: Any]) + var occurrences = try #require(json["occurrences"] as? [[String: Any]]) + var expansion = try #require(occurrences[0]["pluginExpansion"] as? [String: Any]) + expansion["unexpected"] = NSNull() + occurrences[0]["pluginExpansion"] = expansion + json["occurrences"] = occurrences + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode( + JSONSerialization.data(withJSONObject: json), limits: .standard) + } + var before = ResolvedLedger() + before.sources["source"] = .init( + kind: .local, location: .init(kind: .registered, root: "project", path: "."), revision: "é") + var after = before + after.sources["source"]!.revision = "e\u{301}" + let spaced = Data(" \n".utf8) + (try ResolvedLedgerCodec.encode(before, limits: .standard)) + #expect(try ResolvedLedgerCodec.replacement(before, existing: spaced, limits: .standard) == nil) + #expect(try ResolvedLedgerCodec.replacement(after, existing: spaced, limits: .standard) != nil) + let key = ComponentKey( + source: "s", root: ".", group: nil, kind: .command, name: "é", containerRoot: "é") + let other = ComponentKey( + source: "s", root: ".", group: nil, kind: .command, name: "e\u{301}", + containerRoot: "e\u{301}") + #expect(Set([key, other]).count == 2) + #expect( + LedgerPluginMember(parent: 0, kind: "subagent", name: "é") + != LedgerPluginMember(parent: 0, kind: "subagent", name: "e\u{301}")) + let input = LedgerInputProvenance(format: "native/claudePluginV1@1", adapterVersion: "1") + #expect( + LedgerPluginExpansion( + source: "s", root: ".", containerRoot: "é", + document: "é/.claude-plugin/plugin.json", input: input, children: []) + != LedgerPluginExpansion( + source: "s", root: ".", containerRoot: "e\u{301}", + document: "e\u{301}/.claude-plugin/plugin.json", input: input, children: [])) + } +} From e340ac0a35935c3ee886401e67aebc6db2a484ba Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:10:28 +0800 Subject: [PATCH 105/171] feat: publish private component trees atomically --- Sources/AgentsCore/DirectoryHandle.swift | 17 +- Sources/AgentsCore/FileAccess.swift | 14 +- Sources/AgentsCore/FileHash.swift | 2 +- Sources/AgentsCore/FileTransaction.swift | 94 ++- .../AgentsCore/LedgerDisplayEvidence.swift | 12 +- Sources/AgentsCore/LedgerStateStore.swift | 14 + .../AgentsCore/NativeTargetCoordination.swift | 51 ++ .../AgentsCore/PrivateMaterialization.swift | 97 ++- Sources/AgentsCore/PrivateTree.swift | 220 +++++++ Sources/AgentsCore/TransactionDisposal.swift | 9 +- Sources/AgentsCore/TransactionEvidence.swift | 220 ++++++- Sources/AgentsCore/TransactionJournal.swift | 31 +- .../AgentsCore/TransactionPublication.swift | 32 +- Sources/AgentsCore/TransactionRecovery.swift | 5 +- Sources/AgentsCore/TransactionSession.swift | 31 +- Tests/AgentsCoreTests/PrivateTreeTests.swift | 562 ++++++++++++++++++ .../RegisteredNativeTargetTests.swift | 1 - .../StateTransactionTests.swift | 15 +- .../PrivateMaterializationProbe.swift | 44 ++ 19 files changed, 1372 insertions(+), 99 deletions(-) create mode 100644 Sources/AgentsCore/PrivateTree.swift create mode 100644 Tests/AgentsCoreTests/PrivateTreeTests.swift diff --git a/Sources/AgentsCore/DirectoryHandle.swift b/Sources/AgentsCore/DirectoryHandle.swift index bd4773e..4dcfc6d 100644 --- a/Sources/AgentsCore/DirectoryHandle.swift +++ b/Sources/AgentsCore/DirectoryHandle.swift @@ -122,11 +122,13 @@ final class DirectoryHandle { var names: [String] = [] errno = 0 while let entry = readdir(stream) { - let name = String(cString: platform_entry_name(entry)) + guard let name = String(validatingCString: platform_entry_name(entry)) else { + throw CoreError.unsafePath("filesystem entry is not valid UTF-8") + } if name != "." && name != ".." { names.append(name) } } guard errno == 0 else { throw CoreError.unsafePath("cannot enumerate \(url.path)") } - return names.sorted() + return names.sorted { $0.utf8.lexicographicallyPrecedes($1.utf8) } } enum RemovalStep: String { case unlinked, synced } @@ -170,12 +172,15 @@ final class DirectoryHandle { throw CoreError.unsafePath("cannot make removed directory writable: \(name)") } } + let recorded = expected?.children.map { + Dictionary(uniqueKeysWithValues: $0.map { (Data($0.name.utf8), $0.snapshot) }) + } for child in try directory.names() { - if let expected, expected.children?[child] == nil { + if expected != nil, recorded?[Data(child.utf8)] == nil { throw CoreError.invalidState("unexpected descendant during removal: \(child)") } try directory.removeContents( - child, expected: expected?.children?[child], identity: nil, + child, expected: recorded?[Data(child.utf8)], identity: nil, prefix: prefix.isEmpty ? child : prefix + "/" + child, checkpoint: checkpoint) } try directory.sync() @@ -564,8 +569,8 @@ final class DirectoryHandle { private func synchronizeContents(_ name: String, as snapshot: FileSnapshot) throws { if let children = snapshot.children { let directory = try child(name) - for (child, value) in children.sorted(by: { $0.key < $1.key }) { - try directory.synchronizeContents(child, as: value) + for member in children { + try directory.synchronizeContents(member.name, as: member.snapshot) } try directory.sync() } else if snapshot.isRegular { diff --git a/Sources/AgentsCore/FileAccess.swift b/Sources/AgentsCore/FileAccess.swift index cc31a25..b4967c6 100644 --- a/Sources/AgentsCore/FileAccess.swift +++ b/Sources/AgentsCore/FileAccess.swift @@ -17,6 +17,14 @@ package struct FileAccessEvidence: Codable, Equatable, Sendable { let acl: Data let defaultACL: Data + func admits(_ current: Self, removal: Bool, directoryWrite: Bool = false) -> Bool { + if self == current { return true } + guard removal || directoryWrite, identity.isDirectory else { return false } + return Self( + identity: identity, owner: owner, group: group, mode: mode | (removal ? 0o700 : 0o200), + aclFormat: aclFormat, acl: acl, defaultACL: defaultACL) == current + } + static func capture(descriptor: Int32) throws -> Self { try read(descriptor: descriptor).evidence } @@ -119,10 +127,12 @@ extension DirectoryHandle { /// Returns an empty verified inode. No producer receives a writable payload /// path before verification; inherited ACLs are retained and evaluated as found. - func createPrivateFile(_ name: String) throws -> PrivateFileHandle { + func createPrivateFile(_ name: String, executable: Bool = false) throws -> PrivateFileHandle { try requireAccessComponent(name) let parentEvidence = try privateCreationParent() - let file = openat(descriptor, name, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) + let file = openat( + descriptor, name, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, + executable ? 0o700 : 0o600) guard file >= 0 else { throw CoreError.invalidState("cannot create private file: \(errno)") } var retained = false defer { if !retained { close(file) } } diff --git a/Sources/AgentsCore/FileHash.swift b/Sources/AgentsCore/FileHash.swift index db5827e..5b92fa2 100644 --- a/Sources/AgentsCore/FileHash.swift +++ b/Sources/AgentsCore/FileHash.swift @@ -63,7 +63,7 @@ package enum FileHash { var hasher = SHA256() // Each field has a fixed-width byte length, so arbitrary payload bytes cannot // impersonate paths, entry types or record boundaries. - for (path, content) in entries.sorted(by: { $0.0 < $1.0 }) { + for (path, content) in entries.sorted(by: { $0.0.utf8.lexicographicallyPrecedes($1.0.utf8) }) { for field in [Data(path.utf8), content] { var length = UInt64(field.count).bigEndian withUnsafeBytes(of: &length) { hasher.update(data: Data($0)) } diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 9b542ac..9f6c4ba 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -16,6 +16,8 @@ package final class FileTransaction { /// Checks for the sealed staging; nil fields are not compared. struct Expectation { var hash: String? + /// Complete byte-identified subtree content and execute intent, independent of inode copies. + var objectDigest: String? var executableFlags: [String: Bool]? var kind: mode_t? var mode: mode_t? @@ -30,6 +32,7 @@ package final class FileTransaction { let expectation: Expectation let security: TransactionSecurity let privateData: (() throws -> Data)? + var privateTree: PrivateTree? = nil var installs: Bool { source != nil || security.replacement == .privateMaterialization } } private let store: StateStore @@ -126,7 +129,8 @@ package final class FileTransaction { provider: any RuntimeBindingProvider, render: @escaping (RuntimeBindingValues) throws -> Data ) throws { - guard prepared.target.scope.path == store.directory.path, prepared.owner == geteuid(), + guard NativeTargetRoute.targetRoute(prepared.target.path)?.isContainer != true, + prepared.target.scope.path == store.directory.path, prepared.owner == geteuid(), bindings.allSatisfy({ !$0.isEmpty && !$0.contains("\0") }) else { throw CoreError.invalidState("invalid private materialization inputs") } guard let receiptEvidence = prepared.receiptEvidence else { @@ -163,6 +167,33 @@ package final class FileTransaction { })) } + /// Replaces one registered named container atomically. Inputs own their bytes. + package func replacePrivateTree( + _ prepared: PreparedPrivateMaterialization, entries: [PrivateTreeEntry], + provider: any RuntimeBindingProvider + ) throws { + guard NativeTargetRoute.targetRoute(prepared.target.path)?.isContainer == true, + prepared.target.scope.path.utf8.elementsEqual(store.directory.path.utf8), + prepared.owner == geteuid(), let receipt = prepared.receiptEvidence + else { throw CoreError.invalidState("private tree requires its prepared registered container") } + let tree = try PrivateTree(entries: entries, provider: provider, environment: store.environment) + try receipt.validate() + let (path, evidence, previous) = try request(prepared.target.url, expecting: prepared.evidence) + guard path.utf8.elementsEqual(prepared.target.path.utf8) else { + throw CoreError.invalidState("materialization registration changed") + } + var security = previous + security.replacement = .privateMaterialization + security.permissionChange = prepared.accessChange != nil + security.preimageAccess = prepared.beforeAccess + security.preimageTreeAccess = prepared.preimageTreeAccess + security.ancestry = prepared.ancestry + requests.append( + Request( + path: path, evidence: evidence, source: nil, + expectation: .init(kind: S_IFDIR), security: security, privateData: nil, privateTree: tree)) + } + private func queueReceipt() throws { let originals = requests for state in receiptStates.values.sorted(by: { $0.path < $1.path }) { @@ -235,6 +266,25 @@ package final class FileTransaction { guard evidence.url.path == destination.standardizedFileURL.path else { throw CoreError.invalidState("precondition belongs to another target") } + if let snapshot = evidence.snapshot, snapshot.identity.isDirectory { + func holdsCoordination(_ value: FileSnapshot) -> Bool { + (value.children ?? []).contains { member in + let metadata = + member.name.utf8.elementsEqual(SharedResource.metadataName.utf8) + && member.snapshot.identity.isDirectory + && (member.snapshot.children ?? []).contains { domain in + domain.name.utf8.count == 64 + && domain.name.utf8.allSatisfy { (48...57).contains($0) || (97...102).contains($0) } + && domain.snapshot.identity.isDirectory + && domain.snapshot.child(named: "lock")?.isRegular == true + } + return metadata || holdsCoordination(member.snapshot) + } + } + guard !holdsCoordination(snapshot) else { + throw CoreError.unsafePath("container contains independently coordinated native targets") + } + } var security = TransactionSecurity() if let record = receiptState.records.targets[path] { let paths = TransactionPaths(store: store) @@ -251,6 +301,10 @@ package final class FileTransaction { _ = try parent.requirePrivateAccess(destination.lastPathComponent, matching: record.access) security.preimage = .privateMaterialization security.preimageAccess = record.access + security.preimageTreeAccess = record.treeAccess + try TreeMemberAccess.verify( + record.treeAccess, snapshot: evidence.snapshot!, named: destination.lastPathComponent, + in: parent, requirePrivate: true) security.ancestry = try DirectoryAccessEvidence.capture(at: parent.url) } return (path, evidence, security) @@ -261,16 +315,10 @@ package final class FileTransaction { ) throws -> Expectation { let physical = source.resolvingSymlinksInPath() let parent = try DirectoryHandle(at: physical.deletingLastPathComponent()) - if let hash, let flags { - let info = try parent.info(physical.lastPathComponent) - return Expectation( - hash: hash, executableFlags: flags, kind: info.map(FileObjectIdentity.init)?.kind, - mode: info.map { $0.st_mode & 0o7777 }) - } let capture = try FileSnapshot.capture(physical.lastPathComponent, from: parent) guard let snapshot = capture.snapshot else { throw CoreError.notFound(source.path) } return Expectation( - hash: hash ?? "sha256:" + capture.contentHash, + hash: hash ?? "sha256:" + capture.contentHash, objectDigest: snapshot.digest, executableFlags: flags ?? capture.executableFlags, kind: snapshot.identity.kind, mode: snapshot.mode) } @@ -319,15 +367,17 @@ package final class FileTransaction { for (index, request) in requests.enumerated() { if let state = receiptIndices[index] { try session.stage(index, source: request.source, expectation: request.expectation) { - try StateStore.encode( + let bytes = try StateStore.encode( session.materializationReceipts( previous: state.records, targetRoot: NativeTargetRoute.metadataRoute(state.path)?.root)) + try LedgerAdmission.check(bytes, limits: .standard) + return bytes } } else { try session.stage( index, source: request.source, expectation: request.expectation, - privateData: request.privateData) + privateData: request.privateData, privateTree: request.privateTree) } } try session.emit(.preconditions) @@ -358,7 +408,16 @@ package final class FileTransaction { private func validateOverlap() throws { var targets: [URL] = [] + var treeMembers = 0 + var treeBytes = 0 for request in requests { + if let tree = request.privateTree { + guard tree.entries.count <= LedgerLimits.standard.entries - treeMembers, + tree.inputBytes <= LedgerLimits.standard.resourceBytes - treeBytes + else { throw CoreError.invalidState("private trees exceed candidate limits") } + treeMembers += tree.entries.count + treeBytes += tree.inputBytes + } let target = request.evidence.physicalURL guard !targets.contains(where: { @@ -426,12 +485,25 @@ package final class FileTransaction { roots.keys.compactMap { key in NativeTargetRoute.sharedRoute(key) ?? NativeTargetRoute.metadataRoute(key) }) - let resources = try sharedRoutes.map { route in + let admittedResources = try sharedRoutes.map { route in guard let context = TransactionLockContext.current(store) else { throw CoreError.invalidState("shared transaction requires its held footprint") } return try context.resource(for: route) }.sorted { $0.identity < $1.identity } + var resources: [SharedResource] = [] + for resource in admittedResources + where !resources.contains(where: { $0.identity == resource.identity }) { + resources.append(resource) + } + for index in entries.indices { + if let route = NativeTargetRoute.sharedRoute(entries[index].path) + ?? NativeTargetRoute.metadataRoute(entries[index].path) + { + let resource = try TransactionLockContext.current(store)!.resource(for: route) + entries[index].coordination = resources.firstIndex { $0.identity == resource.identity } + } + } let journal = TransactionJournal( id: id, scope: try directory.identity, roots: try roots.mapValues { try $0.identity }, entries: entries, containers: containers, diff --git a/Sources/AgentsCore/LedgerDisplayEvidence.swift b/Sources/AgentsCore/LedgerDisplayEvidence.swift index a920a3f..baa3781 100644 --- a/Sources/AgentsCore/LedgerDisplayEvidence.swift +++ b/Sources/AgentsCore/LedgerDisplayEvidence.swift @@ -28,12 +28,22 @@ extension TargetPrecondition { let linkGroup: UInt32? } let access = try TargetAccessPrecondition.capture(at: physicalURL) + var ancestry = access.ancestry.directories + for (root, before) in TransactionLockContext.currentForDisplay?.createdAncestry ?? [] { + let parent = physicalURL.deletingLastPathComponent().path + if parent.utf8.elementsEqual(root.path.utf8) || parent.hasPrefix(root.path + "/") { + guard ancestry.starts(with: before.directories) else { + throw CoreError.invalidState("existing publication ancestry access changed") + } + ancestry = before.directories + } + } return try ResolvedLedgerCodec.digest( Display( path: physicalURL.path, exists: snapshot != nil, content: includeContent ? snapshot?.digest : nil, target: access.target.map(Access.init), - ancestry: access.ancestry.directories.map(Access.init), linkOwner: access.linkOwner, + ancestry: ancestry.map(Access.init), linkOwner: access.linkOwner, linkGroup: access.linkGroup)) } } diff --git a/Sources/AgentsCore/LedgerStateStore.swift b/Sources/AgentsCore/LedgerStateStore.swift index c189a33..d8b01b9 100644 --- a/Sources/AgentsCore/LedgerStateStore.swift +++ b/Sources/AgentsCore/LedgerStateStore.swift @@ -48,6 +48,20 @@ extension StateStore { for route in NativeTargetRoute.allCases { roots[route.root] = try? route.logicalDirectory(environment).resolvingSymlinksInPath() } + for route in TransactionLockContext.current(self)?.requestedRoutes ?? [] + where route.isNamed && route.permits(scope) { + roots[route.root] = try? route.physicalDirectory(environment) + } + if let ledger = try? readLedger() { + for deployment in ledger.deployments { + guard deployment.target.kind == .registered, let key = deployment.target.root, + let route = NativeTargetRoute.targetRoute(key), route.isNamed, + route.permits(scope), deployment.target.path.utf8.elementsEqual(route.basename.utf8), + Set(deployment.recipients).isSubset(of: route.knownReaders) + else { continue } + roots[key] = try? route.physicalDirectory(environment) + } + } return roots } diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index 284c31b..19b9a4d 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -742,6 +742,7 @@ final class TransactionLockContext { private static let threadKey = "agents.core.transaction-lock-context" let scopeURL: URL let resources: [SharedResource] + var createdAncestry: [(URL, DirectoryAccessEvidence)] = [] let admissions: [SharedResource] let requestedRoutes: Set let writable: Bool @@ -767,6 +768,10 @@ final class TransactionLockContext { self.absentRoots = absentRoots } + static var currentForDisplay: TransactionLockContext? { + Thread.current.threadDictionary[threadKey] as? TransactionLockContext + } + static var isHeld: Bool { Thread.current.threadDictionary[threadKey] != nil } static func current(_ store: StateStore) -> TransactionLockContext? { @@ -883,6 +888,17 @@ extension StateStore { if !route.shared, route.isNamed { let target = try route.physicalDirectory(environment).appendingPathComponent(route.basename) try requireProjectNativeAuthority(at: target) + if route.isContainer { + for shared in NativeTargetRoute.allCases where shared.shared { + let parent = try shared.rootAuthority(environment, validateExistingOverride: false) + .plannedPhysicalDirectory + if parent.path.utf8.elementsEqual(target.path.utf8) + || parent.path.utf8.starts(with: (target.path + "/").utf8) + { + throw CoreError.unsafePath("registered container encloses a shared native loader") + } + } + } } var canonical = route let parent: URL @@ -929,6 +945,13 @@ extension StateStore { while true { let before = try pendingCoordinationJournal(diagnosing: !writable) var resources: [SharedResource] = [] + var createdAncestry: [(URL, DirectoryAccessEvidence)] = [] + if writable { + let evidence = try DirectoryAccessEvidence.capture(at: directory) + if evidence.directories.count < directory.pathComponents.count { + createdAncestry.append((directory, evidence)) + } + } var absentRoots: [AbsentSharedRoot] = [] let pending = before?.footprint ?? [] var admissions: [SharedResource] = [] @@ -943,8 +966,35 @@ extension StateStore { let rightPending = recoveryRoutes.contains(right) return leftPending == rightPending ? left.rawValue < right.rawValue : leftPending } + let physicalTargets = try ordered.map { route in + try route.physicalDirectory(environment).appendingPathComponent(route.basename) + } + for parent in physicalTargets.map({ $0.deletingLastPathComponent() }) { + var ancestor = parent + while ancestor.path != "/" { + if let enclosing = try NativeTargetRoute.userRoute( + at: ancestor, environment: environment), enclosing.isContainer + { + throw CoreError.unsafePath("native coordination would be inside a registered container") + } + ancestor.deleteLastPathComponent() + } + } + for (index, target) in physicalTargets.enumerated() { + for (other, nested) in physicalTargets.enumerated() where index != other { + let parent = nested.deletingLastPathComponent() + if parent.path.utf8.elementsEqual(target.path.utf8) + || parent.path.hasPrefix(target.path + "/") + { + throw CoreError.unsafePath("nested native coordination domains conflict") + } + } + } for route in ordered { let recovering = recoveryRoutes.contains(route) + if writable, !recovering, let absent = try AbsentSharedRoot(store: self, route: route) { + createdAncestry.append((absent.physical, absent.ancestry)) + } if !writable, !recovering, let absent = try AbsentSharedRoot(store: self, route: route) { absentRoots.append(absent) continue @@ -983,6 +1033,7 @@ extension StateStore { store: self, resources: resources.sorted { $0.identity < $1.identity }, writable: writable, requestedShared: routes.contains(where: \.shared), absentRoots: absentRoots, admissions: admissions, requestedRoutes: routes) + context.createdAncestry = createdAncestry context.existingProjectRoot = existingRoot context.projectRootDirectory = projectRoot func locked(_ index: Int) throws -> T? { diff --git a/Sources/AgentsCore/PrivateMaterialization.swift b/Sources/AgentsCore/PrivateMaterialization.swift index 2fc02cf..7371f49 100644 --- a/Sources/AgentsCore/PrivateMaterialization.swift +++ b/Sources/AgentsCore/PrivateMaterialization.swift @@ -17,7 +17,7 @@ package struct RuntimeBindingValues: CustomStringConvertible, CustomDebugStringC package var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } private let values: [String: Data] - init(_ values: [String: Data]) { self.values = values } + package init(_ values: [String: Data]) { self.values = values } package func value(for binding: String) throws -> Data { guard let value = values[binding] else { @@ -27,7 +27,7 @@ package struct RuntimeBindingValues: CustomStringConvertible, CustomDebugStringC } } -/// A physical file admitted by Core's existing, scope-owned path registrations. +/// A file or complete named container admitted by Core's scope-owned path registrations. package struct MaterializationTarget { package let url: URL package let path: String @@ -41,10 +41,18 @@ package struct PrivateAccessChange { package let mode: UInt32 } +package struct PrivateTreeAccessChange { + package let path: String + package let before: FileAccessEvidence + package let owner: UInt32 + package let mode: UInt32 +} + /// A local receipt view has no payload digest or serializable binding data. package struct MaterializationReceipt { package let generation: UUID package let access: FileAccessEvidence + package let treeAccess: [TreeMemberAccess]? } package struct PreparedPrivateMaterialization { @@ -54,14 +62,18 @@ package struct PreparedPrivateMaterialization { package let target: MaterializationTarget let evidence: TargetPrecondition let receiptEvidence: TargetPrecondition? + package let memberAccessChanges: [PrivateTreeAccessChange] + let preimageTreeAccess: [TreeMemberAccess]? var ancestry: DirectoryAccessEvidence { evidence.access!.ancestry } var beforeAccess: FileAccessEvidence? { evidence.access?.target } /// A non-secret access segment for the enclosing candidate's displayed fingerprint. package func accessFingerprint() throws -> String { let input = PrivateAccessFingerprint( - target: target.path, owner: owner, before: beforeAccess, ancestry: ancestry, - permissionChange: accessChange != nil, receiptGeneration: receiptGeneration) + target: target.path, owner: owner, + publicationAccess: try evidence.displayEvidence(includeContent: false), + permissionChange: accessChange != nil, receiptGeneration: receiptGeneration, + members: preimageTreeAccess) return "sha256:" + FileHash.sha256Hex(data: try StateStore.encode(input)) } } @@ -70,10 +82,10 @@ private struct PrivateAccessFingerprint: Encodable { let version = 1 let target: String let owner: UInt32 - let before: FileAccessEvidence? - let ancestry: DirectoryAccessEvidence + let publicationAccess: String let permissionChange: Bool let receiptGeneration: UUID? + let members: [TreeMemberAccess]? } extension StateStore { @@ -106,7 +118,8 @@ extension StateStore { return nil } _ = try preparePrivateMaterialization(target, expecting: record.generation) - return MaterializationReceipt(generation: record.generation, access: record.access) + return MaterializationReceipt( + generation: record.generation, access: record.access, treeAccess: record.treeAccess) } /// Under the caller's scope lock, preparation never calls a provider or renderer. @@ -114,9 +127,6 @@ extension StateStore { _ target: MaterializationTarget, changingAccess: Bool = false, requiringReceiptForExistingTarget: Bool = false, expecting generation: UUID? = nil ) throws -> PreparedPrivateMaterialization { - if NativeTargetRoute.targetRoute(target.path)?.isContainer == true { - throw CoreError.invalidState("private materialization requires a registered regular file") - } guard target.scope.path == directory.path, try TransactionPaths(store: self).path(for: target.url) == target.path else { throw CoreError.invalidState("materialization target belongs to another scope") } @@ -129,7 +139,7 @@ extension StateStore { let evidence = try TargetPrecondition(target.url).capturingAccess() return PreparedPrivateMaterialization( owner: UInt32(geteuid()), receiptGeneration: nil, accessChange: nil, target: target, - evidence: evidence, receiptEvidence: nil) + evidence: evidence, receiptEvidence: nil, memberAccessChanges: [], preimageTreeAccess: nil) } let receipt = try materializationReceipts(for: target.path) let record = receipt.records.targets[target.path] @@ -140,17 +150,50 @@ extension StateStore { guard !requiringReceiptForExistingTarget || evidence.snapshot == nil || record != nil else { throw CoreError.invalidState("known materialized target is missing its private receipt") } - guard evidence.snapshot == nil || evidence.snapshot?.isRegular == true else { - throw CoreError.unsafePath("private materialization requires a regular file") + guard + evidence.snapshot == nil || evidence.snapshot?.isRegular == true + || evidence.snapshot?.identity.isDirectory == true + else { + throw CoreError.unsafePath( + "private materialization requires a regular file or registered container") } let parentURL = evidence.physicalURL.deletingLastPathComponent() let ancestry = try DirectoryAccessEvidence.capture(at: parentURL) var beforeAccess: FileAccessEvidence? var change: PrivateAccessChange? + var tree: [TreeMemberAccess]? + var memberChanges: [PrivateTreeAccessChange] = [] + let privateMode: mode_t = evidence.snapshot?.identity.isDirectory == true ? 0o700 : 0o600 if evidence.snapshot != nil { let parent = try DirectoryHandle(at: parentURL) beforeAccess = try parent.accessEvidence(target.url.lastPathComponent) - var changesAccess = beforeAccess?.mode != 0o600 + if let snapshot = evidence.snapshot { + tree = try TreeMemberAccess.capture( + target.url.lastPathComponent, in: parent, snapshot: snapshot) + } + for member in tree ?? [] { + let parts = member.path.split(separator: "/").map(String.init) + var directory = try parent.child(target.url.lastPathComponent) + for name in parts.dropLast() { directory = try directory.child(name) } + let mode: UInt32 = + member.access.identity.isDirectory || member.access.mode & 0o100 != 0 ? 0o700 : 0o600 + var changes = UInt32(member.access.mode) != mode + do { _ = try directory.requirePrivateAccess(parts.last!, matching: member.access) } catch { + changes = true + } + if changes { + memberChanges.append( + .init(path: member.path, before: member.access, owner: UInt32(geteuid()), mode: mode)) + } + } + var changesAccess = beforeAccess?.mode != privateMode || !memberChanges.isEmpty + if let snapshot = evidence.snapshot { + do { + try TreeMemberAccess.verify( + tree, snapshot: snapshot, named: target.url.lastPathComponent, + in: parent, requirePrivate: true) + } catch { changesAccess = true } + } do { _ = try parent.requirePrivateAccess(target.url.lastPathComponent) } catch { changesAccess = true } @@ -158,7 +201,8 @@ extension StateStore { guard changingAccess, let beforeAccess else { throw CoreError.invalidState("private materialization requires an explicit access change") } - change = PrivateAccessChange(before: beforeAccess, owner: UInt32(geteuid()), mode: 0o600) + change = PrivateAccessChange( + before: beforeAccess, owner: UInt32(geteuid()), mode: UInt32(privateMode)) } } if let record = receipt.records.targets[target.path] { @@ -168,11 +212,16 @@ extension StateStore { throw CoreError.invalidState("materialization receipt root changed") } if evidence.snapshot != nil { - guard evidence.snapshot?.digest == record.digest, beforeAccess == record.access else { + guard evidence.snapshot?.digest == record.digest, beforeAccess == record.access, + tree == record.treeAccess + else { throw CoreError.invalidState("materialized preimage differs from its receipt") } _ = try DirectoryHandle(at: parentURL).requirePrivateAccess( target.url.lastPathComponent, matching: record.access) + try TreeMemberAccess.verify( + record.treeAccess, snapshot: evidence.snapshot!, named: target.url.lastPathComponent, + in: DirectoryHandle(at: parentURL), requirePrivate: true) } } try evidence.validate() @@ -180,7 +229,8 @@ extension StateStore { return PreparedPrivateMaterialization( owner: UInt32(geteuid()), receiptGeneration: record?.generation, accessChange: change, target: target, - evidence: evidence, receiptEvidence: receipt.evidence) + evidence: evidence, receiptEvidence: receipt.evidence, memberAccessChanges: memberChanges, + preimageTreeAccess: tree) } } @@ -195,6 +245,7 @@ struct MaterializationReceipts: Codable { let rootIdentity: String let digest: String let access: FileAccessEvidence + var treeAccess: [TreeMemberAccess]? = nil } func validate(store: StateStore) throws { @@ -217,9 +268,13 @@ struct MaterializationReceipts: Codable { throw CoreError.invalidState("invalid materialization receipt target") } guard - record.access.identity.kind == S_IFREG, + [mode_t(S_IFREG), mode_t(S_IFDIR)].contains(record.access.identity.kind), + record.access.identity.isDirectory == (record.treeAccess != nil), + record.access.identity.isDirectory + == (NativeTargetRoute.targetRoute(path)?.isContainer == true), !record.rootIdentity.isEmpty else { throw CoreError.invalidState("invalid materialization receipt target") } + if let members = record.treeAccess { try TreeMemberAccess.validateStructure(members) } try StateValidation.digest("sha256:" + record.digest) } } @@ -271,8 +326,10 @@ extension StateStore { let evidenceWithAccess = try evidence.capturingAccess() let access = try directory.requirePrivateAccess(url.lastPathComponent) do { - var records = try Self.decode( - directory.read(url.lastPathComponent), as: MaterializationReceipts.self) + let bytes = try directory.read( + url.lastPathComponent, maximumBytes: LedgerLimits.standard.encodedBytes) + try LedgerAdmission.check(bytes, limits: .standard) + var records = try Self.decode(bytes, as: MaterializationReceipts.self) try records.validate(store: self) if let resource { guard records.targets.count == 1, let (key, record) = records.targets.first, diff --git a/Sources/AgentsCore/PrivateTree.swift b/Sources/AgentsCore/PrivateTree.swift new file mode 100644 index 0000000..f238617 --- /dev/null +++ b/Sources/AgentsCore/PrivateTree.swift @@ -0,0 +1,220 @@ +import Foundation + +/// An owned complete candidate. Renderers receive values, never writable filesystem authority. +package struct PrivateTreeEntry { + package enum Content { + case directory + case file(Data, executable: Bool = false) + case boundFile( + bindings: Set, executable: Bool = false, + render: (RuntimeBindingValues) throws -> Data) + case symlink(String) + } + package let relativePath: String + package let content: Content + package init(_ relativePath: String, content: Content) { + self.relativePath = relativePath + self.content = content + } +} + +struct PrivateTree { + let entries: [PrivateTreeEntry] + let provider: any RuntimeBindingProvider + let environment: RuntimeEnvironment + let inputBytes: Int + let metadataBytes: Int + + init( + entries: [PrivateTreeEntry], provider: any RuntimeBindingProvider, + environment: RuntimeEnvironment + ) throws { + let limits = LedgerLimits.standard + guard entries.count <= limits.entries else { + throw CoreError.invalidState("private tree exceeds member limit") + } + var bytes = 0 + var contentBytes = 0 + var paths = Set() + var directories = Set() + var links: [(String, String)] = [] + for entry in entries { + let parts = entry.relativePath.split(separator: "/", omittingEmptySubsequences: false) + guard !parts.isEmpty, parts.count < limits.depth / 4, + parts.allSatisfy({ + !$0.isEmpty && $0 != "." && $0 != ".." && !$0.contains("\\") && !$0.contains("\0") + }), + paths.insert(Data(entry.relativePath.utf8)).inserted + else { throw CoreError.unsafePath("invalid or duplicate private tree member") } + bytes += entry.relativePath.utf8.count + switch entry.content { + case .directory: directories.insert(Data(entry.relativePath.utf8)) + case .file(let data, _): + bytes += data.count + contentBytes += data.count + case .boundFile(let names, _, _): + guard names.allSatisfy({ !$0.isEmpty && !$0.contains("\0") }) else { + throw CoreError.invalidState("invalid private tree bindings") + } + bytes += names.reduce(0) { $0 + $1.utf8.count } + case .symlink(let destination): + links.append((entry.relativePath, destination)) + bytes += destination.utf8.count + } + guard bytes <= limits.resourceBytes else { + throw CoreError.invalidState("private tree exceeds byte limit") + } + } + for entry in entries { + let parts = entry.relativePath.split(separator: "/").dropLast() + for count in 1...max(1, parts.count) where count <= parts.count { + guard directories.contains(Data(parts.prefix(count).joined(separator: "/").utf8)) else { + throw CoreError.unsafePath("private tree member lacks a real directory parent") + } + } + } + // Resolve the closed candidate graph with the same containment/dangling semantics + // as PathSafety.linkStaysInside, before creating anything or requesting bindings. + let destinations = Dictionary(uniqueKeysWithValues: links.map { (Data($0.0.utf8), $0.1) }) + var work = 0 + for (path, destination) in links { + guard !destination.hasPrefix("/"), !destination.isEmpty, !destination.contains("\0") else { + throw CoreError.unsafePath("private tree link escapes container") + } + var pending = destination.split(separator: "/").reversed().map(String.init) + var resolved = path.split(separator: "/").dropLast().map(String.init) + var expansions = 0 + while let component = pending.popLast() { + work += 1 + guard work <= limits.nodes else { + throw CoreError.invalidState("private tree link work limit") + } + if component == "." { continue } + if component == ".." { + guard !resolved.isEmpty else { + throw CoreError.unsafePath("private tree link escapes container") + } + resolved.removeLast() + continue + } + let key = Data((resolved + [component]).joined(separator: "/").utf8) + if let next = destinations[key] { + expansions += 1 + guard expansions <= 32, !next.hasPrefix("/") else { + throw CoreError.unsafePath("private tree link cycle or escape") + } + pending += next.split(separator: "/").reversed().map(String.init) + } else if paths.contains(key) { + resolved.append(component) + } else { + guard !pending.contains("..") else { + throw CoreError.unsafePath("private tree dangling link escapes container") + } + break + } + } + } + self.entries = entries.sorted { + $0.relativePath.utf8.lexicographicallyPrecedes($1.relativePath.utf8) + } + self.provider = provider + self.environment = environment + inputBytes = bytes + metadataBytes = bytes - contentBytes + } + + func construct( + named name: String, in container: DirectoryHandle, bytes: inout Int, + admit: (FileSnapshot, FileAccessEvidence, [TreeMemberAccess]?) throws -> Void, + validate: () throws -> Void + ) + throws + { + let root = try container.createPrivateDirectory(name) + func parent(_ path: String) throws -> (DirectoryHandle, String) { + let parts = path.split(separator: "/").map(String.init) + var directory = root + for component in parts.dropLast() { directory = try directory.child(component) } + return (directory, parts.last!) + } + for entry in entries { + if case .directory = entry.content { + let (directory, name) = try parent(entry.relativePath) + _ = try directory.createPrivateDirectory(name) + } + } + var files: [(PrivateTreeEntry, PrivateFileHandle)] = [] + for entry in entries { + let executable: Bool + switch entry.content { + case .file(_, let flag), .boundFile(_, let flag, _): executable = flag + default: continue + } + let (directory, name) = try parent(entry.relativePath) + files.append((entry, try directory.createPrivateFile(name, executable: executable))) + } + for entry in entries { + if case .symlink(let destination) = entry.content { + let (directory, name) = try parent(entry.relativePath) + try directory.link(name, destination: destination) + } + } + guard let physicalRoot = PathSafety.realPath(root.url.path) else { + throw CoreError.invalidState("private tree root changed during construction") + } + for entry in entries { + if case .symlink = entry.content { + guard + try PathSafety.linkStaysInside( + root.url.appendingPathComponent(entry.relativePath), root: physicalRoot) + else { + throw CoreError.unsafePath("private tree link escapes container") + } + } + } + try validate() + let emptySnapshot = try FileSnapshot.read(name, from: container)! + let rootAccess = try container.requirePrivateAccess(name) + let memberAccess = try TreeMemberAccess.capture( + name, in: container, snapshot: emptySnapshot, requirePrivate: true) + try admit(emptySnapshot, rootAccess, memberAccess) + var names = Set() + for entry in entries { + if case .boundFile(let bindings, _, _) = entry.content { names.formUnion(bindings) } + } + var values: [String: Data] = [:] + guard metadataBytes <= LedgerLimits.standard.resourceBytes - bytes else { + throw CoreError.invalidState("private trees exceed byte limit") + } + bytes += metadataBytes + do { + for binding in names.sorted() { + let data = try provider.value(for: binding, environment: environment) + guard data.count <= LedgerLimits.standard.resourceBytes - bytes else { + throw CoreError.invalidState("private tree exceeds byte limit") + } + bytes += data.count + values[binding] = data + } + let bound = RuntimeBindingValues(values) + for (entry, file) in files { + let data: Data + switch entry.content { + case .file(let bytes, _): data = bytes + case .boundFile(_, _, let render): data = try render(bound) + default: preconditionFailure() + } + guard data.count <= LedgerLimits.standard.resourceBytes - bytes else { + throw CoreError.invalidState("private tree exceeds byte limit") + } + bytes += data.count + try validate() + try file.write(data) + } + } catch { + throw CoreError.invalidState("private tree could not resolve or construct its content") + } + let sealed = try FileSnapshot.read(name, from: container)! + try container.synchronize(name, as: sealed) + } +} diff --git a/Sources/AgentsCore/TransactionDisposal.swift b/Sources/AgentsCore/TransactionDisposal.swift index 82808f0..15072ec 100644 --- a/Sources/AgentsCore/TransactionDisposal.swift +++ b/Sources/AgentsCore/TransactionDisposal.swift @@ -45,7 +45,7 @@ extension TransactionSession { for entryIndex in journal.entries.indices where journal.entries[entryIndex].container == index { for (slot, expected) in layouts[entryIndex].objects { let name = slot.name(entryIndex) - guard snapshot?.children?[name] == expected else { + guard snapshot?.child(named: name) == expected else { throw conflict(record.entry, "user object \(name) changed while sealing disposal") } } @@ -144,12 +144,17 @@ extension TransactionSession { if let expected = [entry.preimage, entry.staged].compactMap({ $0 }).first(where: { $0.identity == FileObjectIdentity(info) }) { - try entry.security.validateObject(expected, named: name, in: handle) + try entry.security.validateObject( + expected, named: name, in: handle, remaining: journal.disposing) } else if entry.progress == .queued && entry.security.replacement == .privateMaterialization && slot == TransactionSlot.staging(for: entry) { _ = try handle.requirePrivateAccess(name) + if let snapshot = try FileSnapshot.read(name, from: handle) { + _ = try TreeMemberAccess.capture( + name, in: handle, snapshot: snapshot, requirePrivate: true) + } } } } diff --git a/Sources/AgentsCore/TransactionEvidence.swift b/Sources/AgentsCore/TransactionEvidence.swift index 1a976ab..3baa172 100644 --- a/Sources/AgentsCore/TransactionEvidence.swift +++ b/Sources/AgentsCore/TransactionEvidence.swift @@ -39,7 +39,19 @@ struct FileSnapshot: Codable, Equatable, Sendable { let executable: Bool /// Final permission bits. Only publishing/restoring may temporarily add directory owner-write. let mode: mode_t - let children: [String: FileSnapshot]? + let children: [Member]? + + struct Member: Codable, Equatable, Sendable { + let name: String + let snapshot: FileSnapshot + static func == (lhs: Self, rhs: Self) -> Bool { + lhs.name.utf8.elementsEqual(rhs.name.utf8) && lhs.snapshot == rhs.snapshot + } + } + + func child(named name: String) -> FileSnapshot? { + children?.first { $0.name.utf8.elementsEqual(name.utf8) }?.snapshot + } static func read(at url: URL) throws -> FileSnapshot? { var info = stat() @@ -79,7 +91,9 @@ struct FileSnapshot: Codable, Equatable, Sendable { var records: [(String, Data)] = [] var rootBytes: Data? var flags: [String: Bool] = [:] - let value = try read(name, from: parent, relative: "") { path, kind, bytes, executable in + var budget = CaptureBudget() + let value = try read(name, from: parent, relative: "", budget: &budget) { + path, kind, bytes, executable in guard !path.isEmpty else { if kind == S_IFREG { rootBytes = bytes @@ -103,37 +117,58 @@ struct FileSnapshot: Codable, Equatable, Sendable { } static func read(_ name: String, from parent: DirectoryHandle) throws -> FileSnapshot? { - try read(name, from: parent, relative: "", collect: nil) + var budget = CaptureBudget() + return try read(name, from: parent, relative: "", budget: &budget, collect: nil) + } + + private struct CaptureBudget { + var entries = 0 + var bytes = 0 + mutating func consume(_ name: String, info: stat, depth: Int) throws { + let limits = LedgerLimits.standard + entries += 1 + let size = info.st_mode & S_IFMT == S_IFREG ? info.st_size : 0 + guard entries <= limits.entries, depth < limits.depth / 4, + size >= 0, size <= limits.resourceBytes - bytes, + name.utf8.count <= limits.resourceBytes - bytes - Int(size) + else { throw CoreError.invalidState("transaction tree exceeds resource limits") } + bytes += Int(size) + name.utf8.count + } } private static func read( - _ name: String, from parent: DirectoryHandle, relative: String, + _ name: String, from parent: DirectoryHandle, relative: String, budget: inout CaptureBudget, collect: ((String, mode_t, Data, Bool) -> Void)? ) throws -> FileSnapshot? { guard let before = try parent.info(name) else { return nil } - let children: [String: FileSnapshot]? + try budget.consume(name, info: before, depth: relative.split(separator: "/").count) + let children: [Member]? let payload: Data switch before.st_mode & S_IFMT { case S_IFDIR: let directory = try parent.child(name, matching: before) - var entries: [String: FileSnapshot] = [:] + var entries: [Member] = [] for child in try directory.names() { guard let value = try read( child, from: directory, relative: relative.isEmpty ? child : relative + "/" + child, - collect: collect) + budget: &budget, collect: collect) else { throw CoreError.invalidState("entry changed while reading: \(child)") } - entries[child] = value + entries.append(Member(name: child, snapshot: value)) } + entries.sort { $0.name.utf8.lexicographicallyPrecedes($1.name.utf8) } children = entries // Only content enters the digest; ownership is compared independently. payload = try StateStore.encode( - entries.mapValues { "\($0.identity.kind):\($0.executable):\($0.digest)" }) + entries.map { + [$0.name, "\($0.snapshot.identity.kind):\($0.snapshot.executable):\($0.snapshot.digest)"] + }) case S_IFREG: children = nil - payload = try parent.read(name, matching: before) + payload = try parent.read( + name, matching: before, maximumBytes: LedgerLimits.standard.resourceBytes) case S_IFLNK: children = nil payload = try parent.readLinkData(name) @@ -171,7 +206,15 @@ struct FileSnapshot: Codable, Equatable, Sendable { guard kinds.contains(identity.kind), mode & ~0o7777 == 0, (identity.kind == S_IFDIR) == (children != nil) else { throw CoreError.invalidState("invalid transaction object evidence") } - for (name, child) in children ?? [:] { + let members = children ?? [] + guard + zip(members, members.dropFirst()).allSatisfy({ + $0.name.utf8.lexicographicallyPrecedes($1.name.utf8) + }) + else { throw CoreError.invalidState("duplicate or unordered transaction descendants") } + for member in members { + let name = member.name + let child = member.snapshot guard !name.isEmpty, name != ".", name != "..", !name.contains("/"), !name.contains("\0") else { throw CoreError.invalidState("invalid transaction descendant") } @@ -182,7 +225,11 @@ struct FileSnapshot: Codable, Equatable, Sendable { func containsRemaining(_ current: FileSnapshot) -> Bool { guard identity == current.identity else { return false } guard let children, let remaining = current.children else { return self == current } - return remaining.allSatisfy { name, value in children[name]?.containsRemaining(value) == true } + let recorded = Dictionary( + uniqueKeysWithValues: children.map { (Data($0.name.utf8), $0.snapshot) }) + return remaining.allSatisfy { member in + recorded[Data(member.name.utf8)]?.containsRemaining(member.snapshot) == true + } } } @@ -201,45 +248,178 @@ struct TransactionSecurity: Codable { preimage == .privateMaterialization || replacement == .privateMaterialization } + var preimageTreeAccess: [TreeMemberAccess]? + var stagedTreeAccess: [TreeMemberAccess]? + func validate(entry: TransactionJournal.Entry) throws { guard !isPrivate || ancestry != nil, !permissionChange || (replacement == .privateMaterialization && entry.preimage != nil), !isPrivate || (entry.preimage == nil) == (preimageAccess == nil), replacement != .privateMaterialization || (entry.staged == nil) == (stagedAccess == nil), - !isPrivate || entry.preimage == nil || entry.preimage?.isRegular == true, - preimage != .privateMaterialization || entry.preimage?.isRegular == true, - replacement != .privateMaterialization || entry.staged == nil - || entry.staged?.isRegular == true, + preimage != .privateMaterialization || entry.preimage != nil, replacement != .privateMaterialization || entry.action == .install else { throw CoreError.invalidState("missing or contradictory transaction security evidence") } - for (snapshot, access) in [(entry.preimage, preimageAccess), (entry.staged, stagedAccess)] { + for (snapshot, access, members) in [ + (entry.preimage, preimageAccess, preimageTreeAccess), + (entry.staged, stagedAccess, stagedTreeAccess), + ] { if let access { - guard access.identity == snapshot?.identity, access.mode == snapshot?.mode else { + guard let snapshot, access.identity == snapshot.identity, access.mode == snapshot.mode, + snapshot.isRegular || snapshot.identity.isDirectory + else { throw CoreError.invalidState("transaction access evidence belongs to another object") } + try TreeMemberAccess.validate(members, snapshot: snapshot) + } else if members != nil { + throw CoreError.invalidState("tree access requires root access evidence") } } } - func validateObject(_ snapshot: FileSnapshot, named name: String, in parent: DirectoryHandle) + func validateObject( + _ snapshot: FileSnapshot, named name: String, in parent: DirectoryHandle, + remaining: Bool = false, permittingDirectoryWrite: Bool = false + ) throws { let access: FileAccessEvidence? let classification: Classification + let members: [TreeMemberAccess]? if snapshot.identity == preimageAccess?.identity { access = preimageAccess classification = preimage + members = preimageTreeAccess } else if snapshot.identity == stagedAccess?.identity { access = stagedAccess classification = replacement + members = stagedTreeAccess } else { return } guard let access else { return } if classification == .privateMaterialization { _ = try parent.requirePrivateAccess(name, matching: access) - } else if try parent.accessEvidence(name) != access { + } else if try parent.accessEvidence(name).map({ + access.admits($0, removal: remaining, directoryWrite: permittingDirectoryWrite) + }) != true { throw CoreError.invalidState("transaction object access changed") } + try TreeMemberAccess.verify( + members, snapshot: snapshot, named: name, in: parent, + requirePrivate: classification == .privateMaterialization, remaining: remaining, + permittingDirectoryWrite: permittingDirectoryWrite) + + } +} + +/// Complete, byte-ordered access evidence for real tree members; links remain snapshots. +package struct TreeMemberAccess: Codable, Equatable { + package let path: String + package let access: FileAccessEvidence + + package static func == (lhs: Self, rhs: Self) -> Bool { + lhs.path.utf8.elementsEqual(rhs.path.utf8) && lhs.access == rhs.access + } + + static func capture( + _ name: String, in parent: DirectoryHandle, snapshot: FileSnapshot, + requirePrivate: Bool = false + ) throws -> [Self]? { + guard snapshot.identity.isDirectory else { return nil } + var result: [Self] = [] + func walk(_ directory: DirectoryHandle, _ snapshot: FileSnapshot, prefix: String) throws { + for member in snapshot.children ?? [] { + let path = prefix + member.name + let value = member.snapshot + if value.isSymbolicLink { continue } + guard let access = try directory.accessEvidence(member.name), + access.identity == value.identity, + access.mode == value.mode + else { throw CoreError.invalidState("tree access changed during capture") } + if requirePrivate { _ = try directory.requirePrivateAccess(member.name, matching: access) } + result.append(Self(path: path, access: access)) + if value.identity.isDirectory { + try walk(directory.child(member.name), value, prefix: path + "/") + } + } + } + try walk(parent.child(name), snapshot, prefix: "") + result.sort { $0.path.utf8.lexicographicallyPrecedes($1.path.utf8) } + try validate(result, snapshot: snapshot) + return result + } + + static func validateStructure(_ members: [Self]) throws { + var previous: String? + guard members.count <= LedgerLimits.standard.entries else { + throw CoreError.invalidState("tree access exceeds member limit") + } + for member in members { + let parts = member.path.split(separator: "/", omittingEmptySubsequences: false) + guard !parts.isEmpty, parts.count < LedgerLimits.standard.depth / 4, + parts.allSatisfy({ + !$0.isEmpty && $0 != "." && $0 != ".." && !$0.contains("\\") && !$0.contains("\0") + }), + previous.map({ $0.utf8.lexicographicallyPrecedes(member.path.utf8) }) ?? true, + [mode_t(S_IFREG), mode_t(S_IFDIR)].contains(member.access.identity.kind), + member.access.mode & ~0o7777 == 0 + else { throw CoreError.invalidState("invalid tree access member") } + previous = member.path + } + } + + static func validate(_ members: [Self]?, snapshot: FileSnapshot) throws { + guard snapshot.identity.isDirectory else { + guard members == nil else { + throw CoreError.invalidState("file carries tree access evidence") + } + return + } + guard let members else { throw CoreError.invalidState("directory lacks tree access evidence") } + try validateStructure(members) + var expected: [(String, FileSnapshot)] = [] + func walk(_ value: FileSnapshot, prefix: String) { + for member in value.children ?? [] { + let path = prefix + member.name + if !member.snapshot.isSymbolicLink { expected.append((path, member.snapshot)) } + walk(member.snapshot, prefix: path + "/") + } + } + walk(snapshot, prefix: "") + expected.sort { $0.0.utf8.lexicographicallyPrecedes($1.0.utf8) } + guard members.count == expected.count, + zip(members, expected).allSatisfy({ + $0.path.utf8.elementsEqual($1.0.utf8) && $0.access.identity == $1.1.identity + && $0.access.mode == $1.1.mode + }) + else { throw CoreError.invalidState("incomplete or contradictory tree access evidence") } + } + + static func verify( + _ members: [Self]?, snapshot: FileSnapshot, named name: String, + in parent: DirectoryHandle, requirePrivate: Bool, remaining: Bool = false, + permittingDirectoryWrite: Bool = false + ) throws { + try validate(members, snapshot: snapshot) + guard let members else { return } + let current = try FileSnapshot.read(name, from: parent) + guard let current, + remaining + ? snapshot.containsRemaining(current) + : snapshot.matches(current, permittingDirectoryWrite: permittingDirectoryWrite) + else { + throw CoreError.invalidState("tree changed while checking access") + } + let actual = + try capture(name, in: parent, snapshot: current, requirePrivate: requirePrivate) ?? [] + let recorded = Dictionary(uniqueKeysWithValues: members.map { (Data($0.path.utf8), $0.access) }) + guard + remaining + ? actual.allSatisfy({ item in + recorded[Data(item.path.utf8)]?.admits(item.access, removal: true) == true + }) : actual == members + else { + throw CoreError.invalidState("tree member access changed") + } } } diff --git a/Sources/AgentsCore/TransactionJournal.swift b/Sources/AgentsCore/TransactionJournal.swift index aef0b43..f38caf8 100644 --- a/Sources/AgentsCore/TransactionJournal.swift +++ b/Sources/AgentsCore/TransactionJournal.swift @@ -2,7 +2,7 @@ import Foundation /// The version is independent of declaration, resolved and watch formats. struct TransactionJournal: Codable { - static let currentVersion = 3 + static let currentVersion = 4 static let fileName = "transaction.json" /// The next journal generation before it replaces `fileName`. static let incompleteFileName = "transaction.new" @@ -38,20 +38,20 @@ struct TransactionJournal: Codable { throw CoreError.invalidState("finalized transaction contradicts its terminal outcome") } } - if !finalized { - let sharedRoots = Set( - roots.keys.compactMap { key in - (NativeTargetRoute.sharedRoute(key) ?? NativeTargetRoute.metadataRoute(key))?.root - }) - let routes = sharedRoots.compactMap(NativeTargetRoute.sharedRoute) - guard sharedRoots.count == routes.count, sharedRoots.count == footprint.count, - routes.allSatisfy({ route in - footprint.contains { $0.basename.utf8.elementsEqual(route.basename.utf8) } - }), - footprint.allSatisfy({ identity in - routes.contains { $0.basename.utf8.elementsEqual(identity.basename.utf8) } - }) - else { throw CoreError.invalidState("journal roots contradict shared footprint") } + for entry in entries { + let route = + NativeTargetRoute.sharedRoute(entry.path) ?? NativeTargetRoute.metadataRoute(entry.path) + guard entry.coordination.map({ footprint.indices.contains($0) }) ?? (route == nil) else { + throw CoreError.invalidState("invalid entry coordination index") + } + if let route { + guard let index = entry.coordination, + footprint[index].basename.utf8.elementsEqual(route.basename.utf8) + else { throw CoreError.invalidState("journal route contradicts its coordination") } + } + } + guard Set(entries.compactMap(\.coordination)) == Set(footprint.indices) else { + throw CoreError.invalidState("unreferenced journal footprint") } } @@ -94,6 +94,7 @@ struct TransactionJournal: Codable { var progress: Progress = .queued var conflict: Conflict? var security = TransactionSecurity() + var coordination: Int? var name: String { String(path.split(separator: "/").last!) } } diff --git a/Sources/AgentsCore/TransactionPublication.swift b/Sources/AgentsCore/TransactionPublication.swift index 4380769..577c3a9 100644 --- a/Sources/AgentsCore/TransactionPublication.swift +++ b/Sources/AgentsCore/TransactionPublication.swift @@ -41,7 +41,7 @@ extension TransactionSession { func stage( _ index: Int, source: FileTransaction.Source?, expectation: FileTransaction.Expectation, - privateData: (() throws -> Data)? = nil + privateData: (() throws -> Data)? = nil, privateTree: PrivateTree? = nil ) throws { let entry = journal.entries[index] let parent = parents[index] @@ -53,7 +53,7 @@ extension TransactionSession { if source != nil || entry.security.replacement == .privateMaterialization { let sealed = try construct( source, expectation: expectation, named: staging.name(index), index: index, - container: container, parent: parent, privateData: privateData) + container: container, parent: parent, privateData: privateData, privateTree: privateTree) try emit(.stage(index, .constructed)) let capture = try FileSnapshot.capture(staging.name(index), from: container) try verify(source, sealed, capture: capture) @@ -64,6 +64,8 @@ extension TransactionSession { if entry.security.replacement == .privateMaterialization { journal.entries[index].security.stagedAccess = try container.requirePrivateAccess( staging.name(index)) + journal.entries[index].security.stagedTreeAccess = try TreeMemberAccess.capture( + staging.name(index), in: container, snapshot: snapshot, requirePrivate: true) } } else { try emit(.stage(index, .constructed)) @@ -82,11 +84,30 @@ extension TransactionSession { private func construct( _ source: FileTransaction.Source?, expectation: FileTransaction.Expectation, named name: String, index: Int, container: DirectoryHandle, parent: DirectoryHandle, - privateData: (() throws -> Data)? + privateData: (() throws -> Data)?, privateTree: PrivateTree? ) throws -> FileTransaction.Expectation { let entry = journal.entries[index] var expectation = expectation if entry.security.replacement == .privateMaterialization { + if let privateTree { + var bytes = privateTreeBytes + defer { privateTreeBytes = bytes } + try privateTree.construct( + named: name, in: container, bytes: &bytes, + admit: { snapshot, access, members in + // Payload writes change fixed-width digests, not the sealed evidence's shape. + var candidate = self.journal + candidate.entries[index].staged = snapshot + candidate.entries[index].security.stagedAccess = access + candidate.entries[index].security.stagedTreeAccess = members + candidate.entries[index].progress = .ready + try LedgerAdmission.check(StateStore.encode(candidate), limits: .standard) + }, + validate: { try self.requirePreimage(index) }) + expectation.kind = S_IFDIR + expectation.mode = 0o700 + return expectation + } guard let privateData else { throw conflict(index, "missing private materialization producer") } @@ -159,6 +180,9 @@ extension TransactionSession { capture: FileSnapshot.Capture ) throws { let snapshot = capture.snapshot + if let digest = expectation.objectDigest, snapshot?.digest != digest { + throw CoreError.invalidState("staged subtree content or executable intent mismatch") + } if let kind = expectation.kind, snapshot?.identity.kind != kind { throw CoreError.invalidState("staged content type mismatch") } @@ -276,7 +300,7 @@ extension TransactionSession { records.targets[entry.path] = .init( generation: journal.id, rootIdentity: resource?.identity.orderingKey ?? identity, - digest: snapshot.digest, access: access) + digest: snapshot.digest, access: access, treeAccess: entry.security.stagedTreeAccess) } else { records.targets.removeValue(forKey: entry.path) } diff --git a/Sources/AgentsCore/TransactionRecovery.swift b/Sources/AgentsCore/TransactionRecovery.swift index 4aca362..249717c 100644 --- a/Sources/AgentsCore/TransactionRecovery.swift +++ b/Sources/AgentsCore/TransactionRecovery.swift @@ -188,6 +188,7 @@ extension FileTransaction { } static func readJournal(_ bytes: Data) throws -> TransactionJournal { + try LedgerAdmission.check(bytes, limits: .standard) try JSONKeys.validate(bytes) let value = try JSONSerialization.jsonObject(with: bytes) as? [String: Any] guard value?["version"] as? Int == TransactionJournal.currentVersion else { @@ -350,7 +351,9 @@ extension TransactionSession { try requireParent(index) if let preimage = entry.preimage { let slot: TransactionSlot = entry.action == .install ? .exchanged : .deleted - try entry.security.validateObject(preimage, named: slot.name(index), in: container) + try entry.security.validateObject( + preimage, named: slot.name(index), in: container, + permittingDirectoryWrite: entry.progress.permitsDirectoryWrite) } if entry.preimage != nil { if entry.action == .install { diff --git a/Sources/AgentsCore/TransactionSession.swift b/Sources/AgentsCore/TransactionSession.swift index 3322ee5..19103f4 100644 --- a/Sources/AgentsCore/TransactionSession.swift +++ b/Sources/AgentsCore/TransactionSession.swift @@ -28,13 +28,17 @@ final class TransactionSession { self.outcome = outcome } + var privateTreeBytes = 0 + func emit(_ point: TransactionCheckpoint) throws { try checkpoint(point.name) } func persist(_ change: TransactionCheckpoint.Change) throws { try requireScope() + let bytes = try StateStore.encode(journal) + try LedgerAdmission.check(bytes, limits: .standard) try directory.replaceFile( TransactionJournal.fileName, through: TransactionJournal.incompleteFileName, - with: StateStore.encode(journal), + with: bytes, afterWrite: { try emit(.persisted(journal.phase, change, .written)) }, @@ -167,6 +171,20 @@ final class TransactionSession { try requireParent(index) try entry.security.validate(entry: entry) let target = parents[index].url.appendingPathComponent(entry.name) + if let coordination = entry.coordination { + let identity = journal.footprint[coordination] + if let route = NativeTargetRoute.metadataRoute(entry.path) { + guard let resource = resources.first(where: { $0.identity == identity }), + resource.route.basename.utf8.elementsEqual(route.basename.utf8), + try resource.metadata?.objectIdentity == parents[index].objectIdentity, + entry.name == "receipt" + else { throw CoreError.invalidState("invalid coordinated receipt entry") } + } else { + guard try parents[index].objectIdentity == identity.parent, + entry.name.utf8.elementsEqual(identity.basename.utf8) + else { throw CoreError.invalidState("entry contradicts physical coordination") } + } + } guard !targets.contains(where: { PathSafety.isContained(target, in: $0) || PathSafety.isContained($0, in: target) @@ -262,14 +280,15 @@ final class TransactionSession { return layouts[0] } let container = try self.container(entry.container) + let permitsWrite = permittingDirectoryWrite && entry.progress.permitsDirectoryWrite var objects: [TransactionSlot: FileSnapshot] = [:] for slot in TransactionSlot.objectSlots { if let value = try FileSnapshot.read(slot.name(index), from: container) { - try entry.security.validateObject(value, named: slot.name(index), in: container) + try entry.security.validateObject( + value, named: slot.name(index), in: container, permittingDirectoryWrite: permitsWrite) objects[slot] = value } } - let permitsWrite = permittingDirectoryWrite && entry.progress.permitsDirectoryWrite for layout in layouts where Set(layout.objects.keys) == Set(objects.keys) { guard layout.objects.allSatisfy({ slot, expected in @@ -278,12 +297,14 @@ final class TransactionSession { }) else { continue } if layout.kind == .prepared, let original = entry.preimage { - try entry.security.validateObject(original, named: entry.name, in: parents[index]) + try entry.security.validateObject( + original, named: entry.name, in: parents[index], permittingDirectoryWrite: permitsWrite) } if case .object(let expected) = layout.target, try parents[index].info(entry.name).map(FileObjectIdentity.init) == expected.identity { - try entry.security.validateObject(expected, named: entry.name, in: parents[index]) + try entry.security.validateObject( + expected, named: entry.name, in: parents[index], permittingDirectoryWrite: permitsWrite) } if try layout.target.matches( entry.name, from: parents[index], permittingDirectoryWrite: permitsWrite) diff --git a/Tests/AgentsCoreTests/PrivateTreeTests.swift b/Tests/AgentsCoreTests/PrivateTreeTests.swift new file mode 100644 index 0000000..113d767 --- /dev/null +++ b/Tests/AgentsCoreTests/PrivateTreeTests.swift @@ -0,0 +1,562 @@ +import CPlatform +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite("Private complete native trees") +struct PrivateTreeTests { + @Test func completeTreeIsPrivateBeforeProviderAndOrdinarySiblingUpdatesRetainItsReceipt() throws { + let fixture = try TransactionFixture() + let route = try NativeTargetRoute.named( + .claudeSkillPlugin, scope: .user, name: "private-fixture") + var environment = fixture.store.environment + environment.environment["CLAUDE_CONFIG_DIR"] = + fixture.root.appendingPathComponent("configured-claude").path + let store = StateStore(scope: .user, environment: environment) + var first: UUID? + try store.withLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + let prepared = try store.preparePrivateMaterialization(target) + let provider = TreeBindings { + let journal = try treeJournal(store) + let parent = try DirectoryHandle(at: target.url.deletingLastPathComponent()) + let container = try parent.child(journal.containerName(0)) + let name = TransactionSlot.staging(for: journal.entries[0]).name(0) + let snapshot = try #require(try FileSnapshot.read(name, from: container)) + _ = try container.requirePrivateAccess(name) + let members = try #require( + try TreeMemberAccess.capture( + name, in: container, snapshot: snapshot, requirePrivate: true)) + #expect(members.map(\.path) == ["bin", "bin/run", "config", "sibling"]) + #expect(try container.child(name).read("config").isEmpty) + #expect(try container.child(name).child("bin").read("run").isEmpty) + #expect(members.first { $0.path == "bin/run" }?.access.mode == 0o700) + return Data("fixture-private".utf8) + } + let transaction = FileTransaction(store: store) + try transaction.replacePrivateTree(prepared, entries: treeEntries(), provider: provider) + try transaction.commit() + let receipt = try #require(try store.materializationReceipt(for: target)) + first = receipt.generation + #expect(receipt.treeAccess?.count == 4) + #expect( + try Data(contentsOf: target.url.appendingPathComponent("config")) + == Data("fixture-private".utf8)) + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: target.url.appendingPathComponent("alias").path) == "bin/run") + } + // A cold scope has no source/provider need for an ordinary sibling update. + var other = environment + other.homeDirectory = fixture.root.appendingPathComponent("other-home") + try FileManager.default.createDirectory( + at: other.homeDirectory, withIntermediateDirectories: true) + let second = StateStore(scope: .user, environment: other) + try second.withLock(footprint: [route]) { + let target = try second.nativeTarget(for: route) + let privateBytes = try Data(contentsOf: target.url.appendingPathComponent("config")) + let transaction = FileTransaction(store: second) + #expect(throws: CoreError.self) { + try transaction.replace(target.url, with: .copy(fixture.root.appendingPathComponent("new"))) + } + let update = FileTransaction(store: second) + try update.replacePrivateTree( + second.preparePrivateMaterialization(target), + entries: [ + .init("config", content: .file(privateBytes)), + .init("sibling", content: .file(Data("changed ordinary sibling".utf8))), + ], + provider: TreeBindings { + throw CoreError.invalidState("ordinary edit must not resolve bindings") + }) + try update.commit() + let receipt = try #require(try second.materializationReceipt(for: target)) + #expect(receipt.generation != first) + #expect(receipt.treeAccess?.map(\.path) == ["config", "sibling"]) + let remove = FileTransaction(store: second) + try remove.delete(target.url) + try remove.commit() + #expect(try second.materializationReceipt(for: target) == nil) + } + } + + @Test(arguments: ["provider", "entry.0.applied", "entry.1.applied", "journal.committed"]) + func failuresPreserveCompleteGenerationAndReceipt(_ failure: String) throws { + let fixture = try TransactionFixture() + let route = try NativeTargetRoute.named( + .cursorLocalPlugin, scope: .user, name: "rollback-fixture") + let store = StateStore(scope: .user, environment: fixture.store.environment) + try store.withLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + let original = FileTransaction(store: store) + try original.replacePrivateTree( + store.preparePrivateMaterialization(target), + entries: [ + .init("old", content: .file(Data("old-private".utf8))) + ], provider: TreeBindings { Data() }) + try original.commit() + let before = try FileSnapshot.read(at: target.url) + let generation = try store.materializationReceipt(for: target)?.generation + let outcome = TransactionOutcome() + let transaction = FileTransaction(store: store, outcome: outcome) { point in + if point == failure { throw CoreError.invalidState("bounded tree interruption") } + } + try transaction.replacePrivateTree( + store.preparePrivateMaterialization(target), entries: treeEntries(), + provider: TreeBindings { + if failure == "provider" { throw CoreError.invalidState("private fixture failure") } + return Data("new-private".utf8) + }) + #expect(throws: CoreError.self) { try transaction.commit() } + if failure == "journal.committed" { + #expect(outcome.terminal == .committed) + #expect(try store.materializationReceipt(for: target)?.generation != generation) + #expect( + try Data(contentsOf: target.url.appendingPathComponent("config")) + == Data("new-private".utf8)) + } else { + #expect(try FileSnapshot.read(at: target.url) == before) + #expect(try store.materializationReceipt(for: target)?.generation == generation) + } + #expect(!outcome.recoveryPending) + #expect( + !FileManager.default.fileExists( + atPath: store.directory.appendingPathComponent("transaction.json").path)) + } + } + + @Test func accessChangesArePreparedAndInvalidTreesNeverResolveBindings() throws { + let fixture = try TransactionFixture() + let route = try NativeTargetRoute.named( + .claudeSkillPlugin, scope: .project, name: "private-plugin") + try fixture.store.withLock(footprint: [route]) { + let target = try fixture.store.nativeTarget(for: route) + try FileManager.default.createDirectory(at: target.url, withIntermediateDirectories: true) + try Data("ordinary".utf8).write(to: target.url.appendingPathComponent("ordinary")) + try #require(chmod(target.url.path, 0o755) == 0) + try #require(chmod(target.url.appendingPathComponent("ordinary").path, 0o644) == 0) + #expect(throws: CoreError.self) { try fixture.store.preparePrivateMaterialization(target) } + let prepared = try fixture.store.preparePrivateMaterialization(target, changingAccess: true) + #expect(prepared.accessChange?.mode == 0o700) + #expect(prepared.memberAccessChanges.map(\.path) == ["ordinary"]) + let before = try FileSnapshot.read(at: target.url) + let bad: [[PrivateTreeEntry]] = [ + [.init("../escape", content: .file(Data()))], + [.init("link", content: .symlink(".."))], + [.init("link", content: .symlink("other")), .init("other", content: .symlink("link"))], + [.init("link", content: .symlink("missing")), .init("link/file", content: .file(Data()))], + [.init("duplicate", content: .directory), .init("duplicate", content: .file(Data()))], + ] + for entries in bad { + let transaction = FileTransaction(store: fixture.store) + #expect(throws: CoreError.self) { + try transaction.replacePrivateTree( + prepared, entries: entries, + provider: TreeBindings { throw CoreError.invalidState("must not resolve") }) + } + } + #expect(try FileSnapshot.read(at: target.url) == before) + let update = FileTransaction(store: fixture.store) + try update.replacePrivateTree( + prepared, entries: [.init("safe-dangling", content: .symlink("missing/file"))], + provider: TreeBindings { Data() }) + try update.commit() + #expect(try fixture.store.materializationReceipt(for: target)?.treeAccess == []) + } + } + + @Test func readOnlyOrdinaryPreimageIsRestoredWithItsAccess() throws { + let fixture = try TransactionFixture() + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .project, name: "read-only") + try fixture.store.withLock(footprint: [route]) { + let target = try fixture.store.nativeTarget(for: route) + try FileManager.default.createDirectory(at: target.url, withIntermediateDirectories: true) + try Data("original".utf8).write(to: target.url.appendingPathComponent("old")) + try #require(chmod(target.url.path, 0o555) == 0) + defer { _ = chmod(target.url.path, 0o755) } + let original = try FileSnapshot.read(at: target.url) + let transaction = FileTransaction(store: fixture.store) { point in + if point == "entry.0.applied" { throw CoreError.invalidState("bounded interruption") } + } + try transaction.replacePrivateTree( + fixture.store.preparePrivateMaterialization(target, changingAccess: true), + entries: [.init("new", content: .file(Data()))], provider: TreeBindings { Data() }) + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(try FileSnapshot.read(at: target.url) == original) + #expect( + !FileManager.default.fileExists( + atPath: fixture.store.directory.appendingPathComponent("transaction.json").path)) + } + } + + @Test func changedSealedMemberRetainsRecoveryEvidenceUntilAccessIsRestored() throws { + let fixture = try TransactionFixture() + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .project, name: "freshness") + var changed: URL? + var cleanupPending = false + do { + try fixture.store.withLock(footprint: [route]) { + let target = try fixture.store.nativeTarget(for: route) + let outcome = TransactionOutcome() + let transaction = FileTransaction(store: fixture.store, outcome: outcome) { point in + if point == "entry.0.ready" { + let journal = try treeJournal(fixture.store) + let file = target.url.deletingLastPathComponent() + .appendingPathComponent(journal.containerName(0)) + .appendingPathComponent(TransactionSlot.staging(for: journal.entries[0]).name(0)) + .appendingPathComponent("member") + try #require(chmod(file.path, 0o644) == 0) + changed = file + } + } + try transaction.replacePrivateTree( + fixture.store.preparePrivateMaterialization(target), + entries: [.init("member", content: .file(Data("fixture".utf8)))], + provider: TreeBindings { Data() }) + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(outcome.recoveryPending) + #expect(!FileManager.default.fileExists(atPath: target.url.path)) + let sealed = try #require(changed) + #expect(FileManager.default.fileExists(atPath: sealed.path)) + try #require(chmod(sealed.path, 0o600) == 0) + } + } catch CoreError.invalidState { + cleanupPending = true + } + #expect(cleanupPending) + #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { + try fixture.store.withLock(footprint: [route]) {} + } + #expect( + !FileManager.default.fileExists( + atPath: fixture.store.directory.appendingPathComponent("transaction.json").path)) + } + + @Test(arguments: ["missing", "duplicate", "kind"]) + func malformedTreeReceiptNeverBecomesOrdinary(_ field: String) throws { + let fixture = try TransactionFixture() + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .project, name: "receipt") + try fixture.store.withLock(footprint: [route]) { + let target = try fixture.store.nativeTarget(for: route) + let transaction = FileTransaction(store: fixture.store) + try transaction.replacePrivateTree( + fixture.store.preparePrivateMaterialization(target), + entries: [.init("member", content: .file(Data()))], provider: TreeBindings { Data() }) + try transaction.commit() + let url = fixture.store.materializationReceiptURL + var json = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) + var targets = try #require(json["targets"] as? [String: [String: Any]]) + var record = try #require(targets[target.path]) + if field == "missing" { + record.removeValue(forKey: "treeAccess") + } else if field == "duplicate" { + var members = try #require(record["treeAccess"] as? [[String: Any]]) + members.append(try #require(members.first)) + record["treeAccess"] = members + } else { + var access = try #require(record["access"] as? [String: Any]) + var identity = try #require(access["identity"] as? [String: Any]) + identity["kind"] = Int(S_IFREG) + access["identity"] = identity + record["access"] = access + } + targets[target.path] = record + json["targets"] = targets + try JSONSerialization.data(withJSONObject: json).write(to: url) + let before = try FileSnapshot.read(at: fixture.root) + #expect(throws: CoreError.self) { try fixture.store.materializationReceipt(for: target) } + #expect(try FileSnapshot.read(at: fixture.root) == before) + } + } + + @Test func missingNativeRootHasStablePreviewEvidenceDuringAdmission() throws { + let fixture = try TransactionFixture() + let store = StateStore(scope: .project, environment: fixture.store.environment) + var before = "" + var privateBefore = "" + try store.withReadLock(footprint: [.cursorMCPUser]) { + let target = try store.nativeTarget(for: .cursorMCPUser) + before = try TargetPrecondition(target.url).displayEvidence(includeContent: false) + privateBefore = try store.preparePrivateMaterialization(target).accessFingerprint() + #expect(!FileManager.default.fileExists(atPath: target.url.deletingLastPathComponent().path)) + } + try store.withLock(footprint: [.cursorMCPUser]) { + let target = try store.nativeTarget(for: .cursorMCPUser) + #expect(try TargetPrecondition(target.url).displayEvidence(includeContent: false) == before) + #expect(try store.preparePrivateMaterialization(target).accessFingerprint() == privateBefore) + } + try store.withReadLock(footprint: [.cursorMCPUser]) { + let target = try store.nativeTarget(for: .cursorMCPUser) + let parent = target.url.deletingLastPathComponent() + try #require(chmod(parent.path, 0o750) == 0) + #expect(try TargetPrecondition(target.url).displayEvidence(includeContent: false) != before) + } + } + + #if os(Linux) + @Test func unicodeDistinctMembersSurviveSnapshotCodecDigestAndDisposal() throws { + let fixture = try TransactionFixture() + let parent = try DirectoryHandle(at: fixture.root.appendingPathComponent("new")) + let nfc = "\u{e9}" + let nfd = "e\u{301}" + try parent.write(nfc, data: Data("nfc".utf8)) + try parent.link(nfd, destination: "SKILL.md") + let before = try #require(try FileSnapshot.read(at: parent.url)) + #expect(before.children?.count == 3) + #expect(before.child(named: nfc)?.isRegular == true) + #expect(before.child(named: nfd)?.isSymbolicLink == true) + let decoded = try StateStore.decode(StateStore.encode(before), as: FileSnapshot.self) + #expect(decoded == before) + try parent.remove(nfc, expecting: before.child(named: nfc)) + let remaining = try #require(try FileSnapshot.read(at: parent.url)) + #expect(before.containsRemaining(remaining)) + try DirectoryHandle(at: fixture.root).remove( + "new", expecting: before, identity: before.identity) + #expect(!FileManager.default.fileExists(atPath: parent.url.path)) + } + #endif +} + +private struct TreeBindings: RuntimeBindingProvider { + let resolve: @Sendable () throws -> Data + init(_ resolve: @escaping @Sendable () throws -> Data) { self.resolve = resolve } + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { try resolve() } +} + +private func treeEntries() -> [PrivateTreeEntry] { + [ + .init("bin", content: .directory), + .init( + "bin/run", + content: .boundFile(bindings: ["fixture"], executable: true) { try $0.value(for: "fixture") }), + .init("config", content: .boundFile(bindings: ["fixture"]) { try $0.value(for: "fixture") }), + .init("sibling", content: .file(Data("ordinary sibling".utf8))), + .init("alias", content: .symlink("bin/run")), + ] +} + +private func treeJournal(_ store: StateStore) throws -> TransactionJournal { + try StateStore.decode( + Data(contentsOf: store.directory.appendingPathComponent("transaction.json")), + as: TransactionJournal.self) +} + +extension PrivateTreeTests { + @Test(arguments: [ + "stage.0.constructed", "entry.0.ready", "entry.0.applied", "entry.1.applied", + "journal.committed", "disposal.0.unlinked.entry.0.exchanged/old", "journal.finalized", + ]) + func restartRecoveryKeepsCompleteTreeAndSealedDisposalSubset(_ point: String) throws { + let fixture = try TransactionFixture() + let route = try NativeTargetRoute.named( + .claudeSkillPlugin, scope: .user, name: "private-fixture") + var environment = fixture.store.environment + environment.environment["CLAUDE_CONFIG_DIR"] = + fixture.root.appendingPathComponent("configured-claude").path + let store = StateStore(scope: .user, environment: environment) + var generation: UUID? + try store.withLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + let transaction = FileTransaction(store: store) + try transaction.replacePrivateTree( + store.preparePrivateMaterialization(target), + entries: [ + .init("old", content: .file(Data("old tree".utf8))), + .init("other", content: .file(Data("old sibling".utf8))), + ], provider: TreeBindings { Data() }) + try transaction.commit() + generation = try store.materializationReceipt(for: target)?.generation + } + let child = try stateTestProcess( + root: fixture.root, arguments: ["private-tree-install", point, "--scope", "user"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let beforeRead = try FileSnapshot.read(at: fixture.root) + try store.withReadLock( + onPendingRecovery: { + #expect(!FileTransaction.recoveryDiagnostic(store: store).requiresOwner) + }, { Issue.record("a sealed tree journal must remain pending on a read") }) + #expect(try FileSnapshot.read(at: fixture.root) == beforeRead) + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + let committed = + point == "journal.committed" || point.hasPrefix("disposal.") || point == "journal.finalized" + try store.withReadLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + let receipt = try #require(try store.materializationReceipt(for: target)) + #expect((receipt.generation != generation) == committed) + let directory = try DirectoryHandle(at: target.url) + _ = try FileAccessEvidence.requirePrivate(descriptor: directory.descriptor) + if committed { + #expect(try directory.read("config") == Data("tree-private-after".utf8)) + #expect(try directory.child("nested").read("run") == Data("tree-private-after".utf8)) + #expect(try directory.readLink("alias") == "nested/run") + } else { + #expect(try directory.read("old") == Data("old tree".utf8)) + #expect(try directory.read("other") == Data("old sibling".utf8)) + } + } + } + + @Test func differentHomesShareTreeLockBeforeCallbackAndProvider() throws { + let fixture = try TransactionFixture() + let config = fixture.root.appendingPathComponent("tree-shared-root") + let other = fixture.root.appendingPathComponent("other-project") + try FileManager.default.createDirectory(at: other, withIntermediateDirectories: true) + let holder = try stateTestProcess( + root: fixture.root, + arguments: [ + "private-tree-lock", "tree.locked", "--scope", "user", "--shared-config", config.path, + ]) + defer { terminateProcess(holder) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: holder, root: fixture.root) + let waiter = try stateTestProcess( + root: other, + arguments: [ + "private-tree-install", "shared.0.lock.contended", "--scope", "user", "--shared-config", + config.path, + ]) + defer { terminateProcess(waiter) } + try ProcessWait.marker(other.appendingPathComponent("ready"), child: waiter, root: other) + #expect( + !FileManager.default.fileExists( + atPath: other.appendingPathComponent("tree-provider-resolved").path)) + try #require(kill(holder.processIdentifier, SIGCONT) == 0) + try ProcessWait.exit(holder, root: fixture.root) + #expect(holder.terminationStatus == 0) + try #require(kill(waiter.processIdentifier, SIGCONT) == 0) + try ProcessWait.exit(waiter, root: other) + #expect(waiter.terminationStatus == 0) + #expect( + FileManager.default.fileExists( + atPath: other.appendingPathComponent("tree-provider-resolved").path)) + #expect( + try Data(contentsOf: config.appendingPathComponent("skills/private-fixture/config")) + == Data("tree-private-after".utf8)) + } + + @Test(arguments: ["stagedTreeAccess", "duplicateMember", "coordination", "version"]) + func malformedTreeJournalIsReadOnlyRejected(_ field: String) throws { + let fixture = try TransactionFixture() + let child = try stateTestProcess( + root: fixture.root, + arguments: ["private-tree-install", "entry.0.ready", "--scope", "user"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + var environment = fixture.store.environment + environment.environment["CLAUDE_CONFIG_DIR"] = + fixture.root.appendingPathComponent("configured-claude").path + let store = StateStore(scope: .user, environment: environment) + let journalURL = store.directory.appendingPathComponent("transaction.json") + var json = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: journalURL)) as? [String: Any]) + var entries = try #require(json["entries"] as? [[String: Any]]) + switch field { + case "version": json["version"] = 3 + case "coordination": entries[0]["coordination"] = 999 + case "duplicateMember": + var staged = try #require(entries[0]["staged"] as? [String: Any]) + var children = try #require(staged["children"] as? [[String: Any]]) + children.append(try #require(children.first)) + staged["children"] = children + entries[0]["staged"] = staged + default: + var security = try #require(entries[0]["security"] as? [String: Any]) + security.removeValue(forKey: field) + entries[0]["security"] = security + } + json["entries"] = entries + try JSONSerialization.data(withJSONObject: json).write(to: journalURL) + let before = try FileSnapshot.read(at: fixture.root) + #expect(throws: (any Error).self) { try store.withLock {} } + #expect(try FileSnapshot.read(at: fixture.root) == before) + } + + @Test func recordedNamedRootsResolveOnColdReadWithoutPathAuthority() throws { + let fixture = try TransactionFixture() + let route = try NativeTargetRoute.named(.claudeCommand, scope: .project, name: "team/review") + var ledger = ResolvedLedger() + ledger.sources["fixture"] = LedgerSource(kind: .local, revision: "live") + ledger.components["command"] = LedgerComponent( + declaringSource: "fixture", source: "fixture", root: ".", kind: "command", + name: "review", payload: .init(object: [:]), conditions: [], recipients: [.claudeCode], + chatGPT: false, resources: []) + ledger.deployments = [ + .init( + id: "deployment", target: .init(kind: .registered, root: route.root, path: route.basename), + route: "fixture/command@1", + owners: ["command"], recipients: [.claudeCode], ownership: .generated, + expectedHash: "sha256:" + String(repeating: "a", count: 64), created: true) + ] + ledger.lowerings = [ + .init( + id: "lowering", format: "fixture/command@1", inputs: ["command"], resources: [], + deployments: ["deployment"], layout: .init(object: [:]), platform: "macos", artifacts: []) + ] + try ResolvedLedgerCodec.encode(ledger, limits: .standard).write(to: fixture.store.resolvedURL) + let cold = StateStore(scope: .project, environment: fixture.store.environment) + let target = try ledger.deployments[0].target.resolve(roots: cold.ledgerRoots) + #expect(target == fixture.root.appendingPathComponent(".claude/commands/team/review.md")) + #expect(throws: CoreError.self) { + try FileTransaction(store: cold).replace(target, with: .data(Data())) + } + try cold.withLock(footprint: [route]) { + let admitted = try cold.nativeTarget(for: route) + let transaction = FileTransaction(store: cold) + try transaction.replace(admitted.url, with: .data(Data("command".utf8))) + try transaction.commit() + } + ledger.deployments[0].target.path = "unrecorded.md" + try ResolvedLedgerCodec.encode(ledger, limits: .standard).write(to: fixture.store.resolvedURL) + #expect(cold.ledgerRoots[route.root] == nil) + ledger.deployments[0].target.root = "native-member-2e2e2f657363617065" + try ResolvedLedgerCodec.encode(ledger, limits: .standard).write(to: fixture.store.resolvedURL) + #expect(cold.ledgerRoots[ledger.deployments[0].target.root!] == nil) + #expect(RuntimeBindingValues([:]).description == "") + } +} + +extension PrivateTreeTests { + @Test func independentNestedCoordinationIsRefusedBeforeCreatingMetadata() throws { + let fixture = try TransactionFixture() + var environment = fixture.store.environment + let configured = fixture.root.appendingPathComponent("configured") + try FileManager.default.createDirectory(at: configured, withIntermediateDirectories: true) + environment.environment["CLAUDE_CONFIG_DIR"] = configured.path + environment.environment["CODEX_HOME"] = configured.appendingPathComponent("skills/plugin").path + let store = StateStore(scope: .user, environment: environment) + let before = try FileSnapshot.read(at: fixture.root) + #expect(throws: CoreError.self) { try store.withReadLock(footprint: [.codexMCPUser]) {} } + #expect(throws: CoreError.self) { try store.withLock(footprint: [.codexMCPUser]) {} } + #expect(try FileSnapshot.read(at: fixture.root) == before) + environment.environment["CODEX_HOME"] = + fixture.root.appendingPathComponent("independent-codex").path + try FileManager.default.createDirectory( + at: fixture.root.appendingPathComponent("independent-codex"), + withIntermediateDirectories: true) + let allowed = StateStore(scope: .user, environment: environment) + let plugin = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: "plugin") + try allowed.withLock(footprint: [plugin, .codexMCPUser]) { + let target = try allowed.nativeTarget(for: plugin) + let transaction = FileTransaction(store: allowed) + try transaction.replacePrivateTree( + allowed.preparePrivateMaterialization(target), entries: [], + provider: TreeBindings { Data() }) + let codex = try allowed.nativeTarget(for: .codexMCPUser) + try transaction.replacePrivate( + allowed.preparePrivateMaterialization(codex), provider: TreeBindings { Data() } + ) { _ in Data("ordinary fixture".utf8) } + try transaction.commit() + #expect(try allowed.materializationReceipt(for: target)?.treeAccess == []) + #expect(try allowed.materializationReceipt(for: codex)?.treeAccess == nil) + #expect(try allowed.materializationReceipt(for: codex) != nil) + } + } +} diff --git a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift index fc59f84..13417b0 100644 --- a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift +++ b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift @@ -791,7 +791,6 @@ extension RegisteredNativeTargetTests { to: payload.appendingPathComponent("manifest.json")) try store.withLock(footprint: [route]) { let target = try store.nativeTarget(for: route) - #expect(throws: CoreError.self) { try store.preparePrivateMaterialization(target) } #expect(throws: CoreError.self) { let invalid = FileTransaction(store: store) try invalid.replace(target.url, with: .data(Data("wrong kind".utf8))) diff --git a/Tests/AgentsCoreTests/StateTransactionTests.swift b/Tests/AgentsCoreTests/StateTransactionTests.swift index fa147eb..354a17f 100644 --- a/Tests/AgentsCoreTests/StateTransactionTests.swift +++ b/Tests/AgentsCoreTests/StateTransactionTests.swift @@ -222,8 +222,7 @@ extension StateTransactionTests { } #expect { try store.withLock {} } throws: { error in if json == "{broken" { - let error = error as NSError - return error.domain == NSCocoaErrorDomain && error.code == 3840 + return error as? CoreError == .invalidState("invalid ledger JSON") } return error as? CoreError == .invalidState( @@ -501,22 +500,18 @@ extension StateTransactionTests { text.data(using: .utf16BigEndian)!, text.data(using: .utf32)!, Data(text.utf8) + Data(" {}".utf8), ] - for (index, bytes) in encodings.enumerated() { + for bytes in encodings { try bytes.write(to: url) let snapshot = try FileSnapshot.read(at: fixture.root) #expect { try fixture.store.withLock {} } throws: { error in - if index < 4 { - return error as? CoreError - == .invalidState("JSON must be UTF-8 without a byte order mark") - } - let error = error as NSError - return error.domain == NSCocoaErrorDomain && error.code == 3840 + guard case CoreError.invalidState = error else { return false } + return true } #expect(try FileSnapshot.read(at: fixture.root) == snapshot) } } try Data(duplicate.utf8).write(to: url) - #expect(throws: CoreError.invalidState("duplicate JSON key: phase")) { + #expect(throws: CoreError.invalidState("duplicate ledger key")) { try fixture.store.withLock {} } try original.write(to: url) diff --git a/Tests/StateTestProcess/PrivateMaterializationProbe.swift b/Tests/StateTestProcess/PrivateMaterializationProbe.swift index bba4281..e8be40e 100644 --- a/Tests/StateTestProcess/PrivateMaterializationProbe.swift +++ b/Tests/StateTestProcess/PrivateMaterializationProbe.swift @@ -2,12 +2,44 @@ import AgentsCore import AgentsInstructions import AgentsSkills import AgentsUpdates +import CPlatform import Foundation func privateMaterializationProbe( _ command: String, store: StateStore, checkpoint: @escaping (String) throws -> Void ) throws { let root = store.environment.projectDirectory + if command.hasPrefix("private-tree-") { + if command == "private-tree-recover" { + do { try store.withLock(checkpoint: checkpoint, {}) } catch CoreError.transactionRecovered {} + return + } + let route = try NativeTargetRoute.named( + .claudeSkillPlugin, scope: .user, name: "private-fixture") + try store.withLock(checkpoint: checkpoint, footprint: [route]) { + if command == "private-tree-lock" { + try checkpoint("tree.locked") + return + } + let target = try store.nativeTarget(for: route) + let prepared = try store.preparePrivateMaterialization(target, changingAccess: true) + let transaction = FileTransaction(store: store, checkpoint: checkpoint) + try transaction.replacePrivateTree( + prepared, + entries: [ + .init("nested", content: .directory), + .init( + "nested/run", + content: .boundFile(bindings: ["value"], executable: true) { + try $0.value(for: "value") + }), + .init("config", content: .boundFile(bindings: ["value"]) { try $0.value(for: "value") }), + .init("alias", content: .symlink("nested/run")), + ], provider: TreeProbeBindings(root: root)) + try transaction.commit() + } + return + } if command == "private-recover" { do { try store.withLock(checkpoint: checkpoint, {}) } catch CoreError.transactionRecovered {} return @@ -123,3 +155,15 @@ func sharedMaterializationProbe( try transaction.commit() } } + +private struct TreeProbeBindings: RuntimeBindingProvider { + let root: URL + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + let descriptor = open( + root.appendingPathComponent("tree-provider-resolved").path, + O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) + guard descriptor >= 0 else { throw CoreError.invalidState("tree provider cannot replay") } + close(descriptor) + return Data("tree-private-after".utf8) + } +} From 14b341f3f8ec0d5556e00b4d8fc13d1e9d8c798f Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:33:31 +0800 Subject: [PATCH 106/171] fix: retain final native regions and diagnostic origins --- .../Components/NativeComponentFieldsV1.swift | 114 ++++++++--- Sources/Components/NativePluginFieldsV1.swift | 110 +++++++---- Sources/NativeDocuments/NativeDocument.swift | 49 ++++- .../NativeComponentFieldsTests.swift | 187 +++++++++++++++--- .../NativeComponentTests.swift | 6 +- .../OccurrenceInsertionTests.swift | 39 ++++ 6 files changed, 404 insertions(+), 101 deletions(-) diff --git a/Sources/Components/NativeComponentFieldsV1.swift b/Sources/Components/NativeComponentFieldsV1.swift index ed51120..a0d0eb5 100644 --- a/Sources/Components/NativeComponentFieldsV1.swift +++ b/Sources/Components/NativeComponentFieldsV1.swift @@ -2,8 +2,10 @@ import AgentsCore import Foundation import NativeDocuments -/// Structural semantic failures contain no imported field values or machine paths. +/// Source coordinates are relative to the caller-selected producer root. Details contain +/// no imported field values or machine paths. package struct NativeComponentFieldIssue: Error { + package let document: String package let field: [String] package let reason: NativeAdapterIssue.Reason package let detail: String @@ -11,6 +13,8 @@ package struct NativeComponentFieldIssue: Error { /// Finite native field semantics shared by rendering and parsed source input. /// Callers own syntax, source locations, aggregate admission and source capture. +/// Supply the document coordinate and the parsed value's field prefix; failures retain +/// both, switching to producer-relative document roots for referenced plugin JSON. package enum NativeComponentFieldsV1 { static func markdownRules(_ surface: NativeClientSurface, kind: String) -> [String: MCPNativeField] @@ -50,7 +54,8 @@ extension NativeComponentFieldsV1 { /// Explicit Claude commands/agents replace discovery; skills add and configs merge. /// Cursor explicit component fields replace default discovery for that component. package static func pluginDefaults( - surface: NativeClientSurface, explicitFields: Set + surface: NativeClientSurface, document: String, fieldPrefix: [String] = [], + explicitFields: Set ) throws -> [String: String] { let defaults: [String: String] switch surface { @@ -69,18 +74,23 @@ extension NativeComponentFieldsV1 { ] return defaults.filter { !explicitFields.contains($0.key) } default: - throw failure([], .unverified, "native plugin defaults are not established for this surface") + throw failure( + document, fieldPrefix, .unverified, + "native plugin defaults are not established for this surface") } } /// Values are already parsed. Resource entries/documents are relative to the producer's /// explicit container root; they convey presence and kind, never deployment ownership. package static func plugin( - surface: NativeClientSurface, fields: [String: NativeValue], + surface: NativeClientSurface, document: String, fieldPrefix: [String] = [], + fields: [String: NativeValue], entries: [LedgerEntry], documents: [String: NativeValue], budget: NativeDocumentBudget ) throws -> [String: NativeValue] { guard surface == .claudeCode || surface == .cursorEditor else { - throw failure([], .unverified, "this container profile has no shared parsed-field contract") + throw failure( + document, fieldPrefix, .unverified, + "this container profile has no shared parsed-field contract") } try admit(.object(fields), budget: budget) try budget.step(entries.count) @@ -91,7 +101,9 @@ extension NativeComponentFieldsV1 { guard (try? PathSafety.sanitizeSubpath(entry.path)) == entry.path, coordinates.insert(entry.path).inserted else { - throw failure([], .invalid, "native resource coordinates must be unique and contained") + throw failure( + document, fieldPrefix, .invalid, + "native resource coordinates must be unique and contained") } } for (path, value) in documents { @@ -99,7 +111,8 @@ extension NativeComponentFieldsV1 { try admit(value, budget: budget) } let validator = NativePluginFieldsV1( - surface: surface, entries: entries, budget: budget, documents: documents) + surface: surface, document: document, fieldPrefix: fieldPrefix, entries: entries, + budget: budget, documents: documents) try validator.validate(fields) return fields } @@ -107,13 +120,18 @@ extension NativeComponentFieldsV1 { /// One native Claude/OpenCode LSP entry, without launch or placeholder expansion. Native /// placeholders remain source syntax; G must convert bindings before canonical capture. package static func lsp( - surface: NativeClientSurface, fields: [String: NativeValue], budget: NativeDocumentBudget + surface: NativeClientSurface, document: String, fieldPrefix: [String] = [], + fields: [String: NativeValue], + budget: NativeDocumentBudget ) throws -> [String: NativeValue] { try admit(.object(fields), budget: budget) switch surface { case .claudeCode: - try NativePluginFieldsV1(surface: surface, entries: [], budget: budget, documents: [:]) - .lsp(.object(fields), field: []) + try NativePluginFieldsV1( + surface: surface, document: document, fieldPrefix: fieldPrefix, entries: [], budget: budget, + documents: [:] + ) + .lsp(.object(fields), field: []) case .openCodeCLI: // A disabled built-in entry has no explicit executable to project into a declaration. if fields == ["disabled": .boolean(true)] { return fields } @@ -122,24 +140,32 @@ extension NativeComponentFieldsV1 { rules["env"] = .object rules["initialization"] = .object guard fields["command"] != nil else { - throw failure(["command"], .invalid, "native LSP server entry requires command argv") + throw failure( + document, fieldPrefix + ["command"], .invalid, + "native LSP server entry requires command argv") } - for (index, item) in fields.sorted(by: { $0.key < $1.key }).enumerated() { + for item in fields.sorted(by: { $0.key < $1.key }) { guard let rule = rules[item.key] else { throw failure( - [String(index)], .unverified, "native LSP field is outside the finite profile") + document, fieldPrefix + [item.key], .unverified, + "native LSP field is outside the finite profile") } guard rule.accepts(item.value) else { - throw failure([item.key], .invalid, "native LSP field has an invalid type or range") + throw failure( + document, fieldPrefix + [item.key], .invalid, + "native LSP field has an invalid type or range") } if item.key == "env", case .object(let values) = item.value, !values.values.allSatisfy({ if case .string = $0 { true } else { false } }) { - throw failure(["env"], .invalid, "native LSP environment requires string values") + throw failure( + document, fieldPrefix + ["env"], .invalid, + "native LSP environment requires string values") } } default: - throw failure([], .unverified, "this surface has no shared native LSP input contract") + throw failure( + document, fieldPrefix, .unverified, "this surface has no shared native LSP input contract") } return fields } @@ -148,13 +174,17 @@ extension NativeComponentFieldsV1 { /// used only by schemas that permit a filename fallback. inPlugin is the actual source /// registration context, not inferred from the desired deployment scope. No fields are dropped. package static func markdown( - surface: NativeClientSurface, kind: DeclaredComponentKind, name: String, + surface: NativeClientSurface, document: String, fieldPrefix: [String] = [], + kind: DeclaredComponentKind, name: String, fields: [String: NativeValue], inPlugin: Bool, budget: NativeDocumentBudget ) throws -> [String: NativeValue] { guard [.claudeCode, .cursorEditor, .geminiCLI].contains(surface), kind == .command || kind == .subagent, !(surface == .geminiCLI && kind == .command) - else { throw failure([], .unverified, "native Markdown input is outside this finite profile") } + else { + throw failure( + document, fieldPrefix, .unverified, "native Markdown input is outside this finite profile") + } try admit(.object(fields), budget: budget) try budget.allocate(name.utf8.count, stage: "native member coordinate") try budget.step(name.utf8.count) @@ -163,11 +193,13 @@ extension NativeComponentFieldsV1 { (try? PathSafety.sanitizeSubpath(name)) == name else { throw failure( - ["name"], .invalid, "native command requires an exact contained relative name") + document, fieldPrefix + ["name"], .invalid, + "native command requires an exact contained relative name") } if surface == .cursorEditor, name.contains("/") { throw failure( - ["name"], .unverified, "nested command discovery is not established for this profile") + document, fieldPrefix + ["name"], .unverified, + "nested command discovery is not established for this profile") } } @@ -180,10 +212,11 @@ extension NativeComponentFieldsV1 { } else if surface == .claudeCode { rules["description"] = .string } - for (index, item) in fields.sorted(by: { $0.key < $1.key }).enumerated() { + for item in fields.sorted(by: { $0.key < $1.key }) { guard let rule = rules[item.key] else { throw failure( - [String(index)], .unverified, "native frontmatter field has no verified projection") + document, fieldPrefix + [item.key], .unverified, + "native frontmatter field has no verified projection") } // The native source format also admits comma-separated tools. Preserve its source // spelling for G's canonical projection rather than guessing tool-pattern tokenization. @@ -193,25 +226,31 @@ extension NativeComponentFieldsV1 { continue } guard rule.accepts(item.value) else { - throw failure([item.key], .invalid, "native frontmatter field has an invalid type or range") + throw failure( + document, fieldPrefix + [item.key], .invalid, + "native frontmatter field has an invalid type or range") } } if inPlugin, surface == .claudeCode, kind == .subagent, fields["permissionMode"] != nil { throw failure( - ["permissionMode"], .unsupported, + document, fieldPrefix + ["permissionMode"], .unsupported, "native plugin agents ignore this field; standalone policy projection would change meaning") } if surface == .claudeCode, kind == .command { for key in ["agent", "background"] where fields[key] != nil && fields["context"] != .string("fork") { - throw failure([key], .unsupported, "native command field requires context fork") + throw failure( + document, fieldPrefix + [key], .unsupported, "native command field requires context fork") } } if kind == .subagent { if surface != .cursorEditor { guard case .string(let description) = fields["description"], !description.isEmpty, fields["name"] != nil - else { throw failure([], .invalid, "native agent requires name and nonempty description") } + else { + throw failure( + document, fieldPrefix, .invalid, "native agent requires name and nonempty description") + } } let effective: String if case .string(let supplied) = fields["name"] { @@ -221,13 +260,18 @@ extension NativeComponentFieldsV1 { } guard !effective.isEmpty, !effective.contains("/"), !effective.contains("\\"), effective != ".", effective != "..", !effective.utf8.contains(0) - else { throw failure(["name"], .invalid, "native agent requires a contained filename") } + else { + throw failure( + document, fieldPrefix + ["name"], .invalid, "native agent requires a contained filename") + } if surface == .claudeCode, effective.count > 256 || effective.contains(":") { - throw failure(["name"], .invalid, "native agent name exceeds its native domain") + throw failure( + document, fieldPrefix + ["name"], .invalid, "native agent name exceeds its native domain") } if surface == .geminiCLI { guard effective.range(of: #"^[a-z0-9_-]+$"#, options: .regularExpression) != nil else { - throw failure(["name"], .invalid, "native agent requires a lowercase slug") + throw failure( + document, fieldPrefix + ["name"], .invalid, "native agent requires a lowercase slug") } if case .array(let tools) = fields["tools"] { guard @@ -235,7 +279,11 @@ extension NativeComponentFieldsV1 { if case .string(let tool) = $0 { return GeminiAdapter.validAgentTool(tool) } return false }) - else { throw failure(["tools"], .invalid, "native tool is outside the pinned schema") } + else { + throw failure( + document, fieldPrefix + ["tools"], .invalid, + "native tool is outside the pinned schema") + } } } } @@ -243,8 +291,10 @@ extension NativeComponentFieldsV1 { } private static func failure( - _ field: [String], _ reason: NativeAdapterIssue.Reason, _ detail: String - ) -> NativeComponentFieldIssue { .init(field: field, reason: reason, detail: detail) } + _ document: String, _ field: [String], _ reason: NativeAdapterIssue.Reason, _ detail: String + ) -> NativeComponentFieldIssue { + .init(document: document, field: field, reason: reason, detail: detail) + } private static func admit(_ value: NativeValue, budget: NativeDocumentBudget, depth: Int = 0) throws diff --git a/Sources/Components/NativePluginFieldsV1.swift b/Sources/Components/NativePluginFieldsV1.swift index b1b9030..ebf810a 100644 --- a/Sources/Components/NativePluginFieldsV1.swift +++ b/Sources/Components/NativePluginFieldsV1.swift @@ -6,14 +6,16 @@ import NativeDocuments /// bytes and discovery precedence are preserved; this is not decomposition or installation. struct NativePluginFieldsV1 { let surface: NativeClientSurface + let document: String let entries: [LedgerEntry] let budget: NativeDocumentBudget let readJSON: (String, [String]) throws -> NativeValue - let issue: ([String], String, NativeAdapterIssue.Reason) -> Error + var issue: ([String], String, NativeAdapterIssue.Reason) -> Error var claude: Bool { surface == .claudeCode } init(input: ComponentRenderInput, resource: LedgerResource, root: URL) { surface = input.request.surface + document = surface == .claudeCode ? ".claude-plugin/plugin.json" : ".cursor-plugin/plugin.json" entries = resource.entries budget = input.budget issue = { input.issue(["manifest"] + $0, $2, $1) } @@ -45,19 +47,25 @@ struct NativePluginFieldsV1 { } init( - surface: NativeClientSurface, entries: [LedgerEntry], budget: NativeDocumentBudget, + surface: NativeClientSurface, document: String, fieldPrefix: [String] = [], + entries: [LedgerEntry], + budget: NativeDocumentBudget, documents: [String: NativeValue] ) { self.surface = surface + self.document = document self.entries = entries self.budget = budget - issue = { NativeComponentFieldIssue(field: $0, reason: $2, detail: $1) } + issue = { + NativeComponentFieldIssue(document: document, field: fieldPrefix + $0, reason: $2, detail: $1) + } readJSON = { relative, field in guard entries.contains(where: { $0.path == relative && $0.kind == .file }), let value = documents[relative] else { throw NativeComponentFieldIssue( - field: field, reason: .invalid, detail: "referenced native JSON document was not supplied" + document: document, field: fieldPrefix + field, reason: .invalid, + detail: "referenced native JSON document was not supplied" ) } return value @@ -248,50 +256,71 @@ struct NativePluginFieldsV1 { } // Native defaults retain their own merge/replacement behavior. They are not rewritten. let defaults = try NativeComponentFieldsV1.pluginDefaults( - surface: surface, explicitFields: Set(fields.keys)) + surface: surface, document: document, explicitFields: Set(fields.keys)) try budget.step(entries.count * 3) for field in claude ? ["hooks", "mcpServers", "lspServers"] : ["hooks", "mcpServers"] { guard let file = defaults[field], entries.contains(where: { $0.path == file }) else { continue } - let value = try json(file, field: [field, "default"]) - try configuration(value, field: field, wrapped: true) + try configurationFile(file, field: field, coordinate: [field]) } } - func configurations(_ value: NativeValue, field: String) throws { + /// The reference is located in the current document; values loaded through it are + /// located in the referenced document, regardless of later native merge winners. + func configurationFile(_ relative: String, field: String, coordinate: [String]) throws { + let value = try json(relative, field: coordinate) + var validator = self + validator.issue = { path, detail, reason in + let original = self.issue(path, detail, reason) + guard original is NativeComponentFieldIssue else { return original } + let local = field == "lspServers" && path.first == field ? Array(path.dropFirst()) : path + return NativeComponentFieldIssue( + document: relative, field: local, reason: reason, detail: detail) + } + try validator.configuration(value, field: field, wrapped: true) + } + + func configurations(_ value: NativeValue, field: String, coordinate: [String]? = nil) throws { try budget.step() + let coordinate = coordinate ?? [field] if case .array(let values) = value { guard claude || field == "mcpServers" else { - throw fail([field], "native hooks do not accept an array of configuration sources") + throw fail(coordinate, "native hooks do not accept an array of configuration sources") + } + for (index, value) in values.enumerated() { + try configurations(value, field: field, coordinate: coordinate + [String(index)]) } - for value in values { try configurations(value, field: field) } } else if case .string = value { if claude, field == "mcpServers" { - let source = try text(value, [field]) + let source = try text(value, coordinate) if source.hasSuffix(".mcpb") || source.hasSuffix(".dxt") { throw fail( - [field], + coordinate, "native MCP bundle extraction and registration require frozen typed children and closed E/D routes", .integrationRequired) } } - let relative = try path(value, [field], kind: .file, suffix: ".json") - try configuration(json(relative, field: [field]), field: field, wrapped: true) + let relative = try path(value, coordinate, kind: .file, suffix: ".json") + try configurationFile(relative, field: field, coordinate: coordinate) } else { guard claude else { throw fail( - [field], + coordinate, "the exact inline Cursor container wrapper requires a primary schema/example beyond its documented object type", .unverified) } - try configuration(value, field: field, wrapped: false) + var validator = self + validator.issue = { path, detail, reason in + self.issue(coordinate + path.dropFirst(), detail, reason) + } + try validator.configuration(value, field: field, wrapped: false) } } func configuration(_ value: NativeValue, field: String, wrapped: Bool) throws { guard case .object(let root) = value else { - throw fail([field], "native config requires an object") + throw fail(wrapped ? [] : [field], "native config requires an object") } let map: [String: NativeValue] if wrapped && field != "lspServers" { @@ -301,9 +330,9 @@ struct NativePluginFieldsV1 { } else { allowed = claude ? [field, "description"] : [field, "version"] } - guard Set(root.keys).isSubset(of: allowed) else { + if let unknown = root.keys.sorted().first(where: { !allowed.contains($0) }) { throw fail( - [field], "native file root contains fields outside the captured wrapper profile", + [unknown], "native file root contains fields outside the captured wrapper profile", .unverified) } guard case .object(let entries) = root[field] else { @@ -312,9 +341,9 @@ struct NativePluginFieldsV1 { field == "mcpServers" ? .unverified : .invalid) } if let description = root["description"] { - _ = try text(description, [field, "description"]) + _ = try text(description, ["description"]) } - if let schema = root["$schema"] { _ = try text(schema, [field, "$schema"]) } + if let schema = root["$schema"] { _ = try text(schema, ["$schema"]) } if let version = root["version"] { let one: Bool switch version { @@ -324,7 +353,7 @@ struct NativePluginFieldsV1 { } guard one else { throw fail( - [field, "version"], "native hook file version is outside the fixed version-one profile", + ["version"], "native hook file version is outside the fixed version-one profile", .unverified) } } @@ -351,50 +380,53 @@ struct NativePluginFieldsV1 { else { throw fail(["hooks", event], "native hook event or handler array is invalid") } - for entry in entries { + for (index, entry) in entries.enumerated() { + let path = ["hooks", event, String(index)] guard case .object(let object) = entry else { - throw fail(["hooks", event], "native hook entry requires an object") + throw fail(path, "native hook entry requires an object") } if claude { guard Set(object.keys).isSubset(of: ["matcher", "hooks"]), case .array(let handlers) = object["hooks"] else { - throw fail(["hooks", event], "Claude hook group requires matcher/hooks fields") + throw fail(path, "Claude hook group requires matcher/hooks fields") } if let matcher = object["matcher"] { - let pattern = try text(matcher, ["hooks", event, "matcher"]) + let pattern = try text(matcher, path + ["matcher"]) guard NativeDocumentedHooksV1.admittedMatcher(pattern) else { throw fail( - ["hooks", event, "matcher"], + path + ["matcher"], "exact native JavaScript regex admission is required beyond this fragment profile", .unverified) } guard !NativeDocumentedHooksV1.claudeWithoutMatcher.contains(event) else { throw fail( - ["hooks", event, "matcher"], "this native event ignores matchers", .unsupported) + path + ["matcher"], "this native event ignores matchers", .unsupported) } } - for handler in handlers { try handlerFields(handler, event: event) } + for (handlerIndex, handler) in handlers.enumerated() { + try handlerFields(handler, event: event, path: path + ["hooks", String(handlerIndex)]) + } } else { - try handlerFields(entry, event: event) + try handlerFields(entry, event: event, path: path) } } } } - func handlerFields(_ value: NativeValue, event: String) throws { + func handlerFields(_ value: NativeValue, event: String, path: [String]) throws { try budget.step() guard case .object(let handler) = value else { - throw fail(["hooks", event], "native handler requires an object") + throw fail(path, "native handler requires an object") } let type = try text( - handler["type"] ?? (claude ? .null : .string("command")), ["hooks", event, "type"]) + handler["type"] ?? (claude ? .null : .string("command")), path + ["type"]) guard claude ? ["command", "http", "prompt", "agent", "mcp_tool"].contains(type) : type == "command" else { throw fail( - ["hooks", event, "type"], + path + ["type"], claude ? "native handler type is not established" : "Cursor plugin hooks are command-only", .unsupported) } @@ -410,7 +442,7 @@ struct NativePluginFieldsV1 { || (type == "http" && ["SessionStart", "Setup"].contains(event)) { throw fail( - ["hooks", event, "type"], "native event skips this handler type", .unsupported) + path + ["type"], "native event skips this handler type", .unsupported) } } let required: [String] @@ -420,7 +452,7 @@ struct NativePluginFieldsV1 { case "prompt", "agent": required = ["prompt"] default: required = ["server", "tool"] } - for key in required { _ = try text(handler[key] ?? .null, ["hooks", event, key]) } + for key in required { _ = try text(handler[key] ?? .null, path + [key]) } let specific: Set switch type { case "command": @@ -433,7 +465,7 @@ struct NativePluginFieldsV1 { default: specific = ["server", "tool", "input"] } for (key, value) in handler { - let field = ["hooks", event, key] + let field = path + [key] guard specific.contains(key) || (claude ? ["type", "if", "timeout", "statusMessage"] : ["type", "timeout"]).contains( @@ -527,14 +559,14 @@ struct NativePluginFieldsV1 { } if claude, type == "mcp_tool", ["SessionStart", "Setup"].contains(event) { throw fail( - ["hooks", event, "type"], "MCP hook availability is not guaranteed during native startup", + path + ["type"], "MCP hook availability is not guaranteed during native startup", .unverified) } if claude, handler["timeout"] != nil, handler["async"] == .boolean(true) || handler["asyncRewake"] == .boolean(true) { throw fail( - ["hooks", event, "timeout"], "native background hook ignores timeout", .unsupported) + path + ["timeout"], "native background hook ignores timeout", .unsupported) } } diff --git a/Sources/NativeDocuments/NativeDocument.swift b/Sources/NativeDocuments/NativeDocument.swift index 676ca0a..1a2d528 100644 --- a/Sources/NativeDocuments/NativeDocument.swift +++ b/Sources/NativeDocuments/NativeDocument.swift @@ -121,7 +121,7 @@ package struct NativeDocument { } var current = self var changed: [NativeRegion] = [] - var created: [NativeRegion] = [] + var created: [(region: NativeRegion, address: [AddressStep])] = [] var observed: [Int] = [] var appended: [(editIndex: Int, ordinal: Int)] = [] var removed: [([AddressStep], Int)] = [] @@ -209,15 +209,17 @@ package struct NativeDocument { throw NativeDocumentError.unsupportedEdit(.ambiguousTrivia, edit.region, old.headers) } } + var editCreated: [NativeRegion] = [] if edit.isAppend && old == nil { try budget.allocate(effective.steps.count + 1, stage: "created array evidence") - created.append(effective) + editCreated.append(effective) } - try current.createdObjects(old: old, new: desired, path: effective.steps, into: &created) + try current.createdObjects( + old: old, new: desired, path: effective.steps, into: &editCreated) let expected = try current.root.copy(budget) try current.change( expected, steps: effective.steps[...], desired: desired, region: effective, - created: &created) + created: &editCreated) var editor = PatchBuilder(document: current, region: effective) let checked: NativeDocument do { @@ -256,6 +258,22 @@ package struct NativeDocument { throw NativeDocumentError.unsupportedEdit( .wouldRewriteUnownedStructure, edit.region, editor.patches.map(\.range)) } + // Creation paths share the admitted edit's original address. Any suffix is a + // newly created object member, so no snapshot selector is reselected by value. + for container in editCreated { + let shared = min(container.steps.count, edit.region.steps.count) + try budget.allocate(container.steps.count * 2 + 1, stage: "created container address") + var address = Array(addresses[editIndex].prefix(shared)) + let suffix = container.steps.dropFirst(shared) + for step in suffix { + guard case .key(let key) = step else { + throw NativeDocumentError.ownershipMismatch(container) + } + try budget.allocate(key.utf8.count, stage: "created member address") + address.append(.key(Data(key.utf8))) + } + created.append((NativeRegion(Array(edit.region.steps.prefix(shared)) + suffix), address)) + } if edit.isAppend { var ordinal = old?.elements.count ?? 0 for (path, _) in removed { @@ -301,9 +319,30 @@ package struct NativeDocument { editIndex: index, observation: try current.observation(array.elements[ordinal], region: region))) } + var createdContainers: [NativeRegion] = [] + for container in created { + var deleted = false + for (parent, ordinal) in removed { + try budget.step(parent.reduce(0) { $0 + $1.work } + container.address.count) + if container.address.count > parent.count, + container.address.starts(with: parent), + container.address[parent.count] == .element(ordinal) + { + deleted = true + break + } + } + if deleted { continue } + let region = try current.region( + container.region, at: container.address, removed: removed) + if try current.resolve(region, on: current.root) != nil { + try budget.allocate(region.steps.count + 1, stage: "final created container evidence") + createdContainers.append(region) + } + } return PreparedNativeChange( bytes: current.bytes, changedRegions: changed, observations: observations, - createdContainers: created, appendedOccurrences: appendedOccurrences) + createdContainers: createdContainers, appendedOccurrences: appendedOccurrences) } } diff --git a/Tests/ComponentsTests/NativeComponentFieldsTests.swift b/Tests/ComponentsTests/NativeComponentFieldsTests.swift index 6ed9824..9c65b54 100644 --- a/Tests/ComponentsTests/NativeComponentFieldsTests.swift +++ b/Tests/ComponentsTests/NativeComponentFieldsTests.swift @@ -22,25 +22,29 @@ struct NativeComponentFieldsTests { ] #expect( try NativeComponentFieldsV1.markdown( - surface: .claudeCode, kind: .subagent, name: "auditor", fields: fields, inPlugin: false, + surface: .claudeCode, document: "source.json", kind: .subagent, name: "auditor", + fields: fields, inPlugin: false, budget: budget()) == fields) #expect(throws: NativeComponentFieldIssue.self) { try NativeComponentFieldsV1.markdown( - surface: .claudeCode, kind: .subagent, name: "auditor", fields: fields, + surface: .claudeCode, document: "source.json", kind: .subagent, name: "auditor", + fields: fields, inPlugin: true, budget: budget()) } var commaTools = fields commaTools["tools"] = .string("Read, Grep") #expect( try NativeComponentFieldsV1.markdown( - surface: .claudeCode, kind: .subagent, name: "auditor", fields: commaTools, inPlugin: false, + surface: .claudeCode, document: "source.json", kind: .subagent, name: "auditor", + fields: commaTools, inPlugin: false, budget: budget()) == commaTools) var unknown = fields unknown["permissionmode"] = .string("value-canary") do { _ = try NativeComponentFieldsV1.markdown( - surface: .claudeCode, kind: .subagent, name: "auditor", fields: unknown, inPlugin: false, + surface: .claudeCode, document: "source.json", kind: .subagent, name: "auditor", + fields: unknown, inPlugin: false, budget: budget()) Issue.record("silently ignored unknown native field") } catch let issue as NativeComponentFieldIssue { @@ -49,17 +53,19 @@ struct NativeComponentFieldsTests { } #expect(throws: NativeComponentFieldIssue.self) { try NativeComponentFieldsV1.markdown( - surface: .claudeCode, kind: .command, name: "review", + surface: .claudeCode, document: "source.json", kind: .command, name: "review", fields: ["background": .boolean(true)], inPlugin: false, budget: budget()) } #expect( try NativeComponentFieldsV1.markdown( - surface: .claudeCode, kind: .command, name: "team/review", fields: [:], + surface: .claudeCode, document: "source.json", kind: .command, name: "team/review", + fields: [:], inPlugin: false, budget: budget() ).isEmpty) #expect(throws: NativeComponentFieldIssue.self) { try NativeComponentFieldsV1.markdown( - surface: .cursorEditor, kind: .command, name: "team/review", fields: [:], + surface: .cursorEditor, document: "source.json", kind: .command, name: "team/review", + fields: [:], inPlugin: false, budget: budget()) } let cursor: [String: NativeValue] = [ @@ -67,12 +73,13 @@ struct NativeComponentFieldsTests { ] #expect( try NativeComponentFieldsV1.markdown( - surface: .cursorEditor, kind: .subagent, name: "auditor", fields: cursor, inPlugin: false, + surface: .cursorEditor, document: "source.json", kind: .subagent, name: "auditor", + fields: cursor, inPlugin: false, budget: budget()) == cursor) #expect(throws: NativeComponentFieldIssue.self) { try NativeComponentFieldsV1.markdown( - surface: .cursorEditor, kind: .subagent, name: "auditor", + surface: .cursorEditor, document: "source.json", kind: .subagent, name: "auditor", fields: ["tools": .array([.string("Read")])], inPlugin: false, budget: budget()) } } @@ -87,17 +94,20 @@ struct NativeComponentFieldsTests { ]), ] #expect( - try NativeComponentFieldsV1.lsp(surface: .claudeCode, fields: fields, budget: budget()) + try NativeComponentFieldsV1.lsp( + surface: .claudeCode, document: "source.json", fields: fields, budget: budget()) == fields) var unknown = fields unknown["cwd"] = .string("value-canary") #expect(throws: NativeComponentFieldIssue.self) { - try NativeComponentFieldsV1.lsp(surface: .claudeCode, fields: unknown, budget: budget()) + try NativeComponentFieldsV1.lsp( + surface: .claudeCode, document: "source.json", fields: unknown, budget: budget()) } var invalid = fields invalid["requestTimeout"] = .integer(0) #expect(throws: NativeComponentFieldIssue.self) { - try NativeComponentFieldsV1.lsp(surface: .claudeCode, fields: invalid, budget: budget()) + try NativeComponentFieldsV1.lsp( + surface: .claudeCode, document: "source.json", fields: invalid, budget: budget()) } } @@ -110,25 +120,29 @@ struct NativeComponentFieldsTests { ] #expect( try NativeComponentFieldsV1.lsp( - surface: .openCodeCLI, fields: fields, budget: budget()) == fields) + surface: .openCodeCLI, document: "source.json", fields: fields, budget: budget()) == fields) let disabled: [String: NativeValue] = ["disabled": .boolean(true)] #expect( try NativeComponentFieldsV1.lsp( - surface: .openCodeCLI, fields: disabled, budget: budget()) == disabled) + surface: .openCodeCLI, document: "source.json", fields: disabled, budget: budget()) + == disabled) var invalid = fields invalid["env"] = .object(["SOURCE": .integer(7)]) #expect(throws: NativeComponentFieldIssue.self) { - try NativeComponentFieldsV1.lsp(surface: .openCodeCLI, fields: invalid, budget: budget()) + try NativeComponentFieldsV1.lsp( + surface: .openCodeCLI, document: "source.json", fields: invalid, budget: budget()) } } @Test func parsedPluginUsesProducerRootAndMergeDefaults() throws { let claudeDefaults = try NativeComponentFieldsV1.pluginDefaults( - surface: .claudeCode, explicitFields: ["commands", "agents", "skills", "hooks"]) + surface: .claudeCode, document: "source.json", + explicitFields: ["commands", "agents", "skills", "hooks"]) #expect(claudeDefaults["commands"] == nil && claudeDefaults["agents"] == nil) #expect(claudeDefaults["skills"] == "skills" && claudeDefaults["hooks"] == "hooks/hooks.json") let cursorDefaults = try NativeComponentFieldsV1.pluginDefaults( - surface: .cursorEditor, explicitFields: ["commands", "skills", "hooks"]) + surface: .cursorEditor, document: "source.json", + explicitFields: ["commands", "skills", "hooks"]) #expect(cursorDefaults["commands"] == nil && cursorDefaults["skills"] == nil) #expect(cursorDefaults["hooks"] == nil && cursorDefaults["mcpServers"] == "mcp.json") let entries: [LedgerEntry] = [ @@ -143,13 +157,13 @@ struct NativeComponentFieldsTests { let badDefault: NativeValue = .object(["hooks": .object(["invented": .array([])])]) #expect(throws: NativeComponentFieldIssue.self) { try NativeComponentFieldsV1.plugin( - surface: .claudeCode, fields: valid, + surface: .claudeCode, document: "source.json", fields: valid, entries: entries, documents: ["hooks/hooks.json": badDefault], budget: budget()) } let emptyHooks: NativeValue = .object(["hooks": .object([:])]) #expect( try NativeComponentFieldsV1.plugin( - surface: .claudeCode, fields: valid, + surface: .claudeCode, document: "source.json", fields: valid, entries: entries, documents: ["hooks/hooks.json": emptyHooks], budget: budget()) == valid) // Cursor explicit hooks replace its default; an absent explicit file still fails. let cursor: [String: NativeValue] = [ @@ -158,19 +172,148 @@ struct NativeComponentFieldsTests { let cursorEntries = entries + [.init(path: "chosen.json", kind: .file, executable: false)] #expect( try NativeComponentFieldsV1.plugin( - surface: .cursorEditor, fields: cursor, + surface: .cursorEditor, document: "source.json", fields: cursor, entries: cursorEntries, documents: ["chosen.json": .object(["version": .integer(1), "hooks": .object([:])])], budget: budget()) == cursor) #expect(throws: NativeComponentFieldIssue.self) { try NativeComponentFieldsV1.plugin( - surface: .cursorEditor, fields: cursor, + surface: .cursorEditor, document: "source.json", fields: cursor, entries: entries, documents: [:], budget: budget()) } #expect(throws: (any Error).self) { try NativeComponentFieldsV1.plugin( - surface: .claudeCode, fields: valid, + surface: .claudeCode, document: "source.json", fields: valid, entries: entries, documents: ["hooks/hooks.json": emptyHooks], budget: budget(1)) } } + @Test func referencedConfigurationFailuresKeepTheirExactDocumentAndField() throws { + let manifest = ".claude-plugin/plugin.json" + let entries: [LedgerEntry] = [ + .init(path: "first.json", kind: .file, executable: false), + .init(path: "second.json", kind: .file, executable: false), + .init(path: ".lsp.json", kind: .file, executable: false), + .init(path: "hooks/hooks.json", kind: .file, executable: false), + ] + let first: NativeValue = .object([ + "mcpServers": .object(["same": .object(["command": .integer(17)])]) + ]) + let second: NativeValue = .object([ + "mcpServers": .object(["same": .object(["command": .string("valid")])]) + ]) + let fields: [String: NativeValue] = [ + "name": .string("fixture"), + "mcpServers": .array([.string("./first.json"), .string("./second.json")]), + ] + do { + _ = try NativeComponentFieldsV1.plugin( + surface: .claudeCode, document: manifest, fields: fields, entries: entries, + documents: ["first.json": first, "second.json": second], budget: budget()) + Issue.record("invalid overwritten source was accepted") + } catch let issue as NativeComponentFieldIssue { + #expect(issue.document == "first.json") + #expect(issue.field == ["mcpServers", "same", "command"]) + #expect(!issue.detail.contains("17")) + } + do { + _ = try NativeComponentFieldsV1.plugin( + surface: .claudeCode, document: manifest, + fields: ["name": .string("fixture")], entries: entries, + documents: [ + "hooks/hooks.json": .object(["hooks": .object([:])]), + ".lsp.json": .object([ + "same": .object([ + "command": .integer(17), "extensionToLanguage": .object([".x": .string("x")]), + ]) + ]), + ], budget: budget()) + Issue.record("invalid default source was accepted") + } catch let issue as NativeComponentFieldIssue { + #expect(issue.document == ".lsp.json") + #expect(issue.field == ["same", "command"]) + } + do { + _ = try NativeComponentFieldsV1.plugin( + surface: .claudeCode, document: manifest, + fields: [ + "name": .string("fixture"), + "hooks": .array([ + .object([:]), + .object([ + "SessionStart": .array([ + .object([ + "hooks": .array([.object(["type": .string("command"), "command": .integer(17)])]) + ]) + ]) + ]), + ]), + ], entries: [], documents: [:], budget: budget()) + Issue.record("invalid inline source was accepted") + } catch let issue as NativeComponentFieldIssue { + #expect(issue.document == manifest) + #expect(issue.field == ["hooks", "1", "SessionStart", "0", "hooks", "0", "command"]) + } + do { + _ = try NativeComponentFieldsV1.plugin( + surface: .claudeCode, document: manifest, + fields: [ + "name": .string("fixture"), + "mcpServers": .array([ + .object([:]), .string("./missing.json"), + ]), + ], entries: [], documents: [:], budget: budget()) + Issue.record("missing referenced file was accepted") + } catch let issue as NativeComponentFieldIssue { + #expect(issue.document == manifest) + #expect(issue.field == ["mcpServers", "1"]) + } + } + + @Test func externalHookCoordinatesIncludeHandlerIndicesAndRootMetadata() throws { + let file = "hooks/chosen.json" + let entries: [LedgerEntry] = [.init(path: file, kind: .file, executable: false)] + let fields: [String: NativeValue] = ["name": .string("fixture"), "hooks": .string(file)] + for invalidMetadata in [false, true] { + let config: NativeValue = .object([ + "version": invalidMetadata ? .integer(2) : .integer(1), + "hooks": .object([ + "stop": .array([ + .object(["command": .string("keep")]), .object(["command": .integer(17)]), + ]) + ]), + ]) + do { + _ = try NativeComponentFieldsV1.plugin( + surface: .cursorEditor, document: ".cursor-plugin/plugin.json", fields: fields, + entries: entries, documents: [file: config], budget: budget()) + Issue.record("invalid external hooks were accepted") + } catch let issue as NativeComponentFieldIssue { + #expect(issue.document == file) + #expect(issue.field == (invalidMetadata ? ["version"] : ["hooks", "stop", "1", "command"])) + } + } + } + + @Test func directParsedFailuresRetainCallerDocumentAndFieldPrefix() throws { + do { + _ = try NativeComponentFieldsV1.lsp( + surface: .claudeCode, document: "settings.json", fieldPrefix: ["lsp", "same"], + fields: ["command": .integer(17), "extensionToLanguage": .object([".x": .string("x")])], + budget: budget()) + Issue.record("invalid LSP command was accepted") + } catch let issue as NativeComponentFieldIssue { + #expect(issue.document == "settings.json") + #expect(issue.field == ["lsp", "same", "command"]) + } + do { + _ = try NativeComponentFieldsV1.markdown( + surface: .claudeCode, document: "commands/review.md", kind: .command, name: "review", + fields: ["model": .integer(17)], inPlugin: true, budget: budget()) + Issue.record("invalid Markdown field was accepted") + } catch let issue as NativeComponentFieldIssue { + #expect(issue.document == "commands/review.md") + #expect(issue.field == ["model"]) + } + } + } diff --git a/Tests/ComponentsTests/NativeComponentTests.swift b/Tests/ComponentsTests/NativeComponentTests.swift index 74b9bca..03998b2 100644 --- a/Tests/ComponentsTests/NativeComponentTests.swift +++ b/Tests/ComponentsTests/NativeComponentTests.swift @@ -1157,7 +1157,7 @@ struct NativeComponentTests { _ = try prepared(skipped, fixture) Issue.record("accepted a handler type the native event skips") } catch let issue as NativeComponentIssue { - #expect(issue.field == ["manifest", "hooks", "PermissionRequest", "type"]) + #expect(issue.field == ["manifest", "hooks", "PermissionRequest", "0", "hooks", "0", "type"]) #expect(issue.reason == .unsupported) } invalid["hooks"] = [ @@ -1173,7 +1173,7 @@ struct NativeComponentTests { _ = try prepared(ignored, fixture) Issue.record("accepted a native failure policy with no effect") } catch let issue as NativeComponentIssue { - #expect(issue.field == ["manifest", "hooks", "Stop", "onFailure"]) + #expect(issue.field == ["manifest", "hooks", "Stop", "0", "hooks", "0", "onFailure"]) #expect(issue.reason == .unsupported) } let locked = try ResolvedLedgerCodec.encode(ledger, limits: .standard) @@ -1264,7 +1264,7 @@ struct NativeComponentTests { _ = try prepared(bad, fixture) Issue.record("accepted a prompt handler in a Cursor plugin") } catch let issue as NativeComponentIssue { - #expect(issue.field == ["manifest", "hooks", "stop", "type"]) + #expect(issue.field == ["manifest", "hooks", "stop", "0", "type"]) #expect(issue.reason == .unsupported) } changed["hooks"] = ["hooks": ["stop": [["command": "fixture"]]]] diff --git a/Tests/NativeDocumentsTests/OccurrenceInsertionTests.swift b/Tests/NativeDocumentsTests/OccurrenceInsertionTests.swift index 88cdb4b..e8d7445 100644 --- a/Tests/NativeDocumentsTests/OccurrenceInsertionTests.swift +++ b/Tests/NativeDocumentsTests/OccurrenceInsertionTests.swift @@ -75,6 +75,45 @@ struct OccurrenceInsertionTests { #expect(text(removed) == "{\"other\":7}") } + @Test func createdContainersUnderSnapshotParentsResolveAndPrune() throws { + for removeEarlier in [false, true] { + let source = + removeEarlier + ? #"{"items":[{"remove":true},{"keep":true}]}"# : #"{"items":[{"keep":true}]}"# + let original = try document(source, .json) + let items = keyRegion("items") + let occurrences = try #require(try original.read(items)).occurrences + let parent = NativeRegion(items.steps + [.occurrence(occurrences[removeEarlier ? 1 : 0])]) + let array = NativeRegion(parent.steps + [.key("nested"), .key("hooks")]) + var edits: [NativeRegionEdit] = [ + .append(region: array, expected: .absent, value: .integer(1)), + .append(region: array, expected: .absent, value: .integer(2)), + ] + if removeEarlier { + let first = NativeRegion(items.steps + [.occurrence(occurrences[0])]) + edits.append(.remove(region: first, expected: try owned(original, first))) + } + let changed = try original.prepare(edits) + let live = try NativeDocument(bytes: changed.bytes, format: .json, budget: generousBudget()) + #expect(changed.createdContainers.count == 2) + var removals: [NativeRegionEdit] = [] + for region in changed.createdContainers { + let observed = try #require(try live.read(region)) + removals.append(.pruneCreatedContainer(region: region, observed: observed)) + } + for insertion in changed.appendedOccurrences { + removals.append( + .remove(region: insertion.observation.region, expected: .owned(insertion.observation))) + } + let restored = try live.prepare(removals) + let restoredDocument = try NativeDocument( + bytes: restored.bytes, format: .json, budget: generousBudget()) + #expect( + try restoredDocument.read(items)?.value == .array([.object(["keep": .boolean(true)])])) + #expect(!text(restored).contains("nested")) + } + } + @Test func tomlOccurrencesAppendWithoutNativeIDsAndPreserveUnrelatedBytes() throws { for source in [ "hooks = [{ command = 'keep' }] # retained\nother = 7\n", From b28f54876ef33f7413a871fc8d06039b8a8646b6 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:33:32 +0800 Subject: [PATCH 107/171] fix: preserve complete native import semantics --- .../Import/NativeContainerImport.swift | 4 +- .../Components/Import/NativeImportInput.swift | 22 ++++ .../Import/NativeMemberImport.swift | 13 +++ .../Import/NativeSourceImport.swift | 1 + .../Import/SourceImportProposal.swift | 23 +++- Tests/ComponentsTests/ImportNativeTests.swift | 106 ++++++++++++++++++ 6 files changed, 167 insertions(+), 2 deletions(-) diff --git a/Sources/Components/Import/NativeContainerImport.swift b/Sources/Components/Import/NativeContainerImport.swift index 5526c86..fd58cbc 100644 --- a/Sources/Components/Import/NativeContainerImport.swift +++ b/Sources/Components/Import/NativeContainerImport.swift @@ -32,7 +32,9 @@ enum NativeContainerImport { let surface = NativeImportSemantics.surface(input.profile) let defaults = agent == .geminiCLI - ? ["commands": "commands", "agents": "agents", "skills": "skills"] + ? [ + "commands": "commands", "agents": "agents", "skills": "skills", "hooks": "hooks/hooks.json", + ] : try NativeComponentFieldsV1.pluginDefaults( surface: surface, explicitFields: Set(parsed.fields.keys)) var documents: [String: NativeImportDocument] = [:] diff --git a/Sources/Components/Import/NativeImportInput.swift b/Sources/Components/Import/NativeImportInput.swift index 0c873c1..39bc382 100644 --- a/Sources/Components/Import/NativeImportInput.swift +++ b/Sources/Components/Import/NativeImportInput.swift @@ -296,6 +296,28 @@ enum NativeImportInput { .init(origin: origin, declaration: declaration, member: member)) } + /// A directory may be captured before a later native document reveals a literal binding. + /// Reconcile every source-relative overlap before the operation publishes its proposal, + /// including partial proposals returned after a parsing failure. + static func reconcilePreservation(into diagnostics: inout ImportDiagnostics) { + for index in diagnostics.proposal.resources.indices { + let resource = diagnostics.proposal.resources[index] + guard let path = resource.path, + let root = diagnostics.proposal.sources.first(where: { + $0.alias == resource.sourceAlias + })?.producerPath + else { continue } + let relative = root == "." ? path : root + (path == "." ? "" : "/" + path) + if diagnostics.proposal.bindings.contains(where: { + relative == "." || $0.location.document == relative + || $0.location.document.hasPrefix(relative + "/") + }) { + diagnostics.proposal.resources[index].requiresBindingRewrite = true + diagnostics.proposal.resources[index].observedHash = nil + } + } + } + static func resource( _ path: String, root: String, input: SourceImportInput, origin: ImportLocation, limits: SourceImportLimits, rewrite: Bool = false, diff --git a/Sources/Components/Import/NativeMemberImport.swift b/Sources/Components/Import/NativeMemberImport.swift index 19789f5..f00b785 100644 --- a/Sources/Components/Import/NativeMemberImport.swift +++ b/Sources/Components/Import/NativeMemberImport.swift @@ -96,6 +96,19 @@ enum NativeMemberImport { isAgent ? ["name", "description", "model", "tools"] : ["description"] NativeImportInput.unknown(fields, allowed: converted, at: origin, into: &diagnostics) guard Set(fields.keys).isSubset(of: converted) else { return } + for field in ["name", "description"] where fields[field] != nil { + guard fields[field]?.importString != nil else { + diagnostics.add( + .invalidInput, parsed.header?[field]?.location ?? origin, + "Native Markdown field requires a string value.") + return + } + } + if let value = fields["model"], value.importString == nil { + NativeImportInput.unconverted( + value, at: parsed.header?["model"]?.location ?? origin, into: &diagnostics) + return + } } name = fields["name"]?.importString ?? name model = fields["model"]?.importString diff --git a/Sources/Components/Import/NativeSourceImport.swift b/Sources/Components/Import/NativeSourceImport.swift index 3fe00e2..7017397 100644 --- a/Sources/Components/Import/NativeSourceImport.swift +++ b/Sources/Components/Import/NativeSourceImport.swift @@ -7,6 +7,7 @@ enum NativeSourceImport { _ input: SourceImportInput, limits: SourceImportLimits, into diagnostics: inout ImportDiagnostics ) throws { + defer { NativeImportInput.reconcilePreservation(into: &diagnostics) } switch input.profile { case .geminiIgnoreV1, .cursorIgnoreV1: let bytes = try ImportInput.bytes(input, limits: limits) diff --git a/Sources/Components/Import/SourceImportProposal.swift b/Sources/Components/Import/SourceImportProposal.swift index 2397e50..0498744 100644 --- a/Sources/Components/Import/SourceImportProposal.swift +++ b/Sources/Components/Import/SourceImportProposal.swift @@ -138,6 +138,27 @@ package struct ImportMemberCoordinate: Equatable, Sendable { package let selector: ComponentReferenceDeclaration package let profile: SourceImportProfile package let formatVersion: Int + + /// Producer identifiers are byte identities, including canonically equivalent Unicode names. + package static func == (lhs: Self, rhs: Self) -> Bool { + guard lhs.containerRoot.utf8.elementsEqual(rhs.containerRoot.utf8), + lhs.profile == rhs.profile, lhs.formatVersion == rhs.formatVersion + else { return false } + switch (lhs.selector, rhs.selector) { + case (.skill(let left), .skill(let right)), + (.instruction(let left), .instruction(let right)), + (.mcpServer(let left), .mcpServer(let right)), + (.hook(let left), .hook(let right)), + (.subagent(let left), .subagent(let right)), + (.command(let left), .command(let right)), + (.lspServer(let left), .lspServer(let right)), + (.permissions(let left), .permissions(let right)), + (.ignore(let left), .ignore(let right)), + (.plugin(let left), .plugin(let right)): + return left.utf8.elementsEqual(right.utf8) + default: return false + } + } } package struct ImportedComponent: Equatable, Sendable { @@ -156,7 +177,7 @@ package struct ImportResourceProposal: Equatable, Sendable { /// Relative to the corresponding source root. Nil means exact producer coordinates are absent. package let path: String? package let producerIntegrity: ImportPin.Integrity? - package let observedHash: String? + package var observedHash: String? package let executableFlags: [String: Bool] package let requiresStandaloneSource: Bool package var kind: DeclaredComponentKind? = nil diff --git a/Tests/ComponentsTests/ImportNativeTests.swift b/Tests/ComponentsTests/ImportNativeTests.swift index 79c0c7f..5b760b8 100644 --- a/Tests/ComponentsTests/ImportNativeTests.swift +++ b/Tests/ComponentsTests/ImportNativeTests.swift @@ -670,6 +670,112 @@ struct ImportNativeTests { }) } + @Test func overlappingPreservationResourcesUseCompleteBindingClassification() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "opencode.jsonc", + #"{"mcp":{"servers":{"clean":{"type":"local","command":["tool"],"cwd":"."}}},"lsp":{"language":{"command":["language-server"],"env":{"TOKEN":"LATE_LITERAL_CANARY"}}}}"# + ) + let before = try fixture.hash() + let result = try SourceImport.preview(fixture.input(.openCodeConfigV2, "opencode.jsonc")) + #expect(result.components.count == 2) + let directory = try #require(result.resources.first { $0.path == "." }) + #expect(directory.requiresBindingRewrite) + #expect(directory.observedHash == nil) + #expect(!String(reflecting: result).contains("LATE_LITERAL_CANARY")) + #expect(try fixture.hash() == before) + + try fixture.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"bundle","lspServers":"./skills/audit/language.json"}"#) + try fixture.write( + "bundle/skills/audit/SKILL.md", "---\nname: audit\ndescription: Audit\n---\nBody\n") + try fixture.write( + "bundle/skills/audit/language.json", + #"{"language":{"command":"language-server","extensionToLanguage":{".x":"x"},"env":{"TOKEN":"LATE_SKILL_CANARY"}}}"# + ) + let bundleBefore = try fixture.hash() + let bundle = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(bundle.components.contains { $0.declaration.kind == .skills }) + let skill = try #require(bundle.resources.first { $0.kind == .skills }) + #expect(skill.requiresBindingRewrite) + #expect(skill.observedHash == nil) + #expect(!String(reflecting: bundle).contains("LATE_SKILL_CANARY")) + #expect(try fixture.hash() == bundleBefore) + } + + @Test(arguments: [SourceImportProfile.openCodeCommandV2, .openCodeAgentV2]) + func openCodeMarkdownRejectsInvalidDescriptionAtOriginalField(_ profile: SourceImportProfile) + throws + { + let fixture = try NativeImportFixture() + try fixture.write("review.md", "---\ndescription: [invalid]\n---\nBody\n") + let before = try fixture.hash() + let result = try SourceImport.preview(fixture.input(profile, "review.md")) + #expect(result.components.isEmpty) + #expect( + result.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == "review.md" + && $0.location.span?.line == 2 + }) + #expect(try fixture.hash() == before) + try fixture.write("review.md", "---\ndescription: Review\n---\nBody\n") + let valid = try SourceImport.preview(fixture.input(profile, "review.md")) + #expect(valid.components.count == 1) + #expect(valid.diagnostics.isEmpty) + } + + @Test func geminiExtensionHooksRemainVisibleAndPrivatelyPreserved() throws { + let fixture = try NativeImportFixture() + try fixture.write("bundle/gemini-extension.json", #"{"name":"bundle","version":"1"}"#) + try fixture.write( + "bundle/commands/review.toml", "description='Review'\nprompt='Review changes'\n") + try fixture.write( + "bundle/hooks/hooks.json", + #"{"hooks":{"BeforeTool":[{"hooks":[{"type":"command","command":"./check","token":"HOOK_LITERAL_CANARY"}]}]}}"# + ) + let before = try fixture.hash() + let result = try SourceImport.preview( + fixture.input(.geminiExtensionV1, "bundle/gemini-extension.json")) + #expect(result.components.count == 1) + #expect(result.components.first?.declaration.kind == .command) + #expect( + result.diagnostics.contains { + $0.code == .unconverted && $0.location.document == "bundle/hooks/hooks.json" + }) + #expect(result.bindings.contains { $0.location.document == "bundle/hooks/hooks.json" }) + let hooks = try #require(result.resources.first { $0.path == "hooks/hooks.json" }) + #expect(hooks.requiresBindingRewrite && hooks.observedHash == nil) + #expect(!String(reflecting: result).contains("HOOK_LITERAL_CANARY")) + #expect(try fixture.hash() == before) + } + + @Test func nativeMemberCoordinatesPreserveExactUTF8Selectors() throws { + let fixture = try NativeImportFixture() + try fixture.write("unicode/.claude-plugin/plugin.json", #"{"name":"unicode"}"#) + for (path, name) in [("first", "\u{e9}"), ("second", "e\u{301}")] { + try fixture.write( + "unicode/agents/" + path + ".md", + "---\nname: \(name)\ndescription: Agent\n---\nBody\n") + } + let result = try SourceImport.preview( + fixture.input(.claudePluginV1, "unicode/.claude-plugin/plugin.json")) + #expect(result.components.count == 2) + let members = result.components.compactMap(\.member) + #expect(members.count == 2) + #expect(members.first != members.last) + #expect(!result.diagnostics.contains { $0.code == .ambiguousSource }) + let first = try #require(members.first) + #expect(first == first) + try fixture.write( + "unicode/agents/second.md", "---\nname: \u{e9}\ndescription: Agent\n---\nBody\n") + let duplicate = try SourceImport.preview( + fixture.input(.claudePluginV1, "unicode/.claude-plugin/plugin.json")) + #expect(duplicate.components.isEmpty) + #expect(duplicate.diagnostics.contains { $0.code == .ambiguousSource }) + } + @Test func typedMembersStayStableWhenCallerMovesTheInputRoot() throws { let one = try NativeImportFixture() let two = try NativeImportFixture() From ae1fb30e8fe483d7cb3cd8e9ee7f7b54c8aa8791 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:55:33 +0800 Subject: [PATCH 108/171] fix: report exact native import field locations --- .../Import/NativeContainerImport.swift | 55 +++++++++---------- .../Import/NativeExecutableMembers.swift | 9 ++- .../Import/NativeMemberImport.swift | 28 ++++++---- Tests/ComponentsTests/ImportNativeTests.swift | 34 ++++++++---- 4 files changed, 68 insertions(+), 58 deletions(-) diff --git a/Sources/Components/Import/NativeContainerImport.swift b/Sources/Components/Import/NativeContainerImport.swift index fd58cbc..c42f751 100644 --- a/Sources/Components/Import/NativeContainerImport.swift +++ b/Sources/Components/Import/NativeContainerImport.swift @@ -30,13 +30,22 @@ enum NativeContainerImport { let alias = NativeImportInput.source( input, root: root, origin: parsed.location(), into: &diagnostics) let surface = NativeImportSemantics.surface(input.profile) - let defaults = - agent == .geminiCLI - ? [ - "commands": "commands", "agents": "agents", "skills": "skills", "hooks": "hooks/hooks.json", - ] - : try NativeComponentFieldsV1.pluginDefaults( - surface: surface, explicitFields: Set(parsed.fields.keys)) + let defaults: [String: String] + do { + defaults = + agent == .geminiCLI + ? [ + "commands": "commands", "agents": "agents", "skills": "skills", + "hooks": "hooks/hooks.json", + ] + : try NativeComponentFieldsV1.pluginDefaults( + surface: surface, document: suffix, fieldPrefix: [], + explicitFields: Set(parsed.fields.keys)) + } catch let issue as NativeComponentFieldIssue { + guard issue.document == suffix else { throw ImportReadFailure.invalid } + NativeImportSemantics.report(issue, at: parsed.fieldLocation(issue.field), into: &diagnostics) + return + } var documents: [String: NativeImportDocument] = [:] let metadata: Set = ["name", "version"] let members: Set = @@ -213,33 +222,19 @@ enum NativeContainerImport { } do { _ = try NativeComponentFieldsV1.plugin( - surface: surface, fields: parsed.fields, + surface: surface, document: suffix, fieldPrefix: [], fields: parsed.fields, entries: try inventory(snapshot, root: root, limits: limits), documents: documents.mapValues { .object($0.fields) }, budget: parsed.admission.parser) } catch let issue as NativeComponentFieldIssue { - var document = parsed - var keys = issue.field - if let field = issue.field.first { - let sources = - field == "mcpServers" - ? mcpSources : field == "lspServers" ? lspSources : field == "hooks" ? hookSources : [] - let external = sources.filter { $0.1.input.document != input.document } - // The helper does not return a document coordinate. Only a single original - // source can be located uniquely; multiple inputs retain their manifest location. - let declaredPaths = - parsed.fields[field]?.importStrings - ?? parsed.fields[field]?.importString.map { [$0] } - if Set(external.map { $0.1.input.document }).count == 1, let source = external.first, - parsed.fields[field] == nil - || (declaredPaths?.count == 1 - && documents[(try? ImportInput.path(declaredPaths![0])) ?? ""]?.input.document - == source.1.input.document) - { - document = source.1 - keys = source.2 + Array(issue.field.dropFirst().filter { $0 != "default" }) - } + let document: NativeImportDocument + if issue.document == suffix { + document = parsed + } else { + guard let captured = documents[issue.document] else { throw ImportReadFailure.invalid } + document = captured } - NativeImportSemantics.report(issue, at: document.fieldLocation(keys), into: &diagnostics) + NativeImportSemantics.report( + issue, at: document.fieldLocation(issue.field), into: &diagnostics) } } for field in metadata { diff --git a/Sources/Components/Import/NativeExecutableMembers.swift b/Sources/Components/Import/NativeExecutableMembers.swift index 0eddc0e..a35fba0 100644 --- a/Sources/Components/Import/NativeExecutableMembers.swift +++ b/Sources/Components/Import/NativeExecutableMembers.swift @@ -136,14 +136,13 @@ extension NativeSourceImport { } do { _ = try NativeComponentFieldsV1.lsp( - surface: NativeImportSemantics.surface(parsed.input.profile), fields: fields, + surface: NativeImportSemantics.surface(parsed.input.profile), + document: parsed.input.document, fieldPrefix: keys + [name], fields: fields, budget: parsed.admission.parser) } catch let issue as NativeComponentFieldIssue { - let path = issue.field.enumerated().map { index, key in - index == 0 && Int(key) != nil ? fields.keys.sorted()[Int(key)!] : key - } + guard issue.document == parsed.input.document else { throw ImportReadFailure.invalid } NativeImportSemantics.report( - issue, at: parsed.fieldLocation(keys + [name] + path), into: &diagnostics) + issue, at: parsed.fieldLocation(issue.field), into: &diagnostics) continue } var executable: String diff --git a/Sources/Components/Import/NativeMemberImport.swift b/Sources/Components/Import/NativeMemberImport.swift index f00b785..b3bf5ba 100644 --- a/Sources/Components/Import/NativeMemberImport.swift +++ b/Sources/Components/Import/NativeMemberImport.swift @@ -75,20 +75,24 @@ enum NativeMemberImport { do { fields = try NativeComponentFieldsV1.markdown( surface: NativeImportSemantics.surface(input.profile), - kind: isAgent ? .subagent : .command, name: fallback, fields: fields, + document: input.document, fieldPrefix: [], kind: isAgent ? .subagent : .command, + name: fallback, fields: fields, inPlugin: inPlugin, budget: admission.parser) } catch let issue as NativeComponentFieldIssue { - let location = - parsed.header.flatMap { header in - issue.field.first.flatMap { field in - Int(field).flatMap { - header.pairs?.indices.contains($0) == true - ? header.pairs?.sorted { $0.0 < $1.0 }[$0].1 : nil - } - ?? header[field] - } - }?.location ?? origin - NativeImportSemantics.report(issue, at: location, into: &diagnostics) + guard issue.document == input.document else { throw ImportReadFailure.invalid } + var value = parsed.header + for field in issue.field { + guard let node = value else { break } + if let child = node[field] { + value = child + } else if let index = Int(field), let items = node.items, items.indices.contains(index) + { + value = items[index] + } else { + break + } + } + NativeImportSemantics.report(issue, at: value?.location ?? origin, into: &diagnostics) return } } else { diff --git a/Tests/ComponentsTests/ImportNativeTests.swift b/Tests/ComponentsTests/ImportNativeTests.swift index 5b760b8..07d2b2c 100644 --- a/Tests/ComponentsTests/ImportNativeTests.swift +++ b/Tests/ComponentsTests/ImportNativeTests.swift @@ -590,7 +590,15 @@ struct ImportNativeTests { #expect( invalid.diagnostics.contains { $0.code == .invalidInput && $0.location.document == "bundle/.lsp.json" - && $0.location.span != nil + && $0.location.pointer == "/member[0]/member[2]" && $0.location.span != nil + }) + try fixture.write("opencode.json", #"{"lsp":{"source":{"command":17}}}"#) + let wrapped = try SourceImport.preview(fixture.input(.openCodeConfigV2, "opencode.json")) + #expect(wrapped.components.isEmpty) + #expect( + wrapped.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == "opencode.json" + && $0.location.pointer == "/member[0]/member[0]/member[0]" }) } @@ -646,28 +654,32 @@ struct ImportNativeTests { }) } - @Test func multiplePluginConfigurationInputsDoNotInventAnErrorDocument() throws { + @Test(arguments: [false, true]) + func multiplePluginConfigurationInputsKeepExactFailureDocument(_ firstInvalid: Bool) throws { let fixture = try NativeImportFixture() try fixture.write( "bundle/.claude-plugin/plugin.json", #"{"name":"bundle","mcpServers":["./first.json","./second.json"]}"#) - try fixture.write("bundle/first.json", #"{"mcpServers":{"same":{"command":"tool"}}}"#) - try fixture.write("bundle/second.json", #"{"mcpServers":{"same":{"command":17}}}"#) + let invalid = "{\n \"mcpServers\": {\n \"same\": {\n \"command\": 17\n }\n }\n}" + let valid = #"{"mcpServers":{"same":{"command":"tool"}}}"# + try fixture.write("bundle/first.json", firstInvalid ? invalid : valid) + try fixture.write("bundle/second.json", firstInvalid ? valid : invalid) + let before = try fixture.hash() let result = try SourceImport.preview( fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) - #expect(result.components.isEmpty) + #expect(result.components.count == (firstInvalid ? 1 : 0)) + let invalidDocument = firstInvalid ? "bundle/first.json" : "bundle/second.json" #expect( result.diagnostics.contains { - $0.code == .invalidInput && $0.location.document == "bundle/second.json" + $0.code == .invalidInput && $0.location.document == invalidDocument + && $0.location.pointer == "/member[0]/member[0]/member[0]" + && $0.location.span?.line == 4 }) #expect( !result.diagnostics.contains { - $0.code == .invalidInput && $0.location.document == "bundle/first.json" - }) - #expect( - result.diagnostics.contains { - $0.code == .invalidInput && $0.location.document == "bundle/.claude-plugin/plugin.json" + $0.code == .invalidInput && $0.location.document != invalidDocument }) + #expect(try fixture.hash() == before) } @Test func overlappingPreservationResourcesUseCompleteBindingClassification() throws { From 3b0ef9ec4774d4a90df143877988e680b225833a Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:58:55 +0800 Subject: [PATCH 109/171] feat: persist native region authority --- .../AgentsCore/LedgerNativeAuthority.swift | 171 +++++++++++ Sources/AgentsCore/LedgerValidation.swift | 98 ++++++ Sources/AgentsCore/ResolvedLedger.swift | 2 + Sources/AgentsCore/ResolvedLedgerCodec.swift | 30 ++ .../LedgerAuthorityTests.swift | 285 ++++++++++++++++++ 5 files changed, 586 insertions(+) create mode 100644 Sources/AgentsCore/LedgerNativeAuthority.swift create mode 100644 Tests/AgentsCoreTests/LedgerAuthorityTests.swift diff --git a/Sources/AgentsCore/LedgerNativeAuthority.swift b/Sources/AgentsCore/LedgerNativeAuthority.swift new file mode 100644 index 0000000..6db7361 --- /dev/null +++ b/Sources/AgentsCore/LedgerNativeAuthority.swift @@ -0,0 +1,171 @@ +import Foundation + +/// Evidence for one admitted native document. Physical admission and continuity belong to D/E/F. +package struct LedgerNativeAuthority: Codable, Equatable, Sendable { + package var version: Int = 1 + package var target: LedgerLocation + package var targetRoute: String + /// Closed dialects: json, jsonc, jsonc-trailing-commas, toml. JSONC alone forbids trailing commas. + package var documentFormat: String + package var regions: [LedgerNativeOwnedRegion] + package var createdContainers: [LedgerNativeCreatedContainer] + + package init( + target: LedgerLocation, targetRoute: String, documentFormat: String, + regions: [LedgerNativeOwnedRegion], createdContainers: [LedgerNativeCreatedContainer] = [] + ) { + self.target = target + self.targetRoute = targetRoute + self.documentFormat = documentFormat + self.regions = regions + self.createdContainers = createdContainers + } + + package static func == (a: Self, b: Self) -> Bool { + a.version == b.version && a.target.kind == b.target.kind + && a.target.root.map { Data($0.utf8) } == b.target.root.map { Data($0.utf8) } + && Data(a.target.path.utf8) == Data(b.target.path.utf8) + && Data(a.targetRoute.utf8) == Data(b.targetRoute.utf8) + && Data(a.documentFormat.utf8) == Data(b.documentFormat.utf8) + && a.regions == b.regions && a.createdContainers == b.createdContainers + } +} + +package struct LedgerNativeOwnedRegion: Codable, Equatable, Sendable { + package var deployments: [String] + package var path: [LedgerNativePathStep] + package init(deployments: [String], path: [LedgerNativePathStep]) { + self.deployments = deployments + self.path = path + } + package static func == (a: Self, b: Self) -> Bool { + a.deployments.map { Data($0.utf8) } == b.deployments.map { Data($0.utf8) } + && a.path == b.path + } +} + +package struct LedgerNativeCreatedContainer: Codable, Equatable, Sendable { + package var deployments: [String] + package var path: [LedgerNativePathStep] + package var kind: String + package init(deployments: [String], path: [LedgerNativePathStep], kind: String) { + self.deployments = deployments + self.path = path + self.kind = kind + } + package static func == (a: Self, b: Self) -> Bool { + a.deployments.map { Data($0.utf8) } == b.deployments.map { Data($0.utf8) } + && a.path == b.path && Data(a.kind.utf8) == Data(b.kind.utf8) + } +} + +/// Decoded native strings retain UTF-8 identity; these are not filesystem paths. +package enum LedgerNativePathStep: Codable, Equatable, Sendable { + case key(String) + case stableID(key: String, value: String) + case position(index: Int, evidence: LedgerNativeArrayEvidence) + + private enum CodingKeys: String, CodingKey { case kind, key, value, index, evidence } + private enum Kind: String, Codable { case key, stableID, position } + + package init(from decoder: any Decoder) throws { + let fields = try decoder.container(keyedBy: CodingKeys.self) + let kind = try fields.decode(Kind.self, forKey: .kind) + let allowed: Set + switch kind { + case .key: + allowed = [.kind, .key] + self = .key(try fields.decode(String.self, forKey: .key)) + case .stableID: + allowed = [.kind, .key, .value] + self = .stableID( + key: try fields.decode(String.self, forKey: .key), + value: try fields.decode(String.self, forKey: .value)) + case .position: + allowed = [.kind, .index, .evidence] + self = .position( + index: try fields.decode(Int.self, forKey: .index), + evidence: try fields.decode(LedgerNativeArrayEvidence.self, forKey: .evidence)) + } + guard Set(fields.allKeys).isSubset(of: allowed) else { + throw CoreError.invalidState("invalid native path fields") + } + } + + package func encode(to encoder: any Encoder) throws { + var fields = encoder.container(keyedBy: CodingKeys.self) + switch self { + case .key(let key): + try fields.encode(Kind.key, forKey: .kind) + try fields.encode(key, forKey: .key) + case .stableID(let key, let value): + try fields.encode(Kind.stableID, forKey: .kind) + try fields.encode(key, forKey: .key) + try fields.encode(value, forKey: .value) + case .position(let index, let evidence): + try fields.encode(Kind.position, forKey: .kind) + try fields.encode(index, forKey: .index) + try fields.encode(evidence, forKey: .evidence) + } + } + + package static func == (a: Self, b: Self) -> Bool { + switch (a, b) { + case (.key(let x), .key(let y)): x.utf8.elementsEqual(y.utf8) + case (.stableID(let x, let y), .stableID(let u, let v)): + x.utf8.elementsEqual(u.utf8) && y.utf8.elementsEqual(v.utf8) + case (.position(let x, let y), .position(let u, let v)): x == u && y == v + default: false + } + } +} + +/// Semantic digests are non-secret. Private tokens contain no array values or secret digests. +package enum LedgerNativeArrayEvidence: Codable, Equatable, Sendable { + case semantic(format: String, digest: String) + case privateArray(token: UUID) + + private enum CodingKeys: String, CodingKey { case kind, format, digest, token } + private enum Kind: String, Codable { case semantic, privateArray } + + package init(from decoder: any Decoder) throws { + let fields = try decoder.container(keyedBy: CodingKeys.self) + let kind = try fields.decode(Kind.self, forKey: .kind) + let allowed: Set + switch kind { + case .semantic: + allowed = [.kind, .format, .digest] + self = .semantic( + format: try fields.decode(String.self, forKey: .format), + digest: try fields.decode(String.self, forKey: .digest)) + case .privateArray: + allowed = [.kind, .token] + self = .privateArray(token: try fields.decode(UUID.self, forKey: .token)) + } + guard Set(fields.allKeys).isSubset(of: allowed) else { + throw CoreError.invalidState("invalid native array evidence fields") + } + } + + package func encode(to encoder: any Encoder) throws { + var fields = encoder.container(keyedBy: CodingKeys.self) + switch self { + case .semantic(let format, let digest): + try fields.encode(Kind.semantic, forKey: .kind) + try fields.encode(format, forKey: .format) + try fields.encode(digest, forKey: .digest) + case .privateArray(let token): + try fields.encode(Kind.privateArray, forKey: .kind) + try fields.encode(token, forKey: .token) + } + } + + package static func == (a: Self, b: Self) -> Bool { + switch (a, b) { + case (.semantic(let x, let y), .semantic(let u, let v)): + x.utf8.elementsEqual(u.utf8) && y.utf8.elementsEqual(v.utf8) + case (.privateArray(let x), .privateArray(let y)): x == y + default: false + } + } +} diff --git a/Sources/AgentsCore/LedgerValidation.swift b/Sources/AgentsCore/LedgerValidation.swift index a71de12..924617a 100644 --- a/Sources/AgentsCore/LedgerValidation.swift +++ b/Sources/AgentsCore/LedgerValidation.swift @@ -211,6 +211,7 @@ extension ResolvedLedger { throw CoreError.invalidState("invalid deployment ownership") } } + try validateNativeAuthorities() guard Set(lowerings.map(\.id)).count == lowerings.count else { throw CoreError.invalidState("duplicate lowering") } @@ -310,6 +311,96 @@ extension ResolvedLedger { } } + private func validateNativeAuthorities() throws { + let deployments = Dictionary(uniqueKeysWithValues: deployments.map { (Data($0.id.utf8), $0) }) + var targets = Set() + for authority in nativeAuthorities ?? [] { + try authority.target.validate() + guard authority.version == 1, NativeTargetRoute(rawValue: authority.targetRoute) != nil, + ["json", "jsonc", "jsonc-trailing-commas", "toml"].contains(authority.documentFormat), + authority.target.kind != .authoringRelative, !authority.regions.isEmpty, + try targets.insert(ResolvedLedgerCodec.bytes(authority.target)).inserted + else { throw CoreError.invalidState("invalid native authority target") } + + func owners(_ ids: [String]) throws -> Set { + let exact = ids.map { Data($0.utf8) } + guard !ids.isEmpty, Set(exact).count == ids.count, + exact.allSatisfy({ id in + guard let deployment = deployments[id] else { return false } + return deployment.ownership == .ownedValues + && deployment.target.kind == authority.target.kind + && deployment.target.root.map { Data($0.utf8) } + == authority.target.root.map { Data($0.utf8) } + && Data(deployment.target.path.utf8) == Data(authority.target.path.utf8) + }) + else { throw CoreError.invalidState("invalid native authority ownership") } + return Set(exact) + } + + var arrays: [[NativeAddressStep]: LedgerNativeArrayEvidence] = [:] + var kinds: [[NativeAddressStep]: String] = [:] + func address(_ path: [LedgerNativePathStep]) throws -> [NativeAddressStep] { + var prefix: [NativeAddressStep] = [] + for step in path { + let kind: String + let next: NativeAddressStep + switch step { + case .key(let key): + kind = "object" + next = .key(Data(key.utf8)) + case .stableID(let key, let value): + kind = "array" + next = .stableID(Data(key.utf8), Data(value.utf8)) + case .position(let index, let evidence): + guard index >= 0 else { throw CoreError.invalidState("negative native ordinal") } + switch evidence { + case .semantic(let format, let digest): + guard format == "native-array@1" else { + throw CoreError.invalidState("unsupported native array evidence") + } + try StateValidation.digest(digest) + case .privateArray: break + } + guard arrays[prefix] == nil || arrays[prefix] == evidence else { + throw CoreError.invalidState("conflicting native array evidence") + } + arrays[prefix] = evidence + kind = "array" + next = .position(index) + } + guard kinds[prefix] == nil || kinds[prefix] == kind else { + throw CoreError.invalidState("conflicting native container kind") + } + kinds[prefix] = kind + prefix.append(next) + } + return prefix + } + + var regions = Set<[NativeAddressStep]>() + var descendants: [[NativeAddressStep]: Set] = [:] + for region in authority.regions { + let owners = try owners(region.deployments) + let path = try address(region.path) + guard regions.insert(path).inserted else { + throw CoreError.invalidState("duplicate native region") + } + for count in 0..() + for container in authority.createdContainers { + let owners = try owners(container.deployments) + let path = try address(container.path) + guard !path.isEmpty, ["object", "array"].contains(container.kind), + kinds[path] == container.kind, containers.insert(path).inserted, + owners.isSubset(of: descendants[path] ?? []) + else { throw CoreError.invalidState("orphan or invalid native created container") } + } + } + } + private func requireSource(_ id: String) throws { guard sources[id] != nil else { throw CoreError.invalidState("dangling ledger source") } } @@ -327,3 +418,10 @@ extension ResolvedLedger { } } } + +/// Array evidence is checked separately so contradictory descriptions cannot create distinct slots. +private enum NativeAddressStep: Hashable { + case key(Data) + case stableID(Data, Data) + case position(Int) +} diff --git a/Sources/AgentsCore/ResolvedLedger.swift b/Sources/AgentsCore/ResolvedLedger.swift index 82d24d9..8e4ad6f 100644 --- a/Sources/AgentsCore/ResolvedLedger.swift +++ b/Sources/AgentsCore/ResolvedLedger.swift @@ -11,6 +11,8 @@ package struct ResolvedLedger: Codable, Equatable, Sendable { package var resources: [String: LedgerResource] = [:] package var deployments: [LedgerDeployment] = [] package var lowerings: [LockedLowering] = [] + /// Local regional evidence; nil grants no occurrence or container creation rights. + package var nativeAuthorities: [LedgerNativeAuthority]? /// Digest-keyed non-secret bytes. These are authoritative; materializations are disposable. package var contentObjects: [String: Data] = [:] package init() {} diff --git a/Sources/AgentsCore/ResolvedLedgerCodec.swift b/Sources/AgentsCore/ResolvedLedgerCodec.swift index da62e59..bc9ff6b 100644 --- a/Sources/AgentsCore/ResolvedLedgerCodec.swift +++ b/Sources/AgentsCore/ResolvedLedgerCodec.swift @@ -75,6 +75,28 @@ package enum ResolvedLedgerCodec { nodes += occurrence.pluginExpansion?.children.count ?? 0 guard nodes <= limits.nodes else { throw CoreError.invalidState("ledger relation budget") } } + for authority in ledger.nativeAuthorities ?? [] { + func charge(_ count: Int) throws { + guard count <= limits.nodes - nodes else { + throw CoreError.invalidState("ledger authority budget") + } + nodes += count + } + try charge(1) + for (deployments, path) in authority.regions.map({ ($0.deployments, $0.path) }) + + authority.createdContainers.map({ ($0.deployments, $0.path) }) + { + guard path.count < limits.depth else { + throw CoreError.invalidState("ledger native path depth budget") + } + try charge(1) + try charge(deployments.count) + try charge(path.count) + for step in path { + if case .position = step { try charge(1) } + } + } + } while let (value, depth) = pending.popLast() { nodes += 1 guard depth < limits.depth / 2, nodes <= limits.nodes else { @@ -102,11 +124,13 @@ package enum ResolvedLedgerCodec { case ledger, source, location, sourceUse, component, condition, occurrence, group case resource, entry, deployment, lowering, value, artifact, requirement, scalar case pluginMember, input, pluginExpansion + case nativeAuthority, nativeRegion, nativeContainer, nativeStep, nativeEvidence case map(WireShape) case list(WireShape) var nullable: Set { switch self { + case .ledger: ["nativeAuthorities"] case .source: ["transport", "location", "version", "container", "namespace"] case .location: ["root"] case .sourceUse: ["requirement"] @@ -127,6 +151,12 @@ package enum ResolvedLedgerCodec { func member(_ key: String) -> Self { switch (self, key) { + case (.ledger, "nativeAuthorities"): .list(.nativeAuthority) + case (.nativeAuthority, "target"): .location + case (.nativeAuthority, "regions"): .list(.nativeRegion) + case (.nativeAuthority, "createdContainers"): .list(.nativeContainer) + case (.nativeRegion, "path"), (.nativeContainer, "path"): .list(.nativeStep) + case (.nativeStep, "evidence"): .nativeEvidence case (.ledger, "sources"): .map(.source) case (.ledger, "sourceUses"): .list(.sourceUse) case (.ledger, "components"): .map(.component) diff --git a/Tests/AgentsCoreTests/LedgerAuthorityTests.swift b/Tests/AgentsCoreTests/LedgerAuthorityTests.swift new file mode 100644 index 0000000..cab4064 --- /dev/null +++ b/Tests/AgentsCoreTests/LedgerAuthorityTests.swift @@ -0,0 +1,285 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Ledger native authority") +struct LedgerAuthorityTests { + private let hash = "sha256:" + String(repeating: "a", count: 64) + private var semantic: LedgerNativeArrayEvidence { + .semantic(format: "native-array@1", digest: hash) + } + + private func fixture() -> ResolvedLedger { + var ledger = ResolvedLedger() + ledger.sources["root"] = .init(kind: .local, revision: "live") + ledger.components["hook"] = .init( + declaringSource: "root", source: "root", root: ".", kind: "hook", name: "hook", + payload: .init(), conditions: [], recipients: [.claudeCode], chatGPT: false, resources: []) + let target = LedgerLocation(kind: .registered, root: "native-claude-project", path: ".mcp.json") + ledger.deployments = [ + .init( + id: "deployment", target: target, route: "test/native@1", owners: ["hook"], + recipients: [.claudeCode], ownership: .ownedValues, expectedHash: hash, created: false) + ] + ledger.lowerings = [ + .init( + id: "lowering", format: "test/native@1", inputs: ["hook"], resources: [], + deployments: ["deployment"], layout: .init(), platform: "macos", artifacts: []) + ] + ledger.nativeAuthorities = [ + .init( + target: target, targetRoute: "claude.mcp.project", documentFormat: "json", + regions: [ + .init( + deployments: ["deployment"], + path: [.key("hooks"), .position(index: 1, evidence: semantic)]) + ], + createdContainers: [ + .init(deployments: ["deployment"], path: [.key("hooks")], kind: "array") + ]) + ] + return ledger + } + + private func encoded(_ ledger: ResolvedLedger) throws -> Data { + try ResolvedLedgerCodec.encode(ledger, limits: .standard) + } + + @Test func publicAndPrivateEvidenceRoundTripWithoutRewriting() throws { + for evidence in [semantic, .privateArray(token: UUID())] { + var ledger = fixture() + ledger.nativeAuthorities![0].regions[0].path[1] = .position(index: 1, evidence: evidence) + let bytes = try encoded(ledger) + let pretty = try JSONSerialization.data( + withJSONObject: JSONSerialization.jsonObject(with: bytes), options: [.prettyPrinted]) + #expect(try ResolvedLedgerCodec.decode(pretty, limits: .standard) == ledger) + #expect( + try ResolvedLedgerCodec.replacement(ledger, existing: pretty, limits: .standard) == nil) + #expect(ledger.deployments[0].created == false) + } + var old = fixture() + old.nativeAuthorities = nil + let oldBytes = try encoded(old) + var wire = try #require(JSONSerialization.jsonObject(with: oldBytes) as? [String: Any]) + #expect(wire["nativeAuthorities"] == nil) + wire["nativeAuthorities"] = NSNull() + let nullable = try JSONSerialization.data(withJSONObject: wire) + #expect(try ResolvedLedgerCodec.decode(nullable, limits: .standard) == old) + #expect(try ResolvedLedgerCodec.replacement(old, existing: nullable, limits: .standard) == nil) + } + + @Test func strictTaggedWireRejectsUnknownAndWrongFields() throws { + let bytes = try encoded(fixture()) + let root = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + let authority = try #require((root["nativeAuthorities"] as? [[String: Any]])?.first) + let region = try #require((authority["regions"] as? [[String: Any]])?.first) + let path = try #require(region["path"] as? [[String: Any]]) + let evidence = try #require(path[1]["evidence"] as? [String: Any]) + for level in 0..<6 { + var changed = root + var a = authority + var r = region + var p = path + var e = evidence + switch level { + case 0: a["unknown"] = NSNull() + case 1: r["unknown"] = NSNull() + case 2: p[0]["index"] = NSNull() + case 3: p[1]["unknown"] = NSNull() + case 4: e["token"] = NSNull() + default: + var containers = try #require(a["createdContainers"] as? [[String: Any]]) + containers[0]["unknown"] = NSNull() + a["createdContainers"] = containers + } + p[1]["evidence"] = e + r["path"] = p + a["regions"] = [r] + changed["nativeAuthorities"] = [a] + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode( + JSONSerialization.data(withJSONObject: changed), limits: .standard) + } + } + for invalid in [ + ["kind": "unknown"], ["kind": "key", "value": "x"], + [ + "kind": "position", "index": 0, + "evidence": ["kind": "privateArray", "token": "not-a-uuid"], + ], + ["kind": "position", "index": 0, "evidence": ["kind": "unknown"]], + ] as [[String: Any]] { + var changed = root + var a = authority + var r = region + r["path"] = [invalid] + a["regions"] = [r] + changed["nativeAuthorities"] = [a] + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode( + JSONSerialization.data(withJSONObject: changed), limits: .standard) + } + } + } + + @Test func ownershipAndCreationRequireSurvivingDescendants() throws { + let original = fixture() + var valid = original + valid.deployments.append(original.deployments[0]) + valid.deployments[1].id = "second" + valid.lowerings[0].deployments.append("second") + valid.nativeAuthorities![0].regions[0].deployments.append("second") + valid.nativeAuthorities![0].createdContainers[0].deployments.append("second") + _ = try encoded(valid) + for failure in 0..<12 { + var ledger = original + switch failure { + case 0: ledger.nativeAuthorities![0].regions[0].deployments = [] + case 1: ledger.nativeAuthorities![0].regions[0].deployments = ["missing"] + case 2: ledger.nativeAuthorities![0].regions[0].deployments.append("deployment") + case 3: ledger.deployments[0].target.path = "other.json" + case 4: ledger.deployments[0].ownership = .generated + case 5: ledger.nativeAuthorities![0].createdContainers[0].path = [] + case 6: ledger.nativeAuthorities![0].createdContainers[0].path = [.key("other")] + case 7: ledger.nativeAuthorities![0].createdContainers[0].kind = "object" + case 8: ledger.nativeAuthorities![0].regions = [] + case 9: ledger.nativeAuthorities![0].createdContainers[0].deployments = [] + case 10: + ledger = valid + ledger.nativeAuthorities![0].regions[0].deployments = ["deployment"] + default: + ledger.nativeAuthorities![0].createdContainers[0].path = + ledger.nativeAuthorities![0].regions[0].path + } + #expect(throws: (any Error).self) { _ = try encoded(ledger) } + } + } + + @Test func closedVersionsFormatsAndOrdinalEvidence() throws { + for failure in 0..<7 { + var ledger = fixture() + switch failure { + case 0: ledger.nativeAuthorities![0].version = 2 + case 1: ledger.nativeAuthorities![0].targetRoute = "arbitrary.route" + case 2: ledger.nativeAuthorities![0].documentFormat = "yaml" + case 3: + ledger.nativeAuthorities![0].regions[0].path[1] = .position(index: -1, evidence: semantic) + case 4: + ledger.nativeAuthorities![0].regions[0].path[1] = .position( + index: 0, evidence: .semantic(format: "native-array@2", digest: hash)) + case 5: + ledger.nativeAuthorities![0].regions[0].path[1] = .position( + index: 0, evidence: .semantic(format: "native-array@1", digest: "bad")) + default: + ledger.nativeAuthorities![0].target = .init( + kind: .authoringRelative, root: "project", path: "x") + } + #expect(throws: (any Error).self) { _ = try encoded(ledger) } + } + for format in ["json", "jsonc", "jsonc-trailing-commas", "toml"] { + var ledger = fixture() + ledger.nativeAuthorities![0].documentFormat = format + _ = try encoded(ledger) + } + } + + @Test func duplicateLocationsAndContradictoryArrayPreimagesFail() throws { + for failure in 0..<5 { + var ledger = fixture() + switch failure { + case 0: ledger.nativeAuthorities!.append(ledger.nativeAuthorities![0]) + case 1: ledger.nativeAuthorities![0].regions.append(ledger.nativeAuthorities![0].regions[0]) + case 2: + ledger.nativeAuthorities![0].createdContainers.append( + ledger.nativeAuthorities![0].createdContainers[0]) + case 3: + ledger.nativeAuthorities![0].regions.append( + .init( + deployments: ["deployment"], + path: [.key("hooks"), .position(index: 0, evidence: .privateArray(token: UUID()))])) + default: + ledger.nativeAuthorities![0].regions.append( + .init( + deployments: ["deployment"], path: [.key("hooks"), .key("not-an-array")])) + } + #expect(throws: (any Error).self) { _ = try encoded(ledger) } + } + var distinct = fixture() + distinct.nativeAuthorities![0].regions.append( + .init( + deployments: ["deployment"], path: [.key("hooks"), .position(index: 0, evidence: semantic)]) + ) + _ = try encoded(distinct) + } + + @Test func nativeStringsAreByteExactAcrossKeysAndStableIDs() throws { + let composed = "é" + let decomposed = "e\u{301}" + #expect(composed == decomposed) + var ledger = fixture() + ledger.nativeAuthorities![0].createdContainers = [] + ledger.nativeAuthorities![0].regions = [composed, decomposed].flatMap { value in + [ + .init(deployments: ["deployment"], path: [.key(value)]), + .init( + deployments: ["deployment"], path: [.key("items"), .stableID(key: "id", value: value)]), + ] as [LedgerNativeOwnedRegion] + } + let encoded = try encoded(ledger) + #expect(try ResolvedLedgerCodec.decode(encoded, limits: .standard) == ledger) + var changed = ledger + changed.nativeAuthorities![0].regions[0].path = [.key(decomposed)] + #expect(changed != ledger) + #expect( + LedgerNativePathStep.stableID(key: composed, value: "x") + != .stableID(key: decomposed, value: "x")) + var mismatch = fixture() + mismatch.deployments[0].id = composed + mismatch.lowerings[0].deployments = [composed] + mismatch.nativeAuthorities![0].regions[0].deployments = [composed] + mismatch.nativeAuthorities![0].createdContainers[0].deployments = [composed] + _ = try self.encoded(mismatch) + mismatch.nativeAuthorities![0].regions[0].deployments = [decomposed] + #expect(throws: (any Error).self) { _ = try self.encoded(mismatch) } + var target = fixture() + target.deployments[0].target.path = composed + target.nativeAuthorities![0].target.path = composed + _ = try self.encoded(target) + target.nativeAuthorities![0].target.path = decomposed + #expect(throws: (any Error).self) { _ = try self.encoded(target) } + } + + @Test func authoritySharesAggregateModelAndWireBudgets() throws { + var ledger = fixture() + ledger.nativeAuthorities![0].createdContainers = [] + // Exercise the codec boundary with a budget measured from the actual encoded object graph. + func nodes(_ value: Any) -> Int { + if let object = value as? [String: Any] { + return 1 + object.values.reduce(0) { $0 + nodes($1) } + } + if let array = value as? [Any] { return 1 + array.reduce(0) { $0 + nodes($1) } } + return 1 + } + let bytes = try encoded(ledger) + let count = nodes(try JSONSerialization.jsonObject(with: bytes)) + var limits = LedgerLimits.standard + limits.nodes = count + limits.encodedBytes = bytes.count + #expect(try ResolvedLedgerCodec.decode(bytes, limits: limits) == ledger) + limits.nodes -= 1 + #expect(throws: (any Error).self) { _ = try ResolvedLedgerCodec.encode(ledger, limits: limits) } + limits = .standard + limits.nodes = 16 + ledger.nativeAuthorities![0].regions = (0..<20).map { + .init(deployments: ["deployment"], path: [.key("key-\($0)")]) + } + #expect(throws: (any Error).self) { try ResolvedLedgerCodec.checkModel(ledger, limits: limits) } + limits = .standard + limits.depth = 8 + ledger.nativeAuthorities![0].regions = [ + .init(deployments: ["deployment"], path: (0..<8).map { .key("\($0)") }) + ] + #expect(throws: (any Error).self) { try ResolvedLedgerCodec.checkModel(ledger, limits: limits) } + } +} From 132d52e9c89da5e8ad4e8c7c24d66fd0af2ce28d Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:58:55 +0800 Subject: [PATCH 110/171] feat: compose private native containers --- Sources/AgentsUpdates/UpdateModels.swift | 10 + Sources/AgentsUpdates/UpdatePlan.swift | 7 +- Sources/Components/ArtifactAggregation.swift | 287 +++++++++++--- .../FirstUserDeclarationTests.swift | 66 ++++ .../PrivateNativeCompositionTests.swift | 363 ++++++++++++++++++ 5 files changed, 682 insertions(+), 51 deletions(-) create mode 100644 Tests/AgentsUpdatesTests/FirstUserDeclarationTests.swift create mode 100644 Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift diff --git a/Sources/AgentsUpdates/UpdateModels.swift b/Sources/AgentsUpdates/UpdateModels.swift index d4496c1..fa4f4bb 100644 --- a/Sources/AgentsUpdates/UpdateModels.swift +++ b/Sources/AgentsUpdates/UpdateModels.swift @@ -76,4 +76,14 @@ public struct ComponentPermissionChange: Codable, Sendable, Equatable { public let afterOwner: UInt32 public let afterMode: UInt32 public let ownerOnly: Bool + public let members: [ComponentMemberPermissionChange] +} + +public struct ComponentMemberPermissionChange: Codable, Sendable, Equatable { + public let path: String + public let beforeOwner: UInt32 + public let beforeGroup: UInt32 + public let beforeMode: UInt32 + public let afterOwner: UInt32 + public let afterMode: UInt32 } diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 03ac97f..74d936e 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -383,7 +383,12 @@ final class UpdatePlan { ComponentPermissionChange( beforeOwner: access.before.owner, beforeGroup: access.before.group, beforeMode: UInt32(access.before.mode), afterOwner: access.owner, - afterMode: access.mode, ownerOnly: true) + afterMode: access.mode, ownerOnly: true, + members: change.memberAccessChanges.map { + ComponentMemberPermissionChange( + path: $0.path, beforeOwner: $0.before.owner, beforeGroup: $0.before.group, + beforeMode: UInt32($0.before.mode), afterOwner: $0.owner, afterMode: $0.mode) + }) }, symbolicBefore: try change.symbolicBefore.map { String(decoding: try ResolvedLedgerCodec.bytes($0), as: UTF8.self) diff --git a/Sources/Components/ArtifactAggregation.swift b/Sources/Components/ArtifactAggregation.swift index 917ab1a..5ca9991 100644 --- a/Sources/Components/ArtifactAggregation.swift +++ b/Sources/Components/ArtifactAggregation.swift @@ -15,6 +15,7 @@ package struct AggregatedChange { package var effectiveReaders: [AgentID] = [] package var privateMaterialization = false package var requiredBindings: [String] = [] + package var memberAccessChanges: [PrivateTreeAccessChange] = [] package var symbolicBefore: LedgerValue? = nil package var symbolicAfter: LedgerValue? = nil } @@ -39,6 +40,7 @@ package final class ArtifactAggregation: PreparedEvidence { private var skillContent: [String: (String, [String: Bool])] = [:] private var privateWrites: [(PreparedPrivateMaterialization, Set, (RuntimeBindingValues) throws -> Data)] = [] + private var privateTrees: [(PreparedPrivateMaterialization, [PrivateTreeEntry])] = [] private var resourceEvidence: [TargetPrecondition] = [] private var physicalPaths: [NativeTargetIdentity: String] = [:] @@ -153,12 +155,23 @@ package final class ArtifactAggregation: PreparedEvidence { }) { try prepareWholeNative( path: path, next: next, old: old, previous: previous, - artifacts: artifacts, workspace: workspace) + artifacts: artifacts, workspace: workspace, changingAccess: changingAccess) } else { for entry in next { + let privatePlan = + try store.materializationReceipt(for: entry.target) == nil + ? nil : store.preparePrivateMaterialization(entry.target) try record( entry, previous: previous, changed: false, - readers: entry.contribution.knownReaders, ownership: .generated) + readers: Array( + Set( + entry.contribution.knownReaders + + DeploymentConstruction.route( + entry.output, request: entry.contribution.request + ) + .knownReaders) + ).sorted { $0.rawValue < $1.rawValue }, + privatePlan: privatePlan, ownership: .generated) } } case .ignore: @@ -411,17 +424,8 @@ package final class ArtifactAggregation: PreparedEvidence { } private func location(_ target: MaterializationTarget) -> LedgerLocation { - for (key, root) in [ - ("project", store.environment.projectDirectory), ("home", store.environment.homeDirectory), - ] { - let root = root.resolvingSymlinksInPath().standardizedFileURL - if PathSafety.isContained(target.url, in: root) { - return .init( - kind: .registered, root: key, - path: String(target.url.path.dropFirst(root.path.count + 1))) - } - } - return .init(kind: .absolute, path: target.url.path) + let parts = target.path.split(separator: "/", maxSplits: 1) + return .init(kind: .registered, root: String(parts[0]), path: String(parts[1])) } private func record( @@ -455,6 +459,7 @@ package final class ArtifactAggregation: PreparedEvidence { changed: changed, native: true, accessChange: privatePlan?.accessChange, effectiveReaders: readers, privateMaterialization: privatePlan != nil, requiredBindings: bindings, + memberAccessChanges: privatePlan?.memberAccessChanges ?? [], symbolicBefore: oldComponent?.payload, symbolicAfter: ledger.components[entry.contribution.component]?.payload)) } @@ -463,12 +468,36 @@ package final class ArtifactAggregation: PreparedEvidence { _ value: NativeComponentValue, values: RuntimeBindingValues?, selected: ResolvedLedger ) throws -> NativeValue { - guard let values else { return try value.referenceValue(budget: nativeBudget()) } + try Self.componentValue(value, values: values, selected: selected, store: store) + } + + private static func componentValue( + _ value: NativeComponentValue, values: RuntimeBindingValues?, + selected: ResolvedLedger, store: StateStore, symbolicVariant: Int = 0 + ) throws -> NativeValue { + var environment = store.environment + var symbolic: [String: Data] = [:] + if values == nil { + // Preview converts the typed program without reading runtime values. + for placement in value.bindings { + switch placement.binding { + case .secret(let name): + symbolic[name] = Data( + ("agents-symbolic-secret-" + String(symbolicVariant) + "-" + + FileHash.sha256Hex(data: Data(name.utf8))).utf8) + case .environment(let name): + environment.environment[name] = + "agents-symbolic-environment-" + String(symbolicVariant) + "-" + + FileHash.sha256Hex(data: Data(name.utf8)) + case .literal: break + } + } + } let paths = try selected.resources.keys.reduce(into: [String: String]()) { $0[$1] = try Self.resourceDestination($1, ledger: selected, store: store).path } return try value.stagedValue( - bindings: values, environment: store.environment, + bindings: values ?? RuntimeBindingValues(symbolic), environment: environment, resourcePaths: paths, budget: NativeDocumentBudget( limits: .init( @@ -478,9 +507,64 @@ package final class ArtifactAggregation: PreparedEvidence { codexCommandShell: .posix, cursorCommandShell: .posix) } + private static func generatedManifestMatches( + _ manifest: NativeComponentValue, observed: NativeValue?, selected: ResolvedLedger, + privateGeneration: Bool, store: StateStore + ) throws -> Bool { + guard let observed else { return false } + let first = try Self.componentValue(manifest, values: nil, selected: selected, store: store) + guard privateGeneration, !manifest.bindings.isEmpty else { return observed == first } + let second = try Self.componentValue( + manifest, values: nil, selected: selected, store: store, symbolicVariant: 1) + // F determines the native positions. Only leaves changed by its binding conversion vary. + func matches(_ actual: NativeValue, _ a: NativeValue, _ b: NativeValue) -> Bool { + if a == b { return actual == a } + switch (actual, a, b) { + case (.string, .string, .string): return true + case (.object(let actual), .object(let a), .object(let b)): + guard Set(actual.keys) == Set(a.keys), Set(a.keys) == Set(b.keys) else { return false } + return a.allSatisfy { matches(actual[$0.key]!, $0.value, b[$0.key]!) } + case (.array(let actual), .array(let a), .array(let b)): + guard actual.count == a.count, a.count == b.count else { return false } + return a.indices.allSatisfy { matches(actual[$0], a[$0], b[$0]) } + default: return false + } + } + return matches(observed, first, second) + } + + private func generatedManifestBytes( + _ manifest: NativeComponentValue, values: RuntimeBindingValues? + ) throws -> Data { + try Self.generatedManifestBytes(manifest, values: values, selected: ledger, store: store) + } + + private static func generatedManifestBytes( + _ manifest: NativeComponentValue, values: RuntimeBindingValues?, + selected: ResolvedLedger, store: StateStore + ) throws -> Data { + guard + case .object(let fields) = try componentValue( + manifest, values: values, selected: selected, store: store) + else { throw CoreError.invalidState("generated native manifest must be an object") } + let document = try NativeDocument( + bytes: Data("{}".utf8), format: .json, + budget: NativeDocumentBudget( + limits: .init( + storage: LedgerLimits.standard.resourceBytes, work: LedgerLimits.standard.encodedBytes, + nodes: LedgerLimits.standard.nodes, depth: LedgerLimits.standard.depth, + uninterruptedBytes: LedgerLimits.standard.keyBytes))) + return try document.prepare( + fields.keys.sorted().map { + .put(region: .init(keys: [$0]), expected: .absent, value: fields[$0]!) + } + ).bytes + } + private func prepareWholeNative( path: String, next: [ComponentOutputEntry], old: [ComponentOutputEntry], - previous: ResolvedLedger, artifacts: [String: ReplayedArtifact], workspace: URL + previous: ResolvedLedger, artifacts: [String: ReplayedArtifact], workspace: URL, + changingAccess: Bool ) throws { guard let target = (next.first ?? old.first)?.target else { return } let capture = try TargetPrecondition(target.url).capturingPublicationAccess() @@ -496,6 +580,49 @@ package final class ArtifactAggregation: PreparedEvidence { guard next.count <= 1, old.count <= 1 else { throw CoreError.invalidState("conflicting native whole-object owners") } + let hasBindings: Bool = next.contains { + if case .generatedLSPPlugin(_, _, let manifest) = $0.output.content { + return !manifest.bindings.isEmpty + } + return false + } + let hadBindings: Bool = old.contains { + if case .generatedLSPPlugin(_, _, let manifest) = $0.output.content { + return !manifest.bindings.isEmpty + } + return false + } + let receipt = try store.materializationReceipt(for: target) + let privatePlan = + try hasBindings || hadBindings || receipt != nil + ? store.preparePrivateMaterialization( + target, changingAccess: changingAccess, + requiringReceiptForExistingTarget: hadBindings) : nil + if let privatePlan { + struct MemberAccess: Encodable { + let path: String + let before: String + let afterOwner: UInt32 + let afterMode: UInt32 + } + fingerprints.append( + try ResolvedLedgerCodec.digest( + privatePlan.memberAccessChanges.map { + let file = try PathSafety.resolvedChild(base: target.url, subpath: $0.path) + return MemberAccess( + path: $0.path, + before: try TargetPrecondition(file).displayEvidence(includeContent: false), + afterOwner: $0.owner, afterMode: $0.mode) + })) + } + func bindingNames(_ entry: ComponentOutputEntry) -> Set { + guard case .generatedLSPPlugin(_, _, let manifest) = entry.output.content else { return [] } + return Set( + manifest.bindings.compactMap { + if case .secret(let name) = $0.binding { return name } + return nil + }) + } func source(_ entry: ComponentOutputEntry) throws -> FileTransaction.Source { switch entry.output.content { case .file(_, let bytes): return .data(bytes) @@ -505,23 +632,11 @@ package final class ArtifactAggregation: PreparedEvidence { else { throw CoreError.invalidState("missing frozen native container") } return .copy(tree) case .generatedLSPPlugin(_, let manifestPath, let manifest): - guard manifest.bindings.isEmpty else { - throw CoreError.invalidState( - "native private container materialization requires the Core tree construction interface" - ) - } let tree = workspace.appendingPathComponent( "native-tree-" + FileHash.sha256Hex(data: Data(entry.id.utf8))) let file = try PathSafety.resolvedChild(base: tree, subpath: manifestPath) try FileSystem.createDirectory(at: file.deletingLastPathComponent()) - let document = try NativeDocument( - bytes: Data("{}".utf8), format: .json, budget: nativeBudget()) - let observation = try document.read(.init(keys: []))! - let bytes = try document.prepare([ - .put( - region: .init(keys: []), expected: .owned(observation), - value: componentValue(manifest, values: nil, selected: ledger)) - ]).bytes + let bytes = try generatedManifestBytes(manifest, values: nil) try bytes.write(to: file) return .copy(tree) default: throw CoreError.invalidState("native whole-object content has a regional shape") @@ -530,7 +645,8 @@ package final class ArtifactAggregation: PreparedEvidence { let exists = FileManager.default.fileExists(atPath: path) if exists { guard let old = old.first, - let deployment = previous.deployments.first(where: { $0.id == old.id }) + let deployment = previous.deployments.first(where: { $0.id == old.id }), + deployment.ownership == .generated else { throw CoreError.invalidState("native target contains unmanaged content") } @@ -548,7 +664,7 @@ package final class ArtifactAggregation: PreparedEvidence { case .generatedLSPPlugin(_, let manifestPath, let manifest): let captured = try LedgerResources.capture(target.url, embed: false, limits: .standard) let expectedPaths = Set([ - manifestPath, (manifestPath as NSString).deletingLastPathComponent, + ".", manifestPath, (manifestPath as NSString).deletingLastPathComponent, ]) guard captured.entries.allSatisfy({ expectedPaths.contains($0.path) && !$0.executable }) else { @@ -558,9 +674,9 @@ package final class ArtifactAggregation: PreparedEvidence { bytes: Data(contentsOf: target.url.appendingPathComponent(manifestPath)), format: .json, budget: nativeBudget()) guard - try current.read(.init(keys: []))?.value - == componentValue(manifest, values: nil, selected: previous), - deployment.ownership == .generated + try Self.generatedManifestMatches( + manifest, observed: current.read(.init(keys: []))?.value, selected: previous, + privateGeneration: receipt != nil, store: store) else { throw CoreError.invalidState("owned generated native tree drifted") } default: throw CoreError.invalidState("invalid whole-object ownership") } @@ -574,9 +690,54 @@ package final class ArtifactAggregation: PreparedEvidence { changed = try !exists || FileHash.folderHash(target.url) != FileHash.folderHash(tree) default: throw CoreError.invalidState("invalid native whole-object source") } - if changed { writes[path] = desired } + if let privatePlan { + switch entry.output.content { + case .generatedLSPPlugin(_, let manifestPath, let manifest): + let parts = manifestPath.split(separator: "/") + var members: [PrivateTreeEntry] = [] + for count in 1.. Set { Set( bindings.compactMap { @@ -729,7 +892,7 @@ package final class ArtifactAggregation: PreparedEvidence { }) return .init( key: key, region: region, bindings: bindings, symbolic: c.value, - render: { try self.nativeValue(c, values: $0, ledger: selected) }) + render: { try Self.nativeValue(c, values: $0, ledger: selected, store: selectedStore) }) } func regional(_ entry: ComponentOutputEntry, selected: ResolvedLedger) throws -> [NativeRegionOwner] @@ -756,7 +919,9 @@ package final class ArtifactAggregation: PreparedEvidence { try region( member.keys, symbolic: selected.components[entry.contribution.component]!.payload, bindings: names(value.bindings), - render: { try self.componentValue(value, values: $0, selected: selected) }) + render: { + try Self.componentValue(value, values: $0, selected: selected, store: selectedStore) + }) ] case .claudePermissions(let policy): var values: [(String, NativeValue)] = [] @@ -788,8 +953,12 @@ package final class ArtifactAggregation: PreparedEvidence { func keyed(_ items: [NativeRegionOwner]) throws -> [String: NativeRegionOwner] { var result: [String: NativeRegionOwner] = [:] for item in items { - if let existing = result[item.key], try existing.render(nil) != item.render(nil) { - throw CoreError.invalidState("conflicting native physical region owners") + if let existing = result[item.key] { + guard + (existing.bindings.isEmpty && item.bindings.isEmpty) + || existing.symbolic == item.symbolic, + try existing.render(nil) == item.render(nil) + else { throw CoreError.invalidState("conflicting native physical region owners") } } result[item.key] = item } @@ -931,12 +1100,6 @@ package final class ArtifactAggregation: PreparedEvidence { depth: LedgerLimits.standard.depth, uninterruptedBytes: LedgerLimits.standard.keyBytes)) } - private func nativeValue( - _ contribution: NativeMCPContribution, values: RuntimeBindingValues?, ledger: ResolvedLedger - ) throws -> NativeValue { - try Self.nativeValue(contribution, values: values, ledger: ledger, store: store) - } - private static func nativeValue( _ contribution: NativeMCPContribution, values: RuntimeBindingValues?, ledger: ResolvedLedger, store: StateStore @@ -1041,6 +1204,9 @@ package final class ArtifactAggregation: PreparedEvidence { for path in deletes.sorted() { try transaction.delete(URL(fileURLWithPath: path), expecting: targets[path]) } + for (prepared, entries) in privateTrees { + try transaction.replacePrivateTree(prepared, entries: entries, provider: provider) + } for (prepared, bindings, render) in privateWrites { try transaction.replacePrivate( prepared, bindings: bindings, provider: provider, render: render) @@ -1196,7 +1362,13 @@ extension ArtifactAggregation { for: DeploymentConstruction.physicalRoute( DeploymentConstruction.route(output, request: contribution.request), ledger: ledger, store: store)) - if try store.materializationReceipt(for: target) != nil { return ("current", nil) } + let privateGeneration = try store.materializationReceipt(for: target) != nil + if privateGeneration { + switch output.content { + case .file, .nativePlugin, .generatedLSPPlugin: break + default: return ("current", nil) + } + } let budget = NativeDocumentBudget( limits: .init( storage: LedgerLimits.standard.resourceBytes, @@ -1211,7 +1383,7 @@ extension ArtifactAggregation { bytes: Data(contentsOf: url), format: output.route.documentFormat!, budget: budget) matches = try document.read(.init(keys: member.keys))?.value - == value.referenceValue(budget: budget) + == componentValue(value, values: nil, selected: ledger, store: store) case .claudePermissions(let policy): let document = try NativeDocument( bytes: Data(contentsOf: url), format: .json, budget: budget) @@ -1259,7 +1431,22 @@ extension ArtifactAggregation { text.components(separatedBy: opening).count == 2 && text.components(separatedBy: closing).count == 2 && text.contains(opening + patterns.joined(separator: "\n") + "\n" + closing) - case .generatedLSPPlugin, .hook, .orderedPermissions: + case .generatedLSPPlugin(_, let manifestPath, let manifest): + let captured = try LedgerResources.capture(url, embed: false, limits: .standard) + let paths = Set([ + ".", manifestPath, (manifestPath as NSString).deletingLastPathComponent, + ]) + let document = try NativeDocument( + bytes: Data(contentsOf: url.appendingPathComponent(manifestPath)), format: .json, + budget: budget) + matches = + try captured.entries.allSatisfy { + paths.contains($0.path) && !$0.executable + } + && generatedManifestMatches( + manifest, observed: document.read(.init(keys: []))?.value, selected: ledger, + privateGeneration: privateGeneration, store: store) + case .hook, .orderedPermissions: return ( "unverified", "native ownership observation requires the integrated regional evidence" ) diff --git a/Tests/AgentsUpdatesTests/FirstUserDeclarationTests.swift b/Tests/AgentsUpdatesTests/FirstUserDeclarationTests.swift new file mode 100644 index 0000000..a2813b7 --- /dev/null +++ b/Tests/AgentsUpdatesTests/FirstUserDeclarationTests.swift @@ -0,0 +1,66 @@ +import AgentsCore +import AgentsManifest +import AgentsUpdates +import Foundation +import Testing + +struct FirstUserDeclarationTests { + @Test func firstUserMCPDeclarationCanConfirmPurePreview() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent( + "first-user-declaration-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let environment = RuntimeEnvironment( + projectDirectory: root, homeDirectory: root, environment: [:]) + let store = StateStore(scope: .user, environment: environment) + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + try Data("version: 1\ndefaultAgents: [codex]\n".utf8).write(to: store.declarationURL) + var declaration = try store.loadDeclaration() + declaration.components.append( + .mcpServer( + name: "documentation", transport: .stdio(.init(executable: "fixture-command")))) + let request = UpdateRequest(operation: .declaration(declaration)) + let before = try FileHash.folderHash(root) + let preview = try UpdateOperations.preview(request, scope: .user, environment: environment) + #expect(try FileHash.folderHash(root) == before) + #expect( + try UpdateOperations.preview(request, scope: .user, environment: environment) + .displayedFingerprint == preview.displayedFingerprint) + _ = try UpdateOperations.withPreparedUpdate(request, scope: .user, environment: environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let current = try UpdateOperations.inspect(scope: .user, environment: environment) + #expect(current.components.count == 1) + #expect(current.components.first?.name == "documentation") + #expect(current.deployments.allSatisfy { $0.status == .current }) + let config = root.appendingPathComponent(".codex/config.toml") + #expect(try String(contentsOf: config, encoding: .utf8).contains("fixture-command")) + } + @Test func nativeAccessChangeInvalidatesDisplayedConfirmation() throws { + let f = try UpdateFixture(scope: .user) + try f.store.save( + declaration: Declaration(components: [ + .mcpServer( + name: "documentation", transport: .stdio(.init(executable: "fixture-command")), + agents: [.codex]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let before = try f.preview() + let config = f.environment.homeDirectory.appendingPathComponent(".codex/config.toml") + let parent = config.deletingLastPathComponent() + let mode = try #require( + try FileManager.default.attributesOfItem(atPath: parent.path)[.posixPermissions] as? NSNumber) + try FileManager.default.setAttributes( + [.posixPermissions: mode.intValue == 0o700 ? 0o755 : 0o700], ofItemAtPath: parent.path) + let after = try f.preview() + #expect(before.displayedFingerprint != after.displayedFingerprint) + let bytes = try Data(contentsOf: config) + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(scope: .user, environment: f.environment) { + try $0.apply(ifUnchangedFrom: before.displayedFingerprint) + } + } + #expect(try Data(contentsOf: config) == bytes) + } + +} diff --git a/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift b/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift new file mode 100644 index 0000000..f13cac8 --- /dev/null +++ b/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift @@ -0,0 +1,363 @@ +import AgentsCore +import AgentsUpdates +import Foundation +import Synchronization +import Testing + +private final class NativeBindings: RuntimeBindingProvider { + let calls = Mutex(0) + let secret = "private-tree-materialization-canary" + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + calls.withLock { $0 += 1 } + return Data(secret.utf8) + } +} + +private struct RefuseNativeBindings: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + throw CoreError.invalidState("an unselected binding must not be replayed") + } +} + +struct PrivateNativeCompositionTests { + @Test(arguments: [false, true]) + func generatedLSPContainerUsesProductionRenderingAndPrivatePublication(_ sensitive: Bool) throws { + let f = try UpdateFixture() + let provider = NativeBindings() + try f.store.save( + declaration: Declaration(components: [ + .lspServer( + name: "language", + run: .init( + executable: "fixture-language-server", + environment: sensitive ? ["TOKEN": .secret("token")] : [:]), + languages: [".swift": "swift"], agents: [.claudeCode]), + .command( + name: "review", description: "Review", prompt: .literal("Before"), agents: [.claudeCode]), + ]), ledger: ResolvedLedger()) + let inventory = try FileHash.folderHash(f.root) + let preview = try f.preview() + #expect(try FileHash.folderHash(f.root) == inventory) + #expect(provider.calls.withLock { $0 } == 0) + #expect( + !String(decoding: try JSONEncoder().encode(preview), as: UTF8.self).contains(provider.secret)) + _ = try UpdateOperations.withPreparedUpdate( + environment: f.environment, bindingProvider: provider + ) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + #expect(provider.calls.withLock { $0 } == (sensitive ? 1 : 0)) + let installed = try UpdateOperations.inspect(environment: f.environment) + #expect(installed.deployments.allSatisfy { $0.status == .current }) + let lsp = try #require(installed.components.first { $0.kind == .lspServer }) + let tree = try #require( + installed.deployments.first { $0.ownerRecords.contains(lsp.record) }?.location) + let manifest = tree.appendingPathComponent(".claude-plugin/plugin.json") + let bytes = try Data(contentsOf: manifest) + #expect(String(decoding: bytes, as: UTF8.self).contains("fixture-language-server")) + #expect(String(decoding: bytes, as: UTF8.self).contains(provider.secret) == sensitive) + #expect( + !String(decoding: try Data(contentsOf: f.store.resolvedURL), as: UTF8.self).contains( + provider.secret)) + if sensitive { + for url in [tree, manifest.deletingLastPathComponent(), manifest] { + let mode = + try FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions] as? NSNumber + #expect(mode?.intValue == (url == manifest ? 0o600 : 0o700)) + } + } + let committed = try f.snapshot() + let command = try #require( + installed.deployments.first { !$0.ownerRecords.contains(lsp.record) }?.location) + let oldCommand = try Data(contentsOf: command) + var failedDeclaration = try f.store.loadDeclaration() + failedDeclaration.components[0] = .lspServer( + name: "language", + run: .init( + executable: "fixture-language-server", arguments: ["new-generation"], + environment: sensitive ? ["TOKEN": .secret("token")] : [:]), + languages: [".swift": "swift"], agents: [.claudeCode]) + failedDeclaration.components[1] = .command( + name: "review", description: "Review", prompt: .literal("Interrupted"), agents: [.claudeCode]) + var interrupted = false + let failed = UpdateOperations.perform( + .init(operation: .declaration(failedDeclaration)), environment: f.environment, + bindingProvider: provider, + checkpoint: { _ in + if !interrupted, (try? Data(contentsOf: manifest)) != bytes { + interrupted = true + throw CoreError.invalidState("fixture interruption after container publication") + } + }, { try $0.apply() }) + #expect(interrupted && failed.disposition == .rolledBack && !failed.recovery.pending) + #expect(throws: (any Error).self) { try failed.result.get() } + #expect(try f.snapshot() == committed) + #expect(try Data(contentsOf: manifest) == bytes) + #expect(try Data(contentsOf: command) == oldCommand) + let callsBeforeEdit = provider.calls.withLock { $0 } + #expect(callsBeforeEdit == (sensitive ? 2 : 0)) + var declaration = try f.store.loadDeclaration() + declaration.components[1] = .command( + name: "review", description: "Review", prompt: .literal("After"), agents: [.claudeCode]) + let request = UpdateRequest(operation: .declaration(declaration), kinds: [.command]) + let edit = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate( + request, environment: f.environment, bindingProvider: RefuseNativeBindings() + ) { try $0.apply(ifUnchangedFrom: edit.displayedFingerprint) } + #expect(try Data(contentsOf: manifest) == bytes) + #expect(provider.calls.withLock { $0 } == callsBeforeEdit) + let cold = f.root.appendingPathComponent("cold-project") + var coldEnvironment = f.environment + coldEnvironment.projectDirectory = cold + let coldStore = StateStore(scope: .project, environment: coldEnvironment) + try FileManager.default.createDirectory( + at: coldStore.directory, withIntermediateDirectories: true) + let locked = try Data(contentsOf: f.store.resolvedURL) + try locked.write(to: coldStore.resolvedURL) + try Data("invalid: [".utf8).write(to: coldStore.declarationURL) + try FileManager.default.removeItem(at: tree) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .restore), environment: coldEnvironment, bindingProvider: provider + ) { try $0.apply() } + #expect(try Data(contentsOf: coldStore.resolvedURL) == locked) + try Data(contentsOf: f.store.declarationURL).write(to: coldStore.declarationURL) + let current = try UpdateOperations.inspect(environment: coldEnvironment) + let restoredRecord = try #require(current.components.first { $0.kind == .lspServer }) + let restored = try #require( + current.deployments.first { $0.ownerRecords.contains(restoredRecord.record) }?.location) + #expect(restored.path.hasPrefix(cold.path + "/")) + #expect( + try Data(contentsOf: restored.appendingPathComponent(".claude-plugin/plugin.json")) == bytes) + #expect(try Data(contentsOf: coldStore.resolvedURL) == locked) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [restoredRecord.selection]), + environment: coldEnvironment, + bindingProvider: RefuseNativeBindings() + ) { try $0.apply() } + #expect(!FileManager.default.fileExists(atPath: restored.path)) + } +} + +extension PrivateNativeCompositionTests { + @Test func opaqueFrozenTreeRetainsPrivateClassificationWithoutProviderReplay() throws { + let f = try UpdateFixture() + let source = f.root.appendingPathComponent("native-source") + let tree = source.appendingPathComponent("demo-plugin") + let manifest = Data("{\"name\":\"demo-plugin\",\"version\":\"1.0.0\"}".utf8) + let executable = Data("#!/bin/sh\n# Not executed.\n".utf8) + try f.write( + String(decoding: manifest, as: UTF8.self), + to: tree.appendingPathComponent(".claude-plugin/plugin.json")) + try f.write( + String(decoding: executable, as: UTF8.self), to: tree.appendingPathComponent("bin/check")) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: tree.appendingPathComponent("bin/check").path) + try FileManager.default.createSymbolicLink( + atPath: tree.appendingPathComponent("current").path, withDestinationPath: "bin/check") + try f.store.save( + declaration: Declaration( + sources: ["producer": .init(kind: .local, location: source.path)], + components: [ + .plugin( + name: "demo-plugin", path: "demo-plugin", source: "producer", mode: .native, + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let installed = try UpdateOperations.inspect(environment: f.environment) + let location = try #require(installed.deployments.first?.location) + // A real previously materialized private generation is the input to this E continuity case. + let route = try NativeTargetRoute.named( + .claudeSkillPlugin, scope: .project, name: "demo-plugin") + try f.store.withLock(footprint: [route]) { + let target = try f.store.nativeTarget(for: route) + let prepared = try f.store.preparePrivateMaterialization(target, changingAccess: true) + let transaction = FileTransaction(store: f.store) + try transaction.replacePrivateTree( + prepared, + entries: [ + .init(".claude-plugin", content: .directory), + .init(".claude-plugin/plugin.json", content: .file(manifest)), + .init("bin", content: .directory), + .init("bin/check", content: .file(executable, executable: true)), + .init("current", content: .symlink("bin/check")), + ], provider: RefuseNativeBindings()) + try transaction.commit() + } + let bytes = try FileHash.folderHash(location) + let report = try f.preview() + #expect(report.components.first?.privateMaterialization == true) + _ = try UpdateOperations.withPreparedUpdate( + environment: f.environment, bindingProvider: RefuseNativeBindings() + ) { try $0.apply(ifUnchangedFrom: report.displayedFingerprint) } + #expect(try FileHash.folderHash(location) == bytes) + let current = try UpdateOperations.inspect(environment: f.environment) + #expect(current.deployments.first?.privateMaterialization == true) + #expect(current.deployments.first?.status == .current) + let mode = + try FileManager.default.attributesOfItem( + atPath: location.appendingPathComponent("bin/check").path)[.posixPermissions] as? NSNumber + #expect(mode?.intValue == 0o700) + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: location.appendingPathComponent("current").path) == "bin/check") + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(current.components.first?.selection)]), + environment: f.environment, bindingProvider: RefuseNativeBindings() + ) { try $0.apply() } + #expect(!FileManager.default.fileExists(atPath: location.path)) + } +} + +extension PrivateNativeCompositionTests { + @Test func addingBindingToOwnedContainerReportsExplicitMemberAccessChanges() throws { + let f = try UpdateFixture() + var declaration = Declaration(components: [ + .lspServer( + name: "language", run: .init(executable: "fixture-server"), languages: [".swift": "swift"], + agents: [.claudeCode]) + ]) + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + let installed = try UpdateOperations.inspect(environment: f.environment) + let tree = try #require(installed.deployments.first?.location) + for directory in [tree, tree.appendingPathComponent(".claude-plugin")] { + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: directory.path) + } + declaration.components[0] = .lspServer( + name: "language", + run: .init(executable: "fixture-server", environment: ["TOKEN": .secret("token")]), + languages: [".swift": "swift"], agents: [.claudeCode]) + var request = UpdateRequest(operation: .declaration(declaration)) + #expect(throws: (any Error).self) { + try UpdateOperations.preview(request, environment: f.environment) + } + request.changingAccess = true + let before = try FileHash.folderHash(f.root) + let preview = try UpdateOperations.preview(request, environment: f.environment) + let access = try #require(preview.components.first?.permissionChange) + #expect( + access.members.contains { $0.path == ".claude-plugin/plugin.json" && $0.afterMode == 0o600 }) + #expect(access.members.contains { $0.path == ".claude-plugin" && $0.afterMode == 0o700 }) + #expect(try FileHash.folderHash(f.root) == before) + let manifest = tree.appendingPathComponent(".claude-plugin/plugin.json") + let bytes = try Data(contentsOf: manifest) + try bytes.write(to: manifest, options: .atomic) + #expect( + try UpdateOperations.preview(request, environment: f.environment).displayedFingerprint + == preview.displayedFingerprint) + let provider = NativeBindings() + try UpdateOperations.withPreparedUpdate( + request, environment: f.environment, bindingProvider: provider + ) { prepared in + try bytes.write(to: manifest, options: .atomic) + #expect(throws: UpdateApplyError.self) { + try prepared.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + } + #expect(provider.calls.withLock { $0 } == 0) + try FileManager.default.setAttributes([.posixPermissions: 0o640], ofItemAtPath: manifest.path) + let changed = try UpdateOperations.preview(request, environment: f.environment) + #expect(changed.displayedFingerprint != preview.displayedFingerprint) + _ = try UpdateOperations.withPreparedUpdate( + request, environment: f.environment, bindingProvider: provider + ) { try $0.apply(ifUnchangedFrom: changed.displayedFingerprint) } + let current = try UpdateOperations.inspect(environment: f.environment) + #expect(current.deployments.allSatisfy { $0.privateMaterialization && $0.status == .current }) + } +} + +extension PrivateNativeCompositionTests { + @Test func differentSymbolicNativeOwnersCannotShareAProgramRegion() throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .lspServer( + name: "language", + run: .init(executable: "fixture-server", environment: ["TOKEN": .secret("first")]), + languages: [:], agents: [.opencode]), + .lspServer( + name: "language", + run: .init(executable: "fixture-server", environment: ["TOKEN": .secret("second")]), + languages: [:], agents: [.opencode]), + ]), ledger: ResolvedLedger()) + let before = try FileHash.folderHash(f.root) + #expect(throws: (any Error).self) { try f.preview() } + #expect(try FileHash.folderHash(f.root) == before) + } +} + +extension PrivateNativeCompositionTests { + @Test func generatedEnvironmentValuesStayOutOfPreviewAndLedger() throws { + let f = try UpdateFixture() + var environment = f.environment + let canary = "private-native-environment-canary" + environment.environment["NATIVE_FIXTURE_VALUE"] = canary + try f.store.save( + declaration: Declaration(components: [ + .lspServer( + name: "language", + run: .init( + executable: "fixture-server", + environment: ["TOKEN": .environment("NATIVE_FIXTURE_VALUE")]), + languages: [".swift": "swift"], agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + let before = try FileHash.folderHash(f.root) + let preview = try UpdateOperations.preview(environment: environment) + #expect(!String(decoding: try JSONEncoder().encode(preview), as: UTF8.self).contains(canary)) + #expect(try FileHash.folderHash(f.root) == before) + _ = try UpdateOperations.withPreparedUpdate( + environment: environment, bindingProvider: RefuseNativeBindings() + ) { try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) } + let current = try UpdateOperations.inspect(environment: environment) + let tree = try #require(current.deployments.first?.location) + #expect(current.deployments.first?.privateMaterialization == true) + #expect( + try String( + contentsOf: tree.appendingPathComponent(".claude-plugin/plugin.json"), encoding: .utf8 + ).contains(canary)) + #expect( + !String(decoding: try Data(contentsOf: f.store.resolvedURL), as: UTF8.self).contains(canary)) + } +} + +extension PrivateNativeCompositionTests { + @Test func aPrivateReceiptDoesNotHideChangedGeneratedManifestSemantics() throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .lspServer( + name: "language", + run: .init(executable: "fixture-server", environment: ["TOKEN": .secret("token")]), + languages: [".swift": "swift"], agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + environment: f.environment, bindingProvider: NativeBindings() + ) { try $0.apply() } + let installed = try UpdateOperations.inspect(environment: f.environment) + let tree = try #require(installed.deployments.first?.location) + let manifest = tree.appendingPathComponent(".claude-plugin/plugin.json") + let original = try String(contentsOf: manifest, encoding: .utf8) + let changed = Data( + original.replacingOccurrences(of: "fixture-server", with: "different-server").utf8) + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .project, name: "language") + try f.store.withLock(footprint: [route]) { + let prepared = try f.store.preparePrivateMaterialization(f.store.nativeTarget(for: route)) + let transaction = FileTransaction(store: f.store) + try transaction.replacePrivateTree( + prepared, + entries: [ + .init(".claude-plugin", content: .directory), + .init(".claude-plugin/plugin.json", content: .file(changed)), + ], provider: RefuseNativeBindings()) + try transaction.commit() + } + let before = try FileHash.folderHash(f.root) + #expect( + try UpdateOperations.inspect(environment: f.environment).deployments.first?.status == .drifted + ) + #expect(throws: (any Error).self) { try f.preview() } + #expect(try FileHash.folderHash(f.root) == before) + #expect(try Data(contentsOf: manifest) == changed) + } +} From 4c046205ab3722e1c226350d96c2936ca99525be Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:00:07 +0800 Subject: [PATCH 111/171] feat: coordinate native and skill targets --- Sources/AgentsCore/FileTransaction.swift | 78 +++-- .../AgentsCore/NativeTargetCoordination.swift | 88 +++++- Sources/AgentsCore/PathSafety.swift | 21 ++ .../AgentsCore/PrivateMaterialization.swift | 24 +- Sources/AgentsCore/StateInspection.swift | 3 +- Sources/AgentsCore/StateStore.swift | 3 +- Sources/AgentsCore/TransactionJournal.swift | 10 + Sources/AgentsCore/TransactionPaths.swift | 106 ++++++- .../AgentsCore/TransactionPublication.swift | 11 +- Sources/AgentsCore/TransactionSession.swift | 14 +- Sources/AgentsCore/UpdatePreconditions.swift | 10 +- .../CoordinationAdmissionTests.swift | 297 ++++++++++++++++++ .../RegisteredNativeTargetTests.swift | 21 +- .../PrivateMaterializationProbe.swift | 10 + 14 files changed, 625 insertions(+), 71 deletions(-) create mode 100644 Tests/AgentsCoreTests/CoordinationAdmissionTests.swift diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 9f6c4ba..8aeb943 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -40,6 +40,7 @@ package final class FileTransaction { private let outcome: TransactionOutcome private var requests: [Request] = [] private var skillInitialization: SkillInitializationTarget? + private var skillInstallation: SkillInstallationTarget? private var receiptStates: [String: MaterializationReceiptState] = [:] private var receiptIndices: [Int: MaterializationReceiptState] = [:] private var unchanged: [any PreparedEvidence] = [] @@ -84,6 +85,19 @@ package final class FileTransaction { } expectation.kind = requiredKind } + if skillInstallation != nil { + switch source { + case .data: + throw CoreError.unsafePath("skill installation requires a directory or live link") + case .link: + expectation.kind = S_IFLNK + case .copy, .prepared: + guard expectation.kind == nil || expectation.kind == S_IFDIR else { + throw CoreError.unsafePath("skill copy requires a directory") + } + expectation.kind = S_IFDIR + } + } if security.preimage == .privateMaterialization { guard case .data(let data) = source else { throw CoreError.invalidState("sensitive replacement requires private byte construction") @@ -115,6 +129,29 @@ package final class FileTransaction { try replace(target.file, with: .data(bytes), expecting: target.evidence) } + package func replaceSkill( + _ target: SkillInstallationTarget, with source: Source, + expectedHash: String? = nil, expecting: TargetPrecondition? = nil + ) throws { + guard target.scope.path.utf8.elementsEqual(store.directory.path.utf8) else { + throw CoreError.invalidState("installation target belongs to another scope") + } + skillInstallation = target + defer { skillInstallation = nil } + try replace(target.url, with: source, expectedHash: expectedHash, expecting: expecting) + } + + package func deleteSkill(_ target: SkillInstallationTarget, expecting: TargetPrecondition? = nil) + throws + { + guard target.scope.path.utf8.elementsEqual(store.directory.path.utf8) else { + throw CoreError.invalidState("installation target belongs to another scope") + } + skillInstallation = target + defer { skillInstallation = nil } + try delete(target.url, expecting: expecting) + } + package func delete(_ destination: URL, expecting: TargetPrecondition? = nil) throws { let (path, evidence, security) = try request(destination, expecting: expecting) requests.append( @@ -199,17 +236,22 @@ package final class FileTransaction { for state in receiptStates.values.sorted(by: { $0.path < $1.path }) { let receiptRoute = NativeTargetRoute.metadataRoute(state.path) let shared = receiptRoute != nil - let affected = originals.filter { - NativeTargetRoute.sharedRoute($0.path)?.root == receiptRoute?.root - && ($0.security.isPrivate || state.records.targets[$0.path] != nil) + let affected = try originals.filter { + let route = try TransactionPaths(store: store).coordinationRoute(for: $0.path) + let root = try route.map { + try TransactionLockContext.current(store).requiredResourceForRoute($0).route.root + } + let key = try store.materializationReceiptKey(for: $0.path) + return root == receiptRoute?.root + && ($0.security.isPrivate || state.records.targets[key] != nil) } guard !affected.isEmpty else { continue } var sensitiveTargets = Set(state.records.targets.keys) for request in affected { if request.security.replacement == .privateMaterialization { - sensitiveTargets.insert(request.path) + sensitiveTargets.insert(try store.materializationReceiptKey(for: request.path)) } else { - sensitiveTargets.remove(request.path) + sensitiveTargets.remove(try store.materializationReceiptKey(for: request.path)) } } var security = TransactionSecurity() @@ -241,11 +283,11 @@ package final class FileTransaction { path: String, evidence: TargetPrecondition, security: TransactionSecurity ) { let path = try TransactionPaths(store: store).path( - for: destination, skillInitialization: skillInitialization) + for: destination, skillInitialization: skillInitialization, installation: skillInstallation) guard path != "state/" + MaterializationReceipts.fileName else { throw CoreError.unsafePath("materialization receipts are transaction-owned") } - if NativeTargetRoute.sharedRoute(path) != nil { + if try TransactionPaths(store: store).coordinationRoute(for: path) != nil { guard TransactionLockContext.current(store)?.writable == true else { throw CoreError.invalidState("shared writes require the held writer footprint") } @@ -286,10 +328,8 @@ package final class FileTransaction { } } var security = TransactionSecurity() - if let record = receiptState.records.targets[path] { - let paths = TransactionPaths(store: store) - let key = try paths.components(path).root - guard try store.materializationRootIdentity(key) == record.rootIdentity else { + if let record = receiptState.records.targets[try store.materializationReceiptKey(for: path)] { + guard try store.materializationRootIdentity(path) == record.rootIdentity else { throw CoreError.invalidState("materialization receipt root changed") } // A known absence has no sensitive preimage; its receipt is reconciled in this journal. @@ -325,14 +365,17 @@ package final class FileTransaction { package func commit() throws { guard !requests.isEmpty else { return } - let shared = requests.filter { NativeTargetRoute.sharedRoute($0.path) != nil } + let shared = try requests.filter { + try TransactionPaths(store: store).coordinationRoute(for: $0.path) != nil + } if !shared.isEmpty { guard let context = TransactionLockContext.current(store), context.writable else { throw CoreError.invalidState("shared commit requires its held writer footprint") } try context.requireWriterScope() for request in shared { - let resource = try context.resource(for: NativeTargetRoute.sharedRoute(request.path)!) + let resource = try context.resource( + for: TransactionPaths(store: store).coordinationRoute(for: request.path)!) let parent = try DirectoryHandle( at: request.evidence.physicalURL.deletingLastPathComponent()) guard try parent.objectIdentity == resource.identity.parent else { @@ -482,8 +525,8 @@ package final class FileTransaction { security: security)) } let sharedRoutes = Set( - roots.keys.compactMap { key in - NativeTargetRoute.sharedRoute(key) ?? NativeTargetRoute.metadataRoute(key) + try entries.compactMap { + try paths.coordinationRoute(for: $0.path) }) let admittedResources = try sharedRoutes.map { route in guard let context = TransactionLockContext.current(store) else { @@ -497,11 +540,10 @@ package final class FileTransaction { resources.append(resource) } for index in entries.indices { - if let route = NativeTargetRoute.sharedRoute(entries[index].path) - ?? NativeTargetRoute.metadataRoute(entries[index].path) - { + if let route = try paths.coordinationRoute(for: entries[index].path) { let resource = try TransactionLockContext.current(store)!.resource(for: route) entries[index].coordination = resources.firstIndex { $0.identity == resource.identity } + entries[index].coordinationRoot = resource.route.root } } let journal = TransactionJournal( diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index 19b9a4d..89e3c41 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -389,7 +389,7 @@ package struct NativeTargetRoute: RawRepresentable, Hashable, Codable, Sendable func matches(_ route: Self) throws -> Bool { guard route.basename.utf8.elementsEqual(target.lastPathComponent.utf8) else { return false } let authority = try route.rootAuthority(environment, validateExistingOverride: false) - let planned = authority.plannedPhysicalDirectory + let planned = try authority.plannedPhysicalDirectory let targetParent = target.deletingLastPathComponent() if planned.path.utf8.elementsEqual(targetParent.path.utf8) { _ = try authority.physicalDirectory() @@ -417,7 +417,7 @@ package struct NativeTargetRoute: RawRepresentable, Hashable, Codable, Sendable let suffix = String(probe.basename.dropFirst("probe".count)) guard target.lastPathComponent.hasSuffix(suffix) else { continue } let authority = try probe.rootAuthority(environment, validateExistingOverride: false) - let container = authority.plannedPhysicalDirectory + let container = try authority.plannedPhysicalDirectory var ancestor = target.deletingLastPathComponent() var relativeParts = [target.lastPathComponent] let containerIdentity = try? DirectoryHandle(at: container).objectIdentity @@ -463,10 +463,14 @@ struct NativeRootAuthority { let descendants: [String] var logicalDirectory: URL { descendants.reduce(loader) { $0.appendingPathComponent($1) } } var plannedPhysicalDirectory: URL { - descendants.reduce(loader.resolvingSymlinksInPath()) { $0.appendingPathComponent($1) } + get throws { + try descendants.reduce(PathSafety.resolvedDirectoryBoundary(loader)) { + $0.appendingPathComponent($1) + } + } } func physicalDirectory() throws -> URL { - var result = loader.resolvingSymlinksInPath() + var result = try PathSafety.resolvedDirectoryBoundary(loader) let ancestry = try DirectoryAccessEvidence.capture(at: result) var opened = ancestry.directories.count == result.pathComponents.count @@ -748,6 +752,7 @@ final class TransactionLockContext { let writable: Bool let requestedShared: Bool let absentRoots: [AbsentSharedRoot] + var installations: [SkillInstallationTarget] = [] var existingProjectRoot: ExistingProjectRoot? var projectRootDirectory: DirectoryHandle? private var scopeDirectory: DirectoryHandle? @@ -811,6 +816,7 @@ final class TransactionLockContext { func validateScope() throws { try existingProjectRoot?.validate() + for target in installations { try target.validateAuthority() } guard let directory = scopeDirectory else { return } var info = stat() guard let descriptor = scopeDescriptor, let identity = scopeLockIdentity, @@ -887,7 +893,7 @@ extension StateStore { } if !route.shared, route.isNamed { let target = try route.physicalDirectory(environment).appendingPathComponent(route.basename) - try requireProjectNativeAuthority(at: target) + _ = try coordinationRoute(for: route) if route.isContainer { for shared in NativeTargetRoute.allCases where shared.shared { let parent = try shared.rootAuthority(environment, validateExistingOverride: false) @@ -902,10 +908,12 @@ extension StateStore { } var canonical = route let parent: URL - if route.shared, let context = TransactionLockContext.current(self) { - parent = try context.targetDirectory(for: route) - if try context.absentRoot(for: route) == nil { - canonical = try context.resource(for: route).route + let coordinated = try coordinationRoute(for: route) + if let coordinated, let context = TransactionLockContext.current(self) { + let held = try context.targetDirectory(for: coordinated) + parent = route.shared ? held : try route.physicalDirectory(environment) + if route.shared, try context.absentRoot(for: coordinated) == nil { + canonical = try context.resource(for: coordinated).route } } else { parent = try route.physicalDirectory(environment) @@ -929,7 +937,7 @@ extension StateStore { /// Acquire the union before the scope lock. Re-admission never replays a delivered callback. func withCoordination( - routes: Set, writable: Bool, + routes: Set, installations: [SkillInstallationTarget] = [], writable: Bool, checkpoint: (String) throws -> Void = { _ in }, existingRoot: ExistingProjectRoot? = nil, projectRoot: DirectoryHandle? = nil, _ body: () throws -> T @@ -941,6 +949,17 @@ extension StateStore { guard routes.allSatisfy({ $0.permits(scope) }) else { throw CoreError.unsafePath("registered native request belongs to another scope") } + for target in installations { + try target.validateAuthority() + let current = try skillInstallationTarget(for: target.agent, named: target.name) + guard current.scope.path.utf8.elementsEqual(target.scope.path.utf8), + current.url.path.utf8.elementsEqual(target.url.path.utf8), + current.footprint == target.footprint + else { throw CoreError.invalidState("installation authority changed before admission") } + } + let installationRoutes = installations.reduce(into: Set()) { + $0.formUnion($1.footprint) + } for route in routes where !route.shared && route.isNamed { _ = try nativeTarget(for: route) } while true { let before = try pendingCoordinationJournal(diagnosing: !writable) @@ -956,10 +975,14 @@ extension StateStore { let pending = before?.footprint ?? [] var admissions: [SharedResource] = [] let recoveryRoutes = Set( - (before?.roots.keys.map { $0 } ?? []).compactMap { - NativeTargetRoute.sharedRoute($0) ?? NativeTargetRoute.metadataRoute($0) + (before?.entries ?? []).compactMap { entry in + entry.coordinationRoot.flatMap { NativeTargetRoute.sharedRoute($0) } + ?? NativeTargetRoute.sharedRoute(entry.path) + ?? NativeTargetRoute.metadataRoute(entry.path) }) - var requested = Set(routes.filter(\.shared).map { NativeTargetRoute.targetRoute($0.root)! }) + var requested = Set(try routes.compactMap { try coordinationRoute(for: $0) }) + requested.formUnion(installationRoutes) + let requestedShared = !requested.isEmpty requested.formUnion(recoveryRoutes) let ordered = requested.sorted { left, right in let leftPending = recoveryRoutes.contains(left) @@ -1031,8 +1054,9 @@ extension StateStore { } let context = TransactionLockContext( store: self, resources: resources.sorted { $0.identity < $1.identity }, writable: writable, - requestedShared: routes.contains(where: \.shared), absentRoots: absentRoots, + requestedShared: requestedShared, absentRoots: absentRoots, admissions: admissions, requestedRoutes: routes) + context.installations = installations context.createdAncestry = createdAncestry context.existingProjectRoot = existingRoot context.projectRootDirectory = projectRoot @@ -1113,6 +1137,12 @@ extension StateStore { guard let directory else { throw CoreError.invalidState("missing transaction scope") } try context.validate(journal, scope: directory) } + for target in context.installations { + let current = try skillInstallationTarget(for: target.agent, named: target.name) + guard current.url.path.utf8.elementsEqual(target.url.path.utf8), + current.footprint == target.footprint + else { throw CoreError.invalidState("installation authority changed during admission") } + } for admission in context.admissions { try admission.validate() } for resource in context.resources { if journal?.finalized != true && (context.writable || journal == nil) { @@ -1166,3 +1196,33 @@ extension StateStore { kind: UInt32(identity.kind), basename: target.url.lastPathComponent) } } + +extension StateStore { + func coordinationRoute(for route: NativeTargetRoute) throws -> NativeTargetRoute? { + if route.shared { return route } + let target = try route.physicalDirectory(environment).appendingPathComponent(route.basename) + guard let shared = try NativeTargetRoute.userRoute(at: target, environment: environment) + else { return nil } + guard route.knownReaders == shared.knownReaders, route.isContainer == shared.isContainer else { + throw CoreError.unsafePath("native alias has incompatible reader or object authority") + } + return shared + } + + func materializationReceiptKey(for path: String) throws -> String { + if let route = try TransactionPaths(store: self).coordinationRoute(for: path) { + let resource = try TransactionLockContext.current(self).requiredResourceForRoute(route) + return resource.route.root + "/" + resource.identity.basename + } + return path + } +} + +extension Optional where Wrapped == TransactionLockContext { + func requiredResourceForRoute(_ route: NativeTargetRoute) throws -> SharedResource { + guard let context = self else { + throw CoreError.invalidState("shared target requires its held footprint") + } + return try context.resource(for: route) + } +} diff --git a/Sources/AgentsCore/PathSafety.swift b/Sources/AgentsCore/PathSafety.swift index 2ac30e7..508d346 100644 --- a/Sources/AgentsCore/PathSafety.swift +++ b/Sources/AgentsCore/PathSafety.swift @@ -122,3 +122,24 @@ public enum PathSafety { return components.isEmpty ? "." : components.joined(separator: "/") } } + +extension PathSafety { + /// Resolve the configured loader boundary's existing prefix; missing suffixes carry no identity. + static func resolvedDirectoryBoundary(_ directory: URL) throws -> URL { + var prefix = directory.standardizedFileURL + var suffix: [String] = [] + while true { + if let physical = realPath(prefix.path) { + return suffix.reduce(URL(fileURLWithPath: physical).resolvingSymlinksInPath()) { + $0.appendingPathComponent($1) + } + } + var info = stat() + guard lstat(prefix.path, &info) != 0, errno == ENOENT, prefix.path != "/" else { + throw CoreError.unsafePath("cannot resolve registered loader boundary") + } + suffix.insert(prefix.lastPathComponent, at: 0) + prefix.deleteLastPathComponent() + } + } +} diff --git a/Sources/AgentsCore/PrivateMaterialization.swift b/Sources/AgentsCore/PrivateMaterialization.swift index 7371f49..a14208a 100644 --- a/Sources/AgentsCore/PrivateMaterialization.swift +++ b/Sources/AgentsCore/PrivateMaterialization.swift @@ -108,12 +108,14 @@ extension StateStore { guard target.scope.path == directory.path, try TransactionPaths(store: self).path(for: target.url) == target.path else { throw CoreError.invalidState("materialization target belongs to another scope") } - if let route = NativeTargetRoute.sharedRoute(target.path), + if let route = try TransactionPaths(store: self).coordinationRoute(for: target.path), try TransactionLockContext.current(self)?.absentRoot(for: route) != nil { return nil } - guard let record = try materializationReceipts(for: target.path).records.targets[target.path] + guard + let record = try materializationReceipts(for: target.path).records.targets[ + materializationReceiptKey(for: target.path)] else { return nil } @@ -130,7 +132,7 @@ extension StateStore { guard target.scope.path == directory.path, try TransactionPaths(store: self).path(for: target.url) == target.path else { throw CoreError.invalidState("materialization target belongs to another scope") } - if let route = NativeTargetRoute.sharedRoute(target.path), + if let route = try TransactionPaths(store: self).coordinationRoute(for: target.path), try TransactionLockContext.current(self)?.absentRoot(for: route) != nil { guard generation == nil else { @@ -142,7 +144,7 @@ extension StateStore { evidence: evidence, receiptEvidence: nil, memberAccessChanges: [], preimageTreeAccess: nil) } let receipt = try materializationReceipts(for: target.path) - let record = receipt.records.targets[target.path] + let record = receipt.records.targets[try materializationReceiptKey(for: target.path)] if let generation, record?.generation != generation { throw CoreError.invalidState("materialization receipt generation changed or is missing") } @@ -205,10 +207,8 @@ extension StateStore { before: beforeAccess, owner: UInt32(geteuid()), mode: UInt32(privateMode)) } } - if let record = receipt.records.targets[target.path] { - let paths = TransactionPaths(store: self) - let key = try paths.components(target.path).root - guard try materializationRootIdentity(key) == record.rootIdentity else { + if let record = receipt.records.targets[try materializationReceiptKey(for: target.path)] { + guard try materializationRootIdentity(target.path) == record.rootIdentity else { throw CoreError.invalidState("materialization receipt root changed") } if evidence.snapshot != nil { @@ -286,17 +286,19 @@ extension StateStore { } func materializationRootIdentity(_ root: String) throws -> String { - if let route = NativeTargetRoute.sharedRoute(root) { + if let route = try TransactionPaths(store: self).coordinationRoute(for: root) { guard let context = TransactionLockContext.current(self) else { throw CoreError.invalidState("shared receipt requires its held footprint") } return try context.resource(for: route).identity.orderingKey } - return try TransactionPaths(store: self).root(root).identity + return try TransactionPaths(store: self).root( + root.split(separator: "/").first.map(String.init) ?? root + ).identity } func materializationReceipts(for path: String = "") throws -> MaterializationReceiptState { - let route = NativeTargetRoute.sharedRoute(path) + let route = try TransactionPaths(store: self).coordinationRoute(for: path) let shared = route != nil let resource: SharedResource? if let route { diff --git a/Sources/AgentsCore/StateInspection.swift b/Sources/AgentsCore/StateInspection.swift index ff22e70..8845553 100644 --- a/Sources/AgentsCore/StateInspection.swift +++ b/Sources/AgentsCore/StateInspection.swift @@ -9,9 +9,10 @@ extension StateStore { package func withReadLock( onPendingRecovery: (() throws -> T)? = nil, footprint: Set = [], + installations: [SkillInstallationTarget] = [], _ body: () throws -> T ) throws -> T { - try withCoordination(routes: footprint, writable: false) { + try withCoordination(routes: footprint, installations: installations, writable: false) { try withScopeReadLock(onPendingRecovery: onPendingRecovery, body) } } diff --git a/Sources/AgentsCore/StateStore.swift b/Sources/AgentsCore/StateStore.swift index f975512..6ab73b1 100644 --- a/Sources/AgentsCore/StateStore.swift +++ b/Sources/AgentsCore/StateStore.swift @@ -82,12 +82,13 @@ public struct StateStore: Sendable { package func withLock( createIfMissing: Bool = true, checkpoint: @escaping (String) throws -> Void = { _ in }, outcome: TransactionOutcome? = nil, footprint: Set = [], + installations: [SkillInstallationTarget] = [], existingRoot: ExistingProjectRoot? = nil, _ body: () throws -> T ) throws -> T { let root = try existingRoot?.open(for: self) return try withCoordination( - routes: footprint, writable: true, checkpoint: checkpoint, + routes: footprint, installations: installations, writable: true, checkpoint: checkpoint, existingRoot: existingRoot, projectRoot: root ) { try withScopeLock( diff --git a/Sources/AgentsCore/TransactionJournal.swift b/Sources/AgentsCore/TransactionJournal.swift index f38caf8..e8208f1 100644 --- a/Sources/AgentsCore/TransactionJournal.swift +++ b/Sources/AgentsCore/TransactionJournal.swift @@ -44,6 +44,15 @@ struct TransactionJournal: Codable { guard entry.coordination.map({ footprint.indices.contains($0) }) ?? (route == nil) else { throw CoreError.invalidState("invalid entry coordination index") } + if let root = entry.coordinationRoot { + guard let registered = NativeTargetRoute.sharedRoute(root), + root.utf8.elementsEqual(registered.root.utf8), + let index = entry.coordination, + footprint[index].basename.utf8.elementsEqual(registered.basename.utf8) + else { throw CoreError.invalidState("invalid registered coordination root") } + } else if entry.coordination != nil, route == nil { + throw CoreError.invalidState("coordinated alias lacks its registered root") + } if let route { guard let index = entry.coordination, footprint[index].basename.utf8.elementsEqual(route.basename.utf8) @@ -95,6 +104,7 @@ struct TransactionJournal: Codable { var conflict: Conflict? var security = TransactionSecurity() var coordination: Int? + var coordinationRoot: String? var name: String { String(path.split(separator: "/").last!) } } diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index 5f25b8b..de1ef93 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -5,9 +5,28 @@ import Foundation struct TransactionPaths { let store: StateStore - func path(for destination: URL, skillInitialization: SkillInitializationTarget? = nil) throws + func path( + for destination: URL, skillInitialization: SkillInitializationTarget? = nil, + installation: SkillInstallationTarget? = nil + ) throws -> String { + if let installation, + installation.scope.path.utf8.elementsEqual(store.directory.path.utf8), + installation.url.path.utf8.elementsEqual(destination.standardizedFileURL.path.utf8) + { + try installation.validateAuthority() + let canonical = installation.name.utf8.elementsEqual( + PathSafety.sanitizeName(installation.name).utf8) + let recorded = + canonical ? false : try persistedInstallation(installation.name, agent: installation.agent) + guard canonical || recorded + else { throw CoreError.unsafePath("installation recipient changed") } + if let route = try coordinationRoute(for: installation.path) { + _ = try TransactionLockContext.current(store).requiredResourceForRoute(route) + } + return installation.path + } let base = store.scope == .project ? store.environment.projectDirectory : store.environment.homeDirectory let physicalState = base.resolvingSymlinksInPath().appendingPathComponent( @@ -15,7 +34,9 @@ struct TransactionPaths { let admitted = Array(TransactionLockContext.current(store)?.requestedRoutes ?? []) + (TransactionLockContext.current(store)?.admissions.map(\.route) ?? []) + let requested = TransactionLockContext.current(store)?.requestedRoutes ?? [] let nativeRoutes = Array(Set(admitted + NativeTargetRoute.allCases)).sorted { + if requested.contains($0) != requested.contains($1) { return requested.contains($0) } if $0.shared != $1.shared { return $0.shared } if admitted.contains($0) != admitted.contains($1) { return admitted.contains($0) } return $0.shared == $1.shared ? $0.rawValue < $1.rawValue : $0.shared @@ -38,7 +59,7 @@ struct TransactionPaths { } _ = try context.targetDirectory(for: route) } - if !route.shared { try store.requireProjectNativeAuthority(at: target.url) } + if !route.shared { _ = try store.coordinationRoute(for: route) } return target.path } } @@ -158,9 +179,10 @@ struct TransactionPaths { } else if let agent = AgentID(rawValue: key) { // Configured agent containers are trusted inputs. Resolve that boundary once; // journal descendants are opened without following links and roots are identity-bound. - url = AgentRegistry.installSkillsDirectory( - for: agent, scope: store.scope, environment: store.environment - ).resolvingSymlinksInPath() + url = try NativeRootAuthority( + loader: AgentRegistry.installSkillsDirectory( + for: agent, scope: store.scope, environment: store.environment), descendants: [] + ).physicalDirectory() } else { throw CoreError.invalidState("unknown transaction root") } @@ -172,6 +194,10 @@ struct TransactionPaths { for key in keys { if let route = NativeTargetRoute.targetRoute(key), !route.shared { result[key] = try route.rootAuthority(store.environment) + } else if let agent = AgentID(rawValue: key) { + result[key] = NativeRootAuthority( + loader: AgentRegistry.installSkillsDirectory( + for: agent, scope: store.scope, environment: store.environment), descendants: []) } } return result @@ -179,7 +205,7 @@ struct TransactionPaths { /// Only committed exact recipients authorize legacy spellings at the queue boundary. /// Recovery instead consumes the journal's already-admitted single-component path. - private func persistedInstallation(_ name: String, agent: AgentID) throws -> Bool { + fileprivate func persistedInstallation(_ name: String, agent: AgentID) throws -> Bool { guard !name.isEmpty, name != ".", name != "..", !name.contains("/"), !name.contains("\\"), !name.contains("\0"), let bytes = try store.existingData(store.resolvedURL) @@ -232,7 +258,7 @@ struct TransactionPaths { throw CoreError.unsafePath("unregistered shared transaction metadata") } } else if key == "skill-authoring", store.scope == .project { - guard (1...2).contains(descendants.count), descendants.last == "SKILL.md" + guard (1...3).contains(descendants.count), descendants.last == "SKILL.md" else { throw CoreError.unsafePath("invalid local skill authoring path") } } else if key == "instructions-project", store.scope == .project { guard InstructionLocations.isProjectTarget(descendants.joined(separator: "/")) else { @@ -282,3 +308,69 @@ struct TransactionPaths { return directory } } + +/// Exact closed installation authority; coordination does not change its payload intention. +package struct SkillInstallationTarget { + package let url: URL + package let footprint: Set + let path: String + let scope: URL + let agent: AgentID + let name: String + let authority: NativeRootAuthority + let parentIdentity: FileObjectIdentity? + + func validateAuthority() throws { + let parent = try authority.physicalDirectory() + guard parent.path.utf8.elementsEqual(url.deletingLastPathComponent().path.utf8), + try parentIdentity.map({ try DirectoryHandle(at: parent).objectIdentity == $0 }) ?? true + else { throw CoreError.invalidState("installation authority changed") } + } +} + +extension StateStore { + package func skillInstallationTarget(for agent: AgentID, named name: String) throws + -> SkillInstallationTarget + { + let paths = TransactionPaths(store: self) + let canonical = name.utf8.elementsEqual(PathSafety.sanitizeName(name).utf8) + let recorded = canonical ? false : try paths.persistedInstallation(name, agent: agent) + guard !name.isEmpty, name != ".", name != "..", !name.contains("/"), + !name.contains("\\"), !name.contains("\0"), + canonical || recorded + else { throw CoreError.unsafePath("unrecorded installation target") } + let authority = NativeRootAuthority( + loader: AgentRegistry.installSkillsDirectory( + for: agent, scope: scope, environment: environment), descendants: []) + let parent = try authority.physicalDirectory() + let ancestry = try DirectoryAccessEvidence.capture(at: parent) + let identity = + ancestry.directories.count == parent.pathComponents.count + ? try DirectoryHandle(at: parent).objectIdentity : nil + let url = parent.appendingPathComponent(name) + let path = agent.rawValue + "/" + name + let route = try paths.coordinationRoute(for: path) + return SkillInstallationTarget( + url: url, footprint: Set(route.map { [$0] } ?? []), path: path, scope: directory, + agent: agent, name: name, authority: authority, parentIdentity: identity) + } +} + +extension TransactionPaths { + func coordinationRoute(for path: String) throws -> NativeTargetRoute? { + if let metadata = NativeTargetRoute.metadataRoute(path) { return metadata } + if let route = NativeTargetRoute.targetRoute(path) { + return try store.coordinationRoute(for: route) + } + let parts = path.split(separator: "/").map(String.init) + guard parts.count == 2, let agent = AgentID(rawValue: parts[0]) else { return nil } + _ = try components(path) + let target = try rootURL(parts[0]).appendingPathComponent(parts[1]) + guard let route = try NativeTargetRoute.userRoute(at: target, environment: store.environment) + else { return nil } + guard route.isContainer, route.knownReaders.contains(agent) else { + throw CoreError.unsafePath("installation aliases incompatible native readers") + } + return route + } +} diff --git a/Sources/AgentsCore/TransactionPublication.swift b/Sources/AgentsCore/TransactionPublication.swift index 577c3a9..afc2042 100644 --- a/Sources/AgentsCore/TransactionPublication.swift +++ b/Sources/AgentsCore/TransactionPublication.swift @@ -286,23 +286,26 @@ extension TransactionSession { for entry in journal.entries where entry.path != "state/" + MaterializationReceipts.fileName && NativeTargetRoute.metadataRoute(entry.path) == nil - && NativeTargetRoute.sharedRoute(entry.path)?.root == targetRoot { + let resource = entry.coordination.flatMap { index in + resources.first { $0.identity == journal.footprint[index] } + } + guard resource?.route.root == targetRoot else { continue } + let recordPath = resource.map { $0.route.root + "/" + entry.name } ?? entry.path if entry.security.replacement == .privateMaterialization { guard let snapshot = entry.staged, let access = entry.security.stagedAccess, let root = entry.path.split(separator: "/").first, let identity = journal.roots[String(root)] else { throw CoreError.invalidState("materialization is missing sealed receipt evidence") } - let resource = resources.first { $0.route.root == String(root) } if targetRoot != nil, resource == nil { throw CoreError.invalidState("receipt resource is outside the transaction footprint") } - records.targets[entry.path] = .init( + records.targets[recordPath] = .init( generation: journal.id, rootIdentity: resource?.identity.orderingKey ?? identity, digest: snapshot.digest, access: access, treeAccess: entry.security.stagedTreeAccess) } else { - records.targets.removeValue(forKey: entry.path) + records.targets.removeValue(forKey: recordPath) } } return records diff --git a/Sources/AgentsCore/TransactionSession.swift b/Sources/AgentsCore/TransactionSession.swift index 19103f4..699d39a 100644 --- a/Sources/AgentsCore/TransactionSession.swift +++ b/Sources/AgentsCore/TransactionSession.swift @@ -95,13 +95,10 @@ final class TransactionSession { func requireParent(_ index: Int) throws { try requireScope() - if let route = NativeTargetRoute.targetRoute(journal.entries[index].path), !route.shared { - guard let logical = nativeRoots[route.root], - try DirectoryHandle(at: logical.physicalDirectory()).identity - == journal.roots[route.root] - else { - throw conflict(index, "registered native root changed after preparation") - } + let root = String(journal.entries[index].path.split(separator: "/").first!) + if let logical = nativeRoots[root] { + guard try DirectoryHandle(at: logical.physicalDirectory()).identity == journal.roots[root] + else { throw conflict(index, "registered root changed after preparation") } } try journal.entries[index].security.ancestry?.validate(at: parents[index].url) guard @@ -171,6 +168,9 @@ final class TransactionSession { try requireParent(index) try entry.security.validate(entry: entry) let target = parents[index].url.appendingPathComponent(entry.name) + if try paths.coordinationRoute(for: entry.path) != nil, entry.coordination == nil { + throw CoreError.invalidState("shared target lacks physical coordination") + } if let coordination = entry.coordination { let identity = journal.footprint[coordination] if let route = NativeTargetRoute.metadataRoute(entry.path) { diff --git a/Sources/AgentsCore/UpdatePreconditions.swift b/Sources/AgentsCore/UpdatePreconditions.swift index 24b9c30..73f70ef 100644 --- a/Sources/AgentsCore/UpdatePreconditions.swift +++ b/Sources/AgentsCore/UpdatePreconditions.swift @@ -255,7 +255,9 @@ package struct SkillInitializationTarget { }) ?? true else { throw CoreError.unsafePath("invalid local skill initialization target") } scope = store.directory - descendants = ((selectedDirectory ?? name).map { [$0] } ?? []) + ["SKILL.md"] + descendants = + (selectedDirectory.map { [$0] } ?? []) + + (name.map { [$0] } ?? []) + ["SKILL.md"] file = descendants.reduce(store.environment.projectDirectory.resolvingSymlinksInPath()) { $0.appendingPathComponent($1) } @@ -274,9 +276,11 @@ extension StateStore { } /// Preserves an explicitly selected directory spelling below the observed existing parent. - package func skillInitializationTarget(inChildDirectory directory: String) throws + package func skillInitializationTarget( + inChildDirectory directory: String, named name: String? = nil + ) throws -> SkillInitializationTarget { - try SkillInitializationTarget(store: self, name: nil, selectedDirectory: directory) + try SkillInitializationTarget(store: self, name: name, selectedDirectory: directory) } } diff --git a/Tests/AgentsCoreTests/CoordinationAdmissionTests.swift b/Tests/AgentsCoreTests/CoordinationAdmissionTests.swift new file mode 100644 index 0000000..9dd4adb --- /dev/null +++ b/Tests/AgentsCoreTests/CoordinationAdmissionTests.swift @@ -0,0 +1,297 @@ +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite struct CoordinationAdmissionTests { + @Test func standaloneSelectionAndCanonicalChildUseObservedParent() throws { + let fixture = try TransactionFixture() + let store = fixture.store + let root = try store.captureExistingProjectRoot() + let before = try FileSnapshot.read(at: fixture.root) + let target = try store.skillInitializationTarget( + inChildDirectory: "Selected Skill", named: "demo") + #expect(try FileSnapshot.read(at: fixture.root) == before) + #expect(target.file == fixture.root.appendingPathComponent("Selected Skill/demo/SKILL.md")) + try store.withLock(existingRoot: root) { + let transaction = FileTransaction(store: store) + try transaction.initializeSkill(target, bytes: Data("exact template".utf8)) + try transaction.commit() + } + #expect(try Data(contentsOf: target.file) == Data("exact template".utf8)) + #expect(throws: CoreError.self) { + try store.skillInitializationTarget(inChildDirectory: "../escape", named: "demo") + } + } + + @Test func legacySymlinkAndPluginKeepDistinctIntentWithOnePhysicalDomain() throws { + let fixture = try TransactionFixture() + let store = StateStore(scope: .user, environment: fixture.store.environment) + let skill = try store.skillInstallationTarget(for: .claudeCode, named: "shared") + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: "shared") + #expect(skill.footprint == [route]) + #expect(throws: CoreError.self) { + try store.withLock { + let transaction = FileTransaction(store: store) + try transaction.replaceSkill(skill, with: .link(fixture.root.appendingPathComponent("new"))) + } + } + try store.withLock(footprint: skill.footprint) { + let transaction = FileTransaction(store: store) + try transaction.replaceSkill(skill, with: .link(fixture.root.appendingPathComponent("new"))) + try transaction.commit() + #expect(try FileSnapshot.read(at: skill.url)?.isSymbolicLink == true) + let native = try store.nativeTarget(for: route) + #expect(throws: CoreError.self) { try store.preparePrivateMaterialization(native) } + let copy = FileTransaction(store: store) + try copy.replaceSkill(skill, with: .copy(fixture.root.appendingPathComponent("new"))) + try copy.commit() + let privateTree = FileTransaction(store: store) + try privateTree.replacePrivateTree( + store.preparePrivateMaterialization(native, changingAccess: true), + entries: [.init("secret", content: .file(Data("retained".utf8)))], + provider: AdmissionBindings()) + try privateTree.commit() + let generation = try store.materializationReceipt(for: native)?.generation + let refuses = FileTransaction(store: store) + #expect(throws: CoreError.self) { + try refuses.replaceSkill(skill, with: .copy(fixture.root.appendingPathComponent("new"))) + } + let rollback = FileTransaction(store: store) { point in + if point == "entry.0.applied" { throw CoreError.invalidState("bounded rollback") } + } + try rollback.deleteSkill(skill) + #expect(throws: CoreError.self) { try rollback.commit() } + #expect(try store.materializationReceipt(for: native)?.generation == generation) + #expect( + try Data(contentsOf: native.url.appendingPathComponent("secret")) == Data("retained".utf8)) + #expect(!FileManager.default.fileExists(atPath: store.materializationReceiptURL.path)) + } + } + + @Test func compatibleProjectUserAliasesRetainOnePrivateReceiptAndLogicalAuthority() throws { + let fixture = try TransactionFixture() + var environment = fixture.store.environment + environment.environment["CLAUDE_CONFIG_DIR"] = + fixture.root.appendingPathComponent(".claude").path + let project = StateStore(scope: .project, environment: environment) + let user = StateStore(scope: .user, environment: environment) + let local = try NativeTargetRoute.named(.claudeCommand, scope: .project, name: "team/review") + let global = try NativeTargetRoute.named(.claudeCommand, scope: .user, name: "team/review") + var generation: UUID? + try project.withLock(footprint: [local]) { + let target = try project.nativeTarget(for: local) + #expect(target.path == local.root + "/" + local.basename) + let transaction = FileTransaction(store: project) + try transaction.replacePrivate( + project.preparePrivateMaterialization(target), provider: AdmissionBindings() + ) { _ in Data("secret sibling".utf8) } + try transaction.commit() + generation = try project.materializationReceipt(for: target)?.generation + #expect(!FileManager.default.fileExists(atPath: project.materializationReceiptURL.path)) + } + try user.withLock(footprint: [global]) { + let target = try user.nativeTarget(for: global) + #expect(try user.materializationReceipt(for: target)?.generation == generation) + let transaction = FileTransaction(store: user) + try transaction.replace(target.url, with: .data(Data("secret sibling; ordinary edit".utf8))) + try transaction.commit() + #expect(try user.materializationReceipt(for: target)?.generation != generation) + } + try project.withReadLock(footprint: [local]) { + let target = try project.nativeTarget(for: local) + #expect(try project.materializationReceipt(for: target) != nil) + #expect(try Data(contentsOf: target.url) == Data("secret sibling; ordinary edit".utf8)) + } + } +} + +extension CoordinationAdmissionTests { + @Test func nativeAndLegacyWritersContendBeforeLegacyCallback() throws { + let f = try TransactionFixture() + let config = f.root.appendingPathComponent("home/.claude") + let holder = try stateTestProcess( + root: f.root, + arguments: [ + "private-tree-lock", "tree.locked", "--scope", "user", "--shared-config", config.path, + ]) + defer { terminateProcess(holder) } + try ProcessWait.marker(f.root.appendingPathComponent("ready"), child: holder, root: f.root) + try FileManager.default.removeItem(at: f.root.appendingPathComponent("ready")) + let waiter = try stateTestProcess( + root: f.root, + arguments: [ + "private-legacy-install", "shared.0.lock.contended", "--scope", "user", "--shared-config", + config.path, + ]) + defer { terminateProcess(waiter) } + try ProcessWait.marker(f.root.appendingPathComponent("ready"), child: waiter, root: f.root) + #expect( + !FileManager.default.fileExists(atPath: f.root.appendingPathComponent("legacy-callback").path) + ) + try #require(kill(holder.processIdentifier, SIGCONT) == 0) + try ProcessWait.exit(holder, root: f.root) + #expect(holder.terminationStatus == 0) + try #require(kill(waiter.processIdentifier, SIGCONT) == 0) + try ProcessWait.exit(waiter, root: f.root) + #expect(waiter.terminationStatus == 0) + #expect( + FileManager.default.fileExists( + atPath: config.appendingPathComponent("skills/private-fixture/SKILL.md").path)) + } + + @Test(arguments: ["entry.0.applied", "journal.finalized"]) + func legacyJournalReconstructsOnlyItsClosedCoordinator(_ point: String) throws { + let f = try TransactionFixture() + let config = f.root.appendingPathComponent("home/.claude") + let child = try stateTestProcess( + root: f.root, + arguments: [ + "private-legacy-install", point, "--scope", "user", "--shared-config", config.path, + ]) + defer { terminateProcess(child) } + try ProcessWait.marker(f.root.appendingPathComponent("ready"), child: child, root: f.root) + terminateProcess(child) + var environment = f.store.environment + environment.environment["CLAUDE_CONFIG_DIR"] = config.path + let store = StateStore(scope: .user, environment: environment) + let before = try FileSnapshot.read(at: f.root) + try store.withReadLock( + onPendingRecovery: { + #expect(!FileTransaction.recoveryDiagnostic(store: store).requiresOwner) + }, { Issue.record("expected recovery diagnostic") }) + #expect(try FileSnapshot.read(at: f.root) == before) + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + let target = try store.skillInstallationTarget(for: .claudeCode, named: "private-fixture") + #expect( + FileManager.default.fileExists(atPath: target.url.path) == (point == "journal.finalized")) + } +} + +extension CoordinationAdmissionTests { + @Test func projectLegacyAliasDoesNotGrantUserNativeScopeAuthority() throws { + let f = try TransactionFixture() + let destination = f.root.appendingPathComponent("home/.claude") + try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: f.root.appendingPathComponent(".claude"), withDestinationURL: destination) + let target = try f.store.skillInstallationTarget(for: .claudeCode, named: "legacy") + let userRoute = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: "legacy") + #expect(throws: CoreError.self) { try f.store.withLock(footprint: [userRoute]) {} } + try f.store.withLock(installations: [target]) { () -> Void in + #expect(throws: CoreError.self) { try f.store.nativeTarget(for: userRoute) } + let transaction = FileTransaction(store: f.store) + try transaction.replaceSkill(target, with: .link(f.root.appendingPathComponent("new"))) + try transaction.commit() + } + #expect(try FileSnapshot.read(at: target.url)?.isSymbolicLink == true) + } + + @Test func incompatibleReadersAndSymlinkDescendantsCannotAcquireAliasAuthority() throws { + let f = try TransactionFixture() + let claude = f.root.appendingPathComponent(".claude") + try FileManager.default.createDirectory(at: claude, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: f.root.appendingPathComponent(".gemini"), withDestinationURL: claude) + var environment = f.store.environment + environment.environment["GEMINI_CLI_HOME"] = f.root.path + let store = StateStore(scope: .project, environment: environment) + let before = try FileSnapshot.read(at: f.root) + #expect(throws: CoreError.self) { try store.withLock(footprint: [.claudeSettingsProject]) {} } + #expect(try FileSnapshot.read(at: f.root) == before) + let external = f.root.appendingPathComponent("external") + try FileManager.default.createDirectory(at: external, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: claude.appendingPathComponent("commands"), withDestinationURL: external) + let route = try NativeTargetRoute.named(.claudeCommand, scope: .project, name: "example") + #expect(throws: CoreError.self) { try store.withReadLock(footprint: [route]) {} } + #expect( + !FileManager.default.fileExists( + atPath: external.appendingPathComponent(".agents-native").path)) + } +} + +extension CoordinationAdmissionTests { + @Test func finalizedLegacyCleanupPreservesLaterGenerationAfterLogicalAliasReplacement() throws { + let f = try TransactionFixture() + let config = f.root.appendingPathComponent("home/.claude") + try FileManager.default.createDirectory(at: config, withIntermediateDirectories: true) + let alias = f.root.appendingPathComponent(".claude") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: config) + let child = try stateTestProcess( + root: f.root, + arguments: [ + "private-legacy-install", "shared.0.reservation.removed", "--shared-config", config.path, + ]) + defer { terminateProcess(child) } + try ProcessWait.marker(f.root.appendingPathComponent("ready"), child: child, root: f.root) + terminateProcess(child) + var environment = f.store.environment + environment.environment["CLAUDE_CONFIG_DIR"] = config.path + let later = StateStore(scope: .user, environment: environment) + let target = try later.skillInstallationTarget(for: .claudeCode, named: "private-fixture") + let source = f.root.appendingPathComponent("later") + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: false) + try Data("later generation".utf8).write(to: source.appendingPathComponent("SKILL.md")) + try later.withLock(installations: [target]) { + let transaction = FileTransaction(store: later) + try transaction.replaceSkill(target, with: .copy(source)) + try transaction.commit() + } + try FileManager.default.removeItem(at: alias) + try FileManager.default.createDirectory(at: alias, withIntermediateDirectories: false) + let owner = StateStore(scope: .project, environment: environment) + let before = try FileSnapshot.read(at: f.root) + try owner.withReadLock( + onPendingRecovery: { + #expect(!FileTransaction.recoveryDiagnostic(store: owner).requiresOwner) + }, { Issue.record("expected finalized cleanup diagnostic") }) + #expect(try FileSnapshot.read(at: f.root) == before) + #expect(throws: CoreError.transactionRecovered(owner.directory.path)) { try owner.withLock {} } + #expect( + try Data(contentsOf: target.url.appendingPathComponent("SKILL.md")) + == Data("later generation".utf8)) + #expect(!FileManager.default.fileExists(atPath: alias.appendingPathComponent("skills").path)) + } +} + +extension CoordinationAdmissionTests { + @Test func legacyLoaderReplacementAndArbitraryPayloadCannotExpandAuthority() throws { + let f = try TransactionFixture() + let first = f.root.appendingPathComponent("home/.claude") + let other = f.root.appendingPathComponent("other-loader") + for parent in [first, other] { + try FileManager.default.createDirectory( + at: parent.appendingPathComponent("skills"), withIntermediateDirectories: true) + } + let alias = f.root.appendingPathComponent(".claude") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: first) + let target = try f.store.skillInstallationTarget(for: .claudeCode, named: "example") + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: other) + let before = try FileSnapshot.read(at: f.root) + #expect(throws: CoreError.self) { + try f.store.withLock(installations: [target]) { + Issue.record("stale authority must not deliver a callback") + } + } + #expect(try FileSnapshot.read(at: f.root) == before) + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: first) + try f.store.withLock(installations: [target]) { + #expect(throws: CoreError.self) { + try FileTransaction(store: f.store).replaceSkill(target, with: .data(Data())) + } + } + #expect(throws: CoreError.self) { + try f.store.skillInstallationTarget(for: .claudeCode, named: "../escape") + } + } +} + +private struct AdmissionBindings: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + throw CoreError.invalidState("no binding was requested") + } +} diff --git a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift index 13417b0..4f5fe49 100644 --- a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift +++ b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift @@ -345,12 +345,17 @@ struct RegisteredNativeTargetTests { environment: RuntimeEnvironment( projectDirectory: fixture.root, homeDirectory: fixture.root.appendingPathComponent("home"), environment: ["CODEX_HOME": root.path])) + #expect(throws: CoreError.self) { + try store.withLock { + let transaction = FileTransaction(store: store) + try transaction.replace(root.appendingPathComponent("config.toml"), with: .data(Data())) + } + } try store.withLock(footprint: [.codexMCPProject]) { let target = try store.nativeTarget(for: .codexMCPProject) let transaction = FileTransaction(store: store) - #expect(throws: CoreError.self) { - try transaction.replace(target.url, with: .data(Data("owned region".utf8))) - } + try transaction.replace(target.url, with: .data(Data("owned region".utf8))) + try transaction.commit() } try store.withLock(footprint: [.codexMCPUser]) { let target = try store.nativeTarget(for: .codexMCPUser) @@ -679,10 +684,16 @@ extension RegisteredNativeTargetTests { collidingEnvironment.environment["CLAUDE_CONFIG_DIR"] = fixture.root.appendingPathComponent(".claude").path let colliding = StateStore(scope: .project, environment: collidingEnvironment) + let collidingRoute = try NativeTargetRoute.named(.claudeAgent, scope: .project, name: "example") + let collidingTarget = try colliding.nativeTarget(for: collidingRoute) + #expect(collidingTarget.path == collidingRoute.root + "/" + collidingRoute.basename) + #expect(try FileSnapshot.read(at: fixture.root) == beforeRefusal) #expect(throws: CoreError.self) { - try colliding.nativeTarget(for: .named(.claudeAgent, scope: .project, name: "example")) + try colliding.withLock { + try FileTransaction(store: colliding).replace(collidingTarget.url, with: .data(Data())) + } } - #expect(try FileSnapshot.read(at: fixture.root) == beforeRefusal) + #expect(!FileManager.default.fileExists(atPath: collidingTarget.url.path)) let linkParent = fixture.config.appendingPathComponent("commands") try FileManager.default.createSymbolicLink(at: linkParent, withDestinationURL: fixture.root) let user = StateStore(scope: .user, environment: fixture.store.environment) diff --git a/Tests/StateTestProcess/PrivateMaterializationProbe.swift b/Tests/StateTestProcess/PrivateMaterializationProbe.swift index e8be40e..c94bdf6 100644 --- a/Tests/StateTestProcess/PrivateMaterializationProbe.swift +++ b/Tests/StateTestProcess/PrivateMaterializationProbe.swift @@ -9,6 +9,16 @@ func privateMaterializationProbe( _ command: String, store: StateStore, checkpoint: @escaping (String) throws -> Void ) throws { let root = store.environment.projectDirectory + if command.hasPrefix("private-legacy-") { + let target = try store.skillInstallationTarget(for: .claudeCode, named: "private-fixture") + try store.withLock(checkpoint: checkpoint, installations: [target]) { + try Data().write(to: root.appendingPathComponent("legacy-callback")) + let transaction = FileTransaction(store: store, checkpoint: checkpoint) + try transaction.replaceSkill(target, with: .copy(root.appendingPathComponent("new"))) + try transaction.commit() + } + return + } if command.hasPrefix("private-tree-") { if command == "private-tree-recover" { do { try store.withLock(checkpoint: checkpoint, {}) } catch CoreError.transactionRecovered {} From c285b2647286232f9e65a4d5353f62398d1bd774 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:13:53 +0800 Subject: [PATCH 112/171] feat: preserve native array continuity --- Sources/NativeDocuments/Model.swift | 42 +++- Sources/NativeDocuments/NativeDocument.swift | 151 ++++++++++- Sources/NativeDocuments/Semantics.swift | 25 +- .../ArrayAuthorityTests.swift | 238 ++++++++++++++++++ 4 files changed, 443 insertions(+), 13 deletions(-) create mode 100644 Tests/NativeDocumentsTests/ArrayAuthorityTests.swift diff --git a/Sources/NativeDocuments/Model.swift b/Sources/NativeDocuments/Model.swift index 3e20bbf..92bb7db 100644 --- a/Sources/NativeDocuments/Model.swift +++ b/Sources/NativeDocuments/Model.swift @@ -54,10 +54,9 @@ package enum NativePathStep: Equatable { package struct NativeOccurrenceEvidence: Equatable { package let idKey: String? package let id: String? - /// Versioned format owners may retain these semantic fingerprints and neighbor evidence. - /// They contain no byte offsets and do not authorize adoption of an observed occurrence. - /// Fingerprints contain value bytes: secret-bearing matches stay in E/D's private plan, - /// while only non-secret semantic evidence may enter a versioned locked layout. + /// Ephemeral semantic fingerprints contain value bytes and never grant adoption. + /// Keep the complete occurrence evidence in the current private operation; persisted + /// positions use versioned array digests or D-validated opaque private array tokens. package let snapshot: Data? /// Insertion ownership pins the complete semantic array and its position. Changed arrays /// require fresh evidence from an authorized same-snapshot prepare, never duplicate reselection. @@ -154,6 +153,37 @@ package enum NativeRegionEdit { } } +/// Versioned native semantics, not a NativeValue projection. The caller decides whether +/// this digest is public-safe; private-array digests belong only in D's private receipt. +package struct NativeArrayDigest: Equatable, CustomStringConvertible, CustomDebugStringConvertible { + package static let currentFormat = "native-array@1" + package let format: String + package let digest: String + package init(format: String, digest: String) { + self.format = format + self.digest = digest + } + package var description: String { "Native array semantic evidence." } + package var debugDescription: String { description } +} + +/// Index refers to the caller's retaining observations. Nil means that the admitted edit +/// removed the region or replaced its ancestry, so its old authority cannot be rematched. +package struct NativeRegionRemap { + package let index: Int + package let observation: NativeObservation? +} + +/// Index refers to trackingArrays. A present final region/digest does not confer ownership. +/// Only canRetainToken proves unchanged structure, durable address and exact semantics. +/// All fields remain private-operation evidence until E/D classify and encode them. +package struct NativeArrayTransition { + package let index: Int + package let region: NativeRegion? + package let digest: NativeArrayDigest? + package let canRetainToken: Bool +} + package struct PreparedNativeChange { package let bytes: Data package let changedRegions: [NativeRegion] @@ -161,6 +191,8 @@ package struct PreparedNativeChange { package let createdContainers: [NativeRegion] /// Input edit index associates each inserted owner with its final, rematchable observation. package let appendedOccurrences: [NativeAppendedOccurrence] + package let survivingRegions: [NativeRegionRemap] + package let arrayTransitions: [NativeArrayTransition] } package struct NativeAppendedOccurrence { @@ -178,6 +210,8 @@ struct Member { final class Node { enum Kind: String { case object, array, string, integer, decimal, boolean, null, atom } + // Parsed document nodes are immutable; expected edit copies never inherit this cache. + var cachedArrayDigest: NativeArrayDigest? var kind: Kind var text: String var raw: String diff --git a/Sources/NativeDocuments/NativeDocument.swift b/Sources/NativeDocuments/NativeDocument.swift index 1a2d528..f6f870f 100644 --- a/Sources/NativeDocuments/NativeDocument.swift +++ b/Sources/NativeDocuments/NativeDocument.swift @@ -63,7 +63,53 @@ package struct NativeDocument { } } - package func prepare(_ edits: [NativeRegionEdit]) throws -> PreparedNativeChange { + /// Hashes the full native array with bounded, versioned semantics. No value-bearing + /// fingerprint bytes escape this operation; callers must keep private digests private. + package func arrayDigest(_ region: NativeRegion) throws -> NativeArrayDigest { + try translated { + guard let array = try resolve(region, on: root), array.kind == .array else { + throw NativeDocumentError.ownershipMismatch(region) + } + return try array.arrayDigest(budget) + } + } + + /// Validates the entire same-preimage array before selecting any persisted ordinal. + /// Returned selectors contain private snapshots and remain ephemeral, never ledger data. + package func validatedOccurrences( + in region: NativeRegion, matching digest: NativeArrayDigest, ordinals: [Int] + ) throws -> [NativeRegion] { + try translated { + try budget.check() + guard digest.format.utf8.elementsEqual(NativeArrayDigest.currentFormat.utf8), + digest.digest.utf8.count == 64, + digest.digest.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }), + let array = try resolve(region, on: root), array.kind == .array, + try array.arrayDigest(budget) == digest + else { throw NativeDocumentError.ownershipMismatch(region) } + for ordinal in ordinals { + try budget.step() + guard ordinal >= 0 && ordinal < array.elements.count else { + throw NativeDocumentError.ownershipMismatch(region) + } + } + let snapshot = try array.fingerprint(budget) + var result: [NativeRegion] = [] + for ordinal in ordinals { + try budget.allocate(region.steps.count + 2, stage: "validated occurrence") + let evidence = try insertionEvidence(in: array, ordinal: ordinal, arraySnapshot: snapshot) + result.append(NativeRegion(region.steps + [.occurrence(evidence)])) + } + return result + } + } + + /// retaining contains fresh, already authorized observations; trackingArrays contains + /// every admitted receipt array, including foreign scopes. Neither input grants authority. + package func prepare( + _ edits: [NativeRegionEdit], retaining: [NativeObservation] = [], + trackingArrays: [NativeRegion] = [] + ) throws -> PreparedNativeChange { try translated { try budget.check() var addresses: [[AddressStep]] = [] @@ -116,6 +162,30 @@ package struct NativeDocument { } addresses.append(address) } + var retainedAddresses: [[AddressStep]] = [] + for observation in retaining { + try budget.step(observation.fingerprint.count) + guard let node = try resolve(observation.region, on: root), + try node.fingerprint(budget) == observation.fingerprint + else { throw NativeDocumentError.ownershipMismatch(observation.region) } + try budget.allocate(1, stage: "retained region address") + retainedAddresses.append(try address(observation.region)) + } + var arrayAddresses: [[AddressStep]] = [] + var arrayDigests: [NativeArrayDigest] = [] + for region in trackingArrays { + let path = try address(region) + for previous in arrayAddresses { + try budget.step(path.reduce(0) { $0 + $1.work } + previous.reduce(0) { $0 + $1.work }) + guard path != previous else { throw NativeDocumentError.ownershipMismatch(region) } + } + guard let array = try resolve(region, on: root), array.kind == .array else { + throw NativeDocumentError.ownershipMismatch(region) + } + try budget.allocate(path.count + 2, stage: "tracked array") + arrayAddresses.append(path) + arrayDigests.append(try array.arrayDigest(budget)) + } if !edits.isEmpty && !located { throw NativeDocumentError.unsupportedEdit(.syntaxNotLocated, edits[0].region, []) } @@ -125,6 +195,7 @@ package struct NativeDocument { var observed: [Int] = [] var appended: [(editIndex: Int, ordinal: Int)] = [] var removed: [([AddressStep], Int)] = [] + var effects: [(address: [AddressStep], removal: Bool, append: Bool)] = [] try budget.allocate(edits.count, stage: "native edit order") var prunes: [Int] = [] var appends: [Int] = [] @@ -285,6 +356,8 @@ package struct NativeDocument { } else if desired != nil { observed.append(editIndex) } + try budget.allocate(addresses[editIndex].count + 1, stage: "native structural transition") + effects.append((addresses[editIndex], desired == nil, edit.isAppend)) removed = nextRemoved current = checked changed.append(edit.region) @@ -340,9 +413,73 @@ package struct NativeDocument { createdContainers.append(region) } } + var survivingRegions: [NativeRegionRemap] = [] + for (index, observation) in retaining.enumerated() { + let path = retainedAddresses[index] + let lost = try effects.contains { effect in + try budget.step( + path.reduce(0) { $0 + $1.work } + effect.address.reduce(0) { $0 + $1.work }) + return !effect.append && path.starts(with: effect.address) + && (effect.removal || path.count > effect.address.count) + } + var final: NativeObservation? + if !lost { + let region = try current.region( + observation.region, at: path, removed: removed, anchored: true) + if let node = try current.resolve(region, on: current.root) { + final = try current.observation(node, region: region) + } + } + try budget.allocate(1, stage: "surviving region remap") + survivingRegions.append(.init(index: index, observation: final)) + } + var arrayTransitions: [NativeArrayTransition] = [] + for (index, original) in trackingArrays.enumerated() { + let path = arrayAddresses[index] + var removedAncestor = false + var touched = false + for effect in effects { + try budget.step( + path.reduce(0) { $0 + $1.work } + effect.address.reduce(0) { $0 + $1.work }) + let ancestor = path.starts(with: effect.address) + if ancestor || effect.address.starts(with: path) { touched = true } + if ancestor && effect.removal { removedAncestor = true } + } + var region: NativeRegion? + var digest: NativeArrayDigest? + var sameAddress = true + if !removedAncestor { + let final: NativeRegion? + do { + final = try current.region(original, at: path, removed: removed, anchored: true) + } catch NativeDocumentError.ownershipMismatch { + final = nil + } + if let final, let node = try current.resolve(final, on: current.root), node.kind == .array + { + region = final + digest = try node.arrayDigest(budget) + let finalAddress = try current.address(final) + for (stepIndex, step) in original.steps.enumerated() { + if case .occurrence(let evidence) = step, evidence.idKey != nil { + if step != final.steps[stepIndex] { sameAddress = false } + } else if path[stepIndex] != finalAddress[stepIndex] { + sameAddress = false + } + } + } + } + try budget.allocate(1, stage: "array transition result") + arrayTransitions.append( + .init( + index: index, region: region, digest: digest, + canRetainToken: region != nil && !touched && sameAddress + && digest == arrayDigests[index])) + } return PreparedNativeChange( bytes: current.bytes, changedRegions: changed, observations: observations, - createdContainers: createdContainers, appendedOccurrences: appendedOccurrences) + createdContainers: createdContainers, appendedOccurrences: appendedOccurrences, + survivingRegions: survivingRegions, arrayTransitions: arrayTransitions) } } @@ -459,7 +596,7 @@ package struct NativeDocument { /// Addresses refer to the original snapshot. Only removals can shift other owned occurrences. private func region( _ original: NativeRegion, at address: [AddressStep], removed: [([AddressStep], Int)], - on startingRoot: Node? = nil + on startingRoot: Node? = nil, anchored: Bool = false ) throws -> NativeRegion { var node: Node? = startingRoot ?? root var steps: [NativePathStep] = [] @@ -494,7 +631,7 @@ package struct NativeDocument { } let element = current.elements[i] let next: NativeOccurrenceEvidence - if evidence.arraySnapshot != nil { + if evidence.arraySnapshot != nil || (anchored && evidence.idKey == nil) { next = try insertionEvidence(in: current, ordinal: i) } else if let key = evidence.idKey, let m = try element.member(key, budget: budget), element.members[m].node.kind == .string @@ -534,13 +671,15 @@ package struct NativeDocument { return false } - private func insertionEvidence(in array: Node, ordinal: Int) throws -> NativeOccurrenceEvidence { + private func insertionEvidence(in array: Node, ordinal: Int, arraySnapshot: Data? = nil) throws + -> NativeOccurrenceEvidence + { .init( snapshot: try array.elements[ordinal].fingerprint(budget), ordinal: ordinal, previous: ordinal > 0 ? try array.elements[ordinal - 1].fingerprint(budget) : nil, next: ordinal + 1 < array.elements.count ? try array.elements[ordinal + 1].fingerprint(budget) : nil, - arraySnapshot: try array.fingerprint(budget)) + arraySnapshot: try arraySnapshot ?? array.fingerprint(budget)) } func occurrence(_ evidence: NativeOccurrenceEvidence, in node: Node, region: NativeRegion) throws diff --git a/Sources/NativeDocuments/Semantics.swift b/Sources/NativeDocuments/Semantics.swift index 5ee9d09..f608b21 100644 --- a/Sources/NativeDocuments/Semantics.swift +++ b/Sources/NativeDocuments/Semantics.swift @@ -25,7 +25,7 @@ extension Node { return try budget.equal(text, other.text) } - func fingerprint(_ budget: NativeDocumentBudget) throws -> Data { + func fingerprint(_ budget: NativeDocumentBudget, exactScalars: Bool = false) throws -> Data { var data = Data() func append(_ text: String) throws { try budget.allocate(text.utf8.count + 24, stage: "observation") @@ -49,23 +49,42 @@ extension Node { } for m in sorted { try append(m.key) - let child = try m.node.fingerprint(budget) + let child = try m.node.fingerprint(budget, exactScalars: exactScalars) try budget.allocate(child.count, stage: "observation subtree") data.append(child) } } else if kind == .array { try append(String(elements.count)) for e in elements { - let child = try e.fingerprint(budget) + let child = try e.fingerprint(budget, exactScalars: exactScalars) try budget.allocate(child.count, stage: "observation subtree") data.append(child) } } else { try append(text) + if exactScalars { + if kind == .integer || kind == .decimal { try append(raw) } + if kind == .atom { try append(atomType ?? "nativeAtom") } + } } return data } + func arrayDigest(_ budget: NativeDocumentBudget) throws -> NativeArrayDigest { + try budget.check() + if let cachedArrayDigest { return cachedArrayDigest } + let semantic = try fingerprint(budget, exactScalars: true) + let domain = NativeArrayDigest.currentFormat + "\0" + try budget.allocate(domain.utf8.count + semantic.count + 192, stage: "native array digest") + try budget.step(domain.utf8.count + semantic.count) + var bytes = Data(domain.utf8) + bytes.append(semantic) + let result = NativeArrayDigest( + format: NativeArrayDigest.currentFormat, digest: FileHash.sha256Hex(data: bytes)) + cachedArrayDigest = result + return result + } + func projectionFailure(_ budget: NativeDocumentBudget) throws -> NativeProjectionFailure? { try budget.step() if kind == .atom { return .nativeType(atomType ?? "nativeAtom") } diff --git a/Tests/NativeDocumentsTests/ArrayAuthorityTests.swift b/Tests/NativeDocumentsTests/ArrayAuthorityTests.swift new file mode 100644 index 0000000..b5a84cf --- /dev/null +++ b/Tests/NativeDocumentsTests/ArrayAuthorityTests.swift @@ -0,0 +1,238 @@ +import Foundation +import NativeDocuments +import Testing + +@Suite("Native array semantic authority") +struct ArrayAuthorityTests { + @Test func nativeDigestPinsKindsLexemesDecodedBytesAndObjectOrdering() throws { + let base = try document(#"{"a":[1,"x",true,null]}"#, .json) + let digest = try base.arrayDigest(keyRegion("a")) + #expect(digest.format == "native-array@1") + #expect(digest.digest == "ca94654645dcd00338f30082bb9324bc2af825a26709c3507da05b9215d932fb") + let trivia = try document( + #"{/* retained */"a":[1,"\u0078",true,null,]}"#, .jsonc(trailingCommas: true)) + #expect(try trivia.arrayDigest(keyRegion("a")) == digest) + for changed in [#"[1.0,"x",true,null]"#, #"[1e0,"x",true,null]"#, #"[1,"x",null,true]"#] { + #expect(try document("{\"a\":" + changed + "}", .json).arrayDigest(keyRegion("a")) != digest) + } + let ordered = try document(#"{"a":[{"z":1,"a":2}]}"#, .json) + let reordered = try document(#"{"a":[{"a":2,"z":1}]}"#, .json) + #expect(try ordered.arrayDigest(keyRegion("a")) == reordered.arrayDigest(keyRegion("a"))) + let composed = try document("{\"a\":[{\"é\":1}]}", .json) + let decomposed = try document("{\"a\":[{\"e\u{301}\":1}]}", .json) + #expect(try composed.arrayDigest(keyRegion("a")) != decomposed.arrayDigest(keyRegion("a"))) + let collision = try document("{\"a\":[{\"é\":1,\"e\u{301}\":2}]}", .json) + #expect(try collision.read(keyRegion("a"))?.value == nil) + #expect(try collision.arrayDigest(keyRegion("a")).digest.count == 64) + let hex = try document("a=[0x10,1979-05-27,nan]\n") + let decimal = try document("a=[16,1979-05-27,nan]\n") + #expect(try hex.arrayDigest(keyRegion("a")) != decimal.arrayDigest(keyRegion("a"))) + let ids = try document("{\"a\":[{\"id\":\"é\",\"n\":1},{\"id\":\"e\u{301}\",\"n\":2}]}", .json) + for (id, value) in [("é", 1), ("e\u{301}", 2)] { + let region = NativeRegion([.key("a"), .occurrence(.init(idKey: "id", id: id)), .key("n")]) + #expect(try ids.read(region)?.value == .integer(value)) + } + #expect(!String(describing: digest).contains(digest.digest)) + #expect(!String(reflecting: digest).contains(digest.digest)) + } + + @Test func persistedDigestValidatesWholePreimageBeforeDuplicateOrdinalSelection() throws { + let source = #"{"a":["same","same","same","same","same"]}"# + let original = try document(source, .json) + let array = keyRegion("a") + let digest = try original.arrayDigest(array) + let regions = try original.validatedOccurrences(in: array, matching: digest, ordinals: [2, 4]) + #expect(regions.count == 2) + #expect(try original.read(regions[0])?.value == .string("same")) + for invalid in [ + NativeArrayDigest(format: "native-array@2", digest: digest.digest), + NativeArrayDigest(format: digest.format, digest: String(repeating: "0", count: 64)), + NativeArrayDigest(format: digest.format, digest: "PRIVATE_VALUE"), + ] { + do { + _ = try original.validatedOccurrences(in: array, matching: invalid, ordinals: [2]) + Issue.record("unvalidated persisted evidence selected an occurrence") + } catch let error as NativeDocumentError { + #expect(!error.description.contains("PRIVATE_VALUE")) + #expect(!error.description.contains(digest.digest)) + } + } + for index in [-1, 5] { + #expect(throws: NativeDocumentError.self) { + try original.validatedOccurrences(in: array, matching: digest, ordinals: [index]) + } + } + let changed = try document(#"{"a":["same","same","same","same","changed"]}"#, .json) + #expect(throws: NativeDocumentError.self) { + try changed.validatedOccurrences(in: array, matching: digest, ordinals: [2]) + } + let all = try original.validatedOccurrences(in: array, matching: digest, ordinals: [0, 2, 4]) + let retained = try [all[1], all[2]].map { try #require(try original.read($0)) } + let prepared = try original.prepare( + [ + .remove(region: all[0], expected: owned(original, all[0])), + .append(region: array, expected: owned(original, array), value: .string("same")), + ], retaining: retained, trackingArrays: [array]) + let fresh = try NativeDocument(bytes: prepared.bytes, format: .json, budget: generousBudget()) + #expect(try fresh.arrayDigest(array) == digest) + // Equal final values cannot preserve foreign ordinal authority after remove/append. + #expect(!prepared.arrayTransitions[0].canRetainToken) + let first = try #require(prepared.survivingRegions[0].observation) + let second = try #require(prepared.survivingRegions[1].observation) + guard case .occurrence(let a) = first.region.steps.last, + case .occurrence(let b) = second.region.steps.last + else { + Issue.record("missing remaps") + return + } + #expect(a.ordinal == 1 && b.ordinal == 3) + let removed = try fresh.prepare( + [.remove(region: first.region, expected: .owned(first))], retaining: [second]) + #expect(removed.survivingRegions[0].observation != nil) + #expect(throws: NativeDocumentError.self) { + try changed.prepare([], retaining: retained) + } + } + + @Test func siblingChangesPreservePrivateArrayContinuityAndDescendantChangesRotateIt() throws { + let original = try document( + #"{/* private sibling */"a":[{"secret":"PRIVATE"}],"b":["UNSELECTED"],"other":1}"#, + .jsonc(trailingCommas: false) + ) + let array = keyRegion("a") + let digest = try original.arrayDigest(array) + let selected = try original.validatedOccurrences(in: array, matching: digest, ordinals: [0])[0] + let observation = try #require(try original.read(selected)) + let sibling = try original.prepare( + [ + .put( + region: keyRegion("other"), expected: owned(original, keyRegion("other")), + value: .integer(2)) + ], retaining: [observation], trackingArrays: [array, keyRegion("b")]) + #expect(sibling.arrayTransitions[0].canRetainToken) + #expect(sibling.arrayTransitions[0].digest == digest) + #expect(sibling.arrayTransitions[1].index == 1) + #expect(sibling.arrayTransitions[1].canRetainToken) + #expect(text(sibling).contains("/* private sibling */")) + let secret = NativeRegion(selected.steps + [.key("secret")]) + let updated = try original.prepare( + [ + .put(region: secret, expected: owned(original, secret), value: .string("CHANGED")) + ], retaining: [observation], trackingArrays: [array, keyRegion("b")]) + #expect(!updated.arrayTransitions[0].canRetainToken) + #expect(updated.arrayTransitions[0].digest != digest) + #expect(updated.arrayTransitions[1].canRetainToken) + #expect( + updated.survivingRegions[0].observation?.value == .object(["secret": .string("CHANGED")])) + #expect(throws: NativeDocumentError.self) { + try original.prepare([], trackingArrays: [array, array]) + } + } + + @Test func ancestorReplacementAndArrayRemovalCannotContinueEqualAuthority() throws { + let original = try document(#"{"parent":{"a":[1],"other":true}}"#, .json) + let parent = keyRegion("parent") + let array = keyRegion("parent", "a") + let old = try #require(try original.read(array)) + let replacement = try original.prepare( + [ + .put( + region: parent, expected: owned(original, parent), + value: .object(["a": .array([.integer(1)]), "other": .boolean(false)])) + ], retaining: [old], trackingArrays: [array]) + #expect(try replacement.arrayTransitions[0].digest == original.arrayDigest(array)) + #expect(!replacement.arrayTransitions[0].canRetainToken) + #expect(replacement.survivingRegions[0].observation == nil) + let noOp = try original.prepare( + [ + .put( + region: parent, expected: owned(original, parent), + value: .object(["a": .array([.integer(1)]), "other": .boolean(true)])) + ], retaining: [old], trackingArrays: [array]) + #expect(noOp.bytes == original.bytes) + #expect(noOp.arrayTransitions[0].canRetainToken) + let removed = try original.prepare( + [.remove(region: array, expected: .owned(old))], retaining: [old], trackingArrays: [array]) + #expect(removed.arrayTransitions[0].region == nil) + #expect(removed.arrayTransitions[0].digest == nil) + #expect(removed.survivingRegions[0].observation == nil) + #expect(throws: NativeDocumentError.self) { + try original.prepare([ + .remove(region: array, expected: .owned(old)), + .put(region: array, expected: .owned(old), value: .array([.integer(1)])), + ]) + } + } + + @Test func movedPositionalAncestorsRotateButStableNativeIDsKeepTheirAddress() throws { + for stable in [false, true] { + let original = try document(#"{"items":[{"id":"first"},{"id":"second","a":[1]}]}"#, .json) + let items = keyRegion("items") + let occurrences = try #require(try original.read(items)).occurrences + let first = NativeRegion(items.steps + [.occurrence(occurrences[0])]) + let second = NativeRegion( + items.steps + [.occurrence(stable ? .init(idKey: "id", id: "second") : occurrences[1])]) + let array = NativeRegion(second.steps + [.key("a")]) + let prepared = try original.prepare( + [.remove(region: first, expected: owned(original, first))], trackingArrays: [array]) + #expect(prepared.arrayTransitions[0].canRetainToken == stable) + let fresh = try NativeDocument(bytes: prepared.bytes, format: .json, budget: generousBudget()) + #expect( + try fresh.read(#require(prepared.arrayTransitions[0].region))?.value + == .array([.integer(1)])) + } + } + + @Test func conditionalPruningReportsArrayDisappearanceAndSurvivorRemoval() throws { + let original = try document(#"{"a":[1],"keep":true}"#, .json) + let array = keyRegion("a") + let digest = try original.arrayDigest(array) + let element = try original.validatedOccurrences(in: array, matching: digest, ordinals: [0])[0] + let observed = try #require(try original.read(element)) + let prepared = try original.prepare( + [ + .remove(region: element, expected: .owned(observed)), + .pruneCreatedContainer(region: array, observed: #require(try original.read(array))), + ], retaining: [observed], trackingArrays: [array]) + #expect(text(prepared) == #"{"keep":true}"#) + #expect(prepared.arrayTransitions[0].region == nil) + #expect(!prepared.arrayTransitions[0].canRetainToken) + #expect(prepared.survivingRegions[0].observation == nil) + } + + @Test func nativeAtomArraysRetainContinuityWithoutProjectingTheirValues() throws { + let original = try document("a=[1979-05-27,nan] # native atoms\nother=1\n") + let array = keyRegion("a") + let digest = try original.arrayDigest(array) + let region = try original.validatedOccurrences(in: array, matching: digest, ordinals: [0])[0] + let observation = try #require(try original.read(region)) + #expect(observation.value == nil) + let prepared = try original.prepare( + [ + .put( + region: keyRegion("other"), expected: owned(original, keyRegion("other")), + value: .integer(2)) + ], retaining: [observation], trackingArrays: [array]) + #expect(prepared.arrayTransitions[0].canRetainToken) + #expect(prepared.arrayTransitions[0].digest == digest) + #expect(prepared.survivingRegions[0].observation?.nativeKind == "dateTime") + #expect(text(prepared).contains("a=[1979-05-27,nan] # native atoms\n")) + } + + @Test func repeatedDigestQueriesShareBudgetAndCancellationStillApplies() throws { + var cancelled = false + let budget = NativeDocumentBudget( + limits: .init( + storage: 2_000_000, work: 200_000, nodes: 10_000, depth: 64, uninterruptedBytes: 1_000_000), + cancellation: { cancelled }) + let source = "{\"a\":[\"" + String(repeating: "x", count: 4096) + "\"]}" + let original = try NativeDocument(bytes: Data(source.utf8), format: .json, budget: budget) + let digest = try original.arrayDigest(keyRegion("a")) + for _ in 0..<100 { #expect(try original.arrayDigest(keyRegion("a")) == digest) } + cancelled = true + do { + _ = try original.arrayDigest(keyRegion("a")) + Issue.record("cached digest bypassed cancellation") + } catch NativeDocumentError.cancelled {} + } +} From 5b275d81edb6a7feee983e335caedb159a6f0dd4 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:14:08 +0800 Subject: [PATCH 113/171] feat: preserve private native array continuity --- Sources/AgentsCore/FileTransaction.swift | 53 ++- .../AgentsCore/LedgerDisplayEvidence.swift | 4 +- .../AgentsCore/PrivateMaterialization.swift | 62 ++- Sources/AgentsCore/PrivateNativeArrays.swift | 215 +++++++++ .../AgentsCore/TransactionPublication.swift | 24 +- Sources/AgentsCore/TransactionSession.swift | 15 + .../NativeArrayReceiptTests.swift | 437 ++++++++++++++++++ .../PrivateMaterializationProbe.swift | 9 +- 8 files changed, 793 insertions(+), 26 deletions(-) create mode 100644 Sources/AgentsCore/PrivateNativeArrays.swift create mode 100644 Tests/AgentsCoreTests/NativeArrayReceiptTests.swift diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 8aeb943..3397f02 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -31,7 +31,7 @@ package final class FileTransaction { let source: Source? let expectation: Expectation let security: TransactionSecurity - let privateData: (() throws -> Data)? + let privateData: (() throws -> PrivateMaterializationResult)? var privateTree: PrivateTree? = nil var installs: Bool { source != nil || security.replacement == .privateMaterialization } } @@ -58,7 +58,8 @@ package final class FileTransaction { /// `expectedHash` and `executableFlags` describe the content's tree hash and execute bits. package func replace( _ destination: URL, with source: Source, expectedHash: String? = nil, - executableFlags: [String: Bool]? = nil, expecting: TargetPrecondition? = nil + executableFlags: [String: Bool]? = nil, expecting: TargetPrecondition? = nil, + nativeArrayTransitions: [PrivateNativeArrayTransition]? = nil ) throws { if let expectedHash { try StateValidation.digest(expectedHash) } let (path, evidence, previous) = try request(destination, expecting: expecting) @@ -106,8 +107,12 @@ package final class FileTransaction { requests.append( Request( path: path, evidence: evidence, source: nil, expectation: expectation, - security: security, privateData: { data })) + security: security, + privateData: { .init(bytes: data, nativeArrayTransitions: nativeArrayTransitions) })) } else { + guard nativeArrayTransitions == nil else { + throw CoreError.invalidState("array tracking requires private materialization") + } requests.append( Request( path: path, evidence: evidence, source: source, expectation: expectation, @@ -153,7 +158,8 @@ package final class FileTransaction { } package func delete(_ destination: URL, expecting: TargetPrecondition? = nil) throws { - let (path, evidence, security) = try request(destination, expecting: expecting) + let (path, evidence, security) = try request( + destination, expecting: expecting, allowMissingNativeArrays: true) requests.append( Request( path: path, evidence: evidence, source: nil, expectation: .init(), security: security, @@ -165,6 +171,19 @@ package final class FileTransaction { _ prepared: PreparedPrivateMaterialization, bindings: Set = [], provider: any RuntimeBindingProvider, render: @escaping (RuntimeBindingValues) throws -> Data + ) throws { + try replacePrivate( + prepared, bindings: bindings, provider: provider, + produce: { + .init(bytes: try render($0)) + }) + } + + /// Actual bytes and same-edit array transitions are resolved only in verified private staging. + package func replacePrivate( + _ prepared: PreparedPrivateMaterialization, bindings: Set = [], + provider: any RuntimeBindingProvider, + produce: @escaping (RuntimeBindingValues) throws -> PrivateMaterializationResult ) throws { guard NativeTargetRoute.targetRoute(prepared.target.path)?.isContainer != true, prepared.target.scope.path == store.directory.path, prepared.owner == geteuid(), @@ -175,7 +194,8 @@ package final class FileTransaction { "private publication requires an existing admitted native parent") } try receiptEvidence.validate() - let (path, evidence, previous) = try request(prepared.target.url, expecting: prepared.evidence) + let (path, evidence, previous) = try request( + prepared.target.url, expecting: prepared.evidence, allowMissingNativeArrays: true) guard path == prepared.target.path else { throw CoreError.invalidState("materialization registration changed") } @@ -196,7 +216,7 @@ package final class FileTransaction { for name in bindings.sorted() { values[name] = try provider.value(for: name, environment: environment) } - return try render(RuntimeBindingValues(values)) + return try produce(RuntimeBindingValues(values)) } catch { throw CoreError.invalidState( "private materialization could not resolve or render its bindings") @@ -215,7 +235,8 @@ package final class FileTransaction { else { throw CoreError.invalidState("private tree requires its prepared registered container") } let tree = try PrivateTree(entries: entries, provider: provider, environment: store.environment) try receipt.validate() - let (path, evidence, previous) = try request(prepared.target.url, expecting: prepared.evidence) + let (path, evidence, previous) = try request( + prepared.target.url, expecting: prepared.evidence, allowMissingNativeArrays: true) guard path.utf8.elementsEqual(prepared.target.path.utf8) else { throw CoreError.invalidState("materialization registration changed") } @@ -279,7 +300,9 @@ package final class FileTransaction { for evidence in unchanged { try evidence.validate(excludingTargets: targetPaths) } } - private func request(_ destination: URL, expecting: TargetPrecondition?) throws -> ( + private func request( + _ destination: URL, expecting: TargetPrecondition?, allowMissingNativeArrays: Bool = false + ) throws -> ( path: String, evidence: TargetPrecondition, security: TransactionSecurity ) { let path = try TransactionPaths(store: store).path( @@ -333,7 +356,12 @@ package final class FileTransaction { throw CoreError.invalidState("materialization receipt root changed") } // A known absence has no sensitive preimage; its receipt is reconciled in this journal. - guard evidence.snapshot != nil else { return (path, evidence, security) } + guard evidence.snapshot != nil else { + guard record.nativeArrays == nil || allowMissingNativeArrays else { + throw CoreError.invalidState("tracked native file is missing its receipted preimage") + } + return (path, evidence, security) + } guard evidence.snapshot?.digest == record.digest, evidence.snapshot?.identity == record.access.identity else { throw CoreError.invalidState("materialized preimage differs from its receipt") } @@ -415,12 +443,15 @@ package final class FileTransaction { previous: state.records, targetRoot: NativeTargetRoute.metadataRoute(state.path)?.root)) try LedgerAdmission.check(bytes, limits: .standard) - return bytes + return .init(bytes: bytes) } } else { + let key = try store.materializationReceiptKey(for: request.path) + let previous = receiptStates.values.compactMap { $0.records.targets[key] }.first try session.stage( index, source: request.source, expectation: request.expectation, - privateData: request.privateData, privateTree: request.privateTree) + privateData: request.privateData, privateTree: request.privateTree, + previousReceipt: previous) } } try session.emit(.preconditions) diff --git a/Sources/AgentsCore/LedgerDisplayEvidence.swift b/Sources/AgentsCore/LedgerDisplayEvidence.swift index baa3781..93fe2c2 100644 --- a/Sources/AgentsCore/LedgerDisplayEvidence.swift +++ b/Sources/AgentsCore/LedgerDisplayEvidence.swift @@ -32,10 +32,10 @@ extension TargetPrecondition { for (root, before) in TransactionLockContext.currentForDisplay?.createdAncestry ?? [] { let parent = physicalURL.deletingLastPathComponent().path if parent.utf8.elementsEqual(root.path.utf8) || parent.hasPrefix(root.path + "/") { - guard ancestry.starts(with: before.directories) else { + guard access.ancestry.directories.starts(with: before.directories) else { throw CoreError.invalidState("existing publication ancestry access changed") } - ancestry = before.directories + if before.directories.count < ancestry.count { ancestry = before.directories } } } return try ResolvedLedgerCodec.digest( diff --git a/Sources/AgentsCore/PrivateMaterialization.swift b/Sources/AgentsCore/PrivateMaterialization.swift index a14208a..ad0fe9f 100644 --- a/Sources/AgentsCore/PrivateMaterialization.swift +++ b/Sources/AgentsCore/PrivateMaterialization.swift @@ -48,11 +48,12 @@ package struct PrivateTreeAccessChange { package let mode: UInt32 } -/// A local receipt view has no payload digest or serializable binding data. +/// Package-only physical evidence. Array semantic digests remain private to the materializer. package struct MaterializationReceipt { package let generation: UUID package let access: FileAccessEvidence package let treeAccess: [TreeMemberAccess]? + package let nativeArrays: [PrivateNativeArrayRecord]? } package struct PreparedPrivateMaterialization { @@ -72,7 +73,7 @@ package struct PreparedPrivateMaterialization { let input = PrivateAccessFingerprint( target: target.path, owner: owner, publicationAccess: try evidence.displayEvidence(includeContent: false), - permissionChange: accessChange != nil, receiptGeneration: receiptGeneration, + permissionChange: accessChange != nil, members: preimageTreeAccess) return "sha256:" + FileHash.sha256Hex(data: try StateStore.encode(input)) } @@ -84,7 +85,6 @@ private struct PrivateAccessFingerprint: Encodable { let owner: UInt32 let publicationAccess: String let permissionChange: Bool - let receiptGeneration: UUID? let members: [TreeMemberAccess]? } @@ -121,7 +121,8 @@ extension StateStore { } _ = try preparePrivateMaterialization(target, expecting: record.generation) return MaterializationReceipt( - generation: record.generation, access: record.access, treeAccess: record.treeAccess) + generation: record.generation, access: record.access, treeAccess: record.treeAccess, + nativeArrays: record.nativeArrays) } /// Under the caller's scope lock, preparation never calls a provider or renderer. @@ -246,10 +247,55 @@ struct MaterializationReceipts: Codable { let digest: String let access: FileAccessEvidence var treeAccess: [TreeMemberAccess]? = nil + var nativeArrays: [PrivateNativeArrayRecord]? = nil + + private enum CodingKeys: String, CodingKey { + case generation, rootIdentity, digest, access, treeAccess, nativeArrays + } + init( + generation: UUID, rootIdentity: String, digest: String, access: FileAccessEvidence, + treeAccess: [TreeMemberAccess]? = nil, nativeArrays: [PrivateNativeArrayRecord]? = nil + ) { + self.generation = generation + self.rootIdentity = rootIdentity + self.digest = digest + self.access = access + self.treeAccess = treeAccess + self.nativeArrays = nativeArrays + } + init(from decoder: any Decoder) throws { + try ReceiptFields.require( + decoder, ["generation", "rootIdentity", "digest", "access", "treeAccess", "nativeArrays"]) + let c = try decoder.container(keyedBy: CodingKeys.self) + generation = try c.decode(UUID.self, forKey: .generation) + rootIdentity = try c.decode(String.self, forKey: .rootIdentity) + digest = try c.decode(String.self, forKey: .digest) + access = try c.decode(FileAccessEvidence.self, forKey: .access) + treeAccess = try c.decodeIfPresent([TreeMemberAccess].self, forKey: .treeAccess) + nativeArrays = try c.decodeIfPresent([PrivateNativeArrayRecord].self, forKey: .nativeArrays) + if c.contains(.nativeArrays), nativeArrays == nil { + throw CoreError.invalidState("invalid private array records") + } + } + } + private enum CodingKeys: String, CodingKey { case version, targets } + init() {} + init(from decoder: any Decoder) throws { + try ReceiptFields.require(decoder, ["version", "targets"]) + let c = try decoder.container(keyedBy: CodingKeys.self) + version = try c.decode(Int.self, forKey: .version) + targets = try c.decode([String: Record].self, forKey: .targets) + guard version == 1 || version == 2, + version != 1 || targets.values.allSatisfy({ $0.nativeArrays == nil }) + else { + throw CoreError.invalidState("unsupported materialization receipt") + } } func validate(store: StateStore) throws { - guard version == 1 else { throw CoreError.invalidState("unsupported materialization receipt") } + guard version == 1 || version == 2 else { + throw CoreError.invalidState("unsupported materialization receipt") + } for (path, record) in targets { let paths = TransactionPaths(store: store) let parts: (root: String, descendants: [String]) @@ -274,6 +320,12 @@ struct MaterializationReceipts: Codable { == (NativeTargetRoute.targetRoute(path)?.isContainer == true), !record.rootIdentity.isEmpty else { throw CoreError.invalidState("invalid materialization receipt target") } + if let arrays = record.nativeArrays { + guard version == 2, record.access.identity.kind == S_IFREG, + let route = NativeTargetRoute.targetRoute(path), !route.isContainer + else { throw CoreError.invalidState("private arrays require a registered native file") } + try PrivateNativeArrayRecord.validate(arrays) + } if let members = record.treeAccess { try TreeMemberAccess.validateStructure(members) } try StateValidation.digest("sha256:" + record.digest) } diff --git a/Sources/AgentsCore/PrivateNativeArrays.swift b/Sources/AgentsCore/PrivateNativeArrays.swift new file mode 100644 index 0000000..025a096 --- /dev/null +++ b/Sources/AgentsCore/PrivateNativeArrays.swift @@ -0,0 +1,215 @@ +import Foundation + +/// Private document coordinates, not edit instructions or filesystem authority. +package enum PrivateNativeAddressStep: Codable, Equatable, Sendable { + case key(String) + case stableID(key: String, value: String) + case position(index: Int) + + private enum CodingKeys: String, CodingKey { case kind, key, value, index } + package init(from decoder: any Decoder) throws { + let fields = try decoder.container(keyedBy: CodingKeys.self) + switch try fields.decode(String.self, forKey: .kind) { + case "key": + try ReceiptFields.require(decoder, ["kind", "key"]) + self = .key(try fields.decode(String.self, forKey: .key)) + case "stableID": + try ReceiptFields.require(decoder, ["kind", "key", "value"]) + self = .stableID( + key: try fields.decode(String.self, forKey: .key), + value: try fields.decode(String.self, forKey: .value)) + case "position": + try ReceiptFields.require(decoder, ["kind", "index"]) + self = .position(index: try fields.decode(Int.self, forKey: .index)) + default: throw CoreError.invalidState("unsupported private array address") + } + } + package func encode(to encoder: any Encoder) throws { + var fields = encoder.container(keyedBy: CodingKeys.self) + switch self { + case .key(let key): + try fields.encode("key", forKey: .kind) + try fields.encode(key, forKey: .key) + case .stableID(let key, let value): + try fields.encode("stableID", forKey: .kind) + try fields.encode(key, forKey: .key) + try fields.encode(value, forKey: .value) + case .position(let index): + try fields.encode("position", forKey: .kind) + try fields.encode(index, forKey: .index) + } + } + package static func == (a: Self, b: Self) -> Bool { + switch (a, b) { + case (.key(let a), .key(let b)): return Data(a.utf8) == Data(b.utf8) + case (.stableID(let ak, let av), .stableID(let bk, let bv)): + return Data(ak.utf8) == Data(bk.utf8) && Data(av.utf8) == Data(bv.utf8) + case (.position(let a), .position(let b)): return a == b + default: return false + } + } +} + +/// Only the private receipt encodes this evidence. Diagnostic reflection is redacted. +package struct PrivateNativeArrayRecord: Codable, Equatable, Sendable, CustomStringConvertible, + CustomDebugStringConvertible, CustomReflectable +{ + package let path: [PrivateNativeAddressStep] + package let documentFormat: String + package let token: UUID + package let semanticFormat: String + package let semanticDigest: String + package var description: String { "" } + package var debugDescription: String { description } + package var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } + + package init( + path: [PrivateNativeAddressStep], documentFormat: String, token: UUID, + semanticFormat: String = "native-array@1", semanticDigest: String + ) { + self.path = path + self.documentFormat = documentFormat + self.token = token + self.semanticFormat = semanticFormat + self.semanticDigest = semanticDigest + } + private enum CodingKeys: String, CodingKey { + case path, documentFormat, token, semanticFormat, semanticDigest + } + package init(from decoder: any Decoder) throws { + try ReceiptFields.require( + decoder, ["path", "documentFormat", "token", "semanticFormat", "semanticDigest"]) + let c = try decoder.container(keyedBy: CodingKeys.self) + path = try c.decode([PrivateNativeAddressStep].self, forKey: .path) + documentFormat = try c.decode(String.self, forKey: .documentFormat) + token = try c.decode(UUID.self, forKey: .token) + semanticFormat = try c.decode(String.self, forKey: .semanticFormat) + semanticDigest = try c.decode(String.self, forKey: .semanticDigest) + } +} + +/// E/F supplies same-edit structural proof; Core validates coverage and the sealed preimage. +package struct PrivateNativeArrayTransition { + package let previous: PrivateNativeArrayRecord? + package let current: PrivateNativeArrayRecord? + package init(previous: PrivateNativeArrayRecord?, current: PrivateNativeArrayRecord?) { + self.previous = previous + self.current = current + } +} + +/// Ephemeral actual render output. It has no encoding or payload diagnostic representation. +package struct PrivateMaterializationResult: CustomStringConvertible, CustomDebugStringConvertible, + CustomReflectable +{ + let bytes: Data + let nativeArrayTransitions: [PrivateNativeArrayTransition]? + package init(bytes: Data, nativeArrayTransitions: [PrivateNativeArrayTransition]? = nil) { + self.bytes = bytes + self.nativeArrayTransitions = nativeArrayTransitions + } + package var description: String { "" } + package var debugDescription: String { description } + package var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } +} + +/// Unknown fields, including null, are rejected before decoding receipt records. +enum ReceiptFields { + private struct Key: CodingKey { + var stringValue: String + var intValue: Int? { nil } + init?(stringValue: String) { self.stringValue = stringValue } + init?(intValue: Int) { return nil } + } + static func require(_ decoder: any Decoder, _ allowed: Set) throws { + let fields = try decoder.container(keyedBy: Key.self) + guard Set(fields.allKeys.map(\.stringValue)).isSubset(of: allowed) else { + throw CoreError.invalidState("invalid private receipt fields") + } + } +} + +extension PrivateNativeArrayRecord { + static func validate(_ records: [Self]) throws { + guard records.count <= LedgerLimits.standard.entries else { + throw CoreError.invalidState("private array records exceed limits") + } + let bytes = try StateStore.encode(records) + try LedgerAdmission.check(bytes, limits: .standard) + var paths = Set() + var tokens = Set() + for record in records { + guard ["json", "jsonc", "jsonc-trailing-commas", "toml"].contains(record.documentFormat), + record.documentFormat == records.first?.documentFormat, + record.semanticFormat == "native-array@1", + record.path.count <= LedgerLimits.standard.depth, + tokens.insert(record.token).inserted, + paths.insert(try StateStore.encode(record.path)).inserted + else { throw CoreError.invalidState("invalid private array record") } + for step in record.path { + if case .position(let index) = step, index < 0 { + throw CoreError.invalidState("invalid private array address") + } + } + guard record.semanticDigest.utf8.count == 71, + record.semanticDigest.range(of: #"^sha256:[0-9a-f]{64}$"#, options: .regularExpression) + != nil + else { + throw CoreError.invalidState("invalid private array digest") + } + } + } + + static func applying( + _ result: PrivateMaterializationResult, previous: MaterializationReceipts.Record?, + admitted: Bool, hasPreimage: Bool = true + ) throws -> [Self]? { + let old = previous?.nativeArrays ?? [] + guard let transitions = result.nativeArrayTransitions else { + guard + old.isEmpty || (hasPreimage && previous?.digest == FileHash.sha256Hex(data: result.bytes)) + else { + throw CoreError.invalidState("changed tracked file requires complete array transitions") + } + return previous?.nativeArrays + } + guard admitted else { + throw CoreError.invalidState("array transitions require a registered native file") + } + guard transitions.count <= LedgerLimits.standard.entries else { + throw CoreError.invalidState("private array transitions exceed limits") + } + var oldByToken: [UUID: Self] = [:] + for record in old { + guard oldByToken.updateValue(record, forKey: record.token) == nil else { + throw CoreError.invalidState("duplicate private array records") + } + } + var covered = Set() + var next: [Self] = [] + for transition in transitions { + guard transition.previous != nil || transition.current != nil else { + throw CoreError.invalidState("empty private array transition") + } + if let before = transition.previous { + guard oldByToken[before.token] == before, covered.insert(before.token).inserted else { + throw CoreError.invalidState( + "private array transition does not match the current receipt") + } + } + if let after = transition.current { + if let existing = oldByToken[after.token] { + guard hasPreimage, transition.previous == existing, after == existing else { + throw CoreError.invalidState("changed private array requires a new continuity token") + } + } + next.append(after) + } + } + guard covered == Set(old.map(\.token)) else { + throw CoreError.invalidState("incomplete private array transitions") + } + try validate(next) + return next.isEmpty ? nil : next + } +} diff --git a/Sources/AgentsCore/TransactionPublication.swift b/Sources/AgentsCore/TransactionPublication.swift index afc2042..1ed26f6 100644 --- a/Sources/AgentsCore/TransactionPublication.swift +++ b/Sources/AgentsCore/TransactionPublication.swift @@ -41,7 +41,9 @@ extension TransactionSession { func stage( _ index: Int, source: FileTransaction.Source?, expectation: FileTransaction.Expectation, - privateData: (() throws -> Data)? = nil, privateTree: PrivateTree? = nil + privateData: (() throws -> PrivateMaterializationResult)? = nil, + privateTree: PrivateTree? = nil, + previousReceipt: MaterializationReceipts.Record? = nil ) throws { let entry = journal.entries[index] let parent = parents[index] @@ -53,7 +55,8 @@ extension TransactionSession { if source != nil || entry.security.replacement == .privateMaterialization { let sealed = try construct( source, expectation: expectation, named: staging.name(index), index: index, - container: container, parent: parent, privateData: privateData, privateTree: privateTree) + container: container, parent: parent, privateData: privateData, privateTree: privateTree, + previousReceipt: previousReceipt) try emit(.stage(index, .constructed)) let capture = try FileSnapshot.capture(staging.name(index), from: container) try verify(source, sealed, capture: capture) @@ -84,7 +87,8 @@ extension TransactionSession { private func construct( _ source: FileTransaction.Source?, expectation: FileTransaction.Expectation, named name: String, index: Int, container: DirectoryHandle, parent: DirectoryHandle, - privateData: (() throws -> Data)?, privateTree: PrivateTree? + privateData: (() throws -> PrivateMaterializationResult)?, privateTree: PrivateTree?, + previousReceipt: MaterializationReceipts.Record? ) throws -> FileTransaction.Expectation { let entry = journal.entries[index] var expectation = expectation @@ -116,7 +120,13 @@ extension TransactionSession { try requirePreimage(index) _ = try container.requirePrivateAccess(name, matching: file.evidence) // The callback is never given a path or unverified descriptor. - let data = try privateData() + let result = try privateData() + let route = NativeTargetRoute.targetRoute(entry.path) + let arrays = try PrivateNativeArrayRecord.applying( + result, previous: previousReceipt, admitted: route != nil && route?.isContainer == false, + hasPreimage: entry.preimage != nil) + try sealNativeArrays(arrays, for: index) + let data = result.bytes try requireParent(index) let hash = "sha256:" + FileHash.sha256Hex(data: data) if let expected = expectation.hash, expected != hash { @@ -283,7 +293,7 @@ extension TransactionSession { { var records = previous - for entry in journal.entries + for (index, entry) in journal.entries.enumerated() where entry.path != "state/" + MaterializationReceipts.fileName && NativeTargetRoute.metadataRoute(entry.path) == nil { @@ -303,7 +313,9 @@ extension TransactionSession { records.targets[recordPath] = .init( generation: journal.id, rootIdentity: resource?.identity.orderingKey ?? identity, - digest: snapshot.digest, access: access, treeAccess: entry.security.stagedTreeAccess) + digest: snapshot.digest, access: access, treeAccess: entry.security.stagedTreeAccess, + nativeArrays: privateNativeArrays[index]) + if privateNativeArrays[index] != nil { records.version = 2 } } else { records.targets.removeValue(forKey: recordPath) } diff --git a/Sources/AgentsCore/TransactionSession.swift b/Sources/AgentsCore/TransactionSession.swift index 699d39a..5c96993 100644 --- a/Sources/AgentsCore/TransactionSession.swift +++ b/Sources/AgentsCore/TransactionSession.swift @@ -29,6 +29,21 @@ final class TransactionSession { } var privateTreeBytes = 0 + var privateNativeArrays: [Int: [PrivateNativeArrayRecord]] = [:] + + func sealNativeArrays(_ arrays: [PrivateNativeArrayRecord]?, for index: Int) throws { + var candidate = privateNativeArrays + candidate[index] = arrays + var count = 0 + for records in candidate.values { + guard records.count <= LedgerLimits.standard.entries - count else { + throw CoreError.invalidState("private array candidate exceeds limits") + } + count += records.count + } + try LedgerAdmission.check(StateStore.encode(candidate), limits: .standard) + privateNativeArrays = candidate + } func emit(_ point: TransactionCheckpoint) throws { try checkpoint(point.name) } diff --git a/Tests/AgentsCoreTests/NativeArrayReceiptTests.swift b/Tests/AgentsCoreTests/NativeArrayReceiptTests.swift new file mode 100644 index 0000000..6d4e871 --- /dev/null +++ b/Tests/AgentsCoreTests/NativeArrayReceiptTests.swift @@ -0,0 +1,437 @@ +import CPlatform +import Foundation +import StateTestSupport +import Synchronization +import Testing + +@testable import AgentsCore + +@Suite("Private native array continuity receipts") +struct NativeArrayReceiptTests { + private let original = Data(#"{"hooks":["private-value"],"sibling":0}"#.utf8) + private let sibling = Data(#"{"hooks":["private-value"],"sibling":1}"#.utf8) + + private func array(_ key: String = "hooks", token: UUID = UUID(), digest: String = "array") + -> PrivateNativeArrayRecord + { + .init( + path: [.key(key)], documentFormat: "json", token: token, + semanticDigest: "sha256:" + FileHash.sha256Hex(data: Data(digest.utf8))) + } + + private func install( + _ bytes: Data, arrays: [PrivateNativeArrayRecord], target: MaterializationTarget, + store: StateStore + ) throws { + let transaction = FileTransaction(store: store) + try transaction.replacePrivate( + store.preparePrivateMaterialization(target), provider: NoArrayBindings(), + produce: { _ in + .init( + bytes: bytes, nativeArrayTransitions: arrays.map { .init(previous: nil, current: $0) }) + }) + try transaction.commit() + } + + @Test func overlappingCreatedAncestryUsesOriginalAccessAndStillRefusesRealDrift() throws { + let fixture = try TransactionFixture() + let store = StateStore(scope: .user, environment: fixture.store.environment) + try FileManager.default.createDirectory( + at: store.environment.homeDirectory, withIntermediateDirectories: true) + let named = try NativeTargetRoute.named(.codexAgent, scope: .user, name: "review") + var before = "" + try store.withReadLock(footprint: [.codexMCPUser, named]) { + before = try TargetPrecondition(store.nativeTarget(for: named).url).displayEvidence( + includeContent: false) + } + try store.withLock(footprint: [.codexMCPUser, named]) { + let target = try store.nativeTarget(for: named) + #expect(try TargetPrecondition(target.url).displayEvidence(includeContent: false) == before) + let parent = store.environment.homeDirectory + let mode = try #require( + try DirectoryHandle(at: parent.deletingLastPathComponent()).accessEvidence( + parent.lastPathComponent) + ).mode + defer { _ = chmod(parent.path, mode) } + try #require(chmod(parent.path, mode ^ 0o010) == 0) + #expect(throws: CoreError.self) { + try TargetPrecondition(target.url).displayEvidence(includeContent: false) + } + } + } + + @Test func actualArrayProducerReceivesBindingsOnlyAfterVerifiedEmptyPrivateStage() throws { + let fixture = try TransactionFixture() + let provider = StagedArrayBindings() + try fixture.store.withLock(footprint: [.claudeMCPLocal]) { + let store = fixture.store + let target = try store.nativeTarget(for: .claudeMCPLocal) + let transaction = FileTransaction(store: store) { point in + if point == "stage.0.writeCreated" { + let journal = try StateStore.decode( + Data(contentsOf: store.directory.appendingPathComponent(TransactionJournal.fileName)), + as: TransactionJournal.self) + let parent = try DirectoryHandle(at: target.url.deletingLastPathComponent()) + let container = try parent.child(journal.containerName(0)) + let slot = TransactionSlot.staging(for: journal.entries[0]).name(0) + _ = try container.requirePrivateAccess(slot) + #expect(try container.read(slot).isEmpty) + provider.ready.withLock { $0 = true } + } + } + try transaction.replacePrivate( + store.preparePrivateMaterialization(target), bindings: ["value"], provider: provider, + produce: { values in + let bytes = try values.value(for: "value") + return .init( + bytes: bytes, nativeArrayTransitions: [.init(previous: nil, current: array())]) + }) + try transaction.commit() + #expect(try store.materializationReceipt(for: target)?.nativeArrays?.count == 1) + } + } + + @Test func siblingGenerationPreservesContinuityAndExactNoOpNeedsNoTransition() throws { + let fixture = try TransactionFixture() + try fixture.store.withLock(footprint: [.claudeMCPLocal]) { + let store = fixture.store + let target = try store.nativeTarget(for: .claudeMCPLocal) + let record = array() + try install(original, arrays: [record], target: target, store: store) + let first = try #require(try store.materializationReceipt(for: target)) + let accessFingerprint = try store.preparePrivateMaterialization(target).accessFingerprint() + let transaction = FileTransaction(store: store) + try transaction.replace( + target.url, with: .data(sibling), + nativeArrayTransitions: [.init(previous: record, current: record)]) + try transaction.commit() + let next = try #require(try store.materializationReceipt(for: target)) + #expect(next.generation != first.generation) + #expect(next.nativeArrays == [record]) + #expect( + try store.preparePrivateMaterialization(target).accessFingerprint() == accessFingerprint) + #expect(throws: CoreError.self) { + try store.preparePrivateMaterialization(target, expecting: first.generation) + } + let noOp = FileTransaction(store: store) + try noOp.replace(target.url, with: .data(sibling)) + try noOp.commit() + #expect(try store.materializationReceipt(for: target)?.nativeArrays == [record]) + let raw = try store.materializationReceipts(for: target.path) + #expect(raw.records.version == 2) + #expect(!String(reflecting: next).contains(record.semanticDigest)) + #expect( + !String(reflecting: PrivateMaterializationResult(bytes: original)).contains("private-value") + ) + _ = try DirectoryHandle(at: target.url.deletingLastPathComponent()).requirePrivateAccess( + target.url.lastPathComponent) + } + } + + @Test func anotherScopeUsesTheSamePhysicalArrayReceiptThroughAnAlias() throws { + let fixture = try TransactionFixture() + let config = fixture.root.appendingPathComponent("config") + let alias = fixture.root.appendingPathComponent("config-alias") + try FileManager.default.createDirectory(at: config, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: config) + var aEnvironment = fixture.store.environment + aEnvironment.environment["CLAUDE_CONFIG_DIR"] = config.path + var bEnvironment = aEnvironment + bEnvironment.environment["CLAUDE_CONFIG_DIR"] = alias.path + bEnvironment.homeDirectory = fixture.root.appendingPathComponent("other-home") + try FileManager.default.createDirectory( + at: bEnvironment.homeDirectory, withIntermediateDirectories: true) + let a = StateStore(scope: .project, environment: aEnvironment) + let b = StateStore(scope: .user, environment: bEnvironment) + let record = array() + var generation: UUID? + var receiptURL: URL! + try a.withLock(footprint: [.claudeMCPLocal]) { + let target = try a.nativeTarget(for: .claudeMCPLocal) + try install(original, arrays: [record], target: target, store: a) + generation = try a.materializationReceipt(for: target)?.generation + receiptURL = try a.materializationReceipts(for: target.path).url + } + try b.withLock(footprint: [.claudeMCPUser]) { + let target = try b.nativeTarget(for: .claudeMCPUser) + #expect(try b.materializationReceipt(for: target)?.nativeArrays == [record]) + #expect( + try b.materializationReceipts(for: target.path).url.resolvingSymlinksInPath() + == receiptURL.resolvingSymlinksInPath()) + let transaction = FileTransaction(store: b) + try transaction.replace( + target.url, with: .data(sibling), + nativeArrayTransitions: [.init(previous: record, current: record)]) + try transaction.commit() + } + try a.withReadLock(footprint: [.claudeMCPLocal]) { + let target = try a.nativeTarget(for: .claudeMCPLocal) + #expect(throws: CoreError.self) { + try a.preparePrivateMaterialization(target, expecting: generation) + } + #expect(try a.materializationReceipt(for: target)?.nativeArrays == [record]) + } + #expect(!FileManager.default.fileExists(atPath: a.materializationReceiptURL.path)) + #expect(!FileManager.default.fileExists(atPath: b.materializationReceiptURL.path)) + } + + @Test(arguments: [ + "missing", "duplicate", "wrong-path", "same-token-change", "unsupported", "incomplete", + "over-depth", "private-error", "mixed-format", "newline-digest", + ]) + func invalidTransitionsPublishNothing(_ kind: String) throws { + let fixture = try TransactionFixture() + try fixture.store.withLock(footprint: [.claudeMCPLocal]) { + let store = fixture.store + let target = try store.nativeTarget(for: .claudeMCPLocal) + let a = array() + let b = array("other") + try install(original, arrays: [a, b], target: target, store: store) + let state = try store.materializationReceipts(for: target.path) + let receipt = try Data(contentsOf: state.url) + var transitions: [PrivateNativeArrayTransition]? = [ + .init(previous: a, current: a), .init(previous: b, current: b), + ] + switch kind { + case "missing": transitions = nil + case "duplicate": transitions!.append(.init(previous: a, current: a)) + case "wrong-path": + transitions![0] = .init(previous: array("wrong", token: a.token), current: a) + case "same-token-change": + transitions![0] = .init(previous: a, current: array(token: a.token, digest: "changed")) + case "unsupported": + transitions![0] = .init( + previous: a, + current: .init( + path: a.path, documentFormat: "yaml", token: UUID(), semanticDigest: a.semanticDigest)) + case "mixed-format": + transitions![0] = .init( + previous: a, + current: .init( + path: a.path, documentFormat: "toml", token: UUID(), semanticDigest: a.semanticDigest)) + case "over-depth": + transitions![0] = .init( + previous: a, + current: .init( + path: Array(repeating: .key("nested"), count: LedgerLimits.standard.depth + 1), + documentFormat: "json", token: UUID(), semanticDigest: a.semanticDigest)) + case "newline-digest": + transitions![0] = .init( + previous: a, + current: .init( + path: a.path, documentFormat: "json", token: UUID(), + semanticDigest: a.semanticDigest + "\n")) + case "private-error": + transitions![0] = .init( + previous: a, + current: .init( + path: a.path, documentFormat: "json", token: UUID(), + semanticDigest: "private-error-must-not-escape")) + default: transitions!.removeLast() + } + let transaction = FileTransaction(store: store) + try transaction.replace(target.url, with: .data(sibling), nativeArrayTransitions: transitions) + do { + try transaction.commit() + Issue.record("expected transition refusal") + } catch { + #expect(!String(describing: error).contains("private-error-must-not-escape")) + } + #expect(try Data(contentsOf: target.url) == original) + #expect(try Data(contentsOf: state.url) == receipt) + #expect(try !TransactionJournal.isPresent(in: DirectoryHandle(at: store.directory))) + } + } + + @Test(arguments: [false, true]) + func arrayRotationRollbackAndWholeFileDeletionAreAtomic(_ rollback: Bool) throws { + let fixture = try TransactionFixture() + try fixture.store.withLock(footprint: [.claudeMCPLocal]) { + let store = fixture.store + let target = try store.nativeTarget(for: .claudeMCPLocal) + let old = array() + let changed = array(digest: "changed") + try install(original, arrays: [old], target: target, store: store) + let state = try store.materializationReceipts(for: target.path) + let receipt = try Data(contentsOf: state.url) + let transaction = FileTransaction(store: store) { point in + if rollback && point == "entry.1.applied" { + throw CoreError.invalidState("injected receipt publication failure") + } + } + try transaction.replace( + target.url, with: .data(sibling), + nativeArrayTransitions: [.init(previous: old, current: changed)]) + if rollback { + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(try Data(contentsOf: target.url) == original) + #expect(try Data(contentsOf: state.url) == receipt) + #expect(try store.materializationReceipt(for: target)?.nativeArrays == [old]) + } else { + try transaction.commit() + #expect(try store.materializationReceipt(for: target)?.nativeArrays == [changed]) + let clear = FileTransaction(store: store) + try clear.replace( + target.url, with: .data(sibling), + nativeArrayTransitions: [.init(previous: changed, current: nil)]) + try clear.commit() + #expect(try store.materializationReceipts(for: target.path).records.version == 2) + #expect(try store.materializationReceipt(for: target)?.nativeArrays == nil) + let deletion = FileTransaction(store: store) + try deletion.delete(target.url) + try deletion.commit() + #expect(!FileManager.default.fileExists(atPath: target.url.path)) + #expect(!FileManager.default.fileExists(atPath: state.url.path)) + } + } + } + + @Test func missingTargetNeedsExplicitFreshArrayEvidence() throws { + let fixture = try TransactionFixture() + try fixture.store.withLock(footprint: [.claudeMCPLocal]) { + let store = fixture.store + let target = try store.nativeTarget(for: .claudeMCPLocal) + let old = array() + let fresh = array() + try install(original, arrays: [old], target: target, store: store) + try FileManager.default.removeItem(at: target.url) + #expect(throws: CoreError.self) { + try FileTransaction(store: store).replace(target.url, with: .data(original)) + } + let stale = FileTransaction(store: store) + try stale.replacePrivate( + store.preparePrivateMaterialization(target), provider: NoArrayBindings(), + produce: { _ in + .init(bytes: original, nativeArrayTransitions: [.init(previous: old, current: old)]) + }) + #expect(throws: CoreError.self) { try stale.commit() } + #expect(!FileManager.default.fileExists(atPath: target.url.path)) + let restore = FileTransaction(store: store) + try restore.replacePrivate( + store.preparePrivateMaterialization(target), provider: NoArrayBindings(), + produce: { _ in + .init(bytes: original, nativeArrayTransitions: [.init(previous: old, current: fresh)]) + }) + try restore.commit() + #expect(try store.materializationReceipt(for: target)?.nativeArrays == [fresh]) + } + } + + @Test(arguments: ["stage.0.constructed", "entry.1.applied", "journal.committed"]) + func restartRecoversSealedArrayReceiptWithoutAProducer(_ point: String) throws { + let fixture = try TransactionFixture() + var environment = fixture.store.environment + environment.environment["CLAUDE_CONFIG_DIR"] = + fixture.root.appendingPathComponent("configured-claude").path + let store = StateStore(scope: .project, environment: environment) + let record = array() + var targetURL: URL! + var receiptURL: URL! + var previousReceipt = Data() + try store.withLock(footprint: [.claudeMCPLocal]) { + let target = try store.nativeTarget(for: .claudeMCPLocal) + targetURL = target.url + try install(original, arrays: [record], target: target, store: store) + receiptURL = try store.materializationReceipts(for: target.path).url + previousReceipt = try Data(contentsOf: receiptURL) + } + let child = try stateTestProcess(root: fixture.root, arguments: ["shared-array-edit", point]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let before = try FileSnapshot.read(at: fixture.root) + try store.withReadLock( + onPendingRecovery: { + #expect(!FileTransaction.recoveryDiagnostic(store: store).requiresOwner) + }, { Issue.record("expected pending array transaction") }) + #expect(try FileSnapshot.read(at: fixture.root) == before) + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + let committed = point == "journal.committed" + #expect(try Data(contentsOf: targetURL) == (committed ? sibling : original)) + if !committed { #expect(try Data(contentsOf: receiptURL) == previousReceipt) } + try store.withReadLock(footprint: [.claudeMCPLocal]) { + let target = try store.nativeTarget(for: .claudeMCPLocal) + #expect(try store.materializationReceipt(for: target)?.nativeArrays == [record]) + } + #expect( + !FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("provider-called").path)) + } + + @Test func receiptVersionsAndNestedFieldsAreStrictAndUTF8AddressesStayDistinct() throws { + let fixture = try TransactionFixture() + try fixture.store.withLock(footprint: [.claudeMCPLocal]) { + let store = fixture.store + let target = try store.nativeTarget(for: .claudeMCPLocal) + let transaction = FileTransaction(store: store) + try transaction.replacePrivate( + store.preparePrivateMaterialization(target), provider: NoArrayBindings() + ) { _ in original } + try transaction.commit() + let v1 = try store.materializationReceipts(for: target.path) + #expect(v1.records.version == 1) + #expect( + try StateStore.decode(Data(contentsOf: v1.url), as: MaterializationReceipts.self).version + == 1) + let records = [array("\u{e9}"), array("e\u{301}")] + #expect(records[0].path != records[1].path) + let upgrade = FileTransaction(store: store) + try upgrade.replace( + target.url, with: .data(original), + nativeArrayTransitions: records.map { .init(previous: nil, current: $0) }) + try upgrade.commit() + let bytes = try Data(contentsOf: v1.url) + let object = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + func refuses(_ edit: (inout [String: Any]) -> Void) throws { + var value = object + edit(&value) + let data = try JSONSerialization.data(withJSONObject: value) + #expect(throws: (any Error).self) { + let decoded = try StateStore.decode(data, as: MaterializationReceipts.self) + try decoded.validate(store: store) + } + } + try refuses { $0["version"] = 1 } + try refuses { $0["unknown"] = NSNull() } + for kind in ["record", "step", "duplicate", "negative", "digest", "null"] { + try refuses { value in + var targets = value["targets"] as! [String: Any] + let key = targets.keys.first! + var record = targets[key] as! [String: Any] + var arrays = record["nativeArrays"] as! [[String: Any]] + switch kind { + case "record": arrays[0]["unknown"] = NSNull() + case "step": + var path = arrays[0]["path"] as! [[String: Any]] + path[0]["unknown"] = NSNull() + arrays[0]["path"] = path + case "duplicate": arrays.append(arrays[0]) + case "negative": arrays[0]["path"] = [["kind": "position", "index": -1]] + case "digest": arrays[0]["semanticDigest"] = "invalid" + default: record["nativeArrays"] = NSNull() + } + if kind != "null" { record["nativeArrays"] = arrays } + targets[key] = record + value["targets"] = targets + } + } + } + } +} + +private struct NoArrayBindings: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + throw CoreError.invalidState("unexpected binding request") + } +} + +private final class StagedArrayBindings: RuntimeBindingProvider { + let ready = Mutex(false) + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + guard ready.withLock({ $0 }) else { + throw CoreError.invalidState("private stage was not verified") + } + return Data(#"{"hooks":["private-value"],"sibling":0}"#.utf8) + } +} diff --git a/Tests/StateTestProcess/PrivateMaterializationProbe.swift b/Tests/StateTestProcess/PrivateMaterializationProbe.swift index c94bdf6..ef73b21 100644 --- a/Tests/StateTestProcess/PrivateMaterializationProbe.swift +++ b/Tests/StateTestProcess/PrivateMaterializationProbe.swift @@ -145,7 +145,12 @@ func sharedMaterializationProbe( let transaction = FileTransaction(store: store, checkpoint: checkpoint) for route in routes { let target = try store.nativeTarget(for: route) - if command == "shared-delete" { + if command == "shared-array-edit" { + let arrays = try store.materializationReceipt(for: target)?.nativeArrays ?? [] + try transaction.replace( + target.url, with: .data(Data(#"{"hooks":["private-value"],"sibling":1}"#.utf8)), + nativeArrayTransitions: arrays.map { .init(previous: $0, current: $0) }) + } else if command == "shared-delete" { try transaction.delete(target.url) } else if command == "shared-install" { let prepared = try store.preparePrivateMaterialization(target, changingAccess: true) @@ -157,7 +162,7 @@ func sharedMaterializationProbe( try transaction.replace(target.url, with: .data(Data("secret sibling; edited region".utf8))) } } - if store.scope == .project { + if store.scope == .project && command != "shared-array-edit" { try transaction.replace( store.environment.projectDirectory.appendingPathComponent("old-data/AGENTS.md"), with: .data(Data("ordinary after".utf8))) From a739245fe019e2c320c1dc45bab4c161ee661c91 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:14:08 +0800 Subject: [PATCH 114/171] feat: support finite skill lifecycle and configuration previews --- Documentation/Architecture/Updates.md | 10 +- .../AgentsSkills/SkillInitialization.swift | 26 +++-- Sources/AgentsSkills/SkillLifecycle.swift | 42 +++++++++ Sources/AgentsSkills/SkillOperations.swift | 7 +- Sources/AgentsUpdates/ScopeInspection.swift | 22 +++-- Sources/AgentsUpdates/UpdateModels.swift | 11 +++ Sources/AgentsUpdates/UpdateOperations.swift | 21 ++++- Sources/AgentsUpdates/UpdatePlan.swift | 32 +++++-- Sources/Components/ArtifactAggregation.swift | 94 +++++++++++++++++-- .../InstalledInventoryTests.swift | 7 ++ .../FiniteSkillInstallationTests.swift | 93 ++++++++++++++++++ .../FirstUserDeclarationTests.swift | 50 +++++++++- .../InitializationIntegrationTests.swift | 16 ++++ .../PrivateNativeCompositionTests.swift | 16 +++- 14 files changed, 395 insertions(+), 52 deletions(-) create mode 100644 Tests/AgentsUpdatesTests/FiniteSkillInstallationTests.swift diff --git a/Documentation/Architecture/Updates.md b/Documentation/Architecture/Updates.md index e70ccae..90b67c5 100644 --- a/Documentation/Architecture/Updates.md +++ b/Documentation/Architecture/Updates.md @@ -30,7 +30,11 @@ Reports include skill membership and typed file differences, instruction targets and prompts, selected native changes, missing-lock status, `hasChanges` and a `displayedFingerprint`. Native reports contain the owned symbolic values; complete shared documents, unrelated siblings, runtime secret values and private freshness -evidence remain internal. Equal unmanaged values do not establish ownership. +evidence remain internal. `ComponentUpdateChange.symbolicBefore` and `symbolicAfter` +are readable selected configuration JSON, rendered through the native JSON owner. +Environment and secret references remain symbolic objects; `nil` means the selected +value is unavailable. Consumers can display these strings directly. Equal unmanaged +values do not establish ownership. `hasChanges` includes declaration and ledger changes even when target bytes agree. The versioned display fingerprint covers the operation and selection, complete @@ -45,7 +49,9 @@ the same fingerprint. This is a presentation comparison, not an authorization to `withPreparedUpdate(_:scope:environment:_:)` acquires the request and pending-journal footprint before the scope writer lock. Source linking can discover a larger footprint; preparation releases the locks and readmits the union before delivering -the consumer closure. This never repeats a delivered callback or binding provider. +the consumer closure. Finite skill installation targets for current and previous +slots join this admission union and retain their legacy directory/link intention. +This never repeats a delivered callback or binding provider. It captures declaration, ledger and watch together, links and freezes one paired source result, lowers it and aggregates contributions by physical destination. Shared native files receive one aggregated regional edit with all logical owners. diff --git a/Sources/AgentsSkills/SkillInitialization.swift b/Sources/AgentsSkills/SkillInitialization.swift index 25ed8f9..c277c63 100644 --- a/Sources/AgentsSkills/SkillInitialization.swift +++ b/Sources/AgentsSkills/SkillInitialization.swift @@ -23,22 +23,18 @@ package struct SkillInitialization: Sendable { name = canonicalName selectedChild = nil } else { - guard canonicalName == nil else { - throw CoreError.unsupported( - "initializing a named skill below a new directory requires admission of both creating levels" - ) - } environment.projectDirectory = directory.deletingLastPathComponent() - name = nil + name = canonicalName selectedChild = directory.lastPathComponent } store = StateStore(scope: .project, environment: environment) root = try store.captureExistingProjectRoot() let observedDirectory = root.directory.resolvingSymlinksInPath() - file = - (selectedChild ?? name).map { observedDirectory.appendingPathComponent($0) } - .map { $0.appendingPathComponent("SKILL.md") } - ?? root.directory.resolvingSymlinksInPath().appendingPathComponent("SKILL.md") + let selectedDirectory = + selectedChild.map { observedDirectory.appendingPathComponent($0) } + ?? observedDirectory + file = (name.map { selectedDirectory.appendingPathComponent($0) } ?? selectedDirectory) + .appendingPathComponent("SKILL.md") let title = canonicalName ?? PathSafety.sanitizeName(directory.lastPathComponent) template = Data( "---\nname: \(title)\ndescription: Describe when to use this skill\n---\n\n# \(title)\n\nWrite the skill instructions here.\n" @@ -46,8 +42,9 @@ package struct SkillInitialization: Sendable { if validateState { try store.withReadLock { let target = - try selectedChild.map { try store.skillInitializationTarget(inChildDirectory: $0) } - ?? store.skillInitializationTarget(named: name) + try selectedChild.map { + try store.skillInitializationTarget(inChildDirectory: $0, named: name) + } ?? store.skillInitializationTarget(named: name) guard target.file == file else { throw CoreError.invalidState("skill initialization target changed") } @@ -64,8 +61,9 @@ package struct SkillInitialization: Sendable { _ = try store.declarationBytes() _ = try store.readLedger() let target = - try selectedChild.map { try store.skillInitializationTarget(inChildDirectory: $0) } - ?? store.skillInitializationTarget(named: name) + try selectedChild.map { + try store.skillInitializationTarget(inChildDirectory: $0, named: name) + } ?? store.skillInitializationTarget(named: name) guard target.file == file else { throw CoreError.invalidState("skill initialization target changed") } diff --git a/Sources/AgentsSkills/SkillLifecycle.swift b/Sources/AgentsSkills/SkillLifecycle.swift index e8bf104..802733d 100644 --- a/Sources/AgentsSkills/SkillLifecycle.swift +++ b/Sources/AgentsSkills/SkillLifecycle.swift @@ -103,6 +103,48 @@ package final class SkillLifecycle { return selected } + package static func installationTargets(_ ledger: ResolvedLedger, store: StateStore) throws + -> [String: SkillInstallationTarget] + { + var targets: [String: SkillInstallationTarget] = [:] + for deployment in ledger.deployments where deployment.route == "agents/skill@1" { + guard deployment.target.kind == .registered, + let agent = deployment.recipients.first, deployment.recipients.count == 1, + deployment.target.root == "skills-" + agent.rawValue + else { throw CoreError.invalidState("invalid skill installation recipient") } + let name = deployment.target.path + targets[agent.rawValue + "/" + name] = try store.skillInstallationTarget( + for: agent, named: name) + } + return targets + } + + private struct RequiredInstallations: Error { + let targets: [String: SkillInstallationTarget] + } + + /// Capture all managed slots before admitting physical reads; never recover during inventory. + static func withInstallationReadLock( + store: StateStore, onPendingRecovery: (() throws -> T)? = nil, _ body: () throws -> T + ) throws -> T { + var targets: [String: SkillInstallationTarget] = [:] + while true { + do { + return try store.withReadLock( + onPendingRecovery: onPendingRecovery, installations: Array(targets.values) + ) { + let required = try installationTargets(store.readLedger(), store: store) + guard Set(required.keys).isSubset(of: Set(targets.keys)) else { + throw RequiredInstallations(targets: required) + } + return try body() + } + } catch let required as RequiredInstallations { + targets.merge(required.targets, uniquingKeysWith: { _, next in next }) + } + } + } + package static func target(name: String, agent: AgentID, store: StateStore) -> URL { AgentRegistry.installSkillsDirectory( for: agent, scope: store.scope, environment: store.environment diff --git a/Sources/AgentsSkills/SkillOperations.swift b/Sources/AgentsSkills/SkillOperations.swift index f1cc26e..87b13a1 100644 --- a/Sources/AgentsSkills/SkillOperations.swift +++ b/Sources/AgentsSkills/SkillOperations.swift @@ -16,7 +16,7 @@ public enum SkillOperations { environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> [InstalledSkill] { let store = StateStore(scope: scope, environment: environment) - return try store.withReadLock { + return try SkillLifecycle.withInstallationReadLock(store: store) { _ = try store.readDeclaration() let ledger = try store.readLedger() return try managedInventory(store: store, ledger: ledger, agents: agents) @@ -78,7 +78,7 @@ public enum SkillOperations { environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> [InstalledSkill] { let store = StateStore(scope: scope, environment: environment) - return try store.withReadLock { + return try SkillLifecycle.withInstallationReadLock(store: store) { _ = try store.readDeclaration() let ledger = try store.readLedger() var result = try managedInventory(store: store, ledger: ledger, agents: agents).filter { @@ -126,7 +126,8 @@ public enum SkillOperations { environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> DoctorReport { let store = StateStore(scope: scope, environment: environment) - return try store.withReadLock( + return try SkillLifecycle.withInstallationReadLock( + store: store, onPendingRecovery: { let recovery = FileTransaction.recoveryDiagnostic(store: store) return DoctorReport(checks: [ diff --git a/Sources/AgentsUpdates/ScopeInspection.swift b/Sources/AgentsUpdates/ScopeInspection.swift index a7e3b5e..8229824 100644 --- a/Sources/AgentsUpdates/ScopeInspection.swift +++ b/Sources/AgentsUpdates/ScopeInspection.swift @@ -1,6 +1,7 @@ import AgentsCore import AgentsInstructions import AgentsManifest +import AgentsSkills import Components import Foundation @@ -141,6 +142,7 @@ extension UpdateOperations { ) throws -> ScopeInspection { let store = StateStore(scope: scope, environment: environment) var admitted = Set() + var installations: [String: SkillInstallationTarget] = [:] let stateLocations = [store.declarationURL, store.resolvedURL, store.watchURL] while true { do { @@ -154,14 +156,17 @@ extension UpdateOperations { pending: true, requiresOwner: diagnostic.requiresOwner, diagnostic: diagnostic.message), readLocations: stateLocations) - }, footprint: admitted, + }, footprint: admitted, installations: Array(installations.values), { let baseline = try StatePrecondition(store: store) let document = try store.declarationDocument(prepared: baseline) let declaration = try store.readDeclaration(prepared: baseline) let ledger = try store.readLedger(prepared: baseline) let routes = try DeploymentConstruction.routes(ledger) - guard routes.isSubset(of: admitted) else { throw RequiredRoutes(routes: routes) } + let required = try SkillLifecycle.installationTargets(ledger, store: store) + guard routes.isSubset(of: admitted), + Set(required.keys).isSubset(of: Set(installations.keys)) + else { throw RequiredRoutes(routes: routes, installations: required) } let watch = try store.readWatch(prepared: baseline) let generation = try ResolvedLedgerCodec.digest([ ResolvedLedgerCodec.digest(ledger), document?.digest ?? "absent", @@ -219,8 +224,10 @@ extension UpdateOperations { name: g.name, requirement: g.requirement, manifestHash: g.manifestHash, children: g.children) } - let paths = try readLocations( - declarations: [declaration], ledgers: [ledger], store: store) + let paths = + try readLocations( + declarations: [declaration], ledgers: [ledger], store: store) + + installations.values.map(\.url) try baseline.validate() return ScopeInspection( scope: scope, document: document, declaration: declaration, generation: generation, @@ -229,7 +236,10 @@ extension UpdateOperations { recovery: .init(pending: false, requiresOwner: false, diagnostic: nil), readLocations: Array(Set(paths)).sorted { $0.path < $1.path }) }) - } catch let required as RequiredRoutes { admitted.formUnion(required.routes) } + } catch let required as RequiredRoutes { + admitted.formUnion(required.routes) + installations.merge(required.installations, uniquingKeysWith: { _, next in next }) + } } } @@ -265,7 +275,7 @@ extension UpdateOperations { } } - private static func symbolicValue(_ value: LedgerValue) -> NativeValue { + static func symbolicValue(_ value: LedgerValue) -> NativeValue { switch value.kind { case .environment: return .object(["environment": .string(value.text!)]) case .secret: return .object(["secret": .string(value.text!)]) diff --git a/Sources/AgentsUpdates/UpdateModels.swift b/Sources/AgentsUpdates/UpdateModels.swift index fa4f4bb..935916c 100644 --- a/Sources/AgentsUpdates/UpdateModels.swift +++ b/Sources/AgentsUpdates/UpdateModels.swift @@ -1,6 +1,7 @@ import AgentsCore import AgentsInstructions import AgentsSkills +import Components import Foundation public struct CombinedUpdateReport: Codable, Sendable, Equatable { @@ -54,7 +55,10 @@ public struct ComponentUpdateChange: Codable, Sendable, Equatable { public let effectiveReaders: [AgentID] public let privateMaterialization: Bool public let permissionChange: ComponentPermissionChange? + /// Readable selected configuration JSON with symbolic environment/secret references. + /// Nil means the old selected value is unavailable; native sibling values are never included. public let symbolicBefore: String? + /// Readable selected configuration JSON, using the same symbolic projection as inspection. public let symbolicAfter: String? public let kind: String public let name: String @@ -87,3 +91,10 @@ public struct ComponentMemberPermissionChange: Codable, Sendable, Equatable { public let afterOwner: UInt32 public let afterMode: UInt32 } + +// Public preview text uses the inspection projection, never the ledger wire representation. +extension UpdateOperations { + static func symbolicConfigurationText(_ value: LedgerValue) throws -> String { + try ArtifactAggregation.configurationPreview(symbolicValue(value)) + } +} diff --git a/Sources/AgentsUpdates/UpdateOperations.swift b/Sources/AgentsUpdates/UpdateOperations.swift index 81022de..5fe6dd5 100644 --- a/Sources/AgentsUpdates/UpdateOperations.swift +++ b/Sources/AgentsUpdates/UpdateOperations.swift @@ -23,15 +23,21 @@ public enum UpdateOperations { ) throws -> CombinedUpdateReport { let store = StateStore(scope: scope, environment: environment) var admitted = Set() + var installations: [String: SkillInstallationTarget] = [:] while true { do { - return try store.withReadLock(footprint: admitted) { + return try store.withReadLock( + footprint: admitted, installations: Array(installations.values) + ) { try UpdatePlan.withPlan( - request: request, store: store, admitted: admitted, + request: request, store: store, admitted: admitted, installations: installations, checkpoint: checkpoint, provider: RequiredBindingProvider() ) { $0.report } } - } catch let required as RequiredRoutes { admitted.formUnion(required.routes) } + } catch let required as RequiredRoutes { + admitted.formUnion(required.routes) + installations.merge(required.installations, uniquingKeysWith: { _, next in next }) + } } } @@ -70,11 +76,15 @@ public enum UpdateOperations { var delivered = false var returned = false var admitted = Set() + var installations: [String: SkillInstallationTarget] = [:] while true { do { - return try store.withLock(checkpoint: checkpoint, outcome: outcome, footprint: admitted) { + return try store.withLock( + checkpoint: checkpoint, outcome: outcome, footprint: admitted, + installations: Array(installations.values) + ) { try UpdatePlan.withPlan( - request: request, store: store, admitted: admitted, + request: request, store: store, admitted: admitted, installations: installations, checkpoint: checkpoint, provider: provider ) { plan in try plan.requireSkillOwnership() @@ -88,6 +98,7 @@ public enum UpdateOperations { } } catch let required as RequiredRoutes where !delivered { admitted.formUnion(required.routes) + installations.merge(required.installations, uniquingKeysWith: { _, next in next }) } catch { if returned || error is UpdateApplyError { throw UpdateApplyError(outcome: outcome, underlyingError: error) diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 74d936e..5905546 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -5,7 +5,10 @@ import AgentsSkills import Components import Foundation -struct RequiredRoutes: Error { let routes: Set } +struct RequiredRoutes: Error { + let routes: Set + var installations: [String: SkillInstallationTarget] = [:] +} /// The composition plan borrows both source/replay resources and the admitted writer scope. final class UpdatePlan { @@ -25,6 +28,7 @@ final class UpdatePlan { static func withPlan( request: UpdateRequest, store: StateStore, admitted: Set, + installations: [String: SkillInstallationTarget], checkpoint: @escaping (String) throws -> Void, provider: any RuntimeBindingProvider, _ body: (UpdatePlan) throws -> T ) throws -> T { @@ -78,7 +82,9 @@ final class UpdatePlan { } if restoring { let routes = try DeploymentConstruction.routes(previous) - guard routes.isSubset(of: admitted) else { throw RequiredRoutes(routes: routes) } + let required = try SkillLifecycle.installationTargets(previous, store: store) + guard routes.isSubset(of: admitted), Set(required.keys).isSubset(of: Set(installations.keys)) + else { throw RequiredRoutes(routes: routes, installations: required) } return try LedgerReplay.withLockedResources( previous, store: store, roots: store.ledgerRoots, limits: .standard ) { artifacts, resources, workspace in @@ -88,7 +94,7 @@ final class UpdatePlan { watch: watch, change: nil, artifacts: artifacts, resources: resources, workspace: workspace, decisionInputs: [], originalInputs: [], - checkpoint: checkpoint, provider: provider)) + checkpoint: checkpoint, provider: provider, installations: Array(installations.values))) } } var document: DeclarationDocument @@ -198,6 +204,12 @@ final class UpdatePlan { } let complete = try DeploymentConstruction.complete( native, linked: linked, store: store, previous: previous, platform: platform) + let required = try SkillLifecycle.installationTargets(previous, store: store).merging( + SkillLifecycle.installationTargets(complete.ledger, store: store), + uniquingKeysWith: { _, next in next }) + guard Set(required.keys).isSubset(of: Set(installations.keys)) else { + throw RequiredRoutes(routes: routes, installations: required) + } let originals = try linked.components.flatMap { c -> [TargetPrecondition] in if case .skill(_, .edit, _) = c.payload { return [] } return try c.resources.filter { $0.snapshot.revision == "live" }.map { @@ -214,7 +226,7 @@ final class UpdatePlan { watch: watch, change: change, artifacts: artifacts, resources: resources, workspace: workspace, decisionInputs: complete.inputs, originalInputs: originals + importInputs, - checkpoint: checkpoint, provider: provider)) + checkpoint: checkpoint, provider: provider, installations: Array(installations.values))) } } } @@ -225,7 +237,8 @@ final class UpdatePlan { change: DeclarationChange?, artifacts: [ReplayedArtifact], resources: [String: URL], workspace: URL, decisionInputs: [TargetPrecondition], originalInputs: [TargetPrecondition], - checkpoint: @escaping (String) throws -> Void, provider: any RuntimeBindingProvider + checkpoint: @escaping (String) throws -> Void, provider: any RuntimeBindingProvider, + installations: [SkillInstallationTarget] ) throws { self.store = store self.baseline = baseline @@ -239,7 +252,8 @@ final class UpdatePlan { ledger: next, previous: previous, artifacts: artifacts, resources: resources, workspace: workspace, store: store, replace: request.replace, changingAccess: request.changingAccess, kinds: request.kinds, - names: Set(request.names), selectedIdentities: request.selectedIdentities) + names: Set(request.names), selectedIdentities: request.selectedIdentities, + installations: installations) if let imported = request.importPreparation { for resource in imported.proposal.resources where resource.selected && resource.requiresStandaloneSource { @@ -344,7 +358,7 @@ final class UpdatePlan { let readPaths = try UpdateOperations.readLocations( declarations: readDeclarations, ledgers: [previous, self.next], store: store) - + decisionInputs.map(\.url) + + decisionInputs.map(\.url) + installations.map(\.url) let finalNext = self.next report = CombinedUpdateReport( scope: store.scope, skills: publicResults, instructions: instructions, @@ -391,10 +405,10 @@ final class UpdatePlan { }) }, symbolicBefore: try change.symbolicBefore.map { - String(decoding: try ResolvedLedgerCodec.bytes($0), as: UTF8.self) + try UpdateOperations.symbolicConfigurationText($0) }, symbolicAfter: try change.symbolicAfter.map { - String(decoding: try ResolvedLedgerCodec.bytes($0), as: UTF8.self) + try UpdateOperations.symbolicConfigurationText($0) }, kind: component.kind, name: component.name, path: change.url.path, agents: change.deployment.recipients, changed: change.changed) diff --git a/Sources/Components/ArtifactAggregation.swift b/Sources/Components/ArtifactAggregation.swift index 5ca9991..82c6c0d 100644 --- a/Sources/Components/ArtifactAggregation.swift +++ b/Sources/Components/ArtifactAggregation.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsInstructions +import AgentsSkills import Foundation import NativeDocuments @@ -37,6 +38,9 @@ package final class ArtifactAggregation: PreparedEvidence { private var writes: [String: FileTransaction.Source] = [:] private var deletes = Set() private var capsules: [String: URL] = [:] + private var skillTargets: [String: SkillInstallationTarget] = [:] + private var skillWritePaths = Set() + private var skillDeletePaths = Set() private var skillContent: [String: (String, [String: Bool])] = [:] private var privateWrites: [(PreparedPrivateMaterialization, Set, (RuntimeBindingValues) throws -> Data)] = [] @@ -49,12 +53,14 @@ package final class ArtifactAggregation: PreparedEvidence { resources: [String: URL], workspace: URL, store: StateStore, replace: Bool, changingAccess: Bool, kinds: Set? = nil, names: Set = [], - selectedIdentities: Set? = nil + selectedIdentities: Set? = nil, + installations: [SkillInstallationTarget] = [] ) throws { self.ledger = ledger self.store = store self.resources = resources self.replace = replace + for target in installations { skillTargets[target.url.path] = target } selectedKinds = kinds selectedNames = names self.selectedIdentities = selectedIdentities @@ -107,10 +113,10 @@ package final class ArtifactAggregation: PreparedEvidence { let previousByPath = try Dictionary( grouping: previous.deployments.filter { selected($0, in: previous) } ) { - InstructionLocations.physical(try $0.target.resolve(roots: roots)).path + try installationURL($0).path } var byPath = try Dictionary(grouping: ledger.deployments.filter { selected($0, in: ledger) }) { - InstructionLocations.physical(try $0.target.resolve(roots: roots)).path + try installationURL($0).path } var native: [String: [(LockedLowering, NativeMCPContribution, MaterializationTarget)]] = [:] for lowering in ledger.lowerings @@ -210,6 +216,7 @@ package final class ArtifactAggregation: PreparedEvidence { guard let deployment = old.first else { continue } if deployment.route == "agents/skill@1" { deletes.insert(path) + skillDeletePaths.insert(path) changes.append( .init( deployment: deployment, url: url, before: nil, after: nil, @@ -295,7 +302,10 @@ package final class ArtifactAggregation: PreparedEvidence { { skillContent[path] = (resource.hash, try FileHash.executableFlags(tree)) } - if changed { writes[path] = source } + if changed { + writes[path] = source + skillWritePaths.insert(path) + } changes.append( .init( deployment: deployment, url: url, before: nil, after: nil, @@ -330,6 +340,20 @@ package final class ArtifactAggregation: PreparedEvidence { try Self.resourceDestination(id, ledger: selected ?? ledger, store: store) } + private func installationURL(_ deployment: LedgerDeployment) throws -> URL { + guard deployment.route == "agents/skill@1" else { + return InstructionLocations.physical(try deployment.target.resolve(roots: store.ledgerRoots)) + } + guard let agent = deployment.recipients.first else { + throw CoreError.invalidState("missing skill recipient") + } + let target = try store.skillInstallationTarget(for: agent, named: deployment.target.path) + guard let admitted = skillTargets[target.url.path] else { + throw CoreError.invalidState("skill installation was not admitted") + } + return admitted.url + } + package static func resourceDestination(_ id: String, ledger: ResolvedLedger, store: StateStore) throws -> URL { @@ -539,6 +563,27 @@ package final class ArtifactAggregation: PreparedEvidence { try Self.generatedManifestBytes(manifest, values: values, selected: ledger, store: store) } + /// Renders a selected symbolic value with the native JSON serializer, without physical input. + package static func configurationPreview(_ value: NativeValue) throws -> String { + func document(_ bytes: Data) throws -> NativeDocument { + try NativeDocument( + bytes: bytes, format: .json, + budget: NativeDocumentBudget( + limits: .init( + storage: LedgerLimits.standard.resourceBytes, work: LedgerLimits.standard.encodedBytes, + nodes: LedgerLimits.standard.nodes, depth: LedgerLimits.standard.depth, + uninterruptedBytes: LedgerLimits.standard.keyBytes))) + } + let region = NativeRegion(keys: ["selected"]) + let bytes = try document(Data("{}".utf8)).prepare([ + .put(region: region, expected: .absent, value: value) + ]).bytes + guard let range = try document(bytes).read(region)?.valueRange else { + throw CoreError.invalidState("selected configuration has no rendered range") + } + return String(decoding: bytes.subdata(in: range), as: UTF8.self) + } + private static func generatedManifestBytes( _ manifest: NativeComponentValue, values: RuntimeBindingValues?, selected: ResolvedLedger, store: StateStore @@ -1195,14 +1240,23 @@ package final class ArtifactAggregation: PreparedEvidence { } } for path in writes.keys.sorted() { - try transaction.replace( - URL(fileURLWithPath: path), with: writes[path]!, - expectedHash: { if case .link = writes[path]! { nil } else { skillContent[path]?.0 } }(), - executableFlags: { if case .link = writes[path]! { nil } else { skillContent[path]?.1 } }(), - expecting: targets[path]) + let source = writes[path]! + let hash: String? = { if case .link = source { nil } else { skillContent[path]?.0 } }() + if skillWritePaths.contains(path), let target = skillTargets[path] { + try transaction.replaceSkill( + target, with: source, expectedHash: hash, expecting: targets[path]) + } else { + try transaction.replace( + URL(fileURLWithPath: path), with: source, expectedHash: hash, + executableFlags: skillContent[path]?.1, expecting: targets[path]) + } } for path in deletes.sorted() { - try transaction.delete(URL(fileURLWithPath: path), expecting: targets[path]) + if skillDeletePaths.contains(path), let target = skillTargets[path] { + try transaction.deleteSkill(target, expecting: targets[path]) + } else { + try transaction.delete(URL(fileURLWithPath: path), expecting: targets[path]) + } } for (prepared, entries) in privateTrees { try transaction.replacePrivateTree(prepared, entries: entries, provider: provider) @@ -1288,6 +1342,26 @@ extension ArtifactAggregation { } do { if deployment.route == "agents/skill@1" { + if let lowering = ledger.lowerings.first(where: { $0.deployments.contains(deployment.id) }), + lowering.layout.object?["mode"]?.text == InstallMode.edit.rawValue + { + guard let owner = deployment.owners.first.flatMap({ ledger.components[$0] }), + let name = owner.payload.object?["name"]?.text, + let resource = owner.resources.first.flatMap({ ledger.resources[$0] }), + resource.kind == .liveEdit, let source = resource.location, + let link = try? FileManager.default.destinationOfSymbolicLink(atPath: url.path) + else { return ("drifted", "live skill is not linked to its recorded source") } + let observed = URL(fileURLWithPath: link, relativeTo: url.deletingLastPathComponent()) + .standardizedFileURL + let expected = try source.resolve(roots: store.ledgerRoots).standardizedFileURL + guard observed.path == expected.path else { + return ("drifted", "live skill is not linked to its recorded source") + } + do { try SkillOperations.validateLiveMetadata(at: expected, name: name) } catch { + return ("drifted", "live skill source metadata changed") + } + return ("current", nil) + } let expected = deployment.expectedHash let hash = "sha256:" + (try FileHash.folderHash(url)) let flags = try FileHash.executableFlags(url) diff --git a/Tests/AgentsSkillsTests/InstalledInventoryTests.swift b/Tests/AgentsSkillsTests/InstalledInventoryTests.swift index a23483a..aed4e65 100644 --- a/Tests/AgentsSkillsTests/InstalledInventoryTests.swift +++ b/Tests/AgentsSkillsTests/InstalledInventoryTests.swift @@ -37,9 +37,16 @@ struct InstalledInventoryTests { to: universal.appendingPathComponent("invalid/SKILL.md")) let claude = AgentRegistry.installSkillsDirectory( for: .claudeCode, scope: scope, environment: environment) + try FileManager.default.createDirectory( + at: claude.deletingLastPathComponent(), withIntermediateDirectories: true) _ = try SkillOperations.initializeSkill(named: "claude-only", directory: claude) var expectedCodex = Set(["linked"]) if scope == .user { + for agent in [AgentID.codex, .opencode] { + let selected = AgentRegistry.userSkillsDirectory(for: agent, environment: environment) + try FileManager.default.createDirectory( + at: selected.deletingLastPathComponent(), withIntermediateDirectories: true) + } _ = try SkillOperations.initializeSkill( named: "codex-native", directory: AgentRegistry.userSkillsDirectory(for: .codex, environment: environment)) diff --git a/Tests/AgentsUpdatesTests/FiniteSkillInstallationTests.swift b/Tests/AgentsUpdatesTests/FiniteSkillInstallationTests.swift new file mode 100644 index 0000000..9abd66c --- /dev/null +++ b/Tests/AgentsUpdatesTests/FiniteSkillInstallationTests.swift @@ -0,0 +1,93 @@ +import AgentsCore +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import Foundation +import Testing + +struct FiniteSkillInstallationTests { + @Test func registeredLoaderAliasExposesLogicalAndPhysicalReadLocations() throws { + let f = try UpdateFixture() + let physical = f.root.appendingPathComponent("physical-claude") + try FileManager.default.createDirectory(at: physical, withIntermediateDirectories: false) + try FileManager.default.createSymbolicLink( + at: f.root.appendingPathComponent(".claude"), withDestinationURL: physical) + _ = try SkillOperations.add( + AddOptions( + source: f.repo.path, agents: [.claudeCode], mode: .copy, + all: true, environment: f.environment)) + let expected = Set([ + f.target(.claudeCode).path, physical.appendingPathComponent("skills/demo").path, + ]) + #expect(Set(try f.preview().readLocations.map(\.path)).isSuperset(of: expected)) + #expect( + Set(try UpdateOperations.inspect(environment: f.environment).readLocations.map(\.path)) + .isSuperset(of: expected)) + } + + @Test func liveMetadataUsesDeclaredNameWhileInstallationUsesCanonicalName() throws { + let f = try UpdateFixture(scope: .user) + let file = f.repo.appendingPathComponent("skills/demo/SKILL.md") + try f.write("---\nname: Demo Skill\ndescription: fixture\n---\nLive body\n", to: file) + try f.commit() + _ = try SkillOperations.add( + AddOptions( + source: f.repo.path, agents: [.claudeCode], scope: .user, + mode: .edit, all: true, environment: f.environment)) + let current = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(current.deployments.first?.location.lastPathComponent == "demo-skill") + #expect(current.deployments.first?.status == .current) + try f.write("---\nname: Other Skill\ndescription: fixture\n---\nLive body\n", to: file) + let changed = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(changed.deployments.first?.status == .drifted) + } + + @Test(arguments: [InstallMode.link, .copy, .edit]) + func userClaudeSkillUsesLegacyIntentionAcrossPublicLifecycle(_ mode: InstallMode) throws { + let f = try UpdateFixture(scope: .user) + _ = try SkillOperations.add( + AddOptions( + source: f.repo.path, alias: "fixture", agents: [.claudeCode], scope: .user, + mode: mode, all: true, environment: f.environment)) + let target = f.target(.claudeCode) + #expect(FileManager.default.fileExists(atPath: target.appendingPathComponent("SKILL.md").path)) + if mode != .copy { + #expect((try? FileManager.default.destinationOfSymbolicLink(atPath: target.path)) != nil) + } + let before = try FileHash.folderHash(f.root) + let preview = try f.preview() + #expect(try FileHash.folderHash(f.root) == before) + #expect(try SkillOperations.listManaged(scope: .user, environment: f.environment).count == 1) + #expect(try SkillOperations.listInstalled(scope: .user, environment: f.environment).count == 1) + #expect(try SkillOperations.doctor(scope: .user, environment: f.environment).checks.isEmpty) + _ = try UpdateOperations.withPreparedUpdate(scope: .user, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + try f.advance() + _ = try SkillOperations.updateInstalled(scope: .user, environment: f.environment, apply: true) + #expect( + try String(contentsOf: target.appendingPathComponent("SKILL.md"), encoding: .utf8).contains( + "new")) + try FileManager.default.removeItem(at: target) + _ = try SkillOperations.installResolvedReport(scope: .user, environment: f.environment) + #expect( + try UpdateOperations.inspect(scope: .user, environment: f.environment).deployments.allSatisfy + { $0.status == .current }) + if mode == .edit { + let alternate = f.root.appendingPathComponent("equal-live-source") + try FileManager.default.copyItem( + at: f.repo.appendingPathComponent("skills/demo"), to: alternate) + try FileManager.default.removeItem(at: target) + try FileManager.default.createSymbolicLink(at: target, withDestinationURL: alternate) + let drift = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(drift.deployments.first?.status == .drifted) + _ = try SkillOperations.installResolvedReport(scope: .user, environment: f.environment) + #expect( + try UpdateOperations.inspect(scope: .user, environment: f.environment).deployments.first? + .status == .current) + } + _ = try SkillOperations.remove(skillNames: ["demo"], scope: .user, environment: f.environment) + #expect(!FileManager.default.fileExists(atPath: target.path)) + #expect(try SkillOperations.listManaged(scope: .user, environment: f.environment).isEmpty) + } +} diff --git a/Tests/AgentsUpdatesTests/FirstUserDeclarationTests.swift b/Tests/AgentsUpdatesTests/FirstUserDeclarationTests.swift index a2813b7..b0a842c 100644 --- a/Tests/AgentsUpdatesTests/FirstUserDeclarationTests.swift +++ b/Tests/AgentsUpdatesTests/FirstUserDeclarationTests.swift @@ -1,9 +1,10 @@ import AgentsCore import AgentsManifest -import AgentsUpdates import Foundation import Testing +@testable import AgentsUpdates + struct FirstUserDeclarationTests { @Test func firstUserMCPDeclarationCanConfirmPurePreview() throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent( @@ -23,6 +24,11 @@ struct FirstUserDeclarationTests { let before = try FileHash.folderHash(root) let preview = try UpdateOperations.preview(request, scope: .user, environment: environment) #expect(try FileHash.folderHash(root) == before) + let selectedText = try #require(preview.components.first?.symbolicAfter) + let selectedFields = try #require( + JSONSerialization.jsonObject(with: Data(selectedText.utf8)) as? [String: Any]) + #expect(selectedFields["command"] as? String == "fixture-command") + #expect(selectedFields["kind"] == nil && selectedFields["object"] == nil) #expect( try UpdateOperations.preview(request, scope: .user, environment: environment) .displayedFingerprint == preview.displayedFingerprint) @@ -36,6 +42,48 @@ struct FirstUserDeclarationTests { let config = root.appendingPathComponent(".codex/config.toml") #expect(try String(contentsOf: config, encoding: .utf8).contains("fixture-command")) } + @Test func readablePreviewContainsOnlySelectedSymbolicConfiguration() throws { + let f = try UpdateFixture() + let sibling = "UNMANAGED-SIBLING-MUST-STAY-PRIVATE" + let config = f.root.appendingPathComponent(".mcp.json") + try f.write( + "{\"mcpServers\":{\"unmanaged\":{\"command\":\"" + sibling + "\"}}}", to: config) + try f.store.save( + declaration: Declaration(components: [ + .mcpServer( + name: "selected", transport: .stdio(.init(executable: "fixture-command")), + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + let before = try FileHash.folderHash(f.root) + let preview = try f.preview() + #expect(try FileHash.folderHash(f.root) == before) + #expect(preview.components.first?.symbolicBefore == nil) + let after = try #require(preview.components.first?.symbolicAfter) + #expect(after.contains("fixture-command")) + #expect(!after.contains(sibling) && !after.contains("unmanaged")) + #expect(!String(decoding: try JSONEncoder().encode(preview), as: UTF8.self).contains(sibling)) + _ = try UpdateOperations.withPreparedUpdate(environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + #expect(try String(contentsOf: config, encoding: .utf8).contains(sibling)) + } + + @Test func readableProjectionPreservesNumericLexemesAndSymbolicReferences() throws { + let payload = LedgerValue(object: [ + "limit": .init("1e200", kind: .decimal), + "environment": .init("FIXTURE_INPUT", kind: .environment), + "credential": .init("fixture-token", kind: .secret), + "text": .init("quoted \"field\"\nnext line"), + ]) + let rendered = try UpdateOperations.symbolicConfigurationText(payload) + #expect(rendered.contains("1e200")) + let fields = try #require( + JSONSerialization.jsonObject(with: Data(rendered.utf8)) as? [String: Any]) + #expect((fields["environment"] as? [String: String])?["environment"] == "FIXTURE_INPUT") + #expect((fields["credential"] as? [String: String])?["secret"] == "fixture-token") + #expect(fields["text"] as? String == "quoted \"field\"\nnext line") + } + @Test func nativeAccessChangeInvalidatesDisplayedConfirmation() throws { let f = try UpdateFixture(scope: .user) try f.store.save( diff --git a/Tests/AgentsUpdatesTests/InitializationIntegrationTests.swift b/Tests/AgentsUpdatesTests/InitializationIntegrationTests.swift index 347d3d4..9d521f8 100644 --- a/Tests/AgentsUpdatesTests/InitializationIntegrationTests.swift +++ b/Tests/AgentsUpdatesTests/InitializationIntegrationTests.swift @@ -39,6 +39,22 @@ import Testing #expect(try UpdateOperations.initialize(description).result.get().path == directory.path) } + @Test func namedSkillUnderAbsentSelectedDirectoryCapturesBothLevels() throws { + let f = try UpdateFixture() + let directory = f.root.appendingPathComponent("Chosen Directory") + let before = try FileSnapshot.read(at: f.root) + let description = try UpdateOperations.describeSkillInitialization( + named: "My Skill", directory: directory, environment: f.environment) + #expect(description.existingRoot.path == f.root.path) + #expect(description.file == directory.appendingPathComponent("my-skill/SKILL.md")) + #expect(try FileSnapshot.read(at: f.root) == before) + let completion = UpdateOperations.initialize(description) + let result = try completion.result.get() + #expect(result.path == directory.appendingPathComponent("my-skill").path) + #expect(completion.disposition == .committed && !completion.recovery.pending) + #expect(try String(contentsOf: description.file, encoding: .utf8) == description.template) + } + @Test(arguments: [false, true]) func missingOrReplacedObservedProjectIsNeverRecreated(_ replace: Bool) throws { let f = try UpdateFixture() diff --git a/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift b/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift index f13cac8..6c1c36b 100644 --- a/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift +++ b/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift @@ -139,9 +139,12 @@ struct PrivateNativeCompositionTests { } extension PrivateNativeCompositionTests { - @Test func opaqueFrozenTreeRetainsPrivateClassificationWithoutProviderReplay() throws { + @Test(arguments: [false, true]) + func opaqueFrozenTreeRetainsPrivateClassificationWithoutProviderReplay(_ separateProducer: Bool) + throws + { let f = try UpdateFixture() - let source = f.root.appendingPathComponent("native-source") + let source = separateProducer ? f.root.appendingPathComponent("native-source") : f.root let tree = source.appendingPathComponent("demo-plugin") let manifest = Data("{\"name\":\"demo-plugin\",\"version\":\"1.0.0\"}".utf8) let executable = Data("#!/bin/sh\n# Not executed.\n".utf8) @@ -200,6 +203,15 @@ extension PrivateNativeCompositionTests { #expect( try FileManager.default.destinationOfSymbolicLink( atPath: location.appendingPathComponent("current").path) == "bin/check") + // Exact locked replay must not consult a mutable producer or request a binding. + try FileManager.default.removeItem(at: tree) + try FileManager.default.removeItem(at: location) + _ = try UpdateOperations.restore( + environment: f.environment, bindingProvider: RefuseNativeBindings()) + #expect(try FileHash.folderHash(location) == bytes) + #expect( + try UpdateOperations.inspect(environment: f.environment).deployments.first?.status == .current + ) _ = try UpdateOperations.withPreparedUpdate( .init(operation: .remove, selections: [try #require(current.components.first?.selection)]), environment: f.environment, bindingProvider: RefuseNativeBindings() From b9a30827d1a6a6a53db19b0670ad3a783840ce5d Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:14:08 +0800 Subject: [PATCH 115/171] feat: describe captured MCP connection tests --- .../MCPConnectionOperations.swift | 80 +++++++++++++------ .../MCPConnectionRedaction.swift | 35 ++++++++ .../MCPConnectionResources.swift | 15 +++- .../MCPConnectionSelection.swift | 9 ++- .../MCPConnectionOperationsTests.swift | 64 +++++++++++++++ .../MCPManagedSelectionTests.swift | 8 ++ 6 files changed, 181 insertions(+), 30 deletions(-) create mode 100644 Sources/AgentsUpdates/MCPConnectionRedaction.swift diff --git a/Sources/AgentsUpdates/MCPConnectionOperations.swift b/Sources/AgentsUpdates/MCPConnectionOperations.swift index 4e2e547..e6d4621 100644 --- a/Sources/AgentsUpdates/MCPConnectionOperations.swift +++ b/Sources/AgentsUpdates/MCPConnectionOperations.swift @@ -13,6 +13,9 @@ public struct MCPConnectionSnapshot: Sendable, CustomStringConvertible, { public let id: UUID public let selectionID: String + var durableReadLocations: [URL] + /// Durable invalidation inputs; never borrowed or per-test staging directories. + public var readLocations: [URL] { durableReadLocations } fileprivate let inputBytes: Int fileprivate let transport: MCPTransportDeclaration fileprivate let directory: MCPConnectionResource? @@ -29,6 +32,16 @@ public struct MCPConnectionDescription: Codable, Sendable, Equatable { public let startsOwnedProcess: Bool public let requiredBindings: [String] public let environmentBindings: [String] + /// Display text only; never reconstruct a command from this redacted projection. + public let executable: String? + public let arguments: [String]? + public let workingDirectory: String? + /// Captured paths identify fixed source content, not a future staging location. + public let executableIsCaptured: Bool + public let workingDirectoryIsCaptured: Bool + /// Origin with path/query withheld; no header or credential values are exposed. + public let endpoint: String? + public let readLocations: [URL] } /// Protocol time excludes the separately bounded owned cleanup. The total timer @@ -165,6 +178,11 @@ public enum MCPConnectionOperations { } return MCPConnectionSnapshot( id: UUID(), selectionID: selectionID, + durableReadLocations: Array( + Set( + (workingDirectory?.readLocations ?? []) + (executable?.readLocations ?? []) + ) + ).sorted { $0.path < $1.path }, inputBytes: MCPConnectionLimits().inputBytes - remaining, transport: transport, directory: workingDirectory, executable: executable) @@ -173,6 +191,33 @@ public enum MCPConnectionOperations { /// Pure metadata projection: no filesystem, provider, process or network access. public static func describe(_ snapshot: MCPConnectionSnapshot) -> MCPConnectionDescription { let bindings = snapshot.transport.bindings.values + var privateValues = bindings.compactMap { + if case .literal(let value) = $0 { value } else { nil } + } + if snapshot.transport.kind != .stdio { + privateValues += privateValues.flatMap { + $0.split(whereSeparator: { $0.isWhitespace }).map(String.init) + } + } + let redaction = MCPConnectionRedaction( + privateValues: privateValues, byteLimit: MCPConnectionLimits().textBytes) + var executable: String? + var arguments: [String]? + var directory: String? + var endpoint: String? + switch snapshot.transport { + case .stdio(let run): + executable = redaction.text(run.executable) + arguments = run.arguments.map(redaction.text) + directory = snapshot.directory.map { redaction.text($0.displayPath) } + case .streamableHTTP(let url, _), .sse(let url, _): + if var origin = URLComponents(string: url) { + let withheld = !origin.percentEncodedPath.isEmpty || origin.percentEncodedQuery != nil + origin.percentEncodedPath = "" + origin.percentEncodedQuery = nil + endpoint = redaction.text((origin.string ?? "[redacted]") + (withheld ? "/[redacted]" : "")) + } + } return MCPConnectionDescription( snapshotID: snapshot.id, transport: snapshot.transport.kind, startsOwnedProcess: snapshot.transport.kind == .stdio, @@ -181,7 +226,11 @@ public enum MCPConnectionOperations { ).sorted(), environmentBindings: Set( bindings.compactMap { if case .environment(let name) = $0 { name } else { nil } } - ).sorted()) + ).sorted(), + executable: executable, arguments: arguments, workingDirectory: directory, + executableIsCaptured: snapshot.executable?.isCaptured ?? false, + workingDirectoryIsCaptured: snapshot.directory?.isCaptured ?? false, + endpoint: endpoint, readLocations: snapshot.readLocations) } /// Tests only this selected value, never a refreshed source or matching name. @@ -330,33 +379,12 @@ public enum MCPConnectionOperations { outcome = .failed issue = .init(rawValue: error.rawValue) } - func withoutControls(_ value: String) -> String { - String(value.unicodeScalars.filter { !CharacterSet.controlCharacters.contains($0) }) - } - // Match the final text projection, including private values containing - // controls. No character removal may join text after this masking pass. - let redactions = Set(privateValues.map(withoutControls).filter { !$0.isEmpty }).sorted { - $0.count > $1.count - } - let expression = try NSRegularExpression( - pattern: redactions.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|")) - func redact(_ value: String) -> String { - let filtered = withoutControls(value) - let text = - redactions.isEmpty - ? filtered - : expression.stringByReplacingMatches( - in: filtered, range: NSRange(filtered.startIndex..., in: filtered), - withTemplate: "[redacted]") - var bytes = Data(text.utf8.prefix(options.limits.textBytes)) - // A byte cap may split the last Unicode scalar; remove only that suffix. - while String(data: bytes, encoding: .utf8) == nil { bytes.removeLast() } - return String(decoding: bytes, as: UTF8.self) - } + let redaction = MCPConnectionRedaction( + privateValues: privateValues, byteLimit: options.limits.textBytes) tools = result.tools.map { .init( - name: redact($0.name), title: $0.title.map(redact), - description: $0.description.map(redact)) + name: redaction.text($0.name), title: $0.title.map(redaction.text), + description: $0.description.map(redaction.text)) } } catch is CancellationError { issue = .cancelled diff --git a/Sources/AgentsUpdates/MCPConnectionRedaction.swift b/Sources/AgentsUpdates/MCPConnectionRedaction.swift new file mode 100644 index 0000000..b853f23 --- /dev/null +++ b/Sources/AgentsUpdates/MCPConnectionRedaction.swift @@ -0,0 +1,35 @@ +import Foundation + +/// One final public text projection: controls are removed before known private +/// values are masked, then the valid UTF8 result is bounded in bytes. +struct MCPConnectionRedaction { + private let expression: NSRegularExpression? + private let byteLimit: Int + private let hasPrivateValues: Bool + init(privateValues: [String], byteLimit: Int) { + self.byteLimit = byteLimit + let values = Set(privateValues.map(Self.withoutControls).filter { !$0.isEmpty }).sorted { + $0.count > $1.count + } + hasPrivateValues = !values.isEmpty + expression = + values.isEmpty + ? nil + : try? NSRegularExpression( + pattern: values.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|")) + } + func text(_ value: String) -> String { + guard !hasPrivateValues || expression != nil else { return "[redacted]" } + let filtered = Self.withoutControls(value) + let text = + expression?.stringByReplacingMatches( + in: filtered, range: NSRange(filtered.startIndex..., in: filtered), + withTemplate: "[redacted]") ?? filtered + var bytes = Data(text.utf8.prefix(byteLimit)) + while String(data: bytes, encoding: .utf8) == nil { bytes.removeLast() } + return String(decoding: bytes, as: UTF8.self) + } + private static func withoutControls(_ value: String) -> String { + String(value.unicodeScalars.filter { !CharacterSet.controlCharacters.contains($0) }) + } +} diff --git a/Sources/AgentsUpdates/MCPConnectionResources.swift b/Sources/AgentsUpdates/MCPConnectionResources.swift index 89084f0..9bf3554 100644 --- a/Sources/AgentsUpdates/MCPConnectionResources.swift +++ b/Sources/AgentsUpdates/MCPConnectionResources.swift @@ -18,12 +18,20 @@ public struct MCPConnectionResource: Sendable, CustomStringConvertible, let realPath: String } private let storage: Storage + private let sourcePath: String let directory: Bool let byteCount: Int var sensitivePaths: [String] { if case .live(let url, let identity) = storage { return [url.path, identity.realPath] } return [] } + var isCaptured: Bool { + if case .captured = storage { true } else { false } + } + var displayPath: String { sourcePath } + var readLocations: [URL] { + sensitivePaths.map { URL(fileURLWithPath: $0).standardizedFileURL } + } public var description: String { "" } public var debugDescription: String { description } public var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } @@ -40,7 +48,8 @@ public struct MCPConnectionResource: Sendable, CustomStringConvertible, guard directory || attributes[.type] as? FileAttributeType == .typeRegular else { throw MCPConnectionPreparationError.invalidResource } - return Self(storage: .live(url, identity), directory: directory, byteCount: 0) + return Self( + storage: .live(url, identity), sourcePath: url.path, directory: directory, byteCount: 0) } catch { throw MCPConnectionPreparationError.invalidResource } } @@ -73,7 +82,7 @@ public struct MCPConnectionResource: Sendable, CustomStringConvertible, let count = (captured.entries + captured.support).reduce(0) { $0 + ($1.byteCount ?? 0) } return Self( storage: .captured(resource, captured.objects, expectedExecutableFiles), - directory: directory, byteCount: count) + sourcePath: resource.path, directory: directory, byteCount: count) } catch is CancellationError { throw CancellationError() } catch let error as MCPConnectionPreparationError { @@ -136,7 +145,7 @@ public struct MCPConnectionResource: Sendable, CustomStringConvertible, let count = (captured.entries + captured.support).reduce(0) { $0 + ($1.byteCount ?? 0) } return Self( storage: .captured(retained, captured.objects, captured.flags), - directory: type == .typeDirectory, byteCount: count) + sourcePath: resource.path, directory: type == .typeDirectory, byteCount: count) } try FileManager.default.removeItem(at: workspace) return try result.get() diff --git a/Sources/AgentsUpdates/MCPConnectionSelection.swift b/Sources/AgentsUpdates/MCPConnectionSelection.swift index 81fac86..f66bfa3 100644 --- a/Sources/AgentsUpdates/MCPConnectionSelection.swift +++ b/Sources/AgentsUpdates/MCPConnectionSelection.swift @@ -85,9 +85,16 @@ extension MCPConnectionOperations { try run.workingDirectory == nil ? .live(environment.projectDirectory) : capture() } guard resources.next() == nil else { throw MCPConnectionPreparationError.invalidResource } - let result = try snapshot( + var result = try snapshot( selectionID: selection.identity, transport: transport, workingDirectory: directory, executable: executable) + result.durableReadLocations = Array( + Set( + result.readLocations + + (try UpdateOperations.readLocations( + declarations: [], ledgers: [ledger], store: store)) + ) + ).sorted { $0.path < $1.path } try baseline.validate() return result } diff --git a/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift b/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift index d8f7db0..cd54da8 100644 --- a/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift +++ b/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift @@ -148,6 +148,70 @@ final class MCPFacadeFixture { try fixture.unchanged() } + @Test func confirmationShowsFixedCommandAndSafeEndpointWithoutEffects() throws { + let fixture = try MCPFacadeFixture() + let live = try MCPConnectionResource.live(fixture.root) + let snapshot = try MCPConnectionOperations.snapshot( + selectionID: "description-only", + transport: .stdio( + .init( + executable: "safe-command", arguments: ["--mode", "read-only", "literal-\ncanary", "é"], + environment: ["TOKEN": .literal("literal-canary"), "SECRET": .secret("named-secret")])), + workingDirectory: live) + let before = try FileHash.folderHash(fixture.root) + let description = MCPConnectionOperations.describe(snapshot) + #expect(description.executable == "safe-command") + #expect(description.arguments == ["--mode", "read-only", "[redacted]", "é"]) + #expect(description.workingDirectory == fixture.root.path) + #expect(!description.workingDirectoryIsCaptured && !description.executableIsCaptured) + #expect(description.endpoint == nil && description.startsOwnedProcess) + #expect(description.requiredBindings == ["named-secret"]) + #expect(description.readLocations == snapshot.readLocations) + #expect(snapshot.readLocations.contains { $0.path == fixture.root.path }) + #expect(try FileHash.folderHash(fixture.root) == before && fixture.text("pid") == nil) + for transport: MCPTransportDeclaration in [ + .sse( + url: "http://127.0.0.1:1/private-path?token=query-canary", + headers: [ + "Authorization": .literal("header-canary"), "X-Secret": .secret("remote-secret"), + ]), + .streamableHTTP(url: "http://127.0.0.1:1/private-path?token=query-canary", headers: [:]), + ] { + // Projection only. No test() call is admitted for these endpoint values. + let remote = try MCPConnectionOperations.snapshot(selectionID: "remote", transport: transport) + let info = MCPConnectionOperations.describe(remote) + #expect(info.endpoint == "http://127.0.0.1:1/[redacted]") + #expect(!info.startsOwnedProcess && info.executable == nil && info.arguments == nil) + #expect(info.workingDirectory == nil && info.readLocations.isEmpty) + let text = String(decoding: try JSONEncoder().encode(info), as: UTF8.self) + for hidden in ["private-path", "query-canary", "header-canary"] { + #expect(!text.contains(hidden)) + } + } + let credentialInOrigin = try MCPConnectionOperations.snapshot( + selectionID: "header-redaction-only", + transport: .sse( + url: "http://127.0.0.1:1/mcp", + headers: [ + "Authorization": .literal("Bearer 127.0.0.1") + ])) + #expect( + MCPConnectionOperations.describe(credentialInOrigin).endpoint + == "http://[redacted]:1/[redacted]") + let long = try MCPConnectionOperations.snapshot( + selectionID: "bounded", + transport: .stdio( + .init( + executable: "safe-command", arguments: ["a" + String(repeating: "é", count: 20_000)])), + workingDirectory: live) + let projected = try #require(MCPConnectionOperations.describe(long).arguments?.first) + #expect(projected.utf8.count == 4095 && projected.hasPrefix("a")) + #expect(String(data: Data(projected.utf8), encoding: .utf8) != nil) + #expect(fixture.text("pid") == nil) + try FileManager.default.removeItem(at: fixture.root) + #expect(MCPConnectionOperations.describe(snapshot) == description) + } + @Test func invalidOptionsAndUnavailableEnvironmentDoNotConsultProvider() async throws { let fixture = try MCPFacadeFixture() let spy = MCPBindingSpy() diff --git a/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift b/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift index 496622a..dba4257 100644 --- a/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift +++ b/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift @@ -119,6 +119,14 @@ private struct ManagedMCPFixture { let snapshot = try MCPConnectionOperations.snapshot( selection: selected.occurrences[0].selection, scope: .project, environment: f.fixture.environment) + let description = MCPConnectionOperations.describe(snapshot) + #expect(description.executable == "./tool" && description.executableIsCaptured) + #expect(description.workingDirectory == "cwd" && description.workingDirectoryIsCaptured) + #expect(snapshot.readLocations.contains(f.store.declarationURL)) + #expect(snapshot.readLocations.contains(f.store.resolvedURL)) + #expect(snapshot.readLocations.contains(f.store.watchURL)) + #expect(description.readLocations == snapshot.readLocations) + #expect(!snapshot.readLocations.contains { $0.path.contains("agents-mcp-capture-") }) let spy = MCPBindingSpy(["wanted": Data("provider-canary".utf8)]) #expect(MCPConnectionOperations.describe(snapshot).requiredBindings == ["wanted"]) #expect(spy.calls.isEmpty) From bd1e157ede4cf7e259499abdcbb56801a787b93c Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:14:08 +0800 Subject: [PATCH 116/171] fix: validate complete plugin parent relations --- Sources/AgentsCore/LedgerValidation.swift | 8 +- .../ComponentsTests/PluginLinkingTests.swift | 76 +++++++++++++++++++ 2 files changed, 83 insertions(+), 1 deletion(-) diff --git a/Sources/AgentsCore/LedgerValidation.swift b/Sources/AgentsCore/LedgerValidation.swift index 924617a..bf28a44 100644 --- a/Sources/AgentsCore/LedgerValidation.swift +++ b/Sources/AgentsCore/LedgerValidation.swift @@ -250,7 +250,12 @@ extension ResolvedLedger { } for occurrence in occurrences { if let provenance = occurrence.input { try input(provenance) } - guard let member = occurrence.pluginMember else { continue } + guard let member = occurrence.pluginMember else { + guard components[occurrence.component]?.containerRoot == nil else { + throw CoreError.invalidState("container occurrence lacks plugin member relation") + } + continue + } guard !member.name.isEmpty, !member.name.contains("\0"), member.parent >= 0, member.parent < occurrence.id, let parent = index[member.parent], let expansion = parent.pluginExpansion, @@ -284,6 +289,7 @@ extension ResolvedLedger { guard let expansion = occurrence.pluginExpansion else { continue } guard let component = components[occurrence.component], component.kind == "plugin", component.payload.object?["mode"]?.text == "components", + exact(expansion.source, component.source), occurrence.dependencies.contains(expansion.source), expansion.children == (children[occurrence.id] ?? []).sorted() else { throw CoreError.invalidState("invalid plugin expansion closure") } diff --git a/Tests/ComponentsTests/PluginLinkingTests.swift b/Tests/ComponentsTests/PluginLinkingTests.swift index 922e223..94fe6bd 100644 --- a/Tests/ComponentsTests/PluginLinkingTests.swift +++ b/Tests/ComponentsTests/PluginLinkingTests.swift @@ -249,6 +249,82 @@ struct PluginLinkingTests { } } + @Test func emptyExpansionMustIdentifySelectedProducer() throws { + let fixture = try LinkFixture() + let declaring = fixture.root.appendingPathComponent("declaring") + let selected = fixture.root.appendingPathComponent("selected") + try container(fixture, "one", at: selected) + try fixture.manifest( + """ + version: 1 + sources: {b: {path: "\(selected.path)"}} + exports: [bundle] + groups: {bundle: {components: [{kind: plugin, name: empty, path: one, source: b, select: []}]}} + """, at: declaring) + let ledger = try freeze( + fixture, + """ + version: 1 + sources: {a: {path: "\(declaring.path)"}} + uses: [{source: a, group: bundle}] + """) + let parent = try #require(ledger.occurrences.firstIndex { $0.pluginExpansion != nil }) + let occurrence = ledger.occurrences[parent] + let component = try #require(ledger.components[occurrence.component]) + let expansion = try #require(occurrence.pluginExpansion) + #expect(expansion.children.isEmpty) + #expect(expansion.source == component.source) + #expect(component.declaringSource != component.source) + #expect(occurrence.dependencies.contains(component.declaringSource)) + #expect(occurrence.dependencies.contains(component.source)) + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + #expect(try ResolvedLedgerCodec.decode(bytes, limits: .standard) == ledger) + var wrongProducer = ledger + wrongProducer.occurrences[parent].pluginExpansion!.source = component.declaringSource + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.bytes(wrongProducer), limits: .standard) + } + } + + @Test func everyContainerArrivalNeedsItsParentRelation() throws { + let fixture = try LinkFixture() + try container(fixture, "one", at: fixture.project) + let ledger = try freeze( + fixture, + """ + version: 1 + components: + - {kind: ignore, name: direct, patterns: [temp]} + - {kind: plugin, name: first, path: one, source: ".", select: [command]} + - {kind: plugin, name: repeated, path: one, source: ".", select: [command]} + """) + let members = ledger.occurrences.filter { $0.pluginMember != nil } + #expect(members.count == 2) + #expect(Set(members.map(\.component)).count == 1) + #expect(Set(members.map { $0.pluginMember!.parent }).count == 2) + #expect( + ledger.occurrences.contains { + $0.pluginMember == nil && ledger.components[$0.component]?.containerRoot == nil + && $0.consumerEditable + }) + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + #expect(try ResolvedLedgerCodec.decode(bytes, limits: .standard) == ledger) + for editable in [false, true] { + var orphaned = ledger + var orphan = try #require(members.first) + orphan.id = (ledger.occurrences.map(\.id).max() ?? 0) + 1 + orphan.reference = nil + orphan.pluginMember = nil + orphan.consumerEditable = editable + orphaned.occurrences.append(orphan) + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.bytes(orphaned), limits: .standard) + } + } + } + @Test func strictClosureAndByteExactNoOp() throws { let fixture = try LinkFixture() try container(fixture, "one", at: fixture.project) From f381ca29e5b510fcb6daea18e509c0db19f68139 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:14:08 +0800 Subject: [PATCH 117/171] feat: render selected native plugin components --- .../Adapters/ClaudeComponents.swift | 5 + Sources/Components/CapabilityRegistry.swift | 4 +- Sources/Components/FrozenNativeIdentity.swift | 59 +++- .../Components/NativeComponentLayoutsV1.swift | 15 +- .../Components/NativeComponentLowering.swift | 7 +- .../NativeGeneratedPluginContribution.swift | 282 +++++++++++++++ .../NativeGeneratedPluginLayoutV1.swift | 320 +++++++++++++++++ Sources/Components/NativePluginLayoutV1.swift | 2 +- .../GeneratedPluginTests.swift | 326 ++++++++++++++++++ 9 files changed, 1001 insertions(+), 19 deletions(-) create mode 100644 Sources/Components/NativeGeneratedPluginContribution.swift create mode 100644 Sources/Components/NativeGeneratedPluginLayoutV1.swift create mode 100644 Tests/ComponentsTests/GeneratedPluginTests.swift diff --git a/Sources/Components/Adapters/ClaudeComponents.swift b/Sources/Components/Adapters/ClaudeComponents.swift index 9dcbb7f..519d02e 100644 --- a/Sources/Components/Adapters/ClaudeComponents.swift +++ b/Sources/Components/Adapters/ClaudeComponents.swift @@ -24,6 +24,11 @@ extension ClaudeAdapter { route: .claudeCommand, path: name + ".md", selection: "file", value: .init(try input.frontmatter(fields, body: input.prompt())))) case "subagent": + if input.inPlugin, input.native["permissionMode"] != nil { + throw input.issue( + ["native", "claude-code", "permissionMode"], .unsupported, + "native plugin agents ignore this permission field") + } var fields = try input.checkedNative( NativeComponentFieldsV1.markdownRules(.claudeCode, kind: "subagent")) let name = try input.filename() diff --git a/Sources/Components/CapabilityRegistry.swift b/Sources/Components/CapabilityRegistry.swift index 404d0da..edbc950 100644 --- a/Sources/Components/CapabilityRegistry.swift +++ b/Sources/Components/CapabilityRegistry.swift @@ -160,7 +160,7 @@ extension CapabilityRegistry { } package static func component( _ request: NativeComponentRequest, - kind: DeclaredComponentKind, name: String + kind: DeclaredComponentKind, name: String, inPlugin: Bool = false ) throws -> NativeComponentDescriptor { func issue(_ field: String, _ reason: NativeAdapterIssue.Reason, _ detail: String) -> NativeComponentIssue @@ -183,7 +183,7 @@ extension CapabilityRegistry { "the pinned TUI dispatch does not register persistent named prompt files") } if request.surface == .cursorCLI - || (request.surface == .cursorEditor && request.scope == .user) + || (request.surface == .cursorEditor && request.scope == .user && !inPlugin) { throw issue( "scope", .unverified, diff --git a/Sources/Components/FrozenNativeIdentity.swift b/Sources/Components/FrozenNativeIdentity.swift index 0c7c567..e0504d7 100644 --- a/Sources/Components/FrozenNativeIdentity.swift +++ b/Sources/Components/FrozenNativeIdentity.swift @@ -1,4 +1,5 @@ import AgentsCore +import Foundation /// Uses C's exact ephemeral pairing, never equal bytes or graph-local occurrence numbers alone. enum FrozenNativeIdentity { @@ -11,22 +12,36 @@ enum FrozenNativeIdentity { try ledger.validate() let sourceIDs = frozen.sources func invalid(_ detail: String) -> CoreError { .invalidState(detail) } - guard linked.recipients.contains(agent), case .declaration(let declaration) = linked.payload, - let name = declaration.name - else { throw invalid("the linked component does not target this recipient") } + guard linked.recipients.contains(agent) else { + throw invalid("the linked component does not target this recipient") + } + let payload: LedgerValue + switch linked.payload { + case .declaration(let declaration): payload = try LedgerPayload.component(declaration) + case .skill(let skill, let mode, let native): + payload = .init(object: [ + "name": .init(skill.name), "description": .init(skill.description), + "mode": .init(mode.rawValue), "native": LedgerPayload.native(native), + ]) + case .instruction: throw invalid("instructions use their existing domain renderer") + } let ids = Set(linked.origins.map(\.occurrence)) let occurrences = ledger.occurrences.filter { ids.contains($0.id) } let owners = Set(occurrences.map(\.component)) guard !ids.isEmpty, occurrences.count == ids.count, owners.count == 1, let id = owners.first, let record = ledger.components[id], - record.kind == linked.key.kind.rawValue, record.kind == declaration.kind.rawValue, - record.name == name, + record.kind == linked.key.kind.rawValue, + record.name.utf8.elementsEqual(linked.key.name.utf8), record.chatGPT == linked.chatGPT, record.declaringSource == sourceIDs[linked.declaringSnapshot], - record.source == sourceIDs[linked.snapshot], linked.key.source == linked.snapshot.source, + record.source == sourceIDs[linked.snapshot], + linked.key.source.utf8.elementsEqual(linked.declaringSnapshot.source.utf8), record.revision == linked.pin?.revision, record.version == linked.pin?.version, - record.root == linked.key.root, record.group == linked.key.group, - record.payload == (try LedgerPayload.component(declaration)), + record.root.utf8.elementsEqual(linked.key.root.utf8), + record.group.map({ Data($0.utf8) }) == linked.key.group.map({ Data($0.utf8) }), + record.containerRoot.map({ Data($0.utf8) }) + == linked.key.containerRoot.map({ Data($0.utf8) }), + try ResolvedLedgerCodec.bytes(record.payload) == ResolvedLedgerCodec.bytes(payload), record.conditions == linked.conditions.map(LedgerCondition.init), Set(record.recipients) == linked.recipients, record.resources.count == linked.resources.count @@ -38,13 +53,32 @@ enum FrozenNativeIdentity { origin.dependencies.compactMap({ sourceIDs[$0] }) == frozen.dependencies, origin.dependencies.allSatisfy({ sourceIDs[$0] != nil }), LedgerCondition(origin.condition) == frozen.condition, - origin.provenance.relativePath == frozen.manifestPath, + origin.provenance.relativePath.utf8.elementsEqual(frozen.manifestPath.utf8), Set(origin.recipients) == Set(frozen.recipients), - origin.consumerEditable == frozen.consumerEditable + origin.consumerEditable == frozen.consumerEditable, + origin.provenance.pointer.map({ Data($0.utf8) }) + == frozen.input?.pointer.map({ Data($0.utf8) }), + (origin.provenance.format == "yaml" + ? nil + : LedgerInputProvenance( + format: origin.provenance.format, adapterVersion: origin.provenance.adapterVersion, + pointer: origin.provenance.pointer)) == frozen.input, + origin.pluginMember.map { member in + let selector = LedgerPayload.reference(member.selector).object! + return LedgerPluginMember( + parent: member.parentOccurrence, + kind: selector["kind"]!.text!, name: selector["name"]!.text!) + } == frozen.pluginMember, + origin.pluginExpansion.map { expansion in + LedgerPluginExpansion( + source: sourceIDs[expansion.snapshot] ?? "", root: expansion.root, + containerRoot: expansion.containerRoot, document: expansion.document, + input: expansion.input, children: expansion.children) + } == frozen.pluginExpansion else { throw invalid("linked origin and frozen occurrence do not match") } } for (resource, frozen) in zip(linked.resources, record.resources) { - guard let item = ledger.resources[frozen], item.path == resource.path, + guard let item = ledger.resources[frozen], item.path.utf8.elementsEqual(resource.path.utf8), item.source == sourceIDs[resource.snapshot], item.artifact == resource.artifact, item.hash == resource.hash, try ResolvedLedgerCodec.digest(item) == frozen else { throw invalid("linked resource and frozen evidence do not match") } @@ -120,6 +154,9 @@ enum FrozenNativeIdentity { } } let target = path.isEmpty ? "." : path.joined(separator: "/") + if let entry = entries[target], entry.kind == .file { + return [resource.path: entry.executable] + } guard entries[target]?.kind == .directory else { throw CoreError.invalidState("selected native resource link is not a directory") } diff --git a/Sources/Components/NativeComponentLayoutsV1.swift b/Sources/Components/NativeComponentLayoutsV1.swift index f70fe83..3a00f7a 100644 --- a/Sources/Components/NativeComponentLayoutsV1.swift +++ b/Sources/Components/NativeComponentLayoutsV1.swift @@ -25,7 +25,7 @@ package enum NativeComponentLayoutsV1 { "agents/cursor-components@1": { try render($0, $1, $2, limits: limits, surface: .cursorEditor) }, - ] + ].merging(NativeGeneratedPluginLayoutV1.renderers(limits: limits)) { existing, _ in existing } } private static func render( @@ -55,7 +55,8 @@ package enum NativeComponentLayoutsV1 { ) throws -> ComponentRenderInput { func invalid() -> CoreError { .invalidState("invalid version 1 native component layout") } guard lowering.layout.kind == .object, let layout = lowering.layout.object, - Set(layout.keys) == ["surface", "scope", "occurrences"], + Set(layout.keys).subtracting(["inPlugin"]) == ["surface", "scope", "occurrences"], + layout["inPlugin"] == nil || layout["inPlugin"] == .init(boolean: true), layout["surface"]?.kind == .string, let declared = layout["surface"]?.text.flatMap(NativeClientSurface.init(rawValue:)), layout["scope"]?.kind == .string, @@ -80,10 +81,18 @@ package enum NativeComponentLayoutsV1 { && ($0.condition.platforms?.contains(lowering.platform) ?? true) }) else { throw invalid() } + if layout["inPlugin"] != nil, + !ledger.occurrences.filter({ occurrences.contains($0.id) }).allSatisfy({ + $0.pluginMember != nil + }) + { + throw invalid() + } let input = ComponentRenderInput( record: record, component: component, request: .init(surface: declared, scope: scope), occurrences: occurrences, - resources: resources ?? [:], ledger: ledger, limits: limits) + resources: resources ?? [:], ledger: ledger, limits: limits, + inPlugin: layout["inPlugin"] != nil) if let resources, !record.resources.allSatisfy({ resources[$0] != nil }) { throw invalid() } diff --git a/Sources/Components/NativeComponentLowering.swift b/Sources/Components/NativeComponentLowering.swift index c70e2c7..af590dd 100644 --- a/Sources/Components/NativeComponentLowering.swift +++ b/Sources/Components/NativeComponentLowering.swift @@ -100,10 +100,13 @@ struct ComponentRenderInput { let ledger: ResolvedLedger let limits: LedgerLimits let budget: NativeDocumentBudget + let inPlugin: Bool init( record: LedgerComponent, component: String, request: NativeComponentRequest, - occurrences: [Int], resources: [String: URL], ledger: ResolvedLedger, limits: LedgerLimits + occurrences: [Int], resources: [String: URL], ledger: ResolvedLedger, limits: LedgerLimits, + inPlugin: Bool = false ) { + self.inPlugin = inPlugin self.record = record self.component = component self.request = request @@ -184,7 +187,7 @@ struct ComponentRenderInput { guard let kind = DeclaredComponentKind(rawValue: record.kind) else { throw issue(["kind"], .invalid, "invalid frozen component kind") } - _ = try CapabilityRegistry.component(request, kind: kind, name: record.name) + _ = try CapabilityRegistry.component(request, kind: kind, name: record.name, inPlugin: inPlugin) if kind == .ignore, fields["purpose"]?.text != "context" { throw issue( ["purpose"], .unverified, "a distinct current indexing-only contract is not established") diff --git a/Sources/Components/NativeGeneratedPluginContribution.swift b/Sources/Components/NativeGeneratedPluginContribution.swift new file mode 100644 index 0000000..054a0d2 --- /dev/null +++ b/Sources/Components/NativeGeneratedPluginContribution.swift @@ -0,0 +1,282 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// Registration is the existing closed named-directory recipe. E owns reader union, all physical +/// writes, owner retirement, private receipts and publication. Members never become direct owners. +package struct NativeGeneratedPluginContribution { + package let request: NativeComponentRequest + package let component: String + package let directory: String + package let route: NativeComponentRoute + package let manifestPath: String + package let occurrences: [Int] + package let recipients: [AgentID] + package let knownReaders: [AgentID] + package let members: [Member] + package let resources: [String: LedgerResource] + private let metadata: [String: NativeValue] + + package struct Member { + package let component: String + package let occurrences: [Int] + package let content: Content + package enum Content { + case component(NativeComponentContribution) + case mcp(NativeMCPContribution) + case skill(name: String, resource: String) + } + } + + /// E materializes these exact frozen resource roots through Core, including supporting links + /// and file modes; it admits final paths before calling stagedBundle. No copy is performed here. + package struct ResourcePlacement { + package let resource: String + package let path: String + } + package var resourcePlacements: [ResourcePlacement] { + let skills = members.compactMap { member -> ResourcePlacement? in + if case .skill(let name, let resource) = member.content { + return .init(resource: resource, path: "skills/" + name) + } + return nil + } + let skillResources = Set(skills.map(\.resource)) + return skills + + resources.keys.sorted().filter { !skillResources.contains($0) }.map { + .init(resource: $0, path: "resources/" + $0.replacingOccurrences(of: "sha256:", with: "")) + } + } + + package struct Bundle { + /// UTF8 native files are nonexecutable. Resource modes are on the frozen resource entries. + package let files: [String: Data] + /// JSON document values for the existing NativeDocuments writer, including the manifest. + package let documents: [String: NativeValue] + } + + /// Invoke only inside D/E's private render closure. Values and intermediate bundle documents + /// are ephemeral; never persist them in the public lowering, content store, report or hashes. + package func stagedBundle( + bindings: RuntimeBindingValues, environment: RuntimeEnvironment, + resourcePaths: [String: String], budget: NativeDocumentBudget, + cursorCommandShell: NativeProgramV1.CommandShell? = nil + ) throws -> Bundle { + var files: [String: Data] = [:] + var manifest = metadata + manifest["name"] = .string(directory) + var hooks: [String: [NativeValue]] = [:] + var servers: [String: NativeValue] = [:] + var lsps: [String: NativeValue] = [:] + var paths: [String: [NativeValue]] = [:] + func invalid() -> CoreError { .invalidState("invalid generated native bundle composition") } + func put(_ path: String, _ bytes: Data) throws { + try budget.allocate(bytes.count, stage: "generated native file") + try budget.step(bytes.count) + guard files[path] == nil else { throw invalid() } + files[path] = bytes + } + for member in members { + try budget.step() + switch member.content { + case .skill(let name, _): + paths["skills", default: []].append(.string("./skills/" + name)) + case .mcp(let contribution): + guard servers[contribution.name] == nil else { throw invalid() } + servers[contribution.name] = try contribution.stagedValue( + bindings: bindings, environment: environment, resourcePaths: resourcePaths, budget: budget + ) + case .component(let contribution): + for output in contribution.outputs { + switch output.content { + case .file(let path, let bytes): + let field = contribution.kind == .command ? "commands" : "agents" + let relative = field + "/" + path + try put(relative, bytes) + paths[field, default: []].append(.string("./" + relative)) + case .hook(let hook): + if request.surface == .cursorEditor { + // Plugin hooks only support command handlers, regardless of standalone capability. + let value = try hook.value.stagedValue( + bindings: bindings, environment: environment, resourcePaths: resourcePaths, + budget: budget, cursorCommandShell: cursorCommandShell) + guard case .object(let handler) = value, handler["type"] == .string("command") else { + throw invalid() + } + hooks[hook.event, default: []].append(value) + } else { + hooks[hook.event, default: []].append( + try hook.value.stagedValue( + bindings: bindings, environment: environment, resourcePaths: resourcePaths, + budget: budget)) + } + case .generatedLSPPlugin(_, _, let value): + guard request.surface == .claudeCode, + case .object(let fields) = try value.stagedValue( + bindings: bindings, environment: environment, resourcePaths: resourcePaths, + budget: budget), + case .object(let entries) = fields["lspServers"] + else { throw invalid() } + for (name, server) in entries { + guard lsps[name] == nil else { throw invalid() } + lsps[name] = server + } + default: throw invalid() + } + } + } + } + var documents: [String: NativeValue] = [:] + if !hooks.isEmpty { + var value: [String: NativeValue] = ["hooks": .object(hooks.mapValues(NativeValue.array))] + if request.surface == .cursorEditor { value["version"] = .integer(1) } + if request.surface == .claudeCode { + manifest["hooks"] = .object(hooks.mapValues(NativeValue.array)) + } else { + documents["hooks/hooks.json"] = .object(value) + if request.surface == .cursorEditor { manifest["hooks"] = .string("./hooks/hooks.json") } + } + } + if !servers.isEmpty { + if request.surface == .cursorEditor { + documents["mcp.json"] = .object(["mcpServers": .object(servers)]) + manifest["mcpServers"] = .string("./mcp.json") + } else { + manifest["mcpServers"] = .object(servers) + } + } + if !lsps.isEmpty { manifest["lspServers"] = .object(lsps) } + if request.surface != .geminiCLI { + for (field, values) in paths { manifest[field] = .array(values) } + } + documents[manifestPath] = .object(manifest) + return .init(files: files, documents: documents) + } + + package static func decode( + _ lowering: LockedLowering, ledger: ResolvedLedger, artifacts: [ReplayedArtifact], + limits: LedgerLimits + ) throws -> NativeGeneratedPluginContribution { + let (input, nested, owners) = try NativeGeneratedPluginLayoutV1.decode( + lowering, ledger: ledger, limits: limits) + func invalid() -> CoreError { + .invalidState("invalid sealed generated native plugin contribution") + } + guard ledger.lowerings.filter({ $0.id == lowering.id }) == [lowering], + lowering.artifacts.count == 1, artifacts.count == 1, artifacts[0].name == lowering.id, + artifacts[0].kind == .ownedValues, artifacts[0].location == nil, + let values = artifacts[0].values?.object?["members"]?.array, values.count == nested.count + else { throw invalid() } + try admit(artifacts[0].values!, budget: input.budget) + guard try artifacts[0].digest(limits: limits) == lowering.artifacts[0], + try ResolvedLedgerCodec.bytes(artifacts[0].values!) + == ResolvedLedgerCodec.bytes( + NativeGeneratedPluginLayoutV1.envelope(input, members: values)) + else { throw invalid() } + let (route, manifest) = try NativeGeneratedPluginLayoutV1.recipe(input) + let directory = try input.filename() + if input.request.surface == .claudeCode, !NativePluginFieldsV1.validClaudeName(directory) { + throw invalid() + } + if input.request.surface == .cursorEditor, + directory.range(of: #"^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$"#, options: .regularExpression) + == nil + { + throw invalid() + } + if input.request.surface == .geminiCLI, + directory.range(of: #"^[a-zA-Z0-9-]+$"#, options: .regularExpression) == nil + { + throw invalid() + } + let metadataFields = try input.checkedNative(["version": .string, "description": .string]) + if input.request.surface == .geminiCLI, metadataFields["version"]?.text?.isEmpty != false { + throw input.issue( + ["native", "gemini-cli", "version"], .integrationRequired, + "generated Gemini extensions require explicit frozen native version metadata") + } + var metadata: [String: NativeValue] = [:] + for (key, value) in metadataFields { metadata[key] = .string(value.text!) } + if input.request.surface != .geminiCLI { + _ = try NativeComponentFieldsV1.plugin( + surface: input.request.surface, document: manifest, + fields: metadata.merging(["name": .string(directory)]) { value, _ in value }, + entries: [], documents: [:], budget: input.budget) + } + var members: [Member] = [] + var names = Set() + var nativeNames = Set() + for (index, var child) in nested.enumerated() { + let component = child.inputs[0] + let record = ledger.components[component]! + let identity = record.kind + "/" + record.name + guard names.insert(Data(identity.utf8)).inserted, nativeNames.insert(identity).inserted else { + throw input.issue( + ["children"], .invalid, "native member identities conflict in the generated container") + } + let content: Member.Content + if record.kind == "skills" { + guard + record.payload.object?["native"]?.object?[input.request.surface.agent.rawValue]?.object? + .isEmpty ?? true + else { + throw input.issue( + ["children", "skills", "native"], .unverified, + "native skill options require their exact container interpretation") + } + guard values[index] == .init(), !record.name.isEmpty, + !record.name.contains("/"), !record.name.contains("\\"), record.name != ".", + record.name != ".." + else { throw invalid() } + content = .skill(name: record.name, resource: record.resources[0]) + } else if record.kind == "mcpServer" { + guard values[index] == child.layout else { throw invalid() } + content = .mcp(try MCPLayoutV1.contribution(child, ledger: ledger)) + } else { + let output = ReplayedArtifact(name: child.id, kind: .ownedValues, values: values[index]) + child.artifacts = [try output.digest(limits: limits)] + var childLedger = ledger + childLedger.lowerings = [child] + let contribution = try NativeComponentLayoutsV1.contribution( + child, ledger: childLedger, artifacts: [output], limits: limits) + content = .component(contribution) + } + members.append(.init(component: component, occurrences: owners[index], content: content)) + } + var readers: Set = [input.request.surface.agent] + for member in members { + if case .component(let contribution) = member.content { + readers.formUnion(contribution.knownReaders) + } else if case .mcp(let contribution) = member.content { + readers.formUnion(contribution.descriptor.knownReaders) + } + } + return .init( + request: input.request, component: input.component, directory: directory, route: route, + manifestPath: manifest, occurrences: input.occurrences, + recipients: [input.request.surface.agent], + knownReaders: readers.sorted { $0.rawValue < $1.rawValue }, members: members, + resources: Dictionary( + uniqueKeysWithValues: lowering.resources.map { ($0, ledger.resources[$0]!) }), + metadata: metadata) + } + + static func admit(_ value: LedgerValue, budget: NativeDocumentBudget, depth: Int = 0) throws { + try budget.node(depth: depth) + try budget.step() + if let text = value.text { + try budget.allocate(text.utf8.count, stage: "generated native input") + try budget.step(text.utf8.count) + } + for child in value.array ?? [] { try admit(child, budget: budget, depth: depth + 1) } + for (key, child) in value.object ?? [:] { + try budget.allocate(key.utf8.count, stage: "generated native key") + try budget.step(key.utf8.count) + try admit(child, budget: budget, depth: depth + 1) + } + var node = value + if node.array != nil { node.array = [] } + if node.object != nil { node.object = [:] } + try node.validate() + } +} diff --git a/Sources/Components/NativeGeneratedPluginLayoutV1.swift b/Sources/Components/NativeGeneratedPluginLayoutV1.swift new file mode 100644 index 0000000..63eccd2 --- /dev/null +++ b/Sources/Components/NativeGeneratedPluginLayoutV1.swift @@ -0,0 +1,320 @@ +import AgentsCore +import Foundation + +/// A fixed closure of native members. Cold rendering consumes sealed layouts, never import input. +package enum NativeGeneratedPluginLayoutV1 { + package static func format(_ surface: NativeClientSurface) -> String { + "agents/\(surface.agent.rawValue)-generated-plugin@1" + } + + static func renderers(limits: LedgerLimits) -> [String: LedgerRenderer] { + Dictionary( + uniqueKeysWithValues: [NativeClientSurface.claudeCode, .cursorEditor, .geminiCLI].map { + ( + format($0), + { lowering, ledger, resources in + try render(lowering, ledger: ledger, resources: resources, limits: limits) + } as LedgerRenderer + ) + }) + } + + /// Members must be the actual linked graph frozen by C, including independent occurrences. + /// Only origins reachable through this parent's complete frozen closure enter this lowering. + package static func lower( + _ parent: LinkedComponent, members: [LinkedComponent], frozen: LedgerFreeze.Result, + request: NativeComponentRequest, id: String, platform: DeclarationPlatform + ) throws -> LockedLowering { + let identity = try FrozenNativeIdentity.match( + parent, frozen: frozen, agent: request.surface.agent, scope: request.scope) + let ledger = frozen.ledger + let record = ledger.components[identity.id]! + let input = ComponentRenderInput( + record: record, component: identity.id, request: request, occurrences: identity.occurrences, + resources: [:], ledger: ledger, limits: .standard) + _ = try recipe(input) + guard record.payload.object?["mode"] == .init("components") else { + throw input.issue(["mode"], .invalid, "generated native plugins require typed component mode") + } + let closure = try selectedChildren(input, platform: platform.rawValue) + let grouped = Dictionary(grouping: closure, by: \.component) + var byOrigin: [Int: LinkedComponent] = [:] + for member in members { + for origin in member.origins { + try input.budget.step() + guard byOrigin.updateValue(member, forKey: origin.occurrence) == nil else { + throw input.issue(["children"], .invalid, "duplicate linked native occurrence") + } + } + } + var childLayouts: [LedgerValue] = [] + var inputs = [identity.id] + var resources: [String] = [] + var resourceSet = Set() + var seen = Set() + for occurrence in closure { + guard seen.insert(occurrence.component).inserted else { continue } + let owners = grouped[occurrence.component]!.map(\.id) + let child = ledger.components[occurrence.component]! + guard + ["skills", "mcpServer", "command", "subagent", "hook", "lspServer"].contains(child.kind) + else { + throw input.issue( + ["children", child.kind], .unverified, + "this component has no established generated native container field") + } + inputs.append(occurrence.component) + for resource in child.resources where resourceSet.insert(resource).inserted { + resources.append(resource) + } + let childID = id + "/member/" + String(childLayouts.count) + try input.budget.step(ledger.occurrences.count + ledger.components.count) + let linked = byOrigin[occurrence.id] + guard let linked else { + throw input.issue(["children"], .invalid, "frozen member has no paired linked input") + } + let lowering: LockedLowering + if child.kind == "skills" { + let paired = try FrozenNativeIdentity.match( + linked, frozen: frozen, agent: request.surface.agent, scope: request.scope) + guard case .skill(_, let mode, _) = linked.payload, mode != .edit, + paired.id == occurrence.component, child.resources.count == 1 + else { + throw input.issue( + ["children", "skills"], .invalid, "generated native skill requires frozen content") + } + lowering = .init( + id: childID, format: "native/skill-resource@1", inputs: [occurrence.component], + resources: child.resources, deployments: [], layout: .init(), platform: platform.rawValue, + artifacts: []) + } else if child.kind == "mcpServer" { + let contribution = try NativeMCPLowering.lower( + linked, frozen: frozen, + request: .init(surface: request.surface, scope: request.scope == .user ? .user : .project) + ) + var value = contribution.lowering(id: childID, artifact: childID, platform: platform) + value.layout.object!["occurrences"] = .init(array: owners.map { .init(integer: $0) }) + lowering = value + } else { + let paired = try FrozenNativeIdentity.match( + linked, frozen: frozen, agent: request.surface.agent, scope: request.scope) + guard paired.id == occurrence.component else { + throw input.issue(["children"], .invalid, "frozen native member identity mismatch") + } + let childInput = ComponentRenderInput( + record: child, component: occurrence.component, request: request, occurrences: owners, + resources: [:], ledger: ledger, limits: .standard, inPlugin: true) + try childInput.validateProfile() + lowering = .init( + id: childID, format: NativeComponentLayoutsV1.format(request.surface), + inputs: [occurrence.component], resources: child.resources, deployments: [], + layout: .init(object: [ + "surface": .init(request.surface.rawValue), "scope": .init(request.scope.rawValue), + "occurrences": .init(array: owners.map { .init(integer: $0) }), + "inPlugin": .init(boolean: true), + ]), platform: platform.rawValue, artifacts: []) + } + childLayouts.append(encode(lowering, owners: owners)) + } + return .init( + id: id, format: format(request.surface), inputs: inputs, resources: resources, + deployments: [], + layout: .init(object: [ + "surface": .init(request.surface.rawValue), "scope": .init(request.scope.rawValue), + "occurrences": .init(array: identity.occurrences.map { .init(integer: $0) }), + "members": .init(array: childLayouts), + ]), platform: platform.rawValue, artifacts: []) + } + + static func recipe(_ input: ComponentRenderInput) throws -> (NativeComponentRoute, String) { + switch input.request.surface { + case .claudeCode: return (.claudeSkillPlugin, ".claude-plugin/plugin.json") + case .cursorEditor where input.request.scope == .user: + return (.cursorLocalPlugin, ".cursor-plugin/plugin.json") + case .geminiCLI where input.request.scope == .user: + return (.geminiExtension, "gemini-extension.json") + default: + throw input.issue( + ["scope"], .unverified, + "generated native container registration is not established for this surface/scope") + } + } + + static func selectedChildren(_ input: ComponentRenderInput, platform: String) throws + -> [LedgerOccurrence] + { + var byID: [Int: LedgerOccurrence] = [:] + for occurrence in input.ledger.occurrences { + try input.budget.step() + guard byID.updateValue(occurrence, forKey: occurrence.id) == nil else { + throw input.issue(["occurrences"], .invalid, "duplicate frozen native occurrence identity") + } + } + var result: [LedgerOccurrence] = [] + for parent in input.occurrences { + try input.budget.step() + guard let owner = byID[parent], owner.component == input.component, + let expansion = owner.pluginExpansion, + ["native/claudePluginV1@1", "native/cursorPluginV1@1", "native/geminiExtensionV1@1"] + .contains(expansion.input.format), + expansion.input.adapterVersion == "1" + else { + throw input.issue( + ["children"], .invalid, "complete frozen native expansion evidence is required") + } + for id in expansion.children { + try input.budget.node(depth: 1) + try input.budget.step() + guard let child = byID[id], child.pluginMember?.parent == parent, + let record = input.ledger.components[child.component], + record.containerRoot.map({ Data($0.utf8) }) == Data(expansion.containerRoot.utf8), + record.source == expansion.source + else { throw input.issue(["children"], .invalid, "invalid frozen native member relation") } + if child.recipients.contains(input.request.surface.agent), + child.condition.scopes?.contains(input.request.scope) ?? true, + child.condition.platforms?.contains(platform) ?? true, + child.condition.agents?.contains(input.request.surface.agent) ?? true + { + result.append(child) + } + } + } + return result + } + + static func encode(_ lowering: LockedLowering, owners: [Int]) -> LedgerValue { + .init(object: [ + "id": .init(lowering.id), "format": .init(lowering.format), + "inputs": LedgerPayload.strings(lowering.inputs), + "resources": LedgerPayload.strings(lowering.resources), "layout": lowering.layout, + "occurrences": .init(array: owners.map { .init(integer: $0) }), + ]) + } + + static func decode( + _ lowering: LockedLowering, ledger: ResolvedLedger, limits: LedgerLimits + ) throws -> (ComponentRenderInput, [LockedLowering], [[Int]]) { + func invalid() -> CoreError { .invalidState("invalid sealed generated native plugin layout") } + guard let fields = lowering.layout.object, + Set(fields.keys) == ["surface", "scope", "occurrences", "members"], + let surface = fields["surface"]?.text.flatMap(NativeClientSurface.init(rawValue:)), + let scope = fields["scope"]?.text.flatMap(InstallScope.init(rawValue:)), + lowering.format == format(surface), let parent = lowering.inputs.first, + let record = ledger.components[parent], record.kind == "plugin", + record.payload.object?["mode"] == .init("components"), record.resources.isEmpty, + let ids = fields["occurrences"]?.array, ids.allSatisfy({ $0.kind == .integer }), + !ids.isEmpty, let encoded = fields["members"]?.array + else { throw invalid() } + let owners = ids.compactMap(\.integer) + let ownerSet = Set(owners) + guard ownerSet.count == owners.count, + owners + == ledger.occurrences.filter({ $0.component == parent && ownerSet.contains($0.id) }).map( + \.id), + ledger.occurrences.filter({ ownerSet.contains($0.id) }).allSatisfy({ + $0.recipients.contains(surface.agent) && ($0.condition.scopes?.contains(scope) ?? true) + && ($0.condition.agents?.contains(surface.agent) ?? true) + && ($0.condition.platforms?.contains(lowering.platform) ?? true) + }) + else { throw invalid() } + let input = ComponentRenderInput( + record: record, component: parent, request: .init(surface: surface, scope: scope), + occurrences: owners, resources: [:], ledger: ledger, limits: limits) + try input.validateProfile() + _ = try recipe(input) + // Charge the complete layout before indexing/copying child layouts. + try NativeGeneratedPluginContribution.admit(lowering.layout, budget: input.budget) + let closure = try selectedChildren(input, platform: lowering.platform) + let grouped = Dictionary(grouping: closure, by: \.component) + var expected: [String] = [] + var seen = Set() + for item in closure where seen.insert(item.component).inserted { + expected.append(item.component) + } + guard lowering.inputs == [parent] + expected, encoded.count == expected.count else { + throw invalid() + } + var nested: [LockedLowering] = [] + var memberOwners: [[Int]] = [] + var resources: [String] = [] + var resourceSet = Set() + for (index, value) in encoded.enumerated() { + let component = expected[index] + let record = ledger.components[component]! + let owners = grouped[component]!.map(\.id) + guard let child = value.object, + Set(child.keys) == ["id", "format", "inputs", "resources", "layout", "occurrences"], + child["id"] == .init(lowering.id + "/member/" + String(index)), + child["inputs"] == LedgerPayload.strings([component]), + child["resources"] == LedgerPayload.strings(record.resources), + child["occurrences"] == .init(array: owners.map { .init(integer: $0) }), + let format = child["format"]?.text, let layout = child["layout"] + else { throw invalid() } + let childLowering = LockedLowering( + id: child["id"]!.text!, format: format, inputs: [component], resources: record.resources, + deployments: [], layout: layout, platform: lowering.platform, artifacts: []) + if record.kind == "skills" { + guard format == "native/skill-resource@1", layout == .init(), record.resources.count == 1, + record.payload.object?["mode"] != .init("edit") + else { throw invalid() } + } else if record.kind == "mcpServer" { + let contribution = try MCPLayoutV1.contribution(childLowering, ledger: ledger) + guard contribution.occurrences == owners, + contribution.descriptor.request.surface == surface, + contribution.descriptor.request.scope == (scope == .user ? .user : .project) + else { throw invalid() } + } else { + let parsed = try NativeComponentLayoutsV1.input( + childLowering, ledger: ledger, limits: limits) + guard parsed.inPlugin, parsed.occurrences == owners, parsed.request == input.request, + ["command", "subagent", "hook", "lspServer"].contains(record.kind) + else { throw invalid() } + } + nested.append(childLowering) + memberOwners.append(owners) + for resource in record.resources where resourceSet.insert(resource).inserted { + resources.append(resource) + } + } + guard resources == lowering.resources else { throw invalid() } + return (input, nested, memberOwners) + } + + static func render( + _ lowering: LockedLowering, ledger: ResolvedLedger, resources: [String: URL], + limits: LedgerLimits + ) throws -> [ReplayedArtifact] { + let (input, members, _) = try decode(lowering, ledger: ledger, limits: limits) + let table = NativeComponentLayoutsV1.renderers(limits: limits).merging(MCPLayoutV1.renderers) { + a, _ in a + } + let values = try members.map { member -> LedgerValue in + if member.format == "native/skill-resource@1" { return .init() } + guard let renderer = table[member.format] else { + throw CoreError.invalidState("unknown native member renderer") + } + let artifacts = try renderer(member, ledger, resources) + guard artifacts.count == 1, artifacts[0].kind == .ownedValues, let value = artifacts[0].values + else { + throw CoreError.invalidState("invalid generated native member output") + } + return value + } + return [ + .init(name: lowering.id, kind: .ownedValues, values: try envelope(input, members: values)) + ] + } + static func envelope(_ input: ComponentRenderInput, members: [LedgerValue]) throws -> LedgerValue + { + let (route, manifest) = try recipe(input) + let metadata = try input.checkedNative(["version": .string, "description": .string]) + return .init(object: [ + "component": .init(input.component), "directory": .init(try input.filename()), + "route": .init(route.rawValue), "manifest": .init(manifest), + "metadata": .init(object: metadata), + "occurrences": .init(array: input.occurrences.map { .init(integer: $0) }), + "members": .init(array: members), + ]) + } + +} diff --git a/Sources/Components/NativePluginLayoutV1.swift b/Sources/Components/NativePluginLayoutV1.swift index cf01c9a..0bcc914 100644 --- a/Sources/Components/NativePluginLayoutV1.swift +++ b/Sources/Components/NativePluginLayoutV1.swift @@ -12,7 +12,7 @@ enum NativePluginLayoutV1 { guard input.fields["mode"]?.text == "native" else { throw input.issue( ["mode"], .integrationRequired, - "decomposed plugins require G's typed child declarations linked/frozen with their source provenance" + "decomposed plugins require the frozen-member generated plugin renderer format" ) } guard input.record.recipients == [input.request.surface.agent] else { diff --git a/Tests/ComponentsTests/GeneratedPluginTests.swift b/Tests/ComponentsTests/GeneratedPluginTests.swift new file mode 100644 index 0000000..7fd1f28 --- /dev/null +++ b/Tests/ComponentsTests/GeneratedPluginTests.swift @@ -0,0 +1,326 @@ +import AgentsManifest +import Foundation +import NativeDocuments +import Testing + +@testable import AgentsCore +@testable import Components + +@Suite("Frozen generated native plugins") +struct GeneratedPluginTests { + private func freeze( + _ fixture: LinkFixture, _ expression: String, scope: InstallScope = .project + ) throws -> ([LinkedComponent], LedgerFreeze.Result) { + let store = StateStore(scope: scope, environment: fixture.environment) + return try ComponentLinker.withLinkedComponents( + document: fixture.document(expression), store: store, platform: .macOS + ) { graph, session in + let locations = Dictionary( + (graph.sourceSnapshots + graph.declaringSnapshots).map { + ( + $0.snapshot.source, + LedgerLocation(kind: .absolute, path: String($0.snapshot.source.dropFirst(6))) + ) + }, uniquingKeysWith: { first, _ in first }) + return ( + graph.components, + try LedgerFreeze.freezeWithSources( + graph, session: session, locations: .init(sources: locations), limits: .standard) + ) + } + } + + private func budget() -> NativeDocumentBudget { + .init( + limits: .init( + storage: 32_000_000, work: 100_000_000, nodes: 100_000, depth: 128, + uninterruptedBytes: 1_000_000)) + } + + private func lower( + _ components: [LinkedComponent], _ frozen: LedgerFreeze.Result, + surface: NativeClientSurface = .claudeCode, scope: InstallScope = .project + ) throws -> LockedLowering { + try NativeGeneratedPluginLayoutV1.lower( + components.first { $0.key.kind == .plugin }!, members: components, frozen: frozen, + request: .init(surface: surface, scope: scope), id: "generated", platform: .macOS) + } + + @Test func frozenClosureColdReplayPreservesOrderBindingsResourcesAndRegistration() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"source-name","mcpServers":{"server":{"command":"${CLAUDE_PLUGIN_ROOT}/bin/server","env":{"TOKEN":"private-source-canary"}}},"hooks":{"PreToolUse":[{"matcher":"Read","hooks":[{"type":"command","command":"first"}]},{"matcher":"Write","hooks":[{"type":"command","command":"second"}]}]}}"#, + to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + try fixture.write( + "---\ndescription: Review exactly\n---\nLiteral source body\n", + to: "bundle/commands/review.md", base: fixture.project) + try fixture.write( + "---\nname: inspect\ndescription: Inspect\n---\nInspect exact sources\n", + to: "bundle/agents/inspect.md", base: fixture.project) + try fixture.write( + "---\nname: helper\ndescription: Help\n---\nSkill body\n", + to: "bundle/skills/helper/SKILL.md", base: fixture.project) + try fixture.write( + "#!/bin/sh\n# source-owned, never executed\n", to: "bundle/bin/server", base: fixture.project) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: fixture.project.appendingPathComponent("bundle/bin/server").path) + let (components, frozen) = try freeze( + fixture, + """ + version: 1 + components: + - {kind: plugin, name: selected, source: ".", path: bundle, agents: ["claude-code"]} + - {kind: command, name: review, description: Independent, prompt: Direct body, agents: ["claude-code"]} + """) + var ledger = frozen.ledger + ledger.lowerings = [try lower(components, frozen)] + #expect(ledger.lowerings[0].inputs.count == components.count - 1) + #expect( + !ledger.occurrences.filter { ledger.lowerings[0].inputs.contains($0.component) }.contains { + $0.id == components.last!.origins[0].occurrence + }) + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: .standard) + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + #expect(!String(decoding: encoded, as: UTF8.self).contains("private-source-canary")) + let expected = ledger.lowerings[0].artifacts + try FileManager.default.removeItem(at: fixture.project) + ledger = try ResolvedLedgerCodec.decode(encoded, limits: .standard) + try LedgerReplay.withReplay(ledger, store: fixture.store, roots: [:], limits: .standard) { + artifacts in + #expect(try artifacts.map { try $0.digest(limits: .standard) } == expected) + let contribution = try NativeGeneratedPluginContribution.decode( + ledger.lowerings[0], ledger: ledger, artifacts: artifacts, limits: .standard) + #expect(contribution.route == .claudeSkillPlugin) + #expect(contribution.directory == "selected") + #expect(contribution.recipients == [.claudeCode]) + #expect(Set(contribution.knownReaders) == [.claudeCode, .cursor]) + #expect( + contribution.members.flatMap(\.occurrences) + == ledger.occurrences[0].pluginExpansion!.children) + var values: [String: Data] = [:] + for member in contribution.members { + if case .mcp(let server) = member.content { + for binding in server.bindings { + if case .secret(let name) = binding.binding { + values[name] = Data("resolved-private-value".utf8) + } + } + } + } + let paths = Dictionary( + uniqueKeysWithValues: contribution.resourcePlacements.map { + ($0.resource, "/registered/selected/" + $0.path) + }) + let bundle = try contribution.stagedBundle( + bindings: RuntimeBindingValues(values), environment: fixture.environment, + resourcePaths: paths, budget: budget()) + #expect( + String(decoding: bundle.files["commands/review.md"]!, as: UTF8.self).hasSuffix( + "Literal source body\n")) + guard case .object(let manifest) = bundle.documents[contribution.manifestPath], + case .object(let events) = manifest["hooks"], + case .array(let groups) = events["PreToolUse"] + else { + Issue.record("missing native hook groups") + return + } + #expect(groups.count == 2) + guard case .object(let first) = groups[0], case .object(let second) = groups[1] else { + Issue.record("missing hook metadata") + return + } + #expect(first["matcher"] == .string("Read")) + #expect(second["matcher"] == .string("Write")) + #expect(contribution.resourcePlacements.contains { $0.path == "skills/helper" }) + #expect( + contribution.resources.values.contains { + $0.entries.contains { $0.kind == .file && $0.executable } + }) + var changed = artifacts + changed[0].values!.object!["members"]!.array!.removeLast() + #expect(throws: (any Error).self) { + try NativeGeneratedPluginContribution.decode( + ledger.lowerings[0], ledger: ledger, artifacts: changed, limits: .standard) + } + } + var missing = frozen + missing.ledger.occurrences[0].pluginExpansion = nil + #expect(throws: (any Error).self) { try lower(components, missing) } + } + + @Test func explicitEmptySelectionHasSealedManifestAndNoAdoptedChildren() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"upstream"}"#, to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + try fixture.write( + "---\ndescription: Unselected\n---\nNever included\n", to: "bundle/commands/unselected.md", + base: fixture.project) + let (components, frozen) = try freeze( + fixture, + """ + version: 1 + components: + - {kind: plugin, name: empty, source: ".", path: bundle, select: [], agents: ["claude-code"]} + """) + var ledger = frozen.ledger + ledger.lowerings = [try lower(components, frozen)] + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: .standard) + try LedgerReplay.withReplay(ledger, store: fixture.store, roots: [:], limits: .standard) { + artifacts in + let result = try NativeGeneratedPluginContribution.decode( + ledger.lowerings[0], ledger: ledger, artifacts: artifacts, limits: .standard) + #expect(result.members.isEmpty) + #expect(result.resources.isEmpty) + let bundle = try result.stagedBundle( + bindings: RuntimeBindingValues([:]), environment: fixture.environment, resourcePaths: [:], + budget: budget()) + #expect(bundle.files.isEmpty) + #expect( + bundle.documents == [".claude-plugin/plugin.json": .object(["name": .string("empty")])]) + } + } + + @Test func cursorPluginCommandUsesPluginScopeAndNativePlainBody() throws { + let fixture = try LinkFixture() + let store = StateStore(scope: .user, environment: fixture.environment) + try fixture.write( + #"{"name":"upstream"}"#, to: "bundle/.cursor-plugin/plugin.json", base: store.directory) + try fixture.write("Exact plain body\n", to: "bundle/commands/review.md", base: store.directory) + try fixture.write( + #"{"mcpServers":{"native":{"command":"fixture-server"}}}"#, + to: "bundle/mcp.json", base: store.directory) + try fixture.write( + #"{"version":1,"hooks":{"preToolUse":[{"type":"command","command":"fixture-hook"}]}}"#, + to: "bundle/hooks/hooks.json", base: store.directory) + let (components, frozen) = try freeze( + fixture, + """ + version: 1 + components: + - {kind: plugin, name: selected, source: ".", path: bundle, agents: [cursor]} + """, scope: .user) + var ledger = frozen.ledger + ledger.lowerings = [try lower(components, frozen, surface: .cursorEditor, scope: .user)] + ledger = try LedgerReplay.prepareLowerings(ledger, store: store, roots: [:], limits: .standard) + try LedgerReplay.withReplay(ledger, store: store, roots: [:], limits: .standard) { artifacts in + let result = try NativeGeneratedPluginContribution.decode( + ledger.lowerings[0], ledger: ledger, artifacts: artifacts, limits: .standard) + #expect(result.route == .cursorLocalPlugin) + let bundle = try result.stagedBundle( + bindings: RuntimeBindingValues([:]), environment: fixture.environment, resourcePaths: [:], + budget: budget(), cursorCommandShell: .posix) + #expect(bundle.files["commands/review.md"] == Data("Exact plain body\n".utf8)) + guard case .object(let manifest) = bundle.documents[result.manifestPath] else { + Issue.record("missing manifest") + return + } + #expect(manifest["mcpServers"] == .string("./mcp.json")) + #expect(manifest["hooks"] == .string("./hooks/hooks.json")) + #expect(bundle.documents["mcp.json"] != nil) + #expect(bundle.documents["hooks/hooks.json"] != nil) + } + } + @Test func independentParentsKeepSeparateMemberOwnersAndNativeLSPFields() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"producer","lspServers":{"native-lsp":{"command":"fixture-lsp","extensionToLanguage":{".fixture":"fixture"},"restartOnCrash":true,"requestTimeout":1200}}}"#, + to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + let (components, frozen) = try freeze( + fixture, + """ + version: 1 + components: + - {kind: plugin, name: first, source: ".", path: bundle, agents: ["claude-code"]} + - {kind: plugin, name: second, source: ".", path: bundle, agents: ["claude-code"]} + """) + let parents = components.filter { $0.key.kind == .plugin } + var ledger = frozen.ledger + ledger.lowerings = try parents.enumerated().map { index, parent in + try NativeGeneratedPluginLayoutV1.lower( + parent, members: components, frozen: frozen, + request: .init(surface: .claudeCode, scope: .project), id: "parent/" + String(index), + platform: .macOS) + } + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: .standard) + try LedgerReplay.withReplay(ledger, store: fixture.store, roots: [:], limits: .standard) { + artifacts in + var ownerSets: [Set] = [] + for lowering in ledger.lowerings { + let result = try NativeGeneratedPluginContribution.decode( + lowering, ledger: ledger, + artifacts: artifacts.filter { $0.name == lowering.id }, limits: .standard) + ownerSets.append(Set(result.members.flatMap(\.occurrences))) + let bundle = try result.stagedBundle( + bindings: RuntimeBindingValues([:]), environment: fixture.environment, resourcePaths: [:], + budget: budget()) + guard case .object(let manifest) = bundle.documents[result.manifestPath], + case .object(let servers) = manifest["lspServers"], + case .object(let server) = servers["native-lsp"] + else { + Issue.record("missing native LSP fields") + return + } + #expect(server["requestTimeout"] == .integer(1200)) + #expect(server["restartOnCrash"] == .boolean(true)) + } + #expect(ownerSets.count == 2) + #expect(ownerSets[0].isDisjoint(with: ownerSets[1])) + var corrupted = ledger + corrupted.lowerings[0].layout.object!["members"]!.array![0].object!["occurrences"] = + .init(array: ownerSets[1].map { .init(integer: $0) }) + #expect(throws: (any Error).self) { + try NativeGeneratedPluginContribution.decode( + corrupted.lowerings[0], ledger: corrupted, + artifacts: artifacts.filter { $0.name == ledger.lowerings[0].id }, limits: .standard) + } + } + } + + @Test func geminiUsesFrozenExplicitVersionAndNativeExtensionFiles() throws { + let fixture = try LinkFixture() + let store = StateStore(scope: .user, environment: fixture.environment) + try fixture.write( + #"{"name":"upstream","version":"9.0.0","mcpServers":{"native":{"command":"fixture-server"}}}"#, + to: "extension/gemini-extension.json", base: store.directory) + try fixture.write( + "description = \"Native review\"\nprompt = \"Literal review body\"\n".replacingOccurrences( + of: "\\", with: ""), + to: "extension/commands/review.toml", base: store.directory) + let (components, frozen) = try freeze( + fixture, + """ + version: 1 + components: + - kind: plugin + name: selected + source: "." + path: extension + agents: [gemini-cli] + native: {gemini-cli: {version: "1.2.3"}} + """, scope: .user) + var ledger = frozen.ledger + ledger.lowerings = [try lower(components, frozen, surface: .geminiCLI, scope: .user)] + ledger = try LedgerReplay.prepareLowerings(ledger, store: store, roots: [:], limits: .standard) + try LedgerReplay.withReplay(ledger, store: store, roots: [:], limits: .standard) { artifacts in + let result = try NativeGeneratedPluginContribution.decode( + ledger.lowerings[0], ledger: ledger, + artifacts: artifacts, limits: .standard) + #expect(result.route == .geminiExtension) + let bundle = try result.stagedBundle( + bindings: RuntimeBindingValues([:]), environment: fixture.environment, + resourcePaths: [:], budget: budget()) + guard case .object(let manifest) = bundle.documents["gemini-extension.json"] else { + Issue.record("missing extension") + return + } + #expect(manifest["version"] == .string("1.2.3")) + #expect(bundle.files["commands/review.toml"] != nil) + #expect(manifest["mcpServers"] != nil) + } + } + +} From 30b454c5c94de697d014f35c5c43e8d3bbd77c33 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:39:06 +0800 Subject: [PATCH 118/171] fix: preserve nested native array continuity --- Sources/NativeDocuments/NativeDocument.swift | 3 +- .../OpaquePluginIdentityTests.swift | 103 ++++++++++++++++++ .../ArrayAuthorityTests.swift | 29 +++++ 3 files changed, 134 insertions(+), 1 deletion(-) create mode 100644 Tests/ComponentsTests/OpaquePluginIdentityTests.swift diff --git a/Sources/NativeDocuments/NativeDocument.swift b/Sources/NativeDocuments/NativeDocument.swift index f6f870f..edf0d8d 100644 --- a/Sources/NativeDocuments/NativeDocument.swift +++ b/Sources/NativeDocuments/NativeDocument.swift @@ -442,7 +442,8 @@ package struct NativeDocument { try budget.step( path.reduce(0) { $0 + $1.work } + effect.address.reduce(0) { $0 + $1.work }) let ancestor = path.starts(with: effect.address) - if ancestor || effect.address.starts(with: path) { touched = true } + let ancestorAppend = ancestor && effect.append && effect.address.count < path.count + if (ancestor && !ancestorAppend) || effect.address.starts(with: path) { touched = true } if ancestor && effect.removal { removedAncestor = true } } var region: NativeRegion? diff --git a/Tests/ComponentsTests/OpaquePluginIdentityTests.swift b/Tests/ComponentsTests/OpaquePluginIdentityTests.swift new file mode 100644 index 0000000..0a4f923 --- /dev/null +++ b/Tests/ComponentsTests/OpaquePluginIdentityTests.swift @@ -0,0 +1,103 @@ +import AgentsManifest +import Foundation +import Testing + +@testable import AgentsCore +@testable import Components + +@Suite("Opaque native plugin producer identity") +struct OpaquePluginIdentityTests { + @Test(arguments: [false, true]) + func declaringNamespaceAndSelectedProducerPairThroughColdReplay(_ separateProducer: Bool) throws { + let fixture = try LinkFixture() + let producer = + separateProducer ? fixture.root.appendingPathComponent("producer") : fixture.project + let manifest = #"{"name":"demo-plugin","version":"1.0.0"}"# + try fixture.write(manifest, to: "demo-plugin/.claude-plugin/plugin.json", base: producer) + try fixture.write("#!/bin/sh\n# frozen only\n", to: "demo-plugin/bin/check", base: producer) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: producer.appendingPathComponent("demo-plugin/bin/check").path) + try FileManager.default.createSymbolicLink( + atPath: producer.appendingPathComponent("demo-plugin/current").path, + withDestinationPath: "bin/check") + let input: [String: Any] = [ + "version": 1, "sources": ["producer": ["path": producer.path]], + "components": [ + [ + "kind": "plugin", "name": "demo-plugin", "path": "demo-plugin", + "source": "producer", "mode": "native", "agents": ["claude-code"], + ] + ], + ] + let document = try DeclarationDocument( + bytes: Array(JSONSerialization.data(withJSONObject: input, options: [.sortedKeys])), + identity: .init("consumer/agents.yaml")) + let (linked, frozen) = try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + let locations = Dictionary( + (graph.sourceSnapshots + graph.declaringSnapshots).map { + ( + $0.snapshot.source, + LedgerLocation( + kind: .absolute, path: String($0.snapshot.source.dropFirst("local:".count))) + ) + }, uniquingKeysWith: { first, _ in first }) + return ( + try #require(graph.components.first), + try LedgerFreeze.freezeWithSources( + graph, session: session, locations: .init(sources: locations), limits: .standard) + ) + } + let lowering = try NativeComponentLowering.lower( + linked, frozen: frozen, + request: .init(surface: .claudeCode, scope: .project), id: "opaque", platform: .macOS) + let record = try #require(frozen.ledger.components[lowering.inputs[0]]) + #expect(linked.key.source == linked.declaringSnapshot.source) + #expect(record.declaringSource == frozen.sources[linked.declaringSnapshot]) + #expect(record.source == frozen.sources[linked.snapshot]) + #expect((linked.declaringSnapshot.source != linked.snapshot.source) == separateProducer) + let resource = try #require(record.resources.first) + #expect(frozen.ledger.resources[resource]?.source == record.source) + var corrupt = frozen + corrupt.ledger.resources[resource]!.source = "missing-selected-producer" + #expect(throws: NativeComponentIssue.self) { + try NativeComponentLowering.lower( + linked, frozen: corrupt, + request: .init(surface: .claudeCode, scope: .project), id: "invalid", platform: .macOS) + } + var ledger = frozen.ledger + ledger.lowerings = [lowering] + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: .standard) + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + try FileManager.default.removeItem(at: producer.appendingPathComponent("demo-plugin")) + let restored = try ResolvedLedgerCodec.decode(bytes, limits: .standard) + try LedgerReplay.withReplay(restored, store: fixture.store, roots: [:], limits: .standard) { + artifacts in + let contribution = try NativeComponentLayoutsV1.contribution( + restored.lowerings[0], ledger: restored, + artifacts: artifacts, limits: .standard) + #expect(contribution.occurrences == linked.origins.map(\.occurrence)) + guard + case .nativePlugin(let directory, let selected, let entry) = contribution.outputs[0].content + else { + Issue.record("missing opaque native contribution") + return + } + #expect( + directory == "demo-plugin" && selected == resource && entry == ".claude-plugin/plugin.json") + let root = try #require(artifacts[1].tree) + #expect( + try String(contentsOf: root.appendingPathComponent(entry), encoding: .utf8) == manifest) + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: root.appendingPathComponent("current").path) == "bin/check") + let mode = + try FileManager.default.attributesOfItem( + atPath: root.appendingPathComponent("bin/check").path)[.posixPermissions] as? NSNumber + #expect(mode.map { $0.intValue & 0o111 != 0 } == true) + } + } +} diff --git a/Tests/NativeDocumentsTests/ArrayAuthorityTests.swift b/Tests/NativeDocumentsTests/ArrayAuthorityTests.swift index b5a84cf..2c0f72b 100644 --- a/Tests/NativeDocumentsTests/ArrayAuthorityTests.swift +++ b/Tests/NativeDocumentsTests/ArrayAuthorityTests.swift @@ -183,6 +183,35 @@ struct ArrayAuthorityTests { } } + @Test func ancestorAppendPreservesStableIDNestedArrayWhileOuterArrayRotates() throws { + let original = try document(#"{"items":[{"id":"first","hooks":[1]}]}"#, .json) + let items = keyRegion("items") + let hooks = NativeRegion([ + .key("items"), .occurrence(.init(idKey: "id", id: "first")), .key("hooks"), + ]) + let old = try #require(try original.read(hooks)) + let digest = try original.arrayDigest(hooks) + let appended = try original.prepare( + [ + .append( + region: items, expected: owned(original, items), value: .object(["id": .string("second")]) + ) + ], retaining: [old], trackingArrays: [hooks, items]) + #expect(appended.arrayTransitions[0].canRetainToken) + #expect(appended.arrayTransitions[0].digest == digest) + #expect(appended.arrayTransitions[0].region == hooks) + #expect(!appended.arrayTransitions[1].canRetainToken) + let fresh = try NativeDocument(bytes: appended.bytes, format: .json, budget: generousBudget()) + #expect(try fresh.read(hooks)?.value == .array([.integer(1)])) + let surviving = try #require(appended.survivingRegions[0].observation) + let edited = try fresh.prepare( + [ + .append(region: hooks, expected: .owned(surviving), value: .integer(2)) + ], trackingArrays: [hooks]) + #expect(!edited.arrayTransitions[0].canRetainToken) + #expect(edited.arrayTransitions[0].digest != digest) + } + @Test func conditionalPruningReportsArrayDisappearanceAndSurvivorRemoval() throws { let original = try document(#"{"a":[1],"keep":true}"#, .json) let array = keyRegion("a") From 6740f8c9d888cce4f86c452e684fec4e8f4306c3 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:39:06 +0800 Subject: [PATCH 119/171] fix: preserve valid empty YAML collections --- Sources/AgentsManifest/YAMLPatches.swift | 16 ++++- Tests/AgentsManifestTests/EditPlanTests.swift | 60 +++++++++++++++++++ 2 files changed, 73 insertions(+), 3 deletions(-) diff --git a/Sources/AgentsManifest/YAMLPatches.swift b/Sources/AgentsManifest/YAMLPatches.swift index c8014ab..259c02d 100644 --- a/Sources/AgentsManifest/YAMLPatches.swift +++ b/Sources/AgentsManifest/YAMLPatches.swift @@ -374,15 +374,25 @@ struct YAMLPatches { let range = owned(node, container: container) let comments = retainComments ? document.comments.filter { range.contains($0.lowerBound) } : [] let kept = comments.map { - indentation(at: node.entryRange.lowerBound) + source.spelling($0) + newline + let prefix = source.spelling(lineStart($0.lowerBound)..<$0.lowerBound) + let indent = + prefix.allSatisfy { $0 == " " } ? prefix : indentation(at: node.entryRange.lowerBound) + return indent + source.spelling($0) + newline }.joined() // An emptied block collection must remain an explicit empty collection, preserving its field. let count = container.items?.count ?? container.pairs?.count ?? 0 if count == 1 { let replacement = container.pairs == nil ? "[]" : "{}" - let indent = indentation(at: node.entryRange.lowerBound) + var indent = indentation(at: node.entryRange.lowerBound) + // An indentationless sequence aligns with its key, but a flow value must be nested. + if container.entryRange.lowerBound < container.range.lowerBound { + let column = container.entryRange.lowerBound - lineStart(container.entryRange.lowerBound) + if indent.utf8.count <= column { indent = String(repeating: " ", count: column + 2) } + } + var text = indent + replacement + newline + kept + if range.upperBound == bytes.count, bytes.last != 10 { text.removeLast(newline.count) } return [ - SourcePatch(range: range, replacement: Array((indent + replacement + newline + kept).utf8)) + SourcePatch(range: range, replacement: Array(text.utf8)) ] } return [SourcePatch(range: range, replacement: Array(kept.utf8))] diff --git a/Tests/AgentsManifestTests/EditPlanTests.swift b/Tests/AgentsManifestTests/EditPlanTests.swift index 72838ea..19e6040 100644 --- a/Tests/AgentsManifestTests/EditPlanTests.swift +++ b/Tests/AgentsManifestTests/EditPlanTests.swift @@ -73,6 +73,66 @@ struct EditPlanTests { ]) } } + + @Test(arguments: ["", " ", "flow"], ["", "\n", "\r\n"]) + func removingSoleComponentKeepsMappingTriviaAndEOF(_ style: String, _ ending: String) throws { + let newline = ending == "\r\n" ? ending : "\n" + for nested in [false, true] { + for comments in [false, true] { + for sibling in [false, true] { + let owner = nested ? " " : "" + let indent = owner + (style == "flow" ? "" : style) + let prefix = + "# Preserve this comment\nversion: 1\nsources: {s: {path: ./keep}}\n" + + (nested ? "groups:\n local:\n" : "") + let field = owner + "components:" + let component = + "{kind: command, name: review, description: Review, prompt: Review sources., agents: [claude-code]}" + let retained = comments ? indent + "# entry\n" + indent + "# prompt\n" : "" + let collection: String + let empty: String + if style == "flow" { + collection = field + " [" + component + "]" + (comments ? " # field" : "") + empty = field + " []" + (comments ? " # field" : "") + } else { + let header = field + (comments ? " # field" : "") + "\n" + collection = + header + (comments ? indent + "# entry\n" : "") + + indent + "- kind: command\n" + indent + " name: review\n" + + indent + " description: Review\n" + indent + " prompt: Review sources." + + (comments ? " # prompt" : "") + "\n" + indent + " agents: [claude-code]" + empty = header + owner + " []" + (comments ? "\n" + retained.dropLast() : "") + } + let suffix = sibling ? "\n# unrelated tail\nwatch: []" : "" + let input = + (prefix + collection + suffix).replacingOccurrences(of: "\n", with: newline) + + ending + let expected = + (prefix + empty + suffix).replacingOccurrences(of: "\n", with: newline) + + ending + let doc = try document(input) + let pointer = nested ? "/groups/0/components/0" : "/components/0" + let change = try doc.preparing([.removeComponent(#require(doc.node(at: pointer)))]) + #expect(String(decoding: change.bytes, as: UTF8.self) == expected) + let result = try DeclarationDocument( + bytes: change.bytes, identity: DocumentIdentity("manifest")) + #expect(result.declaration == change.expectedDeclaration) + let previous = try projected(input) + var next = previous + if nested { + next.groups[0].components = [] + } else { + next.components = [] + } + #expect( + try ManifestProjection.declaration(of: result, environment: projectionEnvironment) + == next) + #expect(try planned(previous, next, in: input) == change.bytes) + #expect(try planned(next, next, in: expected) == nil) + } + } + } + } } extension EditPlanTests { From 47855ccd91d35f4a40c80f282d54966e8bbf07eb Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:43:22 +0800 Subject: [PATCH 120/171] fix: describe the selected MCP executable --- .../MCPConnectionOperations.swift | 2 +- .../MCPConnectionOperationsTests.swift | 37 +++++++++++++++++++ .../MCPManagedSelectionTests.swift | 2 +- 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/Sources/AgentsUpdates/MCPConnectionOperations.swift b/Sources/AgentsUpdates/MCPConnectionOperations.swift index e6d4621..a911643 100644 --- a/Sources/AgentsUpdates/MCPConnectionOperations.swift +++ b/Sources/AgentsUpdates/MCPConnectionOperations.swift @@ -207,7 +207,7 @@ public enum MCPConnectionOperations { var endpoint: String? switch snapshot.transport { case .stdio(let run): - executable = redaction.text(run.executable) + executable = redaction.text(snapshot.executable?.displayPath ?? run.executable) arguments = run.arguments.map(redaction.text) directory = snapshot.directory.map { redaction.text($0.displayPath) } case .streamableHTTP(let url, _), .sse(let url, _): diff --git a/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift b/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift index cd54da8..d83bbf0 100644 --- a/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift +++ b/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift @@ -212,6 +212,43 @@ final class MCPFacadeFixture { #expect(MCPConnectionOperations.describe(snapshot) == description) } + @Test func confirmationIdentifiesSelectedExecutableResourceInsteadOfDeclaration() throws { + let fixture = try MCPFacadeFixture() + let file = fixture.root.appendingPathComponent("selected-executable") + try Data("description-only resource".utf8).write(to: file) + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: file.path) + let cwd = try MCPConnectionResource.live(fixture.root) + let declared = "/declared/different-executable" + let live = try MCPConnectionOperations.snapshot( + selectionID: "live-resource", + transport: .stdio(.init(executable: declared, arguments: ["fixed-argument"])), + workingDirectory: cwd, executable: .live(file)) + let captured = try MCPConnectionOperations.snapshot( + selectionID: "captured-resource", + transport: .stdio(.init(executable: declared)), workingDirectory: cwd, + executable: .capture( + sourceRoot: fixture.root, path: "selected-executable", + expectedHash: "sha256:" + FileHash.sha256Hex(file: file), + expectedExecutableFiles: [".": true])) + let before = try FileHash.folderHash(fixture.root) + let liveDescription = MCPConnectionOperations.describe(live) + #expect(liveDescription.executable == file.path && !liveDescription.executableIsCaptured) + #expect(liveDescription.arguments == ["fixed-argument"]) + #expect(liveDescription.readLocations.contains { $0.path == file.path }) + let capturedDescription = MCPConnectionOperations.describe(captured) + #expect(capturedDescription.executable == "selected-executable") + #expect(capturedDescription.executableIsCaptured) + #expect(!capturedDescription.readLocations.contains { $0.path == file.path }) + let path = try MCPConnectionOperations.snapshot( + selectionID: "path-command", transport: .stdio(.init(executable: "path-command")), + workingDirectory: cwd) + #expect(MCPConnectionOperations.describe(path).executable == "path-command") + #expect(try FileHash.folderHash(fixture.root) == before && fixture.text("pid") == nil) + try FileManager.default.removeItem(at: file) + #expect(MCPConnectionOperations.describe(live) == liveDescription) + #expect(MCPConnectionOperations.describe(captured) == capturedDescription) + } + @Test func invalidOptionsAndUnavailableEnvironmentDoNotConsultProvider() async throws { let fixture = try MCPFacadeFixture() let spy = MCPBindingSpy() diff --git a/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift b/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift index dba4257..2aa54a4 100644 --- a/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift +++ b/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift @@ -120,7 +120,7 @@ private struct ManagedMCPFixture { selection: selected.occurrences[0].selection, scope: .project, environment: f.fixture.environment) let description = MCPConnectionOperations.describe(snapshot) - #expect(description.executable == "./tool" && description.executableIsCaptured) + #expect(description.executable == "tool" && description.executableIsCaptured) #expect(description.workingDirectory == "cwd" && description.workingDirectoryIsCaptured) #expect(snapshot.readLocations.contains(f.store.declarationURL)) #expect(snapshot.readLocations.contains(f.store.resolvedURL)) From 9880d57dbd4f236149b25c2bd3e9e73e6bbf504b Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:00:22 +0800 Subject: [PATCH 121/171] fix: preserve source identity and instruction diagnostics --- Sources/AgentsCore/LedgerProjection.swift | 4 +- Sources/Components/ComponentLinker.swift | 10 ++ .../LedgerProjectionTests.swift | 42 ++++++ .../ConsumerSourceRegressionTests.swift | 140 ++++++++++++++++++ 4 files changed, 194 insertions(+), 2 deletions(-) create mode 100644 Tests/AgentsCoreTests/LedgerProjectionTests.swift create mode 100644 Tests/AgentsUpdatesTests/ConsumerSourceRegressionTests.swift diff --git a/Sources/AgentsCore/LedgerProjection.swift b/Sources/AgentsCore/LedgerProjection.swift index 37856fc..b5e2a62 100644 --- a/Sources/AgentsCore/LedgerProjection.swift +++ b/Sources/AgentsCore/LedgerProjection.swift @@ -54,8 +54,8 @@ extension ResolvedLedger { } seen.insert(id) } - for deployment in deployments where deployment.ownership != .ownedValues { - guard deployment.route != "agents/skill@1" else { continue } + for deployment in deployments + where ["agents/instructions@1", "agents/claude-import@1"].contains(deployment.route) { let file = try deployment.target.resolve(roots: roots) let base = roots["project"]! let home = roots["home"]! diff --git a/Sources/Components/ComponentLinker.swift b/Sources/Components/ComponentLinker.swift index 38abdd5..06a3cf1 100644 --- a/Sources/Components/ComponentLinker.swift +++ b/Sources/Components/ComponentLinker.swift @@ -147,6 +147,16 @@ final class Linking { func solve(preserving pins: [String: SourceRevision]) throws -> LinkedComponents { try budget.step(document.metrics.evaluationSteps) + // Recorded commits preserve local Git provenance independently of current working-tree metadata. + if let ledger = retainedLedger { + for id in ledger.sources.keys.sorted() { + try budget.step() + let source = ledger.sources[id]! + if source.kind == .local, SourceCache.isObjectID(source.revision) { + git.insert(try retainedSourceIdentity(id, ledger: ledger)) + } + } + } let declaration = try ManifestProjection.declaration( of: document, environment: store.environment) let packageRoot = diff --git a/Tests/AgentsCoreTests/LedgerProjectionTests.swift b/Tests/AgentsCoreTests/LedgerProjectionTests.swift new file mode 100644 index 0000000..72b287e --- /dev/null +++ b/Tests/AgentsCoreTests/LedgerProjectionTests.swift @@ -0,0 +1,42 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Ledger domain projection") +struct LedgerProjectionTests { + @Test func instructionTargetsUseTheirActualRoutes() throws { + let root = URL(fileURLWithPath: "/projection-project") + let home = URL(fileURLWithPath: "/projection-home") + var ledger = ResolvedLedger() + let hash = "sha256:" + String(repeating: "a", count: 64) + ledger.sources["root"] = .init(kind: .local, revision: "live") + ledger.components["input"] = .init( + declaringSource: "root", source: "root", root: ".", kind: "command", name: "review", + payload: .init(), conditions: [], recipients: [.claudeCode], chatGPT: false, resources: []) + for (index, record) in [ + ("agents/instructions@1", "AGENTS.md", LedgerDeployment.Ownership.generated), + ("agents/claude-import@1", "CLAUDE.md", .importBlock), + ("agents/claude-components@1", ".claude/commands/review.md", .generated), + ("agents/claude-components@1", ".claude/plugins/review", .generated), + ("agents/skill@1", ".claude/skills/review", .generated), + ].enumerated() { + let id = "deployment-\(index)" + ledger.deployments.append( + .init( + id: id, target: .init(kind: .registered, root: "project", path: record.1), + route: record.0, owners: ["input"], recipients: [.claudeCode], ownership: record.2, + expectedHash: hash, created: index == 1, importReference: index == 1 ? "AGENTS.md" : nil)) + ledger.lowerings.append( + .init( + id: "lowering-\(index)", format: record.0, inputs: ["input"], resources: [], + deployments: [id], layout: .init(), platform: "macos", artifacts: [])) + } + try ledger.validate() + let projection = try ledger.domainProjection(roots: ["project": root, "home": home]) + #expect(Set(projection.instructions.targets.keys) == ["AGENTS.md", "CLAUDE.md"]) + #expect(projection.instructions.targets["CLAUDE.md"]?.import == "AGENTS.md") + #expect(projection.instructions.targets["CLAUDE.md"]?.created == true) + #expect(projection.instructions.targets["AGENTS.md"]?.blockHash == hash) + } +} diff --git a/Tests/AgentsUpdatesTests/ConsumerSourceRegressionTests.swift b/Tests/AgentsUpdatesTests/ConsumerSourceRegressionTests.swift new file mode 100644 index 0000000..eefd02e --- /dev/null +++ b/Tests/AgentsUpdatesTests/ConsumerSourceRegressionTests.swift @@ -0,0 +1,140 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +@Suite("Consumer local source provenance", .serialized) +struct ConsumerSourceRegressionTests { + private func declare(_ fixture: UpdateFixture, mode: InstallMode = .copy, source: URL? = nil) + throws + { + try fixture.store.save( + declaration: Declaration( + sources: ["local": .init(kind: .local, location: (source ?? fixture.repo).path)], + skills: ["local": .init(select: .all, agents: [.codex], mode: mode)]), + ledger: fixture.store.loadLedger()) + } + + @Test(arguments: [InstallMode.copy, .link]) + func retainedGitSelectionRefusesWorkingTreeDowngrade(_ mode: InstallMode) throws { + let fixture = try UpdateFixture() + try declare(fixture, mode: mode) + _ = try fixture.apply() + let committed = try fixture.bytes(fixture.target().appendingPathComponent("SKILL.md")) + let revision = try fixture.git(["rev-parse", "HEAD"]) + try fixture.writeSource("uncommitted working tree") + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(try fixture.bytes(fixture.target().appendingPathComponent("SKILL.md")) == committed) + #expect(try fixture.store.loadResolved().skills["demo"]?.revision == revision) + try FileManager.default.removeItem(at: fixture.repo.appendingPathComponent(".git")) + let before = try fixture.snapshot() + do { + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + Issue.record("a recorded Git selection became a working-tree snapshot") + } catch { + let diagnostic = String(describing: error) + #expect(diagnostic.contains("Git could not ")) + #expect(diagnostic.contains(fixture.repo.path)) + #expect(diagnostic.contains("fatal:")) + #expect(diagnostic.contains(fixture.store.declarationURL.path)) + } + #expect(try fixture.snapshot() == before) + } + + @Test func genuineDirectoryTracksItsWorkingContent() throws { + let fixture = try UpdateFixture() + try FileManager.default.removeItem(at: fixture.repo.appendingPathComponent(".git")) + try declare(fixture) + _ = try fixture.apply() + try fixture.writeSource("new directory bytes") + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect( + String( + decoding: try fixture.bytes(fixture.target().appendingPathComponent("SKILL.md")), + as: UTF8.self + ).contains("new directory bytes")) + #expect(try fixture.store.loadResolved().skills["demo"]?.revision == nil) + } + + @Test func explicitEditRemainsLiveAfterGitMetadataDisappears() throws { + let fixture = try UpdateFixture() + try declare(fixture) + _ = try fixture.apply() + try FileManager.default.removeItem(at: fixture.repo.appendingPathComponent(".git")) + try fixture.writeSource("live edit bytes") + try declare(fixture, mode: .edit) + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect( + fixture.target().resolvingSymlinksInPath().path + == fixture.repo.appendingPathComponent("skills/demo").resolvingSymlinksInPath().path) + #expect( + String( + decoding: try fixture.bytes(fixture.target().appendingPathComponent("SKILL.md")), + as: UTF8.self + ).contains("live edit bytes")) + try fixture.writeSource("later live bytes") + #expect( + String( + decoding: try fixture.bytes(fixture.target().appendingPathComponent("SKILL.md")), + as: UTF8.self + ).contains("later live bytes")) + } + + @Test func aliasRebindingUsesActualRecordedSourceIdentity() throws { + let fixture = try UpdateFixture() + try declare(fixture) + _ = try fixture.apply() + let directory = fixture.root.appendingPathComponent("directory") + try fixture.write( + "---\nname: demo\ndescription: Directory\n---\nRebound content\n", + to: directory.appendingPathComponent("skills/demo/SKILL.md")) + try declare(fixture, source: directory) + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect( + String( + decoding: try fixture.bytes(fixture.target().appendingPathComponent("SKILL.md")), + as: UTF8.self + ).contains("Rebound content")) + #expect(try fixture.store.loadResolved().skills["demo"]?.source == "local:" + directory.path) + } +} + +@Suite("Consumer native instruction projection", .serialized) +struct ConsumerProjectionRegressionTests { + @Test(arguments: [InstallScope.project, .user]) + func nativeCommandDoesNotBecomeInstructionTarget(_ scope: InstallScope) throws { + let fixture = try UpdateFixture(scope: scope) + try fixture.write( + """ + version: 1 + sources: {rules: {path: "\(fixture.repo.path)"}} + components: + - {kind: command, name: review, description: Review, prompt: Review sources., agents: [claude-code]} + - {kind: instructions, agents: [codex, claude-code], sections: [{name: rules, source: rules}]} + """, to: fixture.store.declarationURL) + if scope == .project { + try fixture.write( + "# Existing Claude instructions\n", to: fixture.root.appendingPathComponent("CLAUDE.md")) + } + _ = try fixture.apply() + let ledger = try fixture.store.loadLedger() + #expect(ledger.deployments.contains { $0.route == "agents/claude-components@1" }) + if scope == .project { + #expect(ledger.deployments.contains { $0.route == "agents/claude-import@1" }) + } + let healthy = try InstructionOperations.doctor(scope: scope, environment: fixture.environment) + #expect(!healthy.diagnostics.contains { $0.kind == .invalidTarget }) + let file = fixture.instruction() + let original = try fixture.bytes(file) + try (original + Data("\nEdited target\n".utf8)).write(to: file) + let drift = try InstructionOperations.doctor(scope: scope, environment: fixture.environment) + #expect(drift.diagnostics.contains { $0.kind == .drift && $0.path == file }) + try FileManager.default.removeItem(at: file) + let missing = try InstructionOperations.doctor(scope: scope, environment: fixture.environment) + #expect(missing.diagnostics.contains { $0.kind == .missingTarget && $0.path == file }) + } +} From d97947bfbe89412cc4a17a8a4ffd489ea8831e07 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:02:34 +0800 Subject: [PATCH 122/171] fix: preserve scoped lifecycle and restore invariants --- .../InstructionTargets.swift | 10 + Sources/AgentsUpdates/SkillOperations.swift | 31 ++- Sources/AgentsUpdates/UpdateOperations.swift | 7 +- Sources/AgentsUpdates/UpdatePlan.swift | 35 ++- Sources/AgentsUpdates/UpdateReporting.swift | 7 +- Sources/Components/ArtifactAggregation.swift | 41 +++- Sources/Components/LedgerImpact.swift | 12 +- Sources/Components/LedgerReplay.swift | 22 +- .../ConsumerLifecycleRegressionTests.swift | 231 ++++++++++++++++++ .../UpdateTransactionTests.swift | 20 +- 10 files changed, 367 insertions(+), 49 deletions(-) create mode 100644 Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift diff --git a/Sources/AgentsInstructions/InstructionTargets.swift b/Sources/AgentsInstructions/InstructionTargets.swift index 6597d8d..5c73e92 100644 --- a/Sources/AgentsInstructions/InstructionTargets.swift +++ b/Sources/AgentsInstructions/InstructionTargets.swift @@ -199,6 +199,16 @@ package struct InstructionTargets { } } + /// Checks frozen rendered output against its receiving checkout, not mutable authoring input. + package func validateRenderedLinks(_ bytes: Data, at file: URL) throws { + guard let text = String(data: bytes, encoding: .utf8) else { + throw InstructionError.invalidLockedBlock + } + let problems = linkProblems( + in: text, file: file, key: InstructionLocations.key(for: file, store: store)) + guard problems.isEmpty else { throw InstructionError.invalidLinks(problems) } + } + /// 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] { diff --git a/Sources/AgentsUpdates/SkillOperations.swift b/Sources/AgentsUpdates/SkillOperations.swift index 140555b..666e021 100644 --- a/Sources/AgentsUpdates/SkillOperations.swift +++ b/Sources/AgentsUpdates/SkillOperations.swift @@ -1,6 +1,7 @@ import AgentsCore import AgentsManifest import AgentsSkills +import Components import Foundation extension SkillOperations { @@ -124,19 +125,25 @@ extension SkillOperations { skillNames: [String] = [], apply: Bool = false, beforeApply: (([UpdateResult]) throws -> Void)? = nil ) throws -> [UpdateResult] { - let request = UpdateRequest(kinds: [.skills], names: skillNames) - if !apply { - return try UpdateOperations.preview(request, scope: scope, environment: environment).skills - } - return try UpdateOperations.withDomainUpdate(request, scope: scope, environment: environment) { - prepared in - try beforeApply?(prepared.report.skills) - let applied = try prepared.apply() - return applied.report.skills.map { item in - var item = item - item.installed = applied.installedSkills.filter { $0.skill == item.skill } - return item + do { + let request = UpdateRequest(kinds: [.skills], names: skillNames) + if !apply { + return try UpdateOperations.preview(request, scope: scope, environment: environment).skills + } + return try UpdateOperations.withDomainUpdate(request, scope: scope, environment: environment) + { + prepared in + try beforeApply?(prepared.report.skills) + let applied = try prepared.apply() + return applied.report.skills.map { item in + var item = item + item.installed = applied.installedSkills.filter { $0.skill == item.skill } + return item + } } + } catch let error as LinkError { + if case .missing = error { throw CoreError.notFound(error.description) } + throw error } } diff --git a/Sources/AgentsUpdates/UpdateOperations.swift b/Sources/AgentsUpdates/UpdateOperations.swift index 5fe6dd5..b1f2d33 100644 --- a/Sources/AgentsUpdates/UpdateOperations.swift +++ b/Sources/AgentsUpdates/UpdateOperations.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsInstructions import AgentsManifest import Foundation @@ -87,7 +88,11 @@ public enum UpdateOperations { request: request, store: store, admitted: admitted, installations: installations, checkpoint: checkpoint, provider: provider ) { plan in - try plan.requireSkillOwnership() + do { + try plan.requireOwnership() + } catch let error as InstructionError { + throw UpdateApplyError(outcome: outcome, underlyingError: error) + } let update = PreparedUpdate(plan: plan, outcome: outcome) defer { update.invalidate() } delivered = true diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 5905546..40521ac 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -12,7 +12,7 @@ struct RequiredRoutes: Error { /// The composition plan borrows both source/replay resources and the admitted writer scope. final class UpdatePlan { - func requireSkillOwnership() throws { try aggregation.requireSkillOwnership() } + func requireOwnership() throws { try aggregation.requireOwnership() } let report: CombinedUpdateReport private let store: StateStore @@ -80,6 +80,20 @@ final class UpdatePlan { candidate = try removing(request, from: declaration, ledger: previous, store: store) change = try store.planDeclaration(candidate, replacing: declaration, prepared: baseline) } + let retargetedInstructions: Set + if case .remove = request.operation, request.agents != nil, + request.kinds?.contains(.instructions) ?? true + { + retargetedInstructions = try Set( + previous.occurrences.filter { $0.consumerEditable }.compactMap { + guard let component = previous.components[$0.component], component.kind == "instructions", + component.group == nil + else { return nil } + return try LedgerImpact.identity(component, ledger: previous, roots: store.ledgerRoots) + }) + } else { + retargetedInstructions = [] + } if restoring { let routes = try DeploymentConstruction.routes(previous) let required = try SkillLifecycle.installationTargets(previous, store: store) @@ -94,7 +108,8 @@ final class UpdatePlan { watch: watch, change: nil, artifacts: artifacts, resources: resources, workspace: workspace, decisionInputs: [], originalInputs: [], - checkpoint: checkpoint, provider: provider, installations: Array(installations.values))) + checkpoint: checkpoint, provider: provider, installations: Array(installations.values), + retargetedInstructions: retargetedInstructions)) } } var document: DeclarationDocument @@ -200,7 +215,8 @@ final class UpdatePlan { let kinds = request.kinds ?? Set(DeclaredComponentKind.allCases) try LedgerImpact.requireProtected( previous: previous, next: native, kinds: kinds, names: Set(request.names), - roots: store.ledgerRoots, selectedIdentities: request.selectedIdentities) + roots: store.ledgerRoots, selectedIdentities: request.selectedIdentities, + retargetedInstructions: retargetedInstructions) } let complete = try DeploymentConstruction.complete( native, linked: linked, store: store, previous: previous, platform: platform) @@ -226,7 +242,8 @@ final class UpdatePlan { watch: watch, change: change, artifacts: artifacts, resources: resources, workspace: workspace, decisionInputs: complete.inputs, originalInputs: originals + importInputs, - checkpoint: checkpoint, provider: provider, installations: Array(installations.values))) + checkpoint: checkpoint, provider: provider, installations: Array(installations.values), + retargetedInstructions: retargetedInstructions)) } } } @@ -238,7 +255,7 @@ final class UpdatePlan { workspace: URL, decisionInputs: [TargetPrecondition], originalInputs: [TargetPrecondition], checkpoint: @escaping (String) throws -> Void, provider: any RuntimeBindingProvider, - installations: [SkillInstallationTarget] + installations: [SkillInstallationTarget], retargetedInstructions: Set ) throws { self.store = store self.baseline = baseline @@ -253,7 +270,7 @@ final class UpdatePlan { resources: resources, workspace: workspace, store: store, replace: request.replace, changingAccess: request.changingAccess, kinds: request.kinds, names: Set(request.names), selectedIdentities: request.selectedIdentities, - installations: installations) + installations: installations, retargetedInstructions: retargetedInstructions) if let imported = request.importPreparation { for resource in imported.proposal.resources where resource.selected && resource.requiresStandaloneSource { @@ -283,7 +300,7 @@ final class UpdatePlan { previous: previous, next: self.next, resources: resources, changes: aggregation.changes, store: store, lockMissing: lockMissing, included: request.kinds == nil || request.kinds!.contains(.skills), - selectedIdentities: request.selectedIdentities) + selectedIdentities: request.selectedIdentities, names: Set(request.names)) let results = request.names.isEmpty ? allResults : allResults.filter { request.names.contains($0.skill) } receipts = results.flatMap(\.installed) @@ -366,7 +383,9 @@ final class UpdatePlan { hasChanges: self.next != previous || change != nil || aggregation.changes.contains(where: \.changed), displayedFingerprint: fingerprint, - readLocations: Array(Set(readPaths)).sorted { $0.path < $1.path }, + readLocations: Set(readPaths.map(\.path)).sorted().map { + URL(fileURLWithPath: $0, isDirectory: false) + }, components: try aggregation.changes.filter { change in guard change.native else { return false } guard let identities = request.selectedIdentities else { return true } diff --git a/Sources/AgentsUpdates/UpdateReporting.swift b/Sources/AgentsUpdates/UpdateReporting.swift index 481785a..936d6d6 100644 --- a/Sources/AgentsUpdates/UpdateReporting.swift +++ b/Sources/AgentsUpdates/UpdateReporting.swift @@ -9,7 +9,7 @@ enum UpdateReporting { static func skills( previous: ResolvedLedger, next: ResolvedLedger, resources: [String: URL], changes: [AggregatedChange], store: StateStore, lockMissing: Bool, included: Bool, - selectedIdentities: Set? = nil + selectedIdentities: Set? = nil, names: Set = [] ) throws -> [UpdateResult] { guard included else { return [] } struct Item { @@ -27,6 +27,9 @@ enum UpdateReporting { { continue } + guard names.isEmpty || names.contains(PathSafety.sanitizeName(component.name)) else { + continue + } guard let id = component.resources.first, let resource = ledger.resources[id] else { continue } @@ -158,7 +161,7 @@ enum UpdateReporting { after: try change.deployment.ownership == .importBlock ? InstructionTargets.ownedImportBytes(change.after) : change.after, beforeAgents: old?.agents, - afterAgents: change.after == nil ? [] : change.deployment.recipients, + afterAgents: after.targets[key]?.agents ?? [], drift: drift, foreign: change.deployment.ownership != .importBlock && change.before.map { $0 != change.after && !Instructions.isOwned($0) } ?? false) diff --git a/Sources/Components/ArtifactAggregation.swift b/Sources/Components/ArtifactAggregation.swift index 82c6c0d..c71fcd2 100644 --- a/Sources/Components/ArtifactAggregation.swift +++ b/Sources/Components/ArtifactAggregation.swift @@ -32,6 +32,7 @@ package final class ArtifactAggregation: PreparedEvidence { private let selectedKinds: Set? private let selectedNames: Set private let selectedIdentities: Set? + private let retargetedInstructions: Set private var unownedInstructions: [String] = [] private var unownedSkills: [String] = [] private var targets: [String: TargetPrecondition] = [:] @@ -54,7 +55,7 @@ package final class ArtifactAggregation: PreparedEvidence { changingAccess: Bool, kinds: Set? = nil, names: Set = [], selectedIdentities: Set? = nil, - installations: [SkillInstallationTarget] = [] + installations: [SkillInstallationTarget] = [], retargetedInstructions: Set = [] ) throws { self.ledger = ledger self.store = store @@ -64,16 +65,12 @@ package final class ArtifactAggregation: PreparedEvidence { selectedKinds = kinds selectedNames = names self.selectedIdentities = selectedIdentities + self.retargetedInstructions = retargetedInstructions for (id, file) in resources where ledger.resources[id]?.kind != .liveEdit { resourceEvidence.append(try TargetPrecondition(file)) } - func selected(_ deployment: LedgerDeployment, in ledger: ResolvedLedger) -> Bool { - kinds == nil - || deployment.owners.contains { - ledger.components[$0].flatMap { DeclaredComponentKind(rawValue: $0.kind) }.map { - kinds!.contains($0) - } ?? false - } + func selected(_ deployment: LedgerDeployment, in ledger: ResolvedLedger) throws -> Bool { + try deployment.owners.contains { try isSelected($0, in: ledger) } } for (id, source) in resources where ledger.resources[id]?.kind != .liveEdit { let resource = ledger.resources[id]! @@ -111,11 +108,13 @@ package final class ArtifactAggregation: PreparedEvidence { let roots = store.ledgerRoots let artifacts = Dictionary(uniqueKeysWithValues: artifacts.map { ($0.name, $0) }) let previousByPath = try Dictionary( - grouping: previous.deployments.filter { selected($0, in: previous) } + grouping: previous.deployments.filter { try selected($0, in: previous) } ) { try installationURL($0).path } - var byPath = try Dictionary(grouping: ledger.deployments.filter { selected($0, in: ledger) }) { + var byPath = try Dictionary( + grouping: ledger.deployments.filter { try selected($0, in: ledger) } + ) { try installationURL($0).path } var native: [String: [(LockedLowering, NativeMCPContribution, MaterializationTarget)]] = [:] @@ -137,7 +136,11 @@ package final class ArtifactAggregation: PreparedEvidence { if native[path] == nil { native[path] = [] } } let currentComponents = try componentOutputs(ledger, artifacts: artifacts, routing: previous) - try LedgerReplay.withLockedResources(previous, store: store, roots: roots, limits: .standard) { + let oldNative = Set( + previous.lowerings.filter { $0.format.hasSuffix("-components@1") }.map(\.id)) + try LedgerReplay.withLockedResources( + previous, store: store, roots: roots, limits: .standard, lowerings: oldNative + ) { oldArtifacts, _, _ in let oldComponents = try componentOutputs( previous, @@ -314,6 +317,9 @@ package final class ArtifactAggregation: PreparedEvidence { } else { let before = try TargetPrecondition.readingFile(url).bytes var after = artifact.bytes + if deployment.route == "agents/instructions@1", let after { + try InstructionTargets(store: store).validateRenderedLinks(after, at: url) + } if deployment.ownership == .importBlock { guard let path = ClaudeInstructionPath(rawValue: deployment.target.path) else { throw CoreError.invalidState("invalid locked import location") @@ -401,6 +407,11 @@ package final class ArtifactAggregation: PreparedEvidence { private func isSelected(_ id: String, in selected: ResolvedLedger) throws -> Bool { guard let c = selected.components[id] else { return false } + if try retargetedInstructions.contains( + LedgerImpact.identity(c, ledger: selected, roots: store.ledgerRoots)) + { + return true + } if let selectedIdentities { return try selectedIdentities.contains( LedgerImpact.identity(c, ledger: selected, roots: store.ledgerRoots)) @@ -1185,6 +1196,14 @@ package final class ArtifactAggregation: PreparedEvidence { } package func validate(excludingTargets excluded: Set = []) throws { + for change in changes + where change.deployment.route == "agents/instructions@1" + && ledger.deployments.contains(where: { $0.id == change.deployment.id }) + { + if let bytes = change.after { + try InstructionTargets(store: store).validateRenderedLinks(bytes, at: change.url) + } + } let paths = targets.keys.sorted().map { URL(fileURLWithPath: $0) } for (index, path) in paths.enumerated() { if paths.prefix(index).contains(where: { diff --git a/Sources/Components/LedgerImpact.swift b/Sources/Components/LedgerImpact.swift index b2a349f..6e5d047 100644 --- a/Sources/Components/LedgerImpact.swift +++ b/Sources/Components/LedgerImpact.swift @@ -93,7 +93,8 @@ package struct LedgerImpact { package static func requireProtected( previous: ResolvedLedger, next: ResolvedLedger, kinds: Set, - names: Set = [], roots: [String: URL], selectedIdentities: Set? = nil + names: Set = [], roots: [String: URL], selectedIdentities: Set? = nil, + retargetedInstructions: Set = [] ) throws { struct Projection: Encodable { let component: LedgerComponent @@ -104,6 +105,9 @@ package struct LedgerImpact { var result: [String: [String]] = [:] for occurrence in ledger.occurrences { guard var c = ledger.components[occurrence.component] else { continue } + let retargeted = + try c.kind == "instructions" && !c.chatGPT + && retargetedInstructions.contains(identity(c, ledger: ledger, roots: roots)) let selected = try selectedIdentities.map { try $0.contains(identity(c, ledger: ledger, roots: roots)) } @@ -173,6 +177,8 @@ package struct LedgerImpact { if !result.contains(condition) { result.append(condition) } } } + let retargetIdentity = retargeted ? try identity(c, ledger: ledger, roots: roots) : nil + if retargeted { c.recipients = [] } if c.kind == "skills" { c.name = PathSafety.sanitizeName(c.name) } c.source = "input" c.declaringSource = "producer" @@ -180,7 +186,9 @@ package struct LedgerImpact { let digest = try ResolvedLedgerCodec.digest( Projection(component: c, sources: sources, resources: resources)) let destinations: [String] - if c.kind == DeclaredComponentKind.instructions.rawValue { + if retargeted { + destinations = ["retarget:" + retargetIdentity!] + } else if c.kind == DeclaredComponentKind.instructions.rawValue { destinations = c.recipients.map(\.rawValue) + (c.chatGPT ? ["prompt:" + (c.payload.object?["prompt"]?.text ?? "")] : []) diff --git a/Sources/Components/LedgerReplay.swift b/Sources/Components/LedgerReplay.swift index 25d8a11..c6efe47 100644 --- a/Sources/Components/LedgerReplay.swift +++ b/Sources/Components/LedgerReplay.swift @@ -106,9 +106,13 @@ package enum LedgerReplay { package static func withLockedResources( _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], limits: LedgerLimits, + lowerings selected: Set? = nil, _ body: ([ReplayedArtifact], [String: URL], URL) throws -> T ) throws -> T { - try run(ledger, store: store, roots: roots, limits: limits, renderers: nil, recording: false) { + try run( + ledger, store: store, roots: roots, limits: limits, renderers: nil, recording: false, + selectedLowerings: selected + ) { artifacts, _, resources, workspace in try body(artifacts, resources, workspace) } } @@ -132,18 +136,25 @@ package enum LedgerReplay { private static func run( _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], limits: LedgerLimits, renderers: [String: LedgerRenderer]?, recording: Bool, + selectedLowerings: Set? = nil, _ body: ([ReplayedArtifact], [LockedLowering], [String: URL], URL) throws -> T ) throws -> T { try ResolvedLedgerCodec.checkModel(ledger, limits: limits) try ledger.validate() try Task.checkCancellation() + let lowerings = ledger.lowerings.filter { selectedLowerings?.contains($0.id) ?? true } + guard selectedLowerings.map({ $0.isSubset(of: Set(ledger.lowerings.map(\.id))) }) ?? true else { + throw CoreError.invalidState("unknown selected locked lowering") + } + let resourceIDs = + selectedLowerings == nil ? Set(ledger.resources.keys) : Set(lowerings.flatMap(\.resources)) let platform = ProcessInfo.processInfo.operatingSystemVersionString #if os(macOS) let current = "macos" #else let current = "linux" #endif - for lowering in ledger.lowerings { + for lowering in lowerings { guard (renderers ?? compatibilityRenderers)[lowering.format] != nil else { throw CoreError.invalidState("unknown renderer format") } @@ -157,7 +168,7 @@ package enum LedgerReplay { (resource.entries + resource.support).reduce(0) { $0 + ($1.byteCount ?? 0) } } var remaining = limits.resourceBytes - for lowering in ledger.lowerings { + for lowering in lowerings { for id in lowering.resources { let size = sizes[id]! guard size <= remaining else { throw CoreError.invalidState("replay input byte budget") } @@ -170,7 +181,8 @@ package enum LedgerReplay { defer { try? FileManager.default.removeItem(at: workspace) } return try SourceResolutionSession.withTemporaryRead(store: store) { session in var acquired: [String: URL] = [:] - for (id, resource) in ledger.resources.sorted(by: { $0.key < $1.key }) { + for (id, resource) in ledger.resources.sorted(by: { $0.key < $1.key }) + where resourceIDs.contains(id) { try Task.checkCancellation() let file: URL if resource.kind == .liveEdit { @@ -227,7 +239,7 @@ package enum LedgerReplay { var result: [ReplayedArtifact] = [] var sealed: [LockedLowering] = [] var names = Set() - for lowering in ledger.lowerings { + for lowering in lowerings { try Task.checkCancellation() let table = renderers ?? compatibilityRenderers(outputBytes: remaining) let rendered = try table[lowering.format]!(lowering, ledger, acquired) diff --git a/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift b/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift new file mode 100644 index 0000000..a7a1b3a --- /dev/null +++ b/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift @@ -0,0 +1,231 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import Foundation +import Testing + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +struct ConsumerLifecycleRegressionTests { + @Test(arguments: ["valid", "missing", "escape"]) + func frozenRestoreValidatesReceivingCheckoutLinks(mode: String) throws { + let f = try UpdateFixture() + let guide = f.root.appendingPathComponent("guide.md") + try f.write("Guide", to: guide) + try f.write( + "---\ndescription: Rules.\n---\n# Rules\n\n[Guide](guide.md)\n", + to: f.repo.appendingPathComponent("instructions/rules.md")) + try f.commit() + try f.install(agents: [.codex]) + let locked = try f.bytes(f.instruction()) + try f.write( + "mutable author must not be read", to: f.repo.appendingPathComponent("instructions/rules.md")) + try f.write(String(decoding: locked, as: UTF8.self) + "\nEdited\n", to: f.instruction()) + let outside = FileManager.default.temporaryDirectory.appendingPathComponent( + "restore-link-" + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: outside) } + if mode != "valid" { try FileManager.default.removeItem(at: guide) } + if mode == "escape" { + try f.write("Outside", to: outside) + try FileManager.default.createSymbolicLink(at: guide, withDestinationURL: outside) + } + let before = try f.snapshot() + var delivered = false + do { + _ = try UpdateOperations.withPreparedUpdate( + UpdateRequest(operation: .restore), environment: f.environment + ) { + delivered = true + return try $0.apply() + } + #expect(mode == "valid") + #expect(try f.bytes(f.instruction()) == locked) + } catch { + if mode == "valid" { throw error } + #expect(!delivered) + #expect(try f.snapshot() == before) + } + } + + @Test func restoreRechecksLinkDestinationBeforePublication() throws { + let f = try UpdateFixture() + let guide = f.root.appendingPathComponent("guide.md") + try f.write("Guide", to: guide) + try f.write( + "---\ndescription: Rules.\n---\n# Rules\n\n[Guide](guide.md)\n", + to: f.repo.appendingPathComponent("instructions/rules.md")) + try f.commit() + try f.install(agents: [.codex]) + try f.write( + String(decoding: f.bytes(f.instruction()), as: UTF8.self) + "\nEdited\n", to: f.instruction()) + let before = try f.snapshot() + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate( + UpdateRequest(operation: .restore), environment: f.environment + ) { + try FileManager.default.removeItem(at: guide) + return try $0.apply() + } + } + #expect(try f.snapshot() == before) + } + + @Test func explicitRemovalRetargetsSurvivorsAndKeepsSkillPin() throws { + let f = try UpdateFixture() + try f.write( + "---\ndescription: Other.\n---\n# Other\n", + to: f.repo.appendingPathComponent("instructions/other.md")) + try f.commit() + try f.declare(agents: [.codex]) + var declaration = try f.store.loadDeclaration() + try declaration.updateInstructions { $0?.sections.append("fixture:other") } + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + let previous = try f.store.readLedger() + let skill = try f.bytes(f.target().appendingPathComponent("SKILL.md")) + try f.advance() + _ = try InstructionOperations.remove( + names: ["other"], agents: [.geminiCLI], environment: f.environment) + #expect(!FileManager.default.fileExists(atPath: f.instruction().path)) + #expect( + String(decoding: try f.bytes(f.instruction(.geminiCLI)), as: UTF8.self).contains("# Rules")) + #expect(try f.bytes(f.target().appendingPathComponent("SKILL.md")) == skill) + let next = try f.store.readLedger() + for (id, component) in previous.components where component.kind == "skills" { + #expect(next.components[id] == component) + } + } + + @Test func survivorRetargetDoesNotAuthorizeChangedOwnContent() throws { + let f = try UpdateFixture() + let own = f.root.appendingPathComponent(".agent/instructions/guide.md") + try f.write("---\ndescription: Own.\n---\n# Own\n\nLocked\n", to: own) + try f.declare(agents: [.codex]) + var declaration = try f.store.loadDeclaration() + try declaration.updateInstructions { $0?.sections = ["guide", "fixture:rules"] } + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + try f.write("---\ndescription: Own.\n---\n# Own\n\nChanged\n", to: own) + let before = try f.snapshot() + var delivered = false + #expect(throws: (any Error).self) { + try InstructionOperations.remove( + names: ["rules"], agents: [.geminiCLI], environment: f.environment + ) { _ in delivered = true } + } + #expect(!delivered) + #expect(try f.snapshot() == before) + } + + @Test func instructionMutationRefusesUnappliedSkillRecipientChange() throws { + let f = try UpdateFixture() + try f.install(agents: [.codex]) + var declaration = try f.store.loadDeclaration() + declaration.components = declaration.components.map { + guard case .skills(let source, var selection) = $0 else { return $0 } + selection.agents = [.cursor] + return .skills(source: source, selection) + } + try f.store.save(declaration: declaration, ledger: f.store.readLedger()) + let before = try f.snapshot() + var delivered = false + #expect(throws: (any Error).self) { + try InstructionOperations.add( + InstructionAddOptions( + source: f.repo.path, alias: "fixture", names: ["rules"], environment: f.environment) + ) { _ in delivered = true } + } + #expect(!delivered) + #expect(try f.snapshot() == before) + } + + @Test func retainedEditedOutputReportsNoManagedRecipients() throws { + let f = try UpdateFixture() + try f.install(agents: [.codex]) + try f.write("edited generated output", to: f.instruction()) + let report = try InstructionOperations.remove(names: ["rules"], environment: f.environment) + let target = try #require(report.targets.first { $0.url == f.instruction() }) + #expect(target.before == target.after) + #expect(target.afterAgents.isEmpty) + #expect(try f.bytes(f.instruction()) == Data("edited generated output".utf8)) + } + + @Test func foreignTakeoverRefusesBeforeCallbackButPreviewRemainsAvailable() throws { + let f = try UpdateFixture() + try f.declare(agents: [.codex]) + try f.write("handwritten", to: f.instruction()) + let before = try f.snapshot() + #expect(try f.preview().instructions.targets.contains { $0.foreign }) + var delivered = false + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(environment: f.environment) { + delivered = true + return try $0.apply() + } + } + #expect(!delivered) + #expect(try f.snapshot() == before) + } + + @Test func missingLiveSkillReconciliationReplaysOnlyPreviousNativeResources() throws { + let f = try UpdateFixture() + try f.declare(mode: .edit, agents: [.codex]) + var declaration = try f.store.loadDeclaration() + declaration.components.removeAll { + if case .instructions = $0 { return true } + return false + } + declaration.components.append( + .command( + name: "review", description: "Review", prompt: .literal("Frozen review"), + agents: [.claudeCode])) + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + let ledger = try f.store.readLedger() + let command = try #require(ledger.deployments.first { $0.route.hasSuffix("-components@1") }) + let commandURL = try command.target.resolve(roots: f.store.ledgerRoots) + let commandBytes = try f.bytes(commandURL) + try FileManager.default.removeItem(at: f.repo.appendingPathComponent("skills/demo")) + let before = try f.snapshot() + #expect(throws: (any Error).self) { try UpdateOperations.restore(environment: f.environment) } + #expect(try f.snapshot() == before) + _ = try SkillOperations.updateInstalled(environment: f.environment, apply: true) + #expect(try f.store.loadResolved().skills.isEmpty) + #expect(try f.bytes(commandURL) == commandBytes) + } + + @Test func namedSkillActionsDoNotReadUnselectedFIFO() throws { + let f = try UpdateFixture() + try f.write( + "---\nname: broken\ndescription: Broken.\n---\nBroken\n", + to: f.repo.appendingPathComponent("skills/broken/SKILL.md")) + try f.commit() + try f.declare(agents: [.codex]) + _ = try f.apply() + let broken = f.target().deletingLastPathComponent().appendingPathComponent("broken") + let fifo = broken.appendingPathComponent("fifo") + #expect(mkfifo(fifo.path, 0o600) == 0) + let brokenBytes = try f.bytes(broken.appendingPathComponent("SKILL.md")) + try f.advance() + let updated = try SkillOperations.updateInstalled( + environment: f.environment, skillNames: ["demo"], apply: true) + #expect(updated.map(\.skill) == ["demo"]) + _ = try SkillOperations.remove(skillNames: ["demo"], environment: f.environment) + #expect(try f.bytes(broken.appendingPathComponent("SKILL.md")) == brokenBytes) + var info = stat() + #expect(lstat(fifo.path, &info) == 0) + #expect(info.st_mode & mode_t(S_IFMT) == mode_t(S_IFIFO)) + let before = try f.snapshot() + #expect(throws: (any Error).self) { + try SkillOperations.updateInstalled( + environment: f.environment, skillNames: ["broken"], apply: true) + } + #expect(try f.snapshot() == before) + } +} diff --git a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift index 7ea7da8..5457c54 100644 --- a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift +++ b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift @@ -50,16 +50,20 @@ struct UpdateTransactionTests { #expect(try !fixture.preview().hasChanges) } - @Test(arguments: [false, true]) - func outerTerminalReportsTheDurablePublication(_ committed: Bool) throws { + @Test(arguments: [ + (TransactionCheckpoint.phase(.preparing).name, UpdateTerminalDisposition.unchanged), + ( + TransactionCheckpoint.persisted(.applying, .entry(0, .publishing), .renamed).name, .rolledBack + ), + (TransactionCheckpoint.phase(.committed).name, .committed), + ]) + func outerTerminalReportsTheDurablePublication( + point: String, expected: UpdateTerminalDisposition + ) throws { let fixture = try UpdateFixture() try fixture.install() let before = try fixture.snapshot() try fixture.advance() - let point = - committed - ? TransactionCheckpoint.phase(.committed).name - : TransactionCheckpoint.phase(.preparing).name var interrupted = false let result = UpdateOperations.perform( environment: fixture.environment, @@ -70,10 +74,10 @@ struct UpdateTransactionTests { } }, { try $0.apply() }) #expect(interrupted) - #expect(result.disposition == (committed ? .committed : .rolledBack)) + #expect(result.disposition == expected) #expect(!result.recovery.pending) #expect(throws: UpdateApplyError.self) { try result.result.get() } - if !committed { #expect(try fixture.snapshot() == before) } + if expected != .committed { #expect(try fixture.snapshot() == before) } } @Test(arguments: [ From 696c81e5952033bd00122d2477ae128641f8ebfc Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:04:11 +0800 Subject: [PATCH 123/171] fix: preserve imported Gemini package metadata --- .../Import/NativeContainerImport.swift | 17 +++++-- Tests/ComponentsTests/ImportNativeTests.swift | 48 +++++++++++++++++++ 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/Sources/Components/Import/NativeContainerImport.swift b/Sources/Components/Import/NativeContainerImport.swift index c42f751..f31ce01 100644 --- a/Sources/Components/Import/NativeContainerImport.swift +++ b/Sources/Components/Import/NativeContainerImport.swift @@ -54,10 +54,19 @@ enum NativeContainerImport { : ["commands", "agents", "skills", "hooks", "mcpServers", "lspServers", "rules"] NativeImportInput.unknown( parsed.fields, allowed: metadata.union(members), at: parsed.location(), into: &diagnostics) - if agent == .geminiCLI, parsed.fields["version"]?.importString?.isEmpty != false { - diagnostics.add( - .invalidInput, parsed.location(["version"]), "Native extension requires a version string.") - return + if agent == .geminiCLI { + guard let version = parsed.fields["version"]?.importString, !version.isEmpty else { + diagnostics.add( + .invalidInput, parsed.location(["version"]), "Native extension requires a version string." + ) + return + } + if !version.contains("://") || ImportInput.safeLocator(version) { + diagnostics.proposal.packageMetadata = .init( + name: name, version: version, + nameLocation: parsed.fieldLocation(["name"]), + versionLocation: parsed.fieldLocation(["version"])) + } } // A container contributes typed children; .native selection/registration belongs to B/F. // Unknown/dependency fields are already diagnosed rather than becoming opaque payloads. diff --git a/Tests/ComponentsTests/ImportNativeTests.swift b/Tests/ComponentsTests/ImportNativeTests.swift index 07d2b2c..cc70165 100644 --- a/Tests/ComponentsTests/ImportNativeTests.swift +++ b/Tests/ComponentsTests/ImportNativeTests.swift @@ -145,6 +145,54 @@ struct ImportNativeTests { #expect(gemini.components.first?.origin.document == "extension/commands/gcs/sync.toml") } + @Test func geminiPackageMetadataKeepsExactFieldsAndOriginalCoordinates() throws { + let fixture = try NativeImportFixture() + let file = "extension/gemini-extension.json" + let name = "cafe\u{301}" + let version = "1.2.3-e\u{301}" + let manifest = + "{\n \"version\": \"\(version)\",\n \"name\": \"\(name)\",\n \"contextFileName\": \"extra.md\"\n}" + try fixture.write(file, manifest) + try fixture.write("extension/commands/review.toml", "description='Review'\nprompt='Review'\n") + var input = fixture.input(.geminiExtensionV1, file) + input.selection = [] + let before = try fixture.hash() + let proposal = try SourceImport.preview(input) + let metadata = try #require(proposal.packageMetadata) + #expect(metadata.name.utf8.elementsEqual(name.utf8)) + #expect(metadata.version.utf8.elementsEqual(version.utf8)) + #expect(metadata.nameLocation.document == file) + #expect(metadata.nameLocation.pointer == "/member[1]") + #expect(metadata.nameLocation.span?.line == 3) + #expect(metadata.versionLocation.document == file) + #expect(metadata.versionLocation.pointer == "/member[2]") + #expect(metadata.versionLocation.span?.line == 2) + #expect(proposal.components.map(\.member?.selector) == [.command(name: "review")]) + #expect(proposal.diagnostics.contains { $0.code == .unconverted }) + #expect(try fixture.hash() == before) + + for field in ["", ", \"version\": \"\"", ", \"version\": 7", ", \"version\": null"] { + try fixture.write(file, "{\"name\":\"review\"\(field)}") + let invalidBefore = try fixture.hash() + let invalid = try SourceImport.preview(input) + #expect(invalid.packageMetadata == nil) + #expect(invalid.components.isEmpty) + #expect( + invalid.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == file + && $0.message == "Native extension requires a version string." + }) + #expect(try fixture.hash() == invalidBefore) + } + try fixture.write( + file, #"{"name":"review","version":"https://user:PRIVATE_VERSION_CANARY@example.test"}"#) + let sensitive = try SourceImport.preview(input) + #expect(sensitive.packageMetadata == nil) + #expect(!sensitive.bindings.isEmpty) + #expect(sensitive.components.count == 1) + #expect(!String(reflecting: sensitive).contains("PRIVATE_VERSION_CANARY")) + } + @Test func codexRoleRelativeFileAndOpenCodeOrderedPolicyBecomeTypedIntent() throws { let fixture = try NativeImportFixture() try fixture.write( From 5fdc84c2c6cf7833a2f359f9a9695adb903f07c2 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:28:34 +0800 Subject: [PATCH 124/171] fix: retain producer version in generated plugins --- Sources/Components/PluginExpansion.swift | 22 +++- .../GeneratedPluginTests.swift | 109 ++++++++++++++++-- 2 files changed, 122 insertions(+), 9 deletions(-) diff --git a/Sources/Components/PluginExpansion.swift b/Sources/Components/PluginExpansion.swift index 5fea1f5..4b92b71 100644 --- a/Sources/Components/PluginExpansion.swift +++ b/Sources/Components/PluginExpansion.swift @@ -10,7 +10,7 @@ extension Expansion { guard case .plugin( let name, let path, let alias, let mode, let select, let exclude, - let agents, _, _) = declaration + let agents, let authoredCondition, let authoredNative) = declaration else { return } guard active.count + pluginDepth < 64 else { throw LinkError.budget("active references") } let componentKey = key(name, kind: .plugin, context: context, group: group) @@ -62,6 +62,24 @@ extension Expansion { "native plugin \(failure.code.rawValue) at \(failure.location.document)\(failure.location.pointer)", chain) } + var effective = declaration + if profile == .geminiExtensionV1, let metadata = proposal.packageMetadata { + guard proposal.profile == profile, + [metadata.nameLocation, metadata.versionLocation].allSatisfy({ + $0.document.utf8.elementsEqual(document.utf8) + && $0.span?.document.rawValue.utf8.elementsEqual(document.utf8) == true + }) + else { + throw LinkError.invalid("native package metadata has different producer coordinates", chain) + } + if authoredNative[AgentID.geminiCLI.rawValue]?["version"] == nil { + var native = authoredNative + native[AgentID.geminiCLI.rawValue, default: [:]]["version"] = .string(metadata.version) + effective = .plugin( + name: name, path: path, source: alias, mode: mode, select: select, exclude: exclude, + agents: agents, condition: authoredCondition, native: native) + } + } // G's aliases are read coordinates in the already selected immutable producer tree. var aliases: [String: SourceSnapshot] = [:] for source in proposal.sources { @@ -80,7 +98,7 @@ extension Expansion { let parent = nextOccurrence try append( key: componentKey, snapshot: view.snapshot, pin: view.pin, - payload: .declaration(declaration), context: context, group: group, + payload: .declaration(effective), context: context, group: group, condition: condition, recipients: recipients, chatGPT: false, resources: [], chain: chain, position: position, dependencies: dependencies + [view.snapshot]) let actualRecipients = components[parentIndex].origins[0].recipients diff --git a/Tests/ComponentsTests/GeneratedPluginTests.swift b/Tests/ComponentsTests/GeneratedPluginTests.swift index 7fd1f28..8ab9f00 100644 --- a/Tests/ComponentsTests/GeneratedPluginTests.swift +++ b/Tests/ComponentsTests/GeneratedPluginTests.swift @@ -16,7 +16,9 @@ struct GeneratedPluginTests { document: fixture.document(expression), store: store, platform: .macOS ) { graph, session in let locations = Dictionary( - (graph.sourceSnapshots + graph.declaringSnapshots).map { + (graph.sourceSnapshots + graph.declaringSnapshots).filter { + $0.source?.kind == .local && $0.container == nil + }.map { ( $0.snapshot.source, LedgerLocation(kind: .absolute, path: String($0.snapshot.source.dropFirst(6))) @@ -280,11 +282,17 @@ struct GeneratedPluginTests { } } - @Test func geminiUsesFrozenExplicitVersionAndNativeExtensionFiles() throws { + @Test(arguments: [String?.none, "1.2.3"], [false, true]) + func geminiUsesFrozenVersionAndNativeExtensionFiles( + authoredVersion: String?, emptySelection: Bool + ) throws { let fixture = try LinkFixture() let store = StateStore(scope: .user, environment: fixture.environment) + let producerVersion = "9.0.0-e\u{301}" try fixture.write( - #"{"name":"upstream","version":"9.0.0","mcpServers":{"native":{"command":"fixture-server"}}}"#, + """ + {"name":"upstream","version":"\(producerVersion)","mcpServers":{"native":{"command":"fixture-server"}}} + """, to: "extension/gemini-extension.json", base: store.directory) try fixture.write( "description = \"Native review\"\nprompt = \"Literal review body\"\n".replacingOccurrences( @@ -300,11 +308,24 @@ struct GeneratedPluginTests { source: "." path: extension agents: [gemini-cli] - native: {gemini-cli: {version: "1.2.3"}} + \(emptySelection ? "select: []" : "") + native: + gemini-cli: + description: Consumer description + \(authoredVersion.map { "version: \"\($0)\"" } ?? "") """, scope: .user) + let expectedVersion = authoredVersion ?? producerVersion + let parent = try #require(frozen.ledger.components.values.first { $0.kind == "plugin" }) + let effective = try #require( + parent.payload.object?["native"]?.object?["gemini-cli"]? + .object?["version"]?.text) + #expect(effective.utf8.elementsEqual(expectedVersion.utf8)) var ledger = frozen.ledger ledger.lowerings = [try lower(components, frozen, surface: .geminiCLI, scope: .user)] ledger = try LedgerReplay.prepareLowerings(ledger, store: store, roots: [:], limits: .standard) + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + try FileManager.default.removeItem(at: store.directory.appendingPathComponent("extension")) + ledger = try ResolvedLedgerCodec.decode(encoded, limits: .standard) try LedgerReplay.withReplay(ledger, store: store, roots: [:], limits: .standard) { artifacts in let result = try NativeGeneratedPluginContribution.decode( ledger.lowerings[0], ledger: ledger, @@ -317,10 +338,84 @@ struct GeneratedPluginTests { Issue.record("missing extension") return } - #expect(manifest["version"] == .string("1.2.3")) - #expect(bundle.files["commands/review.toml"] != nil) - #expect(manifest["mcpServers"] != nil) + guard case .string(let version) = manifest["version"] else { + Issue.record("missing extension version") + return + } + #expect(version.utf8.elementsEqual(expectedVersion.utf8)) + #expect(manifest["description"] == .string("Consumer description")) + #expect((bundle.files["commands/review.toml"] == nil) == emptySelection) + #expect((manifest["mcpServers"] == nil) == emptySelection) + } + } + + @Test func geminiUnavailableVersionKeepsImportRefusalAndBindingBoundary() throws { + let fixture = try LinkFixture() + let declaration = """ + version: 1 + components: + - {kind: plugin, name: selected, source: ".", path: extension, select: [], agents: [gemini-cli]} + """ + for field in ["", ", \"version\": \"\"", ", \"version\": 7"] { + try fixture.write( + "{\"name\":\"upstream\"\(field)}", to: "extension/gemini-extension.json", + base: fixture.project) + do { + _ = try freeze(fixture, declaration) + Issue.record("Invalid producer version was admitted") + } catch { + #expect(String(describing: error).contains("native plugin invalidInput")) + } } + try fixture.write( + #"{"name":"upstream","version":"https://user:PRIVATE_VERSION_CANARY@example.test"}"#, + to: "extension/gemini-extension.json", base: fixture.project) + let (components, frozen) = try freeze(fixture, declaration) + let parent = try #require(frozen.ledger.components.values.first { $0.kind == "plugin" }) + #expect(parent.payload.object?["native"]?.object?["gemini-cli"]?.object?["version"] == nil) + let encoded = try ResolvedLedgerCodec.encode(frozen.ledger, limits: .standard) + #expect(!String(decoding: encoded, as: UTF8.self).contains("PRIVATE_VERSION_CANARY")) + var ledger = frozen.ledger + ledger.lowerings = [try lower(components, frozen, surface: .geminiCLI, scope: .user)] + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: .standard) + _ = try LedgerReplay.withReplay(ledger, store: fixture.store, roots: [:], limits: .standard) { + artifacts in + #expect(throws: (any Error).self) { + try NativeGeneratedPluginContribution.decode( + ledger.lowerings[0], ledger: ledger, artifacts: artifacts, limits: .standard) + } + } + } + + @Test func geminiVersionComesFromSelectedProducerCommitAndContainer() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("producer") + try fixture.initialize(repository) + try fixture.write( + #"{"name":"selected","version":"2.0.0"}"#, + to: "chosen/gemini-extension.json", base: repository) + try fixture.write( + #"{"name":"other","version":"3.0.0"}"#, + to: "other/gemini-extension.json", base: repository) + let commit = try fixture.commit(repository, tag: "1.0.0") + try fixture.write( + #"{"name":"selected","version":"99.0.0"}"#, + to: "chosen/gemini-extension.json", base: repository) + let (_, frozen) = try freeze( + fixture, + """ + version: 1 + sources: {p: {url: "file://localhost\(repository.path)", requirement: {exact: "1.0.0"}}} + components: + - {kind: plugin, name: consumer, source: p, path: chosen, select: [], agents: [gemini-cli]} + """) + let parent = try #require(frozen.ledger.components.values.first { $0.kind == "plugin" }) + #expect( + parent.payload.object?["native"]?.object?["gemini-cli"]?.object?["version"] == .init("2.0.0")) + let expansion = try #require(frozen.ledger.occurrences.first?.pluginExpansion) + #expect(expansion.document == "chosen/gemini-extension.json") + #expect(frozen.ledger.sources[expansion.source]?.revision == commit) } } From cc999442e0204aee04fd2b2ae7664d44313271aa Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:42:11 +0800 Subject: [PATCH 125/171] feat(watch): capture acknowledgment context and completion --- Sources/AgentsCore/WatchModels.swift | 9 + Sources/AgentsCore/WatchOperations.swift | 124 +++++++++-- Sources/AgentsUpdates/WatchCompletion.swift | 8 + .../WatchInspectionTests.swift | 5 + .../WatchConfirmationTests.swift | 192 +++++++++++++++++- 5 files changed, 313 insertions(+), 25 deletions(-) diff --git a/Sources/AgentsCore/WatchModels.swift b/Sources/AgentsCore/WatchModels.swift index 8afed57..cce3b79 100644 --- a/Sources/AgentsCore/WatchModels.swift +++ b/Sources/AgentsCore/WatchModels.swift @@ -70,6 +70,15 @@ public struct WatchStatus: Equatable, Sendable { /// Commits reachable from the current head but not from the seen revision; nil for indexes. public let commitCount: Int? public var changes: [WatchItemChange] + /// Durable scope files and local source roots; absent state leaves remain in the footprint. + public var readLocations: [URL] { acknowledgment.readLocations } + package let acknowledgment: WatchMutationPreview +} + +/// Read-only watch results retain their input locations even when there are no subscriptions. +public struct WatchInspection: Equatable, Sendable { + public let statuses: [WatchStatus] + public let readLocations: [URL] } /// A subscription after a watch change. `seen` is the acknowledged baseline, or nil after removal. diff --git a/Sources/AgentsCore/WatchOperations.swift b/Sources/AgentsCore/WatchOperations.swift index 766c2fe..4c36e89 100644 --- a/Sources/AgentsCore/WatchOperations.swift +++ b/Sources/AgentsCore/WatchOperations.swift @@ -65,14 +65,28 @@ public struct WatchOperations: Sendable { public func status( scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> [WatchStatus] { + try inspectStatus(scope: scope, environment: environment).statuses + } + + /// Captures statuses and durable inputs, including absent state files in an empty scope. + public func inspectStatus( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> WatchInspection { let store = StateStore(scope: scope, environment: environment) return try store.withReadLock { - let declaration = try declarations.read(store, nil) - _ = try store.readLedger() - let watch = try store.readWatch() - return try (declaration.watch ?? []).sorted().map { alias in - try inspect(alias: alias, declaration: declaration, watch: watch, store: store) + let baseline = try StatePrecondition(store: store) + let declaration = try declarations.read(store, baseline) + _ = try store.readLedger(prepared: baseline) + let watch = try store.readWatch(prepared: baseline) + let statuses = try (declaration.watch ?? []).sorted().map { alias in + try inspect( + alias: alias, declaration: declaration, watch: watch, store: store, baseline: baseline) } + try baseline.validate() + return WatchInspection( + statuses: statuses, + readLocations: durableReadLocations( + store, sources: (declaration.watch ?? []).compactMap { declaration.sources[$0] })) } } @@ -83,14 +97,17 @@ public struct WatchOperations: Sendable { ) throws -> WatchStatus { let store = StateStore(scope: scope, environment: environment) return try store.withReadLock { - let declaration = try declarations.read(store, nil) - _ = try store.readLedger() - let watch = try store.readWatch() + let baseline = try StatePrecondition(store: store) + let declaration = try declarations.read(store, baseline) + _ = try store.readLedger(prepared: baseline) + let watch = try store.readWatch(prepared: baseline) let alias = try subscription(source, declaration: declaration, environment: environment) - var result = try inspect(alias: alias, declaration: declaration, watch: watch, store: store) + var result = try inspect( + alias: alias, declaration: declaration, watch: watch, store: store, baseline: baseline) result.changes = result.changes.filter { (name == nil || $0.name == name) && (kind == nil || $0.kind == kind) } + try baseline.validate() return result } } @@ -101,9 +118,19 @@ public struct WatchOperations: Sendable { ifSourceIs expectedSource: String? = nil, scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> WatchChange { + try seen( + source, revision: revision, ifCurrentIs: expected, ifSourceIs: expectedSource, + scope: scope, environment: environment, preview: nil, outcome: TransactionOutcome()) + } + + private func seen( + _ source: String, revision: String? = nil, ifCurrentIs expected: WatchSeen?, + ifSourceIs expectedSource: String?, scope: InstallScope, environment: RuntimeEnvironment, + preview: WatchMutationPreview?, outcome: TransactionOutcome ) throws -> WatchChange { let store = StateStore(scope: scope, environment: environment) - return try store.withLock(checkpoint: checkpoint) { + return try store.withLock(checkpoint: checkpoint, outcome: outcome) { let baseline = try StatePrecondition(store: store) let declaration = try declarations.read(store, baseline) let lock = try store.readLedger(prepared: baseline) @@ -114,12 +141,18 @@ public struct WatchOperations: Sendable { guard expectedSource == nil || expectedSource == id else { throw CoreError.invalidState("watch source changed; refresh before acknowledging") } + if let preview { + try requireFingerprint( + preview, baseline: baseline, change: nil, seen: expected, store: store, + alias: alias, sourceID: id, removing: false) + } let current = try acknowledge(declared, revision: revision, expected: expected, store: store) guard expected == nil || expected == current else { throw CoreError.invalidState("watch content changed; refresh before acknowledging") } watch.sources[id] = WatchSourceState(seen: current) - try commit(nil, watch: watch, lock: lock, store: store, baseline: baseline) + try commit( + nil, watch: watch, lock: lock, store: store, baseline: baseline, outcome: outcome) return WatchChange(alias: alias, sourceID: id, seen: current) } } @@ -130,9 +163,16 @@ public struct WatchOperations: Sendable { _ status: WatchStatus, scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> WatchChange { - try seen( - status.alias, ifCurrentIs: status.current, ifSourceIs: status.sourceID, - scope: scope, environment: environment) + guard status.acknowledgment.matches(scope: scope, environment: environment) else { + throw CoreError.invalidState( + "watch scope or environment changed; refresh before acknowledging") + } + return try apply(previewSeen(status)) + } + + /// Confirms the displayed status in its captured scope and environment without acquiring resources. + public func previewSeen(_ status: WatchStatus) -> WatchMutationPreview { + status.acknowledgment } /// Removes only the subscription and baseline. Source declarations and installations remain. @@ -241,6 +281,11 @@ public struct WatchOperations: Sendable { source, alias: alias, requirement: requirement, path: path, scope: preview.store.scope, environment: preview.store.environment, expected: preview, outcome: outcome) + case .seen(let source): + return try seen( + source, ifCurrentIs: preview.seen, ifSourceIs: preview.sourceID, + scope: preview.store.scope, environment: preview.store.environment, + preview: preview, outcome: outcome) case .remove(let source): return try remove( source, scope: preview.store.scope, environment: preview.store.environment, @@ -249,8 +294,14 @@ public struct WatchOperations: Sendable { } private func mutationReadLocations(_ store: StateStore, source: SourceDeclaration) -> [URL] { - [store.declarationURL, store.resolvedURL, store.watchURL] - + (source.kind == .local ? [source.localURL(environment: store.environment)] : []) + durableReadLocations(store, sources: [source]) + } + + private func durableReadLocations(_ store: StateStore, sources: [SourceDeclaration]) -> [URL] { + let paths = + [store.declarationURL, store.resolvedURL, store.watchURL] + + sources.filter { $0.kind == .local }.map { $0.localURL(environment: store.environment) } + return Array(Set(paths.map(\.standardizedFileURL))).sorted { $0.path < $1.path } } private func mutationFingerprint( @@ -259,6 +310,8 @@ public struct WatchOperations: Sendable { ) throws -> String { struct Evidence: Encodable { let scope: InstallScope + let projectDirectory: String + let homeDirectory: String let alias: String let sourceID: String let removing: Bool @@ -268,7 +321,9 @@ public struct WatchOperations: Sendable { } return try ResolvedLedgerCodec.digest( Evidence( - scope: store.scope, alias: alias, sourceID: sourceID, removing: removing, + scope: store.scope, projectDirectory: store.environment.projectDirectory.path, + homeDirectory: store.environment.homeDirectory.path, + alias: alias, sourceID: sourceID, removing: removing, state: [store.declarationURL, store.resolvedURL, store.watchURL].map { try baseline.bytes(for: $0).map { FileHash.sha256Hex(data: $0) } }, declaration: change.map { FileHash.sha256Hex(data: $0.bytes) }, seen: seen)) @@ -492,7 +547,8 @@ public struct WatchOperations: Sendable { } private func inspect( - alias: String, declaration: Declaration, watch: WatchState, store: StateStore + alias: String, declaration: Declaration, watch: WatchState, store: StateStore, + baseline: StatePrecondition ) throws -> WatchStatus { let source = declaration.sources[alias]! let id = try source.identity(environment: store.environment) @@ -557,9 +613,17 @@ public struct WatchOperations: Sendable { oldPath: old?.path, newPath: new?.path, oldDigest: old?.digest, newDigest: new?.digest, files: files) } + let acknowledgment = WatchMutationPreview( + action: .seen(alias), store: store, alias: alias, sourceID: id, seen: current, + displayedFingerprint: try mutationFingerprint( + baseline: baseline, change: nil, seen: current, store: store, alias: alias, + sourceID: id, removing: false), + readLocations: mutationReadLocations(store, source: source)) return WatchStatus( - alias: alias, sourceID: id, seen: seen, current: current, commitCount: count, changes: changes - ) + alias: alias, sourceID: id, seen: seen, current: current, commitCount: count, + changes: changes, + acknowledgment: acknowledgment) + } private func units( @@ -651,10 +715,11 @@ private struct WatchUnit: Equatable { } /// Immutable subscription confirmation; no locks or borrowed resources escape preview. -public struct WatchMutationPreview: Sendable { - fileprivate enum Action: Sendable { +public struct WatchMutationPreview: Equatable, Sendable { + fileprivate enum Action: Equatable, Sendable { case add(String, String?, SourceRequirement?, String?) case remove(String) + case seen(String) } fileprivate let action: Action package let store: StateStore @@ -663,4 +728,19 @@ public struct WatchMutationPreview: Sendable { public let seen: WatchSeen? public let displayedFingerprint: String public let readLocations: [URL] + + fileprivate func matches(scope: InstallScope, environment: RuntimeEnvironment) -> Bool { + store.scope == scope + && store.environment.projectDirectory == environment.projectDirectory + && store.environment.homeDirectory == environment.homeDirectory + && store.environment.environment == environment.environment + } + + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.action == rhs.action + && lhs.matches(scope: rhs.store.scope, environment: rhs.store.environment) + && lhs.alias == rhs.alias && lhs.sourceID == rhs.sourceID && lhs.seen == rhs.seen + && lhs.displayedFingerprint == rhs.displayedFingerprint + && lhs.readLocations == rhs.readLocations + } } diff --git a/Sources/AgentsUpdates/WatchCompletion.swift b/Sources/AgentsUpdates/WatchCompletion.swift index dc9d80a..fd54d0e 100644 --- a/Sources/AgentsUpdates/WatchCompletion.swift +++ b/Sources/AgentsUpdates/WatchCompletion.swift @@ -2,6 +2,14 @@ import AgentsCore import AgentsSkills extension UpdateOperations { + /// Acknowledges exactly the displayed content in its captured scope and environment. + public static func performWatch( + _ status: WatchStatus, + operations: WatchOperations = SkillOperations.watchOperations() + ) -> UpdateCompletion { + performWatch(operations.previewSeen(status), operations: operations) + } + /// Uses WatchOperations' single subscription writer, then reports its actual outer terminal. public static func performWatch( _ preview: WatchMutationPreview, diff --git a/Tests/AgentsCoreTests/WatchInspectionTests.swift b/Tests/AgentsCoreTests/WatchInspectionTests.swift index 44207d8..df50225 100644 --- a/Tests/AgentsCoreTests/WatchInspectionTests.swift +++ b/Tests/AgentsCoreTests/WatchInspectionTests.swift @@ -77,6 +77,11 @@ struct WatchInspectionTests { discoverSkills: { _ in [] }, fetchArtifacts: { _ in throw CoreError.unsupported("no subscribed sources") }) + let inspection = try watch.inspectStatus(scope: scope, environment: environment) + #expect(inspection.statuses.isEmpty) + #expect( + Set(inspection.readLocations) + == Set([store.declarationURL, store.resolvedURL, store.watchURL])) #expect(try watch.status(scope: scope, environment: environment).isEmpty) #expect(try FileHash.folderHash(root) == before) #expect(throws: CoreError.notFound("source is not subscribed: ./source")) { diff --git a/Tests/AgentsUpdatesTests/WatchConfirmationTests.swift b/Tests/AgentsUpdatesTests/WatchConfirmationTests.swift index cb640b0..dd3f89e 100644 --- a/Tests/AgentsUpdatesTests/WatchConfirmationTests.swift +++ b/Tests/AgentsUpdatesTests/WatchConfirmationTests.swift @@ -81,11 +81,22 @@ struct WatchConfirmationTests { #expect(try f.store.loadDeclaration().watch == ["watched"]) } - @Test func committedWatchDisposalFailureHasAnOuterTerminalAndRetainedRecovery() throws { + @Test(arguments: [false, true]) + func committedWatchDisposalFailureHasAnOuterTerminalAndRetainedRecovery(_ acknowledging: Bool) + throws + { let f = try UpdateFixture() let operations = SkillOperations.watchOperations() - let preview = try operations.previewAdd( - f.repo.path, alias: "watched", environment: f.environment) + let preview: WatchMutationPreview + if acknowledging { + _ = try operations.add(f.repo.path, alias: "watched", environment: f.environment) + try f.advance() + preview = operations.previewSeen( + try #require(operations.status(environment: f.environment).first)) + } else { + preview = try operations.previewAdd( + f.repo.path, alias: "watched", environment: f.environment) + } let displaced = f.root.appendingPathComponent("displaced-watch") let interrupted = WatchOperations( discoverSkills: { _ in throw CoreError.invalidState("unexpected discovery") }, @@ -112,3 +123,178 @@ struct WatchConfirmationTests { #expect(try f.store.loadWatch().sources[preview.sourceID]?.seen == preview.seen) } } + +extension WatchConfirmationTests { + @Test(arguments: [InstallScope.project, .user]) + func displayedStatusRetainsDurableInputsAndAcknowledgesInItsCapturedScope(_ scope: InstallScope) + throws + { + let f = try UpdateFixture(scope: scope) + let operations = SkillOperations.watchOperations() + _ = try operations.add(f.repo.path, alias: "watched", scope: scope, environment: f.environment) + try f.advance() + let before = try f.snapshot() + let inspection = try operations.inspectStatus(scope: scope, environment: f.environment) + let displayed = try #require(inspection.statuses.first) + let diff = try operations.diff( + "watched", name: "demo", kind: .skill, scope: scope, environment: f.environment) + let expected = Set( + [f.store.declarationURL, f.store.resolvedURL, f.store.watchURL, f.repo].map(\.path)) + #expect(Set(inspection.readLocations.map(\.path)) == expected) + #expect(Set(displayed.readLocations.map(\.path)) == expected) + #expect(diff.readLocations == displayed.readLocations) + #expect(diff.changes.count == 1) + #expect(try f.snapshot() == before) + let preview = operations.previewSeen(diff) + #expect(preview == operations.previewSeen(displayed)) + let completion = UpdateOperations.performWatch(diff) + #expect(completion.disposition == .committed && !completion.recovery.pending) + #expect(!completion.recoveredBeforePreparation) + #expect(try completion.result.get().seen == displayed.current) + #expect(try f.store.loadWatch().sources[displayed.sourceID]?.seen == displayed.current) + #expect(!FileManager.default.fileExists(atPath: f.target().path)) + } + + @Test(arguments: ["content", "source", "declaration", "baseline"]) + func displayedAcknowledgmentRejectsChangedEvidence(_ changed: String) throws { + let f = try UpdateFixture() + let operations = SkillOperations.watchOperations() + _ = try operations.add(f.repo.path, alias: "watched", environment: f.environment) + try f.advance() + let displayed = try operations.diff("watched", environment: f.environment) + switch changed { + case "content": + try f.writeSource("later") + try f.commit() + case "source": + let other = f.root.appendingPathComponent("other-source") + try FileManager.default.copyItem(at: f.repo, to: other) + var declaration = try f.store.loadDeclaration() + declaration.sources["watched"]?.location = other.path + try f.store.save(declaration: declaration, ledger: f.store.loadLedger()) + case "declaration": + let bytes = try Data(contentsOf: f.store.declarationURL) + Data("# External edit.\n".utf8) + try bytes.write(to: f.store.declarationURL) + default: + _ = try operations.seen("watched", environment: f.environment) + } + let before = try f.snapshot() + let completion = UpdateOperations.performWatch(displayed) + #expect(completion.disposition == .unchanged && !completion.recovery.pending) + #expect(throws: (any Error).self) { try completion.result.get() } + #expect(try f.snapshot() == before) + } + + @Test(arguments: ["scope", "project", "home", "environment"]) + func displayedAcknowledgmentRejectsAnotherContext(_ changed: String) throws { + let f = try UpdateFixture() + let operations = SkillOperations.watchOperations() + _ = try operations.add(f.repo.path, alias: "watched", environment: f.environment) + let displayed = try operations.diff("watched", environment: f.environment) + var environment = f.environment + var scope = InstallScope.project + switch changed { + case "scope": scope = .user + case "project": environment.projectDirectory = f.root.appendingPathComponent("other-project") + case "home": environment.homeDirectory = f.root.appendingPathComponent("other-home") + default: environment.environment["WATCH_TEST_CONTEXT"] = "changed" + } + let before = try FileHash.folderHash(f.root) + #expect(throws: (any Error).self) { + try operations.seen(displayed, scope: scope, environment: environment) + } + #expect(try FileHash.folderHash(f.root) == before) + } + + @Test func unrelatedSecretVariationPreservesPublicFingerprintAndPrivateContextGuard() throws { + let f = try UpdateFixture() + let operations = SkillOperations.watchOperations() + _ = try operations.add(f.repo.path, alias: "watched", environment: f.environment) + var originalEnvironment = f.environment + originalEnvironment.environment["UNRELATED_CREDENTIAL"] = "first-private-value" + var changedEnvironment = originalEnvironment + changedEnvironment.environment["UNRELATED_CREDENTIAL"] = "second-private-value" + let original = try operations.diff("watched", environment: originalEnvironment) + let changed = try operations.diff("watched", environment: changedEnvironment) + let originalPreview = operations.previewSeen(original) + let changedPreview = operations.previewSeen(changed) + #expect(originalPreview.displayedFingerprint == changedPreview.displayedFingerprint) + #expect(originalPreview != changedPreview) + let before = try f.snapshot() + #expect(throws: (any Error).self) { + try operations.seen(original, environment: changedEnvironment) + } + #expect(try f.snapshot() == before) + let completion = UpdateOperations.performWatch(original) + #expect(completion.disposition == .committed && !completion.recovery.pending) + #expect(try completion.result.get().seen == original.current) + } + + @Test func displayedAcknowledgmentReportsRollbackAfterPublicationFailure() throws { + let f = try UpdateFixture() + let operations = SkillOperations.watchOperations() + _ = try operations.add(f.repo.path, alias: "watched", environment: f.environment) + try f.advance() + let displayed = try operations.diff("watched", environment: f.environment) + let before = try f.snapshot() + let interrupted = WatchOperations( + discoverSkills: { _ in [] }, fetchArtifacts: { _ in [] }, declarations: .manifest, + checkpoint: { point in + if point == TransactionCheckpoint.publication(0, .exchanged).name { + throw CoreError.invalidState("fixture publication interruption") + } + }) + let completion = UpdateOperations.performWatch(displayed, operations: interrupted) + #expect(completion.disposition == .rolledBack && !completion.recovery.pending) + #expect(throws: (any Error).self) { try completion.result.get() } + #expect(try f.snapshot() == before) + } +} + +extension WatchConfirmationTests { + @Test func artifactAcknowledgmentUsesTheOuterOutcomeAndRevalidatesDigests() throws { + let f = try UpdateFixture() + func operations(_ body: String, failPreparation: Bool = false) -> WatchOperations { + let bytes = Data(body.utf8) + let digest = "sha256:" + FileHash.sha256Hex(data: bytes) + return WatchOperations( + discoverSkills: { _ in [] }, + fetchArtifacts: { _ in + [ + WatchArtifact( + name: "demo", + artifact: LockedArtifact( + type: .skillMD, url: "https://example.invalid/demo.md", digest: digest), + files: ["SKILL.md": bytes], payloads: [digest: bytes]) + ] + }, declarations: .manifest, + checkpoint: { point in + if failPreparation && point == "watch.artifact.0.content.journal.committed" { + throw CoreError.invalidState("fixture artifact preparation interruption") + } + }) + } + let original = operations("original") + _ = try original.add( + "https://example.invalid/index", alias: "watched", environment: f.environment) + let originalStatus = try original.diff("watched", environment: f.environment) + let advanced = operations("advanced") + let before = try f.snapshot() + let stale = UpdateOperations.performWatch(originalStatus, operations: advanced) + #expect(stale.disposition == .unchanged && !stale.recovery.pending) + #expect(throws: (any Error).self) { try stale.result.get() } + #expect(try f.snapshot() == before) + let displayed = try advanced.diff("watched", environment: f.environment) + #expect( + Set(displayed.readLocations.map(\.path)) + == Set([f.store.declarationURL, f.store.resolvedURL, f.store.watchURL].map(\.path))) + let interrupted = UpdateOperations.performWatch( + displayed, operations: operations("advanced", failPreparation: true)) + #expect(interrupted.disposition == .unchanged && !interrupted.recovery.pending) + #expect(throws: (any Error).self) { try interrupted.result.get() } + #expect(try f.snapshot() == before) + let completed = UpdateOperations.performWatch(displayed, operations: advanced) + #expect(completed.disposition == .committed && !completed.recovery.pending) + #expect(try completed.result.get().seen == displayed.current) + } +} From 3cb0848281f9a5cb3a7f6cbcbd080584c704be2f Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:55:50 +0800 Subject: [PATCH 126/171] feat(clients): inspect local clients and supported configuration --- Documentation/Reference/AgentClients.md | 70 ++++++ Documentation/Reference/README.md | 2 + .../AgentsCore/AgentClientApplications.swift | 37 +++ .../AgentsCore/AgentClientObservation.swift | 181 ++++++++++++++ Sources/AgentsCore/AgentRegistry.swift | 51 ++++ Sources/AgentsCore/InstructionLocations.swift | 17 ++ .../AgentsCore/NativeTargetCoordination.swift | 73 +++++- .../AgentsUpdates/AgentClientInspection.swift | 202 ++++++++++++++++ .../ClientCapabilityInspection.swift | 73 ++++++ .../AgentClientObservationTests.swift | 72 ++++++ .../AgentClientInspectionTests.swift | 225 ++++++++++++++++++ 11 files changed, 992 insertions(+), 11 deletions(-) create mode 100644 Documentation/Reference/AgentClients.md create mode 100644 Sources/AgentsCore/AgentClientApplications.swift create mode 100644 Sources/AgentsCore/AgentClientObservation.swift create mode 100644 Sources/AgentsUpdates/AgentClientInspection.swift create mode 100644 Sources/Components/ClientCapabilityInspection.swift create mode 100644 Tests/AgentsCoreTests/AgentClientObservationTests.swift create mode 100644 Tests/AgentsUpdatesTests/AgentClientInspectionTests.swift diff --git a/Documentation/Reference/AgentClients.md b/Documentation/Reference/AgentClients.md new file mode 100644 index 0000000..82c4b0c --- /dev/null +++ b/Documentation/Reference/AgentClients.md @@ -0,0 +1,70 @@ +# Passive agent client inspection + +`AgentsUpdates` exposes a synchronous, read-only client observation API. Supply +one captured `RuntimeEnvironment`; the default scope is `.user`. + +```swift +import AgentsCore +import AgentsUpdates + +let environment = RuntimeEnvironment() +let report = try AgentClientOperations.inspect(environment: environment) +for client in report.clients { + for command in client.commands { + print(client.agent.displayName, command.name, command.status.rawValue) + print(command.version.rawVersion ?? "Unknown") + } +} +``` + +`AgentClientInspection` and its immutable `Sendable` records describe the +observation interval, captured project/home context, PATH coverage, command and +application observations, logical configuration locations and frozen schema +evidence. Request `.project` with the selected project's explicit environment +to inspect its locations. + +Command lookup searches only absolute entries in the supplied PATH, in order, +and stops at the first regular executable for each command. Empty and relative +entries appear in `excludedEntries`. `lookupIssues` preserves failed access +before a selection; a later selection then does not guarantee shell resolution. +Missing commands mean no executable was found within this coverage. Shell +aliases, functions and installations outside PATH are outside this observation. +Cursor's `editorLauncher` and `agentCLI` records are separate. + +On macOS, application lookup uses registered bundle identifiers with an existing +discovery recipe and validates the bundle's metadata identity. Other platforms +report application lookup as unavailable. Currently the evidenced application +recipe is Cursor; other agents return an unavailable application observation. +Only Cursor's recognized editor launcher layout is associated with that bundle. +Other executable layouts return `unrecognizedLayout`; arbitrary neighboring +package metadata and directory labels do not supply versions. + +Versions retain raw labels. Bundle version and build are separate fields, with +metadata URL/key provenance. Missing, unreadable, malformed, oversized or +non-regular metadata has a typed `unknownReason`. Metadata reads follow ordinary +installation symlinks, validate the opened descriptor and enforce a 1 MiB limit +throughout reading. Inspection never executes candidate files. + +Configuration locations come from their existing skill, instruction and native +route owners. Presence checks inspect type only, without reading configuration +contents. Semantic records remain distinct when paths coincide, including +Claude local/user MCP regions. OpenCode JSON and JSONC alternatives are both +reported. Skill scan paths and installation destinations have different +purposes. Gemini/OpenCode skill and native overrides follow their respective +owners, so their paths can differ. Invalid native overrides affect their own +location observations; absent roots still yield logical paths. + +Schema evidence preserves the registry's surface, component kind, scope and +standalone/plugin-member placement. `recorded` means the profile has frozen +schema evidence; `unsupportedUnderEvidence` reflects an explicit unsupported +contract, and `unverified` means the contract is not established. Revisions and +source references are evidence provenance. In particular, `installed:2.1.309` +is a historical evidence revision, not a currently detected client version. +Preview remains responsible for configuration admission. + +Consumers should run inspection on their existing operation executor and retain +the latest result in their client settings state. Re-detection is explicit. +Returned paths are provenance, rather than workspace-monitor read footprints. +Unknown versions, missing clients and detection failures do not change editing +availability. The report is an interval of observations, rather than an atomic +filesystem snapshot. This operation neither recovers nor writes managed state. diff --git a/Documentation/Reference/README.md b/Documentation/Reference/README.md index 69730c4..aa905fd 100644 --- a/Documentation/Reference/README.md +++ b/Documentation/Reference/README.md @@ -4,6 +4,8 @@ This directory holds supporting reference material for `core`. ## Guides +- [Agent client inspection](AgentClients.md): passive observations and schema evidence through the public API. + - [Agents manifest language](Manifest.md): YAML field shapes, scalar semantics, limits, source edits, dump and diagnostics. - [Repository presentation](Presentation.md): the README Quick look fixture and standalone consumer validation. diff --git a/Sources/AgentsCore/AgentClientApplications.swift b/Sources/AgentsCore/AgentClientApplications.swift new file mode 100644 index 0000000..5160770 --- /dev/null +++ b/Sources/AgentsCore/AgentClientApplications.swift @@ -0,0 +1,37 @@ +import Foundation + +#if os(macOS) + import AppKit +#endif + +package struct ClientApplicationObservation: Sendable { + package let bundleIdentifier: String? + package let location: URL? + package let state: ClientObservationState + package let version: ClientVersionObservation +} + +package enum AgentClientApplications { + package static func inspect(agent: AgentID) -> ClientApplicationObservation { + guard let identifier = AgentRegistry.clientBundleIdentifier(for: agent) else { + return .init( + bundleIdentifier: nil, location: nil, state: .unavailable, + version: .unknown(.unrecognizedLayout)) + } + #if os(macOS) + guard let location = NSWorkspace.shared.urlForApplication(withBundleIdentifier: identifier) + else { + return .init( + bundleIdentifier: identifier, location: nil, state: .notFound, + version: .unknown(.artifactNotFound)) + } + let (state, version) = AgentClientObservation.bundleVersion( + at: location, identifier: identifier) + return .init(bundleIdentifier: identifier, location: location, state: state, version: version) + #else + return .init( + bundleIdentifier: identifier, location: nil, state: .unavailable, + version: .unknown(.unavailable)) + #endif + } +} diff --git a/Sources/AgentsCore/AgentClientObservation.swift b/Sources/AgentsCore/AgentClientObservation.swift new file mode 100644 index 0000000..60b7d06 --- /dev/null +++ b/Sources/AgentsCore/AgentClientObservation.swift @@ -0,0 +1,181 @@ +import CPlatform +import Foundation + +package enum ClientObservationState: String, Sendable { + case present, notFound, inaccessible, invalid, unavailable +} + +package enum ClientVersionUnknown: String, Sendable { + case artifactNotFound, unrecognizedLayout, missingMetadata, unreadableMetadata + case malformedMetadata, oversizedMetadata, nonRegularMetadata, missingVersion, unavailable +} + +package struct ClientVersionObservation: Sendable { + package let version: String? + package let build: String? + package let metadata: URL? + package let key: String? + package let unknown: ClientVersionUnknown? + + package static func unknown(_ reason: ClientVersionUnknown, at metadata: URL? = nil) -> Self { + .init(version: nil, build: nil, metadata: metadata, key: nil, unknown: reason) + } +} + +package struct ClientPathIssue: Sendable { + package let path: String + package let state: ClientObservationState + package let reason: String +} + +package struct ClientPathCoverage: Sendable { + package let supplied: Bool + package let directories: [URL] + package let excluded: [String] + + package init(environment: RuntimeEnvironment) { + supplied = environment.environment["PATH"] != nil + let entries = environment.environment["PATH"]?.components(separatedBy: ":") ?? [] + directories = entries.filter { $0.hasPrefix("/") && !$0.contains("\0") } + .map { URL(fileURLWithPath: $0, isDirectory: true) } + excluded = entries.filter { !$0.hasPrefix("/") || $0.contains("\0") } + } +} + +package struct ClientCommandObservation: Sendable { + package let command: String + package let role: String + package let location: URL? + package let resolvedLocation: URL? + package let state: ClientObservationState + package let issues: [ClientPathIssue] + package let version: ClientVersionObservation +} + +package enum AgentClientObservation { + package static func failureState(_ code: Int32) -> ClientObservationState { + switch code { + case ENOENT, ENOTDIR: .notFound + case EACCES, EPERM: .inaccessible + default: .invalid + } + } + + package static func presence(_ url: URL, directory: Bool) -> ClientObservationState { + guard url.isFileURL, !url.path.contains("\0") else { return .invalid } + var info = stat() + guard stat(url.path, &info) == 0 else { return failureState(errno) } + let kind = info.st_mode & mode_t(S_IFMT) + return kind == mode_t(directory ? S_IFDIR : S_IFREG) ? .present : .invalid + } + + package static func command( + _ candidate: AgentRegistry.ClientCommand, coverage: ClientPathCoverage + ) -> ClientCommandObservation { + var issues: [ClientPathIssue] = [] + for directory in coverage.directories { + let url = directory.appendingPathComponent(candidate.name) + var info = stat() + if stat(url.path, &info) != 0 { + let code = errno + if code != ENOENT && code != ENOTDIR { + issues.append( + .init(path: url.path, state: failureState(code), reason: "executable lookup failed")) + } + continue + } + guard info.st_mode & mode_t(S_IFMT) == mode_t(S_IFREG) else { continue } + guard access(url.path, X_OK) == 0 else { + issues.append( + .init(path: url.path, state: failureState(errno), reason: "executable access denied")) + continue + } + let resolved = url.resolvingSymlinksInPath() + let version: ClientVersionObservation + if let bundle = AgentRegistry.clientBundle(for: candidate.name, resolvedExecutable: resolved), + let identifier = AgentRegistry.clientBundleIdentifier(for: .cursor) + { + version = bundleVersion(at: bundle, identifier: identifier).1 + } else { + version = .unknown(.unrecognizedLayout) + } + return .init( + command: candidate.name, role: candidate.role, location: url, resolvedLocation: resolved, + state: .present, issues: issues, version: version) + } + return .init( + command: candidate.name, role: candidate.role, location: nil, resolvedLocation: nil, + state: coverage.directories.isEmpty + ? .unavailable : issues.first?.state ?? .notFound, + issues: issues, + version: .unknown( + coverage.directories.isEmpty || !issues.isEmpty ? .unavailable : .artifactNotFound)) + } + + /// Follows installation symlinks, validates the opened object, and bounds even growing files. + package static func metadata(_ url: URL) throws -> Data { + guard url.isFileURL, !url.path.contains("\0") else { + throw ClientVersionUnknownError(.unreadableMetadata) + } + let fd = open(url.path, O_RDONLY | O_CLOEXEC | O_NONBLOCK) + guard fd >= 0 else { + throw ClientVersionUnknownError( + errno == ENOENT || errno == ENOTDIR ? .missingMetadata : .unreadableMetadata) + } + defer { close(fd) } + var info = stat() + guard fstat(fd, &info) == 0 else { throw ClientVersionUnknownError(.unreadableMetadata) } + guard info.st_mode & mode_t(S_IFMT) == mode_t(S_IFREG) else { + throw ClientVersionUnknownError(.nonRegularMetadata) + } + let limit = 1_048_576 + guard info.st_size >= 0, info.st_size <= limit else { + throw ClientVersionUnknownError(.oversizedMetadata) + } + var result = Data() + var buffer = [UInt8](repeating: 0, count: 16_384) + while true { + let count = read(fd, &buffer, min(buffer.count, limit + 1 - result.count)) + if count < 0 { + if errno == EINTR { continue } + throw ClientVersionUnknownError(.unreadableMetadata) + } + if count == 0 { return result } + result.append(contentsOf: buffer.prefix(count)) + guard result.count <= limit else { throw ClientVersionUnknownError(.oversizedMetadata) } + } + } + + package static func bundleVersion(at bundle: URL, identifier: String) + -> (ClientObservationState, ClientVersionObservation) + { + let url = bundle.appendingPathComponent("Contents/Info.plist") + do { + let bytes = try metadata(url) + guard + let plist = try? PropertyListSerialization.propertyList(from: bytes, format: nil) + as? [String: Any], + plist["CFBundleIdentifier"] as? String == identifier + else { return (.invalid, .unknown(.malformedMetadata, at: url)) } + let version = (plist["CFBundleShortVersionString"] as? String).flatMap { + $0.isEmpty ? nil : $0 + } + let build = (plist["CFBundleVersion"] as? String).flatMap { $0.isEmpty ? nil : $0 } + return ( + .present, + .init( + version: version, build: build, metadata: url, + key: "CFBundleShortVersionString", unknown: version == nil ? .missingVersion : nil) + ) + } catch let error as ClientVersionUnknownError { + let state: ClientObservationState = + error.reason == .unreadableMetadata ? .inaccessible : .invalid + return (state, .unknown(error.reason, at: url)) + } catch { return (.invalid, .unknown(.malformedMetadata, at: url)) } + } +} + +package struct ClientVersionUnknownError: Error { + package let reason: ClientVersionUnknown + package init(_ reason: ClientVersionUnknown) { self.reason = reason } +} diff --git a/Sources/AgentsCore/AgentRegistry.swift b/Sources/AgentsCore/AgentRegistry.swift index 2f02b7f..912d661 100644 --- a/Sources/AgentsCore/AgentRegistry.swift +++ b/Sources/AgentsCore/AgentRegistry.swift @@ -200,3 +200,54 @@ package enum AgentRegistry { } } + +extension AgentRegistry { + package struct ClientCommand: Sendable { + package let name: String + package let role: String + } + + package static func clientCommands(for agent: AgentID) -> [ClientCommand] { + switch agent { + case .codex: [.init(name: "codex", role: "agentCLI")] + case .claudeCode: [.init(name: "claude", role: "agentCLI")] + case .geminiCLI: [.init(name: "gemini", role: "agentCLI")] + case .opencode: [.init(name: "opencode", role: "agentCLI")] + case .cursor: + [ + .init(name: "cursor", role: "editorLauncher"), + .init(name: "cursor-agent", role: "agentCLI"), + ] + } + } + + // Registered editor bundle identity; the agent CLI has independent metadata. + package static func clientBundleIdentifier(for agent: AgentID) -> String? { + agent == .cursor ? "com.todesktop.230313mzl4w4u92" : nil + } + + package static func clientSkillLocations( + for agent: AgentID, scope: InstallScope, environment: RuntimeEnvironment + ) -> [(String, URL)] { + let scans = + scope == .user + ? nativeUserScanDirectories(for: agent, environment: environment) + : projectScanDirectories(for: agent, environment: environment) + return [ + ("skills.install", installSkillsDirectory(for: agent, scope: scope, environment: environment)) + ] + + scans.enumerated().map { ("skills.scan.\($0.offset)", $0.element) } + } +} + +extension AgentRegistry { + /// Only the bundled editor launcher carries this bundle metadata association. + package static func clientBundle(for command: String, resolvedExecutable: URL) -> URL? { + guard command == "cursor", + resolvedExecutable.path.hasSuffix("/Contents/Resources/app/bin/cursor") + else { return nil } + var bundle = resolvedExecutable + for _ in 0..<5 { bundle.deleteLastPathComponent() } + return bundle + } +} diff --git a/Sources/AgentsCore/InstructionLocations.swift b/Sources/AgentsCore/InstructionLocations.swift index 4efb755..a0f8925 100644 --- a/Sources/AgentsCore/InstructionLocations.swift +++ b/Sources/AgentsCore/InstructionLocations.swift @@ -82,3 +82,20 @@ package enum InstructionLocations { return file.standardizedFileURL } } + +extension InstructionLocations { + package static func clientFiles( + for agent: AgentID, scope: InstallScope, environment: RuntimeEnvironment + ) -> [(String, URL)] { + var result = + file(for: agent, scope: scope, environment: environment).map { + [("instructions.fixed", $0)] + } ?? [] + if agent == .claudeCode && scope == .project { + result += projectPaths.filter { $0.contains("CLAUDE") }.map { + ("instructions." + $0, environment.projectDirectory.appendingPathComponent($0)) + } + } + return result + } +} diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index 89e3c41..dd2c71a 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -287,6 +287,11 @@ package struct NativeTargetRoute: RawRepresentable, Hashable, Codable, Sendable } /// Known readers are a lower bound; plugin/custom-root exclusivity needs reader evidence. package var knownReaders: Set { + Self.knownReaders(rawValue: rawValue, fixed: fixed, member: member) + } + private static func knownReaders( + rawValue: String, fixed: FixedNativeTargetRoute?, member: Member? + ) -> Set { if fixed == .claudeSettingsProject || fixed == .claudeSettingsUser || member == .claudeAgent { return [.claudeCode, .cursor] } @@ -351,29 +356,75 @@ package struct NativeTargetRoute: RawRepresentable, Hashable, Codable, Sendable loader: try fixed.logicalDirectory( environment, validateExistingOverride: validateExistingOverride), descendants: []) } + let recipe = Self.memberRecipe(member!, scope: memberScope!) + return NativeRootAuthority( + loader: try recipe.base.logicalDirectory( + environment, validateExistingOverride: validateExistingOverride), + descendants: recipe.container + name!.split(separator: "/").dropLast().map(String.init)) + } + + private static func memberRecipe(_ member: Member, scope: InstallScope) + -> (base: FixedNativeTargetRoute, container: [String]) + { let base: FixedNativeTargetRoute - switch member! { + switch member { case .claudeCommand, .claudeAgent, .claudeSkillPlugin: - base = memberScope == .project ? .claudeSettingsProject : .claudeSettingsUser - case .codexAgent: - base = memberScope == .project ? .codexMCPProject : .codexMCPUser + base = scope == .project ? .claudeSettingsProject : .claudeSettingsUser + case .codexAgent: base = scope == .project ? .codexMCPProject : .codexMCPUser case .geminiCommand, .geminiAgent, .geminiExtension: - base = memberScope == .project ? .geminiMCPProject : .geminiMCPUser + base = scope == .project ? .geminiMCPProject : .geminiMCPUser case .cursorCommand, .cursorAgent, .cursorLocalPlugin: - base = memberScope == .project ? .cursorMCPProject : .cursorMCPUser + base = scope == .project ? .cursorMCPProject : .cursorMCPUser } let container: [String] - switch member! { + switch member { case .claudeCommand, .geminiCommand, .cursorCommand: container = ["commands"] case .claudeAgent, .codexAgent, .geminiAgent, .cursorAgent: container = ["agents"] case .claudeSkillPlugin: container = ["skills"] case .cursorLocalPlugin: container = ["plugins", "local"] case .geminiExtension: container = ["extensions"] } - return NativeRootAuthority( - loader: try base.logicalDirectory( - environment, validateExistingOverride: validateExistingOverride), - descendants: container + name!.split(separator: "/").dropLast().map(String.init)) + return (base, container) + } + + package struct ClientLocation { + package let identity: String + package let agents: Set + package let evidenceScope: String + package let container: Bool + package let location: Result + } + + package static func clientLocations(scope: InstallScope, environment: RuntimeEnvironment) + -> [ClientLocation] + { + let fixed = FixedNativeTargetRoute.allCases.filter { + scope == .user ? $0.shared : !$0.shared || $0 == .claudeMCPLocal + }.map { route in + return ClientLocation( + identity: route.rawValue, agents: Self(route).knownReaders, + evidenceScope: route == .claudeMCPLocal ? "local" : scope.rawValue, container: false, + location: Result { + try route.logicalDirectory(environment, validateExistingOverride: false) + .appendingPathComponent(route.basename) + }) + } + let members = Member.allCases.filter { + !($0 == .cursorCommand && scope != .project) + && !([Member.cursorLocalPlugin, .geminiExtension].contains($0) && scope != .user) + }.map { member in + let recipe = memberRecipe(member, scope: scope) + return ClientLocation( + identity: member.rawValue + "." + scope.rawValue, + agents: knownReaders(rawValue: member.rawValue, fixed: nil, member: member), + evidenceScope: scope.rawValue, container: true, + location: Result { + try recipe.container.reduce( + recipe.base.logicalDirectory(environment, validateExistingOverride: false) + ) { $0.appendingPathComponent($1) } + }) + } + return fixed + members } func logicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { try rootAuthority(environment).logicalDirectory diff --git a/Sources/AgentsUpdates/AgentClientInspection.swift b/Sources/AgentsUpdates/AgentClientInspection.swift new file mode 100644 index 0000000..63a2c79 --- /dev/null +++ b/Sources/AgentsUpdates/AgentClientInspection.swift @@ -0,0 +1,202 @@ +import AgentsCore +import Components +import Foundation + +public enum AgentClientObservationStatus: String, Sendable { + case present, notFound, inaccessible, invalid, unavailable +} + +public enum AgentClientVersionUnknown: String, Sendable { + case artifactNotFound, unrecognizedLayout, missingMetadata, unreadableMetadata + case malformedMetadata, oversizedMetadata, nonRegularMetadata, missingVersion, unavailable +} + +/// Raw artifact metadata, independent of historical schema evidence and configuration admission. +public struct AgentClientVersion: Sendable { + public let rawVersion: String? + public let build: String? + public let metadataURL: URL? + public let metadataKey: String? + public let unknownReason: AgentClientVersionUnknown? + + fileprivate init(_ value: ClientVersionObservation) { + rawVersion = value.version + build = value.build + metadataURL = value.metadata + metadataKey = value.key + unknownReason = value.unknown.flatMap { AgentClientVersionUnknown(rawValue: $0.rawValue) } + } +} + +public struct AgentClientLookupIssue: Sendable { + public let path: String + public let status: AgentClientObservationStatus + public let reason: String +} + +public struct AgentClientPATHCoverage: Sendable { + public let pathWasSupplied: Bool + public let absoluteDirectories: [URL] + /// Empty and relative entries are excluded rather than resolved against an implicit directory. + public let excludedEntries: [String] +} + +public struct AgentClientCommand: Sendable { + public enum Role: String, Sendable { case agentCLI, editorLauncher } + public let name: String + public let role: Role + public let location: URL? + public let resolvedLocation: URL? + public let status: AgentClientObservationStatus + /// Earlier lookup errors mean a later selection is not guaranteed shell resolution. + public let lookupIssues: [AgentClientLookupIssue] + public let version: AgentClientVersion +} + +public struct AgentClientApplication: Sendable { + public let bundleIdentifier: String? + public let location: URL? + public let status: AgentClientObservationStatus + public let version: AgentClientVersion +} + +public struct AgentClientConfigurationLocation: Sendable { + public enum Purpose: String, Sendable { + case skillInstallation, skillScan, instructions, nativeConfiguration + } + public enum ObjectRole: String, Sendable { case file, container } + public let identity: String + public let scope: String + public let purpose: Purpose + public let objectRole: ObjectRole + public let location: URL? + public let status: AgentClientObservationStatus + public let diagnostic: String? +} + +public struct AgentClientSurface: Sendable { + public let identifier: String + public let displayName: String +} + +public struct AgentClientSchemaEvidence: Sendable { + public enum Status: String, Sendable { case recorded, unsupportedUnderEvidence, unverified } + public enum Placement: String, Sendable { case standalone, pluginMember } + public let surface: AgentClientSurface + public let kind: DeclaredComponentKind + public let scope: String + public let placement: Placement + public let status: Status + public let revision: String? + public let sources: [String] + public let limitation: String? +} + +public struct AgentClientRecord: Sendable { + public let agent: AgentID + public let commands: [AgentClientCommand] + public let applications: [AgentClientApplication] + public let configurationLocations: [AgentClientConfigurationLocation] + public let schemaEvidence: [AgentClientSchemaEvidence] +} + +/// An interval of passive observations, not an atomic snapshot or a configuration admission result. +public struct AgentClientInspection: Sendable { + public let startedAt: Date + public let finishedAt: Date + public let scope: InstallScope + public let projectDirectory: URL + public let homeDirectory: URL + public let pathCoverage: AgentClientPATHCoverage + public let clients: [AgentClientRecord] +} + +public enum AgentClientOperations { + /// Never invokes clients, reads configuration contents, recovers state or writes destinations. + /// Returned URLs are provenance; consumers should keep explicit re-detection independent of editing. + public static func inspect( + scope: InstallScope = .user, environment: RuntimeEnvironment + ) throws -> AgentClientInspection { + let started = Date() + let coverage = ClientPathCoverage(environment: environment) + let nativeLocations = NativeTargetRoute.clientLocations(scope: scope, environment: environment) + let clients = AgentID.allCases.map { agent in + let commands = AgentRegistry.clientCommands(for: agent).map { candidate in + let value = AgentClientObservation.command(candidate, coverage: coverage) + return AgentClientCommand( + name: value.command, role: .init(rawValue: value.role)!, + location: value.location, resolvedLocation: value.resolvedLocation, + status: status(value.state), + lookupIssues: value.issues.map { + .init(path: $0.path, status: status($0.state), reason: $0.reason) + }, version: .init(value.version)) + } + let application = AgentClientApplications.inspect(agent: agent) + var locations = AgentRegistry.clientSkillLocations( + for: agent, scope: scope, environment: environment + ) + .map { identity, url in + location( + identity, scope: scope.rawValue, + purpose: identity == "skills.install" ? .skillInstallation : .skillScan, + container: true, result: .success(url)) + } + locations += InstructionLocations.clientFiles( + for: agent, scope: scope, environment: environment + ).map { + location( + $0.0, scope: scope.rawValue, purpose: .instructions, container: false, + result: .success($0.1)) + } + locations += nativeLocations.filter { $0.agents.contains(agent) }.map { + location( + $0.identity, scope: $0.evidenceScope, purpose: .nativeConfiguration, + container: $0.container, result: $0.location) + } + return AgentClientRecord( + agent: agent, commands: commands, + applications: [ + .init( + bundleIdentifier: application.bundleIdentifier, + location: application.location, status: status(application.state), + version: .init(application.version)) + ], + configurationLocations: locations, + schemaEvidence: ClientCapabilityInspection.entries(for: agent).map { + .init( + surface: .init(identifier: $0.surface.rawValue, displayName: $0.displayName), + kind: $0.kind, scope: $0.scope, placement: .init(rawValue: $0.placement)!, + status: .init(rawValue: $0.status)!, revision: $0.evidence?.revision, + sources: $0.evidence?.sources ?? [], limitation: $0.reason) + }) + } + return .init( + startedAt: started, finishedAt: Date(), scope: scope, + projectDirectory: environment.projectDirectory, homeDirectory: environment.homeDirectory, + pathCoverage: .init( + pathWasSupplied: coverage.supplied, absoluteDirectories: coverage.directories, + excludedEntries: coverage.excluded), clients: clients) + } + + private static func status(_ value: ClientObservationState) -> AgentClientObservationStatus { + .init(rawValue: value.rawValue)! + } + + private static func location( + _ identity: String, scope: String, purpose: AgentClientConfigurationLocation.Purpose, + container: Bool, result: Result + ) -> AgentClientConfigurationLocation { + switch result { + case .success(let url): + .init( + identity: identity, scope: scope, purpose: purpose, + objectRole: container ? .container : .file, location: url, + status: status(AgentClientObservation.presence(url, directory: container)), diagnostic: nil) + case .failure(let error): + .init( + identity: identity, scope: scope, purpose: purpose, + objectRole: container ? .container : .file, location: nil, status: .invalid, + diagnostic: String(describing: error)) + } + } +} diff --git a/Sources/Components/ClientCapabilityInspection.swift b/Sources/Components/ClientCapabilityInspection.swift new file mode 100644 index 0000000..2248cfc --- /dev/null +++ b/Sources/Components/ClientCapabilityInspection.swift @@ -0,0 +1,73 @@ +import AgentsCore + +/// Describes registry evidence only; field, resource and integration admission belongs to preview. +package struct ClientCapabilityEvidence { + package let surface: NativeClientSurface + package let displayName: String + package let kind: DeclaredComponentKind + package let scope: String + package let placement: String + package let status: String + package let evidence: NativeSchemaEvidence? + package let reason: String? +} + +extension NativeClientSurface { + package var displayName: String { + switch self { + case .claudeCode: "Claude Code" + case .codexCLI: "Codex CLI" + case .geminiCLI: "Gemini CLI" + case .openCodeCLI: "OpenCode CLI" + case .cursorEditor: "Cursor Editor" + case .cursorCLI: "Cursor CLI" + case .cursorCloud: "Cursor Cloud" + } + } +} + +package enum ClientCapabilityInspection { + package static func entries(for agent: AgentID) -> [ClientCapabilityEvidence] { + NativeClientSurface.allCases.filter { $0.agent == agent }.flatMap { surface in + DeclaredComponentKind.allCases.flatMap { kind -> [ClientCapabilityEvidence] in + let scopes = kind == .mcpServer ? ["project", "local", "user"] : ["project", "user"] + return scopes.flatMap { scope in + let placements = kind == .command ? ["standalone", "pluginMember"] : ["standalone"] + return placements.map { placement in + var evidence: NativeSchemaEvidence? + var status = "unverified" + var reason: String? + do { + if kind == .skills || kind == .instructions { + reason = + "Existing domain locations are available; comparable frozen schema evidence is not recorded." + } else if kind == .mcpServer { + evidence = try CapabilityRegistry.mcp( + .init(surface: surface, scope: NativeMCPScope(rawValue: scope)!), component: "" + ).evidence + } else { + evidence = try CapabilityRegistry.component( + .init(surface: surface, scope: InstallScope(rawValue: scope)!), + kind: kind, name: "", inPlugin: placement == "pluginMember" + ).evidence + } + if evidence != nil { status = "recorded" } + } catch let issue as NativeAdapterIssue { + status = issue.reason == .unsupported ? "unsupportedUnderEvidence" : "unverified" + reason = issue.detail + } catch let issue as NativeComponentIssue { + status = issue.reason == .unsupported ? "unsupportedUnderEvidence" : "unverified" + reason = issue.detail + } catch { + reason = "Registry evidence could not be projected." + } + return ClientCapabilityEvidence( + surface: surface, displayName: surface.displayName, kind: kind, + scope: scope, placement: placement, status: status, evidence: evidence, reason: reason + ) + } + } + } + } + } +} diff --git a/Tests/AgentsCoreTests/AgentClientObservationTests.swift b/Tests/AgentsCoreTests/AgentClientObservationTests.swift new file mode 100644 index 0000000..b5561e1 --- /dev/null +++ b/Tests/AgentsCoreTests/AgentClientObservationTests.swift @@ -0,0 +1,72 @@ +import AgentsCore +import CPlatform +import Foundation +import Testing + +struct AgentClientObservationTests { + @Test func metadataReadsOrdinarySymlinksAndKeepsVersionAndBuildSeparate() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let bundle = root.appendingPathComponent("Editor.app") + let metadata = bundle.appendingPathComponent("Contents/Info.plist") + try FileManager.default.createDirectory( + at: metadata.deletingLastPathComponent(), withIntermediateDirectories: true) + let source = root.appendingPathComponent("metadata.plist") + let bytes = try PropertyListSerialization.data( + fromPropertyList: [ + "CFBundleIdentifier": "fixture.editor", "CFBundleShortVersionString": "3.27-preview", + "CFBundleVersion": "42", + ], format: .xml, options: 0) + try bytes.write(to: source) + try FileManager.default.createSymbolicLink(at: metadata, withDestinationURL: source) + let (state, version) = AgentClientObservation.bundleVersion( + at: bundle, identifier: "fixture.editor") + #expect(state == .present) + #expect(version.version == "3.27-preview") + #expect(version.build == "42") + #expect(version.unknown == nil) + #expect(version.metadata == metadata) + #expect( + AgentClientObservation.bundleVersion(at: bundle, identifier: "another.editor").0 == .invalid) + } + + @Test func metadataFailuresAreBoundedAndDoNotReadNonRegularObjects() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let missing = root.appendingPathComponent("missing") + #expect(throws: ClientVersionUnknownError.self) { try AgentClientObservation.metadata(missing) } + let oversized = root.appendingPathComponent("oversized") + try Data(repeating: 1, count: 1_048_577).write(to: oversized) + do { + _ = try AgentClientObservation.metadata(oversized) + Issue.record("oversized metadata was admitted") + } catch let error as ClientVersionUnknownError { #expect(error.reason == .oversizedMetadata) } + let pipe = root.appendingPathComponent("pipe") + #expect(mkfifo(pipe.path, 0o600) == 0) + do { + _ = try AgentClientObservation.metadata(pipe) + Issue.record("FIFO metadata was admitted") + } catch let error as ClientVersionUnknownError { #expect(error.reason == .nonRegularMetadata) } + let bundle = root.appendingPathComponent("Broken.app") + let plist = bundle.appendingPathComponent("Contents/Info.plist") + try FileManager.default.createDirectory( + at: plist.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: plist, withDestinationURL: pipe) + let nonRegular = AgentClientObservation.bundleVersion(at: bundle, identifier: "fixture") + #expect(nonRegular.0 == .invalid) + #expect(nonRegular.1.unknown == .nonRegularMetadata) + try FileManager.default.removeItem(at: plist) + try Data("invalid plist".utf8).write(to: plist) + #expect( + AgentClientObservation.bundleVersion(at: bundle, identifier: "fixture").1.unknown + == .malformedMetadata) + try PropertyListSerialization.data( + fromPropertyList: ["CFBundleIdentifier": "fixture", "CFBundleVersion": "11"], + format: .binary, options: 0 + ).write(to: plist) + let observation = AgentClientObservation.bundleVersion(at: bundle, identifier: "fixture").1 + #expect(observation.unknown == .missingVersion) + #expect(observation.build == "11") + } +} diff --git a/Tests/AgentsUpdatesTests/AgentClientInspectionTests.swift b/Tests/AgentsUpdatesTests/AgentClientInspectionTests.swift new file mode 100644 index 0000000..74baed3 --- /dev/null +++ b/Tests/AgentsUpdatesTests/AgentClientInspectionTests.swift @@ -0,0 +1,225 @@ +import AgentsCore +import AgentsUpdates +import CPlatform +import Foundation +import Testing + +struct AgentClientInspectionTests { + private func fixture() throws -> URL { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + return root + } + + @Test func missingClientsKeepFiveRecordsAndStaticEvidence() throws { + let root = try fixture() + defer { try? FileManager.default.removeItem(at: root) } + let environment = RuntimeEnvironment( + projectDirectory: root.appendingPathComponent("project"), + homeDirectory: root.appendingPathComponent("absent-home"), environment: [:]) + let before = try FileManager.default.contentsOfDirectory(atPath: root.path) + let report = try AgentClientOperations.inspect(environment: environment) + #expect(report.clients.map(\.agent) == AgentID.allCases) + #expect(report.startedAt <= report.finishedAt) + #expect(!report.pathCoverage.pathWasSupplied) + #expect( + report.clients.flatMap(\.commands).allSatisfy { + $0.status == .unavailable && $0.version.rawVersion == nil + && $0.version.unknownReason == .unavailable + }) + #expect(report.clients.flatMap(\.configurationLocations).allSatisfy { $0.status == .notFound }) + let claude = try #require(report.clients.first { $0.agent == .claudeCode }) + #expect( + claude.schemaEvidence.contains { + $0.kind == .mcpServer && $0.scope == "local" && $0.revision == "installed:2.1.309" + }) + #expect(claude.commands.allSatisfy { $0.version.rawVersion == nil }) + #expect(claude.schemaEvidence.contains { $0.kind == .skills && $0.status == .unverified }) + let codex = try #require(report.clients.first { $0.agent == .codex }) + #expect( + codex.configurationLocations.contains { + $0.identity == "codex.mcp.user" + && $0.location?.path + == environment.homeDirectory.appendingPathComponent(".codex/config.toml").path + }) + #expect( + codex.schemaEvidence.contains { + $0.kind == .command && $0.status == .unsupportedUnderEvidence + }) + let cursor = try #require(report.clients.first { $0.agent == .cursor }) + #expect( + cursor.schemaEvidence.contains { + $0.surface.identifier == "cursorCloud" && $0.kind == .mcpServer && $0.status == .unverified + }) + #expect( + cursor.schemaEvidence.contains { + $0.surface.identifier == "cursorEditor" && $0.kind == .command && $0.scope == "user" + && $0.placement == .standalone && $0.status == .unverified + }) + #expect( + cursor.schemaEvidence.contains { + $0.surface.identifier == "cursorEditor" && $0.kind == .command && $0.scope == "user" + && $0.placement == .pluginMember && $0.status == .recorded + }) + #expect(try FileManager.default.contentsOfDirectory(atPath: root.path) == before) + } + + @Test func pathOrderSymlinksAndCursorRolesNeverExecuteClients() throws { + let root = try fixture() + defer { try? FileManager.default.removeItem(at: root) } + let first = root.appendingPathComponent("first") + let second = root.appendingPathComponent("second") + for directory in [first, second] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let sentinel = root.appendingPathComponent("executed") + let executable = second.appendingPathComponent("codex") + try Data("#!/bin/sh\ntouch '\(sentinel.path)'\n".utf8).write(to: executable) + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: executable.path) + try FileManager.default.createSymbolicLink( + at: first.appendingPathComponent("codex"), withDestinationURL: executable) + try Data("not executable".utf8).write(to: first.appendingPathComponent("cursor")) + let bundle = root.appendingPathComponent("Cursor.app") + let launcher = bundle.appendingPathComponent("Contents/Resources/app/bin/cursor") + try FileManager.default.createDirectory( + at: launcher.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.copyItem(at: executable, to: launcher) + try FileManager.default.createSymbolicLink( + at: second.appendingPathComponent("cursor"), withDestinationURL: launcher) + try PropertyListSerialization.data( + fromPropertyList: [ + "CFBundleIdentifier": "com.todesktop.230313mzl4w4u92", + "CFBundleShortVersionString": "3.27-test", "CFBundleVersion": "42", + ], format: .xml, options: 0 + ).write(to: bundle.appendingPathComponent("Contents/Info.plist")) + try FileManager.default.createDirectory( + at: first.appendingPathComponent("cursor-agent"), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: first.appendingPathComponent("gemini").path, + withDestinationPath: root.appendingPathComponent("missing").path) + let environment = RuntimeEnvironment( + projectDirectory: root, homeDirectory: root, + environment: ["PATH": ":relative:\(first.path):\(second.path)"]) + let bytes = try Data(contentsOf: executable) + let report = try AgentClientOperations.inspect(environment: environment) + #expect(report.pathCoverage.excludedEntries == ["", "relative"]) + #expect(report.pathCoverage.absoluteDirectories.map(\.path) == [first.path, second.path]) + let codex = try #require(report.clients.first { $0.agent == .codex }?.commands.first) + #expect(codex.location == first.appendingPathComponent("codex")) + #expect(codex.resolvedLocation == executable) + #expect(codex.version.unknownReason == .unrecognizedLayout) + let cursor = try #require(report.clients.first { $0.agent == .cursor }) + #expect( + cursor.commands.first { $0.role == .editorLauncher }?.location + == second.appendingPathComponent("cursor")) + #expect(cursor.commands.first { $0.role == .editorLauncher }?.version.rawVersion == "3.27-test") + #expect(cursor.commands.first { $0.role == .editorLauncher }?.version.build == "42") + #expect(cursor.commands.first { $0.name == "cursor-agent" }?.status == .notFound) + #expect(cursor.commands.first { $0.name == "cursor-agent" }?.version.rawVersion == nil) + #expect(!FileManager.default.fileExists(atPath: sentinel.path)) + #expect(try Data(contentsOf: executable) == bytes) + } + + @Test func pathSearchPermissionsAndExistingConfigurationRemainLocalObservations() throws { + let root = try fixture() + defer { try? FileManager.default.removeItem(at: root) } + let denied = root.appendingPathComponent("denied") + let bin = root.appendingPathComponent("bin") + let state = root.appendingPathComponent(".agents/transaction.json") + let configuration = root.appendingPathComponent(".codex/config.toml") + for directory in [ + denied, bin, state.deletingLastPathComponent(), configuration.deletingLastPathComponent(), + ] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let canary = Data("not configuration; never parse or recover".utf8) + try canary.write(to: state) + try canary.write(to: configuration) + let executable = bin.appendingPathComponent("codex") + try Data("never execute".utf8).write(to: executable) + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: executable.path) + try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: denied.path) + defer { + try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: denied.path) + } + let environment = RuntimeEnvironment( + projectDirectory: root, homeDirectory: root, + environment: ["PATH": "\(denied.path):\(bin.path)"]) + let report = try AgentClientOperations.inspect(environment: environment) + let command = try #require(report.clients.first { $0.agent == .codex }?.commands.first) + #expect(command.location == executable) + #expect( + command.lookupIssues.contains { $0.path.hasPrefix(denied.path) && $0.status == .inaccessible } + == (access(denied.path, X_OK) != 0) + ) + #expect( + report.clients.first { $0.agent == .codex }?.configurationLocations.contains { + $0.identity == "codex.mcp.user" && $0.status == .present + } == true) + #expect(try Data(contentsOf: state) == canary) + #expect(try Data(contentsOf: configuration) == canary) + #expect( + try FileManager.default.contentsOfDirectory(atPath: state.deletingLastPathComponent().path) + == ["transaction.json"]) + } + + @Test func ownerLocationsPreserveOverridesAlternativesAndSemanticRecords() throws { + let root = try fixture() + defer { try? FileManager.default.removeItem(at: root) } + var environment = RuntimeEnvironment( + projectDirectory: root.appendingPathComponent("project"), + homeDirectory: root.appendingPathComponent("home"), + environment: [ + "CODEX_HOME": root.appendingPathComponent("codex-override").path, + "CLAUDE_CONFIG_DIR": root.appendingPathComponent("claude-override").path, + "GEMINI_CLI_HOME": root.appendingPathComponent("gemini-native").path, + "OPENCODE_CONFIG_DIR": root.appendingPathComponent("opencode-native").path, + "XDG_CONFIG_HOME": root.appendingPathComponent("xdg").path, + ]) + let report = try AgentClientOperations.inspect(environment: environment) + let claude = try #require(report.clients.first { $0.agent == .claudeCode }) + let regions = claude.configurationLocations.filter { $0.identity.hasPrefix("claude.mcp.") } + #expect(regions.count == 2) + #expect(Set(regions.compactMap(\.location)).count == 1) + #expect(Set(regions.map(\.scope)) == ["local", "user"]) + let opencode = try #require(report.clients.first { $0.agent == .opencode }) + #expect( + opencode.configurationLocations.contains { + $0.location?.path == root.appendingPathComponent("opencode-native/opencode.jsonc").path + }) + #expect( + opencode.configurationLocations.contains { + $0.location?.path == root.appendingPathComponent("xdg/opencode/skills").path + }) + let codex = try #require(report.clients.first { $0.agent == .codex }) + #expect( + codex.configurationLocations.contains { + $0.identity == "codex.mcp.user" + && $0.location?.path == root.appendingPathComponent("codex-override/config.toml").path + }) + #expect( + codex.configurationLocations.contains { + $0.purpose == .instructions + && $0.location?.path == root.appendingPathComponent("codex-override/AGENTS.md").path + }) + let project = try AgentClientOperations.inspect(scope: .project, environment: environment) + #expect( + project.clients.first { $0.agent == .claudeCode }?.configurationLocations.contains { + $0.identity == "instructions.CLAUDE.local.md" + } == true) + environment.environment["CODEX_HOME"] = "relative" + let invalid = try AgentClientOperations.inspect(environment: environment) + #expect( + invalid.clients.first { $0.agent == .codex }?.configurationLocations.contains { + $0.identity == "codex.mcp.user" && $0.status == .invalid && $0.location == nil + && $0.diagnostic?.contains("CODEX_HOME") == true + } == true) + #expect(invalid.clients.first { $0.agent == .claudeCode }?.schemaEvidence.isEmpty == false) + #expect( + report.clients.first { $0.agent == .cursor }?.configurationLocations.contains { + $0.identity == "claudeAgent.user" + && $0.location?.path == root.appendingPathComponent("claude-override/agents").path + } == true) + #expect(try FileManager.default.contentsOfDirectory(atPath: root.path).isEmpty) + } +} From d4664f1b180c2c847ab30f1fb65d4f08f517c0f1 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:57:27 +0800 Subject: [PATCH 127/171] fix(core): retain Git error context through source expansion --- Sources/AgentsCore/GitError.swift | 6 +++- Sources/Components/Expansion.swift | 8 ++++- Tests/AgentsCoreTests/GitErrorTests.swift | 24 +++++++++++++++ Tests/ComponentsTests/SnapshotTests.swift | 37 +++++++++++++++++++++++ 4 files changed, 73 insertions(+), 2 deletions(-) diff --git a/Sources/AgentsCore/GitError.swift b/Sources/AgentsCore/GitError.swift index b703a52..683b0cd 100644 --- a/Sources/AgentsCore/GitError.swift +++ b/Sources/AgentsCore/GitError.swift @@ -53,6 +53,8 @@ public struct GitError: Error, CustomStringConvertible, Equatable, Sendable { public let command: [String] /// Git's exit status, for debugging only. Classify with `operation`. public let exitCode: Int32 + /// Declaration and reference locations attached without changing the sanitized Git diagnostic. + public var context: [SourceSpan] = [] init( operation: Operation, source: String, stderr: String, command: [String], exitCode: Int32, @@ -80,7 +82,9 @@ public struct GitError: Error, CustomStringConvertible, Equatable, Sendable { public var description: String { let summary = "Git could not \(operation.description) \(source)." - return stderr.isEmpty ? summary : summary + "\n" + stderr + let diagnostic = stderr.isEmpty ? summary : summary + "\n" + stderr + return diagnostic + + context.map { " at \($0.document.rawValue):\($0.line):\($0.column)" }.joined() } private static func isProgress(_ line: String) -> Bool { diff --git a/Sources/Components/Expansion.swift b/Sources/Components/Expansion.swift index 7e2e221..f0a9c46 100644 --- a/Sources/Components/Expansion.swift +++ b/Sources/Components/Expansion.swift @@ -257,7 +257,13 @@ final class Expansion { resources: resources, chain: chain, position: position, dependencies: dependencies + resources.map(\.snapshot)) } - } catch let error as LinkError { throw error } catch { + } catch let error as LinkError { throw error } catch var error as GitError { + for span in chain + (position.map { [$0.span] + $0.origins } ?? []) + where !error.context.contains(span) { + error.context.append(span) + } + throw error + } catch { throw LinkError.invalid( String(describing: error), chain + (position.map { [$0.span] + $0.origins } ?? [])) } diff --git a/Tests/AgentsCoreTests/GitErrorTests.swift b/Tests/AgentsCoreTests/GitErrorTests.swift index a7375a3..7fd5b81 100644 --- a/Tests/AgentsCoreTests/GitErrorTests.swift +++ b/Tests/AgentsCoreTests/GitErrorTests.swift @@ -36,6 +36,30 @@ struct GitErrorTests { } } + @Test func locationContextPreservesSanitizedGitFailure() { + let source = "file://localhost/producer" + let mirror = URL(fileURLWithPath: "/temporary/cache/source.git") + let command = ["git", "-C", mirror.path, "fetch"] + var error = GitError( + operation: .fetch, source: source, + stderr: "Receiving objects: 100% (1/1), done.\nfatal: cannot read '\(mirror.path)'\n", + command: command, exitCode: 128, replacingPaths: [mirror]) + #expect(error.context.isEmpty) + let original = error + let span = SourceSpan( + document: DocumentIdentity("consumer/agents.yaml"), start: 10, end: 40, line: 3, column: 5) + error.context.append(span) + #expect(error.operation == original.operation) + #expect(error.source == original.source) + #expect(error.stderr == original.stderr) + #expect(error.command == original.command) + #expect(error.exitCode == original.exitCode) + #expect(error.context == [span]) + #expect(error.description == original.description + " at consumer/agents.yaml:3:5") + #expect(!error.description.contains(mirror.path)) + #expect(error.stderr == "fatal: cannot read '\(source)'") + } + @Test func missingFileRepositoryIdentifiesCloneAndSource() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } diff --git a/Tests/ComponentsTests/SnapshotTests.swift b/Tests/ComponentsTests/SnapshotTests.swift index 5503114..e56883d 100644 --- a/Tests/ComponentsTests/SnapshotTests.swift +++ b/Tests/ComponentsTests/SnapshotTests.swift @@ -7,6 +7,43 @@ import Testing @Suite("Exact component snapshots", .serialized) struct SnapshotTests { + @Test func failedGitComponentKeepsTypedFailureAndDeclarationLocation() throws { + let fixture = try LinkFixture() + let missing = fixture.root.appendingPathComponent("missing.git") + let source = "file://localhost" + missing.path + let expression = """ + version: 1 + sources: {producer: {url: "\(source)"}} + groups: + selected: + components: + - {kind: skills, source: producer, select: all} + uses: [{group: selected}] + """ + let before = try FileHash.folderHash(fixture.root) + do { + _ = try fixture.link(expression) + Issue.record("Missing Git source was admitted") + } catch let error as GitError { + #expect(error.operation == .clone) + #expect(error.source == source) + #expect(error.command.contains("clone")) + #expect(error.exitCode != 0) + #expect(error.stderr.contains("fatal:")) + #expect( + error.context.map(\.document.rawValue) == ["consumer/agents.yaml", "consumer/agents.yaml"]) + #expect(error.context.map(\.line) == [7, 6]) + #expect(error.context.allSatisfy { $0.start < $0.end && $0.column > 0 }) + #expect(!error.description.contains(fixture.store.cacheDirectory.path)) + #expect(!error.description.contains(".staging-")) + #expect(!error.description.contains("agents-linking-")) + #expect(error.description.contains("consumer/agents.yaml:6:")) + } catch { + Issue.record("Git failure lost its type: \(type(of: error))") + } + #expect(try FileHash.folderHash(fixture.root) == before) + } + @Test func localDirectoryBeneathRepositoryKeepsItsOwnContent() throws { let fixture = try LinkFixture() try fixture.initialize(fixture.project) From c39dc5fabe34d7e5a2b054295c988c9612683524 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:04:45 +0800 Subject: [PATCH 128/171] feat(core): compose native authority and generated plugins --- Documentation/Architecture/Instructions.md | 8 +- Sources/AgentsCore/LedgerStateStore.swift | 18 + Sources/AgentsUpdates/UpdatePlan.swift | 10 +- Sources/Components/ArtifactAggregation.swift | 753 +++++++++++++++++- .../Components/DeploymentConstruction.swift | 85 +- Sources/Components/LedgerImpact.swift | 33 +- .../NativeAuthorityComposition.swift | 160 ++++ .../ConsumerLifecycleRegressionTests.swift | 4 - .../NativeAuthorityIntegrationTests.swift | 465 +++++++++++ 9 files changed, 1488 insertions(+), 48 deletions(-) create mode 100644 Sources/Components/NativeAuthorityComposition.swift create mode 100644 Tests/AgentsUpdatesTests/NativeAuthorityIntegrationTests.swift diff --git a/Documentation/Architecture/Instructions.md b/Documentation/Architecture/Instructions.md index 6b19585..5b44682 100644 --- a/Documentation/Architecture/Instructions.md +++ b/Documentation/Architecture/Instructions.md @@ -43,10 +43,10 @@ A project's own files live in `.agent/instructions/` and are referenced by bare name; `.section(name:source:)` in `agents.yaml`, or `alias:name` in operation arguments, 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`, 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. +path and the hash, and no revision. Resolution reads only the named file, `.agent/instructions/.md`, and so does +adding named files, so other files in the container affect only listing. Locked +restore publishes the frozen output and preserves the current own source file. +Update reads the current file; doctor reports changes since the recorded hash. `add(InstructionAddOptions, beforeApply:)` accepts a source alias or string, or `.` for own files, plus an optional alias, requirement, search path, ordered diff --git a/Sources/AgentsCore/LedgerStateStore.swift b/Sources/AgentsCore/LedgerStateStore.swift index d8b01b9..7422456 100644 --- a/Sources/AgentsCore/LedgerStateStore.swift +++ b/Sources/AgentsCore/LedgerStateStore.swift @@ -77,6 +77,24 @@ extension StateStore { } } + package func stageLedger( + producing ledger: @escaping () throws -> ResolvedLedger, limits: LedgerLimits, + transaction: FileTransaction, prepared: StatePrecondition + ) throws { + let original = try prepared.bytes(for: resolvedURL) + try transaction.replace( + resolvedURL, + with: .prepared { directory in + let bytes = + try ResolvedLedgerCodec.replacement(ledger(), existing: original, limits: limits) + ?? original + guard let bytes else { throw CoreError.invalidState("missing deferred ledger") } + let file = directory.appendingPathComponent("ledger") + try bytes.write(to: file) + return file + }, expecting: prepared.evidence(for: resolvedURL)) + } + private func ledgerBytes(limits: LedgerLimits) throws -> Data? { guard let directory = try openDirectoryIfPresent(), try directory.info(Self.resolvedFileName) != nil diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 40521ac..c4f9aa4 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -348,13 +348,17 @@ final class UpdatePlan { let declaration: String? let targets: [String] } + var semanticCandidate = self.next + semanticCandidate.nativeAuthorities = nil + var semanticBaseline = previous + semanticBaseline.nativeAuthorities = nil let fingerprint = try ResolvedLedgerCodec.digest( Fingerprint( operation: operation, scope: store.scope, kinds: request.kinds?.map(\.rawValue).sorted(), names: request.names.sorted(), selectedIdentities: request.selectedIdentities?.sorted(), replace: request.replace, changingAccess: request.changingAccess, - candidate: self.next, baseline: previous, + candidate: semanticCandidate, baseline: semanticBaseline, declaration: try (change?.bytes ?? baseline.bytes(for: store.declarationURL)).map { "sha256:" + FileHash.sha256Hex(data: $0) }, @@ -455,7 +459,9 @@ final class UpdatePlan { try store.stageDeclaration(declarationChange, in: transaction, prepared: baseline) // Empty scopes need no lock file; a declaration edit always accompanies first deployment. if try store.declarationBytes(prepared: baseline) != nil || declarationChange != nil { - try store.stageLedger(next, limits: .standard, transaction: transaction, prepared: baseline) + try store.stageLedger( + producing: { self.aggregation.ledger }, limits: .standard, transaction: transaction, + prepared: baseline) } try cache.prune(references: references, transaction: transaction) try transaction.commit() diff --git a/Sources/Components/ArtifactAggregation.swift b/Sources/Components/ArtifactAggregation.swift index c71fcd2..58dc796 100644 --- a/Sources/Components/ArtifactAggregation.swift +++ b/Sources/Components/ArtifactAggregation.swift @@ -45,6 +45,11 @@ package final class ArtifactAggregation: PreparedEvidence { private var skillContent: [String: (String, [String: Bool])] = [:] private var privateWrites: [(PreparedPrivateMaterialization, Set, (RuntimeBindingValues) throws -> Data)] = [] + private var nativePrivateWrites: + [( + PreparedPrivateMaterialization, Set, + (RuntimeBindingValues) throws -> PrivateMaterializationResult + )] = [] private var privateTrees: [(PreparedPrivateMaterialization, [PrivateTreeEntry])] = [] private var resourceEvidence: [TargetPrecondition] = [] private var physicalPaths: [NativeTargetIdentity: String] = [:] @@ -137,7 +142,9 @@ package final class ArtifactAggregation: PreparedEvidence { } let currentComponents = try componentOutputs(ledger, artifacts: artifacts, routing: previous) let oldNative = Set( - previous.lowerings.filter { $0.format.hasSuffix("-components@1") }.map(\.id)) + previous.lowerings.filter { + $0.format.hasSuffix("-components@1") || $0.format.hasSuffix("-generated-plugin@1") + }.map(\.id)) try LedgerReplay.withLockedResources( previous, store: store, roots: roots, limits: .standard, lowerings: oldNative ) { @@ -146,7 +153,22 @@ package final class ArtifactAggregation: PreparedEvidence { previous, artifacts: Dictionary(uniqueKeysWithValues: oldArtifacts.map { ($0.name, $0) }), routing: previous) - for path in Set(native.keys).union(currentComponents.keys).union(oldComponents.keys).sorted() + let generatedPaths = try prepareGeneratedPlugins( + previous: previous, artifacts: artifacts, + oldArtifacts: Dictionary(uniqueKeysWithValues: oldArtifacts.map { ($0.name, $0) }), + workspace: workspace, changingAccess: changingAccess) + guard + generatedPaths.isDisjoint( + with: Set(currentComponents.keys).union(oldComponents.keys).union(native.keys)) + else { + throw CoreError.invalidState("generated native container overlaps another native target") + } + for path in generatedPaths { + native[path] = [] + byPath.removeValue(forKey: path) + } + for path in Set(native.keys).union(currentComponents.keys).union(oldComponents.keys) + .subtracting(generatedPaths).sorted() { let next = currentComponents[path] ?? [] let old = oldComponents[path] ?? [] @@ -879,10 +901,13 @@ package final class ArtifactAggregation: PreparedEvidence { private struct NativeRegionOwner { let key: String - let region: NativeRegion - let bindings: Set + var region: NativeRegion + var deployments: [String] = [] + var append = false + var selected = true + var bindings: Set let symbolic: LedgerValue - let render: (RuntimeBindingValues?) throws -> NativeValue + var render: (RuntimeBindingValues?) throws -> NativeValue } private func prepareNative( @@ -914,9 +939,10 @@ package final class ArtifactAggregation: PreparedEvidence { components.first?.output.route.documentFormat ?? oldComponents.first?.output.route .documentFormat ?? contributions.first?.1.descriptor.documentFormat ?? old.first!.descriptor.documentFormat + let budget = nativeBudget() let document = try NativeDocument( bytes: capture.bytes ?? Data((format == .toml ? "" : "{}\n").utf8), - format: format, budget: nativeBudget()) + format: format, budget: budget) let selectedStore = store func names(_ bindings: [NativeComponentBindingPlacement]) -> Set { Set( @@ -937,7 +963,13 @@ package final class ArtifactAggregation: PreparedEvidence { if try !isSelected(c.component, in: selected) { guard let observed = try document.read(region)?.value else { return nil } return .init( - key: key, region: region, bindings: [], symbolic: c.value, render: { _ in observed }) + key: key, region: region, + deployments: [ + contributions.first(where: { $0.1.component == c.component })?.0.id + ?? previous.lowerings.first(where: { + $0.inputs.contains(c.component) && $0.format.hasSuffix("-mcp@1") + })!.id + ], bindings: [], symbolic: c.value, render: { _ in observed }) } let bindings = Set( c.bindings.filter { !$0.reference }.compactMap { @@ -947,7 +979,13 @@ package final class ArtifactAggregation: PreparedEvidence { } }) return .init( - key: key, region: region, bindings: bindings, symbolic: c.value, + key: key, region: region, + deployments: [ + contributions.first(where: { $0.1.component == c.component })?.0.id + ?? previous.lowerings.first(where: { + $0.inputs.contains(c.component) && $0.format.hasSuffix("-mcp@1") + })!.id + ], bindings: bindings, symbolic: c.value, render: { try Self.nativeValue(c, values: $0, ledger: selected, store: selectedStore) }) } func regional(_ entry: ComponentOutputEntry, selected: ResolvedLedger) throws @@ -958,7 +996,8 @@ package final class ArtifactAggregation: PreparedEvidence { bindings: Set = [], render: @escaping (RuntimeBindingValues?) throws -> NativeValue ) throws -> NativeRegionOwner { .init( - key: try ResolvedLedgerCodec.digest(keys), region: .init(keys: keys), bindings: bindings, + key: try ResolvedLedgerCodec.digest(keys), region: .init(keys: keys), + deployments: [entry.id], bindings: bindings, symbolic: symbolic, render: render) } switch entry.output.content { @@ -992,10 +1031,40 @@ package final class ArtifactAggregation: PreparedEvidence { symbolic: selected.components[entry.contribution.component]!.payload, render: { _ in value }) } - case .hook, .orderedPermissions: - throw CoreError.invalidState( - "native occurrence publication requires durable occurrence ownership and append support" - ) + case .hook(let hook): + let identity = try LedgerImpact.identity( + selected.components[entry.contribution.component]!, ledger: selected, + roots: store.ledgerRoots) + return [ + .init( + key: "hook:" + identity + ":" + String(entry.index), region: .init(keys: hook.keys), + deployments: [entry.id], append: true, + selected: try isSelected(entry.contribution.component, in: selected), + bindings: names(hook.value.bindings), + symbolic: selected.components[entry.contribution.component]!.payload, + render: { + try Self.componentValue( + hook.value, values: $0, selected: selected, store: selectedStore) + }) + ] + case .orderedPermissions(let rules): + let identity = try LedgerImpact.identity( + selected.components[entry.contribution.component]!, ledger: selected, + roots: store.ledgerRoots) + let selectedOwner = try isSelected(entry.contribution.component, in: selected) + return rules.enumerated().map { index, rule in + .init( + key: "permission:" + identity + ":" + String(index), + region: .init(keys: ["permissions"]), deployments: [entry.id], append: true, + selected: selectedOwner, + bindings: [], symbolic: selected.components[entry.contribution.component]!.payload, + render: { _ in + .object([ + "action": .string(rule.tool), "resource": .string(rule.resource), + "effect": .string(rule.effect.rawValue), + ]) + }) + } default: throw CoreError.invalidState("whole native content cannot be prepared as a shared region") } @@ -1016,12 +1085,15 @@ package final class ArtifactAggregation: PreparedEvidence { try existing.render(nil) == item.render(nil) else { throw CoreError.invalidState("conflicting native physical region owners") } } - result[item.key] = item + var combined = item + combined.deployments = Array(Set((result[item.key]?.deployments ?? []) + item.deployments)) + .sorted() + result[item.key] = combined } return result } - let desired = try keyed(desiredItems) - let prior = try keyed(oldItems) + var desired = try keyed(desiredItems) + var prior = try keyed(oldItems) let keys = Set(desired.keys).union(prior.keys).sorted() func componentBindings(_ entries: [ComponentOutputEntry]) -> Bool { entries.contains { entry in @@ -1045,33 +1117,208 @@ package final class ArtifactAggregation: PreparedEvidence { ? store.preparePrivateMaterialization( target, changingAccess: changingAccess, requiringReceiptForExistingTarget: recordedOldBindings) : nil + let receiptArrays = try store.materializationReceipt(for: target)?.nativeArrays ?? [] + let authority = previous.nativeAuthorities?.first { + (try? $0.target.resolve(roots: store.ledgerRoots).path) == path + } + var retained: [NativeObservation] = [] + var retainedOwners: [[String]] = [] var expected: [String: NativeExpectedRegion] = [:] + var staleKeys = Set() + var staleRegions: [LedgerNativeOwnedRegion] = [] for key in keys { - let region = (desired[key] ?? prior[key])!.region + if let old = prior[key], old.append, capture.bytes != nil { + let records = + authority?.regions.filter { !Set($0.deployments).isDisjoint(with: old.deployments) } ?? [] + let index = + oldItems.filter { $0.deployments == old.deployments && $0.append }.firstIndex { + $0.key == key + } ?? 0 + guard records.indices.contains(index) else { + throw CoreError.invalidState("missing durable native occurrence authority") + } + let region: NativeRegion + do { + region = try NativeAuthorityComposition.region( + records[index].path, document: document, arrays: receiptArrays) + } catch { + guard let next = desired[key], !next.selected else { throw error } + staleKeys.insert(key) + staleRegions.append(.init(deployments: next.deployments, path: records[index].path)) + desired[key]!.bindings = [] + continue + } + prior[key]!.region = region + if desired[key] != nil { desired[key]!.region = region } + } + let region = (prior[key] ?? desired[key])!.region + if prior[key] == nil, desired[key]?.append == true { + expected[key] = try document.read(region).map(NativeExpectedRegion.owned) ?? .absent + continue + } if let observation = try document.read(region) { guard let old = prior[key] else { throw NativeDocumentError.ownershipMismatch(region) } if old.bindings.isEmpty, try observation.value != old.render(nil) { throw NativeDocumentError.ownershipMismatch(region) } expected[key] = .owned(observation) + if var next = desired[key] { + if !next.selected { + next.bindings = [] + next.render = { _ in observation.value! } + desired[key] = next + } + retained.append(observation) + retainedOwners.append(next.deployments) + } } else { expected[key] = .absent } } + var created: [NativeRegion] = [] + for container in authority?.createdContainers ?? [] where capture.bytes != nil { + let region = try NativeAuthorityComposition.region( + container.path, document: document, arrays: receiptArrays) + if try document.read(region) != nil { created.append(region) } + } + var editKeys: [String] = [] func edits(_ values: RuntimeBindingValues?) throws -> [NativeRegionEdit] { - try keys.compactMap { key in + var result: [NativeRegionEdit] = [] + editKeys = [] + for key in keys where !staleKeys.contains(key) { if let next = desired[key] { - return .put(region: next.region, expected: expected[key]!, value: try next.render(values)) + if !next.selected { continue } + editKeys.append(key) + if next.append, prior[key] == nil || capture.bytes == nil { + let array = try document.read(next.region) + result.append( + .append( + region: next.region, expected: array.map(NativeExpectedRegion.owned) ?? .absent, + value: try next.render(values))) + } else { + result.append( + .put(region: next.region, expected: expected[key]!, value: try next.render(values))) + } + } else if case .owned = expected[key] { + editKeys.append(key) + result.append(.remove(region: prior[key]!.region, expected: expected[key]!)) } - if case .absent = expected[key] { return nil } - return .remove(region: prior[key]!.region, expected: expected[key]!) } + if (components + oldComponents).contains(where: { + if case .hook(let hook) = $0.output.content { return hook.layout == .cursorVersion1 } + return false + }), + try document.read(.init(keys: ["version"])) == nil + { + result.append(.put(region: .init(keys: ["version"]), expected: .absent, value: .integer(1))) + } + let selectedOldDeployments = Set(prior.values.filter(\.selected).flatMap(\.deployments)) + for region in created + where authority?.createdContainers.contains(where: { record in + !Set(record.deployments).isDisjoint(with: selectedOldDeployments) + && (try? NativeAuthorityComposition.region( + record.path, document: document, arrays: receiptArrays)) == region + }) == true { + result.append(.pruneCreatedContainer(region: region, observed: try document.read(region)!)) + } + return result } - let preview = try document.prepare(edits(nil)) + let tracking = + try capture.bytes == nil + ? [] + : receiptArrays.map { + try NativeAuthorityComposition.region($0.path, document: document) + } + let preview = try document.prepare(edits(nil), retaining: retained, trackingArrays: tracking) + let confirmedKeys = editKeys let changed = preview.bytes != (capture.bytes ?? Data((format == .toml ? "" : "{}\n").utf8)) - let bindings = desiredItems.reduce(into: Set()) { $0.formUnion($1.bindings) } + let bindings = desired.values.reduce(into: Set()) { $0.formUnion($1.bindings) } + let selectedTarget = location(target) + let authorityRoute: NativeTargetRoute + if let entry = (components + oldComponents).first { + authorityRoute = try DeploymentConstruction.route( + entry.output, request: entry.contribution.request) + } else { + authorityRoute = try DeploymentConstruction.route((contributions.map(\.1) + old).first!) + } + let targetRoute = try DeploymentConstruction.physicalRoute( + authorityRoute, ledger: previous, store: store + ).rawValue + func finish(_ result: PreparedNativeChange) throws -> NativeAuthorityComposition.Result { + let final = try NativeDocument(bytes: result.bytes, format: format, budget: budget) + var owners: [(NativeObservation, [String])] = [] + for remap in result.survivingRegions { + if let observation = remap.observation { + owners.append((observation, retainedOwners[remap.index])) + } + } + for append in result.appendedOccurrences { + owners.append((append.observation, desired[confirmedKeys[append.editIndex]]!.deployments)) + } + // Keyed regions replaced by put retain their stable address even when their old value changes. + for key in keys where desired[key]?.append == false { + if let next = desired[key], let observation = try final.read(next.region), + !owners.contains(where: { $0.0.region == observation.region }) + { + owners.append((observation, next.deployments)) + } + } + let finalEvidence = try NativeAuthorityComposition.finish( + result, document: final, owners: owners, + containers: created + result.createdContainers, + previousArrays: capture.bytes == nil ? [] : receiptArrays, + sensitive: sensitive, format: format) + var containers = finalEvidence.containers + for original in authority?.createdContainers ?? [] { + guard + staleRegions.contains(where: { region in + region.path.count > original.path.count + && Array(region.path.prefix(original.path.count)) == original.path + }), !containers.contains(where: { $0.path == original.path }) + else { continue } + let owners = Set( + staleRegions.filter { + $0.path.count > original.path.count + && Array($0.path.prefix(original.path.count)) == original.path + }.flatMap(\.deployments)) + containers.append( + .init(deployments: owners.sorted(), path: original.path, kind: original.kind)) + } + if capture.bytes == nil { + return .init( + regions: finalEvidence.regions + staleRegions, containers: containers, + transitions: receiptArrays.map { .init(previous: $0, current: nil) } + + finalEvidence.transitions) + } + return .init( + regions: finalEvidence.regions + staleRegions, containers: containers, + transitions: finalEvidence.transitions) + } + let previewAuthority = try finish(preview) + recordNativeAuthority( + previewAuthority, target: selectedTarget, route: targetRoute, path: path, format: format) if let privatePlan { - privateWrites.append((privatePlan, bindings, { try document.prepare(edits($0)).bytes })) + nativePrivateWrites.append( + ( + privatePlan, bindings, + { [unowned self] values in + let actual = try document.prepare( + edits(values), retaining: retained, trackingArrays: tracking) + guard + actual.appendedOccurrences.map(\.editIndex) + == preview.appendedOccurrences.map(\.editIndex), + actual.createdContainers == preview.createdContainers, + actual.survivingRegions.map({ $0.observation != nil }) + == preview.survivingRegions.map({ $0.observation != nil }) + else { + throw CoreError.invalidState("private rendering changed confirmed native structure") + } + let evidence = try finish(actual) + self.recordNativeAuthority( + evidence, target: selectedTarget, route: targetRoute, path: path, format: format) + return .init(bytes: actual.bytes, nativeArrayTransitions: evidence.transitions) + } + )) } else if changed { writes[path] = .data(preview.bytes) } @@ -1112,10 +1359,10 @@ package final class ArtifactAggregation: PreparedEvidence { } for entry in components { let ownBindings: [String] - if case .member(_, let value) = entry.output.content { - ownBindings = Array(names(value.bindings)).sorted() - } else { - ownBindings = [] + switch entry.output.content { + case .member(_, let value): ownBindings = Array(names(value.bindings)).sorted() + case .hook(let hook): ownBindings = Array(names(hook.value.bindings)).sorted() + default: ownBindings = [] } try record( entry, previous: previous, changed: changed || sensitive, readers: effectiveReaders, @@ -1148,6 +1395,360 @@ package final class ArtifactAggregation: PreparedEvidence { } } + private func recordNativeAuthority( + _ result: NativeAuthorityComposition.Result, target: LedgerLocation, + route: String, path: String, format: NativeDocumentFormat + ) { + var records = ledger.nativeAuthorities ?? [] + records.removeAll { (try? $0.target.resolve(roots: store.ledgerRoots).path) == path } + if !result.regions.isEmpty { + records.append( + .init( + target: target, targetRoute: route, + documentFormat: NativeAuthorityComposition.dialect(format), regions: result.regions, + createdContainers: result.containers)) + } + ledger.nativeAuthorities = records.isEmpty ? nil : records + } + + private func prepareGeneratedPlugins( + previous: ResolvedLedger, artifacts: [String: ReplayedArtifact], + oldArtifacts: [String: ReplayedArtifact], + workspace: URL, changingAccess: Bool + ) throws -> Set { + typealias Entry = (LockedLowering, NativeGeneratedPluginContribution, MaterializationTarget) + func entries(_ selected: ResolvedLedger, _ outputs: [String: ReplayedArtifact]) throws + -> [String: Entry] + { + var result: [String: Entry] = [:] + for lowering in selected.lowerings where lowering.format.hasSuffix("-generated-plugin@1") { + let contribution = try NativeGeneratedPluginContribution.decode( + lowering, ledger: selected, + artifacts: lowering.artifacts.map { + guard let output = outputs[$0.name] else { + throw CoreError.invalidState("missing generated native artifact") + } + return output + }, limits: .standard) + let route = try DeploymentConstruction.generatedRoute(lowering, ledger: selected) + let target = try store.nativeTarget(for: route) + let path = try physicalPath(route) + guard result[path] == nil else { + throw CoreError.invalidState("overlapping generated native containers") + } + result[path] = (lowering, contribution, target) + } + return result + } + let next = try entries(ledger, artifacts) + let old = try entries(previous, oldArtifacts) + func bindings(_ contribution: NativeGeneratedPluginContribution) -> Set { + var names = Set() + func collect(_ binding: RuntimeBinding) { + switch binding { + case .secret(let name), .environment(let name): names.insert(name) + case .literal: break + } + } + for member in contribution.members { + switch member.content { + case .mcp(let value): + for placement in value.bindings where !placement.reference { collect(placement.binding) } + case .component(let value): + for output in value.outputs { + switch output.content { + case .hook(let hook): + for placement in hook.value.bindings { collect(placement.binding) } + case .generatedLSPPlugin(_, _, let manifest): + for placement in manifest.bindings { collect(placement.binding) } + default: break + } + } + case .skill: break + } + } + return names + } + let selectedEnvironment = store.environment + let generatedBudget = nativeBudget() + func bundle( + _ contribution: NativeGeneratedPluginContribution, target: MaterializationTarget, + values: RuntimeBindingValues, symbolic: Bool = false + ) throws -> [String: Data] { + var environment = selectedEnvironment + if symbolic { + for name in bindings(contribution) { + environment.environment[name] = "agents-symbolic-binding" + } + } + return try Self.generatedPluginFiles( + contribution, target: target, values: values, environment: environment, + budget: generatedBudget) + } + for path in Set(next.keys).union(old.keys).sorted() { + let entry = next[path] ?? old[path]! + let target = entry.2 + let capture = try TargetPrecondition(target.url).capturingPublicationAccess() + targets[path] = capture + fingerprints.append(try capture.displayEvidence(includeContent: false)) + let receipt = try store.materializationReceipt(for: target) + let selected = try isSelected(entry.1.component, in: next[path] == nil ? previous : ledger) + let names = bindings(entry.1) + let priorNames = old[path].map { bindings($0.1) } ?? [] + let sensitive = !names.isEmpty || !priorNames.isEmpty || receipt != nil + let privatePlan = + try sensitive + ? store.preparePrivateMaterialization( + target, changingAccess: changingAccess, + requiringReceiptForExistingTarget: !priorNames.isEmpty) : nil + let exists = FileManager.default.fileExists(atPath: path) + if exists && selected { + guard let prior = old[path], + previous.deployments.contains(where: { $0.id == prior.0.id && $0.ownership == .generated } + ) + else { + throw CoreError.invalidState("generated native container contains unmanaged content") + } + if receipt == nil { + let expected = try bundle(prior.1, target: target, values: .init([:])) + guard try Self.generatedTreeMatches(prior.1, target: target, files: expected) else { + throw CoreError.invalidState("owned generated native container drifted") + } + } + } + if let current = next[path] { + let deployment = LedgerDeployment( + id: current.0.id, target: location(target), route: current.0.format, + owners: [current.1.component], recipients: current.1.recipients, ownership: .generated, + expectedHash: current.0.artifacts[0].hash, + created: previous.deployments.first { $0.id == current.0.id }?.created ?? !exists) + ledger.deployments.removeAll { $0.id == deployment.id } + ledger.deployments.append(deployment) + if let index = ledger.lowerings.firstIndex(where: { $0.id == current.0.id }) { + ledger.lowerings[index].deployments = [deployment.id] + } + if selected { + let symbolicValues = RuntimeBindingValues( + Dictionary( + uniqueKeysWithValues: names.map { ($0, Data("agents-symbolic-binding".utf8)) })) + let symbolic = try bundle( + current.1, target: target, values: symbolicValues, symbolic: true) + let tree = workspace.appendingPathComponent( + "generated-" + FileHash.sha256Hex(data: Data(path.utf8))) + try FileSystem.createDirectory(at: tree) + for placement in current.1.resourcePlacements { + guard let source = resources[placement.resource], + let resource = ledger.resources[placement.resource] + else { throw CoreError.invalidState("missing generated native resource") } + var sourceRoot = source + if resource.path != "." { + for _ in resource.path.split(separator: "/") { sourceRoot.deleteLastPathComponent() } + } + let captured = try LedgerResources.capture( + source, embed: true, limits: .standard, sourceRoot: sourceRoot) + guard captured.hash == resource.hash else { + throw CoreError.invalidState("generated native resource changed") + } + var embedded = resource + embedded.kind = .embedded + embedded.entries = captured.entries + embedded.support = captured.support + let base = Self.generatedResourceBase(placement, resource: resource) + let destination = try PathSafety.resolvedChild(base: tree, subpath: base) + try LedgerResources.materialize(embedded, objects: captured.objects, at: destination) + if !resource.support.isEmpty && placement.path.hasPrefix("skills/") { + let alias = try PathSafety.resolvedChild(base: tree, subpath: placement.path) + try FileSystem.createDirectory(at: alias.deletingLastPathComponent()) + try FileManager.default.createSymbolicLink( + atPath: alias.path, withDestinationPath: "../" + base + "/" + resource.path) + } + } + for (file, bytes) in symbolic { + let destination = try PathSafety.resolvedChild(base: tree, subpath: file) + guard !FileManager.default.fileExists(atPath: destination.path) else { + throw CoreError.invalidState("generated native bundle collision") + } + try FileSystem.createDirectory(at: destination.deletingLastPathComponent()) + try bytes.write(to: destination) + } + if let privatePlan { + let captured = try LedgerResources.capture(tree, embed: false, limits: .standard) + let members = try captured.entries.filter { $0.path != "." }.map { + item -> PrivateTreeEntry in + if symbolic[item.path] != nil { + return .init( + item.path, + content: .boundFile(bindings: names) { values in + let actual = try bundle(current.1, target: target, values: values) + guard Set(actual.keys) == Set(symbolic.keys), let bytes = actual[item.path] + else { + throw CoreError.invalidState( + "private rendering changed generated native structure") + } + return bytes + }) + } + switch item.kind { + case .directory: return .init(item.path, content: .directory) + case .file: + return .init( + item.path, + content: .file( + try Data(contentsOf: tree.appendingPathComponent(item.path)), + executable: item.executable)) + case .symlink: return .init(item.path, content: .symlink(item.link!)) + } + } + privateTrees.append((privatePlan, members)) + } else if try !exists || FileHash.folderHash(tree) != FileHash.folderHash(target.url) { + writes[path] = .copy(tree) + } + } + changes.append( + .init( + deployment: deployment, url: target.url, before: nil, after: nil, + changed: selected && (writes[path] != nil || privatePlan != nil), native: true, + accessChange: privatePlan?.accessChange, effectiveReaders: current.1.knownReaders, + privateMaterialization: sensitive, requiredBindings: names.sorted(), + symbolicBefore: old[path].flatMap { previous.components[$0.1.component]?.payload }, + symbolicAfter: ledger.components[current.1.component]?.payload)) + } else if selected, + let deployment = previous.deployments.first(where: { $0.id == entry.0.id }) + { + if exists { deletes.insert(path) } + changes.append( + .init( + deployment: deployment, url: target.url, before: nil, after: nil, changed: exists, + native: true, + privateMaterialization: sensitive, + symbolicBefore: previous.components[entry.1.component]?.payload)) + } + } + return Set(next.keys).union(old.keys) + } + + private static func generatedTreeMatches( + _ contribution: NativeGeneratedPluginContribution, + target: MaterializationTarget, files: [String: Data] + ) throws -> Bool { + var entries: [String: LedgerEntry] = [ + ".": .init(path: ".", kind: .directory, executable: false) + ] + func add(_ entry: LedgerEntry, at path: String) throws { + var copy = entry + copy.path = path + if let existing = entries[path], existing != copy { + throw CoreError.invalidState("conflicting generated native resource placement") + } + entries[path] = copy + let parents = path.split(separator: "/").dropLast() + if !parents.isEmpty { + for count in 1...parents.count { + let parent = parents.prefix(count).joined(separator: "/") + let directory = LedgerEntry(path: parent, kind: .directory, executable: false) + if let existing = entries[parent], existing.kind != .directory { + throw CoreError.invalidState("generated native resource ancestor collision") + } + entries[parent] = directory + } + } + } + for (path, bytes) in files { + try add( + .init( + path: path, kind: .file, object: "sha256:" + FileHash.sha256Hex(data: bytes), + executable: false, byteCount: bytes.count), at: path) + } + for placement in contribution.resourcePlacements { + let resource = contribution.resources[placement.resource]! + let base = generatedResourceBase(placement, resource: resource) + let primary = generatedResourcePath(placement, resource: resource) + for entry in resource.entries { + try add(entry, at: entry.path == "." ? primary : primary + "/" + entry.path) + } + for entry in resource.support { + try add(entry, at: entry.path == "." ? base : base + "/" + entry.path) + } + if !resource.support.isEmpty && placement.path.hasPrefix("skills/") { + try add( + .init( + path: placement.path, kind: .symlink, link: "../" + base + "/" + resource.path, + executable: false), at: placement.path) + } + } + let actual = try LedgerResources.capture(target.url, embed: true, limits: .standard) + guard actual.entries.count == entries.count else { return false } + guard + actual.entries.allSatisfy({ entry in + guard let expected = entries[entry.path] else { return false } + return entry.kind == expected.kind && entry.executable == expected.executable + && (expected.object == nil || entry.object == expected.object) + && entry.link == expected.link + }) + else { return false } + for placement in contribution.resourcePlacements { + let resource = contribution.resources[placement.resource]! + let observed = try LedgerResources.capture( + target.url.appendingPathComponent(generatedResourcePath(placement, resource: resource)), + embed: false, limits: .standard) + guard observed.hash == resource.hash else { return false } + } + return true + } + + private static func generatedResourceBase( + _ placement: NativeGeneratedPluginContribution.ResourcePlacement, + resource: LedgerResource + ) -> String { + resource.support.isEmpty + ? placement.path + : "resources/" + placement.resource.replacingOccurrences(of: "sha256:", with: "") + } + + private static func generatedResourcePath( + _ placement: NativeGeneratedPluginContribution.ResourcePlacement, + resource: LedgerResource + ) -> String { + resource.support.isEmpty + ? placement.path : generatedResourceBase(placement, resource: resource) + "/" + resource.path + } + + private static func generatedPluginFiles( + _ contribution: NativeGeneratedPluginContribution, + target: MaterializationTarget, values: RuntimeBindingValues, environment: RuntimeEnvironment, + budget: NativeDocumentBudget + ) throws -> [String: Data] { + let paths = try Dictionary( + contribution.resourcePlacements.map { + ( + $0.resource, + try PathSafety.resolvedChild( + base: target.url, + subpath: Self.generatedResourcePath($0, resource: contribution.resources[$0.resource]!) + ).path + ) + }, uniquingKeysWith: { a, _ in a }) + let rendered = try contribution.stagedBundle( + bindings: values, environment: environment, + resourcePaths: paths, budget: budget, cursorCommandShell: .posix) + var result = rendered.files + for (path, value) in rendered.documents { + guard result[path] == nil else { + throw CoreError.invalidState("generated native file collision") + } + guard case .object(let fields) = value else { + throw CoreError.invalidState("generated native document must be an object") + } + let document = try NativeDocument(bytes: Data("{}".utf8), format: .json, budget: budget) + result[path] = try document.prepare( + fields.keys.sorted().map { key in + .put(region: .init(keys: [key]), expected: .absent, value: fields[key]!) + } + ).bytes + } + return result + } + private func nativeBudget() -> NativeDocumentBudget { NativeDocumentBudget( limits: .init( @@ -1280,6 +1881,10 @@ package final class ArtifactAggregation: PreparedEvidence { for (prepared, entries) in privateTrees { try transaction.replacePrivateTree(prepared, entries: entries, provider: provider) } + for (prepared, bindings, produce) in nativePrivateWrites { + try transaction.replacePrivate( + prepared, bindings: bindings, provider: provider, produce: produce) + } for (prepared, bindings, render) in privateWrites { try transaction.replacePrivate( prepared, bindings: bindings, provider: provider, render: render) @@ -1297,7 +1902,10 @@ extension ArtifactAggregation { package static func nativeExposure( _ deployment: LedgerDeployment, ledger: ResolvedLedger, store: StateStore ) throws -> (readers: [AgentID]?, sensitive: Bool) { - guard deployment.ownership == .ownedValues || deployment.route.hasSuffix("-components@1") else { + guard + deployment.ownership == .ownedValues || deployment.route.hasSuffix("-components@1") + || deployment.route.hasSuffix("-generated-plugin@1") + else { return (nil, false) } let path = try deployment.target.resolve(roots: store.ledgerRoots).path @@ -1348,6 +1956,29 @@ extension ArtifactAggregation { } } } + for lowering in ledger.lowerings where lowering.format.hasSuffix("-generated-plugin@1") { + let route = try DeploymentConstruction.generatedRoute(lowering, ledger: ledger) + let target = try store.nativeTarget(for: route) + if try matches(route, target) { + readers.formUnion(route.knownReaders) + if let surface = lowering.layout.object?["surface"]?.text.flatMap( + NativeClientSurface.init(rawValue:)), + let scope = lowering.layout.object?["scope"]?.text.flatMap(InstallScope.init(rawValue:)) + { + for id in lowering.inputs { + if let component = ledger.components[id], + let kind = DeclaredComponentKind(rawValue: component.kind) + { + readers.formUnion( + CapabilityRegistry.componentReaders( + .init(surface: surface, scope: scope), kind: kind)) + sensitive = sensitive || hasBinding(component.payload) + } + } + } + sensitive = try sensitive || store.materializationReceipt(for: target) != nil + } + } return (readers.isEmpty ? nil : readers.sorted { $0.rawValue < $1.rawValue }, sensitive) } @@ -1427,6 +2058,31 @@ extension ArtifactAggregation { return try observed.value == nativeValue(c, values: nil, ledger: ledger, store: store) ? ("current", nil) : ("drifted", "managed native region changed") } + if deployment.route.hasSuffix("-generated-plugin@1"), + let lowering = ledger.lowerings.first(where: { $0.deployments.contains(deployment.id) }) + { + return try LedgerReplay.withLockedResources( + ledger, store: store, roots: store.ledgerRoots, limits: .standard, + lowerings: [lowering.id] + ) { artifacts, _, _ in + let contribution = try NativeGeneratedPluginContribution.decode( + lowering, ledger: ledger, artifacts: artifacts, limits: .standard) + let target = try store.nativeTarget( + for: DeploymentConstruction.generatedRoute(lowering, ledger: ledger)) + if try store.materializationReceipt(for: target) != nil { return ("current", nil) } + let budget = NativeDocumentBudget( + limits: .init( + storage: LedgerLimits.standard.resourceBytes, + work: LedgerLimits.standard.encodedBytes, + nodes: LedgerLimits.standard.nodes, depth: LedgerLimits.standard.depth, + uninterruptedBytes: LedgerLimits.standard.keyBytes)) + let files = try generatedPluginFiles( + contribution, target: target, values: .init([:]), environment: store.environment, + budget: budget) + return try generatedTreeMatches(contribution, target: target, files: files) + ? ("current", nil) : ("drifted", "managed generated native container changed") + } + } if deployment.route.hasSuffix("-components@1"), let lowering = ledger.lowerings.first(where: { $0.deployments.contains(deployment.id) }) { @@ -1458,7 +2114,7 @@ extension ArtifactAggregation { let privateGeneration = try store.materializationReceipt(for: target) != nil if privateGeneration { switch output.content { - case .file, .nativePlugin, .generatedLSPPlugin: break + case .file, .nativePlugin, .generatedLSPPlugin, .hook, .orderedPermissions: break default: return ("current", nil) } } @@ -1540,9 +2196,40 @@ extension ArtifactAggregation { manifest, observed: document.read(.init(keys: []))?.value, selected: ledger, privateGeneration: privateGeneration, store: store) case .hook, .orderedPermissions: - return ( - "unverified", "native ownership observation requires the integrated regional evidence" - ) + let document = try NativeDocument( + bytes: Data(contentsOf: url), format: output.route.documentFormat!, budget: budget) + guard + let authority = ledger.nativeAuthorities?.first(where: { + (try? $0.target.resolve(roots: store.ledgerRoots)) == url + }) + else { + return ("unverified", "managed native occurrence authority is missing") + } + let records = authority.regions.filter { $0.deployments.contains(deployment.id) } + let expected: [NativeValue] + switch output.content { + case .hook(let hook): + expected = [ + try componentValue(hook.value, values: nil, selected: ledger, store: store) + ] + case .orderedPermissions(let rules): + expected = rules.map { + .object([ + "action": .string($0.tool), "resource": .string($0.resource), + "effect": .string($0.effect.rawValue), + ]) + } + default: expected = [] + } + matches = + try records.count == expected.count + && zip(records, expected).allSatisfy { record, value in + let region = try NativeAuthorityComposition.region( + record.path, document: document, + arrays: store.materializationReceipt(for: target)?.nativeArrays ?? []) + return try privateGeneration + ? document.read(region) != nil : document.read(region)?.value == value + } } return matches ? ("current", nil) : ("drifted", "managed native contribution changed") } diff --git a/Sources/Components/DeploymentConstruction.swift b/Sources/Components/DeploymentConstruction.swift index e444032..557f3e9 100644 --- a/Sources/Components/DeploymentConstruction.swift +++ b/Sources/Components/DeploymentConstruction.swift @@ -72,6 +72,53 @@ package enum DeploymentConstruction { default: throw CoreError.invalidState("native surface has no integrated closed route") } } + for lowering in ledger.lowerings where lowering.format.hasSuffix("-generated-plugin@1") { + result.insert(try generatedRoute(lowering, ledger: ledger)) + } + return result + } + + package static func generatedRoute(_ lowering: LockedLowering, ledger: ResolvedLedger) throws + -> NativeTargetRoute + { + guard let surface = lowering.layout.object?["surface"]?.text, + let scopeText = lowering.layout.object?["scope"]?.text, + let scope = InstallScope(rawValue: scopeText), + let id = lowering.inputs.first, let component = ledger.components[id] + else { + throw CoreError.invalidState("invalid generated native route") + } + switch NativeClientSurface(rawValue: surface) { + case .claudeCode: return try .named(.claudeSkillPlugin, scope: scope, name: component.name) + case .cursorEditor: return try .named(.cursorLocalPlugin, scope: scope, name: component.name) + case .geminiCLI: return try .named(.geminiExtension, scope: scope, name: component.name) + default: throw CoreError.invalidState("unregistered generated native route") + } + } + + private static func surface(_ agent: AgentID) -> NativeClientSurface { + switch agent { + case .claudeCode: .claudeCode + case .codex: .codexCLI + case .cursor: .cursorEditor + case .geminiCLI: .geminiCLI + case .opencode: .openCodeCLI + } + } + + private static func direct(_ component: LinkedComponent, ledger: ResolvedLedger, agent: AgentID) + -> LinkedComponent + { + let parents = Set( + ledger.lowerings.filter { + $0.format.hasSuffix("-generated-plugin@1") + && $0.layout.object?["surface"]?.text == surface(agent).rawValue + }.flatMap { $0.layout.object?["occurrences"]?.array?.compactMap(\.integer) ?? [] }) + let consumed = Set( + ledger.occurrences.filter { $0.pluginMember.map { parents.contains($0.parent) } ?? false } + .map(\.id)) + var result = component + result.origins.removeAll { consumed.contains($0.occurrence) } return result } @@ -159,9 +206,37 @@ package enum DeploymentConstruction { platform: DeclarationPlatform ) throws -> ResolvedLedger { var ledger = frozen.ledger - for component in linked.components { - guard case .declaration = component.payload else { continue } - for agent in component.recipients.sorted(by: { $0.rawValue < $1.rawValue }) { + for parent in linked.components where parent.key.kind == .plugin { + guard case .declaration = parent.payload, + let id = frozen.ledger.occurrences.first(where: { $0.id == parent.origins[0].occurrence })? + .component, + let record = frozen.ledger.components[id], + record.payload.object?["mode"] == .init("components") + else { continue } + _ = record + for agent in parent.recipients.sorted(by: { $0.rawValue < $1.rawValue }) { + ledger.lowerings.append( + try NativeGeneratedPluginLayoutV1.lower( + parent, members: linked.components, frozen: frozen, + request: .init(surface: surface(agent), scope: scope), + id: "plugin:" + String(parent.origins[0].occurrence) + ":" + agent.rawValue, + platform: platform)) + } + } + for original in linked.components { + guard case .declaration = original.payload else { continue } + if original.key.kind == .plugin, + ledger.lowerings.contains(where: { + $0.format.hasSuffix("-generated-plugin@1") + && $0.layout.object?["occurrences"]?.array?.contains( + .init(integer: original.origins[0].occurrence)) == true + }) + { + continue + } + for agent in original.recipients.sorted(by: { $0.rawValue < $1.rawValue }) { + let component = direct(original, ledger: ledger, agent: agent) + guard !component.origins.isEmpty else { continue } let surface: NativeClientSurface switch agent { case .claudeCode: surface = .claudeCode @@ -228,7 +303,9 @@ package enum DeploymentConstruction { let record = ledger.components[key]! let resource = ledger.resources[record.resources[0]]! for agent in component.recipients.sorted(by: { $0.rawValue < $1.rawValue }) { - let id = "skill:" + String(component.origins[0].occurrence) + ":" + agent.rawValue + let directComponent = direct(component, ledger: ledger, agent: agent) + guard let origin = directComponent.origins.first else { continue } + let id = "skill:" + String(origin.occurrence) + ":" + agent.rawValue add( id: id, format: "agents/skill@1", inputs: [key], resources: record.resources, location: .init( diff --git a/Sources/Components/LedgerImpact.swift b/Sources/Components/LedgerImpact.swift index 6e5d047..c35234c 100644 --- a/Sources/Components/LedgerImpact.swift +++ b/Sources/Components/LedgerImpact.swift @@ -49,7 +49,7 @@ package struct LedgerImpact { ledger: ResolvedLedger, roots: [String: URL], kinds: Set, names: Set, updating: Bool, selectedIdentities: Set? = nil ) throws { - func selected(_ c: LedgerComponent) -> Bool { + func explicitlySelected(_ c: LedgerComponent) -> Bool { if let selectedIdentities { return (try? Self.identity(c, ledger: ledger, roots: roots)).map( selectedIdentities.contains) == true @@ -58,6 +58,24 @@ package struct LedgerImpact { && (names.isEmpty || names.contains(c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name)) } + let parents = Set( + ledger.occurrences.filter { occurrence in + ledger.components[occurrence.component].map { + $0.kind == "plugin" && explicitlySelected($0) + } ?? false + }.map(\.id)) + let members = try Set( + Dictionary(grouping: ledger.occurrences, by: \.component).compactMap { + id, occurrences -> String? in + guard !occurrences.isEmpty, + occurrences.allSatisfy({ $0.pluginMember.map { parents.contains($0.parent) } ?? false }) + else { return nil } + return try Self.identity(ledger.components[id]!, ledger: ledger, roots: roots) + }) + func selected(_ c: LedgerComponent) -> Bool { + explicitlySelected(c) + || ((try? Self.identity(c, ledger: ledger, roots: roots)).map(members.contains) ?? false) + } var affected = Set() if updating { for occurrence in ledger.occurrences { @@ -103,7 +121,20 @@ package struct LedgerImpact { } func streams(_ ledger: ResolvedLedger) throws -> [String: [String]] { var result: [String: [String]] = [:] + let selectedParents = try Set( + ledger.occurrences.filter { occurrence in + guard let component = ledger.components[occurrence.component], component.kind == "plugin" + else { return false } + if let selectedIdentities { + return try selectedIdentities.contains( + identity(component, ledger: ledger, roots: roots)) + } + return kinds.contains(.plugin) && (names.isEmpty || names.contains(component.name)) + }.map(\.id)) for occurrence in ledger.occurrences { + if let member = occurrence.pluginMember, selectedParents.contains(member.parent) { + continue + } guard var c = ledger.components[occurrence.component] else { continue } let retargeted = try c.kind == "instructions" && !c.chatGPT diff --git a/Sources/Components/NativeAuthorityComposition.swift b/Sources/Components/NativeAuthorityComposition.swift new file mode 100644 index 0000000..0844b20 --- /dev/null +++ b/Sources/Components/NativeAuthorityComposition.swift @@ -0,0 +1,160 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// Bridges durable local authority to one verified native preimage and its same-edit remap. +enum NativeAuthorityComposition { + static func dialect(_ format: NativeDocumentFormat) -> String { + switch format { + case .json: "json" + case .jsonc(let trailing): trailing ? "jsonc-trailing-commas" : "jsonc" + case .toml: "toml" + } + } + + static func address(_ region: NativeRegion) throws -> [PrivateNativeAddressStep] { + try region.steps.map { + switch $0 { + case .key(let key): return .key(key) + case .occurrence(let e): + if let key = e.idKey, let value = e.id { return .stableID(key: key, value: value) } + guard let ordinal = e.ordinal else { + throw CoreError.invalidState("missing native ordinal") + } + return .position(index: ordinal) + } + } + } + + static func region(_ path: [PrivateNativeAddressStep], document: NativeDocument) throws + -> NativeRegion + { + var result = NativeRegion(keys: []) + for step in path { + switch step { + case .key(let key): result = NativeRegion(result.steps + [.key(key)]) + case .stableID(let key, let value): + result = NativeRegion(result.steps + [.occurrence(.init(idKey: key, id: value))]) + case .position(let index): + result = try document.validatedOccurrences( + in: result, matching: document.arrayDigest(result), ordinals: [index])[0] + } + } + return result + } + + static func region( + _ path: [LedgerNativePathStep], document: NativeDocument, + arrays: [PrivateNativeArrayRecord] + ) throws -> NativeRegion { + var result = NativeRegion(keys: []) + for step in path { + switch step { + case .key(let key): result = NativeRegion(result.steps + [.key(key)]) + case .stableID(let key, let value): + result = NativeRegion(result.steps + [.occurrence(.init(idKey: key, id: value))]) + case .position(let index, let evidence): + let digest: NativeArrayDigest + switch evidence { + case .semantic(let format, let hash): + digest = .init(format: format, digest: String(hash.dropFirst("sha256:".count))) + case .privateArray(let token): + let coordinates = try address(result) + guard let record = arrays.first(where: { $0.token == token && $0.path == coordinates }) + else { + throw CoreError.invalidState("native array authority is stale") + } + digest = .init( + format: record.semanticFormat, + digest: String(record.semanticDigest.dropFirst("sha256:".count))) + } + result = try document.validatedOccurrences(in: result, matching: digest, ordinals: [index])[ + 0] + } + } + return result + } + + struct Result { + let regions: [LedgerNativeOwnedRegion] + let containers: [LedgerNativeCreatedContainer] + let transitions: [PrivateNativeArrayTransition] + } + + static func finish( + _ change: PreparedNativeChange, document: NativeDocument, + owners: [(NativeObservation, [String])], containers: [NativeRegion], + previousArrays: [PrivateNativeArrayRecord], sensitive: Bool, + format: NativeDocumentFormat + ) throws -> Result { + var arrays: [PrivateNativeArrayRecord] = [] + var transitions: [PrivateNativeArrayTransition] = [] + for transition in change.arrayTransitions { + let previous = previousArrays[transition.index] + let current: PrivateNativeArrayRecord? + if let region = transition.region, let digest = transition.digest { + current = .init( + path: try address(region), documentFormat: dialect(format), + token: transition.canRetainToken ? previous.token : UUID(), + semanticFormat: digest.format, semanticDigest: "sha256:" + digest.digest) + arrays.append(current!) + } else { + current = nil + } + transitions.append(.init(previous: previous, current: current)) + } + func path(_ region: NativeRegion) throws -> [LedgerNativePathStep] { + var prefix = NativeRegion(keys: []) + var result: [LedgerNativePathStep] = [] + for step in region.steps { + switch step { + case .key(let key): result.append(.key(key)) + case .occurrence(let e): + if let key = e.idKey, let value = e.id { + result.append(.stableID(key: key, value: value)) + } else { + guard let ordinal = e.ordinal else { + throw CoreError.invalidState("missing native ordinal") + } + let digest = try document.arrayDigest(prefix) + let evidence: LedgerNativeArrayEvidence + if sensitive { + let coordinates = try address(prefix) + let record: PrivateNativeArrayRecord + if let existing = arrays.first(where: { $0.path == coordinates }) { + record = existing + } else { + record = .init( + path: coordinates, documentFormat: dialect(format), token: UUID(), + semanticFormat: digest.format, semanticDigest: "sha256:" + digest.digest) + arrays.append(record) + transitions.append(.init(previous: nil, current: record)) + } + evidence = .privateArray(token: record.token) + } else { + evidence = .semantic(format: digest.format, digest: "sha256:" + digest.digest) + } + result.append(.position(index: ordinal, evidence: evidence)) + } + } + prefix = NativeRegion(prefix.steps + [step]) + } + return result + } + let regions = try owners.map { + try LedgerNativeOwnedRegion(deployments: $0.1.sorted(), path: path($0.0.region)) + } + var created: [LedgerNativeCreatedContainer] = [] + for container in containers { + guard let observed = try document.read(container) else { continue } + let p = try path(container) + let ids = Set( + regions.filter { $0.path.count > p.count && Array($0.path.prefix(p.count)) == p }.flatMap( + \.deployments)) + if !ids.isEmpty { + created.append(.init(deployments: ids.sorted(), path: p, kind: observed.nativeKind)) + } + } + return Result(regions: regions, containers: created, transitions: transitions) + } +} diff --git a/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift b/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift index a7a1b3a..030f76e 100644 --- a/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift +++ b/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift @@ -177,10 +177,6 @@ struct ConsumerLifecycleRegressionTests { let f = try UpdateFixture() try f.declare(mode: .edit, agents: [.codex]) var declaration = try f.store.loadDeclaration() - declaration.components.removeAll { - if case .instructions = $0 { return true } - return false - } declaration.components.append( .command( name: "review", description: "Review", prompt: .literal("Frozen review"), diff --git a/Tests/AgentsUpdatesTests/NativeAuthorityIntegrationTests.swift b/Tests/AgentsUpdatesTests/NativeAuthorityIntegrationTests.swift new file mode 100644 index 0000000..6ad671a --- /dev/null +++ b/Tests/AgentsUpdatesTests/NativeAuthorityIntegrationTests.swift @@ -0,0 +1,465 @@ +import Foundation +import Testing + +@testable import AgentsCore +@testable import AgentsUpdates + +struct NativeAuthorityIntegrationTests { + private struct Bindings: RuntimeBindingProvider { + let value: String + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + Data(value.utf8) + } + } + private struct Refuse: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + throw CoreError.invalidState("unselected provider called") + } + } + + @Test func equalHooksKeepDistinctAuthorityAndRemoveOnlySelectedOccurrence() throws { + let f = try UpdateFixture() + let file = f.root.appendingPathComponent(".claude/settings.json") + try f.write( + #"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"same"}]}]}}"#, to: file) + try f.store.save( + declaration: Declaration( + components: ["first", "second"].map { + .hook( + name: $0, event: .native("SessionStart"), run: .init(executable: "same"), + agents: [.claudeCode]) + }), ledger: ResolvedLedger()) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + #expect(snapshot.deployments.allSatisfy { $0.status == .current }) + let first = try #require(snapshot.components.first { $0.name == "first" }) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [first.selection]), environment: f.environment + ) { try $0.apply() } + var object = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any]) + var hooks = try #require(object["hooks"] as? [String: Any]) + #expect((hooks["SessionStart"] as? [Any])?.count == 2) + let remaining = try UpdateOperations.inspect(environment: f.environment) + #expect(remaining.deployments.allSatisfy { $0.status == .current }) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(remaining.components.first?.selection)]), + environment: f.environment + ) { try $0.apply() } + object = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any]) + hooks = try #require(object["hooks"] as? [String: Any]) + #expect((hooks["SessionStart"] as? [Any])?.count == 1) + } + + @Test func privateHookColdRestoreAndRemovalUseActualArrayEvidence() throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .hook( + name: "check", event: .native("SessionStart"), + run: .init(executable: "never-run", environment: ["TOKEN": .secret("token")]), + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + let preview = try f.preview() + _ = try UpdateOperations.withPreparedUpdate( + environment: f.environment, bindingProvider: Bindings(value: "actual-private-array-canary") + ) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let file = f.root.appendingPathComponent(".claude/settings.json") + #expect(try String(contentsOf: file, encoding: .utf8).contains("actual-private-array-canary")) + let bytes = try Data(contentsOf: f.store.resolvedURL) + let text = String(decoding: bytes, as: UTF8.self) + #expect(!text.contains("actual-private-array-canary")) + #expect(text.contains("privateArray")) + #expect(!text.contains("semanticDigest")) + let snapshot = try UpdateOperations.inspect(environment: f.environment) + try FileManager.default.removeItem(at: file) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .restore), environment: f.environment, + bindingProvider: Bindings(value: "restored-private-array-canary") + ) { try $0.apply() } + #expect(try String(contentsOf: file, encoding: .utf8).contains("restored-private-array-canary")) + let restored = try UpdateOperations.inspect(environment: f.environment) + #expect(restored.deployments.allSatisfy { $0.status == .current }) + _ = snapshot + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(restored.components.first?.selection)]), + environment: f.environment, bindingProvider: Refuse() + ) { try $0.apply() } + let object = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any]) + #expect(object["hooks"] == nil) + #expect(try f.store.readLedger().nativeAuthorities == nil) + } + + @Test func pruneRightsRetireWhenUnmanagedContainerContentRemains() throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .command( + name: "review", description: "Review", prompt: .literal("Body"), agents: [.opencode]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let file = f.root.appendingPathComponent("opencode.json") + var object = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any]) + var commands = try #require(object["commands"] as? [String: Any]) + commands["user"] = ["template": "unmanaged"] + object["commands"] = commands + try JSONSerialization.data(withJSONObject: object).write(to: file) + let snapshot = try UpdateOperations.inspect(environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(snapshot.components.first?.selection)]), + environment: f.environment + ) { try $0.apply() } + #expect(try f.store.readLedger().nativeAuthorities == nil) + #expect(try String(contentsOf: file, encoding: .utf8).contains("unmanaged")) + try f.store.save( + declaration: Declaration(components: [ + .command( + name: "review", description: "Review", prompt: .literal("Again"), agents: [.opencode]) + ]), ledger: try f.store.readLedger()) + _ = try f.apply() + #expect( + try f.store.readLedger().nativeAuthorities?.flatMap(\.createdContainers).isEmpty == true) + } + + @Test func independentScopeSiblingEditRetainsPrivateArrayTokenAndFreshRemoval() throws { + let f = try UpdateFixture(scope: .user) + try f.store.save( + declaration: Declaration(components: [ + .hook( + name: "private", event: .native("SessionStart"), + run: .init(executable: "never-run", environment: ["TOKEN": .secret("token")]), + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + scope: .user, environment: f.environment, + bindingProvider: Bindings(value: "cross-scope-private-canary") + ) { try $0.apply() } + func receipt(_ store: StateStore) throws -> MaterializationReceipt { + try store.withLock(footprint: [.claudeSettingsUser]) { + let target = try store.nativeTarget(for: .claudeSettingsUser) + return try #require(try store.materializationReceipt(for: target)) + } + } + let before = try receipt(f.store) + let ledgerBytes = try Data(contentsOf: f.store.resolvedURL) + var other = f.environment + other.homeDirectory = f.root.appendingPathComponent("other-home") + try FileManager.default.createDirectory( + at: other.homeDirectory, withIntermediateDirectories: true) + let store = StateStore(scope: .user, environment: other) + try store.save( + declaration: Declaration(components: [ + .permissions( + name: "read", rules: [], agents: [.claudeCode], + native: ["claude-code": ["allow": .array([.string("Read")])]]) + ]), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + scope: .user, environment: other, bindingProvider: Refuse() + ) { try $0.apply() } + let after = try receipt(f.store) + #expect(before.generation != after.generation) + #expect(before.nativeArrays == after.nativeArrays) + #expect(try Data(contentsOf: f.store.resolvedURL) == ledgerBytes) + let current = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(current.deployments.allSatisfy { $0.status == .current }) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(current.components.first?.selection)]), + scope: .user, environment: f.environment, bindingProvider: Refuse() + ) { try $0.apply() } + let file = try f.store.withLock(footprint: [.claudeSettingsUser]) { + try f.store.nativeTarget(for: .claudeSettingsUser).url + } + let text = try String(contentsOf: file, encoding: .utf8) + #expect(!text.contains("cross-scope-private-canary")) + #expect(text.contains("Read")) + } + + @Test func staleArrayAuthorityDoesNotBlockAnIndependentSelectedSibling() throws { + let f = try UpdateFixture(scope: .user) + func declaration(_ allowed: String) -> Declaration { + Declaration(components: [ + .hook( + name: "private", event: .native("SessionStart"), + run: .init(executable: "never-run", environment: ["TOKEN": .secret("token")]), + agents: [.claudeCode]), + .permissions( + name: "read", rules: [], agents: [.claudeCode], + native: ["claude-code": ["allow": .array([.string(allowed)])]]), + ]) + } + try f.store.save(declaration: declaration("Read"), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + scope: .user, environment: f.environment, + bindingProvider: Bindings(value: "stale-array-private-canary") + ) { try $0.apply() } + var other = f.environment + other.homeDirectory = f.root.appendingPathComponent("other-home") + try FileManager.default.createDirectory( + at: other.homeDirectory, withIntermediateDirectories: true) + let otherStore = StateStore(scope: .user, environment: other) + try otherStore.save( + declaration: Declaration(components: [ + .hook( + name: "foreign", event: .native("SessionStart"), + run: .init(executable: "foreign-never-run"), agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + scope: .user, environment: other, bindingProvider: Refuse() + ) { try $0.apply() } + let ledger = try f.store.readLedger() + try f.store.save(declaration: declaration("Write"), ledger: ledger) + _ = try UpdateOperations.withPreparedUpdate( + .init(kinds: [.permissions], names: ["read"]), scope: .user, environment: f.environment, + bindingProvider: Refuse() + ) { try $0.apply() } + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate( + .init(kinds: [.hook], names: ["private"]), scope: .user, environment: f.environment, + bindingProvider: Refuse() + ) { try $0.apply() } + } + let file = try f.store.withLock(footprint: [.claudeSettingsUser]) { + try f.store.nativeTarget(for: .claudeSettingsUser).url + } + let text = try String(contentsOf: file, encoding: .utf8) + #expect(text.contains("stale-array-private-canary")) + #expect(text.contains("foreign-never-run")) + #expect(text.contains("Write")) + } + + @Test func privateArrayRollbackRestoresTargetLedgerAndReceiptTogether() throws { + let f = try UpdateFixture() + func declaration(_ command: String) -> Declaration { + Declaration(components: [ + .hook( + name: "check", event: .native("SessionStart"), + run: .init(executable: command, environment: ["TOKEN": .secret("token")]), + agents: [.claudeCode]) + ]) + } + try f.store.save(declaration: declaration("before"), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + environment: f.environment, bindingProvider: Bindings(value: "before-private") + ) { try $0.apply() } + let file = f.root.appendingPathComponent(".claude/settings.json") + let before = try Data(contentsOf: file) + let ledger = try Data(contentsOf: f.store.resolvedURL) + let receipt = try Data(contentsOf: f.store.materializationReceiptURL) + try f.store.save(declaration: declaration("after"), ledger: try f.store.readLedger()) + var reached = false + var receiptIndex: Int? + let result = UpdateOperations.perform( + environment: f.environment, bindingProvider: Bindings(value: "after-private"), + checkpoint: { point in + if point == TransactionCheckpoint.phase(.preparing).name { + let journal = try #require( + JSONSerialization.jsonObject( + with: Data(contentsOf: f.store.directory.appendingPathComponent("transaction.json"))) + as? [String: Any]) + let entries = try #require(journal["entries"] as? [[String: Any]]) + receiptIndex = try #require( + entries.firstIndex { ($0["path"] as? String) == "state/materializations.json" }) + } + if let receiptIndex, point == TransactionCheckpoint.progress(receiptIndex, .applied).name { + reached = true + throw CoreError.invalidState("injected native publication failure") + } + }, { try $0.apply() }) + #expect(reached) + #expect(result.disposition == .rolledBack) + #expect(!result.recovery.pending) + #expect(try Data(contentsOf: file) == before) + #expect(try Data(contentsOf: f.store.resolvedURL) == ledger) + #expect(try Data(contentsOf: f.store.materializationReceiptURL) == receipt) + } + + @Test func deferredLedgerNoopPreservesCapturedEncodingDuringColdRestore() throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .command( + name: "review", description: "Review", prompt: .literal("Frozen body"), + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + var original = try Data(contentsOf: f.store.resolvedURL) + original.append(Data("\n \n".utf8)) + try original.write(to: f.store.resolvedURL) + let inspection = try UpdateOperations.inspect(environment: f.environment) + let target = try #require(inspection.deployments.first?.location) + let output = try Data(contentsOf: target) + try FileManager.default.removeItem(at: target) + _ = try UpdateOperations.restore(environment: f.environment) + #expect(try Data(contentsOf: target) == output) + #expect(try Data(contentsOf: f.store.resolvedURL) == original) + } + + @Test func generatedPrivatePluginUsesProductionBindingsAndRetainsFrozenTree() throws { + let f = try UpdateFixture() + let source = f.root.appendingPathComponent("bundle") + try f.write( + #"{"name":"upstream","mcpServers":{"native":{"command":"${CLAUDE_PLUGIN_ROOT}/bin/server","env":{"TOKEN":"source-private-canary"}}}}"#, + to: source.appendingPathComponent(".claude-plugin/plugin.json")) + try f.write( + "#!/bin/sh\n# fixture source; never executed\n", + to: source.appendingPathComponent("bin/server")) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: source.appendingPathComponent("bin/server").path) + try f.store.save( + declaration: Declaration(components: [ + .plugin( + name: "selected", path: "bundle", source: ".", mode: .components, agents: [.claudeCode]), + .command( + name: "independent", description: "Independent", prompt: .literal("Body"), + agents: [.claudeCode]), + ]), ledger: ResolvedLedger()) + let before = try FileHash.folderHash(f.root) + let preview = try f.preview() + #expect(try FileHash.folderHash(f.root) == before) + _ = try UpdateOperations.withPreparedUpdate( + environment: f.environment, + bindingProvider: Bindings(value: "actual-generated-private-canary") + ) { try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) } + let snapshot = try UpdateOperations.inspect(environment: f.environment) + #expect(snapshot.deployments.allSatisfy { $0.status == .current }) + let plugin = try #require(snapshot.components.first { $0.kind == .plugin }) + let tree = try #require( + snapshot.deployments.first { $0.ownerRecords.contains(plugin.record) }?.location) + let manifest = tree.appendingPathComponent(".claude-plugin/plugin.json") + #expect( + try String(contentsOf: manifest, encoding: .utf8).contains("actual-generated-private-canary")) + #expect( + !String(decoding: try Data(contentsOf: f.store.resolvedURL), as: UTF8.self).contains( + "actual-generated-private-canary")) + #expect( + !String(decoding: try Data(contentsOf: f.store.resolvedURL), as: UTF8.self).contains( + "source-private-canary")) + _ = try UpdateOperations.withPreparedUpdate( + .init(kinds: [.command], names: ["independent"]), environment: f.environment, + bindingProvider: Refuse() + ) { try $0.apply() } + try FileManager.default.removeItem(at: source) + try FileManager.default.removeItem(at: tree) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .restore), environment: f.environment, + bindingProvider: Bindings(value: "cold-generated-private-canary") + ) { try $0.apply() } + #expect( + try String(contentsOf: manifest, encoding: .utf8).contains("cold-generated-private-canary")) + } + + @Test(arguments: [AgentID.claudeCode, .cursor, .geminiCLI], [false, true]) + func generatedPluginPublishesOnlySelectedMembersAndColdRestores( + _ agent: AgentID, _ supportingLink: Bool + ) throws { + let f = try UpdateFixture(scope: .user) + let root = f.store.directory.appendingPathComponent("bundle") + let manifest: String + let command: String + switch agent { + case .claudeCode: + manifest = ".claude-plugin/plugin.json" + command = "commands/review.md" + case .cursor: + manifest = ".cursor-plugin/plugin.json" + command = "commands/review.md" + default: + manifest = "gemini-extension.json" + command = "commands/review.toml" + } + try f.write( + #"{"name":"upstream","version":"1.2.3"}"#, to: root.appendingPathComponent(manifest)) + try f.write( + agent == .geminiCLI + ? "description = \"Review\"\nprompt = \"Frozen member\"\n" + : (agent == .cursor ? "Frozen member\n" : "---\ndescription: Review\n---\nFrozen member\n"), + to: root.appendingPathComponent(command) + ) + try f.write( + "---\nname: helper\ndescription: Helper\n---\nFrozen skill\n", + to: root.appendingPathComponent("skills/helper/SKILL.md")) + if supportingLink { + try f.write("Frozen supporting resource", to: root.appendingPathComponent("shared/tool.txt")) + try FileManager.default.createSymbolicLink( + atPath: root.appendingPathComponent("skills/helper/reference.txt").path, + withDestinationPath: "../../shared/tool.txt") + } + try f.store.save(declaration: Declaration(), ledger: ResolvedLedger()) + try f.write( + """ + version: 1 + components: + - kind: plugin + name: selected + source: "." + path: bundle + agents: ["\(agent.rawValue)"] + native: {gemini-cli: {version: "1.2.3"}} + - kind: mcpServer + name: independent + transport: {kind: stdio, executable: fixture-command} + agents: ["\(agent.rawValue)"] + """, to: f.store.declarationURL) + let preview = try f.preview() + _ = try UpdateOperations.withPreparedUpdate(scope: .user, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let ledger = try f.store.readLedger() + #expect(ledger.lowerings.filter { $0.format.hasSuffix("-generated-plugin@1") }.count == 1) + #expect(ledger.deployments.filter { $0.route == "agents/skill@1" }.isEmpty) + #expect(ledger.deployments.count == 2) + let snapshot = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(snapshot.deployments.allSatisfy { $0.status == .current }) + let plugin = try #require(snapshot.components.first { $0.kind == .plugin }) + let tree = try #require( + snapshot.deployments.first { $0.ownerRecords.contains(plugin.record) }?.location) + #expect( + try String(contentsOf: tree.appendingPathComponent(command), encoding: .utf8).contains( + "Frozen member")) + #expect( + try String(contentsOf: tree.appendingPathComponent("skills/helper/SKILL.md"), encoding: .utf8) + .contains("Frozen skill")) + if supportingLink { + #expect( + try String( + contentsOf: tree.appendingPathComponent("skills/helper/reference.txt"), encoding: .utf8) + == "Frozen supporting resource") + } + let unmanaged = tree.appendingPathComponent("unmanaged-empty") + try FileManager.default.createDirectory(at: unmanaged, withIntermediateDirectories: true) + #expect( + try UpdateOperations.inspect(scope: .user, environment: f.environment).deployments.contains { + $0.location == tree && $0.status == .drifted + }) + #expect(throws: (any Error).self) { try f.preview() } + try FileManager.default.removeItem(at: unmanaged) + try FileManager.default.removeItem(at: root) + try FileManager.default.removeItem(at: tree) + _ = try UpdateOperations.restore(scope: .user, environment: f.environment) + #expect( + try String(contentsOf: tree.appendingPathComponent(command), encoding: .utf8).contains( + "Frozen member")) + let restored = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(restored.deployments.allSatisfy { $0.status == .current }) + if supportingLink { + #expect( + try String( + contentsOf: tree.appendingPathComponent("skills/helper/reference.txt"), encoding: .utf8) + == "Frozen supporting resource") + } + _ = try UpdateOperations.withPreparedUpdate( + .init( + operation: .remove, + selections: [try #require(restored.components.first { $0.kind == .plugin }?.selection)]), + scope: .user, environment: f.environment + ) { try $0.apply() } + #expect(!FileManager.default.fileExists(atPath: tree.path)) + #expect( + try UpdateOperations.inspect(scope: .user, environment: f.environment).deployments.count == 1) + } +} From 10cba6ea5d0d08559288d8cdbbb4b0cc53a0f277 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:07:08 +0800 Subject: [PATCH 129/171] test: verify temporary listing alongside watch subscription --- .../WatchMirrorConcurrencyTests.swift | 61 +++++++++---------- 1 file changed, 28 insertions(+), 33 deletions(-) diff --git a/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift b/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift index f9e2790..2135a26 100644 --- a/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift +++ b/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift @@ -51,53 +51,48 @@ struct WatchMirrorConcurrencyTests { #expect(try fixture.cachedInstruction(first).contains("initial")) } - @Test(arguments: [false, true]) - func listingAndFirstWatchMutationShareMirrorLock(_ existingMirror: Bool) throws { + @Test func temporaryListingAndFirstSubscriptionCompleteWithoutSharedMirror() throws { let fixture = try WatchGitFixture() try FileManager.default.removeItem(at: fixture.store.directory) - let scopeLock = fixture.store.directory.appendingPathComponent(".agents.lock") + + let initial = try stateTestProcess(root: fixture.root, arguments: ["instruction-list", ""]) + defer { terminateProcess(initial) } + try finishProcesses([initial], root: fixture.root) + let listingResult = fixture.root.appendingPathComponent("listing-finished") + #expect(try String(contentsOf: listingResult, encoding: .utf8) == "rule") + #expect(!exists(fixture.store.directory)) + #expect(!exists(fixture.store.cacheDirectory)) + try FileManager.default.removeItem(at: listingResult) + let template = fixture.root.appendingPathComponent("template") - if existingMirror { - let listing = try stateTestProcess(root: fixture.root, arguments: ["instruction-list", ""]) - defer { terminateProcess(listing) } - try finishProcesses([listing], root: fixture.root) - try #require(exists(fixture.mirror)) - try #require(!exists(scopeLock)) - try FileManager.default.removeItem( - at: fixture.root.appendingPathComponent("listing-finished")) - 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"]) - } let pause = try GitTransactionPause( - root: fixture.root, - hooks: (existingMirror ? fixture.mirror : template).appendingPathComponent("hooks"), + root: fixture.root, hooks: template.appendingPathComponent("hooks"), condition: "[ \"${ref#refs/heads/}\" != \"$ref\" ]") defer { pause.terminate() } let listing = try stateTestProcess( root: fixture.root, arguments: ["instruction-list", ""], - environment: existingMirror ? [:] : ["GIT_TEMPLATE_DIR": template.path]) + environment: ["GIT_TEMPLATE_DIR": template.path]) defer { terminateProcess(listing) } try pause.wait() - try #require(!exists(scopeLock)) - let mirrorLock = fixture.store.cacheDirectory.appendingPathComponent("locks") - .appendingPathComponent(fixture.mirror.deletingPathExtension().lastPathComponent + ".lock") - try #require(exists(mirrorLock)) - let contention = try ProcessSignal(at: fixture.root.appendingPathComponent("writer-contended")) + #expect(listing.isRunning) + #expect(!exists(listingResult)) + #expect(!exists(fixture.store.directory)) + #expect(!exists(fixture.store.cacheDirectory)) let writer = try stateTestProcess(root: fixture.root, arguments: ["watch-subscribe", ""]) defer { terminateProcess(writer) } - #expect(try contention.receive() == "contended") - #expect(exists(scopeLock)) - #expect(writer.isRunning) - #expect(!exists(fixture.store.watchURL)) - #expect(!exists(fixture.root.appendingPathComponent("writer-finished"))) + try finishProcesses([writer], root: fixture.root) + #expect(listing.isRunning) + #expect(!exists(listingResult)) + #expect(exists(fixture.root.appendingPathComponent("writer-finished"))) + #expect(try fixture.store.loadWatch().sources[fixture.id]?.seen == .revision(fixture.head())) + #expect(try fixture.watchRefs() == [fixture.head()]) + #expect(try gitLocks(fixture).isEmpty) + let published = try FileHash.folderHash(fixture.store.directory) - try finishProcesses([listing, writer], root: fixture.root, resuming: pause) - #expect( - try String( - contentsOf: fixture.root.appendingPathComponent("listing-finished"), encoding: .utf8) - == "rule") + try finishProcesses([listing], root: fixture.root, resuming: pause) + #expect(try String(contentsOf: listingResult, encoding: .utf8) == "rule") + #expect(try FileHash.folderHash(fixture.store.directory) == published) #expect(try fixture.store.loadWatch().sources[fixture.id]?.seen == .revision(fixture.head())) #expect(try fixture.watchRefs() == [fixture.head()]) #expect(try gitLocks(fixture).isEmpty) From 01994664256ffbf18d91e88fc611b21f0a8d57cc Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:09:36 +0800 Subject: [PATCH 130/171] feat(instructions): expose mapping read dependencies --- Documentation/Architecture/Instructions.md | 11 +- Sources/AgentsCore/StateInspection.swift | 10 ++ .../InstructionExport.swift | 17 ++- .../MappingReadLocationsTests.swift | 113 ++++++++++++++++++ 4 files changed, 143 insertions(+), 8 deletions(-) create mode 100644 Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift diff --git a/Documentation/Architecture/Instructions.md b/Documentation/Architecture/Instructions.md index 6b19585..951eaf1 100644 --- a/Documentation/Architecture/Instructions.md +++ b/Documentation/Architecture/Instructions.md @@ -143,10 +143,13 @@ 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. +Export maps each scope's locked deployments and prompt sections from ledger +metadata alone. Each `InstructionMapping.readLocations` includes the scope's +declaration, resolved and watch-state leaves, scope directory, scope lock and +recovery markers, including absent entries. These locations remain available +for missing-lock, pending-recovery and unavailable statuses. Mapping does not +read section bodies, append content or deployed target bytes; content inspection +operations supply their own dependencies. Planning validates required content before applying. Reports include old and new section records, target before/after bytes and recipients, drift, foreign diff --git a/Sources/AgentsCore/StateInspection.swift b/Sources/AgentsCore/StateInspection.swift index 8845553..64c3ab0 100644 --- a/Sources/AgentsCore/StateInspection.swift +++ b/Sources/AgentsCore/StateInspection.swift @@ -2,6 +2,16 @@ import CPlatform import Foundation extension StateStore { + /// Durable admission dependencies for a scope inspection, including absent entries whose + /// creation changes whether the scope can be read. State-file dependencies belong to the caller. + package var readLockLocations: [URL] { + [directory] + + [ + ".agents.lock", TransactionJournal.fileName, TransactionJournal.incompleteFileName, + "watch-refs.pending", + ].map { directory.appendingPathComponent($0) } + } + /// Takes an existing scope lock without creating files or replaying recovery. /// Pending recovery runs the diagnostic callback instead of inspecting inconsistent state; /// by default it throws `CoreError.recoveryPending`. diff --git a/Sources/AgentsInstructions/InstructionExport.swift b/Sources/AgentsInstructions/InstructionExport.swift index c317079..f6b194f 100644 --- a/Sources/AgentsInstructions/InstructionExport.swift +++ b/Sources/AgentsInstructions/InstructionExport.swift @@ -25,10 +25,13 @@ public struct InstructionMapping: Sendable, Equatable { public let root: URL public let status: Status public let targets: [Target] - /// 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. + /// Locked sections without a target assignment. public let unplaced: [LockedSection] public let prompts: [String: [LockedSection]] + /// Durable scope-state and read-admission dependencies, including absent leaves and their + /// scope directory. Retained for every status; section bodies, append files and target bytes + /// are not read by this mapping operation. + public let readLocations: [URL] } extension InstructionOperations { @@ -52,9 +55,15 @@ extension InstructionOperations { { let store = StateStore(scope: scope, environment: environment) let root = scope == .project ? environment.projectDirectory : environment.homeDirectory + let readLocations = Array( + Set( + (store.readLockLocations + [store.declarationURL, store.resolvedURL, store.watchURL]) + .map(\.standardizedFileURL)) + ).sorted { $0.path < $1.path } func empty(_ status: InstructionMapping.Status) -> InstructionMapping { InstructionMapping( - scope: scope, root: root, status: status, targets: [], unplaced: [], prompts: [:]) + scope: scope, root: root, status: status, targets: [], unplaced: [], prompts: [:], + readLocations: readLocations) } do { return try store.withReadLock( @@ -95,7 +104,7 @@ extension InstructionOperations { return InstructionMapping( scope: scope, root: root, status: .locked, targets: targets, unplaced: [], - prompts: lock.instructions.chatgpt.mapValues(\.sections)) + prompts: lock.instructions.chatgpt.mapValues(\.sections), readLocations: readLocations) }) } catch { return empty(.unavailable(String(describing: error))) diff --git a/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift b/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift new file mode 100644 index 0000000..381b6c2 --- /dev/null +++ b/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift @@ -0,0 +1,113 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsUpdates +import Foundation +import Testing + +@Suite("Instruction mapping read locations") +struct MappingReadLocationsTests { + @Test func lockedMappingReadsMetadataWithoutContentDependencies() throws { + let f = try InstructionFixture() + try f.section("shared") + try f.commit() + try f.add(agents: [.codex]) + try f.own("own") + try f.addOwn(names: ["own"], agents: [.codex]) + let store = f.store() + var declaration = try store.loadDeclaration() + try declaration.updateInstructions { + $0?.chatgpt = [ + "daily": PromptDeclaration(sections: ["rules:shared", "own"], append: "append.md") + ] + } + try store.save(declaration: declaration, ledger: store.loadLedger()) + _ = try InstructionOperations.updateInstalled(environment: f.environment, apply: true) + let own = f.project.appendingPathComponent(".agent/instructions/own.md") + let target = f.project.appendingPathComponent("AGENTS.md") + for url in [own, target, store.cacheDirectory] { + try FileManager.default.removeItem(at: url) + } + let before = try f.snapshot() + let mapping = try #require( + InstructionOperations.export(projectRoots: [f.project], environment: f.environment).last) + #expect(mapping.status == .locked) + #expect(mapping.targets.flatMap(\.sections).map(\.name) == ["shared", "own"]) + #expect(mapping.prompts["daily"]?.map(\.name) == ["shared", "own"]) + #expect(mapping.unplaced.isEmpty) + expectStateLocations(mapping, store: store) + let paths = Set(mapping.readLocations.map(\.path)) + #expect(!paths.contains(own.path)) + #expect(!paths.contains(target.path)) + #expect(!paths.contains(f.project.appendingPathComponent("append.md").path)) + #expect(!paths.contains { $0.hasPrefix(store.cacheDirectory.path) }) + #expect(try f.snapshot() == before) + } + + @Test func missingScopesRetainAbsentLeavesWithoutCreatingState() throws { + let f = try InstructionFixture() + let before = try f.snapshot() + let mappings = InstructionOperations.export( + projectRoots: [f.project, f.project.appendingPathComponent(".")], environment: f.environment) + #expect(mappings.map(\.scope) == [.user, .project]) + for mapping in mappings { + #expect(mapping.status == .missingLock) + expectStateLocations(mapping, store: f.store(mapping.scope)) + #expect(!FileManager.default.fileExists(atPath: f.store(mapping.scope).directory.path)) + } + #expect(try f.snapshot() == before) + } + + @Test(arguments: ["transaction.json", "transaction.new", "watch-refs.pending"]) + func pendingRecoveryRetainsAdmissionLocations(_ marker: String) throws { + let f = try InstructionFixture() + let store = f.store() + try f.write("", to: store.directory.appendingPathComponent(marker)) + let before = try f.snapshot() + let mapping = try #require( + InstructionOperations.export(projectRoots: [f.project], environment: f.environment).last) + #expect(mapping.status == .pendingRecovery) + expectStateLocations(mapping, store: store) + #expect(mapping.targets.isEmpty) + #expect(try f.snapshot() == before) + } + + @Test(arguments: ["agents.yaml", "agents.resolved", "agents.watch", ".agents.lock"]) + func unavailableScopesRetainLocationsForRepair(_ name: String) throws { + let f = try InstructionFixture() + let store = f.store() + let file = store.directory.appendingPathComponent(name) + if name == ".agents.lock" { + try FileManager.default.createDirectory( + at: store.directory, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: file, withDestinationURL: f.root.appendingPathComponent("absent-lock")) + } else { + try f.write("invalid", to: file) + } + let before = try f.snapshot() + let mapping = try #require( + InstructionOperations.export(projectRoots: [f.project], environment: f.environment).last) + guard case .unavailable(let message) = mapping.status else { + Issue.record("Expected unavailable scope, got \(mapping.status)") + return + } + if name == "agents.watch" || name == "agents.resolved" { + #expect(message.contains(store.declarationURL.path)) + } + expectStateLocations(mapping, store: store) + #expect(mapping.targets.isEmpty) + #expect(try f.snapshot() == before) + } + + private func expectStateLocations(_ mapping: InstructionMapping, store: StateStore) { + let expected = [ + store.directory, store.declarationURL, store.resolvedURL, store.watchURL, + store.directory.appendingPathComponent(".agents.lock"), + store.directory.appendingPathComponent("transaction.json"), + store.directory.appendingPathComponent("transaction.new"), + store.directory.appendingPathComponent("watch-refs.pending"), + ].map(\.path).sorted() + #expect(mapping.readLocations.map(\.path) == expected) + } +} From 32fe2bf6ffe9fc9c0bc27259927fa50030567c4d Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:34:21 +0800 Subject: [PATCH 131/171] fix: preserve shared targets and preview generated members --- Documentation/Architecture/Updates.md | 9 +- Sources/AgentsUpdates/UpdateModels.swift | 4 +- Sources/AgentsUpdates/UpdatePlan.swift | 14 ++- Sources/Components/ArtifactAggregation.swift | 107 +++++++++++++++--- .../ConsumerLifecycleRegressionTests.swift | 77 +++++++++++++ .../NativeAuthorityIntegrationTests.swift | 49 +++++++- 6 files changed, 230 insertions(+), 30 deletions(-) diff --git a/Documentation/Architecture/Updates.md b/Documentation/Architecture/Updates.md index 90b67c5..a5f57fd 100644 --- a/Documentation/Architecture/Updates.md +++ b/Documentation/Architecture/Updates.md @@ -31,9 +31,12 @@ and prompts, selected native changes, missing-lock status, `hasChanges` and a `displayedFingerprint`. Native reports contain the owned symbolic values; complete shared documents, unrelated siblings, runtime secret values and private freshness evidence remain internal. `ComponentUpdateChange.symbolicBefore` and `symbolicAfter` -are readable selected configuration JSON, rendered through the native JSON owner. -Environment and secret references remain symbolic objects; `nil` means the selected -value is unavailable. Consumers can display these strings directly. Equal unmanaged +are readable selected configuration, rendered through the native document owner. +Generated-plugin text includes the final target, selected native files and member +content, and frozen resource paths and executable flags. Binding values remain +symbolic references; private deployed bytes and unrelated members are never read +for display. `nil` means the selected value is unavailable; unavailable recorded +skill content is labelled in the projection. Consumers display these strings directly. Equal unmanaged values do not establish ownership. `hasChanges` includes declaration and ledger changes even when target bytes agree. diff --git a/Sources/AgentsUpdates/UpdateModels.swift b/Sources/AgentsUpdates/UpdateModels.swift index 935916c..66e794f 100644 --- a/Sources/AgentsUpdates/UpdateModels.swift +++ b/Sources/AgentsUpdates/UpdateModels.swift @@ -55,10 +55,10 @@ public struct ComponentUpdateChange: Codable, Sendable, Equatable { public let effectiveReaders: [AgentID] public let privateMaterialization: Bool public let permissionChange: ComponentPermissionChange? - /// Readable selected configuration JSON with symbolic environment/secret references. + /// Readable selected native configuration/files with symbolic environment/secret references. /// Nil means the old selected value is unavailable; native sibling values are never included. public let symbolicBefore: String? - /// Readable selected configuration JSON, using the same symbolic projection as inspection. + /// Readable selected native configuration/files, including generated member content and targets. public let symbolicAfter: String? public let kind: String public let name: String diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index c4f9aa4..98b9d14 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -427,12 +427,14 @@ final class UpdatePlan { beforeMode: UInt32($0.before.mode), afterOwner: $0.owner, afterMode: $0.mode) }) }, - symbolicBefore: try change.symbolicBefore.map { - try UpdateOperations.symbolicConfigurationText($0) - }, - symbolicAfter: try change.symbolicAfter.map { - try UpdateOperations.symbolicConfigurationText($0) - }, + symbolicBefore: try change.configurationBefore + ?? change.symbolicBefore.map { + try UpdateOperations.symbolicConfigurationText($0) + }, + symbolicAfter: try change.configurationAfter + ?? change.symbolicAfter.map { + try UpdateOperations.symbolicConfigurationText($0) + }, kind: component.kind, name: component.name, path: change.url.path, agents: change.deployment.recipients, changed: change.changed) }) diff --git a/Sources/Components/ArtifactAggregation.swift b/Sources/Components/ArtifactAggregation.swift index 58dc796..7e1a644 100644 --- a/Sources/Components/ArtifactAggregation.swift +++ b/Sources/Components/ArtifactAggregation.swift @@ -19,6 +19,8 @@ package struct AggregatedChange { package var memberAccessChanges: [PrivateTreeAccessChange] = [] package var symbolicBefore: LedgerValue? = nil package var symbolicAfter: LedgerValue? = nil + package var configurationBefore: String? = nil + package var configurationAfter: String? = nil } /// One prepared physical replacement owns all logical contributions at that destination. @@ -112,16 +114,19 @@ package final class ArtifactAggregation: PreparedEvidence { } let roots = store.ledgerRoots let artifacts = Dictionary(uniqueKeysWithValues: artifacts.map { ($0.name, $0) }) + let affectedPaths = try Set( + previous.deployments.filter { try selected($0, in: previous) }.map { + try installationURL($0).path + } + + ledger.deployments.filter { try selected($0, in: ledger) }.map { + try installationURL($0).path + }) let previousByPath = try Dictionary( - grouping: previous.deployments.filter { try selected($0, in: previous) } - ) { - try installationURL($0).path - } + grouping: previous.deployments.filter { try affectedPaths.contains(installationURL($0).path) } + ) { try installationURL($0).path } var byPath = try Dictionary( - grouping: ledger.deployments.filter { try selected($0, in: ledger) } - ) { - try installationURL($0).path - } + grouping: ledger.deployments.filter { try affectedPaths.contains(installationURL($0).path) } + ) { try installationURL($0).path } var native: [String: [(LockedLowering, NativeMCPContribution, MaterializationTarget)]] = [:] for lowering in ledger.lowerings where lowering.format.hasSuffix("-mcp@1") { @@ -1469,6 +1474,9 @@ package final class ArtifactAggregation: PreparedEvidence { } return names } + func bindingPlaceholder(_ name: String) -> String { + "agents-symbolic-binding-" + FileHash.sha256Hex(data: Data(name.utf8)) + } let selectedEnvironment = store.environment let generatedBudget = nativeBudget() func bundle( @@ -1478,13 +1486,75 @@ package final class ArtifactAggregation: PreparedEvidence { var environment = selectedEnvironment if symbolic { for name in bindings(contribution) { - environment.environment[name] = "agents-symbolic-binding" + environment.environment[name] = bindingPlaceholder(name) } } return try Self.generatedPluginFiles( contribution, target: target, values: values, environment: environment, budget: generatedBudget) } + func symbolicFiles( + _ contribution: NativeGeneratedPluginContribution, target: MaterializationTarget + ) throws -> [String: Data] { + let values = RuntimeBindingValues( + Dictionary( + uniqueKeysWithValues: bindings(contribution).map { + ($0, Data(bindingPlaceholder($0).utf8)) + })) + return try bundle(contribution, target: target, values: values, symbolic: true) + } + func preview( + _ contribution: NativeGeneratedPluginContribution, target: MaterializationTarget, + selected: ResolvedLedger, files: [String: Data] + ) throws -> String { + var sections = ["Target: " + target.url.path] + for path in files.keys.sorted() { + guard let text = String(data: files[path]!, encoding: .utf8) else { + throw CoreError.invalidState("generated native preview is not UTF-8") + } + var displayed = text + for name in bindings(contribution).sorted() { + // Native conversion sees inert literals; display labels use the native JSON escaper. + let label = try Self.configurationPreview(.string("«binding:" + name + "»")) + displayed = displayed.replacingOccurrences( + of: bindingPlaceholder(name), with: String(label.dropFirst().dropLast())) + } + sections.append(path + "\n" + displayed) + } + let skillResources = Set( + contribution.members.compactMap { member -> String? in + if case .skill(_, let resource) = member.content { return resource } + return nil + }) + for placement in contribution.resourcePlacements { + let resource = contribution.resources[placement.resource]! + sections.append("Resource: " + placement.path) + for entry in resource.entries where entry.kind != .directory { + let suffix = entry.path == "." ? "" : "/" + entry.path + let detail = + entry.kind == .symlink + ? " -> " + (entry.link ?? "") : entry.executable ? " (executable)" : "" + sections.append(placement.path + suffix + detail) + if skillResources.contains(placement.resource), entry.path == "SKILL.md" { + let bytes: Data? + if let object = entry.object, let captured = selected.contentObjects[object] { + bytes = captured + } else if let source = resources[placement.resource] { + bytes = try Data( + contentsOf: PathSafety.resolvedChild(base: source, subpath: entry.path)) + } else { + bytes = nil + } + if let bytes, let text = String(data: bytes, encoding: .utf8) { + sections.append(text) + } else { + sections.append("Recorded skill content is unavailable in this preview.") + } + } + } + } + return sections.joined(separator: "\n\n") + } for path in Set(next.keys).union(old.keys).sorted() { let entry = next[path] ?? old[path]! let target = entry.2 @@ -1502,6 +1572,10 @@ package final class ArtifactAggregation: PreparedEvidence { target, changingAccess: changingAccess, requiringReceiptForExistingTarget: !priorNames.isEmpty) : nil let exists = FileManager.default.fileExists(atPath: path) + let priorFiles = try old[path].map { try symbolicFiles($0.1, target: target) } + let configurationBefore = try old[path].map { + try preview($0.1, target: target, selected: previous, files: priorFiles!) + } if exists && selected { guard let prior = old[path], previous.deployments.contains(where: { $0.id == prior.0.id && $0.ownership == .generated } @@ -1510,7 +1584,7 @@ package final class ArtifactAggregation: PreparedEvidence { throw CoreError.invalidState("generated native container contains unmanaged content") } if receipt == nil { - let expected = try bundle(prior.1, target: target, values: .init([:])) + let expected = priorFiles! guard try Self.generatedTreeMatches(prior.1, target: target, files: expected) else { throw CoreError.invalidState("owned generated native container drifted") } @@ -1527,12 +1601,8 @@ package final class ArtifactAggregation: PreparedEvidence { if let index = ledger.lowerings.firstIndex(where: { $0.id == current.0.id }) { ledger.lowerings[index].deployments = [deployment.id] } + let symbolic = try symbolicFiles(current.1, target: target) if selected { - let symbolicValues = RuntimeBindingValues( - Dictionary( - uniqueKeysWithValues: names.map { ($0, Data("agents-symbolic-binding".utf8)) })) - let symbolic = try bundle( - current.1, target: target, values: symbolicValues, symbolic: true) let tree = workspace.appendingPathComponent( "generated-" + FileHash.sha256Hex(data: Data(path.utf8))) try FileSystem.createDirectory(at: tree) @@ -1610,8 +1680,9 @@ package final class ArtifactAggregation: PreparedEvidence { changed: selected && (writes[path] != nil || privatePlan != nil), native: true, accessChange: privatePlan?.accessChange, effectiveReaders: current.1.knownReaders, privateMaterialization: sensitive, requiredBindings: names.sorted(), - symbolicBefore: old[path].flatMap { previous.components[$0.1.component]?.payload }, - symbolicAfter: ledger.components[current.1.component]?.payload)) + configurationBefore: configurationBefore, + configurationAfter: try preview( + current.1, target: target, selected: ledger, files: symbolic))) } else if selected, let deployment = previous.deployments.first(where: { $0.id == entry.0.id }) { @@ -1621,7 +1692,7 @@ package final class ArtifactAggregation: PreparedEvidence { deployment: deployment, url: target.url, before: nil, after: nil, changed: exists, native: true, privateMaterialization: sensitive, - symbolicBefore: previous.components[entry.1.component]?.payload)) + configurationBefore: configurationBefore)) } } return Set(next.keys).union(old.keys) diff --git a/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift b/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift index 030f76e..bd37953 100644 --- a/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift +++ b/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift @@ -76,6 +76,83 @@ struct ConsumerLifecycleRegressionTests { #expect(try f.snapshot() == before) } + @Test func ordinaryPartialRemovalKeepsSharedInstructionTargetAndSurvivingPins() throws { + let f = try UpdateFixture() + try f.write( + "---\ndescription: Other.\n---\n# Other\n\nFrozen survivor\n", + to: f.repo.appendingPathComponent("instructions/other.md")) + try f.commit() + try f.declare(agents: [.codex]) + var declaration = try f.store.loadDeclaration() + try declaration.updateInstructions { $0?.sections.append("fixture:other") } + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + let previous = try f.store.readLedger() + let skillBytes = try f.bytes(f.target().appendingPathComponent("SKILL.md")) + try f.advance() + try f.write( + "---\ndescription: Other.\n---\n# Other\n\nMutable producer changed\n", + to: f.repo.appendingPathComponent("instructions/other.md")) + try f.commit() + let before = try f.snapshot() + let preview = try UpdateOperations.preview( + .init(operation: .remove, kinds: [.instructions], names: ["rules"]), + environment: f.environment) + let target = try #require(preview.instructions.targets.first { $0.url == f.instruction() }) + let after = try #require(target.after) + #expect(String(decoding: after, as: UTF8.self).contains("Frozen survivor")) + #expect(!String(decoding: after, as: UTF8.self).contains("# Rules")) + #expect(target.afterAgents == [.codex]) + #expect(try f.snapshot() == before) + _ = try InstructionOperations.remove(names: ["rules"], environment: f.environment) + #expect(try f.bytes(f.instruction()) == after) + #expect(try f.bytes(f.target().appendingPathComponent("SKILL.md")) == skillBytes) + let next = try f.store.readLedger() + for (id, component) in previous.components + where component.kind == "skills" || component.name == "other" { + #expect(next.components[id] == component) + #expect(next.sources[component.source] == previous.sources[component.source]) + } + let deployment = try #require( + next.deployments.first { + $0.route == "agents/instructions@1" && $0.target.path == "AGENTS.md" + }) + #expect(deployment.expectedHash == "sha256:" + FileHash.sha256Hex(data: after)) + #expect( + try UpdateOperations.inspect(environment: f.environment).deployments.filter { + $0.location == f.instruction() + }.allSatisfy { $0.status == .current }) + } + + @Test func handwrittenSharedInstructionPartialRemovalRefusesBeforeCallback() throws { + let f = try UpdateFixture() + try f.write( + "---\ndescription: Other.\n---\n# Other\n", + to: f.repo.appendingPathComponent("instructions/other.md")) + try f.commit() + try f.declare(agents: [.codex]) + var declaration = try f.store.loadDeclaration() + try declaration.updateInstructions { $0?.sections.append("fixture:other") } + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + try f.write("Handwritten shared destination", to: f.instruction()) + let before = try f.snapshot() + let preview = try UpdateOperations.preview( + .init(operation: .remove, kinds: [.instructions], names: ["rules"]), + environment: f.environment) + let target = try #require(preview.instructions.targets.first { $0.url == f.instruction() }) + #expect(target.foreign) + #expect(target.after != nil) + var callbacks = 0 + #expect(throws: InstructionError.self) { + try InstructionOperations.remove(names: ["rules"], environment: f.environment) { _ in + callbacks += 1 + } + } + #expect(callbacks == 0) + #expect(try f.snapshot() == before) + } + @Test func explicitRemovalRetargetsSurvivorsAndKeepsSkillPin() throws { let f = try UpdateFixture() try f.write( diff --git a/Tests/AgentsUpdatesTests/NativeAuthorityIntegrationTests.swift b/Tests/AgentsUpdatesTests/NativeAuthorityIntegrationTests.swift index 6ad671a..201179d 100644 --- a/Tests/AgentsUpdatesTests/NativeAuthorityIntegrationTests.swift +++ b/Tests/AgentsUpdatesTests/NativeAuthorityIntegrationTests.swift @@ -321,6 +321,11 @@ struct NativeAuthorityIntegrationTests { let before = try FileHash.folderHash(f.root) let preview = try f.preview() #expect(try FileHash.folderHash(f.root) == before) + let text = try #require(preview.components.first { $0.kind == "plugin" }?.symbolicAfter) + #expect(text.contains("mcpServers")) + #expect(text.contains("«binding:")) + #expect(!text.contains("source-private-canary")) + #expect(!text.contains("actual-generated-private-canary")) _ = try UpdateOperations.withPreparedUpdate( environment: f.environment, bindingProvider: Bindings(value: "actual-generated-private-canary") @@ -353,6 +358,35 @@ struct NativeAuthorityIntegrationTests { try String(contentsOf: manifest, encoding: .utf8).contains("cold-generated-private-canary")) } + @Test func generatedGeminiAuthoredVersionOverridesProducerAndSurvivesColdRestore() throws { + let f = try UpdateFixture(scope: .user) + let source = f.store.directory.appendingPathComponent("bundle") + try f.write( + #"{"name":"upstream","version":"1.2.3"}"#, + to: source.appendingPathComponent("gemini-extension.json")) + try f.store.save( + declaration: Declaration(components: [ + .plugin( + name: "selected", path: "bundle", source: ".", mode: .components, + agents: [.geminiCLI], native: ["gemini-cli": ["version": .string("9.8.7")]]) + ]), ledger: ResolvedLedger()) + let preview = try f.preview() + #expect(preview.components.first?.symbolicAfter?.contains("9.8.7") == true) + _ = try UpdateOperations.withPreparedUpdate(scope: .user, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let installed = try UpdateOperations.inspect(scope: .user, environment: f.environment) + let tree = try #require(installed.deployments.first?.location) + try FileManager.default.removeItem(at: source) + try FileManager.default.removeItem(at: tree) + _ = try UpdateOperations.restore(scope: .user, environment: f.environment) + let manifest = try #require( + JSONSerialization.jsonObject( + with: Data(contentsOf: tree.appendingPathComponent("gemini-extension.json"))) + as? [String: Any]) + #expect(manifest["version"] as? String == "9.8.7") + } + @Test(arguments: [AgentID.claudeCode, .cursor, .geminiCLI], [false, true]) func generatedPluginPublishesOnlySelectedMembersAndColdRestores( _ agent: AgentID, _ supportingLink: Bool @@ -399,7 +433,6 @@ struct NativeAuthorityIntegrationTests { source: "." path: bundle agents: ["\(agent.rawValue)"] - native: {gemini-cli: {version: "1.2.3"}} - kind: mcpServer name: independent transport: {kind: stdio, executable: fixture-command} @@ -409,6 +442,14 @@ struct NativeAuthorityIntegrationTests { _ = try UpdateOperations.withPreparedUpdate(scope: .user, environment: f.environment) { try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) } + let memberPreview = try #require( + preview.components.first { $0.kind == "plugin" }?.symbolicAfter) + #expect(memberPreview.contains("Target: ")) + #expect(memberPreview.contains(command)) + #expect(memberPreview.contains("Frozen member")) + #expect(memberPreview.contains("skills/helper/SKILL.md")) + #expect(memberPreview.contains("Frozen skill")) + #expect(!memberPreview.contains("\"kind\":\"object\"")) let ledger = try f.store.readLedger() #expect(ledger.lowerings.filter { $0.format.hasSuffix("-generated-plugin@1") }.count == 1) #expect(ledger.deployments.filter { $0.route == "agents/skill@1" }.isEmpty) @@ -446,6 +487,12 @@ struct NativeAuthorityIntegrationTests { "Frozen member")) let restored = try UpdateOperations.inspect(scope: .user, environment: f.environment) #expect(restored.deployments.allSatisfy { $0.status == .current }) + if agent == .geminiCLI { + let native = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: tree.appendingPathComponent(manifest))) + as? [String: Any]) + #expect(native["version"] as? String == "1.2.3") + } if supportingLink { #expect( try String( From 93f1fbb4c5e9df61a276903fd31803b27cc707ff Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:34:21 +0800 Subject: [PATCH 132/171] fix: track external recovery admission inputs --- .../AgentsCore/NativeTargetCoordination.swift | 34 +++++++- Sources/AgentsCore/StateInspection.swift | 8 +- .../InstructionExport.swift | 14 ++-- .../MappingReadLocationsTests.swift | 83 +++++++++++++++++++ 4 files changed, 127 insertions(+), 12 deletions(-) diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index 89e3c41..73630ab 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -537,7 +537,8 @@ final class SharedResource { init( store: StateStore, route: NativeTargetRoute = .claudeMCPLocal, create: Bool, - existingRoot: ExistingProjectRoot? = nil, projectRoot: DirectoryHandle? = nil + existingRoot: ExistingProjectRoot? = nil, projectRoot: DirectoryHandle? = nil, + onReadLocation: ((URL) -> Void)? = nil ) throws { guard route.shared else { throw CoreError.invalidState("project route has no shared resource") } self.route = NativeTargetRoute.targetRoute(route.root)! @@ -552,6 +553,13 @@ final class SharedResource { } ancestry = try DirectoryAccessEvidence.capture(at: url) identity = SharedResourceIdentity(parent: try parent.objectIdentity, basename: route.basename) + // Record the intended private domain before opening it: missing entries or invalid access + // can stop admission before a SharedResource exists. + let baseURL = parent.url.appendingPathComponent(Self.metadataName) + let metadataURL = baseURL.appendingPathComponent(identity.directoryName) + onReadLocation?(baseURL) + onReadLocation?(metadataURL) + onReadLocation?(metadataURL.appendingPathComponent("lock")) func child(_ parent: DirectoryHandle, _ name: String) throws -> DirectoryHandle? { if try parent.info(name) == nil { guard create else { return nil } @@ -940,8 +948,18 @@ extension StateStore { routes: Set, installations: [SkillInstallationTarget] = [], writable: Bool, checkpoint: (String) throws -> Void = { _ in }, existingRoot: ExistingProjectRoot? = nil, projectRoot: DirectoryHandle? = nil, + onReadLocation: ((URL) -> Void)? = nil, _ body: () throws -> T ) throws -> T { + func recordAncestry(_ url: URL) { + guard let onReadLocation else { return } + var ancestor = url.standardizedFileURL + while true { + onReadLocation(ancestor) + guard ancestor.path != "/" else { return } + ancestor.deleteLastPathComponent() + } + } try existingRoot?.validate() if TransactionLockContext.isHeld { throw CoreError.invalidState("nested scope lock acquisition") @@ -990,7 +1008,13 @@ extension StateStore { return leftPending == rightPending ? left.rawValue < right.rawValue : leftPending } let physicalTargets = try ordered.map { route in - try route.physicalDirectory(environment).appendingPathComponent(route.basename) + if onReadLocation != nil { + let authority = try route.rootAuthority(environment, validateExistingOverride: false) + recordAncestry(authority.loader) + recordAncestry(authority.logicalDirectory) + recordAncestry(try authority.plannedPhysicalDirectory) + } + return try route.physicalDirectory(environment).appendingPathComponent(route.basename) } for parent in physicalTargets.map({ $0.deletingLastPathComponent() }) { var ancestor = parent @@ -1026,7 +1050,8 @@ extension StateStore { do { resource = try SharedResource( store: self, route: route, create: writable && !recovering, - existingRoot: existingRoot, projectRoot: projectRoot) + existingRoot: existingRoot, projectRoot: projectRoot, + onReadLocation: onReadLocation) } catch { if recovering { throw CoreError.invalidState( @@ -1066,7 +1091,8 @@ extension StateStore { guard let metadata = resource.metadata else { // No metadata means no prior registered writer. Recheck after the unlocked read. let result = Result { try locked(index + 1) } - let after = try SharedResource(store: self, route: resource.route, create: false) + let after = try SharedResource( + store: self, route: resource.route, create: false, onReadLocation: onReadLocation) guard after.metadata == nil else { return nil } return try result.get() } diff --git a/Sources/AgentsCore/StateInspection.swift b/Sources/AgentsCore/StateInspection.swift index 64c3ab0..40df17d 100644 --- a/Sources/AgentsCore/StateInspection.swift +++ b/Sources/AgentsCore/StateInspection.swift @@ -16,13 +16,19 @@ extension StateStore { /// Pending recovery runs the diagnostic callback instead of inspecting inconsistent state; /// by default it throws `CoreError.recoveryPending`. /// The body may be retried when a first writer creates the scope lock. + /// The location callback reports external shared admission dependencies before opening them, + /// including failed attempts, and may report a location more than once during re-admission. package func withReadLock( onPendingRecovery: (() throws -> T)? = nil, footprint: Set = [], installations: [SkillInstallationTarget] = [], + onReadLocation: ((URL) -> Void)? = nil, _ body: () throws -> T ) throws -> T { - try withCoordination(routes: footprint, installations: installations, writable: false) { + try withCoordination( + routes: footprint, installations: installations, writable: false, + onReadLocation: onReadLocation + ) { try withScopeReadLock(onPendingRecovery: onPendingRecovery, body) } } diff --git a/Sources/AgentsInstructions/InstructionExport.swift b/Sources/AgentsInstructions/InstructionExport.swift index f6b194f..4c52135 100644 --- a/Sources/AgentsInstructions/InstructionExport.swift +++ b/Sources/AgentsInstructions/InstructionExport.swift @@ -55,19 +55,19 @@ extension InstructionOperations { { let store = StateStore(scope: scope, environment: environment) let root = scope == .project ? environment.projectDirectory : environment.homeDirectory - let readLocations = Array( - Set( - (store.readLockLocations + [store.declarationURL, store.resolvedURL, store.watchURL]) - .map(\.standardizedFileURL)) - ).sorted { $0.path < $1.path } + var readLocations = Set( + (store.readLockLocations + [store.declarationURL, store.resolvedURL, store.watchURL]) + .map(\.standardizedFileURL)) + func locations() -> [URL] { readLocations.sorted { $0.path < $1.path } } func empty(_ status: InstructionMapping.Status) -> InstructionMapping { InstructionMapping( scope: scope, root: root, status: status, targets: [], unplaced: [], prompts: [:], - readLocations: readLocations) + readLocations: locations()) } do { return try store.withReadLock( onPendingRecovery: { empty(.pendingRecovery) }, + onReadLocation: { readLocations.insert($0.standardizedFileURL) }, { _ = try store.readDeclaration() guard try store.existingData(store.resolvedURL) != nil else { @@ -104,7 +104,7 @@ extension InstructionOperations { return InstructionMapping( scope: scope, root: root, status: .locked, targets: targets, unplaced: [], - prompts: lock.instructions.chatgpt.mapValues(\.sections), readLocations: readLocations) + prompts: lock.instructions.chatgpt.mapValues(\.sections), readLocations: locations()) }) } catch { return empty(.unavailable(String(describing: error))) diff --git a/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift b/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift index 381b6c2..5a9077b 100644 --- a/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift +++ b/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift @@ -3,10 +3,91 @@ import AgentsInstructions import AgentsManifest import AgentsUpdates import Foundation +import StateTestSupport import Testing @Suite("Instruction mapping read locations") struct MappingReadLocationsTests { + @Test(arguments: [ + "base-absent", "metadata-absent", "lock-absent", "base-access", "metadata-access", + "lock-access", + ]) + func sharedRecoveryAdmissionRepairChangesStatusWithoutChangingScope(_ damage: String) throws { + let f = try InstructionFixture() + let config = f.root.appendingPathComponent("shared-config") + let home = f.project.appendingPathComponent("home") + for directory in [config, home] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let environment = RuntimeEnvironment( + projectDirectory: f.project, homeDirectory: home, + environment: ["CLAUDE_CONFIG_DIR": config.path]) + let store = StateStore(scope: .project, environment: environment) + try store.save(declaration: Declaration(), ledger: ResolvedLedger()) + try f.write("Before", to: f.project.appendingPathComponent("old-data/AGENTS.md")) + var binaryDirectory = Bundle(for: MappingTestBundle.self).bundleURL + while !FileManager.default.isExecutableFile( + atPath: binaryDirectory.appendingPathComponent("StateTestProcess").path), + binaryDirectory.path != "/" + { + binaryDirectory.deleteLastPathComponent() + } + let child = Process() + child.executableURL = binaryDirectory.appendingPathComponent("StateTestProcess") + child.arguments = [ + f.project.path, "shared-install", "shared.ready", "--shared-config", config.path, + ] + child.environment = ProcessInfo.processInfo.environment + try child.run() + defer { do { try ProcessWait.terminate(child) } catch { Issue.record(error) } } + try ProcessWait.marker(f.project.appendingPathComponent("ready"), child: child, root: f.project) + try ProcessWait.terminate(child) + func mapping() throws -> InstructionMapping { + try #require( + InstructionOperations.export(projectRoots: [f.project], environment: environment).last) + } + #expect(try mapping().status == .pendingRecovery) + let base = config.resolvingSymlinksInPath().appendingPathComponent(".agents-native") + let metadata = try #require( + FileManager.default.contentsOfDirectory( + at: base, includingPropertiesForKeys: nil + ).first) + let lock = metadata.appendingPathComponent("lock") + let externalPaths = Set([config, base, metadata, lock].map { $0.standardizedFileURL.path }) + let damaged = damage.hasPrefix("base") ? base : damage.hasPrefix("metadata") ? metadata : lock + let backup = f.root.appendingPathComponent("metadata-backup") + let scopeBefore = try f.snapshot(store.directory) + if damage.hasSuffix("absent") { + try FileManager.default.moveItem(at: damaged, to: backup) + } else { + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: damaged.path) + } + let beforeInspection = try f.snapshot() + let unavailable = try mapping() + guard case .unavailable = unavailable.status else { + Issue.record("Expected failed shared admission, got \(unavailable.status)") + return + } + #expect( + Set(unavailable.readLocations.map(\.path)).isSuperset(of: externalPaths)) + #expect(try f.snapshot() == beforeInspection) + #expect(try f.snapshot(store.directory) == scopeBefore) + if damage.hasSuffix("absent") { + try FileManager.default.moveItem(at: backup, to: damaged) + } else { + try FileManager.default.setAttributes( + [.posixPermissions: damage == "lock-access" ? 0o600 : 0o700], + ofItemAtPath: damaged.path) + } + let repairedBeforeInspection = try f.snapshot() + let repaired = try mapping() + #expect(repaired.status == .pendingRecovery) + #expect( + Set(repaired.readLocations.map(\.path)).isSuperset(of: externalPaths)) + #expect(try f.snapshot(store.directory) == scopeBefore) + #expect(try f.snapshot() == repairedBeforeInspection) + } + @Test func lockedMappingReadsMetadataWithoutContentDependencies() throws { let f = try InstructionFixture() try f.section("shared") @@ -111,3 +192,5 @@ struct MappingReadLocationsTests { #expect(mapping.readLocations.map(\.path) == expected) } } + +private final class MappingTestBundle: NSObject {} From 7c075fb94812a9d8c494d83317fbe39c4dddaac3 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:37:04 +0800 Subject: [PATCH 133/171] feat: expose captured importer choices and symbolic inputs --- .../SourceImportOperations.swift | 281 ++++++++++++++++-- .../Components/Import/ImportFrontmatter.swift | 1 + Sources/Components/Import/ImportInput.swift | 81 ++++- .../Import/NativeCatalogImport.swift | 5 +- .../Import/NativeContainerImport.swift | 15 +- .../Import/NativeExecutableMembers.swift | 2 + .../Components/Import/NativeImportInput.swift | 23 +- .../Import/NativeSourceImport.swift | 30 +- .../Import/RulesyncConfigImport.swift | 24 +- .../Import/RulesyncSourceImport.swift | 13 +- Sources/Components/Import/SourceImport.swift | 11 +- .../Import/SourceImportProposal.swift | 24 +- .../Import/VercelSourceImport.swift | 11 +- .../Components/Import/YAMLSourceImport.swift | 18 +- .../SourceImportSelectionTests.swift | 254 ++++++++++++++++ 15 files changed, 738 insertions(+), 55 deletions(-) create mode 100644 Tests/AgentsUpdatesTests/SourceImportSelectionTests.swift diff --git a/Sources/AgentsUpdates/SourceImportOperations.swift b/Sources/AgentsUpdates/SourceImportOperations.swift index f4e2d69..0967df4 100644 --- a/Sources/AgentsUpdates/SourceImportOperations.swift +++ b/Sources/AgentsUpdates/SourceImportOperations.swift @@ -44,6 +44,7 @@ public struct ImportResourceInspection: Sendable { public let executableFlags: [String: Bool] public let requiresStandaloneSource: Bool public let selected: Bool + public let requiresBindingRewrite: Bool } /// Producer claims remain evidence; they never grant ownership of an existing target. @@ -62,6 +63,8 @@ public struct ImportBindingInspection: Sendable { public let pointer: String public let reason: String public let environmentVariable: String? + /// False means the explicit source/content must be corrected and inspected again. + public let canResolveCanonicalSlot: Bool } public struct ImportSelectionInspection: Sendable { @@ -88,6 +91,81 @@ public struct ImportOrderedSourceInspection: Sendable { public let rules: [String]? } +/// Handles are issued by one immutable inspection and cannot be constructed by consumers. +public struct ImportChoiceID: Hashable, Sendable { + fileprivate let owner: UUID + fileprivate let index: Int +} + +public struct ImportInputID: Hashable, Sendable { + fileprivate let owner: UUID + fileprivate let index: Int +} + +public struct ImportLocationInspection: Sendable { + public let document: String + public let pointer: String + public let span: SourceSpan? +} + +/// Effects from the adapter enumeration. Fixed contributions and unresolved inspection +/// requirements remain relevant when choosing any producer key. +public struct ImportSelectionEffects: Sendable { + public let sources: [ImportSourceInspection] + public let components: [ImportComponentInspection] + public let resources: [ImportResourceInspection] + public let diagnostics: [ImportDiagnosticInspection] +} + +public struct ImportChoiceInspection: Sendable { + public let id: ImportChoiceID + public let label: String + public let locations: [ImportLocationInspection] + public let effects: ImportSelectionEffects + /// Diagnostics emitted by this producer key. Fixed effects and global requirements also + /// participate in admission; an empty list is not permission to publish preserved bytes. + public var hasConversionDiagnostics: Bool { !effects.diagnostics.isEmpty } +} + +public enum ImportInputKind: Sendable { + case sourceCoordinates, explicitContent, bindingReference +} + +/// A binding resolution carries a reference, never the credential value. +public enum ImportBindingReference: Sendable { + case environment(String) + case secret(String) +} + +public struct ImportRequiredInput: Sendable { + public let id: ImportInputID + public let kind: ImportInputKind + public let location: ImportLocationInspection + public let suggestedReference: ImportBindingReference? +} + +/// Source coordinates are accepted only for Git-coordinate requirements. Content paths +/// stay relative to the explicit input root and are re-read by the owning adapter. +public enum ImportInputValue: Sendable { + case source(SourceDeclaration) + case content(path: String) + case binding(ImportBindingReference) +} + +public struct ImportInputResolution: Sendable { + public let id: ImportInputID + public let value: ImportInputValue + public init(id: ImportInputID, value: ImportInputValue) { + self.id = id + self.value = value + } +} + +private enum ImportResolutionTarget: Sendable { + case adapter(ImportInputMetadata) + case binding(String) +} + public struct SourceImportInspection: Sendable { public let format: String public let producerRevision: String? @@ -101,26 +179,26 @@ public struct SourceImportInspection: Sendable { public let selections: [ImportSelectionInspection] public let orderedSources: [ImportOrderedSourceInspection] public let readLocations: [URL] + /// Actual adapter selection units; several component families can share one choice. + public let availableChoices: [ImportChoiceInspection] + /// Only supported missing inputs receive handles. Other requirements remain in bindings + /// or diagnostics and require a corrected explicit input, followed by reinspection. + public let requiredInputs: [ImportRequiredInput] + /// Contributions emitted independently of the adapter selection, including preserved inputs. + public let fixedEffects: ImportSelectionEffects + private let owner: UUID + private let choiceKeys: [String] + private let resolutionTargets: [ImportResolutionTarget] private let preparation: ImportPreparation /// Merges selected canonical intent into the same captured full declaration. Unconverted - /// semantics and required bindings must be resolved by another explicit input selection. + /// semantics and required bindings must be resolved through supported inputs. Preserved + /// resources requiring a binding rewrite need corrected content, even after slot resolution. public func updateRequest(in inspection: ScopeInspection) throws -> UpdateRequest { guard !inspection.recovery.pending, var declaration = inspection.declaration else { throw CoreError.invalidState("inspect the committed scope before preparing an import") } - guard diagnostics.isEmpty, bindings.isEmpty else { - throw CoreError.invalidState( - "import has unresolved conversion diagnostics or binding requirements") - } - guard - !preparation.proposal.resources.contains(where: { - $0.selected && $0.producerIntegrity != nil && $0.observedHash == nil - }) - else { - throw CoreError.invalidState( - "import requires verified captured content for the producer integrity claim") - } + try preparation.validateConversion() for source in preparation.proposal.sources { guard var imported = source.declaration else { throw CoreError.invalidState("import lacks exact canonical source coordinates") @@ -156,7 +234,61 @@ public struct SourceImportInspection: Sendable { return request } - init(_ proposal: SourceImportProposal, preparation: ImportPreparation) { + /// Revalidates the captured inputs, then reruns the same adapter with owner-issued choices. + /// Nil choices preserve the current selection; an empty list uses the adapter's empty semantics. + public func resolving( + choices: [ImportChoiceID]? = nil, inputs: [ImportInputResolution] = [] + ) throws -> SourceImportInspection { + _ = try preparation.capture(admitConversion: false) + var input = preparation.input + if let choices { + guard Set(choices).count == choices.count, + choices.allSatisfy({ $0.owner == owner && choiceKeys.indices.contains($0.index) }) + else { throw CoreError.invalidState("import choices belong to another inspection") } + input.selection = Set(choices.map { choiceKeys[$0.index] }) + } + guard Set(inputs.map(\.id)).count == inputs.count else { + throw CoreError.invalidState("import input was supplied more than once") + } + for resolution in inputs { + guard resolution.id.owner == owner, resolutionTargets.indices.contains(resolution.id.index) + else { throw CoreError.invalidState("import input belongs to another inspection") } + switch (resolutionTargets[resolution.id.index], resolution.value) { + case (.adapter(let requirement), .source(let declaration)) + where requirement.kind == .gitSource: + guard SourceImport.admitsSourceCoordinates(declaration) else { + throw CoreError.invalidSource("import requires Git source coordinates") + } + input.sourceDeclarations[requirement.key] = declaration + case (.adapter(let requirement), .content(let path)) + where requirement.kind == .installedContent: + _ = try PathSafety.resolvedChild(base: input.root, subpath: path) + input.installedSkills[requirement.key] = path + case (.binding(let key), .binding(let reference)): + let value: RuntimeBinding + switch reference { + case .environment(let name): + guard !name.isEmpty, + name.range(of: #"^[A-Za-z_][A-Za-z0-9_]*$"#, options: .regularExpression) != nil + else { throw CoreError.invalidState("invalid symbolic environment reference") } + value = .environment(name) + case .secret(let name): + guard !name.isEmpty, + !name.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }) + else { throw CoreError.invalidState("invalid symbolic secret reference") } + value = .secret(name) + } + input.bindingReferences[key] = value + default: throw CoreError.invalidState("import input value has the wrong supported kind") + } + } + return try SourceImportOperations.inspect(input) + } + + init( + _ proposal: SourceImportProposal, preparation: ImportPreparation, + catalog: SourceImportProposal? = nil + ) { self.preparation = preparation format = proposal.profile.rawValue producerRevision = proposal.profile.producerRevision @@ -187,7 +319,7 @@ public struct SourceImportInspection: Sendable { producerName: $0.producerName, path: $0.path, hash: $0.observedHash, integrityKind: $0.producerIntegrity?.kind.rawValue, integrity: $0.producerIntegrity?.value, executableFlags: $0.executableFlags, requiresStandaloneSource: $0.requiresStandaloneSource, - selected: $0.selected) + selected: $0.selected, requiresBindingRewrite: $0.requiresBindingRewrite) } deployments = proposal.deployments.map { .init( @@ -198,7 +330,9 @@ public struct SourceImportInspection: Sendable { bindings = proposal.bindings.map { .init( document: $0.location.document, - pointer: $0.location.pointer, reason: $0.reason, environmentVariable: $0.environmentVariable + pointer: $0.location.pointer, reason: $0.reason, + environmentVariable: $0.environmentVariable, + canResolveCanonicalSlot: $0.canonicalSlot ) } selections = proposal.selections.map { @@ -215,22 +349,110 @@ public struct SourceImportInspection: Sendable { rulesPath: $0.rulesPath, skills: $0.skills, rules: $0.rules) } readLocations = preparation.locations + let issued = UUID() + owner = issued + choiceKeys = catalog?.choices.map(\.key) ?? [] + var targets: [ImportResolutionTarget] = [] + var requirements: [ImportRequiredInput] = [] + for item in proposal.requiredInputs { + let index = targets.count + targets.append(.adapter(item)) + requirements.append( + .init( + id: .init(owner: issued, index: index), + kind: item.kind == .gitSource ? .sourceCoordinates : .explicitContent, + location: .init( + document: item.location.document, pointer: item.location.pointer, + span: item.location.span), + suggestedReference: nil)) + } + for item in proposal.bindings { + guard item.canonicalSlot, let key = item.key else { continue } + let index = targets.count + targets.append(.binding(key)) + requirements.append( + .init( + id: .init(owner: issued, index: index), kind: .bindingReference, + location: .init( + document: item.location.document, pointer: item.location.pointer, + span: item.location.span), + suggestedReference: item.environmentVariable.map(ImportBindingReference.environment))) + } + resolutionTargets = targets + requiredInputs = requirements + if let catalog { + let view = SourceImportInspection(catalog, preparation: preparation) + func effects(_ component: [Int], _ source: [Int], _ resource: [Int], _ diagnostic: [Int]) + -> ImportSelectionEffects + { + .init( + sources: source.map { view.sources[$0] }, + components: component.map { view.components[$0] }, + resources: resource.map { view.resources[$0] }, + diagnostics: diagnostic.map { view.diagnostics[$0] }) + } + availableChoices = catalog.choices.enumerated().map { index, choice in + .init( + id: .init(owner: issued, index: index), label: "Producer selection \(index + 1)", + locations: choice.locations.map { + .init(document: $0.document, pointer: $0.pointer, span: $0.span) + }, + effects: effects(choice.components, choice.sources, choice.resources, choice.diagnostics)) + } + let assignedComponents = Set(catalog.choices.flatMap(\.components)) + let assignedSources = Set(catalog.choices.flatMap(\.sources)) + let assignedResources = Set(catalog.choices.flatMap(\.resources)) + let assignedDiagnostics = Set(catalog.choices.flatMap(\.diagnostics)) + fixedEffects = effects( + catalog.components.indices.filter { !assignedComponents.contains($0) }, + catalog.sources.indices.filter { !assignedSources.contains($0) }, + catalog.resources.indices.filter { !assignedResources.contains($0) }, + catalog.diagnostics.indices.filter { !assignedDiagnostics.contains($0) }) + } else { + availableChoices = [] + fixedEffects = .init( + sources: sources, components: components, resources: resources, diagnostics: diagnostics) + } } } package struct ImportPreparation: Sendable { let input: SourceImportInput let proposal: SourceImportProposal + let catalog: SourceImportProposal let documentFingerprint: String let locations: [URL] - func capture() throws -> [TargetPrecondition] { + func validateConversion() throws { + guard proposal.diagnostics.isEmpty, proposal.bindings.isEmpty else { + throw CoreError.invalidState( + "import has unresolved conversion diagnostics or binding requirements") + } + guard !proposal.resources.contains(where: { $0.selected && $0.requiresBindingRewrite }) else { + throw CoreError.invalidState( + "import preserved resources require corrected explicit content before publication") + } + guard + !proposal.resources.contains(where: { + $0.selected && $0.producerIntegrity != nil && $0.observedHash == nil + }) + else { + throw CoreError.invalidState( + "import requires verified captured content for the producer integrity claim") + } + } + + func capture(admitConversion: Bool = true) throws -> [TargetPrecondition] { let document = try PathSafety.resolvedChild(base: input.root, subpath: input.document) let evidence = try TargetPrecondition(document) let inputs = try locations.map { try TargetPrecondition($0) } + var enumeration = input + enumeration.enumerateChoices = true + enumeration.selection = nil guard try evidence.displayEvidence(includeContent: true) == documentFingerprint, - try SourceImport.preview(input) == proposal + try SourceImport.preview(input) == proposal, try SourceImport.preview(enumeration) == catalog else { throw CoreError.invalidState("import inputs changed; refresh the import inspection") } + if admitConversion { try validateConversion() } try evidence.validate() for input in inputs { try input.validate() } return inputs @@ -251,15 +473,30 @@ public enum SourceImportOperations { profile: profile, root: root, document: document, selection: selection, sourceDeclarations: sourceDeclarations, installedSkills: installedSkills ) + return try inspect(input) + } + + static func inspect(_ input: SourceImportInput) throws -> SourceImportInspection { + guard input.sourceDeclarations.values.allSatisfy(SourceImport.admitsSourceCoordinates) else { + throw CoreError.invalidSource("import source coordinates are not admitted") + } + let root = input.root + let document = input.document + let installedSkills = input.installedSkills let url = try PathSafety.resolvedChild(base: root, subpath: document) let evidence = try TargetPrecondition(url) let fingerprint = try evidence.displayEvidence(includeContent: true) let proposal = try SourceImport.preview(input) + var enumeration = input + enumeration.selection = nil + enumeration.enumerateChoices = true + let catalog = try SourceImport.preview(enumeration) var locations = [url] for path in installedSkills.values { locations.append(try PathSafety.resolvedChild(base: root, subpath: path)) } - for source in proposal.sources.compactMap(\.declaration) where source.kind == .local { + for source in (proposal.sources + catalog.sources).compactMap(\.declaration) + where source.kind == .local { let environment = source.environment?.runtime ?? RuntimeEnvironment(projectDirectory: root, environment: [:]) let identity = try source.identity(environment: environment) @@ -268,10 +505,10 @@ public enum SourceImportOperations { } } let preparation = ImportPreparation( - input: input, proposal: proposal, + input: input, proposal: proposal, catalog: catalog, documentFingerprint: fingerprint, locations: Array(Set(locations)).sorted { $0.path < $1.path }) - _ = try preparation.capture() - return SourceImportInspection(proposal, preparation: preparation) + _ = try preparation.capture(admitConversion: false) + return SourceImportInspection(proposal, preparation: preparation, catalog: catalog) } } diff --git a/Sources/Components/Import/ImportFrontmatter.swift b/Sources/Components/Import/ImportFrontmatter.swift index 738ea7d..bb8a670 100644 --- a/Sources/Components/Import/ImportFrontmatter.swift +++ b/Sources/Components/Import/ImportFrontmatter.swift @@ -12,6 +12,7 @@ enum ImportFrontmatter { let parsed = try read(bytes, document: document, limits: limits) var diagnostics = ImportDiagnostics(proposal: .init(profile: profile)) parsed.header?.unknown(converted, into: &diagnostics) + diagnostics.finalizeBindings() return (diagnostics.proposal.diagnostics, diagnostics.proposal.bindings) } diff --git a/Sources/Components/Import/ImportInput.swift b/Sources/Components/Import/ImportInput.swift index c82cc57..6ec8906 100644 --- a/Sources/Components/Import/ImportInput.swift +++ b/Sources/Components/Import/ImportInput.swift @@ -141,6 +141,83 @@ enum ImportReadFailure: Error { case invalid } struct ImportDiagnostics { var proposal: SourceImportProposal + var bindingReferences: [String: RuntimeBinding] = [:] + var resolvedBindings: Set = [] + + struct CanonicalAttempt { + let components: Int + let slots: Set + let resolved: Set + } + + func beginCanonicalAttempt() -> CanonicalAttempt { + .init( + components: proposal.components.count, + slots: Set(proposal.bindings.filter(\.canonicalSlot).map(\.location)), + resolved: resolvedBindings) + } + + mutating func endCanonicalAttempt(_ attempt: CanonicalAttempt) { + guard proposal.components.count <= attempt.components else { return } + for index in proposal.bindings.indices + where !attempt.slots.contains(proposal.bindings[index].location) { + proposal.bindings[index].canonicalSlot = false + } + resolvedBindings = attempt.resolved + } + + struct ChoiceCapture { + let index: Int + let components: Int + let sources: Int + let resources: Int + let diagnostics: Int + } + + mutating func beginChoice(_ key: String, at location: ImportLocation) -> ChoiceCapture { + let index: Int + if let found = proposal.choices.firstIndex(where: { $0.key.utf8.elementsEqual(key.utf8) }) { + index = found + if !proposal.choices[index].locations.contains(location) { + proposal.choices[index].locations.append(location) + } + } else { + index = proposal.choices.count + proposal.choices.append(.init(key: key, locations: [location])) + } + return .init( + index: index, components: proposal.components.count, sources: proposal.sources.count, + resources: proposal.resources.count, diagnostics: proposal.diagnostics.count) + } + + mutating func endChoice(_ capture: ChoiceCapture) { + proposal.choices[capture.index].components += Array( + capture.components.. 1 { diagnostics.add( diff --git a/Sources/Components/Import/NativeContainerImport.swift b/Sources/Components/Import/NativeContainerImport.swift index f31ce01..4e15019 100644 --- a/Sources/Components/Import/NativeContainerImport.swift +++ b/Sources/Components/Import/NativeContainerImport.swift @@ -152,8 +152,8 @@ enum NativeContainerImport { let relative = root == "." ? document.input.document : String(document.input.document.dropFirst(root.count + 1)) - let rewrite = diagnostics.proposal.bindings.contains { - $0.location.document == document.input.document + let rewrite = diagnostics.proposal.preservationBindings.contains { + $0.document == document.input.document } try NativeImportInput.resource( relative, root: root, input: input, origin: document.location(), limits: limits, @@ -210,8 +210,8 @@ enum NativeContainerImport { let path = root == "." ? document.input.document : String(document.input.document.dropFirst(root.count + 1)) - let rewrite = diagnostics.proposal.bindings.contains { - $0.location.document == document.input.document + let rewrite = diagnostics.proposal.preservationBindings.contains { + $0.document == document.input.document } try NativeImportInput.resource( path, root: root, input: input, origin: document.location(), limits: limits, @@ -260,7 +260,9 @@ enum NativeContainerImport { } } // Record the actual manifest, not a raw original bundle containing credential literals. - let rewrite = diagnostics.proposal.bindings.contains { $0.location.document == input.document } + let rewrite = diagnostics.proposal.preservationBindings.contains { + $0.document == input.document + } try NativeImportInput.resource( suffix, root: root, input: input, origin: parsed.location(), limits: limits, rewrite: rewrite, into: &diagnostics, admission: parsed.admission) @@ -420,6 +422,9 @@ enum NativeContainerImport { let content = try ImportSkillContent.read(skillPath, input: input, limits: limits) diagnostics.proposal.diagnostics += content.diagnostics diagnostics.proposal.bindings += content.bindings + diagnostics.proposal.preservationBindings += content.bindings.filter { + $0.environmentVariable == nil + }.map(\.location) if !content.bindings.isEmpty { continue } let alias = "native-skill-" + String(diagnostics.proposal.sources.count) diagnostics.proposal.sources.append( diff --git a/Sources/Components/Import/NativeExecutableMembers.swift b/Sources/Components/Import/NativeExecutableMembers.swift index a35fba0..12b4858 100644 --- a/Sources/Components/Import/NativeExecutableMembers.swift +++ b/Sources/Components/Import/NativeExecutableMembers.swift @@ -130,6 +130,8 @@ extension NativeSourceImport { try classifyMembers(value, parsed: parsed, keys: keys, into: &diagnostics) for name in servers.keys.sorted() { let origin = try parsed.memberLocation(keys, name: name) + let canonicalAttempt = diagnostics.beginCanonicalAttempt() + defer { diagnostics.endCanonicalAttempt(canonicalAttempt) } guard NativeImportInput.name(name), let fields = servers[name]?.importObject else { NativeImportInput.unconverted(servers[name]!, at: origin, into: &diagnostics) continue diff --git a/Sources/Components/Import/NativeImportInput.swift b/Sources/Components/Import/NativeImportInput.swift index 39bc382..411a444 100644 --- a/Sources/Components/Import/NativeImportInput.swift +++ b/Sources/Components/Import/NativeImportInput.swift @@ -162,7 +162,7 @@ enum NativeImportInput { } static func binding( - _ location: ImportLocation, environment: String? = nil, + _ location: ImportLocation, environment: String? = nil, canonical: Bool = true, into diagnostics: inout ImportDiagnostics ) -> RuntimeBinding { let key = @@ -170,6 +170,15 @@ enum NativeImportInput { diagnostics.binding(location, environmentVariable: environment) if let index = diagnostics.proposal.bindings.firstIndex(where: { $0.location == location }) { diagnostics.proposal.bindings[index].key = key + if canonical { diagnostics.proposal.bindings[index].canonicalSlot = true } + } + if canonical, let reference = diagnostics.bindingReferences[key] { + switch reference { + case .environment, .secret: + diagnostics.resolvedBindings.insert(location) + return reference + case .literal: break + } } return environment.map(RuntimeBinding.environment) ?? .secret(key) } @@ -213,7 +222,7 @@ enum NativeImportInput { "Native interpolation is not a single admitted symbolic environment reference.") throw ImportReadFailure.invalid } else { - result[key] = binding(item, into: &diagnostics) + result[key] = binding(item, canonical: !literalsOnly, into: &diagnostics) } } } @@ -308,9 +317,9 @@ enum NativeImportInput { })?.producerPath else { continue } let relative = root == "." ? path : root + (path == "." ? "" : "/" + path) - if diagnostics.proposal.bindings.contains(where: { - relative == "." || $0.location.document == relative - || $0.location.document.hasPrefix(relative + "/") + if diagnostics.proposal.preservationBindings.contains(where: { + relative == "." || $0.document == relative + || $0.document.hasPrefix(relative + "/") }) { diagnostics.proposal.resources[index].requiresBindingRewrite = true diagnostics.proposal.resources[index].observedHash = nil @@ -331,8 +340,8 @@ enum NativeImportInput { try admission?.resource(url, snapshot: snapshot) let needsRewrite = rewrite - || diagnostics.proposal.bindings.contains { - $0.location.document == relative || $0.location.document.hasPrefix(relative + "/") + || diagnostics.proposal.preservationBindings.contains { + $0.document == relative || $0.document.hasPrefix(relative + "/") || relative == "." } let frozen = try LedgerResources.capture( diff --git a/Sources/Components/Import/NativeSourceImport.swift b/Sources/Components/Import/NativeSourceImport.swift index 7017397..5d061fb 100644 --- a/Sources/Components/Import/NativeSourceImport.swift +++ b/Sources/Components/Import/NativeSourceImport.swift @@ -104,8 +104,8 @@ enum NativeSourceImport { } NativeImportInput.unknown( parsed.fields, allowed: converted, at: parsed.location(), into: &diagnostics) - let privateInput = diagnostics.proposal.bindings.contains { - $0.location.document == input.document + let privateInput = diagnostics.proposal.preservationBindings.contains { + $0.document == input.document } try NativeImportInput.resource( input.document, root: root, input: input, origin: parsed.location(), @@ -140,13 +140,20 @@ enum NativeSourceImport { let agent = NativeImportInput.agent(parsed.input.profile) for name in servers.keys.sorted() { try Task.checkCancellation() - if ![SourceImportProfile.claudePluginV1, .cursorPluginV1, .geminiExtensionV1].contains( - parsed.input.profile), + let selectable = ![SourceImportProfile.claudePluginV1, .cursorPluginV1, .geminiExtensionV1] + .contains(parsed.input.profile) + let choice = + selectable && NativeImportInput.name(name) + ? diagnostics.beginChoice(name, at: try parsed.memberLocation(keys, name: name)) : nil + defer { if let choice { diagnostics.endChoice(choice) } } + if selectable, !parsed.input.enumerateChoices, !(parsed.input.selection?.contains(name) ?? true) { continue } let location = try parsed.memberLocation(keys, name: name) + let canonicalAttempt = diagnostics.beginCanonicalAttempt() + defer { diagnostics.endCanonicalAttempt(canonicalAttempt) } guard NativeImportInput.name(name), case .object(let fields) = servers[name] else { NativeImportInput.unconverted(servers[name]!, at: location, into: &diagnostics) continue @@ -360,7 +367,8 @@ enum NativeSourceImport { profile: parsed.input.profile, resources: resourceCoordinates) if let bearer = extra["bearer_token_env_var"]?.importString { _ = NativeImportInput.binding( - location.appending("bearer_token_env_var"), environment: bearer, into: &diagnostics) + location.appending("bearer_token_env_var"), environment: bearer, canonical: false, + into: &diagnostics) } NativeImportInput.emit( .mcpServer(name: name, transport: transport, agents: [agent], native: native), @@ -396,8 +404,12 @@ enum NativeSourceImport { guard case .object(let entries) = value else { throw ImportReadFailure.invalid } try classifyMembers(value, parsed: parsed, keys: [key], into: &diagnostics) for (index, name) in entries.keys.sorted().enumerated() { - guard parsed.input.selection?.contains(name) ?? true else { continue } let origin = parsed.location([key, name], display: "/\(key)/member[\(index)]") + let choice = NativeImportInput.name(name) ? diagnostics.beginChoice(name, at: origin) : nil + defer { if let choice { diagnostics.endChoice(choice) } } + guard parsed.input.enumerateChoices || (parsed.input.selection?.contains(name) ?? true) else { + continue + } guard NativeImportInput.name(name), let fields = entries[name]?.importObject else { NativeImportInput.unconverted(entries[name]!, at: origin, into: &diagnostics) continue @@ -471,8 +483,12 @@ enum NativeSourceImport { guard case .object(let agents) = value else { throw ImportReadFailure.invalid } try classifyMembers(value, parsed: parsed, keys: ["agents"], into: &diagnostics) for (index, name) in agents.keys.sorted().enumerated() { - guard parsed.input.selection?.contains(name) ?? true else { continue } let origin = parsed.location(["agents", name], display: "/agents/member[\(index)]") + let choice = NativeImportInput.name(name) ? diagnostics.beginChoice(name, at: origin) : nil + defer { if let choice { diagnostics.endChoice(choice) } } + guard parsed.input.enumerateChoices || (parsed.input.selection?.contains(name) ?? true) else { + continue + } guard NativeImportInput.name(name), let fields = agents[name]?.importObject, Set(fields.keys).isSubset(of: ["description", "config_file"]), let description = fields["description"]?.importString, diff --git a/Sources/Components/Import/RulesyncConfigImport.swift b/Sources/Components/Import/RulesyncConfigImport.swift index a8e0495..7f9ef7c 100644 --- a/Sources/Components/Import/RulesyncConfigImport.swift +++ b/Sources/Components/Import/RulesyncConfigImport.swift @@ -81,6 +81,12 @@ extension NativeValue { } enum RulesyncConfigImport { + static func npmSelector(_ value: String) -> Bool { + value.range( + of: #"^(@[a-z0-9~][a-z0-9._~-]*/)?[a-z0-9~][a-z0-9._~-]*$"#, options: .regularExpression) + != nil + } + static func read( _ input: SourceImportInput, limits: SourceImportLimits, into diagnostics: inout ImportDiagnostics @@ -166,7 +172,16 @@ enum RulesyncConfigImport { .invalidInput, location, "Source fields require producer string identity.") continue } - if let selection = parsed.input.selection, !selection.contains(raw) { continue } + let admissibleKey = + object["transport"]?.importString == "npm" + ? npmSelector(raw) : (ImportInput.safeLocator(raw) || githubLocator(raw) != nil) + let choice = admissibleKey ? diagnostics.beginChoice(raw, at: location) : nil + defer { if let choice { diagnostics.endChoice(choice) } } + if !parsed.input.enumerateChoices, let selection = parsed.input.selection, + !selection.contains(raw) + { + continue + } let transport = object["transport"]?.importString ?? "github" guard ["github", "git", "npm"].contains(transport), object["skills"] == nil || object["skills"]?.importStrings != nil, @@ -245,10 +260,7 @@ enum RulesyncConfigImport { } declaration = .init(kind: .git, location: raw) } else { - guard - raw.range( - of: #"^(@[a-z0-9~][a-z0-9._~-]*/)?[a-z0-9~][a-z0-9._~-]*$"#, - options: .regularExpression) != nil + guard npmSelector(raw) else { diagnostics.add(.invalidInput, location, "Invalid npm source package selector.") continue @@ -324,6 +336,8 @@ enum RulesyncConfigImport { } var winners: Set = [] for (intent, declaration, lockKey) in entries { + let choice = diagnostics.beginChoice(intent.identity, at: intent.origin) + defer { diagnostics.endChoice(choice) } let key = (intent.transport == "npm" ? "npm:" : "git:") + lockKey var match = locked[key] if let candidate = match { diff --git a/Sources/Components/Import/RulesyncSourceImport.swift b/Sources/Components/Import/RulesyncSourceImport.swift index 273c09e..0a75d28 100644 --- a/Sources/Components/Import/RulesyncSourceImport.swift +++ b/Sources/Components/Import/RulesyncSourceImport.swift @@ -23,8 +23,19 @@ enum RulesyncSourceImport { } for (index, key) in sources.keys.sorted().enumerated() { try Task.checkCancellation() - guard input.selection?.contains(key) ?? true else { continue } let location = origin.appending("sources/member[\(index)]") + let repositoryKey = key.components(separatedBy: "#")[0] + let admissibleKey = + npm + ? RulesyncConfigImport.npmSelector(key) + : (ImportInput.safeLocator(repositoryKey) + || RulesyncConfigImport.githubLocator(repositoryKey) != nil) + let choice = admissibleKey ? diagnostics.beginChoice(key, at: location) : nil + defer { if let choice { diagnostics.endChoice(choice) } } + guard input.enumerateChoices || (input.selection?.contains(key) ?? true) else { continue } + if admissibleKey, !npm, input.sourceDeclarations[key] == nil { + diagnostics.requireInput(.gitSource, key: key, at: location) + } guard let entry = sources[key] as? [String: Any] else { diagnostics.add(.invalidInput, location, "Expected a locked source object.") continue diff --git a/Sources/Components/Import/SourceImport.swift b/Sources/Components/Import/SourceImport.swift index 47407e7..03c4182 100644 --- a/Sources/Components/Import/SourceImport.swift +++ b/Sources/Components/Import/SourceImport.swift @@ -3,6 +3,12 @@ import AgentsManifest import Foundation package enum SourceImport { + package static func admitsSourceCoordinates(_ source: SourceDeclaration) -> Bool { + source.kind == .git && ImportInput.safeLocator(source.location) + && (try? source.transportIdentity()) != nil + && (source.path.map { (try? ImportInput.path($0)) != nil } ?? true) + } + /// First explicit config is the project config; the optional second is its local override. /// Each document retains its caller-selected boundary. No ambient config or lock is discovered. package static func previewRulesync( @@ -26,6 +32,7 @@ package enum SourceImport { .invalidInput, .init(document: configs.first?.document ?? "", pointer: ""), "Explicit rulesync inputs are not admitted.") } + diagnostics.finalizeBindings() return diagnostics.proposal } @@ -36,7 +43,8 @@ package enum SourceImport { ) throws -> SourceImportProposal { try Task.checkCancellation() let origin = ImportLocation(document: input.document, pointer: "") - var diagnostics = ImportDiagnostics(proposal: .init(profile: input.profile)) + var diagnostics = ImportDiagnostics( + proposal: .init(profile: input.profile), bindingReferences: input.bindingReferences) do { _ = try ImportInput.path(input.document) switch input.profile { @@ -71,6 +79,7 @@ package enum SourceImport { diagnostics.add( .invalidInput, origin, "Input is not an admitted, readable producer document.") } + diagnostics.finalizeBindings() return diagnostics.proposal } } diff --git a/Sources/Components/Import/SourceImportProposal.swift b/Sources/Components/Import/SourceImportProposal.swift index 0498744..5e882bb 100644 --- a/Sources/Components/Import/SourceImportProposal.swift +++ b/Sources/Components/Import/SourceImportProposal.swift @@ -51,7 +51,7 @@ package enum SourceImportProfile: String, Sendable { } } -package struct ImportLocation: Equatable, Sendable { +package struct ImportLocation: Hashable, Sendable { package let document: String /// Object-map entries use sorted member ordinals, so credential-bearing keys are never echoed. package let pointer: String @@ -80,6 +80,7 @@ package struct ImportBindingRequirement: Equatable, Sendable { package var environmentVariable: String? = nil /// Identifier used by RuntimeBinding.secret; the literal remains outside the proposal. package var key: String? = nil + package var canonicalSlot = false } package struct ImportPin: Equatable, Sendable { @@ -207,6 +208,9 @@ package struct SourceImportProposal: Equatable, Sendable { package var selections: [ImportProducerSelection] = [] package var deployments: [ImportDeploymentEvidence] = [] package var orderedSources: [ImportOrderedSource] = [] + package var choices: [ImportChoiceMetadata] = [] + package var requiredInputs: [ImportInputMetadata] = [] + package var preservationBindings: [ImportLocation] = [] } package struct SourceImportInput: Sendable { @@ -217,6 +221,8 @@ package struct SourceImportInput: Sendable { /// Nil selects every entry; empty selects none. JSON maps use producer keys, YAML lists use /// decimal ordinals, and rulesync config sources use their explicit source selector. package var selection: Set? = nil + package var enumerateChoices = false + package var bindingReferences: [String: RuntimeBinding] = [:] /// Source lock keys do not reliably identify a transport/provider. These are explicit input, /// normally supplied by the config adapter, and never inferred from a normalized lock key. package var sourceDeclarations: [String: SourceDeclaration] = [:] @@ -279,3 +285,19 @@ package struct ImportOrderedSource: Equatable, Sendable { package let skills: [String]? package let rules: [String]? } + +package struct ImportChoiceMetadata: Equatable, Sendable { + package let key: String + package var locations: [ImportLocation] + package var components: [Int] = [] + package var sources: [Int] = [] + package var resources: [Int] = [] + package var diagnostics: [Int] = [] +} + +package struct ImportInputMetadata: Equatable, Sendable { + package enum Kind: String, Sendable { case gitSource, installedContent } + package let kind: Kind + package let key: String + package let location: ImportLocation +} diff --git a/Sources/Components/Import/VercelSourceImport.swift b/Sources/Components/Import/VercelSourceImport.swift index 8461154..83d07fe 100644 --- a/Sources/Components/Import/VercelSourceImport.swift +++ b/Sources/Components/Import/VercelSourceImport.swift @@ -30,8 +30,16 @@ enum VercelSourceImport { } for (index, name) in skills.keys.sorted().enumerated() { try Task.checkCancellation() - guard input.selection?.contains(name) ?? true else { continue } let location = origin.appending("skills/member[\(index)]") + let choice = ImportInput.name(name) ? diagnostics.beginChoice(name, at: location) : nil + defer { if let choice { diagnostics.endChoice(choice) } } + guard input.enumerateChoices || (input.selection?.contains(name) ?? true) else { continue } + var contentAdmitted = false + defer { + if ImportInput.name(name), !contentAdmitted { + diagnostics.requireInput(.installedContent, key: name, at: location) + } + } guard ImportInput.name(name), let entry = skills[name] as? [String: Any], let source = ImportInput.string(entry["source"]), let sourceType = ImportInput.string(entry["sourceType"]) @@ -159,6 +167,7 @@ enum VercelSourceImport { "Captured actual local content has a SHA-256 pin; the recorded GitHub tree hash is not verified." ) } + contentAdmitted = true let contentAlias = alias + "-content" diagnostics.proposal.sources.append( .init( diff --git a/Sources/Components/Import/YAMLSourceImport.swift b/Sources/Components/Import/YAMLSourceImport.swift index 54a8360..ce70c95 100644 --- a/Sources/Components/Import/YAMLSourceImport.swift +++ b/Sources/Components/Import/YAMLSourceImport.swift @@ -266,7 +266,11 @@ enum YAMLSourceImport { for (index, item) in items.enumerated() { try Task.checkCancellation() let alias = "apm-\(group)-\(index)" - guard input.selection?.contains(String(index)) ?? true else { continue } + let choice = diagnostics.beginChoice(String(index), at: item.location) + defer { diagnostics.endChoice(choice) } + guard input.enumerateChoices || (input.selection?.contains(String(index)) ?? true) else { + continue + } let development = group == "devDependencies" let raw: String var requested: String? @@ -484,7 +488,11 @@ enum YAMLSourceImport { } for (index, item) in items.enumerated() { try Task.checkCancellation() - guard input.selection?.contains(String(index)) ?? true else { continue } + let choice = diagnostics.beginChoice(String(index), at: item.location) + defer { diagnostics.endChoice(choice) } + guard input.enumerateChoices || (input.selection?.contains(String(index)) ?? true) else { + continue + } guard item.pairs != nil, let repo = item["repo_url"]?.string else { diagnostics.add(.invalidInput, item.location, "Expected a locked repository entry.") continue @@ -626,7 +634,11 @@ enum YAMLSourceImport { } for (index, item) in items.enumerated() { try Task.checkCancellation() - guard input.selection?.contains(String(index)) ?? true else { continue } + let choice = diagnostics.beginChoice(String(index), at: item.location) + defer { diagnostics.endChoice(choice) } + guard input.enumerateChoices || (input.selection?.contains(String(index)) ?? true) else { + continue + } item.unknown( [ "source", "owner", "repo", "agent", "scope", "skill", "requested_ref", "resolved_ref", diff --git a/Tests/AgentsUpdatesTests/SourceImportSelectionTests.swift b/Tests/AgentsUpdatesTests/SourceImportSelectionTests.swift new file mode 100644 index 0000000..03853ad --- /dev/null +++ b/Tests/AgentsUpdatesTests/SourceImportSelectionTests.swift @@ -0,0 +1,254 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsUpdates +@testable import Components + +struct SourceImportSelectionTests { + @Test func oneProducerKeyShowsEveryFamilyAndFixedContributions() throws { + let f = try ImportSelectionFixture() + let text = + #"{"mcp":{"servers":{"same":{"type":"local","command":["never-run"]}}},"commands":{"same":{"template":"Review"},"other":{"template":"Other"}},"agents":{"same":{"system":"Review","mode":"subagent"}},"lsp":{"fixed":{"command":["never-run"]}}}"# + try f.write("opencode.json", text) + let before = try FileHash.folderHash(f.root) + let report = try SourceImportOperations.inspect( + format: "openCodeConfigV2", root: f.root, document: "opencode.json") + let shared = try #require(report.availableChoices.first { $0.effects.components.count == 3 }) + #expect( + Set(shared.effects.components.map(\.declaration.kind)) == [.mcpServer, .command, .subagent]) + #expect(report.fixedEffects.components.map(\.declaration.kind) == [.lspServer]) + let selected = try report.resolving(choices: [shared.id]) + #expect(selected.components.count == 4) + let empty = try report.resolving(choices: []) + #expect(empty.components.map(\.declaration.kind) == [.lspServer]) + #expect(throws: (any Error).self) { try selected.resolving(choices: [shared.id]) } + #expect(try FileHash.folderHash(f.root) == before) + try f.write("opencode.json", "{}") + #expect(throws: (any Error).self) { try report.resolving(choices: [shared.id]) } + } + + @Test func resolvedCanonicalBindingCannotAdmitRawPreservedBytes() throws { + let f = try ImportSelectionFixture() + try f.write( + "settings.json", + #"{"mcpServers":{"review":{"command":"never-run","env":{"TOKEN":"PRIVATE_INPUT_CANARY"}}}}"#) + let initial = try SourceImportOperations.inspect( + format: "claudeSettingsV1", root: f.root, document: "settings.json") + let slot = try #require(initial.requiredInputs.first { $0.kind == .bindingReference }) + let resolved = try initial.resolving(inputs: [ + .init(id: slot.id, value: .binding(.environment("REVIEW_TOKEN"))) + ]) + #expect(resolved.bindings.isEmpty) + #expect(resolved.diagnostics.isEmpty) + #expect(resolved.resources.allSatisfy { $0.requiresBindingRewrite && $0.hash == nil }) + guard case .mcpServer(_, .stdio(let run), _, _, _) = resolved.components.first?.declaration + else { + Issue.record("Expected canonical MCP transport") + return + } + #expect(run.environment["TOKEN"] == .environment("REVIEW_TOKEN")) + #expect(!String(reflecting: resolved).contains("PRIVATE_INPUT_CANARY")) + let environment = RuntimeEnvironment( + projectDirectory: f.root, homeDirectory: f.root, environment: [:]) + let store = StateStore(scope: .project, environment: environment) + try store.save(declaration: Declaration(), ledger: ResolvedLedger()) + let scope = try UpdateOperations.inspect(environment: environment) + #expect(throws: (any Error).self) { try resolved.updateRequest(in: scope) } + + var input = SourceImportInput( + profile: .claudeSettingsV1, root: f.root, document: "settings.json") + let raw = try SourceImport.preview(input) + let key = try #require(raw.bindings.first(where: \.canonicalSlot)?.key) + input.bindingReferences[key] = .secret("local-review-token") + let proposal = try SourceImport.preview(input) + var enumeration = input + enumeration.enumerateChoices = true + let document = f.root.appendingPathComponent("settings.json") + let fingerprint = try TargetPrecondition(document).displayEvidence(includeContent: true) + let preparation = ImportPreparation( + input: input, proposal: proposal, + catalog: try SourceImport.preview(enumeration), documentFingerprint: fingerprint, + locations: [document]) + #expect(throws: (any Error).self) { try preparation.capture() } + #expect(try preparation.capture(admitConversion: false).count == 1) + let reinspected = try SourceImportOperations.inspect( + format: "claudeSettingsV1", root: f.root, document: "settings.json") + #expect(!reinspected.bindings.isEmpty) + #expect(reinspected.resources.allSatisfy { $0.requiresBindingRewrite }) + } + + @Test func excludedCredentialsRemainBlockedAndCannotReceiveFakeSlotHandles() throws { + let f = try ImportSelectionFixture() + try f.write( + "settings.json", + #"{"mcpServers":{"clean":{"command":"never-run"},"private":{"command":"never-run","env":{"TOKEN":"EXCLUDED_INPUT_CANARY"}}}}"# + ) + let report = try SourceImportOperations.inspect( + format: "claudeSettingsV1", root: f.root, + document: "settings.json", selection: ["clean"]) + #expect(report.components.count == 1) + #expect(!report.bindings.isEmpty) + #expect(report.bindings.allSatisfy { !$0.canResolveCanonicalSlot }) + #expect(!report.requiredInputs.contains { $0.kind == .bindingReference }) + #expect(report.resources.allSatisfy { $0.requiresBindingRewrite && $0.hash == nil }) + #expect(!String(reflecting: report).contains("EXCLUDED_INPUT_CANARY")) + } + + @Test func originalSymbolicBindingsDoNotInventRawCredentialRewrite() throws { + let f = try ImportSelectionFixture() + try f.write( + "settings.json", + #"{"mcpServers":{"review":{"command":"never-run","env":{"TOKEN":"${REVIEW_TOKEN}"}}}}"#) + let original = try SourceImportOperations.inspect( + format: "claudeSettingsV1", root: f.root, document: "settings.json") + let slot = try #require(original.requiredInputs.first { $0.kind == .bindingReference }) + #expect(original.resources.allSatisfy { !$0.requiresBindingRewrite && $0.hash != nil }) + let resolved = try original.resolving(inputs: [ + .init(id: slot.id, value: .binding(.environment("REVIEW_TOKEN"))) + ]) + #expect(resolved.bindings.isEmpty) + #expect(resolved.resources.allSatisfy { !$0.requiresBindingRewrite && $0.hash != nil }) + } + + @Test func failedNativeConversionDoesNotOfferAnUnusedCanonicalBindingSlot() throws { + let f = try ImportSelectionFixture() + try f.write( + "settings.json", + #"{"mcpServers":{"bad":{"command":"./missing-server","env":{"TOKEN":"FAILED_MEMBER_CANARY"}}}}"# + ) + let report = try SourceImportOperations.inspect( + format: "claudeSettingsV1", root: f.root, document: "settings.json") + #expect(report.components.isEmpty) + #expect(!report.bindings.isEmpty) + #expect(report.bindings.allSatisfy { !$0.canResolveCanonicalSlot }) + #expect(!report.requiredInputs.contains { $0.kind == .bindingReference }) + #expect(!String(reflecting: report).contains("FAILED_MEMBER_CANARY")) + } + + @Test func overlappingResourceAdmissionSurvivesCanonicalResolution() throws { + let f = try ImportSelectionFixture() + try f.write( + "opencode.json", + #"{"mcp":{"servers":{"clean":{"type":"local","command":["never-run"],"cwd":"."}}},"lsp":{"fixed":{"command":["never-run"],"env":{"TOKEN":"OVERLAP_CANARY"}}}}"# + ) + let initial = try SourceImportOperations.inspect( + format: "openCodeConfigV2", root: f.root, document: "opencode.json") + let slot = try #require(initial.requiredInputs.first { $0.kind == .bindingReference }) + let resolved = try initial.resolving(inputs: [ + .init(id: slot.id, value: .binding(.secret("local-token"))) + ]) + #expect(resolved.bindings.isEmpty) + #expect(resolved.diagnostics.isEmpty) + let root = try #require(resolved.resources.first { $0.path == "." }) + #expect(root.requiresBindingRewrite && root.hash == nil) + #expect(!String(reflecting: resolved).contains("OVERLAP_CANARY")) + } + + @Test func sourceHandlesRerunTheOwningLockAdapter() throws { + let f = try ImportSelectionFixture() + try f.write( + "lock.json", + "{\"lockfileVersion\":1,\"sources\":{\"acme/repo\":{\"resolvedRef\":\"" + + String(repeating: "a", count: 40) + "\",\"skillsPath\":\"skills\",\"skills\":{}}}}") + let initial = try SourceImportOperations.inspect( + format: "rulesyncSourcesV1", root: f.root, document: "lock.json") + let source = try #require(initial.requiredInputs.first { $0.kind == .sourceCoordinates }) + let resolved = try initial.resolving(inputs: [ + .init( + id: source.id, + value: .source(.init(kind: .git, location: "https://example.invalid/acme/repo"))) + ]) + #expect(resolved.requiredInputs.isEmpty) + #expect(resolved.diagnostics.isEmpty) + #expect(resolved.sources.first?.commit == String(repeating: "a", count: 40)) + #expect(throws: (any Error).self) { + try resolved.resolving(inputs: [.init(id: source.id, value: .content(path: "."))]) + } + } + + @Test func explicitContentAndMarketplaceChoicesRerunTheirOwnAdmission() throws { + let f = try ImportSelectionFixture() + try f.write( + "skills/review/SKILL.md", "---\nname: review\ndescription: Review\n---\nReview\n") + let capture = try ImportSkillContent.read( + "skills/review", input: .init(profile: .vercelProjectV2, root: f.root, document: "lock.json"), + limits: .init()) + let hash = ImportSkillContent.vercelHash(capture) + try f.write( + "lock.json", + "{\"version\":2,\"skills\":{\"review\":{\"source\":\"acme/repo\",\"sourceType\":\"github\",\"computedHash\":\"" + + hash + "\"}}}") + let initial = try SourceImportOperations.inspect( + format: "vercelProjectV2", root: f.root, document: "lock.json") + let content = try #require(initial.requiredInputs.first { $0.kind == .explicitContent }) + #expect(throws: (any Error).self) { + try initial.resolving(inputs: [.init(id: content.id, value: .content(path: "../escape"))]) + } + let missing = try initial.resolving(inputs: [ + .init(id: content.id, value: .content(path: "absent")) + ]) + #expect(missing.requiredInputs.contains { $0.kind == .explicitContent }) + let captured = try initial.resolving(inputs: [ + .init(id: content.id, value: .content(path: "skills/review")) + ]) + #expect(!captured.requiredInputs.contains { $0.kind == .explicitContent }) + #expect(captured.resources.contains { $0.hash != nil && $0.requiresStandaloneSource }) + #expect(captured.sources.allSatisfy { $0.commit == nil }) + #expect(captured.diagnostics.contains { $0.code == "incompletePin" }) + + try f.write( + ".claude-plugin/marketplace.json", + #"{"name":"market","owner":{"name":"Owner"},"plugins":[{"name":"review","source":{"source":"github","repo":"acme/repo","sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}]}"# + ) + let catalog = try SourceImportOperations.inspect( + format: "claudeMarketplaceV1", root: f.root, document: ".claude-plugin/marketplace.json") + #expect(catalog.sources.isEmpty) + #expect(!catalog.diagnostics.isEmpty) + let choice = try #require(catalog.availableChoices.first) + #expect(choice.effects.sources.count == 1) + let selected = try catalog.resolving(choices: [choice.id]) + #expect(selected.sources.count == 1) + #expect(selected.sources.first?.commit == String(repeating: "a", count: 40)) + let empty = try catalog.resolving(choices: []) + #expect(empty.sources.isEmpty) + } + + @Test func ordinalChoicesAndUnfilteredContainersKeepTheirOwnSemantics() throws { + let f = try ImportSelectionFixture() + try f.write( + "apm.yml", + "name: example\nversion: '1.0.0'\ndependencies:\n apm: [acme/one]\ndevDependencies:\n apm: [acme/two]\n" + ) + let yaml = try SourceImportOperations.inspect( + format: "apmManifest", root: f.root, document: "apm.yml") + #expect(yaml.availableChoices.count == 1) + #expect(yaml.availableChoices.first?.locations.count == 2) + #expect(yaml.availableChoices.first?.effects.sources.count == 2) + let empty = try yaml.resolving(choices: []) + #expect(empty.sources.isEmpty) + try f.write("bundle/.cursor-plugin/plugin.json", #"{"name":"bundle"}"#) + try f.write("bundle/commands/review.md", "Review") + let container = try SourceImportOperations.inspect( + format: "cursorPluginV1", root: f.root, document: "bundle/.cursor-plugin/plugin.json") + #expect(container.availableChoices.isEmpty) + #expect(container.fixedEffects.components.count == 1) + #expect(try container.resolving(choices: []).components.count == 1) + } +} + +private final class ImportSelectionFixture { + let root: URL + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "import-selection-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + deinit { try? FileManager.default.removeItem(at: root) } + func write(_ path: String, _ text: String) throws { + let url = root.appendingPathComponent(path) + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: url) + } +} From 92a1e2e9e1eb94d7d04db7e1cf31c4e489c829ae Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:10:38 +0800 Subject: [PATCH 134/171] fix: preserve contained native skill supporting resources --- .../Import/ImportSkillContent.swift | 42 ++- .../Import/NativeContainerImport.swift | 56 +++- .../Components/Import/NativeImportInput.swift | 22 +- .../ImportSupportingLinksTests.swift | 247 ++++++++++++++++++ 4 files changed, 341 insertions(+), 26 deletions(-) create mode 100644 Tests/ComponentsTests/ImportSupportingLinksTests.swift diff --git a/Sources/Components/Import/ImportSkillContent.swift b/Sources/Components/Import/ImportSkillContent.swift index 0cbbc40..bd13147 100644 --- a/Sources/Components/Import/ImportSkillContent.swift +++ b/Sources/Components/Import/ImportSkillContent.swift @@ -11,14 +11,28 @@ struct ImportSkillContent { let diagnostics: [SourceImportDiagnostic] let bindings: [ImportBindingRequirement] - static func read(_ path: String, input: SourceImportInput, limits: SourceImportLimits) throws - -> Self - { + static func read( + _ path: String, input: SourceImportInput, limits: SourceImportLimits, + nativeContainer: String? = nil + ) throws -> Self { let path = try ImportInput.path(path) let source = try ImportInput.snapshot(input.root) let directory = try source.resource(path) - // Admit the finite tree before readers that sort directory entries or recursively discover. - // This capture profile refuses links rather than changing their producer hash semantics. + let boundary: URL + if let nativeContainer { + guard [.claudePluginV1, .cursorPluginV1, .geminiExtensionV1].contains(input.profile) else { + throw ImportReadFailure.invalid + } + boundary = try source.resource(ImportInput.path(nativeContainer)) + guard PathSafety.isContained(directory, in: boundary), + PathSafety.isContained( + directory.resolvingSymlinksInPath(), in: boundary.resolvingSymlinksInPath()) + else { throw ImportReadFailure.invalid } + } else { + boundary = directory + } + // Bound the selected physical tree before discovery. Native supporting links are admitted + // by capture against the explicit enclosing container, never as discovered members. guard limits.resourceEntries > 0, limits.resourceBytes >= 0, limits.depth > 0, let iterator = FileManager.default.enumerator(at: directory, includingPropertiesForKeys: nil) else { throw ImportReadFailure.invalid } @@ -34,7 +48,11 @@ struct ImportSkillContent { guard depth <= limits.depth else { throw ImportReadFailure.invalid } let attributes = try FileManager.default.attributesOfItem(atPath: entry.path) let type = attributes[.type] as? FileAttributeType - guard type == .typeDirectory || type == .typeRegular else { throw ImportReadFailure.invalid } + if type == .typeSymbolicLink, nativeContainer != nil { + iterator.skipDescendants() + } else if type != .typeDirectory && type != .typeRegular { + throw ImportReadFailure.invalid + } if type == .typeRegular { guard let size = (attributes[.size] as? NSNumber)?.intValue, size >= 0, size <= limits.resourceBytes - total @@ -48,10 +66,14 @@ struct ImportSkillContent { encodedBytes: limits.resourceBytes, depth: limits.depth, nodes: limits.nodes, objectBytes: limits.resourceBytes, entries: limits.resourceEntries, keyBytes: limits.resourceBytes, - resourceBytes: limits.resourceBytes), sourceRoot: directory) - // Link identity and link-following producer hashes are different contracts. This bounded - // capture supports regular content; linked trees need explicit conversion before import. - guard frozen.entries.allSatisfy({ $0.kind != .symlink }), frozen.support.isEmpty else { + resourceBytes: limits.resourceBytes), sourceRoot: boundary) + // Producer-specific installed-content hashes retain their regular-file-only admission. + if nativeContainer == nil { + guard frozen.entries.allSatisfy({ $0.kind != .symlink }), frozen.support.isEmpty else { + throw ImportReadFailure.invalid + } + } + guard frozen.support.allSatisfy({ $0.path.split(separator: "/").count <= limits.depth }) else { throw ImportReadFailure.invalid } let files = try frozen.entries.filter { $0.kind == .file }.map { entry -> (String, Data) in diff --git a/Sources/Components/Import/NativeContainerImport.swift b/Sources/Components/Import/NativeContainerImport.swift index 4e15019..8aea708 100644 --- a/Sources/Components/Import/NativeContainerImport.swift +++ b/Sources/Components/Import/NativeContainerImport.swift @@ -394,7 +394,36 @@ enum NativeContainerImport { } return } + guard + try FileManager.default.attributesOfItem(atPath: url.path)[.type] as? FileAttributeType + != .typeSymbolicLink + else { + diagnostics.add( + .unconverted, .init(document: relative, pointer: ""), + "Native member discovery through a link requires explicit contained support closure.") + return + } + // A regular member directory reached through a linked ancestor is still link discovery. + let memberPath = + relative == root ? "." : root == "." ? relative : String(relative.dropFirst(root.count + 1)) + let memberParts = memberPath.split(separator: "/") + if memberParts.count > 1 { + for count in 1..] = [:] + for resource in diagnostics.proposal.resources { guard let path = resource.path, let root = diagnostics.proposal.sources.first(where: { $0.alias == resource.sourceAlias })?.producerPath else { continue } let relative = root == "." ? path : root + (path == "." ? "" : "/" + path) - if diagnostics.proposal.preservationBindings.contains(where: { - relative == "." || $0.document == relative - || $0.document.hasPrefix(relative + "/") - }) { + if resource.requiresBindingRewrite + || diagnostics.proposal.preservationBindings.contains(where: { + relative == "." || $0.document == relative + || $0.document.hasPrefix(relative + "/") + }) + { + blockedCaptures[resource.sourceAlias, default: []].insert(resource.origin) + } + } + // A capture and its supporting resources share an origin and source coordinate. Literal + // classification in any part of that closure blocks preservation of the complete capture. + for index in diagnostics.proposal.resources.indices { + let resource = diagnostics.proposal.resources[index] + if blockedCaptures[resource.sourceAlias]?.contains(resource.origin) == true { diagnostics.proposal.resources[index].requiresBindingRewrite = true diagnostics.proposal.resources[index].observedHash = nil } diff --git a/Tests/ComponentsTests/ImportSupportingLinksTests.swift b/Tests/ComponentsTests/ImportSupportingLinksTests.swift new file mode 100644 index 0000000..294519d --- /dev/null +++ b/Tests/ComponentsTests/ImportSupportingLinksTests.swift @@ -0,0 +1,247 @@ +import AgentsCore +import Foundation +import Testing + +@testable import Components + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +struct ImportSupportingLinksTests { + @Test(arguments: [ + SourceImportProfile.claudePluginV1, .cursorPluginV1, .geminiExtensionV1, + ]) + func nativeSkillPreservesContainedChainedExecutableSupport(_ profile: SourceImportProfile) throws + { + let f = try SupportingSkillFixture(profile) + try f.write("bundle/shared/tool.txt", "Supporting executable\n", executable: true) + try f.link("bundle/shared/current", "tool.txt") + try f.link("bundle/skills/helper/reference.txt", "../../shared/current") + try f.write( + "bundle/shared/directory/SKILL.md", "---\nname: hidden\ndescription: Hidden\n---\nBody\n") + try f.link("bundle/skills/helper/data", "../../shared/directory") + let before = try FileHash.folderHash(f.root) + let proposal = try SourceImport.preview(f.input) + #expect(proposal.diagnostics.isEmpty) + #expect(proposal.components.count == 1) + let member = try #require(proposal.components.first) + #expect(member.member?.selector == .skill(name: "helper")) + #expect(member.member?.containerRoot == "bundle") + #expect(member.origin.document == "bundle/skills/helper/SKILL.md") + let preservation = try #require(proposal.resources.first { $0.kind == .skills }) + #expect(preservation.path == "skills/helper") + #expect(preservation.requiresStandaloneSource && !preservation.requiresBindingRewrite) + #expect( + proposal.sources.first { $0.alias == preservation.sourceAlias }?.producerPath == "bundle") + #expect( + preservation.observedHash + == "sha256:" + + (try FileHash.folderHash(f.root.appendingPathComponent("bundle/skills/helper")))) + #expect( + proposal.resources.contains { + $0.path == "shared/tool.txt" && $0.executableFlags["shared/tool.txt"] == true + }) + let captured = try LedgerResources.capture( + f.root.appendingPathComponent("bundle/skills/helper"), embed: true, limits: .standard, + sourceRoot: f.root.appendingPathComponent("bundle")) + #expect( + captured.entries.contains { $0.path == "reference.txt" && $0.link == "../../shared/current" }) + #expect(captured.support.contains { $0.path == "shared/current" && $0.link == "tool.txt" }) + #expect(captured.support.contains { $0.path == "shared/tool.txt" && $0.executable }) + #expect(try FileHash.folderHash(f.root) == before) + } + + @Test func linkedSkillClosureSurvivesProductionFreezeAndLedgerRoundTrip() throws { + let f = try LinkFixture() + try f.write(#"{"name":"bundle"}"#, to: "bundle/.claude-plugin/plugin.json", base: f.project) + try f.write( + "---\nname: helper\ndescription: Helper\n---\nBody\n", + to: "bundle/skills/helper/SKILL.md", base: f.project) + try f.write("Executable support\n", to: "bundle/shared/tool.txt", base: f.project) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: f.project.appendingPathComponent("bundle/shared/tool.txt").path) + try FileManager.default.createSymbolicLink( + atPath: f.project.appendingPathComponent("bundle/skills/helper/reference.txt").path, + withDestinationPath: "../../shared/tool.txt") + let declaration = try f.document( + """ + version: 1 + components: [{kind: plugin, name: bundle, source: ".", path: bundle, agents: [claude-code]}] + """) + let ledger = try ComponentLinker.withLinkedComponents( + document: declaration, store: f.store, platform: .macOS + ) { graph, session in + let locations = Dictionary( + (graph.sourceSnapshots + graph.declaringSnapshots).filter { + $0.source?.kind == .local && $0.container == nil + }.map { + ( + $0.snapshot.source, + LedgerLocation( + kind: .absolute, path: String($0.snapshot.source.dropFirst("local:".count))) + ) + }, uniquingKeysWith: { first, _ in first }) + return try LedgerFreeze.freeze( + graph, session: session, locations: .init(sources: locations), limits: .standard) + } + let skill = try #require(ledger.resources.values.first { $0.path.hasSuffix("skills/helper") }) + #expect( + skill.entries.contains { $0.path == "reference.txt" && $0.link == "../../shared/tool.txt" }) + #expect(skill.support.contains { $0.path.hasSuffix("shared/tool.txt") && $0.executable }) + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + #expect(try ResolvedLedgerCodec.decode(encoded, limits: .standard) == ledger) + } + + @Test func laterSupportingDocumentCredentialsBlockTheEntireSkillCapture() throws { + let f = try SupportingSkillFixture(.claudePluginV1) + try f.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"bundle","lspServers":"./shared/language.json"}"#) + try f.write( + "bundle/shared/language.json", + #"{"review":{"command":"never-run","extensionToLanguage":{".txt":"text"},"env":{"TOKEN":"SUPPORT_LITERAL_CANARY"}}}"# + ) + try f.link("bundle/skills/helper/reference.txt", "../../shared/language.json") + let proposal = try SourceImport.preview(f.input) + let skill = try #require(proposal.resources.first { $0.kind == .skills }) + #expect(skill.requiresBindingRewrite && skill.observedHash == nil) + #expect( + proposal.resources.filter { $0.origin == skill.origin }.allSatisfy { + $0.requiresBindingRewrite && $0.observedHash == nil + }) + #expect(!proposal.bindings.isEmpty) + #expect(!String(reflecting: proposal).contains("SUPPORT_LITERAL_CANARY")) + } + + @Test(arguments: ["absolute", "outside", "missing", "cycle", "linkThenParent", "fifo"]) + func invalidSupportingClosureCannotEmitASkill(_ kind: String) throws { + let f = try SupportingSkillFixture(.claudePluginV1) + try f.write("bundle/shared/tool.txt", "Support\n") + let reference = "bundle/skills/helper/reference.txt" + switch kind { + case "absolute": + try f.link(reference, f.root.appendingPathComponent("bundle/shared/tool.txt").path) + case "outside": + try f.write("outside.txt", "Outside container\n") + try f.link(reference, "../../../outside.txt") + case "missing": try f.link(reference, "../../shared/missing.txt") + case "cycle": + try f.link(reference, "../../shared/loop") + try f.link("bundle/shared/loop", "../skills/helper/reference.txt") + case "linkThenParent": + try f.write("outside/dir/child.txt", "Child\n") + try f.write("outside/tool.txt", "Outside container\n") + try f.link("bundle/shared/jump", "../../outside/dir") + try f.link(reference, "../../shared/jump/../tool.txt") + default: + let fifo = f.root.appendingPathComponent("bundle/shared/pipe").path + #expect(mkfifo(fifo, 0o600) == 0) + try f.link(reference, "../../shared/pipe") + } + let proposal = try SourceImport.preview(f.input) + #expect(!proposal.diagnostics.isEmpty) + #expect(!proposal.components.contains { $0.declaration.kind == .skills }) + #expect(!proposal.resources.contains { $0.kind == .skills }) + } + + @Test func supportingLinksCannotDiscoverMembersOrChangeOtherProducerHashAdmission() throws { + let f = try SupportingSkillFixture(.cursorPluginV1) + try FileManager.default.removeItem( + at: f.root.appendingPathComponent("bundle/skills/helper/SKILL.md")) + try f.write( + "bundle/shared/SKILL.md", "---\nname: linked\ndescription: Linked\n---\nBody\n") + try f.link("bundle/skills/helper/SKILL.md", "../../shared/SKILL.md") + let proposal = try SourceImport.preview(f.input) + #expect(proposal.components.isEmpty) + #expect( + proposal.diagnostics.contains { + $0.code == .unconverted && $0.location.document.hasSuffix("SKILL.md") + }) + + let regular = try SupportingSkillFixture(.claudePluginV1) + try regular.write("bundle/shared/tool.txt", "Support\n") + try regular.link("bundle/skills/helper/reference.txt", "../../shared/tool.txt") + #expect(throws: (any Error).self) { + try ImportSkillContent.read("bundle/skills/helper", input: regular.input, limits: .init()) + } + var producer = regular.input + producer = .init(profile: .vercelProjectV2, root: producer.root, document: producer.document) + #expect(throws: (any Error).self) { + try ImportSkillContent.read( + "bundle/skills/helper", input: producer, limits: .init(), nativeContainer: "bundle") + } + } + + @Test func explicitMemberPathCannotTraverseALinkedDirectory() throws { + let f = try SupportingSkillFixture(.claudePluginV1) + try f.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"bundle","skills":"./alias/nested"}"#) + try f.write( + "bundle/real/nested/SKILL.md", "---\nname: linked\ndescription: Linked\n---\nBody\n") + try f.link("bundle/alias", "real") + let proposal = try SourceImport.preview(f.input) + #expect(!proposal.components.contains { $0.member?.selector == .skill(name: "linked") }) + #expect(proposal.components.contains { $0.member?.selector == .skill(name: "helper") }) + #expect( + proposal.diagnostics.contains { + $0.code == .unconverted && $0.location.document == "bundle/alias" + }) + } + + @Test(arguments: ["entries", "bytes", "depth"]) + func supportingClosureRemainsBounded(_ budget: String) throws { + let f = try SupportingSkillFixture(.geminiExtensionV1) + try f.write("bundle/shared/tool.txt", String(repeating: "S", count: 256)) + try f.link("bundle/skills/helper/reference.txt", "../../shared/tool.txt") + var limits = SourceImportLimits() + switch budget { + case "entries": limits.resourceEntries = 3 + case "bytes": limits.resourceBytes = 128 + default: limits.depth = 1 + } + #expect(throws: (any Error).self) { + try ImportSkillContent.read( + "bundle/skills/helper", input: f.input, limits: limits, nativeContainer: "bundle") + } + } +} + +private final class SupportingSkillFixture { + let root: URL + let input: SourceImportInput + init(_ profile: SourceImportProfile) throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "import-support-" + UUID().uuidString) + let document: String + switch profile { + case .claudePluginV1: document = "bundle/.claude-plugin/plugin.json" + case .cursorPluginV1: document = "bundle/.cursor-plugin/plugin.json" + default: document = "bundle/gemini-extension.json" + } + input = .init(profile: profile, root: root, document: document) + try write(document, #"{"name":"bundle","version":"1.2.3"}"#) + try write( + "bundle/skills/helper/SKILL.md", "---\nname: helper\ndescription: Helper\n---\nBody\n") + } + deinit { try? FileManager.default.removeItem(at: root) } + func write(_ path: String, _ text: String, executable: Bool = false) throws { + let file = root.appendingPathComponent(path) + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: file) + if executable { + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: file.path) + } + } + func link(_ path: String, _ target: String) throws { + let file = root.appendingPathComponent(path) + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(atPath: file.path, withDestinationPath: target) + } +} From a2eb1507ea33dca7ce06649408eb4d98f0659a9e Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:13:11 +0800 Subject: [PATCH 135/171] fix: track concrete implicit source inputs --- .../AgentsUpdates/UpdateReadLocations.swift | 93 +++++++++-- Sources/Components/ComponentFields.swift | 2 +- .../DeclarationStateTests.swift | 2 +- .../ImplicitReadFootprintTests.swift | 157 ++++++++++++++++++ 4 files changed, 242 insertions(+), 12 deletions(-) create mode 100644 Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift diff --git a/Sources/AgentsUpdates/UpdateReadLocations.swift b/Sources/AgentsUpdates/UpdateReadLocations.swift index 7e8a0b9..e1f4d41 100644 --- a/Sources/AgentsUpdates/UpdateReadLocations.swift +++ b/Sources/AgentsUpdates/UpdateReadLocations.swift @@ -9,12 +9,28 @@ extension UpdateOperations { declarations: [Declaration], ledgers: [ResolvedLedger], store: StateStore ) throws -> [URL] { var paths = [store.declarationURL, store.resolvedURL, store.watchURL] + let scopeRoot = store.scope == .user ? store.directory : store.environment.projectDirectory for declaration in declarations { for source in declaration.sources.values where source.kind == .local { paths.append(source.localURL(environment: source.environment?.runtime ?? store.environment)) } - func collect(_ components: [ComponentDeclaration]) { + func resourceRoot(_ alias: String?) throws -> URL? { + guard let alias, alias != "." else { return scopeRoot } + guard let source = declaration.sources[alias], source.kind == .local else { return nil } + return try PathSafety.resolvedChild( + base: source.localURL(environment: store.environment), subpath: source.path ?? ".") + } + func collect(_ components: [ComponentDeclaration]) throws { for component in components { + for resource in component.resources { + if let root = try resourceRoot(resource.source) { + paths.append(try PathSafety.resolvedChild(base: root, subpath: resource.path)) + } + } + if case .skills(let alias, _) = component, let root = try resourceRoot(alias) { + // Discovery reads the root even when it finds no selected members. + paths.append(root) + } guard case .instructions(let instructions) = component else { continue } let sections = instructions.sectionReferences @@ -24,18 +40,64 @@ extension UpdateOperations { paths += InstructionOperations.ownReadLocations( names: ownNames, environment: store.environment) } + let appendRoot = + store.scope == .user + ? store.environment.homeDirectory : store.environment.projectDirectory + for prompt in instructions.prompts { + if let appendix = prompt.prompt.append { + paths.append(try PathSafety.resolvedChild(base: appendRoot, subpath: appendix)) + } + } } } - collect(declaration.components) - for group in declaration.groups { collect(group.components) } + try collect(declaration.components) + for group in declaration.groups { try collect(group.components) } } for ledger in ledgers { - for source in ledger.sources.values { + func localRoot(_ id: String) throws -> URL? { + guard let source = ledger.sources[id], source.kind == .local else { return nil } + if let location = source.location { return try location.resolve(roots: store.ledgerRoots) } + if let container = source.container { return try localRoot(container) } + return nil + } + let explicitSources = Set(ledger.sourceUses.map(\.source)) + for (id, source) in ledger.sources { if let location = source.location { - paths.append(try location.resolve(roots: store.ledgerRoots)) + let root = try location.resolve(roots: store.ledgerRoots) + // The linker's implicit live snapshot supplies provenance, not a whole-tree read. + // Explicit local declarations above retain their independent whole-tree interests. + let implicit = + source.kind == .local && source.revision == "live" + && source.container == nil + && root.resolvingSymlinksInPath().path == scopeRoot.resolvingSymlinksInPath().path + if !implicit || explicitSources.contains(id) { paths.append(root) } + } + } + for occurrence in ledger.occurrences { + if let root = try localRoot(occurrence.declaringSource) { + paths.append(try PathSafety.resolvedChild(base: root, subpath: occurrence.manifestPath)) + } + if let plugin = occurrence.pluginExpansion, let root = try localRoot(plugin.source) { + paths.append(try PathSafety.resolvedChild(base: root, subpath: plugin.containerRoot)) + paths.append(try PathSafety.resolvedChild(base: root, subpath: plugin.document)) + } + } + for group in ledger.groups { + if let root = try localRoot(group.source) { + let directory = try PathSafety.resolvedChild(base: root, subpath: group.root) + paths.append( + directory.appendingPathComponent( + directory.lastPathComponent == ".agent" ? "agents.yaml" : ".agent/agents.yaml")) } } for component in ledger.components.values { + if component.kind == DeclaredComponentKind.skills.rawValue, + let root = try localRoot(component.source) + { + paths.append( + try PathSafety.resolvedChild( + base: root, subpath: component.containerRoot ?? component.root)) + } if let value = component.payload.object?["localAppend"] { paths.append(try LedgerLocation(ledgerValue: value).resolve(roots: store.ledgerRoots)) } @@ -45,11 +107,22 @@ extension UpdateOperations { } for (id, resource) in ledger.resources { paths.append(try ArtifactAggregation.resourceDestination(id, ledger: ledger, store: store)) - if let source = ledger.sources[resource.source], source.kind == .local, - let location = source.location - { - let root = try location.resolve(roots: store.ledgerRoots) - paths.append(root.appendingPathComponent(try PathSafety.sanitizeSubpath(resource.path))) + if let root = try localRoot(resource.source) { + let selected = try PathSafety.resolvedChild(base: root, subpath: resource.path) + paths.append(selected) + // Support directories also contain structural ancestors. Only actual entries and + // link targets are recursive interests; those ancestors are not source-tree reads. + for entry in resource.support where entry.kind != .directory { + paths.append(try PathSafety.resolvedChild(base: root, subpath: entry.path)) + } + let links = + try resource.entries.filter { $0.kind == .symlink }.map { + try PathSafety.resolvedChild(base: selected, subpath: $0.path) + } + + resource.support.filter { $0.kind == .symlink }.map { + try PathSafety.resolvedChild(base: root, subpath: $0.path) + } + paths += links.map { $0.resolvingSymlinksInPath() } } } } diff --git a/Sources/Components/ComponentFields.swift b/Sources/Components/ComponentFields.swift index 1328299..4acefbc 100644 --- a/Sources/Components/ComponentFields.swift +++ b/Sources/Components/ComponentFields.swift @@ -36,7 +36,7 @@ extension ComponentDeclaration { } } - var resources: [ResourceDeclaration] { + package var resources: [ResourceDeclaration] { func run(_ value: ExecutableDeclaration) -> [ResourceDeclaration] { let executable = value.executable.contains("/") ? [ResourceDeclaration(path: value.executable)] : [] diff --git a/Tests/AgentsCoreTests/DeclarationStateTests.swift b/Tests/AgentsCoreTests/DeclarationStateTests.swift index 6c874ea..f06835b 100644 --- a/Tests/AgentsCoreTests/DeclarationStateTests.swift +++ b/Tests/AgentsCoreTests/DeclarationStateTests.swift @@ -215,7 +215,7 @@ struct DeclarationStateTests { for name in ["agents.yaml", "agents.resolved", "agents.watch"] { #expect(try paths.components("state/" + name).descendants == [name]) } - for name in ["other.json", "agents.swift", "agents.yaml.new"] { + for name in ["other.json", "agents.yaml.new"] { #expect(throws: CoreError.unsafePath("unmanaged state transaction path")) { try paths.components("state/" + name) } diff --git a/Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift b/Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift new file mode 100644 index 0000000..629a33b --- /dev/null +++ b/Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift @@ -0,0 +1,157 @@ +import AgentsCore +import AgentsManifest +import Foundation +import Testing + +@testable import AgentsUpdates + +struct ImplicitReadFootprintTests { + @Test(arguments: [InstallScope.project, .user]) + func implicitResourcesKeepInputsAndTargetsWithoutWatchingOwnedMirrors(_ scope: InstallScope) + throws + { + let f = try UpdateFixture(scope: scope) + let root = scope == .user ? f.store.directory : f.root + let tool = root.appendingPathComponent("bin/tool") + let body = root.appendingPathComponent("prompts/body.md") + try f.write("#!/bin/sh\nexit 0\n", to: tool) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: tool.path) + try f.write("Prompt body", to: body) + let declaration = Declaration( + agents: [.claudeCode], + components: [ + .mcpServer(name: "tool", transport: .stdio(.init(executable: "./bin/tool"))), + .command(name: "body", description: "Body", prompt: .file(.init(path: "prompts/body.md"))), + ]) + let request = UpdateRequest(operation: .declaration(declaration)) + let report = try UpdateOperations.preview(request, scope: scope, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, scope: scope, environment: f.environment) { + try $0.apply(ifUnchangedFrom: report.displayedFingerprint) + } + let inspection = try UpdateOperations.inspect(scope: scope, environment: f.environment) + for locations in [report.readLocations, inspection.readLocations] { + let paths = Set(locations.map(\.path)) + #expect(!paths.contains(root.path)) + #expect( + paths.isSuperset(of: [ + tool.path, body.path, f.store.declarationURL.path, + f.store.resolvedURL.path, f.store.watchURL.path, + ])) + let mirror = f.store.directory.appendingPathComponent("cache/mirrors/owned.git/FETCH_HEAD") + #expect( + !locations.contains { mirror.path.hasPrefix($0.path + "/") || mirror.path == $0.path }) + } + let selected = try #require(inspection.components.first { $0.kind == .mcpServer }) + let connection = try MCPConnectionOperations.snapshot( + selection: selected.selection, scope: scope, environment: f.environment) + #expect(connection.readLocations.map(\.path).contains(tool.path)) + if scope == .user { + #expect(!connection.readLocations.map(\.path).contains(root.path)) + } + #expect( + Set(inspection.readLocations.map(\.path)).isSuperset( + of: + inspection.deployments.map { $0.location.path })) + } + + @Test func absentDeclarationsAndGroupResourcesRemainInputs() throws { + let f = try UpdateFixture() + let absent = f.root.appendingPathComponent("absent-source") + let declaration = Declaration( + sources: ["unused": .init(kind: .local, location: absent.path, path: "nested")], + groups: [ + .init( + name: "unused", + components: [ + .command(name: "future", description: "Future", prompt: .file(.init(path: "future.md"))) + ]) + ]) + let paths = try UpdateOperations.readLocations( + declarations: [declaration], ledgers: [], store: f.store) + #expect( + Set(paths.map(\.path)).isSuperset(of: [ + absent.path, f.root.appendingPathComponent("future.md").path, + ])) + } + + @Test func emptyOwnSkillAndPluginSelectionsKeepDiscoveryRoots() throws { + let f = try UpdateFixture(scope: .user) + let plugin = f.store.directory.appendingPathComponent("plugins/empty") + try f.write( + "{\"name\":\"empty\",\"version\":\"1.0.0\"}", + to: plugin.appendingPathComponent(".claude-plugin/plugin.json")) + let declaration = Declaration( + agents: [.claudeCode], + components: [ + .plugin(name: "empty", path: "plugins/empty", source: ".", agents: []) + ]) + let report = try UpdateOperations.preview( + .init(operation: .declaration(declaration)), scope: .user, environment: f.environment) + #expect(report.readLocations.map(\.path).contains(plugin.path)) + #expect(!report.readLocations.map(\.path).contains(f.store.directory.path)) + let ownSkills = Declaration(components: [.skills(source: ".", .init(select: .all))]) + let ownReport = try UpdateOperations.preview( + .init(operation: .declaration(ownSkills)), scope: .user, environment: f.environment) + #expect(ownReport.readLocations.map(\.path).contains(f.store.directory.path)) + } + + @Test func explicitRootsRetainWholeTreeSemanticsAndLiveIsNotEnoughToSuppressThem() throws { + let f = try UpdateFixture() + let sameRoot = Declaration(sources: [ + "own": .init(kind: .local, location: f.root.path, path: "skills") + ]) + var ledger = ResolvedLedger() + ledger.sources["implicit"] = .init( + kind: .local, location: .init(kind: .absolute, path: f.root.path), revision: "live") + let elsewhere = f.root.appendingPathComponent("elsewhere") + ledger.sources["explicit"] = .init( + kind: .local, location: .init(kind: .absolute, path: elsewhere.path), revision: "live") + ledger.sources["pinned"] = .init( + kind: .local, location: .init(kind: .absolute, path: f.root.path), + revision: String(repeating: "a", count: 40)) + let paths = try UpdateOperations.readLocations( + declarations: [sameRoot], ledgers: [ledger], store: f.store) + #expect(Set(paths.map(\.path)).isSuperset(of: [f.root.path, elsewhere.path])) + ledger.sources = ["implicit": ledger.sources["implicit"]!] + ledger.sourceUses = [.init(source: "implicit", root: "skills")] + let retained = try UpdateOperations.readLocations( + declarations: [], ledgers: [ledger], store: f.store) + #expect(retained.map(\.path).contains(f.root.path)) + } + + @Test func supportingFilesAndLinkReplacementRemainInputs() throws { + let f = try UpdateFixture(scope: .user) + let root = f.store.directory + let selected = root.appendingPathComponent("bin/tool") + let support = root.appendingPathComponent("shared/actual") + try f.write("#!/bin/sh\n", to: support) + try FileManager.default.createDirectory( + at: selected.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: selected.path, withDestinationPath: "../shared/actual") + let declaration = Declaration( + agents: [], + components: [ + .mcpServer(name: "supported", transport: .stdio(.init(executable: "bin/tool"))) + ]) + let request = UpdateRequest(operation: .declaration(declaration)) + let first = try UpdateOperations.preview(request, scope: .user, environment: f.environment) + let paths = first.readLocations + #expect(Set(paths.map(\.path)).isSuperset(of: [selected.path, support.path])) + #expect(!paths.map(\.path).contains(root.path)) + #expect(!paths.map(\.path).contains(root.appendingPathComponent("shared").path)) + try f.write("#!/bin/sh\n# changed support\n", to: support) + let changed = try UpdateOperations.preview(request, scope: .user, environment: f.environment) + #expect(changed.displayedFingerprint != first.displayedFingerprint) + let replacement = root.appendingPathComponent("shared/replacement") + try f.write("#!/bin/sh\n", to: replacement) + try FileManager.default.removeItem(at: selected) + try FileManager.default.createSymbolicLink( + atPath: selected.path, withDestinationPath: "../shared/replacement") + let replaced = try UpdateOperations.preview(request, scope: .user, environment: f.environment) + #expect(replaced.readLocations.map(\.path).contains(selected.path)) + #expect(replaced.readLocations.map(\.path).contains(replacement.path)) + #expect(!replaced.readLocations.map(\.path).contains(support.path)) + #expect(replaced.displayedFingerprint != changed.displayedFingerprint) + } +} From 4bcea8f0d8b6081ccbd874107edd658f2e76917b Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:17:11 +0800 Subject: [PATCH 136/171] feat: bind finite additions to captured destination state --- Documentation/Architecture/Updates.md | 17 +- .../AgentsUpdates/ComponentDiscovery.swift | 161 ++++++++++- Sources/AgentsUpdates/ScopeInspection.swift | 6 +- .../SourceImportOperations.swift | 31 +-- Sources/AgentsUpdates/UpdateOperations.swift | 2 + Sources/AgentsUpdates/UpdatePlan.swift | 3 +- Sources/AgentsUpdates/UpdateRequest.swift | 1 + .../ConsumerLifecycleRegressionTests.swift | 257 ++++++++++++++++++ 8 files changed, 446 insertions(+), 32 deletions(-) diff --git a/Documentation/Architecture/Updates.md b/Documentation/Architecture/Updates.md index a5f57fd..8f46919 100644 --- a/Documentation/Architecture/Updates.md +++ b/Documentation/Architecture/Updates.md @@ -166,6 +166,19 @@ captured declaration identity and discovered graph fingerprint into preparation; a changed source fails before callback delivery. File enumeration and native input conversion remain with their domain/import owners. +Finite source and import additions use the package `UpdateOperations.captureAddition` +seam. It accepts explicit declaration additions and a captured `ScopeInspection`, +returning no candidate for an empty or source-only selection. Composition preserves +existing source aliases, groups, uses, defaults and direct occurrences. Alias/group +conflicts and pending authored changes require resolution rather than a broader +update. All existing pins and protected projections remain fixed while the selected +addition links; its fingerprint is captured after composition. The request retains +Core path identity, scope/root mappings, declaration absence or digest and baseline +state evidence. Another destination, changed evidence or a modified candidate +requires a refreshed inspection. Ordinary preparation repeats these checks before +offering its synchronous handle. Existing authored whole-graph discovery remains +an explicit complete-graph workflow. + `SourceImportOperations.inspect` consumes an explicit existing importer profile, root, document, selection and supplied resource locations. Its immutable report preserves producer coordinates, pins/integrity, ordered sources, selections, @@ -174,7 +187,9 @@ deployment claims. `updateRequest(in:)` merges admitted canonical intent into th captured scope declaration. Preparation rereads the same inputs, compares the proposal, captures their private freshness evidence and validates it again around publication. Unresolved conversion/binding diagnostics stop submission; foreign -claims do not establish ownership. Input content that would overwrite its own +claims do not establish ownership. Import requests use destination-bound finite +addition protection; admitted canonical bindings cannot clear independent raw +preservation/rewrite requirements. Input content that would overwrite its own local authoring source requires independent preservation before submission. Pass D's `RuntimeBindingProvider` as `bindingProvider:` to public diff --git a/Sources/AgentsUpdates/ComponentDiscovery.swift b/Sources/AgentsUpdates/ComponentDiscovery.swift index 1cf95bf..1ad79f2 100644 --- a/Sources/AgentsUpdates/ComponentDiscovery.swift +++ b/Sources/AgentsUpdates/ComponentDiscovery.swift @@ -3,7 +3,7 @@ import AgentsManifest import Components import Foundation -/// A complete explicit selection graph resolved in a temporary source session, before deployment. +/// A linked authored graph or finite addition resolved in a temporary source session before deployment. public struct ComponentDiscovery: Sendable { public let components: [ComponentInspection] public let sourceRevisions: [String: [String]] @@ -11,19 +11,24 @@ public struct ComponentDiscovery: Sendable { public let readLocations: [URL] private let declaration: Declaration private let declarationDigest: String + private let addition: CapturedAddition? - /// Carries both the captured scope and exact discovered content into ordinary preparation. + /// Carries the captured declaration and exact discovered content into ordinary preparation. public func updateRequest() -> UpdateRequest { var request = UpdateRequest( operation: .declaration(declaration), expectedDeclarationDigest: declarationDigest) request.expectedDiscoveryFingerprint = fingerprint + request.capturedAddition = addition + request.selectedIdentities = addition?.selectedIdentities + request.importPreparation = addition?.importPreparation return request } init( components: [ComponentInspection], sourceRevisions: [String: [String]], fingerprint: String, - readLocations: [URL], declaration: Declaration, declarationDigest: String + readLocations: [URL], declaration: Declaration, declarationDigest: String, + addition: CapturedAddition? = nil ) { self.components = components self.sourceRevisions = sourceRevisions @@ -31,6 +36,7 @@ public struct ComponentDiscovery: Sendable { self.readLocations = readLocations self.declaration = declaration self.declarationDigest = declarationDigest + self.addition = addition } } @@ -42,10 +48,19 @@ extension UpdateOperations { environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> ComponentDiscovery { let store = StateStore(scope: scope, environment: environment) + return try discover(declaration, store: store, destination: nil, importPreparation: nil) + } + + private static func discover( + _ declaration: Declaration, store: StateStore, destination: AdditionDestination?, + importPreparation: ImportPreparation?, allowNewIdentities: Bool = true + ) throws -> ComponentDiscovery { return try store.withReadLock { + try destination?.validate(in: store) + _ = try importPreparation?.capture() let baseline = try StatePrecondition(store: store) let previous = try store.readDeclaration(prepared: baseline) - _ = try store.readLedger(prepared: baseline) + let previousLedger = try store.readLedger(prepared: baseline) _ = try store.readWatch(prepared: baseline) let original = try store.declarationDocument(prepared: baseline) let change = try store.planDeclaration(declaration, replacing: previous, prepared: baseline) @@ -57,8 +72,13 @@ extension UpdateOperations { #else let platform = DeclarationPlatform.linux #endif + let impact = try LedgerImpact( + ledger: previousLedger, roots: store.ledgerRoots, kinds: [], names: [], updating: false) return try ComponentLinker.withLinkedComponents( - document: document, store: store, platform: platform + document: document, store: store, platform: platform, + preserving: destination == nil ? [:] : impact.pins, + directPins: destination == nil ? [:] : impact.directPins, + retaining: destination == nil ? nil : previousLedger ) { linked, session in let frozen = try LedgerFreeze.freezeWithSources( linked, session: session, @@ -67,6 +87,20 @@ extension UpdateOperations { limits: .standard) let ledger = frozen.ledger let fingerprint = try LedgerImpact.discoveryFingerprint(ledger, roots: store.ledgerRoots) + let introduced = try Set( + ledger.components.values.map { + try LedgerImpact.identity($0, ledger: ledger, roots: store.ledgerRoots) + } + ).subtracting( + previousLedger.components.values.map { + try LedgerImpact.identity($0, ledger: previousLedger, roots: store.ledgerRoots) + }) + let selected = allowNewIdentities ? introduced : Set() + if destination != nil { + try LedgerImpact.requireProtected( + previous: previousLedger, next: ledger, kinds: [], roots: store.ledgerRoots, + selectedIdentities: selected) + } let components = try componentInspections( ledger, roots: store.ledgerRoots, generation: ResolvedLedgerCodec.digest(ledger)) @@ -86,8 +120,123 @@ extension UpdateOperations { components: components, sourceRevisions: revisions, fingerprint: fingerprint, readLocations: Array(Set(locations)).sorted { $0.path < $1.path }, - declaration: declaration, declarationDigest: original?.digest ?? "absent") + declaration: declaration, declarationDigest: original?.digest ?? "absent", + addition: destination.map { + CapturedAddition( + destination: $0, declaration: declaration, fingerprint: fingerprint, + selectedIdentities: selected, importPreparation: importPreparation) + }) } } } } + +/// Immutable observations only; no source session, descriptor or borrowed resource is retained. +/// Core evidence types do not declare Sendable, but validate never mutates their captured values. +package final class AdditionDestination: @unchecked Sendable, CustomReflectable { + package var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } + let store: StateStore + let declaration: Declaration + private let state: [TargetPrecondition] + private let roots: [String: String] + private let identities: [PathIdentity] + + init(store: StateStore, declaration: Declaration, baseline: StatePrecondition) throws { + self.store = store + self.declaration = declaration + state = try [store.declarationURL, store.resolvedURL, store.watchURL].map { + try baseline.evidence(for: $0) + } + roots = store.ledgerRoots.mapValues { $0.standardizedFileURL.resolvingSymlinksInPath().path } + identities = try [store.environment.projectDirectory, store.environment.homeDirectory].map { + try PathIdentity($0) + } + } + + func validate(in current: StateStore) throws { + guard current.scope == store.scope, + current.directory.standardizedFileURL.path == store.directory.standardizedFileURL.path + else { throw CoreError.invalidState("captured addition belongs to another destination") } + for identity in identities { try identity.validate() } + for evidence in state { try evidence.validate() } + let currentRoots = current.ledgerRoots.mapValues { + $0.standardizedFileURL.resolvingSymlinksInPath().path + } + // New named target roots are admitted separately by Core's closed-route coordination. + guard roots.allSatisfy({ currentRoots[$0.key] == $0.value }) else { + throw CoreError.invalidState("captured addition destination roots changed") + } + } +} + +package struct CapturedAddition: Sendable { + let destination: AdditionDestination + let declaration: Declaration + let fingerprint: String + let selectedIdentities: Set + let importPreparation: ImportPreparation? + + func validate(_ request: UpdateRequest, in store: StateStore) throws { + try destination.validate(in: store) + guard case .declaration(let candidate) = request.operation, candidate == declaration, + request.kinds == nil, request.names.isEmpty, request.selections.isEmpty, + request.agents == nil, + request.selectedIdentities == selectedIdentities, + request.expectedDiscoveryFingerprint == fingerprint + else { throw CoreError.invalidState("captured addition was modified; refresh selection") } + } +} + +extension UpdateOperations { + /// Composes finite root additions without refreshing any recorded component. Empty effects + /// return nil, including a source-only selection, and never initialize destination state. + package static func captureAddition( + _ additions: Declaration, in inspection: ScopeInspection, + importPreparation: ImportPreparation? = nil + ) throws -> ComponentDiscovery? { + guard !additions.components.isEmpty || !additions.groups.isEmpty || !additions.uses.isEmpty + else { return nil } + guard !inspection.recovery.pending, let destination = inspection.additionDestination else { + throw CoreError.invalidState("inspect the committed destination before selecting additions") + } + guard additions.agents == nil, additions.watch == nil, additions.exports.isEmpty else { + throw CoreError.invalidState("finite additions cannot replace scope defaults or exports") + } + try destination.validate(in: destination.store) + // Existing authored intent must already match its lock; selection cannot publish pending + // authoring changes merely because they happen to appear in the composed graph. + _ = try discover( + destination.declaration, store: destination.store, destination: destination, + importPreparation: nil, allowNewIdentities: false) + var candidate = destination.declaration + for entry in additions.sourceDeclarations { + if let existing = candidate.sources[entry.name] { + guard existing.kind == entry.source.kind, existing.requirement == entry.source.requirement, + existing.path == entry.source.path, + try existing.identity(environment: destination.store.environment) + == entry.source.identity(environment: destination.store.environment) + else { + throw CoreError.invalidState("source alias conflicts with the destination: " + entry.name) + } + } else { + candidate.sourceDeclarations.append(entry) + } + } + for group in additions.groups { + if let existing = candidate.groups.first(where: { $0.name == group.name }) { + guard existing == group else { + throw CoreError.invalidState("group conflicts with the destination: " + group.name) + } + } else { + candidate.groups.append(group) + } + } + for component in additions.components where !candidate.components.contains(component) { + candidate.components.append(component) + } + for use in additions.uses where !candidate.uses.contains(use) { candidate.uses.append(use) } + return try discover( + candidate, store: destination.store, destination: destination, + importPreparation: importPreparation) + } +} diff --git a/Sources/AgentsUpdates/ScopeInspection.swift b/Sources/AgentsUpdates/ScopeInspection.swift index 8229824..d8d15ce 100644 --- a/Sources/AgentsUpdates/ScopeInspection.swift +++ b/Sources/AgentsUpdates/ScopeInspection.swift @@ -121,6 +121,7 @@ public struct RecoveryInspection: Sendable { /// One read generation. No native bytes, retained content objects, provider calls or recovery. public struct ScopeInspection: Sendable { + package let additionDestination: AdditionDestination? public let scope: InstallScope public let document: DeclarationDocument? public let declaration: Declaration? @@ -150,7 +151,8 @@ extension UpdateOperations { onPendingRecovery: { let diagnostic = FileTransaction.recoveryDiagnostic(store: store) return ScopeInspection( - scope: scope, document: nil, declaration: nil, generation: nil, + additionDestination: nil, scope: scope, document: nil, declaration: nil, + generation: nil, sources: [], components: [], groups: [], resources: [], deployments: [], watch: nil, recovery: .init( pending: true, requiresOwner: diagnostic.requiresOwner, @@ -230,6 +232,8 @@ extension UpdateOperations { + installations.values.map(\.url) try baseline.validate() return ScopeInspection( + additionDestination: try AdditionDestination( + store: store, declaration: declaration, baseline: baseline), scope: scope, document: document, declaration: declaration, generation: generation, sources: sources, components: components, groups: groups, resources: resources, deployments: deployments, watch: watch, diff --git a/Sources/AgentsUpdates/SourceImportOperations.swift b/Sources/AgentsUpdates/SourceImportOperations.swift index 0967df4..62cdb20 100644 --- a/Sources/AgentsUpdates/SourceImportOperations.swift +++ b/Sources/AgentsUpdates/SourceImportOperations.swift @@ -195,10 +195,8 @@ public struct SourceImportInspection: Sendable { /// semantics and required bindings must be resolved through supported inputs. Preserved /// resources requiring a binding rewrite need corrected content, even after slot resolution. public func updateRequest(in inspection: ScopeInspection) throws -> UpdateRequest { - guard !inspection.recovery.pending, var declaration = inspection.declaration else { - throw CoreError.invalidState("inspect the committed scope before preparing an import") - } try preparation.validateConversion() + var additions = Declaration() for source in preparation.proposal.sources { guard var imported = source.declaration else { throw CoreError.invalidState("import lacks exact canonical source coordinates") @@ -211,27 +209,14 @@ public struct SourceImportInspection: Sendable { imported.location = String(identity.dropFirst("local:".count)) imported.environment = nil } - if let existing = declaration.sources[source.alias] { - let oldIdentity = try existing.identity(environment: RuntimeEnvironment(environment: [:])) - let newIdentity = try imported.identity(environment: RuntimeEnvironment(environment: [:])) - guard existing.kind == imported.kind, existing.requirement == imported.requirement, - existing.path == imported.path, oldIdentity == newIdentity - else { - throw CoreError.invalidState( - "import source alias conflicts with the captured declaration: " + source.alias) - } - } - declaration.sources[source.alias] = imported + additions.sourceDeclarations.append(.init(name: source.alias, source: imported)) } - for component in preparation.proposal.components - where !declaration.components.contains(component.declaration) { - declaration.components.append(component.declaration) - } - var request = UpdateRequest( - operation: .declaration(declaration), - expectedDeclarationDigest: inspection.document?.digest ?? "absent") - request.importPreparation = preparation - return request + additions.components = preparation.proposal.components.map(\.declaration) + guard + let discovery = try UpdateOperations.captureAddition( + additions, in: inspection, importPreparation: preparation) + else { throw CoreError.invalidState("import selection contains no new additions") } + return discovery.updateRequest() } /// Revalidates the captured inputs, then reruns the same adapter with owner-issued choices. diff --git a/Sources/AgentsUpdates/UpdateOperations.swift b/Sources/AgentsUpdates/UpdateOperations.swift index b1f2d33..8944e45 100644 --- a/Sources/AgentsUpdates/UpdateOperations.swift +++ b/Sources/AgentsUpdates/UpdateOperations.swift @@ -23,6 +23,7 @@ public enum UpdateOperations { checkpoint: @escaping (String) throws -> Void ) throws -> CombinedUpdateReport { let store = StateStore(scope: scope, environment: environment) + try request.capturedAddition?.validate(request, in: store) var admitted = Set() var installations: [String: SkillInstallationTarget] = [:] while true { @@ -72,6 +73,7 @@ public enum UpdateOperations { _ body: (PreparedUpdate) throws -> Result ) throws -> Result { let store = StateStore(scope: scope, environment: environment) + try request.capturedAddition?.validate(request, in: store) let outcome = TransactionOutcome() defer { completion?(outcome) } var delivered = false diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 98b9d14..0054f0b 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -33,6 +33,7 @@ final class UpdatePlan { _ body: (UpdatePlan) throws -> T ) throws -> T { var request = request + try request.capturedAddition?.validate(request, in: store) let importInputs = try request.importPreparation?.capture() ?? [] let baseline = try StatePrecondition(store: store) let previous = try store.readLedger(prepared: baseline) @@ -126,7 +127,7 @@ final class UpdatePlan { if case .update = request.operation { updating = true } else { - updating = request.expectedDiscoveryFingerprint != nil + updating = request.expectedDiscoveryFingerprint != nil && request.capturedAddition == nil } let removing: Bool if case .remove = request.operation { removing = true } else { removing = false } diff --git a/Sources/AgentsUpdates/UpdateRequest.swift b/Sources/AgentsUpdates/UpdateRequest.swift index c08f35a..4d007d0 100644 --- a/Sources/AgentsUpdates/UpdateRequest.swift +++ b/Sources/AgentsUpdates/UpdateRequest.swift @@ -11,6 +11,7 @@ public enum UpdateOperation: Sendable { /// Selection constrains application and protects the recorded semantics of every other domain. public struct UpdateRequest: Sendable { + package var capturedAddition: CapturedAddition? package var importPreparation: ImportPreparation? package var expectedDiscoveryFingerprint: String? package var automaticSkill: (source: String, name: String)? diff --git a/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift b/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift index bd37953..52ad878 100644 --- a/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift +++ b/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift @@ -302,3 +302,260 @@ struct ConsumerLifecycleRegressionTests { #expect(try f.snapshot() == before) } } + +extension ConsumerLifecycleRegressionTests { + private func finiteRules(_ f: UpdateFixture) -> Declaration { + Declaration( + sources: ["fixture": SourceDeclaration(kind: .local, location: f.repo.path)], + components: [ + .instructions(InstructionsDeclaration(agents: [.codex], sections: ["fixture:extra"])) + ]) + } + + private func writeFiniteRules(_ f: UpdateFixture) throws { + try f.write( + "---\ndescription: Extra.\n---\n# Extra\n\nSelected addition\n", + to: f.repo.appendingPathComponent("instructions/extra.md")) + try f.commit() + } + + @Test func finiteAdditionPreservesPinsAndSharedInstructionSurvivors() throws { + let f = try UpdateFixture() + try f.install(agents: [.codex]) + let previous = try f.store.loadLedger() + let original = try f.store.loadDeclaration() + try f.advance() + try writeFiniteRules(f) + let before = try FileHash.folderHash(f.root) + let scope = try UpdateOperations.inspect(environment: f.environment) + let discovery = try #require(try UpdateOperations.captureAddition(finiteRules(f), in: scope)) + #expect(try FileHash.folderHash(f.root) == before) + var request = discovery.updateRequest() + request.replace = true + request.changingAccess = true + let preview = try UpdateOperations.preview(request, environment: f.environment) + let target = try #require(preview.instructions.targets.first { $0.url == f.instruction() }) + let bytes = try #require(target.after) + #expect(String(decoding: bytes, as: UTF8.self).contains("Selected addition")) + #expect(String(decoding: bytes, as: UTF8.self).contains("old")) + #expect(!String(decoding: bytes, as: UTF8.self).contains("\nnew\n")) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + #expect(try f.bytes(f.instruction()) == bytes) + let next = try f.store.loadLedger() + for (id, component) in previous.components { + #expect(next.components[id] == component) + #expect(next.sources[component.source] == previous.sources[component.source]) + } + let declaration = try f.store.loadDeclaration() + #expect(Array(declaration.components.prefix(original.components.count)) == original.components) + #expect(declaration.sources["fixture"] == original.sources["fixture"]) + } + + @Test func capturedAdditionRejectsForeignDestinationAndMutatedRequest() throws { + let f = try UpdateFixture() + let other = try UpdateFixture() + try writeFiniteRules(f) + for fixture in [f, other] { + try fixture.store.save(declaration: Declaration(agents: [.codex]), ledger: ResolvedLedger()) + } + #expect(try f.bytes(f.store.declarationURL) == other.bytes(other.store.declarationURL)) + var environment = f.environment + environment.environment["INSPECTION_SECRET"] = "CAPTURED_ENVIRONMENT_CANARY" + let inspection = try UpdateOperations.inspect(environment: environment) + #expect(!String(reflecting: inspection).contains("CAPTURED_ENVIRONMENT_CANARY")) + let discovery = try #require( + try UpdateOperations.captureAddition(finiteRules(f), in: inspection)) + #expect(!String(reflecting: discovery).contains("CAPTURED_ENVIRONMENT_CANARY")) + let otherBefore = try FileHash.folderHash(other.root) + var called = false + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate( + discovery.updateRequest(), environment: other.environment + ) { + _ in called = true + } + } + #expect(!called) + #expect(try FileHash.folderHash(other.root) == otherBefore) + var modified = discovery.updateRequest() + modified.operation = .update + #expect(throws: (any Error).self) { + try UpdateOperations.preview(modified, environment: f.environment) + } + _ = try UpdateOperations.withPreparedUpdate( + discovery.updateRequest(), environment: f.environment + ) { + try $0.apply() + } + #expect(try f.store.loadDeclaration().sources["fixture"] != nil) + } + + @Test(arguments: ["declaration", "ledger", "source"]) + func capturedAdditionRejectsChangedEvidence(_ changed: String) throws { + let f = try UpdateFixture() + try f.install(agents: [.codex]) + try writeFiniteRules(f) + let discovery = try #require( + try UpdateOperations.captureAddition( + finiteRules(f), in: UpdateOperations.inspect(environment: f.environment))) + if changed == "declaration" { + try f.write( + String(decoding: f.bytes(f.store.declarationURL), as: UTF8.self) + "\n# changed\n", + to: f.store.declarationURL) + } else if changed == "ledger" { + try f.write( + String(decoding: f.bytes(f.store.resolvedURL), as: UTF8.self) + "\n", + to: f.store.resolvedURL) + } else { + try f.write( + "---\ndescription: Extra.\n---\n# Extra\n\nChanged selected source\n", + to: f.repo.appendingPathComponent("instructions/extra.md")) + try f.commit() + } + var called = false + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(discovery.updateRequest(), environment: f.environment) + { + _ in called = true + } + } + #expect(!called) + } + + @Test func emptyAdditionDoesNotInitializeAndPendingAuthoredGraphIsProtected() throws { + let f = try UpdateFixture() + let scope = try UpdateOperations.inspect(environment: f.environment) + let before = try FileHash.folderHash(f.root) + #expect( + try UpdateOperations.captureAddition( + Declaration(sources: ["unused": .init(kind: .local, location: "/absent")]), in: scope) + == nil) + #expect(try FileHash.folderHash(f.root) == before) + try f.declare(agents: [.codex]) + try writeFiniteRules(f) + #expect(throws: (any Error).self) { + try UpdateOperations.captureAddition( + finiteRules(f), in: UpdateOperations.inspect(environment: f.environment)) + } + } +} + +extension ConsumerLifecycleRegressionTests { + @Test(arguments: [false, true]) + func finiteAdditionProtectsConditionalProducerUsesAndConflictingPins(_ sharedSource: Bool) throws + { + let f = try UpdateFixture() + let producerFixture = try sharedSource ? f : UpdateFixture() + try producerFixture.write( + """ + version: 1 + groups: + tools: + components: [{kind: mcpServer, name: protected-tool, transport: {kind: stdio, executable: never-run}, agents: [claude-code]}] + exports: [tools] + """, to: producerFixture.repo.appendingPathComponent(".agent/agents.yaml")) + try producerFixture.commit() + try f.declare(agents: [.codex]) + var original = try f.store.loadDeclaration() + let alias = sharedSource ? "fixture" : "producer" + if !sharedSource { + original.sources[alias] = .init(kind: .local, location: producerFixture.repo.path) + } + original.uses = [.init(name: "tools", source: alias, condition: .init(scopes: [.project]))] + try f.store.save(declaration: original, ledger: ResolvedLedger()) + _ = try f.apply() + let previous = try UpdateOperations.inspect(environment: f.environment) + let producer = try #require(previous.components.first { $0.name == "protected-tool" }) + #expect(producer.occurrences.allSatisfy { !$0.consumerEditable }) + try writeFiniteRules(f) + let scope = try UpdateOperations.inspect(environment: f.environment) + var conflicting = finiteRules(f) + conflicting.sources["fixture"]?.location = f.root.path + #expect(throws: (any Error).self) { + try UpdateOperations.captureAddition(conflicting, in: scope) + } + if sharedSource { + let before = try f.snapshot() + #expect(throws: (any Error).self) { + try UpdateOperations.captureAddition(finiteRules(f), in: scope) + } + #expect(try f.snapshot() == before) + return + } + let discovery = try #require(try UpdateOperations.captureAddition(finiteRules(f), in: scope)) + let preview = try UpdateOperations.preview( + discovery.updateRequest(), environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate( + discovery.updateRequest(), environment: f.environment + ) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let next = try UpdateOperations.inspect(environment: f.environment) + let retained = try #require(next.components.first { $0.name == "protected-tool" }) + #expect(retained.revision == producer.revision) + #expect(retained.configuration == producer.configuration) + #expect(retained.conditions == producer.conditions) + #expect(retained.occurrences.allSatisfy { !$0.consumerEditable }) + #expect(try f.store.loadDeclaration().uses == original.uses) + #expect(throws: (any Error).self) { + try UpdateOperations.preview( + .init(operation: .remove, selections: [retained.selection]), + environment: f.environment) + } + } + +} + +extension ConsumerLifecycleRegressionTests { + @Test func finiteAdditionRefusesNewForeignTargetBeforeCallback() throws { + let f = try UpdateFixture() + try writeFiniteRules(f) + let discovery = try #require( + try UpdateOperations.captureAddition( + finiteRules(f), in: UpdateOperations.inspect(environment: f.environment))) + _ = try UpdateOperations.preview(discovery.updateRequest(), environment: f.environment) + try f.write("Handwritten after preview\n", to: f.instruction()) + var called = false + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(discovery.updateRequest(), environment: f.environment) + { + _ in called = true + } + } + #expect(!called) + #expect(try f.bytes(f.instruction()) == Data("Handwritten after preview\n".utf8)) + #expect(!FileManager.default.fileExists(atPath: f.store.declarationURL.path)) + #expect(!FileManager.default.fileExists(atPath: f.store.resolvedURL.path)) + } +} + +extension ConsumerLifecycleRegressionTests { + @Test func finiteNamedCommandAdmitsItsNewClosedRoute() throws { + let f = try UpdateFixture() + let scope = try UpdateOperations.inspect(environment: f.environment) + let discovery = try #require( + try UpdateOperations.captureAddition( + Declaration(components: [ + .command( + name: "review", description: "Review sources", + prompt: .literal("Review exact sources."), agents: [.claudeCode]) + ]), in: scope)) + let before = try FileHash.folderHash(f.root) + let preview = try UpdateOperations.preview( + discovery.updateRequest(), environment: f.environment) + #expect(try FileHash.folderHash(f.root) == before) + _ = try UpdateOperations.withPreparedUpdate( + discovery.updateRequest(), environment: f.environment + ) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let installed = try UpdateOperations.inspect(environment: f.environment) + let deployment = try #require(installed.deployments.first) + #expect(deployment.status == .current) + #expect( + try String(contentsOf: deployment.location, encoding: .utf8).contains("Review exact sources.") + ) + } +} From 02c543b55696c1c50dfe2bd3f7b31a3e234606d2 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:22:49 +0800 Subject: [PATCH 137/171] feat: enumerate representable source catalog choices --- Documentation/Architecture/Package.md | 14 + Sources/Components/ComponentLinker.swift | 5 +- Sources/Components/SourceCatalog.swift | 353 ++++++++++++++++++ .../ComponentsTests/SourceCatalogTests.swift | 237 ++++++++++++ 4 files changed, 607 insertions(+), 2 deletions(-) create mode 100644 Sources/Components/SourceCatalog.swift create mode 100644 Tests/ComponentsTests/SourceCatalogTests.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 62fb9ba..1abc329 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -406,6 +406,20 @@ caller to redact; they have no automatic serialized representation. origin, deadline and resource-cleanup behavior in ComponentsTests. They do not use external services or execute configured third-party clients. +Components' package-only `SourceCatalog` enumerates one explicit source and discovery +root using temporary snapshot acquisition, existing skill/instruction readers, +producer export linking and native import adapters. Inspection-bound IDs identify +representable units; exported groups keep symbolic uses and complete producer-owned +closures. Native registration and component expansion are explicit choices, including +empty containers. Opaque registration requires the exact container name from adapter +metadata; unresolved requirements remain visible and cannot be selected. Member +units carry typed kind selections and byte-exact sibling exclusions. Importer +keys retain the adapter's complete family effects, fixed contributions, requirements +and separate producer selection claims. Captured content and paths remain source- +relative; borrowed extraction URLs never escape. Empty selection yields no addition. +Destination-bound composition, pin protection and publication remain in AgentsUpdates; +the package catalog does not create update requests. + ## AgentsUpdates `UpdateOperations.preview` plans all declared skills, instruction targets and diff --git a/Sources/Components/ComponentLinker.swift b/Sources/Components/ComponentLinker.swift index 06a3cf1..79c4c63 100644 --- a/Sources/Components/ComponentLinker.swift +++ b/Sources/Components/ComponentLinker.swift @@ -60,7 +60,7 @@ final class Linking { let session: SourceResolutionSession let directPins: [ComponentKey: SourceRevision] let retainedLedger: ResolvedLedger? - let budget = LinkBudget() + let budget: LinkBudget var documents: [GroupIdentity: LinkingDocument] = [:] var nonGit = Set() var git = Set() @@ -72,7 +72,7 @@ final class Linking { init( document: DeclarationDocument, store: StateStore, platform: DeclarationPlatform, session: SourceResolutionSession, directPins: [ComponentKey: SourceRevision], - retainedLedger: ResolvedLedger? + retainedLedger: ResolvedLedger?, budget: LinkBudget = LinkBudget() ) { self.document = document self.store = store @@ -80,6 +80,7 @@ final class Linking { self.session = session self.directPins = directPins self.retainedLedger = retainedLedger + self.budget = budget } /// An implicit selection admits only members owned by its recorded index. The component key diff --git a/Sources/Components/SourceCatalog.swift b/Sources/Components/SourceCatalog.swift new file mode 100644 index 0000000..1d45f25 --- /dev/null +++ b/Sources/Components/SourceCatalog.swift @@ -0,0 +1,353 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import Foundation + +/// An explicitly chosen adapter document, relative to the source's discovery root. +package struct SourceCatalogImport: Sendable { + package let profile: SourceImportProfile + package let document: String + package var selection: Set? = nil + package init(profile: SourceImportProfile, document: String, selection: Set? = nil) { + self.profile = profile + self.document = document + self.selection = selection + } +} + +/// Temporary source enumeration, with stable coordinates and no borrowed resource URLs. +/// Destination composition and publication belong to the captured-addition owner. +package struct SourceCatalog: Sendable { + package struct ID: Hashable, Sendable { + fileprivate let owner: UUID + fileprivate let index: Int + } + + package enum Unit: Sendable { + case skill(String) + case instruction(String) + case group(GroupUseDeclaration) + case nativePlugin(ComponentDeclaration) + case componentsPlugin(ComponentDeclaration) + /// One member is representable through typed kind selection and sibling exclusions. + case pluginMember(ComponentDeclaration, ComponentReferenceDeclaration) + /// Metadata is issued by the adapter; its key is never derived from the display label. + case importer(ImportChoiceMetadata) + } + + package struct ImportEffects: Sendable { + package let sources: [ImportedSource] + package let components: [ImportedComponent] + package let resources: [ImportResourceProposal] + package let diagnostics: [SourceImportDiagnostic] + } + + package struct Choice: Sendable { + package let id: ID + package let label: String + package let origin: ImportLocation + package let unit: Unit + /// Actual linked closure, including restrictions, pins, resources and repeated occurrences. + package let graph: LinkedComponents? + package let imported: ImportEffects? + package let artifact: LockedArtifact? + package let unavailableReason: String? + } + + package let alias: String + package let source: SourceDeclaration + package let snapshot: SourceSnapshotID + package let root: String + package let contentHash: String + package let choices: [Choice] + package let fixedEffects: ImportEffects? + package let requiredInputs: [ImportInputMetadata] + package let bindings: [ImportBindingRequirement] + package let producerSelections: [ImportProducerSelection] + package let importDocument: SourceCatalogImport? + private let owner: UUID + + /// Empty catalog selection is no addition. This resolves handles to representable units only; + /// it neither composes a declaration nor grants an unrestricted update capability. + package func selected(_ ids: [ID]) throws -> [Choice]? { + guard Set(ids).count == ids.count, + ids.allSatisfy({ $0.owner == owner && choices.indices.contains($0.index) }) + else { throw CoreError.invalidState("source choices belong to another inspection") } + guard !ids.isEmpty else { return nil } + let selected = ids.map { choices[$0.index] } + if let reason = selected.compactMap(\.unavailableReason).first { + throw CoreError.invalidSource(reason) + } + return selected + } + + package static func inspect( + alias: String, source: SourceDeclaration, store: StateStore, platform: DeclarationPlatform, + importing imported: SourceCatalogImport? = nil + ) throws -> SourceCatalog { + try Declaration(sources: [alias: source]).validate(environment: store.environment) + let owner = UUID() + let budget = LinkBudget() + if source.kind == .wellKnown { + guard imported == nil else { + throw CoreError.invalidSource("skill indexes do not contain adapter documents") + } + let skills = try SkillSnapshotReader.index(source) + let hash = FileHash.sha256Hex( + data: try JSONEncoder().encode(skills.map { [$0.name, $0.artifact.digest] })) + let snapshot = try SourceSnapshotID( + source: source.identity(environment: store.environment), revision: "sha256:" + hash) + try budget.snapshot(snapshot) + let choices = try skills.enumerated().map { index, skill in + try budget.contribution(chain: 0) + try budget.snapshot(.init(source: snapshot.source, revision: skill.artifact.digest)) + return Choice( + id: .init(owner: owner, index: index), label: label("Skill", skill.name), + origin: .init(document: skill.name, pointer: ""), unit: .skill(skill.name), + graph: nil, imported: nil, artifact: skill.artifact, unavailableReason: nil) + } + return .init( + alias: alias, source: source, snapshot: snapshot, root: source.path ?? ".", + contentHash: hash, choices: choices, fixedEffects: nil, requiredInputs: [], bindings: [], + producerSelections: [], importDocument: nil, owner: owner) + } + return try SourceResolutionSession.withTemporaryRead(store: store) { session in + let view: SourceSnapshot + if try source.requirement != nil || session.isGitSource(source) { + guard + let pin = try session.candidates( + for: source, requirements: [source.requirement], spending: budget.step + ).first + else { throw CoreError.invalidSource("source has no matching revision") } + view = try session.snapshot(source, at: pin) + } else { + view = try session.localSnapshot(source) + } + try budget.snapshot(view.snapshot) + let hash = try FileHash.folderHash(view.directory()) + func admitManifest(_ path: String) throws { + let handle = try FileHandle(forReadingFrom: view.resource(path)) + defer { try? handle.close() } + let bytes = try handle.read(upToCount: SourceImportLimits().documentBytes + 1) ?? Data() + try budget.manifest(view.snapshot, path: path, bytes: bytes.count) + } + var choices: [Choice] = [] + func issue( + _ unit: Unit, label: String, origin: ImportLocation, graph: LinkedComponents? = nil, + effects: ImportEffects? = nil, unavailable: String? = nil + ) throws { + try budget.contribution(chain: 0) + choices.append( + .init( + id: .init(owner: owner, index: choices.count), label: label, origin: origin, + unit: unit, graph: graph, imported: effects, artifact: nil, + unavailableReason: unavailable)) + } + func linked(_ component: ComponentDeclaration?, use: GroupUseDeclaration? = nil) throws + -> LinkedComponents + { + let declaration = Declaration( + sources: [alias: source], components: component.map { [$0] } ?? [], + uses: use.map { [$0] } ?? []) + let identity = DocumentIdentity("catalog/agents.yaml") + let bytes = + try DeclarationEditPlan.bytes( + replacing: Declaration(), with: declaration, in: nil, identity: identity, + environment: store.environment) ?? Array("version: 1\n".utf8) + let linker = Linking( + document: try DeclarationDocument(bytes: bytes, identity: identity), store: store, + platform: platform, session: session, directPins: [:], retainedLedger: nil, budget: budget + ) + return try linker.solve(preserving: view.pin.map { [view.snapshot.source: $0] } ?? [:]) + } + func resolved( + _ unit: Unit, component: ComponentDeclaration? = nil, use: GroupUseDeclaration? = nil, + label: String, origin: ImportLocation, unavailable: String? = nil + ) throws { + do { + try issue( + unit, label: label, origin: origin, graph: linked(component, use: use), + unavailable: unavailable) + } catch is CancellationError { throw CancellationError() } catch let error as LinkError { + if case .budget = error { throw error } + try issue(unit, label: label, origin: origin, unavailable: diagnostic(error, view: view)) + } catch { + try issue(unit, label: label, origin: origin, unavailable: diagnostic(error, view: view)) + } + } + if let imported { + let document = try view.relativePath( + PathSafety.resolvedChild(base: view.directory(), subpath: imported.document)) + var input = SourceImportInput( + profile: imported.profile, root: view.root, document: document, + selection: imported.selection) + try admitManifest(document) + let current = try SourceImport.preview(input) + input.selection = nil + input.enumerateChoices = true + let proposal = try SourceImport.preview(input) + func effects( + _ components: [Int], _ sources: [Int], _ resources: [Int], _ diagnostics: [Int] + ) + -> ImportEffects + { + .init( + sources: sources.map { stable(proposal.sources[$0], view: view) }, + components: components.map { proposal.components[$0] }, + resources: resources.map { proposal.resources[$0] }, + diagnostics: diagnostics.map { proposal.diagnostics[$0] }) + } + for (index, choice) in proposal.choices.enumerated() { + try issue( + .importer(choice), label: "Producer selection \(index + 1)", + origin: choice.locations.first ?? .init(document: document, pointer: ""), + effects: effects( + choice.components, choice.sources, choice.resources, choice.diagnostics)) + } + let components = Set(proposal.choices.flatMap(\.components)) + let sources = Set(proposal.choices.flatMap(\.sources)) + let resources = Set(proposal.choices.flatMap(\.resources)) + let diagnostics = Set(proposal.choices.flatMap(\.diagnostics)) + let fixed = effects( + proposal.components.indices.filter { !components.contains($0) }, + proposal.sources.indices.filter { !sources.contains($0) }, + proposal.resources.indices.filter { !resources.contains($0) }, + proposal.diagnostics.indices.filter { !diagnostics.contains($0) }) + return .init( + alias: alias, source: source, snapshot: view.snapshot, root: view.discoveryPath, + contentHash: hash, choices: choices, fixedEffects: fixed, + requiredInputs: proposal.requiredInputs, bindings: proposal.bindings, + producerSelections: current.selections, importDocument: imported, owner: owner) + } + for skill in try SkillSnapshotReader.read(view) { + try resolved( + .skill(skill.name), + component: .skills(source: alias, .init(select: .names([skill.name]))), + label: label("Skill", skill.name), origin: .init(document: skill.path, pointer: "")) + } + for instruction in try InstructionSnapshotReader.read(view) { + let component = ComponentDeclaration.instructions( + .init(sections: [alias + ":" + instruction.name])) + try resolved( + .instruction(instruction.name), component: component, + label: label("Instruction", instruction.name), + origin: .init(document: instruction.path, pointer: "")) + } + let manifest = try view.relativePath( + view.directory().appendingPathComponent( + view.directory().lastPathComponent == ".agent" ? "agents.yaml" : ".agent/agents.yaml")) + if FileManager.default.fileExists(atPath: try view.resource(manifest).path) { + let document = try DeclarationDocument( + bytes: Array("version: 1\n".utf8), identity: .init("catalog/agents.yaml")) + let linker = Linking( + document: document, store: store, platform: platform, session: session, + directPins: [:], retainedLedger: nil, budget: budget) + let producer = try linker.producer(view, chain: []) + for name in producer.declaration.exports { + let use = GroupUseDeclaration(name: name, source: alias) + try resolved( + .group(use), use: use, label: label("Group", name), + origin: .init(document: manifest, pointer: "/exports")) + } + } + var nativeBindings: [ImportBindingRequirement] = [] + var nativeInputs: [ImportInputMetadata] = [] + var nativeSelections: [ImportProducerSelection] = [] + for (profile, suffix, agent) in [ + (SourceImportProfile.claudePluginV1, ".claude-plugin/plugin.json", AgentID.claudeCode), + (.cursorPluginV1, ".cursor-plugin/plugin.json", .cursor), + (.geminiExtensionV1, "gemini-extension.json", .geminiCLI), + ] { + let document = try view.relativePath( + PathSafety.resolvedChild(base: view.directory(), subpath: suffix)) + guard FileManager.default.fileExists(atPath: try view.resource(document).path) else { + continue + } + try admitManifest(document) + let proposal = try SourceImport.preview( + .init(profile: profile, root: view.root, document: document)) + let nativeName = proposal.packageMetadata?.name + let native = ComponentDeclaration.plugin( + name: nativeName ?? alias, path: ".", source: alias, mode: .native, agents: [agent]) + try resolved( + .nativePlugin(native), component: native, label: "Native \(agent.rawValue) registration", + origin: .init(document: document, pointer: ""), + unavailable: nativeName == nil + ? "native registration requires adapter-issued container name metadata" : nil) + nativeBindings += proposal.bindings + nativeInputs += proposal.requiredInputs + nativeSelections += proposal.selections + let whole = ComponentDeclaration.plugin( + name: alias, path: ".", source: alias, mode: .components, agents: [agent]) + try resolved( + .componentsPlugin(whole), component: whole, + label: "Components \(agent.rawValue) container", + origin: .init(document: document, pointer: "")) + for member in proposal.components { + guard let selector = member.member?.selector else { continue } + let identity = try ResolvedLedgerCodec.bytes(LedgerPayload.reference(selector)) + try budget.step(proposal.components.count) + let siblings = proposal.components.filter { + $0.declaration.kind == member.declaration.kind + }.compactMap(\.member?.selector) + let exclusions = try siblings.filter { + try ResolvedLedgerCodec.bytes(LedgerPayload.reference($0)) != identity + } + let component = ComponentDeclaration.plugin( + name: alias, path: ".", source: alias, mode: .components, + select: [member.declaration.kind], exclude: exclusions, agents: [agent]) + try resolved( + .pluginMember(component, selector), component: component, + label: label(member.declaration.kind.rawValue, member.declaration.name ?? "member"), + origin: member.origin) + } + } + return .init( + alias: alias, source: source, snapshot: view.snapshot, root: view.discoveryPath, + contentHash: hash, choices: choices, fixedEffects: nil, requiredInputs: nativeInputs, + bindings: nativeBindings, producerSelections: nativeSelections, importDocument: nil, + owner: owner) + } + } + + private static func label(_ kind: String, _ name: String) -> String { + kind + " " + + String( + String.UnicodeScalarView( + name.unicodeScalars.map { + CharacterSet.controlCharacters.contains($0) ? UnicodeScalar(0xfffd)! : $0 + })) + } + + private static func diagnostic(_ error: any Error, view: SourceSnapshot) -> String { + String(describing: error) + .replacingOccurrences(of: view.root.path, with: view.snapshot.source) + .replacingOccurrences( + of: view.root.resolvingSymlinksInPath().path, with: view.snapshot.source) + } + + /// Relative imported coordinates remain anchored to the catalog snapshot, never its borrowed URL. + private static func stable(_ value: ImportedSource, view: SourceSnapshot) -> ImportedSource { + func relative(_ path: String?) -> String? { + guard let path, path.hasPrefix("/"), + PathSafety.isContained(URL(fileURLWithPath: path), in: view.root) + else { return path } + return PathSafety.relativePath(path, to: view.root.path) + } + var declaration = value.declaration + if let location = declaration?.location, declaration?.kind == .local, + location.hasPrefix("/"), + PathSafety.isContained(URL(fileURLWithPath: location), in: view.root) + { + declaration?.location = PathSafety.relativePath(location, to: view.root.path) + } + declaration?.environment = nil + return .init( + alias: value.alias, origin: value.origin, declaration: declaration, pin: value.pin, + requestedRef: value.requestedRef, producerPath: relative(value.producerPath), + producerIdentity: value.producerIdentity, registry: value.registry, + resolvedRef: value.resolvedRef, + resolvedURL: value.resolvedURL, developmentOnly: value.developmentOnly) + } +} diff --git a/Tests/ComponentsTests/SourceCatalogTests.swift b/Tests/ComponentsTests/SourceCatalogTests.swift new file mode 100644 index 0000000..02601e6 --- /dev/null +++ b/Tests/ComponentsTests/SourceCatalogTests.swift @@ -0,0 +1,237 @@ +import AgentsCore +import AgentsManifest +import Foundation +import Testing + +@testable import Components + +@Suite("Explicit source catalogs", .serialized) +struct SourceCatalogTests { + private func inspect( + _ fixture: LinkFixture, path: String = ".", importing document: SourceCatalogImport? = nil + ) throws -> Components.SourceCatalog { + try Components.SourceCatalog.inspect( + alias: "producer", source: .init(kind: .local, location: fixture.project.path, path: path), + store: fixture.store, platform: .macOS, importing: document) + } + + @Test func directMembersAndSymbolicGroupsHaveCompleteCapturedEffects() throws { + let fixture = try LinkFixture() + try fixture.skill("demo", at: fixture.project, restrictions: "agents: [codex]\n") + try fixture.instruction("rules", at: fixture.project, own: false) + try fixture.manifest( + """ + version: 1 + exports: [outer, empty] + groups: + outer: + components: + - {kind: command, name: review, description: Review, prompt: Exact, agents: [codex]} + uses: [{group: inner}, {group: inner}] + inner: + components: + - {kind: mcpServer, name: safe, transport: {kind: stdio, executable: fixture-server}, agents: [codex]} + empty: {} + """, at: fixture.project) + let before = try FileHash.folderHash(fixture.root) + let catalog = try inspect(fixture) + #expect(catalog.choices.count == 4) + let skill = try #require( + catalog.choices.first { + if case .skill = $0.unit { return true } + return false + }) + #expect(skill.graph?.components.first?.recipients == [.codex]) + let group = try #require( + catalog.choices.first { + if case .group(let use) = $0.unit { return use.name == "outer" && use.source == "producer" } + return false + }) + #expect(group.unavailableReason == nil) + #expect(group.graph?.references.count == 3) + #expect(group.graph?.components.flatMap(\.origins).count == 3) + #expect( + group.graph?.components.allSatisfy { $0.origins.allSatisfy { !$0.consumerEditable } } == true) + let empty = try #require( + catalog.choices.first { + if case .group(let use) = $0.unit { return use.name == "empty" } + return false + }) + #expect(empty.graph?.components.isEmpty == true) + #expect(empty.graph?.references.count == 1) + #expect(try catalog.selected([]) == nil) + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(!String(reflecting: catalog).contains("agents-resolution-")) + let other = try inspect(fixture) + #expect(throws: (any Error).self) { try other.selected([group.id]) } + #expect(throws: (any Error).self) { try catalog.selected([group.id, group.id]) } + #expect(try catalog.selected([group.id])?.count == 1) + } + + @Test func pluginStrategiesAndTypedMemberExclusionsRemainExplicit() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"upstream"}"#, to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + for name in ["one", "two"] { + try fixture.write( + "---\ndescription: Review\n---\nExact body\n", to: "bundle/commands/\(name).md", + base: fixture.project) + } + for (path, name) in [("first", "cafe\u{301}"), ("second", "caf\u{e9}")] { + try fixture.write( + "---\nname: \(name)\ndescription: Agent\n---\nBody\n", + to: "bundle/agents/\(path).md", base: fixture.project) + } + let before = try FileHash.folderHash(fixture.root) + let catalog = try inspect(fixture, path: "bundle") + #expect(catalog.choices.count == 6) + for choice in catalog.choices { + switch choice.unit { + case .nativePlugin(let declaration): + #expect(choice.unavailableReason?.contains("adapter-issued container name") == true) + #expect(throws: (any Error).self) { try catalog.selected([choice.id]) } + guard + case .plugin(_, _, _, let mode, let select, let exclude, let agents, _, _) = declaration + else { + Issue.record("wrong native unit") + continue + } + #expect(mode == .native && select == nil && exclude.isEmpty && agents == [.claudeCode]) + #expect(choice.graph?.components.count == 1) + case .componentsPlugin(let declaration): + guard case .plugin(_, _, _, let mode, let select, let exclude, _, _, _) = declaration + else { + Issue.record("wrong components container") + continue + } + #expect(mode == .components && select == nil && exclude.isEmpty) + #expect( + choice.graph?.components.filter { $0.key.kind == .command }.count == 2 + && choice.graph?.components.filter { $0.key.kind == .subagent }.count == 2) + case .pluginMember(let declaration, _): + guard case .plugin(_, _, _, let mode, let select, let exclude, _, _, _) = declaration + else { + Issue.record("wrong components unit") + continue + } + #expect( + mode == .components && [.command, .subagent].contains(select?.first) && exclude.count == 1 + ) + #expect(choice.graph?.components.filter { $0.key.kind != .plugin }.count == 1) + default: Issue.record("unexpected source choice") + } + } + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(!String(reflecting: catalog).contains("agents-resolution-")) + } + + @Test func importerKeysKeepAllFamiliesFixedEffectsAndProducerClaimsSeparate() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"mcp":{"servers":{"same":{"type":"local","command":["fixture-server"]}}},"commands":{"same":{"description":"Review","template":"Body"}},"agents":{"same":{"description":"Help","system":"Body","mode":"subagent"}},"lsp":{"fixed":{"command":["fixture-lsp"],"extensions":[".fixture"]}}}"#, + to: "opencode.json", base: fixture.project) + let before = try FileHash.folderHash(fixture.root) + let catalog = try inspect( + fixture, + importing: .init(profile: .openCodeConfigV2, document: "opencode.json", selection: [])) + #expect(catalog.choices.count == 1) + let choice = try #require(catalog.choices.first) + guard case .importer(let metadata) = choice.unit else { + Issue.record("not an importer key") + return + } + #expect(metadata.key == "same") + #expect( + Set(choice.imported!.components.map(\.declaration.kind)) == [.mcpServer, .command, .subagent]) + #expect(catalog.fixedEffects?.components.contains { $0.declaration.kind == .lspServer } == true) + #expect(catalog.importDocument?.selection == []) + #expect(!String(reflecting: catalog).contains("agents-resolution-")) + #expect(try FileHash.folderHash(fixture.root) == before) + } + + @Test func unavailableClosureRemainsVisibleAndEmptySourceDoesNotAddAnything() throws { + let fixture = try LinkFixture() + #expect(try inspect(fixture).selected([]) == nil) + try fixture.manifest( + "version: 1\nsources: {absent: {path: ../missing}}\nexports: [broken]\ngroups: {broken: {uses: [{group: missing, source: absent}]}}", + at: fixture.project) + let catalog = try inspect(fixture) + #expect(catalog.choices.count == 1) + #expect(catalog.choices[0].graph == nil) + #expect(catalog.choices[0].unavailableReason != nil) + } + @Test func emptyPluginStillOffersExplicitStrategiesAndSnapshotEvidence() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"empty"}"#, to: ".claude-plugin/plugin.json", base: fixture.project) + let catalog = try inspect(fixture) + #expect(catalog.choices.count == 2) + let expanded = try #require( + catalog.choices.first { + if case .componentsPlugin = $0.unit { return true } + return false + }) + #expect(expanded.unavailableReason == nil) + #expect(expanded.graph?.components.count == 1) + #expect(expanded.graph?.components[0].origins[0].pluginExpansion?.children == []) + #expect(expanded.graph?.sourceSnapshots.contains { $0.snapshot == catalog.snapshot } == true) + } + + @Test func gitCatalogUsesSelectedCommitAndChangesItsContentEvidence() throws { + let fixture = try LinkFixture() + try fixture.initialize(fixture.project) + try fixture.skill("committed", at: fixture.project) + let first = try fixture.commit(fixture.project) + try fixture.skill("dirty", at: fixture.project) + let catalog = try inspect(fixture) + #expect(catalog.snapshot.revision == first) + #expect(catalog.choices.count == 1) + #expect(catalog.choices[0].unavailableReason == nil) + _ = try fixture.commit(fixture.project) + let next = try inspect(fixture) + #expect(next.choices.count == 2) + #expect(next.contentHash != catalog.contentHash) + #expect(!String(reflecting: next).contains("agents-resolution-")) + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } + + @Test func importedLocalCoordinatesStayRelativeToCapturedSource() throws { + let fixture = try LinkFixture() + try fixture.skill("local", at: fixture.project.appendingPathComponent("content")) + try fixture.write( + "name: package\nversion: '1.0.0'\ndependencies:\n apm:\n - path: content\n", + to: "apm.yml", base: fixture.project) + let catalog = try inspect( + fixture, importing: .init(profile: .apmManifest, document: "apm.yml")) + let choice = try #require(catalog.choices.first) + let source = try #require(choice.imported?.sources.first) + #expect(source.declaration?.location == "content") + #expect(source.declaration?.environment == nil) + #expect(!String(reflecting: catalog).contains("agents-resolution-")) + } + + @Test func nativeRegistrationUsesAdapterIssuedName() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"actual-producer","version":"1.0.0"}"#, + to: "gemini-extension.json", base: fixture.project) + let catalog = try inspect(fixture) + let choice = try #require( + catalog.choices.first { + if case .nativePlugin = $0.unit { return true } + return false + }) + guard + case .nativePlugin( + .plugin(let name, _, let source, let mode, let select, let exclude, let agents, _, _)) = + choice.unit + else { + Issue.record("missing native declaration") + return + } + #expect(name == "actual-producer" && source == "producer") + #expect(mode == .native && select == nil && exclude.isEmpty && agents == [.geminiCLI]) + #expect(choice.unavailableReason == nil) + } + +} From cd302e802c1862cc010479ff0317198be192d9a4 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:34:29 +0800 Subject: [PATCH 138/171] fix: preserve concrete inputs in component discovery --- Sources/AgentsUpdates/ComponentDiscovery.swift | 5 +---- Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift | 4 +++- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/Sources/AgentsUpdates/ComponentDiscovery.swift b/Sources/AgentsUpdates/ComponentDiscovery.swift index 1ad79f2..8bb5f58 100644 --- a/Sources/AgentsUpdates/ComponentDiscovery.swift +++ b/Sources/AgentsUpdates/ComponentDiscovery.swift @@ -105,14 +105,11 @@ extension UpdateOperations { ledger, roots: store.ledgerRoots, generation: ResolvedLedgerCodec.digest(ledger)) var revisions: [String: [String]] = [:] - var locations = try readLocations( + let locations = try readLocations( declarations: [previous, declaration], ledgers: [ledger], store: store) for id in ledger.sources.keys.sorted() { let identity = try ledger.sourceIdentity(id, roots: store.ledgerRoots) revisions[identity, default: []].append(ledger.sources[id]!.revision) - if let location = ledger.sources[id]!.location { - locations.append(try location.resolve(roots: store.ledgerRoots)) - } } for key in revisions.keys { revisions[key] = Array(Set(revisions[key]!)).sorted() } try baseline.validate() diff --git a/Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift b/Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift index 629a33b..fa742c1 100644 --- a/Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift +++ b/Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift @@ -25,11 +25,13 @@ struct ImplicitReadFootprintTests { ]) let request = UpdateRequest(operation: .declaration(declaration)) let report = try UpdateOperations.preview(request, scope: scope, environment: f.environment) + let discovery = try UpdateOperations.discover( + declaration, scope: scope, environment: f.environment) _ = try UpdateOperations.withPreparedUpdate(request, scope: scope, environment: f.environment) { try $0.apply(ifUnchangedFrom: report.displayedFingerprint) } let inspection = try UpdateOperations.inspect(scope: scope, environment: f.environment) - for locations in [report.readLocations, inspection.readLocations] { + for locations in [report.readLocations, discovery.readLocations, inspection.readLocations] { let paths = Set(locations.map(\.path)) #expect(!paths.contains(root.path)) #expect( From 1c3a9bb4f44d3020000fb9f87aa8857e914f2510 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:40:19 +0800 Subject: [PATCH 139/171] fix: preserve captured import inputs and package metadata --- .../SourceImportOperations.swift | 31 +++--- .../Import/NativeContainerImport.swift | 7 ++ .../Import/SourceImportProposal.swift | 20 +++- Sources/Components/PluginExpansion.swift | 7 +- .../SourceImportSelectionTests.swift | 98 ++++++++++++++++++- Tests/ComponentsTests/ImportNativeTests.swift | 50 +++++++++- .../ComponentsTests/ImportProfileTests.swift | 2 +- 7 files changed, 189 insertions(+), 26 deletions(-) diff --git a/Sources/AgentsUpdates/SourceImportOperations.swift b/Sources/AgentsUpdates/SourceImportOperations.swift index 62cdb20..a5f7db4 100644 --- a/Sources/AgentsUpdates/SourceImportOperations.swift +++ b/Sources/AgentsUpdates/SourceImportOperations.swift @@ -405,8 +405,19 @@ package struct ImportPreparation: Sendable { let input: SourceImportInput let proposal: SourceImportProposal let catalog: SourceImportProposal - let documentFingerprint: String let locations: [URL] + private let originalInputs: [TargetPrecondition] + + init( + input: SourceImportInput, proposal: SourceImportProposal, catalog: SourceImportProposal, + locations: [URL] + ) throws { + self.input = input + self.proposal = proposal + self.catalog = catalog + self.locations = locations + originalInputs = try locations.map { try TargetPrecondition($0) } + } func validateConversion() throws { guard proposal.diagnostics.isEmpty, proposal.bindings.isEmpty else { @@ -428,19 +439,16 @@ package struct ImportPreparation: Sendable { } func capture(admitConversion: Bool = true) throws -> [TargetPrecondition] { - let document = try PathSafety.resolvedChild(base: input.root, subpath: input.document) - let evidence = try TargetPrecondition(document) - let inputs = try locations.map { try TargetPrecondition($0) } + for original in originalInputs { try original.validate() } var enumeration = input enumeration.enumerateChoices = true enumeration.selection = nil - guard try evidence.displayEvidence(includeContent: true) == documentFingerprint, - try SourceImport.preview(input) == proposal, try SourceImport.preview(enumeration) == catalog + guard try SourceImport.preview(input) == proposal, + try SourceImport.preview(enumeration) == catalog else { throw CoreError.invalidState("import inputs changed; refresh the import inspection") } if admitConversion { try validateConversion() } - try evidence.validate() - for input in inputs { try input.validate() } - return inputs + for original in originalInputs { try original.validate() } + return originalInputs } } @@ -469,8 +477,6 @@ public enum SourceImportOperations { let document = input.document let installedSkills = input.installedSkills let url = try PathSafety.resolvedChild(base: root, subpath: document) - let evidence = try TargetPrecondition(url) - let fingerprint = try evidence.displayEvidence(includeContent: true) let proposal = try SourceImport.preview(input) var enumeration = input enumeration.selection = nil @@ -489,9 +495,8 @@ public enum SourceImportOperations { locations.append(URL(fileURLWithPath: String(identity.dropFirst(6)))) } } - let preparation = ImportPreparation( + let preparation = try ImportPreparation( input: input, proposal: proposal, catalog: catalog, - documentFingerprint: fingerprint, locations: Array(Set(locations)).sorted { $0.path < $1.path }) _ = try preparation.capture(admitConversion: false) return SourceImportInspection(proposal, preparation: preparation, catalog: catalog) diff --git a/Sources/Components/Import/NativeContainerImport.swift b/Sources/Components/Import/NativeContainerImport.swift index 8aea708..0fedd9a 100644 --- a/Sources/Components/Import/NativeContainerImport.swift +++ b/Sources/Components/Import/NativeContainerImport.swift @@ -68,6 +68,10 @@ enum NativeContainerImport { versionLocation: parsed.fieldLocation(["version"])) } } + if agent != .geminiCLI { + diagnostics.proposal.packageMetadata = .init( + name: name, nameLocation: parsed.fieldLocation(["name"])) + } // A container contributes typed children; .native selection/registration belongs to B/F. // Unknown/dependency fields are already diagnosed rather than becoming opaque payloads. for (field, kind) in [ @@ -235,6 +239,9 @@ enum NativeContainerImport { entries: try inventory(snapshot, root: root, limits: limits), documents: documents.mapValues { .object($0.fields) }, budget: parsed.admission.parser) } catch let issue as NativeComponentFieldIssue { + if issue.document == suffix, issue.field == ["name"] { + diagnostics.proposal.packageMetadata = nil + } let document: NativeImportDocument if issue.document == suffix { document = parsed diff --git a/Sources/Components/Import/SourceImportProposal.swift b/Sources/Components/Import/SourceImportProposal.swift index 5e882bb..82d2dd2 100644 --- a/Sources/Components/Import/SourceImportProposal.swift +++ b/Sources/Components/Import/SourceImportProposal.swift @@ -190,9 +190,25 @@ package struct ImportResourceProposal: Equatable, Sendable { /// Producer package identity is provenance, not a component, source pin or deployment choice. package struct ImportPackageMetadata: Equatable, Sendable { package let name: String - package let version: String + package let version: String? package let nameLocation: ImportLocation - package let versionLocation: ImportLocation + package let versionLocation: ImportLocation? + + package init(name: String, nameLocation: ImportLocation) { + self.name = name + self.nameLocation = nameLocation + version = nil + versionLocation = nil + } + + package init( + name: String, version: String, nameLocation: ImportLocation, versionLocation: ImportLocation + ) { + self.name = name + self.version = version + self.nameLocation = nameLocation + self.versionLocation = versionLocation + } } /// Canonical intent and evidence only. Raw documents and literal credentials never escape parsing. diff --git a/Sources/Components/PluginExpansion.swift b/Sources/Components/PluginExpansion.swift index 4b92b71..060726a 100644 --- a/Sources/Components/PluginExpansion.swift +++ b/Sources/Components/PluginExpansion.swift @@ -64,8 +64,9 @@ extension Expansion { } var effective = declaration if profile == .geminiExtensionV1, let metadata = proposal.packageMetadata { - guard proposal.profile == profile, - [metadata.nameLocation, metadata.versionLocation].allSatisfy({ + guard let version = metadata.version, let versionLocation = metadata.versionLocation, + proposal.profile == profile, + [metadata.nameLocation, versionLocation].allSatisfy({ $0.document.utf8.elementsEqual(document.utf8) && $0.span?.document.rawValue.utf8.elementsEqual(document.utf8) == true }) @@ -74,7 +75,7 @@ extension Expansion { } if authoredNative[AgentID.geminiCLI.rawValue]?["version"] == nil { var native = authoredNative - native[AgentID.geminiCLI.rawValue, default: [:]]["version"] = .string(metadata.version) + native[AgentID.geminiCLI.rawValue, default: [:]]["version"] = .string(version) effective = .plugin( name: name, path: path, source: alias, mode: mode, select: select, exclude: exclude, agents: agents, condition: authoredCondition, native: native) diff --git a/Tests/AgentsUpdatesTests/SourceImportSelectionTests.swift b/Tests/AgentsUpdatesTests/SourceImportSelectionTests.swift index 03853ad..7bddb3a 100644 --- a/Tests/AgentsUpdatesTests/SourceImportSelectionTests.swift +++ b/Tests/AgentsUpdatesTests/SourceImportSelectionTests.swift @@ -28,6 +28,99 @@ struct SourceImportSelectionTests { #expect(throws: (any Error).self) { try report.resolving(choices: [shared.id]) } } + @Test func linkedSkillSupportingBytesInvalidateResolution() throws { + let f = try ImportSelectionFixture() + try f.write("bundle/.claude-plugin/plugin.json", #"{"name":"producer"}"#) + try f.write( + "bundle/skills/helper/SKILL.md", "---\nname: helper\ndescription: Helper\n---\nBody\n") + try f.write("bundle/shared/tool.txt", "Original support\n") + try FileManager.default.createSymbolicLink( + atPath: f.root.appendingPathComponent("bundle/skills/helper/reference.txt").path, + withDestinationPath: "../../shared/tool.txt") + let report = try SourceImportOperations.inspect( + format: "claudePluginV1", root: f.root, document: "bundle/.claude-plugin/plugin.json") + #expect(report.diagnostics.isEmpty) + let support = try #require(report.resources.first { $0.path == "shared/tool.txt" }) + #expect(support.hash == nil && !support.requiresBindingRewrite) + try f.write("bundle/shared/tool.txt", "Modified support\n") + #expect(throws: (any Error).self) { try report.resolving() } + let refreshed = try SourceImportOperations.inspect( + format: "claudePluginV1", root: f.root, document: "bundle/.claude-plugin/plugin.json") + #expect(try refreshed.resolving().diagnostics.isEmpty) + } + + @Test func supportingBytesInvalidateCapturedRequestPreparation() throws { + let f = try ImportSelectionFixture() + try f.write("bundle/.claude-plugin/plugin.json", #"{"name":"producer"}"#) + try f.write( + "bundle/commands/review.md", + "---\ndescription: Review\n---\nUse [support](../shared/tool.txt).\n") + try f.write("bundle/shared/tool.txt", "Original support\n") + let environment = RuntimeEnvironment( + projectDirectory: f.root, homeDirectory: f.root, environment: [:]) + let scope = try UpdateOperations.inspect(environment: environment) + let report = try SourceImportOperations.inspect( + format: "claudePluginV1", root: f.root, document: "bundle/.claude-plugin/plugin.json") + #expect(report.diagnostics.isEmpty) + let request = try report.updateRequest(in: scope) + try f.write("bundle/shared/tool.txt", "Modified support\n") + #expect(throws: (any Error).self) { try report.resolving() } + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(request, environment: environment) { _ in + Issue.record("Stale supporting content must not reach the prepared handle") + } + } + let refreshed = try SourceImportOperations.inspect( + format: "claudePluginV1", root: f.root, document: "bundle/.claude-plugin/plugin.json") + let freshRequest = try refreshed.updateRequest(in: scope) + _ = try UpdateOperations.preview(freshRequest, environment: environment) + } + + @Test func literalSupportingBytesRemainPrivateAndFreshAfterSymbolicResolution() throws { + let f = try ImportSelectionFixture() + try f.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"producer","lspServers":"./shared/language.json"}"#) + try f.write( + "bundle/skills/helper/SKILL.md", "---\nname: helper\ndescription: Helper\n---\nBody\n") + let original = + #"{"review":{"command":"never-run","extensionToLanguage":{".txt":"text"},"env":{"TOKEN":"PRIVATE_SUPPORT_A"}}}"# + try f.write("bundle/shared/language.json", original) + try FileManager.default.createSymbolicLink( + atPath: f.root.appendingPathComponent("bundle/skills/helper/reference.txt").path, + withDestinationPath: "../../shared/language.json") + let report = try SourceImportOperations.inspect( + format: "claudePluginV1", root: f.root, document: "bundle/.claude-plugin/plugin.json") + let slot = try #require(report.requiredInputs.first { $0.kind == .bindingReference }) + let resolved = try report.resolving(inputs: [ + .init(id: slot.id, value: .binding(.environment("SUPPORT_TOKEN"))) + ]) + #expect(resolved.bindings.isEmpty) + let preserved = resolved.resources.filter { + $0.path == "skills/helper" || $0.path == "shared/language.json" + } + #expect(!preserved.isEmpty) + #expect(preserved.allSatisfy { $0.hash == nil && $0.requiresBindingRewrite }) + #expect(!String(reflecting: resolved).contains("PRIVATE_SUPPORT_A")) + let environment = RuntimeEnvironment( + projectDirectory: f.root, homeDirectory: f.root, environment: [:]) + let scope = try UpdateOperations.inspect(environment: environment) + #expect(throws: (any Error).self) { try resolved.updateRequest(in: scope) } + try f.write( + "bundle/shared/language.json", + original.replacingOccurrences(of: "PRIVATE_SUPPORT_A", with: "PRIVATE_SUPPORT_B")) + #expect(throws: (any Error).self) { try report.resolving() } + #expect(throws: (any Error).self) { try resolved.resolving() } + let refreshed = try SourceImportOperations.inspect( + format: "claudePluginV1", root: f.root, document: "bundle/.claude-plugin/plugin.json") + #expect(!refreshed.bindings.isEmpty) + #expect(!String(reflecting: refreshed).contains("PRIVATE_SUPPORT_B")) + #expect( + refreshed.resources.filter { $0.path == "skills/helper" }.allSatisfy { + $0.hash == nil && $0.requiresBindingRewrite + }) + } + @Test func resolvedCanonicalBindingCannotAdmitRawPreservedBytes() throws { let f = try ImportSelectionFixture() try f.write( @@ -65,10 +158,9 @@ struct SourceImportSelectionTests { var enumeration = input enumeration.enumerateChoices = true let document = f.root.appendingPathComponent("settings.json") - let fingerprint = try TargetPrecondition(document).displayEvidence(includeContent: true) - let preparation = ImportPreparation( + let preparation = try ImportPreparation( input: input, proposal: proposal, - catalog: try SourceImport.preview(enumeration), documentFingerprint: fingerprint, + catalog: try SourceImport.preview(enumeration), locations: [document]) #expect(throws: (any Error).self) { try preparation.capture() } #expect(try preparation.capture(admitConversion: false).count == 1) diff --git a/Tests/ComponentsTests/ImportNativeTests.swift b/Tests/ComponentsTests/ImportNativeTests.swift index cc70165..3718ad9 100644 --- a/Tests/ComponentsTests/ImportNativeTests.swift +++ b/Tests/ComponentsTests/ImportNativeTests.swift @@ -160,13 +160,13 @@ struct ImportNativeTests { let proposal = try SourceImport.preview(input) let metadata = try #require(proposal.packageMetadata) #expect(metadata.name.utf8.elementsEqual(name.utf8)) - #expect(metadata.version.utf8.elementsEqual(version.utf8)) + #expect((try #require(metadata.version)).utf8.elementsEqual(version.utf8)) #expect(metadata.nameLocation.document == file) #expect(metadata.nameLocation.pointer == "/member[1]") #expect(metadata.nameLocation.span?.line == 3) - #expect(metadata.versionLocation.document == file) - #expect(metadata.versionLocation.pointer == "/member[2]") - #expect(metadata.versionLocation.span?.line == 2) + #expect(metadata.versionLocation?.document == file) + #expect(metadata.versionLocation?.pointer == "/member[2]") + #expect(metadata.versionLocation?.span?.line == 2) #expect(proposal.components.map(\.member?.selector) == [.command(name: "review")]) #expect(proposal.diagnostics.contains { $0.code == .unconverted }) #expect(try fixture.hash() == before) @@ -193,6 +193,48 @@ struct ImportNativeTests { #expect(!String(reflecting: sensitive).contains("PRIVATE_VERSION_CANARY")) } + @Test(arguments: [SourceImportProfile.claudePluginV1, .cursorPluginV1]) + func nativePackageNameKeepsExactProducerCoordinatesWithoutVersion( + _ profile: SourceImportProfile + ) throws { + let fixture = try NativeImportFixture() + let suffix = + profile == .claudePluginV1 ? ".claude-plugin/plugin.json" : ".cursor-plugin/plugin.json" + let file = "different-folder/" + suffix + let name = profile == .claudePluginV1 ? "cafe\u{301}" : "exact.producer-name" + try fixture.write(file, "{\n \"name\": \"\(name)\"\n}") + try fixture.write( + "different-folder/skills/helper/SKILL.md", + "---\nname: helper\ndescription: Helper\n---\nBody\n") + let before = try fixture.hash() + let proposal = try SourceImport.preview(fixture.input(profile, file)) + let metadata = try #require(proposal.packageMetadata) + #expect(metadata.name.utf8.elementsEqual(name.utf8)) + #expect(metadata.nameLocation.document == file) + #expect(metadata.nameLocation.pointer == "/member[0]") + #expect(metadata.nameLocation.span?.line == 2) + #expect(metadata.version == nil && metadata.versionLocation == nil) + #expect(proposal.components.count == 1 && proposal.diagnostics.isEmpty) + #expect(try fixture.hash() == before) + for invalidName in [#"7"#, #""""#, #""https://user:PRIVATE_NAME_CANARY@example.test""#] { + try fixture.write(file, "{\"name\":\(invalidName)}") + let invalid = try SourceImport.preview(fixture.input(profile, file)) + #expect(invalid.packageMetadata == nil) + #expect(!invalid.diagnostics.isEmpty) + #expect(!String(reflecting: invalid).contains("PRIVATE_NAME_CANARY")) + } + if profile == .cursorPluginV1 { + try fixture.write(file, #"{"name":"Invalid_Producer"}"#) + let invalid = try SourceImport.preview(fixture.input(profile, file)) + #expect(invalid.packageMetadata == nil) + #expect( + invalid.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == file + && $0.location.pointer == "/member[0]" + }) + } + } + @Test func codexRoleRelativeFileAndOpenCodeOrderedPolicyBecomeTypedIntent() throws { let fixture = try NativeImportFixture() try fixture.write( diff --git a/Tests/ComponentsTests/ImportProfileTests.swift b/Tests/ComponentsTests/ImportProfileTests.swift index bb35382..99f4da7 100644 --- a/Tests/ComponentsTests/ImportProfileTests.swift +++ b/Tests/ComponentsTests/ImportProfileTests.swift @@ -46,7 +46,7 @@ struct ImportProfileTests { #expect(metadata.version == "1.0.0") #expect(metadata.nameLocation.document == "apm.yml") #expect(metadata.nameLocation.span?.line == 1) - #expect(metadata.versionLocation.span?.line == 2) + #expect(metadata.versionLocation?.span?.line == 2) #expect(proposal.profile.producerRevision == "787a97cc52fbbcc344374e1567b2a1e5b8adf441") #expect(try fixture.hash() == before) From 1640400ad093bf54c7d3954dcf88fe2caada1b11 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:52:58 +0800 Subject: [PATCH 140/171] feat: add captured source catalog selection --- Documentation/Architecture/Package.md | 13 + .../AgentsUpdates/ComponentDiscovery.swift | 2 + .../SourceCatalogInspection.swift | 432 ++++++++++++++++++ Sources/AgentsUpdates/UpdatePlan.swift | 4 +- Sources/AgentsUpdates/UpdateRequest.swift | 1 + Sources/Components/SourceCatalog.swift | 2 +- .../Components/SourceCatalogSelection.swift | 194 ++++++++ .../SourceCatalogInspectionTests.swift | 229 ++++++++++ .../ComponentsTests/SourceCatalogTests.swift | 20 +- 9 files changed, 893 insertions(+), 4 deletions(-) create mode 100644 Sources/AgentsUpdates/SourceCatalogInspection.swift create mode 100644 Sources/Components/SourceCatalogSelection.swift create mode 100644 Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 1abc329..04ba772 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -422,6 +422,19 @@ the package catalog does not create update requests. ## AgentsUpdates +`UpdateOperations.inspectSource` exposes inspection-bound source choices, linked +closures, adapter key effects, fixed contributions and typed missing inputs. +`SourceCatalogInspection.select` composes a finite addition through the captured +scope destination. Empty selection returns nil without acquiring a source or +creating a request. Exported groups remain symbolic; plugin member selections +compose into one components declaration per container, and native registration +remains indivisible. Adapter selections rerun the owning converter with its real +keys and retain independent raw-resource admission. Source evidence is revalidated +at selection and preparation, including original documents behind inline imported +intent. Public inspection values contain no borrowed extraction URLs or runtime +environment/private freshness observations. The ordinary request retains exact +protected pins and destination identity through preview, reprepare and apply. + `UpdateOperations.preview` plans all declared skills, instruction targets and prompts under one shared scope lock. `withPreparedUpdate` holds one writer lock through preparation and the synchronous consumer closure. Its diff --git a/Sources/AgentsUpdates/ComponentDiscovery.swift b/Sources/AgentsUpdates/ComponentDiscovery.swift index 1ad79f2..29ef05f 100644 --- a/Sources/AgentsUpdates/ComponentDiscovery.swift +++ b/Sources/AgentsUpdates/ComponentDiscovery.swift @@ -5,6 +5,7 @@ import Foundation /// A linked authored graph or finite addition resolved in a temporary source session before deployment. public struct ComponentDiscovery: Sendable { + package var catalogPreparation: CatalogPreparation? = nil public let components: [ComponentInspection] public let sourceRevisions: [String: [String]] public let fingerprint: String @@ -19,6 +20,7 @@ public struct ComponentDiscovery: Sendable { operation: .declaration(declaration), expectedDeclarationDigest: declarationDigest) request.expectedDiscoveryFingerprint = fingerprint + request.catalogPreparation = catalogPreparation request.capturedAddition = addition request.selectedIdentities = addition?.selectedIdentities request.importPreparation = addition?.importPreparation diff --git a/Sources/AgentsUpdates/SourceCatalogInspection.swift b/Sources/AgentsUpdates/SourceCatalogInspection.swift new file mode 100644 index 0000000..06826c8 --- /dev/null +++ b/Sources/AgentsUpdates/SourceCatalogInspection.swift @@ -0,0 +1,432 @@ +import AgentsCore +import Components +import Foundation + +/// A handle from one immutable source inspection; labels are never selection keys. +public struct SourceCatalogChoiceID: Hashable, Sendable { + fileprivate let owner: UUID + fileprivate let index: Int +} + +public struct SourceCatalogInputID: Hashable, Sendable { + fileprivate let owner: UUID + fileprivate let index: Int +} + +public enum SourceCatalogUnit: Sendable { + case skill, instruction, group, nativePlugin, componentsPlugin + case pluginMember(ComponentReferenceDeclaration) + case importer +} + +public struct SourceCatalogOccurrenceEffect: Sendable { + public let provenance: SourceProvenance + public let condition: DeclarationCondition + public let recipients: [AgentID] + public let dependencies: [String] +} + +public struct SourceCatalogConstraintInspection: Sendable { + public let source: String + public let root: String + public let requirement: SourceRequirement? + public let referenceChain: [SourceSpan] +} + +public struct SourceCatalogEffect: Sendable { + public let kind: DeclaredComponentKind + public let name: String + public let source: String + public let revision: String + public let conditions: [DeclarationCondition] + public let recipients: [AgentID] + public let chatGPT: Bool + public let resources: [String] + public let declaration: ComponentDeclaration? + public let occurrences: [SourceCatalogOccurrenceEffect] +} + +public struct SourceCatalogChoiceInspection: Sendable { + public let id: SourceCatalogChoiceID + public let label: String + public let origin: ImportLocationInspection + public let unit: SourceCatalogUnit + public let effects: [SourceCatalogEffect] + public let importedEffects: ImportSelectionEffects? + public let constraints: [SourceCatalogConstraintInspection] + public let artifactDigest: String? + public let unavailableReason: String? +} + +public struct SourceCatalogRequiredInput: Sendable { + public let id: SourceCatalogInputID + public let kind: ImportInputKind + public let location: ImportLocationInspection + public let suggestedReference: ImportBindingReference? +} + +public struct SourceCatalogInputResolution: Sendable { + public let id: SourceCatalogInputID + public let value: ImportInputValue + public init(id: SourceCatalogInputID, value: ImportInputValue) { + self.id = id + self.value = value + } +} + +/// The explicit adapter and document within the selected discovery root. Omission and an +/// empty producer selection retain their adapter-defined meanings during inspection. +public struct SourceCatalogImportOptions: Sendable { + public let format: String + public let document: String + public let selection: Set? + public init(format: String, document: String, selection: Set? = nil) { + self.format = format + self.document = document + self.selection = selection + } +} + +public struct SourceCatalogSelectionOptions: Sendable { + public var agents: [AgentID]? + public var condition: DeclarationCondition? + public var skillMode: InstallMode? + public init( + agents: [AgentID]? = nil, condition: DeclarationCondition? = nil, skillMode: InstallMode? = nil + ) { + self.agents = agents + self.condition = condition + self.skillMode = skillMode + } +} + +/// Explicit source choices and their full linked or adapter-issued effects. Source sessions and +/// private freshness observations are retained only as opaque preparation authority. +public struct SourceCatalogInspection: Sendable, CustomReflectable { + public let alias: String + public let sourceIdentity: String + public let revision: String + public let availableChoices: [SourceCatalogChoiceInspection] + public let fixedEffects: ImportSelectionEffects? + public let requiredInputs: [SourceCatalogRequiredInput] + public let bindings: [ImportBindingInspection] + public let producerSelections: [ImportSelectionInspection] + private let capture: CatalogCapture + public var customMirror: Mirror { + Mirror(self, children: ["alias": alias, "choices": availableChoices]) + } + + /// Empty selection returns nil before opening sources or initializing a request. Every other + /// selection revalidates this inspection and composes only the selected finite additions. + public func select( + _ choices: [SourceCatalogChoiceID], options: SourceCatalogSelectionOptions = .init(), + inputs: [SourceCatalogInputResolution] = [] + ) throws -> ComponentDiscovery? { + guard !choices.isEmpty else { return nil } + guard Set(choices).count == choices.count, + choices.allSatisfy({ + $0.owner == capture.owner && capture.catalog.choices.indices.contains($0.index) + }), + Set(inputs.map(\.id)).count == inputs.count, + inputs.allSatisfy({ + $0.id.owner == capture.owner && capture.targets.indices.contains($0.id.index) + }) + else { throw CoreError.invalidState("catalog handles belong to another inspection") } + let preparation = CatalogPreparation( + capture: capture, choices: choices.map(\.index), options: options, inputs: inputs) + let additions = try preparation.additions() + guard var discovery = try UpdateOperations.captureAddition(additions, in: capture.destination) + else { return nil } + discovery.catalogPreparation = preparation + return discovery + } + + fileprivate init(capture: CatalogCapture) { + self.capture = capture + let catalog = capture.catalog + alias = catalog.alias + sourceIdentity = catalog.snapshot.source + revision = catalog.snapshot.revision + availableChoices = catalog.choices.enumerated().map { index, choice in + let unit: SourceCatalogUnit + switch choice.unit { + case .skill: unit = .skill + case .instruction: unit = .instruction + case .group: unit = .group + case .nativePlugin: unit = .nativePlugin + case .componentsPlugin: unit = .componentsPlugin + case .pluginMember(_, let selector): unit = .pluginMember(selector) + case .importer: unit = .importer + } + return .init( + id: .init(owner: capture.owner, index: index), label: choice.label, + origin: location(choice.origin), unit: unit, + effects: choice.graph?.components.map { component in + .init( + kind: component.key.kind, name: component.key.name, source: component.snapshot.source, + revision: component.snapshot.revision, conditions: component.conditions, + recipients: component.recipients.sorted { $0.rawValue < $1.rawValue }, + chatGPT: component.chatGPT, + resources: component.resources.map(\.path), + declaration: { + if case .declaration(let declaration) = component.payload { return declaration } + return nil + }(), + occurrences: component.origins.map { origin in + .init( + provenance: origin.provenance, + condition: origin.condition, + recipients: origin.recipients.sorted { $0.rawValue < $1.rawValue }, + dependencies: origin.dependencies.map { $0.source + "@" + $0.revision }) + }) + } ?? [], importedEffects: choice.imported.map(effects), + constraints: choice.graph?.constraints.map { + .init( + source: $0.source, root: $0.root, requirement: $0.requirement, + referenceChain: $0.referenceChain) + } ?? [], + artifactDigest: choice.artifact?.digest, unavailableReason: choice.unavailableReason) + } + fixedEffects = catalog.fixedEffects.map(effects) + requiredInputs = capture.targets.enumerated().map { index, target in + let kind: ImportInputKind + let origin: ImportLocation + let suggested: ImportBindingReference? + switch target { + case .adapter(let input): + kind = input.kind == .gitSource ? .sourceCoordinates : .explicitContent + origin = input.location + suggested = nil + case .binding(let binding): + kind = .bindingReference + origin = binding.location + suggested = binding.environmentVariable.map(ImportBindingReference.environment) + } + return .init( + id: .init(owner: capture.owner, index: index), kind: kind, + location: location(origin), suggestedReference: suggested) + } + bindings = catalog.bindings.map { + .init( + document: $0.location.document, pointer: $0.location.pointer, + reason: $0.reason, environmentVariable: $0.environmentVariable, + canResolveCanonicalSlot: $0.canonicalSlot) + } + producerSelections = catalog.producerSelections.map { + .init( + document: $0.origin.document, pointer: $0.origin.pointer, + sourceAlias: $0.sourceAlias, kind: $0.kind.rawValue, values: $0.values, + automatic: $0.automatic, + developmentOnly: $0.developmentOnly) + } + } +} + +extension UpdateOperations { + /// Enumerates only the explicit source/root. Inspection neither publishes state nor retains + /// a source extraction. Selection remains bound to this destination and source generation. + public static func inspectSource( + alias: String, source: SourceDeclaration, importing: SourceCatalogImportOptions? = nil, + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> SourceCatalogInspection { + let destination = try inspect(scope: scope, environment: environment) + let store = StateStore(scope: scope, environment: environment) + let imported: SourceCatalogImport? + if let importing { + guard let profile = SourceImportProfile(rawValue: importing.format) else { + throw CoreError.invalidSource("unknown source import profile") + } + imported = .init( + profile: profile, document: importing.document, selection: importing.selection) + } else { + imported = nil + } + #if os(macOS) + let platform = DeclarationPlatform.macOS + #else + let platform = DeclarationPlatform.linux + #endif + let localGit = + try source.kind == .local + && SourceResolutionSession.withTemporaryRead(store: store) { try $0.isGitSource(source) } + let original = + try source.kind == .local && !localGit + ? TargetPrecondition(source.localURL(environment: environment)) : nil + let catalog = try SourceCatalog.inspect( + alias: alias, source: source, store: store, platform: platform, importing: imported) + let liveOriginal = catalog.snapshot.revision.hasPrefix("sha256:") ? original : nil + try liveOriginal?.validate() + return SourceCatalogInspection( + capture: .init( + catalog: catalog, store: store, + destination: destination, platform: platform, original: liveOriginal)) + } +} + +private enum CatalogInputTarget: Sendable { + case adapter(ImportInputMetadata) + case binding(ImportBindingRequirement) +} + +private final class CatalogCapture: @unchecked Sendable, CustomReflectable { + let owner = UUID() + let catalog: SourceCatalog + let store: StateStore + let destination: ScopeInspection + let platform: DeclarationPlatform + let original: TargetPrecondition? + let targets: [CatalogInputTarget] + var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } + init( + catalog: SourceCatalog, store: StateStore, destination: ScopeInspection, + platform: DeclarationPlatform, original: TargetPrecondition? + ) { + self.catalog = catalog + self.store = store + self.destination = destination + self.platform = platform + self.original = original + targets = + catalog.requiredInputs.map(CatalogInputTarget.adapter) + + catalog.bindings.filter { $0.canonicalSlot && $0.key != nil }.map( + CatalogInputTarget.binding) + } +} + +/// Concrete catalog evidence, rechecked at selection and ordinary request preparation. +package final class CatalogPreparation: @unchecked Sendable, CustomReflectable { + private let capture: CatalogCapture + private let choices: [Int] + private let options: SourceCatalogSelectionOptions + private let inputs: [SourceCatalogInputResolution] + package var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } + fileprivate init( + capture: CatalogCapture, choices: [Int], options: SourceCatalogSelectionOptions, + inputs: [SourceCatalogInputResolution] + ) { + self.capture = capture + self.choices = choices + self.options = options + self.inputs = inputs + } + package func validate() throws -> [TargetPrecondition] { + _ = try additions() + return capture.original.map { [$0] } ?? [] + } + package func validateStandalone(replacing targets: [URL]) throws { + guard capture.catalog.importDocument != nil else { return } + let (_, proposal) = try conversion() + for resource in proposal.resources where resource.selected && resource.requiresStandaloneSource + { + guard + let source = proposal.sources.first(where: { $0.alias == resource.sourceAlias })? + .declaration, + source.kind == .local + else { continue } + let root = source.localURL(environment: capture.store.environment) + if targets.contains(where: { + PathSafety.isContained(root, in: $0) || PathSafety.isContained($0, in: root) + }) { + throw CoreError.invalidState( + "import requires an independent authoring source before replacing its installed content") + } + } + } + fileprivate func additions() throws -> Declaration { + try capture.original?.validate() + let catalog = capture.catalog + let fresh = try SourceCatalog.inspect( + alias: catalog.alias, source: catalog.source, store: capture.store, + platform: capture.platform, importing: catalog.importDocument) + guard fresh.snapshot == catalog.snapshot, fresh.root.utf8.elementsEqual(catalog.root.utf8), + fresh.contentHash == catalog.contentHash + else { throw CoreError.invalidState("catalog source changed; refresh inspection") } + try capture.original?.validate() + let selected = try catalog.selected(choices.map { catalog.choices[$0].id }) ?? [] + if catalog.importDocument == nil { + guard inputs.isEmpty else { throw CoreError.invalidState("catalog has no adapter input") } + return try catalog.additions( + selected.map(\.id), agents: options.agents, condition: options.condition, + mode: options.skillMode) + } + guard options.agents == nil, options.condition == nil, options.skillMode == nil else { + throw CoreError.invalidState( + "import recipients and restrictions belong to the adapter conversion") + } + return try conversion().0 + } + private func conversion() throws -> (Declaration, SourceImportProposal) { + let catalog = capture.catalog + let selected = try catalog.selected(choices.map { catalog.choices[$0].id }) ?? [] + var bindings: [String: RuntimeBinding] = [:] + var sources: [String: SourceDeclaration] = [:] + var content: [String: String] = [:] + for input in inputs { + switch (capture.targets[input.id.index], input.value) { + case (.adapter(let target), .source(let source)) where target.kind == .gitSource: + guard SourceImport.admitsSourceCoordinates(source) else { + throw CoreError.invalidSource("import requires Git coordinates") + } + sources[target.key] = source + case (.adapter(let target), .content(let path)) where target.kind == .installedContent: + _ = try PathSafety.sanitizeSubpath(path) + content[target.key] = path + case (.binding(let target), .binding(let reference)): + switch reference { + case .environment(let name): + guard name.range(of: #"^[A-Za-z_][A-Za-z0-9_]*$"#, options: .regularExpression) != nil + else { throw CoreError.invalidState("invalid symbolic environment reference") } + bindings[target.key!] = .environment(name) + case .secret(let name): + guard !name.isEmpty, + !name.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }) + else { throw CoreError.invalidState("invalid symbolic secret reference") } + bindings[target.key!] = .secret(name) + } + default: throw CoreError.invalidState("wrong catalog input kind") + } + } + let keys = Set( + selected.compactMap { choice -> String? in + if case .importer(let metadata) = choice.unit { return metadata.key } + return nil + }) + let result = try catalog.conversion( + keys: keys, bindings: bindings, sources: sources, content: content, store: capture.store) + try capture.original?.validate() + return result + } +} + +private func location(_ value: ImportLocation) -> ImportLocationInspection { + .init(document: value.document, pointer: value.pointer, span: value.span) +} + +private func effects(_ value: SourceCatalog.ImportEffects) -> ImportSelectionEffects { + .init( + sources: value.sources.map { s in + .init( + alias: s.alias, document: s.origin.document, pointer: s.origin.pointer, + declaration: s.declaration, commit: s.pin.commit, version: s.pin.version, + integrityKind: s.pin.integrity?.kind.rawValue, integrity: s.pin.integrity?.value, + requestedRef: s.requestedRef, resolvedRef: s.resolvedRef, resolvedURL: s.resolvedURL, + developmentOnly: s.developmentOnly, producerPath: s.producerPath, + producerIdentity: s.producerIdentity, registry: s.registry) + }, + components: value.components.map { + .init(document: $0.origin.document, pointer: $0.origin.pointer, declaration: $0.declaration) + }, + resources: value.resources.map { + .init( + sourceAlias: $0.sourceAlias, producerName: $0.producerName, path: $0.path, + hash: $0.observedHash, integrityKind: $0.producerIntegrity?.kind.rawValue, + integrity: $0.producerIntegrity?.value, + executableFlags: $0.executableFlags, requiresStandaloneSource: $0.requiresStandaloneSource, + selected: $0.selected, requiresBindingRewrite: $0.requiresBindingRewrite) + }, + diagnostics: value.diagnostics.map { + .init( + code: $0.code.rawValue, document: $0.location.document, + pointer: $0.location.pointer, span: $0.location.span, message: $0.message) + }) +} diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 0054f0b..deb6961 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -34,7 +34,8 @@ final class UpdatePlan { ) throws -> T { var request = request try request.capturedAddition?.validate(request, in: store) - let importInputs = try request.importPreparation?.capture() ?? [] + let catalogInputs = try request.catalogPreparation?.validate() ?? [] + let importInputs = try (request.importPreparation?.capture() ?? []) + catalogInputs let baseline = try StatePrecondition(store: store) let previous = try store.readLedger(prepared: baseline) try resolveSelection(&request, ledger: previous, store: store, baseline: baseline) @@ -272,6 +273,7 @@ final class UpdatePlan { changingAccess: request.changingAccess, kinds: request.kinds, names: Set(request.names), selectedIdentities: request.selectedIdentities, installations: installations, retargetedInstructions: retargetedInstructions) + try request.catalogPreparation?.validateStandalone(replacing: aggregation.changes.map(\.url)) if let imported = request.importPreparation { for resource in imported.proposal.resources where resource.selected && resource.requiresStandaloneSource { diff --git a/Sources/AgentsUpdates/UpdateRequest.swift b/Sources/AgentsUpdates/UpdateRequest.swift index 4d007d0..5f4dd11 100644 --- a/Sources/AgentsUpdates/UpdateRequest.swift +++ b/Sources/AgentsUpdates/UpdateRequest.swift @@ -11,6 +11,7 @@ public enum UpdateOperation: Sendable { /// Selection constrains application and protects the recorded semantics of every other domain. public struct UpdateRequest: Sendable { + package var catalogPreparation: CatalogPreparation? package var capturedAddition: CapturedAddition? package var importPreparation: ImportPreparation? package var expectedDiscoveryFingerprint: String? diff --git a/Sources/Components/SourceCatalog.swift b/Sources/Components/SourceCatalog.swift index 1d45f25..a928d0d 100644 --- a/Sources/Components/SourceCatalog.swift +++ b/Sources/Components/SourceCatalog.swift @@ -272,7 +272,7 @@ package struct SourceCatalog: Sendable { name: nativeName ?? alias, path: ".", source: alias, mode: .native, agents: [agent]) try resolved( .nativePlugin(native), component: native, label: "Native \(agent.rawValue) registration", - origin: .init(document: document, pointer: ""), + origin: proposal.packageMetadata?.nameLocation ?? .init(document: document, pointer: ""), unavailable: nativeName == nil ? "native registration requires adapter-issued container name metadata" : nil) nativeBindings += proposal.bindings diff --git a/Sources/Components/SourceCatalogSelection.swift b/Sources/Components/SourceCatalogSelection.swift new file mode 100644 index 0000000..6e77516 --- /dev/null +++ b/Sources/Components/SourceCatalogSelection.swift @@ -0,0 +1,194 @@ +import AgentsCore +import Foundation + +extension SourceCatalog { + /// Combines member recipes by container, preserving typed exclusions and byte-exact selectors. + package func additions( + _ ids: [ID], agents: [AgentID]?, condition: DeclarationCondition?, mode: InstallMode? + ) throws -> Declaration { + guard let selected = try selected(ids) else { return Declaration() } + var result = Declaration(sources: [alias: source]) + var plugins: [(Data, ComponentDeclaration, [ComponentReferenceDeclaration]?)] = [] + for choice in selected { + switch choice.unit { + case .skill(let name): + result.components.append( + .skills( + source: alias, + .init( + select: .names([name]), agents: agents, mode: mode, condition: condition))) + case .instruction(let name): + result.components.append( + .instructions( + .init( + agents: agents, sections: [alias + ":" + name], condition: condition))) + case .group(var use): + var restriction = condition + if let agents { + restriction = restriction ?? .init() + let existingAgents = restriction?.agents + restriction?.agents = + existingAgents.map { existing in agents.filter { existing.contains($0) } } ?? agents + } + use.condition = restriction + result.uses.append(use) + case .nativePlugin(let declaration), .componentsPlugin(let declaration): + try addPlugin(declaration, member: nil) + case .pluginMember(let declaration, let selector): + try addPlugin(declaration, member: selector) + case .importer: + throw CoreError.invalidState("importer choices require adapter conversion") + } + } + for (_, declaration, members) in plugins { + guard + case .plugin( + let name, let path, let source, let strategy, _, _, let defaults, _, let native) = + declaration + else { continue } + let recipients = agents ?? defaults + if strategy == .native, recipients?.count != 1 { + throw CoreError.invalidState("native registration requires exactly one recipient") + } + var kinds: [DeclaredComponentKind]? = nil + var exclusions: [ComponentReferenceDeclaration] = [] + if let members { + let identities = try Set(members.map(Self.referenceIdentity)) + let recipes = choices.compactMap { + choice -> (ComponentDeclaration, ComponentReferenceDeclaration)? in + if case .pluginMember(let recipe, let selector) = choice.unit { + return (recipe, selector) + } + return nil + } + kinds = [] + for (recipe, selector) in recipes { + guard case .plugin(_, let p, let s, _, let select, _, let a, _, _) = recipe, + try containerIdentity(path: p, source: s, agents: a) + == containerIdentity(path: path, source: source, agents: defaults) + else { continue } + if try identities.contains(Self.referenceIdentity(selector)) { + for kind in select ?? [] where !kinds!.contains(kind) { kinds!.append(kind) } + } + } + for (recipe, selector) in recipes { + guard case .plugin(_, let p, let s, _, let select, _, let a, _, _) = recipe, + try containerIdentity(path: p, source: s, agents: a) + == containerIdentity(path: path, source: source, agents: defaults), + select?.contains(where: { kinds!.contains($0) }) == true, + try !identities.contains(Self.referenceIdentity(selector)) + else { continue } + exclusions.append(selector) + } + } + result.components.append( + .plugin( + name: name, path: path, source: source, mode: strategy, + select: kinds, exclude: exclusions, agents: recipients, condition: condition, + native: native)) + } + return result + + func addPlugin(_ declaration: ComponentDeclaration, member: ComponentReferenceDeclaration?) + throws + { + guard + case .plugin(_, let path, let source, let strategy, _, _, let agents, _, _) = declaration + else { return } + let key = try containerIdentity(path: path, source: source, agents: agents) + if let index = plugins.firstIndex(where: { $0.0 == key }) { + guard case .plugin(_, _, _, let existing, _, _, _, _, _) = plugins[index].1, + existing == strategy + else { throw CoreError.invalidState("incompatible plugin strategies") } + if let member, plugins[index].2 != nil { + plugins[index].2!.append(member) + } else { + plugins[index].2 = nil + } + } else { + plugins.append((key, declaration, member.map { [$0] })) + } + } + func containerIdentity(path: String, source: String, agents: [AgentID]?) throws -> Data { + try JSONEncoder().encode([source, path] + (agents ?? []).map(\.rawValue)) + } + } + + private static func referenceIdentity(_ value: ComponentReferenceDeclaration) throws -> Data { + Data(try ResolvedLedgerCodec.bytes(LedgerPayload.reference(value))) + } + + /// Runs the adapter inside an owned, freshly verified snapshot. No borrowed path is returned. + package func conversion( + keys: Set, bindings: [String: RuntimeBinding], sources: [String: SourceDeclaration], + content: [String: String], store: StateStore + ) throws -> (Declaration, SourceImportProposal) { + guard let imported = importDocument else { + throw CoreError.invalidState("not an importer catalog") + } + let budget = LinkBudget() + return try SourceResolutionSession.withTemporaryRead(store: store) { session in + let view: SourceSnapshot + if try source.requirement != nil || session.isGitSource(source) { + guard + let pin = try session.candidates( + for: source, requirements: [source.requirement], spending: budget.step + ).first + else { + throw CoreError.invalidSource("source has no matching revision") + } + view = try session.snapshot(source, at: pin) + } else { + view = try session.localSnapshot(source) + } + try budget.snapshot(view.snapshot) + guard view.snapshot == snapshot, try FileHash.folderHash(view.directory()) == contentHash + else { + throw CoreError.invalidState("catalog source changed; refresh inspection") + } + let document = try view.relativePath( + PathSafety.resolvedChild(base: view.directory(), subpath: imported.document)) + var input = SourceImportInput( + profile: imported.profile, root: view.root, document: document, + selection: keys, sourceDeclarations: sources, installedSkills: content) + input.bindingReferences = bindings + var proposal = try SourceImport.preview(input) + guard proposal.diagnostics.isEmpty, proposal.bindings.isEmpty, + !proposal.resources.contains(where: { + $0.selected + && ($0.requiresBindingRewrite + || ($0.producerIntegrity != nil && $0.observedHash == nil)) + }) + else { + throw CoreError.invalidState( + "import has unresolved conversion, binding or preserved resource requirements") + } + var declaration = Declaration() + for index in proposal.sources.indices { + let imported = proposal.sources[index] + guard var coordinate = imported.declaration else { + throw CoreError.invalidSource("import lacks canonical source coordinates") + } + if coordinate.kind == .local { + let local = coordinate.localURL( + environment: .init( + projectDirectory: view.root, homeDirectory: view.root, environment: [:])) + let relative = try view.relativePath(local) + coordinate = source + coordinate.path = relative + if let pin = view.pin { coordinate.requirement = .revision(pin.revision) } + coordinate.environment = source.environment + } + declaration.sourceDeclarations.append(.init(name: imported.alias, source: coordinate)) + proposal.sources[index] = .init( + alias: imported.alias, origin: imported.origin, declaration: coordinate, + pin: imported.pin, requestedRef: imported.requestedRef, producerPath: nil, + producerIdentity: imported.producerIdentity, registry: imported.registry, + resolvedRef: imported.resolvedRef, resolvedURL: imported.resolvedURL, + developmentOnly: imported.developmentOnly) + } + declaration.components = proposal.components.map(\.declaration) + return (declaration, proposal) + } + } +} diff --git a/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift b/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift new file mode 100644 index 0000000..317d15e --- /dev/null +++ b/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift @@ -0,0 +1,229 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsUpdates +@testable import Components + +@Suite("Captured source catalog additions", .serialized) +struct SourceCatalogInspectionTests { + @Test func instructionSelectionPreparesAppliesAndRejectsForeignDestination() throws { + let f = try UpdateFixture() + let other = try UpdateFixture() + var environment = f.environment + environment.environment["PRIVATE_CATALOG_ENV"] = "CATALOG_ENV_CANARY" + let before = try FileHash.folderHash(f.root) + let catalog = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: f.repo.path), environment: environment + ) + #expect(!String(reflecting: catalog).contains("CATALOG_ENV_CANARY")) + #expect(!String(reflecting: catalog).contains("agents-resolution-")) + let choice = try #require( + catalog.availableChoices.first { + if case .instruction = $0.unit { return true } + return false + }) + let otherCatalog = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: f.repo.path), environment: environment + ) + #expect(throws: (any Error).self) { try otherCatalog.select([choice.id]) } + #expect(throws: (any Error).self) { try catalog.select([choice.id, choice.id]) } + let discovery = try #require(try catalog.select([choice.id], options: .init(agents: [.codex]))) + #expect(try FileHash.folderHash(f.root) == before) + let request = discovery.updateRequest() + #expect(throws: (any Error).self) { + try UpdateOperations.preview(request, environment: other.environment) + } + let preview = try UpdateOperations.preview(request, environment: environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + #expect( + try UpdateOperations.inspect(environment: environment).components.contains { + $0.kind == .instructions + }) + } + + @Test func emptySelectionDoesNotReadDeletedSourceAndStaleRequestsReject() throws { + let f = try UpdateFixture() + let catalog = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: f.repo.path), + environment: f.environment) + let choice = try #require( + catalog.availableChoices.first { + if case .skill = $0.unit { return true } + return false + }) + let discovery = try #require( + try catalog.select([choice.id], options: .init(agents: [.codex], skillMode: .copy))) + try f.advance() + #expect(throws: (any Error).self) { try catalog.select([choice.id]) } + #expect(throws: (any Error).self) { + try UpdateOperations.preview(discovery.updateRequest(), environment: f.environment) + } + try FileManager.default.removeItem(at: f.repo) + #expect(try catalog.select([]) == nil) + #expect(!FileManager.default.fileExists(atPath: f.store.declarationURL.path)) + #expect(!FileManager.default.fileExists(atPath: f.store.resolvedURL.path)) + } + + @Test func importerRealKeyRetainsAllFamiliesAndFixedEffectsAndOriginalFreshness() throws { + let f = try UpdateFixture() + let producer = f.root.appendingPathComponent("import-source") + try f.write( + #"{"mcp":{"servers":{"same":{"type":"local","command":["never-run"]}}},"commands":{"same":{"template":"Review"},"other":{"template":"Other"}},"agents":{"same":{"system":"Review","mode":"subagent"}},"lsp":{"fixed":{"command":["never-run"]}}}"#, + to: producer.appendingPathComponent("opencode.json")) + let before = try FileHash.folderHash(f.root) + let catalog = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: producer.path), + importing: .init(format: "openCodeConfigV2", document: "opencode.json", selection: []), + environment: f.environment) + let key = try #require( + catalog.availableChoices.first { $0.importedEffects?.components.count == 3 }) + #expect( + Set(key.importedEffects!.components.map(\.declaration.kind)) == [ + .mcpServer, .command, .subagent, + ]) + #expect(catalog.fixedEffects?.components.map(\.declaration.kind) == [.lspServer]) + let discovery = try #require(try catalog.select([key.id])) + #expect(discovery.components.count == 4) + #expect(try FileHash.folderHash(f.root) == before) + _ = try UpdateOperations.preview(discovery.updateRequest(), environment: f.environment) + // Inline canonical declarations alone cannot attest this original adapter document. + try f.write("{}", to: producer.appendingPathComponent("opencode.json")) + #expect(throws: (any Error).self) { + try UpdateOperations.preview(discovery.updateRequest(), environment: f.environment) + } + try f.write( + #"{"commands":{"review":{"template":"Review captured sources"}}}"#, + to: producer.appendingPathComponent("opencode.json")) + let refreshed = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: producer.path), + importing: .init(format: "openCodeConfigV2", document: "opencode.json"), + environment: f.environment) + let refreshedChoice = try #require(refreshed.availableChoices.first) + let selected = try #require(try refreshed.select([refreshedChoice.id])) + let preview = try UpdateOperations.preview(selected.updateRequest(), environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate( + selected.updateRequest(), environment: f.environment + ) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + #expect( + try UpdateOperations.inspect(environment: f.environment).components.contains { + $0.kind == .command + }) + } + + @Test func membersComposeOneContainerAndNativeStrategyConflicts() throws { + let f = try UpdateFixture() + let producer = f.root.appendingPathComponent("plugin-source") + try f.write( + #"{"name":"exact-package","version":"1.2.3"}"#, + to: producer.appendingPathComponent("gemini-extension.json")) + try f.write( + "description = \"First\"\nprompt = \"One\"\n", + to: producer.appendingPathComponent("commands/one.toml")) + try f.write( + "description = \"Second\"\nprompt = \"Two\"\n", + to: producer.appendingPathComponent("commands/two.toml")) + let catalog = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: producer.path), + environment: f.environment) + let members = catalog.availableChoices.filter { + if case .pluginMember = $0.unit { return true } + return false + } + #expect(members.count == 2) + let discovery = try #require(try catalog.select(members.map(\.id))) + let request = discovery.updateRequest() + guard case .declaration(let declaration) = request.operation else { + Issue.record("missing addition") + return + } + #expect(declaration.components.count == 1) + guard + case .plugin(_, _, _, let strategy, let kinds, let exclusions, _, _, _) = + declaration.components[0] + else { + Issue.record("missing container") + return + } + #expect(strategy == .components && kinds == [.command] && exclusions.isEmpty) + let native = try #require( + catalog.availableChoices.first { + if case .nativePlugin = $0.unit { return true } + return false + }) + let metadata = try #require( + try SourceImport.preview( + .init(profile: .geminiExtensionV1, root: producer, document: "gemini-extension.json") + ).packageMetadata) + #expect(native.origin.pointer == metadata.nameLocation.pointer) + #expect(native.origin.span == metadata.nameLocation.span) + #expect(throws: (any Error).self) { try catalog.select([native.id, members[0].id]) } + } +} + +extension SourceCatalogInspectionTests { + @Test func symbolicGroupAdditionPreservesUnrelatedCommittedPins() throws { + let f = try UpdateFixture() + try f.install(agents: [.codex]) + let previous = try f.store.loadLedger() + try f.advance() + let producer = f.root.appendingPathComponent("export-source") + try f.write( + """ + version: 1 + exports: [review] + groups: + review: + components: + - {kind: command, name: review, description: Review, prompt: Exact, agents: [claude-code]} + """, to: producer.appendingPathComponent(".agent/agents.yaml")) + let catalog = try UpdateOperations.inspectSource( + alias: "exports", source: .init(kind: .local, location: producer.path), + environment: f.environment) + let choice = try #require( + catalog.availableChoices.first { + if case .group = $0.unit { return true } + return false + }) + let discovery = try #require(try catalog.select([choice.id])) + let request = discovery.updateRequest() + guard case .declaration(let declaration) = request.operation else { + Issue.record("missing declaration") + return + } + #expect(declaration.uses == [.init(name: "review", source: "exports")]) + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let next = try f.store.loadLedger() + for (id, component) in previous.components { + #expect(next.components[id] == component) + #expect(next.sources[component.source] == previous.sources[component.source]) + } + } + + @Test func rawResourceRewriteCannotBeClearedThroughCatalogBindingInput() throws { + let f = try UpdateFixture() + let producer = f.root.appendingPathComponent("credential-source") + try f.write( + #"{"mcpServers":{"review":{"command":"never-run","env":{"TOKEN":"CATALOG_PRIVATE_CANARY"}}}}"#, + to: producer.appendingPathComponent("settings.json")) + let catalog = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: producer.path), + importing: .init(format: "claudeSettingsV1", document: "settings.json"), + environment: f.environment) + let choice = try #require(catalog.availableChoices.first) + let binding = try #require(catalog.requiredInputs.first { $0.kind == .bindingReference }) + #expect(!String(reflecting: catalog).contains("CATALOG_PRIVATE_CANARY")) + #expect(throws: (any Error).self) { + try catalog.select( + [choice.id], inputs: [.init(id: binding.id, value: .binding(.environment("REVIEW_TOKEN")))]) + } + #expect(!FileManager.default.fileExists(atPath: f.store.declarationURL.path)) + } +} diff --git a/Tests/ComponentsTests/SourceCatalogTests.swift b/Tests/ComponentsTests/SourceCatalogTests.swift index 02601e6..58f282e 100644 --- a/Tests/ComponentsTests/SourceCatalogTests.swift +++ b/Tests/ComponentsTests/SourceCatalogTests.swift @@ -88,8 +88,24 @@ struct SourceCatalogTests { for choice in catalog.choices { switch choice.unit { case .nativePlugin(let declaration): - #expect(choice.unavailableReason?.contains("adapter-issued container name") == true) - #expect(throws: (any Error).self) { try catalog.selected([choice.id]) } + let metadata = try SourceImport.preview( + .init( + profile: .claudePluginV1, root: fixture.project, + document: "bundle/.claude-plugin/plugin.json") + ).packageMetadata + if let metadata { + guard case .plugin(let name, _, _, _, _, _, _, _, _) = declaration else { + Issue.record("wrong native unit") + continue + } + #expect(name.utf8.elementsEqual(metadata.name.utf8)) + #expect(choice.origin == metadata.nameLocation) + #expect(choice.unavailableReason == nil) + #expect(try catalog.selected([choice.id])?.count == 1) + } else { + #expect(choice.unavailableReason?.contains("adapter-issued container name") == true) + #expect(throws: (any Error).self) { try catalog.selected([choice.id]) } + } guard case .plugin(_, _, _, let mode, let select, let exclude, let agents, _, _) = declaration else { From d27f8e3f551be65ef260507f4297393db6f5a0da Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:03:07 +0800 Subject: [PATCH 141/171] test: verify native catalog lifecycle integration --- .../SourceCatalogInspectionTests.swift | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift b/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift index 317d15e..f709bef 100644 --- a/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift +++ b/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift @@ -227,3 +227,111 @@ extension SourceCatalogInspectionTests { #expect(!FileManager.default.fileExists(atPath: f.store.declarationURL.path)) } } + +extension SourceCatalogInspectionTests { + @Test(arguments: [AgentID.claudeCode, .cursor], [PluginModeDeclaration.native, .components]) + func nativeCatalogSelectionPublishesExactRegistrationAndSelectedGeneratedMembers( + _ agent: AgentID, _ strategy: PluginModeDeclaration + ) throws { + let f = try UpdateFixture(scope: .user) + let producer = f.root.appendingPathComponent("catalog-package") + let container = producer.appendingPathComponent("bundle") + let manifest = + agent == .claudeCode ? ".claude-plugin/plugin.json" : ".cursor-plugin/plugin.json" + let profile: SourceImportProfile = agent == .claudeCode ? .claudePluginV1 : .cursorPluginV1 + try f.write(#"{"name":"producer-package"}"#, to: container.appendingPathComponent(manifest)) + for (name, body) in [("review", "Selected captured command"), ("other", "Unselected command")] { + try f.write( + agent == .claudeCode ? "---\ndescription: Review\n---\n\(body)\n" : body + "\n", + to: container.appendingPathComponent("commands/\(name).md")) + } + try f.write( + "---\nname: helper\ndescription: Helper\n---\nSelected captured skill\n", + to: container.appendingPathComponent("skills/helper/SKILL.md")) + let script = container.appendingPathComponent("scripts/never-run") + try f.write("#!/bin/sh\n# Never executed.\n", to: script) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: script.path) + let before = try FileHash.folderHash(f.root) + let catalog = try UpdateOperations.inspectSource( + alias: "consumer-alias", + source: .init(kind: .local, location: producer.path, path: "bundle"), scope: .user, + environment: f.environment) + let native = try #require( + catalog.availableChoices.first { + if case .nativePlugin = $0.unit { return true } + return false + }) + let metadata = try #require( + try SourceImport.preview( + .init( + profile: profile, root: producer, + document: "bundle/" + manifest) + ).packageMetadata) + #expect(native.unavailableReason == nil) + #expect(native.origin.document == metadata.nameLocation.document) + #expect(native.origin.pointer == metadata.nameLocation.pointer) + #expect(native.origin.span == metadata.nameLocation.span) + #expect(native.effects.first?.name.utf8.elementsEqual(metadata.name.utf8) == true) + #expect(native.effects.first?.recipients == [agent]) + let choices: [SourceCatalogChoiceID] + if strategy == .native { + choices = [native.id] + } else { + choices = catalog.availableChoices.compactMap { + guard case .pluginMember(let selector) = $0.unit else { return nil } + switch selector { + case .command(name: "review"), .skill(name: "helper"): return $0.id + default: return nil + } + } + #expect(choices.count == 2) + } + let discovery = try #require(try catalog.select(choices, options: .init(agents: [agent]))) + let request = discovery.updateRequest() + guard case .declaration(let declaration) = request.operation else { + Issue.record("missing captured declaration") + return + } + #expect(declaration.components.count == 1) + guard + case .plugin(_, _, _, let mode, let select, let exclude, let recipients, _, _) = + declaration.components[0] + else { + Issue.record("missing plugin declaration") + return + } + #expect(mode == strategy && recipients == [agent]) + if strategy == .native { #expect(select == nil && exclude.isEmpty) } + #expect(try FileHash.folderHash(f.root) == before) + let preview = try UpdateOperations.preview(request, scope: .user, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, scope: .user, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let installed = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(installed.deployments.allSatisfy { $0.status == .current }) + let tree = try #require( + installed.deployments.first { + FileManager.default.fileExists(atPath: $0.location.appendingPathComponent(manifest).path) + }?.location) + #expect( + try String(contentsOf: tree.appendingPathComponent("commands/review.md"), encoding: .utf8) + .contains("Selected captured command")) + #expect( + try String(contentsOf: tree.appendingPathComponent("skills/helper/SKILL.md"), encoding: .utf8) + .contains("Selected captured skill")) + #expect( + FileManager.default.fileExists(atPath: tree.appendingPathComponent("commands/other.md").path) + == (strategy == .native)) + let frozen = try FileHash.folderHash(tree) + let flags = try FileHash.executableFlags(tree) + if strategy == .native { #expect(flags["scripts/never-run"] == true) } + try FileManager.default.removeItem(at: producer) + if FileManager.default.fileExists(atPath: f.store.cacheDirectory.path) { + try FileManager.default.removeItem(at: f.store.cacheDirectory) + } + try FileManager.default.removeItem(at: tree) + _ = try UpdateOperations.restore(scope: .user, environment: f.environment) + #expect(try FileHash.folderHash(tree) == frozen) + #expect(try FileHash.executableFlags(tree) == flags) + } +} From 6e6774e7c3bba8d1dd6cf4966f40a94ce0de3f03 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:24:33 +0800 Subject: [PATCH 142/171] feat: distinguish metadata and content read dependencies --- Documentation/Architecture/Instructions.md | 15 ++- Documentation/Architecture/Package.md | 10 ++ Sources/AgentsCore/ReadDependency.swift | 15 +++ Sources/AgentsCore/StateInspection.swift | 23 ++-- .../InstructionExport.swift | 20 +-- .../MCPConnectionOperations.swift | 17 +-- .../MCPConnectionResources.swift | 4 +- .../MCPConnectionSelection.swift | 13 +- .../AgentsCoreTests/ReadDependencyTests.swift | 21 ++++ .../MappingReadLocationsTests.swift | 116 ++++++++++++++++-- .../ImplicitReadFootprintTests.swift | 4 +- .../MCPConnectionOperationsTests.swift | 58 ++++++++- .../MCPManagedSelectionTests.swift | 32 ++++- 13 files changed, 286 insertions(+), 62 deletions(-) create mode 100644 Sources/AgentsCore/ReadDependency.swift create mode 100644 Tests/AgentsCoreTests/ReadDependencyTests.swift diff --git a/Documentation/Architecture/Instructions.md b/Documentation/Architecture/Instructions.md index 557279d..cb25f8a 100644 --- a/Documentation/Architecture/Instructions.md +++ b/Documentation/Architecture/Instructions.md @@ -144,11 +144,16 @@ prompts are removed. Other source declarations and skill records remain available to their owners. Export maps each scope's locked deployments and prompt sections from ledger -metadata alone. Each `InstructionMapping.readLocations` includes the scope's -declaration, resolved and watch-state leaves, scope directory, scope lock and -recovery markers, including absent entries. These locations remain available -for missing-lock, pending-recovery and unavailable statuses. Mapping does not -read section bodies, append content or deployed target bytes; content inspection +metadata alone. `InstructionMapping.readDependencies` contains `ReadDependency.entry` +values for declaration, resolved and watch-state leaves, the scope root and state +directory, scope lock, recovery markers and attempted external admission paths. +Absent paths and failed admission anchors remain available for missing-lock, +pending-recovery and unavailable statuses. Permitted scope-root aliases retain +both logical and physical paths; forbidden state-directory and lock links do not +introduce their destinations as authority. Entry dependencies observe the named +path and its ancestors, including creation, replacement and access changes; they +do not observe unrelated descendants of directory entries. Mapping does not read +section bodies, append content or deployed target bytes; content inspection operations supply their own dependencies. Planning validates required content before applying. Reports include old and diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 62fb9ba..e04b172 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -376,6 +376,16 @@ fails export without a frozen-byte fallback. Producer-owned append content remai anchored to the selected immutable source and is a frozen replay resource. Installation replay reads only its recorded resources and does not open consumer append references. +`ReadDependency` in AgentsCore distinguishes entry/access interests from recursive +subtree interests. `MCPConnectionSnapshot.readDependencies` and the Codable +`MCPConnectionDescription.readDependencies` expose logical and resolved entry +paths for live resources. Live directories retain live content semantics and +revalidate their identity before binding and start. Captured resources expose no +borrowed or staging paths. Managed selections additionally preserve the existing +ledger/source read footprint as subtree dependencies; an independent subtree +interest remains recursive when it overlaps a live entry. These monitoring fields +do not change CLI reports, which use their existing report types and binding list. + The package-only `MCPConnectionRunner` performs one explicit connection test on already-bound ephemeral values. Only Components links the exact official MCP SDK; SDK models do not enter public APIs. The SDK Client owns automatic initialization diff --git a/Sources/AgentsCore/ReadDependency.swift b/Sources/AgentsCore/ReadDependency.swift new file mode 100644 index 0000000..fc557cd --- /dev/null +++ b/Sources/AgentsCore/ReadDependency.swift @@ -0,0 +1,15 @@ +import Foundation + +/// Producer-owned invalidation interest. Entry dependencies observe the path and its ancestors; +/// subtree dependencies also observe descendants. An independent subtree interest remains valid +/// when an entry dependency names the same path. +public enum ReadDependency: Sendable, Hashable, Codable { + case entry(URL) + case subtree(URL) + + public var url: URL { + switch self { + case .entry(let url), .subtree(let url): url + } + } +} diff --git a/Sources/AgentsCore/StateInspection.swift b/Sources/AgentsCore/StateInspection.swift index 40df17d..a4a12ca 100644 --- a/Sources/AgentsCore/StateInspection.swift +++ b/Sources/AgentsCore/StateInspection.swift @@ -2,14 +2,21 @@ import CPlatform import Foundation extension StateStore { - /// Durable admission dependencies for a scope inspection, including absent entries whose - /// creation changes whether the scope can be read. State-file dependencies belong to the caller. - package var readLockLocations: [URL] { - [directory] - + [ - ".agents.lock", TransactionJournal.fileName, TransactionJournal.incompleteFileName, - "watch-refs.pending", - ].map { directory.appendingPathComponent($0) } + /// Metadata and admission entries, including absent paths. Only the supplied scope root + /// resolves through links; state-directory and lock links do not grant new path authority. + package var metadataReadLocations: [URL] { + let root = scope == .project ? environment.projectDirectory : environment.homeDirectory + let roots = [root, root.resolvingSymlinksInPath()] + return roots + + roots.flatMap { root in + let directory = root.appendingPathComponent(self.directory.lastPathComponent) + return [directory] + + [ + Self.declarationFileName, Self.resolvedFileName, Self.watchFileName, ".agents.lock", + TransactionJournal.fileName, TransactionJournal.incompleteFileName, + "watch-refs.pending", + ].map { directory.appendingPathComponent($0) } + } } /// Takes an existing scope lock without creating files or replaying recovery. diff --git a/Sources/AgentsInstructions/InstructionExport.swift b/Sources/AgentsInstructions/InstructionExport.swift index 4c52135..03131c0 100644 --- a/Sources/AgentsInstructions/InstructionExport.swift +++ b/Sources/AgentsInstructions/InstructionExport.swift @@ -28,10 +28,9 @@ public struct InstructionMapping: Sendable, Equatable { /// Locked sections without a target assignment. public let unplaced: [LockedSection] public let prompts: [String: [LockedSection]] - /// Durable scope-state and read-admission dependencies, including absent leaves and their - /// scope directory. Retained for every status; section bodies, append files and target bytes - /// are not read by this mapping operation. - public let readLocations: [URL] + /// Scope metadata and read-admission entries, including absent paths and logical/physical + /// root aliases. Retained for every status; bodies, append files and target bytes are not read. + public let readDependencies: [ReadDependency] } extension InstructionOperations { @@ -55,14 +54,14 @@ extension InstructionOperations { { let store = StateStore(scope: scope, environment: environment) let root = scope == .project ? environment.projectDirectory : environment.homeDirectory - var readLocations = Set( - (store.readLockLocations + [store.declarationURL, store.resolvedURL, store.watchURL]) - .map(\.standardizedFileURL)) - func locations() -> [URL] { readLocations.sorted { $0.path < $1.path } } + var readLocations = Set(store.metadataReadLocations.map(\.standardizedFileURL)) + func dependencies() -> [ReadDependency] { + readLocations.sorted { $0.path < $1.path }.map(ReadDependency.entry) + } func empty(_ status: InstructionMapping.Status) -> InstructionMapping { InstructionMapping( scope: scope, root: root, status: status, targets: [], unplaced: [], prompts: [:], - readLocations: locations()) + readDependencies: dependencies()) } do { return try store.withReadLock( @@ -104,7 +103,8 @@ extension InstructionOperations { return InstructionMapping( scope: scope, root: root, status: .locked, targets: targets, unplaced: [], - prompts: lock.instructions.chatgpt.mapValues(\.sections), readLocations: locations()) + prompts: lock.instructions.chatgpt.mapValues(\.sections), + readDependencies: dependencies()) }) } catch { return empty(.unavailable(String(describing: error))) diff --git a/Sources/AgentsUpdates/MCPConnectionOperations.swift b/Sources/AgentsUpdates/MCPConnectionOperations.swift index a911643..cc12e3a 100644 --- a/Sources/AgentsUpdates/MCPConnectionOperations.swift +++ b/Sources/AgentsUpdates/MCPConnectionOperations.swift @@ -13,9 +13,10 @@ public struct MCPConnectionSnapshot: Sendable, CustomStringConvertible, { public let id: UUID public let selectionID: String - var durableReadLocations: [URL] - /// Durable invalidation inputs; never borrowed or per-test staging directories. - public var readLocations: [URL] { durableReadLocations } + var durableReadDependencies: [ReadDependency] + /// Durable invalidation interests. Live resources observe entries; independently required + /// source inputs may observe subtrees. Borrowed and per-test staging paths are never exposed. + public var readDependencies: [ReadDependency] { durableReadDependencies } fileprivate let inputBytes: Int fileprivate let transport: MCPTransportDeclaration fileprivate let directory: MCPConnectionResource? @@ -41,7 +42,7 @@ public struct MCPConnectionDescription: Codable, Sendable, Equatable { public let workingDirectoryIsCaptured: Bool /// Origin with path/query withheld; no header or credential values are exposed. public let endpoint: String? - public let readLocations: [URL] + public let readDependencies: [ReadDependency] } /// Protocol time excludes the separately bounded owned cleanup. The total timer @@ -178,11 +179,11 @@ public enum MCPConnectionOperations { } return MCPConnectionSnapshot( id: UUID(), selectionID: selectionID, - durableReadLocations: Array( + durableReadDependencies: Array( Set( - (workingDirectory?.readLocations ?? []) + (executable?.readLocations ?? []) + (workingDirectory?.readDependencies ?? []) + (executable?.readDependencies ?? []) ) - ).sorted { $0.path < $1.path }, + ).sorted { $0.url.path < $1.url.path }, inputBytes: MCPConnectionLimits().inputBytes - remaining, transport: transport, directory: workingDirectory, executable: executable) @@ -230,7 +231,7 @@ public enum MCPConnectionOperations { executable: executable, arguments: arguments, workingDirectory: directory, executableIsCaptured: snapshot.executable?.isCaptured ?? false, workingDirectoryIsCaptured: snapshot.directory?.isCaptured ?? false, - endpoint: endpoint, readLocations: snapshot.readLocations) + endpoint: endpoint, readDependencies: snapshot.readDependencies) } /// Tests only this selected value, never a refreshed source or matching name. diff --git a/Sources/AgentsUpdates/MCPConnectionResources.swift b/Sources/AgentsUpdates/MCPConnectionResources.swift index 9bf3554..635dbc9 100644 --- a/Sources/AgentsUpdates/MCPConnectionResources.swift +++ b/Sources/AgentsUpdates/MCPConnectionResources.swift @@ -29,8 +29,8 @@ public struct MCPConnectionResource: Sendable, CustomStringConvertible, if case .captured = storage { true } else { false } } var displayPath: String { sourcePath } - var readLocations: [URL] { - sensitivePaths.map { URL(fileURLWithPath: $0).standardizedFileURL } + var readDependencies: [ReadDependency] { + sensitivePaths.map { .entry(URL(fileURLWithPath: $0).standardizedFileURL) } } public var description: String { "" } public var debugDescription: String { description } diff --git a/Sources/AgentsUpdates/MCPConnectionSelection.swift b/Sources/AgentsUpdates/MCPConnectionSelection.swift index f66bfa3..63b5848 100644 --- a/Sources/AgentsUpdates/MCPConnectionSelection.swift +++ b/Sources/AgentsUpdates/MCPConnectionSelection.swift @@ -88,13 +88,18 @@ extension MCPConnectionOperations { var result = try snapshot( selectionID: selection.identity, transport: transport, workingDirectory: directory, executable: executable) - result.durableReadLocations = Array( + result.durableReadDependencies = Array( Set( - result.readLocations + result.readDependencies + (try UpdateOperations.readLocations( - declarations: [], ledgers: [ledger], store: store)) + declarations: [], ledgers: [ledger], store: store)).map(ReadDependency.subtree) ) - ).sorted { $0.path < $1.path } + ).sorted { + if $0.url.path != $1.url.path { return $0.url.path < $1.url.path } + if case .entry = $0 { return false } + if case .entry = $1 { return true } + return false + } try baseline.validate() return result } diff --git a/Tests/AgentsCoreTests/ReadDependencyTests.swift b/Tests/AgentsCoreTests/ReadDependencyTests.swift new file mode 100644 index 0000000..97e0209 --- /dev/null +++ b/Tests/AgentsCoreTests/ReadDependencyTests.swift @@ -0,0 +1,21 @@ +import AgentsCore +import Foundation +import Testing + +struct ReadDependencyTests { + @Test func codableRetainsEntryAndSubtreeAtTheSameURL() throws { + let url = URL(fileURLWithPath: "/scope/absent") + let values: [ReadDependency] = [.entry(url), .subtree(url)] + #expect(Set(values).count == 2) + #expect(values.map(\.url) == [url, url]) + let bytes = try JSONEncoder().encode(values) + #expect(try JSONDecoder().decode([ReadDependency].self, from: bytes) == values) + let expected = Data( + "[{\"entry\":{\"_0\":\"file:///scope/absent\"}},{\"subtree\":{\"_0\":\"file:///scope/absent\"}}]" + .utf8) + #expect(try JSONDecoder().decode([ReadDependency].self, from: expected) == values) + #expect( + try JSONSerialization.jsonObject(with: bytes) as? NSArray == JSONSerialization.jsonObject( + with: expected) as? NSArray) + } +} diff --git a/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift b/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift index 5a9077b..ad38f71 100644 --- a/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift +++ b/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift @@ -6,7 +6,7 @@ import Foundation import StateTestSupport import Testing -@Suite("Instruction mapping read locations") +@Suite("Instruction mapping read dependencies") struct MappingReadLocationsTests { @Test(arguments: [ "base-absent", "metadata-absent", "lock-absent", "base-access", "metadata-access", @@ -53,7 +53,9 @@ struct MappingReadLocationsTests { at: base, includingPropertiesForKeys: nil ).first) let lock = metadata.appendingPathComponent("lock") - let externalPaths = Set([config, base, metadata, lock].map { $0.standardizedFileURL.path }) + let externalPaths = Set( + [config, base, metadata, lock, URL(fileURLWithPath: "/")] + .map { $0.standardizedFileURL.path }) let damaged = damage.hasPrefix("base") ? base : damage.hasPrefix("metadata") ? metadata : lock let backup = f.root.appendingPathComponent("metadata-backup") let scopeBefore = try f.snapshot(store.directory) @@ -68,8 +70,9 @@ struct MappingReadLocationsTests { Issue.record("Expected failed shared admission, got \(unavailable.status)") return } + #expect(unavailable.readDependencies.allSatisfy { if case .entry = $0 { true } else { false } }) #expect( - Set(unavailable.readLocations.map(\.path)).isSuperset(of: externalPaths)) + Set(unavailable.readDependencies.map { $0.url.path }).isSuperset(of: externalPaths)) #expect(try f.snapshot() == beforeInspection) #expect(try f.snapshot(store.directory) == scopeBefore) if damage.hasSuffix("absent") { @@ -82,8 +85,9 @@ struct MappingReadLocationsTests { let repairedBeforeInspection = try f.snapshot() let repaired = try mapping() #expect(repaired.status == .pendingRecovery) + #expect(repaired.readDependencies.allSatisfy { if case .entry = $0 { true } else { false } }) #expect( - Set(repaired.readLocations.map(\.path)).isSuperset(of: externalPaths)) + Set(repaired.readDependencies.map { $0.url.path }).isSuperset(of: externalPaths)) #expect(try f.snapshot(store.directory) == scopeBefore) #expect(try f.snapshot() == repairedBeforeInspection) } @@ -117,7 +121,7 @@ struct MappingReadLocationsTests { #expect(mapping.prompts["daily"]?.map(\.name) == ["shared", "own"]) #expect(mapping.unplaced.isEmpty) expectStateLocations(mapping, store: store) - let paths = Set(mapping.readLocations.map(\.path)) + let paths = Set(mapping.readDependencies.map { $0.url.path }) #expect(!paths.contains(own.path)) #expect(!paths.contains(target.path)) #expect(!paths.contains(f.project.appendingPathComponent("append.md").path)) @@ -181,15 +185,101 @@ struct MappingReadLocationsTests { #expect(try f.snapshot() == before) } + @Test(arguments: [InstallScope.project, .user]) + func allowedRootAliasesRetainLogicalAndPhysicalEntries(_ scope: InstallScope) throws { + let f = try InstructionFixture() + let logical = f.root.appendingPathComponent("scope-alias") + let first = f.root.appendingPathComponent("physical-first").resolvingSymlinksInPath() + let second = f.root.appendingPathComponent("physical-second").resolvingSymlinksInPath() + for root in [first, second] { + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false) + } + try FileManager.default.createSymbolicLink(at: logical, withDestinationURL: first) + var environment = f.environment + if scope == .project { + environment.projectDirectory = logical + } else { + environment.homeDirectory = logical + } + let stateName = scope == .project ? ".agent" : ".agents" + func mapping() throws -> InstructionMapping { + let values = InstructionOperations.export( + projectRoots: scope == .project ? [logical] : [], environment: environment) + return try #require(scope == .project ? values.last : values.first) + } + let absent = try mapping() + #expect(absent.status == .missingLock) + let expected = Set( + [ + logical, first, logical.appendingPathComponent(stateName), + first.appendingPathComponent(stateName), + first.appendingPathComponent(stateName + "/agents.resolved"), + ].map(\.path)) + #expect(Set(absent.readDependencies.map { $0.url.path }).isSuperset(of: expected)) + #expect(absent.readDependencies.allSatisfy { if case .entry = $0 { true } else { false } }) + let physicalMarker = first.appendingPathComponent(stateName + "/transaction.new") + try f.write("", to: physicalMarker) + let before = try f.snapshot() + let pending = try mapping() + #expect(pending.status == .pendingRecovery) + #expect(pending.readDependencies.map { $0.url.path }.contains(physicalMarker.path)) + #expect(try f.snapshot() == before) + try FileManager.default.removeItem(at: logical) + try FileManager.default.createSymbolicLink(at: logical, withDestinationURL: second) + let retargetedBefore = try f.snapshot() + let retargeted = try mapping() + #expect(retargeted.status == .missingLock) + #expect(retargeted.readDependencies.map { $0.url.path }.contains(logical.path)) + #expect(retargeted.readDependencies.map { $0.url.path }.contains(second.path)) + #expect(!retargeted.readDependencies.map { $0.url.path }.contains(first.path)) + #expect(try f.snapshot() == retargetedBefore) + } + + @Test(arguments: ["state", "lock"]) + func forbiddenLinksDoNotIntroduceTargetAuthority(_ kind: String) throws { + let f = try InstructionFixture() + let store = f.store() + let external = f.root.appendingPathComponent("forbidden-target") + if kind == "state" { + try FileManager.default.createDirectory(at: external, withIntermediateDirectories: false) + try FileManager.default.createSymbolicLink(at: store.directory, withDestinationURL: external) + } else { + try f.write("", to: external) + try FileManager.default.createDirectory( + at: store.directory, withIntermediateDirectories: false) + try FileManager.default.createSymbolicLink( + at: store.directory.appendingPathComponent(".agents.lock"), withDestinationURL: external) + } + let before = try f.snapshot() + let mapping = try #require( + InstructionOperations.export( + projectRoots: [f.project], environment: f.environment + ).last) + guard case .unavailable = mapping.status else { + Issue.record("Forbidden link was admitted") + return + } + #expect(!mapping.readDependencies.map { $0.url.path }.contains(external.path)) + #expect(mapping.readDependencies.allSatisfy { if case .entry = $0 { true } else { false } }) + #expect(try f.snapshot() == before) + } + private func expectStateLocations(_ mapping: InstructionMapping, store: StateStore) { - let expected = [ - store.directory, store.declarationURL, store.resolvedURL, store.watchURL, - store.directory.appendingPathComponent(".agents.lock"), - store.directory.appendingPathComponent("transaction.json"), - store.directory.appendingPathComponent("transaction.new"), - store.directory.appendingPathComponent("watch-refs.pending"), - ].map(\.path).sorted() - #expect(mapping.readLocations.map(\.path) == expected) + let root = + store.scope == .project + ? store.environment.projectDirectory : store.environment.homeDirectory + let expected = Set( + [root, root.resolvingSymlinksInPath()].flatMap { root in + let state = root.appendingPathComponent(store.scope == .project ? ".agent" : ".agents") + return [root, state] + + [ + "agents.yaml", "agents.resolved", "agents.watch", ".agents.lock", + "transaction.json", "transaction.new", "watch-refs.pending", + ].map { state.appendingPathComponent($0) } + }.map(\.path) + ).sorted() + #expect(mapping.readDependencies.map { $0.url.path } == expected) + #expect(mapping.readDependencies.allSatisfy { if case .entry = $0 { true } else { false } }) } } diff --git a/Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift b/Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift index fa742c1..e522df3 100644 --- a/Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift +++ b/Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift @@ -46,9 +46,9 @@ struct ImplicitReadFootprintTests { let selected = try #require(inspection.components.first { $0.kind == .mcpServer }) let connection = try MCPConnectionOperations.snapshot( selection: selected.selection, scope: scope, environment: f.environment) - #expect(connection.readLocations.map(\.path).contains(tool.path)) + #expect(connection.readDependencies.map { $0.url.path }.contains(tool.path)) if scope == .user { - #expect(!connection.readLocations.map(\.path).contains(root.path)) + #expect(!connection.readDependencies.map { $0.url.path }.contains(root.path)) } #expect( Set(inspection.readLocations.map(\.path)).isSuperset( diff --git a/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift b/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift index d83bbf0..542873a 100644 --- a/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift +++ b/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift @@ -166,8 +166,16 @@ final class MCPFacadeFixture { #expect(!description.workingDirectoryIsCaptured && !description.executableIsCaptured) #expect(description.endpoint == nil && description.startsOwnedProcess) #expect(description.requiredBindings == ["named-secret"]) - #expect(description.readLocations == snapshot.readLocations) - #expect(snapshot.readLocations.contains { $0.path == fixture.root.path }) + #expect(description.readDependencies == snapshot.readDependencies) + #expect(snapshot.readDependencies.contains { $0.url.path == fixture.root.path }) + #expect(snapshot.readDependencies.allSatisfy { if case .entry = $0 { true } else { false } }) + let encoded = try JSONEncoder().encode(description) + #expect(try JSONDecoder().decode(MCPConnectionDescription.self, from: encoded) == description) + let object = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + #expect(object["readLocations"] == nil) + let dependencies = try #require(object["readDependencies"] as? [[String: [String: String]]]) + #expect( + dependencies == description.readDependencies.map { ["entry": ["_0": $0.url.absoluteString]] }) #expect(try FileHash.folderHash(fixture.root) == before && fixture.text("pid") == nil) for transport: MCPTransportDeclaration in [ .sse( @@ -182,7 +190,7 @@ final class MCPFacadeFixture { let info = MCPConnectionOperations.describe(remote) #expect(info.endpoint == "http://127.0.0.1:1/[redacted]") #expect(!info.startsOwnedProcess && info.executable == nil && info.arguments == nil) - #expect(info.workingDirectory == nil && info.readLocations.isEmpty) + #expect(info.workingDirectory == nil && info.readDependencies.isEmpty) let text = String(decoding: try JSONEncoder().encode(info), as: UTF8.self) for hidden in ["private-path", "query-canary", "header-canary"] { #expect(!text.contains(hidden)) @@ -234,11 +242,11 @@ final class MCPFacadeFixture { let liveDescription = MCPConnectionOperations.describe(live) #expect(liveDescription.executable == file.path && !liveDescription.executableIsCaptured) #expect(liveDescription.arguments == ["fixed-argument"]) - #expect(liveDescription.readLocations.contains { $0.path == file.path }) + #expect(liveDescription.readDependencies.contains { $0.url.path == file.path }) let capturedDescription = MCPConnectionOperations.describe(captured) #expect(capturedDescription.executable == "selected-executable") #expect(capturedDescription.executableIsCaptured) - #expect(!capturedDescription.readLocations.contains { $0.path == file.path }) + #expect(!capturedDescription.readDependencies.contains { $0.url.path == file.path }) let path = try MCPConnectionOperations.snapshot( selectionID: "path-command", transport: .stdio(.init(executable: "path-command")), workingDirectory: cwd) @@ -368,6 +376,46 @@ final class MCPFacadeFixture { try fixture.unchanged() } + @Test func liveAliasChildrenStayLiveAndRetargetingRefusesBeforeBinding() async throws { + let fixture = try MCPFacadeFixture() + let logical = fixture.root.appendingPathComponent("live-alias") + let first = fixture.root.appendingPathComponent("physical-first").resolvingSymlinksInPath() + let second = fixture.root.appendingPathComponent("physical-second").resolvingSymlinksInPath() + for directory in [first, second] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + } + try FileManager.default.createSymbolicLink(at: logical, withDestinationURL: first) + let marker = first.appendingPathComponent("live-marker") + try Data("before".utf8).write(to: marker) + let snapshot = try MCPConnectionOperations.snapshot( + selectionID: "live-alias", + transport: .stdio( + .init( + executable: "MCPTestProcess", + arguments: ["normal", fixture.observation.path], + environment: ["TOKEN": .secret("wanted")])), workingDirectory: .live(logical)) + #expect(Set(snapshot.readDependencies.map { $0.url.path }) == Set([logical.path, first.path])) + #expect(snapshot.readDependencies.allSatisfy { if case .entry = $0 { true } else { false } }) + try Data("after".utf8).write(to: marker) + let spy = MCPBindingSpy(["wanted": Data("value".utf8)]) + let live = await MCPConnectionOperations.test( + snapshot, environment: fixture.environment, bindings: spy) + #expect(live.outcome == .discovered && live.cleanupComplete && spy.calls == ["wanted"]) + let wire = try String( + contentsOf: fixture.observation.appendingPathComponent("wire.jsonl"), encoding: .utf8) + let startup = try #require(wire.split(separator: "\n").first) + let record = try #require( + JSONSerialization.jsonObject(with: Data(startup.utf8)) as? [String: Any]) + #expect(record["liveMarker"] as? String == "after") + try FileManager.default.removeItem(at: logical) + try FileManager.default.createSymbolicLink(at: logical, withDestinationURL: second) + let forbidden = MCPBindingSpy(["wanted": Data("unused".utf8)]) + let stale = await MCPConnectionOperations.test( + snapshot, environment: fixture.environment, bindings: forbidden) + #expect(stale.issue == .resourceChanged && stale.cleanupComplete && forbidden.calls.isEmpty) + try fixture.unchanged() + } + @Test func replacedLiveDirectoryRequiresNewSnapshotBeforeBinding() async throws { let fixture = try MCPFacadeFixture() let live = fixture.root.appendingPathComponent("live") diff --git a/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift b/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift index 2aa54a4..f3f9a49 100644 --- a/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift +++ b/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift @@ -122,11 +122,25 @@ private struct ManagedMCPFixture { let description = MCPConnectionOperations.describe(snapshot) #expect(description.executable == "tool" && description.executableIsCaptured) #expect(description.workingDirectory == "cwd" && description.workingDirectoryIsCaptured) - #expect(snapshot.readLocations.contains(f.store.declarationURL)) - #expect(snapshot.readLocations.contains(f.store.resolvedURL)) - #expect(snapshot.readLocations.contains(f.store.watchURL)) - #expect(description.readLocations == snapshot.readLocations) - #expect(!snapshot.readLocations.contains { $0.path.contains("agents-mcp-capture-") }) + #expect(snapshot.readDependencies.contains(.subtree(f.store.declarationURL))) + #expect(snapshot.readDependencies.contains(.subtree(f.store.resolvedURL))) + #expect(snapshot.readDependencies.contains(.subtree(f.store.watchURL))) + #expect(description.readDependencies == snapshot.readDependencies) + #expect(snapshot.readDependencies.allSatisfy { if case .subtree = $0 { true } else { false } }) + let encoded = try JSONEncoder().encode(description) + #expect(try JSONDecoder().decode(MCPConnectionDescription.self, from: encoded) == description) + let object = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + let dependencies = try #require(object["readDependencies"] as? [[String: [String: String]]]) + #expect( + dependencies + == description.readDependencies.map { ["subtree": ["_0": $0.url.absoluteString]] }) + if !remote { + #expect( + snapshot.readDependencies.contains { + if case .subtree(let url) = $0 { url.path == f.producer.path } else { false } + }) + } + #expect(!snapshot.readDependencies.contains { $0.url.path.contains("agents-mcp-capture-") }) let spy = MCPBindingSpy(["wanted": Data("provider-canary".utf8)]) #expect(MCPConnectionOperations.describe(snapshot).requiredBindings == ["wanted"]) #expect(spy.calls.isEmpty) @@ -232,6 +246,14 @@ private struct ManagedMCPFixture { let selection = try f.inspection().selection let snapshot = try MCPConnectionOperations.snapshot( selection: selection, scope: .project, environment: f.fixture.environment) + #expect( + snapshot.readDependencies.contains { + if case .entry(let url) = $0 { url.path == f.fixture.root.path } else { false } + }) + #expect( + snapshot.readDependencies.contains { + if case .subtree(let url) = $0 { url.path == f.producer.path } else { false } + }) try Data("after".utf8).write(to: marker) let spy = MCPBindingSpy() let result = await MCPConnectionOperations.test( From 9f50b49d2607757c2020cf62442beea71e170138 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:44:55 +0800 Subject: [PATCH 143/171] feat: preserve native component source coordinates --- Documentation/Reference/ManifestSchema.md | 3 + Sources/AgentsCore/ComponentDeclaration.swift | 6 +- Sources/AgentsCore/Declaration.swift | 25 +++- .../AgentsManifest/ManifestProjection.swift | 7 +- Sources/AgentsManifest/ManifestSchema.swift | 6 +- .../Resources/agents.schema.json | 12 ++ Sources/AgentsManifest/YAMLConstruction.swift | 6 +- .../AgentsManifest/YAMLDomainValidation.swift | 12 ++ Sources/AgentsManifest/YAMLProjection.swift | 4 +- Sources/AgentsManifest/YAMLWriter.swift | 2 +- .../MCPConnectionOperations.swift | 6 + .../MCPConnectionSelection.swift | 8 +- .../AgentsUpdates/UpdateReadLocations.swift | 5 +- Sources/Components/ComponentFields.swift | 4 +- Sources/Components/Expansion.swift | 16 +++ .../Import/NativeContainerImport.swift | 18 +-- .../Import/NativeExecutableMembers.swift | 11 +- .../Import/NativeSourceImport.swift | 6 +- Sources/Components/LedgerPayload.swift | 1 + Sources/Components/NativeProgramV1.swift | 10 +- Sources/Components/PluginExpansion.swift | 4 +- .../NativeCoordinateTests.swift | 71 ++++++++++ ...ImportNativeExecutableLifecycleTests.swift | 115 ++++++++++++++++ .../ImportNativeLifecycleTests.swift | 125 ++++++++++++++++++ .../SkillPathReadLocationsTests.swift | 25 ++++ .../ImportSupportingLinksTests.swift | 10 ++ .../NativeCoordinateLinkingTests.swift | 71 ++++++++++ 27 files changed, 553 insertions(+), 36 deletions(-) create mode 100644 Tests/AgentsManifestTests/NativeCoordinateTests.swift create mode 100644 Tests/AgentsUpdatesTests/ImportNativeExecutableLifecycleTests.swift create mode 100644 Tests/AgentsUpdatesTests/ImportNativeLifecycleTests.swift create mode 100644 Tests/AgentsUpdatesTests/SkillPathReadLocationsTests.swift create mode 100644 Tests/ComponentsTests/NativeCoordinateLinkingTests.swift diff --git a/Documentation/Reference/ManifestSchema.md b/Documentation/Reference/ManifestSchema.md index 68a8bbe..008f248 100644 --- a/Documentation/Reference/ManifestSchema.md +++ b/Documentation/Reference/ManifestSchema.md @@ -110,6 +110,7 @@ A declared invocation, preserved as data until a consuming operation explicitly | `arguments` | | sequence of string (at most 10000 items) | Arguments in invocation order, passed as individual strings. Omission or an empty sequence supplies no arguments. | | `environment` | | name → binding (at most 10000 properties) | Environment variable names mapped to literals or local bindings. Omission or an empty mapping supplies no declared entries; reading the declaration does not resolve bindings. | | `workingDirectory` | | resource | Working directory resource, resolved by the consuming operation. Omission leaves the directory unspecified in the declaration. | +| `executableSource` | | string | Source alias for a resource executable path. Omission uses the declaring source; a bare PATH command cannot specify a source. | ## transport @@ -126,6 +127,7 @@ Local MCP server invocation over standard input/output. | `arguments` | | sequence of string (at most 10000 items) | Arguments in invocation order, passed as individual strings. Omission or an empty sequence supplies no arguments. | | `environment` | | name → binding (at most 10000 properties) | Environment variable names mapped to literals or local bindings. Omission or an empty mapping supplies no declared entries; reading the declaration does not resolve bindings. | | `workingDirectory` | | resource | Working directory resource, resolved by the consuming operation. Omission leaves the directory unspecified in the declaration. | +| `executableSource` | | string | Source alias for a resource executable path. Omission uses the declaring source; a bare PATH command cannot specify a source. | ### Alternative 2 @@ -326,6 +328,7 @@ Examples: {"kind": "skills", "source": "team", "select": ["review"], "agen | `exclude` | | sequence of string (at most 10000 items) | Skill names removed from the selection. Omission or an empty sequence excludes none. | | `mode` | | `link` / `copy` / `edit` | link shares cached content, copy creates an installed directory, and edit links live local content. Omission defaults to link. edit requires a local source without a requirement or pin. | | `overrides` | | name → override (at most 10000 properties) | Skill names mapped to recipient/mode overrides. Omission or an empty mapping supplies none; omitted override fields inherit the component settings. | +| `path` | | string | Optional discovery path relative to the selected filesystem source view. Narrows discovery without changing containment. Not supported for index sources. | ## component_instructions diff --git a/Sources/AgentsCore/ComponentDeclaration.swift b/Sources/AgentsCore/ComponentDeclaration.swift index a8cfb91..e17e374 100644 --- a/Sources/AgentsCore/ComponentDeclaration.swift +++ b/Sources/AgentsCore/ComponentDeclaration.swift @@ -89,15 +89,19 @@ public enum PromptBody: Equatable, Sendable { public struct ExecutableDeclaration: Equatable, Sendable { public var executable: String + /// Source alias for a resource executable; nil uses the declaring source. + public var executableSource: String? public var arguments: [String] public var environment: [String: RuntimeBinding] public var workingDirectory: ResourceDeclaration? public init( - executable: String, arguments: [String] = [], environment: [String: RuntimeBinding] = [:], + executable: String, executableSource: String? = nil, arguments: [String] = [], + environment: [String: RuntimeBinding] = [:], workingDirectory: ResourceDeclaration? = nil ) { self.executable = executable + self.executableSource = executableSource self.arguments = arguments self.environment = environment self.workingDirectory = workingDirectory diff --git a/Sources/AgentsCore/Declaration.swift b/Sources/AgentsCore/Declaration.swift index e165fcf..ea3cfa7 100644 --- a/Sources/AgentsCore/Declaration.swift +++ b/Sources/AgentsCore/Declaration.swift @@ -108,6 +108,8 @@ public struct SkillOverride: Equatable, Sendable { public struct SkillDeclaration: Equatable, Sendable { public var select: SkillSelection + /// Narrows filesystem discovery relative to the source view while retaining its containment. + public var path: String? public var exclude: [String]? public var agents: [AgentID]? public var mode: InstallMode? @@ -137,11 +139,12 @@ public struct SkillDeclaration: Equatable, Sendable { public var native: NativeConfiguration public init( - select: SkillSelection, exclude: [String]? = nil, agents: [AgentID]? = nil, + select: SkillSelection, path: String? = nil, exclude: [String]? = nil, agents: [AgentID]? = nil, mode: InstallMode? = nil, overrides: [String: SkillOverride]? = nil, condition: DeclarationCondition? = nil, native: NativeConfiguration = [:] ) { self.select = select + self.path = path self.exclude = exclude self.agents = agents self.mode = mode @@ -378,6 +381,12 @@ public struct Declaration: Equatable, Sendable { throw CoreError.invalidState("unknown source alias: \(alias)") } let source = sources[alias] + if let path = selection.path { + _ = try PathSafety.sanitizeSubpath(path) + guard source?.kind != .wellKnown else { + throw CoreError.invalidState("skill paths require a filesystem source") + } + } let modes = [selection.mode ?? .link] + selection.overrideDeclarations.compactMap { $0.override.mode } if modes.contains(.edit), alias != ".", source?.kind != .local || source?.requirement != nil @@ -402,6 +411,20 @@ public struct Declaration: Equatable, Sendable { } default: break } + let program: ExecutableDeclaration? + switch component { + case .mcpServer(_, .stdio(let value), _, _, _): program = value + case .hook(_, _, let value, _, _, _, _, _), .lspServer(_, let value, _, _, _, _, _): + program = value + default: program = nil + } + if let program, let alias = program.executableSource { + guard alias == "." || sources[alias] != nil, program.executable.contains("/") else { + throw CoreError.invalidState( + "executable source requires an existing alias and resource path") + } + _ = try PathSafety.sanitizeSubpath(program.executable) + } } guard Set(watch ?? []).count == (watch ?? []).count else { throw CoreError.invalidState("duplicate watch subscription") diff --git a/Sources/AgentsManifest/ManifestProjection.swift b/Sources/AgentsManifest/ManifestProjection.swift index 963d460..20d9555 100644 --- a/Sources/AgentsManifest/ManifestProjection.swift +++ b/Sources/AgentsManifest/ManifestProjection.swift @@ -103,7 +103,8 @@ package enum ManifestProjection { uniqueKeysWithValues: lhs.overrideDeclarations.map { ($0.name, $0.override) }) let right = Dictionary( uniqueKeysWithValues: rhs.overrideDeclarations.map { ($0.name, $0.override) }) - return selections && Set(lhs.exclude ?? []) == Set(rhs.exclude ?? []) && lhs.mode == rhs.mode + return lhs.path == rhs.path && selections && Set(lhs.exclude ?? []) == Set(rhs.exclude ?? []) + && lhs.mode == rhs.mode && sameRecipients(lhs.agents, rhs.agents) && left.keys == right.keys && left.allSatisfy { equivalent($1, right[$0]!) } && lhs.condition == rhs.condition && lhs.native == rhs.native @@ -171,7 +172,8 @@ private struct Projection { } func executable(_ r: DeclarationRecord) -> ExecutableDeclaration { ExecutableDeclaration( - executable: r["executable"]!.string!, arguments: strings(r["arguments"]), + executable: r["executable"]!.string!, executableSource: r["executableSource"]?.string, + arguments: strings(r["arguments"]), environment: dictionary(r["environment"]).mapValues(binding), workingDirectory: r["workingDirectory"]?.record.map(resource)) } @@ -253,6 +255,7 @@ private struct Projection { } var result = SkillDeclaration( select: r["select"]?.elements.map { .names($0.map { $0.string! }) } ?? .all, + path: r["path"]?.string, exclude: strings(r["exclude"]).isEmpty ? nil : strings(r["exclude"]), agents: agents, mode: r["mode"]?.string.flatMap(InstallMode.init(rawValue:)), overrides: nil, condition: condition, native: native) diff --git a/Sources/AgentsManifest/ManifestSchema.swift b/Sources/AgentsManifest/ManifestSchema.swift index 99e2cec..a0f3574 100644 --- a/Sources/AgentsManifest/ManifestSchema.swift +++ b/Sources/AgentsManifest/ManifestSchema.swift @@ -33,7 +33,7 @@ enum ManifestSchema { [ "executable": .string, "arguments": .array(.string, maximum: 10000), "environment": .dictionary(.named("binding"), maximum: 10000), - "workingDirectory": .named("resource"), + "workingDirectory": .named("resource"), "executableSource": .string, ], required: ["executable"], maximum: nil), "transport": .oneOf([ .object( @@ -41,7 +41,7 @@ enum ManifestSchema { "kind": .constant("stdio"), "executable": .string, "arguments": .array(.string, maximum: 10000), "environment": .dictionary(.named("binding"), maximum: 10000), - "workingDirectory": .named("resource"), + "workingDirectory": .named("resource"), "executableSource": .string, ], required: ["kind", "executable"], maximum: nil), .object( [ @@ -106,7 +106,7 @@ enum ManifestSchema { "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), "source": .string, "select": .oneOf([.constant("all"), .array(.string, maximum: 10000)]), "exclude": .array(.string, maximum: 10000), "mode": .enumeration(["link", "copy", "edit"]), - "overrides": .dictionary(.named("override"), maximum: 10000), + "overrides": .dictionary(.named("override"), maximum: 10000), "path": .string, ], required: ["kind", "source"], maximum: nil), "component_instructions": .object( [ diff --git a/Sources/AgentsManifest/Resources/agents.schema.json b/Sources/AgentsManifest/Resources/agents.schema.json index 3903bbd..793f6b7 100644 --- a/Sources/AgentsManifest/Resources/agents.schema.json +++ b/Sources/AgentsManifest/Resources/agents.schema.json @@ -272,6 +272,10 @@ "workingDirectory": { "$ref": "#/$defs/resource", "description": "Working directory resource, resolved by the consuming operation. Omission leaves the directory unspecified in the declaration." + }, + "executableSource": { + "type": "string", + "description": "Source alias for a resource executable path. Omission uses the declaring source; a bare PATH command cannot specify a source." } }, "required": [ @@ -312,6 +316,10 @@ "workingDirectory": { "$ref": "#/$defs/resource", "description": "Working directory resource, resolved by the consuming operation. Omission leaves the directory unspecified in the declaration." + }, + "executableSource": { + "type": "string", + "description": "Source alias for a resource executable path. Omission uses the declaring source; a bare PATH command cannot specify a source." } }, "required": [ @@ -795,6 +803,10 @@ }, "maxProperties": 10000, "description": "Skill names mapped to recipient/mode overrides. Omission or an empty mapping supplies none; omitted override fields inherit the component settings." + }, + "path": { + "type": "string", + "description": "Optional discovery path relative to the selected filesystem source view. Narrows discovery without changing containment. Not supported for index sources." } }, "required": [ diff --git a/Sources/AgentsManifest/YAMLConstruction.swift b/Sources/AgentsManifest/YAMLConstruction.swift index dd8b0bb..67d2b33 100644 --- a/Sources/AgentsManifest/YAMLConstruction.swift +++ b/Sources/AgentsManifest/YAMLConstruction.swift @@ -149,7 +149,8 @@ enum YAMLConstruction { record( kind, [ - "executable": .string(value.executable), "arguments": strings(value.arguments), + "executable": .string(value.executable), "executableSource": text(value.executableSource), + "arguments": strings(value.arguments), "environment": .dictionary(value.environment.mapValues(binding)), "workingDirectory": value.workingDirectory.map { .record(resource($0)) } ?? .null, ]) @@ -253,7 +254,8 @@ enum YAMLConstruction { case .names(let values): selection = strings(values) } fields = [ - "source": .string(source), "select": selection, "exclude": strings(value.exclude ?? []), + "source": .string(source), "path": text(value.path), "select": selection, + "exclude": strings(value.exclude ?? []), "mode": text(value.mode?.rawValue), "overrides": .array(value.overrideDeclarations.map { .record(override($0)) }), ] diff --git a/Sources/AgentsManifest/YAMLDomainValidation.swift b/Sources/AgentsManifest/YAMLDomainValidation.swift index 7f57756..087adde 100644 --- a/Sources/AgentsManifest/YAMLDomainValidation.swift +++ b/Sources/AgentsManifest/YAMLDomainValidation.swift @@ -174,6 +174,12 @@ struct YAMLDomainValidation { throw fail(pointer, "invalid executable") } if executable.contains("/") || executable.hasPrefix("~") { try resource(executable, pointer) } + if let alias = record["executableSource"]?.string { + try self.alias(alias, pointer + "/executableSource") + guard executable.contains("/") else { + throw fail(pointer + "/executableSource", "executable source requires a resource path") + } + } if let directory = record["workingDirectory"]?.record { try resource(directory, pointer) } } private func component(_ record: DeclarationRecord, _ pointer: String) throws { @@ -184,6 +190,12 @@ struct YAMLDomainValidation { case "skills": let source = record["source"]!.string! try alias(source, pointer) + if let path = record["path"]?.string { + try resource(path, pointer + "/path") + guard sources[source]?.kind != "index" else { + throw fail(pointer + "/path", "skill paths require a filesystem source") + } + } let selected = record["select"]?.elements.map { $0.map { $0.string! } } let excluded = strings(record["exclude"]) do { diff --git a/Sources/AgentsManifest/YAMLProjection.swift b/Sources/AgentsManifest/YAMLProjection.swift index 9d71c13..3e8b9e4 100644 --- a/Sources/AgentsManifest/YAMLProjection.swift +++ b/Sources/AgentsManifest/YAMLProjection.swift @@ -157,11 +157,13 @@ final class YAMLProjection { case "run", "transport": defaults = [ "arguments": .array([]), "environment": .dictionary([:]), "workingDirectory": .null, + "executableSource": .null, ] case "parameter": defaults = ["defaultValue": .null] case "skills": defaults.merge([ - "select": .string("all"), "exclude": .array([]), "mode": .null, "overrides": .array([]), + "path": .null, "select": .string("all"), "exclude": .array([]), "mode": .null, + "overrides": .array([]), ]) { _, r in r } case "instructions": defaults.merge(["sections": .array([]), "chatGPT": .array([])]) { _, r in r } diff --git a/Sources/AgentsManifest/YAMLWriter.swift b/Sources/AgentsManifest/YAMLWriter.swift index 895002b..3bc91a1 100644 --- a/Sources/AgentsManifest/YAMLWriter.swift +++ b/Sources/AgentsManifest/YAMLWriter.swift @@ -117,7 +117,7 @@ enum YAMLWriter { "name", "source", "url", "path", "index", "requirement", "subpath", "select", "exclude", "mode", "overrides", "sections", "chatGPT", "description", "prompt", "model", "tools", "parameters", "transport", "event", "run", "matcher", "timeoutSeconds", "executable", - "arguments", "environment", "workingDirectory", "headers", "languages", + "executableSource", "arguments", "environment", "workingDirectory", "headers", "languages", "initializationOptions", "rules", "operation", "pattern", "patterns", "purpose", "components", "uses", "append", "agents", "scopes", "platforms", "condition", "native", ] diff --git a/Sources/AgentsUpdates/MCPConnectionOperations.swift b/Sources/AgentsUpdates/MCPConnectionOperations.swift index a911643..b6ff05a 100644 --- a/Sources/AgentsUpdates/MCPConnectionOperations.swift +++ b/Sources/AgentsUpdates/MCPConnectionOperations.swift @@ -133,6 +133,12 @@ public enum MCPConnectionOperations { !run.executable.isEmpty, run.executable.contains("/") == (executable != nil), executable?.directory != true else { throw MCPConnectionPreparationError.invalidConfiguration } + if let source = run.executableSource { + guard !source.isEmpty, run.executable.contains("/") else { + throw MCPConnectionPreparationError.invalidConfiguration + } + try charge(source) + } try charge(run.executable) for argument in run.arguments { try charge(argument) } for (key, binding) in run.environment { diff --git a/Sources/AgentsUpdates/MCPConnectionSelection.swift b/Sources/AgentsUpdates/MCPConnectionSelection.swift index f66bfa3..50ef33d 100644 --- a/Sources/AgentsUpdates/MCPConnectionSelection.swift +++ b/Sources/AgentsUpdates/MCPConnectionSelection.swift @@ -127,11 +127,14 @@ extension MCPConnectionOperations { switch try string(fields["kind"]) { case "stdio": guard Set(fields.keys) == ["kind", "run"], let run = fields["run"]?.object, - Set(run.keys).subtracting(["workingDirectory"]) == [ + Set(run.keys).subtracting(["workingDirectory", "executableSource"]) == [ "executable", "arguments", "environment", ], run["arguments"]?.kind == .array, let arguments = run["arguments"]?.array else { throw invalid() } + let executable = try string(run["executable"]) + let executableSource = try run["executableSource"].map { try string($0) } + if executableSource != nil && !executable.contains("/") { throw invalid() } let cwd: ResourceDeclaration? if let directory = run["workingDirectory"] { guard let object = directory.object, Set(object.keys).isSubset(of: ["path", "source"]) @@ -145,7 +148,8 @@ extension MCPConnectionOperations { } return try .stdio( .init( - executable: string(run["executable"]), arguments: arguments.map { try string($0) }, + executable: executable, executableSource: executableSource, + arguments: arguments.map { try string($0) }, environment: bindings(run["environment"]), workingDirectory: cwd)) case "streamableHTTP", "sse": guard Set(fields.keys) == ["kind", "url", "headers"] else { throw invalid() } diff --git a/Sources/AgentsUpdates/UpdateReadLocations.swift b/Sources/AgentsUpdates/UpdateReadLocations.swift index e1f4d41..51b2c0a 100644 --- a/Sources/AgentsUpdates/UpdateReadLocations.swift +++ b/Sources/AgentsUpdates/UpdateReadLocations.swift @@ -27,9 +27,10 @@ extension UpdateOperations { paths.append(try PathSafety.resolvedChild(base: root, subpath: resource.path)) } } - if case .skills(let alias, _) = component, let root = try resourceRoot(alias) { + if case .skills(let alias, let selection) = component, let root = try resourceRoot(alias) + { // Discovery reads the root even when it finds no selected members. - paths.append(root) + paths.append(try PathSafety.resolvedChild(base: root, subpath: selection.path ?? ".")) } guard case .instructions(let instructions) = component else { continue } let sections = diff --git a/Sources/Components/ComponentFields.swift b/Sources/Components/ComponentFields.swift index 4acefbc..cd24ad5 100644 --- a/Sources/Components/ComponentFields.swift +++ b/Sources/Components/ComponentFields.swift @@ -39,7 +39,8 @@ extension ComponentDeclaration { package var resources: [ResourceDeclaration] { func run(_ value: ExecutableDeclaration) -> [ResourceDeclaration] { let executable = - value.executable.contains("/") ? [ResourceDeclaration(path: value.executable)] : [] + value.executable.contains("/") + ? [ResourceDeclaration(path: value.executable, source: value.executableSource)] : [] return executable + (value.workingDirectory.map { [$0] } ?? []) } func prompt(_ value: PromptBody) -> [ResourceDeclaration] { @@ -62,6 +63,7 @@ extension ComponentDeclaration { var comparisonPayload: ComponentDeclaration { func run(_ value: ExecutableDeclaration) -> ExecutableDeclaration { var result = value + result.executableSource = nil if let path = value.workingDirectory { result.workingDirectory = ResourceDeclaration(path: path.path) } diff --git a/Sources/Components/Expansion.swift b/Sources/Components/Expansion.swift index f0a9c46..5535960 100644 --- a/Sources/Components/Expansion.swift +++ b/Sources/Components/Expansion.swift @@ -337,11 +337,27 @@ final class Expansion { root: context.view.discoveryPath) } if let source = address.source, source.kind == .wellKnown { + guard selection.path == nil else { + throw LinkError.invalid("skill paths require a filesystem source", location) + } try indexSkills( selection, address: address, source: source, context: context, group: group, condition: condition, chain: chain, position: position, dependencies: dependencies) return } + if let path = selection.path { + let path = try PathSafety.sanitizeSubpath(path) + let root = try PathSafety.sanitizeSubpath(address.root + "/" + path) + let contained = try address.contained.map { + try SourceSnapshot( + snapshot: $0.snapshot, pin: $0.pin, root: $0.root, discoveryPath: root, + localEnvironment: $0.localEnvironment, liveRoot: $0.liveRoot, + packageIdentity: $0.packageIdentity) + } + var source = address.source + source?.path = root + address = SourceAddress(id: address.id, source: source, contained: contained, root: root) + } let requestedNames: [String]? switch selection.select { case .all: requestedNames = nil diff --git a/Sources/Components/Import/NativeContainerImport.swift b/Sources/Components/Import/NativeContainerImport.swift index 0fedd9a..6618d60 100644 --- a/Sources/Components/Import/NativeContainerImport.swift +++ b/Sources/Components/Import/NativeContainerImport.swift @@ -276,7 +276,7 @@ enum NativeContainerImport { if diagnostics.proposal.components.isEmpty { diagnostics.add( .unconverted, parsed.location(), - "No typed child was converted; native container preservation/registration remains an explicit B/F operation." + "No typed child was converted; native container registration is required to preserve this container." ) } _ = alias @@ -461,25 +461,17 @@ enum NativeContainerImport { $0.environmentVariable == nil }.map(\.location) if !content.bindings.isEmpty { continue } - let alias = "native-skill-" + String(diagnostics.proposal.sources.count) - diagnostics.proposal.sources.append( - .init( - alias: alias, origin: .init(document: file, pointer: ""), - declaration: .init( - kind: .local, location: skillPath, - environment: .init(projectDirectory: input.root, homeDirectory: input.root)), - pin: .init(), requestedRef: nil, producerPath: skillPath)) + let preservationPath = + root == "." ? skillPath : String(skillPath.dropFirst(root.count + 1)) NativeImportInput.emit( .skills( - source: alias, + source: "native-input", .init( - select: .names([content.skill.name]), + select: .names([content.skill.name]), path: preservationPath, agents: [NativeImportInput.agent(input.profile)], condition: content.skill.condition)), selector: .skill(name: content.skill.name), origin: .init(document: file, pointer: "/frontmatter"), container: root, profile: input.profile, into: &diagnostics, admission: admission) - let preservationPath = - root == "." ? skillPath : String(skillPath.dropFirst(root.count + 1)) let resourceIndex = diagnostics.proposal.resources.count try NativeImportInput.resource( preservationPath, root: root, input: input, diff --git a/Sources/Components/Import/NativeExecutableMembers.swift b/Sources/Components/Import/NativeExecutableMembers.swift index 12b4858..cb06e9e 100644 --- a/Sources/Components/Import/NativeExecutableMembers.swift +++ b/Sources/Components/Import/NativeExecutableMembers.swift @@ -47,7 +47,7 @@ extension NativeSourceImport { { diagnostics.add( .unconverted, groupLocation, - "F's native event/matcher contract cannot preserve this matcher.") + "This native event and matcher combination cannot be preserved.") continue } for (handlerIndex, handler) in handlers.enumerated() { @@ -108,7 +108,10 @@ extension NativeSourceImport { let name = base + (occurrence == 1 ? "" : "-\(occurrence)") NativeImportInput.emit( .hook( - name: name, event: .native(event), run: .init(executable: executable), + name: name, event: .native(event), + run: .init( + executable: executable, + executableSource: executable.contains("/") ? "native-input" : nil), matcher: matcher, timeoutSeconds: timeout, agents: [agent]), selector: .hook(name: name), origin: origin, container: container, profile: parsed.input.profile, into: &diagnostics, @@ -251,7 +254,9 @@ extension NativeSourceImport { NativeImportInput.emit( .lspServer( name: name, - run: .init(executable: program, arguments: arguments, environment: environment), + run: .init( + executable: program, executableSource: program.contains("/") ? "native-input" : nil, + arguments: arguments, environment: environment), languages: languages, initializationOptions: options, agents: [agent], native: native), selector: .lspServer(name: name), origin: origin, container: container, profile: parsed.input.profile, into: &diagnostics, diff --git a/Sources/Components/Import/NativeSourceImport.swift b/Sources/Components/Import/NativeSourceImport.swift index 5d061fb..3aac7fc 100644 --- a/Sources/Components/Import/NativeSourceImport.swift +++ b/Sources/Components/Import/NativeSourceImport.swift @@ -354,7 +354,9 @@ enum NativeSourceImport { } transport = .stdio( .init( - executable: executable, arguments: arguments, environment: environment, + executable: executable, + executableSource: executable.contains("/") ? "native-input" : nil, + arguments: arguments, environment: environment, workingDirectory: cwd)) } var resourceCoordinates: [String] = [] @@ -377,7 +379,7 @@ enum NativeSourceImport { } catch let issue as NativeAdapterIssue { diagnostics.add( issue.reason == .invalid ? .invalidInput : .unconverted, location, - "F's fixed native field profile cannot admit this member; its field/default semantics are not converted." + "The native field profile cannot preserve this member's field or default semantics." ) } catch is CancellationError { throw CancellationError() } catch CoreError.unsafePath { diagnostics.add(.unsafePath, location, "Native resource escapes its format-owned root.") diff --git a/Sources/Components/LedgerPayload.swift b/Sources/Components/LedgerPayload.swift index 6223339..69c9fa2 100644 --- a/Sources/Components/LedgerPayload.swift +++ b/Sources/Components/LedgerPayload.swift @@ -120,6 +120,7 @@ enum LedgerPayload { "executable": .init(run.executable), "arguments": strings(run.arguments), "environment": .init(object: run.environment.mapValues(binding)), ] + fields["executableSource"] = run.executableSource.map { .init($0) } fields["workingDirectory"] = run.workingDirectory.map(resource) return .init(object: fields) } diff --git a/Sources/Components/NativeProgramV1.swift b/Sources/Components/NativeProgramV1.swift index 064c190..eda3033 100644 --- a/Sources/Components/NativeProgramV1.swift +++ b/Sources/Components/NativeProgramV1.swift @@ -12,7 +12,7 @@ package enum NativeProgramV1 { /// Frozen program shape is still the typed declaration's run, not native settings data. static func validateFrozenRun(_ input: ComponentRenderInput) throws { guard let run = input.fields["run"]?.object, - Set(run.keys).subtracting(["workingDirectory"]) == [ + Set(run.keys).subtracting(["workingDirectory", "executableSource"]) == [ "executable", "arguments", "environment", ], run["executable"]?.kind == .string, run["executable"]?.text?.isEmpty == false, @@ -24,6 +24,14 @@ package enum NativeProgramV1 { && ($0.value.kind == .literal || $0.value.text?.isEmpty == false) }) else { throw input.issue(["run"], .invalid, "invalid frozen typed native program") } + if let source = run["executableSource"] { + guard source.kind == .string, source.text?.isEmpty == false, + run["executable"]!.text!.contains("/") + else { + throw input.issue( + ["run", "executableSource"], .invalid, "invalid executable source coordinate") + } + } if let cwd = run["workingDirectory"] { guard let fields = cwd.object, Set(fields.keys).isSubset(of: ["path", "source"]), fields["path"]?.kind == .string, fields["path"]?.text?.isEmpty == false, diff --git a/Sources/Components/PluginExpansion.swift b/Sources/Components/PluginExpansion.swift index 060726a..13c2d86 100644 --- a/Sources/Components/PluginExpansion.swift +++ b/Sources/Components/PluginExpansion.swift @@ -217,7 +217,9 @@ extension Expansion { func run(_ value: ExecutableDeclaration) throws -> ExecutableDeclaration { var value = value if value.executable.contains("/") { - value.executable = try path(.init(path: value.executable)).path + let relative = try path(.init(path: value.executable, source: value.executableSource)).path + value.executable = relative.contains("/") ? relative : "./" + relative + value.executableSource = nil } value.workingDirectory = try value.workingDirectory.map(path) return value diff --git a/Tests/AgentsManifestTests/NativeCoordinateTests.swift b/Tests/AgentsManifestTests/NativeCoordinateTests.swift new file mode 100644 index 0000000..52bccd7 --- /dev/null +++ b/Tests/AgentsManifestTests/NativeCoordinateTests.swift @@ -0,0 +1,71 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsManifest + +struct NativeCoordinateTests { + @Test func completeCoordinatesRoundTripAndRenameLosslessly() throws { + let body = """ + # retained header + version: 1 + sources: {s: {path: missing, subpath: bundle}} + components: + - {kind: skills, source: s, path: skills/helper, select: [helper]} + - {kind: mcpServer, name: server, transport: {kind: stdio, executable: ./server, executableSource: s, workingDirectory: {path: cwd, source: s}}} + - {kind: hook, name: check, event: sessionStart, run: {executable: ./server, executableSource: s}} + groups: + unused: + components: + - {kind: lspServer, name: language, run: {executable: bin/server, executableSource: s}, languages: {".swift": swift}} + # retained tail + """ + let previous = try projected(body) + let ir = YAMLConstruction.root(previous) + #expect(try projected(String(decoding: YAMLWriter.manifest(ir), as: UTF8.self)) == previous) + #expect(try planned(previous, previous, in: body) == nil) + let target = body.replacingOccurrences(of: "{s:", with: "{t:") + .replacingOccurrences(of: "source: s", with: "source: t") + .replacingOccurrences(of: "executableSource: s", with: "executableSource: t") + .replacingOccurrences(of: "skills/helper", with: "skills/other") + let next = try projected(target) + let output = String( + decoding: try #require(try planned(previous, next, in: body)), as: UTF8.self) + #expect(try projected(output) == next) + #expect(output.hasPrefix("# retained header\n") && output.hasSuffix("# retained tail")) + #expect(SkillDeclaration(select: .all).path == nil) + #expect(ExecutableDeclaration(executable: "tool").executableSource == nil) + } + + @Test func invalidCoordinatesAreRejectedByTypedAndManifestAdmission() throws { + let index = SourceDeclaration(kind: .wellKnown, location: "https://example.invalid/index.json") + let invalid = Declaration( + sources: ["s": index], + components: [ + .skills(source: "s", .init(select: .all, path: "skills")) + ]) + #expect(throws: (any Error).self) { try invalid.validate(environment: projectionEnvironment) } + for component in [ + "{kind: skills, source: s, path: ../outside}", + "{kind: mcpServer, name: server, transport: {kind: stdio, executable: tool, executableSource: s}}", + "{kind: hook, name: check, event: sessionStart, run: {executable: ./server, executableSource: missing}}", + ] { + #expect(throws: (any Error).self) { + try projected( + "version: 1\nsources: {s: {path: missing}}\ncomponents: [" + component + "]\n") + } + } + #expect(throws: (any Error).self) { + try projected( + "version: 1\nsources: {s: {index: https://example.invalid/index.json}}\ncomponents: [{kind: skills, source: s, path: skills}]\n" + ) + } + let ambient = Declaration( + sources: ["s": .init(kind: .local, location: "missing")], + components: [ + .mcpServer( + name: "server", transport: .stdio(.init(executable: "tool", executableSource: "s"))) + ]) + #expect(throws: (any Error).self) { try ambient.validate(environment: projectionEnvironment) } + } +} diff --git a/Tests/AgentsUpdatesTests/ImportNativeExecutableLifecycleTests.swift b/Tests/AgentsUpdatesTests/ImportNativeExecutableLifecycleTests.swift new file mode 100644 index 0000000..81bc7d3 --- /dev/null +++ b/Tests/AgentsUpdatesTests/ImportNativeExecutableLifecycleTests.swift @@ -0,0 +1,115 @@ +import AgentsCore +import AgentsUpdates +import Components +import Foundation +import Testing + +struct ImportNativeExecutableLifecycleTests { + @Test(arguments: [false, true], [(false, false), (false, true), (true, false), (true, true)]) + func nativeContainerExecutableUsesItsDeclaredInputRoot( + _ linked: Bool, _ configuration: (Bool, Bool) + ) throws { + let (rootBasename, gemini) = configuration + let f = try UpdateFixture() + let input = f.root.appendingPathComponent("producer") + let executable = rootBasename ? "server" : "bin/server" + let document = gemini ? "gemini-extension.json" : ".claude-plugin/plugin.json" + let prefix = gemini ? "${extensionPath}/" : "${CLAUDE_PLUGIN_ROOT}/" + let cwd = gemini ? ",\"cwd\":\"./cwd\"" : "" + try f.write( + "{\"name\":\"producer\",\"version\":\"1.2.3\",\"mcpServers\":{\"review\":{\"command\":\"" + + prefix + executable + "\"" + cwd + "}}}", + to: input.appendingPathComponent("bundle/" + document)) + if gemini { + try f.write( + "Working directory support", to: input.appendingPathComponent("bundle/cwd/config.txt")) + } + let program = linked ? "shared/server" : executable + try f.write("Frozen executable bytes\n", to: input.appendingPathComponent("bundle/" + program)) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: input.appendingPathComponent("bundle/" + program).path) + if linked { + try FileManager.default.createDirectory( + at: input.appendingPathComponent("bundle/bin"), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: input.appendingPathComponent("bundle/" + executable).path, + withDestinationPath: rootBasename ? "shared/server" : "../shared/server") + } + let report = try SourceImportOperations.inspect( + format: gemini ? "geminiExtensionV1" : "claudePluginV1", root: input, + document: "bundle/" + document) + #expect(report.diagnostics.isEmpty) + #expect(report.sources.first?.declaration?.location == "bundle") + #expect( + report.resources.contains { $0.path == executable && $0.sourceAlias == "native-input" }) + guard case .mcpServer(_, .stdio(let run), _, _, _) = report.components.first?.declaration else { + Issue.record("Expected native MCP executable") + return + } + #expect(run.executable == (rootBasename ? "./server" : "bin/server")) + #expect(run.executableSource == "native-input") + let request = try report.updateRequest(in: UpdateOperations.inspect(environment: f.environment)) + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + #expect($0.report.displayedFingerprint == preview.displayedFingerprint) + return try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + func verify() throws { + let installed = try UpdateOperations.inspect(environment: f.environment) + #expect(installed.deployments.allSatisfy { $0.status == .current }) + let component = try #require(installed.components.first { $0.kind == .mcpServer }) + let ledger = try f.store.readLedger() + let record = try #require(ledger.components.values.first { $0.kind == "mcpServer" }) + try LedgerReplay.withLockedResources( + ledger, store: f.store, roots: f.store.ledgerRoots, limits: .standard + ) { _, resources, _ in + let programID = try #require(record.resources.first) + let program = try #require(resources[programID]) + #expect(try String(contentsOf: program, encoding: .utf8) == "Frozen executable bytes\n") + let mode = + try FileManager.default.attributesOfItem(atPath: program.resolvingSymlinksInPath().path)[ + .posixPermissions] as? NSNumber + #expect((mode?.intValue ?? 0) & 0o777 == 0o755) + if linked { + #expect( + try FileManager.default.destinationOfSymbolicLink(atPath: program.path) + == (rootBasename ? "shared/server" : "../shared/server")) + } + if gemini { + #expect(record.resources.count == 2) + let directory = try #require(resources[record.resources[1]]) + #expect( + try String(contentsOf: directory.appendingPathComponent("config.txt"), encoding: .utf8) + == "Working directory support") + } + } + let snapshot = try MCPConnectionOperations.snapshot( + selection: component.selection, scope: .project, environment: f.environment) + let description = MCPConnectionOperations.describe(snapshot) + #expect(description.executableIsCaptured) + #expect(description.executable == executable) + #expect(description.workingDirectoryIsCaptured == gemini) + if gemini { #expect(description.workingDirectory == "cwd") } + } + try verify() + let installed = try UpdateOperations.inspect(environment: f.environment) + try FileManager.default.removeItem(at: input) + for target in Set(installed.deployments.map(\.location)) { + try FileManager.default.removeItem(at: target) + } + try FileManager.default.removeItem(at: f.store.cacheDirectory) + _ = try UpdateOperations.restore(environment: f.environment) + try verify() + } + @Test func sourceQualifiedAmbientCommandCannotProduceSnapshot() throws { + let f = try UpdateFixture() + #expect(throws: MCPConnectionPreparationError.self) { + try MCPConnectionOperations.snapshot( + selectionID: "qualified", + transport: .stdio(.init(executable: "tool", executableSource: "producer")), + workingDirectory: .live(f.root)) + } + } + +} diff --git a/Tests/AgentsUpdatesTests/ImportNativeLifecycleTests.swift b/Tests/AgentsUpdatesTests/ImportNativeLifecycleTests.swift new file mode 100644 index 0000000..4a927e0 --- /dev/null +++ b/Tests/AgentsUpdatesTests/ImportNativeLifecycleTests.swift @@ -0,0 +1,125 @@ +import AgentsCore +import AgentsUpdates +import Foundation +import Testing + +struct ImportNativeLifecycleTests { + @Test(arguments: [AgentID.claudeCode, .cursor, .geminiCLI], [false, true]) + func standaloneNativeSkillRetainsContainerSupportThroughColdRestore( + _ agent: AgentID, _ atInputRoot: Bool + ) throws { + let f = try UpdateFixture() + let input = f.root.appendingPathComponent("producer") + let prefix = atInputRoot ? "" : "bundle/" + let container = atInputRoot ? input : input.appendingPathComponent("bundle") + let format: String + let suffix: String + switch agent { + case .claudeCode: + format = "claudePluginV1" + suffix = ".claude-plugin/plugin.json" + case .cursor: + format = "cursorPluginV1" + suffix = ".cursor-plugin/plugin.json" + default: + format = "geminiExtensionV1" + suffix = "gemini-extension.json" + } + try f.write( + #"{"name":"producer","version":"1.2.3"}"#, to: container.appendingPathComponent(suffix)) + let body = "---\nname: helper\ndescription: Helper\n---\nFrozen helper\n" + try f.write(body, to: container.appendingPathComponent("skills/helper/SKILL.md")) + try f.write("Frozen support\n", to: container.appendingPathComponent("shared/tool.txt")) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: container.appendingPathComponent("shared/tool.txt").path) + try FileManager.default.createSymbolicLink( + atPath: container.appendingPathComponent("skills/helper/reference.txt").path, + withDestinationPath: "../../shared/tool.txt") + try f.write( + "---\nname: helper\ndescription: Hidden\n---\nHidden support skill\n", + to: container.appendingPathComponent("shared/extras/SKILL.md")) + try FileManager.default.createSymbolicLink( + atPath: container.appendingPathComponent("skills/helper/data").path, + withDestinationPath: "../../shared/extras") + try f.write( + "---\nname: helper\ndescription: Sibling\n---\nUnselected sibling\n", + to: container.appendingPathComponent("other/SKILL.md")) + try f.write( + "---\nname: second\ndescription: Second\n---\nSelected second\n", + to: container.appendingPathComponent("skills/second/SKILL.md")) + let report = try SourceImportOperations.inspect( + format: format, root: input, document: prefix + suffix) + #expect(report.diagnostics.isEmpty) + #expect(report.components.count == 2) + #expect(report.sources.count == 1) + let skillSource = try #require(report.sources.first { $0.alias == "native-input" }) + #expect(skillSource.declaration?.location == (atInputRoot ? "." : "bundle")) + #expect(skillSource.declaration?.path == nil) + let helper = try #require( + report.components.first { + if case .skills(_, let selection) = $0.declaration { + return selection.path == "skills/helper" + } + return false + }) + guard case .skills(let alias, let selection) = helper.declaration else { + Issue.record("Expected selected native skill") + return + } + #expect(alias == "native-input" && selection.path == "skills/helper") + let scope = try UpdateOperations.inspect(environment: f.environment) + let originalRequest = try report.updateRequest(in: scope) + try f.write("Refreshed support\n", to: container.appendingPathComponent("shared/tool.txt")) + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(originalRequest, environment: f.environment) { _ in + Issue.record("Changed linked support must reject the original request") + } + } + let refreshed = try SourceImportOperations.inspect( + format: format, root: input, document: prefix + suffix) + let request = try refreshed.updateRequest(in: scope) + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + #expect($0.report.displayedFingerprint == preview.displayedFingerprint) + return try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let installed = try UpdateOperations.inspect(environment: f.environment) + #expect(Set(installed.components.compactMap(\.name)) == ["helper", "second"]) + #expect(installed.deployments.allSatisfy { $0.status == .current }) + let tree = try #require( + installed.deployments.first { $0.location.lastPathComponent == "helper" }?.location) + func verify() throws { + #expect( + try String(contentsOf: tree.appendingPathComponent("SKILL.md"), encoding: .utf8) == body) + #expect( + try String(contentsOf: tree.appendingPathComponent("reference.txt"), encoding: .utf8) + == "Refreshed support\n") + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: tree.appendingPathComponent("reference.txt").path) == "../../shared/tool.txt") + let support = tree.appendingPathComponent("reference.txt").resolvingSymlinksInPath() + let mode = + try FileManager.default.attributesOfItem(atPath: support.path)[.posixPermissions] + as? NSNumber + #expect((mode?.intValue ?? 0) & 0o777 == 0o755) + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: tree.appendingPathComponent("data").path) == "../../shared/extras") + #expect( + try String(contentsOf: tree.appendingPathComponent("data/SKILL.md"), encoding: .utf8) + .contains("Hidden support skill")) + } + try verify() + try FileManager.default.removeItem(at: input) + for target in Set(installed.deployments.map(\.location)) { + try FileManager.default.removeItem(at: target) + } + try FileManager.default.removeItem(at: f.store.cacheDirectory) + _ = try UpdateOperations.restore(environment: f.environment) + try verify() + let restored = try UpdateOperations.inspect(environment: f.environment) + #expect(Set(restored.components.compactMap(\.name)) == ["helper", "second"]) + #expect(restored.deployments.allSatisfy { $0.status == .current }) + } +} diff --git a/Tests/AgentsUpdatesTests/SkillPathReadLocationsTests.swift b/Tests/AgentsUpdatesTests/SkillPathReadLocationsTests.swift new file mode 100644 index 0000000..aba8a2a --- /dev/null +++ b/Tests/AgentsUpdatesTests/SkillPathReadLocationsTests.swift @@ -0,0 +1,25 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsUpdates + +struct SkillPathReadLocationsTests { + @Test func ownSkillPathsKeepNarrowRootAndUnusedGroupDiscovery() throws { + let f = try UpdateFixture() + let declaration = Declaration( + components: [.skills(source: ".", .init(select: .all, path: "selected/one"))], + groups: [ + .init( + name: "unused", + components: [ + .skills(source: ".", .init(select: .names([]), path: "selected/two")) + ]) + ]) + let paths = try UpdateOperations.readLocations( + declarations: [declaration], ledgers: [], store: f.store) + #expect(paths.contains(f.root.appendingPathComponent("selected/one"))) + #expect(paths.contains(f.root.appendingPathComponent("selected/two"))) + #expect(!paths.contains(f.root)) + } +} diff --git a/Tests/ComponentsTests/ImportSupportingLinksTests.swift b/Tests/ComponentsTests/ImportSupportingLinksTests.swift index 294519d..fcb64f1 100644 --- a/Tests/ComponentsTests/ImportSupportingLinksTests.swift +++ b/Tests/ComponentsTests/ImportSupportingLinksTests.swift @@ -31,6 +31,16 @@ struct ImportSupportingLinksTests { #expect(member.member?.selector == .skill(name: "helper")) #expect(member.member?.containerRoot == "bundle") #expect(member.origin.document == "bundle/skills/helper/SKILL.md") + guard case .skills(let alias, let selection) = member.declaration else { + Issue.record("Expected selected skill declaration") + return + } + let source = try #require(proposal.sources.first { $0.alias == alias }) + #expect(source.declaration?.location == "bundle") + #expect(source.declaration?.path == nil) + #expect(selection.path == "skills/helper") + #expect(source.producerPath == "bundle") + #expect(selection.select == .names(["helper"])) let preservation = try #require(proposal.resources.first { $0.kind == .skills }) #expect(preservation.path == "skills/helper") #expect(preservation.requiresStandaloneSource && !preservation.requiresBindingRewrite) diff --git a/Tests/ComponentsTests/NativeCoordinateLinkingTests.swift b/Tests/ComponentsTests/NativeCoordinateLinkingTests.swift new file mode 100644 index 0000000..58bcfc4 --- /dev/null +++ b/Tests/ComponentsTests/NativeCoordinateLinkingTests.swift @@ -0,0 +1,71 @@ +import AgentsCore +import Components +import Foundation +import Testing + +struct NativeCoordinateLinkingTests { + @Test(arguments: [false, true]) + func generatedExecutableAndCwdRebaseOnceAndConsumeAliases(_ nested: Bool) throws { + let f = try LinkFixture() + let producer = f.root.appendingPathComponent("producer") + let container = nested ? "bundle" : "." + let prefix = nested ? "bundle/" : "" + try f.write( + #"{"name":"producer","version":"1.2.3","mcpServers":{"server":{"command":"${extensionPath}/server","cwd":"./cwd"}}}"#, + to: prefix + "gemini-extension.json", base: producer) + try f.write("Never executed", to: prefix + "server", base: producer) + try f.write("Working support", to: prefix + "cwd/config", base: producer) + let graph = try f.link( + """ + version: 1 + sources: {producer: {path: "\(producer.path)"}} + components: [{kind: plugin, name: p, path: "\(container)", source: producer, agents: [gemini-cli]}] + """) + let member = try #require(graph.components.first { $0.key.kind == .mcpServer }) + guard case .declaration(.mcpServer(_, .stdio(let run), _, _, _)) = member.payload else { + Issue.record("Expected generated MCP child") + return + } + #expect(run.executable == (nested ? "bundle/server" : "./server")) + #expect(run.executableSource == nil) + #expect(run.workingDirectory == .init(path: prefix + "cwd")) + #expect(member.resources.count == 2) + } + @Test(arguments: [false, true]) + func generatedHookAndLSPRetainResourceSpelling(_ nested: Bool) throws { + let f = try LinkFixture() + let producer = f.root.appendingPathComponent("producer") + let prefix = nested ? "bundle/" : "" + try f.write(#"{"name":"producer"}"#, to: prefix + ".claude-plugin/plugin.json", base: producer) + try f.write("Never executed", to: prefix + "server", base: producer) + try f.write( + #"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"./server"}]}]}}"#, + to: prefix + "hooks/hooks.json", base: producer) + try f.write( + #"{"language":{"command":"./server","extensionToLanguage":{".swift":"swift"}}}"#, + to: prefix + ".lsp.json", base: producer) + let graph = try f.link( + """ + version: 1 + sources: {producer: {path: "\(producer.path)"}} + components: [{kind: plugin, name: p, path: "\(nested ? "bundle" : ".")", source: producer, agents: [claude-code]}] + """) + let members = graph.components.filter { [.hook, .lspServer].contains($0.key.kind) } + #expect(members.count == 2) + for member in members { + let run: ExecutableDeclaration + switch member.payload { + case .declaration(.hook(_, _, let value, _, _, _, _, _)), + .declaration(.lspServer(_, let value, _, _, _, _, _)): + run = value + default: + Issue.record("Expected executable native child") + continue + } + #expect(run.executable == (nested ? "bundle/server" : "./server")) + #expect(run.executableSource == nil) + #expect(member.resources.count == 1) + } + } + +} From 3e9037cac216febb668cbf59ccb3239c811124fc Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:55:09 +0800 Subject: [PATCH 144/171] fix: copy local snapshots without source clone events --- .../AgentsCore/SourceResolutionSession.swift | 6 +- .../SourceRegressionTests.swift | 93 +++++++++++++++++++ 2 files changed, 98 insertions(+), 1 deletion(-) diff --git a/Sources/AgentsCore/SourceResolutionSession.swift b/Sources/AgentsCore/SourceResolutionSession.swift index ce619b9..f7482f6 100644 --- a/Sources/AgentsCore/SourceResolutionSession.swift +++ b/Sources/AgentsCore/SourceResolutionSession.swift @@ -224,7 +224,11 @@ package final class SourceResolutionSession { } let live = source.localURL(environment: store.environment) let root = workspace.appendingPathComponent(UUID().uuidString) - try FileManager.default.copyItem(at: live, to: root) + let origin = try DirectoryHandle(at: live.resolvingSymlinksInPath()) + let destination = try DirectoryHandle(at: workspace) + try destination.copy(root.lastPathComponent, from: origin, named: ".") { _ in + try Task.checkCancellation() + } try Self.validateLinks(root) let flags = try FileHash.executableFlags(root) let content = try FileHash.folderHash(root) diff --git a/Tests/AgentsCoreTests/SourceRegressionTests.swift b/Tests/AgentsCoreTests/SourceRegressionTests.swift index 4f35ff3..b443edd 100644 --- a/Tests/AgentsCoreTests/SourceRegressionTests.swift +++ b/Tests/AgentsCoreTests/SourceRegressionTests.swift @@ -1,3 +1,4 @@ +import CPlatform import Foundation import Testing @@ -5,6 +6,98 @@ import Testing @Suite("Source regressions") struct SourceRegressionTests { + @Test func localSnapshotsPreserveAliasedTreesMetadataAndMemoizedIdentity() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let live = root.appendingPathComponent("source") + let nested = live.appendingPathComponent("nested") + try FileManager.default.createDirectory(at: nested, withIntermediateDirectories: true) + let file = nested.appendingPathComponent("executable") + let bytes = Data(repeating: 0xa5, count: 200_000) + try bytes.write(to: file) + let link = live.appendingPathComponent("link") + try FileManager.default.createSymbolicLink( + atPath: link.path, withDestinationPath: "nested/executable") + try FileManager.default.createSymbolicLink( + atPath: live.appendingPathComponent("dangling").path, withDestinationPath: "nested/missing") + for (url, mode): (URL, mode_t) in [ + (live, 0o750), (nested, 0o751), (file, 0o751), (link, 0o755), + ] { + try setFixtureMetadata(url, mode: mode, value: Data(url.lastPathComponent.utf8)) + } + let alias = root.appendingPathComponent("alias") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: live) + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment(projectDirectory: root, homeDirectory: root, environment: [:]) + ) + let source = SourceDeclaration(kind: .local, location: alias.path) + let session = try SourceResolutionSession(store: store) + defer { try? session.close() } + let snapshot = try session.localSnapshot(source) + #expect(snapshot.liveRoot == alias) + #expect(try Data(contentsOf: snapshot.resource("link")) == bytes) + #expect(try FileHash.folderHash(snapshot.root) == FileHash.folderHash(live)) + #expect(try FileHash.executableFlags(snapshot.root) == FileHash.executableFlags(live)) + for path in [".", "nested", "nested/executable", "link"] { + #expect( + try fixtureMetadata(snapshot.root.appendingPathComponent(path)) + == fixtureMetadata(live.appendingPathComponent(path))) + } + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: snapshot.root.appendingPathComponent("link").path) == "nested/executable") + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: snapshot.root.appendingPathComponent("dangling").path) == "nested/missing") + let repeated = try SourceResolutionSession.withTemporaryRead(store: store) { + try $0.localSnapshot(source).snapshot + } + #expect(repeated == snapshot.snapshot) + try Data("changed".utf8).write(to: file) + let memoized = try session.localSnapshot(source) + #expect(memoized.snapshot == snapshot.snapshot && memoized.root == snapshot.root) + #expect(try Data(contentsOf: memoized.resource("link")) == bytes) + let changed = try SourceResolutionSession.withTemporaryRead(store: store) { + try $0.localSnapshot(source).snapshot + } + #expect(changed != snapshot.snapshot) + let workspace = snapshot.root.deletingLastPathComponent() + try session.close() + #expect(!FileManager.default.fileExists(atPath: workspace.path)) + } + + @Test(arguments: ["unsupported", "escaping-link"]) + func localSnapshotRefusesUnsafeEntriesAndCleansPartialCopies(_ kind: String) throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment(projectDirectory: root, homeDirectory: root, environment: [:]) + ) + let live = root.appendingPathComponent("source") + try FileManager.default.createDirectory(at: live, withIntermediateDirectories: true) + let session = try SourceResolutionSession(store: store) + defer { try? session.close() } + let first = try session.localSnapshot(SourceDeclaration(kind: .local, location: live.path)) + let invalid = root.appendingPathComponent("invalid") + try FileManager.default.createDirectory(at: invalid, withIntermediateDirectories: true) + try Data("copied first".utf8).write(to: invalid.appendingPathComponent("a")) + if kind == "unsupported" { + try #require(mkfifo(invalid.appendingPathComponent("z").path, 0o600) == 0) + } else { + try FileManager.default.createSymbolicLink( + atPath: invalid.appendingPathComponent("z").path, withDestinationPath: "../source") + } + #expect(throws: CoreError.self) { + try session.localSnapshot(SourceDeclaration(kind: .local, location: invalid.path)) + } + let workspace = first.root.deletingLastPathComponent() + try session.close() + #expect(!FileManager.default.fileExists(atPath: workspace.path)) + #expect(FileManager.default.fileExists(atPath: live.path)) + } + @Test func parsesLocalPathsAndGitLabSubgroupsAndTrees() throws { let cwd = URL(fileURLWithPath: "/workspace/project") for (input, expected) in [ From c4076e4877ede6208a1026ce2769605d825ef87e Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:03:34 +0800 Subject: [PATCH 145/171] fix: preserve equivalent ledger requirements --- Sources/AgentsCore/ResolvedLedgerCodec.swift | 27 +++- .../LedgerAuthorityTests.swift | 16 +++ .../RequirementSemanticsTests.swift | 117 ++++++++++++++++++ 3 files changed, 159 insertions(+), 1 deletion(-) diff --git a/Sources/AgentsCore/ResolvedLedgerCodec.swift b/Sources/AgentsCore/ResolvedLedgerCodec.swift index bc9ff6b..93ccba5 100644 --- a/Sources/AgentsCore/ResolvedLedgerCodec.swift +++ b/Sources/AgentsCore/ResolvedLedgerCodec.swift @@ -31,10 +31,35 @@ package enum ResolvedLedgerCodec { ) throws -> Data? { try checkModel(ledger, limits: limits) try ledger.validate() - if let existing, try bytes(decode(existing, limits: limits)) == bytes(ledger) { return nil } + if let existing { + let original = try decode(existing, limits: limits) + try LedgerAdmission.check(bytes(ledger), limits: limits) + var comparison = ledger + for index in 0.. SourceRequirement? { + guard let requirement, let original, requirement.isVersionRequirement, + requirement.declarationEquivalent(to: original) + else { return requirement } + return original + } + package static func checkModel(_ ledger: ResolvedLedger, limits: LedgerLimits) throws { var bytes = 0 for object in ledger.contentObjects.values { diff --git a/Tests/AgentsCoreTests/LedgerAuthorityTests.swift b/Tests/AgentsCoreTests/LedgerAuthorityTests.swift index cab4064..878fabe 100644 --- a/Tests/AgentsCoreTests/LedgerAuthorityTests.swift +++ b/Tests/AgentsCoreTests/LedgerAuthorityTests.swift @@ -69,6 +69,22 @@ struct LedgerAuthorityTests { #expect(try ResolvedLedgerCodec.replacement(old, existing: nullable, limits: .standard) == nil) } + @Test func equivalentRequirementsDoNotMaskPrivateContinuityChanges() throws { + var ledger = fixture() + ledger.sourceUses = [ + .init(source: "root", root: ".", requirement: .range(from: "v1.2.0", to: "2.0.0+meta")) + ] + ledger.nativeAuthorities![0].regions[0].path[1] = .position( + index: 1, evidence: .privateArray(token: UUID())) + let bytes = try encoded(ledger) + var next = ledger + next.sourceUses[0].requirement = .upToNextMajor(from: "1.2.0") + #expect(try ResolvedLedgerCodec.replacement(next, existing: bytes, limits: .standard) == nil) + next.nativeAuthorities![0].regions[0].path[1] = .position( + index: 1, evidence: .privateArray(token: UUID())) + #expect(try ResolvedLedgerCodec.replacement(next, existing: bytes, limits: .standard) != nil) + } + @Test func strictTaggedWireRejectsUnknownAndWrongFields() throws { let bytes = try encoded(fixture()) let root = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) diff --git a/Tests/AgentsCoreTests/RequirementSemanticsTests.swift b/Tests/AgentsCoreTests/RequirementSemanticsTests.swift index 1684ca5..ab41317 100644 --- a/Tests/AgentsCoreTests/RequirementSemanticsTests.swift +++ b/Tests/AgentsCoreTests/RequirementSemanticsTests.swift @@ -140,3 +140,120 @@ struct RequirementSemanticsTests { try String(contentsOf: after.appendingPathComponent("content"), encoding: .utf8) == "old") } } + +extension RequirementSemanticsTests { + @Test(arguments: [ + ( + SourceRequirement.range(from: "v1.2.0+lower", to: "2.0.0+upper"), + SourceRequirement.upToNextMajor(from: "1.2.0") + ), + (.range(from: "1.2.0-beta+lower", to: "1.3.0+upper"), .upToNextMinor(from: "v1.2.0-beta")), + (.exact(" V1.2.3+build "), .exact("1.2.3+build")), + ]) + func sourceAndGroupRequirementsPreserveOriginalLayout( + _ original: SourceRequirement, _ equivalent: SourceRequirement + ) throws { + var ledger = ResolvedLedger() + ledger.sources["source"] = .init( + kind: .git, transport: "https://intranet/team.git", + revision: String(repeating: "a", count: 40)) + ledger.sourceUses = [.init(source: "source", root: ".", requirement: original)] + ledger.groups = [ + .init( + id: 0, source: "source", root: ".", name: "export", requirement: original, + manifestHash: "sha256:" + String(repeating: "a", count: 64), children: []) + ] + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + let originalBytes = try JSONSerialization.data( + withJSONObject: JSONSerialization.jsonObject(with: encoded), + options: [.prettyPrinted, .sortedKeys]) + var next = ledger + next.sourceUses[0].requirement = equivalent + next.groups[0].requirement = equivalent + #expect( + try ResolvedLedgerCodec.replacement(next, existing: originalBytes, limits: .standard) == nil) + #expect( + try ResolvedLedgerCodec.decode(originalBytes, limits: .standard).groups[0].requirement + == original) + next.groups[0].requirement = .branch("different") + #expect( + try ResolvedLedgerCodec.replacement(next, existing: originalBytes, limits: .standard) != nil) + } + + @Test func equivalentRequirementsDoNotMaskByteExactNativeOrRefChanges() throws { + var ledger = ResolvedLedger() + ledger.sources["source"] = .init( + kind: .git, transport: "https://intranet/team.git", + revision: String(repeating: "a", count: 40)) + ledger.sourceUses = [ + .init(source: "source", root: ".", requirement: .range(from: "v1.2.0", to: "2.0.0+meta")) + ] + ledger.lowerings = [ + .init( + id: "native", format: "test/value@1", inputs: [], resources: [], deployments: [], + layout: .init("é"), platform: "macos", artifacts: []) + ] + let original = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + var next = ledger + next.sourceUses[0].requirement = .upToNextMajor(from: "1.2.0") + next.lowerings[0].layout = .init("e\u{301}") + #expect(try ResolvedLedgerCodec.replacement(next, existing: original, limits: .standard) != nil) + for (before, after) in [ + (LedgerValue("1.0", kind: .decimal), LedgerValue("1.00", kind: .decimal)), + (LedgerValue(), LedgerValue(object: [:])), + ( + LedgerValue(object: [ + "requirement": .init(object: ["from": .init("v1.2.0"), "to": .init("2.0.0+meta")]) + ]), + LedgerValue(object: ["requirement": .init(object: ["from": .init("1.2.0")])]) + ), + ] { + ledger.lowerings[0].layout = before + let valueBytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + next = ledger + next.sourceUses[0].requirement = .upToNextMajor(from: "1.2.0") + next.lowerings[0].layout = after + #expect( + try ResolvedLedgerCodec.replacement(next, existing: valueBytes, limits: .standard) != nil) + } + ledger.sourceUses[0].requirement = .exact("1.2.3+one") + let exactBytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + next = ledger + next.sourceUses[0].requirement = .exact("1.2.3+two") + #expect( + try ResolvedLedgerCodec.replacement(next, existing: exactBytes, limits: .standard) != nil) + for requirement in [SourceRequirement.branch("é"), .revision("é")] { + ledger.sourceUses[0].requirement = requirement + let refBytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + next = ledger + if case .branch = requirement { + next.sourceUses[0].requirement = .branch("e\u{301}") + } else { + next.sourceUses[0].requirement = .revision("e\u{301}") + } + #expect( + try ResolvedLedgerCodec.replacement(next, existing: refBytes, limits: .standard) != nil) + } + } +} + +extension RequirementSemanticsTests { + @Test func equivalentRequirementsStillRespectCandidateWireBudget() throws { + var ledger = ResolvedLedger() + ledger.sources["source"] = .init( + kind: .git, transport: "https://intranet/team.git", + revision: String(repeating: "a", count: 40)) + ledger.sourceUses = [ + .init(source: "source", root: ".", requirement: .upToNextMajor(from: "1.2.0")) + ] + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + var next = ledger + next.sourceUses[0].requirement = .range( + from: "1.2.0", to: "2.0.0+" + String(repeating: "metadata", count: 20)) + var limits = LedgerLimits.standard + limits.encodedBytes = bytes.count + #expect(throws: (any Error).self) { + try ResolvedLedgerCodec.replacement(next, existing: bytes, limits: limits) + } + } +} From d94eb1c77af0d612c38b7acfabf286a25fed92bf Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:20:57 +0800 Subject: [PATCH 146/171] fix: qualify client observation file types --- Sources/AgentsCore/AgentClientObservation.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Sources/AgentsCore/AgentClientObservation.swift b/Sources/AgentsCore/AgentClientObservation.swift index 60b7d06..fc1ed44 100644 --- a/Sources/AgentsCore/AgentClientObservation.swift +++ b/Sources/AgentsCore/AgentClientObservation.swift @@ -65,8 +65,8 @@ package enum AgentClientObservation { guard url.isFileURL, !url.path.contains("\0") else { return .invalid } var info = stat() guard stat(url.path, &info) == 0 else { return failureState(errno) } - let kind = info.st_mode & mode_t(S_IFMT) - return kind == mode_t(directory ? S_IFDIR : S_IFREG) ? .present : .invalid + let kind = info.st_mode & mode_t(CPlatform.S_IFMT) + return kind == mode_t(directory ? CPlatform.S_IFDIR : CPlatform.S_IFREG) ? .present : .invalid } package static func command( @@ -84,7 +84,7 @@ package enum AgentClientObservation { } continue } - guard info.st_mode & mode_t(S_IFMT) == mode_t(S_IFREG) else { continue } + guard info.st_mode & mode_t(CPlatform.S_IFMT) == mode_t(CPlatform.S_IFREG) else { continue } guard access(url.path, X_OK) == 0 else { issues.append( .init(path: url.path, state: failureState(errno), reason: "executable access denied")) @@ -125,7 +125,7 @@ package enum AgentClientObservation { defer { close(fd) } var info = stat() guard fstat(fd, &info) == 0 else { throw ClientVersionUnknownError(.unreadableMetadata) } - guard info.st_mode & mode_t(S_IFMT) == mode_t(S_IFREG) else { + guard info.st_mode & mode_t(CPlatform.S_IFMT) == mode_t(CPlatform.S_IFREG) else { throw ClientVersionUnknownError(.nonRegularMetadata) } let limit = 1_048_576 From ac26b9c886955bf7ce193726bdcbcb96f9ebc2c5 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:39:43 +0800 Subject: [PATCH 147/171] fix: qualify private materialization file types --- Sources/AgentsCore/PrivateMaterialization.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Sources/AgentsCore/PrivateMaterialization.swift b/Sources/AgentsCore/PrivateMaterialization.swift index ad0fe9f..afd2525 100644 --- a/Sources/AgentsCore/PrivateMaterialization.swift +++ b/Sources/AgentsCore/PrivateMaterialization.swift @@ -314,7 +314,8 @@ struct MaterializationReceipts: Codable { throw CoreError.invalidState("invalid materialization receipt target") } guard - [mode_t(S_IFREG), mode_t(S_IFDIR)].contains(record.access.identity.kind), + [mode_t(CPlatform.S_IFREG), mode_t(CPlatform.S_IFDIR)].contains( + record.access.identity.kind), record.access.identity.isDirectory == (record.treeAccess != nil), record.access.identity.isDirectory == (NativeTargetRoute.targetRoute(path)?.isContainer == true), From c6547a7c7be309f1c18d4c901c43dc5417c9bdf3 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:46:34 +0800 Subject: [PATCH 148/171] feat: replace sources with typed reference updates --- Documentation/Reference/Manifest.md | 10 ++ Sources/AgentsManifest/DocumentEditor.swift | 15 ++ Sources/AgentsManifest/DocumentModels.swift | 2 + .../AgentsManifest/SourceReferenceEdits.swift | 53 +++++++ .../SourceReplacementTests.swift | 143 ++++++++++++++++++ .../SourceReplacementUpdateTests.swift | 64 ++++++++ 6 files changed, 287 insertions(+) create mode 100644 Sources/AgentsManifest/SourceReferenceEdits.swift create mode 100644 Tests/AgentsManifestTests/SourceReplacementTests.swift create mode 100644 Tests/AgentsUpdatesTests/SourceReplacementUpdateTests.swift diff --git a/Documentation/Reference/Manifest.md b/Documentation/Reference/Manifest.md index 7467d26..ac1c28a 100644 --- a/Documentation/Reference/Manifest.md +++ b/Documentation/Reference/Manifest.md @@ -72,6 +72,16 @@ group components to `/groups/0/components/...`. Handles belong to one digest. Agents App uses these document and edit APIs for configuration editing. Save operations preserve YAML text and scalar identity through the prepared edits. +Editing a named source uses `replaceSource(sourceNode, with: replacement)`, where +`sourceNode` is captured from `/sources/` in the current document snapshot. +The replacement retains collection position and rewrites typed references to the +old alias, including declaration `watch`, root and unused-group references, +executable sources and independent working-directory sources. Native data and +other strings remain unchanged. Same-alias replacement updates the definition; +new sources use `upsertSource`. Handles and the expected document digest must come +from the same snapshot. Invalid final source kinds, modes or aliases are rejected; +persisted Watch source-identity keys are outside document editing. + No-op changes return exact bytes. Changed fields and collection entries preserve unrelated bytes. Adjacent leading comments and same-line trailing comments belong to their item; moves carry them. Deletion retains comments unless explicitly diff --git a/Sources/AgentsManifest/DocumentEditor.swift b/Sources/AgentsManifest/DocumentEditor.swift index bb90d2b..4eaf3f2 100644 --- a/Sources/AgentsManifest/DocumentEditor.swift +++ b/Sources/AgentsManifest/DocumentEditor.swift @@ -211,6 +211,21 @@ struct DocumentEditor { case .setDefaultAgents(let agents): return [.set("/defaultAgents", YAMLConstruction.agents(agents))] case .upsertSource(let source): return try upsert("/sources", YAMLConstruction.source(source)) + case .replaceSource(let id, let replacement): + let path = try pointer(id) + let segments = IRTree.segments(path) + guard segments.count == 2, segments[0] == "sources", let index = Int(segments[1]), + current.declaration.sources.indices.contains(index) + else { throw failure("manifest.edit.readOnly", "expected a source occurrence") } + guard + !current.declaration.sources.enumerated().contains(where: { + $0.offset != index && $0.element["name"]?.string == replacement.name + }) + else { throw failure("manifest.domain", "duplicate source alias") } + let alias = current.declaration.sources[index]["name"]!.string! + return [.set(path, .record(YAMLConstruction.source(replacement)))] + + (alias == replacement.name + ? [] : SourceReferenceEdits.replacing(alias, with: replacement.name, in: root)) case .removeSource(let alias): return try removeNamed("/sources", alias) case .insertComponent(let value, let owner, let position): let path = try container(owner, "components") diff --git a/Sources/AgentsManifest/DocumentModels.swift b/Sources/AgentsManifest/DocumentModels.swift index 005c1b9..21d901d 100644 --- a/Sources/AgentsManifest/DocumentModels.swift +++ b/Sources/AgentsManifest/DocumentModels.swift @@ -25,6 +25,8 @@ public enum Editability: Sendable, Equatable { public enum ManifestEdit: Sendable { case setDefaultAgents([AgentID]?) case upsertSource(NamedSourceDeclaration) + /// Replaces one source in place and retargets its typed alias references. + case replaceSource(NodeID, with: NamedSourceDeclaration) case removeSource(alias: String) case insertComponent(ComponentDeclaration, into: ContainerID, at: InsertionPosition) case replaceComponent(NodeID, with: ComponentDeclaration) diff --git a/Sources/AgentsManifest/SourceReferenceEdits.swift b/Sources/AgentsManifest/SourceReferenceEdits.swift new file mode 100644 index 0000000..1eb3114 --- /dev/null +++ b/Sources/AgentsManifest/SourceReferenceEdits.swift @@ -0,0 +1,53 @@ +import AgentsCore + +/// Source references are roles in admitted declaration IR, not matching strings in YAML/native data. +enum SourceReferenceEdits { + static func replacing(_ alias: String, with replacement: String, in root: DeclarationValue) + -> [IREdit] + { + var edits: [IREdit] = [] + func visit(_ value: DeclarationValue, at pointer: String) { + guard let record = value.record else { return } + func reference(_ field: String) { + if record[field]?.string == alias { + edits.append(.set(pointer + "/" + field, .string(replacement))) + } + } + func child(_ field: String) { + if let value = record[field] { visit(value, at: pointer + "/" + field) } + } + func children(_ field: String) { + for (index, value) in (record[field]?.elements ?? []).enumerated() { + visit(value, at: pointer + "/" + field + "/" + String(index)) + } + } + switch record.kind { + case "declaration": + children("components") + children("groups") + children("uses") + for (index, value) in (record["watch"]?.elements ?? []).enumerated() + where value.string == alias { + edits.append(.set("/watch/" + String(index), .string(replacement))) + } + case "group": + children("components") + children("uses") + case "instructions": + children("sections") + children("chatGPT") + case "prompt": children("sections") + case "mcpServer": child("transport") + case "hook", "lspServer": child("run") + case "command", "subagent": child("prompt") + case "skills", "plugin", "section", "exported", "path", "file": reference("source") + case "executable", "stdio": + reference("executableSource") + child("workingDirectory") + default: break + } + } + visit(root, at: "") + return edits + } +} diff --git a/Tests/AgentsManifestTests/SourceReplacementTests.swift b/Tests/AgentsManifestTests/SourceReplacementTests.swift new file mode 100644 index 0000000..e2960a8 --- /dev/null +++ b/Tests/AgentsManifestTests/SourceReplacementTests.swift @@ -0,0 +1,143 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsManifest + +struct SourceReplacementTests { + @Test func replacementRetargetsTypedReferencesAndPreservesOtherBytes() throws { + let body = """ + # source header + version: 1 + sources: + first: {path: first} + original: {path: original, subpath: original} # source comment + other: {path: other} + components: + - {kind: skills, source: original, path: original, select: [], mode: copy} + - {kind: instructions, sections: [{name: original, source: original}], chatgpt: {original: {sections: [{name: original, source: original}], append: original}}} + - {kind: mcpServer, name: original, transport: {kind: stdio, executable: ./original, executableSource: original, arguments: [original], workingDirectory: {path: original, source: other}}, native: {schema: {source: original, executableSource: original}}} + - {kind: hook, name: hook, event: sessionStart, run: {executable: ./original, executableSource: other, workingDirectory: {path: original, source: original}}} + - {kind: lspServer, name: language, run: {executable: ./original, executableSource: original}, languages: {".original": original}} + - {kind: command, name: command, description: original, prompt: {file: {path: original, source: original}}} + - {kind: subagent, name: agent, description: original, prompt: {file: {path: original, source: original}}} + - {kind: plugin, name: plugin, path: original, source: original} + groups: + unused: + components: + - {kind: skills, source: original, select: []} + - {kind: instructions, sections: [{name: original, source: original}], chatgpt: {p: {sections: [{name: original, source: original}]}}} + - {kind: command, name: unused, description: original, prompt: {file: {path: original, source: original}}} + uses: [{group: original, source: original}] + uses: [{group: original, source: original}, {group: unused, source: "."}] + watch: [original, other] + # tail + """ + let doc = try document(body) + let source = try #require(doc.node(at: "/sources/1")) + let change = try doc.preparing([ + .replaceSource( + source, + with: .init( + name: "renamed", source: .init(kind: .local, location: "new-location", path: "original"))) + ]) + let output = String(decoding: change.bytes, as: UTF8.self) + let next = try DeclarationDocument(bytes: change.bytes, identity: .init("manifest")) + let tree = IRTree.root(next.declaration) + for pointer in [ + "/components/0/source", "/components/1/sections/0/source", + "/components/1/chatGPT/0/sections/0/source", + "/components/2/transport/executableSource", "/components/3/run/workingDirectory/source", + "/components/4/run/executableSource", "/components/5/prompt/source", + "/components/6/prompt/source", "/components/7/source", + "/groups/0/components/0/source", "/groups/0/components/1/sections/0/source", + "/groups/0/components/1/chatGPT/0/sections/0/source", + "/groups/0/components/2/prompt/source", "/groups/0/uses/0/source", "/uses/0/source", + "/watch/0", + ] { #expect(IRTree.value(tree, at: pointer)?.string == "renamed") } + #expect(next.declaration.sources.map { $0["name"]?.string } == ["first", "renamed", "other"]) + #expect( + IRTree.value(tree, at: "/components/2/transport/workingDirectory/source")?.string == "other") + #expect(IRTree.value(tree, at: "/components/3/run/executableSource")?.string == "other") + #expect(IRTree.value(tree, at: "/uses/1/source")?.string == ".") + #expect(output.contains("native: {schema: {source: original, executableSource: original}}")) + #expect(output.contains("executable: ./original") && output.contains("arguments: [original]")) + #expect( + output.contains(#"languages: {".original": original}"#) && output.contains("append: original") + ) + #expect( + output.contains("# source comment") && output.hasPrefix("# source header\n") + && output.hasSuffix("# tail")) + #expect(doc.bytes == Array(body.utf8)) + } + + @Test func handlesNoopsCollisionsAndSourceKindsKeepExistingAdmission() throws { + let doc = try document( + "version: 1\nsources: {s: {path: old}, other: {path: other}}\ncomponents: [{kind: skills, source: s, mode: edit}]\n" + ) + let source = try #require(doc.node(at: "/sources/0")) + let same = NamedSourceDeclaration(name: "s", source: .init(kind: .local, location: "old")) + #expect(try doc.preparing([.replaceSource(source, with: same)]).patches.isEmpty) + let updated = try doc.preparing([ + .replaceSource(source, with: .init(name: "s", source: .init(kind: .local, location: "new"))) + ]) + #expect( + try DeclarationDocument(bytes: updated.bytes, identity: .init("manifest")).declaration + .sources[0]["path"]?.string == "new") + for name in ["other", "."] { + #expect(throws: (any Error).self) { + try doc.preparing([.replaceSource(source, with: .init(name: name, source: same.source))]) + } + } + #expect(throws: (any Error).self) { + try doc.preparing([ + .replaceSource( + source, + with: .init( + name: "s", source: .init(kind: .git, location: "https://example.invalid/repo.git"))) + ]) + } + #expect(throws: (any Error).self) { + try doc.preparing([.replaceSource(#require(doc.node(at: "/components/0")), with: same)]) + } + #expect(throws: (any Error).self) { + try doc.preparing([.removeSource(alias: "s"), .replaceSource(source, with: same)]) + } + let changed = try document("# changed\n" + String(decoding: doc.bytes, as: UTF8.self)) + #expect(throws: (any Error).self) { + try changed.preparing([.replaceSource(source, with: same)]) + } + #expect(throws: (any Error).self) { + try doc.preparing([ + .replaceSource(NodeID(digest: doc.digest, pointer: "/sources/99", syntax: 0), with: same) + ]) + } + let chained = try doc.preparing([ + .replaceSource(source, with: .init(name: "temporary", source: same.source)), + .replaceSource(source, with: .init(name: "final", source: same.source)), + ]) + #expect( + try DeclarationDocument(bytes: chained.bytes, identity: .init("manifest")).declaration + .components[0]["source"]?.string == "final") + } + + @Test func replacementComposesAcrossBatchesAndRemapsOriginalHandles() throws { + let uses = (0..<105).map { "{group: g\($0), source: original}" }.joined(separator: ", ") + let doc = try document( + "version: 1\nsources: {first: {path: first}, original: {path: original}}\nuses: [" + uses + + "]\nwatch: [original]\n") + let source = try #require(doc.node(at: "/sources/1")) + let reference = try #require(doc.node(at: "/uses/104")) + let change = try doc.preparing([ + .removeSource(alias: "first"), + .replaceSource( + source, with: .init(name: "renamed", source: .init(kind: .local, location: "new"))), + .removeGroupReference(reference), + ]) + let result = try DeclarationDocument(bytes: change.bytes, identity: .init("manifest")) + #expect(result.declaration.uses.count == 104) + #expect(result.declaration.uses.allSatisfy { $0["source"]?.string == "renamed" }) + #expect(result.declaration.watch == ["renamed"]) + #expect(result.declaration.sources.first?["name"]?.string == "renamed") + } +} diff --git a/Tests/AgentsUpdatesTests/SourceReplacementUpdateTests.swift b/Tests/AgentsUpdatesTests/SourceReplacementUpdateTests.swift new file mode 100644 index 0000000..c270fbb --- /dev/null +++ b/Tests/AgentsUpdatesTests/SourceReplacementUpdateTests.swift @@ -0,0 +1,64 @@ +import AgentsCore +import AgentsManifest +import AgentsUpdates +import Foundation +import Testing + +struct SourceReplacementUpdateTests { + @Test func sourceReplacementPreviewApplyAndStaleReadUseCapturedDocument() throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration( + sources: ["original": .init(kind: .local, location: f.repo.path)], watch: ["original"], + components: [ + .skills( + source: "original", .init(select: .names(["demo"]), agents: [.claudeCode], mode: .copy)) + ]), ledger: .init()) + let identity = "local:" + f.repo.path + let watch = try JSONEncoder().encode( + WatchState(sources: [identity: .init(seen: .revision(try f.git(["rev-parse", "HEAD"])))])) + try watch.write(to: f.store.watchURL) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + let doc = try #require(snapshot.document) + let source = try #require(doc.node(at: "/sources/0")) + let request = UpdateRequest( + operation: .edit([ + .replaceSource( + source, with: .init(name: "renamed", source: .init(kind: .local, location: f.repo.path))) + ]), expectedDeclarationDigest: doc.digest) + let before = try Data(contentsOf: f.store.declarationURL) + let preview = try UpdateOperations.preview(request, environment: f.environment) + #expect(try Data(contentsOf: f.store.declarationURL) == before) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + #expect($0.report.displayedFingerprint == preview.displayedFingerprint) + return try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let cold = try UpdateOperations.inspect(environment: f.environment) + #expect(cold.deployments.allSatisfy { $0.status == .current }) + let declaration = try f.store.loadDeclaration() + #expect(declaration.sources["original"] == nil && declaration.sources["renamed"] != nil) + #expect(declaration.watch == ["renamed"]) + #expect(try Data(contentsOf: f.store.watchURL) == watch) + #expect(throws: (any Error).self) { + try UpdateOperations.preview(request, environment: f.environment) + } + let refreshed = try #require(cold.document) + let replacement = try #require(refreshed.node(at: "/sources/0")) + let nextRequest = UpdateRequest( + operation: .edit([ + .replaceSource( + replacement, + with: .init(name: "final", source: .init(kind: .local, location: f.repo.path))) + ]), expectedDeclarationDigest: refreshed.digest) + _ = try UpdateOperations.preview(nextRequest, environment: f.environment) + let external = Data("# external edit\n".utf8) + Data(refreshed.bytes) + try external.write(to: f.store.declarationURL) + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(nextRequest, environment: f.environment) { _ in + Issue.record("Changed source document must reject replacement before publication") + } + } + #expect(try Data(contentsOf: f.store.declarationURL) == external) + } +} From 46cbc6569b9e765763b61600b1e514b7b631e2d8 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:59:37 +0800 Subject: [PATCH 149/171] fix: preserve mapping indentation when adding fields --- Sources/AgentsManifest/YAMLPatches.swift | 8 +- .../MappingFieldInsertionTests.swift | 98 +++++++++++++++++++ 2 files changed, 103 insertions(+), 3 deletions(-) create mode 100644 Tests/AgentsManifestTests/MappingFieldInsertionTests.swift diff --git a/Sources/AgentsManifest/YAMLPatches.swift b/Sources/AgentsManifest/YAMLPatches.swift index 259c02d..53fcfa0 100644 --- a/Sources/AgentsManifest/YAMLPatches.swift +++ b/Sources/AgentsManifest/YAMLPatches.swift @@ -204,9 +204,11 @@ struct YAMLPatches { } return appendFlow(text, to: container) } - let indent = - pairs.first.map { indentation(at: $0.key.range.lowerBound) } - ?? indentation(at: container.range.lowerBound) + // The mapping starts after a compact sequence indicator, before any explicit key indicator. + let offset = container.range.lowerBound + let start = lineStart(offset) + let bom = start == 0 && bytes.starts(with: [0xEF, 0xBB, 0xBF]) ? 3 : 0 + let indent = String(repeating: " ", count: offset - start - bom) let end = pairs.last.map { lineEnd($0.value.entryRange.upperBound) } ?? container.range.upperBound return [ diff --git a/Tests/AgentsManifestTests/MappingFieldInsertionTests.swift b/Tests/AgentsManifestTests/MappingFieldInsertionTests.swift new file mode 100644 index 0000000..1184a3a --- /dev/null +++ b/Tests/AgentsManifestTests/MappingFieldInsertionTests.swift @@ -0,0 +1,98 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsManifest + +struct MappingFieldInsertionTests { + @Test(arguments: [false, true], ["\n", "\r\n"]) + func skillPathAlignsWithCompactMappingKeys(_ nested: Bool, _ newline: String) throws { + let owner = nested ? " " : "" + let prefix = + "# header\nversion: 1\ndefaultAgents: [codex]\nsources: {team: {path: ./source}}\n" + + (nested ? "groups:\n local:\n" : "") + let first = """ + \(owner)components: + \(owner) - kind: skills # component + \(owner) source: team + \(owner) select: [demo] + \(owner) mode: link # mode + """ + "\n" + let following = """ + \(owner) # following component + \(owner) - kind: instructions + \(owner) sections: [{name: style, source: team}] + # tail + """ + "\n" + let body = (prefix + first + following).replacingOccurrences(of: "\n", with: newline) + let doc = try document(body) + let pointer = nested ? "/groups/0/components/0" : "/components/0" + let edit = IREdit.set(pointer + "/path", .string(".")) + let patches = try YAMLPatches(document: doc).patches( + for: edit, expected: edit.applying(to: IRTree.root(doc.declaration))) + #expect(patches.count == 1) + #expect( + String(decoding: patches[0].replacement, as: UTF8.self) == owner + " \"path\": \".\"" + + newline) + let change = try doc.preparing([ + .replaceComponent( + #require(doc.node(at: pointer)), + with: .skills(source: "team", .init(select: .names(["demo"]), path: ".", mode: .link))) + ]) + let expected = (prefix + first + owner + " \"path\": \".\"\n" + following) + .replacingOccurrences(of: "\n", with: newline) + #expect(String(decoding: change.bytes, as: UTF8.self) == expected) + #expect(try document(expected).declaration == change.expectedDeclaration) + } + + @Test(arguments: [false, true]) + func executableSourcePreservesNestedBlockAndFlowMappings(_ flow: Bool) throws { + let transport = + flow + ? " transport: {kind: stdio, executable: ./tool} # transport\n" + : " transport:\n kind: stdio\n executable: ./tool # executable\n" + let prefix = + "version: 1\nsources: {team: {path: ./source}}\ncomponents:\n - kind: mcpServer\n name: server\n" + let tail = " - {kind: ignore, name: keep, patterns: []}\n" + let doc = try document(prefix + transport + tail) + let change = try doc.preparing([ + .replaceComponent( + #require(doc.node(at: "/components/0")), + with: .mcpServer( + name: "server", transport: .stdio(.init(executable: "./tool", executableSource: "team")))) + ]) + let expectedTransport = + flow + ? " transport: {kind: stdio, executable: ./tool, \"executableSource\": \"team\"} # transport\n" + : transport + " \"executableSource\": \"team\"\n" + #expect(String(decoding: change.bytes, as: UTF8.self) == prefix + expectedTransport + tail) + #expect( + try document(prefix + expectedTransport + tail).declaration == change.expectedDeclaration) + } + + @Test func flowSkillPathPreservesCommentsAndFollowingComponent() throws { + let body = + "version: 1\nsources: {team: {path: ./source}}\ncomponents:\n - {kind: skills, source: team, select: [demo], mode: link} # skill\n - {kind: ignore, name: keep, patterns: []}\n" + let doc = try document(body) + let change = try doc.preparing([ + .replaceComponent( + #require(doc.node(at: "/components/0")), + with: .skills(source: "team", .init(select: .names(["demo"]), path: ".", mode: .link))) + ]) + #expect( + String(decoding: change.bytes, as: UTF8.self) + == body.replacingOccurrences(of: "mode: link}", with: "mode: link, \"path\": \".\"}")) + } + + @Test(arguments: [false, true]) + func rootFieldInsertionPreservesByteOrderMark(_ explicitKey: Bool) throws { + let first = explicitKey ? "? version\r\n: 1" : "version: 1" + let body = "\u{FEFF}" + first + "\r\n# retained\r\n" + let doc = try document(body) + let change = try doc.preparing([.setDefaultAgents([.codex])]) + #expect( + String(decoding: change.bytes, as: UTF8.self) + == "\u{FEFF}" + first + "\r\n\"defaultAgents\": [\"codex\"]\r\n# retained\r\n") + } + +} From ecfb70576dad6e6b11cfe21eeda3783af416d0ca Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:13:46 +0800 Subject: [PATCH 150/171] test: qualify native tree file type --- Tests/AgentsCoreTests/PrivateTreeTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/AgentsCoreTests/PrivateTreeTests.swift b/Tests/AgentsCoreTests/PrivateTreeTests.swift index 113d767..91efc3d 100644 --- a/Tests/AgentsCoreTests/PrivateTreeTests.swift +++ b/Tests/AgentsCoreTests/PrivateTreeTests.swift @@ -259,7 +259,7 @@ struct PrivateTreeTests { } else { var access = try #require(record["access"] as? [String: Any]) var identity = try #require(access["identity"] as? [String: Any]) - identity["kind"] = Int(S_IFREG) + identity["kind"] = Int(CPlatform.S_IFREG) access["identity"] = identity record["access"] = access } From 70148ece2847ae63adaed6bd7fff90347272971b Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:39:09 +0800 Subject: [PATCH 151/171] fix: honor exact declared instruction references --- Sources/AgentsUpdates/UpdatePlan.swift | 90 ++++++++++++++----- .../OwnershipAndPlacementTests.swift | 42 +++++++++ 2 files changed, 108 insertions(+), 24 deletions(-) diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index deb6961..73d9a28 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -38,7 +38,8 @@ final class UpdatePlan { let importInputs = try (request.importPreparation?.capture() ?? []) + catalogInputs let baseline = try StatePrecondition(store: store) let previous = try store.readLedger(prepared: baseline) - try resolveSelection(&request, ledger: previous, store: store, baseline: baseline) + let instructionReferences = try resolveSelection( + &request, ledger: previous, store: store, baseline: baseline) let restoringRequest: Bool if case .restore = request.operation { restoringRequest = true @@ -79,7 +80,9 @@ final class UpdatePlan { previous, kinds: request.kinds ?? Set(DeclaredComponentKind.allCases), names: Set(request.names), roots: store.ledgerRoots, selectedIdentities: request.selectedIdentities) - candidate = try removing(request, from: declaration, ledger: previous, store: store) + candidate = try removing( + request, from: declaration, ledger: previous, store: store, + selectedInstructionReferences: instructionReferences) change = try store.planDeclaration(candidate, replacing: declaration, prepared: baseline) } let retargetedInstructions: Set @@ -519,12 +522,42 @@ final class UpdatePlan { private static func resolveSelection( _ request: inout UpdateRequest, ledger: ResolvedLedger, store: StateStore, baseline: StatePrecondition - ) throws { + ) throws -> Set? { let kinds = request.kinds ?? Set(DeclaredComponentKind.allCases) func name(_ c: LedgerComponent) -> String { c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name } if request.selections.isEmpty { + if case .remove = request.operation, request.kinds == [.instructions] { + let declaration = try store.readDeclaration(prepared: baseline) + let references = try selectedInstructionReferences(Set(request.names), in: declaration) + let sections = declaration.components.flatMap { component -> [SectionDeclaration] in + guard case .instructions(let selection) = component else { return [] } + return selection.sectionReferences + + selection.prompts.flatMap { $0.prompt.sectionReferences } + } + var selected = Set() + for section in sections where references.contains(section.reference) { + let source: String + if let alias = section.source, alias != "." { + guard let sourceDeclaration = declaration.sources[alias] else { continue } + source = try sourceDeclaration.identity(environment: store.environment) + } else { + source = "local:" + store.environment.projectDirectory.resolvingSymlinksInPath().path + } + for component in ledger.components.values + where component.kind == "instructions" && component.group == nil + && component.name == section.name + { + if try ledger.sourceIdentity(component.source, roots: store.ledgerRoots) == source { + selected.insert( + try LedgerImpact.identity(component, ledger: ledger, roots: store.ledgerRoots)) + } + } + } + request.selectedIdentities = selected + return references + } for requested in request.names { let matches = try ledger.components.values.filter { kinds.contains(DeclaredComponentKind(rawValue: $0.kind)!) && name($0) == requested @@ -534,7 +567,7 @@ final class UpdatePlan { "component name is ambiguous; select a component from inspection: " + requested) } } - return + return nil } guard request.names.isEmpty else { throw CoreError.invalidState("use names or precise selections, not both") @@ -583,25 +616,43 @@ final class UpdatePlan { request.selectedIdentities = selected request.names = names.sorted() request.kinds = selectedKinds + return nil + } + + private static func selectedInstructionReferences( + _ names: Set, in declaration: Declaration + ) throws -> Set { + let references = Set( + declaration.components.flatMap { component -> [String] in + guard case .instructions(let selection) = component else { return [] } + return selection.sectionReferences.map(\.reference) + + selection.prompts.flatMap { $0.prompt.sectionReferences.map(\.reference) } + }) + var selected = Set() + for name in names { + let exact = references.filter { $0 == name } + let matches = + exact.isEmpty + ? references.filter { $0.split(separator: ":").last.map(String.init) == name } : exact + guard matches.count == 1, let reference = matches.first else { + throw CoreError.notFound("instruction name is missing or ambiguous: " + name) + } + selected.insert(reference) + } + return selected } private static func removing( _ request: UpdateRequest, from declaration: Declaration, ledger: ResolvedLedger, - store: StateStore + store: StateStore, selectedInstructionReferences: Set? ) throws -> Declaration { var result = declaration let names = Set(request.names) let kinds = request.kinds ?? Set(DeclaredComponentKind.allCases) - let references = Set( - declaration.components.flatMap { component -> [String] in - if case .instructions(let value) = component { - return value.sectionReferences.map(\.reference) - + value.prompts.flatMap { $0.prompt.sectionReferences.map(\.reference) } - } - return [] - }) var instructionReferences = Set() - if kinds.contains(.instructions), let identities = request.selectedIdentities { + if let selectedInstructionReferences { + instructionReferences = selectedInstructionReferences + } else if kinds.contains(.instructions), let identities = request.selectedIdentities { let sections = declaration.components.flatMap { component -> [SectionDeclaration] in guard case .instructions(let selection) = component else { return [] } return selection.sectionReferences @@ -625,16 +676,7 @@ final class UpdatePlan { } } } else if kinds.contains(.instructions) { - for name in names { - let exact = references.filter { $0 == name } - let matches = - exact.isEmpty - ? references.filter { $0.split(separator: ":").last.map(String.init) == name } : exact - guard matches.count == 1, let reference = matches.first else { - throw CoreError.notFound("instruction name is missing or ambiguous: " + name) - } - instructionReferences.insert(reference) - } + instructionReferences = try Self.selectedInstructionReferences(names, in: declaration) } result.components = declaration.components.compactMap { component in switch component { diff --git a/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift b/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift index 5b30bf4..03a8e4a 100644 --- a/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift +++ b/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift @@ -216,3 +216,45 @@ struct OwnershipAndPlacementTests { #expect(user.targets.map { $0.sections.map(\.name) } == [["rules"]]) } } + +extension OwnershipAndPlacementTests { + @Test func removeBareNameFallsBackOnlyToAUniqueDeclaredSource() throws { + let fixture = try InstructionFixture() + try fixture.section("guide") + try fixture.commit() + try fixture.add(names: ["guide"]) + try InstructionOperations.remove(names: ["guide"], environment: fixture.environment) + #expect(try fixture.store().loadDeclaration().instructions?.sections == []) + #expect(try fixture.store().loadResolved().instructions.sections.isEmpty) + } + + @Test func ambiguousFallbackRefusesAndQualifiedReferencesPreserveOtherGuides() throws { + let fixture = try InstructionFixture() + try fixture.section("guide", heading: "# Shared Guide") + try fixture.commit() + try fixture.add(names: ["guide"]) + let store = fixture.store() + var declaration = try store.loadDeclaration() + declaration.sources["other"] = .init( + kind: .local, location: fixture.root.appendingPathComponent("unresolved-other").path) + try declaration.updateInstructions { $0?.sections.append("other:guide") } + try store.save(declaration: declaration, ledger: store.loadLedger()) + let before = try fixture.snapshot() + var called = false + #expect(throws: CoreError.notFound("instruction name is missing or ambiguous: guide")) { + try InstructionOperations.remove(names: ["guide"], environment: fixture.environment) { _ in + called = true + } + } + #expect(!called) + #expect(try fixture.snapshot() == before) + try declaration.updateInstructions { $0?.sections.removeAll { $0 == "other:guide" } } + declaration.sources["other"] = nil + try store.save(declaration: declaration, ledger: store.loadLedger()) + try fixture.own("guide", heading: "# Project Guide") + try fixture.addOwn(names: ["guide"]) + try InstructionOperations.remove(names: ["rules:guide"], environment: fixture.environment) + #expect(try store.loadDeclaration().instructions?.sections == ["guide"]) + #expect(try fixture.text() == generated(["# Project Guide\n\nOriginal"])) + } +} From 55bf4d503d0ce12ff202e756e31932c115746b6e Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:40:18 +0800 Subject: [PATCH 152/171] fix: retain symlinked directory executable metadata --- Sources/Components/LedgerFreeze.swift | 8 +++-- .../RetainedLifecycleTests.swift | 5 +-- Tests/ComponentsTests/LedgerReplayTests.swift | 35 +++++++++++++++++++ 3 files changed, 44 insertions(+), 4 deletions(-) diff --git a/Sources/Components/LedgerFreeze.swift b/Sources/Components/LedgerFreeze.swift index e3b8655..0b9b2ae 100644 --- a/Sources/Components/LedgerFreeze.swift +++ b/Sources/Components/LedgerFreeze.swift @@ -96,9 +96,13 @@ package enum LedgerFreeze { let captured = try LedgerResources.capture( url, embed: kind != .git, limits: limits, sourceRoot: try session.resource(snapshot: resource.snapshot, path: ".")) + var directory: ObjCBool = false + guard FileManager.default.fileExists(atPath: url.path, isDirectory: &directory) else { + throw CoreError.invalidState("linked resource disappeared before freeze") + } let flags = - captured.entries.count == 1 && captured.entries[0].kind != .directory - ? [resource.path: captured.flags["."] ?? false] : captured.flags + directory.boolValue + ? captured.flags : [resource.path: captured.flags["."] ?? false] guard captured.hash == resource.hash, resource.executableFlags.isEmpty || flags == resource.executableFlags else { diff --git a/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift b/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift index 2d732e2..9bd65ca 100644 --- a/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift @@ -60,8 +60,9 @@ struct RetainedLifecycleTests { named: "internal", directory: fixture.repo.appendingPathComponent("skills")) try Data("---\nname: internal\ndescription: Internal\nmetadata:\n internal: true\n---".utf8) .write(to: internalDirectory.appendingPathComponent("SKILL.md")) - _ = try SkillOperations.initializeSkill( - named: "deep", directory: fixture.repo.appendingPathComponent("skills/level/level")) + let deepDirectory = fixture.repo.appendingPathComponent("skills/level/level") + try FileManager.default.createDirectory(at: deepDirectory, withIntermediateDirectories: true) + _ = try SkillOperations.initializeSkill(named: "deep", directory: deepDirectory) for value in ["", "false", "TRUE", "yes", "true", "1"] { var environment = fixture.environment environment.environment["INSTALL_INTERNAL_SKILLS"] = value diff --git a/Tests/ComponentsTests/LedgerReplayTests.swift b/Tests/ComponentsTests/LedgerReplayTests.swift index 4a04aba..f735128 100644 --- a/Tests/ComponentsTests/LedgerReplayTests.swift +++ b/Tests/ComponentsTests/LedgerReplayTests.swift @@ -79,6 +79,41 @@ struct LedgerReplayTests { } } + @Test(arguments: ["content", "executable", "escape"]) + func linkedDirectoryResourceMutationIsRejectedBeforeFreeze(_ mutation: String) throws { + let fixture = try LinkFixture() + try fixture.write("support", to: "working/check", base: fixture.project) + let check = fixture.project.appendingPathComponent("working/check") + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: check.path) + let alias = fixture.project.appendingPathComponent("working-alias") + try FileManager.default.createSymbolicLink(atPath: alias.path, withDestinationPath: "working") + let document = try fixture.document( + """ + version: 1 + components: [{"kind": "mcpServer", "name": "server", "transport": {"kind": "stdio", "executable": "server", "workingDirectory": {"path": "working-alias"}}}] + """ + ) + try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + if mutation == "content" { + try Data("changed".utf8).write(to: check) + } else if mutation == "executable" { + try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: check.path) + } else { + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: fixture.home) + } + #expect(throws: CoreError.self) { + _ = try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: [ + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: ".") + ]), limits: .standard) + } + } + } + private func run(_ action: String, root: URL) throws { var directory = Bundle(for: LedgerTestBundle.self).bundleURL while directory.path != "/", From 1958b5375e32c6f548b272d902727613d5038459 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:46:14 +0800 Subject: [PATCH 153/171] test: verify admitted recovery and publication races --- .../CachePublicationTests.swift | 12 ++++++-- .../PreparationEvidenceTests.swift | 11 ++++--- Tests/AgentsCoreTests/PublicationTests.swift | 30 +++++++++++++++++-- .../StateTransactionTests.swift | 21 ++++++++----- Tests/StateTestProcess/main.swift | 29 +++++++++++++----- 5 files changed, 79 insertions(+), 24 deletions(-) diff --git a/Tests/AgentsCoreTests/CachePublicationTests.swift b/Tests/AgentsCoreTests/CachePublicationTests.swift index b27eb70..593ab2d 100644 --- a/Tests/AgentsCoreTests/CachePublicationTests.swift +++ b/Tests/AgentsCoreTests/CachePublicationTests.swift @@ -88,6 +88,7 @@ struct CachePublicationTests { @Test func verifiesPrivateCopyBeforePublication() throws { let fixture = try CacheFixture() let beforeState = try FileSnapshot.read(at: fixture.store.resolvedURL) + var tampered = false let cache = SourceCache(store: fixture.store) { step in if step == TransactionCheckpoint.stage(0, .constructed).name { let parent = fixture.destination.deletingLastPathComponent() @@ -96,16 +97,21 @@ struct CachePublicationTests { try Data("tampered".utf8).write( to: parent.appendingPathComponent(name).appendingPathComponent( TransactionSlot.staged.name(0) + "/injected")) + tampered = true } } } - #expect(throws: CoreError.invalidState("staged content digest mismatch")) { + #expect { try fixture.store.withLock { try cache.materializeArtifact( fixture.root.appendingPathComponent("new"), digest: fixture.digest, hash: "sha256:" + fixture.hash) } + } throws: { error in + guard case CoreError.invalidState = error else { return false } + return true } + #expect(tampered) #expect(try FileSnapshot.read(at: fixture.destination) == nil) #expect(try FileSnapshot.read(at: fixture.store.resolvedURL) == beforeState) #expect( @@ -159,8 +165,8 @@ struct CachePublicationTests { #expect { try fixture.store.withLock { try cache.storeArtifact(payload, digest: fixture.digest) } } throws: { error in - guard case CoreError.invalidState(let reason) = error else { return false } - return reason.contains("transaction destination already exists") + guard case CoreError.invalidState = error else { return false } + return true } #expect(external != nil) #expect(try FileSnapshot.read(at: final) == external) diff --git a/Tests/AgentsCoreTests/PreparationEvidenceTests.swift b/Tests/AgentsCoreTests/PreparationEvidenceTests.swift index 032610d..8ad18be 100644 --- a/Tests/AgentsCoreTests/PreparationEvidenceTests.swift +++ b/Tests/AgentsCoreTests/PreparationEvidenceTests.swift @@ -108,6 +108,7 @@ struct PreparationEvidenceTests { @Test(arguments: [false, true]) func constructionMustMatchTheRequestedCopyOrLink(_ link: Bool) throws { let fixture = try PublicationFixture(.fileCreate) + var tampered = false let transaction = FileTransaction(store: fixture.store) { point in if point == TransactionCheckpoint.stage(0, .constructed).name { let name = try #require( @@ -122,6 +123,7 @@ struct PreparationEvidenceTests { } else { try Data("injected".utf8).write(to: staged.appendingPathComponent("injected")) } + tampered = true } } try transaction.replace( @@ -129,10 +131,11 @@ struct PreparationEvidenceTests { with: link ? .link(fixture.root.appendingPathComponent("new")) : .copy(fixture.root.appendingPathComponent("new"))) - #expect( - throws: CoreError.invalidState( - link ? "staged symbolic link destination mismatch" : "staged content digest mismatch") - ) { try transaction.commit() } + #expect { try transaction.commit() } throws: { error in + guard case CoreError.invalidState = error else { return false } + return true + } + #expect(tampered) try fixture.check(committed: false, journal: nil) try fixture.expectClean() } diff --git a/Tests/AgentsCoreTests/PublicationTests.swift b/Tests/AgentsCoreTests/PublicationTests.swift index 2c79f7e..afd5e39 100644 --- a/Tests/AgentsCoreTests/PublicationTests.swift +++ b/Tests/AgentsCoreTests/PublicationTests.swift @@ -132,7 +132,7 @@ struct PublicationTests { } @Test(arguments: [false, true]) - func exchangedUnexpectedPreimageIsNeverDiscarded(_ inPlace: Bool) throws { + func changedPreimageBeforeExchangeKeepsExternalBytesAndInode(_ inPlace: Bool) throws { let fixture = try PublicationFixture(.fileReplace) let child = try fixture.pause( "publication", at: TransactionCheckpoint.publication(1, .validated).name) @@ -143,9 +143,33 @@ struct PublicationTests { } try Data("external preimage".utf8).write(to: fixture.target) let external = try FileSnapshot.read(at: fixture.target) - try fixture.restop(child, at: TransactionCheckpoint.publication(1, .exchanged).name) - terminateProcess(child) + try fixture.resume(child) + #expect(try fixture.result("publication-result").hasPrefix("unchanged\n")) + #expect(try FileSnapshot.read(at: fixture.target) == external) + #expect(try FileSnapshot.read(at: fixture.auxiliary) == fixture.beforeAuxiliary) + if !inPlace { + #expect( + try FileSnapshot.read(at: fixture.root.appendingPathComponent("original")) + == fixture.beforeTarget) + } + try fixture.expectClean() + } + + @Test(arguments: [false, true]) + func exchangedUnexpectedPreimageIsNeverDiscarded(_ inPlace: Bool) throws { + let fixture = try PublicationFixture(.fileReplace) + let child = try fixture.pause( + "publication", at: TransactionCheckpoint.publication(1, .exchanged).name) + defer { terminateProcess(child) } let journal = try #require(try fixture.lastJournal()) + let exchanged = fixture.slot(.exchanged, entry: 1, journal: journal) + if !inPlace { + try FileManager.default.moveItem( + at: exchanged, to: fixture.root.appendingPathComponent("original")) + } + try Data("external preimage".utf8).write(to: exchanged) + let external = try FileSnapshot.read(at: exchanged) + terminateProcess(child) let postimage = try #require(journal.entries[1].staged) #expect(try FileSnapshot.read(at: fixture.target) == postimage) #expect( diff --git a/Tests/AgentsCoreTests/StateTransactionTests.swift b/Tests/AgentsCoreTests/StateTransactionTests.swift index 354a17f..512b94c 100644 --- a/Tests/AgentsCoreTests/StateTransactionTests.swift +++ b/Tests/AgentsCoreTests/StateTransactionTests.swift @@ -281,9 +281,8 @@ extension StateTransactionTests { #expect(recovery.terminationReason == .uncaughtSignal) var steps: [String] = [] - try FileLock.withLock(at: store.directory.appendingPathComponent(".agents.lock")) { - let recovered = try FileTransaction.recover(store: store) { steps.append($0) } - #expect(recovered) + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { + try store.withLock(checkpoint: { steps.append($0) }, {}) } #expect(!steps.contains(TransactionCheckpoint.restoration(4, .withdrawn).name)) let synced = try #require( @@ -300,9 +299,16 @@ extension StateTransactionTests { #expect( !FileManager.default.fileExists( atPath: store.directory.appendingPathComponent("transaction.json").path)) - #expect( - try FileManager.default.contentsOfDirectory(atPath: target.deletingLastPathComponent().path) - .isEmpty) + let remaining = try FileManager.default.contentsOfDirectory( + atPath: target.deletingLastPathComponent().path) + #expect(remaining == (scope == .user ? [SharedResource.metadataName] : [])) + if scope == .user { + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: scope, name: "created") + try store.withReadLock(footprint: [route]) { + let reservation = try TransactionLockContext.current(store).requiredResource().reservation() + #expect(reservation == nil) + } + } } @Test(arguments: [ @@ -596,8 +602,9 @@ extension StateTransactionTests { try Data("original".utf8).write(to: target.appendingPathComponent("SKILL.md")) } let before = try Data(contentsOf: store.resolvedURL) + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: "demo") #expect(throws: CoreError.invalidState("interrupted user write")) { - try store.withLock { + try store.withLock(footprint: [route]) { let transaction = FileTransaction(store: store) { step in if step == TransactionCheckpoint.publication(3, .exchanged).name { let journal = try String( diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 8d06651..0ec3b0c 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -253,8 +253,14 @@ if arguments[2].hasPrefix("ledger-") { try Data((String(describing: outcome.disposition) + "\n" + failure).utf8).write( to: root.appendingPathComponent("publication-result")) } else if arguments[2] == "recover" { - try FileLock.withLock(at: store.directory.appendingPathComponent(".agents.lock")) { - _ = try FileTransaction.recover(store: store) { try stop($0, marker: "recovery-ready") } + if scope == .user { + do { + try store.withLock(checkpoint: { try stop($0, marker: "recovery-ready") }, {}) + } catch CoreError.transactionRecovered {} + } else { + try FileLock.withLock(at: store.directory.appendingPathComponent(".agents.lock")) { + _ = try FileTransaction.recover(store: store) { try stop($0, marker: "recovery-ready") } + } } } else if arguments[2] == "read" { try Data().write(to: root.appendingPathComponent("reader-started")) @@ -312,7 +318,12 @@ if arguments[2].hasPrefix("ledger-") { try Data().write(to: root.appendingPathComponent("lock-acquired")) }) } else { - try store.withLock { + let createdSkill = + arguments[2] == "crash" && scope == .user + ? try store.skillInstallationTarget(for: .claudeCode, named: "created") : nil + try store.withLock( + footprint: createdSkill?.footprint ?? [], installations: createdSkill.map { [$0] } ?? [] + ) { if arguments[2] == "cache-content" || arguments[2] == "cache-git" || arguments[2] == "cache-bytes" { @@ -397,10 +408,14 @@ if arguments[2].hasPrefix("ledger-") { ledger.sources["local:/new"] = LedgerSource(kind: .local, revision: "live") try transaction.replace(store.resolvedURL, with: .data(StateStore.encode(ledger))) try transaction.delete(store.cacheDirectory.appendingPathComponent("artifact-content/pruned")) - try transaction.replace( - AgentRegistry.installSkillsDirectory( - for: .claudeCode, scope: scope, environment: store.environment - ).appendingPathComponent("created"), with: .link(root.appendingPathComponent("new"))) + if let createdSkill { + try transaction.replaceSkill(createdSkill, with: .link(root.appendingPathComponent("new"))) + } else { + try transaction.replace( + AgentRegistry.installSkillsDirectory( + for: .claudeCode, scope: scope, environment: store.environment + ).appendingPathComponent("created"), with: .link(root.appendingPathComponent("new"))) + } try transaction.replace( InstructionLocations.file(for: .codex, scope: scope, environment: store.environment)!, with: .data(Data("new instructions".utf8))) From 19f0df059e8f7a07ed641151bee277663a030d01 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:57:58 +0800 Subject: [PATCH 154/171] fix: bind catalog choices to composed source evidence --- .../AgentsUpdates/ComponentDiscovery.swift | 9 +- .../SourceCatalogInspection.swift | 87 +++++++++++++++++- Sources/Components/SourceCatalog.swift | 75 ++++++++++++++-- .../SourceCatalogInspectionTests.swift | 88 +++++++++++++++++++ .../ArtifactLinkingTests.swift | 45 +++++++++- 5 files changed, 291 insertions(+), 13 deletions(-) diff --git a/Sources/AgentsUpdates/ComponentDiscovery.swift b/Sources/AgentsUpdates/ComponentDiscovery.swift index af400c9..a3825eb 100644 --- a/Sources/AgentsUpdates/ComponentDiscovery.swift +++ b/Sources/AgentsUpdates/ComponentDiscovery.swift @@ -55,7 +55,8 @@ extension UpdateOperations { private static func discover( _ declaration: Declaration, store: StateStore, destination: AdditionDestination?, - importPreparation: ImportPreparation?, allowNewIdentities: Bool = true + importPreparation: ImportPreparation?, allowNewIdentities: Bool = true, + catalogExpectation: CatalogCompositionExpectation? = nil ) throws -> ComponentDiscovery { return try store.withReadLock { try destination?.validate(in: store) @@ -82,6 +83,7 @@ extension UpdateOperations { directPins: destination == nil ? [:] : impact.directPins, retaining: destination == nil ? nil : previousLedger ) { linked, session in + try catalogExpectation?.validate(linked) let frozen = try LedgerFreeze.freezeWithSources( linked, session: session, locations: .init( @@ -191,7 +193,8 @@ extension UpdateOperations { /// return nil, including a source-only selection, and never initialize destination state. package static func captureAddition( _ additions: Declaration, in inspection: ScopeInspection, - importPreparation: ImportPreparation? = nil + importPreparation: ImportPreparation? = nil, + catalogExpectation: CatalogCompositionExpectation? = nil ) throws -> ComponentDiscovery? { guard !additions.components.isEmpty || !additions.groups.isEmpty || !additions.uses.isEmpty else { return nil } @@ -236,6 +239,6 @@ extension UpdateOperations { for use in additions.uses where !candidate.uses.contains(use) { candidate.uses.append(use) } return try discover( candidate, store: destination.store, destination: destination, - importPreparation: importPreparation) + importPreparation: importPreparation, catalogExpectation: catalogExpectation) } } diff --git a/Sources/AgentsUpdates/SourceCatalogInspection.swift b/Sources/AgentsUpdates/SourceCatalogInspection.swift index 06826c8..16cef02 100644 --- a/Sources/AgentsUpdates/SourceCatalogInspection.swift +++ b/Sources/AgentsUpdates/SourceCatalogInspection.swift @@ -135,7 +135,9 @@ public struct SourceCatalogInspection: Sendable, CustomReflectable { let preparation = CatalogPreparation( capture: capture, choices: choices.map(\.index), options: options, inputs: inputs) let additions = try preparation.additions() - guard var discovery = try UpdateOperations.captureAddition(additions, in: capture.destination) + guard + var discovery = try UpdateOperations.captureAddition( + additions, in: capture.destination, catalogExpectation: preparation.compositionExpectation) else { return nil } discovery.catalogPreparation = preparation return discovery @@ -341,6 +343,13 @@ package final class CatalogPreparation: @unchecked Sendable, CustomReflectable { guard fresh.snapshot == catalog.snapshot, fresh.root.utf8.elementsEqual(catalog.root.utf8), fresh.contentHash == catalog.contentHash else { throw CoreError.invalidState("catalog source changed; refresh inspection") } + for index in choices { + guard fresh.choices.indices.contains(index), + fresh.choices[index].graph == catalog.choices[index].graph, + fresh.choices[index].artifact == catalog.choices[index].artifact, + fresh.choices[index].unavailableReason == catalog.choices[index].unavailableReason + else { throw CoreError.invalidState("catalog dependency changed; refresh inspection") } + } try capture.original?.validate() let selected = try catalog.selected(choices.map { catalog.choices[$0].id }) ?? [] if catalog.importDocument == nil { @@ -355,6 +364,13 @@ package final class CatalogPreparation: @unchecked Sendable, CustomReflectable { } return try conversion().0 } + fileprivate var compositionExpectation: CatalogCompositionExpectation { + .init( + components: choices.flatMap { capture.catalog.choices[$0].graph?.components ?? [] }, + references: choices.flatMap { capture.catalog.choices[$0].graph?.references ?? [] }, + liveEdits: options.skillMode == .edit) + } + private func conversion() throws -> (Declaration, SourceImportProposal) { let catalog = capture.catalog let selected = try catalog.selected(choices.map { catalog.choices[$0].id }) ?? [] @@ -430,3 +446,72 @@ private func effects(_ value: SourceCatalog.ImportEffects) -> ImportSelectionEff pointer: $0.location.pointer, span: $0.location.span, message: $0.message) }) } + +/// Selected producer evidence is checked against the composed graph before it is frozen. +/// Consumer restrictions, recipients, modes and container filters remain authored composition. +package struct CatalogCompositionExpectation { + let components: [LinkedComponent] + let references: [LinkedReference] + let liveEdits: Bool + + func validate(_ linked: LinkedComponents) throws { + for reference in references { + let candidates = linked.references.filter { + $0.group.utf8.elementsEqual(reference.group.utf8) + && $0.root.utf8.elementsEqual(reference.root.utf8) + && $0.snapshot.source.utf8.elementsEqual(reference.snapshot.source.utf8) + } + guard !candidates.isEmpty, + candidates.allSatisfy({ + $0.snapshot.revision.utf8.elementsEqual(reference.snapshot.revision.utf8) + && $0.manifestHash.utf8.elementsEqual(reference.manifestHash.utf8) + }) + else { throw CoreError.invalidState("catalog group changed dependency; refresh inspection") } + } + let expected = Dictionary(grouping: components, by: \.key) + let actual = Dictionary(grouping: linked.components, by: \.key) + for (key, requirements) in expected { + let candidates = actual[key] ?? [] + guard !candidates.isEmpty, + try Set(requirements.map(evidence)) == Set(candidates.map(evidence)) + else { + throw CoreError.invalidState("catalog addition changed dependency; refresh inspection") + } + } + } + + private func evidence(_ component: LinkedComponent) throws -> Data { + let editing = liveEdits && component.key.kind == .skills + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + func snapshot(_ value: SourceSnapshotID) throws -> Data { + try encoder.encode([ + value.source, + editing && value.source.utf8.elementsEqual(component.snapshot.source.utf8) + ? "live" : value.revision, + ]) + } + var fields = try [snapshot(component.snapshot), snapshot(component.declaringSnapshot)] + for resource in component.resources { + fields.append( + try encoder.encode([ + snapshot(resource.snapshot), Data(resource.path.utf8), Data(resource.hash.utf8), + encoder.encode(resource.executableFlags), encoder.encode(resource.artifact), + ])) + } + // Root occurrence numbers and declaration positions differ after finite composition. + // Complete producer dependency clauses remain distinct; their collection order is incidental. + let dependencies = try Set( + component.origins.map { origin in + try encoder.encode( + Set( + origin.dependencies.filter { + $0.revision != "live" + && !(editing && $0.source.utf8.elementsEqual(component.snapshot.source.utf8)) + }.map(snapshot) + ).sorted { $0.lexicographicallyPrecedes($1) }) + }) + fields.append(try encoder.encode(dependencies.sorted { $0.lexicographicallyPrecedes($1) })) + return try encoder.encode(fields) + } +} diff --git a/Sources/Components/SourceCatalog.swift b/Sources/Components/SourceCatalog.swift index a928d0d..ba3991e 100644 --- a/Sources/Components/SourceCatalog.swift +++ b/Sources/Components/SourceCatalog.swift @@ -99,13 +99,16 @@ package struct SourceCatalog: Sendable { let snapshot = try SourceSnapshotID( source: source.identity(environment: store.environment), revision: "sha256:" + hash) try budget.snapshot(snapshot) - let choices = try skills.enumerated().map { index, skill in - try budget.contribution(chain: 0) - try budget.snapshot(.init(source: snapshot.source, revision: skill.artifact.digest)) - return Choice( - id: .init(owner: owner, index: index), label: label("Skill", skill.name), - origin: .init(document: skill.name, pointer: ""), unit: .skill(skill.name), - graph: nil, imported: nil, artifact: skill.artifact, unavailableReason: nil) + let choices = try SourceResolutionSession.withTemporaryRead(store: store) { session in + try skills.enumerated().map { index, skill in + let graph = try capturedIndexSkill( + skill, alias: alias, source: source, store: store, platform: platform, + session: session, budget: budget) + return Choice( + id: .init(owner: owner, index: index), label: label("Skill", skill.name), + origin: .init(document: skill.name, pointer: ""), unit: .skill(skill.name), + graph: graph, imported: nil, artifact: skill.artifact, unavailableReason: nil) + } } return .init( alias: alias, source: source, snapshot: snapshot, root: source.path ?? ".", @@ -351,3 +354,61 @@ package struct SourceCatalog: Sendable { resolvedURL: value.resolvedURL, developmentOnly: value.developmentOnly) } } + +extension SourceCatalog { + /// Interprets the already verified artifact through ordinary skill expansion, without fetching + /// again or promoting the borrowed extraction to a source identity. + private static func capturedIndexSkill( + _ skill: SnapshotIndexSkill, alias: String, source: SourceDeclaration, store: StateStore, + platform: DeclarationPlatform, session: SourceResolutionSession, budget: LinkBudget + ) throws -> LinkedComponents { + let id = try source.identity(environment: store.environment) + let view = try session.fileSnapshot( + source: id, revision: skill.artifact.digest, + files: skill.files, executableFlags: skill.executableFlags) + try budget.snapshot(view.snapshot) + let declaration = Declaration( + sources: [alias: source], + components: [ + .skills(source: alias, .init(select: .names([skill.name]))) + ]) + let identity = DocumentIdentity("catalog/agents.yaml") + let bytes = + try DeclarationEditPlan.bytes( + replacing: Declaration(), with: declaration, + in: nil, identity: identity, environment: store.environment) ?? Array("version: 1\n".utf8) + let document = try DeclarationDocument(bytes: bytes, identity: identity) + let root = store.scope == .user ? store.directory : store.environment.projectDirectory + let consumer = try SourceSnapshot( + snapshot: .init(source: "local:" + root.path, revision: "live"), + pin: nil, root: root, + localEnvironment: .init( + projectDirectory: root, + homeDirectory: store.environment.homeDirectory), liveRoot: root) + session.register(consumer) + let context = LinkingDocument( + declaration: declaration, document: document, view: consumer, + manifestPath: store.scope == .user ? "agents.yaml" : ".agent/agents.yaml", producer: false, + importedSources: [alias: view]) + try budget.manifest(consumer.snapshot, path: context.manifestPath, bytes: bytes.count) + let linking = Linking( + document: document, store: store, platform: platform, session: session, + directPins: [:], retainedLedger: nil, budget: budget) + linking.sourceUses = [.init(source: id, root: ".", requirement: source.requirement)] + let expansion = Expansion(linking: linking, choices: [:], emit: true) + try expansion.expandRoot(context) + let graph = try expansion.result() + return LinkedComponents( + components: graph.components.map { component in + var component = component + component.resources = component.resources.map { resource in + LinkedResource( + snapshot: resource.snapshot, path: resource.path, hash: resource.hash, + executableFlags: resource.executableFlags, artifact: skill.artifact) + } + return component + }, references: graph.references, constraints: graph.constraints, selections: graph.selections, + sourceSnapshots: graph.sourceSnapshots, sourceUses: graph.sourceUses, + declaringSnapshots: graph.declaringSnapshots) + } +} diff --git a/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift b/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift index f709bef..a51c8c5 100644 --- a/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift +++ b/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift @@ -335,3 +335,91 @@ extension SourceCatalogInspectionTests { #expect(try FileHash.executableFlags(tree) == flags) } } + +extension SourceCatalogInspectionTests { + @Test func selectionRejectsChangedExternalDependencyWithUnchangedCatalogRoot() throws { + let f = try UpdateFixture() + let a = f.root.appendingPathComponent("producer-a") + let b = f.root.appendingPathComponent("producer-b") + try f.write( + """ + version: 1 + sources: {b: {path: '\(b.path)'}} + exports: [outer] + groups: + outer: + uses: [{source: b, group: inner}] + """, to: a.appendingPathComponent(".agent/agents.yaml")) + func dependency(_ prompt: String) throws { + try f.write( + """ + version: 1 + exports: [inner] + groups: + inner: + components: + - {kind: command, name: review, description: Review, prompt: '\(prompt)', agents: [claude-code]} + """, to: b.appendingPathComponent(".agent/agents.yaml")) + } + try dependency("before") + let rootHash = try FileHash.folderHash(a) + let catalog = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: a.path), environment: f.environment) + let choice = try #require( + catalog.availableChoices.first { + if case .group = $0.unit { return true } + return false + }) + let discovery = try #require(try catalog.select([choice.id])) + try dependency("after") + #expect(try FileHash.folderHash(a) == rootHash) + #expect(throws: (any Error).self) { try catalog.select([choice.id]) } + #expect(throws: (any Error).self) { + try UpdateOperations.preview(discovery.updateRequest(), environment: f.environment) + } + } +} + +extension SourceCatalogInspectionTests { + @Test func protectedUnrelatedRevisionCannotAttestSelectedSkill() throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration( + sources: ["fixture": .init(kind: .local, location: f.repo.path)], + skills: ["fixture": .init(select: .names(["demo"]), agents: [.codex], mode: .copy)], + instructions: .init(agents: [.claudeCode], sections: ["fixture:rules"])), + ledger: ResolvedLedger()) + _ = try f.apply() + try f.writeSource("new") + try f.commit() + _ = try UpdateOperations.withPreparedUpdate( + .init(kinds: [.instructions]), environment: f.environment + ) { try $0.apply() } + let catalog = try UpdateOperations.inspectSource( + alias: "fixture", source: .init(kind: .local, location: f.repo.path), + environment: f.environment) + let choice = try #require(catalog.availableChoices.first { $0.label == "Skill demo" }) + let retained = try f.store.loadLedger() + #expect(retained.sources.values.contains { $0.revision == catalog.revision }) + #expect(throws: (any Error).self) { + _ = try catalog.select([choice.id], options: .init(agents: [.codex], skillMode: .copy)) + } + } +} + +extension SourceCatalogInspectionTests { + @Test(arguments: [InstallMode.copy, .edit]) + func unchangedSkillCompositionRetainsConsumerModeAndRestrictions(_ mode: InstallMode) throws { + let f = try UpdateFixture() + let catalog = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: f.repo.path), + environment: f.environment) + let choice = try #require(catalog.availableChoices.first { $0.label == "Skill demo" }) + let discovery = try #require( + try catalog.select( + [choice.id], options: .init(agents: [.codex], skillMode: mode))) + #expect(discovery.components.count == 1) + #expect(discovery.components[0].recipients == [.codex]) + _ = try UpdateOperations.preview(discovery.updateRequest(), environment: f.environment) + } +} diff --git a/Tests/ComponentsTests/ArtifactLinkingTests.swift b/Tests/ComponentsTests/ArtifactLinkingTests.swift index ee07390..067e957 100644 --- a/Tests/ComponentsTests/ArtifactLinkingTests.swift +++ b/Tests/ComponentsTests/ArtifactLinkingTests.swift @@ -233,12 +233,53 @@ struct ArtifactLinkingTests { #expect(throws: LinkError.self) { try freeze(pins: pins, previous: corrupt) } } - private func archive(_ name: String, body: String, fixture: LinkFixture, web: URL) throws + @Test func catalogIndexSkillCarriesCapturedRestrictionsAndResourceEffects() throws { + let fixture = try LinkFixture() + let web = fixture.root.appendingPathComponent("web") + try FileManager.default.createDirectory(at: web, withIntermediateDirectories: true) + let server = try IndexHTTPServer(root: web) + defer { server.stop() } + let digest = try archive( + "alpha", body: "restricted", fixture: fixture, web: web, + restrictions: "agents: [codex]\n") + try index([("alpha", digest)], fixture: fixture, web: web) + let source = SourceDeclaration(kind: .wellKnown, location: server.url) + let catalog = try Components.SourceCatalog.inspect( + alias: "web", source: source, + store: fixture.store, platform: .macOS) + let choice = try #require(catalog.choices.first) + let graph = try #require(choice.graph) + let effect = try #require(graph.components.first) + #expect(effect.recipients == [.codex]) + #expect(effect.conditions.first?.agents == [.codex]) + #expect(effect.resources.first?.artifact?.digest == digest) + let document = try fixture.document( + """ + version: 1 + sources: {web: {index: '\(server.url)'}} + components: [{kind: skills, source: web, select: [alpha]}] + """) + try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { elected, _ in + let actual = try #require(elected.components.first) + #expect(actual.snapshot == effect.snapshot) + #expect(actual.payload == effect.payload) + #expect(actual.conditions == effect.conditions) + #expect(actual.recipients == effect.recipients) + #expect(actual.resources == effect.resources) + } + } + + private func archive( + _ name: String, body: String, fixture: LinkFixture, web: URL, restrictions: String = "" + ) throws -> String { let root = fixture.root.appendingPathComponent(name) try fixture.write( - "---\nname: \(name)\ndescription: Fixture\n---\n\(body)\n", to: "SKILL.md", base: root) + "---\nname: \(name)\ndescription: Fixture\n\(restrictions)---\n\(body)\n", to: "SKILL.md", + base: root) try fixture.write(body + " context", to: "references/context.md", base: root) try fixture.write("fixture script", to: "scripts/run", base: root) try FileManager.default.setAttributes( From 51b19cc40ca0532253e7130383ba05aad8eb3b49 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:01:08 +0800 Subject: [PATCH 155/171] test: replay generated plugin fixtures on the host platform --- Tests/ComponentsTests/GeneratedPluginTests.swift | 14 +++++++++++--- .../OpaquePluginIdentityTests.swift | 14 +++++++++++--- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/Tests/ComponentsTests/GeneratedPluginTests.swift b/Tests/ComponentsTests/GeneratedPluginTests.swift index 8ab9f00..cfe2ae3 100644 --- a/Tests/ComponentsTests/GeneratedPluginTests.swift +++ b/Tests/ComponentsTests/GeneratedPluginTests.swift @@ -8,12 +8,20 @@ import Testing @Suite("Frozen generated native plugins") struct GeneratedPluginTests { + private var platform: DeclarationPlatform { + #if os(macOS) + .macOS + #else + .linux + #endif + } + private func freeze( _ fixture: LinkFixture, _ expression: String, scope: InstallScope = .project ) throws -> ([LinkedComponent], LedgerFreeze.Result) { let store = StateStore(scope: scope, environment: fixture.environment) return try ComponentLinker.withLinkedComponents( - document: fixture.document(expression), store: store, platform: .macOS + document: fixture.document(expression), store: store, platform: platform ) { graph, session in let locations = Dictionary( (graph.sourceSnapshots + graph.declaringSnapshots).filter { @@ -45,7 +53,7 @@ struct GeneratedPluginTests { ) throws -> LockedLowering { try NativeGeneratedPluginLayoutV1.lower( components.first { $0.key.kind == .plugin }!, members: components, frozen: frozen, - request: .init(surface: surface, scope: scope), id: "generated", platform: .macOS) + request: .init(surface: surface, scope: scope), id: "generated", platform: platform) } @Test func frozenClosureColdReplayPreservesOrderBindingsResourcesAndRegistration() throws { @@ -244,7 +252,7 @@ struct GeneratedPluginTests { try NativeGeneratedPluginLayoutV1.lower( parent, members: components, frozen: frozen, request: .init(surface: .claudeCode, scope: .project), id: "parent/" + String(index), - platform: .macOS) + platform: platform) } ledger = try LedgerReplay.prepareLowerings( ledger, store: fixture.store, roots: [:], limits: .standard) diff --git a/Tests/ComponentsTests/OpaquePluginIdentityTests.swift b/Tests/ComponentsTests/OpaquePluginIdentityTests.swift index 0a4f923..1c6e534 100644 --- a/Tests/ComponentsTests/OpaquePluginIdentityTests.swift +++ b/Tests/ComponentsTests/OpaquePluginIdentityTests.swift @@ -7,6 +7,14 @@ import Testing @Suite("Opaque native plugin producer identity") struct OpaquePluginIdentityTests { + private var platform: DeclarationPlatform { + #if os(macOS) + .macOS + #else + .linux + #endif + } + @Test(arguments: [false, true]) func declaringNamespaceAndSelectedProducerPairThroughColdReplay(_ separateProducer: Bool) throws { let fixture = try LinkFixture() @@ -34,7 +42,7 @@ struct OpaquePluginIdentityTests { bytes: Array(JSONSerialization.data(withJSONObject: input, options: [.sortedKeys])), identity: .init("consumer/agents.yaml")) let (linked, frozen) = try ComponentLinker.withLinkedComponents( - document: document, store: fixture.store, platform: .macOS + document: document, store: fixture.store, platform: platform ) { graph, session in let locations = Dictionary( (graph.sourceSnapshots + graph.declaringSnapshots).map { @@ -52,7 +60,7 @@ struct OpaquePluginIdentityTests { } let lowering = try NativeComponentLowering.lower( linked, frozen: frozen, - request: .init(surface: .claudeCode, scope: .project), id: "opaque", platform: .macOS) + request: .init(surface: .claudeCode, scope: .project), id: "opaque", platform: platform) let record = try #require(frozen.ledger.components[lowering.inputs[0]]) #expect(linked.key.source == linked.declaringSnapshot.source) #expect(record.declaringSource == frozen.sources[linked.declaringSnapshot]) @@ -65,7 +73,7 @@ struct OpaquePluginIdentityTests { #expect(throws: NativeComponentIssue.self) { try NativeComponentLowering.lower( linked, frozen: corrupt, - request: .init(surface: .claudeCode, scope: .project), id: "invalid", platform: .macOS) + request: .init(surface: .claudeCode, scope: .project), id: "invalid", platform: platform) } var ledger = frozen.ledger ledger.lowerings = [lowering] From f88e6dd0d18e85800ce93e92ddc6429825625452 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:05:16 +0800 Subject: [PATCH 156/171] fix: preserve pinned evidence for copied catalog skills --- .../SourceCatalogInspection.swift | 32 ++++-- .../SourceCatalogInspectionTests.swift | 106 ++++++++++++++++++ 2 files changed, 131 insertions(+), 7 deletions(-) diff --git a/Sources/AgentsUpdates/SourceCatalogInspection.swift b/Sources/AgentsUpdates/SourceCatalogInspection.swift index 16cef02..d58dceb 100644 --- a/Sources/AgentsUpdates/SourceCatalogInspection.swift +++ b/Sources/AgentsUpdates/SourceCatalogInspection.swift @@ -366,9 +366,7 @@ package final class CatalogPreparation: @unchecked Sendable, CustomReflectable { } fileprivate var compositionExpectation: CatalogCompositionExpectation { .init( - components: choices.flatMap { capture.catalog.choices[$0].graph?.components ?? [] }, - references: choices.flatMap { capture.catalog.choices[$0].graph?.references ?? [] }, - liveEdits: options.skillMode == .edit) + choices: choices.map { capture.catalog.choices[$0] }, skillMode: options.skillMode) } private func conversion() throws -> (Declaration, SourceImportProposal) { @@ -450,9 +448,19 @@ private func effects(_ value: SourceCatalog.ImportEffects) -> ImportSelectionEff /// Selected producer evidence is checked against the composed graph before it is frozen. /// Consumer restrictions, recipients, modes and container filters remain authored composition. package struct CatalogCompositionExpectation { - let components: [LinkedComponent] - let references: [LinkedReference] - let liveEdits: Bool + private let components: [LinkedComponent] + private let references: [LinkedReference] + private let liveEditKeys: Set + + init(choices: [SourceCatalog.Choice], skillMode: InstallMode?) { + components = choices.flatMap { $0.graph?.components ?? [] } + references = choices.flatMap { $0.graph?.references ?? [] } + liveEditKeys = Set( + choices.flatMap { choice -> [ComponentKey] in + guard skillMode == .edit, case .skill = choice.unit else { return [] } + return choice.graph?.components.map(\.key) ?? [] + }) + } func validate(_ linked: LinkedComponents) throws { for reference in references { @@ -472,6 +480,16 @@ package struct CatalogCompositionExpectation { let actual = Dictionary(grouping: linked.components, by: \.key) for (key, requirements) in expected { let candidates = actual[key] ?? [] + if liveEditKeys.contains(key) { + guard + candidates.allSatisfy({ + if case .skill(_, .edit, _) = $0.payload { return true } + return false + }) + else { + throw CoreError.invalidState("catalog live edit changed mode; refresh inspection") + } + } guard !candidates.isEmpty, try Set(requirements.map(evidence)) == Set(candidates.map(evidence)) else { @@ -481,7 +499,7 @@ package struct CatalogCompositionExpectation { } private func evidence(_ component: LinkedComponent) throws -> Data { - let editing = liveEdits && component.key.kind == .skills + let editing = liveEditKeys.contains(component.key) let encoder = JSONEncoder() encoder.outputFormatting = [.sortedKeys] func snapshot(_ value: SourceSnapshotID) throws -> Data { diff --git a/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift b/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift index a51c8c5..04cdda9 100644 --- a/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift +++ b/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import Foundation import Testing @@ -423,3 +424,108 @@ extension SourceCatalogInspectionTests { _ = try UpdateOperations.preview(discovery.updateRequest(), environment: f.environment) } } + +extension SourceCatalogInspectionTests { + @Test func directEditDoesNotEraseExportedSkillRevisionEvidence() throws { + let f = try UpdateFixture() + try f.git(["tag", "1.0.0"]) + let oldRevision = try f.git(["rev-parse", "HEAD"]) + try f.write("Unrelated producer change\n", to: f.repo.appendingPathComponent("README.md")) + try f.commit() + try f.git(["tag", "1.1.0"]) + let newRevision = try f.git(["rev-parse", "HEAD"]) + try #require(newRevision != oldRevision) + + let producer = f.root.appendingPathComponent("mixed-producer") + try f.write( + "---\nname: helper\ndescription: Helper\n---\nUnchanged live skill\n", + to: producer.appendingPathComponent("skills/helper/SKILL.md")) + try f.write( + """ + version: 1 + sources: {b: {path: '\(f.repo.path)'}} + exports: [empty, review] + groups: + empty: + components: [] + review: + components: + - kind: skills + source: b + select: [demo] + agents: [claude-code] + mode: copy + """, to: producer.appendingPathComponent(".agent/agents.yaml")) + #if os(macOS) + let platform = DeclarationPlatform.macOS + #else + let platform = DeclarationPlatform.linux + #endif + let catalog = try SourceCatalog.inspect( + alias: "mixed", source: .init(kind: .local, location: producer.path), + store: f.store, platform: platform) + let direct = try #require(catalog.choices.first { $0.label == "Skill helper" }) + let review = try #require( + catalog.choices.first { + if case .group(let use) = $0.unit { return use.name == "review" } + return false + }) + let source = try SourceDeclaration(kind: .local, location: f.repo.path) + .identity(environment: f.environment) + let expected = try #require(review.graph?.components.first) + let expectedResource = try #require(expected.resources.first) + try requireCopiedReview(expected, source: source, revision: newRevision) + + let declaration = try catalog.additions( + [direct.id, review.id], agents: nil, condition: nil, mode: .edit) + let identity = DocumentIdentity(f.store.declarationURL.path) + let bytes = try #require( + try DeclarationEditPlan.bytes( + replacing: Declaration(), with: declaration, in: nil, identity: identity, + environment: f.environment)) + let document = try DeclarationDocument(bytes: bytes, identity: identity) + let expectation = CatalogCompositionExpectation(choices: [direct, review], skillMode: .edit) + + for revision in [oldRevision, newRevision] { + try ComponentLinker.withLinkedComponents( + document: document, store: f.store, platform: platform, + directPins: [expected.key: SourceRevision(revision: revision)] + ) { linked, _ in + let copied = try #require(linked.components.first { $0.key == expected.key }) + try requireCopiedReview(copied, source: source, revision: revision) + let resource = try #require(copied.resources.first) + try #require(resource.path == expectedResource.path) + try #require(resource.hash == expectedResource.hash) + try #require(resource.snapshot == copied.snapshot) + let helper = try #require(linked.components.first { $0.key.name == "helper" }) + guard case .skill(_, .edit, _) = helper.payload else { + Issue.record("Expected the direct helper to be linked in edit mode") + return + } + if revision == oldRevision { + #expect( + throws: CoreError.invalidState( + "catalog addition changed dependency; refresh inspection") + ) { + try expectation.validate(linked) + } + } else { + try expectation.validate(linked) + } + } + } + } + + private func requireCopiedReview(_ component: LinkedComponent, source: String, revision: String) + throws + { + guard case .skill(_, .copy, _) = component.payload else { + throw CoreError.invalidState("Expected the review skill to be linked in copy mode") + } + try #require(component.key.name == "demo") + try #require(component.key.group == "review") + try #require(component.snapshot.source == source) + try #require(component.snapshot.revision == revision) + try #require(component.origins.contains { $0.dependencies.contains(component.snapshot) }) + } +} From e4ed1ba28f738fdb991af6f8ace7824874061b06 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:19:19 +0800 Subject: [PATCH 157/171] docs: describe the configuration management release --- CHANGELOG.md | 17 +++++++++++++++++ Documentation/Decisions/AgentComponents.md | 8 ++++---- .../Decisions/ConfigurationApplication.md | 4 ++-- README.md | 5 +++-- 4 files changed, 26 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0be230c..e974194 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,26 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ## Unreleased +## 0.3.0 + ### Added - Linux support. +- The `AgentsManifest` library reads and edits YAML declarations, reports field + locations and preserves comments and unrelated text during configuration edits. +- Consumers can inspect and import sources, select exported groups, preview + native component changes and apply the reviewed configuration. An explicit + MCP connection test supports initialization and tool discovery. + +### Changed + +- Projects declare configuration in `.agent/agents.yaml` and users in + `~/.agents/agents.yaml`. Prepare and verify the declaration in each existing + scope before applying it with the updated CLI. See the + [manifest reference](Documentation/Reference/Manifest.md). +- `agents.resolved` uses the version 2 JSON ledger. It records locked resources + and ownership of native configuration. Both CLI consumers must use the same + ledger format. See [state and recovery](Documentation/Architecture/State.md). ## 0.2.0 - 2026-10-27 diff --git a/Documentation/Decisions/AgentComponents.md b/Documentation/Decisions/AgentComponents.md index 0af6f00..33ecfa9 100644 --- a/Documentation/Decisions/AgentComponents.md +++ b/Documentation/Decisions/AgentComponents.md @@ -33,7 +33,7 @@ physical locations; Codex, Cursor, Gemini CLI and OpenCode read the same and content hash, and cleanup removes only what the lock proves agents owns. - **Agent targeting.** Every component can be limited to agents and platforms. A producer declares targeting in front matter or a package manifest; a - consumer narrows it in the manifest with `agents` or `.when(...)` and never + consumer narrows it in the manifest with `agents` or `condition` and never widens it. A component reaches the declared agents that the registry says support it. When a shared location exposes a component to agents beyond its targeting, agents reports the conflict and the user chooses to share or to @@ -55,8 +55,8 @@ physical locations; Codex, Cursor, Gemini CLI and OpenCode read the same component an agent cannot represent is reported, not dropped or approximated. - **Distribution.** A source is a Git repository, local directory or index. - A repository publishes reusable groups by declaring them in its - `Agents.swift`; agents runs no hosted marketplace or registry. + A repository publishes reusable groups through the `exports` field in its + [YAML manifest](../Reference/Manifest.md). ## Consequences @@ -88,5 +88,5 @@ physical locations; Codex, Cursor, Gemini CLI and OpenCode read the same - Accepted by the repository owner (showxu) on 2026-10-28. - Current agent locations and state: [Package](../Architecture/Package.md), [State](../Architecture/State.md) -- Manifest that declares components: [Swift Manifest](SwiftManifest.md) +- Manifest that declares components: [YAML Manifest](YAMLManifest.md) - Configuration application and connection tests: [Configuration Application](ConfigurationApplication.md) diff --git a/Documentation/Decisions/ConfigurationApplication.md b/Documentation/Decisions/ConfigurationApplication.md index 46a39e9..1b97c10 100644 --- a/Documentation/Decisions/ConfigurationApplication.md +++ b/Documentation/Decisions/ConfigurationApplication.md @@ -49,5 +49,5 @@ or enabled the component. ## Related Documentation - [Agent Components and Adapters](AgentComponents.md) -- [Swift Manifest](SwiftManifest.md) -- [Agents Manifest Contract](../Archive/AgentsManifest.md) +- [YAML Manifest](YAMLManifest.md) +- [Manifest reference](../Reference/Manifest.md) diff --git a/README.md b/README.md index da52335..fe77198 100644 --- a/README.md +++ b/README.md @@ -67,8 +67,9 @@ command parsing, terminal output and executable distribution. `AgentsCore` for sources, state and transactions, `AgentsManifest` for the declaration, and `swift-markdown` for CommonMark structure. Pure text APIs remain available separately. -- **AgentsUpdates**: shared preparation, reporting and one recoverable apply - for all declared skills and instructions in a scope. +- **AgentsUpdates**: previews and applies the declared configuration in one + recoverable transaction. It also exposes source import, component inspection + and explicit MCP connection tests to CLI and GUI consumers. ## Quick look From 837594db43b2ba716c080c07475c4e69c25cc904 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:19:44 +0800 Subject: [PATCH 158/171] perf: group transaction requests by receipt and reuse parent validation --- Sources/AgentsCore/FileTransaction.swift | 42 +++---- .../AgentsCore/NativeTargetCoordination.swift | 111 +++++++++++++++--- .../AgentsCore/PrivateMaterialization.swift | 2 +- Sources/AgentsCore/TransactionEvidence.swift | 2 +- Sources/AgentsCore/TransactionPaths.swift | 28 ++++- Sources/AgentsCore/TransactionSession.swift | 2 +- .../TransactionCostTests.swift | 99 ++++++++++++++++ 7 files changed, 240 insertions(+), 46 deletions(-) diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 3397f02..b3be4d8 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -253,26 +253,23 @@ package final class FileTransaction { } private func queueReceipt() throws { - let originals = requests + var byReceipt: [String: [(key: String, security: TransactionSecurity)]] = [:] + for request in requests { + let location = try store.materializationReceiptLocation(for: request.path) + byReceipt[location.path, default: []].append((location.key, request.security)) + } for state in receiptStates.values.sorted(by: { $0.path < $1.path }) { - let receiptRoute = NativeTargetRoute.metadataRoute(state.path) - let shared = receiptRoute != nil - let affected = try originals.filter { - let route = try TransactionPaths(store: store).coordinationRoute(for: $0.path) - let root = try route.map { - try TransactionLockContext.current(store).requiredResourceForRoute($0).route.root - } - let key = try store.materializationReceiptKey(for: $0.path) - return root == receiptRoute?.root - && ($0.security.isPrivate || state.records.targets[key] != nil) + let shared = NativeTargetRoute.metadataRoute(state.path) != nil + let affected = (byReceipt[state.path] ?? []).filter { + $0.security.isPrivate || state.records.targets[$0.key] != nil } guard !affected.isEmpty else { continue } var sensitiveTargets = Set(state.records.targets.keys) for request in affected { if request.security.replacement == .privateMaterialization { - sensitiveTargets.insert(try store.materializationReceiptKey(for: request.path)) + sensitiveTargets.insert(request.key) } else { - sensitiveTargets.remove(try store.materializationReceiptKey(for: request.path)) + sensitiveTargets.remove(request.key) } } var security = TransactionSecurity() @@ -446,8 +443,8 @@ package final class FileTransaction { return .init(bytes: bytes) } } else { - let key = try store.materializationReceiptKey(for: request.path) - let previous = receiptStates.values.compactMap { $0.records.targets[key] }.first + let location = try store.materializationReceiptLocation(for: request.path) + let previous = receiptStates[location.path]?.records.targets[location.key] try session.stage( index, source: request.source, expectation: request.expectation, privateData: request.privateData, privateTree: request.privateTree, @@ -555,10 +552,8 @@ package final class FileTransaction { preimage: request.evidence.snapshot, parentIdentity: identity, container: container, security: security)) } - let sharedRoutes = Set( - try entries.compactMap { - try paths.coordinationRoute(for: $0.path) - }) + let entryRoutes = try entries.map { try paths.coordinationRoute(for: $0.path) } + let sharedRoutes = Set(entryRoutes.compactMap { $0 }) let admittedResources = try sharedRoutes.map { route in guard let context = TransactionLockContext.current(store) else { throw CoreError.invalidState("shared transaction requires its held footprint") @@ -566,14 +561,15 @@ package final class FileTransaction { return try context.resource(for: route) }.sorted { $0.identity < $1.identity } var resources: [SharedResource] = [] - for resource in admittedResources - where !resources.contains(where: { $0.identity == resource.identity }) { + var resourceIndices: [SharedResourceIdentity: Int] = [:] + for resource in admittedResources where resourceIndices[resource.identity] == nil { + resourceIndices[resource.identity] = resources.count resources.append(resource) } for index in entries.indices { - if let route = try paths.coordinationRoute(for: entries[index].path) { + if let route = entryRoutes[index] { let resource = try TransactionLockContext.current(store)!.resource(for: route) - entries[index].coordination = resources.firstIndex { $0.identity == resource.identity } + entries[index].coordination = resourceIndices[resource.identity] entries[index].coordinationRoot = resource.route.root } } diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index a918c10..cbbf001 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -437,6 +437,15 @@ package struct NativeTargetRoute: RawRepresentable, Hashable, Codable, Sendable static func userRoute(at destination: URL, environment: RuntimeEnvironment) throws -> Self? { let target = destination.deletingLastPathComponent().resolvingSymlinksInPath() .appendingPathComponent(destination.lastPathComponent) + // The candidate routes share ancestors. Reuse opens only within this lookup. + var opened: [Data: DirectoryHandle?] = [:] + func directory(at url: URL) -> DirectoryHandle? { + let key = Data(url.path.utf8) + if let known = opened[key] { return known } + let handle = try? DirectoryHandle(at: url) + opened[key] = .some(handle) + return handle + } func matches(_ route: Self) throws -> Bool { guard route.basename.utf8.elementsEqual(target.lastPathComponent.utf8) else { return false } let authority = try route.rootAuthority(environment, validateExistingOverride: false) @@ -452,8 +461,7 @@ package struct NativeTargetRoute: RawRepresentable, Hashable, Codable, Sendable } // Unselected, disjoint roots do not impose access requirements on this target. // Openable aliases still compare by descriptor identity, including bind aliases. - guard let candidate = try? DirectoryHandle(at: planned), - let parent = try? DirectoryHandle(at: targetParent), + guard let candidate = directory(at: planned), let parent = directory(at: targetParent), try candidate.objectIdentity == parent.objectIdentity else { return false } _ = try authority.physicalDirectory() @@ -471,10 +479,10 @@ package struct NativeTargetRoute: RawRepresentable, Hashable, Codable, Sendable let container = try authority.plannedPhysicalDirectory var ancestor = target.deletingLastPathComponent() var relativeParts = [target.lastPathComponent] - let containerIdentity = try? DirectoryHandle(at: container).objectIdentity + let containerIdentity = try? directory(at: container)?.objectIdentity while ancestor.path != "/" { if let containerIdentity, - let opened = try? DirectoryHandle(at: ancestor), + let opened = directory(at: ancestor), try opened.objectIdentity == containerIdentity { break @@ -539,7 +547,7 @@ struct NativeRootAuthority { } /// Pathname authorization is checked separately. Neither route nor caller participates here. -struct SharedResourceIdentity: Codable, Equatable, Comparable { +struct SharedResourceIdentity: Codable, Hashable, Comparable { let parent: FileObjectIdentity let basename: String @@ -550,6 +558,10 @@ struct SharedResourceIdentity: Codable, Equatable, Comparable { static func == (lhs: Self, rhs: Self) -> Bool { lhs.parent == rhs.parent && lhs.basename.utf8.elementsEqual(rhs.basename.utf8) } + func hash(into hasher: inout Hasher) { + hasher.combine(parent) + hasher.combine(Data(basename.utf8)) + } static func < (lhs: Self, rhs: Self) -> Bool { lhs.orderingKey.utf8.lexicographicallyPrecedes(rhs.orderingKey.utf8) } @@ -574,6 +586,13 @@ struct SharedReservation: Codable, Equatable { /// An opened, verified physical coordination domain. Its lock inode is never removed. final class SharedResource { + private struct ParentValidationKey: Hashable { + let loader: Data + let descendants: [Data] + let parent: Data + let identity: FileObjectIdentity + } + static let metadataName = ".agents-native" let identity: SharedResourceIdentity let route: NativeTargetRoute @@ -583,9 +602,12 @@ final class SharedResource { let metadataAccess: FileAccessEvidence? let metadataAncestry: DirectoryAccessEvidence? let authority: NativeRootAuthority + private let parentValidationKey: ParentValidationKey private var lockDescriptor: Int32? private var lockAccess: FileAccessEvidence? + var receiptPath: String { route.metadata + "/receipt" } + init( store: StateStore, route: NativeTargetRoute = .claudeMCPLocal, create: Bool, existingRoot: ExistingProjectRoot? = nil, projectRoot: DirectoryHandle? = nil, @@ -604,6 +626,10 @@ final class SharedResource { } ancestry = try DirectoryAccessEvidence.capture(at: url) identity = SharedResourceIdentity(parent: try parent.objectIdentity, basename: route.basename) + parentValidationKey = ParentValidationKey( + loader: Data(authority.loader.path.utf8), + descendants: authority.descendants.map { Data($0.utf8) }, + parent: Data(parent.url.path.utf8), identity: identity.parent) // Record the intended private domain before opening it: missing entries or invalid access // can stop admission before a SharedResource exists. let baseURL = parent.url.appendingPathComponent(Self.metadataName) @@ -637,6 +663,29 @@ final class SharedResource { } func validate() throws { + try validateLock() + try validateParent() + try validateMetadata() + } + + /// Each pass revalidates the root and every domain's lock and metadata. + static func validateAll(_ resources: [SharedResource]) throws { + var parents: [ParentValidationKey: DirectoryAccessEvidence] = [:] + for resource in resources { + try resource.validateLock() + if let ancestry = parents[resource.parentValidationKey] { + guard ancestry == resource.ancestry else { + throw CoreError.invalidState("filesystem access ancestry changed during preparation") + } + } else { + try resource.validateParent() + parents[resource.parentValidationKey] = resource.ancestry + } + try resource.validateMetadata() + } + } + + private func validateLock() throws { if let descriptor = lockDescriptor, let access = lockAccess { guard let metadata, try metadata.info("lock").map(FileObjectIdentity.init) == access.identity @@ -645,6 +694,9 @@ final class SharedResource { } try access.validate(descriptor: descriptor) } + } + + private func validateParent() throws { try ancestry.validate(at: parent.url) guard try DirectoryHandle(at: authority.physicalDirectory()).objectIdentity @@ -653,6 +705,9 @@ final class SharedResource { else { throw CoreError.invalidState("shared target parent identity changed") } + } + + private func validateMetadata() throws { if let metadata { try metadataAncestry?.validate(at: metadata.url) let current = try DirectoryHandle(at: metadata.url) @@ -807,11 +862,14 @@ final class TransactionLockContext { let resources: [SharedResource] var createdAncestry: [(URL, DirectoryAccessEvidence)] = [] let admissions: [SharedResource] + private let resourcesByIdentity: [SharedResourceIdentity: SharedResource] + private let admissionsByRoot: [String: SharedResource] let requestedRoutes: Set let writable: Bool let requestedShared: Bool let absentRoots: [AbsentSharedRoot] - var installations: [SkillInstallationTarget] = [] + let installations: [SkillInstallationTarget] + private let installationAuthorities: [SkillInstallationTarget] var existingProjectRoot: ExistingProjectRoot? var projectRootDirectory: DirectoryHandle? private var scopeDirectory: DirectoryHandle? @@ -821,15 +879,21 @@ final class TransactionLockContext { init( store: StateStore, resources: [SharedResource], writable: Bool, requestedShared: Bool, absentRoots: [AbsentSharedRoot] = [], admissions: [SharedResource] = [], - requestedRoutes: Set = [] + requestedRoutes: Set = [], installations: [SkillInstallationTarget] = [] ) { scopeURL = store.directory.standardizedFileURL self.resources = resources self.admissions = admissions.isEmpty ? resources : admissions + resourcesByIdentity = Dictionary( + resources.map { ($0.identity, $0) }, uniquingKeysWith: { first, _ in first }) + admissionsByRoot = Dictionary( + self.admissions.map { ($0.route.root, $0) }, uniquingKeysWith: { first, _ in first }) self.requestedRoutes = requestedRoutes self.writable = writable self.requestedShared = requestedShared self.absentRoots = absentRoots + self.installations = installations + installationAuthorities = SkillInstallationTarget.distinctAuthorities(installations) } static var currentForDisplay: TransactionLockContext? { @@ -875,7 +939,7 @@ final class TransactionLockContext { func validateScope() throws { try existingProjectRoot?.validate() - for target in installations { try target.validateAuthority() } + for target in installationAuthorities { try target.validateAuthority() } guard let directory = scopeDirectory else { return } var info = stat() guard let descriptor = scopeDescriptor, let identity = scopeLockIdentity, @@ -894,9 +958,13 @@ final class TransactionLockContext { func resource(_ identity: SharedResourceIdentity? = nil) throws -> SharedResource { try validateScope() - guard identity != nil || resources.count == 1, - let resource = resources.first(where: { identity == nil || $0.identity == identity }) - else { + let resource = + if let identity { + resourcesByIdentity[identity] + } else { + resources.count == 1 ? resources.first : nil + } + guard let resource else { throw CoreError.invalidState("shared target is outside the held request footprint") } try resource.validate() @@ -904,10 +972,10 @@ final class TransactionLockContext { } func resource(for route: NativeTargetRoute) throws -> SharedResource { - guard let resource = admissions.first(where: { $0.route.root == route.root }) else { + guard let resource = admissionsByRoot[route.root] else { throw CoreError.invalidState("shared target is outside the held request footprint") } - try resource.validate() + if resource !== resourcesByIdentity[resource.identity] { try resource.validate() } return try self.resource(resource.identity) } @@ -1018,8 +1086,10 @@ extension StateStore { guard routes.allSatisfy({ $0.permits(scope) }) else { throw CoreError.unsafePath("registered native request belongs to another scope") } - for target in installations { + for target in SkillInstallationTarget.distinctAuthorities(installations) { try target.validateAuthority() + } + for target in installations { let current = try skillInstallationTarget(for: target.agent, named: target.name) guard current.scope.path.utf8.elementsEqual(target.scope.path.utf8), current.url.path.utf8.elementsEqual(target.url.path.utf8), @@ -1131,8 +1201,7 @@ extension StateStore { let context = TransactionLockContext( store: self, resources: resources.sorted { $0.identity < $1.identity }, writable: writable, requestedShared: requestedShared, absentRoots: absentRoots, - admissions: admissions, requestedRoutes: routes) - context.installations = installations + admissions: admissions, requestedRoutes: routes, installations: installations) context.createdAncestry = createdAncestry context.existingProjectRoot = existingRoot context.projectRootDirectory = projectRoot @@ -1220,7 +1289,7 @@ extension StateStore { current.footprint == target.footprint else { throw CoreError.invalidState("installation authority changed during admission") } } - for admission in context.admissions { try admission.validate() } + try SharedResource.validateAll(context.admissions) for resource in context.resources { if journal?.finalized != true && (context.writable || journal == nil) { try resource.inspect(journal: journal, scope: directory?.identity ?? "") @@ -1287,11 +1356,15 @@ extension StateStore { } func materializationReceiptKey(for path: String) throws -> String { + try materializationReceiptLocation(for: path).key + } + + func materializationReceiptLocation(for path: String) throws -> (path: String, key: String) { if let route = try TransactionPaths(store: self).coordinationRoute(for: path) { let resource = try TransactionLockContext.current(self).requiredResourceForRoute(route) - return resource.route.root + "/" + resource.identity.basename + return (resource.receiptPath, resource.route.root + "/" + resource.identity.basename) } - return path + return ("state/" + MaterializationReceipts.fileName, path) } } diff --git a/Sources/AgentsCore/PrivateMaterialization.swift b/Sources/AgentsCore/PrivateMaterialization.swift index afd2525..6e88b6f 100644 --- a/Sources/AgentsCore/PrivateMaterialization.swift +++ b/Sources/AgentsCore/PrivateMaterialization.swift @@ -368,7 +368,7 @@ extension StateStore { let metadataURL = resource.parent.url.appendingPathComponent(SharedResource.metadataName) .appendingPathComponent(resource.identity.directoryName) url = (resource.metadata?.url ?? metadataURL).appendingPathComponent("receipt") - receiptPath = resource.route.metadata + "/receipt" + receiptPath = resource.receiptPath } else { url = materializationReceiptURL receiptPath = "state/" + MaterializationReceipts.fileName diff --git a/Sources/AgentsCore/TransactionEvidence.swift b/Sources/AgentsCore/TransactionEvidence.swift index 3baa172..efab74a 100644 --- a/Sources/AgentsCore/TransactionEvidence.swift +++ b/Sources/AgentsCore/TransactionEvidence.swift @@ -1,6 +1,6 @@ import Foundation -struct FileObjectIdentity: Codable, Equatable, Sendable { +struct FileObjectIdentity: Codable, Hashable, Sendable { let device: UInt64 let inode: UInt64 let kind: mode_t diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index de1ef93..907e044 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -320,6 +320,26 @@ package struct SkillInstallationTarget { let authority: NativeRootAuthority let parentIdentity: FileObjectIdentity? + /// Coalesces identical parent checks without sharing a successful check across phases. + static func distinctAuthorities(_ targets: [Self]) -> [Self] { + struct Key: Hashable { + let loader: Data + let descendants: [Data] + let parent: Data + let identity: FileObjectIdentity? + } + var seen: Set = [] + return targets.filter { target in + seen.insert( + Key( + loader: Data(target.authority.loader.path.utf8), + descendants: target.authority.descendants.map { Data($0.utf8) }, + parent: Data(target.url.deletingLastPathComponent().path.utf8), + identity: target.parentIdentity) + ).inserted + } + } + func validateAuthority() throws { let parent = try authority.physicalDirectory() guard parent.path.utf8.elementsEqual(url.deletingLastPathComponent().path.utf8), @@ -349,7 +369,7 @@ extension StateStore { ? try DirectoryHandle(at: parent).objectIdentity : nil let url = parent.appendingPathComponent(name) let path = agent.rawValue + "/" + name - let route = try paths.coordinationRoute(for: path) + let route = try paths.installationCoordinationRoute(for: agent, target: url) return SkillInstallationTarget( url: url, footprint: Set(route.map { [$0] } ?? []), path: path, scope: directory, agent: agent, name: name, authority: authority, parentIdentity: identity) @@ -366,6 +386,12 @@ extension TransactionPaths { guard parts.count == 2, let agent = AgentID(rawValue: parts[0]) else { return nil } _ = try components(path) let target = try rootURL(parts[0]).appendingPathComponent(parts[1]) + return try installationCoordinationRoute(for: agent, target: target) + } + + fileprivate func installationCoordinationRoute(for agent: AgentID, target: URL) throws + -> NativeTargetRoute? + { guard let route = try NativeTargetRoute.userRoute(at: target, environment: store.environment) else { return nil } guard route.isContainer, route.knownReaders.contains(agent) else { diff --git a/Sources/AgentsCore/TransactionSession.swift b/Sources/AgentsCore/TransactionSession.swift index 5c96993..619bd3b 100644 --- a/Sources/AgentsCore/TransactionSession.swift +++ b/Sources/AgentsCore/TransactionSession.swift @@ -102,7 +102,7 @@ final class TransactionSession { func requireScope() throws { try TransactionLockContext.validateHeldScope(journal.scope) - for resource in resources { try resource.validate() } + try SharedResource.validateAll(resources) guard try DirectoryHandle(at: directory.url).identity == journal.scope else { throw CoreError.invalidState("transaction scope identity changed") } diff --git a/Tests/AgentsCoreTests/TransactionCostTests.swift b/Tests/AgentsCoreTests/TransactionCostTests.swift index 5b34375..b39093a 100644 --- a/Tests/AgentsCoreTests/TransactionCostTests.swift +++ b/Tests/AgentsCoreTests/TransactionCostTests.swift @@ -7,6 +7,105 @@ import Testing @Suite("Transaction I/O cost") struct TransactionCostTests { + @Test func mixedInstallationBatchKeepsEachTargetUnderItsRegisteredRoot() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let home = root.appendingPathComponent("home") + let loader = root.appendingPathComponent("claude") + let physical = root.appendingPathComponent("physical-claude") + try FileManager.default.createDirectory(at: physical, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: loader, withDestinationURL: physical) + let source = root.appendingPathComponent("source") + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true) + let bytes = Data("generated skill\n".utf8) + try bytes.write(to: source.appendingPathComponent("SKILL.md")) + let store = StateStore( + scope: .user, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: home, + environment: ["CLAUDE_CONFIG_DIR": loader.path])) + try store.save(declaration: Declaration(), resolved: ResolvedState()) + let agents = + Array(repeating: AgentID.codex, count: 16) + + Array(repeating: AgentID.claudeCode, count: 8) + let targets = try agents.enumerated().map { + try store.skillInstallationTarget(for: $0.element, named: "generated-\($0.offset)") + } + try store.withLock(installations: targets) { + let transaction = FileTransaction(store: store) + for target in targets { try transaction.replaceSkill(target, with: .link(source)) } + try transaction.commit() + } + for target in targets { + let installed = try #require(try FileSnapshot.read(at: target.url)) + #expect(installed.isSymbolicLink) + #expect(try Data(contentsOf: target.url.appendingPathComponent("SKILL.md")) == bytes) + let expected = + target.agent == .claudeCode + ? physical.appendingPathComponent("skills") : home.appendingPathComponent(".agents/skills") + #expect(target.url.deletingLastPathComponent().path == expected.path) + } + #expect( + !FileManager.default.fileExists( + atPath: store.directory.appendingPathComponent("transaction.json").path)) + } + + @Test func coincidentInstallationParentsRetainBothLoaderChecks() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let original = root.appendingPathComponent(".agents") + let redirected = root.appendingPathComponent("redirected") + let alias = root.appendingPathComponent(".claude") + for parent in [original, redirected] { + try FileManager.default.createDirectory( + at: parent.appendingPathComponent("skills"), withIntermediateDirectories: true) + } + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: original) + let source = root.appendingPathComponent("source") + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true) + try Data("generated skill\n".utf8).write(to: source.appendingPathComponent("SKILL.md")) + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: [:] + )) + try store.save(declaration: Declaration(), resolved: ResolvedState()) + let codex = try store.skillInstallationTarget(for: .codex, named: "codex-skill") + let claude = try store.skillInstallationTarget(for: .claudeCode, named: "claude-skill") + #expect(try #require(codex.parentIdentity) == claude.parentIdentity) + var moved = false + #expect(throws: CoreError.self) { + try store.withLock(installations: [codex, claude]) { + let transaction = FileTransaction(store: store) { point in + if point == TransactionCheckpoint.phase(.preparing).name { + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: redirected) + moved = true + } + } + try transaction.replaceSkill(codex, with: .link(source)) + try transaction.replaceSkill(claude, with: .link(source)) + try transaction.commit() + } + } + #expect(moved) + for parent in [original, redirected] { + for target in [codex, claude] { + let url = parent.appendingPathComponent("skills").appendingPathComponent(target.name) + #expect(try FileSnapshot.read(at: url) == nil) + } + } + let journal = store.directory.appendingPathComponent("transaction.json") + #expect(FileManager.default.fileExists(atPath: journal.path)) + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: original) + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + #expect(!FileManager.default.fileExists(atPath: journal.path)) + for parent in [original, redirected] { + #expect(try FileManager.default.contentsOfDirectory(atPath: parent.path + "/skills").isEmpty) + } + } + @Test func containersOnOneDeviceShareOneProbe() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } From f918330a477de85409741f05bf595f8149e4e084 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:58:49 +0800 Subject: [PATCH 159/171] perf: reduce repeated journal decoding and ancestry checks --- Sources/AgentsCore/LedgerAdmission.swift | 9 +++- .../AgentsCore/NativeTargetCoordination.swift | 40 ++++++++++++++- .../LedgerWireSpellingTests.swift | 32 ++++++++++++ .../TransactionCostTests.swift | 51 +++++++++++++++++++ 4 files changed, 130 insertions(+), 2 deletions(-) diff --git a/Sources/AgentsCore/LedgerAdmission.swift b/Sources/AgentsCore/LedgerAdmission.swift index 8af659c..716a460 100644 --- a/Sources/AgentsCore/LedgerAdmission.swift +++ b/Sources/AgentsCore/LedgerAdmission.swift @@ -76,7 +76,14 @@ package enum LedgerAdmission { guard range.count <= limits.keyBytes else { throw CoreError.invalidState("ledger key budget") } - let key = try JSONDecoder().decode(String.self, from: data.subdata(in: range)) + let contents = data[(range.lowerBound + 1)..<(range.upperBound - 1)] + // The whole input is valid UTF-8 and string() has checked the token's grammar. + let key = + if contents.contains(92) { + try JSONDecoder().decode(String.self, from: data.subdata(in: range)) + } else { + String(decoding: contents, as: UTF8.self) + } guard keys.insert(key).inserted else { throw CoreError.invalidState("duplicate ledger key") } diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index cbbf001..066e1d9 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -681,7 +681,7 @@ final class SharedResource { try resource.validateParent() parents[resource.parentValidationKey] = resource.ancestry } - try resource.validateMetadata() + try resource.validateMetadataWithValidatedParent() } } @@ -719,6 +719,44 @@ final class SharedResource { } } + private func validateMetadataWithValidatedParent() throws { + guard let metadata else { return } + let name = metadata.url.lastPathComponent + guard let metadataAccess, let directories = metadataAncestry?.directories, + ancestry.directories.count == parent.url.pathComponents.count, + directories.count == ancestry.directories.count + 2, + directories.dropLast(2).elementsEqual(ancestry.directories), + let parentAccess = ancestry.directories.last, parentAccess.identity == identity.parent, + let base = try? parent.child(Self.metadataName), + let current = try? base.child(name) + else { + try validateMetadata() + return + } + + // The pass has checked the physical prefix. Reopen both private entries + // for each resource and check the namespace edges using each child's owner. + let leafAccess = try current.accessEvidence() + let baseAccess = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: base.descriptor, protectingOwner: leafAccess.owner) + let currentParentAccess = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: parent.descriptor, protectingOwner: baseAccess.owner) + let currentLeafAccess = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: current.descriptor, protectingOwner: geteuid()) + guard currentParentAccess == parentAccess, + baseAccess == directories[directories.count - 2], + leafAccess == directories.last, currentLeafAccess == leafAccess, + try parent.info(Self.metadataName).map(FileObjectIdentity.init) == baseAccess.identity, + try base.info(name).map(FileObjectIdentity.init) == leafAccess.identity + else { + throw CoreError.invalidState("filesystem access ancestry changed during preparation") + } + guard try FileAccessEvidence.requirePrivate(descriptor: current.descriptor) == metadataAccess + else { + throw CoreError.invalidState("filesystem access changed during preparation") + } + } + func reservation() throws -> SharedReservation? { try validate() guard let metadata, try metadata.info("reservation") != nil else { return nil } diff --git a/Tests/AgentsCoreTests/LedgerWireSpellingTests.swift b/Tests/AgentsCoreTests/LedgerWireSpellingTests.swift index e896ff6..df52069 100644 --- a/Tests/AgentsCoreTests/LedgerWireSpellingTests.swift +++ b/Tests/AgentsCoreTests/LedgerWireSpellingTests.swift @@ -88,6 +88,38 @@ struct LedgerWireSpellingTests { } } + @Test func literalAndEscapedKeysShareDuplicateDetection() throws { + try LedgerAdmission.check(Data(#"{"é":1,"":2}"#.utf8), limits: .standard) + for object in [ + #"{ "key": 1, "\u006bey": 2 }"#, + #"{ "é": 1, "\u00e9": 2 }"#, + "{\"é\":1,\"e\u{301}\":2}", + ] { + #expect(throws: CoreError.invalidState("duplicate ledger key")) { + try LedgerAdmission.check(Data(object.utf8), limits: .standard) + } + } + } + + @Test func keySpellingPreservesWireSizeAndDecodedBudgetSelection() throws { + var limits = LedgerLimits.standard + limits.keyBytes = 4 + try LedgerAdmission.check(Data(#"{"é":0}"#.utf8), limits: limits) + #expect(throws: CoreError.invalidState("ledger key budget")) { + try LedgerAdmission.check(Data(#"{"\u00e9":0}"#.utf8), limits: limits) + } + limits = .standard + limits.entries = 1 + #expect(throws: CoreError.invalidState("ledger entry budget")) { + try LedgerAdmission.check(Data(#"{"\u0065ntries":[1,2]}"#.utf8), limits: limits) + } + limits.objectBytes = 2 + #expect(throws: CoreError.invalidState("ledger content byte budget")) { + try LedgerAdmission.check( + Data(#"{"\u0063ontentObjects":{"data":"YWJj"}}"#.utf8), limits: limits) + } + } + @Test func invalidEscapedContentCannotBypassAdmission() throws { for spelling in [#"Y\nQ=="#, #"YQ\u003dA"#, #"\uD800Q=="#, #"YQ===\u003d"#] { let bytes = Data((#"{"contentObjects":{"first":""# + spelling + #""}}"#).utf8) diff --git a/Tests/AgentsCoreTests/TransactionCostTests.swift b/Tests/AgentsCoreTests/TransactionCostTests.swift index b39093a..7e48c7c 100644 --- a/Tests/AgentsCoreTests/TransactionCostTests.swift +++ b/Tests/AgentsCoreTests/TransactionCostTests.swift @@ -7,6 +7,57 @@ import Testing @Suite("Transaction I/O cost") struct TransactionCostTests { + enum SharedMetadataDrift: CaseIterable { + case siblingReplacement, siblingRemoval, siblingPermissions, baseReplacement + } + + @Test(arguments: SharedMetadataDrift.allCases) + func sharedMetadataValidationRejectsDriftBetweenPasses(_ drift: SharedMetadataDrift) throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let loader = root.appendingPathComponent("generated-claude") + let store = StateStore( + scope: .user, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root, + environment: ["CLAUDE_CONFIG_DIR": loader.path])) + let resources = try ["first", "second"].map { name in + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: name) + return try SharedResource(store: store, route: route, create: true) + } + try SharedResource.validateAll(resources) + let sibling = try #require(resources[1].metadata).url + defer { + if drift == .siblingPermissions { + try? FileManager.default.setAttributes( + [.posixPermissions: 0o700], ofItemAtPath: sibling.path) + } + } + let displaced = root.appendingPathComponent("displaced") + switch drift { + case .siblingReplacement, .siblingRemoval: + try FileManager.default.moveItem(at: sibling, to: displaced) + if drift == .siblingReplacement { + try FileManager.default.createDirectory( + at: sibling, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + } + case .siblingPermissions: + try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: sibling.path) + case .baseReplacement: + let base = sibling.deletingLastPathComponent() + try FileManager.default.moveItem(at: base, to: displaced) + try FileManager.default.createDirectory( + at: base, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + for resource in resources { + let metadata = try #require(resource.metadata) + try FileManager.default.moveItem( + at: displaced.appendingPathComponent(metadata.url.lastPathComponent), to: metadata.url) + } + } + if drift != .baseReplacement { try SharedResource.validateAll([resources[0]]) } + #expect(throws: CoreError.self) { try SharedResource.validateAll(resources) } + } + @Test func mixedInstallationBatchKeepsEachTargetUnderItsRegisteredRoot() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } From 63df417e4d671c8c45494049d56a84813094c354 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:24:45 +0800 Subject: [PATCH 160/171] test: signal Linux worker readiness before its leader exits --- Tests/ComponentsTests/MCPConnectionTests.swift | 1 + Tests/MCPTestProcess/main.swift | 18 +++++------------- 2 files changed, 6 insertions(+), 13 deletions(-) diff --git a/Tests/ComponentsTests/MCPConnectionTests.swift b/Tests/ComponentsTests/MCPConnectionTests.swift index 5bd6aa0..3ad7c74 100644 --- a/Tests/ComponentsTests/MCPConnectionTests.swift +++ b/Tests/ComponentsTests/MCPConnectionTests.swift @@ -235,6 +235,7 @@ private func runConnection(_ input: MCPConnectionInput, limits: MCPConnectionLim let ready = await fixture.waitFor { var exited = false guard platform_duplex_observe(process.identifier, &exited) == 0, exited, + fixture.text("holder-ready") == "ready", let child = fixture.text("descendant-pid").flatMap({ Int32($0) }), let childState = state(child) else { return false } diff --git a/Tests/MCPTestProcess/main.swift b/Tests/MCPTestProcess/main.swift index 8f806da..ae84b32 100644 --- a/Tests/MCPTestProcess/main.swift +++ b/Tests/MCPTestProcess/main.swift @@ -92,22 +92,14 @@ if scenario == "holder" || scenario == "ignore-input" || scenario == "blocked-in alarm(10) _ = signal(SIGTERM, SIG_IGN) var worker: pthread_t = 0 - let context = UnsafeMutableRawPointer(strdup(root.path)) let created = pthread_create( &worker, nil, - { context in - guard let context else { return nil } - let path = String(cString: context.assumingMemoryBound(to: CChar.self)) - free(context) - try? "ready".write( - to: URL(fileURLWithPath: path).appendingPathComponent("holder-ready"), - atomically: true, encoding: .utf8) + { @Sendable _ in while true { _ = sleep(1) } - }, context) - if created != 0 { - free(context) - exit(2) - } + }, nil) + if created != 0 { exit(2) } + try "ready".write( + to: root.appendingPathComponent("holder-ready"), atomically: true, encoding: .utf8) pthread_exit(nil) } #endif From f2948971377bb9ae16f4a6b31e84ab83f8e22cd6 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:31:41 +0800 Subject: [PATCH 161/171] perf: reuse committed ledger roots during inventory and planning --- Sources/AgentsCore/LedgerStateStore.swift | 14 +- Sources/AgentsSkills/SkillLifecycle.swift | 8 +- Sources/AgentsSkills/SkillOperations.swift | 39 +++--- Sources/AgentsUpdates/UpdatePlan.swift | 78 ++++++----- .../AgentsUpdates/UpdateReadLocations.swift | 16 ++- Sources/AgentsUpdates/UpdateReporting.swift | 9 +- Sources/Components/ArtifactAggregation.swift | 125 ++++++++++-------- .../Components/DeploymentConstruction.swift | 6 +- .../ConsumerLifecycleRegressionTests.swift | 34 +++++ 9 files changed, 204 insertions(+), 125 deletions(-) diff --git a/Sources/AgentsCore/LedgerStateStore.swift b/Sources/AgentsCore/LedgerStateStore.swift index 7422456..cf428b9 100644 --- a/Sources/AgentsCore/LedgerStateStore.swift +++ b/Sources/AgentsCore/LedgerStateStore.swift @@ -27,6 +27,12 @@ extension StateStore { } package var ledgerRoots: [String: URL] { + ledgerRoots(recordedIn: try? readLedger()) + } + + /// Resolves roots using the committed ledger already read for this operation. + /// These URLs locate content; transaction admission independently checks filesystem identity. + package func ledgerRoots(recordedIn committed: ResolvedLedger?) -> [String: URL] { var roots = [ "project": environment.projectDirectory, "home": environment.homeDirectory, "state": directory, @@ -52,8 +58,8 @@ extension StateStore { where route.isNamed && route.permits(scope) { roots[route.root] = try? route.physicalDirectory(environment) } - if let ledger = try? readLedger() { - for deployment in ledger.deployments { + if let committed { + for deployment in committed.deployments { guard deployment.target.kind == .registered, let key = deployment.target.root, let route = NativeTargetRoute.targetRoute(key), route.isNamed, route.permits(scope), deployment.target.path.utf8.elementsEqual(route.basename.utf8), @@ -105,7 +111,7 @@ extension StateStore { /// Ref cleanup consumes the committed closure after physical journal recovery. func retentionReferences() throws -> RetentionReferences { guard let bytes = try ledgerBytes(limits: .standard) else { return RetentionReferences() } - return try RetentionReferences( - ledger: ResolvedLedgerCodec.decode(bytes, limits: .standard), roots: ledgerRoots) + let committed = try ResolvedLedgerCodec.decode(bytes, limits: .standard) + return try RetentionReferences(ledger: committed, roots: ledgerRoots(recordedIn: committed)) } } diff --git a/Sources/AgentsSkills/SkillLifecycle.swift b/Sources/AgentsSkills/SkillLifecycle.swift index 802733d..70ed49f 100644 --- a/Sources/AgentsSkills/SkillLifecycle.swift +++ b/Sources/AgentsSkills/SkillLifecycle.swift @@ -125,7 +125,8 @@ package final class SkillLifecycle { /// Capture all managed slots before admitting physical reads; never recover during inventory. static func withInstallationReadLock( - store: StateStore, onPendingRecovery: (() throws -> T)? = nil, _ body: () throws -> T + store: StateStore, onPendingRecovery: (() throws -> T)? = nil, + _ body: (ResolvedLedger) throws -> T ) throws -> T { var targets: [String: SkillInstallationTarget] = [:] while true { @@ -133,11 +134,12 @@ package final class SkillLifecycle { return try store.withReadLock( onPendingRecovery: onPendingRecovery, installations: Array(targets.values) ) { - let required = try installationTargets(store.readLedger(), store: store) + let ledger = try store.readLedger() + let required = try installationTargets(ledger, store: store) guard Set(required.keys).isSubset(of: Set(targets.keys)) else { throw RequiredInstallations(targets: required) } - return try body() + return try body(ledger) } } catch let required as RequiredInstallations { targets.merge(required.targets, uniquingKeysWith: { _, next in next }) diff --git a/Sources/AgentsSkills/SkillOperations.swift b/Sources/AgentsSkills/SkillOperations.swift index 87b13a1..266e55a 100644 --- a/Sources/AgentsSkills/SkillOperations.swift +++ b/Sources/AgentsSkills/SkillOperations.swift @@ -16,15 +16,15 @@ public enum SkillOperations { environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> [InstalledSkill] { let store = StateStore(scope: scope, environment: environment) - return try SkillLifecycle.withInstallationReadLock(store: store) { + return try SkillLifecycle.withInstallationReadLock(store: store) { ledger in _ = try store.readDeclaration() - let ledger = try store.readLedger() - return try managedInventory(store: store, ledger: ledger, agents: agents) + let roots = store.ledgerRoots(recordedIn: ledger) + return try managedInventory(store: store, ledger: ledger, roots: roots, agents: agents) } } private static func managedInventory( - store: StateStore, ledger: ResolvedLedger, agents: [AgentID]? + store: StateStore, ledger: ResolvedLedger, roots: [String: URL], agents: [AgentID]? ) throws -> [InstalledSkill] { var result: [InstalledSkill] = [] for deployment in ledger.deployments where deployment.route == "agents/skill@1" { @@ -34,7 +34,7 @@ public enum SkillOperations { let resource = component.resources.first.flatMap({ ledger.resources[$0] }) else { continue } let mode = lowering.layout.object?["mode"]?.text.flatMap(InstallMode.init(rawValue:)) ?? .copy - let target = try deployment.target.resolve(roots: store.ledgerRoots) + let target = try deployment.target.resolve(roots: roots) let present = FileManager.default.fileExists( atPath: target.appendingPathComponent("SKILL.md").path) var status: InstalledSkillStatus = @@ -63,7 +63,7 @@ public enum SkillOperations { InstalledSkill( name: PathSafety.sanitizeName(component.name), agent: agent, scope: store.scope, path: target.path, - sourceIdentity: try ledger.sourceIdentity(component.source, roots: store.ledgerRoots), + sourceIdentity: try ledger.sourceIdentity(component.source, roots: roots), isInstalled: present, status: status, mode: mode)) } } @@ -78,15 +78,16 @@ public enum SkillOperations { environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> [InstalledSkill] { let store = StateStore(scope: scope, environment: environment) - return try SkillLifecycle.withInstallationReadLock(store: store) { + return try SkillLifecycle.withInstallationReadLock(store: store) { ledger in _ = try store.readDeclaration() - let ledger = try store.readLedger() - var result = try managedInventory(store: store, ledger: ledger, agents: agents).filter { - $0.isInstalled - && (try? Discovery.parseSkill( - at: URL(fileURLWithPath: $0.path).appendingPathComponent("SKILL.md"), - includeInternal: true)) != nil - } + let roots = store.ledgerRoots(recordedIn: ledger) + var result = try managedInventory(store: store, ledger: ledger, roots: roots, agents: agents) + .filter { + $0.isInstalled + && (try? Discovery.parseSkill( + at: URL(fileURLWithPath: $0.path).appendingPathComponent("SKILL.md"), + includeInternal: true)) != nil + } for agent in agents ?? AgentID.allCases { let roots = scope == .project @@ -138,10 +139,12 @@ public enum SkillOperations { path: store.directory.path) ]) }, - { + { ledger in let declaration = try store.readDeclaration() - let ledger = try store.readLedger() - var checks = try managedInventory(store: store, ledger: ledger, agents: agents).filter { + let roots = store.ledgerRoots(recordedIn: ledger) + var checks = try managedInventory( + store: store, ledger: ledger, roots: roots, agents: agents + ).filter { $0.status != .installed && $0.status != .editLinked }.map { DoctorCheck( @@ -153,7 +156,7 @@ public enum SkillOperations { let id = try source.identity(environment: environment) let skills = try ledger.components.values.filter { guard $0.kind == "skills", !$0.recipients.isEmpty else { return false } - return try ledger.sourceIdentity($0.source, roots: store.ledgerRoots) == id + return try ledger.sourceIdentity($0.source, roots: roots) == id } guard !skills.isEmpty else { continue } if source.kind == .local { diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 73d9a28..486d73b 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -17,6 +17,7 @@ final class UpdatePlan { let report: CombinedUpdateReport private let store: StateStore private let baseline: StatePrecondition + private let previous: ResolvedLedger private let next: ResolvedLedger private let watch: WatchState private let declarationChange: DeclarationChange? @@ -38,8 +39,9 @@ final class UpdatePlan { let importInputs = try (request.importPreparation?.capture() ?? []) + catalogInputs let baseline = try StatePrecondition(store: store) let previous = try store.readLedger(prepared: baseline) + let roots = store.ledgerRoots(recordedIn: previous) let instructionReferences = try resolveSelection( - &request, ledger: previous, store: store, baseline: baseline) + &request, ledger: previous, store: store, roots: roots, baseline: baseline) let restoringRequest: Bool if case .restore = request.operation { restoringRequest = true @@ -78,10 +80,10 @@ final class UpdatePlan { restoring = false try LedgerImpact.requireEditable( previous, kinds: request.kinds ?? Set(DeclaredComponentKind.allCases), - names: Set(request.names), roots: store.ledgerRoots, + names: Set(request.names), roots: roots, selectedIdentities: request.selectedIdentities) candidate = try removing( - request, from: declaration, ledger: previous, store: store, + request, from: declaration, ledger: previous, store: store, roots: roots, selectedInstructionReferences: instructionReferences) change = try store.planDeclaration(candidate, replacing: declaration, prepared: baseline) } @@ -94,7 +96,7 @@ final class UpdatePlan { guard let component = previous.components[$0.component], component.kind == "instructions", component.group == nil else { return nil } - return try LedgerImpact.identity(component, ledger: previous, roots: store.ledgerRoots) + return try LedgerImpact.identity(component, ledger: previous, roots: roots) }) } else { retargetedInstructions = [] @@ -105,11 +107,12 @@ final class UpdatePlan { guard routes.isSubset(of: admitted), Set(required.keys).isSubset(of: Set(installations.keys)) else { throw RequiredRoutes(routes: routes, installations: required) } return try LedgerReplay.withLockedResources( - previous, store: store, roots: store.ledgerRoots, limits: .standard + previous, store: store, roots: roots, limits: .standard ) { artifacts, resources, workspace in try body( UpdatePlan( - request: request, store: store, baseline: baseline, previous: previous, next: previous, + request: request, store: store, roots: roots, baseline: baseline, previous: previous, + next: previous, watch: watch, change: nil, artifacts: artifacts, resources: resources, workspace: workspace, decisionInputs: [], originalInputs: [], @@ -144,7 +147,7 @@ final class UpdatePlan { let identity = try source.identity(environment: store.environment) let existing = try previous.components.values.filter { component in guard component.kind == "skills", component.group == nil else { return false } - return try previous.sourceIdentity(component.source, roots: store.ledgerRoots) == identity + return try previous.sourceIdentity(component.source, roots: roots) == identity }.map { PathSafety.sanitizeName($0.name) }.sorted() let selected = request.names.filter { name in !previous.components.values.contains { $0.kind == "skills" && $0.name == name } @@ -172,7 +175,7 @@ final class UpdatePlan { } } let impact = try LedgerImpact( - ledger: previous, roots: store.ledgerRoots, + ledger: previous, roots: roots, kinds: request.kinds ?? Set(DeclaredComponentKind.allCases), names: Set(request.names), updating: updating, selectedIdentities: request.selectedIdentities) #if os(macOS) @@ -207,7 +210,7 @@ final class UpdatePlan { let frozen = try LedgerFreeze.freezeWithSources( linked, session: session, locations: .init(sources: locations), limits: .standard) if let expected = request.expectedDiscoveryFingerprint, - expected != (try LedgerImpact.discoveryFingerprint(frozen.ledger, roots: store.ledgerRoots)) + expected != (try LedgerImpact.discoveryFingerprint(frozen.ledger, roots: roots)) { throw CoreError.invalidState("discovered source content changed; refresh discovery") } @@ -220,11 +223,11 @@ final class UpdatePlan { let kinds = request.kinds ?? Set(DeclaredComponentKind.allCases) try LedgerImpact.requireProtected( previous: previous, next: native, kinds: kinds, names: Set(request.names), - roots: store.ledgerRoots, selectedIdentities: request.selectedIdentities, + roots: roots, selectedIdentities: request.selectedIdentities, retargetedInstructions: retargetedInstructions) } let complete = try DeploymentConstruction.complete( - native, linked: linked, store: store, previous: previous, platform: platform) + native, linked: linked, store: store, previous: previous, platform: platform, roots: roots) let required = try SkillLifecycle.installationTargets(previous, store: store).merging( SkillLifecycle.installationTargets(complete.ledger, store: store), uniquingKeysWith: { _, next in next }) @@ -238,12 +241,14 @@ final class UpdatePlan { } } try checkpoint("plan.skills") + let roots = store.ledgerRoots(recordedIn: previous) return try LedgerReplay.withPreparedLowerings( - complete.ledger, store: store, roots: store.ledgerRoots, limits: .standard + complete.ledger, store: store, roots: roots, limits: .standard ) { next, artifacts, resources, workspace in try body( UpdatePlan( - request: request, store: store, baseline: baseline, previous: previous, next: next, + request: request, store: store, roots: roots, baseline: baseline, previous: previous, + next: next, watch: watch, change: change, artifacts: artifacts, resources: resources, workspace: workspace, decisionInputs: complete.inputs, originalInputs: originals + importInputs, @@ -254,7 +259,7 @@ final class UpdatePlan { } private init( - request: UpdateRequest, store: StateStore, baseline: StatePrecondition, + request: UpdateRequest, store: StateStore, roots: [String: URL], baseline: StatePrecondition, previous: ResolvedLedger, next: ResolvedLedger, watch: WatchState, change: DeclarationChange?, artifacts: [ReplayedArtifact], resources: [String: URL], workspace: URL, @@ -264,6 +269,7 @@ final class UpdatePlan { ) throws { self.store = store self.baseline = baseline + self.previous = previous self.watch = watch declarationChange = change self.checkpoint = checkpoint @@ -272,7 +278,8 @@ final class UpdatePlan { ledger: next, resources: resources, decisions: decisionInputs, originals: originalInputs) aggregation = try ArtifactAggregation( ledger: next, previous: previous, artifacts: artifacts, - resources: resources, workspace: workspace, store: store, replace: request.replace, + resources: resources, workspace: workspace, store: store, roots: roots, + replace: request.replace, changingAccess: request.changingAccess, kinds: request.kinds, names: Set(request.names), selectedIdentities: request.selectedIdentities, installations: installations, retargetedInstructions: retargetedInstructions) @@ -300,11 +307,11 @@ final class UpdatePlan { self.next = aggregation.ledger try self.next.validate() let lockMissing = try baseline.bytes(for: store.resolvedURL) == nil - let before = try previous.domainProjection(roots: store.ledgerRoots) - let after = try self.next.domainProjection(roots: store.ledgerRoots) + let before = try previous.domainProjection(roots: roots) + let after = try self.next.domainProjection(roots: roots) let allResults = try UpdateReporting.skills( previous: previous, next: self.next, resources: resources, - changes: aggregation.changes, store: store, lockMissing: lockMissing, + changes: aggregation.changes, store: store, roots: roots, lockMissing: lockMissing, included: request.kinds == nil || request.kinds!.contains(.skills), selectedIdentities: request.selectedIdentities, names: Set(request.names)) let results = @@ -384,7 +391,7 @@ final class UpdatePlan { } let readPaths = try UpdateOperations.readLocations( - declarations: readDeclarations, ledgers: [previous, self.next], store: store) + declarations: readDeclarations, ledgers: [previous, self.next], store: store, roots: roots) + decisionInputs.map(\.url) + installations.map(\.url) let finalNext = self.next report = CombinedUpdateReport( @@ -403,14 +410,14 @@ final class UpdatePlan { let ledger = finalNext.components[owner] == nil ? previous : finalNext return try identities.contains( LedgerImpact.identity( - ledger.components[owner]!, ledger: ledger, roots: store.ledgerRoots)) + ledger.components[owner]!, ledger: ledger, roots: roots)) } }.map { change in let owner = change.deployment.owners[0] let ledger = finalNext.components[owner] == nil ? previous : finalNext let component = ledger.components[owner]! return ComponentUpdateChange( - sourceIdentity: try ledger.sourceIdentity(component.source, roots: store.ledgerRoots), + sourceIdentity: try ledger.sourceIdentity(component.source, roots: roots), revision: component.revision, version: component.version, format: change.deployment.route, ownership: change.deployment.ownership.rawValue, resources: component.resources.compactMap { ledger.resources[$0] }.map { resource in @@ -453,7 +460,8 @@ final class UpdatePlan { try aggregation.requireOwnership() try inputs.validate() if report.hasChanges { - var references = try RetentionReferences(ledger: next, roots: store.ledgerRoots) + let roots = store.ledgerRoots(recordedIn: previous) + var references = try RetentionReferences(ledger: next, roots: roots) try references.include(watch: watch) let cache = SourceCache(store: store, checkpoint: checkpoint) try cache.retain(references: references) @@ -463,7 +471,9 @@ final class UpdatePlan { try inputs.validate() let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) transaction.requireUnchanged(since: baseline, aggregation, inputs) - try aggregation.stage(transaction: transaction, provider: provider) + try aggregation.stage( + transaction: transaction, provider: provider, roots: store.ledgerRoots(recordedIn: previous) + ) try store.stageDeclaration(declarationChange, in: transaction, prepared: baseline) // Empty scopes need no lock file; a declaration edit always accompanies first deployment. if try store.declarationBytes(prepared: baseline) != nil || declarationChange != nil { @@ -521,7 +531,7 @@ final class UpdatePlan { private static func resolveSelection( _ request: inout UpdateRequest, ledger: ResolvedLedger, store: StateStore, - baseline: StatePrecondition + roots: [String: URL], baseline: StatePrecondition ) throws -> Set? { let kinds = request.kinds ?? Set(DeclaredComponentKind.allCases) func name(_ c: LedgerComponent) -> String { @@ -549,9 +559,9 @@ final class UpdatePlan { where component.kind == "instructions" && component.group == nil && component.name == section.name { - if try ledger.sourceIdentity(component.source, roots: store.ledgerRoots) == source { + if try ledger.sourceIdentity(component.source, roots: roots) == source { selected.insert( - try LedgerImpact.identity(component, ledger: ledger, roots: store.ledgerRoots)) + try LedgerImpact.identity(component, ledger: ledger, roots: roots)) } } } @@ -561,7 +571,7 @@ final class UpdatePlan { for requested in request.names { let matches = try ledger.components.values.filter { kinds.contains(DeclaredComponentKind(rawValue: $0.kind)!) && name($0) == requested - }.map { try LedgerImpact.identity($0, ledger: ledger, roots: store.ledgerRoots) } + }.map { try LedgerImpact.identity($0, ledger: ledger, roots: roots) } guard Set(matches).count <= 1 else { throw CoreError.invalidState( "component name is ambiguous; select a component from inspection: " + requested) @@ -590,7 +600,7 @@ final class UpdatePlan { throw CoreError.invalidState("inspection changed; refresh component selection") } let entries = try ledger.components.filter { - try LedgerImpact.identity($0.value, ledger: ledger, roots: store.ledgerRoots) + try LedgerImpact.identity($0.value, ledger: ledger, roots: roots) == selection.identity } guard let entry = entries.first, @@ -644,7 +654,7 @@ final class UpdatePlan { private static func removing( _ request: UpdateRequest, from declaration: Declaration, ledger: ResolvedLedger, - store: StateStore, selectedInstructionReferences: Set? + store: StateStore, roots: [String: URL], selectedInstructionReferences: Set? ) throws -> Declaration { var result = declaration let names = Set(request.names) @@ -668,9 +678,9 @@ final class UpdatePlan { } if try ledger.components.values.contains(where: { c in try c.kind == "instructions" && c.name == section.name - && ledger.sourceIdentity(c.source, roots: store.ledgerRoots) == source + && ledger.sourceIdentity(c.source, roots: roots) == source && identities.contains( - LedgerImpact.identity(c, ledger: ledger, roots: store.ledgerRoots)) + LedgerImpact.identity(c, ledger: ledger, roots: roots)) }) { instructionReferences.insert(section.reference) } @@ -685,8 +695,8 @@ final class UpdatePlan { let source = try? declaration.sources[alias]?.identity(environment: store.environment) let matches = ledger.components.values.contains { c in c.kind == "skills" - && (try? ledger.sourceIdentity(c.source, roots: store.ledgerRoots)) == source - && (try? LedgerImpact.identity(c, ledger: ledger, roots: store.ledgerRoots)).map( + && (try? ledger.sourceIdentity(c.source, roots: roots)) == source + && (try? LedgerImpact.identity(c, ledger: ledger, roots: roots)).map( identities.contains) == true } if !matches { return component } @@ -705,7 +715,7 @@ final class UpdatePlan { for name in names { let current = ledger.components.values.first { $0.kind == "skills" && PathSafety.sanitizeName($0.name) == name - && (try? ledger.sourceIdentity($0.source, roots: store.ledgerRoots)) + && (try? ledger.sourceIdentity($0.source, roots: roots)) == (try? declaration.sources[alias]?.identity(environment: store.environment)) } var overrides = original.overrides ?? [:] diff --git a/Sources/AgentsUpdates/UpdateReadLocations.swift b/Sources/AgentsUpdates/UpdateReadLocations.swift index 51b2c0a..4e4dde3 100644 --- a/Sources/AgentsUpdates/UpdateReadLocations.swift +++ b/Sources/AgentsUpdates/UpdateReadLocations.swift @@ -6,7 +6,8 @@ import Foundation extension UpdateOperations { /// Only durable inputs are exposed; replay workspaces and borrowed source URLs stay private. static func readLocations( - declarations: [Declaration], ledgers: [ResolvedLedger], store: StateStore + declarations: [Declaration], ledgers: [ResolvedLedger], store: StateStore, + roots admittedRoots: [String: URL]? = nil ) throws -> [URL] { var paths = [store.declarationURL, store.resolvedURL, store.watchURL] let scopeRoot = store.scope == .user ? store.directory : store.environment.projectDirectory @@ -54,17 +55,18 @@ extension UpdateOperations { try collect(declaration.components) for group in declaration.groups { try collect(group.components) } } + let roots = admittedRoots ?? store.ledgerRoots for ledger in ledgers { func localRoot(_ id: String) throws -> URL? { guard let source = ledger.sources[id], source.kind == .local else { return nil } - if let location = source.location { return try location.resolve(roots: store.ledgerRoots) } + if let location = source.location { return try location.resolve(roots: roots) } if let container = source.container { return try localRoot(container) } return nil } let explicitSources = Set(ledger.sourceUses.map(\.source)) for (id, source) in ledger.sources { if let location = source.location { - let root = try location.resolve(roots: store.ledgerRoots) + let root = try location.resolve(roots: roots) // The linker's implicit live snapshot supplies provenance, not a whole-tree read. // Explicit local declarations above retain their independent whole-tree interests. let implicit = @@ -100,14 +102,16 @@ extension UpdateOperations { base: root, subpath: component.containerRoot ?? component.root)) } if let value = component.payload.object?["localAppend"] { - paths.append(try LedgerLocation(ledgerValue: value).resolve(roots: store.ledgerRoots)) + paths.append(try LedgerLocation(ledgerValue: value).resolve(roots: roots)) } } for deployment in ledger.deployments { - paths.append(try deployment.target.resolve(roots: store.ledgerRoots)) + paths.append(try deployment.target.resolve(roots: roots)) } for (id, resource) in ledger.resources { - paths.append(try ArtifactAggregation.resourceDestination(id, ledger: ledger, store: store)) + paths.append( + try ArtifactAggregation.resourceDestination( + id, ledger: ledger, store: store, roots: roots)) if let root = try localRoot(resource.source) { let selected = try PathSafety.resolvedChild(base: root, subpath: resource.path) paths.append(selected) diff --git a/Sources/AgentsUpdates/UpdateReporting.swift b/Sources/AgentsUpdates/UpdateReporting.swift index 936d6d6..03317f7 100644 --- a/Sources/AgentsUpdates/UpdateReporting.swift +++ b/Sources/AgentsUpdates/UpdateReporting.swift @@ -8,7 +8,8 @@ import Foundation enum UpdateReporting { static func skills( previous: ResolvedLedger, next: ResolvedLedger, resources: [String: URL], - changes: [AggregatedChange], store: StateStore, lockMissing: Bool, included: Bool, + changes: [AggregatedChange], store: StateStore, roots: [String: URL], lockMissing: Bool, + included: Bool, selectedIdentities: Set? = nil, names: Set = [] ) throws -> [UpdateResult] { guard included else { return [] } @@ -23,7 +24,7 @@ enum UpdateReporting { where component.kind == "skills" && !component.recipients.isEmpty { if let selectedIdentities, !selectedIdentities.contains( - try LedgerImpact.identity(component, ledger: ledger, roots: store.ledgerRoots)) + try LedgerImpact.identity(component, ledger: ledger, roots: roots)) { continue } @@ -33,9 +34,9 @@ enum UpdateReporting { guard let id = component.resources.first, let resource = ledger.resources[id] else { continue } - let source = try ledger.sourceIdentity(component.source, roots: store.ledgerRoots) + let source = try ledger.sourceIdentity(component.source, roots: roots) let producer = try ledger.sourceIdentity( - component.declaringSource, roots: store.ledgerRoots) + component.declaringSource, roots: roots) let identity = try ResolvedLedgerCodec.digest( LedgerValue(object: [ "producer": LedgerValue(producer), "source": .init(source), diff --git a/Sources/Components/ArtifactAggregation.swift b/Sources/Components/ArtifactAggregation.swift index 7e1a644..e97d002 100644 --- a/Sources/Components/ArtifactAggregation.swift +++ b/Sources/Components/ArtifactAggregation.swift @@ -29,6 +29,7 @@ package final class ArtifactAggregation: PreparedEvidence { package private(set) var changes: [AggregatedChange] = [] package private(set) var fingerprints: [String] = [] private let store: StateStore + private let roots: [String: URL] private let resources: [String: URL] private let replace: Bool private let selectedKinds: Set? @@ -58,7 +59,8 @@ package final class ArtifactAggregation: PreparedEvidence { package init( ledger: ResolvedLedger, previous: ResolvedLedger, artifacts: [ReplayedArtifact], - resources: [String: URL], workspace: URL, store: StateStore, replace: Bool, + resources: [String: URL], workspace: URL, store: StateStore, roots: [String: URL], + replace: Bool, changingAccess: Bool, kinds: Set? = nil, names: Set = [], selectedIdentities: Set? = nil, @@ -66,6 +68,7 @@ package final class ArtifactAggregation: PreparedEvidence { ) throws { self.ledger = ledger self.store = store + self.roots = roots self.resources = resources self.replace = replace for target in installations { skillTargets[target.url.path] = target } @@ -112,7 +115,6 @@ package final class ArtifactAggregation: PreparedEvidence { resourceEvidence.append(try TargetPrecondition(capsule)) } } - let roots = store.ledgerRoots let artifacts = Dictionary(uniqueKeysWithValues: artifacts.map { ($0.name, $0) }) let affectedPaths = try Set( previous.deployments.filter { try selected($0, in: previous) }.map { @@ -370,12 +372,12 @@ package final class ArtifactAggregation: PreparedEvidence { } private func resourceDestination(_ id: String, in selected: ResolvedLedger? = nil) throws -> URL { - try Self.resourceDestination(id, ledger: selected ?? ledger, store: store) + try Self.resourceDestination(id, ledger: selected ?? ledger, store: store, roots: roots) } private func installationURL(_ deployment: LedgerDeployment) throws -> URL { guard deployment.route == "agents/skill@1" else { - return InstructionLocations.physical(try deployment.target.resolve(roots: store.ledgerRoots)) + return InstructionLocations.physical(try deployment.target.resolve(roots: roots)) } guard let agent = deployment.recipients.first else { throw CoreError.invalidState("missing skill recipient") @@ -387,14 +389,16 @@ package final class ArtifactAggregation: PreparedEvidence { return admitted.url } - package static func resourceDestination(_ id: String, ledger: ResolvedLedger, store: StateStore) - throws -> URL - { + package static func resourceDestination( + _ id: String, ledger: ResolvedLedger, store: StateStore, roots: [String: URL]? = nil + ) throws -> URL { guard let resource = ledger.resources[id] else { throw CoreError.invalidState("missing deployment resource") } - if let location = resource.location { return try location.resolve(roots: store.ledgerRoots) } - if let root = try gitDestination(resource, ledger: ledger, store: store) { + if let location = resource.location { + return try location.resolve(roots: roots ?? store.ledgerRoots) + } + if let root = try gitDestination(resource, ledger: ledger, store: store, roots: roots) { return root.appendingPathComponent(resource.path) } let base = store.cacheDirectory.appendingPathComponent( @@ -402,12 +406,8 @@ package final class ArtifactAggregation: PreparedEvidence { return base.appendingPathComponent(resource.support.isEmpty ? "payload" : resource.path) } - private func gitDestination(_ resource: LedgerResource, ledger: ResolvedLedger) throws -> URL? { - try Self.gitDestination(resource, ledger: ledger, store: store) - } - private static func gitDestination( - _ resource: LedgerResource, ledger: ResolvedLedger, store: StateStore + _ resource: LedgerResource, ledger: ResolvedLedger, store: StateStore, roots: [String: URL]? ) throws -> URL? { guard resource.kind == .git else { return nil } var sourceID = resource.source @@ -416,7 +416,7 @@ package final class ArtifactAggregation: PreparedEvidence { throw CoreError.invalidState("missing resource source") } return SourceCache(store: store).materializedURL( - sourceID: try ledger.sourceIdentity(sourceID, roots: store.ledgerRoots), + sourceID: try ledger.sourceIdentity(sourceID, roots: roots ?? store.ledgerRoots), revision: source.revision) } @@ -435,13 +435,13 @@ package final class ArtifactAggregation: PreparedEvidence { private func isSelected(_ id: String, in selected: ResolvedLedger) throws -> Bool { guard let c = selected.components[id] else { return false } if try retargetedInstructions.contains( - LedgerImpact.identity(c, ledger: selected, roots: store.ledgerRoots)) + LedgerImpact.identity(c, ledger: selected, roots: roots)) { return true } if let selectedIdentities { return try selectedIdentities.contains( - LedgerImpact.identity(c, ledger: selected, roots: store.ledgerRoots)) + LedgerImpact.identity(c, ledger: selected, roots: roots)) } return (selectedKinds?.contains(DeclaredComponentKind(rawValue: c.kind)!) ?? true) && (selectedNames.isEmpty @@ -496,9 +496,9 @@ package final class ArtifactAggregation: PreparedEvidence { bindings: [String] = [], ownership: LedgerDeployment.Ownership = .ownedValues ) throws { let identity = try LedgerImpact.identity( - ledger.components[entry.contribution.component]!, ledger: ledger, roots: store.ledgerRoots) + ledger.components[entry.contribution.component]!, ledger: ledger, roots: roots) let oldComponent = try previous.components.values.first { - try LedgerImpact.identity($0, ledger: previous, roots: store.ledgerRoots) == identity + try LedgerImpact.identity($0, ledger: previous, roots: roots) == identity } let deployment = LedgerDeployment( id: entry.id, target: location(entry.target), route: entry.lowering.format, @@ -506,7 +506,7 @@ package final class ArtifactAggregation: PreparedEvidence { ownership: ownership, expectedHash: entry.lowering.artifacts[0].hash, created: previous.deployments.first { $0.route == entry.lowering.format - && (try? $0.target.resolve(roots: store.ledgerRoots).path) == entry.target.url.path + && (try? $0.target.resolve(roots: roots).path) == entry.target.url.path }?.created ?? !FileManager.default.fileExists(atPath: entry.target.url.path)) ledger.deployments.removeAll { $0.id == entry.id } ledger.deployments.append(deployment) @@ -530,12 +530,12 @@ package final class ArtifactAggregation: PreparedEvidence { _ value: NativeComponentValue, values: RuntimeBindingValues?, selected: ResolvedLedger ) throws -> NativeValue { - try Self.componentValue(value, values: values, selected: selected, store: store) + try Self.componentValue(value, values: values, selected: selected, store: store, roots: roots) } private static func componentValue( _ value: NativeComponentValue, values: RuntimeBindingValues?, - selected: ResolvedLedger, store: StateStore, symbolicVariant: Int = 0 + selected: ResolvedLedger, store: StateStore, roots: [String: URL], symbolicVariant: Int = 0 ) throws -> NativeValue { var environment = store.environment var symbolic: [String: Data] = [:] @@ -556,7 +556,7 @@ package final class ArtifactAggregation: PreparedEvidence { } } let paths = try selected.resources.keys.reduce(into: [String: String]()) { - $0[$1] = try Self.resourceDestination($1, ledger: selected, store: store).path + $0[$1] = try Self.resourceDestination($1, ledger: selected, store: store, roots: roots).path } return try value.stagedValue( bindings: values ?? RuntimeBindingValues(symbolic), environment: environment, @@ -571,13 +571,14 @@ package final class ArtifactAggregation: PreparedEvidence { private static func generatedManifestMatches( _ manifest: NativeComponentValue, observed: NativeValue?, selected: ResolvedLedger, - privateGeneration: Bool, store: StateStore + privateGeneration: Bool, store: StateStore, roots: [String: URL] ) throws -> Bool { guard let observed else { return false } - let first = try Self.componentValue(manifest, values: nil, selected: selected, store: store) + let first = try Self.componentValue( + manifest, values: nil, selected: selected, store: store, roots: roots) guard privateGeneration, !manifest.bindings.isEmpty else { return observed == first } let second = try Self.componentValue( - manifest, values: nil, selected: selected, store: store, symbolicVariant: 1) + manifest, values: nil, selected: selected, store: store, roots: roots, symbolicVariant: 1) // F determines the native positions. Only leaves changed by its binding conversion vary. func matches(_ actual: NativeValue, _ a: NativeValue, _ b: NativeValue) -> Bool { if a == b { return actual == a } @@ -598,7 +599,8 @@ package final class ArtifactAggregation: PreparedEvidence { private func generatedManifestBytes( _ manifest: NativeComponentValue, values: RuntimeBindingValues? ) throws -> Data { - try Self.generatedManifestBytes(manifest, values: values, selected: ledger, store: store) + try Self.generatedManifestBytes( + manifest, values: values, selected: ledger, store: store, roots: roots) } /// Renders a selected symbolic value with the native JSON serializer, without physical input. @@ -624,11 +626,11 @@ package final class ArtifactAggregation: PreparedEvidence { private static func generatedManifestBytes( _ manifest: NativeComponentValue, values: RuntimeBindingValues?, - selected: ResolvedLedger, store: StateStore + selected: ResolvedLedger, store: StateStore, roots: [String: URL] ) throws -> Data { guard case .object(let fields) = try componentValue( - manifest, values: values, selected: selected, store: store) + manifest, values: values, selected: selected, store: store, roots: roots) else { throw CoreError.invalidState("generated native manifest must be an object") } let document = try NativeDocument( bytes: Data("{}".utf8), format: .json, @@ -759,7 +761,7 @@ package final class ArtifactAggregation: PreparedEvidence { guard try Self.generatedManifestMatches( manifest, observed: current.read(.init(keys: []))?.value, selected: previous, - privateGeneration: receipt != nil, store: store) + privateGeneration: receipt != nil, store: store, roots: roots) else { throw CoreError.invalidState("owned generated native tree drifted") } default: throw CoreError.invalidState("invalid whole-object ownership") } @@ -789,7 +791,8 @@ package final class ArtifactAggregation: PreparedEvidence { content: .boundFile(bindings: bindingNames(entry)) { values in try Self.generatedManifestBytes( - manifest, values: values, selected: selected, store: selectedStore) + manifest, values: values, selected: selected, store: selectedStore, + roots: selectedStore.ledgerRoots(recordedIn: previous)) })) privateTrees.append((privatePlan, members)) case .nativePlugin: @@ -880,7 +883,7 @@ package final class ArtifactAggregation: PreparedEvidence { if changed { if after.isEmpty, previous.deployments.contains(where: { - $0.created && (try? $0.target.resolve(roots: store.ledgerRoots).path) == path + $0.created && (try? $0.target.resolve(roots: roots).path) == path }) { deletes.insert(path) @@ -894,7 +897,7 @@ package final class ArtifactAggregation: PreparedEvidence { for entry in next { try record(entry, previous: previous, changed: changed, readers: readers) } if next.isEmpty { for deployment in previous.deployments - where (try? deployment.target.resolve(roots: store.ledgerRoots).path) == path { + where (try? deployment.target.resolve(roots: roots).path) == path { changes.append( .init( deployment: deployment, url: url, before: nil, after: nil, changed: changed, @@ -949,6 +952,10 @@ package final class ArtifactAggregation: PreparedEvidence { bytes: capture.bytes ?? Data((format == .toml ? "" : "{}\n").utf8), format: format, budget: budget) let selectedStore = store + let planningRoots = roots + func valueRoots(_ values: RuntimeBindingValues?) -> [String: URL] { + values == nil ? planningRoots : selectedStore.ledgerRoots(recordedIn: previous) + } func names(_ bindings: [NativeComponentBindingPlacement]) -> Set { Set( bindings.compactMap { @@ -991,7 +998,11 @@ package final class ArtifactAggregation: PreparedEvidence { $0.inputs.contains(c.component) && $0.format.hasSuffix("-mcp@1") })!.id ], bindings: bindings, symbolic: c.value, - render: { try Self.nativeValue(c, values: $0, ledger: selected, store: selectedStore) }) + render: { + try Self.nativeValue( + c, values: $0, ledger: selected, store: selectedStore, + roots: valueRoots($0)) + }) } func regional(_ entry: ComponentOutputEntry, selected: ResolvedLedger) throws -> [NativeRegionOwner] @@ -1020,7 +1031,8 @@ package final class ArtifactAggregation: PreparedEvidence { member.keys, symbolic: selected.components[entry.contribution.component]!.payload, bindings: names(value.bindings), render: { - try Self.componentValue(value, values: $0, selected: selected, store: selectedStore) + try Self.componentValue( + value, values: $0, selected: selected, store: selectedStore, roots: valueRoots($0)) }) ] case .claudePermissions(let policy): @@ -1039,7 +1051,7 @@ package final class ArtifactAggregation: PreparedEvidence { case .hook(let hook): let identity = try LedgerImpact.identity( selected.components[entry.contribution.component]!, ledger: selected, - roots: store.ledgerRoots) + roots: roots) return [ .init( key: "hook:" + identity + ":" + String(entry.index), region: .init(keys: hook.keys), @@ -1049,13 +1061,14 @@ package final class ArtifactAggregation: PreparedEvidence { symbolic: selected.components[entry.contribution.component]!.payload, render: { try Self.componentValue( - hook.value, values: $0, selected: selected, store: selectedStore) + hook.value, values: $0, selected: selected, store: selectedStore, + roots: valueRoots($0)) }) ] case .orderedPermissions(let rules): let identity = try LedgerImpact.identity( selected.components[entry.contribution.component]!, ledger: selected, - roots: store.ledgerRoots) + roots: roots) let selectedOwner = try isSelected(entry.contribution.component, in: selected) return rules.enumerated().map { index, rule in .init( @@ -1124,7 +1137,7 @@ package final class ArtifactAggregation: PreparedEvidence { requiringReceiptForExistingTarget: recordedOldBindings) : nil let receiptArrays = try store.materializationReceipt(for: target)?.nativeArrays ?? [] let authority = previous.nativeAuthorities?.first { - (try? $0.target.resolve(roots: store.ledgerRoots).path) == path + (try? $0.target.resolve(roots: roots).path) == path } var retained: [NativeObservation] = [] var retainedOwners: [[String]] = [] @@ -1374,20 +1387,20 @@ package final class ArtifactAggregation: PreparedEvidence { privatePlan: privatePlan, bindings: ownBindings) } for deployment in previous.deployments - where (try? deployment.target.resolve(roots: store.ledgerRoots).path) == path { + where (try? deployment.target.resolve(roots: roots).path) == path { let oldOwners = try Set( deployment.owners.map { try LedgerImpact.identity( - previous.components[$0]!, ledger: previous, roots: store.ledgerRoots) + previous.components[$0]!, ledger: previous, roots: roots) }) let retained = try ledger.deployments.contains { next in guard next.route == deployment.route, - (try? next.target.resolve(roots: store.ledgerRoots).path) == path + (try? next.target.resolve(roots: roots).path) == path else { return false } return try Set( next.owners.map { try LedgerImpact.identity( - ledger.components[$0]!, ledger: ledger, roots: store.ledgerRoots) + ledger.components[$0]!, ledger: ledger, roots: roots) }) == oldOwners } if retained { continue } @@ -1405,7 +1418,7 @@ package final class ArtifactAggregation: PreparedEvidence { route: String, path: String, format: NativeDocumentFormat ) { var records = ledger.nativeAuthorities ?? [] - records.removeAll { (try? $0.target.resolve(roots: store.ledgerRoots).path) == path } + records.removeAll { (try? $0.target.resolve(roots: roots).path) == path } if !result.regions.isEmpty { records.append( .init( @@ -1830,13 +1843,14 @@ package final class ArtifactAggregation: PreparedEvidence { private static func nativeValue( _ contribution: NativeMCPContribution, values: RuntimeBindingValues?, ledger: ResolvedLedger, - store: StateStore + store: StateStore, roots: [String: URL] ) throws -> NativeValue { func convert(_ value: LedgerValue, path: [MCPValueStep]) throws -> NativeValue { if let resource = contribution.resourcePlacements.first(where: { $0.path == path }), ledger.resources[resource.resource] != nil { - let destination = try resourceDestination(resource.resource, ledger: ledger, store: store) + let destination = try resourceDestination( + resource.resource, ledger: ledger, store: store, roots: roots) return .string(destination.path) } switch value.kind { @@ -1902,12 +1916,14 @@ package final class ArtifactAggregation: PreparedEvidence { } } - package func stage(transaction: FileTransaction, provider: any RuntimeBindingProvider) throws { + package func stage( + transaction: FileTransaction, provider: any RuntimeBindingProvider, roots: [String: URL] + ) throws { var staged = Set() for (id, source) in resources.sorted(by: { $0.key < $1.key }) { guard let resource = ledger.resources[id], resource.kind != .liveEdit else { continue } - let destination = try resourceDestination(id) - let git = try gitDestination(resource, ledger: ledger) + let destination = try Self.resourceDestination(id, ledger: ledger, store: store, roots: roots) + let git = try Self.gitDestination(resource, ledger: ledger, store: store, roots: roots) let container = git ?? store.cacheDirectory.appendingPathComponent( @@ -2126,7 +2142,8 @@ extension ArtifactAggregation { guard let observed = try document.read(region) else { return ("missing", "managed native region is missing") } - return try observed.value == nativeValue(c, values: nil, ledger: ledger, store: store) + return try observed.value + == nativeValue(c, values: nil, ledger: ledger, store: store, roots: store.ledgerRoots) ? ("current", nil) : ("drifted", "managed native region changed") } if deployment.route.hasSuffix("-generated-plugin@1"), @@ -2203,7 +2220,8 @@ extension ArtifactAggregation { bytes: Data(contentsOf: url), format: output.route.documentFormat!, budget: budget) matches = try document.read(.init(keys: member.keys))?.value - == componentValue(value, values: nil, selected: ledger, store: store) + == componentValue( + value, values: nil, selected: ledger, store: store, roots: store.ledgerRoots) case .claudePermissions(let policy): let document = try NativeDocument( bytes: Data(contentsOf: url), format: .json, budget: budget) @@ -2265,7 +2283,7 @@ extension ArtifactAggregation { } && generatedManifestMatches( manifest, observed: document.read(.init(keys: []))?.value, selected: ledger, - privateGeneration: privateGeneration, store: store) + privateGeneration: privateGeneration, store: store, roots: store.ledgerRoots) case .hook, .orderedPermissions: let document = try NativeDocument( bytes: Data(contentsOf: url), format: output.route.documentFormat!, budget: budget) @@ -2281,7 +2299,8 @@ extension ArtifactAggregation { switch output.content { case .hook(let hook): expected = [ - try componentValue(hook.value, values: nil, selected: ledger, store: store) + try componentValue( + hook.value, values: nil, selected: ledger, store: store, roots: store.ledgerRoots) ] case .orderedPermissions(let rules): expected = rules.map { diff --git a/Sources/Components/DeploymentConstruction.swift b/Sources/Components/DeploymentConstruction.swift index 557f3e9..3025dfe 100644 --- a/Sources/Components/DeploymentConstruction.swift +++ b/Sources/Components/DeploymentConstruction.swift @@ -272,7 +272,7 @@ package enum DeploymentConstruction { package static func complete( _ native: ResolvedLedger, linked: LinkedComponents, store: StateStore, - previous: ResolvedLedger, platform: DeclarationPlatform + previous: ResolvedLedger, platform: DeclarationPlatform, roots: [String: URL] ) throws -> Result { var ledger = native var inputs: [TargetPrecondition] = [] @@ -318,7 +318,7 @@ package enum DeploymentConstruction { let instructions = linked.components.filter { if case .instruction = $0.payload { true } else { false } } - let old = try previous.domainProjection(roots: store.ledgerRoots).instructions + let old = try previous.domainProjection(roots: roots).instructions var merged: [String: (LockedTarget, [String], [String])] = [:] for agent in AgentID.allCases { let selected = instructions.filter { $0.recipients.contains(agent) } @@ -330,7 +330,7 @@ package enum DeploymentConstruction { let planned = try InstructionTargets(store: store).plan( sections: sections, agents: [agent], previous: old) for (id, source) in ledger.sources where source.kind == .local && source.location != nil { - let identity = try ledger.sourceIdentity(id, roots: store.ledgerRoots) + let identity = try ledger.sourceIdentity(id, roots: roots) let roots = ledger.sourceUses.filter { $0.source == id }.map(\.root) for root in roots.isEmpty ? ["."] : roots { try InstructionTargets.validateSourceDirectories( diff --git a/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift b/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift index 52ad878..73a3d24 100644 --- a/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift +++ b/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift @@ -250,6 +250,40 @@ struct ConsumerLifecycleRegressionTests { #expect(try f.snapshot() == before) } + @Test func installedSkillsAndUnchangedUpdateKeepRecordedNamedTarget() throws { + let f = try UpdateFixture() + try f.declare(agents: [.codex, .claudeCode]) + var declaration = try f.store.loadDeclaration() + declaration.components.append( + .command( + name: "review", description: "Review", prompt: .literal("Review exact sources."), + agents: [.claudeCode])) + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + + let ledger = try f.store.loadLedger() + let command = try #require(ledger.deployments.first { $0.route.hasSuffix("-components@1") }) + let commandURL = try command.target.resolve(roots: f.store.ledgerRoots(recordedIn: ledger)) + let commandBytes = try f.bytes(commandURL) + let managed = try SkillOperations.listManaged(environment: f.environment) + #expect(managed.map(\.name) == ["demo", "demo"]) + #expect(Set(managed.map(\.agent)) == [.codex, .claudeCode]) + #expect(managed.allSatisfy { $0.status == .installed }) + + let request = UpdateRequest(kinds: [.skills]) + let before = try f.snapshot() + let preview = try UpdateOperations.preview(request, environment: f.environment) + #expect(!preview.hasChanges) + #expect(preview.readLocations.contains { $0.path == commandURL.path }) + let skills = try SkillOperations.updateInstalled(environment: f.environment) + #expect(skills.map(\.skill) == preview.skills.map(\.skill)) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + #expect(try f.snapshot() == before) + #expect(try f.bytes(commandURL) == commandBytes) + } + @Test func missingLiveSkillReconciliationReplaysOnlyPreviousNativeResources() throws { let f = try UpdateFixture() try f.declare(mode: .edit, agents: [.codex]) From c8054692830f6ae1572c50e65075009be132244e Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:44:44 +0800 Subject: [PATCH 162/171] perf: reuse committed roots when inspecting components --- Sources/AgentsUpdates/ScopeInspection.swift | 11 ++++---- Sources/Components/ArtifactAggregation.swift | 28 +++++++++++--------- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/Sources/AgentsUpdates/ScopeInspection.swift b/Sources/AgentsUpdates/ScopeInspection.swift index d8d15ce..a66a7d5 100644 --- a/Sources/AgentsUpdates/ScopeInspection.swift +++ b/Sources/AgentsUpdates/ScopeInspection.swift @@ -173,7 +173,7 @@ extension UpdateOperations { let generation = try ResolvedLedgerCodec.digest([ ResolvedLedgerCodec.digest(ledger), document?.digest ?? "absent", ]) - let roots = store.ledgerRoots + let roots = store.ledgerRoots(recordedIn: ledger) func source(_ id: String) throws -> String { try ledger.sourceIdentity(id, roots: roots) } @@ -201,14 +201,15 @@ extension UpdateOperations { hash: r.hash, kind: r.kind.rawValue, location: try ArtifactAggregation.resourceDestination( - id, ledger: ledger, store: store), + id, ledger: ledger, store: store, roots: roots), entries: r.entries.map(entry), support: r.support.map(entry)) } let deployments = try ledger.deployments.map { d in let url = try d.target.resolve(roots: roots) let observed = try ArtifactAggregation.inspectDeployment( - d, ledger: ledger, store: store) - let exposure = try ArtifactAggregation.nativeExposure(d, ledger: ledger, store: store) + d, ledger: ledger, store: store, roots: roots) + let exposure = try ArtifactAggregation.nativeExposure( + d, ledger: ledger, store: store, roots: roots) return DeploymentInspection( identity: d.id, location: url, format: d.route, owners: try d.owners.map { @@ -228,7 +229,7 @@ extension UpdateOperations { } let paths = try readLocations( - declarations: [declaration], ledgers: [ledger], store: store) + declarations: [declaration], ledgers: [ledger], store: store, roots: roots) + installations.values.map(\.url) try baseline.validate() return ScopeInspection( diff --git a/Sources/Components/ArtifactAggregation.swift b/Sources/Components/ArtifactAggregation.swift index e97d002..8029e1a 100644 --- a/Sources/Components/ArtifactAggregation.swift +++ b/Sources/Components/ArtifactAggregation.swift @@ -1987,7 +1987,8 @@ extension Dictionary { extension ArtifactAggregation { package static func nativeExposure( - _ deployment: LedgerDeployment, ledger: ResolvedLedger, store: StateStore + _ deployment: LedgerDeployment, ledger: ResolvedLedger, store: StateStore, + roots admittedRoots: [String: URL]? = nil ) throws -> (readers: [AgentID]?, sensitive: Bool) { guard deployment.ownership == .ownedValues || deployment.route.hasSuffix("-components@1") @@ -1995,7 +1996,8 @@ extension ArtifactAggregation { else { return (nil, false) } - let path = try deployment.target.resolve(roots: store.ledgerRoots).path + let roots = admittedRoots ?? store.ledgerRoots + let path = try deployment.target.resolve(roots: roots).path var identities = Set() for route in try DeploymentConstruction.routes(ledger) { let target = try store.nativeTarget(for: route) @@ -2071,9 +2073,11 @@ extension ArtifactAggregation { /// Observes only the owned region. Private receipts validate the entire physical preimage. package static func inspectDeployment( - _ deployment: LedgerDeployment, ledger: ResolvedLedger, store: StateStore + _ deployment: LedgerDeployment, ledger: ResolvedLedger, store: StateStore, + roots admittedRoots: [String: URL]? = nil ) throws -> (status: String, diagnostic: String?) { - let url = try deployment.target.resolve(roots: store.ledgerRoots) + let roots = admittedRoots ?? store.ledgerRoots + let url = try deployment.target.resolve(roots: roots) guard FileManager.default.fileExists(atPath: url.path) else { return ("missing", "managed target is missing") } @@ -2090,7 +2094,7 @@ extension ArtifactAggregation { else { return ("drifted", "live skill is not linked to its recorded source") } let observed = URL(fileURLWithPath: link, relativeTo: url.deletingLastPathComponent()) .standardizedFileURL - let expected = try source.resolve(roots: store.ledgerRoots).standardizedFileURL + let expected = try source.resolve(roots: roots).standardizedFileURL guard observed.path == expected.path else { return ("drifted", "live skill is not linked to its recorded source") } @@ -2143,14 +2147,14 @@ extension ArtifactAggregation { return ("missing", "managed native region is missing") } return try observed.value - == nativeValue(c, values: nil, ledger: ledger, store: store, roots: store.ledgerRoots) + == nativeValue(c, values: nil, ledger: ledger, store: store, roots: roots) ? ("current", nil) : ("drifted", "managed native region changed") } if deployment.route.hasSuffix("-generated-plugin@1"), let lowering = ledger.lowerings.first(where: { $0.deployments.contains(deployment.id) }) { return try LedgerReplay.withLockedResources( - ledger, store: store, roots: store.ledgerRoots, limits: .standard, + ledger, store: store, roots: roots, limits: .standard, lowerings: [lowering.id] ) { artifacts, _, _ in let contribution = try NativeGeneratedPluginContribution.decode( @@ -2175,7 +2179,7 @@ extension ArtifactAggregation { let lowering = ledger.lowerings.first(where: { $0.deployments.contains(deployment.id) }) { return try LedgerReplay.withLockedResources( - ledger, store: store, roots: store.ledgerRoots, limits: .standard + ledger, store: store, roots: roots, limits: .standard ) { artifacts, _, _ in let table = Dictionary(uniqueKeysWithValues: artifacts.map { ($0.name, $0) }) @@ -2221,7 +2225,7 @@ extension ArtifactAggregation { matches = try document.read(.init(keys: member.keys))?.value == componentValue( - value, values: nil, selected: ledger, store: store, roots: store.ledgerRoots) + value, values: nil, selected: ledger, store: store, roots: roots) case .claudePermissions(let policy): let document = try NativeDocument( bytes: Data(contentsOf: url), format: .json, budget: budget) @@ -2283,13 +2287,13 @@ extension ArtifactAggregation { } && generatedManifestMatches( manifest, observed: document.read(.init(keys: []))?.value, selected: ledger, - privateGeneration: privateGeneration, store: store, roots: store.ledgerRoots) + privateGeneration: privateGeneration, store: store, roots: roots) case .hook, .orderedPermissions: let document = try NativeDocument( bytes: Data(contentsOf: url), format: output.route.documentFormat!, budget: budget) guard let authority = ledger.nativeAuthorities?.first(where: { - (try? $0.target.resolve(roots: store.ledgerRoots)) == url + (try? $0.target.resolve(roots: roots)) == url }) else { return ("unverified", "managed native occurrence authority is missing") @@ -2300,7 +2304,7 @@ extension ArtifactAggregation { case .hook(let hook): expected = [ try componentValue( - hook.value, values: nil, selected: ledger, store: store, roots: store.ledgerRoots) + hook.value, values: nil, selected: ledger, store: store, roots: roots) ] case .orderedPermissions(let rules): expected = rules.map { From d0d8735032d8235b618c0fa3d4b5c1e47d3008ed Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:20:22 +0800 Subject: [PATCH 163/171] fix: admit large configurations on bounded worker stacks --- Sources/AgentsCore/DirectoryHandle.swift | 15 ++- Sources/AgentsCore/FileAccess.swift | 27 +++- Sources/AgentsCore/FileLock.swift | 53 ++++++-- Sources/AgentsCore/FileSystem.swift | 18 ++- .../AgentsCore/NativeTargetCoordination.swift | 62 ++++++--- Sources/AgentsCore/ProcessLimits.swift | 10 ++ Sources/CPlatform/CPlatform.c | 18 +++ Sources/CPlatform/include/CPlatform.h | 1 + .../CoordinationAdmissionTests.swift | 107 ++++++++++++++++ .../FileSystemAccessTests.swift | 5 +- .../AgentsCoreTests/ProcessLimitsTests.swift | 71 +++++++++++ .../StateTestProcess/OpenFileLimitProbe.swift | 120 ++++++++++++++++++ Tests/StateTestProcess/main.swift | 4 + 13 files changed, 471 insertions(+), 40 deletions(-) create mode 100644 Sources/AgentsCore/ProcessLimits.swift create mode 100644 Tests/AgentsCoreTests/ProcessLimitsTests.swift create mode 100644 Tests/StateTestProcess/OpenFileLimitProbe.swift diff --git a/Sources/AgentsCore/DirectoryHandle.swift b/Sources/AgentsCore/DirectoryHandle.swift index 4dcfc6d..73b2f85 100644 --- a/Sources/AgentsCore/DirectoryHandle.swift +++ b/Sources/AgentsCore/DirectoryHandle.swift @@ -32,7 +32,10 @@ final class DirectoryHandle { ) throws { self.url = url.standardizedFileURL var current = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC) - guard current >= 0 else { throw CoreError.unsafePath("cannot open filesystem root") } + guard current >= 0 else { + if let exhaustion = OpenFileLimitError(errno, at: self.url) { throw exhaustion } + throw CoreError.unsafePath("cannot open filesystem root") + } defer { if current >= 0 { close(current) } } let components = self.url.pathComponents.dropFirst() for (index, component) in components.enumerated() { @@ -114,7 +117,15 @@ final class DirectoryHandle { } func names() throws -> [String] { - guard let stream = fdopendir(dup(descriptor)) else { + let copy = dup(descriptor) + guard copy >= 0 else { + if let exhaustion = OpenFileLimitError(errno, at: url) { throw exhaustion } + throw CoreError.unsafePath("cannot enumerate \(url.path)") + } + guard let stream = fdopendir(copy) else { + let code = errno + close(copy) + if let exhaustion = OpenFileLimitError(code, at: url) { throw exhaustion } throw CoreError.unsafePath("cannot enumerate \(url.path)") } defer { closedir(stream) } diff --git a/Sources/AgentsCore/FileAccess.swift b/Sources/AgentsCore/FileAccess.swift index b4967c6..06da930 100644 --- a/Sources/AgentsCore/FileAccess.swift +++ b/Sources/AgentsCore/FileAccess.swift @@ -115,6 +115,9 @@ extension DirectoryHandle { guard let before = try info(name) else { return nil } let file = openat(descriptor, name, O_RDONLY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC) guard file >= 0 else { + if let exhaustion = OpenFileLimitError(errno, at: url.appendingPathComponent(name)) { + throw exhaustion + } throw CoreError.invalidState("cannot open entry for access evidence") } defer { close(file) } @@ -133,7 +136,13 @@ extension DirectoryHandle { let file = openat( descriptor, name, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, executable ? 0o700 : 0o600) - guard file >= 0 else { throw CoreError.invalidState("cannot create private file: \(errno)") } + guard file >= 0 else { + let code = errno + if let exhaustion = OpenFileLimitError(code, at: url.appendingPathComponent(name)) { + throw exhaustion + } + throw CoreError.invalidState("cannot create private file: \(code)") + } var retained = false defer { if !retained { close(file) } } var created = stat() @@ -266,7 +275,10 @@ struct DirectoryAccessEvidence: Codable, Equatable { static func capture(at url: URL) throws -> Self { var descriptor = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC) - guard descriptor >= 0 else { throw CoreError.unsafePath("cannot open access ancestry") } + guard descriptor >= 0 else { + if let exhaustion = OpenFileLimitError(errno, at: url) { throw exhaustion } + throw CoreError.unsafePath("cannot open access ancestry") + } defer { close(descriptor) } var evidence = [try FileAccessEvidence.capture(descriptor: descriptor)] for (index, name) in url.standardizedFileURL.pathComponents.dropFirst().enumerated() { @@ -274,7 +286,9 @@ struct DirectoryAccessEvidence: Codable, Equatable { let next = openat( descriptor, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC | (alias ? 0 : O_NOFOLLOW)) if next < 0 { - guard errno == ENOENT else { throw CoreError.unsafePath("cannot open access ancestry") } + let code = errno + if let exhaustion = OpenFileLimitError(code, at: url) { throw exhaustion } + guard code == ENOENT else { throw CoreError.unsafePath("cannot open access ancestry") } break } do { @@ -310,7 +324,12 @@ extension DirectoryHandle { { try requireAccessComponent(name) let file = openat(descriptor, name, O_RDONLY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC) - guard file >= 0 else { throw CoreError.invalidState("cannot open private object") } + guard file >= 0 else { + if let exhaustion = OpenFileLimitError(errno, at: url.appendingPathComponent(name)) { + throw exhaustion + } + throw CoreError.invalidState("cannot open private object") + } defer { close(file) } let evidence = try FileAccessEvidence.requirePrivate(descriptor: file) guard expected == nil || expected == evidence, diff --git a/Sources/AgentsCore/FileLock.swift b/Sources/AgentsCore/FileLock.swift index 5a57208..b6e055e 100644 --- a/Sources/AgentsCore/FileLock.swift +++ b/Sources/AgentsCore/FileLock.swift @@ -77,23 +77,52 @@ package enum FileLock { return try withDescriptor(descriptor, at: url, checkpoint: { _ in }, body) } - static func withCoordinationDescriptor( - at url: URL, writable: Bool, checkpoint: (String) throws -> Void = { _ in }, - _ body: (Int32) throws -> T - ) throws -> T { + /// Owns an acquired file description or an absent lock observed through this exact parent. + final class CoordinationDescriptor { + let descriptor: Int32 + private let parent: DirectoryHandle + private let name: String + private var isOpen: Bool + + fileprivate init(_ descriptor: Int32, parent: DirectoryHandle, name: String) { + self.descriptor = descriptor + self.parent = parent + self.name = name + isOpen = descriptor >= 0 + } + + deinit { release() } + + func finish() throws { + if descriptor >= 0 { + release() + } else if try parent.info(name) != nil { + throw CoordinationReadmission.required + } + } + + private func release() { + guard isOpen else { return } + isOpen = false + close(descriptor) + } + } + + static func acquireCoordinationDescriptor( + at url: URL, writable: Bool, checkpoint: (String) throws -> Void + ) throws -> CoordinationDescriptor { let parent = try DirectoryHandle(at: url.deletingLastPathComponent()) + let name = url.lastPathComponent let descriptor = openat( - parent.descriptor, url.lastPathComponent, - (writable ? O_RDWR : O_RDONLY) | O_NOFOLLOW | O_CLOEXEC) + parent.descriptor, name, (writable ? O_RDWR : O_RDONLY) | O_NOFOLLOW | O_CLOEXEC) if descriptor < 0, !writable, errno == ENOENT { - let result = Result { try body(-1) } - if try parent.info(url.lastPathComponent) != nil { throw CoordinationReadmission.required } - return try result.get() + return CoordinationDescriptor(-1, parent: parent, name: name) } guard descriptor >= 0 else { + if let exhaustion = OpenFileLimitError(errno, at: url) { throw exhaustion } throw CoreError.invalidState("cannot open shared coordination lock") } - defer { close(descriptor) } + let acquired = CoordinationDescriptor(descriptor, parent: parent, name: name) let evidence = try FileAccessEvidence.requirePrivate(descriptor: descriptor) guard evidence.identity.kind == S_IFREG else { throw CoreError.invalidState("shared coordination lock is not a regular file") @@ -112,12 +141,12 @@ package enum FileLock { } break } - guard try parent.info(url.lastPathComponent).map(FileObjectIdentity.init) == evidence.identity + guard try parent.info(name).map(FileObjectIdentity.init) == evidence.identity else { throw CoreError.invalidState("shared coordination lock changed") } try evidence.validate(descriptor: descriptor) - return try body(descriptor) + return acquired } private static func withDescriptor( diff --git a/Sources/AgentsCore/FileSystem.swift b/Sources/AgentsCore/FileSystem.swift index 393ee22..e7fd317 100644 --- a/Sources/AgentsCore/FileSystem.swift +++ b/Sources/AgentsCore/FileSystem.swift @@ -1,6 +1,19 @@ import CPlatform import Foundation +struct OpenFileLimitError: LocalizedError, CustomStringConvertible { + let description: String + var errorDescription: String? { description } + + init?(_ code: Int32, at url: URL) { + switch code { + case EMFILE: description = "Too many open files for this process: \(url.path)" + case ENFILE: description = "Too many open files in the system: \(url.path)" + default: return nil + } + } +} + /// Filesystem access diagnostics shared by descriptor and Foundation operations. package enum FileSystem { static func permissionDenied(at url: URL) -> CoreError { @@ -8,8 +21,9 @@ package enum FileSystem { "permission denied: \(url.path); check the directory's permissions and default ACL") } - static func posixError(_ code: Int32, at url: URL, otherwise error: CoreError) -> CoreError { - code == EACCES || code == EPERM ? permissionDenied(at: url) : error + static func posixError(_ code: Int32, at url: URL, otherwise error: CoreError) -> any Error { + if let exhaustion = OpenFileLimitError(code, at: url) { return exhaustion } + return code == EACCES || code == EPERM ? permissionDenied(at: url) : error } static func requireAccess( diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index 066e1d9..afdb809 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -765,6 +765,8 @@ final class SharedResource { do { value = try StateStore.decode( metadata.read("reservation", maximumBytes: 16_384), as: SharedReservation.self) + } catch let exhaustion as OpenFileLimitError { + throw exhaustion } catch { throw CoreError.invalidState("invalid shared reservation; owner action required") } guard value.version == 1, value.resource == identity, !value.scope.isEmpty, !value.owner.isEmpty @@ -1043,6 +1045,11 @@ final class TransactionLockContext { } } +private enum SharedCoordinationFrame { + case lock(FileLock.CoordinationDescriptor) + case missingMetadata(SharedResource) +} + extension StateStore { func requireProjectNativeAuthority(at destination: URL) throws { if scope == .project, @@ -1100,7 +1107,7 @@ extension StateStore { path: canonical.root + "/" + canonical.basename, scope: directory) } - /// Acquire the union before the scope lock. Re-admission never replays a delivered callback. + /// Acquire the union before the scope lock, rechecking optimistic reads on unwind. func withCoordination( routes: Set, installations: [SkillInstallationTarget] = [], writable: Bool, checkpoint: (String) throws -> Void = { _ in }, @@ -1211,6 +1218,8 @@ extension StateStore { store: self, route: route, create: writable && !recovering, existingRoot: existingRoot, projectRoot: projectRoot, onReadLocation: onReadLocation) + } catch let exhaustion as OpenFileLimitError { + throw exhaustion } catch { if recovering { throw CoreError.invalidState( @@ -1243,16 +1252,13 @@ extension StateStore { context.createdAncestry = createdAncestry context.existingProjectRoot = existingRoot context.projectRootDirectory = projectRoot - func locked(_ index: Int) throws -> T? { - if index < context.resources.count { - let resource = context.resources[index] + var frames: [SharedCoordinationFrame] = [] + frames.reserveCapacity(context.resources.count) + var outcome = Result { + for (index, resource) in context.resources.enumerated() { guard let metadata = resource.metadata else { - // No metadata means no prior registered writer. Recheck after the unlocked read. - let result = Result { try locked(index + 1) } - let after = try SharedResource( - store: self, route: resource.route, create: false, onReadLocation: onReadLocation) - guard after.metadata == nil else { return nil } - return try result.get() + frames.append(.missingMetadata(resource)) + continue } let url = metadata.url.appendingPathComponent("lock") if writable { @@ -1261,22 +1267,38 @@ extension StateStore { } _ = try metadata.requirePrivateAccess("lock") } - return try FileLock.withCoordinationDescriptor( + let lock = try FileLock.acquireCoordinationDescriptor( at: url, writable: writable, - checkpoint: { try checkpoint("shared.\(index).lock." + $0) }, - { descriptor in - try resource.bindLock(descriptor) - try resource.validate() - return try locked(index + 1) - }) + checkpoint: { try checkpoint("shared.\(index).lock." + $0) }) + frames.append(.lock(lock)) + try resource.bindLock(lock.descriptor) + try resource.validate() } let result = Result { try context.run { try body() } } - for absent in absentRoots where try !absent.remainsAbsent() { return nil } + for absent in absentRoots where try !absent.remainsAbsent() { + throw CoordinationReadmission.required + } return try result.get() } + + // An outer observation can override a success, failure or requested readmission. + while let frame = frames.popLast() { + do { + switch frame { + case .lock(let lock): + try lock.finish() + case .missingMetadata(let resource): + let current = try SharedResource( + store: self, route: resource.route, create: false, onReadLocation: onReadLocation) + if current.metadata != nil { throw CoordinationReadmission.required } + } + } catch { + outcome = .failure(error) + } + } // The scope-lock body checks that the preflight footprint still covers the journal. do { - if let result = try locked(0) { return result } + return try outcome.get() } catch CoordinationReadmission.required { continue } } } @@ -1296,6 +1318,8 @@ extension StateStore { let journal = try FileTransaction.readJournal(bytes) try journal.validateCoordination() return journal + } catch let exhaustion as OpenFileLimitError { + throw exhaustion } catch { // A corrupt journal admits no data callback. The read boundary still takes the // scope lock and routes to its pending-recovery diagnostic without writes. diff --git a/Sources/AgentsCore/ProcessLimits.swift b/Sources/AgentsCore/ProcessLimits.swift new file mode 100644 index 0000000..1ce5e40 --- /dev/null +++ b/Sources/AgentsCore/ProcessLimits.swift @@ -0,0 +1,10 @@ +import CPlatform + +public enum ProcessLimits { + /// Best-effort increase of this process's soft open-file limit. + /// Call from the owning executable at startup, before beginning scope operations. + /// The hard limit is preserved. If the OS refuses, operations use the existing limit. + public static func raiseOpenFileLimit() { + platform_raise_open_file_limit() + } +} diff --git a/Sources/CPlatform/CPlatform.c b/Sources/CPlatform/CPlatform.c index aa34e56..1026373 100644 --- a/Sources/CPlatform/CPlatform.c +++ b/Sources/CPlatform/CPlatform.c @@ -5,9 +5,11 @@ #include #include #include +#include #if defined(__APPLE__) #include +#include #else #include #endif @@ -16,6 +18,22 @@ int platform_flock(int descriptor, int operation) { return flock(descriptor, operation); } +void platform_raise_open_file_limit(void) { + struct rlimit limit; + if (getrlimit(RLIMIT_NOFILE, &limit) != 0 || limit.rlim_cur >= limit.rlim_max) return; + rlim_t ceiling = limit.rlim_max; +#if defined(__APPLE__) + int maximum; + size_t size = sizeof(maximum); + if (sysctlbyname("kern.maxfilesperproc", &maximum, &size, NULL, 0) != 0 || + size != sizeof(maximum) || maximum <= 0) return; + if ((rlim_t)maximum < ceiling) ceiling = (rlim_t)maximum; +#endif + if (ceiling == RLIM_INFINITY || ceiling <= limit.rlim_cur) return; + limit.rlim_cur = ceiling; + (void)setrlimit(RLIMIT_NOFILE, &limit); +} + int platform_access(int directory, const char *name, int mode) { return faccessat(directory, name, mode, AT_EACCESS); } diff --git a/Sources/CPlatform/include/CPlatform.h b/Sources/CPlatform/include/CPlatform.h index 87ece7d..b3d10ed 100644 --- a/Sources/CPlatform/include/CPlatform.h +++ b/Sources/CPlatform/include/CPlatform.h @@ -24,6 +24,7 @@ #endif int platform_flock(int descriptor, int operation); +void platform_raise_open_file_limit(void); int platform_access(int directory, const char *name, int mode); const char *platform_entry_name(const struct dirent *entry); bool platform_system_alias(const char *name); diff --git a/Tests/AgentsCoreTests/CoordinationAdmissionTests.swift b/Tests/AgentsCoreTests/CoordinationAdmissionTests.swift index 9dd4adb..01d225f 100644 --- a/Tests/AgentsCoreTests/CoordinationAdmissionTests.swift +++ b/Tests/AgentsCoreTests/CoordinationAdmissionTests.swift @@ -1,3 +1,4 @@ +import CPlatform import Foundation import StateTestSupport import Testing @@ -5,6 +6,106 @@ import Testing @testable import AgentsCore @Suite struct CoordinationAdmissionTests { + @Test(arguments: [false, true]) + func partialSharedAcquisitionRechecksAbsenceAndReleasesLocks(_ outerInspectionFails: Bool) + throws + { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore( + scope: .user, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: ["CLAUDE_CONFIG_DIR": root.appendingPathComponent("claude").path])) + let routes = try ["a", "b", "c", "d"].map { + try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: $0) + } + let resources = try routes.enumerated().map { index, route in + try SharedResource(store: store, route: route, create: index != 1) + } + let first = try #require(resources[0].metadata) + let absent = resources[1].parent.url.appendingPathComponent(SharedResource.metadataName) + .appendingPathComponent(resources[1].identity.directoryName) + let unlocked = try #require(resources[2].metadata) + let last = try #require(resources[3].metadata) + _ = try first.createPrivateFile("lock") + _ = try last.createPrivateFile("lock") + let contender = open(first.url.appendingPathComponent("lock").path, O_RDWR | O_CLOEXEC) + try #require(contender >= 0) + defer { close(contender) } + let blocker = open(last.url.appendingPathComponent("lock").path, O_RDWR | O_CLOEXEC) + try #require(blocker >= 0) + defer { close(blocker) } + try #require(platform_flock(blocker, LOCK_EX | LOCK_NB) == 0) + + var contended = 0 + var observedAbsentPath = 0 + var reads = 0 + let result = Result { + try store.withCoordination( + routes: Set(routes), writable: false, + checkpoint: { point in + #expect(point == "shared.3.lock.contended") + contended += 1 + try #require(contended == 1) + #expect(platform_flock(contender, LOCK_EX | LOCK_NB) == -1) + _ = try unlocked.createPrivateFile("lock") + if outerInspectionFails { + try FileManager.default.createSymbolicLink(at: absent, withDestinationURL: root) + } else { + try #require(platform_flock(blocker, LOCK_UN) == 0) + } + throw CoordinationTestInterruption.checkpoint + }, + onReadLocation: { if $0.path == absent.path { observedAbsentPath += 1 } } + ) { () -> Int? in + reads += 1 + return nil + } + } + #expect(contended == 1) + if outerInspectionFails { + if case .failure(let error) = result, + case .unsafePath? = error as? CoreError + { + #expect(reads == 0) + } else { + Issue.record("Expected the outer missing metadata check to replace the inner outcome") + } + #expect(observedAbsentPath == 2) + } else { + #expect(try result.get() == nil) + #expect(reads == 1) + #expect(observedAbsentPath == 4) + } + #expect(platform_flock(contender, LOCK_EX | LOCK_NB) == 0) + } + + @Test func missingSharedRootCanSupersedeReadFailure() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let loader = root.appendingPathComponent("claude") + try FileManager.default.createDirectory(at: loader, withIntermediateDirectories: false) + let store = StateStore( + scope: .user, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: ["CLAUDE_CONFIG_DIR": loader.path])) + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: "demo") + var reads = 0 + let value: Int? = try store.withReadLock(footprint: [route]) { + reads += 1 + if reads == 1 { + try FileManager.default.createDirectory( + at: loader.appendingPathComponent("skills"), withIntermediateDirectories: false) + throw CoordinationTestInterruption.body + } + return nil + } + #expect(reads == 2) + #expect(value == nil) + } + @Test func standaloneSelectionAndCanonicalChildUseObservedParent() throws { let fixture = try TransactionFixture() let store = fixture.store @@ -107,6 +208,10 @@ import Testing } } +private enum CoordinationTestInterruption: Error { + case checkpoint, body +} + extension CoordinationAdmissionTests { @Test func nativeAndLegacyWritersContendBeforeLegacyCallback() throws { let f = try TransactionFixture() @@ -118,6 +223,7 @@ extension CoordinationAdmissionTests { ]) defer { terminateProcess(holder) } try ProcessWait.marker(f.root.appendingPathComponent("ready"), child: holder, root: f.root) + try ProcessWait.stopped(holder, root: f.root) try FileManager.default.removeItem(at: f.root.appendingPathComponent("ready")) let waiter = try stateTestProcess( root: f.root, @@ -127,6 +233,7 @@ extension CoordinationAdmissionTests { ]) defer { terminateProcess(waiter) } try ProcessWait.marker(f.root.appendingPathComponent("ready"), child: waiter, root: f.root) + try ProcessWait.stopped(waiter, root: f.root) #expect( !FileManager.default.fileExists(atPath: f.root.appendingPathComponent("legacy-callback").path) ) diff --git a/Tests/AgentsCoreTests/FileSystemAccessTests.swift b/Tests/AgentsCoreTests/FileSystemAccessTests.swift index a8ec06b..dd7682f 100644 --- a/Tests/AgentsCoreTests/FileSystemAccessTests.swift +++ b/Tests/AgentsCoreTests/FileSystemAccessTests.swift @@ -236,7 +236,10 @@ struct FileSystemErrorTests { #expect(throws: git) { try FileSystem.withAccessErrors(at: path) { throw git } } let other = CoreError.invalidState("unrelated") #expect(throws: other) { try FileSystem.withAccessErrors(at: path) { throw other } } - #expect(FileSystem.posixError(ENOSPC, at: path, otherwise: other) == other) + #expect(FileSystem.posixError(ENOSPC, at: path, otherwise: other) as? CoreError == other) + let exhausted = FileSystem.posixError(ENFILE, at: path, otherwise: other) + #expect(exhausted is OpenFileLimitError) + #expect(exhausted.localizedDescription == "Too many open files in the system: \(path.path)") } @Test func existingLockRetainsContentIdentityAndMetadata() throws { diff --git a/Tests/AgentsCoreTests/ProcessLimitsTests.swift b/Tests/AgentsCoreTests/ProcessLimitsTests.swift new file mode 100644 index 0000000..849e4dd --- /dev/null +++ b/Tests/AgentsCoreTests/ProcessLimitsTests.swift @@ -0,0 +1,71 @@ +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite struct ProcessLimitsTests { + private func createSkillLocks(at root: URL, count: Int) throws { + let store = StateStore( + scope: .user, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: ["CLAUDE_CONFIG_DIR": root.appendingPathComponent("configured-claude").path] + )) + for index in 0.. (soft: UInt64, hard: UInt64, raised: UInt64, result: String) + { + let child = try stateTestProcess( + root: root, arguments: ["open-file-limit", mode, "--scope", "user"]) + defer { terminateProcess(child) } + try ProcessWait.exit(child, root: root, timeout: 30) + try #require(child.terminationStatus == 0) + let lines = try String( + contentsOf: root.appendingPathComponent("open-file-limit-\(mode)"), encoding: .utf8 + ).split(separator: "\n") + try #require(lines.count == 5) + let soft = try #require(UInt64(lines[0])) + let hard = try #require(UInt64(lines[1])) + let raised = try #require(UInt64(lines[2])) + #expect(UInt64(lines[3]) == hard) + return (soft, hard, raised, String(lines[4])) + } + let original = try run("original") + #expect(original.raised == original.soft) + #expect(original.result.hasPrefix("Too many open files for this process:")) + let raised = try run("raised") + #expect(raised.soft == original.soft) + if raised.hard > 256 { + #expect(raised.raised > 256) + #expect(raised.result == "admitted") + } + let bounded = try run("bounded") + #expect(bounded.hard <= 64) + #expect(bounded.raised == bounded.hard) + #expect(bounded.result.hasPrefix("Too many open files for this process:")) + } + + @Test func heldSharedFootprintFitsBoundedWorkerStack() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + try createSkillLocks(at: root, count: 196) + let child = try stateTestProcess( + root: root, arguments: ["open-file-limit", "worker", "--scope", "user"]) + defer { terminateProcess(child) } + try ProcessWait.exit(child, root: root, timeout: 30) + #expect(child.terminationReason == .exit) + #expect(child.terminationStatus == 0) + } +} diff --git a/Tests/StateTestProcess/OpenFileLimitProbe.swift b/Tests/StateTestProcess/OpenFileLimitProbe.swift new file mode 100644 index 0000000..384f7a8 --- /dev/null +++ b/Tests/StateTestProcess/OpenFileLimitProbe.swift @@ -0,0 +1,120 @@ +import AgentsCore +import Foundation + +#if os(Linux) + import Glibc +#else + import Darwin +#endif + +func openFileLimitProbe(_ mode: String, root: URL, store: StateStore) throws { + #if os(Linux) + let resource = RLIMIT_NOFILE.rawValue + #else + let resource = RLIMIT_NOFILE + #endif + var before = rlimit() + guard getrlimit(resource, &before) == 0 else { + throw POSIXError(.EINVAL) + } + if mode == "bounded" { + before.rlim_max = min(before.rlim_max, 64) + before.rlim_cur = min(before.rlim_max, 32) + } else if mode == "worker" { + before.rlim_cur = min(before.rlim_max, 4096) + } else { + before.rlim_cur = min(before.rlim_max, 256) + } + guard setrlimit(resource, &before) == 0 else { throw POSIXError(.EINVAL) } + + if mode == "worker" { + try sharedCoordinationWorkerProbe(store: store) + return + } + + if mode != "original" { ProcessLimits.raiseOpenFileLimit() } + var after = rlimit() + guard getrlimit(resource, &after) == 0 else { throw POSIXError(.EINVAL) } + + let routes = try (0..<96).map { + try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: "generated-\($0)") + } + try store.withReadLock(footprint: Set(routes.prefix(2))) {} + let large: String + do { + try store.withReadLock(footprint: Set(routes)) {} + large = "admitted" + } catch { + large = error.localizedDescription + } + let result = """ + \(before.rlim_cur) + \(before.rlim_max) + \(after.rlim_cur) + \(after.rlim_max) + \(large) + """ + try Data(result.utf8).write(to: root.appendingPathComponent("open-file-limit-\(mode)")) +} + +private func sharedCoordinationWorkerProbe(store: StateStore) throws { + func check(_ code: Int32) throws { + guard code == 0 else { throw POSIXError(POSIXErrorCode(rawValue: code) ?? .EINVAL) } + } + var attributes = pthread_attr_t() + try check(pthread_attr_init(&attributes)) + defer { pthread_attr_destroy(&attributes) } + try check(pthread_attr_setstacksize(&attributes, SharedCoordinationWorker.stackSize)) + #if os(Linux) + var thread: pthread_t = 0 + #else + var thread: pthread_t? + #endif + let worker = SharedCoordinationWorker(store: store) + let argument = Unmanaged.passRetained(worker) + let created = pthread_create( + &thread, &attributes, + { pointer in + let argument: UnsafeMutableRawPointer? = pointer + guard let argument else { return nil } + let worker = Unmanaged.fromOpaque(argument).takeRetainedValue() + worker.run() + return nil + }, argument.toOpaque()) + if created != 0 { + argument.release() + try check(created) + } + #if os(Linux) + try check(pthread_join(thread, nil)) + #else + try check(pthread_join(thread!, nil)) + #endif + guard let result = worker.result else { + throw CoreError.invalidState("coordination worker did not report a result") + } + try result.get() +} + +private final class SharedCoordinationWorker { + static let stackSize = 512 * 1024 + let store: StateStore + var result: Result? + + init(store: StateStore) { self.store = store } + + func run() { + result = Result { + let routes = try Set( + (0..<196).map { + try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: "generated-\($0)") + }) + var calls = 0 + let value: Int? = try store.withReadLock(footprint: routes) { + calls += 1 + return nil + } + precondition(calls == 1 && value == nil) + } + } +} diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 0ec3b0c..ecca1c4 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -28,6 +28,10 @@ let store = StateStore( "OPENCODE_CONFIG_DIR": sharedConfig, "GEMINI_CLI_HOME": sharedConfig, ] : ["CLAUDE_CONFIG_DIR": sharedConfig])) +if arguments[2] == "open-file-limit" { + try openFileLimitProbe(arguments[3], root: root, store: store) + exit(EXIT_SUCCESS) +} let checkpointState = Mutex( (requested: arguments.count > 3 ? arguments[3] : "", seen: Set())) let traceURL = root.appendingPathComponent( From 456ea30a32ab11786f95a6dfebc93e720584d24f Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:22:49 +0800 Subject: [PATCH 164/171] test: isolate connection timeout from protocol assertions --- Tests/ComponentsTests/MCPConnectionTests.swift | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Tests/ComponentsTests/MCPConnectionTests.swift b/Tests/ComponentsTests/MCPConnectionTests.swift index 3ad7c74..023714b 100644 --- a/Tests/ComponentsTests/MCPConnectionTests.swift +++ b/Tests/ComponentsTests/MCPConnectionTests.swift @@ -371,8 +371,7 @@ private func runConnection(_ input: MCPConnectionInput, limits: MCPConnectionLim limits.frameBytes = 1024 limits.receivedBytes = 8192 if mode == "event-flood" { limits.receivedBytes = 128 * 1024 } - limits.totalTimeout = 0.12 - limits.requestTimeout = 1 + if mode == "pending-body" { limits.totalTimeout = 0.12 } let headers = ["Authorization": "fixture-canary"] let input: MCPConnectionInput = mode.hasPrefix("legacy") From 23a666b7e859580d1538bc8732be51385c641a64 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:30:11 +0800 Subject: [PATCH 165/171] test: verify coordination within available process limits --- .../AgentsCoreTests/ProcessLimitsTests.swift | 79 +++++++++++-------- .../StateTestProcess/OpenFileLimitProbe.swift | 66 ++++++++-------- 2 files changed, 79 insertions(+), 66 deletions(-) diff --git a/Tests/AgentsCoreTests/ProcessLimitsTests.swift b/Tests/AgentsCoreTests/ProcessLimitsTests.swift index 849e4dd..1632447 100644 --- a/Tests/AgentsCoreTests/ProcessLimitsTests.swift +++ b/Tests/AgentsCoreTests/ProcessLimitsTests.swift @@ -5,6 +5,13 @@ import Testing @testable import AgentsCore @Suite struct ProcessLimitsTests { + private struct Probe { + let soft: UInt64 + let hard: UInt64 + let after: UInt64 + let result: String + } + private func createSkillLocks(at root: URL, count: Int) throws { let store = StateStore( scope: .user, @@ -21,39 +28,49 @@ import Testing } } - @Test func executableOptInPreservesHardLimitAndAdmitsLargeScope() throws { + private func runProbe(_ mode: String, at root: URL) throws -> Probe { + let child = try stateTestProcess( + root: root, arguments: ["open-file-limit", mode, "--scope", "user"]) + defer { terminateProcess(child) } + try ProcessWait.exit(child, root: root, timeout: 30) + try #require(child.terminationReason == .exit) + try #require(child.terminationStatus == 0) + let lines = try String( + contentsOf: root.appendingPathComponent("open-file-limit-\(mode)"), encoding: .utf8 + ).split(separator: "\n") + try #require(lines.count == 5) + let soft = try #require(UInt64(lines[0])) + let hard = try #require(UInt64(lines[1])) + let after = try #require(UInt64(lines[2])) + #expect(UInt64(lines[3]) == hard) + return Probe(soft: soft, hard: hard, after: after, result: String(lines[4])) + } + + private func checkLargeAdmission(_ probe: Probe, count: UInt64) { + // The probe sets a comfortably sufficient budget of 4096 when testing the worker. + // Below three pinned descriptors per route, the full footprint cannot fit. + if probe.after >= 4096 { + #expect(probe.result == "admitted") + } else if probe.after < 3 * count { + #expect(probe.result.hasPrefix("Too many open files for this process:")) + } + } + + @Test func executableOptInPreservesHardLimitAndUsesAvailableCapacity() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } try createSkillLocks(at: root, count: 96) - func run(_ mode: String) throws -> (soft: UInt64, hard: UInt64, raised: UInt64, result: String) - { - let child = try stateTestProcess( - root: root, arguments: ["open-file-limit", mode, "--scope", "user"]) - defer { terminateProcess(child) } - try ProcessWait.exit(child, root: root, timeout: 30) - try #require(child.terminationStatus == 0) - let lines = try String( - contentsOf: root.appendingPathComponent("open-file-limit-\(mode)"), encoding: .utf8 - ).split(separator: "\n") - try #require(lines.count == 5) - let soft = try #require(UInt64(lines[0])) - let hard = try #require(UInt64(lines[1])) - let raised = try #require(UInt64(lines[2])) - #expect(UInt64(lines[3]) == hard) - return (soft, hard, raised, String(lines[4])) - } - let original = try run("original") - #expect(original.raised == original.soft) + let original = try runProbe("original", at: root) + #expect(original.after == original.soft) #expect(original.result.hasPrefix("Too many open files for this process:")) - let raised = try run("raised") + let raised = try runProbe("raised", at: root) #expect(raised.soft == original.soft) - if raised.hard > 256 { - #expect(raised.raised > 256) - #expect(raised.result == "admitted") - } - let bounded = try run("bounded") + #expect(raised.after <= raised.hard) + if raised.hard > raised.soft { #expect(raised.after > raised.soft) } + checkLargeAdmission(raised, count: 96) + let bounded = try runProbe("bounded", at: root) #expect(bounded.hard <= 64) - #expect(bounded.raised == bounded.hard) + #expect(bounded.after == bounded.hard) #expect(bounded.result.hasPrefix("Too many open files for this process:")) } @@ -61,11 +78,7 @@ import Testing let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } try createSkillLocks(at: root, count: 196) - let child = try stateTestProcess( - root: root, arguments: ["open-file-limit", "worker", "--scope", "user"]) - defer { terminateProcess(child) } - try ProcessWait.exit(child, root: root, timeout: 30) - #expect(child.terminationReason == .exit) - #expect(child.terminationStatus == 0) + let worker = try runProbe("worker", at: root) + checkLargeAdmission(worker, count: 196) } } diff --git a/Tests/StateTestProcess/OpenFileLimitProbe.swift b/Tests/StateTestProcess/OpenFileLimitProbe.swift index 384f7a8..ab523b3 100644 --- a/Tests/StateTestProcess/OpenFileLimitProbe.swift +++ b/Tests/StateTestProcess/OpenFileLimitProbe.swift @@ -9,7 +9,7 @@ import Foundation func openFileLimitProbe(_ mode: String, root: URL, store: StateStore) throws { #if os(Linux) - let resource = RLIMIT_NOFILE.rawValue + let resource = Int32(RLIMIT_NOFILE.rawValue) #else let resource = RLIMIT_NOFILE #endif @@ -27,26 +27,16 @@ func openFileLimitProbe(_ mode: String, root: URL, store: StateStore) throws { } guard setrlimit(resource, &before) == 0 else { throw POSIXError(.EINVAL) } - if mode == "worker" { - try sharedCoordinationWorkerProbe(store: store) - return - } - - if mode != "original" { ProcessLimits.raiseOpenFileLimit() } + if mode == "raised" || mode == "bounded" { ProcessLimits.raiseOpenFileLimit() } var after = rlimit() guard getrlimit(resource, &after) == 0 else { throw POSIXError(.EINVAL) } - let routes = try (0..<96).map { - try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: "generated-\($0)") - } - try store.withReadLock(footprint: Set(routes.prefix(2))) {} - let large: String - do { - try store.withReadLock(footprint: Set(routes)) {} - large = "admitted" - } catch { - large = error.localizedDescription - } + let large = + if mode == "worker" { + try sharedCoordinationWorkerProbe(store: store) + } else { + try sharedCoordinationAdmission(store: store, count: 96) + } let result = """ \(before.rlim_cur) \(before.rlim_max) @@ -57,7 +47,28 @@ func openFileLimitProbe(_ mode: String, root: URL, store: StateStore) throws { try Data(result.utf8).write(to: root.appendingPathComponent("open-file-limit-\(mode)")) } -private func sharedCoordinationWorkerProbe(store: StateStore) throws { +private func sharedCoordinationAdmission(store: StateStore, count: Int) throws -> String { + let routes = try (0..) throws { + var calls = 0 + let value: Int? = try store.withReadLock(footprint: footprint) { + calls += 1 + return nil + } + precondition(calls == 1 && value == nil) + } + try read(Set(routes.prefix(2))) + do { + try read(Set(routes)) + return "admitted" + } catch where error.localizedDescription.hasPrefix("Too many open files for this process:") { + return error.localizedDescription + } +} + +private func sharedCoordinationWorkerProbe(store: StateStore) throws -> String { func check(_ code: Int32) throws { guard code == 0 else { throw POSIXError(POSIXErrorCode(rawValue: code) ?? .EINVAL) } } @@ -93,28 +104,17 @@ private func sharedCoordinationWorkerProbe(store: StateStore) throws { guard let result = worker.result else { throw CoreError.invalidState("coordination worker did not report a result") } - try result.get() + return try result.get() } private final class SharedCoordinationWorker { static let stackSize = 512 * 1024 let store: StateStore - var result: Result? + var result: Result? init(store: StateStore) { self.store = store } func run() { - result = Result { - let routes = try Set( - (0..<196).map { - try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: "generated-\($0)") - }) - var calls = 0 - let value: Int? = try store.withReadLock(footprint: routes) { - calls += 1 - return nil - } - precondition(calls == 1 && value == nil) - } + result = Result { try sharedCoordinationAdmission(store: store, count: 196) } } } From 11365a4e103c46c135d042afc18417b711845a97 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:15:18 +0800 Subject: [PATCH 166/171] ci: validate public agent declarations with shared policy --- .github/workflows/source-policy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/source-policy.yml b/.github/workflows/source-policy.yml index bb2db02..f75a13b 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@bb0a8c8c39827a364b9d3cbf4069754e7d975586 + uses: agents-tools/github-workflows/.github/workflows/policy.yml@c2d32f7279064a45dd7cc152bd4be471ddc8ce33 with: allow-terms: | ChatGPT From 048cbf3f23c8a9986ca3de8654f7ec5f758161ae Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:23:53 +0800 Subject: [PATCH 167/171] fix: support Swift 6.3 in MCP stream handling --- Sources/Components/MCPMessageSink.swift | 4 ++++ Tests/MCPTestProcess/main.swift | 7 +++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/Sources/Components/MCPMessageSink.swift b/Sources/Components/MCPMessageSink.swift index 0b059c5..2d4ad77 100644 --- a/Sources/Components/MCPMessageSink.swift +++ b/Sources/Components/MCPMessageSink.swift @@ -164,6 +164,10 @@ struct MCPSSEParser { private var firstLine = true let limit: Int + init(limit: Int) { + self.limit = limit + } + mutating func restart() { line.removeAll(keepingCapacity: true) data.removeAll(keepingCapacity: true) diff --git a/Tests/MCPTestProcess/main.swift b/Tests/MCPTestProcess/main.swift index ae84b32..88b1729 100644 --- a/Tests/MCPTestProcess/main.swift +++ b/Tests/MCPTestProcess/main.swift @@ -104,10 +104,9 @@ if scenario == "holder" || scenario == "ignore-input" || scenario == "blocked-in } #endif if scenario == "descendant" || scenario == "thread-descendant" { - let argv = - [arguments[0], scenario == "descendant" ? "holder" : "thread-holder", root.path].map { - strdup($0) - } + [nil] + let childScenario = scenario == "descendant" ? "holder" : "thread-holder" + let childArguments = [arguments[0], childScenario, root.path(percentEncoded: false)] + let argv = childArguments.map { strdup($0) } + [nil] let environment = ProcessInfo.processInfo.environment.map { strdup($0.key + "=" + $0.value) } + [nil] var pid: pid_t = 0 From 3111f90a3c6a086345515e43e23912ec7c0ba2cb Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:27:25 +0800 Subject: [PATCH 168/171] ci: align shared workflow revisions --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dd0d3cf..52097be 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,4 +19,4 @@ jobs: permissions: contents: read actions: read - uses: agents-tools/github-workflows/.github/workflows/swift-package.yml@bb0a8c8c39827a364b9d3cbf4069754e7d975586 + uses: agents-tools/github-workflows/.github/workflows/swift-package.yml@c2d32f7279064a45dd7cc152bd4be471ddc8ce33 From a9ded52192756ca1131f1eff92437363f6bf0c82 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:36:08 +0800 Subject: [PATCH 169/171] ci: run Linux suites with their required runtime --- .github/ci/linux-tests.Dockerfile | 13 +++++++++++ .github/swift-package.json | 14 +++++------ README.md | 5 ++-- Scripts/test-linux.py | 39 +++++++++++++++++++++++++++++++ 4 files changed, 61 insertions(+), 10 deletions(-) create mode 100644 .github/ci/linux-tests.Dockerfile create mode 100644 Scripts/test-linux.py diff --git a/.github/ci/linux-tests.Dockerfile b/.github/ci/linux-tests.Dockerfile new file mode 100644 index 0000000..0d63e22 --- /dev/null +++ b/.github/ci/linux-tests.Dockerfile @@ -0,0 +1,13 @@ +ARG SWIFT_IMAGE +FROM ${SWIFT_IMAGE} + +ARG TEST_UID +ARG TEST_GID +RUN apt-get update \ + && apt-get install -y --no-install-recommends python3 \ + && rm -rf /var/lib/apt/lists/* \ + && (getent group "$TEST_GID" || groupadd --gid "$TEST_GID" test-runner) \ + && (getent passwd "$TEST_UID" || useradd --create-home --uid "$TEST_UID" --gid "$TEST_GID" test-runner) + +USER ${TEST_UID}:${TEST_GID} +WORKDIR /workspace diff --git a/.github/swift-package.json b/.github/swift-package.json index 83fa341..55fef85 100644 --- a/.github/swift-package.json +++ b/.github/swift-package.json @@ -3,6 +3,11 @@ { "name": "manifest-schema-generation", "run": "python3 Scripts/generate-manifest-schema.py --check" + }, + { + "name": "linux-swift-6.4.1", + "runner": "ubuntu-24.04", + "run": "python3 Scripts/test-linux.py swift:6.4.1-noble@sha256:6304481cf2717966b7ba175162e397ea2f2cc3161909f2b2a5cf40036079a0f7" } ], "test_configurations": [ @@ -16,12 +21,5 @@ "xcode": "26.6" } ], - "platforms": { - "linux": [ - { - "name": "linux-swift-6.4.1", - "image": "swift:6.4.1-noble@sha256:6304481cf2717966b7ba175162e397ea2f2cc3161909f2b2a5cf40036079a0f7" - } - ] - } + "timeout_minutes": 75 } diff --git a/README.md b/README.md index fe77198..ada28eb 100644 --- a/README.md +++ b/README.md @@ -336,8 +336,9 @@ publication matrix; the full publication matrix is not part of CI. macOS also runs a release build and strict formatting with `.swift-format` over `Package.swift`, `Sources` and `Tests`. The test suites include subprocess recovery tests. The configuration owns the Linux compiler version and image -digest. Tests also require Perl, which is included by the Linux image's Git -dependencies. +digest. Linux runs the suites serially as the checkout owner to exercise kernel +permission checks and subprocess deadlines. The test image includes Python 3 +for the loopback HTTP fixture and Perl through Git. Render and check the committed [social preview](.github/assets/social-preview/social-preview.png) locally with diff --git a/Scripts/test-linux.py b/Scripts/test-linux.py new file mode 100644 index 0000000..ed54d51 --- /dev/null +++ b/Scripts/test-linux.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Run the package tests in the pinned Linux toolchain as the checkout owner.""" + +import json +import os +from pathlib import Path +import subprocess +import sys + + +def main(image): + root = Path(__file__).resolve().parents[1] + config = json.loads((root / ".github/swift-package.json").read_text()) + if os.getuid() == 0: + raise SystemExit("Run Linux validation as a regular user for filesystem permission tests.") + + dockerfile = root / ".github/ci/linux-tests.Dockerfile" + test_image = subprocess.check_output( + [ + "docker", "build", "--quiet", "--file", str(dockerfile), + "--build-arg", f"SWIFT_IMAGE={image}", + "--build-arg", f"TEST_UID={os.getuid()}", + "--build-arg", f"TEST_GID={os.getgid()}", + str(dockerfile.parent), + ], + text=True, + ).strip() + for configuration in config["test_configurations"]: + subprocess.run( + [ + "docker", "run", "--rm", "--init", "--volume", f"{root}:/workspace", + test_image, "swift", "test", "-c", configuration, "--jobs", "2", "--no-parallel", + ], + check=True, + ) + + +if __name__ == "__main__": + main(sys.argv[1]) From 14be21560c8277cce5a4ba2f015dc459cf1c3b9a Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:06:33 +0800 Subject: [PATCH 170/171] ci: serialize time-sensitive configuration tests --- .github/swift-package.json | 5 ++++- README.md | 6 +++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.github/swift-package.json b/.github/swift-package.json index 55fef85..ba98049 100644 --- a/.github/swift-package.json +++ b/.github/swift-package.json @@ -21,5 +21,8 @@ "xcode": "26.6" } ], - "timeout_minutes": 75 + "timeout_minutes": 75, + "environment": { + "SWT_EXPERIMENTAL_MAXIMUM_PARALLELIZATION_WIDTH": "1" + } } diff --git a/README.md b/README.md index ada28eb..be72b78 100644 --- a/README.md +++ b/README.md @@ -336,9 +336,9 @@ publication matrix; the full publication matrix is not part of CI. macOS also runs a release build and strict formatting with `.swift-format` over `Package.swift`, `Sources` and `Tests`. The test suites include subprocess recovery tests. The configuration owns the Linux compiler version and image -digest. Linux runs the suites serially as the checkout owner to exercise kernel -permission checks and subprocess deadlines. The test image includes Python 3 -for the loopback HTTP fixture and Perl through Git. +digest. The suites run serially so other test cases cannot starve subprocess +deadlines. Linux uses the checkout owner to exercise kernel permission checks, +with Python 3 for the loopback HTTP fixture and Perl through Git. Render and check the committed [social preview](.github/assets/social-preview/social-preview.png) locally with From e5cc0556a78f8eb8a569d550e40fb5b23e301253 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:39:00 +0800 Subject: [PATCH 171/171] ci: allow time for both macOS test configurations --- .github/swift-package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/swift-package.json b/.github/swift-package.json index ba98049..1dafec3 100644 --- a/.github/swift-package.json +++ b/.github/swift-package.json @@ -21,7 +21,7 @@ "xcode": "26.6" } ], - "timeout_minutes": 75, + "timeout_minutes": 120, "environment": { "SWT_EXPERIMENTAL_MAXIMUM_PARALLELIZATION_WIDTH": "1" }